repo_name
stringlengths
6
130
hexsha
sequence
file_path
sequence
code
sequence
apis
sequence
possible_versions
list
zengxinzhy/colorization-pytorch
[ "a41e61dfc0d99532728af3cbfd21efbdaf6086c5", "a41e61dfc0d99532728af3cbfd21efbdaf6086c5" ]
[ "util/visualizer.py", "imtest.py" ]
[ "import numpy as np\nimport os\nimport ntpath\nimport time\nfrom . import util\nfrom . import html\nfrom PIL import Image\nfrom torchvision import transforms\n\n\ndef imresize(image, size, interp=Image.BICUBIC):\n return transforms.Resize(size=size, interpolation=interp)(image)\n\n# save image to the disk\n\n\ndef save_images(webpage, visuals, image_path, aspect_ratio=1.0, width=256):\n image_dir = webpage.get_image_dir()\n short_path = ntpath.basename(image_path[0])\n name = os.path.splitext(short_path)[0]\n\n webpage.add_header(name)\n ims, txts, links = [], [], []\n\n for label, im_data in visuals.items():\n im = util.tensor2im(im_data)\n image_name = '%s_%s.png' % (name, label)\n save_path = os.path.join(image_dir, image_name)\n h, w, _ = im.shape\n if aspect_ratio > 1.0:\n im = imresize(im, (h, int(w * aspect_ratio)), interp='bicubic')\n if aspect_ratio < 1.0:\n im = imresize(im, (int(h / aspect_ratio), w), interp='bicubic')\n util.save_image(im, save_path)\n\n ims.append(image_name)\n txts.append(label)\n links.append(image_name)\n webpage.add_images(ims, txts, links, width=width)\n\n\nclass Visualizer():\n def __init__(self, opt):\n self.display_id = opt.display_id\n self.use_html = opt.isTrain and not opt.no_html\n self.win_size = opt.display_winsize\n self.name = opt.name\n self.opt = opt\n self.saved = False\n if self.display_id > 0:\n import visdom\n self.ncols = opt.display_ncols\n self.vis = visdom.Visdom(\n server=opt.display_server, port=opt.display_port)\n\n if self.use_html:\n self.web_dir = os.path.join(opt.checkpoints_dir, opt.name, 'web')\n self.img_dir = os.path.join(self.web_dir, 'images')\n print('create web directory %s...' % self.web_dir)\n util.mkdirs([self.web_dir, self.img_dir])\n self.log_name = os.path.join(\n opt.checkpoints_dir, opt.name, 'loss_log.txt')\n with open(self.log_name, \"a\") as log_file:\n now = time.strftime(\"%c\")\n log_file.write(\n '================ Training Loss (%s) ================\\n' % now)\n\n def reset(self):\n self.saved = False\n\n # |visuals|: dictionary of images to display or save\n def display_current_results(self, visuals, epoch, save_result):\n if self.display_id > 0: # show images in the browser\n ncols = self.ncols\n if ncols > 0:\n ncols = min(ncols, len(visuals))\n h, w = next(iter(visuals.values())).shape[:2]\n table_css = \"\"\"<style>\n table {border-collapse: separate; border-spacing:4px; white-space:nowrap; text-align:center}\n table td {width: %dpx; height: %dpx; padding: 4px; outline: 4px solid black}\n </style>\"\"\" % (w, h)\n title = self.name\n label_html = ''\n label_html_row = ''\n images = []\n idx = 0\n for label, image in visuals.items():\n image_numpy = util.tensor2im(image)\n label_html_row += '<td>%s</td>' % label\n images.append(image_numpy.transpose([2, 0, 1]))\n idx += 1\n if idx % ncols == 0:\n label_html += '<tr>%s</tr>' % label_html_row\n label_html_row = ''\n white_image = np.ones_like(\n image_numpy.transpose([2, 0, 1])) * 255\n while idx % ncols != 0:\n images.append(white_image)\n label_html_row += '<td></td>'\n idx += 1\n if label_html_row != '':\n label_html += '<tr>%s</tr>' % label_html_row\n # pane col = image row\n self.vis.images(images, nrow=ncols, win=self.display_id + 1,\n padding=2, opts=dict(title=title + ' images'))\n label_html = '<table>%s</table>' % label_html\n self.vis.text(table_css + label_html, win=self.display_id + 2,\n opts=dict(title=title + ' labels'))\n else:\n idx = 1\n for label, image in visuals.items():\n image_numpy = util.tensor2im(image)\n self.vis.image(image_numpy.transpose([2, 0, 1]), opts=dict(title=label),\n win=self.display_id + idx)\n idx += 1\n\n # save images to a html file\n if self.use_html and (save_result or not self.saved):\n self.saved = True\n for label, image in visuals.items():\n image_numpy = util.tensor2im(image)\n img_path = os.path.join(\n self.img_dir, 'epoch%.3d_%s.png' % (epoch, label))\n util.save_image(image_numpy, img_path)\n # update website\n webpage = html.HTML(\n self.web_dir, 'Experiment name = %s' % self.name, reflesh=1)\n for n in range(epoch, 0, -1):\n webpage.add_header('epoch [%d]' % n)\n ims, txts, links = [], [], []\n\n for label, image_numpy in visuals.items():\n image_numpy = util.tensor2im(image)\n img_path = 'epoch%.3d_%s.png' % (n, label)\n ims.append(img_path)\n txts.append(label)\n links.append(img_path)\n webpage.add_images(ims, txts, links, width=self.win_size)\n webpage.save()\n\n # losses: dictionary of error labels and values\n def plot_current_losses(self, epoch, counter_ratio, opt, losses):\n if not hasattr(self, 'plot_data'):\n self.plot_data = {'X': [], 'Y': [], 'legend': list(losses.keys())}\n self.plot_data['X'].append(epoch + counter_ratio)\n self.plot_data['Y'].append([losses[k]\n for k in self.plot_data['legend']])\n self.vis.line(\n X=np.stack([np.array(self.plot_data['X'])] *\n len(self.plot_data['legend']), 1),\n Y=np.array(self.plot_data['Y']),\n opts={\n 'title': self.name + ' loss over time',\n 'legend': self.plot_data['legend'],\n 'xlabel': 'epoch',\n 'ylabel': 'loss'},\n win=self.display_id)\n\n # losses: same format as |losses| of plot_current_losses\n def print_current_losses(self, epoch, i, losses, t, t_data):\n message = '(epoch: %d, iters: %d, time: %.3f, data: %.3f) ' % (\n epoch, i, t, t_data)\n for k, v in losses.items():\n message += '%s: %.3f, ' % (k, v)\n\n print(message)\n with open(self.log_name, \"a\") as log_file:\n log_file.write('%s\\n' % message)\n", "import os\nfrom options.train_options import TrainOptions\nfrom models import create_model\nfrom util.visualizer import save_images\nfrom util import html\nfrom PIL import Image\n\nimport string\nimport torch\nimport torchvision\nimport torchvision.transforms as transforms\nimport coremltools as ct\n\n\nfrom util import util\nimport numpy as np\n\nopt = TrainOptions().gather_options()\nopt.isTrain = True\nopt.name = \"siggraph_caffemodel\"\nopt.mask_cent = 0\n# opt.name = \"siggraph_retrained\"\nopt.gpu_ids = []\nopt.load_model = True\nopt.num_threads = 1 # test code only supports num_threads = 1\nopt.batch_size = 1 # test code only supports batch_size = 1\nopt.display_id = -1 # no visdom display\nopt.phase = 'val'\nopt.dataroot = './dataset/ilsvrc2012/%s/' % opt.phase\nopt.serial_batches = True\nopt.aspect_ratio = 1.\n\n# process opt.suffix\nif opt.suffix:\n suffix = ('_' + opt.suffix.format(**vars(opt))\n ) if opt.suffix != '' else ''\n opt.name = opt.name + suffix\n\nopt.A = 2 * opt.ab_max / opt.ab_quant + 1\nopt.B = opt.A\n\n\nclass Colorization(torch.nn.Module):\n def __init__(self):\n super(Colorization, self).__init__()\n model = create_model(opt)\n model.setup(opt)\n model.eval()\n self.model = model\n\n def forward(self, image, hint):\n data = {\n \"A\": image[:, 0:1, :, :],\n \"B\": image[:, 1:3, :, :],\n \"hint_B\": hint[:, 0:2, :, :],\n \"mask_B\": hint[:, 2:3, :, :]\n }\n # with torch.no_grad():\n self.model.set_input(data)\n self.model.forward()\n fake_reg = torch.cat((self.model.real_A, self.model.fake_B_reg), dim=1)\n return fake_reg\n\n\nimage_path = \"./large.JPG\"\nimage = Image.open(image_path)\nimage = transforms.Compose([\n transforms.Resize(512),\n transforms.ToTensor(),\n])(image)\nimage = image.view(1, *image.shape)\nimage = util.crop_mult(image, mult=8, HWmax=[4032, 4032])\ntransforms.ToPILImage()(image[0]).show(command='fim')\n\ndata = util.get_colorization_data(\n [image], opt, ab_thresh=0., p=0.125)\nimg = torch.cat((data[\"A\"], data[\"B\"]), dim=1)\nhint = torch.cat((data[\"hint_B\"], data[\"mask_B\"]), dim=1)\n\n# print(data[\"mask_B\"], data[\"hint_B\"])\n# data[\"hint_B\"] = torch.zeros_like(data[\"hint_B\"])\n# data[\"mask_B\"] = torch.zeros_like(data[\"mask_B\"])\n# model = Colorization()\nwith torch.no_grad():\n model = Colorization()\n model.eval()\n for param in model.parameters():\n param.requires_grad = False\n model.model.set_requires_grad(model.model.netG)\n\n# model(data)\n\n# transforms.ToPILImage()(image[0]).show(command='fim')\n# to_visualize = ['gray', 'hint', 'hint_ab', 'fake_entr',\n# 'real', 'fake_reg', 'real_ab', 'fake_ab_reg', ]\n\n# visuals = util.get_subset_dict(\n# model.model.get_current_visuals(), to_visualize)\n\n# for key, value in visuals.items():\n# print(key)\n# transforms.ToPILImage()(value[0]).show(command='fim')\noutput = model(img, hint)\noutput = util.lab2rgb(output, opt=opt)\ntransforms.ToPILImage()(output[0]).show(command='fim')\n\ntraced_model = torch.jit.trace(\n model, (img, hint), check_trace=False)\n\nmlmodel = ct.convert(model=traced_model, inputs=[\n ct.TensorType(name=\"image\", shape=ct.Shape(\n shape=(1, 3, ct.RangeDim(1, 4096), ct.RangeDim(1, 4096)))),\n ct.TensorType(name=\"hint\", shape=ct.Shape(\n shape=(1, 3, ct.RangeDim(1, 4096), ct.RangeDim(1, 4096)))),\n])\nmlmodel.save(\"~/color.mlmodel\")\n" ]
[ [ "numpy.array" ], [ "torch.no_grad", "torch.jit.trace", "torch.cat" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
carocamargo/pygmt
[ "6139c1735cff7f7d615d243145c21b1efef3f2c6", "6139c1735cff7f7d615d243145c21b1efef3f2c6" ]
[ "pygmt/helpers/testing.py", "pygmt/modules.py" ]
[ "\"\"\"\nHelper functions for testing.\n\"\"\"\nimport inspect\nimport os\nimport string\n\nfrom matplotlib.testing.compare import compare_images\nfrom ..exceptions import GMTImageComparisonFailure\n\n\ndef check_figures_equal(*, extensions=(\"png\",), tol=0.0, result_dir=\"result_images\"):\n \"\"\"\n Decorator for test cases that generate and compare two figures.\n\n The decorated function must return two arguments, *fig_ref* and *fig_test*,\n these two figures will then be saved and compared against each other.\n\n This decorator is practically identical to matplotlib's check_figures_equal\n function, but adapted for PyGMT figures. See also the original code at\n https://matplotlib.org/3.3.1/api/testing_api.html#\n matplotlib.testing.decorators.check_figures_equal\n\n Parameters\n ----------\n extensions : list\n The extensions to test. Default is [\"png\"].\n tol : float\n The RMS threshold above which the test is considered failed.\n result_dir : str\n The directory where the figures will be stored.\n\n Examples\n --------\n\n >>> import pytest\n >>> import shutil\n >>> from pygmt import Figure\n\n >>> @check_figures_equal(result_dir=\"tmp_result_images\")\n ... def test_check_figures_equal():\n ... fig_ref = Figure()\n ... fig_ref.basemap(projection=\"X5c\", region=[0, 5, 0, 5], frame=True)\n ... fig_test = Figure()\n ... fig_test.basemap(projection=\"X5c\", region=[0, 5, 0, 5], frame=\"af\")\n ... return fig_ref, fig_test\n >>> test_check_figures_equal()\n >>> assert len(os.listdir(\"tmp_result_images\")) == 0\n >>> shutil.rmtree(path=\"tmp_result_images\") # cleanup folder if tests pass\n\n >>> @check_figures_equal(result_dir=\"tmp_result_images\")\n ... def test_check_figures_unequal():\n ... fig_ref = Figure()\n ... fig_ref.basemap(projection=\"X5c\", region=[0, 5, 0, 5], frame=True)\n ... fig_test = Figure()\n ... fig_test.basemap(projection=\"X5c\", region=[0, 3, 0, 3], frame=True)\n ... return fig_ref, fig_test\n >>> with pytest.raises(GMTImageComparisonFailure):\n ... test_check_figures_unequal()\n >>> for suffix in [\"\", \"-expected\", \"-failed-diff\"]:\n ... assert os.path.exists(\n ... os.path.join(\n ... \"tmp_result_images\",\n ... f\"test_check_figures_unequal{suffix}.png\",\n ... )\n ... )\n >>> shutil.rmtree(path=\"tmp_result_images\") # cleanup folder if tests pass\n \"\"\"\n # pylint: disable=invalid-name\n ALLOWED_CHARS = set(string.digits + string.ascii_letters + \"_-[]()\")\n KEYWORD_ONLY = inspect.Parameter.KEYWORD_ONLY\n\n def decorator(func):\n import pytest\n\n os.makedirs(result_dir, exist_ok=True)\n old_sig = inspect.signature(func)\n\n @pytest.mark.parametrize(\"ext\", extensions)\n def wrapper(*args, ext=\"png\", request=None, **kwargs):\n if \"ext\" in old_sig.parameters:\n kwargs[\"ext\"] = ext\n if \"request\" in old_sig.parameters:\n kwargs[\"request\"] = request\n try:\n file_name = \"\".join(c for c in request.node.name if c in ALLOWED_CHARS)\n except AttributeError: # 'NoneType' object has no attribute 'node'\n file_name = func.__name__\n try:\n fig_ref, fig_test = func(*args, **kwargs)\n ref_image_path = os.path.join(result_dir, f\"{file_name}-expected.{ext}\")\n test_image_path = os.path.join(result_dir, f\"{file_name}.{ext}\")\n fig_ref.savefig(ref_image_path)\n fig_test.savefig(test_image_path)\n\n # Code below is adapted for PyGMT, and is originally based on\n # matplotlib.testing.decorators._raise_on_image_difference\n err = compare_images(\n expected=ref_image_path,\n actual=test_image_path,\n tol=tol,\n in_decorator=True,\n )\n if err is None: # Images are the same\n os.remove(ref_image_path)\n os.remove(test_image_path)\n else: # Images are not the same\n for key in [\"actual\", \"expected\", \"diff\"]:\n err[key] = os.path.relpath(err[key])\n raise GMTImageComparisonFailure(\n \"images not close (RMS %(rms).3f):\\n\\t%(actual)s\\n\\t%(expected)s \"\n % err\n )\n finally:\n del fig_ref\n del fig_test\n\n parameters = [\n param\n for param in old_sig.parameters.values()\n if param.name not in {\"fig_test\", \"fig_ref\"}\n ]\n if \"ext\" not in old_sig.parameters:\n parameters += [inspect.Parameter(\"ext\", KEYWORD_ONLY)]\n if \"request\" not in old_sig.parameters:\n parameters += [inspect.Parameter(\"request\", KEYWORD_ONLY)]\n new_sig = old_sig.replace(parameters=parameters)\n wrapper.__signature__ = new_sig\n\n # reach a bit into pytest internals to hoist the marks from\n # our wrapped function\n new_marks = getattr(func, \"pytestmark\", []) + wrapper.pytestmark\n wrapper.pytestmark = new_marks\n\n return wrapper\n\n return decorator\n", "\"\"\"\nNon-plot GMT modules.\n\"\"\"\nimport numpy as np\nimport xarray as xr\n\nfrom .clib import Session\nfrom .helpers import (\n build_arg_string,\n fmt_docstring,\n GMTTempFile,\n use_alias,\n data_kind,\n dummy_context,\n)\nfrom .exceptions import GMTInvalidInput\n\n\n@fmt_docstring\ndef grdinfo(grid, **kwargs):\n \"\"\"\n Get information about a grid.\n\n Can read the grid from a file or given as an xarray.DataArray grid.\n\n Full option list at :gmt-docs:`grdinfo.html`\n\n Parameters\n ----------\n grid : str or xarray.DataArray\n The file name of the input grid or the grid loaded as a DataArray.\n\n Returns\n -------\n info : str\n A string with information about the grid.\n\n \"\"\"\n kind = data_kind(grid, None, None)\n with GMTTempFile() as outfile:\n with Session() as lib:\n if kind == \"file\":\n file_context = dummy_context(grid)\n elif kind == \"grid\":\n file_context = lib.virtualfile_from_grid(grid)\n else:\n raise GMTInvalidInput(\"Unrecognized data type: {}\".format(type(grid)))\n with file_context as infile:\n arg_str = \" \".join(\n [infile, build_arg_string(kwargs), \"->\" + outfile.name]\n )\n lib.call_module(\"grdinfo\", arg_str)\n result = outfile.read()\n return result\n\n\n@fmt_docstring\n@use_alias(C=\"per_column\", I=\"spacing\", T=\"nearest_multiple\")\ndef info(table, **kwargs):\n \"\"\"\n Get information about data tables.\n\n Reads from files and finds the extreme values in each of the columns\n reported as min/max pairs. It recognizes NaNs and will print warnings if\n the number of columns vary from record to record. As an option, it will\n find the extent of the first two columns rounded up and down to the nearest\n multiple of the supplied increments given by *spacing*. Such output will be\n in a numpy.ndarray form ``[w, e, s, n]``, which can be used directly as the\n *region* argument for other modules (hence only dx and dy are needed). If\n the *per_column* option is combined with *spacing*, then the numpy.ndarray\n output will be rounded up/down for as many columns as there are increments\n provided in *spacing*. A similar option *nearest_multiple* option will\n provide a numpy.ndarray in the form of ``[zmin, zmax, dz]`` for makecpt.\n\n Full option list at :gmt-docs:`gmtinfo.html`\n\n {aliases}\n\n Parameters\n ----------\n table : pandas.DataFrame or np.ndarray or str\n Either a pandas dataframe, a 1D/2D numpy.ndarray or a file name to an\n ASCII data table.\n per_column : bool\n Report the min/max values per column in separate columns.\n spacing : str\n ``'[b|p|f|s]dx[/dy[/dz...]]'``.\n Report the min/max of the first n columns to the nearest multiple of\n the provided increments and output results in the form\n ``[w, e, s, n]``.\n nearest_multiple : str\n ``'dz[+ccol]'``\n Report the min/max of the first (0'th) column to the nearest multiple\n of dz and output this in the form ``[zmin, zmax, dz]``.\n\n Returns\n -------\n output : np.ndarray or str\n Return type depends on whether any of the 'per_column', 'spacing', or\n 'nearest_multiple' parameters are set.\n\n - np.ndarray if either of the above parameters are used.\n - str if none of the above parameters are used.\n \"\"\"\n kind = data_kind(table)\n with Session() as lib:\n if kind == \"file\":\n file_context = dummy_context(table)\n elif kind == \"matrix\":\n _table = np.asanyarray(table)\n if table.ndim == 1: # 1D arrays need to be 2D and transposed\n _table = np.transpose(np.atleast_2d(_table))\n file_context = lib.virtualfile_from_matrix(_table)\n else:\n raise GMTInvalidInput(f\"Unrecognized data type: {type(table)}\")\n\n with GMTTempFile() as tmpfile:\n with file_context as fname:\n arg_str = \" \".join(\n [fname, build_arg_string(kwargs), \"->\" + tmpfile.name]\n )\n lib.call_module(\"info\", arg_str)\n result = tmpfile.read()\n\n if any(arg in kwargs for arg in [\"C\", \"I\", \"T\"]):\n # Converts certain output types into a numpy array\n # instead of a raw string that is less useful.\n if result.startswith((\"-R\", \"-T\")): # e.g. -R0/1/2/3 or -T0/9/1\n result = result[2:].replace(\"/\", \" \")\n result = np.loadtxt(result.splitlines())\n\n return result\n\n\n@fmt_docstring\n@use_alias(G=\"download\")\ndef which(fname, **kwargs):\n \"\"\"\n Find the full path to specified files.\n\n Reports the full paths to the files given through *fname*. We look for\n the file in (1) the current directory, (2) in $GMT_USERDIR (if defined),\n (3) in $GMT_DATADIR (if defined), or (4) in $GMT_CACHEDIR (if defined).\n\n *fname* can also be a downloadable file (either a full URL, a\n `@file` special file for downloading from the GMT Site Cache, or\n `@earth_relief_*` topography grids). In these cases, use option *download*\n to set the desired behavior. If *download* is not used (or False), the file\n will not be found.\n\n Full option list at :gmt-docs:`gmtwhich.html`\n\n {aliases}\n\n Parameters\n ----------\n fname : str\n The file name that you want to check.\n download : bool or str\n If the file is downloadable and not found, we will try to download the\n it. Use True or 'l' (default) to download to the current directory. Use\n 'c' to place in the user cache directory or 'u' user data directory\n instead.\n\n Returns\n -------\n path : str\n The path of the file, depending on the options used.\n\n Raises\n ------\n FileNotFoundError\n If the file is not found.\n\n \"\"\"\n with GMTTempFile() as tmpfile:\n arg_str = \" \".join([fname, build_arg_string(kwargs), \"->\" + tmpfile.name])\n with Session() as lib:\n lib.call_module(\"which\", arg_str)\n path = tmpfile.read().strip()\n if not path:\n raise FileNotFoundError(\"File '{}' not found.\".format(fname))\n return path\n\n\nclass config: # pylint: disable=invalid-name\n \"\"\"\n Set GMT defaults globally or locally.\n\n Change GMT defaults globally::\n\n pygmt.config(PARAMETER=value)\n\n Change GMT defaults locally by using it as a context manager::\n\n with pygmt.config(PARAMETER=value):\n ...\n\n Full GMT defaults list at :gmt-docs:`gmt.conf.html`\n \"\"\"\n\n def __init__(self, **kwargs):\n # Save values so that we can revert to their initial values\n self.old_defaults = {}\n self.special_params = {\n \"FONT\": [\n \"FONT_ANNOT_PRIMARY\",\n \"FONT_ANNOT_SECONDARY\",\n \"FONT_HEADING\",\n \"FONT_LABEL\",\n \"FONT_TAG\",\n \"FONT_TITLE\",\n ],\n \"FONT_ANNOT\": [\"FONT_ANNOT_PRIMARY\", \"FONT_ANNOT_SECONDARY\"],\n \"FORMAT_TIME_MAP\": [\"FORMAT_TIME_PRIMARY_MAP\", \"FORMAT_TIME_SECONDARY_MAP\"],\n \"MAP_ANNOT_OFFSET\": [\n \"MAP_ANNOT_OFFSET_PRIMARY\",\n \"MAP_ANNOT_OFFSET_SECONDARY\",\n ],\n \"MAP_GRID_CROSS_SIZE\": [\n \"MAP_GRID_CROSS_SIZE_PRIMARY\",\n \"MAP_GRID_CROSS_SIZE_SECONDARY\",\n ],\n \"MAP_GRID_PEN\": [\"MAP_GRID_PEN_PRIMARY\", \"MAP_GRID_PEN_SECONDARY\"],\n \"MAP_TICK_LENGTH\": [\"MAP_TICK_LENGTH_PRIMARY\", \"MAP_TICK_LENGTH_SECONDARY\"],\n \"MAP_TICK_PEN\": [\"MAP_TICK_PEN_PRIMARY\", \"MAP_TICK_PEN_SECONDARY\"],\n }\n with Session() as lib:\n for key in kwargs:\n if key in self.special_params:\n for k in self.special_params[key]:\n self.old_defaults[k] = lib.get_default(k)\n else:\n self.old_defaults[key] = lib.get_default(key)\n\n # call gmt set to change GMT defaults\n arg_str = \" \".join(\n [\"{}={}\".format(key, value) for key, value in kwargs.items()]\n )\n with Session() as lib:\n lib.call_module(\"set\", arg_str)\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n # revert to initial values\n arg_str = \" \".join(\n [\"{}={}\".format(key, value) for key, value in self.old_defaults.items()]\n )\n with Session() as lib:\n lib.call_module(\"set\", arg_str)\n\n\[email protected]_dataarray_accessor(\"gmt\")\nclass GMTDataArrayAccessor:\n \"\"\"\n This is the GMT extension for :class:`xarray.DataArray`.\n\n You can access various GMT specific metadata about your grid as follows:\n\n >>> from pygmt.datasets import load_earth_relief\n >>> # Use the global Earth relief grid with 1 degree spacing\n >>> grid = load_earth_relief(resolution=\"01d\")\n\n >>> # See if grid uses Gridline (0) or Pixel (1) registration\n >>> grid.gmt.registration\n 1\n >>> # See if grid uses Cartesian (0) or Geographic (1) coordinate system\n >>> grid.gmt.gtype\n 1\n \"\"\"\n\n def __init__(self, xarray_obj):\n self._obj = xarray_obj\n try:\n self._source = self._obj.encoding[\"source\"] # filepath to NetCDF source\n # From the shortened summary information of `grdinfo`,\n # get grid registration in column 10, and grid type in column 11\n self._registration, self._gtype = map(\n int, grdinfo(self._source, C=\"n\", o=\"10,11\").split()\n )\n except KeyError:\n self._registration = 0 # Default to Gridline registration\n self._gtype = 0 # Default to Cartesian grid type\n\n @property\n def registration(self):\n \"\"\"\n Registration type of the grid, either Gridline (0) or Pixel (1).\n \"\"\"\n return self._registration\n\n @registration.setter\n def registration(self, value):\n if value in (0, 1):\n self._registration = value\n else:\n raise GMTInvalidInput(\n f\"Invalid grid registration value: {value}, should be a boolean of \"\n \"either 0 for Gridline registration or 1 for Pixel registration\"\n )\n\n @property\n def gtype(self):\n \"\"\"\n Coordinate system type of the grid, either Cartesian (0) or Geographic\n (1).\n \"\"\"\n return self._gtype\n\n @gtype.setter\n def gtype(self, value):\n if value in (0, 1):\n self._gtype = value\n else:\n raise GMTInvalidInput(\n f\"Invalid coordinate system type: {value}, should be a boolean of \"\n \"either 0 for Cartesian or 1 for Geographic\"\n )\n" ]
[ [ "matplotlib.testing.compare.compare_images" ], [ "numpy.atleast_2d", "numpy.asanyarray" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
banasraf/DALI
[ "f834f3e619b15e3df87bf0316ac8806d0998126e" ]
[ "dali/test/python/test_operator_warp.py" ]
[ "# 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\nfrom nvidia.dali.pipeline import Pipeline\nimport nvidia.dali.ops as ops\nimport nvidia.dali.types as types\nimport nvidia.dali as dali\nfrom nvidia.dali.backend_impl import TensorListGPU\nimport numpy as np\nimport math\nfrom numpy.testing import assert_array_equal, assert_allclose\nimport os\nimport cv2\nfrom test_utils import check_batch\nfrom test_utils import compare_pipelines\nfrom test_utils import RandomDataIterator\nimport random\n\ntest_data_root = os.environ['DALI_EXTRA_PATH']\ncaffe_db_folder = os.path.join(test_data_root, 'db', 'lmdb')\n\ndef gen_transform(angle, zoom, dst_cx, dst_cy, src_cx, src_cy):\n t1 = np.array([[1, 0, -dst_cx], [0, 1, -dst_cy], [0, 0, 1]])\n cosa = math.cos(angle)/zoom\n sina = math.sin(angle)/zoom\n r = np.array([\n [cosa, -sina, 0],\n [sina, cosa, 0],\n [0, 0, 1]])\n t2 = np.array([[1, 0, src_cx], [0, 1, src_cy], [0, 0, 1]])\n return (np.matmul(t2, np.matmul(r, t1)))[0:2,0:3]\n\ndef gen_transforms(n, step):\n a = 0.0\n step = step * (math.pi/180)\n out = np.zeros([n, 2, 3])\n for i in range(n):\n out[i,:,:] = gen_transform(a, 2, 160, 120, 100, 100)\n a = a + step\n return out.astype(np.float32)\n\ndef ToCVMatrix(matrix):\n offset = np.matmul(matrix, np.array([[0.5], [0.5], [1]]))\n result = matrix.copy()\n result[0][2] = offset[0] - 0.5\n result[1][2] = offset[1] - 0.5\n return result\n\ndef CVWarp(output_type, input_type, warp_matrix = None, inv_map = False):\n def warp_fn(img, matrix):\n size = (320, 240)\n matrix = ToCVMatrix(matrix)\n if output_type == dali.types.FLOAT or input_type == dali.types.FLOAT:\n img = np.float32(img)\n out = cv2.warpAffine(img, matrix, size, borderMode = cv2.BORDER_CONSTANT, borderValue = [42,42,42],\n flags = (cv2.INTER_LINEAR|cv2.WARP_INVERSE_MAP) if inv_map else cv2.INTER_LINEAR);\n if output_type == dali.types.UINT8 and input_type == dali.types.FLOAT:\n out = np.uint8(np.clip(out, 0, 255))\n return out\n\n if warp_matrix:\n m = np.array(warp_matrix)\n def warp_fixed(img):\n return warp_fn(img, m)\n return warp_fixed\n\n return warp_fn\n\n\nclass WarpPipeline(Pipeline):\n def __init__(self, device, batch_size, output_type, input_type, use_input, num_threads=3, device_id=0, num_gpus=1, inv_map=False):\n super(WarpPipeline, self).__init__(batch_size, num_threads, device_id, seed=7865, exec_async=False, exec_pipelined=False)\n self.use_input = use_input\n self.use_dynamic_size = use_input # avoid Cartesian product\n self.name = device\n self.input = ops.CaffeReader(path = caffe_db_folder, shard_id = device_id, num_shards = num_gpus)\n self.decode = ops.ImageDecoder(device = \"cpu\", output_type = types.RGB)\n if input_type != dali.types.UINT8:\n self.cast = ops.Cast(device = device, dtype = input_type)\n else:\n self.cast = None\n\n static_size = None if self.use_dynamic_size else (240,320)\n\n if use_input:\n self.transform_source = ops.ExternalSource(lambda: gen_transforms(self.batch_size, 10))\n self.warp = ops.WarpAffine(device = device, size=static_size, fill_value = 42, dtype = output_type, inverse_map=inv_map)\n else:\n warp_matrix = (0.1, 0.9, 10, 0.8, -0.2, -20)\n self.warp = ops.WarpAffine(device = device, size=static_size, matrix = warp_matrix, fill_value = 42, dtype = output_type, inverse_map=inv_map)\n\n self.iter = 0\n\n def define_graph(self):\n self.jpegs, self.labels = self.input(name = \"Reader\")\n images = self.decode(self.jpegs)\n if self.warp.device == \"gpu\":\n images = images.gpu()\n if self.cast:\n images = self.cast(images)\n\n dynamic_size = types.Constant(np.array([240, 320], dtype=np.float32)) if self.use_dynamic_size else None\n\n if self.use_input:\n transform = self.transform_source()\n outputs = self.warp(images, transform, size = dynamic_size)\n else:\n outputs = self.warp(images, size = dynamic_size)\n return outputs\n\n\nclass CVPipeline(Pipeline):\n def __init__(self, batch_size, output_type, input_type, use_input, num_threads=3, device_id=0, num_gpus=1, inv_map=False):\n super(CVPipeline, self).__init__(batch_size, num_threads, device_id, seed=7865, exec_async=False, exec_pipelined=False)\n self.use_input = use_input\n self.name = \"cv\"\n self.input = ops.CaffeReader(path = caffe_db_folder, shard_id = device_id, num_shards = num_gpus)\n self.decode = ops.ImageDecoder(device = \"cpu\", output_type = types.RGB)\n if self.use_input:\n self.transform_source = ops.ExternalSource(lambda: gen_transforms(self.batch_size, 10))\n self.warp = ops.PythonFunction(function=CVWarp(output_type, input_type, inv_map=inv_map))\n else:\n self.warp = ops.PythonFunction(function=CVWarp(output_type, input_type, [[0.1, 0.9, 10], [0.8, -0.2, -20]], inv_map))\n self.set_layout = ops.Reshape(layout=\"HWC\")\n self.iter = 0\n\n def define_graph(self):\n self.jpegs, self.labels = self.input(name = \"Reader\")\n images = self.decode(self.jpegs)\n if self.use_input:\n self.transform = self.transform_source()\n outputs = self.warp(images, self.transform)\n else:\n outputs = self.warp(images)\n outputs = self.set_layout(outputs)\n return outputs\n\ndef compare(pipe1, pipe2, eps):\n epoch_size = pipe1.epoch_size(\"Reader\")\n batch_size = pipe1.batch_size\n niter = (epoch_size + batch_size - 1) // batch_size\n compare_pipelines(pipe1, pipe2, batch_size, niter, eps);\n\nio_types = [\n (dali.types.UINT8, dali.types.UINT8),\n (dali.types.UINT8, dali.types.FLOAT),\n (dali.types.FLOAT, dali.types.UINT8),\n (dali.types.FLOAT, dali.types.FLOAT)\n]\n\n\ndef test_cpu_vs_cv():\n random.seed(1009)\n for batch_size in [1, 4, 19]:\n for use_input in [False, True]:\n for (itype, otype) in io_types:\n inv_map = random.choice([False, True])\n print(\"Testing cpu vs cv\",\n \"\\nbatch size: \", batch_size,\n \" matrix as input: \", use_input,\n \" input_type: \", itype,\n \" output_type: \", otype,\n \" map_inverse:\", inv_map)\n cv_pipeline = CVPipeline(batch_size, otype, itype, use_input, inv_map=inv_map);\n cv_pipeline.build();\n\n cpu_pipeline = WarpPipeline(\"cpu\", batch_size, otype, itype, use_input, inv_map=inv_map);\n cpu_pipeline.build();\n\n compare(cv_pipeline, cpu_pipeline, 8)\n\ndef test_gpu_vs_cv():\n random.seed(1007)\n for batch_size in [1, 4, 19]:\n for use_input in [False, True]:\n for (itype, otype) in io_types:\n inv_map = random.choice([False, True])\n print(\"Testing gpu vs cv\",\n \"\\nbatch size: \", batch_size,\n \" matrix as input: \", use_input,\n \" input_type: \", itype,\n \" output_type: \", otype,\n \" map_inverse:\", inv_map)\n cv_pipeline = CVPipeline(batch_size, otype, itype, use_input, inv_map=inv_map);\n cv_pipeline.build();\n\n gpu_pipeline = WarpPipeline(\"gpu\", batch_size, otype, itype, use_input, inv_map=inv_map);\n gpu_pipeline.build();\n\n compare(cv_pipeline, gpu_pipeline, 8)\n\ndef test_gpu_vs_cpu():\n random.seed(1005)\n for batch_size in [1, 4, 19]:\n for use_input in [False, True]:\n for (itype, otype) in io_types:\n inv_map = random.choice([False, True])\n print(\"Testing gpu vs cpu\",\n \"\\nbatch size: \", batch_size,\n \" matrix as input: \", use_input,\n \" input_type: \", itype,\n \" output_type: \", otype,\n \" map_inverse:\", inv_map)\n cpu_pipeline = WarpPipeline(\"cpu\", batch_size, otype, itype, use_input, inv_map=inv_map);\n cpu_pipeline.build();\n\n gpu_pipeline = WarpPipeline(\"gpu\", batch_size, otype, itype, use_input, inv_map=inv_map);\n gpu_pipeline.build();\n\n compare(cpu_pipeline, gpu_pipeline, 1)\n" ]
[ [ "numpy.clip", "numpy.matmul", "numpy.float32", "numpy.array", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jiangyuang/ModelPruningLibrary
[ "9c8ba5a3c5d118f37768d5d42254711f48d88745" ]
[ "mpl/models/base_model.py" ]
[ "from abc import ABC, abstractmethod\nfrom typing import Union, Sized, List, Tuple\nfrom copy import deepcopy\n\nimport torch\nfrom torch import nn as nn\n\nfrom ..nn.linear import DenseLinear\nfrom ..nn.conv2d import DenseConv2d\nfrom .utils import collect_leaf_modules, is_parameterized\n\n\nclass BaseModel(nn.Module, ABC):\n def __init__(self):\n super(BaseModel, self).__init__()\n\n self.prunable_layers: list = []\n self.prunable_layer_prefixes: list = []\n\n def clone_from_model(self, original_model: nn.Module = None):\n # copying all submodules from original model\n for name, module in original_model._modules.items():\n self.add_module(name, deepcopy(module))\n\n def collect_prunable_layers(self) -> None:\n self.prunable_layers, self.prunable_layer_prefixes = self.find_layers(lambda x: is_parameterized(x))\n\n def convert_eligible_layers(self):\n # changing all conv2d and linear layers to customized ones\n for module_name, old_module in zip(self.prunable_layer_prefixes, self.prunable_layers):\n if isinstance(old_module, nn.Linear):\n self.set_module_by_name(module_name, DenseLinear.from_linear(old_module))\n elif isinstance(old_module, nn.Conv2d):\n self.set_module_by_name(module_name, DenseConv2d.from_conv2d(old_module))\n\n def find_layers(self, criterion) -> Tuple[List, List]:\n layers, names = [], []\n collect_leaf_modules(self, criterion, layers, names)\n return layers, names\n\n @abstractmethod\n def forward(self, inputs) -> torch.Tensor:\n pass\n\n def prune_by_threshold(self, thr_arg: Union[int, float, Sized]):\n prunable_layers = self.prunable_layers\n if isinstance(thr_arg, Sized):\n assert len(prunable_layers) == len(thr_arg)\n else:\n thr_arg = [thr_arg] * len(prunable_layers)\n for thr, layer in zip(thr_arg, prunable_layers):\n if thr is not None:\n layer.prune_by_threshold(thr)\n\n return self\n\n def prune_by_rank(self, rank_arg: Union[int, float, Sized]):\n prunable_layers = self.prunable_layers\n if isinstance(rank_arg, Sized):\n assert len(prunable_layers) == len(rank_arg)\n else:\n rank_arg = [rank_arg] * len(prunable_layers)\n for rank, layer in zip(rank_arg, prunable_layers):\n if rank is not None:\n layer.prune_by_rank(rank)\n\n return self\n\n def prune_by_pct(self, pct_arg: Union[int, float, Sized]):\n prunable_layers = self.prunable_layers\n if isinstance(pct_arg, Sized):\n assert len(prunable_layers) == len(pct_arg)\n else:\n pct_arg = [pct_arg] * len(prunable_layers)\n for pct, layer in zip(pct_arg, prunable_layers):\n if pct is not None:\n layer.prune_by_pct(pct)\n\n return self\n\n def random_prune_by_pct(self, pct_arg: Union[int, float, Sized]):\n prunable_layers = self.prunable_layers\n if isinstance(pct_arg, Sized):\n assert len(prunable_layers) == len(pct_arg)\n else:\n pct_arg = [pct_arg] * len(prunable_layers)\n for pct, layer in zip(pct_arg, prunable_layers):\n if pct is not None:\n layer.random_prune_by_pct(pct)\n\n return self\n\n def calc_num_prunable_params(self, count_bias=True, display=False):\n total_param_in_use = 0\n total_param = 0\n for layer, layer_prefix in zip(self.prunable_layers, self.prunable_layer_prefixes):\n num_bias = layer.bias.nelement() if layer.bias is not None and count_bias else 0\n num_weight = layer.num_weight\n num_params_in_use = num_weight + num_bias\n num_params = layer.weight.nelement() + num_bias\n total_param_in_use += num_params_in_use\n total_param += num_params\n\n if display:\n print(\"Layer name: {}. remaining/all: {}/{} = {}\".format(layer_prefix, num_params_in_use, num_params,\n num_params_in_use / num_params))\n if display:\n print(\"Total: remaining/all: {}/{} = {}\".format(total_param_in_use, total_param,\n total_param_in_use / total_param))\n return total_param_in_use, total_param\n\n def nnz(self, count_bias=True):\n # number of parameters in use in prunable layers\n return self.calc_num_prunable_params(count_bias=count_bias)[0]\n\n def nelement(self, count_bias=True):\n # number of all parameters in prunable layers\n return self.calc_num_prunable_params(count_bias=count_bias)[1]\n\n def density(self, count_bias=True):\n total_param_in_use, total_param = self.calc_num_prunable_params(count_bias=count_bias)\n return total_param_in_use / total_param\n\n def _get_module_by_list(self, module_names: List):\n module = self\n for name in module_names:\n module = getattr(module, name)\n return module\n\n def get_module_by_name(self, module_name: str):\n return self._get_module_by_list(module_name.split('.'))\n\n def set_module_by_name(self, module_name: str, new_module):\n splits = module_name.split('.')\n self._get_module_by_list(splits[:-1]).__setattr__(splits[-1], new_module)\n\n def get_mask_by_name(self, param_name: str):\n if param_name.endswith(\"bias\"): # todo\n return None\n module = self._get_module_by_list(param_name.split('.')[:-1])\n return module.mask if hasattr(module, \"mask\") else None\n\n @torch.no_grad()\n def reinit_from_model(self, final_model):\n assert isinstance(final_model, self.__class__)\n for self_layer, layer in zip(self.prunable_layers, final_model.prunable_layers):\n self_layer.mask = layer.mask.clone().to(self_layer.mask.device)\n\n def to_sparse(self):\n self_copy = deepcopy(self)\n for module_name, old_module in zip(self.prunable_layer_prefixes, self.prunable_layers):\n self_copy.set_module_by_name(module_name, old_module.to_sparse())\n self.collect_prunable_layers()\n return self_copy\n\n def to(self, *args, **kwargs):\n device = torch._C._nn._parse_to(*args, **kwargs)[0]\n if device is not None:\n # move masks to device\n for m in self.prunable_layers:\n m.move_data(device)\n return super(BaseModel, self).to(*args, **kwargs)\n" ]
[ [ "torch.no_grad", "torch._C._nn._parse_to" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
veqtrus/electricitymap-contrib
[ "4ec4857da1315899159688fe1fb7f95376a6badd" ]
[ "parsers/AX.py" ]
[ "#!/usr/bin/env python3\n# The arrow library is used to handle datetimes\nimport arrow\n# The request library is used to fetch content through HTTP\nimport requests\n\n# Numpy and PIL are used to process the image\nimport numpy as np\nfrom PIL import Image\n\n\ndef _get_masks(session=None):\n Minus = np.array([[[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255]],\n [[255, 255, 255],[255, 255, 255], [255, 255, 255], [255, 255, 255],[255, 255, 255],[255, 255, 255]],\n [[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255]],\n [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]],\n [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]],\n [[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255]],\n [[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255]],\n [[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255]],\n [[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255]]], dtype = np.uint8)\n Minus = Image.fromarray(Minus)\n \n Dot = np.array([[[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255]],\n [[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255]],\n [[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255]],\n [[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255]],\n [[255, 255, 255],[255, 255, 255],[255, 255, 255], [255, 255, 255],[255, 255, 255],[255, 255, 255]],\n [[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255]],\n [[255, 255, 255],[255, 255, 255],[0, 0, 0],[0, 0, 0],[255, 255, 255],[255, 255, 255]],\n [[255, 255, 255],[0, 0, 0],[0, 0, 0],[0, 0, 0],[0, 0, 0],[255, 255, 255]],\n [[255, 255, 255],[255, 255, 255],[0, 0, 0],[0, 0, 0],[255, 255, 255],[255, 255, 255]]], dtype=np.uint8)\n Dot = Image.fromarray(Dot)\n\n Zero = np.array([[[255, 255, 255],[0, 0, 0],[0, 0, 0],[0, 0, 0],[0, 0, 0],[255, 255, 255]],\n [[0, 0, 0],[0, 0, 0],[255, 255, 255],[255, 255, 255],[0, 0, 0],[0, 0, 0]],\n [[0, 0, 0],[0, 0, 0],[255, 255, 255],[255, 255, 255],[0, 0, 0],[0, 0, 0]],\n [[0, 0, 0], [0, 0, 0], [255, 255, 255], [0, 0, 0], [0, 0, 0], [0, 0, 0]],\n [[0, 0, 0], [0, 0, 0], [0, 0, 0], [255, 255, 255], [0, 0, 0], [0, 0, 0]],\n [[0, 0, 0],[0, 0, 0],[255, 255, 255],[255, 255, 255],[0, 0, 0],[0, 0, 0]],\n [[0, 0, 0],[0, 0, 0],[255, 255, 255],[255, 255, 255],[0, 0, 0],[0, 0, 0]],\n [[255, 255, 255],[0, 0, 0],[0, 0, 0],[0, 0, 0],[0, 0, 0],[255, 255, 255]],\n [[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255]]], dtype = np.uint8)\n Zero = Image.fromarray(Zero)\n\n One = np.array([[[255, 255, 255],[255, 255, 255],[0, 0, 0],[0, 0, 0],[255, 255, 255],[255, 255, 255]],\n [[255, 255, 255],[0, 0, 0],[0, 0, 0],[0, 0, 0],[255, 255, 255],[255, 255, 255]],\n [[0, 0, 0],[255, 255, 255],[0, 0, 0],[0, 0, 0],[255, 255, 255],[255, 255, 255]],\n [[255, 255, 255],[255, 255, 255],[0, 0, 0],[0, 0, 0],[255, 255, 255],[255, 255, 255]],\n [[255, 255, 255],[255, 255, 255],[0, 0, 0],[0, 0, 0],[255, 255, 255],[255, 255, 255]],\n [[255, 255, 255],[255, 255, 255],[0, 0, 0],[0, 0, 0],[255, 255, 255],[255, 255, 255]],\n [[255, 255, 255],[255, 255, 255],[0, 0, 0],[0, 0, 0],[255, 255, 255],[255, 255, 255]],\n [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]],\n [[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255]]], dtype = np.uint8)\n One = Image.fromarray(One)\n\n Two = np.array([[[255, 255, 255],[0, 0, 0],[0, 0, 0],[0, 0, 0],[0, 0, 0],[255, 255, 255]],\n [[0, 0, 0],[0, 0, 0],[255, 255, 255],[255, 255, 255],[0, 0, 0],[0, 0, 0]],\n [[0, 0, 0],[0, 0, 0],[255, 255, 255],[255, 255, 255],[0, 0, 0],[0, 0, 0]],\n [[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255],[0, 0, 0],[0, 0, 0]],\n [[255, 255, 255],[255, 255, 255],[0, 0, 0],[0, 0, 0],[0, 0, 0],[255, 255, 255]],\n [[255, 255, 255],[0, 0, 0],[0, 0, 0],[255, 255, 255],[255, 255, 255],[255, 255, 255]],\n [[0, 0, 0],[0, 0, 0],[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255]],\n [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]],\n [[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255]]], dtype = np.uint8)\n Two = Image.fromarray(Two)\n\n Three = np.array([[[255, 255, 255],[0, 0, 0],[0, 0, 0],[0, 0, 0],[0, 0, 0],[255, 255, 255]],\n [[0, 0, 0],[0, 0, 0],[255, 255, 255],[255, 255, 255],[0, 0, 0],[0, 0, 0]],\n [[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255],[0, 0, 0],[0, 0, 0]],\n [[255, 255, 255],[0, 0, 0],[0, 0, 0],[0, 0, 0],[0, 0, 0],[255, 255, 255]],\n [[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255],[0, 0, 0],[0, 0, 0]],\n [[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255],[0, 0, 0],[0, 0, 0]],\n [[0, 0, 0],[0, 0, 0],[255, 255, 255],[255, 255, 255],[0, 0, 0],[0, 0, 0]],\n [[255, 255, 255],[0, 0, 0],[0, 0, 0],[0, 0, 0],[0, 0, 0],[255, 255, 255]],\n [[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255]]], dtype =np.uint8)\n Three = Image.fromarray(Three)\n\n Four = np.array([[[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255],[0, 0, 0],[0, 0, 0]],\n [[255, 255, 255],[255, 255, 255],[255, 255, 255],[0, 0, 0],[0, 0, 0],[0, 0, 0]],\n [[255, 255, 255],[255, 255, 255],[0, 0, 0],[0, 0, 0],[0, 0, 0],[0, 0, 0]],\n [[255, 255, 255],[0, 0, 0],[0, 0, 0],[255, 255, 255],[0, 0, 0],[0, 0, 0]],\n [[0, 0, 0],[0, 0, 0],[255, 255, 255],[255, 255, 255],[0, 0, 0],[0, 0, 0]],\n [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]],\n [[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255],[0, 0, 0],[0, 0, 0]],\n [[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255],[0, 0, 0],[0, 0, 0]],\n [[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255]]], dtype=np.uint8)\n Four = Image.fromarray(Four)\n\n Five = np.array([[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]],\n [[0, 0, 0],[0, 0, 0],[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255]],\n [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [255, 255, 255]],\n [[0, 0, 0],[0, 0, 0],[255, 255, 255],[255, 255, 255],[0, 0, 0],[0, 0, 0]],\n [[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255],[0, 0, 0],[0, 0, 0]],\n [[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255],[0, 0, 0],[0, 0, 0]],\n [[0, 0, 0],[0, 0, 0],[255, 255, 255],[255, 255, 255],[0, 0, 0],[0, 0, 0]],\n [[255, 255, 255],[0, 0, 0],[0, 0, 0],[0, 0, 0],[0, 0, 0],[255, 255, 255]],\n [[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255]]], dtype = np.uint8)\n Five = Image.fromarray(Five)\n\n Six = np.array([[[255, 255, 255],[0, 0, 0],[0, 0, 0],[0, 0, 0],[0, 0, 0],[255, 255, 255]],\n [[0, 0, 0],[0, 0, 0], [255, 255, 255],[255, 255, 255],[0, 0, 0],[0, 0, 0]],\n [[0, 0, 0],[0, 0, 0],[255, 255, 255],[255, 255, 255], [255, 255, 255], [255, 255, 255]],\n [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [255, 255, 255]],\n [[0, 0, 0], [0, 0, 0], [255, 255, 255], [255, 255, 255], [0, 0, 0], [0, 0, 0]],\n [[0, 0, 0], [0, 0, 0], [255, 255, 255], [255, 255, 255], [0, 0, 0], [0, 0, 0]],\n [[0, 0, 0],[0, 0, 0], [255, 255, 255], [255, 255, 255], [0, 0, 0], [0, 0, 0]],\n [[255, 255, 255], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [255, 255, 255]],\n [[255, 255, 255], [255, 255, 255], [255, 255, 255],[255, 255, 255], [255, 255, 255],[255, 255, 255]]], dtype = np.uint8)\n Six = Image.fromarray(Six)\n\n Seven = np.array([[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]],\n [[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255],[0, 0, 0],[0, 0, 0]],\n [[255, 255, 255],[255, 255, 255],[255, 255, 255],[0, 0, 0],[0, 0, 0],[255, 255, 255]],\n [[255, 255, 255],[255, 255, 255],[255, 255, 255],[0, 0, 0],[0, 0, 0],[255, 255, 255]],\n [[255, 255, 255],[255, 255, 255],[0, 0, 0],[0, 0, 0],[255, 255, 255],[255, 255, 255]],\n [[255, 255, 255], [255, 255, 255], [0, 0, 0], [0, 0, 0], [255, 255, 255], [255, 255, 255]],\n [[255, 255, 255],[0, 0, 0],[0, 0, 0],[255, 255, 255],[255, 255, 255],[255, 255, 255]],\n [[255, 255, 255],[0, 0, 0],[0, 0, 0],[255, 255, 255],[255, 255, 255],[255, 255, 255]],\n [[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255]]], dtype = np.uint8)\n Seven = Image.fromarray(Seven)\n\n Eight = np.array([[[255, 255, 255],[0, 0, 0],[0, 0, 0],[0, 0, 0],[0, 0, 0],[255, 255, 255]],\n [[0, 0, 0],[0, 0, 0],[255, 255, 255],[255, 255, 255],[0, 0, 0],[0, 0, 0]],\n [[0, 0, 0],[0, 0, 0], [255, 255, 255],[255, 255, 255],[0, 0, 0],[0, 0, 0]],\n [[255, 255, 255],[0, 0, 0],[0, 0, 0],[0, 0, 0],[0, 0, 0],[255, 255, 255]],\n [[0, 0, 0],[0, 0, 0],[255, 255, 255],[255, 255, 255],[0, 0, 0], [0, 0, 0]],\n [[0, 0, 0],[0, 0, 0],[255, 255, 255],[255, 255, 255],[0, 0, 0],[0, 0, 0]],\n [[0, 0, 0],[0, 0, 0],[255, 255, 255],[255, 255, 255], [0, 0, 0],[0, 0, 0]],\n [[255, 255, 255],[0, 0, 0],[0, 0, 0],[0, 0, 0],[0, 0, 0],[255, 255, 255]],\n [[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255],[255, 255, 255]]], dtype = np.uint8)\n Eight = Image.fromarray(Eight)\n\n Nine = np.array([[[255, 255, 255],[0, 0, 0],[0, 0, 0],[0, 0, 0],[0, 0, 0],[255, 255, 255]],\n [[0, 0, 0],[0, 0, 0],[255, 255, 255],[255, 255, 255],[0, 0, 0],[0, 0, 0]],\n [[0, 0, 0], [0, 0, 0], [255, 255, 255], [255, 255, 255], [0, 0, 0], [0, 0, 0]],\n [[0, 0, 0], [0, 0, 0], [255, 255, 255], [255, 255, 255], [0, 0, 0], [0, 0, 0]],\n [[255, 255, 255], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]],\n [[255, 255, 255], [255, 255, 255], [255, 255, 255], [255, 255, 255], [0, 0, 0], [0, 0, 0]],\n [[0, 0, 0], [0, 0, 0], [255, 255, 255], [255, 255, 255], [0, 0, 0], [0, 0, 0]],\n [[255, 255, 255],[0, 0, 0],[0, 0, 0],[0, 0, 0],[0, 0, 0],[255, 255, 255]],\n [[255, 255, 255],[255, 255, 255], [255, 255, 255], [255, 255, 255], [255, 255, 255], [255, 255, 255]]], dtype=np.uint8)\n Nine = Image.fromarray(Nine)\n \n shorts = ['-','.','0','1','2','3','4','5','6','7','8','9']\n masks = [Minus, Dot, Zero, One, Two, Three, Four, Five, Six, Seven, Eight, Nine]\n \n return dict(zip(shorts,masks))\n \n\ndef _fetch_data(session=None):\n # Load masks for reading numbers from the image\n # Create a dictionary of symbols and their pixel masks\n mapping = _get_masks(session)\n\n # Download the updating image from Kraftnät Åland\n r = session or requests.session()\n \n url = 'http://194.110.178.135/grafik/stamnat.php'\n \n im = Image.open(r.get(url, stream=True).raw)\n # Get timestamp\n fetchtime = arrow.utcnow().floor('second').to('Europe/Mariehamn')\n \n # \"data\" is a height x width x 3 RGB numpy array\n data = np.array(im) \n #red, green, blue, alpha = data.T # Temporarily unpack the bands for readability\n red, green, blue = data.T\n # Color non-blue areas in the image with white\n blue_areas = ((red == 0) & (green == 0) & (blue == 255))\n data[~blue_areas.T] = (255, 255, 255)\n # Color blue areas in the image with black\n data[blue_areas.T] = (0, 0, 0)\n \n # Transform the array back to image\n im = Image.fromarray(data)\n \n shorts = mapping.keys()\n\n # check import from Sweden\n SE3Flow = []\n for x in range(80, 130-6):\n for abr in shorts:\n im1 = im.crop((x, 443, x+6, 452))\n if im1 == mapping[abr]:\n SE3Flow.append(abr)\n SE3Flow = \"\".join(SE3Flow)\n SE3Flow = round(float(SE3Flow),1)\n\n # export Åland-Finland(Kustavi/Gustafs)\n \n GustafsFlow=[]\n for x in range(780, 825-6):\n for abr in shorts:\n im1 = im.crop((x, 43, x+6, 52))\n if im1 == mapping[abr]:\n GustafsFlow.append(abr)\n GustafsFlow = \"\".join(GustafsFlow)\n GustafsFlow = round(float(GustafsFlow),1)\n \n # Reserve cable import Naantali-Åland\n # Åland administration does not allow export\n # to Finland through this cable\n FIFlow = []\n for x in range(760, 815-6):\n for abr in shorts:\n im1 = im.crop((x, 328, x+6, 337))\n if im1 == mapping[abr]:\n FIFlow.append(abr)\n FIFlow = \"\".join(FIFlow)\n FIFlow = round(float(FIFlow),1)\n\n\n # The shown total consumption is not reliable according to the TSO\n # Consumption\n # Cons = []\n # for x in range(650, 700-6):\n # for abr in shorts:\n # im1 = im.crop((x, 564, x+6, 573))\n # if im1 == mapping[abr]:\n # Cons.append(abr)\n # Cons = \"\".join(Cons)\n # Cons = round(float(Cons),1)\n\n # Wind production\n WProd = []\n for x in range(650, 700-6):\n for abr in shorts:\n im1 = im.crop((x, 576, x+6, 585))\n if im1 == mapping[abr]:\n WProd.append(abr)\n WProd = \"\".join(WProd)\n WProd = round(float(WProd),1)\n\n # Fossil fuel production\n FProd = []\n for x in range(650, 700-6):\n for abr in shorts:\n im1 = im.crop((x, 588, x+6, 597))\n if im1 == mapping[abr]:\n FProd.append(abr)\n FProd = \"\".join(FProd)\n FProd = round(float(FProd),1)\n \n # Both are confirmed to be import from Finland by the TSO\n FIFlow = FIFlow+GustafsFlow\n \n # Calculate sum of exchanges\n SumExchanges = SE3Flow+FIFlow\n \n # Calculate total production\n TotProd = FProd+WProd\n \n # Calculate total consumption\n Cons = round(TotProd + SumExchanges,1)\n \n # The production that is not fossil fuel or wind based is unknown\n # Impossible to estimate with current data\n # UProd = TotProd - WProd - FProd\n \n obj = dict({'production':TotProd,'consumption':Cons,'wind':WProd,\n 'fossil':FProd,'SE3->AX':SE3Flow,\n 'FI->AX':FIFlow,'fetchtime':fetchtime})\n \n return obj\n\n\ndef fetch_production(zone_key='AX', session=None, target_datetime=None, logger=None) -> dict:\n \"\"\"Requests the last known production mix (in MW) of a given country.\"\"\"\n if target_datetime:\n raise NotImplementedError('This parser is not yet able to parse past dates')\n\n obj = _fetch_data(session)\n\n data = {\n 'zoneKey': zone_key,\n 'production': {},\n 'storage': {},\n 'source': 'kraftnat.aland.fi',\n 'datetime': arrow.get(obj['fetchtime']).datetime\n }\n data['production']['biomass'] = None\n data['production']['coal'] = 0\n data['production']['gas'] = 0\n data['production']['hydro'] = None\n data['production']['nuclear'] = 0\n data['production']['oil'] = obj['fossil']\n data['production']['solar'] = None\n data['production']['wind'] = obj['wind']\n data['production']['geothermal'] = None\n data['production']['unknown'] = None\n \n return data\n\n\ndef fetch_consumption(zone_key='AX', session=None, target_datetime=None, logger=None):\n if target_datetime:\n raise NotImplementedError('This parser is not yet able to parse past dates')\n\n obj = _fetch_data(session)\n \n data = {\n 'zoneKey': zone_key,\n 'datetime': arrow.get(obj['fetchtime']).datetime,\n 'consumption': obj['consumption'],\n 'source': 'kraftnat.aland.fi'\n }\n \n return data\n\n\ndef fetch_exchange(zone_key1, zone_key2, session=None, target_datetime=None, logger=None) -> dict:\n \"\"\"Requests the last known power exchange (in MW) between two countries.\"\"\"\n if target_datetime:\n raise NotImplementedError('This parser is not yet able to parse past dates')\n\n obj = _fetch_data(session)\n\n data = {\n 'sortedZoneKeys': '->'.join(sorted([zone_key1, zone_key2])),\n 'source': 'kraftnat.aland.fi',\n 'datetime': arrow.get(obj['fetchtime']).datetime\n }\n\n # Country codes are sorted in order to enable easier indexing in the database\n sorted_zone_keys = sorted([zone_key1, zone_key2])\n # Here we assume that the net flow returned by the api is the flow from\n # country1 to country2. A positive flow indicates an export from country1\n # to country2. A negative flow indicates an import.\n \n if '->'.join(sorted([zone_key1, zone_key2])) in ['AX->SE', 'AX->SE-SE3']:\n netFlow = obj['SE3->AX']\n \n elif '->'.join(sorted([zone_key1, zone_key2]))== 'AX->FI':\n netFlow = obj['FI->AX'] # Import is positive\n \n # The net flow to be reported should be from the first country to the second\n # (sorted alphabetically). This is NOT necessarily the same direction as the flow\n # from country1 to country2\n \n # AX is before both FI and SE\n data['netFlow'] = round(-1*netFlow,1)\n\n return data\n\n\nif __name__ == '__main__':\n \"\"\"Main method, never used by the Electricity Map backend, but handy for testing.\"\"\"\n\n print('fetch_production() ->')\n print(fetch_production())\n print('fetch_consumption() ->')\n print(fetch_consumption())\n print('fetch_exchange(AX, FI) ->')\n print(fetch_exchange('FI', 'AX'))\n print('fetch_exchange(AX, SE) ->')\n print(fetch_exchange('SE', 'AX'))\n" ]
[ [ "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
drcastillo/hicss2020
[ "0a812257215c75054d8b891e23c933d6a8327c0d" ]
[ "utils/helpful_util.py" ]
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# Reference:\n\n#from __future__ import print_function\n#from utils.heaton_utils import *\n\nimport numpy as np\nimport warnings\nimport os\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport sys\nimport glob\n#pip install counter\nfrom collections import Counter\n\nimport pickle\nimport sklearn\nfrom sklearn.model_selection import GridSearchCV, cross_val_score, StratifiedKFold, learning_curve\n\nfrom keras.models import load_model\nfrom keras.models import model_from_json\nfrom sklearn.model_selection import train_test_split\n\nimport seaborn as sns\nfrom IPython.display import display, HTML\nfrom sklearn.metrics import classification_report\nfrom utils.perturbation import load_models_lendingclub\nfrom IPython.display import display_html, display, HTML\nimport lime.lime_tabular\nimport lime\n\nclass KerasModelUtil:\n\n modelwts_extension = \"h5\"\n json_extension = \"json\"\n pickle_extension = \"p\"\n\n def save(self, model_dir, model_name, model, label_class_map):\n if model_dir.endswith('/') == False:\n model_dir = model_dir + '/'\n\n # put the file name into specific tokens\n fn_base, sep, tail = model_name.partition('.')\n if not sep:\n sep = \".\"\n\n json_fn = model_dir + fn_base + sep + self.json_extension\n\n wt_ext = tail\n if not wt_ext:\n wt_ext = self.modelwts_extension\n wt_fn = model_dir + fn_base + sep + wt_ext\n\n pickle_fn = model_dir + fn_base + sep + self.pickle_extension\n\n pickle.dump(label_class_map, open(pickle_fn, 'wb'))\n\n # serialize model to JSON\n model_json = model.to_json()\n\n with open(json_fn, \"w\") as json_file:\n json_file.write(model_json)\n\n # serialize weights to HDF5\n model.save_weights(wt_fn)\n\n def load(self, model_dir, model_name, input_shape=(None, 224, 224, 3)):\n # Load the json model first\n if model_dir.endswith('/') == False:\n model_dir = model_dir + '/'\n\n # put the file name into specific tokens\n fn_base, sep, tail = model_name.partition('.')\n if not sep:\n sep = \".\"\n\n json_fn = model_dir + fn_base + sep + self.json_extension\n json_file = open(json_fn, 'r')\n loaded_model_json = json_file.read()\n json_file.close()\n\n # form the model from the json and rebuild the layers\n loaded_model = model_from_json(loaded_model_json)\n loaded_model.build(input_shape=input_shape)\n\n # Load the weights\n wt_ext = tail\n if not wt_ext:\n wt_ext = self.modelwts_extension\n wt_fn = model_dir + fn_base + sep + wt_ext\n loaded_model.load_weights(wt_fn)\n\n #print(\"Loaded model from disk\")\n\n # Load the labels and Class ids\n pickle_fn = model_dir + fn_base + sep + self.pickle_extension\n label_classids = pickle.load(open(pickle_fn, \"rb\"))\n class_label_map = {v: k for k, v in label_classids.items()}\n #print(label_classids)\n #print(classids_labels)\n\n return loaded_model, class_label_map\n\n\n##################################################\n# Keras callbacks for plotting training model\n# accuracy and loss\n##################################################\nfrom IPython.display import clear_output\nimport math\nimport keras\n\n\n#Can just import LiveLossPlot & add to model callbacks.\nclass TrainingPlot(keras.callbacks.Callback):\n def on_train_begin(self, logs={}):\n self.i = 0\n self.x = []\n self.losses = []\n self.val_losses = []\n self.acc = []\n self.val_acc = []\n\n self.logs = []\n\n def on_epoch_end(self, epoch, logs={}):\n\n self.logs.append(logs)\n self.x.append(self.i)\n self.losses.append(logs.get('loss'))\n self.val_losses.append(logs.get('val_loss'))\n self.acc.append(logs.get('acc'))\n self.val_acc.append(logs.get('val_acc'))\n self.i += 1\n f, (ax1, ax2) = plt.subplots(1, 2, sharex=False)\n\n clear_output(wait=True)\n\n ax1.set_yscale('log')\n ax1.plot(self.x, self.losses, label=\"training loss\")\n ax1.plot(self.x, self.val_losses, label=\"validation loss\")\n ax1.legend()\n\n ax2.set_ylim(0, 1.0)\n ax2.plot(self.x, self.acc, label=\"training accuracy\")\n ax2.plot(self.x, self.val_acc, label=\"validation accuracy\")\n ax2.legend()\n\n plt.show()\n\n\n##################################################\n# Utility code for computing a Confusion Matrix\n##################################################\n\nimport matplotlib.pyplot as plt #for plotting\nimport itertools as it\n\n\n#Note, this code is taken straight from the SKLEARN website, a nice way of viewing confusion matrix.\ndef plot_confusion_matrix(cm,\n classes,\n normalize=False,\n title='Confusion matrix',\n cmap=plt.cm.Blues):\n \"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n\n Note: class is a listlike parameter. Pass in list of classes, eg: [\"No Loan\", \"Loan\"]\n \"\"\"\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar()\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=45)\n plt.yticks(tick_marks, classes)\n\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n\n thresh = cm.max() / 2.\n for i, j in it.product(range(cm.shape[0]), range(cm.shape[1])):\n value = '{0:.2g}'.format(cm[i, j])\n plt.text(j,\n i,\n value,\n fontsize=10,\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n\n plt.tight_layout()\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n\n\n\n##################################################\n# Utility code for measuring model performance given dataset size\n##################################################\ndef plot_learning_curve(estimator,\n title,\n X,\n y,\n ylim=None,\n cv=None,\n n_jobs=-1,\n train_sizes=np.linspace(.1, 1.0, 5)):\n \"\"\"Generate a simple plot of the test and training learning curve\"\"\"\n plt.figure()\n plt.title(title)\n if ylim is not None:\n plt.ylim(*ylim)\n plt.xlabel(\"Training examples\")\n plt.ylabel(\"Score\")\n train_sizes, train_scores, test_scores = learning_curve(\n estimator, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes)\n train_scores_mean = np.mean(train_scores, axis=1)\n train_scores_std = np.std(train_scores, axis=1)\n test_scores_mean = np.mean(test_scores, axis=1)\n test_scores_std = np.std(test_scores, axis=1)\n plt.grid()\n\n plt.fill_between(train_sizes,\n train_scores_mean - train_scores_std,\n train_scores_mean + train_scores_std,\n alpha=0.1,\n color=\"r\")\n plt.fill_between(train_sizes,\n test_scores_mean - test_scores_std,\n test_scores_mean + test_scores_std,\n alpha=0.1,\n color=\"g\")\n plt.plot(train_sizes,\n train_scores_mean,\n 'o-',\n color=\"r\",\n label=\"Training score\")\n plt.plot(train_sizes,\n test_scores_mean,\n 'o-',\n color=\"g\",\n label=\"Cross-validation score\")\n\n plt.legend(loc=\"best\")\n return plt\n\n\n\ndef display_sklearn_feature_importance(data, set, features, n_features):\n '''\n Parameters:\n data: data object; coomatrix w/ encoded features\n n_features: number of features to visualize\n set: str;\n 'lendingclub' - load lending club models\n 'uci' - load uci models\n Returns:\n Graph of basic feature importance measurements\n\n '''\n if 'uci' in set:\n rfc, gbc, logit, keras_ann, sk_ann = load_models_uci()\n else:\n rfc, gbc, logit, keras_ann, sk_ann = load_models_lendingclub()\n feature_importance = pd.DataFrame({\n \"feature\":\n features,\n \"RF_Feature_Importance\":\n np.round(rfc.feature_importances_, 4),\n \"GBC_Feature_Importance\":\n np.round(gbc.feature_importances_, 4),\n \"Logit_Coeff\":\n np.round(logit.coef_[0], 4),\n \"Max_Feature_Val\":\n pd.DataFrame(data.toarray(), columns=features).max(),\n })\n\n n = n_features\n feature_importance['coeff_max'] = feature_importance[\n 'Logit_Coeff'] * feature_importance['Max_Feature_Val']\n temp = feature_importance.nlargest(n, 'RF_Feature_Importance')\n sns.barplot(temp['RF_Feature_Importance'], temp['feature'])\n plt.title('Random Forest - Feature Importance Top {}'.format(n_features))\n plt.show()\n\n temp = feature_importance.nlargest(n, 'GBC_Feature_Importance')\n sns.barplot(temp['GBC_Feature_Importance'], temp['feature'])\n plt.title('Gradient Boosted Classifier - Feature Importance Top {}'.format(\n n_features))\n plt.show()\n\n #We want to show the total possible feature impact here. Take the max of each feature in the training set by the logit coeff.\n lookup = pd.DataFrame(data.toarray(), columns=features).max()\n temp = feature_importance.nlargest(int(n / 2), 'coeff_max')\n temp1 = feature_importance.nsmallest(int(n / 2), 'coeff_max')\n temp = pd.concat([temp, temp1])\n sns.barplot(temp['coeff_max'], temp['feature'])\n plt.title('Logistic Regression - Coefficients Top&Bottom {}'.format(\n int(n_features / 2)))\n plt.show()\n\n\ndef get_best_score(x, y):\n try:\n return sklearn.metrics.accuracy_score(x, y.predict(encoded_test))\n except:\n return sklearn.metrics.accuracy_score(x, keras_ann.predict_classes(encoded_test.toarray()))\n\n\ndef display_side_by_side(*args):\n html_str = ''\n for df in args:\n html_str += df.to_html()\n display_html(html_str.replace('table', 'table style=\"display:inline\"'),\n raw=True)\n\ndef neg_pos_logit_coefficients(model, features):\n logistic_regress_coeff = pd.DataFrame({\n \"features\": features,\n \"Coef\": model.coef_[0]\n })\n\n neg_coef = round(logistic_regress_coeff[\n logistic_regress_coeff['Coef'] < 0].sort_values('Coef', ascending=True),2).head(15)\n pos_coef = round(logistic_regress_coeff[\n logistic_regress_coeff['Coef'] > 0].sort_values('Coef', ascending=False),2).head(15)\n display_side_by_side(neg_coef, pos_coef)\n" ]
[ [ "matplotlib.pyplot.legend", "matplotlib.pyplot.imshow", "numpy.linspace", "pandas.DataFrame", "matplotlib.pyplot.plot", "numpy.round", "numpy.mean", "matplotlib.pyplot.tight_layout", "numpy.std", "matplotlib.pyplot.text", "matplotlib.pyplot.figure", "pandas.concat", "matplotlib.pyplot.title", "matplotlib.pyplot.ylim", "matplotlib.pyplot.fill_between", "matplotlib.pyplot.show", "matplotlib.pyplot.xticks", "matplotlib.pyplot.ylabel", "sklearn.model_selection.learning_curve", "matplotlib.pyplot.subplots", "matplotlib.pyplot.colorbar", "matplotlib.pyplot.grid", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.yticks" ] ]
[ { "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": [] } ]
shday/dash-bio-1
[ "81bb6fa257febb59d7841f8c5573e7231f5a9095" ]
[ "tests/integration/test_clustergram.py" ]
[ "import json\nimport pandas as pd\n\nimport dash\nimport dash_html_components as html\nimport dash_bio\n\nfrom common_features import nested_component_layout, nested_component_app_callback\n\n_data = None\n\n_mtcars_data = pd.read_csv(\n \"tests/dashbio_demos/dash-clustergram/data/mtcars.tsv\", delimiter=\"\\t\", skiprows=4\n).set_index(\"model\")\n\n_data = _mtcars_data.values\n\n\ndef test_dbcl001_colorscale(dash_duo):\n\n app = dash.Dash(__name__)\n\n app.layout = html.Div(nested_component_layout(dash_bio.Clustergram(data=_data)))\n\n nested_component_app_callback(\n app,\n dash_duo,\n component=dash_bio.Clustergram,\n component_data=_data,\n test_prop_name=\"color_map\",\n test_prop_value=json.dumps([[0, \"blue\"], [0.5, \"yellow\"], [1, \"pink\"]]),\n prop_value_type=\"list\",\n path_to_test_prop='[\"data\"][41][\"colorscale\"]',\n take_snapshot=True,\n )\n\n\ndef test_dbcl002_cluster_by_row_or_col(dash_duo):\n\n app = dash.Dash(__name__)\n\n app.layout = html.Div(nested_component_layout(dash_bio.Clustergram(data=_data)))\n\n nested_component_app_callback(\n app,\n dash_duo,\n component=dash_bio.Clustergram,\n component_data=_data,\n test_prop_name=\"cluster\",\n test_prop_value=\"row\",\n prop_value_type=\"string\",\n )\n\n assert len(dash_duo.find_elements(\"g.subplot.x2y2\")) == 0\n assert len(dash_duo.find_elements(\"g.subplot.x4y4\")) == 1\n\n # create a new instance of the app to test column clustering\n\n app = dash.Dash(__name__)\n\n app.layout = html.Div(nested_component_layout(dash_bio.Clustergram(data=_data)))\n\n nested_component_app_callback(\n app,\n dash_duo,\n component=dash_bio.Clustergram,\n component_data=_data,\n test_prop_name=\"cluster\",\n test_prop_value=\"col\",\n prop_value_type=\"string\",\n take_snapshot=True,\n )\n\n assert len(dash_duo.find_elements(\"g.subplot.x4y4\")) == 0\n assert len(dash_duo.find_elements(\"g.subplot.x2y2\")) == 1\n\n\ndef test_dbcl003_row_col_thresholds(dash_duo):\n\n app = dash.Dash(__name__)\n\n app.layout = html.Div(nested_component_layout(dash_bio.Clustergram(data=_data)))\n\n nested_component_app_callback(\n app,\n dash_duo,\n component=dash_bio.Clustergram,\n component_data=_data,\n test_prop_name=\"color_threshold\",\n test_prop_value=json.dumps({\"row\": 250, \"col\": 700}),\n prop_value_type=\"dict\",\n take_snapshot=True,\n )\n\n # there should be 9 traces for the column dendrogram\n # plus one trace for the background\n assert len(dash_duo.find_elements(\"g.subplot.x2y2 > g.plot g.trace.scatter\")) == 10\n\n # 30 traces for the row dendrogram, plus one for the background\n assert len(dash_duo.find_elements(\"g.subplot.x4y4 > g.plot g.trace.scatter\")) == 31\n\n\ndef test_dbcl004_col_annotations(dash_duo):\n\n app = dash.Dash(__name__)\n\n app.layout = html.Div(nested_component_layout(dash_bio.Clustergram(data=_data)))\n\n nested_component_app_callback(\n app,\n dash_duo,\n component=dash_bio.Clustergram,\n component_data=_data,\n test_prop_name=\"col_group_marker\",\n test_prop_value=json.dumps(\n [{\"group\": 1, \"annotation\": \"cluster one\", \"color\": \"rgb(62, 248, 199)\"}]\n ),\n extra_props={\"color_threshold\": {\"row\": 250, \"col\": 700}},\n prop_value_type=\"list\",\n take_snapshot=True,\n )\n\n # the annotation has shown up\n assert len(dash_duo.find_elements(\"g.subplot.x8y8\")) == 1\n\n # the annotation is the correct color\n dash_duo.wait_for_style_to_equal(\n \"g.subplot.x8y8 g.plot g.lines > path\", \"stroke\", \"rgb(62, 248, 199)\"\n )\n\n\ndef test_dbcl005_row_annotations(dash_duo):\n\n app = dash.Dash(__name__)\n\n app.layout = html.Div(nested_component_layout(dash_bio.Clustergram(data=_data)))\n\n nested_component_app_callback(\n app,\n dash_duo,\n component=dash_bio.Clustergram,\n component_data=_data,\n test_prop_name=\"row_group_marker\",\n test_prop_value=json.dumps(\n [{\"group\": 2, \"annotation\": \"cluster two\", \"color\": \"rgb(248, 62, 199)\"}]\n ),\n extra_props={\"color_threshold\": {\"row\": 250, \"col\": 700}},\n prop_value_type=\"list\",\n take_snapshot=True,\n )\n\n # the annotation has shown up\n assert len(dash_duo.find_elements(\"g.subplot.x6y6\")) == 1\n\n # the annotation is the correct color\n dash_duo.wait_for_style_to_equal(\n \"g.subplot.x6y6 g.plot g.lines > path\", \"stroke\", \"rgb(248, 62, 199)\"\n )\n\n\ndef test_dbcl006_df_input_row_cluster(dash_duo):\n\n app = dash.Dash(__name__)\n\n # run the same test as dbcl002 (row clustering) where table of\n # observations (data argument) is left as a DataFrame\n assert isinstance(_mtcars_data, pd.DataFrame)\n app.layout = html.Div(\n nested_component_layout(dash_bio.Clustergram(data=_mtcars_data))\n )\n\n nested_component_app_callback(\n app,\n dash_duo,\n component=dash_bio.Clustergram,\n component_data=_data,\n test_prop_name=\"cluster\",\n test_prop_value=\"row\",\n prop_value_type=\"string\",\n )\n\n assert len(dash_duo.find_elements(\"g.subplot.x2y2\")) == 0\n assert len(dash_duo.find_elements(\"g.subplot.x4y4\")) == 1\n\n\ndef test_dbcl007_hidden_labels(dash_duo):\n\n app = dash.Dash(__name__)\n\n data = _mtcars_data\n row_labels = list(_mtcars_data.index)\n col_labels = list(_mtcars_data.columns)\n\n app.layout = html.Div(\n nested_component_layout(\n dash_bio.Clustergram(\n data=data, row_labels=row_labels, column_labels=col_labels\n )\n )\n )\n\n nested_component_app_callback(\n app,\n dash_duo,\n component=dash_bio.Clustergram,\n component_data=data,\n test_prop_name=\"hidden_labels\",\n test_prop_value=\"row\",\n prop_value_type=\"string\",\n )\n\n # ensure that row labels are hidden\n assert len(dash_duo.find_elements(\"g.yaxislayer-above g.y5tick\")) == 0\n # ensure that column labels are displayed\n assert len(dash_duo.find_elements(\"g.xaxislayer-above g.x5tick\")) == len(col_labels)\n\n # create a new instance of the app to test hiding of column labels\n\n app = dash.Dash(__name__)\n\n app.layout = html.Div(\n nested_component_layout(\n dash_bio.Clustergram(\n data=data, row_labels=row_labels, column_labels=col_labels\n )\n )\n )\n\n nested_component_app_callback(\n app,\n dash_duo,\n component=dash_bio.Clustergram,\n component_data=data,\n test_prop_name=\"hidden_labels\",\n test_prop_value=\"col\",\n prop_value_type=\"string\",\n )\n\n # ensure that column labels are hidden\n assert len(dash_duo.find_elements(\"g.xaxislayer-above g.x5tick\")) == 0\n # ensure that row labels are displayed\n assert len(dash_duo.find_elements(\"g.yaxislayer-above g.y5tick\")) == len(row_labels)\n" ]
[ [ "pandas.read_csv" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
Tim15/MLib
[ "2222dc67ec0cbaf07942371120be1690359e0ab3" ]
[ "MLLib/NeuralNet/net.py" ]
[ "# import curses\r\n# import datetime\r\n#\r\n# stdscr = curses.initscr()\r\n# curses.noecho()\r\n# stdscr.nodelay(1) # set getch() non-blocking\r\n#\r\n# stdscr.addstr(0,0,\"Press \\\"p\\\" to show count, \\\"q\\\" to exit...\")\r\n# line = 1\r\n# try:\r\n# while 1:\r\n# c = stdscr.getch()\r\n# if c == ord('p'):\r\n# stdscr.addstr(line,0,\"Some text here\")\r\n# line += 1\r\n# elif c == ord('q'): break\r\n#\r\n# \"\"\"\r\n# Do more things\r\n# \"\"\"\r\n#\r\n# finally:\r\n# curses.endwin()\r\nimport numpy as np\r\ndef nonlin(x, deriv=False):\r\n if deriv:\r\n return (x*(1-x))\r\n return 1/(1+np.exp(-x))\r\nX = np.array([[0,0],[0,1],[1,0],[1,1]])\r\ny = np.array([[0],[1],[1],[0]])\r\nnp.random.seed(1)\r\nnums = [2, 4, 1]\r\nnetwork = [2*np.random.random((nums[i]+1,nums[i+1]))-1 for i in range(len(nums)-1)]\r\nprint('network', network)\r\nfor j in range(100000):\n outputs = [X]\n for layer in network:\n outputs[-1] = np.c_[outputs[-1], np.ones(len(outputs[-1]))]\n outputs.append(nonlin(np.dot(outputs[-1], layer)))\r\n print('outputs', outputs, '\\n')\r\n errors = [y - outputs[2]]\r\n print('errors', errors)\r\n # if(j % 100000) == 0: # Only print the error every 10000 steps, to save time and limit the amount of output.\r\n # print('outputs, prediction', l0, l1, l2, y, l2.shape)\r\n # print('weights', self.network0, self.network1)\r\n # print(\"Error: \" + str(np.mean(np.abs(errors[2]))))\n # print('Training input l0:', l0, '\\nDot product between training and rand:', np.dot(l0, self.network0), 'non linear dot product l1:', l1, '\\n dot product between l1, and self.network1:', np.dot(l1, self.network1), 'nonlinear dot product between l1, and self.network1:', l2, 'input and output training data: ', self.network0, self.network1, errors[2], nonlin(l2, deriv=True))\r\n deltas = [errors[-1]*nonlin(outputs[2], deriv=True)]\r\n print('deltas', deltas)\r\n # if(j % 100000) == 0:\r\n # print('l2Error, nonlin\\'(l2)', errors[2], nonlin(l2, deriv=True))\r\n # print('l2Delta, self.network1.t', l2_delta, self.network1.T)\r\n for i in range(len(network)-1):\r\n errors.insert(0, deltas[0].dot(network[i+1].T))\r\n print('layer', i, 'error', errors[0])\r\n # if(j % 100000) == 0:\r\n # print('l1Error', errors[1])\r\n # print(nonlin(outputs[i+1],deriv=True))\r\n deltas.insert(0, errors[0] * nonlin(outputs[i+1],deriv=True))\r\n print('layer', i, 'delta', deltas[0], '\\n')\r\n # if(j % 100000) == 0:\r\n # print('self.network1, l1.T, l2Delta', network[1].shape, outputs[1].T.shape, deltas[1].shape)\r\n # if(j % 100000) == 0:\r\n # print('self.network0, l0.T, l1Delta', network[0].shape, outputs[0].T.shape, deltas[0].shape)\r\n #update weights (no learning rate term)\r\n for i in range(len(deltas)):\r\n delta = outputs[i].T.dot(deltas[i])\r\n print(delta,'\\n', network[i])\r\n network[i] += delta\r\n\r\nprint(\"Output after training\")\r\nprint(outputs[2])\r\n" ]
[ [ "numpy.dot", "numpy.random.random", "numpy.random.seed", "numpy.array", "numpy.exp" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
zakerifahimeh/FaceLib
[ "bf8eadc26baf04907e3800ada02896ac7056080c" ]
[ "facelib/InsightFace/models/data/config.py" ]
[ "from easydict import EasyDict as edict\nfrom pathlib import Path\nimport torch\nfrom torch.nn import CrossEntropyLoss\n\n\ndef get_config(training=True):\n conf = edict()\n conf.data_path = Path('models/data')\n conf.work_path = Path('weights/')\n conf.model_path = conf.work_path / 'models'\n conf.log_path = conf.work_path / 'log'\n conf.save_path = conf.work_path\n conf.input_size = [112, 112]\n conf.embedding_size = 512\n conf.use_mobilfacenet = False\n conf.net_depth = 50\n conf.drop_ratio = 0.6\n conf.net_mode = 'ir_se' # or 'ir'\n conf.device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n conf.data_mode = 'emore'\n conf.vgg_folder = conf.data_path / 'faces_vgg_112x112'\n conf.ms1m_folder = conf.data_path / 'faces_ms1m_112x112'\n conf.emore_folder = conf.data_path / 'faces_emore'\n conf.batch_size = 100 # irse net depth 50\n # conf.batch_size = 200 # mobilefacenet\n # --------------------Training Config ------------------------\n if training:\n conf.log_path = conf.work_path / 'log'\n conf.save_path = conf.work_path / 'save'\n # conf.weight_decay = 5e-4\n conf.lr = 1e-3\n conf.momentum = 0.9\n conf.pin_memory = True\n # conf.num_workers = 4 # when batchsize is 200\n conf.num_workers = 3\n conf.ce_loss = CrossEntropyLoss()\n # --------------------Inference Config ------------------------\n else:\n conf.facebank_path = conf.data_path / 'facebank'\n conf.threshold = 1.5\n conf.face_limit = 10\n # when inference, at maximum detect 10 faces in one image, my laptop is slow\n return conf\n" ]
[ [ "torch.nn.CrossEntropyLoss", "torch.cuda.is_available" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
FurkanCan-eee/Convolutional-Neural-Network
[ "e7ee0d94075fa724d394b6a3c32e1b5abfe67285" ]
[ "Transfer Learning with MobileNetV2/MobileNetV2.py" ]
[ "# Packages\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport tensorflow as tf\nimport tensorflow.keras.layers as tfl\n\nfrom tensorflow.keras.preprocessing import image_dataset_from_directory\nfrom tensorflow.keras.layers.experimental.preprocessing import RandomFlip, RandomRotation\n\n# Creating the dataset and splitting it into training and validation sets\n\nBATCH_SIZE = 32\nIMG_SIZE = (160, 160)\ndirectory = \"dataset/\" # One can change this directory\ntrain_dataset = image_dataset_from_directory(directory,\n shuffle=True,\n batch_size=BATCH_SIZE,\n image_size=IMG_SIZE,\n validation_split=0.2,\n subset='training',\n seed=42)\nvalidation_dataset = image_dataset_from_directory(directory,\n shuffle=True,\n batch_size=BATCH_SIZE,\n image_size=IMG_SIZE,\n validation_split=0.2,\n subset='validation',\n seed=42)\n\n# Some of the images from the training set\n\nclass_names = train_dataset.class_names\n\nplt.figure(figsize=(10, 10))\nfor images, labels in train_dataset.take(1):\n for i in range(9):\n ax = plt.subplot(3, 3, i + 1)\n plt.imshow(images[i].numpy().astype(\"uint8\"))\n plt.title(class_names[labels[i]])\n plt.axis(\"off\")\n \n#### Preprocessing and Augmentation of the data ####\n\n\"\"\"\ndataset.prefetch() is an important extra step in data preprocessing.\nUsing prefetch() prevents a memory bottleneck that can occur when reading from disk.\n\"\"\"\nAUTOTUNE = tf.data.experimental.AUTOTUNE\ntrain_dataset = train_dataset.prefetch(buffer_size=AUTOTUNE)\n\n# Function for data augmentation\n\ndef data_augmenter():\n '''\n Create a Sequential model composed of 2 layers\n Returns:\n tf.keras.Sequential\n '''\n \n data_augmentation = tf.keras.Sequential()\n data_augmentation.add(RandomFlip(\"horizontal\"))\n data_augmentation.add(RandomRotation(0.2))\n \n return data_augmentation\n \naugmenter = data_augmenter()\n\n\"\"\"\n# Testing the data_augmenter() function with one image\n\ndata_augmentation = data_augmenter()\n\nfor image, _ in train_dataset.take(1):\n plt.figure(figsize=(10, 10))\n first_image = image[0]\n for i in range(9):\n ax = plt.subplot(3, 3, i + 1)\n augmented_image = data_augmentation(tf.expand_dims(first_image, 0))\n plt.imshow(augmented_image[0] / 255)\n plt.axis('off')\n\"\"\"\n\n# Since we're using a pre-trained model that was trained on the normalization \n# values [-1,1], it's best practice to reuse that standard.\n\npreprocess_input = tf.keras.applications.mobilenet_v2.preprocess_input\n\n# Let's try to train our base model using all the layers and weights from the pretrained model.\n\nIMG_SHAPE = IMG_SIZE + (3,)\nbase_model = tf.keras.applications.MobileNetV2(input_shape=IMG_SHAPE,\n include_top=True,\n weights='imagenet')\n\n# One can check model summary\n\n# base_model.summary()\n\n\"\"\"\nNote the last 2 layers here. They are so called top layers,\nand they are responsible of the classification in the model.\n\"\"\"\n# Their names\n\n# nb_layers = len(base_model.layers)\n# print(base_model.layers[nb_layers - 2].name)\n# print(base_model.layers[nb_layers - 1].name)\n\n# choosing the first batch from the tensorflow dataset to use the images, and runing \n# it through the MobileNetV2 base model to test out the predictions on some of our images.\n\n\"\"\"\nWe can see that shape of the batch is (32,1000). The number 32 refers to the batch size and \n1000 refers to the 1000 classes the model was pretrained on.\n\"\"\"\nimage_batch, label_batch = next(iter(train_dataset))\nfeature_batch = base_model(image_batch)\nprint(feature_batch.shape)\n\n# Decoding the predictions made by the model\n\n\"\"\"\nThe predictions returned by the base model below follow this format:\nFirst the class number, then a human-readable label, and last the probability of the image \nbelonging to that class. You'll notice that there are two of these returned for each image \nin the batch - these the top two probabilities returned for that image.\n\nThere's a whole lot of labels here, some of them hilariously wrong, but none of them say \"alpaca.\"\nThis is because MobileNet pretrained over ImageNet doesn't have the correct labels for alpacas,\nso when we use the full model, all we get is a bunch of incorrectly classified images.\n\nFortunately, you can delete the top layer, which contains all the classification labels,\nand create a new classification layer.\n\"\"\"\nbase_model.trainable = False\nimage_var = tf.Variable(image_batch)\npred = base_model(image_var)\n\ntf.keras.applications.mobilenet_v2.decode_predictions(pred.numpy(), top=2)\n\n# Alpaca model\n\n\"\"\"\nWe can use a pretrained model to modify the classifier task so that it's able to recognize alpacas.\nWe can achieve this in three steps:\n1- Delete the top layer (the classification layer)\n * Set include_top in base_model as False\n2- Add a new classifier layer\n * Train only one layer by freezing the rest of the network\n * A single neuron is enough to solve a binary classification problem.\n3- Freeze the base model and train the newly-created classifier layer\n * Set base model.trainable=False to avoid changing the weights and train only the new layer\n * Set training in base_model to False to avoid keeping track of statistics in the batch norm layer\n\"\"\"\ndef alpaca_model(image_shape=IMG_SIZE, data_augmentation=data_augmenter()):\n ''' Define a tf.keras model for binary classification out of the MobileNetV2 model\n Arguments:\n image_shape -- Image width and height\n data_augmentation -- data augmentation function\n Returns:\n Returns:\n tf.keras.model\n '''\n \n \n input_shape = image_shape + (3,)\n \n base_model = tf.keras.applications.MobileNetV2(input_shape=input_shape,\n include_top=False, # <== Important!!!!\n weights='imagenet') # From imageNet\n \n # Freeze the base model by making it non trainable\n base_model.trainable = False\n \n # create the input layer (Same as the imageNetv2 input size)\n inputs = tf.keras.Input(shape=input_shape) \n \n # apply data augmentation to the inputs\n x = data_augmentation(inputs)\n \n # data preprocessing using the same weights the model was trained on\n # Already Done -> preprocess_input = tf.keras.applications.mobilenet_v2.preprocess_input\n x = preprocess_input(x) \n \n # set training to False to avoid keeping track of statistics in the batch norm layer\n x = base_model(x, training=False) \n \n # Add the new Binary classification layers\n # use global avg pooling to summarize the info in each channel\n x = tfl.GlobalAveragePooling2D()(x) \n #include dropout with probability of 0.2 to avoid overfitting\n x = tfl.Dropout(0.2)(x)\n \n # create a prediction layer with one neuron (as a classifier only needs one)\n prediction_layer = tfl.Dense(1)\n \n outputs = prediction_layer(x) \n model = tf.keras.Model(inputs, outputs)\n \n return model\n\ndata_augmentation = data_augmenter()\nmodel2 = alpaca_model(IMG_SIZE, data_augmentation)\n\n# Compiling the model\n\nbase_learning_rate = 0.01\nmodel2.compile(optimizer=tf.keras.optimizers.Adam(lr=base_learning_rate),\n loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),\n metrics=['accuracy'])\n\n# Running the model\n\ninitial_epochs = 5\nhistory = model2.fit(train_dataset, validation_data=validation_dataset, epochs=initial_epochs)\n\n# Plotting the training and validation accuracy\n\nacc = [0.] + history.history['accuracy']\nval_acc = [0.] + history.history['val_accuracy']\n\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nplt.figure(figsize=(8, 8))\nplt.subplot(2, 1, 1)\nplt.plot(acc, label='Training Accuracy')\nplt.plot(val_acc, label='Validation Accuracy')\nplt.legend(loc='lower right')\nplt.ylabel('Accuracy')\nplt.ylim([min(plt.ylim()),1])\nplt.title('Training and Validation Accuracy')\n\nplt.subplot(2, 1, 2)\nplt.plot(loss, label='Training Loss')\nplt.plot(val_loss, label='Validation Loss')\nplt.legend(loc='upper right')\nplt.ylabel('Cross Entropy')\nplt.ylim([0,1.0])\nplt.title('Training and Validation Loss')\nplt.xlabel('epoch')\nplt.show()\n\n# Printing class names\n\nprint(class_names)\n\n# Fine-tunning the model to increase the accuracy\n\nbase_model.trainable = True\n# Let's take a look to see how many layers are in the base model\nprint(\"Number of layers in the base model: \", len(base_model.layers))\n\n# Fine-tune from this layer onwards\nfine_tune_at = 126\n\n##### One Way ########\n\"\"\"\nfor layer in base_model.layers:\n if layer.name == 'block_16_expand':\n break\n layer.trainable = False\n print('Layer ' + layer.name + ' frozen.')\n\"\"\"\n######## Other Way ######\n# Freeze all the layers before the `fine_tune_at` layer\nfor layer in base_model.layers[:fine_tune_at]:\n #print('Layer ' + layer.name + ' frozen.')\n layer.trainable = None\n \n# Define a BinaryCrossentropy loss function. Use from_logits=True\nloss_function= tf.keras.losses.BinaryCrossentropy(from_logits=True)\n# Define an Adam optimizer with a learning rate of 0.1 * base_learning_rate\noptimizer = tf.keras.optimizers.Adam(learning_rate=base_learning_rate*0.1)# 0.001\n# Use accuracy as evaluation metric\nmetrics=['accuracy']\n\nmodel2.compile(loss=loss_function,\n optimizer = optimizer,\n metrics=metrics)\n\nfine_tune_epochs = 5\ntotal_epochs = initial_epochs + fine_tune_epochs\n\nhistory_fine = model2.fit(train_dataset,\n epochs=total_epochs,\n initial_epoch=history.epoch[-1],\n validation_data=validation_dataset)\n\n# Plotting the training and validation accuracy after fine-tunning process\n\nacc += history_fine.history['accuracy']\nval_acc += history_fine.history['val_accuracy']\n\nloss += history_fine.history['loss']\nval_loss += history_fine.history['val_loss']\nplt.figure(figsize=(8, 8))\nplt.subplot(2, 1, 1)\nplt.plot(acc, label='Training Accuracy')\nplt.plot(val_acc, label='Validation Accuracy')\nplt.ylim([0, 1])\nplt.plot([initial_epochs-1,initial_epochs-1],\n plt.ylim(), label='Start Fine Tuning')\nplt.legend(loc='lower right')\nplt.title('Training and Validation Accuracy')\n\nplt.subplot(2, 1, 2)\nplt.plot(loss, label='Training Loss')\nplt.plot(val_loss, label='Validation Loss')\nplt.ylim([0, 1.0])\nplt.plot([initial_epochs-1,initial_epochs-1],\n plt.ylim(), label='Start Fine Tuning')\nplt.legend(loc='upper right')\nplt.title('Training and Validation Loss')\nplt.xlabel('epoch')\nplt.show()\n\n\"\"\"\nWhat we should remember:\n\n - To adapt the classifier to new data: Delete the top layer, add a new \n classification layer, and train only on that layer\n - When freezing layers, avoid keeping track of statistics (like in the \n batch normalization layer)\n - Fine-tune the final layers of your model to capture high-level details \n near the end of the network and potentially improve accuracy\n\"\"\"\n" ]
[ [ "matplotlib.pyplot.legend", "tensorflow.keras.layers.experimental.preprocessing.RandomFlip", "tensorflow.keras.Sequential", "matplotlib.pyplot.plot", "tensorflow.keras.layers.Dropout", "tensorflow.keras.Input", "tensorflow.Variable", "tensorflow.keras.preprocessing.image_dataset_from_directory", "tensorflow.keras.losses.BinaryCrossentropy", "matplotlib.pyplot.subplot", "matplotlib.pyplot.axis", "matplotlib.pyplot.figure", "matplotlib.pyplot.title", "matplotlib.pyplot.ylim", "tensorflow.keras.layers.Dense", "tensorflow.keras.Model", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel", "tensorflow.keras.applications.MobileNetV2", "tensorflow.keras.layers.experimental.preprocessing.RandomRotation", "tensorflow.keras.layers.GlobalAveragePooling2D", "tensorflow.keras.optimizers.Adam", "matplotlib.pyplot.xlabel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.7", "2.3", "2.4", "2.5", "2.6" ] } ]
xiacijie/dace
[ "2d942440b1d7b139ba112434bfa78f754e10bfe5", "2d942440b1d7b139ba112434bfa78f754e10bfe5", "2d942440b1d7b139ba112434bfa78f754e10bfe5", "2d942440b1d7b139ba112434bfa78f754e10bfe5", "2d942440b1d7b139ba112434bfa78f754e10bfe5" ]
[ "samples/simple/matmul.py", "tests/numpy/assignment_test.py", "tests/fpga/nested_sdfg_as_kernel.py", "samples/fpga/filter_fpga.py", "dace/codegen/targets/framecode.py" ]
[ "# Copyright 2019-2021 ETH Zurich and the DaCe authors. All rights reserved.\nfrom __future__ import print_function\n\nimport argparse\nimport dace\nimport numpy as np\nfrom typing import List\n\n# For optimizations\nfrom dace.transformation.dataflow import (DoubleBuffering, MapCollapse,\n MapExpansion, MapReduceFusion,\n StripMining, InLocalStorage,\n AccumulateTransient, Vectorization)\nfrom dace.transformation.interstate import FPGATransformSDFG\nfrom dace.transformation import helpers as xfutil\n\n# For library node implementations\nimport dace.libraries.blas\n\n# Define symbolic sizes for arbitrary inputs\nM = dace.symbol('M')\nK = dace.symbol('K')\nN = dace.symbol('N')\n\n# Define data type to use\ndtype = dace.float64\nnp_dtype = np.float64\n\n#####################################################################\n# Data-centric functions\n\n\n# Map-Reduce version of matrix multiplication\[email protected]\ndef matmul(A: dtype[M, K], B: dtype[K, N], C: dtype[M, N]):\n tmp = np.ndarray([M, N, K], dtype=A.dtype)\n\n # Multiply every pair of values to a large 3D temporary array\n for i, j, k in dace.map[0:M, 0:N, 0:K]:\n with dace.tasklet:\n in_A << A[i, k]\n in_B << B[k, j]\n out >> tmp[i, j, k]\n\n out = in_A * in_B\n\n # Sum last dimension of temporary array to obtain resulting matrix\n dace.reduce(lambda a, b: a + b, tmp, C, axis=2, identity=0)\n\n\n# Library node version of matrix multiplication, using the numpy interface\[email protected]\ndef matmul_lib(A: dtype[M, K], B: dtype[K, N]):\n return A @ B\n\n\n#####################################################################\n# Data-centric optimization helpers\n\n\ndef find_map_by_param(sdfg: dace.SDFG, pname: str) -> dace.nodes.MapEntry:\n \"\"\" Finds the first map entry node by the given parameter name. \"\"\"\n return next(n for n, _ in sdfg.all_nodes_recursive()\n if isinstance(n, dace.nodes.MapEntry) and pname in n.params)\n\n\ndef find_mapexit_by_param(sdfg: dace.SDFG, pname: str) -> dace.nodes.MapExit:\n \"\"\" Finds the first map exit node by the given parameter name. \"\"\"\n state, entry = next(\n (p, n) for n, p in sdfg.all_nodes_recursive()\n if isinstance(n, dace.nodes.MapEntry) and pname in n.params)\n return state.exit_node(entry)\n\n\n#####################################################################\n# Matrix multiplication data-centric optimization schemes\n\n\ndef optimize_for_cpu(sdfg: dace.SDFG, m: int, n: int, k: int):\n \"\"\" Optimize the matrix multiplication example for multi-core CPUs. \"\"\"\n # Ensure integers are 32-bit by default\n dace.Config.set('compiler', 'default_data_types', value='C')\n\n # Fuse the map and reduce nodes\n sdfg.apply_transformations(MapReduceFusion)\n\n # Find multiplication map\n entry = find_map_by_param(sdfg, 'k')\n\n # Create a tiling strategy\n divides_evenly = (m % 32 == 0) and (n % 32 == 0) and (k % 256 == 0)\n xfutil.tile(sdfg, entry, divides_evenly, False, k=256, i=32, j=32)\n xfutil.tile(sdfg, entry, divides_evenly, divides_evenly, j=16, i=4)\n\n # Reorder internal map to \"k,i,j\"\n xfutil.permute_map(entry, [2, 0, 1])\n\n # Add local storage for B in j tile: we apply InLocalStorage with a\n # parameter \"array\" named B, between the two maps of j and i\n regtile_j = find_map_by_param(sdfg, 'tile1_j')\n regtile_i = find_map_by_param(sdfg, 'tile1_i')\n InLocalStorage.apply_to(sdfg,\n dict(array='B'),\n node_a=regtile_j,\n node_b=regtile_i)\n\n if divides_evenly:\n # Add local storage for C\n exit_inner = find_mapexit_by_param(sdfg, 'k')\n exit_rti = find_mapexit_by_param(sdfg, 'tile1_i')\n AccumulateTransient.apply_to(sdfg,\n dict(array='C', identity=0),\n map_exit=exit_inner,\n outer_map_exit=exit_rti)\n\n # Vectorize microkernel map\n postamble = n % 4 != 0\n sdfg.apply_transformations(\n Vectorization,\n dict(vector_len=4, preamble=False, postamble=postamble))\n\n # Mark outer tile map as sequential to remove atomics\n find_map_by_param(sdfg,\n 'tile_k').map.schedule = dace.ScheduleType.Sequential\n\n # Collapse maps for more parallelism\n find_map_by_param(sdfg, 'o0').map.collapse = 2\n tile_i = find_map_by_param(sdfg, 'tile_i')\n tile_j = find_map_by_param(sdfg, 'tile_j')\n MapCollapse.apply_to(sdfg, _outer_map_entry=tile_i, _inner_map_entry=tile_j)\n tile_ij = find_map_by_param(sdfg, 'tile_i') # Find newly created map\n tile_ij.map.schedule = dace.ScheduleType.CPU_Multicore\n tile_ij.map.collapse = 2\n\n\ndef optimize_for_gpu(sdfg: dace.SDFG, m: int, n: int, k: int):\n \"\"\" Optimize the matrix multiplication example for GPUs. \"\"\"\n # Ensure integers are 32-bit by default\n dace.Config.set('compiler', 'default_data_types', value='C')\n\n # Fuse the map and reduce nodes\n sdfg.apply_transformations(MapReduceFusion)\n\n # Apply GPU transformation\n sdfg.apply_gpu_transformations()\n\n # Find multiplication map\n entry = find_map_by_param(sdfg, 'k')\n\n # Create a tiling strategy\n divides_evenly = (m % 64 == 0) and (n % 64 == 0) and (k % 8 == 0)\n xfutil.tile(sdfg, entry, divides_evenly, True, i=64, j=64, k=8)\n xfutil.tile(sdfg, entry, divides_evenly, True, i=8, j=4)\n\n # Create kernel schedule by collapsing and reordering maps\n gtile_i = find_map_by_param(sdfg, 'tile_i')\n gtile_j = find_map_by_param(sdfg, 'tile_j')\n btile_i = find_map_by_param(sdfg, 'tile1_i')\n btile_j = find_map_by_param(sdfg, 'tile1_j')\n MapCollapse.apply_to(sdfg,\n _outer_map_entry=gtile_i,\n _inner_map_entry=gtile_j)\n MapCollapse.apply_to(sdfg,\n _outer_map_entry=btile_i,\n _inner_map_entry=btile_j)\n btile = find_map_by_param(sdfg, 'tile1_i')\n btile.map.schedule = dace.ScheduleType.GPU_ThreadBlock\n\n # Add local storage (shared memory) for A and B on GPU\n ktile = find_map_by_param(sdfg, 'tile_k')\n smem_a = InLocalStorage.apply_to(sdfg,\n dict(array='A'),\n node_a=ktile,\n node_b=btile)\n smem_b = InLocalStorage.apply_to(sdfg,\n dict(array='B'),\n node_a=ktile,\n node_b=btile)\n sdfg.arrays[smem_a.data].storage = dace.StorageType.GPU_Shared\n sdfg.arrays[smem_b.data].storage = dace.StorageType.GPU_Shared\n\n # Add local storage (registers) for A and B\n ttile = find_map_by_param(sdfg, 'k')\n warptile, ttile = xfutil.extract_map_dims(sdfg, ttile, [2])\n InLocalStorage.apply_to(sdfg,\n dict(array='trans_gpu_A'),\n node_a=warptile,\n node_b=ttile)\n InLocalStorage.apply_to(sdfg,\n dict(array='trans_gpu_B'),\n node_a=warptile,\n node_b=ttile)\n\n # Add local storage (registers) for C\n state = next(s for s in sdfg.nodes() if warptile in s.nodes())\n warptile_exit = state.exit_node(warptile)\n btile_exit = state.exit_node(btile)\n AccumulateTransient.apply_to(sdfg,\n map_exit=warptile_exit,\n outer_map_exit=btile_exit)\n # Set C tile to zero on allocation\n c_access = next(n for n in state.data_nodes() if n.data == 'trans_gpu_C')\n c_access.setzero = True\n\n # Unroll microkernel maps\n ttile.map.unroll = True\n\n # Apply double-buffering on shared memory\n DoubleBuffering.apply_to(sdfg, _map_entry=ktile, _transient=smem_a)\n\n\n#####################################################################\n# Main function\n\nif __name__ == \"__main__\":\n # Arugments\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-M\", type=int, nargs=\"?\", default=64)\n parser.add_argument(\"-K\", type=int, nargs=\"?\", default=64)\n parser.add_argument(\"-N\", type=int, nargs=\"?\", default=64)\n parser.add_argument('--version',\n choices=[\n 'unoptimized', 'optimize_cpu', 'optimize_gpu',\n 'mkl', 'cublas', 'fpga_naive', 'fpga_library'\n ],\n default='unoptimized',\n help='''Different available versions:\nunoptimized: Run `matmul` without optimizations;\noptimize_cpu: Transform `matmul` to a reasonably-optimized version for\n multicore CPU;\noptimize_gpu: Transform `matmul` to a reasonably-optimized version for GPU;\nmkl: Use `matmul_lib` with the MKL library node implementation;\ncublas: Use `matmul_lib` with the CUBLAS library node implementation.''')\n parser.add_argument('--noverify',\n dest='verify',\n action='store_false',\n help=\"If set, skips numpy verification.\",\n default=True)\n\n args = vars(parser.parse_args())\n version = args[\"version\"]\n\n # Prepare data with numpy\n m = args[\"M\"]\n k = args[\"K\"]\n n = args[\"N\"]\n A = np.random.rand(m, k).astype(np_dtype)\n B = np.random.rand(k, n).astype(np_dtype)\n C = np.zeros((m, n), dtype=np_dtype)\n\n print(f'Matrix multiplication {m}x{k}x{n} (version: {version})')\n\n if version == 'unoptimized':\n # Simply call the program to run it\n matmul(A, B, C)\n elif version.startswith('optimize_'):\n # Get the SDFG from the program\n sdfg: dace.SDFG = matmul.to_sdfg()\n # Call transformations to optimize\n if version == 'optimize_cpu':\n optimize_for_cpu(sdfg, m, n, k)\n elif version == 'optimize_gpu':\n optimize_for_gpu(sdfg, m, n, k)\n # Invoke the SDFG to run the optimized program (notice that now we must\n # also directly feed in the symbols)\n sdfg(A=A, B=B, C=C, M=m, N=n, K=k)\n elif version == 'mkl':\n # Set default implementation to MKL\n dace.libraries.blas.default_implementation = 'MKL'\n # Call program\n C = matmul_lib(A, B)\n elif version == 'cublas':\n # Set default implementation to CUBLAS\n dace.libraries.blas.default_implementation = 'cuBLAS'\n # Call program\n C = matmul_lib(A, B)\n elif version == 'fpga_naive':\n matmul = matmul.to_sdfg()\n matmul.apply_transformations(FPGATransformSDFG)\n matmul(A=A, B=B, C=C, N=n, K=k, M=m)\n elif version == 'fpga_systolic':\n dace.libraries.blas.default_implementation = 'FPGA1DSystolic'\n C = matmul_lib(A, B)\n else:\n raise ValueError('Invalid version %s' % version)\n\n if args[\"verify\"]:\n expected = A @ B\n diff = np.linalg.norm(C - expected) / (m * n)\n print('Difference:', diff)\n exit(0 if diff <= 1e-6 else 1)\n", "# Copyright 2019-2021 ETH Zurich and the DaCe authors. All rights reserved.\nimport dace\nimport numpy as np\n\n\ndef test_multiassign():\n @dace.program\n def multiassign(A: dace.float64[20], B: dace.float64[1],\n C: dace.float64[2]):\n tmp = C[0] = A[5]\n B[0] = tmp\n\n A = np.random.rand(20)\n B = np.random.rand(1)\n C = np.random.rand(2)\n multiassign(A, B, C)\n assert B == C[0] and C[0] == A[5]\n\n\ndef test_multiassign_mutable():\n @dace.program\n def mutable(D: dace.float64[2]):\n D[0] += 1\n return D[0]\n\n @dace.program\n def multiassign(B: dace.float64[1],\n C: dace.float64[2]):\n tmp = C[1] = mutable(C)\n B[0] = tmp\n\n B = np.random.rand(1)\n C = np.random.rand(2)\n expected = C[0] + 1\n multiassign(B, C)\n assert B[0] == expected and C[1] == expected\n\n\nif __name__ == '__main__':\n test_multiassign()\n test_multiassign_mutable()\n", "# Copyright 2019-2021 ETH Zurich and the DaCe authors. All rights reserved.\n\n# The scope of the test is to verify that two nested SDFGs within the same state are generated\n# as two different FPGA kernels.\n\n# There are two different tests:\n# - independent: the two nested SDFGs (vector addition and vector multiplication) do not depend one from the other\n# - dependent: the second nested SDFG uses the result produced by the first one. The result is stored on an FPGA array\n# The two Nested SDFGs implements vector addition\n\nimport dace\nimport numpy as np\nimport argparse\nimport subprocess\n\nfrom dace.memlet import Memlet\n\n\ndef make_vec_add_sdfg(dtype=dace.float32):\n\n # Vector addition SDFG\n\n vecWidth = 4\n n = dace.symbol(\"size\")\n vecAdd_sdfg = dace.SDFG(\"vec_add\")\n vecType = dace.vector(dtype, vecWidth)\n fpga_state = vecAdd_sdfg.add_state(\"vec_add_state\")\n\n vecAdd_sdfg.add_array('_device_x',\n shape=[n / vecWidth],\n dtype=vecType,\n storage=dace.dtypes.StorageType.FPGA_Global)\n vecAdd_sdfg.add_array('_device_y',\n shape=[n / vecWidth],\n dtype=vecType,\n storage=dace.dtypes.StorageType.FPGA_Global)\n vecAdd_sdfg.add_array('_device_z',\n shape=[n / vecWidth],\n dtype=vecType,\n storage=dace.dtypes.StorageType.FPGA_Global)\n\n x = fpga_state.add_read(\"_device_x\")\n y = fpga_state.add_read(\"_device_y\")\n z = fpga_state.add_write(\"_device_z\")\n\n # ---------- ----------\n # COMPUTE\n # ---------- ----------\n vecMap_entry, vecMap_exit = fpga_state.add_map(\n 'vecAdd_map',\n dict(i='0:{0}/{1}'.format(n, vecWidth)),\n schedule=dace.dtypes.ScheduleType.FPGA_Device)\n\n vecAdd_tasklet = fpga_state.add_tasklet('vec_add_task', ['x_con', 'y_con'],\n ['z_con'], 'z_con = x_con + y_con')\n\n fpga_state.add_memlet_path(x,\n vecMap_entry,\n vecAdd_tasklet,\n dst_conn='x_con',\n memlet=dace.Memlet(f\"{x.data}[i]\"))\n\n fpga_state.add_memlet_path(y,\n vecMap_entry,\n vecAdd_tasklet,\n dst_conn='y_con',\n memlet=dace.Memlet(f\"{y.data}[i]\"))\n\n fpga_state.add_memlet_path(vecAdd_tasklet,\n vecMap_exit,\n z,\n src_conn='z_con',\n memlet=dace.Memlet(f\"{z.data}[i]\"))\n\n #########\n # Validate\n vecAdd_sdfg.fill_scope_connectors()\n vecAdd_sdfg.validate()\n return vecAdd_sdfg\n\n\ndef make_vec_mul_sdfg(dtype=dace.float32):\n # Vector multiplication SDFG\n\n vecWidth = 4\n n = dace.symbol(\"size\")\n vecMul_sdfg = dace.SDFG(\"vec_mul\")\n vecType = dace.vector(dtype, vecWidth)\n fpga_state = vecMul_sdfg.add_state(\"vec_mul_state\")\n\n vecMul_sdfg.add_array('_device_x',\n shape=[n / vecWidth],\n dtype=vecType,\n storage=dace.dtypes.StorageType.FPGA_Global)\n vecMul_sdfg.add_array('_device_y',\n shape=[n / vecWidth],\n dtype=vecType,\n storage=dace.dtypes.StorageType.FPGA_Global)\n vecMul_sdfg.add_array('_device_z',\n shape=[n / vecWidth],\n dtype=vecType,\n storage=dace.dtypes.StorageType.FPGA_Global)\n\n x = fpga_state.add_read(\"_device_x\")\n y = fpga_state.add_read(\"_device_y\")\n z = fpga_state.add_write(\"_device_z\")\n\n # ---------- ----------\n # COMPUTE\n # ---------- ----------\n vecMap_entry, vecMap_exit = fpga_state.add_map(\n 'vecMul_map',\n dict(i='0:{0}/{1}'.format(n, vecWidth)),\n schedule=dace.dtypes.ScheduleType.FPGA_Device)\n\n vecMul_tasklet = fpga_state.add_tasklet('vecMul_task', ['x_con', 'y_con'],\n ['z_con'], 'z_con = x_con * y_con')\n\n fpga_state.add_memlet_path(x,\n vecMap_entry,\n vecMul_tasklet,\n dst_conn='x_con',\n memlet=dace.Memlet(f\"{x.data}[i]\"))\n\n fpga_state.add_memlet_path(y,\n vecMap_entry,\n vecMul_tasklet,\n dst_conn='y_con',\n memlet=dace.Memlet(f\"{y.data}[i]\"))\n\n fpga_state.add_memlet_path(vecMul_tasklet,\n vecMap_exit,\n z,\n src_conn='z_con',\n memlet=dace.Memlet(f\"{z.data}[i]\"))\n\n #########\n # Validate\n vecMul_sdfg.fill_scope_connectors()\n vecMul_sdfg.validate()\n return vecMul_sdfg\n\n\ndef make_fpga_sdfg():\n '''\n Build an SDFG with two nested SDFGs in a single FPGA state\n '''\n\n n = dace.symbol(\"n\")\n vecWidth = 4\n vecType = dace.vector(dace.float32, vecWidth)\n sdfg = dace.SDFG(\"nested_sdfg_kernels\")\n\n ###########################################################################\n # Copy data to FPGA\n\n copy_in_state = sdfg.add_state(\"copy_to_device\")\n\n sdfg.add_array(\"x\", shape=[n / vecWidth], dtype=vecType)\n sdfg.add_array(\"y\", shape=[n / vecWidth], dtype=vecType)\n\n sdfg.add_array(\"v\", shape=[n / vecWidth], dtype=vecType)\n\n in_host_x = copy_in_state.add_read(\"x\")\n in_host_y = copy_in_state.add_read(\"y\")\n\n in_host_v = copy_in_state.add_read(\"v\")\n\n sdfg.add_array(\"device_x\",\n shape=[n / vecWidth],\n dtype=vecType,\n storage=dace.dtypes.StorageType.FPGA_Global,\n transient=True)\n sdfg.add_array(\"device_y\",\n shape=[n / vecWidth],\n dtype=vecType,\n storage=dace.dtypes.StorageType.FPGA_Global,\n transient=True)\n\n sdfg.add_array(\"device_v\",\n shape=[n / vecWidth],\n dtype=vecType,\n storage=dace.dtypes.StorageType.FPGA_Global,\n transient=True)\n\n in_device_x = copy_in_state.add_write(\"device_x\")\n in_device_y = copy_in_state.add_write(\"device_y\")\n\n in_device_v = copy_in_state.add_write(\"device_v\")\n\n copy_in_state.add_memlet_path(\n in_host_x,\n in_device_x,\n memlet=dace.Memlet(f\"{in_host_x.data}[0:{n}/{vecWidth}]\"))\n copy_in_state.add_memlet_path(\n in_host_y,\n in_device_y,\n memlet=dace.Memlet(f\"{in_host_y.data}[0:{n}/{vecWidth}]\"))\n\n copy_in_state.add_memlet_path(\n in_host_v,\n in_device_v,\n memlet=dace.Memlet(f\"{in_host_v.data}[0:{n}/{vecWidth}]\"))\n\n ###########################################################################\n # Copy data from FPGA\n sdfg.add_array(\"z\", shape=[n / vecWidth], dtype=vecType)\n sdfg.add_array(\"u\", shape=[n / vecWidth], dtype=vecType)\n\n copy_out_state = sdfg.add_state(\"copy_to_host\")\n\n sdfg.add_array(\"device_z\",\n shape=[n / vecWidth],\n dtype=vecType,\n storage=dace.dtypes.StorageType.FPGA_Global,\n transient=True)\n\n sdfg.add_array(\"device_u\",\n shape=[n / vecWidth],\n dtype=vecType,\n storage=dace.dtypes.StorageType.FPGA_Global,\n transient=True)\n\n out_device_z = copy_out_state.add_read(\"device_z\")\n out_host_z = copy_out_state.add_write(\"z\")\n\n out_device_u = copy_out_state.add_read(\"device_u\")\n out_host_u = copy_out_state.add_write(\"u\")\n\n copy_out_state.add_memlet_path(\n out_device_z,\n out_host_z,\n memlet=dace.Memlet(f\"{out_host_z.data}[0:{n}/{vecWidth}]\"))\n copy_out_state.add_memlet_path(\n out_device_u,\n out_host_u,\n memlet=dace.Memlet(f\"{out_host_u.data}[0:{n}/{vecWidth}]\"))\n ###########################################################################\n # State that must not become an FPGA kernel\n\n non_fpga_state = sdfg.add_state(\"I_do_not_want_to_be_fpga_kernel\")\n non_fpga_state.location[\"is_FPGA_kernel\"] = False\n # Build the vec addition SDFG and nest it\n\n to_nest = make_vec_add_sdfg()\n # add nested sdfg with symbol mapping\n nested_sdfg = non_fpga_state.add_nested_sdfg(to_nest, sdfg,\n {\"_device_x\", \"_device_y\"},\n {\"_device_z\"}, {\"size\": \"n\"})\n\n non_fpga_state.add_memlet_path(\n in_device_x,\n nested_sdfg,\n dst_conn=\"_device_x\",\n memlet=dace.Memlet(f\"{in_device_x.data}[0:{n}/{vecWidth}]\"))\n non_fpga_state.add_memlet_path(\n in_device_y,\n nested_sdfg,\n dst_conn=\"_device_y\",\n memlet=dace.Memlet(f\"{in_device_y.data}[0:{n}/{vecWidth}]\"))\n non_fpga_state.add_memlet_path(\n nested_sdfg,\n out_device_z,\n src_conn=\"_device_z\",\n memlet=dace.Memlet(f\"{out_device_z.data}[0:{n}/{vecWidth}]\"))\n\n # Build the second vec addition SDFG and nest it\n\n to_nest = make_vec_add_sdfg()\n # add nested sdfg with symbol mapping\n nested_sdfg = non_fpga_state.add_nested_sdfg(to_nest, sdfg,\n {\"_device_x\", \"_device_y\"},\n {\"_device_z\"}, {\"size\": \"n\"})\n\n non_fpga_state.add_memlet_path(\n out_device_z,\n nested_sdfg,\n dst_conn=\"_device_x\",\n memlet=dace.Memlet(f\"{out_device_z.data}[0:{n}/{vecWidth}]\"))\n non_fpga_state.add_memlet_path(\n in_device_v,\n nested_sdfg,\n dst_conn=\"_device_y\",\n memlet=dace.Memlet(f\"{in_device_v.data}[0:{n}/{vecWidth}]\"))\n non_fpga_state.add_memlet_path(\n nested_sdfg,\n out_device_u,\n src_conn=\"_device_z\",\n memlet=dace.Memlet(f\"{out_device_u.data}[0:{n}/{vecWidth}]\"))\n\n ######################################\n # Interstate edges\n sdfg.add_edge(copy_in_state, non_fpga_state,\n dace.sdfg.sdfg.InterstateEdge())\n sdfg.add_edge(non_fpga_state, copy_out_state,\n dace.sdfg.sdfg.InterstateEdge())\n sdfg.fill_scope_connectors()\n sdfg.validate()\n\n return sdfg\n\n\ndef make_fpga_sdfg_independent():\n '''\n Build an SDFG with two nested SDFGs in a single FPGA state\n '''\n\n n = dace.symbol(\"n\")\n vecWidth = 4\n vecType = dace.vector(dace.float32, vecWidth)\n sdfg = dace.SDFG(\"nested_sdfg_kernels\")\n\n ###########################################################################\n # Copy data to FPGA\n\n copy_in_state = sdfg.add_state(\"copy_to_device\")\n\n sdfg.add_array(\"x\", shape=[n / vecWidth], dtype=vecType)\n sdfg.add_array(\"y\", shape=[n / vecWidth], dtype=vecType)\n\n sdfg.add_array(\"v\", shape=[n / vecWidth], dtype=vecType)\n sdfg.add_array(\"w\", shape=[n / vecWidth], dtype=vecType)\n\n in_host_x = copy_in_state.add_read(\"x\")\n in_host_y = copy_in_state.add_read(\"y\")\n\n in_host_v = copy_in_state.add_read(\"v\")\n in_host_w = copy_in_state.add_read(\"w\")\n\n sdfg.add_array(\"device_x\",\n shape=[n / vecWidth],\n dtype=vecType,\n storage=dace.dtypes.StorageType.FPGA_Global,\n transient=True)\n sdfg.add_array(\"device_y\",\n shape=[n / vecWidth],\n dtype=vecType,\n storage=dace.dtypes.StorageType.FPGA_Global,\n transient=True)\n\n sdfg.add_array(\"device_v\",\n shape=[n / vecWidth],\n dtype=vecType,\n storage=dace.dtypes.StorageType.FPGA_Global,\n transient=True)\n sdfg.add_array(\"device_w\",\n shape=[n / vecWidth],\n dtype=vecType,\n storage=dace.dtypes.StorageType.FPGA_Global,\n transient=True)\n\n in_device_x = copy_in_state.add_write(\"device_x\")\n in_device_y = copy_in_state.add_write(\"device_y\")\n\n in_device_v = copy_in_state.add_write(\"device_v\")\n in_device_w = copy_in_state.add_write(\"device_w\")\n\n copy_in_state.add_memlet_path(\n in_host_x,\n in_device_x,\n memlet=dace.Memlet(f\"{in_host_x.data}[0:{n}/{vecWidth}]\"))\n copy_in_state.add_memlet_path(\n in_host_y,\n in_device_y,\n memlet=dace.Memlet(f\"{in_host_y.data}[0:{n}/{vecWidth}]\"))\n\n copy_in_state.add_memlet_path(\n in_host_v,\n in_device_v,\n memlet=dace.Memlet(f\"{in_host_v.data}[0:{n}/{vecWidth}]\"))\n copy_in_state.add_memlet_path(\n in_host_w,\n in_device_w,\n memlet=dace.Memlet(f\"{in_host_w.data}[0:{n}/{vecWidth}]\"))\n\n ###########################################################################\n # Copy data from FPGA\n sdfg.add_array(\"z\", shape=[n / vecWidth], dtype=vecType)\n sdfg.add_array(\"u\", shape=[n / vecWidth], dtype=vecType)\n\n copy_out_state = sdfg.add_state(\"copy_to_host\")\n\n sdfg.add_array(\"device_z\",\n shape=[n / vecWidth],\n dtype=vecType,\n storage=dace.dtypes.StorageType.FPGA_Global,\n transient=True)\n\n sdfg.add_array(\"device_u\",\n shape=[n / vecWidth],\n dtype=vecType,\n storage=dace.dtypes.StorageType.FPGA_Global,\n transient=True)\n\n out_device_z = copy_out_state.add_read(\"device_z\")\n out_host_z = copy_out_state.add_write(\"z\")\n\n out_device_u = copy_out_state.add_read(\"device_u\")\n out_host_u = copy_out_state.add_write(\"u\")\n\n copy_out_state.add_memlet_path(\n out_device_z,\n out_host_z,\n memlet=dace.Memlet(f\"{out_host_z.data}[0:{n}/{vecWidth}]\"))\n copy_out_state.add_memlet_path(\n out_device_u,\n out_host_u,\n memlet=dace.Memlet(f\"{out_host_u.data}[0:{n}/{vecWidth}]\"))\n ###########################################################################\n # Non-FPGA state\n\n non_fpga_state = sdfg.add_state(\"I_do_not_want_to_be_fpga_kernel\")\n non_fpga_state.location[\"is_FPGA_kernel\"] = False\n\n # Build the vec addition SDFG and nest it\n\n to_nest = make_vec_add_sdfg()\n # add nested sdfg with symbol mapping\n nested_sdfg = non_fpga_state.add_nested_sdfg(to_nest, sdfg,\n {\"_device_x\", \"_device_y\"},\n {\"_device_z\"}, {\"size\": \"n\"})\n\n non_fpga_state.add_memlet_path(\n in_device_x,\n nested_sdfg,\n dst_conn=\"_device_x\",\n memlet=dace.Memlet(f\"{in_device_x.data}[0:{n}/{vecWidth}]\"))\n non_fpga_state.add_memlet_path(\n in_device_y,\n nested_sdfg,\n dst_conn=\"_device_y\",\n memlet=dace.Memlet(f\"{in_device_y.data}[0:{n}/{vecWidth}]\"))\n non_fpga_state.add_memlet_path(\n nested_sdfg,\n out_device_z,\n src_conn=\"_device_z\",\n memlet=dace.Memlet(f\"{out_device_z.data}[0:{n}/{vecWidth}]\"))\n\n # Build the vec multiplication SDFG and nest it\n\n to_nest = make_vec_mul_sdfg()\n # add nested sdfg with symbol mapping\n nested_sdfg = non_fpga_state.add_nested_sdfg(to_nest, sdfg,\n {\"_device_x\", \"_device_y\"},\n {\"_device_z\"}, {\"size\": \"n\"})\n\n non_fpga_state.add_memlet_path(\n in_device_v,\n nested_sdfg,\n dst_conn=\"_device_x\",\n memlet=dace.Memlet(f\"{in_device_v.data}[0:{n}/{vecWidth}]\"))\n non_fpga_state.add_memlet_path(\n in_device_w,\n nested_sdfg,\n dst_conn=\"_device_y\",\n memlet=dace.Memlet(f\"{in_device_w.data}[0:{n}/{vecWidth}]\"))\n non_fpga_state.add_memlet_path(\n nested_sdfg,\n out_device_u,\n src_conn=\"_device_z\",\n memlet=dace.Memlet(f\"{out_device_u.data}[0:{n}/{vecWidth}]\"))\n\n ######################################\n # Interstate edges\n sdfg.add_edge(copy_in_state, non_fpga_state,\n dace.sdfg.sdfg.InterstateEdge())\n sdfg.add_edge(non_fpga_state, copy_out_state,\n dace.sdfg.sdfg.InterstateEdge())\n sdfg.fill_scope_connectors()\n sdfg.validate()\n\n return sdfg\n\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"N\", type=int, nargs=\"?\", default=32)\n args = vars(parser.parse_args())\n\n size_n = args[\"N\"]\n\n ##########################################\n # SDFG with two disconnected Nested SDFGs\n #########################################\n sdfg = make_fpga_sdfg_independent()\n vec_ops = sdfg.compile()\n\n x = np.random.rand(size_n).astype(np.float32)\n y = np.random.rand(size_n).astype(np.float32)\n z = np.random.rand(size_n).astype(np.float32)\n\n v = np.random.rand(size_n).astype(np.float32)\n u = np.random.rand(size_n).astype(np.float32)\n w = np.random.rand(size_n).astype(np.float32)\n\n vec_ops(x=x, y=y, z=z, v=v, w=w, u=u, n=size_n)\n ref1 = np.add(x, y)\n ref2 = np.multiply(v, w)\n diff1 = np.linalg.norm(ref1 - z) / size_n\n diff2 = np.linalg.norm(ref2 - u) / size_n\n\n ##########################################\n # SDFG with two connected Nested SDFGs\n ##########################################\n\n sdfg = make_fpga_sdfg()\n\n vec_ops = sdfg.compile()\n\n x = np.random.rand(size_n).astype(np.float32)\n y = np.random.rand(size_n).astype(np.float32)\n z = np.random.rand(size_n).astype(np.float32)\n\n v = np.random.rand(size_n).astype(np.float32)\n\n vec_ops(x=x, y=y, z=z, v=v, u=u, n=size_n)\n ref3 = np.add(x, y)\n ref4 = np.add(ref3, v)\n\n diff3 = np.linalg.norm(ref3 - z) / size_n\n diff4 = np.linalg.norm(ref4 - u) / size_n\n\n if diff1 <= 1e-5 and diff2 <= 1e-5 and diff3 <= 1e-5 and diff4 <= 1e-5:\n print(\"==== Program end ====\")\n else:\n raise Exception(\"==== Program Error! ====\")\n\n # There is no need to check that the Nested SDFG has been generated only once. If this is not the case\n # the test will fail while compiling\n", "# Copyright 2019-2021 ETH Zurich and the DaCe authors. All rights reserved.\nfrom __future__ import print_function\n\nimport argparse\nimport dace\nimport math\nimport numpy as np\n\nN = dace.symbol(\"N\", positive=True)\n\n\ndef make_copy_to_device(sdfg):\n\n pre_state = sdfg.add_state(\"copy_to_device\")\n\n A_host = pre_state.add_read(\"A\")\n\n A_device = pre_state.add_write(\"A_device\")\n\n pre_state.add_edge(A_host, None, A_device, None,\n dace.memlet.Memlet.simple(A_device, \"0:N\"))\n\n return pre_state\n\n\ndef make_copy_to_host(sdfg):\n\n post_state = sdfg.add_state(\"copy_to_host\")\n\n B_device = post_state.add_read(\"B_device\")\n outsize_device = post_state.add_read(\"outsize_device\")\n\n B_host = post_state.add_write(\"B\")\n outsize_host = post_state.add_write(\"outsize\")\n\n post_state.add_edge(B_device, None, B_host, None,\n dace.memlet.Memlet.simple(B_device, \"0:N\"))\n post_state.add_edge(outsize_device, None, outsize_host, None,\n dace.memlet.Memlet.simple(outsize_device, \"0\"))\n\n return post_state\n\n\ndef make_compute_state(sdfg):\n\n state = sdfg.add_state(\"compute_state\")\n\n A = state.add_read(\"A_device\")\n ratio = state.add_read(\"ratio\")\n\n outsize = state.add_write(\"outsize_device\")\n B = state.add_write(\"B_device\")\n\n for_loop_sdfg = make_nested_sdfg(state)\n nested_sdfg = state.add_nested_sdfg(for_loop_sdfg, sdfg,\n {\"A_nested\", \"ratio_nested\"},\n {\"B_nested\", \"outsize_nested\"})\n\n state.add_edge(A, None, nested_sdfg, \"A_nested\",\n dace.memlet.Memlet.simple(A, \"0:N\"))\n state.add_edge(ratio, None, nested_sdfg, \"ratio_nested\",\n dace.memlet.Memlet.simple(ratio, \"0\"))\n state.add_edge(nested_sdfg, \"B_nested\", B, None,\n dace.memlet.Memlet.simple(B, \"0:N\"))\n state.add_edge(nested_sdfg, \"outsize_nested\", outsize, None,\n dace.memlet.Memlet.simple(outsize, \"0\"))\n\n return state\n\n\ndef make_nested_sdfg(parent):\n\n sdfg = dace.SDFG(\"filter_nested\")\n\n sdfg.add_scalar(\"outsize_buffer\",\n dtype=dace.uint32,\n transient=True,\n storage=dace.dtypes.StorageType.FPGA_Registers)\n sdfg.add_array(\"outsize_nested\", [1],\n dtype=dace.uint32,\n storage=dace.dtypes.StorageType.FPGA_Global)\n sdfg.add_array(\"A_nested\", [N],\n dtype=dace.float32,\n storage=dace.dtypes.StorageType.FPGA_Global)\n sdfg.add_array(\"B_nested\", [N],\n dtype=dace.float32,\n storage=dace.dtypes.StorageType.FPGA_Global)\n sdfg.add_scalar(\"ratio_nested\",\n dtype=dace.float32,\n storage=dace.dtypes.StorageType.FPGA_Global)\n\n set_zero = make_set_zero(sdfg)\n loop_entry = sdfg.add_state(\"loop_entry\")\n loop_body = make_loop_body(sdfg)\n write_out_size = make_write_out_size(sdfg)\n\n sdfg.add_edge(set_zero, loop_entry,\n dace.sdfg.InterstateEdge(assignments={\"i\": 0}))\n\n sdfg.add_edge(\n loop_entry, loop_body,\n dace.sdfg.InterstateEdge(\n condition=dace.properties.CodeProperty.from_string(\n \"i < N\", language=dace.dtypes.Language.Python)))\n\n sdfg.add_edge(\n loop_entry, write_out_size,\n dace.sdfg.InterstateEdge(\n condition=dace.properties.CodeProperty.from_string(\n \"i >= N\", language=dace.dtypes.Language.Python)))\n\n sdfg.add_edge(loop_body, loop_entry,\n dace.sdfg.InterstateEdge(assignments={\"i\": \"i + 1\"}))\n\n return sdfg\n\n\ndef make_set_zero(sdfg):\n\n set_zero = sdfg.add_state(\"set_zero\")\n tasklet = set_zero.add_tasklet(\"set_zero\", {}, {\"size_zero\"},\n \"size_zero = 0\")\n outsize = set_zero.add_write(\"outsize_buffer\")\n set_zero.add_edge(tasklet, \"size_zero\", outsize, None,\n dace.memlet.Memlet.simple(outsize, \"0\"))\n\n return set_zero\n\n\ndef make_write_out_size(sdfg):\n\n write_out = sdfg.add_state(\"write_out\")\n outsize_buffer = write_out.add_read(\"outsize_buffer\")\n outsize = write_out.add_write(\"outsize_nested\")\n write_out.add_edge(outsize_buffer, None, outsize, None,\n dace.memlet.Memlet.simple(outsize, \"0\"))\n\n return write_out\n\n\ndef make_loop_body(sdfg):\n\n state = sdfg.add_state(\"loop_body\")\n\n A = state.add_read(\"A_nested\")\n B = state.add_write(\"B_nested\")\n ratio = state.add_read(\"ratio_nested\")\n\n outsize_buffer_in = state.add_read(\"outsize_buffer\")\n outsize_buffer_out = state.add_write(\"outsize_buffer\")\n\n tasklet = state.add_tasklet(\n \"filter\", {\"a\", \"write_index\", \"r\"}, {\"b\", \"size_out\"}, \"if a > r:\"\n \"\\n\\tb[write_index] = a\"\n \"\\n\\tsize_out = write_index + 1\")\n\n state.add_edge(A, None, tasklet, \"a\", dace.memlet.Memlet.simple(A, \"i\"))\n state.add_edge(ratio, None, tasklet, \"r\",\n dace.memlet.Memlet.simple(ratio, \"0\"))\n state.add_edge(\n tasklet, \"b\", B, None,\n dace.memlet.Memlet.simple(B,\n dace.subsets.Range.from_array(B.desc(sdfg)),\n num_accesses=-1))\n state.add_edge(outsize_buffer_in, None, tasklet, \"write_index\",\n dace.memlet.Memlet.simple(outsize_buffer_in, \"0\"))\n state.add_edge(\n tasklet, \"size_out\", outsize_buffer_out, None,\n dace.memlet.Memlet.simple(outsize_buffer_out, \"0\", num_accesses=-1))\n\n return state\n\n\ndef make_sdfg(specialize):\n\n if not specialize:\n sdfg = dace.SDFG(\"filter_fpga\")\n else:\n sdfg = dace.SDFG(\"filter_fpga_{}\".format(N.get()))\n\n sdfg.add_array(\"A_device\", [N],\n dtype=dace.float32,\n transient=True,\n storage=dace.dtypes.StorageType.FPGA_Global)\n sdfg.add_array(\"A\", [N], dtype=dace.float32)\n\n sdfg.add_array(\"B_device\", [N],\n dtype=dace.float32,\n transient=True,\n storage=dace.dtypes.StorageType.FPGA_Global)\n sdfg.add_array(\"outsize_device\", [1],\n dtype=dace.uint32,\n transient=True,\n storage=dace.dtypes.StorageType.FPGA_Global)\n sdfg.add_array(\"B\", [N], dtype=dace.float32)\n sdfg.add_array(\"outsize\", [1], dtype=dace.uint32)\n sdfg.add_scalar(\"ratio\",\n storage=dace.dtypes.StorageType.FPGA_Global,\n dtype=dace.float32)\n\n copy_to_device_state = make_copy_to_device(sdfg)\n compute_state = make_compute_state(sdfg)\n copy_to_host_state = make_copy_to_host(sdfg)\n\n sdfg.add_edge(copy_to_device_state, compute_state,\n dace.sdfg.InterstateEdge())\n sdfg.add_edge(compute_state, copy_to_host_state, dace.sdfg.InterstateEdge())\n\n return sdfg\n\n\ndef regression(A, ratio):\n return A[np.where(A > ratio)]\n\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"N\", type=int)\n parser.add_argument(\"ratio\", type=float)\n parser.add_argument(\"-specialize\",\n default=False,\n action=\"store_true\",\n help=\"Fix all symbols at compile time/in hardware\")\n args = vars(parser.parse_args())\n\n N.set(args[\"N\"])\n\n A = dace.ndarray([N], dtype=dace.float32)\n B = dace.ndarray([N], dtype=dace.float32)\n outsize = dace.scalar(dace.uint32)\n outsize[0] = 0\n\n ratio = np.float32(args[\"ratio\"])\n\n print(\"Predicate-Based Filter. size={}, ratio={} ({}specialized)\".format(\n N.get(), ratio, \"\" if args[\"specialize\"] else \"not \"))\n\n A[:] = np.random.rand(N.get()).astype(dace.float32.type)\n B[:] = dace.float32(0)\n\n sdfg = make_sdfg(args[\"specialize\"])\n if args[\"specialize\"]:\n sdfg.specialize(dict(N=N))\n sdfg(A=A, B=B, outsize=outsize, ratio=ratio)\n else:\n sdfg(A=A, B=B, outsize=outsize, ratio=ratio, N=N)\n\n if dace.Config.get_bool('profiling'):\n dace.timethis('filter', 'numpy', 0, regression, A, ratio)\n\n filtered = regression(A, ratio)\n\n if len(filtered) != outsize[0]:\n print(\n \"Difference in number of filtered items: %d (DaCe) vs. %d (numpy)\" %\n (outsize[0], len(filtered)))\n totalitems = min(outsize[0], N.get())\n print('DaCe:', B[:totalitems].view(type=np.ndarray))\n print('Regression:', filtered.view(type=np.ndarray))\n exit(1)\n\n # Sort the outputs\n filtered = np.sort(filtered)\n B[:outsize[0]] = np.sort(B[:outsize[0]])\n\n if len(filtered) == 0:\n print(\"==== Program end ====\")\n exit(0)\n\n diff = np.linalg.norm(filtered - B[:outsize[0]]) / float(outsize[0])\n print(\"Difference:\", diff)\n if diff > 1e-5:\n totalitems = min(outsize[0], N.get())\n print('DaCe:', B[:totalitems].view(type=np.ndarray))\n print('Regression:', filtered.view(type=np.ndarray))\n\n print(\"==== Program end ====\")\n exit(0 if diff <= 1e-5 else 1)\n", "# Copyright 2019-2021 ETH Zurich and the DaCe authors. All rights reserved.\nfrom typing import Optional, Set, Tuple\n\nimport collections\nimport copy\nimport dace\nimport functools\nimport re\nfrom dace.codegen import control_flow as cflow\nfrom dace.codegen import dispatcher as disp\nfrom dace.codegen.prettycode import CodeIOStream\nfrom dace.codegen.targets.common import codeblock_to_cpp, sym2cpp\nfrom dace.codegen.targets.cpp import unparse_interstate_edge\nfrom dace.codegen.targets.target import TargetCodeGenerator\nfrom dace.sdfg import SDFG, SDFGState, ScopeSubgraphView\nfrom dace.sdfg import nodes\nfrom dace.sdfg.infer_types import set_default_schedule_and_storage_types\nfrom dace import dtypes, data, config\nfrom typing import Any, List\n\nfrom dace.frontend.python import wrappers\n\nimport networkx as nx\nimport numpy as np\n\n\ndef _get_or_eval_sdfg_first_arg(func, sdfg):\n if callable(func):\n return func(sdfg)\n return func\n\nclass DaCeCodeGenerator(object):\n \"\"\" DaCe code generator class that writes the generated code for SDFG\n state machines, and uses a dispatcher to generate code for\n individual states based on the target. \"\"\"\n def __init__(self, *args, **kwargs):\n self._dispatcher = disp.TargetDispatcher(self)\n self._dispatcher.register_state_dispatcher(self)\n self._initcode = CodeIOStream()\n self._exitcode = CodeIOStream()\n self.statestruct: List[str] = []\n self.environments: List[Any] = []\n\n ##################################################################\n # Target registry\n\n @property\n def dispatcher(self):\n return self._dispatcher\n\n ##################################################################\n # Code generation\n\n def generate_constants(self, sdfg: SDFG, callsite_stream: CodeIOStream):\n # Write constants\n for cstname, (csttype, cstval) in sdfg.constants_prop.items():\n if isinstance(csttype, data.Array):\n const_str = \"constexpr \" + csttype.dtype.ctype + \\\n \" \" + cstname + \"[\" + str(cstval.size) + \"] = {\"\n it = np.nditer(cstval, order='C')\n for i in range(cstval.size - 1):\n const_str += str(it[0]) + \", \"\n it.iternext()\n const_str += str(it[0]) + \"};\\n\"\n callsite_stream.write(const_str, sdfg)\n else:\n callsite_stream.write(\n \"constexpr %s %s = %s;\\n\" %\n (csttype.dtype.ctype, cstname, sym2cpp(cstval)), sdfg)\n\n def generate_fileheader(self,\n sdfg: SDFG,\n global_stream: CodeIOStream,\n backend: str = 'frame'):\n \"\"\" Generate a header in every output file that includes custom types\n and constants.\n :param sdfg: The input SDFG.\n :param global_stream: Stream to write to (global).\n :param backend: Whose backend this header belongs to.\n \"\"\"\n # Hash file include\n if backend == 'frame':\n global_stream.write('#include \"../../include/hash.h\"\\n', sdfg)\n\n #########################################################\n # Environment-based includes\n for env in self.environments:\n if len(env.headers) > 0:\n global_stream.write(\n \"\\n\".join(\"#include \\\"\" + h + \"\\\"\" for h in env.headers),\n sdfg)\n\n #########################################################\n # Custom types\n datatypes = set()\n # Types of this SDFG\n for _, arrname, arr in sdfg.arrays_recursive():\n if arr is not None:\n datatypes.add(arr.dtype)\n\n # Emit unique definitions\n wrote_something = False\n for typ in datatypes:\n if hasattr(typ, 'emit_definition'):\n if not wrote_something:\n global_stream.write(\"\", sdfg)\n wrote_something = True\n global_stream.write(typ.emit_definition(), sdfg)\n if wrote_something:\n global_stream.write(\"\", sdfg)\n\n #########################################################\n # Write constants\n self.generate_constants(sdfg, global_stream)\n\n #########################################################\n # Write state struct\n structstr = '\\n'.join(self.statestruct)\n global_stream.write(\n f'''\nstruct {sdfg.name}_t {{\n {structstr}\n}};\n\n''', sdfg)\n\n for sd in sdfg.all_sdfgs_recursive():\n if None in sd.global_code:\n global_stream.write(codeblock_to_cpp(sd.global_code[None]), sd)\n if backend in sd.global_code:\n global_stream.write(codeblock_to_cpp(sd.global_code[backend]),\n sd)\n\n def generate_header(self, sdfg: SDFG, global_stream: CodeIOStream,\n callsite_stream: CodeIOStream):\n \"\"\" Generate the header of the frame-code. Code exists in a separate\n function for overriding purposes.\n :param sdfg: The input SDFG.\n :param global_stream: Stream to write to (global).\n :param callsite_stream: Stream to write to (at call site).\n \"\"\"\n # Write frame code - header\n global_stream.write(\n '/* DaCe AUTO-GENERATED FILE. DO NOT MODIFY */\\n' +\n '#include <dace/dace.h>\\n', sdfg)\n\n # Write header required by environments\n for env in self.environments:\n self.statestruct.extend(env.state_fields)\n\n # Instrumentation preamble\n if len(self._dispatcher.instrumentation) > 1:\n self.statestruct.append('dace::perf::Report report;')\n # Reset report if written every invocation\n if config.Config.get_bool('instrumentation',\n 'report_each_invocation'):\n callsite_stream.write('__state->report.reset();', sdfg)\n\n self.generate_fileheader(sdfg, global_stream, 'frame')\n\n def generate_footer(self, sdfg: SDFG, global_stream: CodeIOStream,\n callsite_stream: CodeIOStream):\n \"\"\" Generate the footer of the frame-code. Code exists in a separate\n function for overriding purposes.\n :param sdfg: The input SDFG.\n :param global_stream: Stream to write to (global).\n :param callsite_stream: Stream to write to (at call site).\n \"\"\"\n import dace.library\n fname = sdfg.name\n params = sdfg.signature()\n paramnames = sdfg.signature(False, for_call=True)\n initparams = sdfg.signature(with_arrays=False)\n initparamnames = sdfg.signature(False, for_call=True, with_arrays=False)\n\n # Invoke all instrumentation providers\n for instr in self._dispatcher.instrumentation.values():\n if instr is not None:\n instr.on_sdfg_end(sdfg, callsite_stream, global_stream)\n\n # Instrumentation saving\n if (config.Config.get_bool('instrumentation', 'report_each_invocation')\n and len(self._dispatcher.instrumentation) > 1):\n callsite_stream.write(\n '''__state->report.save(\"{path}/perf\", __HASH_{name});'''\n .format(path=sdfg.build_folder.replace('\\\\', '/'),\n name=sdfg.name), sdfg)\n\n # Write closing brace of program\n callsite_stream.write('}', sdfg)\n\n # Write awkward footer to avoid 'extern \"C\"' issues\n params_comma = (', ' + params) if params else ''\n initparams_comma = (', ' + initparams) if initparams else ''\n paramnames_comma = (', ' + paramnames) if paramnames else ''\n initparamnames_comma = (', ' + initparamnames) if initparamnames else ''\n callsite_stream.write(\n f'''\nDACE_EXPORTED void __program_{fname}({fname}_t *__state{params_comma})\n{{\n __program_{fname}_internal(__state{paramnames_comma});\n}}''', sdfg)\n\n for target in self._dispatcher.used_targets:\n if target.has_initializer:\n callsite_stream.write(\n 'DACE_EXPORTED int __dace_init_%s(%s_t *__state%s);\\n' %\n (target.target_name, sdfg.name, initparams_comma), sdfg)\n if target.has_finalizer:\n callsite_stream.write(\n 'DACE_EXPORTED int __dace_exit_%s(%s_t *__state);\\n' %\n (target.target_name, sdfg.name), sdfg)\n\n callsite_stream.write(\n f\"\"\"\nDACE_EXPORTED {sdfg.name}_t *__dace_init_{sdfg.name}({initparams})\n{{\n int __result = 0;\n {sdfg.name}_t *__state = new {sdfg.name}_t;\n\n \"\"\", sdfg)\n\n for target in self._dispatcher.used_targets:\n if target.has_initializer:\n callsite_stream.write(\n '__result |= __dace_init_%s(__state%s);' %\n (target.target_name, initparamnames_comma), sdfg)\n for env in self.environments:\n init_code = _get_or_eval_sdfg_first_arg(env.init_code, sdfg)\n if init_code:\n callsite_stream.write(\"{ // Environment: \" + env.__name__,\n sdfg)\n callsite_stream.write(init_code)\n callsite_stream.write(\"}\")\n\n for sd in sdfg.all_sdfgs_recursive():\n if None in sd.init_code:\n callsite_stream.write(codeblock_to_cpp(sd.init_code[None]), sd)\n callsite_stream.write(codeblock_to_cpp(sd.init_code['frame']), sd)\n\n callsite_stream.write(self._initcode.getvalue(), sdfg)\n\n callsite_stream.write(\n f\"\"\"\n if (__result) {{\n delete __state;\n return nullptr;\n }}\n return __state;\n}}\n\nDACE_EXPORTED void __dace_exit_{sdfg.name}({sdfg.name}_t *__state)\n{{\n\"\"\", sdfg)\n\n # Instrumentation saving\n if (not config.Config.get_bool('instrumentation',\n 'report_each_invocation')\n and len(self._dispatcher.instrumentation) > 1):\n callsite_stream.write(\n '__state->report.save(\"%s/perf\", __HASH_%s);' %\n (sdfg.build_folder.replace('\\\\', '/'), sdfg.name), sdfg)\n\n callsite_stream.write(self._exitcode.getvalue(), sdfg)\n\n for sd in sdfg.all_sdfgs_recursive():\n if None in sd.exit_code:\n callsite_stream.write(codeblock_to_cpp(sd.exit_code[None]), sd)\n callsite_stream.write(codeblock_to_cpp(sd.exit_code['frame']), sd)\n\n for target in self._dispatcher.used_targets:\n if target.has_finalizer:\n callsite_stream.write(\n '__dace_exit_%s(__state);' % target.target_name, sdfg)\n for env in reversed(self.environments):\n finalize_code = _get_or_eval_sdfg_first_arg(env.finalize_code, sdfg)\n if finalize_code:\n callsite_stream.write(\"{ // Environment: \" + env.__name__,\n sdfg)\n callsite_stream.write(finalize_code)\n callsite_stream.write(\"}\")\n\n callsite_stream.write('delete __state;\\n}\\n', sdfg)\n\n def generate_state(self,\n sdfg,\n state,\n global_stream,\n callsite_stream,\n generate_state_footer=True):\n\n sid = sdfg.node_id(state)\n\n # Emit internal transient array allocation\n # Don't allocate transients shared with another state\n data_to_allocate = (set(state.top_level_transients()) -\n set(sdfg.shared_transients()))\n allocated = set()\n for node in state.data_nodes():\n if node.data not in data_to_allocate or node.data in allocated:\n continue\n allocated.add(node.data)\n self._dispatcher.dispatch_allocate(sdfg, state, sid, node,\n global_stream, callsite_stream)\n\n callsite_stream.write('\\n')\n\n # Emit internal transient array allocation for nested SDFGs\n # TODO: Replace with global allocation management\n gpu_persistent_subgraphs = [\n state.scope_subgraph(node) for node in state.nodes()\n if isinstance(node, dace.nodes.MapEntry)\n and node.map.schedule == dace.ScheduleType.GPU_Persistent\n ]\n nested_allocated = set()\n for sub_graph in gpu_persistent_subgraphs:\n for nested_sdfg in [\n n.sdfg for n in sub_graph.nodes()\n if isinstance(n, nodes.NestedSDFG)\n ]:\n nested_shared_transients = set(nested_sdfg.shared_transients())\n for nested_state in nested_sdfg.nodes():\n nested_sid = nested_sdfg.node_id(nested_state)\n nested_to_allocate = (\n set(nested_state.top_level_transients()) -\n nested_shared_transients)\n nodes_to_allocate = [\n n for n in nested_state.data_nodes()\n if n.data in nested_to_allocate\n and n.data not in nested_allocated\n ]\n for nested_node in nodes_to_allocate:\n nested_allocated.add(nested_node.data)\n self._dispatcher.dispatch_allocate(\n nested_sdfg, nested_state, nested_sid, nested_node,\n global_stream, callsite_stream)\n\n callsite_stream.write('\\n')\n\n # Invoke all instrumentation providers\n for instr in self._dispatcher.instrumentation.values():\n if instr is not None:\n instr.on_state_begin(sdfg, state, callsite_stream,\n global_stream)\n\n #####################\n # Create dataflow graph for state's children.\n\n # DFG to code scheme: Only generate code for nodes whose all\n # dependencies have been executed (topological sort).\n # For different connected components, run them concurrently.\n\n components = dace.sdfg.concurrent_subgraphs(state)\n\n if len(components) == 1:\n self._dispatcher.dispatch_subgraph(sdfg,\n state,\n sid,\n global_stream,\n callsite_stream,\n skip_entry_node=False)\n else:\n if config.Config.get_bool('compiler', 'cpu', 'openmp_sections'):\n callsite_stream.write(\"#pragma omp parallel sections\\n{\")\n for c in components:\n if config.Config.get_bool('compiler', 'cpu', 'openmp_sections'):\n callsite_stream.write(\"#pragma omp section\\n{\")\n self._dispatcher.dispatch_subgraph(sdfg,\n c,\n sid,\n global_stream,\n callsite_stream,\n skip_entry_node=False)\n if config.Config.get_bool('compiler', 'cpu', 'openmp_sections'):\n callsite_stream.write(\"} // End omp section\")\n if config.Config.get_bool('compiler', 'cpu', 'openmp_sections'):\n callsite_stream.write(\"} // End omp sections\")\n\n #####################\n # Write state footer\n\n if generate_state_footer:\n\n # Emit internal transient array deallocation for nested SDFGs\n # TODO: Replace with global allocation management\n gpu_persistent_subgraphs = [\n state.scope_subgraph(node) for node in state.nodes()\n if isinstance(node, dace.nodes.MapEntry)\n and node.map.schedule == dace.ScheduleType.GPU_Persistent\n ]\n nested_deallocated = set()\n for sub_graph in gpu_persistent_subgraphs:\n for nested_sdfg in [\n n.sdfg for n in sub_graph.nodes()\n if isinstance(n, nodes.NestedSDFG)\n ]:\n nested_shared_transients = \\\n set(nested_sdfg.shared_transients())\n for nested_state in nested_sdfg:\n nested_sid = nested_sdfg.node_id(nested_state)\n nested_to_allocate = (\n set(nested_state.top_level_transients()) -\n nested_shared_transients)\n nodes_to_deallocate = [\n n for n in nested_state.data_nodes()\n if n.data in nested_to_allocate\n and n.data not in nested_deallocated\n ]\n for nested_node in nodes_to_deallocate:\n nested_deallocated.add(nested_node.data)\n self._dispatcher.dispatch_deallocate(\n nested_sdfg, nested_state, nested_sid,\n nested_node, global_stream, callsite_stream)\n\n # Emit internal transient array deallocation\n deallocated = set()\n for node in state.data_nodes():\n if (node.data not in data_to_allocate\n or node.data in deallocated\n or (node.data in sdfg.arrays\n and sdfg.arrays[node.data].transient == False)):\n continue\n deallocated.add(node.data)\n self._dispatcher.dispatch_deallocate(sdfg, state, sid, node,\n global_stream,\n callsite_stream)\n\n # Invoke all instrumentation providers\n for instr in self._dispatcher.instrumentation.values():\n if instr is not None:\n instr.on_state_end(sdfg, state, callsite_stream,\n global_stream)\n\n def generate_states(self, sdfg, global_stream, callsite_stream):\n states_generated = set()\n\n # Create closure + function for state dispatcher\n def dispatch_state(state: SDFGState) -> str:\n stream = CodeIOStream()\n self._dispatcher.dispatch_state(sdfg, state, global_stream, stream)\n states_generated.add(state) # For sanity check\n return stream.getvalue()\n\n # Handle specialized control flow\n if config.Config.get_bool('optimizer', 'detect_control_flow'):\n # Avoid import loop\n from dace.transformation import helpers as xfh\n # Clean up the state machine by separating combined condition and assignment\n # edges.\n xfh.split_interstate_edges(sdfg)\n\n cft = cflow.structured_control_flow_tree(sdfg, dispatch_state)\n else:\n # If disabled, generate entire graph as general control flow block\n states_topological = list(sdfg.topological_sort(sdfg.start_state))\n last = states_topological[-1]\n cft = cflow.GeneralBlock(dispatch_state, [\n cflow.SingleState(dispatch_state, s, s is last)\n for s in states_topological\n ], [])\n\n callsite_stream.write(\n cft.as_cpp(self.dispatcher.defined_vars, sdfg.symbols), sdfg)\n\n # Write exit label\n callsite_stream.write(f'__state_exit_{sdfg.sdfg_id}:;', sdfg)\n\n return states_generated\n\n def generate_code(\n self,\n sdfg: SDFG,\n schedule: Optional[dtypes.ScheduleType],\n sdfg_id: str = \"\"\n ) -> Tuple[str, str, Set[TargetCodeGenerator], Set[str]]:\n \"\"\" Generate frame code for a given SDFG, calling registered targets'\n code generation callbacks for them to generate their own code.\n :param sdfg: The SDFG to generate code for.\n :param schedule: The schedule the SDFG is currently located, or\n None if the SDFG is top-level.\n :param sdfg_id: An optional string id given to the SDFG label\n :return: A tuple of the generated global frame code, local frame\n code, and a set of targets that have been used in the\n generation of this SDFG.\n \"\"\"\n\n if len(sdfg_id) == 0 and sdfg.sdfg_id != 0:\n sdfg_id = '_%d' % sdfg.sdfg_id\n\n global_stream = CodeIOStream()\n callsite_stream = CodeIOStream()\n\n is_top_level = sdfg.parent is None\n\n # Generate code\n ###########################\n\n # Keep track of allocated variables\n allocated = set()\n\n # Add symbol mappings to allocated variables\n if sdfg.parent_nsdfg_node is not None:\n allocated |= sdfg.parent_nsdfg_node.symbol_mapping.keys()\n\n # Invoke all instrumentation providers\n for instr in self._dispatcher.instrumentation.values():\n if instr is not None:\n instr.on_sdfg_begin(sdfg, callsite_stream, global_stream)\n\n # Allocate outer-level transients\n shared_transients = sdfg.shared_transients()\n for state in sdfg.nodes():\n for node in state.data_nodes():\n if (node.data in shared_transients\n and node.data not in allocated):\n self._dispatcher.dispatch_allocate(sdfg, state, None, node,\n global_stream,\n callsite_stream)\n allocated.add(node.data)\n\n # Allocate inter-state variables\n global_symbols = copy.deepcopy(sdfg.symbols)\n global_symbols.update(\n {aname: arr.dtype\n for aname, arr in sdfg.arrays.items()})\n interstate_symbols = {}\n for e in sdfg.edges():\n symbols = e.data.new_symbols(global_symbols)\n # Inferred symbols only take precedence if global symbol not defined\n symbols = {\n k: v if k not in global_symbols else global_symbols[k]\n for k, v in symbols.items()\n }\n interstate_symbols.update(symbols)\n global_symbols.update(symbols)\n\n for isvarName, isvarType in interstate_symbols.items():\n # Skip symbols that have been declared as outer-level transients\n if isvarName in allocated:\n continue\n isvar = data.Scalar(isvarType)\n callsite_stream.write(\n '%s;\\n' % (isvar.as_arg(with_types=True, name=isvarName)), sdfg)\n self.dispatcher.defined_vars.add(isvarName, isvarType,\n isvarType.ctype)\n\n callsite_stream.write('\\n', sdfg)\n\n #######################################################################\n # Generate actual program body\n\n states_generated = self.generate_states(sdfg, global_stream,\n callsite_stream)\n\n #######################################################################\n\n # Sanity check\n if len(states_generated) != len(sdfg.nodes()):\n raise RuntimeError(\n \"Not all states were generated in SDFG {}!\"\n \"\\n Generated: {}\\n Missing: {}\".format(\n sdfg.label, [s.label for s in states_generated],\n [s.label for s in (set(sdfg.nodes()) - states_generated)]))\n\n # Deallocate transients\n shared_transients = sdfg.shared_transients()\n deallocated = set()\n for state in sdfg.nodes():\n for node in state.data_nodes():\n if (node.data in shared_transients\n and node.data not in deallocated):\n self._dispatcher.dispatch_deallocate(\n sdfg, state, None, node, global_stream, callsite_stream)\n deallocated.add(node.data)\n\n # Now that we have all the information about dependencies, generate\n # header and footer\n if is_top_level:\n # Let each target append code to frame code state before generating\n # header and footer\n for target in self._dispatcher.used_targets:\n target.on_target_used()\n\n header_stream = CodeIOStream()\n header_global_stream = CodeIOStream()\n footer_stream = CodeIOStream()\n footer_global_stream = CodeIOStream()\n\n # Get all environments used in the generated code, including\n # dependent environments\n import dace.library # Avoid import loops\n self.environments = dace.library.get_environments_and_dependencies(\n self._dispatcher.used_environments)\n\n self.generate_header(sdfg, header_global_stream, header_stream)\n\n # Open program function\n params = sdfg.signature()\n if params:\n params = ', ' + params\n function_signature = (\n 'void __program_%s_internal(%s_t *__state%s)\\n{\\n' %\n (sdfg.name, sdfg.name, params))\n\n self.generate_footer(sdfg, footer_global_stream, footer_stream)\n\n header_global_stream.write(global_stream.getvalue())\n header_global_stream.write(footer_global_stream.getvalue())\n generated_header = header_global_stream.getvalue()\n\n all_code = CodeIOStream()\n all_code.write(function_signature)\n all_code.write(header_stream.getvalue())\n all_code.write(callsite_stream.getvalue())\n all_code.write(footer_stream.getvalue())\n generated_code = all_code.getvalue()\n else:\n generated_header = global_stream.getvalue()\n generated_code = callsite_stream.getvalue()\n\n # Clean up generated code\n gotos = re.findall(r'goto (.*);', generated_code)\n clean_code = ''\n for line in generated_code.split('\\n'):\n # Empty line with semicolon\n if re.match(r'^\\s*;\\s*', line):\n continue\n # Label that might be unused\n label = re.findall(\n r'^\\s*([a-zA-Z_][a-zA-Z_0-9]*):\\s*[;]?\\s*////.*$', line)\n if len(label) > 0:\n if label[0] not in gotos:\n continue\n clean_code += line + '\\n'\n\n # Return the generated global and local code strings\n return (generated_header, clean_code, self._dispatcher.used_targets,\n self._dispatcher.used_environments)\n" ]
[ [ "numpy.random.rand", "numpy.zeros", "numpy.ndarray", "numpy.linalg.norm" ], [ "numpy.random.rand" ], [ "numpy.random.rand", "numpy.add", "numpy.linalg.norm", "numpy.multiply" ], [ "numpy.sort", "numpy.where", "numpy.linalg.norm", "numpy.float32" ], [ "numpy.nditer" ] ]
[ { "matplotlib": [], "numpy": [ "1.10", "1.12", "1.11", "1.19", "1.24", "1.13", "1.16", "1.9", "1.18", "1.23", "1.21", "1.22", "1.20", "1.7", "1.15", "1.14", "1.17", "1.8" ], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
artjoms-formulevics/portfolio-builder
[ "d9aa593d52594b795691f7893bd86740ff0eec84" ]
[ "portfolio-theory/updating_stock_prices.py" ]
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Dec 1 10:35:28 2020\n\n@author: afo\n\"\"\"\n\nfrom os import listdir\nfrom os.path import isfile, join, abspath\nimport os\nfrom inspect import getsourcefile\nimport pandas as pd\nfrom datetime import datetime, timedelta\nimport pandas_datareader as pdr\n\n# Function gathers latest ticker data for selected portfolios\ndef update_prices():\n \n p = abspath(getsourcefile(lambda:0))\n p = p.rsplit('/', 1)[0]\n os.chdir(p)\n print('Working Directory is: %s' % os.getcwd())\n \n file_path = p+ '/results_2015-2019/' # !!! Editable Folder with files with weights\n start_time = '2020-01-01' # !!! start date, editable\n end_time = (datetime.today() - timedelta(days=1)).strftime('%Y-%m-%d') # last day = day before today\n \n # Lists of files with portfolio weights\n files = [f for f in listdir(file_path) if isfile(join(file_path, f))]\n files = [f for f in files if f.startswith('portfolio_weights')]\n files = [file_path+f for f in files]\n \n totals = []\n \n for i in range(0, len(files)):\n \n portfolio = pd.read_csv(files[i], index_col=0).iloc[:,0:5]\n \n tickers = portfolio.iloc[:,1].tolist() # tickers inside portfolio (they will be updated)\n \n # Getting stock data (maybe re-do to for loop, if there be problems with memory)\n temp = pdr.DataReader(tickers, 'yahoo', start_time, end_time)['Close']\n \n weights = portfolio['shares_bought'].to_frame().T\n weights.columns = tickers\n \n temp = temp.mul(weights.values) # recalculate each ticker according to weight in portfolio\n temp['total'] = temp.sum(axis=1)\n \n \n # Getting the S&P500 (benchmark)\n data = pdr.DataReader('^GSPC', 'yahoo', start_time, end_time)['Close']\n data = data.rename('SP500')\n data = data.to_frame()\n \n data = data.join(temp)\n del temp\n \n \n # Rearrange cols\n cols = data.columns.tolist()\n cols = cols[-1:] + cols[:-1]\n data = data[cols]\n \n # Get paths & filenames for saving with replacing old csv files\n n = files[i].split('_')[-1]\n s = file_path + 'portfolio_ticker_' + n\n \n data.to_csv(s)\n \n # Create one total file with comparison of all of portfolios\n totals.append(data['total'].to_frame())\n totals[i] = totals[i].rename(columns={'total':'portfolio_'+n.split('.')[0]})\n \n \n total = pd.concat(totals, axis=1)\n \n total.to_excel(file_path+'resulting_portfolios.xlsx')\n \n \nupdate_prices()\n" ]
[ [ "pandas.concat", "pandas.read_csv" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] } ]
mundanePeo/faceRecognition
[ "f3340343a8448372e1031b16ba3c8928419bb9e6" ]
[ "App/exts/face_sdk/api_usage/face_feature.py" ]
[ "\"\"\"\r\n@author: mjs\r\n@based: JiXuan Xu, Jun Wang\r\n\"\"\"\r\n\r\nimport yaml\r\nimport cv2\r\nimport numpy as np\r\n\r\nfrom .logFile import logger\r\nfrom ..core.model_loader.face_recognition.FaceRecModelLoader import FaceRecModelLoader\r\nfrom ..core.model_handler.face_recognition.FaceRecModelHandler import FaceRecModelHandler\r\n\r\nwith open('config/model_conf.yaml') as f:\r\n model_conf = yaml.load(f)\r\n \r\nif __name__ == '__main__':\r\n # common setting for all model, need not modify.\r\n model_path = 'models'\r\n\r\n # model setting, modified along with model\r\n scene = 'non-mask'\r\n model_category = 'face_recognition'\r\n model_name = model_conf[scene][model_category]\r\n\r\n logger.info('Start to load the face recognition model...')\r\n # load model\r\n try:\r\n faceRecModelLoader = FaceRecModelLoader(model_path, model_category, model_name)\r\n except Exception as e:\r\n logger.error('Failed to parse model configuration file!')\r\n logger.error(e)\r\n sys.exit(-1)\r\n else:\r\n logger.info('Successfully parsed the model configuration file model_meta.json!')\r\n \r\n try:\r\n model, cfg = faceRecModelLoader.load_model()\r\n except Exception as e:\r\n logger.error('Model loading failed!')\r\n logger.error(e)\r\n sys.exit(-1)\r\n else:\r\n logger.info('Successfully loaded the face recognition model!')\r\n\r\n # read image\r\n image_path = 'api_usage/test_images/test1_cropped.jpg'\r\n image = cv2.imread(image_path)\r\n faceRecModelHandler = FaceRecModelHandler(model, 'cuda:0', cfg)\r\n\r\n try:\r\n feature = faceRecModelHandler.inference_on_image(image)\r\n except Exception as e:\r\n logger.error('Failed to extract facial features!')\r\n logger.error(e)\r\n sys.exit(-1)\r\n else:\r\n logger.info('Successfully extracted facial features!')\r\n\r\n np.save('api_usage/temp/test1_feature.npy', feature)\r\n" ]
[ [ "numpy.save" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
JackBenny39/mmabm
[ "e79d91232016167bff914495ee63e18063a1697b" ]
[ "tests/testLearningMM.py" ]
[ "import random\r\nimport unittest\r\n\r\nimport numpy as np\r\n\r\nfrom mmabm.shared import Side, OType\r\n\r\nfrom mmabm.learner import MarketMakerL\r\n\r\n\r\nclass TestTrader(unittest.TestCase):\r\n \r\n def setUp(self):\r\n self.l1 = self._makeMML(3001, 1)\r\n \r\n self.q1 = {'order_id': 1, 'timestamp': 1, 'type': OType.ADD, 'quantity': 1, 'side': Side.BID,\r\n 'price': 125}\r\n \r\n self.q1_buy = {'order_id': 1,'timestamp': 2, 'type': OType.ADD, 'quantity': 1, 'side': Side.BID,\r\n 'price': 50}\r\n self.q2_buy = {'order_id': 2, 'timestamp': 3, 'type': OType.ADD, 'quantity': 1, 'side': Side.BID,\r\n 'price': 50}\r\n self.q3_buy = {'order_id': 1, 'timestamp': 4, 'type': OType.ADD, 'quantity': 3, 'side': Side.BID,\r\n 'price': 49}\r\n self.q4_buy = {'order_id': 1, 'timestamp': 5, 'type': OType.ADD, 'quantity': 3, 'side': Side.BID,\r\n 'price': 47}\r\n self.q1_sell = {'order_id': 3, 'timestamp': 2, 'type': OType.ADD, 'quantity': 1, 'side': Side.ASK,\r\n 'price': 52}\r\n self.q2_sell = {'order_id': 4, 'timestamp': 3, 'type': OType.ADD, 'quantity': 1, 'side': Side.ASK,\r\n 'price': 52}\r\n self.q3_sell = {'order_id': 2, 'timestamp': 4, 'type': OType.ADD, 'quantity': 3, 'side': Side.ASK,\r\n 'price': 53}\r\n self.q4_sell = {'order_id': 2, 'timestamp': 5, 'type': OType.ADD, 'quantity': 3, 'side': Side.ASK,\r\n 'price': 55}\r\n \r\n def _makeMML(self, tid, arrInt):\r\n '''\r\n Two sets of market descriptors: arrival count and order imbalance (net signed order flow)\r\n arrival count: 16 bits, 8 for previous period and 8 for the previous 5 periods:\r\n previous period -> one bit each for > 0, 1, 2, 3, 4, 6, 8, 12\r\n previous 5 periods -> one bit each for > 0, 1, 2, 4, 8, 16, 32, 64\r\n order imbalance: 24 bits, 12 for previous period and 12 for previous 5 periods:\r\n previous period -> one bit each for < -8, -4, -3, -2, -1, 0 and > 0, 1, 2, 3, 4, 8\r\n previous 5 periods -> one bit each for < -16, -8, -6, -4, -2, 0 and > 0, 2, 4, 6, 8, 16\r\n \r\n The market maker has a set of predictors (condition/forecast rules) where the condition\r\n matches the market descriptors (i.e., the market state) and the forecasts are used as inputs\r\n to the market maker decision making.\r\n Each market condition is a bit string that coincides with market descriptors with the\r\n additional possibility of \"don't care\" (==2). \r\n Each market condition has an associated forecast\r\n arrival count: 5 bits -> 2^5 - 1 = 31 for a range of 0 - 31\r\n order imbalance: 6 bits -> lhs bit is +1/-1 and 2^5 - 1 = 31 for a range of -31 - +31\r\n \r\n Each market maker receives 100 genes for each of the two sets of market descriptors and\r\n 25 genes for the arrival forecast action rule.\r\n Examples:\r\n arrival count: 1111100011111100 -> >4 for previous period and >8 for previous 5 periods\r\n arrival count gene -> 2222102222221122: 01010 \r\n this gene matches on the \"do care\" (0 or 1) bits and has \"don't care\" for the remaining\r\n bits. It forecasts an arrival count of 10 (0*16 + 1*8 + 0*4 + 1*2 + 0*1).\r\n order imbalance: 011111000000011111000000 - < -4 for previous period and < -8 for previous\r\n 5 periods\r\n order imbalance gene: 222221022222222122222012: 010010\r\n this gene does not match the market state in position 23 and forecasts an order\r\n imbalance of +18 (+1*(1*16 + 0*8 + 0*4 + 1*2 + 0*1))\r\n \r\n The arrival count forecast acts as a condition/action rule where the condition matches the\r\n arrival count forecast and the action adjusts the bid and ask prices:\r\n arrival count forecast: 5 bits -> 2^5 - 1 = 31 for a range of 0 - 31\r\n action: 4 bits -> lhs bit is +1/-1 and 2^3 - 1 = 7 for a range of -7 - +7\r\n Example:\r\n arrival count forecast -> 01010\r\n arrival count gene -> 02210: 0010\r\n this gene matches the arrival count forecast and adjusts the bid (or ask) by (+1*(0*4 + 1*2 + 0*1) = +2.\r\n '''\r\n random.seed(39)\r\n np.random.seed(39)\r\n gene_n1 = 100\r\n gene_n2 = 25\r\n arr_cond_n = 16\r\n oi_cond_n = 24\r\n spr_cond_n = 5\r\n arr_fcst_n = 5\r\n oi_fcst_n = 6\r\n spr_adj_n = 4\r\n probs = [0.05, 0.05, 0.9]\r\n \r\n arr_genes = {'2' * arr_cond_n: '0' * arr_fcst_n}\r\n oi_genes = {'2' * oi_cond_n: '0' * oi_fcst_n}\r\n spread_genes = {'2' * spr_cond_n: '0' * spr_adj_n}\r\n genes = tuple([oi_genes, arr_genes, spread_genes])\r\n while len(arr_genes) < gene_n1:\r\n gk = ''.join(str(x) for x in np.random.choice(np.arange(0, 3), arr_cond_n, p=probs))\r\n gv = ''.join(str(x) for x in np.random.choice(np.arange(0, 2), arr_fcst_n))\r\n arr_genes.update({gk: gv})\r\n while len(oi_genes) < gene_n1:\r\n gk = ''.join(str(x) for x in np.random.choice(np.arange(0, 3), oi_cond_n, p=probs))\r\n gv = ''.join(str(x) for x in np.random.choice(np.arange(0, 2), oi_fcst_n))\r\n oi_genes.update({gk: gv})\r\n while len(spread_genes) < gene_n2:\r\n gk = ''.join(str(x) for x in np.random.choice(np.arange(0, 3), spr_cond_n, p=probs))\r\n gv = ''.join(str(x) for x in np.random.choice(np.arange(0, 2), spr_adj_n))\r\n spread_genes.update({gk: gv})\r\n maxq = 5\r\n a = b = 1\r\n c = -1\r\n keeper = 0.8\r\n mutate_pct = 0.03\r\n genetic_int = 250\r\n return MarketMakerL(tid, maxq, arrInt, a, b, c, genes, keeper, mutate_pct, genetic_int)\r\n \r\n ''' Strategy Construction Tests '''\r\n def test_make_oi_strat2(self):\r\n ''' The OI strat has 100 genes each with 24 bits; one strat is all 2 '''\r\n self.assertEqual(self.l1._oi_len, 24)\r\n self.assertEqual(len(self.l1._oi_strat), 100)\r\n self.assertTrue('2' * 24 in self.l1._oi_strat.keys())\r\n #print(self.l1._oi_strat, self.l1._oi_len, len(self.l1._arr_strat))\r\n \r\n def test_make_arr_strat2(self):\r\n ''' The arr strat has 100 genes each with 16 bits; one strat is all 2 '''\r\n self.assertEqual(self.l1._arr_len, 16)\r\n self.assertEqual(len(self.l1._arr_strat), 100)\r\n self.assertTrue('2' * 16 in self.l1._arr_strat.keys())\r\n #print(self.l1._arr_strat, self.l1._arr_len, len(self.l1._oi_strat))\r\n \r\n def test_make_spread_strat2(self):\r\n ''' The Spread Adj strat has 25 genes each with 5 bits; one strat is all 2 '''\r\n self.assertEqual(self.l1._spr_len, 5)\r\n self.assertEqual(len(self.l1._spradj_strat), 25)\r\n self.assertTrue('2' * 5 in self.l1._spradj_strat.keys())\r\n #print(self.l1._spradj_strat, self.l1._spr_len, len(self.l1._spradj_strat))\r\n \r\n @unittest.skip('Takes too long to run every time')\r\n def test_make_oi_strat(self):\r\n ''' Test for proper conversion from bitstring to integer '''\r\n for i in self.l1._oi_strat.keys():\r\n with self.subTest(i=i):\r\n self.assertEqual(int(self.l1._oi_strat[i]['action'][1:], 2), abs(self.l1._oi_strat[i]['strategy']))\r\n if self.l1._oi_strat[i]['strategy'] != 0:\r\n self.assertEqual(int(self.l1._oi_strat[i]['action'][0]), self.l1._oi_strat[i]['strategy']>0)\r\n self.assertEqual(self.l1._oi_strat[i]['accuracy'], [0, 0, 1000])\r\n \r\n @unittest.skip('Takes too long to run every time') \r\n def test_make_arr_strat(self):\r\n ''' Test for proper conversion from bitstring to integer '''\r\n for i in self.l1._arr_strat.keys():\r\n with self.subTest(i=i):\r\n self.assertEqual(int(self.l1._arr_strat[i]['action'], 2), self.l1._arr_strat[i]['strategy'])\r\n self.assertEqual(self.l1._arr_strat[i]['accuracy'], [0, 0, 1000])\r\n \r\n @unittest.skip('Takes too long to run every time') \r\n def test_make_spread_strat(self):\r\n ''' Test for proper conversion from bitstring to integer '''\r\n # spread strategy\r\n for i in self.l1._spradj_strat.keys():\r\n with self.subTest(i=i):\r\n self.assertEqual(int(self.l1._spradj_strat[i]['action'][1:], 2), abs(self.l1._spradj_strat[i]['strategy']))\r\n if self.l1._spradj_strat[i]['strategy'] != 0:\r\n self.assertEqual(int(self.l1._spradj_strat[i]['action'][0]), self.l1._spradj_strat[i]['strategy']>0)\r\n self.assertEqual(self.l1._spradj_strat[i]['rr_spread'], [0, 0, 0])\r\n \r\n ''' Strategy Matching Tests '''\r\n def test_match_oi_strat2(self):\r\n ''' With seeds == 39, '221212222222222222020222' is the sole winning strategy with a max strength == 4 '''\r\n #oi_state is 24 bits\r\n signal = '011111000000011111000000'\r\n self.l1._match_oi_strat2(signal)\r\n self.assertEqual(self.l1._current_oi_strat, '221212222222222222020222')\r\n self.assertTrue(all([(self.l1._current_oi_strat[x] == signal[x] or self.l1._current_oi_strat[x] == '2') for x in range(self.l1._oi_len)]))\r\n self.assertEqual(sum([self.l1._current_oi_strat[x] == signal[x] for x in range(self.l1._oi_len)]), 4)\r\n # Another winner with strength == 4 could be '212212222222222222020222'\r\n self.l1._oi_strat['212212222222222222020222'] = {'action': 'xxxxx', 'strategy': 999, 'accuracy': [0, 0, 1000]}\r\n # Set '221212222222222222020222' accuracy to less than new strat accuracy\r\n self.l1._oi_strat['221212222222222222020222']['accuracy'][-1] = 999\r\n self.l1._match_oi_strat2(signal)\r\n self.assertEqual(self.l1._current_oi_strat, '212212222222222222020222')\r\n self.assertTrue(all([(self.l1._current_oi_strat[x] == signal[x] or self.l1._current_oi_strat[x] == '2') for x in range(self.l1._oi_len)]))\r\n self.assertEqual(sum([self.l1._current_oi_strat[x] == signal[x] for x in range(self.l1._oi_len)]), 4)\r\n # If they had the same strength and accuracy, only one would be returned\r\n self.l1._oi_strat['221212222222222222020222']['accuracy'][-1] = 1000\r\n self.l1._match_oi_strat2(signal)\r\n self.assertEqual('221212222222222222020222', self.l1._current_oi_strat)\r\n\r\n def test_match_arr_strat2(self):\r\n ''' With seeds == 39, '1222102221222222' is the winning strategy with a max strength == 4 '''\r\n signal = '1111100011111100'\r\n self.l1._match_arr_strat2(signal)\r\n self.assertEqual(self.l1._current_arr_strat, '1222102221222222')\r\n self.assertTrue(all([(self.l1._current_arr_strat[x] == signal[x] or self.l1._current_arr_strat[x] == '2') for x in range(self.l1._arr_len)]))\r\n self.assertEqual(sum([self.l1._current_arr_strat[x] == signal[x] for x in range(self.l1._arr_len)]), 4)\r\n # Another winner with strength == 4 could be '2122102221222222'\r\n self.l1._arr_strat['2122102221222222'] = {'action': 'xxxxx', 'strategy': 999, 'accuracy': [0, 0, 1000]}\r\n # Set '1222102221222222' accuracy to less than new strat accuracy\r\n self.l1._arr_strat['1222102221222222']['accuracy'][-1] = 999\r\n self.l1._match_arr_strat2(signal)\r\n self.assertEqual(self.l1._current_arr_strat, '2122102221222222')\r\n self.assertTrue(all([(self.l1._current_arr_strat[x] == signal[x] or self.l1._current_arr_strat[x] == '2') for x in range(self.l1._arr_len)]))\r\n self.assertEqual(sum([self.l1._current_arr_strat[x] == signal[x] for x in range(self.l1._arr_len)]), 4)\r\n # If they had the same strength and accuracy, only one would be returned\r\n self.l1._arr_strat['1222102221222222']['accuracy'][-1] = 1000\r\n self.l1._match_arr_strat2(signal)\r\n self.assertEqual('1222102221222222', self.l1._current_arr_strat)\r\n\r\n def test_match_spread_strat(self):\r\n ''' With seeds == 39, ['21220', '22020', '02022', '21212', '22210', '02212'] are the winning strategies with a max strength == 2 '''\r\n signal = '01010'\r\n self.l1._match_spread_strat(signal)\r\n for j in ['21220', '22020', '02022', '21212', '22210', '02212']:\r\n self.assertTrue(j in self.l1._current_spradj_strat)\r\n for i in self.l1._current_spradj_strat:\r\n with self.subTest(i=i):\r\n self.assertTrue(all([(i[x] == signal[x] or i[x] == '2') for x in range(self.l1._spr_len)]))\r\n self.assertEqual(sum([i[x] == signal[x] for x in range(self.l1._spr_len)]), 2)\r\n # Winner '01222' - set rr_spread higher\r\n self.l1._spradj_strat['01222'] = {'action': 'xxxxx', 'strategy': 999, 'rr_spread': [0, 0, 1]}\r\n self.l1._match_spread_strat(signal)\r\n self.assertEqual(len(self.l1._current_spradj_strat), 1)\r\n self.assertEqual(self.l1._current_spradj_strat[0], '01222')\r\n self.assertTrue(all([(self.l1._current_spradj_strat[0][x] == signal[x] or self.l1._current_spradj_strat[0][x] == '2') for x in range(self.l1._spr_len)]))\r\n self.assertEqual(sum([self.l1._current_spradj_strat[0][x] == signal[x] for x in range(self.l1._spr_len)]), 2)\r\n \r\n ''' Accuracy/Profitability Update Tests '''\r\n def test_update_oi_acc(self):\r\n self.l1._oi_strat['221212222222222222020222']['accuracy'][0] = 10\r\n self.l1._oi_strat['221212222222222222020222']['accuracy'][1] = 10\r\n self.l1._oi_strat['221212222222222222020222']['accuracy'][-1] = 1000\r\n self.l1._oi_strat['221212222222222222020222']['strategy'] = 4\r\n self.l1._current_oi_strat = '221212222222222222020222'\r\n actual = 6\r\n self.l1._update_oi_acc(actual)\r\n self.assertListEqual(self.l1._oi_strat['221212222222222222020222']['accuracy'], [12, 11, 1000 - 12/11])\r\n\r\n def test_update_arr_acc(self):\r\n self.l1._arr_strat['1222102221222222']['accuracy'][0] = 10\r\n self.l1._arr_strat['1222102221222222']['accuracy'][1] = 10\r\n self.l1._arr_strat['1222102221222222']['accuracy'][-1] = 1000\r\n self.l1._arr_strat['1222102221222222']['strategy'] = 4\r\n self.l1._current_arr_strat = '1222102221222222'\r\n actual = 6\r\n self.l1._update_arr_acc(actual)\r\n self.assertListEqual(self.l1._arr_strat['1222102221222222']['accuracy'], [12, 11, 1000 - 12/11])\r\n\r\n def test_update_rspr(self):\r\n self.l1._spradj_strat['21220']['rr_spread'][0] = 10000\r\n self.l1._spradj_strat['21220']['rr_spread'][1] = 1000\r\n self.l1._spradj_strat['21220']['rr_spread'][-1] = 10\r\n self.l1._current_spradj_strat = ['21220']\r\n mid = 1000\r\n self.l1._last_buy_prices = [998, 999]\r\n self.l1._last_sell_prices = [1001, 1002]\r\n self.l1._update_rspr(mid)\r\n self.assertListEqual(self.l1._spradj_strat['21220']['rr_spread'], [10006, 1004, 10006/1004])\r\n \r\n ''' Order Construction Tests ''' \r\n def test_make_add_quote(self):\r\n ''' Takes 4 inputs, increments the quote sequence and generates a dict '''\r\n time = 1\r\n side = Side.ASK\r\n price = 125\r\n quantity = 5\r\n self.assertFalse(self.l1._quote_sequence)\r\n expected = {'order_id': 1, 'trader_id': self.l1.trader_id, 'timestamp': 1, 'type': OType.ADD, \r\n 'quantity': quantity, 'side': Side.ASK, 'price': 125}\r\n self.assertDictEqual(self.l1._make_add_quote(time, side, price, quantity), expected)\r\n \r\n def test_make_cancel_quote(self):\r\n ''' Takes a quote and current timestamp, resets the timestamp to current,\r\n and updates type to CANCEL '''\r\n self.q1['trader_id'] = self.l1.trader_id\r\n expected = {'order_id': 1, 'trader_id': self.l1.trader_id, 'timestamp': 2, 'type': OType.CANCEL, \r\n 'quantity': 1, 'side': Side.BID, 'price': 125}\r\n self.assertDictEqual(self.l1._make_cancel_quote(self.q1, 2), expected)\r\n \r\n ''' Orderbook Bookkeeping Tests'''\r\n\r\n def test_add_order(self):\r\n '''\r\n add_order_to_book() impacts _bid_book and _bid_book_prices or _ask_book and _ask_book_prices\r\n Add two buy orders, then two sell orders\r\n '''\r\n # 2 buy orders\r\n self.assertFalse(self.l1._bid_book_prices)\r\n self.assertFalse(self.l1._bid_book)\r\n self.l1._add_order(self.q1_buy)\r\n self.assertTrue(50 in self.l1._bid_book_prices)\r\n self.assertTrue(50 in self.l1._bid_book.keys())\r\n self.assertEqual(self.l1._bid_book[50]['num_orders'], 1)\r\n self.assertEqual(self.l1._bid_book[50]['size'], 1)\r\n self.assertEqual(self.l1._bid_book[50]['order_ids'][0], 1)\r\n del self.q1_buy['type']\r\n self.assertDictEqual(self.l1._bid_book[50]['orders'][1], self.q1_buy)\r\n self.l1._add_order(self.q2_buy)\r\n self.assertEqual(self.l1._bid_book[50]['num_orders'], 2)\r\n self.assertEqual(self.l1._bid_book[50]['size'], 2)\r\n self.assertEqual(self.l1._bid_book[50]['order_ids'][1], 2)\r\n del self.q2_buy['type']\r\n self.assertDictEqual(self.l1._bid_book[50]['orders'][2], self.q2_buy)\r\n # 2 sell orders\r\n self.assertFalse(self.l1._ask_book_prices)\r\n self.assertFalse(self.l1._ask_book)\r\n self.l1._add_order(self.q1_sell)\r\n self.assertTrue(52 in self.l1._ask_book_prices)\r\n self.assertTrue(52 in self.l1._ask_book.keys())\r\n self.assertEqual(self.l1._ask_book[52]['num_orders'], 1)\r\n self.assertEqual(self.l1._ask_book[52]['size'], 1)\r\n self.assertEqual(self.l1._ask_book[52]['order_ids'][0], 3)\r\n del self.q1_sell['type']\r\n self.assertDictEqual(self.l1._ask_book[52]['orders'][3], self.q1_sell)\r\n self.l1._add_order(self.q2_sell)\r\n self.assertEqual(self.l1._ask_book[52]['num_orders'], 2)\r\n self.assertEqual(self.l1._ask_book[52]['size'], 2)\r\n self.assertEqual(self.l1._ask_book[52]['order_ids'][1], 4)\r\n del self.q2_sell['type']\r\n self.assertDictEqual(self.l1._ask_book[52]['orders'][4], self.q2_sell)\r\n\r\n def test_remove_order(self):\r\n '''\r\n _remove_order() impacts _bid_book and _bid_book_prices or _ask_book and _ask_book_prices\r\n Add two orders, remove the second order twice\r\n '''\r\n # buy orders\r\n self.l1._add_order(self.q1_buy)\r\n self.l1._add_order(self.q2_buy)\r\n self.assertTrue(50 in self.l1._bid_book_prices)\r\n self.assertTrue(50 in self.l1._bid_book.keys())\r\n self.assertEqual(self.l1._bid_book[50]['num_orders'], 2)\r\n self.assertEqual(self.l1._bid_book[50]['size'], 2)\r\n self.assertEqual(len(self.l1._bid_book[50]['order_ids']), 2)\r\n # remove first order\r\n self.l1._remove_order(Side.BID, 50, 1)\r\n self.assertEqual(self.l1._bid_book[50]['num_orders'], 1)\r\n self.assertEqual(self.l1._bid_book[50]['size'], 1)\r\n self.assertEqual(len(self.l1._bid_book[50]['order_ids']), 1)\r\n self.assertFalse(1 in self.l1._bid_book[50]['orders'].keys())\r\n self.assertTrue(50 in self.l1._bid_book_prices)\r\n # remove second order\r\n self.l1._remove_order(Side.BID, 50, 2)\r\n self.assertFalse(self.l1._bid_book_prices)\r\n self.assertEqual(self.l1._bid_book[50]['num_orders'], 0)\r\n self.assertEqual(self.l1._bid_book[50]['size'], 0)\r\n self.assertEqual(len(self.l1._bid_book[50]['order_ids']), 0)\r\n self.assertFalse(2 in self.l1._bid_book[50]['orders'].keys())\r\n self.assertFalse(50 in self.l1._bid_book_prices)\r\n # remove second order again\r\n self.l1._remove_order(Side.BID, 50, 2)\r\n self.assertFalse(self.l1._bid_book_prices)\r\n self.assertEqual(self.l1._bid_book[50]['num_orders'], 0)\r\n self.assertEqual(self.l1._bid_book[50]['size'], 0)\r\n self.assertEqual(len(self.l1._bid_book[50]['order_ids']), 0)\r\n self.assertFalse(2 in self.l1._bid_book[50]['orders'].keys())\r\n # sell orders\r\n self.l1._add_order(self.q1_sell)\r\n self.l1._add_order(self.q2_sell)\r\n self.assertTrue(52 in self.l1._ask_book_prices)\r\n self.assertTrue(52 in self.l1._ask_book.keys())\r\n self.assertEqual(self.l1._ask_book[52]['num_orders'], 2)\r\n self.assertEqual(self.l1._ask_book[52]['size'], 2)\r\n self.assertEqual(len(self.l1._ask_book[52]['order_ids']), 2)\r\n # remove first order\r\n self.l1._remove_order(Side.ASK, 52, 3)\r\n self.assertEqual(self.l1._ask_book[52]['num_orders'], 1)\r\n self.assertEqual(self.l1._ask_book[52]['size'], 1)\r\n self.assertEqual(len(self.l1._ask_book[52]['order_ids']), 1)\r\n self.assertFalse(3 in self.l1._ask_book[52]['orders'].keys())\r\n self.assertTrue(52 in self.l1._ask_book_prices)\r\n # remove second order\r\n self.l1._remove_order(Side.ASK, 52, 4)\r\n self.assertFalse(self.l1._ask_book_prices)\r\n self.assertEqual(self.l1._ask_book[52]['num_orders'], 0)\r\n self.assertEqual(self.l1._ask_book[52]['size'], 0)\r\n self.assertEqual(len(self.l1._ask_book[52]['order_ids']), 0)\r\n self.assertFalse(4 in self.l1._ask_book[52]['orders'].keys())\r\n self.assertFalse(52 in self.l1._ask_book_prices)\r\n # remove second order again\r\n self.l1._remove_order(Side.ASK, 52, 4)\r\n self.assertFalse(self.l1._ask_book_prices)\r\n self.assertEqual(self.l1._ask_book[52]['num_orders'], 0)\r\n self.assertEqual(self.l1._ask_book[52]['size'], 0)\r\n self.assertEqual(len(self.l1._ask_book[52]['order_ids']), 0)\r\n self.assertFalse(4 in self.l1._ask_book[52]['orders'].keys())\r\n\r\n def test_modify_order(self):\r\n '''\r\n _modify_order() primarily impacts _bid_book or _ask_book \r\n _modify_order() could impact _bid_book_prices or _ask_book_prices if the order results \r\n in removing the full quantity with a call to _remove_order() \r\n Add 1 order, remove partial, then remainder\r\n '''\r\n # Buy order\r\n q1 = {'order_id': 1, 'timestamp': 5, 'type': OType.ADD, 'quantity': 2, 'side': Side.BID, 'price': 50}\r\n self.l1._add_order(q1)\r\n self.assertEqual(self.l1._bid_book[50]['size'], 2)\r\n # remove 1\r\n self.l1._modify_order(Side.BID, 1, 1, 50)\r\n self.assertEqual(self.l1._bid_book[50]['size'], 1)\r\n self.assertEqual(self.l1._bid_book[50]['orders'][1]['quantity'], 1)\r\n self.assertTrue(self.l1._bid_book_prices)\r\n # remove remainder\r\n self.l1._modify_order(Side.BID, 1, 1, 50)\r\n self.assertFalse(self.l1._bid_book_prices)\r\n self.assertEqual(self.l1._bid_book[50]['num_orders'], 0)\r\n self.assertEqual(self.l1._bid_book[50]['size'], 0)\r\n self.assertFalse(1 in self.l1._bid_book[50]['orders'].keys())\r\n # Sell order\r\n q2 = {'order_id': 2, 'timestamp': 5, 'type': OType.ADD, 'quantity': 2, 'side': Side.ASK, 'price': 50}\r\n self.l1._add_order(q2)\r\n self.assertEqual(self.l1._ask_book[50]['size'], 2)\r\n # remove 1\r\n self.l1._modify_order(Side.ASK, 1, 2, 50)\r\n self.assertEqual(self.l1._ask_book[50]['size'], 1)\r\n self.assertEqual(self.l1._ask_book[50]['orders'][2]['quantity'], 1)\r\n self.assertTrue(self.l1._ask_book_prices)\r\n # remove remainder\r\n self.l1._modify_order(Side.ASK, 1, 2, 50)\r\n self.assertFalse(self.l1._ask_book_prices)\r\n self.assertEqual(self.l1._ask_book[50]['num_orders'], 0)\r\n self.assertEqual(self.l1._ask_book[50]['size'], 0)\r\n self.assertFalse(2 in self.l1._ask_book[50]['orders'].keys())\r\n \r\n ''' Trade Handling Tests '''\r\n def test_confirm_trade_local(self):\r\n # _cash_flow and _delta_inv start at 0, _last_buy_prices and last_sell_prices are empty\r\n self.assertFalse(self.l1._last_buy_prices)\r\n self.assertFalse(self.l1._last_sell_prices)\r\n self.assertEqual(self.l1._cash_flow, 0)\r\n self.assertEqual(self.l1._delta_inv, 0)\r\n # add some orders\r\n q1 = {'order_id': 1, 'timestamp': 5, 'type': OType.ADD, 'quantity': 5, 'side': Side.BID, 'price': 995}\r\n q2 = {'order_id': 2, 'timestamp': 5, 'type': OType.ADD, 'quantity': 5, 'side': Side.ASK, 'price': 1005}\r\n self.l1._add_order(q1)\r\n self.l1._add_order(q2)\r\n # Market maker buys\r\n confirm1 = {'timestamp': 20, 'trader': 3001, 'order_id': 1, 'quantity': 1, 'side': Side.BID, 'price': 995}\r\n self.l1.confirm_trade_local(confirm1)\r\n self.assertListEqual(self.l1._last_buy_prices, [995])\r\n self.assertEqual(self.l1._cash_flow, -995/100000)\r\n self.assertEqual(self.l1._delta_inv, 1)\r\n self.assertEqual(self.l1._bid_book[995]['num_orders'], 1)\r\n self.assertEqual(self.l1._bid_book[995]['size'], 4)\r\n confirm2 = {'timestamp': 22, 'trader': 3001, 'order_id': 1, 'quantity': 4, 'side': Side.BID, 'price': 995}\r\n self.l1.confirm_trade_local(confirm2)\r\n self.assertListEqual(self.l1._last_buy_prices, [995, 995])\r\n self.assertEqual(self.l1._cash_flow, -4975/100000)\r\n self.assertEqual(self.l1._delta_inv, 5)\r\n self.assertFalse(self.l1._bid_book_prices)\r\n # Market maker sells\r\n confirm3 = {'timestamp': 20, 'trader': 3001, 'order_id': 2, 'quantity': 1, 'side': Side.ASK, 'price': 1005}\r\n self.l1.confirm_trade_local(confirm3)\r\n self.assertListEqual(self.l1._last_sell_prices, [1005])\r\n self.assertEqual(self.l1._cash_flow, -3970/100000)\r\n self.assertEqual(self.l1._delta_inv, 4)\r\n self.assertEqual(self.l1._ask_book[1005]['num_orders'], 1)\r\n self.assertEqual(self.l1._ask_book[1005]['size'], 4)\r\n confirm4 = {'timestamp': 22, 'trader': 3001, 'order_id': 2, 'quantity': 4, 'side': Side.ASK, 'price': 1005}\r\n self.l1.confirm_trade_local(confirm4)\r\n self.assertListEqual(self.l1._last_sell_prices, [1005, 1005])\r\n self.assertAlmostEqual(self.l1._cash_flow, 50/100000, 4)\r\n self.assertEqual(self.l1._delta_inv, 0)\r\n self.assertFalse(self.l1._ask_book_prices)\r\n\r\n ''' Orderbook Update Tests ''' \r\n def test_update_midpoint(self):\r\n ''' With seeds == 39, '221212222222222222020222' is the sole winning strategy with a max strength == 4 -> action == -3 '''\r\n self.l1._mid = 990\r\n self.l1._delta_inv = 3\r\n #oi_state is 24 bits\r\n oib_signal = '011111000000011111000000'\r\n mid_signal = 1000\r\n self.l1._update_midpoint(oib_signal, mid_signal)\r\n # new mid = mid_signal - 3 + (-1*3)\r\n self.assertEqual(self.l1._mid, 994)\r\n\r\n def test_make_spread(self):\r\n ''' With seeds == 39, '1222102221222222' is the winning arr strategy with a max strength == 4 -> action == '01000' (8)\r\n _match_spread_strat('01000') returns ['21220', '22020', '02022'] with an actions of ['0000', '1100', '1111'] -> \r\n strategy == [0, 4, 7] for an average of 3.67\r\n '''\r\n self.assertFalse(self.l1._ask)\r\n self.assertFalse(self.l1._bid)\r\n self.l1._mid = 1000\r\n arr_signal = '1222102221222222'\r\n vol = 4\r\n self.l1._make_spread(arr_signal, vol)\r\n # spradj = 3.67\r\n # ask = 1000 + round(max(1*4, 1) + 3.67/2) = 1006\r\n # bid = 1000 - round(max(1*4, 1) + 3.67/2) = 994\r\n self.assertEqual(self.l1._bid, 994)\r\n self.assertEqual(self.l1._ask, 1006)\r\n \r\n def test_process_cancels(self):\r\n ''' If desired ask > current best ask, cancel current ask orders with prices < new best ask '''\r\n # Create asks from 1005 - 1035\r\n for p in range(1005, 1036):\r\n self.l1._add_order(self.l1._make_add_quote(35, Side.ASK, p, self.l1._maxq))\r\n for p in range(1005, 1036):\r\n with self.subTest(p=p):\r\n self.assertTrue(p in self.l1._ask_book_prices)\r\n # Create bids from 960 - 990\r\n for p in range(960, 991):\r\n self.l1._add_order(self.l1._make_add_quote(35, Side.BID, p, self.l1._maxq))\r\n for p in range(960, 991):\r\n with self.subTest(p=p):\r\n self.assertTrue(p in self.l1._bid_book_prices)\r\n # case 1a: new ask = 1000, new bid = 995 -> no new cancels\r\n self.l1._ask = 1000\r\n self.l1._bid = 995\r\n self.l1._process_cancels(6)\r\n self.assertFalse(self.l1.cancel_collector)\r\n # case 2a: new ask = 1008 -> cancel 3 prices: 1005, 1006, 1007\r\n self.l1._ask = 1008\r\n self.l1._bid = 995\r\n self.l1._process_cancels(7)\r\n for p in range(1008, 1036):\r\n with self.subTest(p=p):\r\n self.assertTrue(p in self.l1._ask_book_prices)\r\n for p in range(1005, 1008):\r\n with self.subTest(p=p):\r\n self.assertFalse(p in self.l1._ask_book_prices)\r\n self.assertEqual(len(self.l1.cancel_collector), 3)\r\n # case 2b: new bid = 987 -> cancel 988, 989, 990\r\n self.l1._ask = 1000\r\n self.l1._bid = 987\r\n self.l1._process_cancels(8)\r\n for p in range(960, 988):\r\n with self.subTest(p=p):\r\n self.assertTrue(p in self.l1._bid_book_prices)\r\n for p in range(988, 991):\r\n with self.subTest(p=p):\r\n self.assertFalse(p in self.l1._bid_book_prices)\r\n self.assertEqual(len(self.l1.cancel_collector), 3)\r\n\r\n ''' Several cases:\r\n 1. _ask > prevailing worst ask (ask book empty due to canceling first)\r\n 2. _ask > prevailing best bid: add new ask orders from _ask and up\r\n 3. _ask <= prevailing best bid: add new ask orders from prevailing best bid+1 and up\r\n 4. _ask == current best ask: check for max size and add size if necessary\r\n Also, price range should always be between best ask + 20 and best ask + 60\r\n '''\r\n def test_update_ask_book1(self):\r\n ''' 1. _ask > prevailing worst ask (ask book empty due to canceling first) '''\r\n self.assertFalse(self.l1._ask_book_prices)\r\n self.l1._ask = 1000\r\n tob_bid = 995\r\n self.l1._update_ask_book(6, tob_bid)\r\n # case 1: Add orders from 1000 -> 1039\r\n for p in range(1000, 1040):\r\n with self.subTest(p=p):\r\n self.assertTrue(p in self.l1._ask_book_prices)\r\n self.assertEqual(len(self.l1.quote_collector), 40)\r\n\r\n def test_update_ask_book2(self):\r\n ''' 2. _ask > prevailing best bid: add new ask orders from _ask and up '''\r\n # Create asks from 1005 - 1035\r\n for p in range(1005, 1036):\r\n self.l1._add_order(self.l1._make_add_quote(35, Side.ASK, p, self.l1._maxq))\r\n for p in range(1005, 1036):\r\n with self.subTest(p=p):\r\n self.assertTrue(p in self.l1._ask_book_prices)\r\n # case 2: _ask = 1000, best_bid = 995 -> add 5 new prices: 1000 - 1004\r\n self.l1._ask = 1000\r\n tob_bid = 995\r\n self.l1._update_ask_book(6, tob_bid)\r\n for p in range(1000, 1036):\r\n with self.subTest(p=p):\r\n self.assertTrue(p in self.l1._ask_book_prices)\r\n self.assertEqual(len(self.l1.quote_collector), 5)\r\n \r\n def test_update_ask_book3(self):\r\n ''' 3. _ask <= prevailing best bid: add new ask orders from prevailing best bid+1 and up '''\r\n for p in range(1000, 1036):\r\n self.l1._add_order(self.l1._make_add_quote(35, Side.ASK, p, self.l1._maxq))\r\n for p in range(1000, 1036):\r\n with self.subTest(p=p):\r\n self.assertTrue(p in self.l1._ask_book_prices)\r\n # case 3: _ask = 990 but best_bid = 995 -> add 4 new prices: 996 - 999\r\n self.l1._ask = 990\r\n tob_bid = 995\r\n self.l1._update_ask_book(7, tob_bid)\r\n for p in range(996, 1036):\r\n with self.subTest(p=p):\r\n self.assertTrue(p in self.l1._ask_book_prices)\r\n for p in range(990, 996):\r\n with self.subTest(p=p):\r\n self.assertFalse(p in self.l1._ask_book_prices)\r\n self.assertEqual(len(self.l1.quote_collector), 4)\r\n \r\n def test_update_ask_book4(self):\r\n ''' 4. _ask == current best ask: check for max size and add size if necessary '''\r\n for p in range(996, 1036):\r\n self.l1._add_order(self.l1._make_add_quote(35, Side.ASK, p, self.l1._maxq))\r\n for p in range(996, 1036):\r\n with self.subTest(p=p):\r\n self.assertTrue(p in self.l1._ask_book_prices)\r\n # case 4: new ask size == 2 -> replenish size to 5 with new add order\r\n self.l1._ask = 996\r\n tob_bid = 990\r\n self.l1._modify_order(Side.ASK, 3, 1, 996)\r\n self.assertEqual(self.l1._ask_book[996]['orders'][1]['quantity'], 2)\r\n self.assertEqual(self.l1._ask_book[996]['size'], 2)\r\n self.assertEqual(self.l1._ask_book[996]['num_orders'], 1)\r\n self.l1.quote_collector.clear() # happens in process_order\r\n self.l1._update_ask_book(8, tob_bid)\r\n self.assertEqual(self.l1._ask_book[996]['size'], 5)\r\n self.assertEqual(self.l1._ask_book[996]['num_orders'], 2)\r\n self.assertEqual(len(self.l1.quote_collector), 1)\r\n \r\n def test_update_ask_book5(self):\r\n ''' Also, price range should always be between best ask + 20 and best ask + 60 '''\r\n # make best ask == 1020 -> add orders to the other end of the book to make 40 prices\r\n for p in range(1020, 1036):\r\n self.l1._add_order(self.l1._make_add_quote(35, Side.ASK, p, self.l1._maxq))\r\n for p in range(1020, 1036):\r\n with self.subTest(p=p):\r\n self.assertTrue(p in self.l1._ask_book_prices)\r\n tob_bid = 990\r\n self.l1._ask = 1020\r\n self.l1._update_ask_book(10, tob_bid)\r\n for p in range(1020, 1059):\r\n with self.subTest(p=p):\r\n self.assertTrue(p in self.l1._ask_book_prices)\r\n # make best ask == 980 -> cancel orders on the other end of the book to make 40 prices\r\n self.l1._bid = 975\r\n self.l1._ask = 980\r\n tob_bid = 975\r\n self.l1._update_ask_book(10, tob_bid)\r\n for p in range(980, 1019):\r\n with self.subTest(p=p):\r\n self.assertTrue(p in self.l1._ask_book_prices)\r\n for p in range(1020, 1059):\r\n with self.subTest(p=p):\r\n self.assertFalse(p in self.l1._ask_book_prices)\r\n \r\n ''' Several cases:\r\n 1. _bid < prevailing worst bid (bid book empty due to canceling first)\r\n 2. _bid < prevailing best ask: add new bid orders from _bid and down\r\n 3. _bid >= prevailing best ask: add new bid orders from prevailing best ask-1 and down\r\n 4. _bid == current best bid: check for max size and add size if necessary\r\n Also, price range should always be between best bid - 20 and best bid - 60\r\n '''\r\n def test_update_bid_book1(self):\r\n ''' 1. _bid < prevailing worst bid (bid book empty due to canceling first) '''\r\n self.assertFalse(self.l1._bid_book_prices)\r\n self.l1._bid = 995\r\n tob_ask = 1000\r\n self.l1._update_bid_book(6, tob_ask)\r\n # case 1: Add orders from 956 -> 995\r\n for p in range(956, 996):\r\n with self.subTest(p=p):\r\n self.assertTrue(p in self.l1._bid_book_prices)\r\n self.assertEqual(len(self.l1.quote_collector), 40)\r\n\r\n def test_update_bid_book2(self):\r\n ''' 2. _bid < prevailing best ask: add new bid orders from _bid and down '''\r\n # Create bids from 960 - 990\r\n for p in range(960, 991):\r\n self.l1._add_order(self.l1._make_add_quote(35, Side.BID, p, self.l1._maxq))\r\n for p in range(960, 991):\r\n with self.subTest(p=p):\r\n self.assertTrue(p in self.l1._bid_book_prices)\r\n # case 2: _bid = 995, best_ask = 1000 -> add 5 new prices: 991 - 995\r\n self.l1._bid = 995\r\n tob_ask = 1000\r\n self.l1._update_bid_book(6, tob_ask)\r\n for p in range(960, 996):\r\n with self.subTest(p=p):\r\n self.assertTrue(p in self.l1._bid_book_prices)\r\n self.assertEqual(len(self.l1.quote_collector), 5)\r\n \r\n def test_update_bid_book3(self):\r\n ''' _bid >= prevailing best ask: add new bid orders from prevailing best ask-1 and down '''\r\n # Create bids from 960 - 995\r\n for p in range(960, 996):\r\n self.l1._add_order(self.l1._make_add_quote(35, Side.BID, p, self.l1._maxq))\r\n for p in range(960, 996):\r\n with self.subTest(p=p):\r\n self.assertTrue(p in self.l1._bid_book_prices)\r\n # case 2: _bid = 1000, but tob_ask = 988 -> add 2 prices: 996, 997\r\n self.l1._bid = 1000\r\n tob_ask = 998\r\n self.l1._update_bid_book(7, tob_ask)\r\n for p in range(960, 998):\r\n with self.subTest(p=p):\r\n self.assertTrue(p in self.l1._bid_book_prices)\r\n for p in range(998, 1000):\r\n with self.subTest(p=p):\r\n self.assertFalse(p in self.l1._bid_book_prices)\r\n self.assertEqual(len(self.l1.quote_collector), 2)\r\n \r\n def test_update_bid_book4(self):\r\n ''' 4. _bid == current best bid: check for max size and add size if necessary '''\r\n # case 4: new bid size == 2 -> replenish size to 5 with new add order\r\n # Create bids from 960 - 995\r\n for p in range(960, 996):\r\n self.l1._add_order(self.l1._make_add_quote(35, Side.BID, p, self.l1._maxq))\r\n for p in range(960, 996):\r\n with self.subTest(p=p):\r\n self.assertTrue(p in self.l1._bid_book_prices)\r\n self.l1._bid = 995\r\n tob_ask = 1000\r\n self.l1._modify_order(Side.BID, 3, 36, 995)\r\n self.assertEqual(self.l1._bid_book[995]['orders'][36]['quantity'], 2)\r\n self.assertEqual(self.l1._bid_book[995]['size'], 2)\r\n self.assertEqual(self.l1._bid_book[995]['num_orders'], 1)\r\n self.l1.quote_collector.clear() # happens in process_order\r\n self.l1._update_bid_book(8, tob_ask)\r\n self.assertEqual(self.l1._bid_book[995]['size'], 5)\r\n self.assertEqual(self.l1._bid_book[995]['num_orders'], 2)\r\n self.assertEqual(len(self.l1.quote_collector), 1)\r\n \r\n def test_update_bid_book5(self):\r\n ''' Also, price range should always be between best bid - 20 and best bid - 60 '''\r\n # make best bid == 975 -> add orders to the other end of the book to make 40 prices\r\n for p in range(960, 976):\r\n self.l1._add_order(self.l1._make_add_quote(35, Side.BID, p, self.l1._maxq))\r\n for p in range(960, 976):\r\n with self.subTest(p=p):\r\n self.assertTrue(p in self.l1._bid_book_prices)\r\n self.l1._bid = 975\r\n tob_ask = 1040\r\n self.l1._update_bid_book(9, tob_ask)\r\n for p in range(936, 975):\r\n with self.subTest(p=p):\r\n self.assertTrue(p in self.l1._bid_book_prices)\r\n # make best bid == 1030 -> cancel orders on the other end of the book to make 40 prices\r\n self.l1._bid = 1030\r\n tob_ask = 1040\r\n self.l1._update_bid_book(10, tob_ask)\r\n for p in range(991, 1031):\r\n with self.subTest(p=p):\r\n self.assertTrue(p in self.l1._bid_book_prices)\r\n for p in range(961, 991):\r\n with self.subTest(p=p):\r\n self.assertFalse(p in self.l1._bid_book_prices)\r\n \r\n def test_seed_book(self):\r\n ask = 998\r\n bid = 990\r\n step = 20\r\n self.l1.seed_book(step, ask, bid)\r\n self.assertEqual(self.l1._mid, 994)\r\n self.assertTrue(990 in self.l1._bid_book_prices)\r\n self.assertTrue(998 in self.l1._ask_book_prices)\r\n self.assertEqual(self.l1._bid, 990)\r\n self.assertEqual(self.l1._ask, 998)\r\n self.assertEqual(len(self.l1.quote_collector), 2)\r\n\r\n def test_process_signals(self):\r\n ''' Test process_signal1 and process_signal2 '''\r\n signal = {'oibv': 6, 'arrv': 8, 'mid': 1000, 'oib': '011111000000011111000000',\r\n 'arr': '1222102221222222', 'vol': 4}\r\n \r\n self.l1._current_oi_strat = '222222222222222222222222'\r\n self.l1._current_arr_strat = '2222222222222222'\r\n self.l1._current_spradj_strat = ['21220']\r\n self.l1._last_buy_prices = [998, 999]\r\n self.l1._last_sell_prices = [1001, 1002]\r\n self.l1._delta_inv = 3\r\n \r\n ask = 1015 # stub quotes?\r\n bid = 985 # stub quotes?\r\n step = 20\r\n \r\n self.l1.seed_book(step, ask, bid)\r\n self.assertEqual(self.l1._bid, 985)\r\n self.assertEqual(self.l1._ask, 1015)\r\n self.l1.process_signal1(44, signal)\r\n \r\n # Step 1: update scores for predictors:\r\n self.assertListEqual(self.l1._oi_strat['222222222222222222222222']['accuracy'], [1, 1, 999.0])\r\n self.assertListEqual(self.l1._arr_strat['2222222222222222']['accuracy'], [22, 1, 978.0])\r\n self.assertListEqual(self.l1._spradj_strat['21220']['rr_spread'], [6, 4, 1.5])\r\n # Step 2: update the midpoint:\r\n self.assertEqual(self.l1._mid, 994)\r\n # Step 3: update spread: using updated spradj_strat = '21220', adjustment == 0 -> bid == 990, ask == 998\r\n self.assertEqual(self.l1._bid, 990)\r\n self.assertEqual(self.l1._ask, 998)\r\n # Step 4: process cancels: there aren't any\r\n # Step 5: update the book\r\n tob_bid = 988\r\n tob_ask = 1000\r\n self.l1.process_signal2(step, tob_bid, tob_ask)\r\n for p in range(951, 991):\r\n with self.subTest(p=p):\r\n self.assertTrue(p in self.l1._bid_book_prices)\r\n for p in range(998, 1038):\r\n with self.subTest(p=p):\r\n self.assertTrue(p in self.l1._ask_book_prices)\r\n self.assertEqual(len(self.l1.quote_collector), 78)\r\n # Step 6: update cash flow collector, reset inventory, clear recent prices\r\n self.assertDictEqual(self.l1.cash_flow_collector[-1], {'mmid': 3001, 'timestamp': 20, 'cash_flow': 0, 'delta_inv': 3})\r\n self.assertFalse(self.l1._delta_inv)\r\n self.assertFalse(self.l1._last_buy_prices)\r\n self.assertFalse(self.l1._last_sell_prices)\r\n @unittest.skip('for now')\r\n def test_find_winners_oi(self):\r\n for j, k in enumerate(self.l1._oi_strat.keys()):\r\n self.l1._oi_strat[k]['accuracy'][2] = 1000 - j\r\n self.l1._find_winners()\r\n oi_accs = [v['accuracy'][2] for v in self.l1._oi_strat.values()]\r\n for j in range(921, 1001):\r\n with self.subTest(j=j):\r\n self.assertTrue(j in oi_accs)\r\n self.assertEqual(min(oi_accs), 921)\r\n self.assertEqual(max(oi_accs), 1000)\r\n self.l2 = self._makeMML(3002, 1)\r\n for j, k in enumerate(self.l2._oi_strat.keys()):\r\n self.l2._oi_strat[k]['accuracy'][2] = 1000 - j\r\n if j % 5 == 0:\r\n self.l2._oi_strat[k]['accuracy'][1] = j\r\n self.l2._find_winners()\r\n oi_accs = [v['accuracy'] for v in self.l2._oi_strat.values()]\r\n for j in range(0, 100, 5):\r\n with self.subTest(j=j):\r\n self.assertTrue(j in [a[1] for a in oi_accs])\r\n\r\n def test_get_winners_oi(self):\r\n for j, k in enumerate(self.l1._oi_strat.keys()):\r\n self.l1._oi_strat[k]['accuracy'][2] = 1000 - j\r\n self.l1._get_winners()\r\n oi_accs = [v['accuracy'][2] for v in self.l1._oi_strat.values()]\r\n for j in range(921, 1001):\r\n with self.subTest(j=j):\r\n self.assertTrue(j in oi_accs)\r\n self.assertEqual(min(oi_accs), 921)\r\n self.assertEqual(max(oi_accs), 1000)\r\n self.l2 = self._makeMML(3002, 1)\r\n for j, k in enumerate(self.l2._oi_strat.keys()):\r\n self.l2._oi_strat[k]['accuracy'][2] = 1000 - j\r\n if j % 5 == 0:\r\n self.l2._oi_strat[k]['accuracy'][1] = j\r\n self.l2._get_winners()\r\n oi_accs = [v['accuracy'] for v in self.l2._oi_strat.values()]\r\n for j in range(0, 100, 5):\r\n with self.subTest(j=j):\r\n self.assertTrue(j in [a[1] for a in oi_accs])\r\n @unittest.skip('for now') \r\n def test_find_winners_arr(self):\r\n for j, k in enumerate(self.l1._arr_strat.keys()):\r\n self.l1._arr_strat[k]['accuracy'][2] = 1000 - j\r\n self.l1._find_winners()\r\n arr_accs = [v['accuracy'][2] for v in self.l1._arr_strat.values()]\r\n for j in range(921, 1001):\r\n with self.subTest(j=j):\r\n self.assertTrue(j in arr_accs)\r\n self.assertEqual(min(arr_accs), 921)\r\n self.assertEqual(max(arr_accs), 1000)\r\n \r\n self.l2 = self._makeMML(3002, 1)\r\n for j, k in enumerate(self.l2._arr_strat.keys()):\r\n self.l2._arr_strat[k]['accuracy'][2] = 1000 - j\r\n if j % 5 == 0:\r\n self.l2._arr_strat[k]['accuracy'][1] = j\r\n self.l2._find_winners()\r\n arr_accs = [v['accuracy'] for v in self.l2._arr_strat.values()]\r\n for j in range(0, 100, 5):\r\n with self.subTest(j=j):\r\n self.assertTrue(j in [a[1] for a in arr_accs])\r\n @unittest.skip('for now')\r\n def test_find_winners_spr(self):\r\n for j, k in enumerate(self.l1._spradj_strat.keys()):\r\n self.l1._spradj_strat[k]['rr_spread'][2] = j\r\n self.l1._find_winners()\r\n spr_rr = [kv[1]['rr_spread'][2] for kv in self.l1._spradj_strat.items()]\r\n for j in range(6, 25):\r\n with self.subTest(j=j):\r\n self.assertTrue(j in spr_rr)\r\n self.assertTrue(0 in spr_rr)\r\n self.assertEqual(min(spr_rr), 0)\r\n self.assertEqual(max(spr_rr), 24)\r\n self.assertTrue('222222222222222222222222' in self.l1._oi_strat.keys())\r\n self.assertTrue('2222222222222222' in self.l1._arr_strat.keys())\r\n self.assertTrue('22222' in self.l1._spradj_strat.keys())\r\n @unittest.skip('Method Not Used Directly')\r\n def test_uniform_selection(self):\r\n for j, k in enumerate(self.l1._oi_strat.keys()):\r\n self.l1._oi_strat[k]['accuracy'][2] = 1000 - j\r\n for j, k in enumerate(self.l1._arr_strat.keys()):\r\n self.l1._arr_strat[k]['accuracy'][2] = 1000 - j\r\n for j, k in enumerate(self.l1._spradj_strat.keys()):\r\n self.l1._spradj_strat[k]['rr_spread'][2] = j\r\n self.l1._find_winners()\r\n self.l1._uniform_selection()\r\n @unittest.skip('Method Not Used Directly')\r\n def test_weighted_selection(self):\r\n for j, k in enumerate(self.l1._oi_strat.keys()):\r\n self.l1._oi_strat[k]['accuracy'][2] = -j\r\n for j, k in enumerate(self.l1._arr_strat.keys()):\r\n self.l1._arr_strat[k]['accuracy'][2] = -j\r\n for j, k in enumerate(self.l1._spradj_strat.keys()):\r\n self.l1._spradj_strat[k]['rr_spread'][2] = j\r\n self.l1._find_winners()\r\n self.l1._weighted_selection()\r\n \r\n ''' Test before and after length of strategy dict\r\n The genetic manipulations are straightforward but run inline, making\r\n the length of the new strategy dict the only testable outcome\r\n '''\r\n def test_oi_genes_us(self):\r\n for j, k in enumerate(self.l1._oi_strat.keys()):\r\n self.l1._oi_strat[k]['accuracy'][0] = j\r\n self.l1._oi_strat[k]['accuracy'][1] = 1\r\n self.l1._oi_strat[k]['accuracy'][2] = 1000 - j\r\n self.assertEqual(len(self.l1._oi_strat), self.l1._oi_ngene)\r\n self.l1._get_winners()\r\n self.assertEqual(len(self.l1._oi_strat), self.l1._oi_keep)\r\n self.l1._oi_genes_us()\r\n self.assertEqual(len(self.l1._oi_strat), self.l1._oi_ngene)\r\n #for k in self.l1._oi_strat.keys():\r\n #if self.l1._oi_strat[k]['accuracy'][1] != 1:\r\n #print(self.l1._oi_strat[k])\r\n \r\n def test_arr_genes_us(self):\r\n for j, k in enumerate(self.l1._arr_strat.keys()):\r\n self.l1._arr_strat[k]['accuracy'][0] = j\r\n self.l1._arr_strat[k]['accuracy'][1] = 1\r\n self.l1._arr_strat[k]['accuracy'][2] = 1000 - j\r\n self.assertEqual(len(self.l1._arr_strat), self.l1._arr_ngene)\r\n self.l1._get_winners()\r\n self.assertEqual(len(self.l1._arr_strat), self.l1._arr_keep)\r\n self.l1._arr_genes_us()\r\n self.assertEqual(len(self.l1._arr_strat), self.l1._arr_ngene)\r\n #for k in self.l1._arr_strat.keys():\r\n #if self.l1._arr_strat[k]['accuracy'][1] != 1:\r\n #print(self.l1._arr_strat[k])\r\n \r\n def test_spr_genes_us(self):\r\n for j, k in enumerate(self.l1._spradj_strat.keys()):\r\n self.l1._spradj_strat[k]['rr_spread'][0] = j\r\n self.l1._spradj_strat[k]['rr_spread'][1] = 1\r\n self.l1._spradj_strat[k]['rr_spread'][2] = j\r\n self.assertEqual(len(self.l1._spradj_strat), self.l1._spr_ngene)\r\n self.l1._get_winners()\r\n self.assertEqual(len(self.l1._spradj_strat), self.l1._spradj_keep)\r\n self.l1._spr_genes_us()\r\n self.l1._get_winners()\r\n self.l1._spr_genes_us()\r\n self.assertEqual(len(self.l1._spradj_strat), self.l1._spr_ngene)\r\n #for k in self.l1._spradj_strat.keys():\r\n #if self.l1._spradj_strat[k]['rr_spread'][1] != 1:\r\n #print(self.l1._spradj_strat[k])\r\n\r\n def test_new_genes_u(self):\r\n for j, k in enumerate(self.l1._oi_strat.keys()):\r\n self.l1._oi_strat[k]['accuracy'][0] = j\r\n self.l1._oi_strat[k]['accuracy'][1] = 1\r\n self.l1._oi_strat[k]['accuracy'][2] = 1000 - j\r\n self.assertEqual(len(self.l1._oi_strat), self.l1._oi_ngene)\r\n for j, k in enumerate(self.l1._arr_strat.keys()):\r\n self.l1._arr_strat[k]['accuracy'][0] = j\r\n self.l1._arr_strat[k]['accuracy'][1] = 1\r\n self.l1._arr_strat[k]['accuracy'][2] = 1000 - j\r\n self.assertEqual(len(self.l1._arr_strat), self.l1._arr_ngene)\r\n for j, k in enumerate(self.l1._spradj_strat.keys()):\r\n self.l1._spradj_strat[k]['rr_spread'][0] = j\r\n self.l1._spradj_strat[k]['rr_spread'][1] = 1\r\n self.l1._spradj_strat[k]['rr_spread'][2] = j\r\n self.assertEqual(len(self.l1._spradj_strat), self.l1._spr_ngene)\r\n self.l1._genetics_us()\r\n self.assertEqual(len(self.l1._oi_strat), self.l1._oi_ngene)\r\n self.assertEqual(len(self.l1._arr_strat), self.l1._arr_ngene)\r\n self.assertEqual(len(self.l1._spradj_strat), self.l1._spr_ngene)\r\n \r\n def test_oi_genes_ws(self):\r\n for j, k in enumerate(self.l1._oi_strat.keys()):\r\n self.l1._oi_strat[k]['accuracy'][0] = j\r\n self.l1._oi_strat[k]['accuracy'][1] = 1\r\n self.l1._oi_strat[k]['accuracy'][2] = 1000 - j\r\n self.assertEqual(len(self.l1._oi_strat), self.l1._oi_ngene)\r\n self.l1._get_winners()\r\n self.assertEqual(len(self.l1._oi_strat), self.l1._oi_keep)\r\n self.l1._oi_genes_ws()\r\n self.assertEqual(len(self.l1._oi_strat), self.l1._oi_ngene)\r\n #for k in self.l1._oi_strat.keys():\r\n #if self.l1._oi_strat[k]['accuracy'][1] != 1:\r\n #print(self.l1._oi_strat[k])\r\n \r\n def test_arr_genes_ws(self):\r\n for j, k in enumerate(self.l1._arr_strat.keys()):\r\n self.l1._arr_strat[k]['accuracy'][0] = j\r\n self.l1._arr_strat[k]['accuracy'][1] = 1\r\n self.l1._arr_strat[k]['accuracy'][2] = 1000 - j\r\n self.assertEqual(len(self.l1._arr_strat), self.l1._arr_ngene)\r\n self.l1._get_winners()\r\n self.assertEqual(len(self.l1._arr_strat), self.l1._arr_keep)\r\n self.l1._arr_genes_ws()\r\n self.assertEqual(len(self.l1._arr_strat), self.l1._arr_ngene)\r\n #for k in self.l1._arr_strat.keys():\r\n #if self.l1._arr_strat[k]['accuracy'][1] != 1:\r\n #print(self.l1._arr_strat[k])\r\n\r\n def test_spr_genes_ws(self):\r\n for j, k in enumerate(self.l1._spradj_strat.keys()):\r\n self.l1._spradj_strat[k]['rr_spread'][0] = j\r\n self.l1._spradj_strat[k]['rr_spread'][1] = 1\r\n self.l1._spradj_strat[k]['rr_spread'][2] = j\r\n self.assertEqual(len(self.l1._spradj_strat), self.l1._spr_ngene)\r\n self.l1._get_winners()\r\n self.assertEqual(len(self.l1._spradj_strat), self.l1._spradj_keep)\r\n self.l1._spr_genes_ws()\r\n self.assertEqual(len(self.l1._spradj_strat), self.l1._spr_ngene)\r\n #for k in self.l1._spradj_strat.keys():\r\n #if self.l1._spradj_strat[k]['rr_spread'][1] != 1:\r\n #print(self.l1._spradj_strat[k])\r\n\r\n def test_new_genes_w(self):\r\n for j, k in enumerate(self.l1._oi_strat.keys()):\r\n self.l1._oi_strat[k]['accuracy'][0] = j\r\n self.l1._oi_strat[k]['accuracy'][1] = 1\r\n self.l1._oi_strat[k]['accuracy'][2] = 1000 - j\r\n self.assertEqual(len(self.l1._oi_strat), self.l1._oi_ngene)\r\n for j, k in enumerate(self.l1._arr_strat.keys()):\r\n self.l1._arr_strat[k]['accuracy'][0] = j\r\n self.l1._arr_strat[k]['accuracy'][1] = 1\r\n self.l1._arr_strat[k]['accuracy'][2] = 1000 - j\r\n self.assertEqual(len(self.l1._arr_strat), self.l1._arr_ngene)\r\n for j, k in enumerate(self.l1._spradj_strat.keys()):\r\n self.l1._spradj_strat[k]['rr_spread'][0] = j\r\n self.l1._spradj_strat[k]['rr_spread'][1] = 1\r\n self.l1._spradj_strat[k]['rr_spread'][2] = j\r\n self.assertEqual(len(self.l1._spradj_strat), self.l1._spr_ngene)\r\n self.l1._genetics_ws()\r\n self.assertEqual(len(self.l1._oi_strat), self.l1._oi_ngene)\r\n self.assertEqual(len(self.l1._arr_strat), self.l1._arr_ngene)\r\n self.assertEqual(len(self.l1._spradj_strat), self.l1._spr_ngene)" ]
[ [ "numpy.arange", "numpy.random.seed" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Mateo-Lopez-Espejo/context_probe_analysis
[ "55461057fd01f00124aa46682b335313af9cc0f8" ]
[ "scripts/4_sam_data/200221_NTI_CPN_comparison.py" ]
[ "import itertools as itt\r\nimport pathlib as pl\r\n\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom scipy.io import loadmat\r\n\r\nimport src.data.rasters\r\nfrom src.data import dPCA as cdPCA\r\nfrom src.metrics import dprime as cDP\r\nfrom src.data.load import load, get_site_ids\r\nfrom src.data.cache import make_cache, get_cache\r\nfrom src.metrics.reliability import signal_reliability\r\nfrom src.utils.tools import shuffle_along_axis as shuffle\r\nfrom src.utils import fits as fit\r\nfrom src.visualization import fancy_plots as fplt\r\n\r\n'''\r\nsince applying the dprime CPN analysis toe the NTI data was unsuccessfull, the next alternative to compare Sam and my\r\napproach is to perform the CPN and NTI analysis to their respective datasets on recording sites that have both data\r\n'''\r\n\r\n\r\n# 1. list sites with both datasets\r\n# list all NTI sites this have to be done manually\r\n# list all CPN sites, this should be trivial\r\n# check the intersection\r\n\r\n# 2. Calculates the dPrime for each site and all possible probes, context pairs and cells (?). This is the difficult part\r\n# to summarize the outcome of all the\r\n\r\n\r\ndef cell_dprime(site, probe, meta):\r\n # recs = load(site, remote=True, rasterfs=meta['raster_fs'], recache=False)\r\n recs = load(site, rasterfs=meta['raster_fs'], recache=rec_recache)\r\n if len(recs) > 2:\r\n print(f'\\n\\n{recs.keys()}\\n\\n')\r\n\r\n rec = recs['trip0']\r\n sig = rec['resp']\r\n\r\n # calculates response realiability and select only good cells to improve analysis\r\n r_vals, goodcells = signal_reliability(sig, r'\\ASTIM_*', threshold=meta['reliability'])\r\n goodcells = goodcells.tolist()\r\n\r\n # get the full data raster Context x Probe x Rep x Neuron x Time\r\n raster = src.data.rasters.raster_from_sig(sig, probe, channels=goodcells, contexts=meta['transitions'],\r\n smooth_window=meta['smoothing_window'], raster_fs=meta['raster_fs'],\r\n zscore=meta['zscore'], part='probe')\r\n\r\n # trialR shape: Trial x Cell x Context x Probe x Time; R shape: Cell x Context x Probe x Time\r\n trialR, R, _ = cdPCA.format_raster(raster)\r\n trialR, R = trialR.squeeze(axis=3), R.squeeze(axis=2) # squeezes out probe\r\n\r\n rep, chn, ctx, tme = trialR.shape\r\n\r\n trans_pairs = [f'{x}_{y}' for x, y in itt.combinations(meta['transitions'], 2)]\r\n\r\n dprime = cDP.pairwise_dprimes(trialR, observation_axis=0, condition_axis=2) # shape CellPair x Cell x Time\r\n\r\n # Shuffles the rasters n times and organizes in an array with the same shape the raster plus one dimension\r\n # with size n containing each shuffle\r\n\r\n shuffled = list()\r\n # pbar = ProgressBar()\r\n print(f\"\\nshuffling {meta['montecarlo']} times\")\r\n for tp in trans_pairs:\r\n shuf_trialR = np.empty([meta['montecarlo'], rep, chn, 2, tme])\r\n shuf_trialR[:] = np.nan\r\n\r\n tran_idx = np.array([meta['transitions'].index(t) for t in tp.split('_')])\r\n ctx_shuffle = trialR[:, :, tran_idx, :].copy()\r\n\r\n for rr in range(meta['montecarlo']):\r\n shuf_trialR[rr, ...] = shuffle(ctx_shuffle, shuffle_axis=2, indie_axis=0)\r\n\r\n shuffled.append(cDP.pairwise_dprimes(shuf_trialR, observation_axis=1, condition_axis=3))\r\n\r\n shuffled = np.stack(shuffled, axis=1).squeeze(axis=0).swapaxes(0, 1) # shape Montecarlo x ContextPair x Cell x Time\r\n\r\n return dprime, shuffled, goodcells, trans_pairs\r\n\r\n\r\ndef dPCA_fourway_analysis(site, probe, meta):\r\n # recs = load(site, remote=True, rasterfs=meta['raster_fs'], recache=False)\r\n recs = load(site, rasterfs=meta['raster_fs'], recache=rec_recache)\r\n\r\n if len(recs) > 2:\r\n print(f'\\n\\n{recs.keys()}\\n\\n')\r\n\r\n rec = recs['trip0']\r\n sig = rec['resp']\r\n\r\n # calculates response realiability and select only good cells to improve analysis\r\n r_vals, goodcells = signal_reliability(sig, r'\\ASTIM_*', threshold=meta['reliability'])\r\n goodcells = goodcells.tolist()\r\n\r\n # get the full data raster Context x Probe x Rep x Neuron x Time\r\n raster = src.data.rasters.raster_from_sig(sig, probe, channels=goodcells, contexts=meta['transitions'],\r\n smooth_window=meta['smoothing_window'], raster_fs=meta['raster_fs'],\r\n zscore=meta['zscore'])\r\n\r\n # trialR shape: Trial x Cell x Context x Probe x Time; R shape: Cell x Context x Probe x Time\r\n trialR, R, _ = cdPCA.format_raster(raster)\r\n trialR, R = trialR.squeeze(axis=3), R.squeeze(axis=2) # squeezes out probe\r\n Re, C, S, T = trialR.shape\r\n\r\n # calculates full dPCA. i.e. considering all 4 categories\r\n dPCA_projection, dPCA_transformation = cdPCA.fit_transform(R, trialR)\r\n dprime = cDP.pairwise_dprimes(dPCA_projection, observation_axis=0, condition_axis=1)\r\n\r\n # calculates floor (ctx shuffle) and ceiling (simulated data)\r\n sim_dprime = np.empty([meta['montecarlo']] + list(dprime.shape))\r\n shuf_dprime = np.empty([meta['montecarlo']] + list(dprime.shape))\r\n\r\n ctx_shuffle = trialR.copy()\r\n # pbar = ProgressBar()\r\n for rr in range(meta['montecarlo']):\r\n # ceiling: simulates data, calculates dprimes\r\n sim_trial = np.random.normal(np.mean(trialR, axis=0), np.std(trialR, axis=0),\r\n size=[Re, C, S, T])\r\n sim_projection = cdPCA.transform(sim_trial, dPCA_transformation)\r\n sim_dprime[rr, ...] = cDP.pairwise_dprimes(sim_projection, observation_axis=0, condition_axis=1)\r\n\r\n ctx_shuffle = shuffle(ctx_shuffle, shuffle_axis=2, indie_axis=0)\r\n shuf_projection = cdPCA.transform(ctx_shuffle, dPCA_transformation)\r\n shuf_dprime[rr, ...] = cDP.pairwise_dprimes(shuf_projection, observation_axis=0, condition_axis=1)\r\n\r\n return dprime, shuf_dprime, sim_dprime, goodcells\r\n\r\n# transferable plotting parameters\r\nplt.rcParams['svg.fonttype'] = 'none'\r\nsup_title_size = 30\r\nsub_title_size = 20\r\nax_lab_size = 15\r\nax_val_size = 11\r\n\r\nmeta = {'reliability': 0.1, # r value\r\n 'smoothing_window': 0, # ms\r\n 'raster_fs': 30,\r\n 'transitions': ['silence', 'continuous', 'similar', 'sharp'],\r\n 'montecarlo': 1000,\r\n 'zscore': False}\r\n\r\ndprime_recache = False\r\nrec_recache = False\r\n\r\nanalysis_name = 'NTI_singel_cell_dprime'\r\nanalysis_parameters = '_'.join(['{}-{}'.format(key, str(val)) for key, val in meta.items()])\r\ncode_to_name = {'t': 'Probe', 'ct': 'Context'}\r\nfull_screen = [19.2, 9.83]\r\n\r\nall_probes = [2, 3, 5, 6]\r\n\r\nsites = ['ley070a', # good site. A1\r\n 'ley072b', # Primary looking responses with strong contextual effects\r\n 'AMT028b', # good site\r\n 'AMT029a', # Strong response, somehow visible contextual effects\r\n 'AMT030a', # low responses, Ok but not as good\r\n # 'AMT031a', # low response, bad\r\n 'AMT032a'] # great site. PEG\r\n\r\nsites = list(get_site_ids(316).keys())\r\n# problem sites:\r\n# sites = ['AMT031a']\r\n\r\n\r\n# for site, probe in zip(['AMT029a', 'ley070a'],[5,2]):\r\n# all_sites = ['AMT029a']\r\n# all_sites = ['AMT032a']\r\n# all_probes = [5]\r\n\r\nbad_sites = list()\r\nall_pvalues = dict()\r\nall_reals = dict()\r\nall_shuffled = dict()\r\n\r\nfor site in sites:\r\n\r\n this_site_reals = list()\r\n this_site_shuffled = list()\r\n this_site_pvalues = list()\r\n for pp, probe in enumerate(all_probes):\r\n # single cell analysis\r\n object_name = f'200221_{site}_P{probe}_single_cell_dprime'\r\n analysis_parameters = '_'.join(['{}-{}'.format(key, str(val)) for key, val in meta.items()])\r\n analysis_name = 'CPN_singel_cell_dprime'\r\n cache_folder = pl.Path('C:\\\\', 'users', 'mateo', 'mycache', analysis_name, analysis_parameters)\r\n\r\n SC_cache = make_cache(function=cell_dprime,\r\n func_args={'site': site, 'probe': probe, 'meta': meta},\r\n classobj_name=object_name,\r\n cache_folder=cache_folder,\r\n recache=dprime_recache)\r\n\r\n dprime, shuf_dprime, cell_names, trans_pairs = get_cache(SC_cache)\r\n\r\n this_site_reals.append(dprime)\r\n this_site_shuffled.append(shuf_dprime)\r\n\r\n # single tailed p value base on the montecarlo shuffling\r\n SC_pvalues = np.sum((shuf_dprime >= dprime), axis=0) / meta['montecarlo']\r\n this_site_pvalues.append(SC_pvalues)\r\n\r\n this_site_reals = np.stack(this_site_reals, axis=0)\r\n this_site_shuffled = np.stack(this_site_shuffled, axis=0)\r\n this_site_pvalues = np.stack(this_site_pvalues, axis=0)\r\n\r\n # reorders date in dictionary of cells\r\n for cc, cell in enumerate(cell_names):\r\n all_reals[cell] = this_site_reals[:, :, cc, :]\r\n all_shuffled[cell] = this_site_shuffled[:, :, :, cc, :].swapaxes(0, 1)\r\n all_pvalues[cell] = this_site_pvalues[:, :, cc, :]\r\n\r\n# stacks the site individual arrays along a new site dimension. since the sites have disimilar cell number, pads\r\nall_cells = np.array(list(all_pvalues.keys()))\r\n\r\nthreshold = 0.05\r\nall_signif = {key: (val <= threshold) for key, val in all_pvalues.items()}\r\n\r\n# stacks arrays, with different time dimentions, padding with NAN\r\nshape = np.insert(np.max(np.stack([arr.shape for arr in all_signif.values()], axis=0), axis=0), 0,\r\n len(all_signif))\r\nsignif_array = np.empty(shape)\r\nsignif_array[:] = np.nan\r\nfor cc, arr in enumerate(all_signif.values()):\r\n t = arr.shape[-1]\r\n signif_array[cc, :, :, :t] = arr\r\n# sig_array = np.stack(list(all_signif.values()), axis=0) # dimensions: Cell x Probe x trans_pair x time\r\n\r\n# calculates exponential decay for each cell, collapsing across all probes and transisions\r\nnbin = signif_array.shape[-1]\r\nfs = meta['raster_fs']\r\ntimes = np.linspace(0, nbin / fs, nbin, endpoint=False) * 1000 # units in ms!!!!\r\ncollapsed = signif_array.mean(axis=(1, 2))\r\n\r\n# organizes in a dataframe with columns r0: y intercept, decay: eponential valaue and tau: Time to a 36% amplitude\r\ndf = list()\r\nfor cellid, data in zip(all_cells, collapsed):\r\n popt, _, _ = fit.exp_decay(times, data)\r\n df.append({'cellid': cellid,\r\n 'r0_au': popt[0],\r\n 'decay_ms': popt[1]})\r\n\r\ncontext_fits = pd.DataFrame(df)\r\ncontext_fits['tau_ms'] = -1/context_fits['decay_ms']\r\ncontext_fits.set_index(['cellid'], inplace=True)\r\n\r\n\r\n# 3. import and parse matlab results for Sam's NTI analysis. These results are in a cell by cell format, then it makes\r\n# sense to calculate the dprimes idividually forP each cell\r\nfile = pl.Path('C:\\\\', 'Users', 'Mateo', 'Documents', 'Science', 'code', 'integration_quilt', 'scrambling-ferrets',\r\n 'analysis', 'model_fit_pop_summary').with_suffix('.mat')\r\n\r\nbest_fits = loadmat(file)['best_fits'].squeeze()\r\n# orders the data in DF\r\ndf = list()\r\nfor row in best_fits:\r\n df.append({'cellid': row[2][0],\r\n 'intper_ms': row[0][0][0],\r\n 'delay_ms': row[1][0][0]})\r\n\r\nintegration_fits = pd.DataFrame(df)\r\nintegration_fits.set_index(['cellid'], inplace=True)\r\n\r\n\r\n# 4. pools together both approache, selects only common cell, plots relationships\r\n# join='inner' keeps only the intersection between the two Dfs, i.e. the cells that have both approaches\r\ndef savefig(fig, root, name):\r\n root = pl.Path(f'C:\\\\users\\\\mateo\\\\Pictures\\\\{root}')\r\n if not root.exists(): root.mkdir(parents=True, exist_ok=True)\r\n png = root.joinpath(name).with_suffix('.png')\r\n fig.savefig(png, transparent=False, dpi=100)\r\n # svg = root.joinpath(name).with_suffix('.svg')\r\n # fig.savefig(svg, transparent=True)\r\n\r\nDF = pd.concat([context_fits, integration_fits], axis=1, join='inner')\r\n# filter out anomalous outliers i.e taus over 1 second due to poor fiting\r\nff_good = DF['tau_ms'] < 1000\r\n\r\nfiltered = DF.loc[ff_good, :]\r\n\r\n\r\nfig_root = 'sam_vs_mat'\r\nx = filtered['tau_ms']\r\ny = filtered['intper_ms']\r\n\r\nfig, ax = plt.subplots(figsize=full_screen)\r\nax.scatter(x, y)\r\n_ = fplt.lin_reg(x,y, ax=ax)\r\nax.set_xlabel(x.name)\r\nax.set_ylabel(y.name)\r\nax.legend()\r\nfig.tight_layout(rect=(0, 0, 1, 0.95))\r\ntitle = 'Sam integration vs Mateo Tau'\r\nfig.suptitle(title)\r\nsavefig(fig, fig_root, title)" ]
[ [ "pandas.concat", "numpy.linspace", "scipy.io.loadmat", "matplotlib.pyplot.subplots", "numpy.stack", "pandas.DataFrame", "numpy.std", "numpy.mean", "numpy.sum", "numpy.empty" ] ]
[ { "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": [ "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": [] } ]
kastalpes/yt
[ "b1e197ca84433fbd61eaf44b28ff5cdb37981d4c", "b1e197ca84433fbd61eaf44b28ff5cdb37981d4c" ]
[ "doc/source/cookbook/time_series.py", "yt/frontends/stream/tests/test_stream_amrgrids.py" ]
[ "import yt\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# Enable parallelism in the script (assuming it was called with\n# `mpirun -np <n_procs>` )\nyt.enable_parallelism()\n\n# By using wildcards such as ? and * with the load command, we can load up a\n# Time Series containing all of these datasets simultaneously.\nts = yt.load('GasSloshingLowRes/sloshing_low_res_hdf5_plt_cnt_0*')\n\nstorage = {}\n\n# By using the piter() function, we can iterate on every dataset in\n# the TimeSeries object. By using the storage keyword, we can populate\n# a dictionary where the dataset is the key, and sto.result is the value\n# for later use when the loop is complete.\n\n# The serial equivalent of piter() here is just \"for ds in ts:\" .\n\nfor store, ds in ts.piter(storage=storage):\n\n # Create a sphere of radius 100 kpc at the center of the dataset volume\n sphere = ds.sphere(\"c\", (100., \"kpc\"))\n # Calculate the entropy within that sphere\n entr = sphere[\"entropy\"].sum()\n # Store the current time and sphere entropy for this dataset in our\n # storage dictionary as a tuple\n store.result = (ds.current_time.in_units('Gyr'), entr)\n\n# Convert the storage dictionary values to a Nx2 array, so the can be easily\n# plotted\narr = np.array(list(storage.values()))\n\n# Plot up the results: time versus entropy\nplt.semilogy(arr[:,0], arr[:,1], 'r-')\nplt.xlabel(\"Time (Gyr)\")\nplt.ylabel(\"Entropy (ergs/K)\")\nplt.savefig(\"time_versus_entropy.png\")\n", "import numpy as np\nfrom yt.utilities.exceptions import \\\n YTIllDefinedAMR, \\\n YTIntDomainOverflow\n\nfrom yt import load_amr_grids, ProjectionPlot\n\nfrom yt.testing import assert_raises\n\ndef test_qt_overflow():\n grid_data = []\n\n grid_dict = {}\n\n grid_dict['left_edge'] = [-1.0, -1.0, -1.0]\n grid_dict['right_edge'] = [1.0, 1.0, 1.0]\n grid_dict['dimensions'] = [8, 8, 8]\n grid_dict['level'] = 0\n\n grid_dict['density'] = np.ones((8,8,8))\n\n grid_data.append(grid_dict)\n\n domain_dimensions = np.array([8, 8, 8])\n\n spf = load_amr_grids(grid_data, domain_dimensions)\n\n def make_proj():\n p = ProjectionPlot(spf, 'x', [\"density\"], center='c', origin='native')\n return p\n assert_raises(YTIntDomainOverflow, make_proj)\n\ndef test_refine_by():\n grid_data = []\n ref_by = 4\n lo = 0.0\n hi = 1.0\n fine_grid_width = (hi - lo) / ref_by\n for level in range(2):\n grid_dict = {}\n\n grid_dict['left_edge'] = [0.0 + 0.5*fine_grid_width*level]*3\n grid_dict['right_edge'] = [1.0 - 0.5*fine_grid_width*level]*3\n grid_dict['dimensions'] = [8, 8, 8]\n grid_dict['level'] = level\n\n grid_dict['density'] = np.ones((8,8,8))\n\n grid_data.append(grid_dict)\n\n domain_dimensions = np.array([8, 8, 8])\n\n load_amr_grids(grid_data, domain_dimensions, refine_by=ref_by)\n\ndef test_validation():\n dims = np.array([4, 2, 4])\n grid_data = [\n dict(left_edge = [0.0, 0.0, 0.0],\n right_edge = [1.0, 1.0, 1.0],\n level = 0,\n dimensions = dims),\n dict(left_edge = [0.25, 0.25, 0.25],\n right_edge = [0.75, 0.75, 0.75],\n level = 1,\n dimensions = dims),\n ]\n bbox = np.array([[0, 1], [0, 1], [0, 1]])\n def load_grids():\n load_amr_grids(grid_data, dims, bbox=bbox, periodicity=(0, 0, 0),\n length_unit=1.0, refine_by=2)\n assert_raises(YTIllDefinedAMR, load_grids)\n" ]
[ [ "matplotlib.pyplot.semilogy", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.savefig", "matplotlib.pyplot.ylabel" ], [ "numpy.array", "numpy.ones" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
steffenerickson/pytorch
[ "0b656c4c69ce77ecd9aace486e471917e4660746", "0b656c4c69ce77ecd9aace486e471917e4660746", "0b656c4c69ce77ecd9aace486e471917e4660746", "0b656c4c69ce77ecd9aace486e471917e4660746", "0b656c4c69ce77ecd9aace486e471917e4660746", "0b656c4c69ce77ecd9aace486e471917e4660746", "0b656c4c69ce77ecd9aace486e471917e4660746" ]
[ "test/fx2trt/converters/acc_op/test_batchnorm.py", "torch/distributed/_sharded_tensor/api.py", "test/fx2trt/trt_lower/trt_splitter_test.py", "torch/optim/adamw.py", "test/jit/test_backends.py", "torch/utils/data/distributed.py", "test/fx2trt/converters/acc_op/test_relu.py" ]
[ "# Owner(s): [\"oncall: aiacc\"]\n\nimport torch\nimport torch.fx.experimental.fx_acc.acc_ops as acc_ops\nfrom torch.testing._internal.common_fx2trt import AccTestCase, InputTensorSpec\nfrom torch.testing._internal.common_utils import run_tests\n\n\nclass TestBatchNormConverter(AccTestCase):\n def test_batchnorm(self):\n class TestModule(torch.nn.Module):\n def __init__(self):\n super().__init__()\n self.bn = torch.nn.BatchNorm2d(3)\n\n def forward(self, x):\n return self.bn(x)\n\n inputs = [torch.randn(1, 3, 224, 224)]\n self.run_test(TestModule(), inputs, expected_ops={acc_ops.batch_norm})\n\n def test_batchnorm_with_dynamic_shape(self):\n class TestModule(torch.nn.Module):\n def __init__(self):\n super().__init__()\n self.bn = torch.nn.BatchNorm2d(3)\n\n def forward(self, x):\n return self.bn(x)\n\n input_specs = [\n InputTensorSpec(\n shape=(-1, 3, -1, -1),\n dtype=torch.float32,\n shape_ranges=[((1, 3, 1, 1), (1, 3, 5, 5), (2, 3, 10, 10))],\n ),\n ]\n\n self.run_test_with_dynamic_shape(\n TestModule(), input_specs, expected_ops={acc_ops.batch_norm}\n )\n\nif __name__ == '__main__':\n run_tests()\n", "from dataclasses import dataclass, field\nfrom enum import Enum\nfrom typing import (\n Callable,\n Dict,\n List,\n Optional,\n Union\n)\nimport weakref\n\nimport threading\nimport torch\nimport torch.distributed as dist\nfrom torch.distributed import rpc\nfrom torch.distributed import distributed_c10d\nfrom torch.distributed._sharding_spec import (\n ChunkShardingSpec,\n EnumerableShardingSpec,\n ShardMetadata,\n ShardingSpec,\n)\nfrom torch.distributed._sharding_spec._internals import (\n check_tensor,\n get_split_size,\n get_chunked_dim_size,\n validate_non_overlapping_shards_metadata,\n)\nfrom torch.types import Number\nfrom .metadata import TensorProperties, ShardedTensorMetadata\nfrom .shard import Shard\nfrom .utils import (\n get_current_process_group,\n _flatten_tensor_size,\n _parse_and_validate_remote_device,\n _validate_output_tensor_for_gather,\n build_metadata_from_local_shards,\n build_global_metadata\n)\n\n# Tracking for sharded tensor objects.\n_sharded_tensor_lock = threading.Lock()\n_sharded_tensor_current_id = 0\n_sharded_tensor_map: Dict[int, 'weakref.ReferenceType[ShardedTensor]'] = {}\n\n# Custom sharded ops\n_SHARDED_OPS: Dict[str, Callable] = {}\ndef _register_sharded_op(op, func):\n from inspect import signature\n if len(signature(func).parameters) != 4:\n raise TypeError(\n f'Custom sharded op function expects signature: '\n f'(types, args, kwargs, process_group), but received '\n f'signature: {signature(func)}')\n\n global _SHARDED_OPS\n _SHARDED_OPS[op] = func\n\ndef _register_remote_shards(sharded_tensor_id: int, rrefs: List[rpc.RRef[Shard]], rpc_rank: int):\n with _sharded_tensor_lock:\n if sharded_tensor_id not in _sharded_tensor_map:\n raise RuntimeError(\n f'Could not find sharded_tensor_id: {sharded_tensor_id} in map: {_sharded_tensor_map.keys()}')\n\n sharded_tensor = _sharded_tensor_map[sharded_tensor_id]()\n if sharded_tensor is None:\n raise RuntimeError('ShardedTensor weakref has been deallocated')\n else:\n sharded_tensor._register_remote_shards(rrefs, rpc_rank)\n\n\nclass CreateOp(Enum):\n EMPTY = 0\n FULL = 1\n ONES = 2\n RAND = 3\n ZEROS = 4\n\n\n@dataclass\nclass TensorInitParams(object):\n \"\"\" Container for list of common params to create new local tensor. \"\"\"\n\n create_op: CreateOp\n\n # needed when create_op is FULL\n # default set to False (not None) since None is incompatible with Number.\n fill_value: Number = field(default=False)\n\n tensor_properties: TensorProperties = field(\n default=TensorProperties(dtype=torch.get_default_dtype(),\n layout=torch.strided,\n requires_grad=False,\n memory_format=torch.contiguous_format,\n pin_memory=False))\n\n\n\nclass ShardedTensor(object):\n \"\"\"\n ShardedTensor is an abstraction to represent Tensors that are sharded\n across multiple devices and multiple processes.\n\n ShardedTensor is initialized in an SPMD like fashion where each rank\n initializes the ShardedTensor. The ShardedTensor object on each rank\n then only stores the local shard for the Tensor and provides global\n metadata for all the shards.\n\n ShardedTensor doesn't provide any Tensor like operations but is a wrapper\n providing the Tensor representing the local shard and the global metadata.\n Using these, users can build their custom distributed sharded computations\n on top of this primitive. The local shards are all initialized using the\n create_op specified by tensor_init_params.create_op, e.g., torch.ones, or\n torch.empty\n\n Args:\n sharding_spec (:class:`torch.distributed._sharding_spec.ShardingSpec`): The specification\n describing how to shard the Tensor.\n size (int...): a sequence of integers defining the shape of the output\n tensor. Can be a variable number of arguments or a collection like a list or tuple.\n\n Keyword args:\n tensor_init_params (:class: `TensorInitParams`): common params to create tensor.\n init_rrefs (bool, optional): Whether or not to initialize\n :class:`torch.distributed.rpc.RRef`s pointing to remote shards.\n Need to initialize the RPC Framework if specified as ``True``.\n Default: ``False``.\n\n .. note:: ShardedTensor uses collectives to do various operations, i.e. it\n uses all_gather to do cross rank validations. For NCCL-based processed\n groups, internal tensor representations of objects must be moved to the\n GPU device before communication takes place. In this case, the device\n used is given by ``torch.cuda.current_device()`` and it is the user's\n responsiblity to ensure that this is set so that each rank has an\n individual GPU, via ``torch.cuda.set_device()``\n\n \"\"\"\n\n def __new__(cls, *args, **kwargs):\n # Use __new__ for logging purposes.\n torch._C._log_api_usage_once(\"torch.distributed.sharded_tensor\")\n return super(ShardedTensor, cls).__new__(cls)\n\n def __init__(\n self,\n sharding_spec: ShardingSpec,\n *size,\n tensor_init_params: TensorInitParams,\n process_group=None,\n init_rrefs=False,\n ):\n # prepare initialization, initialize fields like\n # _process_group, _local_shards, etc.\n self._prepare_init(process_group=process_group, init_rrefs=init_rrefs)\n\n if tensor_init_params.tensor_properties is None:\n raise ValueError('tensor_properties must not be None.')\n\n if tensor_init_params.tensor_properties.dtype is None:\n tensor_init_params.tensor_properties.dtype = torch.get_default_dtype()\n\n if tensor_init_params.tensor_properties.layout != torch.strided:\n raise ValueError('Only torch.strided layout is currently supported')\n\n if tensor_init_params.tensor_properties.memory_format != torch.contiguous_format:\n raise ValueError('Only torch.contiguous_format memory_format is currently supported')\n\n dims = _flatten_tensor_size(size)\n\n self._sharding_spec = sharding_spec\n\n if isinstance(self._sharding_spec, ChunkShardingSpec):\n self._init_chunked(dims, tensor_init_params)\n elif isinstance(self._sharding_spec, EnumerableShardingSpec):\n self._init_enumerable(dims, tensor_init_params)\n else:\n raise ValueError(f'Unsupported sharding_spec: {self._sharding_spec}')\n\n # do post initialization (i.e. register sharded_tensor_id, initialize_rpc)\n self._post_init()\n\n def _prepare_init(self, process_group=None, init_rrefs=False):\n self._init_rrefs = init_rrefs\n self._sharded_tensor_id = None\n\n self._process_group = (\n process_group\n if process_group is not None\n else distributed_c10d._get_default_group()\n )\n\n self._local_shards: List[Shard] = []\n self._remote_shards: Dict[int, List[rpc.RRef[Shard]]] = {}\n\n def _post_init(self):\n # Initialize RPC if available.\n if self._init_rrefs:\n with _sharded_tensor_lock:\n global _sharded_tensor_current_id, _sharded_tensor_map\n self._sharded_tensor_id = _sharded_tensor_current_id\n _sharded_tensor_map[self._sharded_tensor_id] = weakref.ref(self)\n _sharded_tensor_current_id += 1\n\n if not rpc._is_current_rpc_agent_set():\n raise RuntimeError(\n 'RPC Framework needs to be initialized using'\n ' torch.distributed.rpc.init_rpc if init_rrefs is set to True')\n self._init_rpc()\n\n def __del__(self):\n # Clean up the global map.\n with _sharded_tensor_lock:\n global _sharded_tensor_current_id, _sharded_tensor_map\n if self._sharded_tensor_id in _sharded_tensor_map:\n _sharded_tensor_map.pop(self._sharded_tensor_id) # type: ignore[call-overload]\n\n def _init_rpc(self):\n # Validate PG and RPC ranks match.\n pg_rank = dist.get_rank()\n rpc_rank = rpc.get_worker_info().id\n if pg_rank != rpc_rank:\n raise ValueError(\n f'Default ProcessGroup and RPC ranks must be '\n f'the same for ShardedTensor, found process group rank: '\n f'{pg_rank} and RPC rank: {rpc_rank}'\n )\n\n self._remote_shards = {}\n\n # Gather all the sharded tensor ids.\n worker_infos = rpc._get_current_rpc_agent().get_worker_infos()\n rank_to_name = {}\n name_to_rank = {}\n\n for worker_info in worker_infos:\n rank_to_name[worker_info.id] = worker_info.name\n name_to_rank[worker_info.name] = worker_info.id\n\n all_tensor_ids = rpc.api._all_gather(self._sharded_tensor_id)\n\n # Share the local shards to the entire world.\n futs = []\n rpc_rank = rpc.get_worker_info().id\n for rank in range(dist.get_world_size()):\n # Skip self.\n if rank == dist.get_rank():\n continue\n\n if len(self.local_shards()) != 0:\n rrefs: List[rpc.RRef[Shard]] = [rpc.RRef(shard) for shard in self.local_shards()]\n fut = rpc.rpc_async(\n rank,\n _register_remote_shards,\n args=(all_tensor_ids[rank_to_name[rank]], rrefs, rpc_rank))\n futs.append(fut)\n\n torch.futures.wait_all(futs)\n\n # Barrier for all RPCs to finish on all ranks.\n rpc.api._all_gather(None)\n\n def gather(\n self,\n dst: int = 0,\n out: Optional[torch.Tensor] = None,\n ) -> None:\n \"\"\"\n Creates a full :class:`Tensor` on rank ``dst`` by gathering all shards of the\n sharded tensor.\n\n The API needs to be called on all ranks in SPMD fashion. All ranks should have\n the same ``dst``. ``out`` should be a tensor of the same size as the overall\n size of the sharded tensor on ``dst`` and ``None`` on all other ranks.\n\n Args:\n dst(int): The rank where full tensor is constructed.\n Default: 0\n out (:class `torch.Tensor`, optional): The output full tensor.\n Must to be provided ONLY on ``dst`` rank.\n Default: ``None``\n \"\"\"\n rank = dist.get_rank(self._process_group)\n full_size = self.metadata().size\n _validate_output_tensor_for_gather(rank, dst, full_size, out)\n\n local_shards = self.local_shards()\n\n world_size = dist.get_world_size(self._process_group)\n\n gathered_shards = [None] * world_size\n # will revise this part with CPU support and use dist.gather()\n # once NCCL support for gather() is ready\n # https://github.com/pytorch/pytorch/issues/66187\n dist.all_gather_object(\n obj=local_shards,\n object_list=gathered_shards,\n group=self._process_group,\n )\n\n if rank == dst:\n dims = len(full_size)\n for shards in gathered_shards:\n if shards is None:\n raise RuntimeError(\n 'Gathered shards cannot be None on dst rank {dst}'\n )\n for shard in shards:\n metadata = shard.metadata\n tensor = shard.tensor\n\n out_narrow_view = out\n for dim in range(dims):\n out_narrow_view = out_narrow_view.narrow(\n dim,\n metadata.shard_offsets[dim],\n metadata.shard_sizes[dim],\n )\n\n out_narrow_view.copy_(tensor)\n\n @classmethod\n def _init_from_local_shards(\n cls,\n local_shards: List[Shard],\n *global_size,\n process_group=None,\n init_rrefs=False,\n ):\n # STEP 1: Validate the Shardmetadatas locally\n process_group = (\n process_group\n if process_group is not None\n else distributed_c10d._get_default_group()\n )\n current_rank = dist.get_rank(process_group)\n world_size = dist.get_world_size(process_group)\n\n local_sharded_tensor_metadata: Optional[ShardedTensorMetadata] = None\n global_tensor_size = _flatten_tensor_size(global_size)\n\n if len(local_shards) > 0:\n local_sharded_tensor_metadata = \\\n build_metadata_from_local_shards(local_shards, global_tensor_size, current_rank, process_group)\n\n # STEP 2. Validate metadata across ranks, and build a global sharded tensor\n # metadata by gathering local ShardedTensorMetadata\n gathered_metadatas: List[Optional[ShardedTensorMetadata]] = []\n if world_size > 1:\n gathered_metadatas = [None for _ in range(world_size)]\n\n dist.all_gather_object(\n gathered_metadatas,\n local_sharded_tensor_metadata,\n group=process_group\n )\n else:\n gathered_metadatas = [local_sharded_tensor_metadata]\n\n global_sharded_tensor_metadata = build_global_metadata(gathered_metadatas)\n\n # STEP 3: Validation done, create the actual ShardedTensor and populate fields\n # prepare initialization\n sharded_tensor = cls.__new__(cls)\n sharded_tensor._prepare_init(process_group=process_group, init_rrefs=init_rrefs)\n\n # add to metadata and local_shards\n sharded_tensor._metadata = global_sharded_tensor_metadata\n sharded_tensor._local_shards = local_shards\n # make a EnumerableShardingSpec for sharded tensors that initialized from this API.\n # TODO: make sharding spec a ChunkShardingSpec by inferring from the metadata list.\n # see issue https://github.com/pytorch/pytorch/issues/67244\n sharded_tensor._sharding_spec = EnumerableShardingSpec(global_sharded_tensor_metadata.shards_metadata)\n\n # run post initialization, i.e. map registration, rpc initialization\n sharded_tensor._post_init()\n return sharded_tensor\n\n @classmethod\n def _init_from_local_shards_and_global_metadata(\n cls,\n local_shards: List[Shard],\n sharded_tensor_metadata: ShardedTensorMetadata,\n process_group=None,\n init_rrefs=False,\n ) -> \"ShardedTensor\":\n \"\"\"\n Initialize a ShardedTensor with local shards and a global\n ShardedTensorMetadata built on each rank.\n\n Warning: This API is experimental and subject to change. It does\n not do cross rank validations, and fully rely on the user\n for the correctness of sharded_tensor_metadata on each rank\n \"\"\"\n process_group = (\n process_group\n if process_group is not None\n else distributed_c10d._get_default_group()\n )\n current_rank = dist.get_rank(process_group)\n\n shards_metadata = sharded_tensor_metadata.shards_metadata\n tensor_properties = sharded_tensor_metadata.tensor_properties\n\n if len(shards_metadata) == 0:\n raise ValueError(\"shards_metadata must not be empty!\")\n\n if tensor_properties.layout != torch.strided:\n raise ValueError('Only torch.strided layout is currently supported')\n\n sharded_tensor = cls.__new__(cls)\n sharded_tensor._prepare_init(process_group=process_group, init_rrefs=init_rrefs)\n\n sharded_tensor._metadata = sharded_tensor_metadata\n\n local_shard_metadatas = []\n\n def _raise_if_mismatch(expected, actual, prop_name, rank, is_property=False):\n tensor_property_or_metadata = \"tensor property\" if is_property else \"local ShardMetadata\"\n if expected != actual:\n raise ValueError(f\"Local shards' tensor {prop_name} property is incompatible with \"\n f\"{tensor_property_or_metadata} on rank {rank}: \"\n f\"{tensor_property_or_metadata} {prop_name}={expected}, \"\n f\"local shard tensor {prop_name}={actual}.\")\n\n # collect local shard metadatas from the global sharded_tensor_metadata\n for shard_metadata in shards_metadata: # type: ignore[attr-defined]\n rank, local_device = _parse_and_validate_remote_device(sharded_tensor._process_group, shard_metadata.placement)\n\n if current_rank == rank:\n local_shard_metadatas.append(shard_metadata)\n\n if len(local_shards) != len(local_shard_metadatas):\n raise RuntimeError(\n f'Number of local shards ({len(local_shards)}) does not match number of local '\n f'shards metadata in sharded_tensor_metadata ({len(local_shard_metadatas)}) '\n f'on rank ({current_rank}) '\n )\n\n for shard in local_shards:\n shard_meta = shard.metadata\n local_shard_tensor = shard.tensor\n rank, local_device = _parse_and_validate_remote_device(sharded_tensor._process_group, shard_meta.placement)\n\n # validate if shard_meta in the metadatas collected from sharded_tensor_metadata\n assert shard_meta in local_shard_metadatas, \\\n \"local shard metadata not in sharded_tensor_metadata!\"\n\n _raise_if_mismatch(tensor_properties.layout, local_shard_tensor.layout, \"layout\", current_rank, True)\n if not local_shard_tensor.is_contiguous():\n raise ValueError('Only torch.contiguous_format memory_format is currently supported')\n\n _raise_if_mismatch(shard_meta.shard_sizes, list(local_shard_tensor.size()), \"size\", current_rank)\n _raise_if_mismatch(tensor_properties.pin_memory, local_shard_tensor.is_pinned(), \"pin_memory\", current_rank, True)\n _raise_if_mismatch(local_device, local_shard_tensor.device, \"device\", current_rank)\n _raise_if_mismatch(tensor_properties.dtype, local_shard_tensor.dtype, \"dtype\", current_rank, True)\n _raise_if_mismatch(\n tensor_properties.requires_grad, local_shard_tensor.requires_grad, \"requires_grad\", current_rank, True)\n\n # check if shards_metadata have overlap shards\n validate_non_overlapping_shards_metadata(shards_metadata)\n\n # check if the shards_metadata is compatible with overall size of the sharded tensor.\n check_tensor(shards_metadata, list(sharded_tensor_metadata.size))\n\n # done validation, add local_shards\n sharded_tensor._local_shards = local_shards\n # make a EnumerableShardingSpec for sharded tensors that initialized from this API.\n # TODO: make sharding spec a ChunkShardingSpec by inferring from the metadata list.\n # see issue https://github.com/pytorch/pytorch/issues/67244\n sharded_tensor._sharding_spec = EnumerableShardingSpec(shards_metadata)\n\n # run post initialization, i.e. map registration, rpc initialization\n sharded_tensor._post_init()\n return sharded_tensor\n\n\n def _init_chunked(self, dims, tensor_init_params: TensorInitParams, ):\n current_rank = dist.get_rank(self._process_group)\n sharding_dim = self._sharding_spec.dim # type: ignore[attr-defined]\n\n # Validate the sharding spec.\n if not isinstance(sharding_dim, int):\n raise ValueError(\n f\"Sharding dim needs to be an integer, found: {sharding_dim}\"\n )\n if sharding_dim >= len(dims) or sharding_dim < -len(dims):\n raise ValueError(f\"Invalid sharding dim: {sharding_dim}\")\n\n dim_size = dims[sharding_dim]\n remote_devices = self._sharding_spec.placements # type: ignore[attr-defined]\n chunks = len(remote_devices)\n # split_size computed similar to 'torch.chunk'\n split_size = get_split_size(dim_size, chunks)\n\n shards_metadata = []\n for idx, remote_device in enumerate(remote_devices):\n rank, local_device = _parse_and_validate_remote_device(self._process_group, remote_device)\n\n # Adjust the sharding dim for this rank.\n sharded_dim_size = get_chunked_dim_size(dim_size, split_size, idx)\n\n if sharded_dim_size > 0:\n # Build sharding_metadata.\n\n # deepcopy for modification.\n rank_dims = dims.copy()\n\n rank_offsets = [0] * len(dims)\n rank_offsets[sharding_dim] = split_size * idx\n rank_dims[sharding_dim] = sharded_dim_size\n\n shard_metadata = ShardMetadata(rank_offsets, rank_dims, remote_device)\n shards_metadata.append(shard_metadata)\n\n # Build the local shard for the current rank if it is involved in the sharding spec.\n if current_rank == rank:\n # Initialize the local shard.\n local_shard = _create_tensor_from_params(\n *rank_dims, local_device=local_device, tensor_init_params=tensor_init_params)\n self._local_shards.append(Shard(local_shard, shard_metadata))\n\n # Build overall metadata\n self._metadata = ShardedTensorMetadata(\n shards_metadata, dims, tensor_init_params.tensor_properties, )\n\n def _init_enumerable(self, dims, tensor_init_params: TensorInitParams):\n # Validate the sharding spec is compatible with the tensor.\n check_tensor(self._sharding_spec.shards, dims) # type: ignore[attr-defined]\n\n current_rank = dist.get_rank(self._process_group)\n\n shards_metadata = []\n for shard_metadata in self._sharding_spec.shards: # type: ignore[attr-defined]\n rank, local_device = _parse_and_validate_remote_device(self._process_group, shard_metadata.placement)\n shards_metadata.append(shard_metadata)\n\n if current_rank == rank:\n # Initialize the local shard.\n local_shard = _create_tensor_from_params(\n *shard_metadata.shard_sizes, local_device=local_device,\n tensor_init_params=tensor_init_params)\n self._local_shards.append(Shard(local_shard, shard_metadata))\n\n # Build overall metadata\n self._metadata = ShardedTensorMetadata(\n shards_metadata, dims, tensor_init_params.tensor_properties, )\n\n def sharding_spec(self) -> ShardingSpec:\n \"\"\"\n Returns the ShardingSpec for the tensor.\n \"\"\"\n return self._sharding_spec\n\n def __torch_function__(self, func, types, args=(), kwargs=None):\n if func in _SHARDED_OPS:\n return _SHARDED_OPS[func](types, args, kwargs, self._process_group)\n raise RuntimeError(\n f\"torch function '{func.__name__}', with args: {args} and \"\n f\"kwargs: {kwargs} not supported for ShardedTensor!\")\n\n def metadata(self) -> ShardedTensorMetadata:\n \"\"\"\n Returns a :class:`ShardedTensorMetadata` object corresponding to the\n metadata for the entire tensor.\n \"\"\"\n return self._metadata\n\n def local_shards(self) -> List[Shard]:\n \"\"\"\n Returns a list of :class:`Shard' corresponding to the\n local shards for this rank. Returns an empty list if the current rank\n does not host any shards for this Tensor.\n \"\"\"\n return self._local_shards\n\n def size(self, dim: int = None) -> Union[torch.Size, int]:\n \"\"\"\n Returns a :Union:`[torch.Size, int]` which represents the size of the tensor.\n The dimension can be specified.\n\n Args:\n dim (int, optional): the dimension over which the size represents.\n If specified, it returns the size of the given dimension.\n If not, it returns a subclass of tuple.\n Default: ``None``\n\n Returns:\n A :Union:`[torch.Size, int]` represents the size of the tensor.\n \"\"\"\n size = self._metadata.size\n if dim is None:\n return size\n if dim < 0 or dim >= len(size):\n raise ValueError(\n f\"Argument ``dim`` must be within the range of tensor dimensions [0, {len(size)})\"\n )\n return size[dim]\n\n\n def is_pinned(self) -> bool:\n \"\"\"\n Returns True if the sharded tensor (each local shard) resides in pinned memory.\n \"\"\"\n return self._metadata.tensor_properties.pin_memory\n\n def is_contiguous(self) -> bool:\n \"\"\"\n Returns True if the sharded tensor (each local shard) is contiguous in memory\n in the order specified by memory format.\n \"\"\"\n return self._metadata.tensor_properties.memory_format == torch.contiguous_format\n\n @property\n def shape(self):\n return self._metadata.size\n\n @property\n def requires_grad(self):\n return self._metadata.tensor_properties.requires_grad\n\n @property\n def dtype(self):\n return self._metadata.tensor_properties.dtype\n\n @property\n def layout(self):\n return self._metadata.tensor_properties.layout\n\n def _register_remote_shards(self, remote_shards: List[rpc.RRef[Shard]], rpc_rank: int):\n self._remote_shards[rpc_rank] = remote_shards\n\n def remote_shards(self) -> Dict[int, List[rpc.RRef[Shard]]]:\n \"\"\"\n Returns a Dict[int, RRef] with keys being the RPC rank and values\n being RRefs to shards on that rank. Need to initialize the\n RPC framework for this functionality.\n\n Raises an exception if ShardedTensor was created with ``init_rrefs=False``\n \"\"\"\n if not self._init_rrefs:\n raise RuntimeError(\n 'ShardedTensor created with init_rrefs=False, no RRefs to remote shards available'\n )\n return self._remote_shards\n\n def __hash__(self):\n return id(self)\n\n def __repr__(self):\n return f'ShardedTensor({self._metadata})'\n\n @dataclass\n class ProcessGroupState:\n \"\"\"\n State for ser-de of process group\n \"\"\"\n local_rank: int\n global_rank: int\n local_world_size: int\n global_world_size: int\n\n def __getstate__(self):\n pg_state = ShardedTensor.ProcessGroupState(\n distributed_c10d.get_rank(self._process_group),\n distributed_c10d.get_rank(),\n distributed_c10d.get_world_size(self._process_group),\n distributed_c10d.get_world_size(),\n )\n\n return self._local_shards, self._metadata, pg_state, self._sharding_spec, self._init_rrefs\n\n def __setstate__(self, state):\n self._sharded_tensor_id = None\n if not distributed_c10d.is_initialized():\n raise RuntimeError(\n 'Need to initialize default process group using '\n '\"init_process_group\" before loading ShardedTensor')\n\n self._local_shards, self._metadata, pg_state, self._sharding_spec, self._init_rrefs = state\n\n # Setup process group\n self._process_group = get_current_process_group()\n\n # Validate process group.\n local_rank = distributed_c10d.get_rank(self._process_group)\n if pg_state.local_rank != local_rank:\n raise RuntimeError(\n f'Local rank at save time was {pg_state.local_rank}, but at '\n f'load time was {local_rank}')\n\n global_rank = distributed_c10d.get_rank()\n if pg_state.global_rank != global_rank:\n raise RuntimeError(\n f'Global rank at save time was {pg_state.global_rank}, but at '\n f'load time was {global_rank}')\n\n local_world_size = distributed_c10d.get_world_size(self._process_group)\n if pg_state.local_world_size != local_world_size:\n raise RuntimeError(\n f'Local world size at save time was {pg_state.local_world_size}, '\n f'but at load time was {local_world_size}')\n\n global_world_size = distributed_c10d.get_world_size()\n if pg_state.global_world_size != global_world_size:\n raise RuntimeError(\n f'Global world size at save time was {pg_state.global_world_size}, '\n f'but at load time was {global_world_size}')\n\n self._post_init()\n\n\ndef _create_tensor_from_params(*size, local_device, tensor_init_params: TensorInitParams):\n \"\"\" Helper to construct tensor from size, device and common params. \"\"\"\n\n create_op = tensor_init_params.create_op\n dtype = tensor_init_params.tensor_properties.dtype\n layout = tensor_init_params.tensor_properties.layout\n requires_grad = tensor_init_params.tensor_properties.requires_grad\n memory_format = tensor_init_params.tensor_properties.memory_format\n pin_memory = tensor_init_params.tensor_properties.pin_memory\n\n if create_op == CreateOp.ONES:\n return torch.ones(*size, dtype=dtype, layout=layout,\n device=local_device, pin_memory=pin_memory,\n requires_grad=requires_grad,)\n elif create_op == CreateOp.EMPTY:\n return torch.empty(*size, dtype=dtype, layout=layout,\n device=local_device, requires_grad=requires_grad,\n # NB: memory_format param is not accepted by torch.ones\n memory_format=memory_format, pin_memory=pin_memory,)\n elif tensor_init_params.create_op == CreateOp.ZEROS:\n return torch.zeros(*size,\n dtype=dtype,\n layout=layout,\n device=local_device,\n pin_memory=pin_memory,\n requires_grad=requires_grad,)\n elif tensor_init_params.create_op == CreateOp.RAND:\n return torch.rand(*size,\n dtype=dtype,\n layout=layout,\n device=local_device,\n pin_memory=pin_memory,\n requires_grad=requires_grad,)\n elif tensor_init_params.create_op == CreateOp.FULL:\n return torch.full(size=size,\n fill_value=tensor_init_params.fill_value,\n layout=layout,\n dtype=dtype,\n requires_grad=requires_grad,\n device=local_device, )\n else:\n raise ValueError(f'Unsupported create_op: {tensor_init_params.create_op}')\n", "# Owner(s): [\"oncall: aiacc\"]\n\nimport operator\n\nimport torch # isort:skip\nimport torch.fx # isort:skip\n\nimport torch.fx.experimental.fx_acc.acc_ops as acc_ops\nimport torch.fx.passes.operator_support as op_support\nimport torch.fx.passes.shape_prop as shape_prop\nfrom torch.fx.experimental.fx2trt.tools.trt_splitter import TRTSplitter\nfrom torch.fx.passes import splitter_base\nfrom torch.fx.experimental.fx_acc import acc_tracer\nfrom torch.testing._internal.common_utils import TestCase, run_tests\n\n\nERROR_MSG_NO_ACC_MODULE = \"FX split failed: Did not find any ACC submodule!\"\nERROR_MSG_MULTI_ACC_MODULES = \"FX split failed: Found more than one ACC submodules!\"\nACC_SUBMODULE_PREFIX = \"_run_on_acc_\"\n\n# Check if the split result has expected number of ACC submodule. If not, raise runtime error;\ndef verify_split_model(\n mod: torch.fx.GraphModule, acc_submodule_keyword: str = ACC_SUBMODULE_PREFIX, expected_number: int = 1,\n) -> None:\n acc_submodule_num = 0\n for name, _ in mod.named_children():\n if name.startswith(acc_submodule_keyword):\n acc_submodule_num = acc_submodule_num + 1\n\n if acc_submodule_num < expected_number:\n raise RuntimeError(ERROR_MSG_NO_ACC_MODULE)\n elif acc_submodule_num > expected_number:\n raise RuntimeError(ERROR_MSG_MULTI_ACC_MODULES)\n\ndef find_inputs(module):\n return [n for n in module.graph.nodes if n.op == \"placeholder\"]\n\n\ndef find_fun_calls(module, target):\n return [\n n for n in module.graph.nodes if n.op == \"call_function\" and n.target == target\n ]\n\n\ndef find_output(module):\n return next(n for n in module.graph.nodes if n.op == \"output\")\n\n\nTENSOR_SIZE_DUMMY = \"tensor_size_dummy\"\n\n\ndef find_call_targets(module: torch.fx.GraphModule):\n result = set()\n for n in module.graph.nodes:\n n: torch.fx.Node\n if n.op in {\"call_module\", \"call_function\", \"call_method\"}:\n result.add(n.target)\n return result\n\n\n# We test both FxNetSplitOnly and FxNetSplitter here, since they share most\n# functionalities. The only difference is that FxNetSplitOnly does not implement\n# split_preview() related functions, while FxNetSplitter does.\nclass TestSplit(TestCase):\n def test_demo(self):\n \"\"\"\n ==> b ==>\n // \\\\\n a d\n \\\\ //\n ==> c ==>\n \"\"\"\n\n class SimpleModule(torch.nn.Module):\n def forward(self, a):\n b = torch.sin(a)\n c = torch.cos(a)\n d = b + c\n return d\n\n mod = acc_tracer.trace(SimpleModule(), torch.randn(2, 3))\n\n # Making b and c run on ACC\n splitter = TRTSplitter(\n mod,\n (torch.randn(2, 3),),\n op_support_with_support_dict(\n {\n \"acc_ops.sin\": None,\n \"acc_ops.cos\": None,\n }\n ),\n )\n\n st_split = splitter()\n\n [arg] = find_inputs(st_split)\n\n # First subgraph calculates b = sin(a) and c = cos(a) on ACC\n [sin] = find_fun_calls(st_split._run_on_acc_0, acc_ops.sin)\n self.assertEqual(arg.name, sin.kwargs[\"input\"].name)\n\n [cos] = find_fun_calls(st_split._run_on_acc_0, acc_ops.cos)\n self.assertEqual(arg.name, cos.kwargs[\"input\"].name)\n\n # Second subgraph calculates d = b + c on CPU\n [add] = find_fun_calls(st_split._run_on_gpu_1, acc_ops.add)\n self.assertEqual(sin.name, add.kwargs[\"input\"].name)\n self.assertEqual(cos.name, add.kwargs[\"other\"].name)\n\n def test_mod_with_getattr(self):\n \"\"\"\n CPU subgraph should have get_attr for self.a while ACC subgraph\n should have get_attr for self.b.\n \"\"\"\n\n class SimpleModule(torch.nn.Module):\n def __init__(self):\n super().__init__()\n self.a = torch.randn(1, 1, 1, 1)\n self.b = torch.randn(1, 1, 1, 1)\n self.conv = torch.nn.Conv2d(1, 1, 1)\n self.linear = torch.nn.Linear(1, 1)\n\n def forward(self, x):\n x = x + self.a\n x = self.conv(x)\n return self.linear(x - self.b)\n\n mod = acc_tracer.trace(SimpleModule(), torch.randn(1, 1, 1, 1))\n mod.eval()\n\n splitter = TRTSplitter(\n mod,\n (torch.randn(1, 1, 1, 1),),\n op_support_with_support_dict(\n {\n \"acc_ops.linear\": None,\n \"acc_ops.sub\": None,\n }\n ),\n )\n\n def test_splitter(splitter):\n st_split = splitter()\n verify_split_model(st_split)\n # Should be \"a\", \"conv.weight\", \"conv.bias\".\n get_attr_nodes = [\n node.target\n for node in st_split._run_on_gpu_0.graph.nodes\n if node.op == \"get_attr\"\n ]\n assert len(get_attr_nodes) == 3 and \"a\" in get_attr_nodes\n\n # Should be \"b\", \"conv.weight\", \"conv.bias\".\n get_attr_nodes = [\n node.target\n for node in st_split._run_on_acc_1.graph.nodes\n if node.op == \"get_attr\"\n ]\n assert len(get_attr_nodes) == 3 and \"b\" in get_attr_nodes\n\n test_splitter(splitter)\n\n def test_nothing_to_split(self):\n class SimpleModule(torch.nn.Module):\n def forward(self, a):\n return a\n\n mod = acc_tracer.trace(SimpleModule(), torch.randn(2, 3))\n\n # Mark any operation as runnable on ACC\n class CustomOpSupport(op_support.OperatorSupportBase):\n def is_node_supported(self, submodules, node):\n return True\n\n splitter = TRTSplitter(\n mod, (torch.randn(2, 3),), CustomOpSupport()\n )\n\n def test_splitter(splitter):\n st_split = splitter()\n try:\n verify_split_model(st_split)\n except RuntimeError as err:\n self.assertEqual(\n str(err), ERROR_MSG_NO_ACC_MODULE\n )\n self.assertEqual(splitter.module.__dict__.keys(), st_split.__dict__.keys())\n\n test_splitter(splitter)\n\n def test_multi_output(self):\n class MultiOutputModule(torch.nn.Module):\n def forward(self, x):\n res, ind = torch.topk(x, 3)\n return torch.sigmoid(res), ind\n\n mod = acc_tracer.trace(MultiOutputModule(), torch.randn(2, 3))\n\n # Mark any operation as runnable on ACC\n class CustomOpSupport(op_support.OperatorSupportBase):\n def is_node_supported(self, submodules, node):\n return True\n\n splitter = TRTSplitter(\n mod, (torch.randn(2, 3),), CustomOpSupport()\n )\n\n def test_splitter(splitter):\n st_split = splitter()\n verify_split_model(st_split)\n [arg] = find_inputs(st_split)\n\n # There is only one subgraph that executes topk and sigmoid on ACC\n [topk] = find_fun_calls(st_split._run_on_acc_0, acc_ops.topk)\n self.assertEqual(arg.name, topk.kwargs[\"input\"].name)\n self.assertEqual(3, topk.kwargs[\"k\"])\n\n [topk_res1, topk_res2] = find_fun_calls(\n st_split._run_on_acc_0, acc_ops.getitem\n )\n\n [sigmoid] = find_fun_calls(st_split._run_on_acc_0, acc_ops.sigmoid)\n self.assertIn(\n sigmoid.kwargs[\"input\"].name, {topk_res1.name, topk_res2.name}\n )\n\n # Main graph returns a tuple\n output = find_output(st_split._run_on_acc_0)\n self.assertLess(\n {output.args[0][0].name, output.args[0][1].name},\n {topk_res1.name, topk_res2.name, sigmoid.name},\n )\n\n test_splitter(splitter)\n\n def test_nested_modules(self):\n \"\"\"\n x\n // \\\\\n // \\\\\n relu(x) sin(x)\n \\\\ //\n \\\\ //\n relu(x) + sin(x)\n \"\"\"\n\n class ReluModule(torch.nn.Module):\n def forward(self, x):\n return torch.relu(x)\n\n class SinModule(torch.nn.Module):\n def forward(self, x):\n return torch.sin(x)\n\n class TestModule3(torch.nn.Module):\n def __init__(self, relu_module, sin_module):\n super().__init__()\n self.relu_module = relu_module\n self.sin_module = sin_module\n\n def forward(self, x):\n return self.relu_module(x) + self.sin_module(x)\n\n mod = acc_tracer.trace(TestModule3(ReluModule(), SinModule()), torch.randn(2, 3))\n\n # Making sin(x) run on ACC\n splitter = TRTSplitter(\n mod,\n (torch.randn(2, 3),),\n op_support_with_support_dict(\n {\n \"acc_ops.sin\": None,\n }\n ),\n )\n\n def test_splitter(splitter):\n st_split = splitter()\n verify_split_model(st_split)\n [arg] = find_inputs(st_split)\n\n # First subgraph calculates relu(x) on CPU\n [relu] = find_fun_calls(st_split._run_on_gpu_0, acc_ops.relu)\n self.assertEqual(arg.name, relu.kwargs[\"input\"].name)\n\n # Second subgraph calculates sin(x) on ACC\n [sin] = find_fun_calls(st_split._run_on_acc_1, acc_ops.sin)\n self.assertEqual(arg.name, sin.kwargs[\"input\"].name)\n\n # Third subgraph calculates sum on CPU\n [add] = find_fun_calls(st_split._run_on_gpu_2, acc_ops.add)\n self.assertEqual(relu.name, add.kwargs[\"input\"].name)\n self.assertEqual(sin.name, add.kwargs[\"other\"].name)\n\n # Checking that results of applying split module will be the same\n tensor = torch.randn(5)\n self.assertTrue(torch.equal(mod(tensor), st_split(tensor)))\n\n test_splitter(splitter)\n\n def test_longer_chain(self):\n \"\"\"\n sin relu cos sigmoid tanh\n a ====> b =====> c ====> d ========> e =====> f\n \"\"\"\n\n class TestModule(torch.nn.Module):\n def forward(self, a):\n b = torch.sin(a)\n c = torch.relu(b)\n d = torch.cos(c)\n e = torch.sigmoid(d)\n f = torch.tanh(e)\n return f\n\n mod = acc_tracer.trace(TestModule(), torch.randn(2, 3))\n\n # Making relu and sigmoid execute on ACC\n splitter = TRTSplitter(\n mod,\n (torch.randn(2, 3),),\n op_support_with_support_dict(\n {\n \"acc_ops.relu\": None,\n \"acc_ops.sigmoid\": None,\n }\n ),\n )\n\n def test_splitter(splitter):\n st_split = splitter()\n try:\n verify_split_model(st_split)\n except RuntimeError as err:\n self.assertEqual(\n str(err), ERROR_MSG_MULTI_ACC_MODULES\n )\n [arg] = find_inputs(st_split)\n\n # First subgraph calculates b = sin(a) on CPU\n [sin] = find_fun_calls(st_split._run_on_gpu_0, acc_ops.sin)\n self.assertEqual(arg.name, sin.kwargs[\"input\"].name)\n\n # Second subgraph calculates c = relu(b) on ACC\n [relu] = find_fun_calls(st_split._run_on_acc_1, acc_ops.relu)\n self.assertEqual(sin.name, relu.kwargs[\"input\"].name)\n\n # Third subgraph calculates d = cos(c) on CPU\n [cos] = find_fun_calls(st_split._run_on_gpu_2, acc_ops.cos)\n self.assertEqual(relu.name, cos.kwargs[\"input\"].name)\n\n # Fourth subgraph calculates e = sigmoid(d) on ACC\n [sigmoid] = find_fun_calls(st_split._run_on_acc_3, acc_ops.sigmoid)\n self.assertEqual(cos.name, sigmoid.kwargs[\"input\"].name)\n\n # Fifth subgraph calculates f = tanh(e) on CPU\n [tanh] = find_fun_calls(st_split._run_on_gpu_4, acc_ops.tanh)\n self.assertEqual(sigmoid.name, tanh.kwargs[\"input\"].name)\n\n test_splitter(splitter)\n\n def test_min_acc_module_size(self):\n \"\"\"\n sin relu cos sigmoid tanh\n a ====> b =====> c ====> d ========> e =====> f\n\n We set sin, cos and tanh as acc node but also set min_acc_module_size to 2\n and expect the whole module stay on CPU.\n \"\"\"\n\n class TestModule(torch.nn.Module):\n def forward(self, a):\n b = torch.sin(a)\n c = torch.relu(b)\n d = torch.cos(c)\n e = torch.sigmoid(d)\n f = torch.tanh(e)\n return f\n\n mod = acc_tracer.trace(TestModule(), torch.randn(2, 3))\n\n # Set sin, cos and tanh as acc node and split with settings\n class CustomOpSupport(op_support.OperatorSupport):\n _support_dict = {\n \"acc_ops.sin\": None,\n \"acc_ops.cos\": None,\n \"acc_ops.tanh\": None,\n }\n\n # Create splitter setting and set min_acc_module_size to 2\n settings = splitter_base._SplitterSettingBase()\n settings.min_acc_module_size = 2\n splitter = TRTSplitter(\n mod,\n (torch.randn(2, 3),),\n op_support_with_support_dict(\n {\n \"acc_ops.sin\": None,\n \"acc_ops.cos\": None,\n \"acc_ops.tanh\": None,\n }\n ),\n settings,\n )\n\n def test_splitter(splitter):\n st_split = splitter()\n try:\n verify_split_model(st_split)\n except RuntimeError as err:\n self.assertEqual(\n str(err), ERROR_MSG_NO_ACC_MODULE\n )\n modules = list(st_split.named_modules())\n # Main module and a submodule\n assert len(modules) == 2\n\n assert modules[1][0] == \"_run_on_gpu_0\"\n\n test_splitter(splitter)\n\n def test_extend_acc_subgraph_after_split(self):\n class TestModule(torch.nn.Module):\n r\"\"\" a (input)\n |\n b\n / \\\n c d\n \\ /\n e\n / \\\n | (g1, g2, g3, g4)\n \\ / |\n f |\n \\ |\n h\n\n c and f are not runnable on acc while all other nodes are supported by acc.\n g1, g2, g3 and g4 should be in a fusion group, let's call it g.\n\n After split we have 2 cpu subgraphs (c) and (f), 3 acc subgraphs (b, d), (e, g) and (h).\n We expect 3 acc subgraphs (b), (d, e, g) and (h) after extend the second acc subgraph.\n And expect acc subgraphs stay the same after extend the third acc subgraph because of\n the unbreakable fusion group.\n \"\"\"\n\n def forward(self, a: torch.Tensor):\n b = a + a\n c = b - b\n d = b + b\n e = c + d\n\n # These four nodes should be in a fusion group\n g1 = e.size()\n g2 = g1[0]\n g3 = e + g2\n g4 = g3 + g2\n\n f = e - g3\n h = f + g4\n return h\n\n a = torch.randn(2)\n mod = acc_tracer.trace(TestModule(), (a,))\n\n # Allow all nodes expect subtract run on accelerator\n class CustomOpSupport(op_support.OperatorSupportBase):\n def is_node_supported(self, submodules, node):\n return op_support.get_node_target(submodules, node) != \"acc_ops.sub\"\n\n splitter = TRTSplitter(mod, (a,), CustomOpSupport())\n\n def test_splitter(splitter):\n # Manually tag nodes first in case split algorithm changes in the future\n nodes = list(splitter.module.graph.nodes)\n # b and d\n nodes[1].tag = \"acc_0\"\n nodes[3].tag = \"acc_0\"\n # c\n nodes[2].tag = \"cpu_1\"\n # e and g\n nodes[4].tag = \"acc_2\"\n nodes[5].tag = \"acc_2\"\n nodes[6].tag = \"acc_2\"\n nodes[7].tag = \"acc_2\"\n nodes[8].tag = \"acc_2\"\n # f\n nodes[9].tag = \"cpu_3\"\n # h\n nodes[10].tag = \"acc_4\"\n\n splitter.tags = [\"acc_0\", \"cpu_1\", \"acc_2\", \"cpu_3\", \"acc_4\"]\n split_module = splitter.split()\n try:\n verify_split_model(split_module, \"acc_\")\n except RuntimeError as err:\n self.assertEqual(\n str(err), ERROR_MSG_MULTI_ACC_MODULES\n )\n try:\n verify_split_model(split_module)\n except RuntimeError as err:\n self.assertEqual(\n str(err), ERROR_MSG_NO_ACC_MODULE\n )\n\n module_names = [name for name, _ in split_module.named_modules()]\n # Main module, 2 cpu submodules and 3 acc submodule\n assert len(module_names) == 6\n\n # 1 Placeholder, 2 Adds and 1 Output\n assert len(split_module.acc_0.graph.nodes) == 4\n # 2 Placeholder, 3 Adds, 1 Size, 1 GetItem and 1 Output\n assert len(split_module.acc_2.graph.nodes) == 8\n\n # Extend the second acc subgraph\n splitter.extend_acc_subgraph(\"acc_2\")\n extend_module = splitter.split()\n try:\n verify_split_model(extend_module, \"acc_\")\n except RuntimeError as err:\n self.assertEqual(\n str(err), ERROR_MSG_MULTI_ACC_MODULES\n )\n\n # 1 Placeholder, 1 Adds and 1 Output\n assert len(extend_module.acc_0.graph.nodes) == 3\n # 2 Placeholder, 4 Adds 1 Size, 1 GetItem and 1 Output\n assert len(extend_module.acc_2.graph.nodes) == 9\n\n # Extend the third acc subgraph\n splitter.extend_acc_subgraph(\"acc_4\")\n extend_module = splitter.split()\n try:\n verify_split_model(extend_module, \"acc_\")\n except RuntimeError as err:\n self.assertEqual(\n str(err), ERROR_MSG_MULTI_ACC_MODULES\n )\n\n assert len(extend_module.acc_2.graph.nodes) == 9\n # 2 Placeholder, 1 Adds and 1 Output\n assert len(extend_module.acc_4.graph.nodes) == 4\n\n test_splitter(splitter)\n\n def test_get_attr_into_output(self):\n \"\"\"\n Here we verify the case when get_attr node is consumed directly by the\n output. We don't expect any split to happen in this test, just want to\n make sure that the splitter code doesn't break.\n \"\"\"\n\n class TestModule(torch.nn.Module):\n def __init__(self):\n super().__init__()\n self.a = torch.randn(2, 3)\n\n def forward(self, x):\n return (x, self.a)\n\n # No need to put anything on ACC.\n class TestOperatorSupport:\n def is_node_supported(self, submodules, node):\n return False\n\n module_original = acc_tracer.trace(TestModule(), torch.randn(4, 5))\n\n splitter = TRTSplitter(\n module=module_original,\n sample_input=torch.randn(4, 5),\n operator_support=TestOperatorSupport(),\n )\n\n def test_splitter(splitter):\n module_split = splitter()\n try:\n verify_split_model(module_split)\n except RuntimeError as err:\n self.assertEqual(\n str(err), ERROR_MSG_NO_ACC_MODULE\n )\n\n output = find_output(module_split)\n # Second argument of the output should be get_attr.\n self.assertEqual(\"get_attr\", output.args[0][1].op)\n\n # Check if modules are equivalent.\n tensor = torch.randn(10, 20)\n result_original = module_original(tensor)\n result_split = module_split(tensor)\n self.assertTrue(torch.equal(result_original[0], result_split[0]))\n self.assertTrue(torch.equal(result_original[1], result_split[1]))\n\n test_splitter(splitter)\n\n def test_get_attr_into_starter_node(self):\n \"\"\"\n Here we verify the case when starter nodes depend on get_attr node only.\n We don't expect any split to happen in this test, just want to make sure\n that the splitter code doesn't break.\n \"\"\"\n\n class TestModule(torch.nn.Module):\n def __init__(self):\n super().__init__()\n self.a = torch.randn(2, 3)\n\n def forward(self):\n m = self.a + self.a\n o = m + m\n return o\n\n # No need to put anything on ACC.\n class TestOperatorSupport:\n def is_node_supported(self, submodules, node):\n return False\n\n module_original = acc_tracer.trace(TestModule(), torch.randn(2, 3))\n\n splitter = TRTSplitter(\n module=module_original,\n sample_input=torch.randn(2, 3),\n operator_support=TestOperatorSupport(),\n )\n\n def test_splitter(splitter):\n module_split = splitter()\n try:\n verify_split_model(module_split)\n except RuntimeError as err:\n self.assertEqual(\n str(err), ERROR_MSG_NO_ACC_MODULE\n )\n\n # Check if modules are equivalent.\n result_original = module_original()\n result_split = module_split()\n self.assertTrue(torch.equal(result_original, result_split))\n\n test_splitter(splitter)\n\n\nclass TestSplitComplexGraph(TestCase):\n \"\"\"\n a ======\n // \\\\ \\\\\n b c d\n \\\\ // //\n e //\n \\\\ //\n \\\\ //\n f\n \"\"\"\n\n class TestModule(torch.nn.Module):\n def forward(self, a):\n b = torch.sin(a)\n c = torch.relu(a)\n d = torch.cos(a)\n e = b + c\n f = e - d\n return f\n\n def test_split_complex_graph_1(self):\n mod = acc_tracer.trace(self.TestModule(), torch.randn(2, 3))\n\n # Making 'c' and 'd' run on ACC\n splitter = TRTSplitter(\n mod,\n (torch.randn(2, 3),),\n op_support_with_support_dict(\n {\n \"acc_ops.cos\": None,\n \"acc_ops.relu\": None,\n }\n ),\n )\n\n def test_splitter(splitter):\n st_split = splitter()\n verify_split_model(st_split)\n\n [arg] = find_inputs(st_split)\n\n # First subgraph calculates b = sin(a) on CPU\n [sin] = find_fun_calls(st_split._run_on_gpu_0, acc_ops.sin)\n self.assertEqual(arg.name, sin.kwargs[\"input\"].name)\n\n # Second subgraph calculates c = relu(a) and d = cos(a) on ACC\n [relu] = find_fun_calls(st_split._run_on_acc_1, acc_ops.relu)\n self.assertEqual(arg.name, relu.kwargs[\"input\"].name)\n\n [cos] = find_fun_calls(st_split._run_on_acc_1, acc_ops.cos)\n self.assertEqual(arg.name, cos.kwargs[\"input\"].name)\n\n # Third subgraph calculates the e = b + c and f = e - d on CPU\n [add] = find_fun_calls(st_split._run_on_gpu_2, acc_ops.add)\n self.assertEqual(sin.name, add.kwargs[\"input\"].name)\n self.assertEqual(relu.name, add.kwargs[\"other\"].name)\n\n [sub] = find_fun_calls(st_split._run_on_gpu_2, acc_ops.sub)\n self.assertEqual(add.name, sub.kwargs[\"input\"].name)\n self.assertEqual(cos.name, sub.kwargs[\"other\"].name)\n\n test_splitter(splitter)\n\n def test_split_complex_graph_2(self):\n module_nn = self.TestModule()\n module = acc_tracer.trace(module_nn, (torch.randn(2, 3),))\n\n # Making 'c', 'd' and 'e' run on ACC\n splitter = TRTSplitter(\n module,\n (torch.randn(2, 3),),\n op_support_with_support_dict(\n {\n \"acc_ops.cos\": None,\n \"acc_ops.relu\": None,\n \"acc_ops.add\": None,\n }\n ),\n )\n\n def test_splitter(splitter):\n module_fx_split = splitter()\n verify_split_model(module_fx_split)\n\n [arg] = find_inputs(module)\n\n # First subgraph calculates b = sin(a) on CPU\n [sin] = find_fun_calls(module_fx_split._run_on_gpu_0, acc_ops.sin)\n self.assertEqual(arg.name, sin.kwargs[\"input\"].name)\n\n # Second subgraph calculates c = relu(a), d = cos(a) and e = b + c on ACC\n [relu] = find_fun_calls(module_fx_split._run_on_acc_1, acc_ops.relu)\n self.assertEqual(arg.name, relu.kwargs[\"input\"].name)\n\n [cos] = find_fun_calls(module_fx_split._run_on_acc_1, acc_ops.cos)\n self.assertEqual(arg.name, cos.kwargs[\"input\"].name)\n\n [add] = find_fun_calls(module_fx_split._run_on_acc_1, acc_ops.add)\n self.assertEqual(sin.name, add.kwargs[\"input\"].name)\n self.assertEqual(relu.name, add.kwargs[\"other\"].name)\n\n # Third subgraph calculates f = e + d on CPU\n [sub] = find_fun_calls(module_fx_split._run_on_gpu_2, acc_ops.sub)\n self.assertEqual(add.name, sub.kwargs[\"input\"].name)\n self.assertEqual(cos.name, sub.kwargs[\"other\"].name)\n\n test_splitter(splitter)\n\n\nclass TestSplitNonTensorEdges(TestCase):\n \"\"\"\n a (relu)\n // \\\\\n (b1,b2) c (cos)\n \\\\ //\n d (add)\n ||\n e (sigmoid)\n \"\"\"\n\n # Note non-tensor edge between b2 and d\n class TestModule(torch.nn.Module):\n def forward(self, x):\n a = torch.relu(x)\n\n b1 = a.size()\n b2 = b1[0]\n\n c = torch.cos(a)\n\n d = b2 + c\n e = torch.sigmoid(d)\n return e\n\n def test_split_non_tensor_edges_1(self):\n test_data = torch.randn(2, 3)\n\n module_nn = acc_tracer.trace(self.TestModule(), (test_data,))\n\n # Making 'a', 'b1', 'b2', 'd' and 'e' run on ACC\n splitter = TRTSplitter(\n module_nn,\n (test_data,),\n op_support_with_support_dict(\n {\n \"acc_ops.relu\": None,\n \"acc_ops.sigmoid\": None,\n \"acc_ops.add\": None,\n \"acc_ops.getitem\": None,\n \"acc_ops.size\": None,\n }\n ),\n )\n\n def test_splitter(splitter):\n module_fx_split = splitter()\n try:\n verify_split_model(module_fx_split)\n except RuntimeError as err:\n self.assertEqual(\n str(err), ERROR_MSG_MULTI_ACC_MODULES\n )\n\n self.assertEqual(\n {acc_ops.relu}, find_call_targets(module_fx_split._run_on_acc_0)\n )\n\n self.assertEqual(\n {acc_ops.cos}, find_call_targets(module_fx_split._run_on_gpu_1)\n )\n\n self.assertEqual(\n {acc_ops.size, acc_ops.getitem, acc_ops.add, acc_ops.sigmoid},\n find_call_targets(module_fx_split._run_on_acc_2),\n )\n\n # Make sure we can compile to TorchScript\n module_jit = torch.jit.trace_module(module_fx_split, {\"forward\": test_data})\n self.assertTrue(torch.allclose(module_nn(test_data), module_jit(test_data)))\n\n test_splitter(splitter)\n\n def test_split_non_tensor_edges_2(self):\n test_data = torch.randn(2, 3)\n\n module_nn = acc_tracer.trace(self.TestModule(), (test_data,))\n\n # Making 'a', 'b1', 'b2', 'd' and 'e' run on ACC with limit on ACC\n # subgraph size\n settings = splitter_base._SplitterSettingBase()\n settings.min_acc_module_size = 2\n splitter = TRTSplitter(\n module_nn,\n (test_data,),\n op_support_with_support_dict(\n {\n \"acc_ops.relu\": None,\n \"acc_ops.sigmoid\": None,\n \"acc_ops.add\": None,\n \"acc_ops.getitem\": None,\n \"acc_ops.size\": None,\n }\n ),\n settings,\n )\n\n def test_splitter(splitter):\n module_fx_split = splitter()\n verify_split_model(module_fx_split)\n\n self.assertEqual(\n {acc_ops.relu, acc_ops.cos},\n find_call_targets(module_fx_split._run_on_gpu_0),\n )\n\n self.assertEqual(\n {acc_ops.size, acc_ops.getitem, acc_ops.add, acc_ops.sigmoid},\n find_call_targets(module_fx_split._run_on_acc_1),\n )\n\n # Make sure we can compile to TorchScript\n module_jit = torch.jit.trace_module(module_fx_split, {\"forward\": test_data})\n self.assertTrue(torch.allclose(module_nn(test_data), module_jit(test_data)))\n\n test_splitter(splitter)\n\n def test_split_non_tensor_edges_3(self):\n test_data = torch.randn(2, 3)\n\n module_nn = acc_tracer.trace(self.TestModule(), (test_data,),)\n\n # Making 'a', 'c', 'd' and 'e' run on ACC\n splitter = TRTSplitter(\n module_nn,\n (test_data,),\n op_support_with_support_dict(\n {\n \"acc_ops.relu\": None,\n \"acc_ops.sigmoid\": None,\n \"acc_ops.cos\": None,\n \"acc_ops.add\": None,\n }\n ),\n )\n\n def test_splitter(splitter):\n module_fx_split = splitter()\n try:\n verify_split_model(module_fx_split)\n except RuntimeError as err:\n self.assertEqual(\n str(err), ERROR_MSG_MULTI_ACC_MODULES\n )\n\n self.assertEqual(\n {acc_ops.relu, acc_ops.cos},\n find_call_targets(module_fx_split._run_on_acc_0),\n )\n\n self.assertEqual(\n {acc_ops.size, acc_ops.getitem, acc_ops.add},\n find_call_targets(module_fx_split._run_on_gpu_1),\n )\n\n self.assertEqual(\n {acc_ops.sigmoid},\n find_call_targets(module_fx_split._run_on_acc_2),\n )\n\n # Make sure we can compile to TorchScript\n module_jit = torch.jit.trace_module(module_fx_split, {\"forward\": test_data})\n self.assertTrue(torch.allclose(module_nn(test_data), module_jit(test_data)))\n\n test_splitter(splitter)\n\n def test_split_non_tensor_edges_4(self):\n test_data = torch.randn(2, 3)\n\n module_nn = acc_tracer.trace(self.TestModule(), (test_data,),)\n\n # Making 'a', 'c', 'd' and 'e' run on ACC with limit on ACC\n # subgraph size\n settings = splitter_base._SplitterSettingBase()\n settings.min_acc_module_size = 2\n splitter = TRTSplitter(\n module_nn,\n (test_data,),\n op_support_with_support_dict(\n {\n \"acc_ops.relu\": None,\n \"acc_ops.sigmoid\": None,\n \"acc_ops.cos\": None,\n \"acc_ops.add\": None,\n }\n ),\n settings,\n )\n\n def test_splitter(splitter):\n module_fx_split = splitter()\n verify_split_model(module_fx_split)\n\n self.assertEqual(\n {acc_ops.relu, acc_ops.cos},\n find_call_targets(module_fx_split._run_on_acc_0),\n )\n\n self.assertEqual(\n {acc_ops.size, acc_ops.getitem, acc_ops.add, acc_ops.sigmoid},\n find_call_targets(module_fx_split._run_on_gpu_1),\n )\n\n # Make sure we can compile to TorchScript\n module_jit = torch.jit.trace_module(module_fx_split, {\"forward\": test_data})\n self.assertTrue(torch.allclose(module_nn(test_data), module_jit(test_data)))\n\n test_splitter(splitter)\n\n\nclass TestAccNodesFinder(TestCase):\n def test_acc_nodes_finder_1(self):\n \"\"\"\n y ------------->\n |\n ----> b ---->\n x ----> a d\n ----> c ---->\n |\n z ------------->\n \"\"\"\n\n # Make a return non-tensor data\n class TestModule(torch.nn.Module):\n def forward(self, x, y, z):\n a1 = x.size()\n a1 = a1[0]\n\n b = y + a1\n c = z - a1\n\n d = b + c\n\n return d\n\n module_nn = TestModule()\n module_fx = torch.fx.symbolic_trace(module_nn)\n\n # Make a and c lowerable to ACC\n finder = torch.fx.passes.splitter_base.FxNetAccNodesFinder(\n module_fx,\n op_support_with_support_dict(\n {\n \"acc_ops.sub\": None,\n \"acc_ops.getitem\": None,\n \"acc_ops.size\": None,\n }\n ),\n False,\n )\n acc_nodes = finder()\n self.assertEqual(set(), acc_nodes, \"Shouldn't have ACC nodes\")\n\n\nclass TestAccFusionsFinder(TestCase):\n \"\"\"\n x\n / \\\\\n a b\n / | \\\\\n / | a2\n a0 a1 |\n | / |\n c |\n | |\n d |\n \\\\ /\n e\n \"\"\"\n\n class TestModule(torch.nn.Module):\n def forward(self, x):\n a = x.size()\n b = x + x\n\n a0 = a[0]\n a1 = a[1]\n a2 = a[2]\n c = x.view(a1, a0, -1)\n\n d = c + c\n e = d + a2\n return b, e\n\n def test_acc_fusions_finder_1(self):\n \"\"\"\n Assume every node is acc node. We should have one fusion group\n (a, a0, a1, a2, c, d, e).\n \"\"\"\n module_nn = self.TestModule()\n module_fx = torch.fx.symbolic_trace(module_nn)\n shape_prop.ShapeProp(module_fx).propagate(torch.randn(1, 1, 1))\n\n acc_node = {\n node\n for node in module_fx.graph.nodes\n if node.op in torch.fx.passes.tools_common.CALLABLE_NODE_OPS\n }\n\n fusions_finder = torch.fx.passes.splitter_base.FxNetAccFusionsFinder(\n module_fx,\n acc_node,\n )\n fusion_map = fusions_finder()\n\n self.assertEqual(len(fusion_map), 7)\n for _, v in fusion_map.items():\n self.assertEqual(len(v), 7)\n\n def test_acc_fusions_finder_2(self):\n \"\"\"\n Let b and d be cpu nodes. After fusion all nodes should be cpu nodes\n because d is included in the fusion group which force all other nodes\n in the same fusion group to be on CPU too.\n \"\"\"\n module_nn = self.TestModule()\n module_fx = torch.fx.symbolic_trace(module_nn)\n shape_prop.ShapeProp(module_fx).propagate(torch.randn(1, 1, 1))\n\n acc_node = {\n node for node in module_fx.graph.nodes if node.target == operator.add\n }\n fusions_finder = torch.fx.passes.splitter_base.FxNetAccFusionsFinder(\n module_fx,\n acc_node,\n )\n fusion_map = fusions_finder()\n self.assertEqual(len(fusion_map), 0)\n\n\n def test_start_with_acc_module_(self):\n \"\"\"\n sin relu cos sigmoid tanh\n a ====> b =====> c ====> d ========> e =====> f\n\n We set sin, relu and cos as acc node but also set min_acc_module_size to 2\n and expect the whole module stay on CPU.\n \"\"\"\n\n class TestModule(torch.nn.Module):\n def forward(self, a):\n b = torch.sin(a)\n c = torch.relu(b)\n d = torch.cos(c)\n e = torch.sigmoid(d)\n f = torch.tanh(e)\n return f\n\n mod = acc_tracer.trace(TestModule(), torch.randn(2, 3))\n\n # Set sin, cos and tanh as acc node and split with settings\n class CustomOpSupport(op_support.OperatorSupport):\n _support_dict = {\n \"acc_ops.sin\": None,\n \"acc_ops.cos\": None,\n \"acc_ops.relu\": None,\n }\n\n # Create splitter setting and set min_acc_module_size to 2\n settings = splitter_base._SplitterSettingBase()\n settings.min_acc_module_size = 2\n splitter = TRTSplitter(\n mod,\n (torch.randn(2, 3),),\n op_support_with_support_dict(\n {\n \"acc_ops.sin\": None,\n \"acc_ops.cos\": None,\n \"acc_ops.relu\": None,\n }\n ),\n settings,\n )\n\n def test_splitter(splitter):\n st_split = splitter()\n try:\n verify_split_model(st_split)\n except RuntimeError as err:\n self.assertEqual(\n str(err), ERROR_MSG_NO_ACC_MODULE\n )\n modules = list(st_split.named_modules())\n # Main module and a submodule\n assert len(modules) == 3\n\n assert modules[1][0] == \"_run_on_acc_0\"\n assert modules[2][0] == \"_run_on_gpu_1\"\n\n test_splitter(splitter)\n\n\ndef op_support_with_support_dict(support_dict: dict) -> op_support.OperatorSupportBase:\n return op_support.OperatorSupport(support_dict)\n\nif __name__ == '__main__':\n run_tests()\n", "import torch\nfrom . import _functional as F\nfrom .optimizer import Optimizer\n\n\nclass AdamW(Optimizer):\n r\"\"\"Implements AdamW algorithm.\n\n .. math::\n \\begin{aligned}\n &\\rule{110mm}{0.4pt} \\\\\n &\\textbf{input} : \\gamma \\text{(lr)}, \\: \\beta_1, \\beta_2\n \\text{(betas)}, \\: \\theta_0 \\text{(params)}, \\: f(\\theta) \\text{(objective)},\n \\: \\epsilon \\text{ (epsilon)} \\\\\n &\\hspace{13mm} \\lambda \\text{(weight decay)}, \\: \\textit{amsgrad},\n \\: \\textit{maximize} \\\\\n &\\textbf{initialize} : m_0 \\leftarrow 0 \\text{ (first moment)}, v_0 \\leftarrow 0\n \\text{ ( second moment)}, \\: \\widehat{v_0}^{max}\\leftarrow 0 \\\\[-1.ex]\n &\\rule{110mm}{0.4pt} \\\\\n &\\textbf{for} \\: t=1 \\: \\textbf{to} \\: \\ldots \\: \\textbf{do} \\\\\n\n &\\hspace{5mm}\\textbf{if} \\: \\textit{maximize}: \\\\\n &\\hspace{10mm}g_t \\leftarrow -\\nabla_{\\theta} f_t (\\theta_{t-1}) \\\\\n &\\hspace{5mm}\\textbf{else} \\\\\n &\\hspace{10mm}g_t \\leftarrow \\nabla_{\\theta} f_t (\\theta_{t-1}) \\\\\n &\\hspace{5mm} \\theta_t \\leftarrow \\theta_{t-1} - \\gamma \\lambda \\theta_{t-1} \\\\\n &\\hspace{5mm}m_t \\leftarrow \\beta_1 m_{t-1} + (1 - \\beta_1) g_t \\\\\n &\\hspace{5mm}v_t \\leftarrow \\beta_2 v_{t-1} + (1-\\beta_2) g^2_t \\\\\n &\\hspace{5mm}\\widehat{m_t} \\leftarrow m_t/\\big(1-\\beta_1^t \\big) \\\\\n &\\hspace{5mm}\\widehat{v_t} \\leftarrow v_t/\\big(1-\\beta_2^t \\big) \\\\\n &\\hspace{5mm}\\textbf{if} \\: amsgrad \\\\\n &\\hspace{10mm}\\widehat{v_t}^{max} \\leftarrow \\mathrm{max}(\\widehat{v_t}^{max},\n \\widehat{v_t}) \\\\\n &\\hspace{10mm}\\theta_t \\leftarrow \\theta_t - \\gamma \\widehat{m_t}/\n \\big(\\sqrt{\\widehat{v_t}^{max}} + \\epsilon \\big) \\\\\n &\\hspace{5mm}\\textbf{else} \\\\\n &\\hspace{10mm}\\theta_t \\leftarrow \\theta_t - \\gamma \\widehat{m_t}/\n \\big(\\sqrt{\\widehat{v_t}} + \\epsilon \\big) \\\\\n &\\rule{110mm}{0.4pt} \\\\[-1.ex]\n &\\bf{return} \\: \\theta_t \\\\[-1.ex]\n &\\rule{110mm}{0.4pt} \\\\[-1.ex]\n \\end{aligned}\n\n For further details regarding the algorithm we refer to `Decoupled Weight Decay Regularization`_.\n\n Args:\n params (iterable): iterable of parameters to optimize or dicts defining\n parameter groups\n lr (float, optional): learning rate (default: 1e-3)\n betas (Tuple[float, float], optional): coefficients used for computing\n running averages of gradient and its square (default: (0.9, 0.999))\n eps (float, optional): term added to the denominator to improve\n numerical stability (default: 1e-8)\n weight_decay (float, optional): weight decay coefficient (default: 1e-2)\n amsgrad (boolean, optional): whether to use the AMSGrad variant of this\n algorithm from the paper `On the Convergence of Adam and Beyond`_\n (default: False)\n maximize (bool, optional): maximize the params based on the objective, instead of\n minimizing (default: False)\n\n .. _Decoupled Weight Decay Regularization:\n https://arxiv.org/abs/1711.05101\n .. _On the Convergence of Adam and Beyond:\n https://openreview.net/forum?id=ryQu7f-RZ\n \"\"\"\n\n def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8,\n weight_decay=1e-2, amsgrad=False, *, maximize: bool = False):\n if not 0.0 <= lr:\n raise ValueError(\"Invalid learning rate: {}\".format(lr))\n if not 0.0 <= eps:\n raise ValueError(\"Invalid epsilon value: {}\".format(eps))\n if not 0.0 <= betas[0] < 1.0:\n raise ValueError(\"Invalid beta parameter at index 0: {}\".format(betas[0]))\n if not 0.0 <= betas[1] < 1.0:\n raise ValueError(\"Invalid beta parameter at index 1: {}\".format(betas[1]))\n if not 0.0 <= weight_decay:\n raise ValueError(\"Invalid weight_decay value: {}\".format(weight_decay))\n defaults = dict(lr=lr, betas=betas, eps=eps,\n weight_decay=weight_decay, amsgrad=amsgrad, maximize=maximize)\n super(AdamW, self).__init__(params, defaults)\n\n def __setstate__(self, state):\n super(AdamW, self).__setstate__(state)\n for group in self.param_groups:\n group.setdefault('amsgrad', False)\n group.setdefault('maximize', False)\n\n @torch.no_grad()\n def step(self, closure=None):\n \"\"\"Performs a single optimization step.\n\n Args:\n closure (callable, optional): A closure that reevaluates the model\n and returns the loss.\n \"\"\"\n loss = None\n if closure is not None:\n with torch.enable_grad():\n loss = closure()\n\n for group in self.param_groups:\n params_with_grad = []\n grads = []\n exp_avgs = []\n exp_avg_sqs = []\n state_sums = []\n max_exp_avg_sqs = []\n state_steps = []\n amsgrad = group['amsgrad']\n beta1, beta2 = group['betas']\n\n for p in group['params']:\n if p.grad is None:\n continue\n params_with_grad.append(p)\n if p.grad.is_sparse:\n raise RuntimeError('AdamW does not support sparse gradients')\n grads.append(p.grad)\n\n state = self.state[p]\n\n # State initialization\n if len(state) == 0:\n state['step'] = 0\n # Exponential moving average of gradient values\n state['exp_avg'] = torch.zeros_like(p, memory_format=torch.preserve_format)\n # Exponential moving average of squared gradient values\n state['exp_avg_sq'] = torch.zeros_like(p, memory_format=torch.preserve_format)\n if amsgrad:\n # Maintains max of all exp. moving avg. of sq. grad. values\n state['max_exp_avg_sq'] = torch.zeros_like(p, memory_format=torch.preserve_format)\n\n exp_avgs.append(state['exp_avg'])\n exp_avg_sqs.append(state['exp_avg_sq'])\n\n if amsgrad:\n max_exp_avg_sqs.append(state['max_exp_avg_sq'])\n\n # update the steps for each param group update\n state['step'] += 1\n # record the step after step update\n state_steps.append(state['step'])\n\n F.adamw(params_with_grad,\n grads,\n exp_avgs,\n exp_avg_sqs,\n max_exp_avg_sqs,\n state_steps,\n amsgrad=amsgrad,\n beta1=beta1,\n beta2=beta2,\n lr=group['lr'],\n weight_decay=group['weight_decay'],\n eps=group['eps'],\n maximize=group['maximize'])\n\n return loss\n", "# Owner(s): [\"oncall: jit\"]\n\nfrom torch.testing._internal.jit_utils import JitTestCase\nimport io\nimport os\nimport sys\nimport unittest\n\nimport torch\nimport torch._C\nfrom torch.testing import FileCheck\nfrom torch.jit.mobile import _load_for_lite_interpreter\n\nfrom torch.testing._internal.common_utils import (\n IS_FBCODE,\n IS_MACOS,\n IS_SANDCASTLE,\n IS_WINDOWS,\n TEST_WITH_ROCM,\n skipIfRocm,\n find_library_location,\n)\n# Make the helper files in test/ importable\npytorch_test_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))\nsys.path.append(pytorch_test_dir)\n\nif __name__ == \"__main__\":\n raise RuntimeError(\n \"This test file is not meant to be run directly, use:\\n\\n\"\n \"\\tpython test/test_jit.py TESTNAME\\n\\n\"\n \"instead.\"\n )\n\n\ndef to_test_backend(module, method_compile_spec):\n return torch._C._jit_to_backend(\"test_backend\", module, {\"forward\": method_compile_spec})\n\n\ndef to_test_backend_multi(module, method_compile_spec):\n return torch._C._jit_to_backend(\"test_backend\", module, method_compile_spec)\n\n\ndef to_test_backend_selective(module, method_compile_spec, submodules):\n def _to_test_backend(module):\n return to_test_backend(module, method_compile_spec)\n\n return torch._C._jit_to_backend_selective(module, _to_test_backend, submodules)\n\n\nclass BasicModule(torch.nn.Module):\n \"\"\"\n A simple Module used to test to_backend lowering machinery.\n \"\"\"\n\n def __init__(self):\n super().__init__()\n\n def forward(self, x, h):\n return self.accum(x, h), self.sub_accum(x, h)\n\n def accum(self, x, h):\n return x + h\n\n def sub_accum(self, x, h):\n return x - h\n\n\n# This is ignored in IS_WINDOWS or IS_MACOS cases. Hence we need the one in TestBackends.\[email protected](TEST_WITH_ROCM or IS_SANDCASTLE or IS_WINDOWS or IS_MACOS or IS_FBCODE,\n \"Non-portable load_library call used in test\")\nclass JitBackendTestCase(JitTestCase):\n \"\"\"\n A common base class for JIT backend tests that contains common utility\n functions for output comparison and serialization/deserialization.\n \"\"\"\n\n def setUp(self):\n super().setUp()\n lib_file_path = find_library_location('libjitbackend_test.so')\n torch.ops.load_library(str(lib_file_path))\n # Subclasses are expected to set up three variables in their setUp methods:\n # module - a regular, Python version of the module being tested\n # scripted_module - a scripted version of module\n # lowered_modle - a version of module lowered to a backend\n\n def check_function(self, function_name, input):\n \"\"\"\n Check that the function named 'function_name' produces the same output using\n Python, regular JIT and the backend for the given 'input'.\n \"\"\"\n # Get handles for Python, JIT and backend methods.\n python_method = self.module.__getattribute__(function_name)\n jit_method = self.scripted_module.__getattr__(function_name)\n backend_method = self.lowered_module.__getattr__(function_name)\n\n # Run methods.\n python_output = python_method(*input)\n jit_output = jit_method(*input)\n backend_output = backend_method(*input)\n\n # The answers returned by Python, JIT and to_backend should all match.\n self.assertEqual(python_output, backend_output)\n self.assertEqual(jit_output, backend_output)\n\n def save_load(self):\n \"\"\"\n Save and load the lowered module.\n \"\"\"\n self.lowered_module = self.getExportImportCopy(self.lowered_module)\n\n def test_execution(self):\n \"\"\"\n Stub for correctness tests.\n \"\"\"\n pass\n\n def test_save_load(self):\n \"\"\"\n Stub for serialization tests.\n \"\"\"\n pass\n\n def test_errors(self):\n \"\"\"\n Stub for testing error checking.\n \"\"\"\n pass\n\n\nclass BasicModuleTest(JitBackendTestCase):\n \"\"\"\n Tests for BasicModule.\n \"\"\"\n\n def setUp(self):\n super().setUp()\n # Create Python, JIT and backend versions of BasicModule.\n self.module = BasicModule()\n self.scripted_module = torch.jit.script(BasicModule())\n self.lowered_module = to_test_backend_multi(\n self.scripted_module,\n {\"accum\": {\"\": \"\"}, \"sub_accum\": {\"\": \"\"}, \"forward\": {\"\": \"\"}},\n )\n\n def test_execution(self):\n # Test execution with backend against Python and JIT.\n input = torch.randn(5)\n\n # Test all three module methods.\n self.check_function(\"accum\", (input, input))\n self.check_function(\"sub_accum\", (input, input))\n self.check_function(\"forward\", (input, input))\n\n @skipIfRocm\n def test_save_load(self):\n # Lowered module should produce the same outputs.\n self.test_execution()\n\n # Save the compile spec to compare against the version retrieved after loading.\n pre_compile_spec = self.lowered_module.__getattr__(\"__loweredModule__\").__getattr__(\"__method_compile_spec\")\n\n # Save and load the lowered module.\n self.save_load()\n\n # Get the compile spec after loading.\n post_compile_spec = self.lowered_module.__getattr__(\"__loweredModule__\").__getattr__(\"__method_compile_spec\")\n\n # Compile specs should match.\n self.assertEqual(pre_compile_spec, post_compile_spec)\n\n # Loaded module should produce the same outputs.\n self.test_execution()\n\n\nclass BasicModuleUnavailableTest(JitBackendTestCase):\n \"\"\"\n Tests for BasicModule with a backend that is not available.\n Fundamentally:\n * _jit_to_backend is successful.\n * Execution fails with an exception.\n * Saving is successful.\n * Loading fails with an exception.\n \"\"\"\n\n def setUp(self):\n super().setUp()\n # Create Python, JIT and backend versions of BasicModule.\n self.module = BasicModule()\n self.scripted_module = torch.jit.script(BasicModule())\n self.lowered_module = torch._C._jit_to_backend(\n \"test_backend_unavailable\",\n self.scripted_module,\n {\"forward\": {\"\": \"\"}},\n )\n\n def test_execution(self):\n # Test execution with backend fails because the backend that is not available.\n input = torch.randn(5)\n\n # Test exception is thrown.\n with self.assertRaisesRegexWithHighlight(Exception,\n r\"Backend is not available.\",\n \"raise Exception(\\\"Backend is not available.\\\"\"):\n backend_method = self.lowered_module.__getattr__(\"forward\")\n backend_output = backend_method(*(input, input))\n\n @skipIfRocm\n def test_save_load(self):\n # Test that saving the lowered module is OK but loading fails because the backend is not available.\n buffer = io.BytesIO()\n torch.jit.save(self.lowered_module, buffer)\n buffer.seek(0)\n with self.assertRaisesRegexWithHighlight(Exception,\n r\"Backend is not available.\",\n \"raise Exception(\\\"Backend is not available.\\\"\"):\n imported = torch.jit.load(buffer)\n\n\nclass NestedModuleTest(JitBackendTestCase):\n \"\"\"\n Tests for NestedModule that check that a module lowered to a backend can be used\n as a submodule.\n \"\"\"\n class NestedModule(torch.nn.Module):\n \"\"\"\n A Module with one submodule that is used to test that lowered Modules\n can be used as submodules.\n \"\"\"\n\n def __init__(self, submodule):\n super().__init__()\n self.submodule = submodule\n\n def forward(self, x, h):\n return self.submodule.forward(x, h)\n\n def setUp(self):\n super().setUp()\n # Create Python, JIT and backend versions of NestedModule.\n # Both modules in self.module are regular Python modules.\n self.module = NestedModuleTest.NestedModule(BasicModule())\n # Both modules in self.scripted_module are ScriptModules.\n self.scripted_module = torch.jit.script(NestedModuleTest.NestedModule(BasicModule()))\n\n # First, script another instance of NestedModule with share_types=False so that it can be\n # selectively lowered without modifying the type of self.scripted_module.\n lowered_module = to_test_backend_multi(\n torch.jit.script(BasicModule()),\n {\"accum\": {\"\": \"\"}, \"sub_accum\": {\"\": \"\"}, \"forward\": {\"\": \"\"}},\n )\n # self.lowered_module is a ScriptModule, but its submodule is a lowered module.\n self.lowered_module = torch.jit.script(NestedModuleTest.NestedModule(lowered_module))\n\n def test_execution(self):\n # Test execution with backend against Python and JIT.\n input = torch.randn(5)\n\n # Test forward.\n self.check_function(\"forward\", (input, input))\n\n def test_save_load(self):\n # Lowered module should produce the same outputs.\n self.test_execution()\n\n # Save and load the lowered module.\n self.save_load()\n\n # Loaded module should produce the same outputs.\n self.test_execution()\n\n\nclass SelectiveLoweringTest(JitBackendTestCase):\n \"\"\"\n Tests for the selective lowering API.\n \"\"\"\n class OuterModule(torch.nn.Module):\n def __init__(self, sub1, sub2, other):\n super().__init__()\n self.sub1 = sub1\n self.sub2 = sub2\n self.other = other\n\n def forward(self, x, y):\n # Call the module that will be lowered directly to test\n # type remapping in modules that are not its parent.\n a, b = self.sub1.submodule.forward(x, y)\n c, d = self.sub2.forward(x, y)\n e, f = self.other.forward(x, y)\n return a + c + e, b + d + f\n\n class MiddleModule(torch.nn.Module):\n def __init__(self, submodule):\n super().__init__()\n self.submodule = submodule\n\n def forward(self, x, y):\n return self.submodule.forward(x, y)\n\n def setUp(self):\n super().setUp()\n OuterModule = SelectiveLoweringTest.OuterModule\n MiddleModule = SelectiveLoweringTest.MiddleModule\n\n def script_without_type_sharing(mod):\n return torch.jit._recursive.create_script_module(mod, torch.jit._recursive.infer_methods_to_compile, share_types=False)\n # Create Python, JIT and backend versions of a hierarchy that looks like this:\n # --------- OuterModule --------\n # | | |\n # MiddleModule MiddleModule MiddleModule\n # | | |\n # BasicModule BasicModule BasicModule\n #\n # Two BasicModules will be lowered and the third will not.\n self.module = OuterModule(MiddleModule(BasicModule()), MiddleModule(BasicModule()), MiddleModule(BasicModule()))\n self.scripted_module = script_without_type_sharing(OuterModule(MiddleModule(\n BasicModule()), MiddleModule(BasicModule()), MiddleModule(BasicModule())))\n self.lowered_module = script_without_type_sharing(OuterModule(MiddleModule(\n BasicModule()), MiddleModule(BasicModule()), MiddleModule(BasicModule())))\n self.lowered_module = to_test_backend_selective(self.lowered_module, {\"forward\": \"\"}, [\n \"sub1.submodule\", \"sub2.submodule\"])\n\n def test_execution(self):\n input = torch.randn(5)\n self.check_function(\"forward\", (input, input))\n\n self.test_selective_lowering_type_remap()\n\n def test_save_load(self):\n self.test_execution()\n self.save_load()\n self.test_execution()\n\n self.test_selective_lowering_type_remap()\n\n def test_selective_lowering_type_remap(self):\n \"\"\"\n Check that type remapping and replacement occurred during selective lowering.\n \"\"\"\n # Check that self.lowered_module was not lowered, but that it does contain test_backendLoweredModule due to it\n # calling the lowered module directly.\n FileCheck() \\\n .check(\"OuterModule\") \\\n .check(\"BasicModule\") \\\n .run(self.scripted_module.graph)\n FileCheck() \\\n .check(\"OuterModule\") \\\n .check_not(\"__torch__.torch.classes.__backends__.test_backend\") \\\n .check(\"LoweredWrapper.test_backend\") \\\n .run(self.lowered_module.graph)\n\n # Check that self.lowered_module.sub1/sub2 were not lowered but that BasicModule has been replaced in their graphs.\n FileCheck() \\\n .check(\"MiddleModule\") \\\n .check(\"BasicModule\") \\\n .check_not(\"LoweredWrapper.test_backend\") \\\n .run(self.scripted_module.sub1.graph)\n FileCheck() \\\n .check(\"MiddleModule\") \\\n .check_not(\"__torch__.torch.classes.__backends__.test_backend\") \\\n .check(\"LoweredWrapper.test_backend\") \\\n .run(self.lowered_module.sub1.graph)\n\n FileCheck() \\\n .check(\"MiddleModule\") \\\n .check(\"BasicModule\") \\\n .check_not(\"LoweredWrapper.test_backend\") \\\n .run(self.scripted_module.sub2.graph)\n FileCheck() \\\n .check(\"MiddleModule\") \\\n .check_not(\"__torch__.torch.classes.__backends__.test_backend\") \\\n .check(\"LoweredWrapper.test_backend\") \\\n .run(self.lowered_module.sub2.graph)\n\n # Check that self.lowered_module.sub1/sub2.submodule were lowered. They should have a new attribute\n # __loweredModule__ whose graph should mention __torch__.torch.classes.__backends__.test_backend,\n # the TorchBind class for executing functions on the test JIT backend.\n FileCheck() \\\n .check(\"LoweredModule.test_backend\") \\\n .check(\"__torch__.torch.classes.__backends__.test_backend\") \\\n .run(self.lowered_module.sub1.submodule.__loweredModule__.graph)\n\n FileCheck() \\\n .check(\"LoweredModule.test_backend\") \\\n .check(\"__torch__.torch.classes.__backends__.test_backend\") \\\n .run(self.lowered_module.sub2.submodule.__loweredModule__.graph)\n\n # Check that self.other and self.other.submodule have been left untouched by the selective lowering process.\n FileCheck() \\\n .check(\"MiddleModule\") \\\n .check(\"BasicModule\") \\\n .check_not(\"__torch__.torch.classes.__backends__.test_backend\") \\\n .check_not(\"LoweredWrapper.test_backend\") \\\n .run(self.scripted_module.other.graph)\n FileCheck() \\\n .check(\"BasicModule\") \\\n .check_not(\"__torch__.torch.classes.__backends__.test_backend\") \\\n .check_not(\"LoweredModule.test_backend\") \\\n .run(self.scripted_module.other.submodule.graph)\n\n def test_errors(self):\n \"\"\"\n Check errors associated with selective lowering.\n \"\"\"\n # Check error messages thrown when attempting to lower something that is not a ScriptModule.\n with self.assertRaisesRegexWithHighlight(RuntimeError, r\"Object .* is not a ScriptModule\", \"\"):\n to_test_backend_selective(torch.nn.ReLU(), {\"forward\": \"\"}, [\"submodule\"])\n\n MiddleModule = SelectiveLoweringTest.MiddleModule\n mod = MiddleModule(BasicModule())\n mod.new_attr = 3\n\n with self.assertRaisesRegexWithHighlight(RuntimeError, r\"Attribute named new_attr is not a Module\", \"\"):\n to_test_backend_selective(torch.jit.script(mod), {\"forward\": \"\"}, [\"new_attr\"])\n\n # Check error message thrown when module hierarchy doesn't have unique types.\n OuterModule = SelectiveLoweringTest.OuterModule\n mod = OuterModule(MiddleModule(BasicModule()), MiddleModule(BasicModule()), MiddleModule(BasicModule()))\n\n with self.assertRaisesRegexWithHighlight(RuntimeError,\n r\"Selective lowering is only supported for module hierarchies with unique types\",\n \"\"):\n to_test_backend_selective(torch.jit.script(mod), {\"forward\": \"\"}, [\"sub1.submodule\"])\n\n\n# This is needed for IS_WINDOWS or IS_MACOS to skip the tests.\[email protected](TEST_WITH_ROCM or IS_SANDCASTLE or IS_WINDOWS or IS_MACOS or IS_FBCODE,\n \"Non-portable load_library call used in test\")\nclass TestBackends(JitTestCase):\n \"\"\"\n This class wraps and invokes all subclasses of JitBackendTestCase so that each one\n does not have to be individually imported in test_jit.py.\n \"\"\"\n\n def __init__(self, name):\n super().__init__(name)\n self.basic_module_test = BasicModuleTest(name)\n self.basic_module_unavailable_test = BasicModuleUnavailableTest(name)\n self.nested_module_test = NestedModuleTest(name)\n self.selective_lowering_test = SelectiveLoweringTest(name)\n\n def setUp(self):\n super().setUp()\n if not TEST_WITH_ROCM:\n self.basic_module_test.setUp()\n self.basic_module_unavailable_test.setUp()\n self.nested_module_test.setUp()\n self.selective_lowering_test.setUp()\n\n @skipIfRocm\n def test_execution(self):\n self.basic_module_test.test_execution()\n self.basic_module_unavailable_test.test_execution()\n self.nested_module_test.test_execution()\n self.selective_lowering_test.test_execution()\n\n @skipIfRocm\n def test_save_load(self):\n self.basic_module_test.test_save_load()\n self.basic_module_unavailable_test.test_save_load()\n self.nested_module_test.test_save_load()\n self.selective_lowering_test.test_save_load()\n\n @skipIfRocm\n def test_errors(self):\n self.selective_lowering_test.test_errors()\n\n\"\"\"\nUnit Tests for backend with compiler\nThis test case and the existing TestBackends are separate because they cover different aspects.\nThe actual backend implementation in this test is different.\nIt has a simple demo compiler to test the end-to-end flow in mobile.\nHowever, this test cannot cover the selective_lowering for now, which is covered in TestBackends.\n\"\"\"\nclass BasicModuleAdd(torch.nn.Module):\n \"\"\"\n A simple add Module used to test to_backend lowering machinery.\n \"\"\"\n\n def __init__(self):\n super().__init__()\n\n def forward(self, x, h):\n return x + h\n\n# This is ignored in IS_WINDOWS or IS_MACOS cases. Hence we need the one in TestBackends.\[email protected](TEST_WITH_ROCM or IS_SANDCASTLE or IS_WINDOWS or IS_MACOS or IS_FBCODE,\n \"Non-portable load_library call used in test\")\nclass JitBackendTestCaseWithCompiler(JitTestCase):\n \"\"\"\n A common base class for JIT backend tests with compilers that contains common utility\n functions for output comparison.\n \"\"\"\n\n def setUp(self):\n super().setUp()\n lib_file_path = find_library_location('libbackend_with_compiler.so')\n torch.ops.load_library(str(lib_file_path))\n # Subclasses are expected to set up four variables in their setUp methods:\n # module - a regular, Python version of the module being tested\n # scripted_module - a scripted version of module\n # lowered_modle - a version of module lowered to a backend\n # mobile_module - a module with a format that Pytorch Mobile can execute\n\n def check_forward(self, input):\n \"\"\"\n Check that the forward function produces the same output using\n Python, regular JIT, the backend, and mobile for the given 'input'.\n \"\"\"\n\n # Get outputs from forward.\n python_output = self.module.forward(*input)\n jit_output = self.scripted_module.forward(*input)\n backend_output = self.lowered_module(*input)\n mobile_output = self.mobile_module(*input)\n\n # The answers returned by Python, JIT, to_backend, and mobile should all match.\n self.assertEqual(python_output, backend_output)\n self.assertEqual(jit_output, backend_output)\n self.assertEqual(mobile_output, backend_output)\n\n def test_execution(self):\n \"\"\"\n Stub for correctness tests.\n \"\"\"\n pass\n\n def test_errors(self):\n \"\"\"\n Stub for testing error checking.\n \"\"\"\n pass\n\nclass BasicModuleTestWithCompiler(JitBackendTestCaseWithCompiler):\n \"\"\"\n Tests for BasicModuleAdd.\n \"\"\"\n\n def setUp(self):\n super().setUp()\n # Create Python, JIT and backend versions of BasicModuleAdd.\n self.module = BasicModuleAdd()\n self.scripted_module = torch.jit.script(BasicModuleAdd())\n compile_spec = {\n \"forward\": {\n \"input_shapes\": \"((1, 1, 320, 240), (1, 3))\",\n \"some_other_option\": \"True\",\n },\n }\n self.lowered_module = torch._C._jit_to_backend(\n \"backend_with_compiler_demo\", self.scripted_module, compile_spec)\n # Create mobile version of BasicModuleAdd\n buffer = io.BytesIO(self.lowered_module._save_to_buffer_for_lite_interpreter())\n buffer.seek(0)\n self.mobile_module = _load_for_lite_interpreter(buffer)\n\n def test_execution(self):\n # Test execution with backend against Python and JIT.\n input = torch.ones(1, dtype=torch.float)\n self.check_forward((input, input))\n\nclass ErrorMessagesWithCompiler(JitBackendTestCase):\n \"\"\"\n Tests for errors that occur with compiler, specifically:\n * an operator is not supported by the backend\n \"\"\"\n\n class ModuleNotSupported(torch.nn.Module):\n \"\"\"\n A module with an operator that is not supported.\n \"\"\"\n def __init__(self):\n super().__init__()\n\n def forward(self, x, h):\n return x * h\n self._loweredmodule.forward()\n\n def setUp(self):\n super().setUp()\n\n def test_errors(self):\n scripted_module_n = torch.jit.script(ErrorMessagesWithCompiler.ModuleNotSupported())\n # Test exception is thrown when lowering a module with an unsupported operator\n with self.assertRaisesRegexWithHighlight(RuntimeError,\n # Special escape characters are replaced with '.'\n r\"\"\"The node of aten::mul is not supported in this compiler. .*\n def forward.self, x, h.:\n return x . h\n ~~~~~ <--- HERE\n self._loweredmodule.forward..\n\"\"\", \"\"):\n lowered_module_n = torch._C._jit_to_backend(\"backend_with_compiler_demo\", scripted_module_n, {\"forward\": {\"\": \"\"}})\n\nclass CompModuleTestWithCompiler(JitBackendTestCase):\n \"\"\"\n Tests for CompModule, which is a module with two lowered submodules\n \"\"\"\n\n class BasicModuleSub(torch.nn.Module):\n \"\"\"\n A simple subtraction Module to be used in CompModule.\n \"\"\"\n def __init__(self):\n super().__init__()\n\n def forward(self, x, h):\n return x - h\n\n class CompModule(torch.nn.Module):\n \"\"\"\n A module with two lowered submodules.\n \"\"\"\n\n def __init__(self, addmodule, submodule):\n super().__init__()\n self.lowered_add = addmodule\n self.lowered_sub = submodule\n\n def forward(self, a, b, s):\n c = self.lowered_add.forward(a, b)\n d = self.lowered_sub.forward(a, b)\n y = s * (c * d)\n return y\n\n def setUp(self):\n super().setUp()\n # Create Python and JIT versions of CompModule with lowered submodules.\n compile_spec = {\n \"forward\": {\n \"input_shapes\": \"((1, 1, 320, 240), (1, 3))\",\n \"some_other_option\": \"True\",\n },\n }\n lowered_add = torch._C._jit_to_backend(\n \"backend_with_compiler_demo\", torch.jit.script(BasicModuleAdd()), compile_spec)\n lowered_sub = torch._C._jit_to_backend(\n \"backend_with_compiler_demo\",\n torch.jit.script(CompModuleTestWithCompiler.BasicModuleSub()),\n {\"forward\": {\"\": \"\"}}\n )\n self.module = CompModuleTestWithCompiler.CompModule(lowered_add, lowered_sub)\n self.scripted_module = torch.jit.script(CompModuleTestWithCompiler.CompModule(lowered_add, lowered_sub))\n # No backend version of CompModule currently, so this is filler.\n self.lowered_module = self.scripted_module\n # Create a mobile version of CompModule from JIT version\n buffer = io.BytesIO(self.scripted_module._save_to_buffer_for_lite_interpreter())\n buffer.seek(0)\n self.mobile_module = _load_for_lite_interpreter(buffer)\n\n def test_execution(self):\n # Test execution with backend against Python and JIT.\n input1 = torch.ones(1, dtype=torch.float)\n input2 = torch.ones(1, dtype=torch.float)\n\n # Test forward.\n self.check_function(\"forward\", (input1, input2, input2))\n\n# This is needed for IS_WINDOWS or IS_MACOS to skip the tests.\[email protected](TEST_WITH_ROCM or IS_SANDCASTLE or IS_WINDOWS or IS_MACOS or IS_FBCODE,\n \"Non-portable load_library call used in test\")\nclass TestBackendsWithCompiler(JitTestCase):\n \"\"\"\n This class wraps and invokes all subclasses of JitBackendTestCaseWithCompiler\n so that each one does not have to be individually imported in test_jit.py.\n \"\"\"\n\n def __init__(self, name):\n super().__init__(name)\n self.basic_module_compiler_test = BasicModuleTestWithCompiler(name)\n self.error_module_compiler_test = ErrorMessagesWithCompiler(name)\n self.comp_module_compiler_test = CompModuleTestWithCompiler(name)\n\n def setUp(self):\n super().setUp()\n if not TEST_WITH_ROCM:\n self.basic_module_compiler_test.setUp()\n self.error_module_compiler_test.setUp()\n self.comp_module_compiler_test.setUp()\n\n @skipIfRocm\n def test_execution(self):\n self.basic_module_compiler_test.test_execution()\n self.comp_module_compiler_test.test_execution()\n\n @skipIfRocm\n def test_errors(self):\n self.error_module_compiler_test.test_errors()\n\n\nclass CompModuleTestSameNameWithCompiler(JitBackendTestCase):\n \"\"\"\n Tests for CompModule, which is a module with two lowered submodules with same module name\n \"\"\"\n\n class ModuleAdd(torch.nn.Module):\n \"\"\"\n A simple Module used to test to_backend lowering machinery.\n \"\"\"\n\n def __init__(self):\n super().__init__()\n\n def forward(self, x, h):\n return x + h\n\n class CompModule(torch.nn.Module):\n \"\"\"\n A module with two lowered submodules.\n \"\"\"\n\n def __init__(self):\n super().__init__()\n compile_spec = {\n \"forward\": {\n \"some_other_option\": \"True\",\n },\n }\n self.add = torch._C._jit_to_backend(\n \"backend_with_compiler_demo\",\n torch.jit.script(ModuleAdd()),\n compile_spec,\n )\n self.sub = torch._C._jit_to_backend(\n \"backend_with_compiler_demo\",\n torch.jit.script(ModuleAdd()),\n compile_spec,\n )\n\n def forward(self, a, b, s: int):\n c = self.add.forward(a, b)\n d = self.sub.forward(a, b)\n y = s * (c * d)\n return y\n\n\n def setUp(self):\n super().setUp()\n\n self.module = CompModule()\n self.scripted_module = torch.jit.script(self.module)\n buffer = io.BytesIO(self.scripted_module._save_to_buffer_for_lite_interpreter())\n buffer.seek(0)\n self.mobile_module = _load_for_lite_interpreter(buffer)\n\n def test_execution(self):\n a = torch.ones(1)\n b = 3 * torch.ones(1)\n s = 3\n # Test forward.\n self.check_function(\"forward\", (a, b, s))\n\nclass AddedAttributesTest(JitBackendTestCase):\n \"\"\"\n Tests for adding attributes to a model after lowering.\n \"\"\"\n\n def setUp(self):\n super().setUp()\n # Create Python, JIT and backend versions of BasicModule.\n self.module = BasicModule()\n self.scripted_module = torch.jit.script(BasicModule())\n self.lowered_module = to_test_backend_multi(\n self.scripted_module,\n {\"accum\": {\"\": \"\"}, \"sub_accum\": {\"\": \"\"}, \"forward\": {\"\": \"\"}},\n )\n\n def test_attribute(self):\n input = [(torch.ones(5),)]\n pre_bundled = self.lowered_module(*input[0])\n # Attach bundled inputs which adds several attributes and functions to the model\n self.lowered_module = torch.utils.bundled_inputs.augment_model_with_bundled_inputs(lowered_module, input)\n post_bundled = self.lowered_module(*self.lowered_module.get_all_bundled_inputs()[0])\n # Save and load the lowered module.\n self.save_load()\n # Use bundled after save and load to prove its preserved\n post_load = self.lowered_module(*self.lowered_module.get_all_bundled_inputs()[0])\n self.assertEqual(pre_bundled, post_bundled)\n self.assertEqual(post_bundled, post_load)\n", "import math\nfrom typing import TypeVar, Optional, Iterator\n\nimport torch\nfrom . import Sampler, Dataset\nimport torch.distributed as dist\n\n\nT_co = TypeVar('T_co', covariant=True)\n\n\nclass DistributedSampler(Sampler[T_co]):\n r\"\"\"Sampler that restricts data loading to a subset of the dataset.\n\n It is especially useful in conjunction with\n :class:`torch.nn.parallel.DistributedDataParallel`. In such a case, each\n process can pass a :class:`~torch.utils.data.DistributedSampler` instance as a\n :class:`~torch.utils.data.DataLoader` sampler, and load a subset of the\n original dataset that is exclusive to it.\n\n .. note::\n Dataset is assumed to be of constant size and that any instance of it always\n returns the same elements in the same order.\n\n Args:\n dataset: Dataset used for sampling.\n num_replicas (int, optional): Number of processes participating in\n distributed training. By default, :attr:`world_size` is retrieved from the\n current distributed group.\n rank (int, optional): Rank of the current process within :attr:`num_replicas`.\n By default, :attr:`rank` is retrieved from the current distributed\n group.\n shuffle (bool, optional): If ``True`` (default), sampler will shuffle the\n indices.\n seed (int, optional): random seed used to shuffle the sampler if\n :attr:`shuffle=True`. This number should be identical across all\n processes in the distributed group. Default: ``0``.\n drop_last (bool, optional): if ``True``, then the sampler will drop the\n tail of the data to make it evenly divisible across the number of\n replicas. If ``False``, the sampler will add extra indices to make\n the data evenly divisible across the replicas. Default: ``False``.\n\n .. warning::\n In distributed mode, calling the :meth:`set_epoch` method at\n the beginning of each epoch **before** creating the :class:`DataLoader` iterator\n is necessary to make shuffling work properly across multiple epochs. Otherwise,\n the same ordering will be always used.\n\n Example::\n\n >>> sampler = DistributedSampler(dataset) if is_distributed else None\n >>> loader = DataLoader(dataset, shuffle=(sampler is None),\n ... sampler=sampler)\n >>> for epoch in range(start_epoch, n_epochs):\n ... if is_distributed:\n ... sampler.set_epoch(epoch)\n ... train(loader)\n \"\"\"\n\n def __init__(self, dataset: Dataset, num_replicas: Optional[int] = None,\n rank: Optional[int] = None, shuffle: bool = True,\n seed: int = 0, drop_last: bool = False) -> None:\n if num_replicas is None:\n if not dist.is_available():\n raise RuntimeError(\"Requires distributed package to be available\")\n num_replicas = dist.get_world_size()\n if rank is None:\n if not dist.is_available():\n raise RuntimeError(\"Requires distributed package to be available\")\n rank = dist.get_rank()\n if rank >= num_replicas or rank < 0:\n raise ValueError(\n \"Invalid rank {}, rank should be in the interval\"\n \" [0, {}]\".format(rank, num_replicas - 1))\n self.dataset = dataset\n self.num_replicas = num_replicas\n self.rank = rank\n self.epoch = 0\n self.drop_last = drop_last\n # If the dataset length is evenly divisible by # of replicas, then there\n # is no need to drop any data, since the dataset will be split equally.\n if self.drop_last and len(self.dataset) % self.num_replicas != 0: # type: ignore[arg-type]\n # Split to nearest available length that is evenly divisible.\n # This is to ensure each rank receives the same amount of data when\n # using this Sampler.\n self.num_samples = math.ceil(\n (len(self.dataset) - self.num_replicas) / self.num_replicas # type: ignore[arg-type]\n )\n else:\n self.num_samples = math.ceil(len(self.dataset) / self.num_replicas) # type: ignore[arg-type]\n self.total_size = self.num_samples * self.num_replicas\n self.shuffle = shuffle\n self.seed = seed\n\n def __iter__(self) -> Iterator[T_co]:\n if self.shuffle:\n # deterministically shuffle based on epoch and seed\n g = torch.Generator()\n g.manual_seed(self.seed + self.epoch)\n indices = torch.randperm(len(self.dataset), generator=g).tolist() # type: ignore[arg-type]\n else:\n indices = list(range(len(self.dataset))) # type: ignore[arg-type]\n\n if not self.drop_last:\n # add extra samples to make it evenly divisible\n padding_size = self.total_size - len(indices)\n if padding_size <= len(indices):\n indices += indices[:padding_size]\n else:\n indices += (indices * math.ceil(padding_size / len(indices)))[:padding_size]\n else:\n # remove tail of data to make it evenly divisible.\n indices = indices[:self.total_size]\n assert len(indices) == self.total_size\n\n # subsample\n indices = indices[self.rank:self.total_size:self.num_replicas]\n assert len(indices) == self.num_samples\n\n return iter(indices)\n\n def __len__(self) -> int:\n return self.num_samples\n\n def set_epoch(self, epoch: int) -> None:\n r\"\"\"\n Sets the epoch for this sampler. When :attr:`shuffle=True`, this ensures all replicas\n use a different random ordering for each epoch. Otherwise, the next iteration of this\n sampler will yield the same ordering.\n\n Args:\n epoch (int): Epoch number.\n \"\"\"\n self.epoch = epoch\n", "# Owner(s): [\"oncall: aiacc\"]\n\nimport torch\nimport torch.fx.experimental.fx_acc.acc_ops as acc_ops\nimport torch.nn as nn\nfrom torch.testing._internal.common_fx2trt import AccTestCase, InputTensorSpec\nfrom torch.testing._internal.common_utils import run_tests\n\n\nclass TestReLUConverter(AccTestCase):\n def test_relu(self):\n class TestModule(nn.Module):\n def forward(self, x):\n return nn.functional.relu(x)\n\n inputs = [torch.randn(1, 10)]\n self.run_test(TestModule(), inputs, expected_ops={acc_ops.relu})\n\n def test_relu_with_dynamic_shape(self):\n class TestModule(nn.Module):\n def forward(self, x):\n return nn.functional.relu(x)\n\n input_specs = [\n InputTensorSpec(\n shape=(-1, -1, -1),\n dtype=torch.float32,\n shape_ranges=[((1, 1, 1), (1, 2, 3), (3, 3, 3))],\n ),\n ]\n self.run_test_with_dynamic_shape(\n TestModule(), input_specs, expected_ops={acc_ops.relu}\n )\n\nif __name__ == '__main__':\n run_tests()\n" ]
[ [ "torch.testing._internal.common_fx2trt.InputTensorSpec", "torch.randn", "torch.testing._internal.common_utils.run_tests", "torch.nn.BatchNorm2d" ], [ "torch.zeros", "torch.distributed.all_gather_object", "torch.distributed.distributed_c10d._get_default_group", "torch.distributed.rpc._get_current_rpc_agent", "torch.distributed.rpc.api._all_gather", "torch.distributed.rpc.rpc_async", "torch.distributed.get_rank", "torch.futures.wait_all", "torch.ones", "torch.distributed.rpc._is_current_rpc_agent_set", "torch.distributed._sharding_spec.EnumerableShardingSpec", "torch.distributed.distributed_c10d.is_initialized", "torch._C._log_api_usage_once", "torch.rand", "torch.get_default_dtype", "torch.distributed._sharding_spec.ShardMetadata", "torch.distributed._sharding_spec._internals.get_split_size", "torch.distributed.rpc.RRef", "torch.empty", "torch.distributed._sharding_spec._internals.validate_non_overlapping_shards_metadata", "torch.full", "torch.distributed._sharding_spec._internals.check_tensor", "torch.distributed.distributed_c10d.get_world_size", "torch.distributed._sharding_spec._internals.get_chunked_dim_size", "torch.distributed.get_world_size", "torch.distributed.rpc.get_worker_info", "torch.distributed.distributed_c10d.get_rank" ], [ "torch.sigmoid", "torch.fx.passes.shape_prop.ShapeProp", "torch.sin", "torch.randn", "torch.jit.trace_module", "torch.nn.Conv2d", "torch.equal", "torch.tanh", "torch.fx.symbolic_trace", "torch.relu", "torch.fx.passes.operator_support.OperatorSupport", "torch.fx.passes.splitter_base.FxNetAccFusionsFinder", "torch.nn.Linear", "torch.fx.passes.splitter_base._SplitterSettingBase", "torch.fx.passes.operator_support.get_node_target", "torch.topk", "torch.testing._internal.common_utils.run_tests", "torch.cos" ], [ "torch.zeros_like", "torch.no_grad", "torch.enable_grad" ], [ "torch.jit.save", "torch.jit.script", "torch.jit.load", "torch.ones", "torch.utils.bundled_inputs.augment_model_with_bundled_inputs", "torch.jit.mobile._load_for_lite_interpreter", "torch.randn", "torch.nn.ReLU", "torch.testing.FileCheck", "torch._C._jit_to_backend", "torch.jit._recursive.create_script_module", "torch.testing._internal.common_utils.find_library_location", "torch._C._jit_to_backend_selective" ], [ "torch.distributed.get_rank", "torch.distributed.get_world_size", "torch.distributed.is_available", "torch.Generator" ], [ "torch.testing._internal.common_fx2trt.InputTensorSpec", "torch.randn", "torch.nn.functional.relu", "torch.testing._internal.common_utils.run_tests" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
hieultp/stylegan2-ada-pytorch
[ "d09653fc1c4a8eefe64f29b3e33a2afb3bdd3d22" ]
[ "generate.py" ]
[ "# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.\n#\n# NVIDIA CORPORATION and its licensors retain all intellectual property\n# and proprietary rights in and to this software, related documentation\n# and any modifications thereto. Any use, reproduction, disclosure or\n# distribution of this software and related documentation without an express\n# license agreement from NVIDIA CORPORATION is strictly prohibited.\n\n\"\"\"Generate images using pretrained network pickle.\"\"\"\n\nimport os\nimport subprocess\nimport re\nfrom typing import List, Optional\n\nimport click\nimport dnnlib\nimport numpy as np\nfrom numpy import linalg\nimport PIL.Image\nimport torch\n\nimport legacy\n\nfrom opensimplex import OpenSimplex\n\n# ---------------------------------------------------------------------------\n\nclass OSN():\n min = -1\n max = 1\n\n def __init__(self, seed, diameter):\n self.tmp = OpenSimplex(seed)\n self.d = diameter\n self.x = 0\n self.y = 0\n\n def get_val(self, angle):\n self.xoff = valmap(np.cos(angle), -1, 1, self.x, self.x + self.d)\n self.yoff = valmap(np.sin(angle), -1, 1, self.y, self.y + self.d)\n return self.tmp.noise2(self.xoff,self.yoff)\n\ndef circularloop(nf, d, seed, seeds):\n r = d/2\n\n zs = []\n # hardcoding in 512, prob TODO fix needed\n # latents_c = rnd.randn(1, G.input_shape[1])\n\n if(seeds is None):\n if seed:\n rnd = np.random.RandomState(seed)\n else:\n rnd = np.random\n latents_a = rnd.randn(1, 512)\n latents_b = rnd.randn(1, 512)\n latents_c = rnd.randn(1, 512)\n elif(len(seeds) is not 3):\n assert('Must choose exactly 3 seeds!')\n else:\n latents_a = np.random.RandomState(int(seeds[0])).randn(1, 512)\n latents_b = np.random.RandomState(int(seeds[1])).randn(1, 512)\n latents_c = np.random.RandomState(int(seeds[2])).randn(1, 512)\n\n latents = (latents_a, latents_b, latents_c)\n\n current_pos = 0.0\n step = 1./nf\n\n while(current_pos < 1.0):\n zs.append(circular_interpolation(r, latents, current_pos))\n current_pos += step\n return zs\n\ndef circular_interpolation(radius, latents_persistent, latents_interpolate):\n latents_a, latents_b, latents_c = latents_persistent\n\n latents_axis_x = (latents_a - latents_b).flatten() / linalg.norm(latents_a - latents_b)\n latents_axis_y = (latents_a - latents_c).flatten() / linalg.norm(latents_a - latents_c)\n\n latents_x = np.sin(np.pi * 2.0 * latents_interpolate) * radius\n latents_y = np.cos(np.pi * 2.0 * latents_interpolate) * radius\n\n latents = latents_a + latents_x * latents_axis_x + latents_y * latents_axis_y\n return latents\n\ndef num_range(s: str) -> List[int]:\n '''Accept either a comma separated list of numbers 'a,b,c' or a range 'a-c' and return as a list of ints.'''\n\n range_re = re.compile(r'^(\\d+)-(\\d+)$')\n m = range_re.match(s)\n if m:\n return list(range(int(m.group(1)), int(m.group(2))+1))\n vals = s.split(',')\n return [int(x) for x in vals]\n\ndef size_range(s: str) -> List[int]:\n '''Accept a range 'a-c' and return as a list of 2 ints.'''\n return [int(v) for v in s.split('-')][::-1]\n\ndef line_interpolate(zs, steps, easing):\n out = []\n for i in range(len(zs)-1):\n for index in range(steps):\n t = index/float(steps)\n\n if(easing == 'linear'):\n out.append(zs[i+1]*t + zs[i]*(1-t))\n elif (easing == 'easeInOutQuad'):\n if(t < 0.5):\n fr = 2 * t * t\n else:\n fr = (-2 * t * t) + (4 * t) - 1\n out.append(zs[i+1]*fr + zs[i]*(1-fr))\n elif (easing == 'bounceEaseOut'):\n if (t < 4/11):\n fr = 121 * t * t / 16\n elif (t < 8/11):\n fr = (363 / 40.0 * t * t) - (99 / 10.0 * t) + 17 / 5.0\n elif t < 9/10:\n fr = (4356 / 361.0 * t * t) - (35442 / 1805.0 * t) + 16061 / 1805.0\n else:\n fr = (54 / 5.0 * t * t) - (513 / 25.0 * t) + 268 / 25.0\n out.append(zs[i+1]*fr + zs[i]*(1-fr))\n elif (easing == 'circularEaseOut'):\n fr = np.sqrt((2 - t) * t)\n out.append(zs[i+1]*fr + zs[i]*(1-fr))\n elif (easing == 'circularEaseOut2'):\n fr = np.sqrt(np.sqrt((2 - t) * t))\n out.append(zs[i+1]*fr + zs[i]*(1-fr))\n elif(easing == 'backEaseOut'):\n p = 1 - t\n fr = 1 - (p * p * p - p * math.sin(p * math.pi))\n out.append(zs[i+1]*fr + zs[i]*(1-fr))\n return out\n\ndef noiseloop(nf, d, seed):\n if seed:\n np.random.RandomState(seed)\n\n features = []\n zs = []\n for i in range(512):\n features.append(OSN(i+seed,d))\n\n inc = (np.pi*2)/nf\n for f in range(nf):\n z = np.random.randn(1, 512)\n for i in range(512):\n z[0,i] = features[i].get_val(inc*f)\n zs.append(z)\n\n return zs\n\ndef images(G,device,inputs,space,truncation_psi,label,noise_mode,outdir,start=None,stop=None):\n if(start is not None and stop is not None):\n tp = start\n tp_i = (stop-start)/len(inputs)\n\n for idx, i in enumerate(inputs):\n print('Generating image for frame %d/%d ...' % (idx, len(inputs)))\n \n if (space=='z'):\n z = torch.from_numpy(i).to(device)\n if(start is not None and stop is not None):\n img = G(z, label, truncation_psi=tp, noise_mode=noise_mode)\n tp = tp+tp_i\n else:\n img = G(z, label, truncation_psi=truncation_psi, noise_mode=noise_mode)\n else:\n if len(i.shape) == 2: \n i = torch.from_numpy(i).unsqueeze(0).to(device)\n img = G.synthesis(i, noise_mode=noise_mode, force_fp32=True)\n img = (img.permute(0, 2, 3, 1) * 127.5 + 128).clamp(0, 255).to(torch.uint8)\n PIL.Image.fromarray(img[0].cpu().numpy(), 'RGB').save(f'{outdir}/frame{idx:04d}.png')\n\ndef interpolate(G,device,projected_w,seeds,random_seed,space,truncation_psi,label,frames,noise_mode,outdir,interpolation,easing,diameter,start=None,stop=None):\n if(interpolation=='noiseloop' or interpolation=='circularloop'):\n if seeds is not None:\n print(f'Warning: interpolation type: \"{interpolation}\" doesn’t support set seeds.')\n\n if(interpolation=='noiseloop'):\n points = noiseloop(frames, diameter, random_seed)\n elif(interpolation=='circularloop'):\n points = circularloop(frames, diameter, random_seed, seeds)\n\n else:\n if projected_w is not None:\n points = np.load(projected_w)['w']\n else:\n # get zs from seeds\n points = seeds_to_zs(G,seeds) \n # convert to ws\n if(space=='w'):\n points = zs_to_ws(G,device,label,truncation_psi,points)\n\n # get interpolation points\n if(interpolation=='linear'):\n points = line_interpolate(points,frames,easing)\n elif(interpolation=='slerp'):\n points = slerp_interpolate(points,frames)\n \n # generate frames\n images(G,device,points,space,truncation_psi,label,noise_mode,outdir,start,stop)\n\ndef seeds_to_zs(G,seeds):\n zs = []\n for seed_idx, seed in enumerate(seeds):\n z = np.random.RandomState(seed).randn(1, G.z_dim)\n zs.append(z)\n return zs\n\n# slightly modified version of\n# https://github.com/PDillis/stylegan2-fun/blob/master/run_generator.py#L399\ndef slerp(t, v0, v1, DOT_THRESHOLD=0.9995):\n '''\n Spherical linear interpolation\n Args:\n t (float/np.ndarray): Float value between 0.0 and 1.0\n v0 (np.ndarray): Starting vector\n v1 (np.ndarray): Final vector\n DOT_THRESHOLD (float): Threshold for considering the two vectors as\n colineal. Not recommended to alter this.\n Returns:\n v2 (np.ndarray): Interpolation vector between v0 and v1\n '''\n v0 = v0.cpu().detach().numpy()\n v1 = v1.cpu().detach().numpy()\n # Copy the vectors to reuse them later\n v0_copy = np.copy(v0)\n v1_copy = np.copy(v1)\n # Normalize the vectors to get the directions and angles\n v0 = v0 / np.linalg.norm(v0)\n v1 = v1 / np.linalg.norm(v1)\n # Dot product with the normalized vectors (can't use np.dot in W)\n dot = np.sum(v0 * v1)\n # If absolute value of dot product is almost 1, vectors are ~colineal, so use lerp\n if np.abs(dot) > DOT_THRESHOLD:\n return lerp(t, v0_copy, v1_copy)\n # Calculate initial angle between v0 and v1\n theta_0 = np.arccos(dot)\n sin_theta_0 = np.sin(theta_0)\n # Angle at timestep t\n theta_t = theta_0 * t\n sin_theta_t = np.sin(theta_t)\n # Finish the slerp algorithm\n s0 = np.sin(theta_0 - theta_t) / sin_theta_0\n s1 = sin_theta_t / sin_theta_0\n v2 = s0 * v0_copy + s1 * v1_copy\n return torch.from_numpy(v2).to(\"cuda\")\n\ndef slerp_interpolate(zs, steps):\n out = []\n for i in range(len(zs)-1):\n for index in range(steps):\n fraction = index/float(steps)\n out.append(slerp(fraction,zs[i],zs[i+1]))\n return out\n\ndef truncation_traversal(G,device,z,label,start,stop,increment,noise_mode,outdir):\n count = 1\n trunc = start\n\n z = seeds_to_zs(G,z)[0]\n z = torch.from_numpy(np.asarray(z)).to(device)\n\n while trunc <= stop:\n print('Generating truncation %0.2f' % trunc)\n \n img = G(z, label, truncation_psi=trunc, noise_mode=noise_mode)\n img = (img.permute(0, 2, 3, 1) * 127.5 + 128).clamp(0, 255).to(torch.uint8)\n PIL.Image.fromarray(img[0].cpu().numpy(), 'RGB').save(f'{outdir}/frame{count:04d}.png')\n\n trunc+=increment\n count+=1\n\ndef valmap(value, istart, istop, ostart, ostop):\n return ostart + (ostop - ostart) * ((value - istart) / (istop - istart))\n\ndef zs_to_ws(G,device,label,truncation_psi,zs):\n ws = []\n for z_idx, z in enumerate(zs):\n z = torch.from_numpy(z).to(device)\n w = G.mapping(z, label, truncation_psi=truncation_psi, truncation_cutoff=8)\n ws.append(w)\n return ws\n\n#----------------------------------------------------------------------------\n\[email protected]()\[email protected]_context\[email protected]('--network', 'network_pkl', help='Network pickle filename', required=True)\[email protected]('--seeds', type=num_range, help='List of random seeds')\[email protected]('--trunc', 'truncation_psi', type=float, help='Truncation psi', default=1, show_default=True)\[email protected]('--class', 'class_idx', type=int, help='Class label (unconditional if not specified)')\[email protected]('--diameter', type=float, help='diameter of loops', default=100.0, show_default=True)\[email protected]('--frames', type=int, help='how many frames to produce (with seeds this is frames between each step, with loops this is total length)', default=240, show_default=True)\[email protected]('--fps', type=int, help='framerate for video', default=24, show_default=True)\[email protected]('--increment', type=float, help='truncation increment value', default=0.01, show_default=True)\[email protected]('--interpolation', type=click.Choice(['linear', 'slerp', 'noiseloop', 'circularloop']), default='linear', help='interpolation type', required=True)\[email protected]('--easing',\n type=click.Choice(['linear', 'easeInOutQuad', 'bounceEaseOut','circularEaseOut','circularEaseOut2']),\n default='linear', help='easing method', required=True)\[email protected]('--network', 'network_pkl', help='Network pickle filename', required=True)\[email protected]('--noise-mode', help='Noise mode', type=click.Choice(['const', 'random', 'none']), default='const', show_default=True)\[email protected]('--outdir', help='Where to save the output images', type=str, required=True, metavar='DIR')\[email protected]('--process', type=click.Choice(['image', 'interpolation','truncation','interpolation-truncation']), default='image', help='generation method', required=True)\[email protected]('--projected-w', help='Projection result file', type=str, metavar='FILE')\[email protected]('--random_seed', type=int, help='random seed value (used in noise and circular loop)', default=0, show_default=True)\[email protected]('--scale-type',\n type=click.Choice(['pad', 'padside', 'symm','symmside']),\n default='pad', help='scaling method for --size', required=False)\[email protected]('--size', type=size_range, help='size of output (in format x-y)')\[email protected]('--seeds', type=num_range, help='List of random seeds')\[email protected]('--space', type=click.Choice(['z', 'w']), default='z', help='latent space', required=True)\[email protected]('--start', type=float, help='starting truncation value', default=0.0, show_default=True)\[email protected]('--stop', type=float, help='stopping truncation value', default=1.0, show_default=True)\[email protected]('--trunc', 'truncation_psi', type=float, help='Truncation psi', default=1, show_default=True)\n\ndef generate_images(\n ctx: click.Context,\n easing: str,\n interpolation: str,\n increment: Optional[float],\n network_pkl: str,\n process: str,\n random_seed: Optional[int],\n diameter: Optional[float],\n scale_type: Optional[str],\n size: Optional[List[int]],\n seeds: Optional[List[int]],\n space: str,\n fps: Optional[int],\n frames: Optional[int],\n truncation_psi: float,\n noise_mode: str,\n outdir: str,\n class_idx: Optional[int],\n projected_w: Optional[str],\n start: Optional[float],\n stop: Optional[float],\n):\n \"\"\"Generate images using pretrained network pickle.\n\n Examples:\n\n \\b\n # Generate curated MetFaces images without truncation (Fig.10 left)\n python generate.py --outdir=out --trunc=1 --seeds=85,265,297,849 \\\\\n --network=https://nvlabs-fi-cdn.nvidia.com/stylegan2-ada-pytorch/pretrained/metfaces.pkl\n\n \\b\n # Generate uncurated MetFaces images with truncation (Fig.12 upper left)\n python generate.py --outdir=out --trunc=0.7 --seeds=600-605 \\\\\n --network=https://nvlabs-fi-cdn.nvidia.com/stylegan2-ada-pytorch/pretrained/metfaces.pkl\n\n \\b\n # Generate class conditional CIFAR-10 images (Fig.17 left, Car)\n python generate.py --outdir=out --seeds=0-35 --class=1 \\\\\n --network=https://nvlabs-fi-cdn.nvidia.com/stylegan2-ada-pytorch/pretrained/cifar10.pkl\n\n \\b\n # Render an image from projected W\n python generate.py --outdir=out --projected_w=projected_w.npz \\\\\n --network=https://nvlabs-fi-cdn.nvidia.com/stylegan2-ada-pytorch/pretrained/metfaces.pkl\n \"\"\"\n \n # custom size code from https://github.com/eps696/stylegan2ada/blob/master/src/_genSGAN2.py\n if(size): \n print('render custom size: ',size)\n print('padding method:', scale_type )\n custom = True\n else:\n custom = False\n\n G_kwargs = dnnlib.EasyDict()\n G_kwargs.size = size \n G_kwargs.scale_type = scale_type\n\n # mask/blend latents with external latmask or by splitting the frame\n latmask = False #temp\n if latmask is None:\n nHW = [int(s) for s in a.nXY.split('-')][::-1]\n assert len(nHW)==2, ' Wrong count nXY: %d (must be 2)' % len(nHW)\n n_mult = nHW[0] * nHW[1]\n # if a.verbose is True and n_mult > 1: print(' Latent blending w/split frame %d x %d' % (nHW[1], nHW[0]))\n lmask = np.tile(np.asarray([[[[1]]]]), (1,n_mult,1,1))\n Gs_kwargs.countHW = nHW\n Gs_kwargs.splitfine = a.splitfine\n lmask = torch.from_numpy(lmask).to(device)\n # else:\n # if a.verbose is True: print(' Latent blending with mask', a.latmask)\n # n_mult = 2\n # if os.path.isfile(a.latmask): # single file\n # lmask = np.asarray([[img_read(a.latmask)[:,:,0] / 255.]]) # [h,w]\n # elif os.path.isdir(a.latmask): # directory with frame sequence\n # lmask = np.asarray([[img_read(f)[:,:,0] / 255. for f in img_list(a.latmask)]]) # [h,w]\n # else:\n # print(' !! Blending mask not found:', a.latmask); exit(1)\n # lmask = np.concatenate((lmask, 1 - lmask), 1) # [frm,2,h,w]\n # lmask = torch.from_numpy(lmask).to(device)\n\n print('Loading networks from \"%s\"...' % network_pkl)\n device = torch.device('cuda')\n with dnnlib.util.open_url(network_pkl) as f:\n # G = legacy.load_network_pkl(f)['G_ema'].to(device) # type: ignore\n G = legacy.load_network_pkl(f, custom=custom, **G_kwargs)['G_ema'].to(device) # type: ignore\n\n os.makedirs(outdir, exist_ok=True)\n\n # Synthesize the result of a W projection.\n if (process=='image') and projected_w is not None:\n if seeds is not None:\n print ('Warning: --seeds is ignored when using --projected-w')\n print(f'Generating images from projected W \"{projected_w}\"')\n ws = np.load(projected_w)['w']\n ws = torch.tensor(ws, device=device) # pylint: disable=not-callable\n assert ws.shape[1:] == (G.num_ws, G.w_dim)\n for idx, w in enumerate(ws):\n img = G.synthesis(w.unsqueeze(0), noise_mode=noise_mode)\n img = (img.permute(0, 2, 3, 1) * 127.5 + 128).clamp(0, 255).to(torch.uint8)\n img = PIL.Image.fromarray(img[0].cpu().numpy(), 'RGB').save(f'{outdir}/proj{idx:02d}.png')\n return\n\n # Labels.\n label = torch.zeros([1, G.c_dim], device=device)\n if G.c_dim != 0:\n if class_idx is None:\n ctx.fail('Must specify class label with --class when using a conditional network')\n label[:, class_idx] = 1\n else:\n if class_idx is not None:\n print ('warn: --class=lbl ignored when running on an unconditional network')\n\n\n if(process=='image'):\n if seeds is None:\n ctx.fail('--seeds option is required when not using --projected-w')\n\n # Generate images.\n for seed_idx, seed in enumerate(seeds):\n print('Generating image for seed %d (%d/%d) ...' % (seed, seed_idx, len(seeds)))\n z = torch.from_numpy(np.random.RandomState(seed).randn(1, G.z_dim)).to(device)\n img = G(z, label, truncation_psi=truncation_psi, noise_mode=noise_mode)\n img = (img.permute(0, 2, 3, 1) * 127.5 + 128).clamp(0, 255).to(torch.uint8)\n PIL.Image.fromarray(img[0].cpu().numpy(), 'RGB').save(f'{outdir}/seed{seed:04d}.png')\n\n elif(process=='interpolation' or process=='interpolation-truncation'):\n # create path for frames\n dirpath = os.path.join(outdir,'frames')\n os.makedirs(dirpath, exist_ok=True)\n\n # autogenerate video name: not great!\n if seeds is not None:\n seedstr = '_'.join([str(seed) for seed in seeds])\n vidname = f'{process}-{interpolation}-seeds_{seedstr}-{fps}fps'\n elif(interpolation=='noiseloop' or 'circularloop'):\n vidname = f'{process}-{interpolation}-{diameter}dia-seed_{random_seed}-{fps}fps'\n\n if process=='interpolation-truncation':\n interpolate(G,device,projected_w,seeds,random_seed,space,truncation_psi,label,frames,noise_mode,dirpath,interpolation,easing,diameter,start,stop)\n else:\n interpolate(G,device,projected_w,seeds,random_seed,space,truncation_psi,label,frames,noise_mode,dirpath,interpolation,easing,diameter)\n\n # convert to video\n cmd=f'ffmpeg -y -r {fps} -i {dirpath}/frame%04d.png -vcodec libx264 -pix_fmt yuv420p {outdir}/{vidname}.mp4'\n subprocess.call(cmd, shell=True)\n\n elif(process=='truncation'):\n if seeds is None or (len(seeds)>1):\n ctx.fail('truncation requires a single seed value')\n\n # create path for frames\n dirpath = os.path.join(outdir,'frames')\n os.makedirs(dirpath, exist_ok=True)\n\n #vidname\n seed = seeds[0]\n vidname = f'{process}-seed_{seed}-start_{start}-stop_{stop}-inc_{increment}-{fps}fps'\n\n # generate frames\n truncation_traversal(G,device,seeds,label,start,stop,increment,noise_mode,dirpath)\n\n # convert to video\n cmd=f'ffmpeg -y -r {fps} -i {dirpath}/frame%04d.png -vcodec libx264 -pix_fmt yuv420p {outdir}/{vidname}.mp4'\n subprocess.call(cmd, shell=True)\n\n#----------------------------------------------------------------------------\n\nif __name__ == \"__main__\":\n generate_images() # pylint: disable=no-value-for-parameter\n\n#----------------------------------------------------------------------------\n" ]
[ [ "numpy.abs", "numpy.sqrt", "torch.zeros", "numpy.asarray", "numpy.arccos", "numpy.linalg.norm", "numpy.sin", "numpy.cos", "torch.tensor", "numpy.copy", "torch.from_numpy", "numpy.random.randn", "torch.device", "numpy.load", "numpy.random.RandomState", "numpy.sum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
mgxd/nitransforms
[ "a922f3cb8ee1df5b484f617c34e1816a726e54e0" ]
[ "nitransforms/tests/test_affines.py" ]
[ "import numpy as np\nfrom nibabel.affines import from_matvec\nfrom nibabel.eulerangles import euler2mat\nfrom ..patched import obliquity\n\ndef test_obliquity():\n \"\"\"Check the calculation of inclination of an affine axes.\"\"\"\n from math import pi\n aligned = np.diag([2.0, 2.0, 2.3, 1.0])\n aligned[:-1, -1] = [-10, -10, -7]\n R = from_matvec(euler2mat(x=0.09, y=0.001, z=0.001), [0.0, 0.0, 0.0])\n oblique = R.dot(aligned)\n np.testing.assert_almost_equal(obliquity(aligned), [0.0, 0.0, 0.0])\n np.testing.assert_almost_equal(obliquity(oblique) * 180 / pi,\n [0.0810285, 5.1569949, 5.1569376])\n" ]
[ [ "numpy.diag" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
lizhihao6/HINet
[ "8c3fb71dc3331be32a9af3e1efe5106a0b26cefe" ]
[ "basicsr/data/reds_dataset.py" ]
[ "# ------------------------------------------------------------------------\n# Copyright (c) 2021 megvii-model. All Rights Reserved.\n# ------------------------------------------------------------------------\n# Modified from BasicSR (https://github.com/xinntao/BasicSR)\n# Copyright 2018-2020 BasicSR Authors\n# ------------------------------------------------------------------------\nimport random\nfrom pathlib import Path\n\nimport numpy as np\nimport torch\nfrom torch.utils import data as data\n\nfrom basicsr.data.transforms import augment, paired_random_crop\nfrom basicsr.utils import FileClient, get_root_logger, imfrombytes, img2tensor\nfrom basicsr.utils.flow_util import dequantize_flow\n\n\nclass REDSDataset(data.Dataset):\n \"\"\"REDS dataset for training.\n\n The keys are generated from a meta info txt file.\n basicsr/data/meta_info/meta_info_REDS_GT.txt\n\n Each line contains:\n 1. subfolder (clip) name; 2. frame number; 3. image shape, seperated by\n a white space.\n Examples:\n 000 100 (720,1280,3)\n 001 100 (720,1280,3)\n ...\n\n Key examples: \"000/00000000\"\n GT (gt): Ground-Truth;\n LQ (lq): Low-Quality, e.g., low-resolution/blurry/noisy/compressed frames.\n\n Args:\n opt (dict): Config for train dataset. It contains the following keys:\n dataroot_gt (str): Data root path for gt.\n dataroot_lq (str): Data root path for lq.\n dataroot_flow (str, optional): Data root path for flow.\n meta_info_file (str): Path for meta information file.\n val_partition (str): Validation partition types. 'REDS4' or\n 'official'.\n io_backend (dict): IO backend type and other kwarg.\n\n num_frame (int): Window size for input frames.\n gt_size (int): Cropped patched size for gt patches.\n interval_list (list): Interval list for temporal augmentation.\n random_reverse (bool): Random reverse input frames.\n use_flip (bool): Use horizontal flips.\n use_rot (bool): Use rotation (use vertical flip and transposing h\n and w for implementation).\n\n scale (bool): Scale, which will be added automatically.\n \"\"\"\n\n def __init__(self, opt):\n super(REDSDataset, self).__init__()\n self.opt = opt\n self.gt_root, self.lq_root = Path(opt['dataroot_gt']), Path(\n opt['dataroot_lq'])\n self.flow_root = Path(\n opt['dataroot_flow']) if opt['dataroot_flow'] is not None else None\n assert opt['num_frame'] % 2 == 1, (\n f'num_frame should be odd number, but got {opt[\"num_frame\"]}')\n self.num_frame = opt['num_frame']\n self.num_half_frames = opt['num_frame'] // 2\n\n self.keys = []\n with open(opt['meta_info_file'], 'r') as fin:\n for line in fin:\n folder, frame_num, _ = line.split(' ')\n self.keys.extend(\n [f'{folder}/{i:08d}' for i in range(int(frame_num))])\n\n # remove the video clips used in validation\n if opt['val_partition'] == 'REDS4':\n val_partition = ['000', '011', '015', '020']\n elif opt['val_partition'] == 'official':\n val_partition = [f'{v:03d}' for v in range(240, 270)]\n else:\n raise ValueError(\n f'Wrong validation partition {opt[\"val_partition\"]}.'\n f\"Supported ones are ['official', 'REDS4'].\")\n self.keys = [\n v for v in self.keys if v.split('/')[0] not in val_partition\n ]\n\n # file client (io backend)\n self.file_client = None\n self.io_backend_opt = opt['io_backend']\n self.is_lmdb = False\n if self.io_backend_opt['type'] == 'lmdb':\n self.is_lmdb = True\n if self.flow_root is not None:\n self.io_backend_opt['db_paths'] = [\n self.lq_root, self.gt_root, self.flow_root\n ]\n self.io_backend_opt['client_keys'] = ['lq', 'gt', 'flow']\n else:\n self.io_backend_opt['db_paths'] = [self.lq_root, self.gt_root]\n self.io_backend_opt['client_keys'] = ['lq', 'gt']\n\n # temporal augmentation configs\n self.interval_list = opt['interval_list']\n self.random_reverse = opt['random_reverse']\n interval_str = ','.join(str(x) for x in opt['interval_list'])\n logger = get_root_logger()\n logger.info(f'Temporal augmentation interval list: [{interval_str}]; '\n f'random reverse is {self.random_reverse}.')\n\n def __getitem__(self, index):\n if self.file_client is None:\n self.file_client = FileClient(\n self.io_backend_opt.pop('type'), **self.io_backend_opt)\n\n scale = self.opt['scale']\n gt_size = self.opt['gt_size']\n key = self.keys[index]\n clip_name, frame_name = key.split('/') # key example: 000/00000000\n center_frame_idx = int(frame_name)\n\n # determine the neighboring frames\n interval = random.choice(self.interval_list)\n\n # ensure not exceeding the borders\n start_frame_idx = center_frame_idx - self.num_half_frames * interval\n end_frame_idx = center_frame_idx + self.num_half_frames * interval\n # each clip has 100 frames starting from 0 to 99\n while (start_frame_idx < 0) or (end_frame_idx > 99):\n center_frame_idx = random.randint(0, 99)\n start_frame_idx = (\n center_frame_idx - self.num_half_frames * interval)\n end_frame_idx = center_frame_idx + self.num_half_frames * interval\n frame_name = f'{center_frame_idx:08d}'\n neighbor_list = list(\n range(center_frame_idx - self.num_half_frames * interval,\n center_frame_idx + self.num_half_frames * interval + 1,\n interval))\n # random reverse\n if self.random_reverse and random.random() < 0.5:\n neighbor_list.reverse()\n\n assert len(neighbor_list) == self.num_frame, (\n f'Wrong length of neighbor list: {len(neighbor_list)}')\n\n # get the GT frame (as the center frame)\n if self.is_lmdb:\n img_gt_path = f'{clip_name}/{frame_name}'\n else:\n img_gt_path = self.gt_root / clip_name / f'{frame_name}.png'\n img_bytes = self.file_client.get(img_gt_path, 'gt')\n img_gt = imfrombytes(img_bytes, float32=True)\n\n # get the neighboring LQ frames\n img_lqs = []\n for neighbor in neighbor_list:\n if self.is_lmdb:\n img_lq_path = f'{clip_name}/{neighbor:08d}'\n else:\n img_lq_path = self.lq_root / clip_name / f'{neighbor:08d}.png'\n img_bytes = self.file_client.get(img_lq_path, 'lq')\n img_lq = imfrombytes(img_bytes, float32=True)\n img_lqs.append(img_lq)\n\n # get flows\n if self.flow_root is not None:\n img_flows = []\n # read previous flows\n for i in range(self.num_half_frames, 0, -1):\n if self.is_lmdb:\n flow_path = f'{clip_name}/{frame_name}_p{i}'\n else:\n flow_path = (\n self.flow_root / clip_name / f'{frame_name}_p{i}.png')\n img_bytes = self.file_client.get(flow_path, 'flow')\n cat_flow = imfrombytes(\n img_bytes, flag='grayscale',\n float32=False) # uint8, [0, 255]\n dx, dy = np.split(cat_flow, 2, axis=0)\n flow = dequantize_flow(\n dx, dy, max_val=20,\n denorm=False) # we use max_val 20 here.\n img_flows.append(flow)\n # read next flows\n for i in range(1, self.num_half_frames + 1):\n if self.is_lmdb:\n flow_path = f'{clip_name}/{frame_name}_n{i}'\n else:\n flow_path = (\n self.flow_root / clip_name / f'{frame_name}_n{i}.png')\n img_bytes = self.file_client.get(flow_path, 'flow')\n cat_flow = imfrombytes(\n img_bytes, flag='grayscale',\n float32=False) # uint8, [0, 255]\n dx, dy = np.split(cat_flow, 2, axis=0)\n flow = dequantize_flow(\n dx, dy, max_val=20,\n denorm=False) # we use max_val 20 here.\n img_flows.append(flow)\n\n # for random crop, here, img_flows and img_lqs have the same\n # spatial size\n img_lqs.extend(img_flows)\n\n # randomly crop\n img_gt, img_lqs = paired_random_crop(img_gt, img_lqs, gt_size, scale,\n img_gt_path)\n if self.flow_root is not None:\n img_lqs, img_flows = img_lqs[:self.num_frame], img_lqs[self.\n num_frame:]\n\n # augmentation - flip, rotate\n img_lqs.append(img_gt)\n if self.flow_root is not None:\n img_results, img_flows = augment(img_lqs, self.opt['use_flip'],\n self.opt['use_rot'], img_flows)\n else:\n img_results = augment(img_lqs, self.opt['use_flip'],\n self.opt['use_rot'])\n\n img_results = img2tensor(img_results)\n img_lqs = torch.stack(img_results[0:-1], dim=0)\n img_gt = img_results[-1]\n\n if self.flow_root is not None:\n img_flows = img2tensor(img_flows)\n # add the zero center flow\n img_flows.insert(self.num_half_frames,\n torch.zeros_like(img_flows[0]))\n img_flows = torch.stack(img_flows, dim=0)\n\n # img_lqs: (t, c, h, w)\n # img_flows: (t, 2, h, w)\n # img_gt: (c, h, w)\n # key: str\n if self.flow_root is not None:\n return {'lq': img_lqs, 'flow': img_flows, 'gt': img_gt, 'key': key}\n else:\n return {'lq': img_lqs, 'gt': img_gt, 'key': key}\n\n def __len__(self):\n return len(self.keys)\n" ]
[ [ "torch.stack", "numpy.split", "torch.zeros_like" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ProFatXuanAll/char-RNN
[ "531f101b3d1ba20bafd28ca060aafe6f583d1efb" ]
[ "test/lmp/model/_lstm_1997/test_pred.py" ]
[ "\"\"\"Test prediction.\n\nTest target:\n- :py:meth:`lmp.model._lstm_1997.LSTM1997.pred`.\n\"\"\"\n\nimport torch\n\nfrom lmp.model._lstm_1997 import LSTM1997\n\n\ndef test_prediction_result(lstm_1997: LSTM1997, batch_cur_tkids: torch.Tensor) -> None:\n \"\"\"Return float tensor with correct shape and range.\"\"\"\n lstm_1997 = lstm_1997.eval()\n seq_len = batch_cur_tkids.size(1)\n\n batch_prev_states = None\n for i in range(seq_len):\n batch_next_tkids_pd, batch_prev_states = lstm_1997.pred(\n batch_cur_tkids=batch_cur_tkids[..., i],\n batch_prev_states=batch_prev_states,\n )\n\n # Output float tensor.\n assert batch_next_tkids_pd.dtype == torch.float\n\n # Shape: (batch_size, vocab_size).\n assert batch_next_tkids_pd.size() == torch.Size([batch_cur_tkids.shape[0], lstm_1997.emb.num_embeddings])\n\n # Probabilities are values within range [0, 1].\n assert torch.all(0 <= batch_next_tkids_pd).item()\n assert torch.all(batch_next_tkids_pd <= 1).item()\n\n # Sum of the probabilities equals to 1.\n accum = batch_next_tkids_pd.sum(dim=-1)\n assert torch.allclose(accum, torch.ones_like(accum))\n\n assert isinstance(batch_prev_states, list)\n assert len(batch_prev_states) == 2\n assert batch_prev_states[0].size() == torch.Size([batch_cur_tkids.size(0), lstm_1997.n_blk * lstm_1997.d_blk])\n assert batch_prev_states[1].size() == torch.Size([batch_cur_tkids.size(0), lstm_1997.n_blk, lstm_1997.d_blk])\n" ]
[ [ "torch.all", "torch.Size", "torch.ones_like" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
prteek/sagemaker-boilerplate
[ "372ff5722e5f4b5e2d84008e7186762b5bade2ad" ]
[ "non_linear_model.py" ]
[ "#! /opt/conda/envs/env/bin/python\nimport argparse\nimport os\nfrom sklearn.ensemble import RandomForestClassifier\nimport pandas as pd\nimport joblib\nfrom sklearn.metrics import accuracy_score\n\n\nif __name__ == '__main__':\n \n parser = argparse.ArgumentParser()\n \n parser.add_argument(\"--model-dir\", default=\"/opt/ml/model/\")\n parser.add_argument(\"--training\", default=\"/opt/ml/input/data/training\")\n parser.add_argument(\"--alpha\", type=float, default=0.0001)\n \n args = parser.parse_args()\n \n \n df = pd.read_csv(os.path.join(args.training, 'transfusion.data'))\n\n predictors = ['Recency (months)', 'Time (months)', 'Frequency (times)', 'Monetary (c.c. blood)']\n\n target = 'whether he/she donated blood in March 2007'\n\n X = df[predictors]\n y = df[target]\n \n estimator = RandomForestClassifier()\n \n estimator.fit(X,y)\n \n print(f\"accuracy={accuracy_score(y, estimator.predict(X))};\")\n \n joblib.dump(estimator, os.path.join(args.model_dir, 'model.mdl'))\n \n " ]
[ [ "sklearn.ensemble.RandomForestClassifier" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Anon-Artist/tfx
[ "2692c9ab437d76b5d9517996bfe2596862e0791d", "2692c9ab437d76b5d9517996bfe2596862e0791d", "2692c9ab437d76b5d9517996bfe2596862e0791d", "2692c9ab437d76b5d9517996bfe2596862e0791d", "2692c9ab437d76b5d9517996bfe2596862e0791d", "2692c9ab437d76b5d9517996bfe2596862e0791d", "2692c9ab437d76b5d9517996bfe2596862e0791d", "2692c9ab437d76b5d9517996bfe2596862e0791d", "2692c9ab437d76b5d9517996bfe2596862e0791d", "2692c9ab437d76b5d9517996bfe2596862e0791d" ]
[ "tfx/components/example_validator/component_test.py", "tfx/components/trainer/component_test.py", "tfx/orchestration/portable/runtime_parameter_utils_test.py", "tfx/dsl/experimental/latest_artifacts_resolver_test.py", "tfx/orchestration/experimental/kubernetes/kubernetes_dag_runner_test.py", "tfx/examples/chicago_taxi_pipeline/taxi_utils_native_keras.py", "tfx/experimental/templates/penguin/models/model.py", "tfx/experimental/pipeline_testing/stub_component_launcher_test.py", "tfx/components/util/udf_utils_test.py", "tfx/experimental/templates/taxi/models/preprocessing.py" ]
[ "# Lint as: python2, python3\n# Copyright 2019 Google LLC. 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 tfx.components.example_validator.component.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\nfrom tfx.components.example_validator import component\nfrom tfx.types import artifact_utils\nfrom tfx.types import channel_utils\nfrom tfx.types import standard_artifacts\nfrom tfx.types.standard_component_specs import ANOMALIES_KEY\nfrom tfx.types.standard_component_specs import EXCLUDE_SPLITS_KEY\n\n\nclass ExampleValidatorTest(tf.test.TestCase):\n\n def testConstruct(self):\n statistics_artifact = standard_artifacts.ExampleStatistics()\n statistics_artifact.split_names = artifact_utils.encode_split_names(\n ['train', 'eval'])\n exclude_splits = ['eval']\n example_validator = component.ExampleValidator(\n statistics=channel_utils.as_channel([statistics_artifact]),\n schema=channel_utils.as_channel([standard_artifacts.Schema()]),\n exclude_splits=exclude_splits)\n self.assertEqual(\n standard_artifacts.ExampleAnomalies.TYPE_NAME,\n example_validator.outputs[ANOMALIES_KEY].type_name)\n self.assertEqual(\n example_validator.spec.exec_properties[EXCLUDE_SPLITS_KEY], '[\"eval\"]')\n\n\nif __name__ == '__main__':\n tf.test.main()\n", "# Lint as: python2, python3\n# Copyright 2019 Google LLC. 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 tfx.components.trainer.component.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom typing import Text\n\nimport tensorflow as tf\nfrom tfx.components.trainer import component\nfrom tfx.components.trainer import executor\nfrom tfx.dsl.components.base import executor_spec\nfrom tfx.orchestration import data_types\nfrom tfx.proto import trainer_pb2\nfrom tfx.types import channel_utils\nfrom tfx.types import standard_artifacts\n\n\nclass ComponentTest(tf.test.TestCase):\n\n def setUp(self):\n super(ComponentTest, self).setUp()\n\n self.examples = channel_utils.as_channel([standard_artifacts.Examples()])\n self.transform_output = channel_utils.as_channel(\n [standard_artifacts.TransformGraph()])\n self.schema = channel_utils.as_channel([standard_artifacts.Schema()])\n self.hyperparameters = channel_utils.as_channel(\n [standard_artifacts.HyperParameters()])\n self.train_args = trainer_pb2.TrainArgs(splits=['train'], num_steps=100)\n self.eval_args = trainer_pb2.EvalArgs(splits=['eval'], num_steps=50)\n\n def _verify_outputs(self, trainer):\n self.assertEqual(standard_artifacts.Model.TYPE_NAME,\n trainer.outputs['model'].type_name)\n self.assertEqual(standard_artifacts.ModelRun.TYPE_NAME,\n trainer.outputs['model_run'].type_name)\n\n def testConstructFromModuleFile(self):\n module_file = '/path/to/module/file'\n trainer = component.Trainer(\n module_file=module_file,\n transformed_examples=self.examples,\n transform_graph=self.transform_output,\n schema=self.schema,\n train_args=self.train_args,\n eval_args=self.eval_args)\n self._verify_outputs(trainer)\n self.assertEqual(module_file, trainer.spec.exec_properties['module_file'])\n\n def testConstructWithParameter(self):\n module_file = data_types.RuntimeParameter(name='module-file', ptype=Text)\n n_steps = data_types.RuntimeParameter(name='n-steps', ptype=int)\n trainer = component.Trainer(\n module_file=module_file,\n transformed_examples=self.examples,\n transform_graph=self.transform_output,\n schema=self.schema,\n train_args=dict(splits=['train'], num_steps=n_steps),\n eval_args=dict(splits=['eval'], num_steps=n_steps))\n self._verify_outputs(trainer)\n self.assertJsonEqual(\n str(module_file), str(trainer.spec.exec_properties['module_file']))\n\n def testConstructFromTrainerFn(self):\n trainer_fn = 'path.to.my_trainer_fn'\n trainer = component.Trainer(\n trainer_fn=trainer_fn,\n transformed_examples=self.examples,\n transform_graph=self.transform_output,\n train_args=self.train_args,\n eval_args=self.eval_args)\n self._verify_outputs(trainer)\n self.assertEqual(trainer_fn, trainer.spec.exec_properties['trainer_fn'])\n\n def testConstructFromRunFn(self):\n run_fn = 'path.to.my_run_fn'\n trainer = component.Trainer(\n run_fn=run_fn,\n custom_executor_spec=executor_spec.ExecutorClassSpec(\n executor.GenericExecutor),\n transformed_examples=self.examples,\n transform_graph=self.transform_output,\n train_args=self.train_args,\n eval_args=self.eval_args)\n self._verify_outputs(trainer)\n self.assertEqual(run_fn, trainer.spec.exec_properties['run_fn'])\n\n def testConstructWithoutTransformOutput(self):\n module_file = '/path/to/module/file'\n trainer = component.Trainer(\n module_file=module_file,\n examples=self.examples,\n train_args=self.train_args,\n eval_args=self.eval_args)\n self._verify_outputs(trainer)\n self.assertEqual(module_file, trainer.spec.exec_properties['module_file'])\n\n def testConstructDuplicateExamples(self):\n with self.assertRaises(ValueError):\n _ = component.Trainer(\n module_file='/path/to/module/file',\n examples=self.examples,\n transformed_examples=self.examples,\n schema=self.schema,\n train_args=self.train_args,\n eval_args=self.eval_args)\n\n def testConstructMissingTransformOutput(self):\n with self.assertRaises(ValueError):\n _ = component.Trainer(\n module_file='/path/to/module/file',\n transformed_examples=self.examples,\n schema=self.schema,\n train_args=self.train_args,\n eval_args=self.eval_args)\n\n def testConstructMissingUserModule(self):\n with self.assertRaises(ValueError):\n _ = component.Trainer(\n examples=self.examples,\n transform_graph=self.transform_output,\n schema=self.schema,\n train_args=self.train_args,\n eval_args=self.eval_args)\n\n def testConstructDuplicateUserModule(self):\n with self.assertRaises(ValueError):\n _ = component.Trainer(\n module_file='/path/to/module/file',\n trainer_fn='path.to.my_trainer_fn',\n examples=self.examples,\n transform_graph=self.transform_output,\n schema=self.schema,\n train_args=self.train_args,\n eval_args=self.eval_args)\n\n with self.assertRaises(ValueError):\n _ = component.Trainer(\n module_file='/path/to/module/file',\n run_fn='path.to.my_run_fn',\n examples=self.examples,\n transform_graph=self.transform_output,\n schema=self.schema,\n train_args=self.train_args,\n eval_args=self.eval_args)\n\n def testConstructWithHParams(self):\n trainer = component.Trainer(\n trainer_fn='path.to.my_trainer_fn',\n transformed_examples=self.examples,\n transform_graph=self.transform_output,\n schema=self.schema,\n hyperparameters=self.hyperparameters,\n train_args=self.train_args,\n eval_args=self.eval_args)\n self._verify_outputs(trainer)\n self.assertEqual(standard_artifacts.HyperParameters.TYPE_NAME,\n trainer.inputs['hyperparameters'].type_name)\n\n\nif __name__ == '__main__':\n tf.test.main()\n", "# Copyright 2020 Google LLC. 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 tfx.orchestration.portable.runtime_parameter_utils.\"\"\"\nimport os\n\nimport tensorflow as tf\n\nfrom tfx.orchestration.portable import runtime_parameter_utils\nfrom tfx.proto.orchestration import pipeline_pb2\nfrom tfx.utils import test_case_utils\n\nfrom ml_metadata.proto import metadata_store_pb2\n\n\nclass RuntimeParameterUtilsTest(test_case_utils.TfxTest):\n\n def setUp(self):\n super().setUp()\n self._connection_config = metadata_store_pb2.ConnectionConfig()\n self._connection_config.sqlite.SetInParent()\n self._testdata_dir = os.path.join(os.path.dirname(__file__), 'testdata')\n\n def testFullySubstituteRuntimeParameter(self):\n pipeline = pipeline_pb2.Pipeline()\n expected = pipeline_pb2.Pipeline()\n self.load_proto_from_text(\n os.path.join(self._testdata_dir,\n 'pipeline_with_runtime_parameter.pbtxt'), pipeline)\n self.load_proto_from_text(\n os.path.join(self._testdata_dir,\n 'pipeline_with_runtime_parameter_substituted.pbtxt'),\n expected)\n runtime_parameter_utils.substitute_runtime_parameter(\n pipeline, {\n 'context_name_rp': 'my_context',\n 'prop_one_rp': 2,\n 'prop_two_rp': 'X'\n })\n self.assertProtoEquals(pipeline, expected)\n\n def testPartiallySubstituteRuntimeParameter(self):\n pipeline = pipeline_pb2.Pipeline()\n expected = pipeline_pb2.Pipeline()\n self.load_proto_from_text(\n os.path.join(self._testdata_dir,\n 'pipeline_with_runtime_parameter.pbtxt'), pipeline)\n self.load_proto_from_text(\n os.path.join(\n self._testdata_dir,\n 'pipeline_with_runtime_parameter_partially_substituted.pbtxt'),\n expected)\n runtime_parameter_utils.substitute_runtime_parameter(\n pipeline, {\n 'context_name_rp': 'my_context',\n })\n self.assertProtoEquals(pipeline, expected)\n\n def testSubstituteRuntimeParameterFail(self):\n pipeline = pipeline_pb2.Pipeline()\n self.load_proto_from_text(\n os.path.join(self._testdata_dir,\n 'pipeline_with_runtime_parameter.pbtxt'), pipeline)\n with self.assertRaisesRegex(RuntimeError, 'Runtime parameter type'):\n runtime_parameter_utils.substitute_runtime_parameter(\n pipeline,\n {\n 'context_name_rp': 0, # Wrong type, will lead to failure.\n 'prop_one_rp': 2,\n 'prop_two_rp': 'X'\n })\n\n\nif __name__ == '__main__':\n tf.test.main()\n", "# Lint as: python2, python3\n# Copyright 2019 Google LLC. 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\"\"\"Resolver for getting latest n artifacts.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n# Standard Imports\n\nimport tensorflow as tf\nfrom tfx import types\nfrom tfx.dsl.experimental import latest_artifacts_resolver\nfrom tfx.orchestration import data_types\nfrom tfx.orchestration import metadata\nfrom tfx.types import standard_artifacts\n\nfrom ml_metadata.proto import metadata_store_pb2\n\n\nclass LatestArtifactsResolverTest(tf.test.TestCase):\n\n def setUp(self):\n super(LatestArtifactsResolverTest, self).setUp()\n self._connection_config = metadata_store_pb2.ConnectionConfig()\n self._connection_config.sqlite.SetInParent()\n self._pipeline_info = data_types.PipelineInfo(\n pipeline_name='my_pipeline', pipeline_root='/tmp', run_id='my_run_id')\n self._component_info = data_types.ComponentInfo(\n component_type='a.b.c',\n component_id='my_component',\n pipeline_info=self._pipeline_info)\n\n def testGetLatestArtifact(self):\n with metadata.Metadata(connection_config=self._connection_config) as m:\n contexts = m.register_pipeline_contexts_if_not_exists(self._pipeline_info)\n artifact_one = standard_artifacts.Examples()\n artifact_one.uri = 'uri_one'\n m.publish_artifacts([artifact_one])\n artifact_two = standard_artifacts.Examples()\n artifact_two.uri = 'uri_two'\n m.register_execution(\n exec_properties={},\n pipeline_info=self._pipeline_info,\n component_info=self._component_info,\n contexts=contexts)\n m.publish_execution(\n component_info=self._component_info,\n output_artifacts={'key': [artifact_one, artifact_two]})\n expected_artifact = max(artifact_one, artifact_two, key=lambda a: a.id)\n\n resolver = latest_artifacts_resolver.LatestArtifactsResolver()\n resolve_result = resolver.resolve(\n pipeline_info=self._pipeline_info,\n metadata_handler=m,\n source_channels={\n 'input':\n types.Channel(\n type=artifact_one.type,\n producer_component_id=self._component_info.component_id,\n output_key='key')\n })\n\n self.assertTrue(resolve_result.has_complete_result)\n self.assertEqual([\n artifact.uri\n for artifact in resolve_result.per_key_resolve_result['input']\n ], [expected_artifact.uri])\n self.assertTrue(resolve_result.per_key_resolve_state['input'])\n\n def testGetLatestArtifact_IrMode(self):\n with metadata.Metadata(connection_config=self._connection_config) as m:\n artifact_one = standard_artifacts.Examples()\n artifact_one.uri = 'uri_one'\n artifact_one.id = 1\n artifact_two = standard_artifacts.Examples()\n artifact_two.uri = 'uri_two'\n artifact_one.id = 2\n\n expected_artifact = max(artifact_one, artifact_two, key=lambda a: a.id)\n\n resolver = latest_artifacts_resolver.LatestArtifactsResolver()\n result = resolver.resolve_artifacts(\n m, {'input': [artifact_two, artifact_one]})\n self.assertIsNotNone(result)\n self.assertEqual([a.uri for a in result['input']],\n [expected_artifact.uri])\n\n\nif __name__ == '__main__':\n tf.test.main()\n", "# Copyright 2020 Google LLC. 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 tfx.orchestration.kubernetes.kubernetes_dag_runner.\"\"\"\n\nfrom typing import Optional, Text\n\nimport mock\nimport tensorflow as tf\nfrom tfx import types\nfrom tfx.dsl.components.base import base_component\nfrom tfx.dsl.components.base import base_executor\nfrom tfx.dsl.components.base import base_node\nfrom tfx.dsl.components.base import executor_spec\nfrom tfx.orchestration import pipeline\nfrom tfx.orchestration.experimental.kubernetes import kubernetes_dag_runner\nfrom tfx.types.component_spec import ChannelParameter\n\nfrom ml_metadata.proto import metadata_store_pb2\n\n_executed_components = []\n\n\nclass _ArtifactTypeA(types.Artifact):\n TYPE_NAME = 'ArtifactTypeA'\n\n\nclass _ArtifactTypeB(types.Artifact):\n TYPE_NAME = 'ArtifactTypeB'\n\n\nclass _ArtifactTypeC(types.Artifact):\n TYPE_NAME = 'ArtifactTypeC'\n\n\nclass _ArtifactTypeD(types.Artifact):\n TYPE_NAME = 'ArtifactTypeD'\n\n\nclass _ArtifactTypeE(types.Artifact):\n TYPE_NAME = 'ArtifactTypeE'\n\n\ndef _initialize_executed_components():\n global _executed_components\n _executed_components = []\n\n\ndef _mock_launch_container_component(component: base_node.BaseNode, *_):\n _executed_components.append(component.id)\n\n\n# We define fake component spec classes below for testing. Note that we can't\n# programmatically generate component using anonymous classes for testing\n# because of a limitation in the \"dill\" pickler component used by Apache Beam.\n# An alternative we considered but rejected here was to write a function that\n# returns anonymous classes within that function's closure (as is done in\n# tfx/orchestration/pipeline_test.py), but that strategy does not work here\n# as these anonymous classes cannot be used with Beam, since they cannot be\n# pickled with the \"dill\" library.\nclass _FakeComponentSpecA(types.ComponentSpec):\n PARAMETERS = {}\n INPUTS = {}\n OUTPUTS = {'output': ChannelParameter(type=_ArtifactTypeA)}\n\n\nclass _FakeComponentSpecB(types.ComponentSpec):\n PARAMETERS = {}\n INPUTS = {'a': ChannelParameter(type=_ArtifactTypeA)}\n OUTPUTS = {'output': ChannelParameter(type=_ArtifactTypeB)}\n\n\nclass _FakeComponentSpecC(types.ComponentSpec):\n PARAMETERS = {}\n INPUTS = {'a': ChannelParameter(type=_ArtifactTypeA)}\n OUTPUTS = {'output': ChannelParameter(type=_ArtifactTypeC)}\n\n\nclass _FakeComponentSpecD(types.ComponentSpec):\n PARAMETERS = {}\n INPUTS = {\n 'b': ChannelParameter(type=_ArtifactTypeB),\n 'c': ChannelParameter(type=_ArtifactTypeC),\n }\n OUTPUTS = {'output': ChannelParameter(type=_ArtifactTypeD)}\n\n\nclass _FakeComponentSpecE(types.ComponentSpec):\n PARAMETERS = {}\n INPUTS = {\n 'a': ChannelParameter(type=_ArtifactTypeA),\n 'b': ChannelParameter(type=_ArtifactTypeB),\n 'd': ChannelParameter(type=_ArtifactTypeD),\n }\n OUTPUTS = {'output': ChannelParameter(type=_ArtifactTypeE)}\n\n\nclass _FakeComponentSpecF(types.ComponentSpec):\n PARAMETERS = {}\n INPUTS = {\n 'a': ChannelParameter(type=_ArtifactTypeA),\n }\n OUTPUTS = {}\n\n\nclass _FakeComponent(base_component.BaseComponent):\n\n SPEC_CLASS = types.ComponentSpec\n EXECUTOR_SPEC = executor_spec.ExecutorClassSpec(base_executor.BaseExecutor)\n\n def __init__(self,\n spec: types.ComponentSpec,\n instance_name: Optional[Text] = None):\n if instance_name is None:\n instance_name = spec.__class__.__name__.replace('_FakeComponentSpec',\n '').lower()\n super(_FakeComponent, self).__init__(spec=spec, instance_name=instance_name)\n\n\nclass KubernetesDagRunnerTest(tf.test.TestCase):\n\n @mock.patch.object(\n kubernetes_dag_runner,\n 'launch_container_component',\n _mock_launch_container_component,\n )\n @mock.patch.object(kubernetes_dag_runner, 'kube_utils')\n def testRun(self, mock_kube_utils):\n _initialize_executed_components()\n mock_kube_utils.is_inside_cluster.return_value = True\n\n component_a = _FakeComponent(\n spec=_FakeComponentSpecA(output=types.Channel(type=_ArtifactTypeA)))\n component_b = _FakeComponent(\n spec=_FakeComponentSpecB(\n a=component_a.outputs['output'],\n output=types.Channel(type=_ArtifactTypeB)))\n component_c = _FakeComponent(\n spec=_FakeComponentSpecC(\n a=component_a.outputs['output'],\n output=types.Channel(type=_ArtifactTypeC)))\n component_c.add_upstream_node(component_b)\n component_d = _FakeComponent(\n spec=_FakeComponentSpecD(\n b=component_b.outputs['output'],\n c=component_c.outputs['output'],\n output=types.Channel(type=_ArtifactTypeD)))\n component_e = _FakeComponent(\n spec=_FakeComponentSpecE(\n a=component_a.outputs['output'],\n b=component_b.outputs['output'],\n d=component_d.outputs['output'],\n output=types.Channel(type=_ArtifactTypeE)))\n\n test_pipeline = pipeline.Pipeline(\n pipeline_name='x',\n pipeline_root='y',\n metadata_connection_config=metadata_store_pb2.ConnectionConfig(),\n components=[\n component_d, component_c, component_a, component_b, component_e\n ])\n\n kubernetes_dag_runner.KubernetesDagRunner().run(test_pipeline)\n self.assertEqual(_executed_components, [\n '_FakeComponent.a.Wrapper', '_FakeComponent.b.Wrapper',\n '_FakeComponent.c.Wrapper', '_FakeComponent.d.Wrapper',\n '_FakeComponent.e.Wrapper'\n ])\n\n @mock.patch.object(\n kubernetes_dag_runner,\n 'launch_container_component',\n _mock_launch_container_component,\n )\n @mock.patch.object(kubernetes_dag_runner, 'kube_utils')\n def testRunWithSameSpec(self, mock_kube_utils):\n _initialize_executed_components()\n mock_kube_utils.is_inside_cluster.return_value = True\n\n component_a = _FakeComponent(\n spec=_FakeComponentSpecA(output=types.Channel(type=_ArtifactTypeA)))\n component_f1 = _FakeComponent(\n spec=_FakeComponentSpecF(a=component_a.outputs['output']),\n instance_name='f1')\n component_f2 = _FakeComponent(\n spec=_FakeComponentSpecF(a=component_a.outputs['output']),\n instance_name='f2')\n component_f2.add_upstream_node(component_f1)\n\n test_pipeline = pipeline.Pipeline(\n pipeline_name='x',\n pipeline_root='y',\n metadata_connection_config=metadata_store_pb2.ConnectionConfig(),\n components=[component_f1, component_f2, component_a])\n kubernetes_dag_runner.KubernetesDagRunner().run(test_pipeline)\n self.assertEqual(_executed_components, [\n '_FakeComponent.a.Wrapper', '_FakeComponent.f1.Wrapper',\n '_FakeComponent.f2.Wrapper'\n ])\n\n\nif __name__ == '__main__':\n tf.test.main()\n", "# Lint as: python2, python3\n# Copyright 2019 Google LLC. 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# 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\"\"\"Python source file include taxi pipeline functions and necesasry utils.\n\nThe utilities in this file are used to build a model with native Keras.\nThis module file will be used in Transform and generic Trainer.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom typing import List, Text\n\nimport absl\nimport tensorflow as tf\nimport tensorflow_transform as tft\n\nfrom tfx.components.trainer.fn_args_utils import DataAccessor\nfrom tfx.components.trainer.fn_args_utils import FnArgs\nfrom tfx_bsl.tfxio import dataset_options\n\n# Categorical features are assumed to each have a maximum value in the dataset.\n_MAX_CATEGORICAL_FEATURE_VALUES = [24, 31, 12]\n\n_CATEGORICAL_FEATURE_KEYS = [\n 'trip_start_hour', 'trip_start_day', 'trip_start_month',\n 'pickup_census_tract', 'dropoff_census_tract', 'pickup_community_area',\n 'dropoff_community_area'\n]\n\n_DENSE_FLOAT_FEATURE_KEYS = ['trip_miles', 'fare', 'trip_seconds']\n\n# Number of buckets used by tf.transform for encoding each feature.\n_FEATURE_BUCKET_COUNT = 10\n\n_BUCKET_FEATURE_KEYS = [\n 'pickup_latitude', 'pickup_longitude', 'dropoff_latitude',\n 'dropoff_longitude'\n]\n\n# Number of vocabulary terms used for encoding VOCAB_FEATURES by tf.transform\n_VOCAB_SIZE = 1000\n\n# Count of out-of-vocab buckets in which unrecognized VOCAB_FEATURES are hashed.\n_OOV_SIZE = 10\n\n_VOCAB_FEATURE_KEYS = [\n 'payment_type',\n 'company',\n]\n\n# Keys\n_LABEL_KEY = 'big_tipper'\n\n\ndef _transformed_name(key):\n return key + '_xf'\n\n\ndef _transformed_names(keys):\n return [_transformed_name(key) for key in keys]\n\n\ndef _fill_in_missing(x):\n \"\"\"Replace missing values in a SparseTensor.\n\n Fills in missing values of `x` with '' or 0, and converts to a dense tensor.\n\n Args:\n x: A `SparseTensor` of rank 2. Its dense shape should have size at most 1\n in the second dimension.\n\n Returns:\n A rank 1 tensor where missing values of `x` have been filled in.\n \"\"\"\n if not isinstance(x, tf.sparse.SparseTensor):\n return x\n\n default_value = '' if x.dtype == tf.string else 0\n return tf.squeeze(\n tf.sparse.to_dense(\n tf.SparseTensor(x.indices, x.values, [x.dense_shape[0], 1]),\n default_value),\n axis=1)\n\n\ndef _get_serve_tf_examples_fn(model, tf_transform_output):\n \"\"\"Returns a function that parses a serialized tf.Example and applies TFT.\"\"\"\n\n model.tft_layer = tf_transform_output.transform_features_layer()\n\n @tf.function\n def serve_tf_examples_fn(serialized_tf_examples):\n \"\"\"Returns the output to be used in the serving signature.\"\"\"\n feature_spec = tf_transform_output.raw_feature_spec()\n feature_spec.pop(_LABEL_KEY)\n parsed_features = tf.io.parse_example(serialized_tf_examples, feature_spec)\n\n transformed_features = model.tft_layer(parsed_features)\n\n return model(transformed_features)\n\n return serve_tf_examples_fn\n\n\ndef _input_fn(file_pattern: List[Text],\n data_accessor: DataAccessor,\n tf_transform_output: tft.TFTransformOutput,\n batch_size: int = 200) -> tf.data.Dataset:\n \"\"\"Generates features and label for tuning/training.\n\n Args:\n file_pattern: List of paths or patterns of input tfrecord files.\n data_accessor: DataAccessor for converting input to RecordBatch.\n tf_transform_output: A TFTransformOutput.\n batch_size: representing the number of consecutive elements of returned\n dataset to combine in a single batch\n\n Returns:\n A dataset that contains (features, indices) tuple where features is a\n dictionary of Tensors, and indices is a single Tensor of label indices.\n \"\"\"\n return data_accessor.tf_dataset_factory(\n file_pattern,\n dataset_options.TensorFlowDatasetOptions(\n batch_size=batch_size, label_key=_transformed_name(_LABEL_KEY)),\n tf_transform_output.transformed_metadata.schema)\n\n\ndef _build_keras_model(hidden_units: List[int] = None) -> tf.keras.Model:\n \"\"\"Creates a DNN Keras model for classifying taxi data.\n\n Args:\n hidden_units: [int], the layer sizes of the DNN (input layer first).\n\n Returns:\n A keras Model.\n \"\"\"\n real_valued_columns = [\n tf.feature_column.numeric_column(key, shape=())\n for key in _transformed_names(_DENSE_FLOAT_FEATURE_KEYS)\n ]\n categorical_columns = [\n tf.feature_column.categorical_column_with_identity(\n key, num_buckets=_VOCAB_SIZE + _OOV_SIZE, default_value=0)\n for key in _transformed_names(_VOCAB_FEATURE_KEYS)\n ]\n categorical_columns += [\n tf.feature_column.categorical_column_with_identity(\n key, num_buckets=_FEATURE_BUCKET_COUNT, default_value=0)\n for key in _transformed_names(_BUCKET_FEATURE_KEYS)\n ]\n categorical_columns += [\n tf.feature_column.categorical_column_with_identity( # pylint: disable=g-complex-comprehension\n key,\n num_buckets=num_buckets,\n default_value=0) for key, num_buckets in zip(\n _transformed_names(_CATEGORICAL_FEATURE_KEYS),\n _MAX_CATEGORICAL_FEATURE_VALUES)\n ]\n indicator_column = [\n tf.feature_column.indicator_column(categorical_column)\n for categorical_column in categorical_columns\n ]\n\n model = _wide_and_deep_classifier(\n # TODO(b/139668410) replace with premade wide_and_deep keras model\n wide_columns=indicator_column,\n deep_columns=real_valued_columns,\n dnn_hidden_units=hidden_units or [100, 70, 50, 25])\n return model\n\n\ndef _wide_and_deep_classifier(wide_columns, deep_columns, dnn_hidden_units):\n \"\"\"Build a simple keras wide and deep model.\n\n Args:\n wide_columns: Feature columns wrapped in indicator_column for wide (linear)\n part of the model.\n deep_columns: Feature columns for deep part of the model.\n dnn_hidden_units: [int], the layer sizes of the hidden DNN.\n\n Returns:\n A Wide and Deep Keras model\n \"\"\"\n # Following values are hard coded for simplicity in this example,\n # However prefarably they should be passsed in as hparams.\n\n # Keras needs the feature definitions at compile time.\n # TODO(b/139081439): Automate generation of input layers from FeatureColumn.\n input_layers = {\n colname: tf.keras.layers.Input(name=colname, shape=(), dtype=tf.float32)\n for colname in _transformed_names(_DENSE_FLOAT_FEATURE_KEYS)\n }\n input_layers.update({\n colname: tf.keras.layers.Input(name=colname, shape=(), dtype='int32')\n for colname in _transformed_names(_VOCAB_FEATURE_KEYS)\n })\n input_layers.update({\n colname: tf.keras.layers.Input(name=colname, shape=(), dtype='int32')\n for colname in _transformed_names(_BUCKET_FEATURE_KEYS)\n })\n input_layers.update({\n colname: tf.keras.layers.Input(name=colname, shape=(), dtype='int32')\n for colname in _transformed_names(_CATEGORICAL_FEATURE_KEYS)\n })\n\n # TODO(b/161952382): Replace with Keras premade models and\n # Keras preprocessing layers.\n deep = tf.keras.layers.DenseFeatures(deep_columns)(input_layers)\n for numnodes in dnn_hidden_units:\n deep = tf.keras.layers.Dense(numnodes)(deep)\n wide = tf.keras.layers.DenseFeatures(wide_columns)(input_layers)\n\n output = tf.keras.layers.Dense(\n 1, activation='sigmoid')(\n tf.keras.layers.concatenate([deep, wide]))\n output = tf.squeeze(output, -1)\n\n model = tf.keras.Model(input_layers, output)\n model.compile(\n loss='binary_crossentropy',\n optimizer=tf.keras.optimizers.Adam(lr=0.001),\n metrics=[tf.keras.metrics.BinaryAccuracy()])\n model.summary(print_fn=absl.logging.info)\n return model\n\n\n# TFX Transform will call this function.\ndef preprocessing_fn(inputs):\n \"\"\"tf.transform's callback function for preprocessing inputs.\n\n Args:\n inputs: map from feature keys to raw not-yet-transformed features.\n\n Returns:\n Map from string feature key to transformed feature operations.\n \"\"\"\n outputs = {}\n for key in _DENSE_FLOAT_FEATURE_KEYS:\n # Preserve this feature as a dense float, setting nan's to the mean.\n outputs[_transformed_name(key)] = tft.scale_to_z_score(\n _fill_in_missing(inputs[key]))\n\n for key in _VOCAB_FEATURE_KEYS:\n # Build a vocabulary for this feature.\n outputs[_transformed_name(key)] = tft.compute_and_apply_vocabulary(\n _fill_in_missing(inputs[key]),\n top_k=_VOCAB_SIZE,\n num_oov_buckets=_OOV_SIZE)\n\n for key in _BUCKET_FEATURE_KEYS:\n outputs[_transformed_name(key)] = tft.bucketize(\n _fill_in_missing(inputs[key]),\n _FEATURE_BUCKET_COUNT)\n\n for key in _CATEGORICAL_FEATURE_KEYS:\n outputs[_transformed_name(key)] = _fill_in_missing(inputs[key])\n\n # TODO(b/157064428): Support label transformation for Keras.\n # Do not apply label transformation as it will result in wrong evaluation.\n outputs[_transformed_name(_LABEL_KEY)] = inputs[_LABEL_KEY]\n\n return outputs\n\n\n# TFX Trainer will call this function.\ndef run_fn(fn_args: FnArgs):\n \"\"\"Train the model based on given args.\n\n Args:\n fn_args: Holds args used to train the model as name/value pairs.\n \"\"\"\n # Number of nodes in the first layer of the DNN\n first_dnn_layer_size = 100\n num_dnn_layers = 4\n dnn_decay_factor = 0.7\n\n tf_transform_output = tft.TFTransformOutput(fn_args.transform_output)\n\n train_dataset = _input_fn(fn_args.train_files, fn_args.data_accessor,\n tf_transform_output, 40)\n eval_dataset = _input_fn(fn_args.eval_files, fn_args.data_accessor,\n tf_transform_output, 40)\n\n mirrored_strategy = tf.distribute.MirroredStrategy()\n with mirrored_strategy.scope():\n model = _build_keras_model(\n # Construct layers sizes with exponetial decay\n hidden_units=[\n max(2, int(first_dnn_layer_size * dnn_decay_factor**i))\n for i in range(num_dnn_layers)\n ])\n\n # Write logs to path\n tensorboard_callback = tf.keras.callbacks.TensorBoard(\n log_dir=fn_args.model_run_dir, update_freq='batch')\n\n model.fit(\n train_dataset,\n steps_per_epoch=fn_args.train_steps,\n validation_data=eval_dataset,\n validation_steps=fn_args.eval_steps,\n callbacks=[tensorboard_callback])\n\n signatures = {\n 'serving_default':\n _get_serve_tf_examples_fn(model,\n tf_transform_output).get_concrete_function(\n tf.TensorSpec(\n shape=[None],\n dtype=tf.string,\n name='examples')),\n }\n model.save(fn_args.serving_model_dir, save_format='tf', signatures=signatures)\n", "# Lint as: python3\n# Copyright 2020 Google LLC. 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# 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\"\"\"TFX template penguin model.\n\nA DNN keras model which uses features defined in features.py and network\nparameters defined in constants.py.\n\"\"\"\n\nfrom typing import List, Text\nfrom absl import logging\nimport tensorflow as tf\nfrom tensorflow import keras\nimport tensorflow_transform as tft\nfrom tensorflow_transform.tf_metadata import schema_utils\n\nfrom tfx.components.trainer.executor import TrainerFnArgs\nfrom tfx.components.trainer.fn_args_utils import DataAccessor\nfrom tfx.experimental.templates.penguin.models import constants\nfrom tfx.experimental.templates.penguin.models import features\nfrom tfx.utils import io_utils\nfrom tfx_bsl.tfxio import dataset_options\n\nfrom tensorflow_metadata.proto.v0 import schema_pb2\n\n\ndef _get_serve_tf_examples_fn(model, schema, tf_transform_output):\n \"\"\"Returns a function that parses a serialized tf.Example.\"\"\"\n if tf_transform_output is None: # Transform component is not used.\n @tf.function\n def serve_tf_examples_fn(serialized_tf_examples):\n \"\"\"Returns the output to be used in the serving signature.\"\"\"\n feature_spec = schema_utils.schema_as_feature_spec(schema).feature_spec\n feature_spec.pop(features.LABEL_KEY)\n parsed_features = tf.io.parse_example(serialized_tf_examples,\n feature_spec)\n return model(parsed_features)\n\n else: # Transform component exists.\n model.tft_layer = tf_transform_output.transform_features_layer()\n\n @tf.function\n def serve_tf_examples_fn(serialized_tf_examples):\n \"\"\"Returns the output to be used in the serving signature.\"\"\"\n feature_spec = tf_transform_output.raw_feature_spec()\n feature_spec.pop(features.LABEL_KEY)\n parsed_features = tf.io.parse_example(serialized_tf_examples,\n feature_spec)\n transformed_features = model.tft_layer(parsed_features)\n return model(transformed_features)\n\n return serve_tf_examples_fn\n\n\ndef _input_fn(file_pattern: List[Text],\n data_accessor: DataAccessor,\n schema: schema_pb2.Schema,\n label: Text,\n batch_size: int = 200) -> tf.data.Dataset:\n \"\"\"Generates features and label for tuning/training.\n\n Args:\n file_pattern: List of paths or patterns of input tfrecord files.\n data_accessor: DataAccessor for converting input to RecordBatch.\n schema: A schema proto of input data.\n label: Name of the label.\n batch_size: representing the number of consecutive elements of returned\n dataset to combine in a single batch\n\n Returns:\n A dataset that contains (features, indices) tuple where features is a\n dictionary of Tensors, and indices is a single Tensor of label indices.\n \"\"\"\n return data_accessor.tf_dataset_factory(\n file_pattern,\n dataset_options.TensorFlowDatasetOptions(\n batch_size=batch_size,\n label_key=label), schema)\n\n\ndef _build_keras_model(feature_list: List[Text]) -> tf.keras.Model:\n \"\"\"Creates a DNN Keras model for classifying penguin data.\n\n Args:\n feature_list: List of feature names.\n\n Returns:\n A Keras Model.\n \"\"\"\n # The model below is built with Functional API, please refer to\n # https://www.tensorflow.org/guide/keras/overview for all API options.\n inputs = [keras.layers.Input(shape=(1,), name=f) for f in feature_list]\n d = keras.layers.concatenate(inputs)\n for _ in range(constants.NUM_LAYERS):\n d = keras.layers.Dense(constants.HIDDEN_LAYER_UNITS, activation='relu')(d)\n outputs = keras.layers.Dense(\n constants.OUTPUT_LAYER_UNITS, activation='softmax')(\n d)\n\n model = keras.Model(inputs=inputs, outputs=outputs)\n model.compile(\n optimizer=keras.optimizers.Adam(constants.LEARNING_RATE),\n loss='sparse_categorical_crossentropy',\n metrics=[keras.metrics.SparseCategoricalAccuracy()])\n\n model.summary(print_fn=logging.info)\n return model\n\n\n# TFX Trainer will call this function.\n# TODO(step 4): Construct, train and save your model in this function.\ndef run_fn(fn_args: TrainerFnArgs):\n \"\"\"Train the model based on given args.\n\n Args:\n fn_args: Holds args used to train the model as name/value pairs.\n \"\"\"\n if fn_args.transform_output is None: # Transform is not used.\n tf_transform_output = None\n schema = io_utils.parse_pbtxt_file(fn_args.schema_file, schema_pb2.Schema())\n feature_list = features.FEATURE_KEYS\n label_key = features.LABEL_KEY\n else:\n tf_transform_output = tft.TFTransformOutput(fn_args.transform_output)\n schema = tf_transform_output.transformed_metadata.schema\n feature_list = [features.transformed_name(f) for f in features.FEATURE_KEYS]\n label_key = features.transformed_name(features.LABEL_KEY)\n\n mirrored_strategy = tf.distribute.MirroredStrategy()\n train_batch_size = (\n constants.TRAIN_BATCH_SIZE * mirrored_strategy.num_replicas_in_sync)\n eval_batch_size = (\n constants.EVAL_BATCH_SIZE * mirrored_strategy.num_replicas_in_sync)\n\n train_dataset = _input_fn(\n fn_args.train_files,\n fn_args.data_accessor,\n schema,\n label_key,\n batch_size=train_batch_size)\n eval_dataset = _input_fn(\n fn_args.eval_files,\n fn_args.data_accessor,\n schema,\n label_key,\n batch_size=eval_batch_size)\n\n with mirrored_strategy.scope():\n model = _build_keras_model(feature_list)\n\n # Write logs to path\n tensorboard_callback = tf.keras.callbacks.TensorBoard(\n log_dir=fn_args.model_run_dir, update_freq='batch')\n\n steps_per_epoch = constants.TRAIN_DATA_SIZE // train_batch_size\n\n model.fit(\n train_dataset,\n epochs=fn_args.train_steps // steps_per_epoch,\n steps_per_epoch=steps_per_epoch,\n validation_data=eval_dataset,\n validation_steps=fn_args.eval_steps,\n callbacks=[tensorboard_callback])\n\n signatures = {\n 'serving_default':\n _get_serve_tf_examples_fn(model, schema,\n tf_transform_output).get_concrete_function(\n tf.TensorSpec(\n shape=[None],\n dtype=tf.string,\n name='examples')),\n }\n model.save(fn_args.serving_model_dir, save_format='tf', signatures=signatures)\n", "# Lint as: python3\n# Copyright 2020 Google LLC. 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 tfx.experimental.pipeline_testing.stub_component_launcher.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\n\nimport mock\nimport tensorflow as tf\n\nfrom tfx.dsl.io import fileio\nfrom tfx.experimental.pipeline_testing import stub_component_launcher\nfrom tfx.orchestration import data_types\nfrom tfx.orchestration import metadata\nfrom tfx.orchestration import publisher\nfrom tfx.orchestration.launcher import test_utils\nfrom tfx.types import channel_utils\nfrom tfx.utils import io_utils\n\nfrom ml_metadata.proto import metadata_store_pb2\n\n\nclass StubComponentLauncherTest(tf.test.TestCase):\n\n def setUp(self):\n super(StubComponentLauncherTest, self).setUp()\n test_dir = os.path.join(\n os.environ.get('TEST_UNDECLARED_OUTPUTS_DIR', self.get_temp_dir()),\n self._testMethodName)\n\n connection_config = metadata_store_pb2.ConnectionConfig()\n connection_config.sqlite.SetInParent()\n self.metadata_connection = metadata.Metadata(connection_config)\n\n self.pipeline_root = os.path.join(test_dir, 'Test')\n\n self.input_key = 'input'\n self.output_key = 'output'\n\n self.input_dir = os.path.join(test_dir, self.input_key)\n self.output_dir = os.path.join(test_dir, self.output_key)\n self.record_dir = os.path.join(test_dir, 'record')\n fileio.makedirs(self.input_dir)\n fileio.makedirs(self.output_dir)\n fileio.makedirs(self.record_dir)\n\n input_artifact = test_utils._InputArtifact() # pylint: disable=protected-access\n input_artifact.uri = os.path.join(self.input_dir, 'result.txt')\n output_artifact = test_utils._OutputArtifact() # pylint: disable=protected-access\n output_artifact.uri = os.path.join(self.output_dir, 'result.txt')\n self.component = test_utils._FakeComponent( # pylint: disable=protected-access\n name='FakeComponent',\n input_channel=channel_utils.as_channel([input_artifact]),\n output_channel=channel_utils.as_channel([output_artifact]))\n self.driver_args = data_types.DriverArgs(enable_cache=True)\n\n self.pipeline_info = data_types.PipelineInfo(\n pipeline_name='Test', pipeline_root=self.pipeline_root, run_id='123')\n\n @mock.patch.object(publisher, 'Publisher')\n def testStubExecutor(self, mock_publisher):\n # verify whether base stub executor substitution works\n mock_publisher.return_value.publish_execution.return_value = {}\n\n record_file = os.path.join(self.record_dir, self.component.id,\n self.output_key, '0', 'recorded.txt')\n io_utils.write_string_file(record_file, 'hello world')\n\n stub_component_launcher.StubComponentLauncher.initialize(\n test_data_dir=self.record_dir, test_component_ids=[])\n\n launcher = stub_component_launcher.StubComponentLauncher.create(\n component=self.component,\n pipeline_info=self.pipeline_info,\n driver_args=self.driver_args,\n metadata_connection=self.metadata_connection,\n beam_pipeline_args=[],\n additional_pipeline_args={})\n launcher.launch()\n\n output_path = self.component.outputs[self.output_key].get()[0].uri\n copied_file = os.path.join(output_path, 'recorded.txt')\n self.assertTrue(fileio.exists(copied_file))\n contents = io_utils.read_string_file(copied_file)\n self.assertEqual('hello world', contents)\n\n @mock.patch.object(publisher, 'Publisher')\n def testExecutor(self, mock_publisher):\n # verify whether original executors can run\n mock_publisher.return_value.publish_execution.return_value = {}\n\n io_utils.write_string_file(\n os.path.join(self.input_dir, 'result.txt'), 'test')\n\n stub_component_launcher.StubComponentLauncher.initialize(\n test_data_dir=self.record_dir, test_component_ids=[self.component.id])\n\n launcher = stub_component_launcher.StubComponentLauncher.create(\n component=self.component,\n pipeline_info=self.pipeline_info,\n driver_args=self.driver_args,\n metadata_connection=self.metadata_connection,\n beam_pipeline_args=[],\n additional_pipeline_args={})\n self.assertEqual(\n launcher._component_info.component_type, # pylint: disable=protected-access\n '.'.join([ # pylint: disable=protected-access\n test_utils._FakeComponent.__module__, # pylint: disable=protected-access\n test_utils._FakeComponent.__name__ # pylint: disable=protected-access\n ]))\n launcher.launch()\n\n output_path = self.component.outputs[self.output_key].get()[0].uri\n self.assertTrue(fileio.exists(output_path))\n contents = io_utils.read_string_file(output_path)\n self.assertEqual('test', contents)\n\n\nif __name__ == '__main__':\n tf.test.main()\n", "# Lint as: python2, python3\n# Copyright 2020 Google LLC. 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 tfx.components.util.udf_utils.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport mock\nimport tensorflow as tf\n\nfrom tfx.components.util import udf_utils\nfrom tfx.utils import import_utils\n\n\nclass UdfUtilsTest(tf.test.TestCase):\n\n @mock.patch.object(import_utils, 'import_func_from_source')\n def testGetFnFromSource(self, mock_import_func):\n exec_properties = {'module_file': 'path/to/module_file.py'}\n udf_utils.get_fn(exec_properties, 'test_fn')\n mock_import_func.assert_called_once_with('path/to/module_file.py',\n 'test_fn')\n\n @mock.patch.object(import_utils, 'import_func_from_module')\n def testGetFnFromModule(self, mock_import_func):\n exec_properties = {'module_path': 'path.to.module'}\n udf_utils.get_fn(exec_properties, 'test_fn')\n mock_import_func.assert_called_once_with('path.to.module', 'test_fn')\n\n @mock.patch.object(import_utils, 'import_func_from_module')\n def testGetFnFromModuleFn(self, mock_import_func):\n exec_properties = {'test_fn': 'path.to.module.test_fn'}\n udf_utils.get_fn(exec_properties, 'test_fn')\n mock_import_func.assert_called_once_with('path.to.module', 'test_fn')\n\n def testGetFnFailure(self):\n with self.assertRaises(ValueError):\n udf_utils.get_fn({}, 'test_fn')\n\n\nif __name__ == '__main__':\n tf.test.main()\n", "# Lint as: python2, python3\n# Copyright 2020 Google LLC. 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\"\"\"TFX taxi preprocessing.\n\nThis file defines a template for TFX Transform component.\n\"\"\"\n\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\nimport tensorflow_transform as tft\n\nfrom tfx.experimental.templates.taxi.models import features\n\n\ndef _fill_in_missing(x):\n \"\"\"Replace missing values in a SparseTensor.\n\n Fills in missing values of `x` with '' or 0, and converts to a dense tensor.\n\n Args:\n x: A `SparseTensor` of rank 2. Its dense shape should have size at most 1\n in the second dimension.\n\n Returns:\n A rank 1 tensor where missing values of `x` have been filled in.\n \"\"\"\n if not isinstance(x, tf.sparse.SparseTensor):\n return x\n\n default_value = '' if x.dtype == tf.string else 0\n return tf.squeeze(\n tf.sparse.to_dense(\n tf.SparseTensor(x.indices, x.values, [x.dense_shape[0], 1]),\n default_value),\n axis=1)\n\n\ndef preprocessing_fn(inputs):\n \"\"\"tf.transform's callback function for preprocessing inputs.\n\n Args:\n inputs: map from feature keys to raw not-yet-transformed features.\n\n Returns:\n Map from string feature key to transformed feature operations.\n \"\"\"\n outputs = {}\n for key in features.DENSE_FLOAT_FEATURE_KEYS:\n # Preserve this feature as a dense float, setting nan's to the mean.\n outputs[features.transformed_name(key)] = tft.scale_to_z_score(\n _fill_in_missing(inputs[key]))\n\n for key in features.VOCAB_FEATURE_KEYS:\n # Build a vocabulary for this feature.\n outputs[features.transformed_name(key)] = tft.compute_and_apply_vocabulary(\n _fill_in_missing(inputs[key]),\n top_k=features.VOCAB_SIZE,\n num_oov_buckets=features.OOV_SIZE)\n\n for key, num_buckets in zip(features.BUCKET_FEATURE_KEYS,\n features.BUCKET_FEATURE_BUCKET_COUNT):\n outputs[features.transformed_name(key)] = tft.bucketize(\n _fill_in_missing(inputs[key]),\n num_buckets)\n\n for key in features.CATEGORICAL_FEATURE_KEYS:\n outputs[features.transformed_name(key)] = _fill_in_missing(inputs[key])\n\n # TODO(b/157064428): Support label transformation for Keras.\n # Do not apply label transformation as it will result in wrong evaluation.\n outputs[features.transformed_name(\n features.LABEL_KEY)] = inputs[features.LABEL_KEY]\n\n return outputs\n" ]
[ [ "tensorflow.test.main" ], [ "tensorflow.test.main" ], [ "tensorflow.test.main" ], [ "tensorflow.test.main" ], [ "tensorflow.test.main" ], [ "tensorflow.keras.metrics.BinaryAccuracy", "tensorflow.keras.layers.Input", "tensorflow.keras.layers.DenseFeatures", "tensorflow.keras.layers.Dense", "tensorflow.feature_column.categorical_column_with_identity", "tensorflow.squeeze", "tensorflow.keras.Model", "tensorflow.keras.layers.concatenate", "tensorflow.SparseTensor", "tensorflow.keras.optimizers.Adam", "tensorflow.feature_column.numeric_column", "tensorflow.feature_column.indicator_column", "tensorflow.keras.callbacks.TensorBoard", "tensorflow.io.parse_example", "tensorflow.TensorSpec", "tensorflow.distribute.MirroredStrategy" ], [ "tensorflow.distribute.MirroredStrategy", "tensorflow.keras.layers.Dense", "tensorflow.keras.layers.concatenate", "tensorflow.keras.Model", "tensorflow.keras.optimizers.Adam", "tensorflow.keras.callbacks.TensorBoard", "tensorflow.keras.metrics.SparseCategoricalAccuracy", "tensorflow.io.parse_example", "tensorflow.TensorSpec", "tensorflow.keras.layers.Input" ], [ "tensorflow.test.main" ], [ "tensorflow.test.main" ], [ "tensorflow.SparseTensor" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "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": [] }, { "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" ] } ]
JouniVatanen/NLP-and-Deep-Learning
[ "2fddcc2c39787713d33d17e80565de4ed073ca60", "03357ab98155bf73b8f1d2fd53255cc16bea2333", "03357ab98155bf73b8f1d2fd53255cc16bea2333", "03357ab98155bf73b8f1d2fd53255cc16bea2333", "03357ab98155bf73b8f1d2fd53255cc16bea2333", "03357ab98155bf73b8f1d2fd53255cc16bea2333", "03357ab98155bf73b8f1d2fd53255cc16bea2333", "03357ab98155bf73b8f1d2fd53255cc16bea2333", "03357ab98155bf73b8f1d2fd53255cc16bea2333" ]
[ "src/supervised_class/dt.py", "src/rl/monte_carlo_es.py", "src/hmm_class/hmmc_scaled_concat.py", "src/rl2/cartpole/td_lambda.py", "src/rnn_class/srn_language_tf.py", "src/keras_examples/ann.py", "src/keras_examples/cnn.py", "src/rl/td0_prediction.py", "src/unsupervised_class2/autoencoder_tf.py" ]
[ "# https://deeplearningcourses.com/c/data-science-supervised-machine-learning-in-python\n# https://www.udemy.com/data-science-supervised-machine-learning-in-python\n# Decision Tree for continuous-vector input, binary output\nfrom __future__ import print_function, division\nfrom future.utils import iteritems\nfrom builtins import range, input\n# Note: you may need to update your version of future\n# sudo pip install -U future\n\n\nimport numpy as np\nfrom util import get_data, get_xor, get_donut\nfrom datetime import datetime\n\n\ndef entropy(y):\n # assume y is binary - 0 or 1\n N = len(y)\n s1 = (y == 1).sum()\n if 0 == s1 or N == s1:\n return 0\n p1 = float(s1) / N\n p0 = 1 - p1\n return -p0*np.log2(p0) - p1*np.log2(p1)\n\n\nclass TreeNode:\n def __init__(self, depth=0, max_depth=None):\n # print 'depth:', depth\n self.depth = depth\n self.max_depth = max_depth\n\n def fit(self, X, Y):\n if len(Y) == 1 or len(set(Y)) == 1:\n # base case, only 1 sample\n # another base case\n # this node only receives examples from 1 class\n # we can't make a split\n self.col = None\n self.split = None\n self.left = None\n self.right = None\n self.prediction = Y[0]\n\n else:\n D = X.shape[1]\n cols = range(D)\n\n max_ig = 0\n best_col = None\n best_split = None\n for col in cols:\n ig, split = self.find_split(X, Y, col)\n # print \"ig:\", ig\n if ig > max_ig:\n max_ig = ig\n best_col = col\n best_split = split\n\n if max_ig == 0:\n # nothing we can do\n # no further splits\n self.col = None\n self.split = None\n self.left = None\n self.right = None\n self.prediction = np.round(Y.mean())\n else:\n self.col = best_col\n self.split = best_split\n\n if self.depth == self.max_depth:\n self.left = None\n self.right = None\n self.prediction = [\n np.round(Y[X[:,best_col] < self.split].mean()),\n np.round(Y[X[:,best_col] >= self.split].mean()),\n ]\n else:\n # print \"best split:\", best_split\n left_idx = (X[:,best_col] < best_split)\n # print \"left_idx.shape:\", left_idx.shape, \"len(X):\", len(X)\n Xleft = X[left_idx]\n Yleft = Y[left_idx]\n self.left = TreeNode(self.depth + 1, self.max_depth)\n self.left.fit(Xleft, Yleft)\n\n right_idx = (X[:,best_col] >= best_split)\n Xright = X[right_idx]\n Yright = Y[right_idx]\n self.right = TreeNode(self.depth + 1, self.max_depth)\n self.right.fit(Xright, Yright)\n\n def find_split(self, X, Y, col):\n # print \"finding split for col:\", col\n x_values = X[:, col]\n sort_idx = np.argsort(x_values)\n x_values = x_values[sort_idx]\n y_values = Y[sort_idx]\n\n # Note: optimal split is the midpoint between 2 points\n # Note: optimal split is only on the boundaries between 2 classes\n\n # if boundaries[i] is true\n # then y_values[i] != y_values[i+1]\n # nonzero() gives us indices where arg is true\n # but for some reason it returns a tuple of size 1\n boundaries = np.nonzero(y_values[:-1] != y_values[1:])[0]\n best_split = None\n max_ig = 0\n for b in boundaries:\n split = (x_values[b] + x_values[b+1]) / 2\n ig = self.information_gain(x_values, y_values, split)\n if ig > max_ig:\n max_ig = ig\n best_split = split\n return max_ig, best_split\n\n def information_gain(self, x, y, split):\n # assume classes are 0 and 1\n # print \"split:\", split\n y0 = y[x < split]\n y1 = y[x >= split]\n N = len(y)\n y0len = len(y0)\n if y0len == 0 or y0len == N:\n return 0\n p0 = float(len(y0)) / N\n p1 = 1 - p0 #float(len(y1)) / N\n # print \"entropy(y):\", entropy(y)\n # print \"p0:\", p0\n # print \"entropy(y0):\", entropy(y0)\n # print \"p1:\", p1\n # print \"entropy(y1):\", entropy(y1)\n return entropy(y) - p0*entropy(y0) - p1*entropy(y1)\n\n def predict_one(self, x):\n # use \"is not None\" because 0 means False\n if self.col is not None and self.split is not None:\n feature = x[self.col]\n if feature < self.split:\n if self.left:\n p = self.left.predict_one(x)\n else:\n p = self.prediction[0]\n else:\n if self.right:\n p = self.right.predict_one(x)\n else:\n p = self.prediction[1]\n else:\n # corresponds to having only 1 prediction\n p = self.prediction\n return p\n\n def predict(self, X):\n N = len(X)\n P = np.zeros(N)\n for i in range(N):\n P[i] = self.predict_one(X[i])\n return P\n\n\n# This class is kind of redundant\nclass DecisionTree:\n def __init__(self, max_depth=None):\n self.max_depth = max_depth\n\n def fit(self, X, Y):\n self.root = TreeNode(max_depth=self.max_depth)\n self.root.fit(X, Y)\n\n def predict(self, X):\n return self.root.predict(X)\n\n def score(self, X, Y):\n P = self.predict(X)\n return np.mean(P == Y)\n\n\nif __name__ == '__main__':\n X, Y = get_data()\n\n # try donut and xor\n # from sklearn.utils import shuffle\n # X, Y = get_xor()\n # # X, Y = get_donut()\n # X, Y = shuffle(X, Y)\n\n # only take 0s and 1s since we're doing binary classification\n idx = np.logical_or(Y == 0, Y == 1)\n X = X[idx]\n Y = Y[idx]\n\n # split the data\n Ntrain = len(Y) // 2\n Xtrain, Ytrain = X[:Ntrain], Y[:Ntrain]\n Xtest, Ytest = X[Ntrain:], Y[Ntrain:]\n \n model = DecisionTree()\n # model = DecisionTree(max_depth=7)\n t0 = datetime.now()\n model.fit(Xtrain, Ytrain)\n print(\"Training time:\", (datetime.now() - t0))\n\n t0 = datetime.now()\n print(\"Train accuracy:\", model.score(Xtrain, Ytrain))\n print(\"Time to compute train accuracy:\", (datetime.now() - t0))\n\n t0 = datetime.now()\n print(\"Test accuracy:\", model.score(Xtest, Ytest))\n print(\"Time to compute test accuracy:\", (datetime.now() - t0))\n", "# https://deeplearningcourses.com/c/artificial-intelligence-reinforcement-learning-in-python\n# https://www.udemy.com/artificial-intelligence-reinforcement-learning-in-python\nfrom __future__ import print_function, division\nfrom builtins import range\n# Note: you may need to update your version of future\n# sudo pip install -U future\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom grid_world import standard_grid, negative_grid\nfrom iterative_policy_evaluation import print_values, print_policy\n\nGAMMA = 0.9\nALL_POSSIBLE_ACTIONS = ('U', 'D', 'L', 'R')\n\n# NOTE: this script implements the Monte Carlo Exploring-Starts method\n# for finding the optimal policy\n\ndef play_game(grid, policy):\n # returns a list of states and corresponding returns\n\n # reset game to start at a random position\n # we need to do this if we have a deterministic policy\n # we would never end up at certain states, but we still want to measure their value\n # this is called the \"exploring starts\" method\n start_states = list(grid.actions.keys())\n start_idx = np.random.choice(len(start_states))\n grid.set_state(start_states[start_idx])\n\n s = grid.current_state()\n a = np.random.choice(ALL_POSSIBLE_ACTIONS) # first action is uniformly random\n\n # be aware of the timing\n # each triple is s(t), a(t), r(t)\n # but r(t) results from taking action a(t-1) from s(t-1) and landing in s(t)\n states_actions_rewards = [(s, a, 0)]\n seen_states = set()\n seen_states.add(grid.current_state())\n num_steps = 0\n while True:\n r = grid.move(a)\n num_steps += 1\n s = grid.current_state()\n\n if s in seen_states:\n # hack so that we don't end up in an infinitely long episode\n # bumping into the wall repeatedly\n # if num_steps == 1 -> bumped into a wall and haven't moved anywhere\n # reward = -10\n # else:\n # reward = falls off by 1 / num_steps\n reward = -10. / num_steps\n states_actions_rewards.append((s, None, reward))\n break\n elif grid.game_over():\n states_actions_rewards.append((s, None, r))\n break\n else:\n a = policy[s]\n states_actions_rewards.append((s, a, r))\n seen_states.add(s)\n\n # calculate the returns by working backwards from the terminal state\n G = 0\n states_actions_returns = []\n first = True\n for s, a, r in reversed(states_actions_rewards):\n # the value of the terminal state is 0 by definition\n # we should ignore the first state we encounter\n # and ignore the last G, which is meaningless since it doesn't correspond to any move\n if first:\n first = False\n else:\n states_actions_returns.append((s, a, G))\n G = r + GAMMA*G\n states_actions_returns.reverse() # we want it to be in order of state visited\n return states_actions_returns\n\n\ndef max_dict(d):\n # returns the argmax (key) and max (value) from a dictionary\n # put this into a function since we are using it so often\n max_key = None\n max_val = float('-inf')\n for k, v in d.items():\n if v > max_val:\n max_val = v\n max_key = k\n return max_key, max_val\n\n\nif __name__ == '__main__':\n # use the standard grid again (0 for every step) so that we can compare\n # to iterative policy evaluation\n # grid = standard_grid()\n # try the negative grid too, to see if agent will learn to go past the \"bad spot\"\n # in order to minimize number of steps\n grid = negative_grid(step_cost=-0.9)\n\n # print rewards\n print(\"rewards:\")\n print_values(grid.rewards, grid)\n\n # state -> action\n # initialize a random policy\n policy = {}\n for s in grid.actions.keys():\n policy[s] = np.random.choice(ALL_POSSIBLE_ACTIONS)\n\n # initialize Q(s,a) and returns\n Q = {}\n returns = {} # dictionary of state -> list of returns we've received\n states = grid.all_states()\n for s in states:\n if s in grid.actions: # not a terminal state\n Q[s] = {}\n for a in ALL_POSSIBLE_ACTIONS:\n Q[s][a] = 0 # needs to be initialized to something so we can argmax it\n returns[(s,a)] = []\n else:\n # terminal state or state we can't otherwise get to\n pass\n\n # repeat until convergence\n deltas = []\n for t in range(2000):\n if t % 100 == 0:\n print(t)\n\n # generate an episode using pi\n biggest_change = 0\n states_actions_returns = play_game(grid, policy)\n seen_state_action_pairs = set()\n for s, a, G in states_actions_returns:\n # check if we have already seen s\n # called \"first-visit\" MC policy evaluation\n sa = (s, a)\n if sa not in seen_state_action_pairs:\n old_q = Q[s][a]\n returns[sa].append(G)\n Q[s][a] = np.mean(returns[sa])\n biggest_change = max(biggest_change, np.abs(old_q - Q[s][a]))\n seen_state_action_pairs.add(sa)\n deltas.append(biggest_change)\n\n # update policy\n for s in policy.keys():\n policy[s] = max_dict(Q[s])[0]\n\n plt.plot(deltas)\n plt.show()\n\n print(\"final policy:\")\n print_policy(policy, grid)\n\n # find V\n V = {}\n for s, Qs in Q.items():\n V[s] = max_dict(Q[s])[1]\n\n print(\"final values:\")\n print_values(V, grid)\n", "# https://deeplearningcourses.com/c/unsupervised-machine-learning-hidden-markov-models-in-python\n# https://udemy.com/unsupervised-machine-learning-hidden-markov-models-in-python\n# https://lazyprogrammer.me\n# Continuous-observation HMM with scaling and multiple observations (treated as concatenated sequence)\nfrom __future__ import print_function, division\nfrom builtins import range\n# Note: you may need to update your version of future\n# sudo pip install -U future\n\nimport wave\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom generate_c import get_signals, big_init, simple_init\nfrom scipy.stats import multivariate_normal as mvn\n\ndef random_normalized(d1, d2):\n x = np.random.random((d1, d2))\n return x / x.sum(axis=1, keepdims=True)\n\nclass HMM:\n def __init__(self, M, K):\n self.M = M # number of hidden states\n self.K = K # number of Gaussians\n \n def fit(self, X, max_iter=25, eps=1e-1):\n # train the HMM model using the Baum-Welch algorithm\n # a specific instance of the expectation-maximization algorithm\n\n # concatenate sequences in X and determine start/end positions\n sequenceLengths = []\n for x in X:\n sequenceLengths.append(len(x))\n Xc = np.concatenate(X)\n T = len(Xc)\n startPositions = np.zeros(len(Xc), dtype=np.bool)\n endPositions = np.zeros(len(Xc), dtype=np.bool)\n startPositionValues = []\n last = 0\n for length in sequenceLengths:\n startPositionValues.append(last)\n startPositions[last] = 1\n if last > 0:\n endPositions[last - 1] = 1\n last += length\n\n D = X[0].shape[1] # assume each x is organized (T, D)\n\n # randomly initialize all parameters\n self.pi = np.ones(self.M) / self.M # initial state distribution\n self.A = random_normalized(self.M, self.M) # state transition matrix\n self.R = np.ones((self.M, self.K)) / self.K # mixture proportions\n self.mu = np.zeros((self.M, self.K, D))\n for i in range(self.M):\n for k in range(self.K):\n random_idx = np.random.choice(T)\n self.mu[i,k] = Xc[random_idx]\n self.sigma = np.zeros((self.M, self.K, D, D))\n for j in range(self.M):\n for k in range(self.K):\n self.sigma[j,k] = np.eye(D)\n\n # main EM loop\n costs = []\n for it in range(max_iter):\n if it % 1 == 0:\n print(\"it:\", it)\n \n scale = np.zeros(T)\n\n # calculate B so we can lookup when updating alpha and beta\n B = np.zeros((self.M, T))\n component = np.zeros((self.M, self.K, T)) # we'll need these later\n for j in range(self.M):\n for k in range(self.K):\n p = self.R[j,k] * mvn.pdf(Xc, self.mu[j,k], self.sigma[j,k])\n component[j,k,:] = p\n B[j,:] += p\n\n\n alpha = np.zeros((T, self.M))\n alpha[0] = self.pi*B[:,0]\n scale[0] = alpha[0].sum()\n alpha[0] /= scale[0]\n for t in range(1, T):\n if startPositions[t] == 0:\n alpha_t_prime = alpha[t-1].dot(self.A) * B[:,t]\n else:\n alpha_t_prime = self.pi * B[:,t]\n scale[t] = alpha_t_prime.sum()\n alpha[t] = alpha_t_prime / scale[t]\n logP = np.log(scale).sum()\n\n beta = np.zeros((T, self.M))\n beta[-1] = 1\n for t in range(T - 2, -1, -1):\n if startPositions[t + 1] == 1:\n beta[t] = 1\n else:\n beta[t] = self.A.dot(B[:,t+1] * beta[t+1]) / scale[t+1]\n\n # update for Gaussians\n gamma = np.zeros((T, self.M, self.K))\n for t in range(T):\n alphabeta = alpha[t,:].dot(beta[t,:])\n for j in range(self.M):\n factor = alpha[t,j] * beta[t,j] / alphabeta\n for k in range(self.K):\n gamma[t,j,k] = factor * component[j,k,t] / B[j,t]\n\n costs.append(logP)\n\n # now re-estimate pi, A, R, mu, sigma\n self.pi = np.sum((alpha[t] * beta[t]) for t in startPositionValues) / len(startPositionValues)\n\n a_den = np.zeros((self.M, 1)) # prob don't need this\n a_num = np.zeros((self.M, self.M))\n r_num = np.zeros((self.M, self.K))\n r_den = np.zeros(self.M)\n mu_num = np.zeros((self.M, self.K, D))\n sigma_num = np.zeros((self.M, self.K, D, D))\n\n\n\n nonEndPositions = (1 - endPositions).astype(np.bool)\n a_den += (alpha[nonEndPositions] * beta[nonEndPositions]).sum(axis=0, keepdims=True).T\n\n # numerator for A\n for i in range(self.M):\n for j in range(self.M):\n for t in range(T-1):\n if endPositions[t] != 1:\n a_num[i,j] += alpha[t,i] * beta[t+1,j] * self.A[i,j] * B[j,t+1] / scale[t+1]\n self.A = a_num / a_den\n\n\n # update mixture components\n r_num_n = np.zeros((self.M, self.K))\n r_den_n = np.zeros(self.M)\n for j in range(self.M):\n for k in range(self.K):\n for t in range(T):\n r_num_n[j,k] += gamma[t,j,k]\n r_den_n[j] += gamma[t,j,k]\n r_num = r_num_n\n r_den = r_den_n\n\n mu_num_n = np.zeros((self.M, self.K, D))\n sigma_num_n = np.zeros((self.M, self.K, D, D))\n for j in range(self.M):\n for k in range(self.K):\n for t in range(T):\n # update means\n mu_num_n[j,k] += gamma[t,j,k] * Xc[t]\n\n # update covariances\n sigma_num_n[j,k] += gamma[t,j,k] * np.outer(Xc[t] - self.mu[j,k], Xc[t] - self.mu[j,k])\n mu_num = mu_num_n\n sigma_num = sigma_num_n\n\n\n # update R, mu, sigma\n for j in range(self.M):\n for k in range(self.K):\n self.R[j,k] = r_num[j,k] / r_den[j]\n self.mu[j,k] = mu_num[j,k] / r_num[j,k]\n self.sigma[j,k] = sigma_num[j,k] / r_num[j,k] + np.eye(D)*eps\n assert(np.all(self.R <= 1))\n assert(np.all(self.A <= 1))\n print(\"A:\", self.A)\n print(\"mu:\", self.mu)\n print(\"sigma:\", self.sigma)\n print(\"R:\", self.R)\n print(\"pi:\", self.pi)\n\n plt.plot(costs)\n plt.show()\n\n def log_likelihood(self, x):\n # returns log P(x | model)\n # using the forward part of the forward-backward algorithm\n T = len(x)\n scale = np.zeros(T)\n B = np.zeros((self.M, T))\n for j in range(self.M):\n for k in range(self.K):\n p = self.R[j,k] * mvn.pdf(x, self.mu[j,k], self.sigma[j,k])\n B[j,:] += p\n\n alpha = np.zeros((T, self.M))\n alpha[0] = self.pi*B[:,0]\n scale[0] = alpha[0].sum()\n alpha[0] /= scale[0]\n for t in range(1, T):\n alpha_t_prime = alpha[t-1].dot(self.A) * B[:,t]\n scale[t] = alpha_t_prime.sum()\n alpha[t] = alpha_t_prime / scale[t]\n return np.log(scale).sum()\n\n def log_likelihood_multi(self, X):\n return np.array([self.log_likelihood(x) for x in X])\n\n def set(self, pi, A, R, mu, sigma):\n self.pi = pi\n self.A = A\n self.R = R\n self.mu = mu\n self.sigma = sigma\n M, K = R.shape\n self.M = M\n self.K = K\n\n\ndef real_signal():\n spf = wave.open('helloworld.wav', 'r')\n\n #Extract Raw Audio from Wav File\n # If you right-click on the file and go to \"Get Info\", you can see:\n # sampling rate = 16000 Hz\n # bits per sample = 16\n # The first is quantization in time\n # The second is quantization in amplitude\n # We also do this for images!\n # 2^16 = 65536 is how many different sound levels we have\n signal = spf.readframes(-1)\n signal = np.fromstring(signal, 'Int16')\n T = len(signal)\n signal = (signal - signal.mean()) / signal.std()\n hmm = HMM(5, 3)\n hmm.fit(signal.reshape(1, T, 1))\n print(\"LL for fitted params:\", hmm.log_likelihood(signal.reshape(T, 1)))\n\n\ndef fake_signal(init=big_init):\n signals = get_signals(init=init)\n # for signal in signals:\n # for d in xrange(signal.shape[1]):\n # plt.plot(signal[:,d])\n # plt.show()\n\n hmm = HMM(5, 3)\n hmm.fit(signals)\n L = hmm.log_likelihood_multi(signals).sum()\n print(\"LL for fitted params:\", L)\n\n # test in actual params\n _, _, _, pi, A, R, mu, sigma = init()\n hmm.set(pi, A, R, mu, sigma)\n L = hmm.log_likelihood_multi(signals).sum()\n print(\"LL for actual params:\", L)\n\nif __name__ == '__main__':\n # real_signal()\n fake_signal()\n\n", "# https://deeplearningcourses.com/c/deep-reinforcement-learning-in-python\n# https://www.udemy.com/deep-reinforcement-learning-in-python\nfrom __future__ import print_function, division\nfrom builtins import range\n# Note: you may need to update your version of future\n# sudo pip install -U future\n\nimport gym\nimport os\nimport sys\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom gym import wrappers\nfrom datetime import datetime\nfrom q_learning import FeatureTransformer\nfrom q_learning_bins import plot_running_avg\n\n\nclass SGDRegressor:\n def __init__(self, D):\n self.w = np.random.randn(D) / np.sqrt(D)\n\n def partial_fit(self, x, y, e, lr=1e-1):\n self.w += lr*(y - x.dot(self.w))*e\n\n def predict(self, X):\n X = np.array(X)\n return X.dot(self.w)\n\n\n# Holds one SGDRegressor for each action\nclass Model:\n def __init__(self, env, feature_transformer):\n self.env = env\n self.models = []\n self.feature_transformer = feature_transformer\n\n sample_feature = feature_transformer.transform( [env.reset()] )\n D = sample_feature.shape[1]\n\n for i in range(env.action_space.n):\n # model = SGDRegressor(learning_rate=\"constant\")\n # model.partial_fit(feature_transformer.transform( [env.reset()] ), [0])\n model = SGDRegressor(D)\n self.models.append(model)\n \n self.eligibilities = np.zeros((env.action_space.n, D))\n\n def reset(self):\n self.eligibilities = np.zeros_like(self.eligibilities)\n\n def predict(self, s):\n X = self.feature_transformer.transform([s])\n result = np.stack([m.predict(X) for m in self.models]).T\n return result\n\n def update(self, s, a, G, gamma, lambda_):\n X = self.feature_transformer.transform([s])\n # assert(len(X.shape) == 2)\n\n # slower\n # for action in range(self.env.action_space.n):\n # if action != a:\n # self.eligibilities[action] *= gamma*lambda_\n # else:\n # self.eligibilities[a] = grad + gamma*lambda_*self.eligibilities[a]\n\n self.eligibilities *= gamma*lambda_\n self.eligibilities[a] += X[0]\n self.models[a].partial_fit(X[0], G, self.eligibilities[a])\n\n def sample_action(self, s, eps):\n if np.random.random() < eps:\n return self.env.action_space.sample()\n else:\n return np.argmax(self.predict(s))\n\n\n# returns a list of states_and_rewards, and the total reward\ndef play_one(model, env, eps, gamma, lambda_):\n observation = env.reset()\n done = False\n totalreward = 0\n states_actions_rewards = []\n iters = 0\n model.reset()\n while not done and iters < 1000000:\n action = model.sample_action(observation, eps)\n prev_observation = observation\n observation, reward, done, info = env.step(action)\n\n if done:\n reward = -300\n\n # update the model\n next = model.predict(observation)\n assert(next.shape == (1, env.action_space.n))\n G = reward + gamma*np.max(next[0])\n model.update(prev_observation, action, G, gamma, lambda_)\n\n states_actions_rewards.append((prev_observation, action, reward))\n\n if reward == 1: # if we changed the reward to -200\n totalreward += reward\n\n iters += 1\n\n # if iters > 0 and iters % 1000 == 0:\n # print(iters)\n # if done:\n # print \"finished in < 1000 steps!\"\n\n return states_actions_rewards, totalreward\n\n\nif __name__ == '__main__':\n env = gym.make('CartPole-v0')\n ft = FeatureTransformer(env)\n model = Model(env, ft)\n gamma = 0.999\n lambda_ = 0.7\n\n if 'monitor' in sys.argv:\n filename = os.path.basename(__file__).split('.')[0]\n monitor_dir = './' + filename + '_' + str(datetime.now())\n env = wrappers.Monitor(env, monitor_dir)\n\n\n N = 500\n totalrewards = np.empty(N)\n # costs = np.empty(N)\n for n in range(N):\n # eps = 1.0/(0.1*n+1)\n # eps = 0.1*(0.97**n)\n eps = 1.0/np.sqrt(n+1)\n # eps = 0.1\n states_actions_rewards, totalreward = play_one(model, env, eps, gamma, lambda_)\n totalrewards[n] = totalreward\n if n % 100 == 0:\n print(\"episode:\", n, \"total reward:\", totalreward, \"eps:\", eps, \"avg reward (last 100):\", totalrewards[max(0, n-100):(n+1)].mean())\n print(\"avg reward for last 100 episodes:\", totalrewards[-100:].mean())\n print(\"total steps:\", totalrewards.sum())\n\n plt.plot(totalrewards)\n plt.title(\"Rewards\")\n plt.show()\n\n plot_running_avg(totalrewards)\n\n\n", "# https://deeplearningcourses.com/c/deep-learning-recurrent-neural-networks-in-python\n# https://udemy.com/deep-learning-recurrent-neural-networks-in-python\nfrom __future__ import print_function, division\nfrom future.utils import iteritems\nfrom builtins import range\n# Note: you may need to update your version of future\n# sudo pip install -U future\n\n\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom sklearn.utils import shuffle\nfrom util import init_weight, get_robert_frost, get_wikipedia_data\n\n\nclass SimpleRNN:\n def __init__(self, D, M, V, f, session):\n self.D = D # dimensionality of word embedding\n self.M = M # hidden layer size\n self.V = V # vocabulary size\n self.f = f\n self.session = session\n\n def set_session(self, session):\n self.session = session\n\n def build(self, We, Wx, Wh, bh, h0, Wo, bo):\n # make them tf Variables\n self.We = tf.Variable(We)\n self.Wx = tf.Variable(Wx)\n self.Wh = tf.Variable(Wh)\n self.bh = tf.Variable(bh)\n self.h0 = tf.Variable(h0)\n self.Wo = tf.Variable(Wo)\n self.bo = tf.Variable(bo)\n self.params = [self.We, self.Wx, self.Wh, self.bh, self.h0, self.Wo, self.bo]\n\n # for easy access\n V = self.V\n D = self.D\n M = self.M\n\n # placeholders\n self.tfX = tf.placeholder(tf.int32, shape=(None,), name='X')\n self.tfY = tf.placeholder(tf.int32, shape=(None,), name='Y')\n\n # convert word indexes to word vectors\n # this would be equivalent to doing\n # We[tfX] in Numpy / Theano\n # or:\n # X_one_hot = one_hot_encode(X)\n # X_one_hot.dot(We)\n XW = tf.nn.embedding_lookup(We, self.tfX)\n\n # multiply it by input->hidden so we don't have to do\n # it inside recurrence\n XW_Wx = tf.matmul(XW, self.Wx)\n\n\n def recurrence(h_t1, XW_Wx_t):\n # returns h(t), y(t)\n h_t1 = tf.reshape(h_t1, (1, M))\n h_t = self.f(XW_Wx_t + tf.matmul(h_t1, self.Wh) + self.bh)\n h_t = tf.reshape(h_t, (M,))\n return h_t\n\n h = tf.scan(\n fn=recurrence,\n elems=XW_Wx,\n initializer=self.h0,\n )\n\n # output\n logits = tf.matmul(h, self.Wo) + self.bo\n prediction = tf.argmax(logits, 1)\n self.output_probs = tf.nn.softmax(logits)\n\n nce_weights = tf.transpose(self.Wo, [1,0]) # needs to be VxD, not DxV\n nce_biases = self.bo\n\n h = tf.reshape(h, (-1, M))\n labels = tf.reshape(self.tfY, (-1, 1))\n\n self.cost = tf.reduce_mean(\n tf.nn.sampled_softmax_loss(\n weights=nce_weights,\n biases=nce_biases,\n labels=labels,\n inputs=h,\n num_sampled=50, # number of negative samples\n num_classes=V\n )\n )\n\n self.predict_op = prediction\n self.train_op = tf.train.AdamOptimizer(1e-2).minimize(self.cost)\n # self.train_op = tf.train.MomentumOptimizer(1e-3, 0.9).minimize(self.cost)\n\n # init all variables\n init = tf.global_variables_initializer()\n self.session.run(init)\n\n\n def fit(self, X, epochs=500, show_fig=False):\n N = len(X)\n D = self.D\n M = self.M\n V = self.V\n\n # initial weights\n We = init_weight(V, D).astype(np.float32)\n Wx = init_weight(D, M).astype(np.float32)\n Wh = init_weight(M, M).astype(np.float32)\n bh = np.zeros(M).astype(np.float32)\n h0 = np.zeros(M).astype(np.float32)\n Wo = init_weight(M, V).astype(np.float32)\n bo = np.zeros(V).astype(np.float32)\n\n # build tensorflow functions\n self.build(We, Wx, Wh, bh, h0, Wo, bo)\n\n # sentence input:\n # [START, w1, w2, ..., wn]\n # sentence target:\n # [w1, w2, w3, ..., END]\n\n costs = []\n n_total = sum((len(sentence)+1) for sentence in X)\n for i in range(epochs):\n X = shuffle(X)\n n_correct = 0\n cost = 0\n for j in range(N):\n # problem! many words --> END token are overrepresented\n # result: generated lines will be very short\n # we will try to fix in a later iteration\n # BAD! magic numbers 0 and 1...\n input_sequence = [0] + X[j]\n output_sequence = X[j] + [1]\n\n # we set 0 to start and 1 to end\n _, c, p = self.session.run(\n (self.train_op, self.cost, self.predict_op),\n feed_dict={self.tfX: input_sequence, self.tfY: output_sequence}\n )\n # print \"p:\", p\n cost += c\n # print \"j:\", j, \"c:\", c/len(X[j]+1)\n for pj, xj in zip(p, output_sequence):\n if pj == xj:\n n_correct += 1\n print(\"i:\", i, \"cost:\", cost, \"correct rate:\", (float(n_correct)/n_total))\n costs.append(cost)\n\n if show_fig:\n plt.plot(costs)\n plt.show()\n\n def predict(self, prev_words):\n # don't use argmax, so that we can sample\n # from this probability distribution\n return self.session.run(\n self.output_probs,\n feed_dict={self.tfX: prev_words}\n )\n \n def save(self, filename):\n actual_params = self.session.run(self.params)\n np.savez(filename, *[p for p in actual_params])\n\n @staticmethod\n def load(filename, activation, session):\n # TODO: would prefer to save activation to file too\n npz = np.load(filename)\n We = npz['arr_0']\n Wx = npz['arr_1']\n Wh = npz['arr_2']\n bh = npz['arr_3']\n h0 = npz['arr_4']\n Wo = npz['arr_5']\n bo = npz['arr_6']\n V, D = We.shape\n _, M = Wx.shape\n rnn = SimpleRNN(D, M, V, activation, session)\n rnn.build(We, Wx, Wh, bh, h0, Wo, bo)\n return rnn\n\n def generate(self, pi, word2idx):\n # convert word2idx -> idx2word\n idx2word = {v:k for k,v in iteritems(word2idx)}\n V = len(pi)\n\n # generate 4 lines at a time\n n_lines = 0\n\n # why? because using the START symbol will always yield the same first word!\n X = [ np.random.choice(V, p=pi) ]\n print(idx2word[X[0]], end=\" \")\n\n while n_lines < 4:\n probs = self.predict(X)[-1]\n word_idx = np.random.choice(V, p=probs)\n X.append(word_idx)\n if word_idx > 1:\n # it's a real word, not start/end token\n word = idx2word[word_idx]\n print(word, end=\" \")\n elif word_idx == 1:\n # end token\n n_lines += 1\n print('')\n if n_lines < 4:\n X = [ np.random.choice(V, p=pi) ] # reset to start of line\n print(idx2word[X[0]], end=\" \")\n\n\ndef train_poetry(session, dims, savefile):\n sentences, word2idx = get_robert_frost()\n rnn = SimpleRNN(dims, dims, len(word2idx), tf.nn.relu, session)\n rnn.fit(sentences, epochs=17, show_fig=True)\n rnn.save(savefile)\n\n\ndef generate_poetry(session, savefile):\n sentences, word2idx = get_robert_frost()\n rnn = SimpleRNN.load(savefile, tf.nn.relu, session)\n\n # determine initial state distribution for starting sentences\n V = len(word2idx)\n pi = np.zeros(V)\n for sentence in sentences:\n pi[sentence[0]] += 1\n pi /= pi.sum()\n\n rnn.generate(pi, word2idx)\n\n\nif __name__ == '__main__':\n dims = 50\n savefile = 'RNN_D50_M50_tf.npz'\n session = tf.InteractiveSession()\n train_poetry(session, dims, savefile)\n generate_poetry(session, savefile)\n\n", "from __future__ import print_function, division\nfrom builtins import range\n# Note: you may need to update your version of future\n# sudo pip install -U future\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom util import getKaggleMNIST\nfrom keras.models import Model\nfrom keras.layers import Dense, Activation, Input\n\n\n# get the data\nXtrain, Ytrain, Xtest, Ytest = getKaggleMNIST()\n\n# get shapes\nN, D = Xtrain.shape\nK = len(set(Ytrain))\n\n\n# ANN with layers [784] -> [500] -> [300] -> [10]\ni = Input(shape=(D,))\nx = Dense(500, activation='relu')(i)\nx = Dense(300, activation='relu')(x)\nx = Dense(K, activation='softmax')(x)\n\n# instantiate the model object\nmodel = Model(inputs=i, outputs=x)\n\n\n# list of losses: https://keras.io/losses/\n# list of optimizers: https://keras.io/optimizers/\n# list of metrics: https://keras.io/metrics/\nmodel.compile(\n loss='sparse_categorical_crossentropy',\n optimizer='adam',\n metrics=['accuracy']\n)\n\n# note: multiple ways to choose a backend\n# either theano, tensorflow, or cntk\n# https://keras.io/backend/\n\n\n# gives us back a <keras.callbacks.History object at 0x112e61a90>\nr = model.fit(Xtrain, Ytrain, validation_data=(Xtest, Ytest), epochs=15, batch_size=32)\nprint(\"Returned:\", r)\n\n# print the available keys\n# should see: dict_keys(['val_loss', 'acc', 'loss', 'val_acc'])\nprint(r.history.keys())\n\n# plot some data\nplt.plot(r.history['loss'], label='loss')\nplt.plot(r.history['val_loss'], label='val_loss')\nplt.legend()\nplt.show()\n\n# accuracies\nplt.plot(r.history['acc'], label='acc')\nplt.plot(r.history['val_acc'], label='val_acc')\nplt.legend()\nplt.show()\n\n\n# make predictions and evaluate\nprobs = model.predict(Xtest) # N x K matrix of probabilities\nPtest = np.argmax(probs, axis=1)\nprint(\"Validation acc:\", np.mean(Ptest == Ytest))\n\n", "# https://deeplearningcourses.com/c/data-science-deep-learning-in-theano-tensorflow\n# https://www.udemy.com/data-science-deep-learning-in-theano-tensorflow\nfrom __future__ import print_function, division\nfrom builtins import range\n# Note: you may need to update your version of future\n# sudo pip install -U future\n\nfrom keras.models import Model\nfrom keras.layers import Dense, Activation, Conv2D, MaxPooling2D, Flatten, Input\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\n\nfrom util import getKaggleMNIST3D, getKaggleFashionMNIST3D, getCIFAR10\n\n\n# get the data\nXtrain, Ytrain, Xtest, Ytest = getKaggleFashionMNIST3D()\n\n# get shapes\nN, H, W, C = Xtrain.shape\nK = len(set(Ytrain))\n\n\n\n\n# make the CNN\ni = Input(shape=(H, W, C))\nx = Conv2D(filters=32, kernel_size=(3, 3))(i)\nx = Activation('relu')(x)\nx = MaxPooling2D()(x)\n\nx = Conv2D(filters=64, kernel_size=(3, 3))(x)\nx = Activation('relu')(x)\nx = MaxPooling2D()(x)\n\nx = Flatten()(x)\nx = Dense(units=100)(x)\nx = Activation('relu')(x)\nx = Dense(units=K)(x)\nx = Activation('softmax')(x)\n\nmodel = Model(inputs=i, outputs=x)\n\n\n# list of losses: https://keras.io/losses/\n# list of optimizers: https://keras.io/optimizers/\n# list of metrics: https://keras.io/metrics/\nmodel.compile(\n loss='sparse_categorical_crossentropy',\n optimizer='adam',\n metrics=['accuracy']\n)\n\n# note: multiple ways to choose a backend\n# either theano, tensorflow, or cntk\n# https://keras.io/backend/\n\n\n# gives us back a <keras.callbacks.History object at 0x112e61a90>\nr = model.fit(Xtrain, Ytrain, validation_data=(Xtest, Ytest), epochs=15, batch_size=32)\nprint(\"Returned:\", r)\n\n# print the available keys\n# should see: dict_keys(['val_loss', 'acc', 'loss', 'val_acc'])\nprint(r.history.keys())\n\n# plot some data\nplt.plot(r.history['loss'], label='loss')\nplt.plot(r.history['val_loss'], label='val_loss')\nplt.legend()\nplt.show()\n\n# accuracies\nplt.plot(r.history['acc'], label='acc')\nplt.plot(r.history['val_acc'], label='val_acc')\nplt.legend()\nplt.show()\n\n\n", "# https://deeplearningcourses.com/c/artificial-intelligence-reinforcement-learning-in-python\n# https://www.udemy.com/artificial-intelligence-reinforcement-learning-in-python\nfrom __future__ import print_function, division\nfrom builtins import range\n# Note: you may need to update your version of future\n# sudo pip install -U future\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom grid_world import standard_grid, negative_grid\nfrom iterative_policy_evaluation import print_values, print_policy\n\nSMALL_ENOUGH = 1e-3\nGAMMA = 0.9\nALPHA = 0.1\nALL_POSSIBLE_ACTIONS = ('U', 'D', 'L', 'R')\n\n# NOTE: this is only policy evaluation, not optimization\n\ndef random_action(a, eps=0.1):\n # we'll use epsilon-soft to ensure all states are visited\n # what happens if you don't do this? i.e. eps=0\n p = np.random.random()\n if p < (1 - eps):\n return a\n else:\n return np.random.choice(ALL_POSSIBLE_ACTIONS)\n\ndef play_game(grid, policy):\n # returns a list of states and corresponding rewards (not returns as in MC)\n # start at the designated start state\n s = (2, 0)\n grid.set_state(s)\n states_and_rewards = [(s, 0)] # list of tuples of (state, reward)\n while not grid.game_over():\n a = policy[s]\n a = random_action(a)\n r = grid.move(a)\n s = grid.current_state()\n states_and_rewards.append((s, r))\n return states_and_rewards\n\n\nif __name__ == '__main__':\n # use the standard grid again (0 for every step) so that we can compare\n # to iterative policy evaluation\n grid = standard_grid()\n\n # print rewards\n print(\"rewards:\")\n print_values(grid.rewards, grid)\n\n # state -> action\n policy = {\n (2, 0): 'U',\n (1, 0): 'U',\n (0, 0): 'R',\n (0, 1): 'R',\n (0, 2): 'R',\n (1, 2): 'R',\n (2, 1): 'R',\n (2, 2): 'R',\n (2, 3): 'U',\n }\n\n # initialize V(s) and returns\n V = {}\n states = grid.all_states()\n for s in states:\n V[s] = 0\n\n # repeat until convergence\n for it in range(1000):\n\n # generate an episode using pi\n states_and_rewards = play_game(grid, policy)\n # the first (s, r) tuple is the state we start in and 0\n # (since we don't get a reward) for simply starting the game\n # the last (s, r) tuple is the terminal state and the final reward\n # the value for the terminal state is by definition 0, so we don't\n # care about updating it.\n for t in range(len(states_and_rewards) - 1):\n s, _ = states_and_rewards[t]\n s2, r = states_and_rewards[t+1]\n # we will update V(s) AS we experience the episode\n V[s] = V[s] + ALPHA*(r + GAMMA*V[s2] - V[s])\n\n print(\"values:\")\n print_values(V, grid)\n print(\"policy:\")\n print_policy(policy, grid)\n", "# https://deeplearningcourses.com/c/unsupervised-deep-learning-in-python\n# https://www.udemy.com/unsupervised-deep-learning-in-python\nfrom __future__ import print_function, division\nfrom builtins import range, input\n# Note: you may need to update your version of future\n# sudo pip install -U future\n\nimport numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\n\nfrom sklearn.utils import shuffle\nfrom util import error_rate, getKaggleMNIST\n\n\nclass AutoEncoder(object):\n def __init__(self, D, M, an_id):\n self.M = M\n self.id = an_id\n self.build(D, M)\n\n def set_session(self, session):\n self.session = session\n\n def build(self, D, M):\n self.W = tf.Variable(tf.random_normal(shape=(D, M)))\n self.bh = tf.Variable(np.zeros(M).astype(np.float32))\n self.bo = tf.Variable(np.zeros(D).astype(np.float32))\n\n self.X_in = tf.placeholder(tf.float32, shape=(None, D))\n self.Z = self.forward_hidden(self.X_in) # for transform() later\n self.X_hat = self.forward_output(self.X_in)\n\n\n # using the naive formulation for cross-entropy\n # will have numerical stability issues if X_hat = 0 or 1\n logits = self.forward_logits(self.X_in)\n self.cost = tf.reduce_mean(\n tf.nn.sigmoid_cross_entropy_with_logits(\n labels=self.X_in,\n logits=logits,\n )\n )\n\n self.train_op = tf.train.AdamOptimizer(1e-1).minimize(self.cost)\n # self.train_op = tf.train.MomentumOptimizer(1e-3, momentum=0.9).minimize(self.cost)\n\n def fit(self, X, epochs=1, batch_sz=100, show_fig=False):\n N, D = X.shape\n n_batches = N // batch_sz\n\n costs = []\n print(\"training autoencoder: %s\" % self.id)\n for i in range(epochs):\n print(\"epoch:\", i)\n X = shuffle(X)\n for j in range(n_batches):\n batch = X[j*batch_sz:(j*batch_sz + batch_sz)]\n _, c = self.session.run((self.train_op, self.cost), feed_dict={self.X_in: batch})\n if j % 10 == 0:\n print(\"j / n_batches:\", j, \"/\", n_batches, \"cost:\", c)\n costs.append(c)\n if show_fig:\n plt.plot(costs)\n plt.show()\n\n def transform(self, X):\n # accepts and returns a real numpy array\n # unlike forward_hidden and forward_output\n # which deal with tensorflow variables\n return self.session.run(self.Z, feed_dict={self.X_in: X})\n\n def predict(self, X):\n # accepts and returns a real numpy array\n # unlike forward_hidden and forward_output\n # which deal with tensorflow variables\n return self.session.run(self.X_hat, feed_dict={self.X_in: X})\n\n def forward_hidden(self, X):\n Z = tf.nn.sigmoid(tf.matmul(X, self.W) + self.bh)\n return Z\n\n def forward_logits(self, X):\n Z = self.forward_hidden(X)\n return tf.matmul(Z, tf.transpose(self.W)) + self.bo\n\n def forward_output(self, X):\n return tf.nn.sigmoid(self.forward_logits(X))\n\n\nclass DNN(object):\n def __init__(self, D, hidden_layer_sizes, K, UnsupervisedModel=AutoEncoder):\n self.hidden_layers = []\n count = 0\n input_size = D\n for output_size in hidden_layer_sizes:\n ae = UnsupervisedModel(input_size, output_size, count)\n self.hidden_layers.append(ae)\n count += 1\n input_size = output_size\n self.build_final_layer(D, hidden_layer_sizes[-1], K)\n\n def set_session(self, session):\n self.session = session\n for layer in self.hidden_layers:\n layer.set_session(session)\n\n def build_final_layer(self, D, M, K):\n # initialize logistic regression layer\n self.W = tf.Variable(tf.random_normal(shape=(M, K)))\n self.b = tf.Variable(np.zeros(K).astype(np.float32))\n\n self.X = tf.placeholder(tf.float32, shape=(None, D))\n labels = tf.placeholder(tf.int32, shape=(None,))\n self.Y = labels\n logits = self.forward(self.X)\n\n self.cost = tf.reduce_mean(\n tf.nn.sparse_softmax_cross_entropy_with_logits(\n logits=logits,\n labels=labels\n )\n )\n self.train_op = tf.train.AdamOptimizer(1e-2).minimize(self.cost)\n self.prediction = tf.argmax(logits, 1)\n\n def fit(self, X, Y, Xtest, Ytest, pretrain=True, epochs=1, batch_sz=100):\n N = len(X)\n\n # greedy layer-wise training of autoencoders\n pretrain_epochs = 1\n if not pretrain:\n pretrain_epochs = 0\n\n current_input = X\n for ae in self.hidden_layers:\n ae.fit(current_input, epochs=pretrain_epochs)\n\n # create current_input for the next layer\n current_input = ae.transform(current_input)\n\n n_batches = N // batch_sz\n costs = []\n print(\"supervised training...\")\n for i in range(epochs):\n print(\"epoch:\", i)\n X, Y = shuffle(X, Y)\n for j in range(n_batches):\n Xbatch = X[j*batch_sz:(j*batch_sz + batch_sz)]\n Ybatch = Y[j*batch_sz:(j*batch_sz + batch_sz)]\n self.session.run(\n self.train_op,\n feed_dict={self.X: Xbatch, self.Y: Ybatch}\n )\n c, p = self.session.run(\n (self.cost, self.prediction),\n feed_dict={self.X: Xtest, self.Y: Ytest\n })\n error = error_rate(p, Ytest)\n if j % 10 == 0:\n print(\"j / n_batches:\", j, \"/\", n_batches, \"cost:\", c, \"error:\", error)\n costs.append(c)\n plt.plot(costs)\n plt.show()\n\n def forward(self, X):\n current_input = X\n for ae in self.hidden_layers:\n Z = ae.forward_hidden(current_input)\n current_input = Z\n\n # logistic layer\n logits = tf.matmul(current_input, self.W) + self.b\n return logits\n\n\ndef test_pretraining_dnn():\n Xtrain, Ytrain, Xtest, Ytest = getKaggleMNIST()\n # dnn = DNN([1000, 750, 500])\n # dnn.fit(Xtrain, Ytrain, Xtest, Ytest, epochs=3)\n # vs\n Xtrain = Xtrain.astype(np.float32)\n Xtest = Xtest.astype(np.float32)\n _, D = Xtrain.shape\n K = len(set(Ytrain))\n dnn = DNN(D, [1000, 750, 500], K)\n init_op = tf.global_variables_initializer()\n with tf.Session() as session:\n session.run(init_op)\n dnn.set_session(session)\n dnn.fit(Xtrain, Ytrain, Xtest, Ytest, pretrain=True, epochs=10)\n\n\ndef test_single_autoencoder():\n Xtrain, Ytrain, Xtest, Ytest = getKaggleMNIST()\n Xtrain = Xtrain.astype(np.float32)\n Xtest = Xtest.astype(np.float32)\n\n _, D = Xtrain.shape\n autoencoder = AutoEncoder(D, 300, 0)\n init_op = tf.global_variables_initializer()\n with tf.Session() as session:\n session.run(init_op)\n autoencoder.set_session(session)\n autoencoder.fit(Xtrain, show_fig=True)\n\n done = False\n while not done:\n i = np.random.choice(len(Xtest))\n x = Xtest[i]\n y = autoencoder.predict([x])\n plt.subplot(1,2,1)\n plt.imshow(x.reshape(28,28), cmap='gray')\n plt.title('Original')\n\n plt.subplot(1,2,2)\n plt.imshow(y.reshape(28,28), cmap='gray')\n plt.title('Reconstructed')\n\n plt.show()\n\n ans = input(\"Generate another?\")\n if ans and ans[0] in ('n' or 'N'):\n done = True\n\n\n\nif __name__ == '__main__':\n # test_single_autoencoder()\n test_pretraining_dnn()\n" ]
[ [ "numpy.log2", "numpy.nonzero", "numpy.logical_or", "numpy.mean", "numpy.argsort", "numpy.zeros" ], [ "numpy.abs", "numpy.random.choice", "matplotlib.pyplot.plot", "numpy.mean", "matplotlib.pyplot.show" ], [ "numpy.log", "numpy.random.random", "numpy.random.choice", "numpy.eye", "numpy.ones", "numpy.concatenate", "matplotlib.pyplot.plot", "numpy.all", "numpy.fromstring", "numpy.outer", "matplotlib.pyplot.show", "numpy.zeros", "numpy.sum", "scipy.stats.multivariate_normal.pdf" ], [ "numpy.random.random", "numpy.sqrt", "matplotlib.pyplot.title", "numpy.empty", "matplotlib.pyplot.plot", "numpy.max", "numpy.zeros_like", "numpy.random.randn", "numpy.array", "numpy.zeros", "matplotlib.pyplot.show" ], [ "numpy.savez", "tensorflow.scan", "matplotlib.pyplot.plot", "tensorflow.train.AdamOptimizer", "tensorflow.Variable", "numpy.load", "tensorflow.argmax", "numpy.zeros", "tensorflow.matmul", "tensorflow.InteractiveSession", "numpy.random.choice", "tensorflow.placeholder", "tensorflow.global_variables_initializer", "matplotlib.pyplot.show", "tensorflow.nn.embedding_lookup", "tensorflow.nn.softmax", "tensorflow.transpose", "sklearn.utils.shuffle", "tensorflow.reshape", "tensorflow.nn.sampled_softmax_loss" ], [ "matplotlib.pyplot.legend", "matplotlib.pyplot.plot", "numpy.argmax", "numpy.mean", "matplotlib.pyplot.show" ], [ "matplotlib.pyplot.plot", "matplotlib.pyplot.legend", "matplotlib.pyplot.show" ], [ "numpy.random.random", "numpy.random.choice" ], [ "tensorflow.matmul", "tensorflow.transpose", "matplotlib.pyplot.title", "sklearn.utils.shuffle", "tensorflow.placeholder", "matplotlib.pyplot.plot", "tensorflow.global_variables_initializer", "tensorflow.nn.sigmoid_cross_entropy_with_logits", "matplotlib.pyplot.subplot", "tensorflow.nn.sparse_softmax_cross_entropy_with_logits", "tensorflow.Session", "tensorflow.train.AdamOptimizer", "tensorflow.argmax", "matplotlib.pyplot.show", "numpy.zeros", "tensorflow.random_normal" ] ]
[ { "matplotlib": [], "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" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
liuhuaijjin/rpn_rois_proposals_layers
[ "c5f9f09b3ae8c52e4b6fa3fda391f993cb7d42c1" ]
[ "lib/net/pcn_coarse.py" ]
[ "import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass Encoder(nn.Module):\n def __init__(self):\n super(Encoder, self).__init__()\n\n # first shared mlp\n self.conv1 = nn.Conv1d(3, 128, 1)\n self.conv2 = nn.Conv1d(128, 256, 1)\n self.bn1 = nn.BatchNorm1d(128)\n self.bn2 = nn.BatchNorm1d(256)\n\n # second shared mlp\n self.conv3 = nn.Conv1d(512, 512, 1)\n self.conv4 = nn.Conv1d(512, 1024, 1)\n self.bn3 = nn.BatchNorm1d(512)\n self.bn4 = nn.BatchNorm1d(1024)\n \n def forward(self, x):\n n = x.size()[2]\n\n # first shared mlp\n x = F.relu(self.bn1(self.conv1(x))) # (B, 128, N)\n f = self.bn2(self.conv2(x)) # (B, 256, N)\n \n # point-wise maxpool\n g = torch.max(f, dim=2, keepdim=True)[0] # (B, 256, 1)\n \n # expand and concat\n x = torch.cat([g.repeat(1, 1, n), f], dim=1) # (B, 512, N)\n\n # second shared mlp\n x = F.relu(self.bn3(self.conv3(x))) # (B, 512, N)\n x = self.bn4(self.conv4(x)) # (B, 1024, N)\n \n # point-wise maxpool\n v = torch.max(x, dim=-1)[0] # (B, 1024)\n \n return v\n\n\nclass Decoder(nn.Module):\n def __init__(self, num_coarse=1024, num_dense=16384):\n super(Decoder, self).__init__()\n\n self.num_coarse = num_coarse\n \n # fully connected layers\n self.linear1 = nn.Linear(1024, 1024)\n self.linear2 = nn.Linear(1024, 1024)\n self.linear3 = nn.Linear(1024, 3 * num_coarse)\n self.bn1 = nn.BatchNorm1d(1024)\n self.bn2 = nn.BatchNorm1d(1024)\n\n # shared mlp\n self.conv1 = nn.Conv1d(3+2+1024, 512, 1)\n self.conv2 = nn.Conv1d(512, 512, 1)\n self.conv3 = nn.Conv1d(512, 3, 1)\n self.bn3 = nn.BatchNorm1d(512)\n self.bn4 = nn.BatchNorm1d(512)\n\n # 2D grid\n grids = np.meshgrid(np.linspace(-0.05, 0.05, 4, dtype=np.float32),\n np.linspace(-0.05, 0.05, 4, dtype=np.float32)) # (2, 4, 44)\n self.grids = torch.Tensor(grids).view(2, -1) # (2, 4, 4) -> (2, 16)\n \n def forward(self, x):\n b = x.size()[0]\n # global features\n v = x # (B, 1024)\n\n # fully connected layers to generate the coarse output\n x = F.relu(self.bn1(self.linear1(x)))\n x = F.relu(self.bn2(self.linear2(x)))\n x = self.linear3(x)\n y_coarse = x.view(-1, 3, self.num_coarse) # (B, 3, 1024)\n\n #repeated_centers = y_coarse.unsqueeze(3).repeat(1, 1, 1, 16).view(b, 3, -1) # (B, 3, 16x1024)\n #repeated_v = v.unsqueeze(2).repeat(1, 1, 16 * self.num_coarse) # (B, 1024, 16x1024)\n #grids = self.grids.to(x.device) # (2, 16)\n #grids = grids.unsqueeze(0).repeat(b, 1, self.num_coarse) # (B, 2, 16x1024)\n\n #x = torch.cat([repeated_v, grids, repeated_centers], dim=1) # (B, 2+3+1024, 16x1024)\n #x = F.relu(self.bn3(self.conv1(x)))\n #x = F.relu(self.bn4(self.conv2(x)))\n #x = self.conv3(x) # (B, 3, 16x1024)\n #y_detail = x + repeated_centers # (B, 3, 16x1024)\n\n return y_coarse\n\n\nclass AutoEncoder(nn.Module):\n def __init__(self):\n super(AutoEncoder, self).__init__()\n\n self.encoder = Encoder()\n self.decoder = Decoder()\n self.load_state_dict(torch.load('../../../model/pcn.pth', map_location=lambda storage, loc: storage))\n\n def forward(self, x):\n with torch.no_grad():\n v = self.encoder(x)\n y_coarse = self.decoder(v)\n return v, y_coarse\n\n\n# if __name__ == \"__main__\":\n# pcs = torch.rand(16, 3, 2048)\n# encoder = Encoder()\n# v = encoder(pcs)\n# print(v.size())\n#\n# decoder = Decoder()\n# decoder(v)\n# y_c, y_d = decoder(v)\n# print(y_c.size(), y_d.size())\n#\n# ae = AutoEncoder()\n# v, y_coarse, y_detail = ae(pcs)\n# print(v.size(), y_coarse.size(), y_detail.size())\n" ]
[ [ "torch.nn.BatchNorm1d", "torch.max", "numpy.linspace", "torch.load", "torch.Tensor", "torch.nn.Linear", "torch.no_grad", "torch.nn.Conv1d" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
uwmadison-chm/redcap-examples
[ "376d62cf18a7e76265fc251425d2bfae3a2c6521" ]
[ "download_longitudinal.py" ]
[ "#!/usr/bin/env python\n\n\"\"\"\nDownloads the data for a longitudinal REDCap project, with each event as \na separate file. Also allows filtering by standard REDCap logic, so you can,\nfor example, exclude non-enrolled participants from your data.\n\nRequires an instrument_download_list_file, which is a CSV file containing\nthe fields \"instrument_name\" and \"download\". If download is not blank, the\ninstrument will be included in the download.\n\nOnly instruments belonging to the given event are downloaded in the event's\nfile, to keep file sizes down and column counts more manageable.\n\nThe API URL, API token, and filter logic are all passed using environment\nvariables: API_URL, API_TOK, and FILTER, respectively.\n\nRequires the PyCap library: https://pycap.readthedocs.io/en/latest/\n\"\"\"\n\nimport sys\nimport os\n\nimport redcap\nimport pandas as pd\n\nfrom pathlib import Path\n\nimport logging\nlogging.basicConfig(format='%(message)s')\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\n\n\nAPI_URL = os.environ['REDCAP_API_URL']\nAPI_TOK = os.environ['REDCAP_API_TOKEN']\nFILTER = os.environ.get('REDCAP_FILTER_LOGIC')\nPROJ = redcap.Project(API_URL, API_TOK)\n\n\ndef filtered_ids():\n id_field = PROJ.field_names[0]\n first_event = PROJ.events[0]\n record_names = PROJ.export_records(\n fields=[id_field],\n filter_logic=FILTER,\n format='df'\n )\n logger.debug(record_names.index)\n return list(record_names.index.get_level_values(0))\n\n\ndef main(instrument_download_list_file, out_path):\n # We need this because we can't filter using data that doesn't occur\n # in the target event, because redcap is kinda dumb\n ids = filtered_ids()\n form_events = PROJ.export_fem(format='df')\n all_form_list = pd.read_csv(instrument_download_list_file)\n selected_forms = frozenset(all_form_list.dropna()['instrument_name'])\n logger.debug(f'Forms to download: {selected_forms}')\n\n for event_name, event_rows in form_events.groupby(by='unique_event_name'):\n available_forms = frozenset(event_rows['form'])\n download_forms = selected_forms & available_forms\n logger.debug(f'Event {event_name}: Downloading {download_forms}')\n data = PROJ.export_records(\n records=ids,\n events=[event_name],\n forms=download_forms,\n export_survey_fields=False,\n export_checkbox_labels=True,\n format='df',\n df_kwargs={\n 'dtype': 'str'\n }\n )\n out_filename = out_path / f'{event_name}.csv'\n data.to_csv(out_filename, index=False)\n\n\nif __name__ == \"__main__\":\n instrument_download_list_file = sys.argv[1]\n out_dir = sys.argv[2]\n out_path = Path(out_dir)\n main(instrument_download_list_file, out_path)\n" ]
[ [ "pandas.read_csv" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
mayank42/Earthquake-Signal-Analysis-using-Deep-CNN
[ "fdeca035277acd1b37759c546c90bcdd63168412", "fdeca035277acd1b37759c546c90bcdd63168412" ]
[ "pv.py", "EqDataParser.py" ]
[ "\"\"\" \npv.py\nPhase Vocoder implementation in Python\n\nThe MIT License (MIT)\n\nCopyright (c) 2015 multivac61\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n\"\"\"\n\nimport sys\nimport numpy as np\nfrom math import floor\n\n# CONSTANTS\nepsilon = sys.float_info.epsilon\n\n\nclass PhaseVocoder(object):\n\t\"\"\"docstring for PhaseVocoder\"\"\"\n\tdef __init__(self, N=2**12, M=2**12, Rs=(2**12/8), w=np.hanning(2**12), alpha=1):\n\t\tsuper(PhaseVocoder, self).__init__()\n\t\tself.N\t = N\t\t# FFT size\n\t\tself.M \t = M\t\t# Window size\n\t\tself.Rs \t= Rs \t# Synthesis hop size\n\t\tself.alpha = alpha\t# Timestretch factor\n\t\tself.w = w \t# Analysis/Synthesis window\n\n\tdef timestretch(self, x, alpha):\n\t\t\"\"\"\n\t\tPerform timestretch of a factor alpha to signal x\n\t\tx: input signal, alpha: timestrech factor\n\t\treturns: a signal of length T*alpha\n\t\t\"\"\"\n\t\t# Analysis/Synthesis window function\n\t\tw = self.w; N = self.N; M = self.M\n\t\thM1 = int(floor((M-1)/2.))\n\t\thM2 = int(floor(M/2.))\n\n\t\t# Synthesis and analysis hop sizes\n\t\tRs = self.Rs\n\t\tRa = int(self.Rs / float(alpha))\n\n\t\t# AM scaling factor due to window sliding\n\t\twscale = sum([i**2 for i in w]) / float(Rs)\n\t\tL = x.size\n\t\tL0 = int(x.size*alpha)\n\n\t\t# Get an prior approximation of the fundamental frequency\n\t\tif alpha != 1.0:\n\t\t\tA = np.fft.fft(w*x[0:N])\n\t\t\tB = np.fft.fft(w*x[Ra:Ra+N])\n\t\t\tA[A == 0] = epsilon\n\t\t\tB[B == 0] = epsilon\n\t\t\tFreq0 = B/A * abs(B/A)\n\t\t\tFreq0[Freq0 == 0] = epsilon\n\t\telse:\n\t\t\tFreq0 = 1\n\n\t\tif alpha == 1.0: \t# we can fully retrieve the input (within numerical errors)\n\t\t\t# Place input signal directly over half of window\n\t\t\tx = np.append(np.zeros(N+Rs), x)\n\t\t\tx = np.append(x, np.zeros(N+Rs))\n\n\t\t\t# Initialize output signal\n\t\t\ty = np.zeros(x.size)\n\t\telse:\n\t\t\tx = np.append(np.zeros(Rs), x)\n\t\t\t#x = np.append(x, np.zeros(Rs))\n\n\t\t\ty = np.zeros(int((x.size)*alpha + x.size/Ra * alpha))\n\n\t\t# Pointers and initializations\n\t\tp, pp = 0, 0\n\t\tpend = x.size - (Rs+N)\n\t\tYold = epsilon\n\n\t\ti = 0\n\t\twhile p <= pend:\n\t\t\ti += 1\n\t\t\t# Spectra of two consecutive windows\n\t\t\tXs = np.fft.fft(w*x[p:p+N])\n\t\t\tXt = np.fft.fft(w*x[p+Rs:p+Rs+N])\n\n\t\t\t# Prohibit dividing by zero\n\t\t\tXs[Xs == 0] = epsilon\n\t\t\tXt[Xt == 0] = epsilon\n\n\t\t\t# inverse FFT and overlap-add\n\t\t\tif p > 0 :\n\t\t\t\tY = Xt * (Yold / Xs) / abs(Yold / Xs)\n\t\t\telse:\n\t\t\t\tY = Xt * Freq0\n\n\t\t\tYold = Y\n\t\t\tYold[Yold == 0] = epsilon\n\t\t\t\n\n\t\t\ty[pp:pp+N] += np.array([c.real for c in w*np.fft.ifft(Y)])\n\t\t\t\n\t\t\tp = int(p+Ra)\t\t# analysis hop\n\t\t\tpp += Rs\t\t\t# synthesis hop\n\n\t\t\t#sys.stdout.write (\"Percentage finishied: %d %% \\r\" % int(100.0*p/pend))\n\t\t\t#sys.stdout.flush()\n\n\t\ty = y / wscale\n\n\n\t\tif self.alpha == 1.0:\n\t\t\t# retrieve input signal perfectly\n\t\t\tx = np.delete(x, range(N+Rs))\n\t\t\tx = np.delete(x, range(x.size-(N+Rs), x.size))\n\t\t\t\t\t\t\n\t\t\ty = np.delete(y, range(N))\n\t\t\ty = np.delete(y, range(y.size-(N+2*Rs), y.size))\n\t\telse:\n\t\t\t# retrieve input signal perfectly\n\t\t\tx = np.delete(x, range(Rs))\n\n\t\t\ty = np.delete(y, range(Rs))\n\t\t\ty = np.delete(y, range(L0, y.size))\n\t\t\t\t\t\t\t\n\t\treturn y\n", "\"\"\"This module reads and compiles data in the format required for training\n on the convolution nets.\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nfrom os import listdir\nfrom os.path import isfile, join\nfrom pv import PhaseVocoder\nimport sys\n\n#CONSTANTS\nepsilon = sys.float_info.epsilon\n\ndef shuffle_in_unison(a, b):\n assert len(a) == len(b)\n shuffled_a = np.empty(a.shape, dtype=a.dtype)\n shuffled_b = np.empty(b.shape, dtype=b.dtype)\n permutation = np.random.permutation(len(a))\n for old_index, new_index in enumerate(permutation):\n shuffled_a[new_index] = a[old_index]\n shuffled_b[new_index] = b[old_index]\n return shuffled_a, shuffled_b\n\nclass EarthquakeDataParser:\n\t\n\t\"\"\"This class contains the necessary functions and variables\n\t for parsing the earthquake data in the format necessary for \n\t convolution net training.\n\t\"\"\"\n\n\tdef __init__(self,path,image_data_format,sig_len_thresh, \\\n\t\t\t\t shortw,longw,sfreq,sta_lta_thresh):\n\t\t\n\t\t\"\"\"\n\t\t Init for this parser. See load_earthquake_data() for param details.\n\t\t\"\"\"\n\t\tself.path = path\n\t\tself.image_data_format = image_data_format\n\t\tself.sig_len_thresh = sig_len_thresh\n\t\tself.shortw = shortw\n\t\tself.longw = longw\n\t\tself.sfreq = sfreq\n\t\tself.sta_lta_thresh = sta_lta_thresh\n\n\tdef parse_mag(self):\n\n\t\t\"\"\"To read data given files.\n\t\t :returns: Tuple of three data lists(vt,ns,ew) of the form [(<mag>,<numpy array of signal>)]\n\n\t\t All data format locations are specific to data files I have.\n\t\t\"\"\"\n\t\tonlyfiles = [join(self.path,f) for f in listdir(self.path) if isfile(join(self.path, f))]\n\t\tvtfiles = [f for f in onlyfiles if f.endswith('.vt')] #Vertical component files\t\t\t \t\n\t\tmag1_data = []\n\t\tmag2_data = []\n\t\tmag3_data = []\n\t\tpi=1\n\t\tpf=len(vtfiles)\n\t\tfor f in vtfiles:\n\t\t temp1=pd.read_csv(f,sep='\\n',header=None,encoding='L2')\n\t\t temp2=pd.read_csv(f[:-3]+'.ns',sep='\\n',header=None,encoding='L2')\n\t\t temp3=pd.read_csv(f[:-3]+'.ew',sep='\\n',header=None,encoding='L2')\n\t\t mag1_data.append( [float( temp1.iloc[4][0].split()[-1] ),temp1.iloc[20:].values.ravel().astype(float)] )\n\t\t mag2_data.append( [float( temp2.iloc[4][0].split()[-1] ),temp2.iloc[20:].values.ravel().astype(float)] )\n\t\t mag3_data.append( [float( temp3.iloc[4][0].split()[-1] ),temp3.iloc[20:].values.ravel().astype(float)] ) \n\t\t sys.stdout.write('Percentage finished: %d %% \\r'%int(100.0*pi/pf))\n\t\t sys.stdout.flush()\n\t\t pi=pi+1\n\t\tprint('\\n')\n\t\treturn mag1_data,mag2_data,mag3_data\n\n\tdef sta_lta(self,sig):\n\t\t\"\"\"Implementation of sta_lta algorithm, adapted to the current dataset.\n\t\t \n\t\t :returns: Point of occurence of P-wave ( Adjusted to 90% of detected value )\n\t\t :rtype: int\n\t\t \n\t\t All default values have been adapted for the dataset, I am working on.\n\t\t\"\"\"\n\t\tshortw = self.shortw\n\t\tlongw = self.longw\n\t\tsfreq = self.sfreq\n\t\tsta_lta_thresh = self.sta_lta_thresh\t\t\t\t\n\t\tsw = int(sfreq*shortw)\n\t\tlw = int(sfreq*longw)\n\t\tma_sw = np.convolve(np.abs(sig), np.ones((sw,))/sw, mode='valid')\n\t\tma_lw = np.convolve(np.abs(sig), np.ones((lw,))/lw, mode='valid')\n\t\tma_lw[ma_lw == 0] = epsilon\n\t\treturn np.argmax(np.abs(ma_sw[:len(ma_lw)]/ma_lw)<sta_lta_thresh)\n\t\n\tdef filter_channelize(self,data):\n\t\t\n\t\t\"\"\"Filters signal data w.r.t required sig_len_thresh ( see load_earthquake_data ). \\\n\t\t Also channelizes data into appropriate format for training.\n\t\t :param data: Three-tuple of directional signals.\n\t\t :returns: filtered and channelized data w.r.t. sig_len_thresh and image_data_format\n\t\t :rtype: Two-tuple of form <signals,mag> == <datax,datay>\n\t\t\"\"\"\n\t\tsig_len_thresh = self.sig_len_thresh\n\t\tiformat = self.image_data_format\n\t\tmag1 = data[0]\n\t\tmag2 = data[1]\n\t\tmag3 = data[2]\n\t\tcdatax = []\n\t\tcdatay = []\n\t\tif iformat == 'channels_last':\n\t\t\tfor i in range(len(mag1)):\n\t\t\t\tres = self.sta_lta(mag1[i][1])\n\t\t\t\tif res >= sig_len_thresh:\n\t\t\t\t\ttempsig = np.array([[mag1[i][1][0],mag2[i][1][0],mag3[i][1][0]]])\n\t\t\t\t\tfor j in range(1,res+1):\n\t\t\t\t\t\ttempsig = np.append(tempsig,[[mag1[i][1][j],mag2[i][1][j],mag3[i][1][j]]],axis=0)\n\t\t\t\t\tcdatax.append(tempsig)\n\t\t\t\t\tcdatay.append(mag1[i][0])\n\t\t\t\tsys.stdout.write('Percentage finished: %d %% \\r'%int(100.0*(i+1)/len(mag1)))\n\t\t\t\tsys.stdout.flush()\n\t\t\tprint('\\n')\n\t\t\tcdatax = np.array(cdatax)\t\t\t\n\t\t\tcdatay = np.array(cdatay)\n\t\telse:\n\t\t\tfor i in range(len(mag1)):\n\t\t\t\tres = sta_lta(mag1[i][1])\n\t\t\t\tif res >= sig_len_thresh:\n\t\t\t\t\ttempsig = []\n\t\t\t\t\ttempsig.append(np.array([mag1[i][1][j] for j in range(0,res+1)]))\n\t\t\t\t\ttempsig.append(np.array([mag2[i][1][j] for j in range(0,res+1)]))\n\t\t\t\t\ttempsig.append(np.array([mag3[i][1][j] for j in range(0,res+1)]))\n\t\t\t\t\ttempsig = np.array(tempsig)\n\t\t\t\t\tcdatax.append(tempsig)\n\t\t\t\t\tcdatay.append(mag1[i][0])\n\t\t\t\tsys.stdout.write('Percentage finished: %d %% \\r'%int(100.0*(i+1)/len(mag1)))\n\t\t\t\tsys.stdout.flush()\n\t\t\tprint('\\n')\n\t\t\tcdatax = np.array(cdatax)\t\t\t\n\t\t\tcdatay = np.array(cdatay)\n\t\t\n\t\tcdatax,cdatay = shuffle_in_unison(cdatax,cdatay)\n\t\treturn (cdatax,cdatay)\t\t\t\t\t\n\t\t\t\n\ndef load_earthquake_data(path,image_data_format,timestrech_factors,sig_len_thresh=500, \\\n\t\t\t\t \t\t shortw=0.05,longw=0.3,sfreq=200,sta_lta_thresh=0.07):\n\t\n\t\"\"\"Parses data into a trainable format.\n\t :param path: Path of raw data folder relative to current directory.\n\t :param image_data_format: Keras backend image format requirement \\\n\t\t\t\t\t\t\t\t for training.\n\t :param timestrech_factors: List like object of timestrching factors \\\n\t\t\t\t\t\t\t\t for signal augmentation.\n\t :param sig_len_thresh: Minimum signal length for training \\\n\t\t\t\t\t\t\t after trimming at 90% of P-wave onset.\n\t :param shortw: Length of short window in seconds.\n\t :param longw: Length of long window in seconds.\n\t :param sfreq: Sampling frequency of signal in Hz.\n\t :param sta_lta_thresh: Sensitivity of algorithm. Lower values \\\n\t\t\t\t \t will detect changes in signal early.\n\t :type image_data_format: string\n\t :type timestrech_factors: list-like\n\t :type sig_len_thresh: int\n\n\t All default values have been adapted to the working data set.\n\t\"\"\"\n\tparser = EarthquakeDataParser(path,image_data_format,sig_len_thresh, \\\n\t\t\t\t\t\t\t\t shortw,longw,sfreq,sta_lta_thresh)\n\talphas = timestrech_factors \n\tprint('Reading Data.')\n\tdata = parser.parse_mag()\n\n\t# These parameters should be power of two for FFT\n\tN = 2**10 # Number of channels\n\tM = 2**10 # Size of window\n\n\tw = np.hanning(M-1)# Type of Window (Hanning)\n\t#w = np.hamming(M-1)# Type of Window (Hamming)\n\t#w = np.hamm(M-1)\t\t\t# Type of Window (Hann)\n\tw = np.append(w, [0])# Make window symmetric about (M-1)/2\n\n\t# Synthesis hop factor and hop size\n\tOs = 4 # Synthesis hop factor \n\tRs = int(N / Os)# Synthesis hop size\n\n\tmag1 = []\n\tmag2 = []\n\tmag3 = []\n\tprint('Timestretching signals.')\n\tpci=1\n\tpcf=len(alphas)*len(data[0])\t\n\tfor alpha in alphas:\n\t\tpv = PhaseVocoder(N, M, Rs, w, alpha)\n\t\tfor i in range(0,len(data[0])):\n\t\t\tmag1.append([data[0][i][0],pv.timestretch(data[0][i][1],alpha)])\n\t\t\tmag2.append([data[1][i][0],pv.timestretch(data[1][i][1],alpha)])\n\t\t\tmag3.append([data[2][i][0],pv.timestretch(data[2][i][1],alpha)])\n\t\t\tsys.stdout.write (\"Percentage finishied: %d %% \\r\" % int(100.0*pci/pcf))\n\t\t\tsys.stdout.flush()\n\t\t\tpci=pci+1\n\tprint('\\n')\n\tdel data\n\tdata = (mag1,mag2,mag3)\n\tprint('Filtering & channelizing.')\n\t(cdatax,cdatay) = parser.filter_channelize(data)\n\tlim = int(0.8*len(cdatax))\n\treturn (cdatax[:lim],cdatay[:lim]),(cdatax[lim:],cdatay[lim:])\n" ]
[ [ "numpy.fft.ifft", "numpy.fft.fft", "numpy.zeros", "numpy.hanning" ], [ "pandas.read_csv", "numpy.abs", "numpy.ones", "numpy.append", "numpy.hanning", "numpy.array", "numpy.empty" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
KleinYuan/tf-tailor
[ "70e85643a49ad4484ef856c22a0de2ae8a5a00e9" ]
[ "models/tf_server.py" ]
[ "import tensorflow as tf\n\n\nclass TFServer(object):\n\n\tdef __init__(self, config):\n\t\ttf.reset_default_graph()\n\t\tself.in_progress = False\n\t\tself.prediction = None\n\t\tself.session = None\n\t\tself.graph = None\n\t\tself.frozen = False\n\t\tself.feed_dict = {}\n\t\tself.output_ops = []\n\t\tself.input_ops = []\n\t\tself.model_fp = config.model_fp\n\t\tself.input_tensor_names = config.input_tensor_names\n\t\tself.output_tensor_names = config.output_tensor_names\n\t\tself.device = config.device\n\n\t\twith tf.device(self.device):\n\t\t\tself._load_graph()\n\t\t\tself._init_predictor()\n\n\tdef _load_graph(self):\n\t\tself.graph = tf.Graph()\n\t\twith self.graph.as_default():\n\t\t\tod_graph_def = tf.GraphDef()\n\t\t\twith tf.gfile.GFile(self.model_fp, 'rb') as fid:\n\t\t\t\tserialized_graph = fid.read()\n\t\t\t\tod_graph_def.ParseFromString(serialized_graph)\n\t\t\t\ttf.import_graph_def(od_graph_def, name='')\n\t\ttf.get_default_graph().finalize()\n\n\tdef _init_predictor(self):\n\t\ttf_config = tf.ConfigProto()\n\t\ttf_config.gpu_options.allow_growth = True\n\t\twith self.graph.as_default():\n\t\t\tself.session = tf.Session(config=tf_config, graph=self.graph)\n\t\t\tself._fetch_tensors()\n\n\tdef _fetch_tensors(self):\n\t\tassert len(self.input_tensor_names) > 0\n\t\tassert len(self.output_tensor_names) > 0\n\t\tfor _tensor_name in self.input_tensor_names:\n\t\t\t_op = self.graph.get_tensor_by_name(_tensor_name)\n\t\t\tself.input_ops.append(_op)\n\t\t\tself.feed_dict[_op] = None\n\t\tfor _tensor_name in self.output_tensor_names:\n\t\t\t_op = self.graph.get_tensor_by_name(_tensor_name)\n\t\t\tself.output_ops.append(_op)\n\n\tdef _set_feed_dict(self, data):\n\t\tassert len(data) == len(self.input_ops), 'Data len = {} | Input Ops len = {}'.format(len(data), len(self.input_ops))\n\t\twith self.graph.as_default():\n\t\t\tfor ind, op in enumerate(self.input_ops):\n\t\t\t\tself.feed_dict[op] = data[ind]\n\n\tdef inference(self, data):\n\t\tself.in_progress = True\n\n\t\twith self.graph.as_default():\n\t\t\tself._set_feed_dict(data=data)\n\t\t\tself.prediction = self.session.run(self.output_ops, feed_dict=self.feed_dict)\n\t\tself.in_progress = False\n\n\t\treturn self.prediction\n\n\tdef get_status(self):\n\t\treturn self.in_progress\n\n\tdef clean_up(self):\n\t\t# In old version tensorflow\n\t\t# session sometimes will not be closed automatically\n\t\tself.session.close()\n\t\tself.session = None\n\t\ttf.reset_default_graph()" ]
[ [ "tensorflow.Graph", "tensorflow.device", "tensorflow.import_graph_def", "tensorflow.gfile.GFile", "tensorflow.ConfigProto", "tensorflow.reset_default_graph", "tensorflow.Session", "tensorflow.get_default_graph", "tensorflow.GraphDef" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
RajaSudalai/Motorcyclist_Helmet_Detection
[ "5f739115ed1453ce01a51204219abe080e159761" ]
[ "mrcnn/model.py" ]
[ "\"\"\"\nMask R-CNN\nThe main Mask R-CNN model implementation.\n\nCopyright (c) 2017 Matterport, Inc.\nLicensed under the MIT License (see LICENSE for details)\nWritten by Waleed Abdulla\n\"\"\"\n\nimport os\nimport random\nimport datetime\nimport re\nimport math\nimport logging\nfrom collections import OrderedDict\nimport multiprocessing\nimport numpy as np\nimport tensorflow as tf\nimport keras\nimport keras.backend as K\nimport keras.layers as KL\nimport keras.engine as KE\nimport keras.models as KM\n\nfrom mrcnn import utils\n\n# Requires TensorFlow 1.3+ and Keras 2.0.8+.\nfrom distutils.version import LooseVersion\nassert LooseVersion(tf.__version__) >= LooseVersion(\"1.3\")\nassert LooseVersion(keras.__version__) >= LooseVersion('2.0.8')\n\n\n############################################################\n# Utility Functions\n############################################################\n\ndef log(text, array=None):\n \"\"\"Prints a text message. And, optionally, if a Numpy array is provided it\n prints it's shape, min, and max values.\n \"\"\"\n if array is not None:\n text = text.ljust(25)\n text += (\"shape: {:20} \".format(str(array.shape)))\n if array.size:\n text += (\"min: {:10.5f} max: {:10.5f}\".format(array.min(),array.max()))\n else:\n text += (\"min: {:10} max: {:10}\".format(\"\",\"\"))\n text += \" {}\".format(array.dtype)\n print(text)\n\n\nclass BatchNorm(KL.BatchNormalization):\n \"\"\"Extends the Keras BatchNormalization class to allow a central place\n to make changes if needed.\n\n Batch normalization has a negative effect on training if batches are small\n so this layer is often frozen (via setting in Config class) and functions\n as linear layer.\n \"\"\"\n def call(self, inputs, training=None):\n \"\"\"\n Note about training values:\n None: Train BN layers. This is the normal mode\n False: Freeze BN layers. Good when batch size is small\n True: (don't use). Set layer in training mode even when making inferences\n \"\"\"\n return super(self.__class__, self).call(inputs, training=training)\n\n\ndef compute_backbone_shapes(config, image_shape):\n \"\"\"Computes the width and height of each stage of the backbone network.\n\n Returns:\n [N, (height, width)]. Where N is the number of stages\n \"\"\"\n if callable(config.BACKBONE):\n return config.COMPUTE_BACKBONE_SHAPE(image_shape)\n\n # Currently supports ResNet only\n assert config.BACKBONE in [\"resnet50\", \"resnet101\"]\n return np.array(\n [[int(math.ceil(image_shape[0] / stride)),\n int(math.ceil(image_shape[1] / stride))]\n for stride in config.BACKBONE_STRIDES])\n\n\n############################################################\n# Resnet Graph\n############################################################\n\n# Code adopted from:\n# https://github.com/fchollet/deep-learning-models/blob/master/resnet50.py\n\ndef identity_block(input_tensor, kernel_size, filters, stage, block,\n use_bias=True, train_bn=True):\n \"\"\"The identity_block is the block that has no conv layer at shortcut\n # Arguments\n input_tensor: input tensor\n kernel_size: default 3, the kernel size of middle conv layer at main path\n filters: list of integers, the nb_filters of 3 conv layer at main path\n stage: integer, current stage label, used for generating layer names\n block: 'a','b'..., current block label, used for generating layer names\n use_bias: Boolean. To use or not use a bias in conv layers.\n train_bn: Boolean. Train or freeze Batch Norm layers\n \"\"\"\n nb_filter1, nb_filter2, nb_filter3 = filters\n conv_name_base = 'res' + str(stage) + block + '_branch'\n bn_name_base = 'bn' + str(stage) + block + '_branch'\n\n x = KL.Conv2D(nb_filter1, (1, 1), name=conv_name_base + '2a',\n use_bias=use_bias)(input_tensor)\n x = BatchNorm(name=bn_name_base + '2a')(x, training=train_bn)\n x = KL.Activation('relu')(x)\n\n x = KL.Conv2D(nb_filter2, (kernel_size, kernel_size), padding='same',\n name=conv_name_base + '2b', use_bias=use_bias)(x)\n x = BatchNorm(name=bn_name_base + '2b')(x, training=train_bn)\n x = KL.Activation('relu')(x)\n\n x = KL.Conv2D(nb_filter3, (1, 1), name=conv_name_base + '2c',\n use_bias=use_bias)(x)\n x = BatchNorm(name=bn_name_base + '2c')(x, training=train_bn)\n\n x = KL.Add()([x, input_tensor])\n x = KL.Activation('relu', name='res' + str(stage) + block + '_out')(x)\n return x\n\n\ndef conv_block(input_tensor, kernel_size, filters, stage, block,\n strides=(2, 2), use_bias=True, train_bn=True):\n \"\"\"conv_block is the block that has a conv layer at shortcut\n # Arguments\n input_tensor: input tensor\n kernel_size: default 3, the kernel size of middle conv layer at main path\n filters: list of integers, the nb_filters of 3 conv layer at main path\n stage: integer, current stage label, used for generating layer names\n block: 'a','b'..., current block label, used for generating layer names\n use_bias: Boolean. To use or not use a bias in conv layers.\n train_bn: Boolean. Train or freeze Batch Norm layers\n Note that from stage 3, the first conv layer at main path is with subsample=(2,2)\n And the shortcut should have subsample=(2,2) as well\n \"\"\"\n nb_filter1, nb_filter2, nb_filter3 = filters\n conv_name_base = 'res' + str(stage) + block + '_branch'\n bn_name_base = 'bn' + str(stage) + block + '_branch'\n\n x = KL.Conv2D(nb_filter1, (1, 1), strides=strides,\n name=conv_name_base + '2a', use_bias=use_bias)(input_tensor)\n x = BatchNorm(name=bn_name_base + '2a')(x, training=train_bn)\n x = KL.Activation('relu')(x)\n\n x = KL.Conv2D(nb_filter2, (kernel_size, kernel_size), padding='same',\n name=conv_name_base + '2b', use_bias=use_bias)(x)\n x = BatchNorm(name=bn_name_base + '2b')(x, training=train_bn)\n x = KL.Activation('relu')(x)\n\n x = KL.Conv2D(nb_filter3, (1, 1), name=conv_name_base +\n '2c', use_bias=use_bias)(x)\n x = BatchNorm(name=bn_name_base + '2c')(x, training=train_bn)\n\n shortcut = KL.Conv2D(nb_filter3, (1, 1), strides=strides,\n name=conv_name_base + '1', use_bias=use_bias)(input_tensor)\n shortcut = BatchNorm(name=bn_name_base + '1')(shortcut, training=train_bn)\n\n x = KL.Add()([x, shortcut])\n x = KL.Activation('relu', name='res' + str(stage) + block + '_out')(x)\n return x\n\n\ndef resnet_graph(input_image, architecture, stage5=False, train_bn=True):\n \"\"\"Build a ResNet graph.\n architecture: Can be resnet50 or resnet101\n stage5: Boolean. If False, stage5 of the network is not created\n train_bn: Boolean. Train or freeze Batch Norm layers\n \"\"\"\n assert architecture in [\"resnet50\", \"resnet101\"]\n # Stage 1\n x = KL.ZeroPadding2D((3, 3))(input_image)\n x = KL.Conv2D(64, (7, 7), strides=(2, 2), name='conv1', use_bias=True)(x)\n x = BatchNorm(name='bn_conv1')(x, training=train_bn)\n x = KL.Activation('relu')(x)\n C1 = x = KL.MaxPooling2D((3, 3), strides=(2, 2), padding=\"same\")(x)\n # Stage 2\n x = conv_block(x, 3, [64, 64, 256], stage=2, block='a', strides=(1, 1), train_bn=train_bn)\n x = identity_block(x, 3, [64, 64, 256], stage=2, block='b', train_bn=train_bn)\n C2 = x = identity_block(x, 3, [64, 64, 256], stage=2, block='c', train_bn=train_bn)\n # Stage 3\n x = conv_block(x, 3, [128, 128, 512], stage=3, block='a', train_bn=train_bn)\n x = identity_block(x, 3, [128, 128, 512], stage=3, block='b', train_bn=train_bn)\n x = identity_block(x, 3, [128, 128, 512], stage=3, block='c', train_bn=train_bn)\n C3 = x = identity_block(x, 3, [128, 128, 512], stage=3, block='d', train_bn=train_bn)\n # Stage 4\n x = conv_block(x, 3, [256, 256, 1024], stage=4, block='a', train_bn=train_bn)\n block_count = {\"resnet50\": 5, \"resnet101\": 22}[architecture]\n for i in range(block_count):\n x = identity_block(x, 3, [256, 256, 1024], stage=4, block=chr(98 + i), train_bn=train_bn)\n C4 = x\n # Stage 5\n if stage5:\n x = conv_block(x, 3, [512, 512, 2048], stage=5, block='a', train_bn=train_bn)\n x = identity_block(x, 3, [512, 512, 2048], stage=5, block='b', train_bn=train_bn)\n C5 = x = identity_block(x, 3, [512, 512, 2048], stage=5, block='c', train_bn=train_bn)\n else:\n C5 = None\n return [C1, C2, C3, C4, C5]\n\n\n############################################################\n# Proposal Layer\n############################################################\n\ndef apply_box_deltas_graph(boxes, deltas):\n \"\"\"Applies the given deltas to the given boxes.\n boxes: [N, (y1, x1, y2, x2)] boxes to update\n deltas: [N, (dy, dx, log(dh), log(dw))] refinements to apply\n \"\"\"\n # Convert to y, x, h, w\n height = boxes[:, 2] - boxes[:, 0]\n width = boxes[:, 3] - boxes[:, 1]\n center_y = boxes[:, 0] + 0.5 * height\n center_x = boxes[:, 1] + 0.5 * width\n # Apply deltas\n center_y += deltas[:, 0] * height\n center_x += deltas[:, 1] * width\n height *= tf.exp(deltas[:, 2])\n width *= tf.exp(deltas[:, 3])\n # Convert back to y1, x1, y2, x2\n y1 = center_y - 0.5 * height\n x1 = center_x - 0.5 * width\n y2 = y1 + height\n x2 = x1 + width\n result = tf.stack([y1, x1, y2, x2], axis=1, name=\"apply_box_deltas_out\")\n return result\n\n\ndef clip_boxes_graph(boxes, window):\n \"\"\"\n boxes: [N, (y1, x1, y2, x2)]\n window: [4] in the form y1, x1, y2, x2\n \"\"\"\n # Split\n wy1, wx1, wy2, wx2 = tf.split(window, 4)\n y1, x1, y2, x2 = tf.split(boxes, 4, axis=1)\n # Clip\n y1 = tf.maximum(tf.minimum(y1, wy2), wy1)\n x1 = tf.maximum(tf.minimum(x1, wx2), wx1)\n y2 = tf.maximum(tf.minimum(y2, wy2), wy1)\n x2 = tf.maximum(tf.minimum(x2, wx2), wx1)\n clipped = tf.concat([y1, x1, y2, x2], axis=1, name=\"clipped_boxes\")\n clipped.set_shape((clipped.shape[0], 4))\n return clipped\n\n\nclass ProposalLayer(KE.Layer):\n \"\"\"Receives anchor scores and selects a subset to pass as proposals\n to the second stage. Filtering is done based on anchor scores and\n non-max suppression to remove overlaps. It also applies bounding\n box refinement deltas to anchors.\n\n Inputs:\n rpn_probs: [batch, num_anchors, (bg prob, fg prob)]\n rpn_bbox: [batch, num_anchors, (dy, dx, log(dh), log(dw))]\n anchors: [batch, num_anchors, (y1, x1, y2, x2)] anchors in normalized coordinates\n\n Returns:\n Proposals in normalized coordinates [batch, rois, (y1, x1, y2, x2)]\n \"\"\"\n\n def __init__(self, proposal_count, nms_threshold, config=None, **kwargs):\n super(ProposalLayer, self).__init__(**kwargs)\n self.config = config\n self.proposal_count = proposal_count\n self.nms_threshold = nms_threshold\n\n def call(self, inputs):\n # Box Scores. Use the foreground class confidence. [Batch, num_rois, 1]\n scores = inputs[0][:, :, 1]\n # Box deltas [batch, num_rois, 4]\n deltas = inputs[1]\n deltas = deltas * np.reshape(self.config.RPN_BBOX_STD_DEV, [1, 1, 4])\n # Anchors\n anchors = inputs[2]\n\n # Improve performance by trimming to top anchors by score\n # and doing the rest on the smaller subset.\n pre_nms_limit = tf.minimum(self.config.PRE_NMS_LIMIT, tf.shape(anchors)[1])\n ix = tf.nn.top_k(scores, pre_nms_limit, sorted=True,\n name=\"top_anchors\").indices\n scores = utils.batch_slice([scores, ix], lambda x, y: tf.gather(x, y),\n self.config.IMAGES_PER_GPU)\n deltas = utils.batch_slice([deltas, ix], lambda x, y: tf.gather(x, y),\n self.config.IMAGES_PER_GPU)\n pre_nms_anchors = utils.batch_slice([anchors, ix], lambda a, x: tf.gather(a, x),\n self.config.IMAGES_PER_GPU,\n names=[\"pre_nms_anchors\"])\n\n # Apply deltas to anchors to get refined anchors.\n # [batch, N, (y1, x1, y2, x2)]\n boxes = utils.batch_slice([pre_nms_anchors, deltas],\n lambda x, y: apply_box_deltas_graph(x, y),\n self.config.IMAGES_PER_GPU,\n names=[\"refined_anchors\"])\n\n # Clip to image boundaries. Since we're in normalized coordinates,\n # clip to 0..1 range. [batch, N, (y1, x1, y2, x2)]\n window = np.array([0, 0, 1, 1], dtype=np.float32)\n boxes = utils.batch_slice(boxes,\n lambda x: clip_boxes_graph(x, window),\n self.config.IMAGES_PER_GPU,\n names=[\"refined_anchors_clipped\"])\n\n # Filter out small boxes\n # According to Xinlei Chen's paper, this reduces detection accuracy\n # for small objects, so we're skipping it.\n\n # Non-max suppression\n def nms(boxes, scores):\n indices = tf.image.non_max_suppression(\n boxes, scores, self.proposal_count,\n self.nms_threshold, name=\"rpn_non_max_suppression\")\n proposals = tf.gather(boxes, indices)\n # Pad if needed\n padding = tf.maximum(self.proposal_count - tf.shape(proposals)[0], 0)\n proposals = tf.pad(proposals, [(0, padding), (0, 0)])\n return proposals\n proposals = utils.batch_slice([boxes, scores], nms,\n self.config.IMAGES_PER_GPU)\n return proposals\n\n def compute_output_shape(self, input_shape):\n return (None, self.proposal_count, 4)\n\n\n############################################################\n# ROIAlign Layer\n############################################################\n\ndef log2_graph(x):\n \"\"\"Implementation of Log2. TF doesn't have a native implementation.\"\"\"\n return tf.log(x) / tf.log(2.0)\n\n\nclass PyramidROIAlign(KE.Layer):\n \"\"\"Implements ROI Pooling on multiple levels of the feature pyramid.\n\n Params:\n - pool_shape: [pool_height, pool_width] of the output pooled regions. Usually [7, 7]\n\n Inputs:\n - boxes: [batch, num_boxes, (y1, x1, y2, x2)] in normalized\n coordinates. Possibly padded with zeros if not enough\n boxes to fill the array.\n - image_meta: [batch, (meta data)] Image details. See compose_image_meta()\n - feature_maps: List of feature maps from different levels of the pyramid.\n Each is [batch, height, width, channels]\n\n Output:\n Pooled regions in the shape: [batch, num_boxes, pool_height, pool_width, channels].\n The width and height are those specific in the pool_shape in the layer\n constructor.\n \"\"\"\n\n def __init__(self, pool_shape, **kwargs):\n super(PyramidROIAlign, self).__init__(**kwargs)\n self.pool_shape = tuple(pool_shape)\n\n def call(self, inputs):\n # Crop boxes [batch, num_boxes, (y1, x1, y2, x2)] in normalized coords\n boxes = inputs[0]\n\n # Image meta\n # Holds details about the image. See compose_image_meta()\n image_meta = inputs[1]\n\n # Feature Maps. List of feature maps from different level of the\n # feature pyramid. Each is [batch, height, width, channels]\n feature_maps = inputs[2:]\n\n # Assign each ROI to a level in the pyramid based on the ROI area.\n y1, x1, y2, x2 = tf.split(boxes, 4, axis=2)\n h = y2 - y1\n w = x2 - x1\n # Use shape of first image. Images in a batch must have the same size.\n image_shape = parse_image_meta_graph(image_meta)['image_shape'][0]\n # Equation 1 in the Feature Pyramid Networks paper. Account for\n # the fact that our coordinates are normalized here.\n # e.g. a 224x224 ROI (in pixels) maps to P4\n image_area = tf.cast(image_shape[0] * image_shape[1], tf.float32)\n roi_level = log2_graph(tf.sqrt(h * w) / (224.0 / tf.sqrt(image_area)))\n roi_level = tf.minimum(5, tf.maximum(\n 2, 4 + tf.cast(tf.round(roi_level), tf.int32)))\n roi_level = tf.squeeze(roi_level, 2)\n\n # Loop through levels and apply ROI pooling to each. P2 to P5.\n pooled = []\n box_to_level = []\n for i, level in enumerate(range(2, 6)):\n ix = tf.where(tf.equal(roi_level, level))\n level_boxes = tf.gather_nd(boxes, ix)\n\n # Box indices for crop_and_resize.\n box_indices = tf.cast(ix[:, 0], tf.int32)\n\n # Keep track of which box is mapped to which level\n box_to_level.append(ix)\n\n # Stop gradient propogation to ROI proposals\n level_boxes = tf.stop_gradient(level_boxes)\n box_indices = tf.stop_gradient(box_indices)\n\n # Crop and Resize\n # From Mask R-CNN paper: \"We sample four regular locations, so\n # that we can evaluate either max or average pooling. In fact,\n # interpolating only a single value at each bin center (without\n # pooling) is nearly as effective.\"\n #\n # Here we use the simplified approach of a single value per bin,\n # which is how it's done in tf.crop_and_resize()\n # Result: [batch * num_boxes, pool_height, pool_width, channels]\n pooled.append(tf.image.crop_and_resize(\n feature_maps[i], level_boxes, box_indices, self.pool_shape,\n method=\"bilinear\"))\n\n # Pack pooled features into one tensor\n pooled = tf.concat(pooled, axis=0)\n\n # Pack box_to_level mapping into one array and add another\n # column representing the order of pooled boxes\n box_to_level = tf.concat(box_to_level, axis=0)\n box_range = tf.expand_dims(tf.range(tf.shape(box_to_level)[0]), 1)\n box_to_level = tf.concat([tf.cast(box_to_level, tf.int32), box_range],\n axis=1)\n\n # Rearrange pooled features to match the order of the original boxes\n # Sort box_to_level by batch then box index\n # TF doesn't have a way to sort by two columns, so merge them and sort.\n sorting_tensor = box_to_level[:, 0] * 100000 + box_to_level[:, 1]\n ix = tf.nn.top_k(sorting_tensor, k=tf.shape(\n box_to_level)[0]).indices[::-1]\n ix = tf.gather(box_to_level[:, 2], ix)\n pooled = tf.gather(pooled, ix)\n\n # Re-add the batch dimension\n shape = tf.concat([tf.shape(boxes)[:2], tf.shape(pooled)[1:]], axis=0)\n pooled = tf.reshape(pooled, shape)\n return pooled\n\n def compute_output_shape(self, input_shape):\n return input_shape[0][:2] + self.pool_shape + (input_shape[2][-1], )\n\n\n############################################################\n# Detection Target Layer\n############################################################\n\ndef overlaps_graph(boxes1, boxes2):\n \"\"\"Computes IoU overlaps between two sets of boxes.\n boxes1, boxes2: [N, (y1, x1, y2, x2)].\n \"\"\"\n # 1. Tile boxes2 and repeat boxes1. This allows us to compare\n # every boxes1 against every boxes2 without loops.\n # TF doesn't have an equivalent to np.repeat() so simulate it\n # using tf.tile() and tf.reshape.\n b1 = tf.reshape(tf.tile(tf.expand_dims(boxes1, 1),\n [1, 1, tf.shape(boxes2)[0]]), [-1, 4])\n b2 = tf.tile(boxes2, [tf.shape(boxes1)[0], 1])\n # 2. Compute intersections\n b1_y1, b1_x1, b1_y2, b1_x2 = tf.split(b1, 4, axis=1)\n b2_y1, b2_x1, b2_y2, b2_x2 = tf.split(b2, 4, axis=1)\n y1 = tf.maximum(b1_y1, b2_y1)\n x1 = tf.maximum(b1_x1, b2_x1)\n y2 = tf.minimum(b1_y2, b2_y2)\n x2 = tf.minimum(b1_x2, b2_x2)\n intersection = tf.maximum(x2 - x1, 0) * tf.maximum(y2 - y1, 0)\n # 3. Compute unions\n b1_area = (b1_y2 - b1_y1) * (b1_x2 - b1_x1)\n b2_area = (b2_y2 - b2_y1) * (b2_x2 - b2_x1)\n union = b1_area + b2_area - intersection\n # 4. Compute IoU and reshape to [boxes1, boxes2]\n iou = intersection / union\n overlaps = tf.reshape(iou, [tf.shape(boxes1)[0], tf.shape(boxes2)[0]])\n return overlaps\n\n\ndef detection_targets_graph(proposals, gt_class_ids, gt_boxes, gt_masks, config):\n \"\"\"Generates detection targets for one image. Subsamples proposals and\n generates target class IDs, bounding box deltas, and masks for each.\n\n Inputs:\n proposals: [POST_NMS_ROIS_TRAINING, (y1, x1, y2, x2)] in normalized coordinates. Might\n be zero padded if there are not enough proposals.\n gt_class_ids: [MAX_GT_INSTANCES] int class IDs\n gt_boxes: [MAX_GT_INSTANCES, (y1, x1, y2, x2)] in normalized coordinates.\n gt_masks: [height, width, MAX_GT_INSTANCES] of boolean type.\n\n Returns: Target ROIs and corresponding class IDs, bounding box shifts,\n and masks.\n rois: [TRAIN_ROIS_PER_IMAGE, (y1, x1, y2, x2)] in normalized coordinates\n class_ids: [TRAIN_ROIS_PER_IMAGE]. Integer class IDs. Zero padded.\n deltas: [TRAIN_ROIS_PER_IMAGE, (dy, dx, log(dh), log(dw))]\n masks: [TRAIN_ROIS_PER_IMAGE, height, width]. Masks cropped to bbox\n boundaries and resized to neural network output size.\n\n Note: Returned arrays might be zero padded if not enough target ROIs.\n \"\"\"\n # Assertions\n asserts = [\n tf.Assert(tf.greater(tf.shape(proposals)[0], 0), [proposals],\n name=\"roi_assertion\"),\n ]\n with tf.control_dependencies(asserts):\n proposals = tf.identity(proposals)\n\n # Remove zero padding\n proposals, _ = trim_zeros_graph(proposals, name=\"trim_proposals\")\n gt_boxes, non_zeros = trim_zeros_graph(gt_boxes, name=\"trim_gt_boxes\")\n gt_class_ids = tf.boolean_mask(gt_class_ids, non_zeros,\n name=\"trim_gt_class_ids\")\n gt_masks = tf.gather(gt_masks, tf.where(non_zeros)[:, 0], axis=2,\n name=\"trim_gt_masks\")\n\n # Handle COCO crowds\n # A crowd box in COCO is a bounding box around several instances. Exclude\n # them from training. A crowd box is given a negative class ID.\n crowd_ix = tf.where(gt_class_ids < 0)[:, 0]\n non_crowd_ix = tf.where(gt_class_ids > 0)[:, 0]\n crowd_boxes = tf.gather(gt_boxes, crowd_ix)\n gt_class_ids = tf.gather(gt_class_ids, non_crowd_ix)\n gt_boxes = tf.gather(gt_boxes, non_crowd_ix)\n gt_masks = tf.gather(gt_masks, non_crowd_ix, axis=2)\n\n # Compute overlaps matrix [proposals, gt_boxes]\n overlaps = overlaps_graph(proposals, gt_boxes)\n\n # Compute overlaps with crowd boxes [proposals, crowd_boxes]\n crowd_overlaps = overlaps_graph(proposals, crowd_boxes)\n crowd_iou_max = tf.reduce_max(crowd_overlaps, axis=1)\n no_crowd_bool = (crowd_iou_max < 0.001)\n\n # Determine positive and negative ROIs\n roi_iou_max = tf.reduce_max(overlaps, axis=1)\n # 1. Positive ROIs are those with >= 0.5 IoU with a GT box\n positive_roi_bool = (roi_iou_max >= 0.5)\n positive_indices = tf.where(positive_roi_bool)[:, 0]\n # 2. Negative ROIs are those with < 0.5 with every GT box. Skip crowds.\n negative_indices = tf.where(tf.logical_and(roi_iou_max < 0.5, no_crowd_bool))[:, 0]\n\n # Subsample ROIs. Aim for 33% positive\n # Positive ROIs\n positive_count = int(config.TRAIN_ROIS_PER_IMAGE *\n config.ROI_POSITIVE_RATIO)\n positive_indices = tf.random_shuffle(positive_indices)[:positive_count]\n positive_count = tf.shape(positive_indices)[0]\n # Negative ROIs. Add enough to maintain positive:negative ratio.\n r = 1.0 / config.ROI_POSITIVE_RATIO\n negative_count = tf.cast(r * tf.cast(positive_count, tf.float32), tf.int32) - positive_count\n negative_indices = tf.random_shuffle(negative_indices)[:negative_count]\n # Gather selected ROIs\n positive_rois = tf.gather(proposals, positive_indices)\n negative_rois = tf.gather(proposals, negative_indices)\n\n # Assign positive ROIs to GT boxes.\n positive_overlaps = tf.gather(overlaps, positive_indices)\n roi_gt_box_assignment = tf.cond(\n tf.greater(tf.shape(positive_overlaps)[1], 0),\n true_fn = lambda: tf.argmax(positive_overlaps, axis=1),\n false_fn = lambda: tf.cast(tf.constant([]),tf.int64)\n )\n roi_gt_boxes = tf.gather(gt_boxes, roi_gt_box_assignment)\n roi_gt_class_ids = tf.gather(gt_class_ids, roi_gt_box_assignment)\n\n # Compute bbox refinement for positive ROIs\n deltas = utils.box_refinement_graph(positive_rois, roi_gt_boxes)\n deltas /= config.BBOX_STD_DEV\n\n # Assign positive ROIs to GT masks\n # Permute masks to [N, height, width, 1]\n transposed_masks = tf.expand_dims(tf.transpose(gt_masks, [2, 0, 1]), -1)\n # Pick the right mask for each ROI\n roi_masks = tf.gather(transposed_masks, roi_gt_box_assignment)\n\n # Compute mask targets\n boxes = positive_rois\n if config.USE_MINI_MASK:\n # Transform ROI coordinates from normalized image space\n # to normalized mini-mask space.\n y1, x1, y2, x2 = tf.split(positive_rois, 4, axis=1)\n gt_y1, gt_x1, gt_y2, gt_x2 = tf.split(roi_gt_boxes, 4, axis=1)\n gt_h = gt_y2 - gt_y1\n gt_w = gt_x2 - gt_x1\n y1 = (y1 - gt_y1) / gt_h\n x1 = (x1 - gt_x1) / gt_w\n y2 = (y2 - gt_y1) / gt_h\n x2 = (x2 - gt_x1) / gt_w\n boxes = tf.concat([y1, x1, y2, x2], 1)\n box_ids = tf.range(0, tf.shape(roi_masks)[0])\n masks = tf.image.crop_and_resize(tf.cast(roi_masks, tf.float32), boxes,\n box_ids,\n config.MASK_SHAPE)\n # Remove the extra dimension from masks.\n masks = tf.squeeze(masks, axis=3)\n\n # Threshold mask pixels at 0.5 to have GT masks be 0 or 1 to use with\n # binary cross entropy loss.\n masks = tf.round(masks)\n\n # Append negative ROIs and pad bbox deltas and masks that\n # are not used for negative ROIs with zeros.\n rois = tf.concat([positive_rois, negative_rois], axis=0)\n N = tf.shape(negative_rois)[0]\n P = tf.maximum(config.TRAIN_ROIS_PER_IMAGE - tf.shape(rois)[0], 0)\n rois = tf.pad(rois, [(0, P), (0, 0)])\n roi_gt_boxes = tf.pad(roi_gt_boxes, [(0, N + P), (0, 0)])\n roi_gt_class_ids = tf.pad(roi_gt_class_ids, [(0, N + P)])\n deltas = tf.pad(deltas, [(0, N + P), (0, 0)])\n masks = tf.pad(masks, [[0, N + P], (0, 0), (0, 0)])\n\n return rois, roi_gt_class_ids, deltas, masks\n\n\nclass DetectionTargetLayer(KE.Layer):\n \"\"\"Subsamples proposals and generates target box refinement, class_ids,\n and masks for each.\n\n Inputs:\n proposals: [batch, N, (y1, x1, y2, x2)] in normalized coordinates. Might\n be zero padded if there are not enough proposals.\n gt_class_ids: [batch, MAX_GT_INSTANCES] Integer class IDs.\n gt_boxes: [batch, MAX_GT_INSTANCES, (y1, x1, y2, x2)] in normalized\n coordinates.\n gt_masks: [batch, height, width, MAX_GT_INSTANCES] of boolean type\n\n Returns: Target ROIs and corresponding class IDs, bounding box shifts,\n and masks.\n rois: [batch, TRAIN_ROIS_PER_IMAGE, (y1, x1, y2, x2)] in normalized\n coordinates\n target_class_ids: [batch, TRAIN_ROIS_PER_IMAGE]. Integer class IDs.\n target_deltas: [batch, TRAIN_ROIS_PER_IMAGE, (dy, dx, log(dh), log(dw)]\n target_mask: [batch, TRAIN_ROIS_PER_IMAGE, height, width]\n Masks cropped to bbox boundaries and resized to neural\n network output size.\n\n Note: Returned arrays might be zero padded if not enough target ROIs.\n \"\"\"\n\n def __init__(self, config, **kwargs):\n super(DetectionTargetLayer, self).__init__(**kwargs)\n self.config = config\n\n def call(self, inputs):\n proposals = inputs[0]\n gt_class_ids = inputs[1]\n gt_boxes = inputs[2]\n gt_masks = inputs[3]\n\n # Slice the batch and run a graph for each slice\n # TODO: Rename target_bbox to target_deltas for clarity\n names = [\"rois\", \"target_class_ids\", \"target_bbox\", \"target_mask\"]\n outputs = utils.batch_slice(\n [proposals, gt_class_ids, gt_boxes, gt_masks],\n lambda w, x, y, z: detection_targets_graph(\n w, x, y, z, self.config),\n self.config.IMAGES_PER_GPU, names=names)\n return outputs\n\n def compute_output_shape(self, input_shape):\n return [\n (None, self.config.TRAIN_ROIS_PER_IMAGE, 4), # rois\n (None, self.config.TRAIN_ROIS_PER_IMAGE), # class_ids\n (None, self.config.TRAIN_ROIS_PER_IMAGE, 4), # deltas\n (None, self.config.TRAIN_ROIS_PER_IMAGE, self.config.MASK_SHAPE[0],\n self.config.MASK_SHAPE[1]) # masks\n ]\n\n def compute_mask(self, inputs, mask=None):\n return [None, None, None, None]\n\n\n############################################################\n# Detection Layer\n############################################################\n\ndef refine_detections_graph(rois, probs, deltas, window, config):\n \"\"\"Refine classified proposals and filter overlaps and return final\n detections.\n\n Inputs:\n rois: [N, (y1, x1, y2, x2)] in normalized coordinates\n probs: [N, num_classes]. Class probabilities.\n deltas: [N, num_classes, (dy, dx, log(dh), log(dw))]. Class-specific\n bounding box deltas.\n window: (y1, x1, y2, x2) in normalized coordinates. The part of the image\n that contains the image excluding the padding.\n\n Returns detections shaped: [num_detections, (y1, x1, y2, x2, class_id, score)] where\n coordinates are normalized.\n \"\"\"\n # Class IDs per ROI\n class_ids = tf.argmax(probs, axis=1, output_type=tf.int32)\n # Class probability of the top class of each ROI\n indices = tf.stack([tf.range(probs.shape[0]), class_ids], axis=1)\n class_scores = tf.gather_nd(probs, indices)\n # Class-specific bounding box deltas\n deltas_specific = tf.gather_nd(deltas, indices)\n # Apply bounding box deltas\n # Shape: [boxes, (y1, x1, y2, x2)] in normalized coordinates\n refined_rois = apply_box_deltas_graph(\n rois, deltas_specific * config.BBOX_STD_DEV)\n # Clip boxes to image window\n refined_rois = clip_boxes_graph(refined_rois, window)\n\n # TODO: Filter out boxes with zero area\n\n # Filter out background boxes\n keep = tf.where(class_ids > 0)[:, 0]\n # Filter out low confidence boxes\n if config.DETECTION_MIN_CONFIDENCE:\n conf_keep = tf.where(class_scores >= config.DETECTION_MIN_CONFIDENCE)[:, 0]\n keep = tf.sets.set_intersection(tf.expand_dims(keep, 0),\n tf.expand_dims(conf_keep, 0))\n keep = tf.sparse_tensor_to_dense(keep)[0]\n\n # Apply per-class NMS\n # 1. Prepare variables\n pre_nms_class_ids = tf.gather(class_ids, keep)\n pre_nms_scores = tf.gather(class_scores, keep)\n pre_nms_rois = tf.gather(refined_rois, keep)\n unique_pre_nms_class_ids = tf.unique(pre_nms_class_ids)[0]\n\n def nms_keep_map(class_id):\n \"\"\"Apply Non-Maximum Suppression on ROIs of the given class.\"\"\"\n # Indices of ROIs of the given class\n ixs = tf.where(tf.equal(pre_nms_class_ids, class_id))[:, 0]\n # Apply NMS\n class_keep = tf.image.non_max_suppression(\n tf.gather(pre_nms_rois, ixs),\n tf.gather(pre_nms_scores, ixs),\n max_output_size=config.DETECTION_MAX_INSTANCES,\n iou_threshold=config.DETECTION_NMS_THRESHOLD)\n # Map indices\n class_keep = tf.gather(keep, tf.gather(ixs, class_keep))\n # Pad with -1 so returned tensors have the same shape\n gap = config.DETECTION_MAX_INSTANCES - tf.shape(class_keep)[0]\n class_keep = tf.pad(class_keep, [(0, gap)],\n mode='CONSTANT', constant_values=-1)\n # Set shape so map_fn() can infer result shape\n class_keep.set_shape([config.DETECTION_MAX_INSTANCES])\n return class_keep\n\n # 2. Map over class IDs\n nms_keep = tf.map_fn(nms_keep_map, unique_pre_nms_class_ids,\n dtype=tf.int64)\n # 3. Merge results into one list, and remove -1 padding\n nms_keep = tf.reshape(nms_keep, [-1])\n nms_keep = tf.gather(nms_keep, tf.where(nms_keep > -1)[:, 0])\n # 4. Compute intersection between keep and nms_keep\n keep = tf.sets.set_intersection(tf.expand_dims(keep, 0),\n tf.expand_dims(nms_keep, 0))\n keep = tf.sparse_tensor_to_dense(keep)[0]\n # Keep top detections\n roi_count = config.DETECTION_MAX_INSTANCES\n class_scores_keep = tf.gather(class_scores, keep)\n num_keep = tf.minimum(tf.shape(class_scores_keep)[0], roi_count)\n top_ids = tf.nn.top_k(class_scores_keep, k=num_keep, sorted=True)[1]\n keep = tf.gather(keep, top_ids)\n\n # Arrange output as [N, (y1, x1, y2, x2, class_id, score)]\n # Coordinates are normalized.\n detections = tf.concat([\n tf.gather(refined_rois, keep),\n tf.to_float(tf.gather(class_ids, keep))[..., tf.newaxis],\n tf.gather(class_scores, keep)[..., tf.newaxis]\n ], axis=1)\n\n # Pad with zeros if detections < DETECTION_MAX_INSTANCES\n gap = config.DETECTION_MAX_INSTANCES - tf.shape(detections)[0]\n detections = tf.pad(detections, [(0, gap), (0, 0)], \"CONSTANT\")\n return detections\n\n\nclass DetectionLayer(KE.Layer):\n \"\"\"Takes classified proposal boxes and their bounding box deltas and\n returns the final detection boxes.\n\n Returns:\n [batch, num_detections, (y1, x1, y2, x2, class_id, class_score)] where\n coordinates are normalized.\n \"\"\"\n\n def __init__(self, config=None, **kwargs):\n super(DetectionLayer, self).__init__(**kwargs)\n self.config = config\n\n def call(self, inputs):\n rois = inputs[0]\n mrcnn_class = inputs[1]\n mrcnn_bbox = inputs[2]\n image_meta = inputs[3]\n\n # Get windows of images in normalized coordinates. Windows are the area\n # in the image that excludes the padding.\n # Use the shape of the first image in the batch to normalize the window\n # because we know that all images get resized to the same size.\n m = parse_image_meta_graph(image_meta)\n image_shape = m['image_shape'][0]\n window = norm_boxes_graph(m['window'], image_shape[:2])\n\n # Run detection refinement graph on each item in the batch\n detections_batch = utils.batch_slice(\n [rois, mrcnn_class, mrcnn_bbox, window],\n lambda x, y, w, z: refine_detections_graph(x, y, w, z, self.config),\n self.config.IMAGES_PER_GPU)\n\n # Reshape output\n # [batch, num_detections, (y1, x1, y2, x2, class_id, class_score)] in\n # normalized coordinates\n return tf.reshape(\n detections_batch,\n [self.config.BATCH_SIZE, self.config.DETECTION_MAX_INSTANCES, 6])\n\n def compute_output_shape(self, input_shape):\n return (None, self.config.DETECTION_MAX_INSTANCES, 6)\n\n\n############################################################\n# Region Proposal Network (RPN)\n############################################################\n\ndef rpn_graph(feature_map, anchors_per_location, anchor_stride):\n \"\"\"Builds the computation graph of Region Proposal Network.\n\n feature_map: backbone features [batch, height, width, depth]\n anchors_per_location: number of anchors per pixel in the feature map\n anchor_stride: Controls the density of anchors. Typically 1 (anchors for\n every pixel in the feature map), or 2 (every other pixel).\n\n Returns:\n rpn_class_logits: [batch, H * W * anchors_per_location, 2] Anchor classifier logits (before softmax)\n rpn_probs: [batch, H * W * anchors_per_location, 2] Anchor classifier probabilities.\n rpn_bbox: [batch, H * W * anchors_per_location, (dy, dx, log(dh), log(dw))] Deltas to be\n applied to anchors.\n \"\"\"\n # TODO: check if stride of 2 causes alignment issues if the feature map\n # is not even.\n # Shared convolutional base of the RPN\n shared = KL.Conv2D(512, (3, 3), padding='same', activation='relu',\n strides=anchor_stride,\n name='rpn_conv_shared')(feature_map)\n\n # Anchor Score. [batch, height, width, anchors per location * 2].\n x = KL.Conv2D(2 * anchors_per_location, (1, 1), padding='valid',\n activation='linear', name='rpn_class_raw')(shared)\n\n # Reshape to [batch, anchors, 2]\n rpn_class_logits = KL.Lambda(\n lambda t: tf.reshape(t, [tf.shape(t)[0], -1, 2]))(x)\n\n # Softmax on last dimension of BG/FG.\n rpn_probs = KL.Activation(\n \"softmax\", name=\"rpn_class_xxx\")(rpn_class_logits)\n\n # Bounding box refinement. [batch, H, W, anchors per location * depth]\n # where depth is [x, y, log(w), log(h)]\n x = KL.Conv2D(anchors_per_location * 4, (1, 1), padding=\"valid\",\n activation='linear', name='rpn_bbox_pred')(shared)\n\n # Reshape to [batch, anchors, 4]\n rpn_bbox = KL.Lambda(lambda t: tf.reshape(t, [tf.shape(t)[0], -1, 4]))(x)\n\n return [rpn_class_logits, rpn_probs, rpn_bbox]\n\n\ndef build_rpn_model(anchor_stride, anchors_per_location, depth):\n \"\"\"Builds a Keras model of the Region Proposal Network.\n It wraps the RPN graph so it can be used multiple times with shared\n weights.\n\n anchors_per_location: number of anchors per pixel in the feature map\n anchor_stride: Controls the density of anchors. Typically 1 (anchors for\n every pixel in the feature map), or 2 (every other pixel).\n depth: Depth of the backbone feature map.\n\n Returns a Keras Model object. The model outputs, when called, are:\n rpn_class_logits: [batch, H * W * anchors_per_location, 2] Anchor classifier logits (before softmax)\n rpn_probs: [batch, H * W * anchors_per_location, 2] Anchor classifier probabilities.\n rpn_bbox: [batch, H * W * anchors_per_location, (dy, dx, log(dh), log(dw))] Deltas to be\n applied to anchors.\n \"\"\"\n input_feature_map = KL.Input(shape=[None, None, depth],\n name=\"input_rpn_feature_map\")\n outputs = rpn_graph(input_feature_map, anchors_per_location, anchor_stride)\n return KM.Model([input_feature_map], outputs, name=\"rpn_model\")\n\n\n############################################################\n# Feature Pyramid Network Heads\n############################################################\n\ndef fpn_classifier_graph(rois, feature_maps, image_meta,\n pool_size, num_classes, train_bn=True,\n fc_layers_size=1024):\n \"\"\"Builds the computation graph of the feature pyramid network classifier\n and regressor heads.\n\n rois: [batch, num_rois, (y1, x1, y2, x2)] Proposal boxes in normalized\n coordinates.\n feature_maps: List of feature maps from different layers of the pyramid,\n [P2, P3, P4, P5]. Each has a different resolution.\n image_meta: [batch, (meta data)] Image details. See compose_image_meta()\n pool_size: The width of the square feature map generated from ROI Pooling.\n num_classes: number of classes, which determines the depth of the results\n train_bn: Boolean. Train or freeze Batch Norm layers\n fc_layers_size: Size of the 2 FC layers\n\n Returns:\n logits: [batch, num_rois, NUM_CLASSES] classifier logits (before softmax)\n probs: [batch, num_rois, NUM_CLASSES] classifier probabilities\n bbox_deltas: [batch, num_rois, NUM_CLASSES, (dy, dx, log(dh), log(dw))] Deltas to apply to\n proposal boxes\n \"\"\"\n # ROI Pooling\n # Shape: [batch, num_rois, POOL_SIZE, POOL_SIZE, channels]\n x = PyramidROIAlign([pool_size, pool_size],\n name=\"roi_align_classifier\")([rois, image_meta] + feature_maps)\n # Two 1024 FC layers (implemented with Conv2D for consistency)\n x = KL.TimeDistributed(KL.Conv2D(fc_layers_size, (pool_size, pool_size), padding=\"valid\"),\n name=\"mrcnn_class_conv1\")(x)\n x = KL.TimeDistributed(BatchNorm(), name='mrcnn_class_bn1')(x, training=train_bn)\n x = KL.Activation('relu')(x)\n x = KL.TimeDistributed(KL.Conv2D(fc_layers_size, (1, 1)),\n name=\"mrcnn_class_conv2\")(x)\n x = KL.TimeDistributed(BatchNorm(), name='mrcnn_class_bn2')(x, training=train_bn)\n x = KL.Activation('relu')(x)\n\n shared = KL.Lambda(lambda x: K.squeeze(K.squeeze(x, 3), 2),\n name=\"pool_squeeze\")(x)\n\n # Classifier head\n mrcnn_class_logits = KL.TimeDistributed(KL.Dense(num_classes),\n name='mrcnn_class_logits')(shared)\n mrcnn_probs = KL.TimeDistributed(KL.Activation(\"softmax\"),\n name=\"mrcnn_class\")(mrcnn_class_logits)\n\n # BBox head\n # [batch, num_rois, NUM_CLASSES * (dy, dx, log(dh), log(dw))]\n x = KL.TimeDistributed(KL.Dense(num_classes * 4, activation='linear'),\n name='mrcnn_bbox_fc')(shared)\n # Reshape to [batch, num_rois, NUM_CLASSES, (dy, dx, log(dh), log(dw))]\n s = K.int_shape(x)\n mrcnn_bbox = KL.Reshape((s[1], num_classes, 4), name=\"mrcnn_bbox\")(x)\n\n return mrcnn_class_logits, mrcnn_probs, mrcnn_bbox\n\n\ndef build_fpn_mask_graph(rois, feature_maps, image_meta,\n pool_size, num_classes, train_bn=True):\n \"\"\"Builds the computation graph of the mask head of Feature Pyramid Network.\n\n rois: [batch, num_rois, (y1, x1, y2, x2)] Proposal boxes in normalized\n coordinates.\n feature_maps: List of feature maps from different layers of the pyramid,\n [P2, P3, P4, P5]. Each has a different resolution.\n image_meta: [batch, (meta data)] Image details. See compose_image_meta()\n pool_size: The width of the square feature map generated from ROI Pooling.\n num_classes: number of classes, which determines the depth of the results\n train_bn: Boolean. Train or freeze Batch Norm layers\n\n Returns: Masks [batch, num_rois, MASK_POOL_SIZE, MASK_POOL_SIZE, NUM_CLASSES]\n \"\"\"\n # ROI Pooling\n # Shape: [batch, num_rois, MASK_POOL_SIZE, MASK_POOL_SIZE, channels]\n x = PyramidROIAlign([pool_size, pool_size],\n name=\"roi_align_mask\")([rois, image_meta] + feature_maps)\n\n # Conv layers\n x = KL.TimeDistributed(KL.Conv2D(256, (3, 3), padding=\"same\"),\n name=\"mrcnn_mask_conv1\")(x)\n x = KL.TimeDistributed(BatchNorm(),\n name='mrcnn_mask_bn1')(x, training=train_bn)\n x = KL.Activation('relu')(x)\n\n x = KL.TimeDistributed(KL.Conv2D(256, (3, 3), padding=\"same\"),\n name=\"mrcnn_mask_conv2\")(x)\n x = KL.TimeDistributed(BatchNorm(),\n name='mrcnn_mask_bn2')(x, training=train_bn)\n x = KL.Activation('relu')(x)\n\n x = KL.TimeDistributed(KL.Conv2D(256, (3, 3), padding=\"same\"),\n name=\"mrcnn_mask_conv3\")(x)\n x = KL.TimeDistributed(BatchNorm(),\n name='mrcnn_mask_bn3')(x, training=train_bn)\n x = KL.Activation('relu')(x)\n\n x = KL.TimeDistributed(KL.Conv2D(256, (3, 3), padding=\"same\"),\n name=\"mrcnn_mask_conv4\")(x)\n x = KL.TimeDistributed(BatchNorm(),\n name='mrcnn_mask_bn4')(x, training=train_bn)\n x = KL.Activation('relu')(x)\n\n x = KL.TimeDistributed(KL.Conv2DTranspose(256, (2, 2), strides=2, activation=\"relu\"),\n name=\"mrcnn_mask_deconv\")(x)\n x = KL.TimeDistributed(KL.Conv2D(num_classes, (1, 1), strides=1, activation=\"sigmoid\"),\n name=\"mrcnn_mask\")(x)\n return x\n\n\n############################################################\n# Loss Functions\n############################################################\n\ndef smooth_l1_loss(y_true, y_pred):\n \"\"\"Implements Smooth-L1 loss.\n y_true and y_pred are typically: [N, 4], but could be any shape.\n \"\"\"\n diff = K.abs(y_true - y_pred)\n less_than_one = K.cast(K.less(diff, 1.0), \"float32\")\n loss = (less_than_one * 0.5 * diff**2) + (1 - less_than_one) * (diff - 0.5)\n return loss\n\n\ndef rpn_class_loss_graph(rpn_match, rpn_class_logits):\n \"\"\"RPN anchor classifier loss.\n\n rpn_match: [batch, anchors, 1]. Anchor match type. 1=positive,\n -1=negative, 0=neutral anchor.\n rpn_class_logits: [batch, anchors, 2]. RPN classifier logits for BG/FG.\n \"\"\"\n # Squeeze last dim to simplify\n rpn_match = tf.squeeze(rpn_match, -1)\n # Get anchor classes. Convert the -1/+1 match to 0/1 values.\n anchor_class = K.cast(K.equal(rpn_match, 1), tf.int32)\n # Positive and Negative anchors contribute to the loss,\n # but neutral anchors (match value = 0) don't.\n indices = tf.where(K.not_equal(rpn_match, 0))\n # Pick rows that contribute to the loss and filter out the rest.\n rpn_class_logits = tf.gather_nd(rpn_class_logits, indices)\n anchor_class = tf.gather_nd(anchor_class, indices)\n # Cross entropy loss\n loss = K.sparse_categorical_crossentropy(target=anchor_class,\n output=rpn_class_logits,\n from_logits=True)\n loss = K.switch(tf.size(loss) > 0, K.mean(loss), tf.constant(0.0))\n return loss\n\n\ndef rpn_bbox_loss_graph(config, target_bbox, rpn_match, rpn_bbox):\n \"\"\"Return the RPN bounding box loss graph.\n\n config: the model config object.\n target_bbox: [batch, max positive anchors, (dy, dx, log(dh), log(dw))].\n Uses 0 padding to fill in unsed bbox deltas.\n rpn_match: [batch, anchors, 1]. Anchor match type. 1=positive,\n -1=negative, 0=neutral anchor.\n rpn_bbox: [batch, anchors, (dy, dx, log(dh), log(dw))]\n \"\"\"\n # Positive anchors contribute to the loss, but negative and\n # neutral anchors (match value of 0 or -1) don't.\n rpn_match = K.squeeze(rpn_match, -1)\n indices = tf.where(K.equal(rpn_match, 1))\n\n # Pick bbox deltas that contribute to the loss\n rpn_bbox = tf.gather_nd(rpn_bbox, indices)\n\n # Trim target bounding box deltas to the same length as rpn_bbox.\n batch_counts = K.sum(K.cast(K.equal(rpn_match, 1), tf.int32), axis=1)\n target_bbox = batch_pack_graph(target_bbox, batch_counts,\n config.IMAGES_PER_GPU)\n\n loss = smooth_l1_loss(target_bbox, rpn_bbox)\n \n loss = K.switch(tf.size(loss) > 0, K.mean(loss), tf.constant(0.0))\n return loss\n\n\ndef mrcnn_class_loss_graph(target_class_ids, pred_class_logits,\n active_class_ids):\n \"\"\"Loss for the classifier head of Mask RCNN.\n\n target_class_ids: [batch, num_rois]. Integer class IDs. Uses zero\n padding to fill in the array.\n pred_class_logits: [batch, num_rois, num_classes]\n active_class_ids: [batch, num_classes]. Has a value of 1 for\n classes that are in the dataset of the image, and 0\n for classes that are not in the dataset.\n \"\"\"\n # During model building, Keras calls this function with\n # target_class_ids of type float32. Unclear why. Cast it\n # to int to get around it.\n target_class_ids = tf.cast(target_class_ids, 'int64')\n\n # Find predictions of classes that are not in the dataset.\n pred_class_ids = tf.argmax(pred_class_logits, axis=2)\n # TODO: Update this line to work with batch > 1. Right now it assumes all\n # images in a batch have the same active_class_ids\n pred_active = tf.gather(active_class_ids[0], pred_class_ids)\n\n # Loss\n loss = tf.nn.sparse_softmax_cross_entropy_with_logits(\n labels=target_class_ids, logits=pred_class_logits)\n\n # Erase losses of predictions of classes that are not in the active\n # classes of the image.\n loss = loss * pred_active\n\n # Computer loss mean. Use only predictions that contribute\n # to the loss to get a correct mean.\n loss = tf.reduce_sum(loss) / tf.reduce_sum(pred_active)\n return loss\n\n\ndef mrcnn_bbox_loss_graph(target_bbox, target_class_ids, pred_bbox):\n \"\"\"Loss for Mask R-CNN bounding box refinement.\n\n target_bbox: [batch, num_rois, (dy, dx, log(dh), log(dw))]\n target_class_ids: [batch, num_rois]. Integer class IDs.\n pred_bbox: [batch, num_rois, num_classes, (dy, dx, log(dh), log(dw))]\n \"\"\"\n # Reshape to merge batch and roi dimensions for simplicity.\n target_class_ids = K.reshape(target_class_ids, (-1,))\n target_bbox = K.reshape(target_bbox, (-1, 4))\n pred_bbox = K.reshape(pred_bbox, (-1, K.int_shape(pred_bbox)[2], 4))\n\n # Only positive ROIs contribute to the loss. And only\n # the right class_id of each ROI. Get their indices.\n positive_roi_ix = tf.where(target_class_ids > 0)[:, 0]\n positive_roi_class_ids = tf.cast(\n tf.gather(target_class_ids, positive_roi_ix), tf.int64)\n indices = tf.stack([positive_roi_ix, positive_roi_class_ids], axis=1)\n\n # Gather the deltas (predicted and true) that contribute to loss\n target_bbox = tf.gather(target_bbox, positive_roi_ix)\n pred_bbox = tf.gather_nd(pred_bbox, indices)\n\n # Smooth-L1 Loss\n loss = K.switch(tf.size(target_bbox) > 0,\n smooth_l1_loss(y_true=target_bbox, y_pred=pred_bbox),\n tf.constant(0.0))\n loss = K.mean(loss)\n return loss\n\n\ndef mrcnn_mask_loss_graph(target_masks, target_class_ids, pred_masks):\n \"\"\"Mask binary cross-entropy loss for the masks head.\n\n target_masks: [batch, num_rois, height, width].\n A float32 tensor of values 0 or 1. Uses zero padding to fill array.\n target_class_ids: [batch, num_rois]. Integer class IDs. Zero padded.\n pred_masks: [batch, proposals, height, width, num_classes] float32 tensor\n with values from 0 to 1.\n \"\"\"\n # Reshape for simplicity. Merge first two dimensions into one.\n target_class_ids = K.reshape(target_class_ids, (-1,))\n mask_shape = tf.shape(target_masks)\n target_masks = K.reshape(target_masks, (-1, mask_shape[2], mask_shape[3]))\n pred_shape = tf.shape(pred_masks)\n pred_masks = K.reshape(pred_masks,\n (-1, pred_shape[2], pred_shape[3], pred_shape[4]))\n # Permute predicted masks to [N, num_classes, height, width]\n pred_masks = tf.transpose(pred_masks, [0, 3, 1, 2])\n\n # Only positive ROIs contribute to the loss. And only\n # the class specific mask of each ROI.\n positive_ix = tf.where(target_class_ids > 0)[:, 0]\n positive_class_ids = tf.cast(\n tf.gather(target_class_ids, positive_ix), tf.int64)\n indices = tf.stack([positive_ix, positive_class_ids], axis=1)\n\n # Gather the masks (predicted and true) that contribute to loss\n y_true = tf.gather(target_masks, positive_ix)\n y_pred = tf.gather_nd(pred_masks, indices)\n\n # Compute binary cross entropy. If no positive ROIs, then return 0.\n # shape: [batch, roi, num_classes]\n loss = K.switch(tf.size(y_true) > 0,\n K.binary_crossentropy(target=y_true, output=y_pred),\n tf.constant(0.0))\n loss = K.mean(loss)\n return loss\n\n\n############################################################\n# Data Generator\n############################################################\n\ndef load_image_gt(dataset, config, image_id, augment=False, augmentation=None,\n use_mini_mask=False):\n \"\"\"Load and return ground truth data for an image (image, mask, bounding boxes).\n\n augment: (deprecated. Use augmentation instead). If true, apply random\n image augmentation. Currently, only horizontal flipping is offered.\n augmentation: Optional. An imgaug (https://github.com/aleju/imgaug) augmentation.\n For example, passing imgaug.augmenters.Fliplr(0.5) flips images\n right/left 50% of the time.\n use_mini_mask: If False, returns full-size masks that are the same height\n and width as the original image. These can be big, for example\n 1024x1024x100 (for 100 instances). Mini masks are smaller, typically,\n 224x224 and are generated by extracting the bounding box of the\n object and resizing it to MINI_MASK_SHAPE.\n\n Returns:\n image: [height, width, 3]\n shape: the original shape of the image before resizing and cropping.\n class_ids: [instance_count] Integer class IDs\n bbox: [instance_count, (y1, x1, y2, x2)]\n mask: [height, width, instance_count]. The height and width are those\n of the image unless use_mini_mask is True, in which case they are\n defined in MINI_MASK_SHAPE.\n \"\"\"\n # Load image and mask\n image = dataset.load_image(image_id)\n mask, class_ids = dataset.load_mask(image_id)\n original_shape = image.shape\n image, window, scale, padding, crop = utils.resize_image(\n image,\n min_dim=config.IMAGE_MIN_DIM,\n min_scale=config.IMAGE_MIN_SCALE,\n max_dim=config.IMAGE_MAX_DIM,\n mode=config.IMAGE_RESIZE_MODE)\n mask = utils.resize_mask(mask, scale, padding, crop)\n\n # Random horizontal flips.\n # TODO: will be removed in a future update in favor of augmentation\n if augment:\n logging.warning(\"'augment' is deprecated. Use 'augmentation' instead.\")\n if random.randint(0, 1):\n image = np.fliplr(image)\n mask = np.fliplr(mask)\n\n # Augmentation\n # This requires the imgaug lib (https://github.com/aleju/imgaug)\n if augmentation:\n import imgaug\n\n # Augmenters that are safe to apply to masks\n # Some, such as Affine, have settings that make them unsafe, so always\n # test your augmentation on masks\n MASK_AUGMENTERS = [\"Sequential\", \"SomeOf\", \"OneOf\", \"Sometimes\",\n \"Fliplr\", \"Flipud\", \"CropAndPad\",\n \"Affine\", \"PiecewiseAffine\"]\n\n def hook(images, augmenter, parents, default):\n \"\"\"Determines which augmenters to apply to masks.\"\"\"\n return augmenter.__class__.__name__ in MASK_AUGMENTERS\n\n # Store shapes before augmentation to compare\n image_shape = image.shape\n mask_shape = mask.shape\n # Make augmenters deterministic to apply similarly to images and masks\n det = augmentation.to_deterministic()\n image = det.augment_image(image)\n # Change mask to np.uint8 because imgaug doesn't support np.bool\n mask = det.augment_image(mask.astype(np.uint8),\n hooks=imgaug.HooksImages(activator=hook))\n # Verify that shapes didn't change\n assert image.shape == image_shape, \"Augmentation shouldn't change image size\"\n assert mask.shape == mask_shape, \"Augmentation shouldn't change mask size\"\n # Change mask back to bool\n mask = mask.astype(np.bool)\n\n # Note that some boxes might be all zeros if the corresponding mask got cropped out.\n # and here is to filter them out\n _idx = np.sum(mask, axis=(0, 1)) > 0\n mask = mask[:, :, _idx]\n class_ids = class_ids[_idx]\n # Bounding boxes. Note that some boxes might be all zeros\n # if the corresponding mask got cropped out.\n # bbox: [num_instances, (y1, x1, y2, x2)]\n bbox = utils.extract_bboxes(mask)\n\n # Active classes\n # Different datasets have different classes, so track the\n # classes supported in the dataset of this image.\n active_class_ids = np.zeros([dataset.num_classes], dtype=np.int32)\n source_class_ids = dataset.source_class_ids[dataset.image_info[image_id][\"source\"]]\n active_class_ids[source_class_ids] = 1\n\n # Resize masks to smaller size to reduce memory usage\n if use_mini_mask:\n mask = utils.minimize_mask(bbox, mask, config.MINI_MASK_SHAPE)\n\n # Image meta data\n image_meta = compose_image_meta(image_id, original_shape, image.shape,\n window, scale, active_class_ids)\n\n return image, image_meta, class_ids, bbox, mask\n\n\ndef build_detection_targets(rpn_rois, gt_class_ids, gt_boxes, gt_masks, config):\n \"\"\"Generate targets for training Stage 2 classifier and mask heads.\n This is not used in normal training. It's useful for debugging or to train\n the Mask RCNN heads without using the RPN head.\n\n Inputs:\n rpn_rois: [N, (y1, x1, y2, x2)] proposal boxes.\n gt_class_ids: [instance count] Integer class IDs\n gt_boxes: [instance count, (y1, x1, y2, x2)]\n gt_masks: [height, width, instance count] Ground truth masks. Can be full\n size or mini-masks.\n\n Returns:\n rois: [TRAIN_ROIS_PER_IMAGE, (y1, x1, y2, x2)]\n class_ids: [TRAIN_ROIS_PER_IMAGE]. Integer class IDs.\n bboxes: [TRAIN_ROIS_PER_IMAGE, NUM_CLASSES, (y, x, log(h), log(w))]. Class-specific\n bbox refinements.\n masks: [TRAIN_ROIS_PER_IMAGE, height, width, NUM_CLASSES). Class specific masks cropped\n to bbox boundaries and resized to neural network output size.\n \"\"\"\n assert rpn_rois.shape[0] > 0\n assert gt_class_ids.dtype == np.int32, \"Expected int but got {}\".format(\n gt_class_ids.dtype)\n assert gt_boxes.dtype == np.int32, \"Expected int but got {}\".format(\n gt_boxes.dtype)\n assert gt_masks.dtype == np.bool_, \"Expected bool but got {}\".format(\n gt_masks.dtype)\n\n # It's common to add GT Boxes to ROIs but we don't do that here because\n # according to XinLei Chen's paper, it doesn't help.\n\n # Trim empty padding in gt_boxes and gt_masks parts\n instance_ids = np.where(gt_class_ids > 0)[0]\n assert instance_ids.shape[0] > 0, \"Image must contain instances.\"\n gt_class_ids = gt_class_ids[instance_ids]\n gt_boxes = gt_boxes[instance_ids]\n gt_masks = gt_masks[:, :, instance_ids]\n\n # Compute areas of ROIs and ground truth boxes.\n rpn_roi_area = (rpn_rois[:, 2] - rpn_rois[:, 0]) * \\\n (rpn_rois[:, 3] - rpn_rois[:, 1])\n gt_box_area = (gt_boxes[:, 2] - gt_boxes[:, 0]) * \\\n (gt_boxes[:, 3] - gt_boxes[:, 1])\n\n # Compute overlaps [rpn_rois, gt_boxes]\n overlaps = np.zeros((rpn_rois.shape[0], gt_boxes.shape[0]))\n for i in range(overlaps.shape[1]):\n gt = gt_boxes[i]\n overlaps[:, i] = utils.compute_iou(\n gt, rpn_rois, gt_box_area[i], rpn_roi_area)\n\n # Assign ROIs to GT boxes\n rpn_roi_iou_argmax = np.argmax(overlaps, axis=1)\n rpn_roi_iou_max = overlaps[np.arange(\n overlaps.shape[0]), rpn_roi_iou_argmax]\n # GT box assigned to each ROI\n rpn_roi_gt_boxes = gt_boxes[rpn_roi_iou_argmax]\n rpn_roi_gt_class_ids = gt_class_ids[rpn_roi_iou_argmax]\n\n # Positive ROIs are those with >= 0.5 IoU with a GT box.\n fg_ids = np.where(rpn_roi_iou_max > 0.5)[0]\n\n # Negative ROIs are those with max IoU 0.1-0.5 (hard example mining)\n # TODO: To hard example mine or not to hard example mine, that's the question\n # bg_ids = np.where((rpn_roi_iou_max >= 0.1) & (rpn_roi_iou_max < 0.5))[0]\n bg_ids = np.where(rpn_roi_iou_max < 0.5)[0]\n\n # Subsample ROIs. Aim for 33% foreground.\n # FG\n fg_roi_count = int(config.TRAIN_ROIS_PER_IMAGE * config.ROI_POSITIVE_RATIO)\n if fg_ids.shape[0] > fg_roi_count:\n keep_fg_ids = np.random.choice(fg_ids, fg_roi_count, replace=False)\n else:\n keep_fg_ids = fg_ids\n # BG\n remaining = config.TRAIN_ROIS_PER_IMAGE - keep_fg_ids.shape[0]\n if bg_ids.shape[0] > remaining:\n keep_bg_ids = np.random.choice(bg_ids, remaining, replace=False)\n else:\n keep_bg_ids = bg_ids\n # Combine indices of ROIs to keep\n keep = np.concatenate([keep_fg_ids, keep_bg_ids])\n # Need more?\n remaining = config.TRAIN_ROIS_PER_IMAGE - keep.shape[0]\n if remaining > 0:\n # Looks like we don't have enough samples to maintain the desired\n # balance. Reduce requirements and fill in the rest. This is\n # likely different from the Mask RCNN paper.\n\n # There is a small chance we have neither fg nor bg samples.\n if keep.shape[0] == 0:\n # Pick bg regions with easier IoU threshold\n bg_ids = np.where(rpn_roi_iou_max < 0.5)[0]\n assert bg_ids.shape[0] >= remaining\n keep_bg_ids = np.random.choice(bg_ids, remaining, replace=False)\n assert keep_bg_ids.shape[0] == remaining\n keep = np.concatenate([keep, keep_bg_ids])\n else:\n # Fill the rest with repeated bg rois.\n keep_extra_ids = np.random.choice(\n keep_bg_ids, remaining, replace=True)\n keep = np.concatenate([keep, keep_extra_ids])\n assert keep.shape[0] == config.TRAIN_ROIS_PER_IMAGE, \\\n \"keep doesn't match ROI batch size {}, {}\".format(\n keep.shape[0], config.TRAIN_ROIS_PER_IMAGE)\n\n # Reset the gt boxes assigned to BG ROIs.\n rpn_roi_gt_boxes[keep_bg_ids, :] = 0\n rpn_roi_gt_class_ids[keep_bg_ids] = 0\n\n # For each kept ROI, assign a class_id, and for FG ROIs also add bbox refinement.\n rois = rpn_rois[keep]\n roi_gt_boxes = rpn_roi_gt_boxes[keep]\n roi_gt_class_ids = rpn_roi_gt_class_ids[keep]\n roi_gt_assignment = rpn_roi_iou_argmax[keep]\n\n # Class-aware bbox deltas. [y, x, log(h), log(w)]\n bboxes = np.zeros((config.TRAIN_ROIS_PER_IMAGE,\n config.NUM_CLASSES, 4), dtype=np.float32)\n pos_ids = np.where(roi_gt_class_ids > 0)[0]\n bboxes[pos_ids, roi_gt_class_ids[pos_ids]] = utils.box_refinement(\n rois[pos_ids], roi_gt_boxes[pos_ids, :4])\n # Normalize bbox refinements\n bboxes /= config.BBOX_STD_DEV\n\n # Generate class-specific target masks\n masks = np.zeros((config.TRAIN_ROIS_PER_IMAGE, config.MASK_SHAPE[0], config.MASK_SHAPE[1], config.NUM_CLASSES),\n dtype=np.float32)\n for i in pos_ids:\n class_id = roi_gt_class_ids[i]\n assert class_id > 0, \"class id must be greater than 0\"\n gt_id = roi_gt_assignment[i]\n class_mask = gt_masks[:, :, gt_id]\n\n if config.USE_MINI_MASK:\n # Create a mask placeholder, the size of the image\n placeholder = np.zeros(config.IMAGE_SHAPE[:2], dtype=bool)\n # GT box\n gt_y1, gt_x1, gt_y2, gt_x2 = gt_boxes[gt_id]\n gt_w = gt_x2 - gt_x1\n gt_h = gt_y2 - gt_y1\n # Resize mini mask to size of GT box\n placeholder[gt_y1:gt_y2, gt_x1:gt_x2] = \\\n np.round(utils.resize(class_mask, (gt_h, gt_w))).astype(bool)\n # Place the mini batch in the placeholder\n class_mask = placeholder\n\n # Pick part of the mask and resize it\n y1, x1, y2, x2 = rois[i].astype(np.int32)\n m = class_mask[y1:y2, x1:x2]\n mask = utils.resize(m, config.MASK_SHAPE)\n masks[i, :, :, class_id] = mask\n\n return rois, roi_gt_class_ids, bboxes, masks\n\n\ndef build_rpn_targets(image_shape, anchors, gt_class_ids, gt_boxes, config):\n \"\"\"Given the anchors and GT boxes, compute overlaps and identify positive\n anchors and deltas to refine them to match their corresponding GT boxes.\n\n anchors: [num_anchors, (y1, x1, y2, x2)]\n gt_class_ids: [num_gt_boxes] Integer class IDs.\n gt_boxes: [num_gt_boxes, (y1, x1, y2, x2)]\n\n Returns:\n rpn_match: [N] (int32) matches between anchors and GT boxes.\n 1 = positive anchor, -1 = negative anchor, 0 = neutral\n rpn_bbox: [N, (dy, dx, log(dh), log(dw))] Anchor bbox deltas.\n \"\"\"\n # RPN Match: 1 = positive anchor, -1 = negative anchor, 0 = neutral\n rpn_match = np.zeros([anchors.shape[0]], dtype=np.int32)\n # RPN bounding boxes: [max anchors per image, (dy, dx, log(dh), log(dw))]\n rpn_bbox = np.zeros((config.RPN_TRAIN_ANCHORS_PER_IMAGE, 4))\n\n # Handle COCO crowds\n # A crowd box in COCO is a bounding box around several instances. Exclude\n # them from training. A crowd box is given a negative class ID.\n crowd_ix = np.where(gt_class_ids < 0)[0]\n if crowd_ix.shape[0] > 0:\n # Filter out crowds from ground truth class IDs and boxes\n non_crowd_ix = np.where(gt_class_ids > 0)[0]\n crowd_boxes = gt_boxes[crowd_ix]\n gt_class_ids = gt_class_ids[non_crowd_ix]\n gt_boxes = gt_boxes[non_crowd_ix]\n # Compute overlaps with crowd boxes [anchors, crowds]\n crowd_overlaps = utils.compute_overlaps(anchors, crowd_boxes)\n crowd_iou_max = np.amax(crowd_overlaps, axis=1)\n no_crowd_bool = (crowd_iou_max < 0.001)\n else:\n # All anchors don't intersect a crowd\n no_crowd_bool = np.ones([anchors.shape[0]], dtype=bool)\n\n # Compute overlaps [num_anchors, num_gt_boxes]\n overlaps = utils.compute_overlaps(anchors, gt_boxes)\n\n # Match anchors to GT Boxes\n # If an anchor overlaps a GT box with IoU >= 0.7 then it's positive.\n # If an anchor overlaps a GT box with IoU < 0.3 then it's negative.\n # Neutral anchors are those that don't match the conditions above,\n # and they don't influence the loss function.\n # However, don't keep any GT box unmatched (rare, but happens). Instead,\n # match it to the closest anchor (even if its max IoU is < 0.3).\n #\n # 1. Set negative anchors first. They get overwritten below if a GT box is\n # matched to them. Skip boxes in crowd areas.\n anchor_iou_argmax = np.argmax(overlaps, axis=1)\n anchor_iou_max = overlaps[np.arange(overlaps.shape[0]), anchor_iou_argmax]\n rpn_match[(anchor_iou_max < 0.3) & (no_crowd_bool)] = -1\n # 2. Set an anchor for each GT box (regardless of IoU value).\n # If multiple anchors have the same IoU match all of them\n gt_iou_argmax = np.argwhere(overlaps == np.max(overlaps, axis=0))[:,0]\n rpn_match[gt_iou_argmax] = 1\n # 3. Set anchors with high overlap as positive.\n rpn_match[anchor_iou_max >= 0.7] = 1\n\n # Subsample to balance positive and negative anchors\n # Don't let positives be more than half the anchors\n ids = np.where(rpn_match == 1)[0]\n extra = len(ids) - (config.RPN_TRAIN_ANCHORS_PER_IMAGE // 2)\n if extra > 0:\n # Reset the extra ones to neutral\n ids = np.random.choice(ids, extra, replace=False)\n rpn_match[ids] = 0\n # Same for negative proposals\n ids = np.where(rpn_match == -1)[0]\n extra = len(ids) - (config.RPN_TRAIN_ANCHORS_PER_IMAGE -\n np.sum(rpn_match == 1))\n if extra > 0:\n # Rest the extra ones to neutral\n ids = np.random.choice(ids, extra, replace=False)\n rpn_match[ids] = 0\n\n # For positive anchors, compute shift and scale needed to transform them\n # to match the corresponding GT boxes.\n ids = np.where(rpn_match == 1)[0]\n ix = 0 # index into rpn_bbox\n # TODO: use box_refinement() rather than duplicating the code here\n for i, a in zip(ids, anchors[ids]):\n # Closest gt box (it might have IoU < 0.7)\n gt = gt_boxes[anchor_iou_argmax[i]]\n\n # Convert coordinates to center plus width/height.\n # GT Box\n gt_h = gt[2] - gt[0]\n gt_w = gt[3] - gt[1]\n gt_center_y = gt[0] + 0.5 * gt_h\n gt_center_x = gt[1] + 0.5 * gt_w\n # Anchor\n a_h = a[2] - a[0]\n a_w = a[3] - a[1]\n a_center_y = a[0] + 0.5 * a_h\n a_center_x = a[1] + 0.5 * a_w\n\n # Compute the bbox refinement that the RPN should predict.\n rpn_bbox[ix] = [\n (gt_center_y - a_center_y) / a_h,\n (gt_center_x - a_center_x) / a_w,\n np.log(gt_h / a_h),\n np.log(gt_w / a_w),\n ]\n # Normalize\n rpn_bbox[ix] /= config.RPN_BBOX_STD_DEV\n ix += 1\n\n return rpn_match, rpn_bbox\n\n\ndef generate_random_rois(image_shape, count, gt_class_ids, gt_boxes):\n \"\"\"Generates ROI proposals similar to what a region proposal network\n would generate.\n\n image_shape: [Height, Width, Depth]\n count: Number of ROIs to generate\n gt_class_ids: [N] Integer ground truth class IDs\n gt_boxes: [N, (y1, x1, y2, x2)] Ground truth boxes in pixels.\n\n Returns: [count, (y1, x1, y2, x2)] ROI boxes in pixels.\n \"\"\"\n # placeholder\n rois = np.zeros((count, 4), dtype=np.int32)\n\n # Generate random ROIs around GT boxes (90% of count)\n rois_per_box = int(0.9 * count / gt_boxes.shape[0])\n for i in range(gt_boxes.shape[0]):\n gt_y1, gt_x1, gt_y2, gt_x2 = gt_boxes[i]\n h = gt_y2 - gt_y1\n w = gt_x2 - gt_x1\n # random boundaries\n r_y1 = max(gt_y1 - h, 0)\n r_y2 = min(gt_y2 + h, image_shape[0])\n r_x1 = max(gt_x1 - w, 0)\n r_x2 = min(gt_x2 + w, image_shape[1])\n\n # To avoid generating boxes with zero area, we generate double what\n # we need and filter out the extra. If we get fewer valid boxes\n # than we need, we loop and try again.\n while True:\n y1y2 = np.random.randint(r_y1, r_y2, (rois_per_box * 2, 2))\n x1x2 = np.random.randint(r_x1, r_x2, (rois_per_box * 2, 2))\n # Filter out zero area boxes\n threshold = 1\n y1y2 = y1y2[np.abs(y1y2[:, 0] - y1y2[:, 1]) >=\n threshold][:rois_per_box]\n x1x2 = x1x2[np.abs(x1x2[:, 0] - x1x2[:, 1]) >=\n threshold][:rois_per_box]\n if y1y2.shape[0] == rois_per_box and x1x2.shape[0] == rois_per_box:\n break\n\n # Sort on axis 1 to ensure x1 <= x2 and y1 <= y2 and then reshape\n # into x1, y1, x2, y2 order\n x1, x2 = np.split(np.sort(x1x2, axis=1), 2, axis=1)\n y1, y2 = np.split(np.sort(y1y2, axis=1), 2, axis=1)\n box_rois = np.hstack([y1, x1, y2, x2])\n rois[rois_per_box * i:rois_per_box * (i + 1)] = box_rois\n\n # Generate random ROIs anywhere in the image (10% of count)\n remaining_count = count - (rois_per_box * gt_boxes.shape[0])\n # To avoid generating boxes with zero area, we generate double what\n # we need and filter out the extra. If we get fewer valid boxes\n # than we need, we loop and try again.\n while True:\n y1y2 = np.random.randint(0, image_shape[0], (remaining_count * 2, 2))\n x1x2 = np.random.randint(0, image_shape[1], (remaining_count * 2, 2))\n # Filter out zero area boxes\n threshold = 1\n y1y2 = y1y2[np.abs(y1y2[:, 0] - y1y2[:, 1]) >=\n threshold][:remaining_count]\n x1x2 = x1x2[np.abs(x1x2[:, 0] - x1x2[:, 1]) >=\n threshold][:remaining_count]\n if y1y2.shape[0] == remaining_count and x1x2.shape[0] == remaining_count:\n break\n\n # Sort on axis 1 to ensure x1 <= x2 and y1 <= y2 and then reshape\n # into x1, y1, x2, y2 order\n x1, x2 = np.split(np.sort(x1x2, axis=1), 2, axis=1)\n y1, y2 = np.split(np.sort(y1y2, axis=1), 2, axis=1)\n global_rois = np.hstack([y1, x1, y2, x2])\n rois[-remaining_count:] = global_rois\n return rois\n\n\ndef data_generator(dataset, config, shuffle=True, augment=False, augmentation=None,\n random_rois=0, batch_size=1, detection_targets=False,\n no_augmentation_sources=None):\n \"\"\"A generator that returns images and corresponding target class ids,\n bounding box deltas, and masks.\n\n dataset: The Dataset object to pick data from\n config: The model config object\n shuffle: If True, shuffles the samples before every epoch\n augment: (deprecated. Use augmentation instead). If true, apply random\n image augmentation. Currently, only horizontal flipping is offered.\n augmentation: Optional. An imgaug (https://github.com/aleju/imgaug) augmentation.\n For example, passing imgaug.augmenters.Fliplr(0.5) flips images\n right/left 50% of the time.\n random_rois: If > 0 then generate proposals to be used to train the\n network classifier and mask heads. Useful if training\n the Mask RCNN part without the RPN.\n batch_size: How many images to return in each call\n detection_targets: If True, generate detection targets (class IDs, bbox\n deltas, and masks). Typically for debugging or visualizations because\n in trainig detection targets are generated by DetectionTargetLayer.\n no_augmentation_sources: Optional. List of sources to exclude for\n augmentation. A source is string that identifies a dataset and is\n defined in the Dataset class.\n\n Returns a Python generator. Upon calling next() on it, the\n generator returns two lists, inputs and outputs. The contents\n of the lists differs depending on the received arguments:\n inputs list:\n - images: [batch, H, W, C]\n - image_meta: [batch, (meta data)] Image details. See compose_image_meta()\n - rpn_match: [batch, N] Integer (1=positive anchor, -1=negative, 0=neutral)\n - rpn_bbox: [batch, N, (dy, dx, log(dh), log(dw))] Anchor bbox deltas.\n - gt_class_ids: [batch, MAX_GT_INSTANCES] Integer class IDs\n - gt_boxes: [batch, MAX_GT_INSTANCES, (y1, x1, y2, x2)]\n - gt_masks: [batch, height, width, MAX_GT_INSTANCES]. The height and width\n are those of the image unless use_mini_mask is True, in which\n case they are defined in MINI_MASK_SHAPE.\n\n outputs list: Usually empty in regular training. But if detection_targets\n is True then the outputs list contains target class_ids, bbox deltas,\n and masks.\n \"\"\"\n b = 0 # batch item index\n image_index = -1\n image_ids = np.copy(dataset.image_ids)\n error_count = 0\n no_augmentation_sources = no_augmentation_sources or []\n\n # Anchors\n # [anchor_count, (y1, x1, y2, x2)]\n backbone_shapes = compute_backbone_shapes(config, config.IMAGE_SHAPE)\n anchors = utils.generate_pyramid_anchors(config.RPN_ANCHOR_SCALES,\n config.RPN_ANCHOR_RATIOS,\n backbone_shapes,\n config.BACKBONE_STRIDES,\n config.RPN_ANCHOR_STRIDE)\n\n # Keras requires a generator to run indefinitely.\n while True:\n try:\n # Increment index to pick next image. Shuffle if at the start of an epoch.\n image_index = (image_index + 1) % len(image_ids)\n if shuffle and image_index == 0:\n np.random.shuffle(image_ids)\n\n # Get GT bounding boxes and masks for image.\n image_id = image_ids[image_index]\n\n # If the image source is not to be augmented pass None as augmentation\n if dataset.image_info[image_id]['source'] in no_augmentation_sources:\n image, image_meta, gt_class_ids, gt_boxes, gt_masks = \\\n load_image_gt(dataset, config, image_id, augment=augment,\n augmentation=None,\n use_mini_mask=config.USE_MINI_MASK)\n else:\n image, image_meta, gt_class_ids, gt_boxes, gt_masks = \\\n load_image_gt(dataset, config, image_id, augment=augment,\n augmentation=augmentation,\n use_mini_mask=config.USE_MINI_MASK)\n\n # Skip images that have no instances. This can happen in cases\n # where we train on a subset of classes and the image doesn't\n # have any of the classes we care about.\n if not np.any(gt_class_ids > 0):\n continue\n\n # RPN Targets\n rpn_match, rpn_bbox = build_rpn_targets(image.shape, anchors,\n gt_class_ids, gt_boxes, config)\n\n # Mask R-CNN Targets\n if random_rois:\n rpn_rois = generate_random_rois(\n image.shape, random_rois, gt_class_ids, gt_boxes)\n if detection_targets:\n rois, mrcnn_class_ids, mrcnn_bbox, mrcnn_mask =\\\n build_detection_targets(\n rpn_rois, gt_class_ids, gt_boxes, gt_masks, config)\n\n # Init batch arrays\n if b == 0:\n batch_image_meta = np.zeros(\n (batch_size,) + image_meta.shape, dtype=image_meta.dtype)\n batch_rpn_match = np.zeros(\n [batch_size, anchors.shape[0], 1], dtype=rpn_match.dtype)\n batch_rpn_bbox = np.zeros(\n [batch_size, config.RPN_TRAIN_ANCHORS_PER_IMAGE, 4], dtype=rpn_bbox.dtype)\n batch_images = np.zeros(\n (batch_size,) + image.shape, dtype=np.float32)\n batch_gt_class_ids = np.zeros(\n (batch_size, config.MAX_GT_INSTANCES), dtype=np.int32)\n batch_gt_boxes = np.zeros(\n (batch_size, config.MAX_GT_INSTANCES, 4), dtype=np.int32)\n batch_gt_masks = np.zeros(\n (batch_size, gt_masks.shape[0], gt_masks.shape[1],\n config.MAX_GT_INSTANCES), dtype=gt_masks.dtype)\n if random_rois:\n batch_rpn_rois = np.zeros(\n (batch_size, rpn_rois.shape[0], 4), dtype=rpn_rois.dtype)\n if detection_targets:\n batch_rois = np.zeros(\n (batch_size,) + rois.shape, dtype=rois.dtype)\n batch_mrcnn_class_ids = np.zeros(\n (batch_size,) + mrcnn_class_ids.shape, dtype=mrcnn_class_ids.dtype)\n batch_mrcnn_bbox = np.zeros(\n (batch_size,) + mrcnn_bbox.shape, dtype=mrcnn_bbox.dtype)\n batch_mrcnn_mask = np.zeros(\n (batch_size,) + mrcnn_mask.shape, dtype=mrcnn_mask.dtype)\n\n # If more instances than fits in the array, sub-sample from them.\n if gt_boxes.shape[0] > config.MAX_GT_INSTANCES:\n ids = np.random.choice(\n np.arange(gt_boxes.shape[0]), config.MAX_GT_INSTANCES, replace=False)\n gt_class_ids = gt_class_ids[ids]\n gt_boxes = gt_boxes[ids]\n gt_masks = gt_masks[:, :, ids]\n\n # Add to batch\n batch_image_meta[b] = image_meta\n batch_rpn_match[b] = rpn_match[:, np.newaxis]\n batch_rpn_bbox[b] = rpn_bbox\n batch_images[b] = mold_image(image.astype(np.float32), config)\n batch_gt_class_ids[b, :gt_class_ids.shape[0]] = gt_class_ids\n batch_gt_boxes[b, :gt_boxes.shape[0]] = gt_boxes\n batch_gt_masks[b, :, :, :gt_masks.shape[-1]] = gt_masks\n if random_rois:\n batch_rpn_rois[b] = rpn_rois\n if detection_targets:\n batch_rois[b] = rois\n batch_mrcnn_class_ids[b] = mrcnn_class_ids\n batch_mrcnn_bbox[b] = mrcnn_bbox\n batch_mrcnn_mask[b] = mrcnn_mask\n b += 1\n\n # Batch full?\n if b >= batch_size:\n inputs = [batch_images, batch_image_meta, batch_rpn_match, batch_rpn_bbox,\n batch_gt_class_ids, batch_gt_boxes, batch_gt_masks]\n outputs = []\n\n if random_rois:\n inputs.extend([batch_rpn_rois])\n if detection_targets:\n inputs.extend([batch_rois])\n # Keras requires that output and targets have the same number of dimensions\n batch_mrcnn_class_ids = np.expand_dims(\n batch_mrcnn_class_ids, -1)\n outputs.extend(\n [batch_mrcnn_class_ids, batch_mrcnn_bbox, batch_mrcnn_mask])\n\n yield inputs, outputs\n\n # start a new batch\n b = 0\n except (GeneratorExit, KeyboardInterrupt):\n raise\n except:\n # Log it and skip the image\n logging.exception(\"Error processing image {}\".format(\n dataset.image_info[image_id]))\n error_count += 1\n if error_count > 5:\n raise\n\n\n############################################################\n# MaskRCNN Class\n############################################################\n\nclass MaskRCNN():\n \"\"\"Encapsulates the Mask RCNN model functionality.\n\n The actual Keras model is in the keras_model property.\n \"\"\"\n\n def __init__(self, mode, config, model_dir):\n \"\"\"\n mode: Either \"training\" or \"inference\"\n config: A Sub-class of the Config class\n model_dir: Directory to save training logs and trained weights\n \"\"\"\n assert mode in ['training', 'inference']\n self.mode = mode\n self.config = config\n self.model_dir = model_dir\n self.set_log_dir()\n self.keras_model = self.build(mode=mode, config=config)\n\n def build(self, mode, config):\n \"\"\"Build Mask R-CNN architecture.\n input_shape: The shape of the input image.\n mode: Either \"training\" or \"inference\". The inputs and\n outputs of the model differ accordingly.\n \"\"\"\n assert mode in ['training', 'inference']\n\n # Image size must be dividable by 2 multiple times\n h, w = config.IMAGE_SHAPE[:2]\n if h / 2**6 != int(h / 2**6) or w / 2**6 != int(w / 2**6):\n raise Exception(\"Image size must be dividable by 2 at least 6 times \"\n \"to avoid fractions when downscaling and upscaling.\"\n \"For example, use 256, 320, 384, 448, 512, ... etc. \")\n\n # Inputs\n input_image = KL.Input(\n shape=[None, None, config.IMAGE_SHAPE[2]], name=\"input_image\")\n input_image_meta = KL.Input(shape=[config.IMAGE_META_SIZE],\n name=\"input_image_meta\")\n if mode == \"training\":\n # RPN GT\n input_rpn_match = KL.Input(\n shape=[None, 1], name=\"input_rpn_match\", dtype=tf.int32)\n input_rpn_bbox = KL.Input(\n shape=[None, 4], name=\"input_rpn_bbox\", dtype=tf.float32)\n\n # Detection GT (class IDs, bounding boxes, and masks)\n # 1. GT Class IDs (zero padded)\n input_gt_class_ids = KL.Input(\n shape=[None], name=\"input_gt_class_ids\", dtype=tf.int32)\n # 2. GT Boxes in pixels (zero padded)\n # [batch, MAX_GT_INSTANCES, (y1, x1, y2, x2)] in image coordinates\n input_gt_boxes = KL.Input(\n shape=[None, 4], name=\"input_gt_boxes\", dtype=tf.float32)\n # Normalize coordinates\n gt_boxes = KL.Lambda(lambda x: norm_boxes_graph(\n x, K.shape(input_image)[1:3]))(input_gt_boxes)\n # 3. GT Masks (zero padded)\n # [batch, height, width, MAX_GT_INSTANCES]\n if config.USE_MINI_MASK:\n input_gt_masks = KL.Input(\n shape=[config.MINI_MASK_SHAPE[0],\n config.MINI_MASK_SHAPE[1], None],\n name=\"input_gt_masks\", dtype=bool)\n else:\n input_gt_masks = KL.Input(\n shape=[config.IMAGE_SHAPE[0], config.IMAGE_SHAPE[1], None],\n name=\"input_gt_masks\", dtype=bool)\n elif mode == \"inference\":\n # Anchors in normalized coordinates\n input_anchors = KL.Input(shape=[None, 4], name=\"input_anchors\")\n\n # Build the shared convolutional layers.\n # Bottom-up Layers\n # Returns a list of the last layers of each stage, 5 in total.\n # Don't create the thead (stage 5), so we pick the 4th item in the list.\n if callable(config.BACKBONE):\n _, C2, C3, C4, C5 = config.BACKBONE(input_image, stage5=True,\n train_bn=config.TRAIN_BN)\n else:\n _, C2, C3, C4, C5 = resnet_graph(input_image, config.BACKBONE,\n stage5=True, train_bn=config.TRAIN_BN)\n # Top-down Layers\n # TODO: add assert to varify feature map sizes match what's in config\n P5 = KL.Conv2D(config.TOP_DOWN_PYRAMID_SIZE, (1, 1), name='fpn_c5p5')(C5)\n P4 = KL.Add(name=\"fpn_p4add\")([\n KL.UpSampling2D(size=(2, 2), name=\"fpn_p5upsampled\")(P5),\n KL.Conv2D(config.TOP_DOWN_PYRAMID_SIZE, (1, 1), name='fpn_c4p4')(C4)])\n P3 = KL.Add(name=\"fpn_p3add\")([\n KL.UpSampling2D(size=(2, 2), name=\"fpn_p4upsampled\")(P4),\n KL.Conv2D(config.TOP_DOWN_PYRAMID_SIZE, (1, 1), name='fpn_c3p3')(C3)])\n P2 = KL.Add(name=\"fpn_p2add\")([\n KL.UpSampling2D(size=(2, 2), name=\"fpn_p3upsampled\")(P3),\n KL.Conv2D(config.TOP_DOWN_PYRAMID_SIZE, (1, 1), name='fpn_c2p2')(C2)])\n # Attach 3x3 conv to all P layers to get the final feature maps.\n P2 = KL.Conv2D(config.TOP_DOWN_PYRAMID_SIZE, (3, 3), padding=\"SAME\", name=\"fpn_p2\")(P2)\n P3 = KL.Conv2D(config.TOP_DOWN_PYRAMID_SIZE, (3, 3), padding=\"SAME\", name=\"fpn_p3\")(P3)\n P4 = KL.Conv2D(config.TOP_DOWN_PYRAMID_SIZE, (3, 3), padding=\"SAME\", name=\"fpn_p4\")(P4)\n P5 = KL.Conv2D(config.TOP_DOWN_PYRAMID_SIZE, (3, 3), padding=\"SAME\", name=\"fpn_p5\")(P5)\n # P6 is used for the 5th anchor scale in RPN. Generated by\n # subsampling from P5 with stride of 2.\n P6 = KL.MaxPooling2D(pool_size=(1, 1), strides=2, name=\"fpn_p6\")(P5)\n\n\n # Note that P6 is used in RPN, but not in the classifier heads.\n rpn_feature_maps = [P2, P3, P4, P5, P6]\n mrcnn_feature_maps = [P2, P3, P4, P5]\n\n # Anchors\n if mode == \"training\":\n anchors = self.get_anchors(config.IMAGE_SHAPE)\n # Duplicate across the batch dimension because Keras requires it\n # TODO: can this be optimized to avoid duplicating the anchors?\n anchors = np.broadcast_to(anchors, (config.BATCH_SIZE,) + anchors.shape)\n # A hack to get around Keras's bad support for constants\n anchors = KL.Lambda(lambda x: tf.Variable(anchors), name=\"anchors\")(input_image)\n else:\n anchors = input_anchors\n\n # RPN Model\n rpn = build_rpn_model(config.RPN_ANCHOR_STRIDE,\n len(config.RPN_ANCHOR_RATIOS), config.TOP_DOWN_PYRAMID_SIZE)\n # Loop through pyramid layers\n layer_outputs = [] # list of lists\n for p in rpn_feature_maps:\n layer_outputs.append(rpn([p]))\n # Concatenate layer outputs\n # Convert from list of lists of level outputs to list of lists\n # of outputs across levels.\n # e.g. [[a1, b1, c1], [a2, b2, c2]] => [[a1, a2], [b1, b2], [c1, c2]]\n output_names = [\"rpn_class_logits\", \"rpn_class\", \"rpn_bbox\"]\n outputs = list(zip(*layer_outputs))\n outputs = [KL.Concatenate(axis=1, name=n)(list(o))\n for o, n in zip(outputs, output_names)]\n\n rpn_class_logits, rpn_class, rpn_bbox = outputs\n\n # Generate proposals\n # Proposals are [batch, N, (y1, x1, y2, x2)] in normalized coordinates\n # and zero padded.\n proposal_count = config.POST_NMS_ROIS_TRAINING if mode == \"training\"\\\n else config.POST_NMS_ROIS_INFERENCE\n rpn_rois = ProposalLayer(\n proposal_count=proposal_count,\n nms_threshold=config.RPN_NMS_THRESHOLD,\n name=\"ROI\",\n config=config)([rpn_class, rpn_bbox, anchors])\n\n if mode == \"training\":\n # Class ID mask to mark class IDs supported by the dataset the image\n # came from.\n active_class_ids = KL.Lambda(\n lambda x: parse_image_meta_graph(x)[\"active_class_ids\"]\n )(input_image_meta)\n\n if not config.USE_RPN_ROIS:\n # Ignore predicted ROIs and use ROIs provided as an input.\n input_rois = KL.Input(shape=[config.POST_NMS_ROIS_TRAINING, 4],\n name=\"input_roi\", dtype=np.int32)\n # Normalize coordinates\n target_rois = KL.Lambda(lambda x: norm_boxes_graph(\n x, K.shape(input_image)[1:3]))(input_rois)\n else:\n target_rois = rpn_rois\n\n # Generate detection targets\n # Subsamples proposals and generates target outputs for training\n # Note that proposal class IDs, gt_boxes, and gt_masks are zero\n # padded. Equally, returned rois and targets are zero padded.\n rois, target_class_ids, target_bbox, target_mask =\\\n DetectionTargetLayer(config, name=\"proposal_targets\")([\n target_rois, input_gt_class_ids, gt_boxes, input_gt_masks])\n\n # Network Heads\n # TODO: verify that this handles zero padded ROIs\n mrcnn_class_logits, mrcnn_class, mrcnn_bbox =\\\n fpn_classifier_graph(rois, mrcnn_feature_maps, input_image_meta,\n config.POOL_SIZE, config.NUM_CLASSES,\n train_bn=config.TRAIN_BN,\n fc_layers_size=config.FPN_CLASSIF_FC_LAYERS_SIZE)\n\n mrcnn_mask = build_fpn_mask_graph(rois, mrcnn_feature_maps,\n input_image_meta,\n config.MASK_POOL_SIZE,\n config.NUM_CLASSES,\n train_bn=config.TRAIN_BN)\n\n # TODO: clean up (use tf.identify if necessary)\n output_rois = KL.Lambda(lambda x: x * 1, name=\"output_rois\")(rois)\n\n # Losses\n rpn_class_loss = KL.Lambda(lambda x: rpn_class_loss_graph(*x), name=\"rpn_class_loss\")(\n [input_rpn_match, rpn_class_logits])\n rpn_bbox_loss = KL.Lambda(lambda x: rpn_bbox_loss_graph(config, *x), name=\"rpn_bbox_loss\")(\n [input_rpn_bbox, input_rpn_match, rpn_bbox])\n class_loss = KL.Lambda(lambda x: mrcnn_class_loss_graph(*x), name=\"mrcnn_class_loss\")(\n [target_class_ids, mrcnn_class_logits, active_class_ids])\n bbox_loss = KL.Lambda(lambda x: mrcnn_bbox_loss_graph(*x), name=\"mrcnn_bbox_loss\")(\n [target_bbox, target_class_ids, mrcnn_bbox])\n mask_loss = KL.Lambda(lambda x: mrcnn_mask_loss_graph(*x), name=\"mrcnn_mask_loss\")(\n [target_mask, target_class_ids, mrcnn_mask])\n\n # Model\n inputs = [input_image, input_image_meta,\n input_rpn_match, input_rpn_bbox, input_gt_class_ids, input_gt_boxes, input_gt_masks]\n if not config.USE_RPN_ROIS:\n inputs.append(input_rois)\n outputs = [rpn_class_logits, rpn_class, rpn_bbox,\n mrcnn_class_logits, mrcnn_class, mrcnn_bbox, mrcnn_mask,\n rpn_rois, output_rois,\n rpn_class_loss, rpn_bbox_loss, class_loss, bbox_loss, mask_loss]\n model = KM.Model(inputs, outputs, name='mask_rcnn')\n else:\n # Network Heads\n # Proposal classifier and BBox regressor heads\n mrcnn_class_logits, mrcnn_class, mrcnn_bbox =\\\n fpn_classifier_graph(rpn_rois, mrcnn_feature_maps, input_image_meta,\n config.POOL_SIZE, config.NUM_CLASSES,\n train_bn=config.TRAIN_BN,\n fc_layers_size=config.FPN_CLASSIF_FC_LAYERS_SIZE)\n\n # Detections\n # output is [batch, num_detections, (y1, x1, y2, x2, class_id, score)] in\n # normalized coordinates\n detections = DetectionLayer(config, name=\"mrcnn_detection\")(\n [rpn_rois, mrcnn_class, mrcnn_bbox, input_image_meta])\n\n # Create masks for detections\n detection_boxes = KL.Lambda(lambda x: x[..., :4])(detections)\n mrcnn_mask = build_fpn_mask_graph(detection_boxes, mrcnn_feature_maps,\n input_image_meta,\n config.MASK_POOL_SIZE,\n config.NUM_CLASSES,\n train_bn=config.TRAIN_BN)\n\n model = KM.Model([input_image, input_image_meta, input_anchors],\n [detections, mrcnn_class, mrcnn_bbox,\n mrcnn_mask, rpn_rois, rpn_class, rpn_bbox],\n name='mask_rcnn')\n\n # Add multi-GPU support.\n if config.GPU_COUNT > 1:\n from mrcnn.parallel_model import ParallelModel\n model = ParallelModel(model, config.GPU_COUNT)\n\n return model\n\n def find_last(self):\n \"\"\"Finds the last checkpoint file of the last trained model in the\n model directory.\n Returns:\n The path of the last checkpoint file\n \"\"\"\n # Get directory names. Each directory corresponds to a model\n dir_names = next(os.walk(self.model_dir))[1]\n key = self.config.NAME.lower()\n dir_names = filter(lambda f: f.startswith(key), dir_names)\n dir_names = sorted(dir_names)\n if not dir_names:\n import errno\n raise FileNotFoundError(\n errno.ENOENT,\n \"Could not find model directory under {}\".format(self.model_dir))\n # Pick last directory\n dir_name = os.path.join(self.model_dir, dir_names[-1])\n # Find the last checkpoint\n checkpoints = next(os.walk(dir_name))[2]\n checkpoints = filter(lambda f: f.startswith(\"mask_rcnn\"), checkpoints)\n checkpoints = sorted(checkpoints)\n if not checkpoints:\n import errno\n raise FileNotFoundError(\n errno.ENOENT, \"Could not find weight files in {}\".format(dir_name))\n checkpoint = os.path.join(dir_name, checkpoints[-1])\n return checkpoint\n\n def load_weights(self, filepath, by_name=False, exclude=None):\n \"\"\"Modified version of the corresponding Keras function with\n the addition of multi-GPU support and the ability to exclude\n some layers from loading.\n exclude: list of layer names to exclude\n \"\"\"\n import h5py\n # Conditional import to support versions of Keras before 2.2\n # TODO: remove in about 6 months (end of 2018)\n try:\n from keras.engine import saving\n except ImportError:\n # Keras before 2.2 used the 'topology' namespace.\n from keras.engine import topology as saving\n\n if exclude:\n by_name = True\n\n if h5py is None:\n raise ImportError('`load_weights` requires h5py.')\n f = h5py.File(filepath, mode='r')\n if 'layer_names' not in f.attrs and 'model_weights' in f:\n f = f['model_weights']\n\n # In multi-GPU training, we wrap the model. Get layers\n # of the inner model because they have the weights.\n keras_model = self.keras_model\n layers = keras_model.inner_model.layers if hasattr(keras_model, \"inner_model\")\\\n else keras_model.layers\n\n # Exclude some layers\n if exclude:\n layers = filter(lambda l: l.name not in exclude, layers)\n\n if by_name:\n saving.load_weights_from_hdf5_group_by_name(f, layers)\n else:\n saving.load_weights_from_hdf5_group(f, layers)\n if hasattr(f, 'close'):\n f.close()\n\n # Update the log directory\n self.set_log_dir(filepath)\n\n def get_imagenet_weights(self):\n \"\"\"Downloads ImageNet trained weights from Keras.\n Returns path to weights file.\n \"\"\"\n from keras.utils.data_utils import get_file\n TF_WEIGHTS_PATH_NO_TOP = 'https://github.com/fchollet/deep-learning-models/'\\\n 'releases/download/v0.2/'\\\n 'resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5'\n weights_path = get_file('resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5',\n TF_WEIGHTS_PATH_NO_TOP,\n cache_subdir='models',\n md5_hash='a268eb855778b3df3c7506639542a6af')\n return weights_path\n\n def compile(self, learning_rate, momentum):\n \"\"\"Gets the model ready for training. Adds losses, regularization, and\n metrics. Then calls the Keras compile() function.\n \"\"\"\n # Optimizer object\n optimizer = keras.optimizers.SGD(\n lr=learning_rate, momentum=momentum,\n clipnorm=self.config.GRADIENT_CLIP_NORM)\n # Add Losses\n # First, clear previously set losses to avoid duplication\n self.keras_model._losses = []\n self.keras_model._per_input_losses = {}\n loss_names = [\n \"rpn_class_loss\", \"rpn_bbox_loss\",\n \"mrcnn_class_loss\", \"mrcnn_bbox_loss\", \"mrcnn_mask_loss\"]\n for name in loss_names:\n layer = self.keras_model.get_layer(name)\n if layer.output in self.keras_model.losses:\n continue\n loss = (\n tf.reduce_mean(layer.output, keepdims=True)\n * self.config.LOSS_WEIGHTS.get(name, 1.))\n self.keras_model.add_loss(loss)\n\n # Add L2 Regularization\n # Skip gamma and beta weights of batch normalization layers.\n reg_losses = [\n keras.regularizers.l2(self.config.WEIGHT_DECAY)(w) / tf.cast(tf.size(w), tf.float32)\n for w in self.keras_model.trainable_weights\n if 'gamma' not in w.name and 'beta' not in w.name]\n self.keras_model.add_loss(tf.add_n(reg_losses))\n\n # Compile\n self.keras_model.compile(\n optimizer=optimizer,\n loss=[None] * len(self.keras_model.outputs))\n\n # Add metrics for losses\n for name in loss_names:\n if name in self.keras_model.metrics_names:\n continue\n layer = self.keras_model.get_layer(name)\n self.keras_model.metrics_names.append(name)\n loss = (\n tf.reduce_mean(layer.output, keepdims=True)\n * self.config.LOSS_WEIGHTS.get(name, 1.))\n self.keras_model.metrics_tensors.append(loss)\n\n def set_trainable(self, layer_regex, keras_model=None, indent=0, verbose=1):\n \"\"\"Sets model layers as trainable if their names match\n the given regular expression.\n \"\"\"\n # Print message on the first call (but not on recursive calls)\n if verbose > 0 and keras_model is None:\n log(\"Selecting layers to train\")\n\n keras_model = keras_model or self.keras_model\n\n # In multi-GPU training, we wrap the model. Get layers\n # of the inner model because they have the weights.\n layers = keras_model.inner_model.layers if hasattr(keras_model, \"inner_model\")\\\n else keras_model.layers\n\n for layer in layers:\n # Is the layer a model?\n if layer.__class__.__name__ == 'Model':\n print(\"In model: \", layer.name)\n self.set_trainable(\n layer_regex, keras_model=layer, indent=indent + 4)\n continue\n\n if not layer.weights:\n continue\n # Is it trainable?\n trainable = bool(re.fullmatch(layer_regex, layer.name))\n # Update layer. If layer is a container, update inner layer.\n if layer.__class__.__name__ == 'TimeDistributed':\n layer.layer.trainable = trainable\n else:\n layer.trainable = trainable\n # Print trainable layer names\n if trainable and verbose > 0:\n log(\"{}{:20} ({})\".format(\" \" * indent, layer.name,\n layer.__class__.__name__))\n\n def set_log_dir(self, model_path=None):\n \"\"\"Sets the model log directory and epoch counter.\n\n model_path: If None, or a format different from what this code uses\n then set a new log directory and start epochs from 0. Otherwise,\n extract the log directory and the epoch counter from the file\n name.\n \"\"\"\n # Set date and epoch counter as if starting a new model\n self.epoch = 0\n now = datetime.datetime.now()\n\n # If we have a model path with date and epochs use them\n if model_path:\n # Continue from we left of. Get epoch and date from the file name\n # A sample model path might look like:\n # \\path\\to\\logs\\coco20171029T2315\\mask_rcnn_coco_0001.h5 (Windows)\n # /path/to/logs/coco20171029T2315/mask_rcnn_coco_0001.h5 (Linux)\n regex = r\".*[/\\\\][\\w-]+(\\d{4})(\\d{2})(\\d{2})T(\\d{2})(\\d{2})[/\\\\]mask\\_rcnn\\_[\\w-]+(\\d{4})\\.h5\"\n m = re.match(regex, model_path)\n if m:\n now = datetime.datetime(int(m.group(1)), int(m.group(2)), int(m.group(3)),\n int(m.group(4)), int(m.group(5)))\n # Epoch number in file is 1-based, and in Keras code it's 0-based.\n # So, adjust for that then increment by one to start from the next epoch\n self.epoch = int(m.group(6)) - 1 + 1\n print('Re-starting from epoch %d' % self.epoch)\n\n # Directory for training logs\n self.log_dir = os.path.join(self.model_dir, \"{}{:%Y%m%dT%H%M}\".format(\n self.config.NAME.lower(), now))\n\n # Path to save after each epoch. Include placeholders that get filled by Keras.\n self.checkpoint_path = os.path.join(self.log_dir, \"mask_rcnn_{}_*epoch*.h5\".format(\n self.config.NAME.lower()))\n self.checkpoint_path = self.checkpoint_path.replace(\n \"*epoch*\", \"{epoch:04d}\")\n\n def train(self, train_dataset, val_dataset, learning_rate, epochs, layers,\n augmentation=None, custom_callbacks=None, no_augmentation_sources=None):\n \"\"\"Train the model.\n train_dataset, val_dataset: Training and validation Dataset objects.\n learning_rate: The learning rate to train with\n epochs: Number of training epochs. Note that previous training epochs\n are considered to be done alreay, so this actually determines\n the epochs to train in total rather than in this particaular\n call.\n layers: Allows selecting wich layers to train. It can be:\n - A regular expression to match layer names to train\n - One of these predefined values:\n heads: The RPN, classifier and mask heads of the network\n all: All the layers\n 3+: Train Resnet stage 3 and up\n 4+: Train Resnet stage 4 and up\n 5+: Train Resnet stage 5 and up\n augmentation: Optional. An imgaug (https://github.com/aleju/imgaug)\n augmentation. For example, passing imgaug.augmenters.Fliplr(0.5)\n flips images right/left 50% of the time. You can pass complex\n augmentations as well. This augmentation applies 50% of the\n time, and when it does it flips images right/left half the time\n and adds a Gaussian blur with a random sigma in range 0 to 5.\n\n augmentation = imgaug.augmenters.Sometimes(0.5, [\n imgaug.augmenters.Fliplr(0.5),\n imgaug.augmenters.GaussianBlur(sigma=(0.0, 5.0))\n ])\n\t custom_callbacks: Optional. Add custom callbacks to be called\n\t with the keras fit_generator method. Must be list of type keras.callbacks.\n no_augmentation_sources: Optional. List of sources to exclude for\n augmentation. A source is string that identifies a dataset and is\n defined in the Dataset class.\n \"\"\"\n assert self.mode == \"training\", \"Create model in training mode.\"\n\n # Pre-defined layer regular expressions\n layer_regex = {\n # all layers but the backbone\n \"heads\": r\"(mrcnn\\_.*)|(rpn\\_.*)|(fpn\\_.*)\",\n # From a specific Resnet stage and up\n \"3+\": r\"(res3.*)|(bn3.*)|(res4.*)|(bn4.*)|(res5.*)|(bn5.*)|(mrcnn\\_.*)|(rpn\\_.*)|(fpn\\_.*)\",\n \"4+\": r\"(res4.*)|(bn4.*)|(res5.*)|(bn5.*)|(mrcnn\\_.*)|(rpn\\_.*)|(fpn\\_.*)\",\n \"5+\": r\"(res5.*)|(bn5.*)|(mrcnn\\_.*)|(rpn\\_.*)|(fpn\\_.*)\",\n # All layers\n \"all\": \".*\",\n }\n if layers in layer_regex.keys():\n layers = layer_regex[layers]\n\n # Data generators\n train_generator = data_generator(train_dataset, self.config, shuffle=True,\n augmentation=augmentation,\n batch_size=self.config.BATCH_SIZE,\n no_augmentation_sources=no_augmentation_sources)\n val_generator = data_generator(val_dataset, self.config, shuffle=True,\n batch_size=self.config.BATCH_SIZE)\n\n # Create log_dir if it does not exist\n if not os.path.exists(self.log_dir):\n os.makedirs(self.log_dir)\n\n # Callbacks\n callbacks = [\n keras.callbacks.TensorBoard(log_dir=self.log_dir,\n histogram_freq=0, write_graph=True, write_images=False),\n keras.callbacks.ModelCheckpoint(self.checkpoint_path,\n verbose=0, save_weights_only=True),\n ]\n\n # Add custom callbacks to the list\n if custom_callbacks:\n callbacks += custom_callbacks\n\n # Train\n log(\"\\nStarting at epoch {}. LR={}\\n\".format(self.epoch, learning_rate))\n log(\"Checkpoint Path: {}\".format(self.checkpoint_path))\n self.set_trainable(layers)\n self.compile(learning_rate, self.config.LEARNING_MOMENTUM)\n\n # Work-around for Windows: Keras fails on Windows when using\n # multiprocessing workers. See discussion here:\n # https://github.com/matterport/Mask_RCNN/issues/13#issuecomment-353124009\n if os.name is 'nt':\n workers = 0\n else:\n workers = multiprocessing.cpu_count()\n\n self.keras_model.fit_generator(\n train_generator,\n initial_epoch=self.epoch,\n epochs=epochs,\n steps_per_epoch=self.config.STEPS_PER_EPOCH,\n callbacks=callbacks,\n validation_data=val_generator,\n validation_steps=self.config.VALIDATION_STEPS,\n max_queue_size=100,\n workers=workers,\n use_multiprocessing=True,\n )\n self.epoch = max(self.epoch, epochs)\n\n def mold_inputs(self, images):\n \"\"\"Takes a list of images and modifies them to the format expected\n as an input to the neural network.\n images: List of image matrices [height,width,depth]. Images can have\n different sizes.\n\n Returns 3 Numpy matrices:\n molded_images: [N, h, w, 3]. Images resized and normalized.\n image_metas: [N, length of meta data]. Details about each image.\n windows: [N, (y1, x1, y2, x2)]. The portion of the image that has the\n original image (padding excluded).\n \"\"\"\n molded_images = []\n image_metas = []\n windows = []\n for image in images:\n # Resize image\n # TODO: move resizing to mold_image()\n molded_image, window, scale, padding, crop = utils.resize_image(\n image,\n min_dim=self.config.IMAGE_MIN_DIM,\n min_scale=self.config.IMAGE_MIN_SCALE,\n max_dim=self.config.IMAGE_MAX_DIM,\n mode=self.config.IMAGE_RESIZE_MODE)\n molded_image = mold_image(molded_image, self.config)\n # Build image_meta\n image_meta = compose_image_meta(\n 0, image.shape, molded_image.shape, window, scale,\n np.zeros([self.config.NUM_CLASSES], dtype=np.int32))\n # Append\n molded_images.append(molded_image)\n windows.append(window)\n image_metas.append(image_meta)\n # Pack into arrays\n molded_images = np.stack(molded_images)\n image_metas = np.stack(image_metas)\n windows = np.stack(windows)\n return molded_images, image_metas, windows\n\n def unmold_detections(self, detections, mrcnn_mask, original_image_shape,\n image_shape, window):\n \"\"\"Reformats the detections of one image from the format of the neural\n network output to a format suitable for use in the rest of the\n application.\n\n detections: [N, (y1, x1, y2, x2, class_id, score)] in normalized coordinates\n mrcnn_mask: [N, height, width, num_classes]\n original_image_shape: [H, W, C] Original image shape before resizing\n image_shape: [H, W, C] Shape of the image after resizing and padding\n window: [y1, x1, y2, x2] Pixel coordinates of box in the image where the real\n image is excluding the padding.\n\n Returns:\n boxes: [N, (y1, x1, y2, x2)] Bounding boxes in pixels\n class_ids: [N] Integer class IDs for each bounding box\n scores: [N] Float probability scores of the class_id\n masks: [height, width, num_instances] Instance masks\n \"\"\"\n # How many detections do we have?\n # Detections array is padded with zeros. Find the first class_id == 0.\n zero_ix = np.where(detections[:, 4] == 0)[0]\n N = zero_ix[0] if zero_ix.shape[0] > 0 else detections.shape[0]\n\n # Extract boxes, class_ids, scores, and class-specific masks\n boxes = detections[:N, :4]\n class_ids = detections[:N, 4].astype(np.int32)\n scores = detections[:N, 5]\n masks = mrcnn_mask[np.arange(N), :, :, class_ids]\n\n # Translate normalized coordinates in the resized image to pixel\n # coordinates in the original image before resizing\n window = utils.norm_boxes(window, image_shape[:2])\n wy1, wx1, wy2, wx2 = window\n shift = np.array([wy1, wx1, wy1, wx1])\n wh = wy2 - wy1 # window height\n ww = wx2 - wx1 # window width\n scale = np.array([wh, ww, wh, ww])\n # Convert boxes to normalized coordinates on the window\n boxes = np.divide(boxes - shift, scale)\n # Convert boxes to pixel coordinates on the original image\n boxes = utils.denorm_boxes(boxes, original_image_shape[:2])\n\n # Filter out detections with zero area. Happens in early training when\n # network weights are still random\n exclude_ix = np.where(\n (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1]) <= 0)[0]\n if exclude_ix.shape[0] > 0:\n boxes = np.delete(boxes, exclude_ix, axis=0)\n class_ids = np.delete(class_ids, exclude_ix, axis=0)\n scores = np.delete(scores, exclude_ix, axis=0)\n masks = np.delete(masks, exclude_ix, axis=0)\n N = class_ids.shape[0]\n\n # Resize masks to original image size and set boundary threshold.\n full_masks = []\n for i in range(N):\n # Convert neural network mask to full size mask\n full_mask = utils.unmold_mask(masks[i], boxes[i], original_image_shape)\n full_masks.append(full_mask)\n full_masks = np.stack(full_masks, axis=-1)\\\n if full_masks else np.empty(original_image_shape[:2] + (0,))\n\n return boxes, class_ids, scores, full_masks\n\n def detect(self, images, verbose=0):\n \"\"\"Runs the detection pipeline.\n\n images: List of images, potentially of different sizes.\n\n Returns a list of dicts, one dict per image. The dict contains:\n rois: [N, (y1, x1, y2, x2)] detection bounding boxes\n class_ids: [N] int class IDs\n scores: [N] float probability scores for the class IDs\n masks: [H, W, N] instance binary masks\n \"\"\"\n assert self.mode == \"inference\", \"Create model in inference mode.\"\n assert len(\n images) == self.config.BATCH_SIZE, \"len(images) must be equal to BATCH_SIZE\"\n\n if verbose:\n log(\"Processing {} images\".format(len(images)))\n for image in images:\n log(\"image\", image)\n\n # Mold inputs to format expected by the neural network\n molded_images, image_metas, windows = self.mold_inputs(images)\n\n # Validate image sizes\n # All images in a batch MUST be of the same size\n image_shape = molded_images[0].shape\n for g in molded_images[1:]:\n assert g.shape == image_shape,\\\n \"After resizing, all images must have the same size. Check IMAGE_RESIZE_MODE and image sizes.\"\n\n # Anchors\n anchors = self.get_anchors(image_shape)\n # Duplicate across the batch dimension because Keras requires it\n # TODO: can this be optimized to avoid duplicating the anchors?\n anchors = np.broadcast_to(anchors, (self.config.BATCH_SIZE,) + anchors.shape)\n\n if verbose:\n log(\"molded_images\", molded_images)\n log(\"image_metas\", image_metas)\n log(\"anchors\", anchors)\n # Run object detection\n detections, _, _, mrcnn_mask, _, _, _ =\\\n self.keras_model.predict([molded_images, image_metas, anchors], verbose=0)\n # Process detections\n results = []\n for i, image in enumerate(images):\n final_rois, final_class_ids, final_scores, final_masks =\\\n self.unmold_detections(detections[i], mrcnn_mask[i],\n image.shape, molded_images[i].shape,\n windows[i])\n results.append({\n \"rois\": final_rois,\n \"class_ids\": final_class_ids,\n \"scores\": final_scores,\n \"masks\": final_masks,\n })\n return results\n\n def detect_molded(self, molded_images, image_metas, verbose=0):\n \"\"\"Runs the detection pipeline, but expect inputs that are\n molded already. Used mostly for debugging and inspecting\n the model.\n\n molded_images: List of images loaded using load_image_gt()\n image_metas: image meta data, also returned by load_image_gt()\n\n Returns a list of dicts, one dict per image. The dict contains:\n rois: [N, (y1, x1, y2, x2)] detection bounding boxes\n class_ids: [N] int class IDs\n scores: [N] float probability scores for the class IDs\n masks: [H, W, N] instance binary masks\n \"\"\"\n assert self.mode == \"inference\", \"Create model in inference mode.\"\n assert len(molded_images) == self.config.BATCH_SIZE,\\\n \"Number of images must be equal to BATCH_SIZE\"\n\n if verbose:\n log(\"Processing {} images\".format(len(molded_images)))\n for image in molded_images:\n log(\"image\", image)\n\n # Validate image sizes\n # All images in a batch MUST be of the same size\n image_shape = molded_images[0].shape\n for g in molded_images[1:]:\n assert g.shape == image_shape, \"Images must have the same size\"\n\n # Anchors\n anchors = self.get_anchors(image_shape)\n # Duplicate across the batch dimension because Keras requires it\n # TODO: can this be optimized to avoid duplicating the anchors?\n anchors = np.broadcast_to(anchors, (self.config.BATCH_SIZE,) + anchors.shape)\n\n if verbose:\n log(\"molded_images\", molded_images)\n log(\"image_metas\", image_metas)\n log(\"anchors\", anchors)\n # Run object detection\n detections, _, _, mrcnn_mask, _, _, _ =\\\n self.keras_model.predict([molded_images, image_metas, anchors], verbose=0)\n # Process detections\n results = []\n for i, image in enumerate(molded_images):\n window = [0, 0, image.shape[0], image.shape[1]]\n final_rois, final_class_ids, final_scores, final_masks =\\\n self.unmold_detections(detections[i], mrcnn_mask[i],\n image.shape, molded_images[i].shape,\n window)\n results.append({\n \"rois\": final_rois,\n \"class_ids\": final_class_ids,\n \"scores\": final_scores,\n \"masks\": final_masks,\n })\n return results\n\n def get_anchors(self, image_shape):\n \"\"\"Returns anchor pyramid for the given image size.\"\"\"\n backbone_shapes = compute_backbone_shapes(self.config, image_shape)\n # Cache anchors and reuse if image shape is the same\n if not hasattr(self, \"_anchor_cache\"):\n self._anchor_cache = {}\n if not tuple(image_shape) in self._anchor_cache:\n # Generate Anchors\n a = utils.generate_pyramid_anchors(\n self.config.RPN_ANCHOR_SCALES,\n self.config.RPN_ANCHOR_RATIOS,\n backbone_shapes,\n self.config.BACKBONE_STRIDES,\n self.config.RPN_ANCHOR_STRIDE)\n # Keep a copy of the latest anchors in pixel coordinates because\n # it's used in inspect_model notebooks.\n # TODO: Remove this after the notebook are refactored to not use it\n self.anchors = a\n # Normalize coordinates\n self._anchor_cache[tuple(image_shape)] = utils.norm_boxes(a, image_shape[:2])\n return self._anchor_cache[tuple(image_shape)]\n\n def ancestor(self, tensor, name, checked=None):\n \"\"\"Finds the ancestor of a TF tensor in the computation graph.\n tensor: TensorFlow symbolic tensor.\n name: Name of ancestor tensor to find\n checked: For internal use. A list of tensors that were already\n searched to avoid loops in traversing the graph.\n \"\"\"\n checked = checked if checked is not None else []\n # Put a limit on how deep we go to avoid very long loops\n if len(checked) > 500:\n return None\n # Convert name to a regex and allow matching a number prefix\n # because Keras adds them automatically\n if isinstance(name, str):\n name = re.compile(name.replace(\"/\", r\"(\\_\\d+)*/\"))\n\n parents = tensor.op.inputs\n for p in parents:\n if p in checked:\n continue\n if bool(re.fullmatch(name, p.name)):\n return p\n checked.append(p)\n a = self.ancestor(p, name, checked)\n if a is not None:\n return a\n return None\n\n def find_trainable_layer(self, layer):\n \"\"\"If a layer is encapsulated by another layer, this function\n digs through the encapsulation and returns the layer that holds\n the weights.\n \"\"\"\n if layer.__class__.__name__ == 'TimeDistributed':\n return self.find_trainable_layer(layer.layer)\n return layer\n\n def get_trainable_layers(self):\n \"\"\"Returns a list of layers that have weights.\"\"\"\n layers = []\n # Loop through all layers\n for l in self.keras_model.layers:\n # If layer is a wrapper, find inner trainable layer\n l = self.find_trainable_layer(l)\n # Include layer if it has weights\n if l.get_weights():\n layers.append(l)\n return layers\n\n def run_graph(self, images, outputs, image_metas=None):\n \"\"\"Runs a sub-set of the computation graph that computes the given\n outputs.\n\n image_metas: If provided, the images are assumed to be already\n molded (i.e. resized, padded, and normalized)\n\n outputs: List of tuples (name, tensor) to compute. The tensors are\n symbolic TensorFlow tensors and the names are for easy tracking.\n\n Returns an ordered dict of results. Keys are the names received in the\n input and values are Numpy arrays.\n \"\"\"\n model = self.keras_model\n\n # Organize desired outputs into an ordered dict\n outputs = OrderedDict(outputs)\n for o in outputs.values():\n assert o is not None\n\n # Build a Keras function to run parts of the computation graph\n inputs = model.inputs\n if model.uses_learning_phase and not isinstance(K.learning_phase(), int):\n inputs += [K.learning_phase()]\n kf = K.function(model.inputs, list(outputs.values()))\n\n # Prepare inputs\n if image_metas is None:\n molded_images, image_metas, _ = self.mold_inputs(images)\n else:\n molded_images = images\n image_shape = molded_images[0].shape\n # Anchors\n anchors = self.get_anchors(image_shape)\n # Duplicate across the batch dimension because Keras requires it\n # TODO: can this be optimized to avoid duplicating the anchors?\n anchors = np.broadcast_to(anchors, (self.config.BATCH_SIZE,) + anchors.shape)\n model_in = [molded_images, image_metas, anchors]\n\n # Run inference\n if model.uses_learning_phase and not isinstance(K.learning_phase(), int):\n model_in.append(0.)\n outputs_np = kf(model_in)\n\n # Pack the generated Numpy arrays into a a dict and log the results.\n outputs_np = OrderedDict([(k, v)\n for k, v in zip(outputs.keys(), outputs_np)])\n for k, v in outputs_np.items():\n log(k, v)\n return outputs_np\n\n\n############################################################\n# Data Formatting\n############################################################\n\ndef compose_image_meta(image_id, original_image_shape, image_shape,\n window, scale, active_class_ids):\n \"\"\"Takes attributes of an image and puts them in one 1D array.\n\n image_id: An int ID of the image. Useful for debugging.\n original_image_shape: [H, W, C] before resizing or padding.\n image_shape: [H, W, C] after resizing and padding\n window: (y1, x1, y2, x2) in pixels. The area of the image where the real\n image is (excluding the padding)\n scale: The scaling factor applied to the original image (float32)\n active_class_ids: List of class_ids available in the dataset from which\n the image came. Useful if training on images from multiple datasets\n where not all classes are present in all datasets.\n \"\"\"\n meta = np.array(\n [image_id] + # size=1\n list(original_image_shape) + # size=3\n list(image_shape) + # size=3\n list(window) + # size=4 (y1, x1, y2, x2) in image cooredinates\n [scale] + # size=1\n list(active_class_ids) # size=num_classes\n )\n return meta\n\n\ndef parse_image_meta(meta):\n \"\"\"Parses an array that contains image attributes to its components.\n See compose_image_meta() for more details.\n\n meta: [batch, meta length] where meta length depends on NUM_CLASSES\n\n Returns a dict of the parsed values.\n \"\"\"\n image_id = meta[:, 0]\n original_image_shape = meta[:, 1:4]\n image_shape = meta[:, 4:7]\n window = meta[:, 7:11] # (y1, x1, y2, x2) window of image in in pixels\n scale = meta[:, 11]\n active_class_ids = meta[:, 12:]\n return {\n \"image_id\": image_id.astype(np.int32),\n \"original_image_shape\": original_image_shape.astype(np.int32),\n \"image_shape\": image_shape.astype(np.int32),\n \"window\": window.astype(np.int32),\n \"scale\": scale.astype(np.float32),\n \"active_class_ids\": active_class_ids.astype(np.int32),\n }\n\n\ndef parse_image_meta_graph(meta):\n \"\"\"Parses a tensor that contains image attributes to its components.\n See compose_image_meta() for more details.\n\n meta: [batch, meta length] where meta length depends on NUM_CLASSES\n\n Returns a dict of the parsed tensors.\n \"\"\"\n image_id = meta[:, 0]\n original_image_shape = meta[:, 1:4]\n image_shape = meta[:, 4:7]\n window = meta[:, 7:11] # (y1, x1, y2, x2) window of image in in pixels\n scale = meta[:, 11]\n active_class_ids = meta[:, 12:]\n return {\n \"image_id\": image_id,\n \"original_image_shape\": original_image_shape,\n \"image_shape\": image_shape,\n \"window\": window,\n \"scale\": scale,\n \"active_class_ids\": active_class_ids,\n }\n\n\ndef mold_image(images, config):\n \"\"\"Expects an RGB image (or array of images) and subtracts\n the mean pixel and converts it to float. Expects image\n colors in RGB order.\n \"\"\"\n return images.astype(np.float32) - config.MEAN_PIXEL\n\n\ndef unmold_image(normalized_images, config):\n \"\"\"Takes a image normalized with mold() and returns the original.\"\"\"\n return (normalized_images + config.MEAN_PIXEL).astype(np.uint8)\n\n\n############################################################\n# Miscellenous Graph Functions\n############################################################\n\ndef trim_zeros_graph(boxes, name='trim_zeros'):\n \"\"\"Often boxes are represented with matrices of shape [N, 4] and\n are padded with zeros. This removes zero boxes.\n\n boxes: [N, 4] matrix of boxes.\n non_zeros: [N] a 1D boolean mask identifying the rows to keep\n \"\"\"\n non_zeros = tf.cast(tf.reduce_sum(tf.abs(boxes), axis=1), tf.bool)\n boxes = tf.boolean_mask(boxes, non_zeros, name=name)\n return boxes, non_zeros\n\n\ndef batch_pack_graph(x, counts, num_rows):\n \"\"\"Picks different number of values from each row\n in x depending on the values in counts.\n \"\"\"\n outputs = []\n for i in range(num_rows):\n outputs.append(x[i, :counts[i]])\n return tf.concat(outputs, axis=0)\n\n\ndef norm_boxes_graph(boxes, shape):\n \"\"\"Converts boxes from pixel coordinates to normalized coordinates.\n boxes: [..., (y1, x1, y2, x2)] in pixel coordinates\n shape: [..., (height, width)] in pixels\n\n Note: In pixel coordinates (y2, x2) is outside the box. But in normalized\n coordinates it's inside the box.\n\n Returns:\n [..., (y1, x1, y2, x2)] in normalized coordinates\n \"\"\"\n h, w = tf.split(tf.cast(shape, tf.float32), 2)\n scale = tf.concat([h, w, h, w], axis=-1) - tf.constant(1.0)\n shift = tf.constant([0., 0., 1., 1.])\n return tf.divide(boxes - shift, scale)\n\n\ndef denorm_boxes_graph(boxes, shape):\n \"\"\"Converts boxes from normalized coordinates to pixel coordinates.\n boxes: [..., (y1, x1, y2, x2)] in normalized coordinates\n shape: [..., (height, width)] in pixels\n\n Note: In pixel coordinates (y2, x2) is outside the box. But in normalized\n coordinates it's inside the box.\n\n Returns:\n [..., (y1, x1, y2, x2)] in pixel coordinates\n \"\"\"\n h, w = tf.split(tf.cast(shape, tf.float32), 2)\n scale = tf.concat([h, w, h, w], axis=-1) - tf.constant(1.0)\n shift = tf.constant([0., 0., 1., 1.])\n return tf.cast(tf.round(tf.multiply(boxes, scale) + shift), tf.int32)\n" ]
[ [ "numpy.amax", "numpy.expand_dims", "tensorflow.concat", "tensorflow.control_dependencies", "tensorflow.stack", "tensorflow.reduce_sum", "tensorflow.minimum", "tensorflow.cast", "tensorflow.image.non_max_suppression", "tensorflow.equal", "tensorflow.image.crop_and_resize", "numpy.concatenate", "numpy.max", "tensorflow.abs", "tensorflow.map_fn", "numpy.any", "tensorflow.pad", "tensorflow.where", "tensorflow.random_shuffle", "numpy.where", "tensorflow.add_n", "numpy.divide", "numpy.random.randint", "tensorflow.boolean_mask", "numpy.hstack", "tensorflow.Variable", "numpy.reshape", "numpy.fliplr", "numpy.arange", "tensorflow.squeeze", "numpy.stack", "tensorflow.divide", "tensorflow.stop_gradient", "tensorflow.gather", "numpy.copy", "numpy.argmax", "tensorflow.nn.top_k", "tensorflow.argmax", "numpy.zeros", "numpy.log", "tensorflow.gather_nd", "tensorflow.unique", "tensorflow.shape", "numpy.random.choice", "tensorflow.identity", "tensorflow.exp", "tensorflow.sparse_tensor_to_dense", "numpy.delete", "tensorflow.nn.sparse_softmax_cross_entropy_with_logits", "tensorflow.split", "tensorflow.round", "numpy.array", "numpy.sum", "tensorflow.size", "tensorflow.reduce_max", "tensorflow.multiply", "tensorflow.transpose", "tensorflow.constant", "tensorflow.range", "tensorflow.reduce_mean", "numpy.abs", "tensorflow.maximum", "tensorflow.reshape", "tensorflow.expand_dims", "numpy.sort", "numpy.ones", "numpy.random.shuffle", "tensorflow.log", "numpy.broadcast_to", "tensorflow.sqrt", "numpy.empty", "tensorflow.logical_and" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
leo6033/Graduation-Project
[ "c1cf68edaffc346b37ac6e615d580cd05c4f0711" ]
[ "TextCNN.py" ]
[ "\"\"\"\n@Description: TextCNN 网络\n@Author: 吕明伟\n@Date: 2021-4-6\n\"\"\"\nfrom tensorflow.keras import Input, Model\nfrom tensorflow.keras.layers import Embedding, Dense, Conv1D, GlobalMaxPooling1D, Concatenate, Dropout\n\nclass TextCNN(object):\n def __init__(self, maxlen, max_features, embedding_dims,\n class_num=5,\n last_activation='softmax'):\n self.maxlen = maxlen\n self.max_features = max_features\n self.embedding_dims = embedding_dims\n self.class_num = class_num\n self.last_activation = last_activation\n\n def get_model(self):\n input = Input((self.maxlen,))\n embedding = Embedding(self.max_features, self.embedding_dims, input_length=self.maxlen, mask_zero=True)(input)\n convs = []\n for kernel_size in [3, 4, 5]:\n c = Conv1D(128, kernel_size, activation='relu')(embedding)\n c = GlobalMaxPooling1D()(c)\n convs.append(c)\n x = Concatenate()(convs)\n\n output = Dense(self.class_num, activation=self.last_activation)(x)\n model = Model(inputs=input, outputs=output)\n return model" ]
[ [ "tensorflow.keras.layers.Concatenate", "tensorflow.keras.Input", "tensorflow.keras.layers.Embedding", "tensorflow.keras.layers.GlobalMaxPooling1D", "tensorflow.keras.layers.Dense", "tensorflow.keras.layers.Conv1D", "tensorflow.keras.Model" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.7", "2.6", "2.4", "2.3", "2.5", "2.2" ] } ]
jtapanes21/RADGIS
[ "2322f75f23cec4dde9f8c7b21d9137f1986e6382", "2322f75f23cec4dde9f8c7b21d9137f1986e6382" ]
[ "RADGIS/preprocessing/knn.py", "RADGIS/preprocessing/kph.py" ]
[ "from sklearn.neighbors import BallTree\nimport numpy as np\n\n'''\nReturns the KNN and distance in meters to the KNN.\n\nParameters\n ----------\n left_gdf : GeoDataFrame\n the target geodataframe; all columns are kept.\n \n right_gdf : GeoDataFrame\n the geodataframe that is the subject of the measurement.\n \n keep_columns : list of strings\n the columns in the right_gdf that are kept.\n \n return_dist : boolean, optional\n if True, the distance in meters is added.\n Returns\n -------\n \n GeoDataFrame\n a GeoDataFrame with all of the columns from the left_gdf and only\n the columns from the right_gdf specified in keep_columns parameter.\n\n\nTaken from https://automating-gis-processes.github.io/site/notebooks/L3/nearest-neighbor-faster.html#Efficient-nearest-neighbor-search-with-Geopandas-and-scikit-learn\n\n\n'''\n\ndef _get_nearest(src_points, candidates, k_neighbors=1):\n \"\"\"Find nearest neighbors for all source points from a set of candidate points\"\"\"\n\n # Create tree from the candidate points\n tree = BallTree(candidates, leaf_size=15, metric='haversine')\n\n # Find closest points and distances\n distances, indices = tree.query(src_points, k=k_neighbors)\n\n # Transpose to get distances and indices into arrays\n distances = distances.transpose()\n indices = indices.transpose()\n\n # Get closest indices and distances (i.e. array at index 0)\n # note: for the second closest points, you would take index 1, etc.\n closest = indices[0]\n closest_dist = distances[0]\n\n # Return indices and distances\n return (closest, closest_dist)\n\n\n\n\ndef _complete_neighbor(left_gdf, right_gdf, return_dist):\n \"\"\"\n For each point in left_gdf, find closest point in right GeoDataFrame and return them.\n\n NOTICE: Assumes that the input Points are in WGS84 projection (lat/lon).\n \"\"\"\n\n left_geom_col = left_gdf.geometry.name\n right_geom_col = right_gdf.geometry.name\n\n # Ensure that index in right gdf is formed of sequential numbers\n right = right_gdf.copy().reset_index(drop=True)\n\n # Parse coordinates from points and insert them into a numpy array as RADIANS\n left_radians = np.array(left_gdf[left_geom_col].apply(lambda geom: (geom.x * np.pi / 180, geom.y * np.pi / 180)).to_list())\n right_radians = np.array(right[right_geom_col].apply(lambda geom: (geom.x * np.pi / 180, geom.y * np.pi / 180)).to_list())\n\n # Find the nearest points\n # -----------------------\n # closest ==> index in right_gdf that corresponds to the closest point\n # dist ==> distance between the nearest neighbors (in meters)\n\n closest, dist = _get_nearest(src_points=left_radians, candidates=right_radians)\n\n # Return points from right GeoDataFrame that are closest to points in left GeoDataFrame\n closest_points = right.loc[closest]\n\n # Ensure that the index corresponds the one in left_gdf\n closest_points = closest_points.reset_index(drop=True)\n\n # Add distance if requested\n if return_dist:\n # Convert to meters from radians\n earth_radius = 6371000 # meters\n closest_points['distance'] = dist * earth_radius\n\n return closest_points\n\ndef nearest_neighbor(left_gdf, right_gdf, keep_columns, return_dist=False):\n keep_columns.append(\"distance\")\n knn = _complete_neighbor(left_gdf, right_gdf, return_dist=return_dist)\n knn = knn[keep_columns]\n knn_join = left_gdf.join(knn.add_suffix(\"_knn\"))\n return knn_join\n \n \n \n ", "from ..core.trajectorydataframe import *\nfrom ..utils import constants, gislib, utils\nimport numpy as np\nimport pandas as pd\n\n\ndef kph(tdf):\n\n\n tdf = tdf.sort_by_uid_and_datetime().reset_index(drop=True)\n\n\n\n # Save the column names\n global column_names\n column_names = tdf.columns\n \n\n # Save the column indexes that will be used once the TrajDataFrame is converted to a multi-dimensional numpy array.\n\n global time_index\n global lat_index\n global lon_index\n\n time_index = tdf.columns.get_loc(constants.DATETIME) + 1\n lat_index = tdf.columns.get_loc(constants.LATITUDE)\n lon_index = tdf.columns.get_loc(constants.LONGITUDE)\n\n\n\n\n if utils.is_multi_user(tdf) == True:\n stdf = tdf.groupby(constants.UID, group_keys=False, as_index=False, sort=False).apply(_kph_work).reset_index(drop=True)\n else:\n stdf = _kph_work(tdf)\n\n\n #tdf = pd.DataFrame(stdf)\n \n\n\n \n # Name the dataframe's columns.\n #new_column_names = [\"kph\"]\n #new_column_names.extend(column_names)\n #tdf.columns = new_column_names\n\n stdf = TrajDataFrame(stdf, latitude=constants.LATITUDE, longitude=constants.LONGITUDE, datetime=constants.DATETIME, user_id=constants.UID)\n \n\n return stdf\n\ndef _kph_work(tdf):\n\n\n\n array = tdf.values\n\n \n\n\n \n array = np.hstack((((gislib.haversine_np(array[:,lat_index],array[:,lon_index], array[:,lat_index][1:], array[:,lon_index][1:]))[...,np.newaxis]), array))\n\n\n \n #return time_index\n \n \n transportation_mode = array[:,time_index][1:] - array[:,time_index][:-1]\n transportation_mode = np.append(transportation_mode, np.timedelta64(0, \"s\"))\n transportation_mode = transportation_mode.astype(\"timedelta64[ms]\").astype(int)/1000\n \n transportation_mode = transportation_mode[..., np.newaxis]\n \n array = np.hstack((transportation_mode, array))\n \n c = (np.divide((array[:,1]/1000), (array[:,0]/3600), out=np.zeros_like(array[:,1]), where=array[:,0]!=0))\n \n c = c[...,np.newaxis]\n array = np.hstack((c,array))\n \n # delete the time difference column\n array = np.delete(array, 1, 1)\n \n # delete the distance column\n \n array = np.delete(array, 1, 1)\n\n f = pd.DataFrame(array)\n\n\n\n new_column_names = [\"kph\"]\n new_column_names.extend(column_names)\n f.columns = new_column_names\n\n\n\n \n return f\n" ]
[ [ "sklearn.neighbors.BallTree" ], [ "numpy.hstack", "pandas.DataFrame", "numpy.timedelta64", "numpy.delete", "numpy.zeros_like" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
bianxg/BackgroundMattingV2
[ "af15097de99564f5042121601abe4050cc2e3c2e" ]
[ "collect_env.py" ]
[ "# Copyright (c) Facebook, Inc. and its affiliates.\r\nimport importlib\r\nimport numpy as np\r\nimport os\r\nimport re\r\nimport subprocess\r\nimport sys\r\nfrom collections import defaultdict\r\nimport PIL\r\nimport torch\r\nimport torchvision\r\nfrom tabulate import tabulate\r\n\r\n__all__ = [\"collect_env_info\"]\r\n\r\n\r\ndef collect_torch_env():\r\n try:\r\n import torch.__config__\r\n\r\n return torch.__config__.show()\r\n except ImportError:\r\n # compatible with older versions of pytorch\r\n from torch.utils.collect_env import get_pretty_env_info\r\n\r\n return get_pretty_env_info()\r\n\r\n\r\ndef get_env_module():\r\n var_name = \"DETECTRON2_ENV_MODULE\"\r\n return var_name, os.environ.get(var_name, \"<not set>\")\r\n\r\n\r\ndef detect_compute_compatibility(CUDA_HOME, so_file):\r\n try:\r\n cuobjdump = os.path.join(CUDA_HOME, \"bin\", \"cuobjdump\")\r\n if os.path.isfile(cuobjdump):\r\n output = subprocess.check_output(\r\n \"'{}' --list-elf '{}'\".format(cuobjdump, so_file), shell=True\r\n )\r\n output = output.decode(\"utf-8\").strip().split(\"\\n\")\r\n arch = []\r\n for line in output:\r\n line = re.findall(r\"\\.sm_([0-9]*)\\.\", line)[0]\r\n arch.append(\".\".join(line))\r\n arch = sorted(set(arch))\r\n return \", \".join(arch)\r\n else:\r\n return so_file + \"; cannot find cuobjdump\"\r\n except Exception:\r\n # unhandled failure\r\n return so_file\r\n\r\n\r\ndef collect_env_info():\r\n has_gpu = torch.cuda.is_available() # true for both CUDA & ROCM\r\n torch_version = torch.__version__\r\n\r\n # NOTE that CUDA_HOME/ROCM_HOME could be None even when CUDA runtime libs are functional\r\n from torch.utils.cpp_extension import CUDA_HOME, ROCM_HOME\r\n\r\n has_rocm = False\r\n if (getattr(torch.version, \"hip\", None) is not None) and (ROCM_HOME is not None):\r\n has_rocm = True\r\n has_cuda = has_gpu and (not has_rocm)\r\n\r\n data = []\r\n data.append((\"sys.platform\", sys.platform)) # check-template.yml depends on it\r\n data.append((\"Python\", sys.version.replace(\"\\n\", \"\")))\r\n data.append((\"numpy\", np.__version__))\r\n\r\n try:\r\n import detectron2 # noqa\r\n\r\n data.append(\r\n (\"detectron2\", detectron2.__version__ + \" @\" + os.path.dirname(detectron2.__file__))\r\n )\r\n except ImportError:\r\n data.append((\"detectron2\", \"failed to import\"))\r\n\r\n try:\r\n import detectron2._C as _C\r\n except ImportError as e:\r\n data.append((\"detectron2._C\", f\"not built correctly: {e}\"))\r\n\r\n # print system compilers when extension fails to build\r\n if sys.platform != \"win32\": # don't know what to do for windows\r\n try:\r\n # this is how torch/utils/cpp_extensions.py choose compiler\r\n cxx = os.environ.get(\"CXX\", \"c++\")\r\n cxx = subprocess.check_output(\"'{}' --version\".format(cxx), shell=True)\r\n cxx = cxx.decode(\"utf-8\").strip().split(\"\\n\")[0]\r\n except subprocess.SubprocessError:\r\n cxx = \"Not found\"\r\n data.append((\"Compiler ($CXX)\", cxx))\r\n\r\n if has_cuda and CUDA_HOME is not None:\r\n try:\r\n nvcc = os.path.join(CUDA_HOME, \"bin\", \"nvcc\")\r\n nvcc = subprocess.check_output(\"'{}' -V\".format(nvcc), shell=True)\r\n nvcc = nvcc.decode(\"utf-8\").strip().split(\"\\n\")[-1]\r\n except subprocess.SubprocessError:\r\n nvcc = \"Not found\"\r\n data.append((\"CUDA compiler\", nvcc))\r\n if has_cuda and sys.platform != \"win32\":\r\n try:\r\n so_file = importlib.util.find_spec(\"detectron2._C\").origin\r\n except ImportError:\r\n pass\r\n else:\r\n data.append(\r\n (\"detectron2 arch flags\", detect_compute_compatibility(CUDA_HOME, so_file))\r\n )\r\n else:\r\n # print compilers that are used to build extension\r\n data.append((\"Compiler\", _C.get_compiler_version()))\r\n data.append((\"CUDA compiler\", _C.get_cuda_version())) # cuda or hip\r\n if has_cuda and getattr(_C, \"has_cuda\", lambda: True)():\r\n data.append(\r\n (\"detectron2 arch flags\", detect_compute_compatibility(CUDA_HOME, _C.__file__))\r\n )\r\n\r\n data.append(get_env_module())\r\n data.append((\"PyTorch\", torch_version + \" @\" + os.path.dirname(torch.__file__)))\r\n data.append((\"PyTorch debug build\", torch.version.debug))\r\n\r\n data.append((\"GPU available\", has_gpu))\r\n if has_gpu:\r\n devices = defaultdict(list)\r\n for k in range(torch.cuda.device_count()):\r\n cap = \".\".join((str(x) for x in torch.cuda.get_device_capability(k)))\r\n name = torch.cuda.get_device_name(k) + f\" (arch={cap})\"\r\n devices[name].append(str(k))\r\n for name, devids in devices.items():\r\n data.append((\"GPU \" + \",\".join(devids), name))\r\n\r\n if has_rocm:\r\n msg = \" - invalid!\" if not (ROCM_HOME and os.path.isdir(ROCM_HOME)) else \"\"\r\n data.append((\"ROCM_HOME\", str(ROCM_HOME) + msg))\r\n else:\r\n msg = \" - invalid!\" if not (CUDA_HOME and os.path.isdir(CUDA_HOME)) else \"\"\r\n data.append((\"CUDA_HOME\", str(CUDA_HOME) + msg))\r\n\r\n cuda_arch_list = os.environ.get(\"TORCH_CUDA_ARCH_LIST\", None)\r\n if cuda_arch_list:\r\n data.append((\"TORCH_CUDA_ARCH_LIST\", cuda_arch_list))\r\n data.append((\"Pillow\", PIL.__version__))\r\n\r\n try:\r\n data.append(\r\n (\r\n \"torchvision\",\r\n str(torchvision.__version__) + \" @\" + os.path.dirname(torchvision.__file__),\r\n )\r\n )\r\n if has_cuda:\r\n try:\r\n torchvision_C = importlib.util.find_spec(\"torchvision._C\").origin\r\n msg = detect_compute_compatibility(CUDA_HOME, torchvision_C)\r\n data.append((\"torchvision arch flags\", msg))\r\n except ImportError:\r\n data.append((\"torchvision._C\", \"Not found\"))\r\n except AttributeError:\r\n data.append((\"torchvision\", \"unknown\"))\r\n\r\n try:\r\n import fvcore\r\n\r\n data.append((\"fvcore\", fvcore.__version__))\r\n except ImportError:\r\n pass\r\n\r\n try:\r\n import iopath\r\n\r\n data.append((\"iopath\", iopath.__version__))\r\n except (ImportError, AttributeError):\r\n pass\r\n\r\n try:\r\n import cv2\r\n\r\n data.append((\"cv2\", cv2.__version__))\r\n except ImportError:\r\n data.append((\"cv2\", \"Not found\"))\r\n env_str = tabulate(data) + \"\\n\"\r\n env_str += collect_torch_env()\r\n return env_str\r\n\r\n\r\nif __name__ == \"__main__\":\r\n try:\r\n from detectron2.utils.collect_env import collect_env_info as f\r\n\r\n print(f())\r\n except ImportError:\r\n print(collect_env_info())\r\n\r\n if torch.cuda.is_available():\r\n for k in range(torch.cuda.device_count()):\r\n device = f\"cuda:{k}\"\r\n try:\r\n x = torch.tensor([1, 2.0], dtype=torch.float32)\r\n x = x.to(device)\r\n except Exception as e:\r\n print(\r\n f\"Unable to copy tensor to device={device}: {e}. \"\r\n \"Your CUDA environment is broken.\"\r\n )\r\n" ]
[ [ "torch.__config__.show", "torch.cuda.get_device_capability", "torch.utils.collect_env.get_pretty_env_info", "torch.tensor", "torch.cuda.is_available", "torch.cuda.get_device_name", "torch.cuda.device_count" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ysy9893/object_recognition_with_hand_gesture
[ "fc43211a1e6fe8a19f726f156cf276a8acdcb246" ]
[ "motpy_edit/tracker.py" ]
[ "import uuid\nfrom collections.abc import Iterable\nfrom typing import Any, Optional, Sequence, Union\n\nimport numpy as np\nimport scipy\nfrom filterpy.kalman import KalmanFilter\n\nfrom motpy.core import Box, Detection, Track, Vector, setup_logger\nfrom motpy.metrics import angular_similarity, calculate_iou\nfrom motpy.model import Model, ModelPreset\n\nlogger = setup_logger(__name__)\n\n\ndef get_single_object_tracker(model: Model, x0: Optional[Vector] = None) -> KalmanFilter:\n \"\"\" returns Kalman-based tracker based on a specified motion model spec.\n e.g. for spec = {'order_pos': 1, 'dim_pos': 2, 'order_size': 0, 'dim_size': 1}\n we expect the following setup:\n state x, x', y, y', w, h\n where x and y are centers of boxes\n w and h are width and height\n \"\"\"\n\n tracker = KalmanFilter(dim_x=model.state_length,\n dim_z=model.measurement_length)\n tracker.F = model.build_F()\n tracker.Q = model.build_Q()\n tracker.H = model.build_H()\n tracker.R = model.build_R()\n tracker.P = model.build_P()\n\n if x0 is not None:\n tracker.x = x0\n\n return tracker\n\n\nDEFAULT_MODEL_SPEC = ModelPreset.constant_velocity_and_static_box_size_2d.value\n\n\ndef exponential_moving_average_fn(gamma: float) -> Any:\n def fn(old, new):\n if new is None:\n return old\n\n if isinstance(new, Iterable):\n new = np.array(new)\n\n if old is None:\n return new # first call\n else:\n return gamma * old + (1 - gamma) * new\n\n return fn\n\n\nclass Tracker:\n def __init__(\n self,\n model_spec: dict = DEFAULT_MODEL_SPEC,\n dt: float = 1 / 24,\n x0: Optional[Vector] = None,\n box0: Optional[Box] = None,\n score0: float=None,\n class0: float=None,\n max_staleness: float = 12.0,\n smooth_score_gamma: float = 0.8,\n smooth_feature_gamma: float = 0.9):\n self.id = str(uuid.uuid4())\n self.model_spec = model_spec\n\n self.steps_alive = 1\n self.steps_positive = 1\n self.staleness = 0.0\n self.max_staleness = max_staleness\n\n self.update_score_fn = exponential_moving_average_fn(smooth_score_gamma)\n self.update_feature_fn = exponential_moving_average_fn(smooth_feature_gamma)\n\n self.score = score0\n self.feature = None\n self.cl=class0\n\n logger.debug(\n 'creating new object tracker with %s and id %s' % (self.model_spec, self.id))\n\n self.model = Model(dt=dt, **self.model_spec)\n\n if x0 is None:\n x0 = self.model.box_to_x(box0)\n\n self._tracker = get_single_object_tracker(model=self.model, x0=x0)\n\n def predict(self):\n self.steps_alive += 1\n self._tracker.predict()\n\n def update(self, detection: Detection):\n self.steps_positive += 1\n\n # KF tracker update for position and size\n z = self.model.box_to_z(detection.box)\n self._tracker.update(z)\n \n self.cl=detection.cl\n\n self.score = self.update_score_fn(old=self.score, new=detection.score)\n #self.feature = self.update_feature_fn(old=self.feature, new=detection.feature)\n\n\n # reduce the staleness of a tracker, faster than growth rate\n self.unstale(rate=3)\n\n def stale(self, rate: float = 1.0):\n self.staleness += 4.5\n return self.staleness\n\n def unstale(self, rate: float = 2.0):\n self.staleness = max(0, self.staleness - rate)\n return self.staleness\n\n @property\n def is_stale(self) -> bool:\n return self.staleness >= self.max_staleness\n\n @property\n def is_invalid(self) -> bool:\n try:\n has_nans = any(np.isnan(self._tracker.x))\n return has_nans\n except Exception as e:\n logger.warning('invalid tracker, exception: %s' % str(e))\n return True\n\n @property\n def box(self):\n return self.model.x_to_box(self._tracker.x)\n\n def __repr__(self):\n fmt = \"box: %s\\tstaleness: %d\"\n return fmt % (self.box, self.staleness)\n\n\n\"\"\" assignment cost calculation & matching methods \"\"\"\n\n\ndef match_by_cost_matrix(trackers: Sequence[Tracker],\n detections: Sequence[Detection],\n min_iou: float = 0.1,\n **kwargs) -> np.ndarray:\n if len(trackers) == 0 or len(detections) == 0:\n return []\n\n cost_mat, iou_mat = cost_matrix_iou_feature(trackers, detections, **kwargs)\n row_ind, col_ind = scipy.optimize.linear_sum_assignment(cost_mat)\n\n # filter out low IOU matches\n ret = [[r, c] for r, c in zip(row_ind, col_ind) if iou_mat[r, c] >= min_iou]\n return np.array(ret)\n\n\ndef _sequence_has_none(seq: Sequence[Any]) -> Sequence[Any]:\n return any(r is None for r in seq)\n\n\ndef cost_matrix_iou_feature(trackers: Sequence[Tracker],\n detections: Sequence[Detection],\n feature_similarity_fn=angular_similarity,\n feature_similarity_beta: float = None):\n\n # boxes\n b1 = np.array([t.box for t in trackers])\n b2 = np.array([d.box for d in detections])\n\n # box iou\n inferred_dim = int(len(b1[0]) / 2)\n iou_mat = calculate_iou(b1, b2, dim=inferred_dim)\n\n # feature similarity\n if feature_similarity_beta is not None:\n # get features\n f1 = [t.feature for t in trackers]\n f2 = [d.feature for d in detections]\n\n if _sequence_has_none(f1) or _sequence_has_none(f2):\n # fallback to pure IOU due to missing features\n apt_mat = iou_mat\n else:\n sim_mat = feature_similarity_fn(f1, f2)\n sim_mat = feature_similarity_beta + (1 - feature_similarity_beta) * sim_mat\n\n # combined aptitude\n apt_mat = np.multiply(iou_mat, sim_mat)\n else:\n apt_mat = iou_mat\n\n cost_mat = -1.0 * apt_mat\n return cost_mat, iou_mat\n\n\nclass MatchingFunction:\n def __call__(self,\n trackers: Sequence[Tracker],\n detections: Sequence[Detection]) -> np.ndarray:\n raise NotImplementedError()\n\n\nclass BasicMatchingFunction(MatchingFunction):\n \"\"\" class implements the most basic matching function, taking\n detections boxes and optional feature similarity into account \"\"\"\n\n def __init__(self, min_iou: float = 0.1,\n feature_similarity_fn=angular_similarity,\n feature_similarity_beta: Optional[float] = None) -> None:\n\n self.min_iou = min_iou\n self.feature_similarity_fn = feature_similarity_fn\n self.feature_similarity_beta = feature_similarity_beta\n\n def __call__(self,\n trackers: Sequence[Tracker],\n detections: Sequence[Detection]) -> np.ndarray:\n return match_by_cost_matrix(\n trackers, detections,\n self.min_iou,\n feature_similarity_fn=self.feature_similarity_fn,\n feature_similarity_beta=self.feature_similarity_beta)\n\n\nclass MultiObjectTracker:\n def __init__(self, dt: float,\n model_spec: Union[str, dict] = DEFAULT_MODEL_SPEC,\n matching_fn: Optional[MatchingFunction] = None,\n tracker_kwargs: dict = None,\n matching_fn_kwargs: dict = None,\n active_tracks_kwargs: dict = None) -> None:\n \"\"\"\n model_spec specifies the dimension and order for position and size of the object\n matching_fn determines the strategy on which the trackers and detections are assigned.\n\n tracker_kwargs are passed to each single object tracker\n active_tracks_kwargs limits surfacing of fresh/fading out tracks\n \"\"\"\n\n self.dt = dt\n self.trackers = []\n\n if isinstance(model_spec, dict):\n self.model_spec = model_spec\n elif isinstance(model_spec, str) and model_spec in ModelPreset.__members__:\n self.model_spec = ModelPreset[model_spec].value\n else:\n raise NotImplementedError('unsupported motion model %s' % str(model_spec))\n logger.debug('using model spec: %s' % str(self.model_spec))\n\n self.matching_fn = matching_fn\n self.matching_fn_kwargs = matching_fn_kwargs if matching_fn_kwargs is not None else {}\n if self.matching_fn is None:\n self.matching_fn = BasicMatchingFunction(**self.matching_fn_kwargs)\n\n # kwargs to be passed to each single object tracker\n self.tracker_kwargs = tracker_kwargs if tracker_kwargs is not None else {}\n logger.debug('using tracker_kwargs: %s' % str(self.tracker_kwargs))\n\n # kwargs to be used when self.step returns active tracks\n self.active_tracks_kwargs = active_tracks_kwargs if active_tracks_kwargs is not None else {}\n logger.debug('using active_tracks_kwargs: %s' % str(self.active_tracks_kwargs))\n\n def active_tracks(self,\n max_staleness_to_positive_ratio: float = 3.0,\n max_staleness: float = 999,\n min_steps_alive: int = -1) -> Sequence[Track]:\n \"\"\" returns all active tracks after optional filtering by tracker steps count and staleness \"\"\"\n\n tracks = []\n for tracker in self.trackers:\n cond1 = tracker.staleness / tracker.steps_positive < max_staleness_to_positive_ratio # early stage\n cond2 = tracker.staleness < max_staleness\n cond3 = tracker.steps_alive >= min_steps_alive\n if cond1 and cond2 and cond3:\n tracks.append(Track(id=tracker.id, box=tracker.box, score=tracker.score,\n cl=tracker.cl))\n\n logger.debug('active/all tracks: %d/%d' % (len(self.trackers), len(tracks)))\n return tracks\n\n def cleanup_trackers(self) -> None:\n count_before = len(self.trackers)\n self.trackers = [t for t in self.trackers if not (t.is_stale or t.is_invalid)]\n count_after = len(self.trackers)\n logger.debug('deleted %s/%s trackers' % (count_before - count_after, count_before))\n\n def step(self, detections: Sequence[Detection]) -> Sequence[Track]:\n \"\"\" the method matches the new detections with existing trackers,\n creates new trackers if necessary and performs the cleanup.\n Returns the active tracks after active filtering applied \"\"\"\n \n\n\n #Delete detection if it contains empty bbox\n detections = [det for det in detections if det.box is not None]\n \n \n \n\n logger.debug('step with %d detections' % len(detections))\n #Matching btw previously tracked objects and newly detected objects \n matches = self.matching_fn(self.trackers, detections)\n logger.debug('matched %d pairs' % len(matches))\n\n # all trackers: predict\n for t in self.trackers:\n t.predict()#?????\n\n # assigned trackers: correct\n for match in matches:\n track_idx, det_idx = match[0], match[1]\n self.trackers[track_idx].update(detection=detections[det_idx])\n\n # not assigned detections: create new trackers POF\n assigned_det_idxs = set(matches[:, 1]) if len(matches) > 0 else []\n for det_idx in set(range(len(detections))).difference(assigned_det_idxs):\n tracker = Tracker(box0=detections[det_idx].box,score0=detections[det_idx].score,\n class0=detections[det_idx].cl,\n model_spec=self.model_spec,\n **self.tracker_kwargs)\n self.trackers.append(tracker)\n\n # unassigned trackers\n assigned_track_idxs = set(matches[:, 0]) if len(matches) > 0 else []\n for track_idx in set(range(len(self.trackers))).difference(assigned_track_idxs):\n self.trackers[track_idx].stale()\n\n # cleanup dead trackers\n self.cleanup_trackers()\n \n\n return self.active_tracks(**self.active_tracks_kwargs)\n\n" ]
[ [ "numpy.isnan", "scipy.optimize.linear_sum_assignment", "numpy.array", "numpy.multiply" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "1.6", "1.4", "0.19", "1.5", "0.18", "1.2", "1.7", "1.0", "0.17", "1.3", "1.8" ], "tensorflow": [] } ]
borisbolliet/CCL
[ "6ddd35e49f9d2968cef3d3bc1bac8b55dbb4cf91", "6ddd35e49f9d2968cef3d3bc1bac8b55dbb4cf91" ]
[ "pyccl/tracers.py", "pyccl/boltzmann.py" ]
[ "from . import ccllib as lib\nfrom .core import check\nfrom .background import comoving_radial_distance, growth_rate, \\\n growth_factor, scale_factor_of_chi\nfrom .pyutils import _check_array_params, NoneArr\nimport numpy as np\n\n\ndef get_density_kernel(cosmo, dndz):\n \"\"\"This convenience function returns the radial kernel for\n galaxy-clustering-like tracers. Given an unnormalized\n redshift distribution, it returns two arrays: chi, w(chi),\n where chi is an array of radial distances in units of\n Mpc and w(chi) = p(z) * H(z), where H(z) is the expansion\n rate in units of Mpc^-1 and p(z) is the normalized\n redshift distribution.\n\n Args:\n cosmo (:class:`~pyccl.core.Cosmology`): cosmology object used to\n transform redshifts into distances.\n dndz (tulple of arrays): A tuple of arrays (z, N(z))\n giving the redshift distribution of the objects.\n The units are arbitrary; N(z) will be normalized\n to unity.\n \"\"\"\n z_n, n = _check_array_params(dndz, 'dndz')\n # this call inits the distance splines neded by the kernel functions\n chi = comoving_radial_distance(cosmo, 1./(1.+z_n))\n status = 0\n wchi, status = lib.get_number_counts_kernel_wrapper(cosmo.cosmo,\n z_n, n,\n len(z_n),\n status)\n check(status)\n return chi, wchi\n\n\ndef get_lensing_kernel(cosmo, dndz, mag_bias=None):\n \"\"\"This convenience function returns the radial kernel for\n weak-lensing-like. Given an unnormalized redshift distribution\n and an optional magnification bias function, it returns\n two arrays: chi, w(chi), where chi is an array of radial\n distances in units of Mpc and w(chi) is the lensing shear\n kernel (or the magnification one if `mag_bias` is not `None`).\n\n Args:\n cosmo (:class:`~pyccl.core.Cosmology`): cosmology object used to\n transform redshifts into distances.\n dndz (tulple of arrays): A tuple of arrays (z, N(z))\n giving the redshift distribution of the objects.\n The units are arbitrary; N(z) will be normalized\n to unity.\n mag_bias (tuple of arrays, optional): A tuple of arrays (z, s(z))\n giving the magnification bias as a function of redshift. If\n `None`, s=0 will be assumed\n \"\"\"\n # we need the distance functions at the C layer\n cosmo.compute_distances()\n\n z_n, n = _check_array_params(dndz, 'dndz')\n has_magbias = mag_bias is not None\n z_s, s = _check_array_params(mag_bias, 'mag_bias')\n\n # Calculate number of samples in chi\n nchi = lib.get_nchi_lensing_kernel_wrapper(z_n)\n # Compute array of chis\n status = 0\n chi, status = lib.get_chis_lensing_kernel_wrapper(cosmo.cosmo, z_n[-1],\n nchi, status)\n # Compute kernel\n wchi, status = lib.get_lensing_kernel_wrapper(cosmo.cosmo,\n z_n, n, z_n[-1],\n int(has_magbias), z_s, s,\n chi, nchi, status)\n check(status)\n return chi, wchi\n\n\ndef get_kappa_kernel(cosmo, z_source, nsamples):\n \"\"\"This convenience function returns the radial kernel for\n CMB-lensing-like tracers.\n\n Args:\n cosmo (:class:`~pyccl.core.Cosmology`): Cosmology object.\n z_source (float): Redshift of source plane for CMB lensing.\n nsamples (int): number of samples over which the kernel\n is desired. These will be equi-spaced in radial distance.\n The kernel is quite smooth, so usually O(100) samples\n is enough.\n \"\"\"\n # this call inits the distance splines neded by the kernel functions\n chi_source = comoving_radial_distance(cosmo, 1./(1.+z_source))\n chi = np.linspace(0, chi_source, nsamples)\n\n status = 0\n wchi, status = lib.get_kappa_kernel_wrapper(cosmo.cosmo, chi_source,\n chi, nsamples, status)\n check(status)\n return chi, wchi\n\n\nclass Tracer(object):\n \"\"\"Tracers contain the information necessary to describe the\n contribution of a given sky observable to its cross-power spectrum\n with any other tracer. Tracers are composed of 4 main ingredients:\n\n * A radial kernel: this expresses the support in redshift/distance\n over which this tracer extends.\n\n * A transfer function: this is a function of wavenumber and\n scale factor that describes the connection between the tracer\n and the power spectrum on different scales and at different\n cosmic times.\n\n * An ell-dependent prefactor: normally associated with angular\n derivatives of a given fundamental quantity.\n\n * The order of the derivative of the Bessel functions with which\n they enter the computation of the angular power spectrum.\n\n A `Tracer` object will in reality be a list of different such\n tracers that get combined linearly when computing power spectra.\n Further details can be found in Section 4.9 of the CCL note.\n \"\"\"\n def __init__(self):\n \"\"\"By default this `Tracer` object will contain no actual\n tracers\n \"\"\"\n # Do nothing, just initialize list of tracers\n self._trc = []\n\n def _dndz(self, z):\n raise NotImplementedError(\"`get_dndz` not implemented for \"\n \"this `Tracer` type.\")\n\n def get_dndz(self, z):\n \"\"\"Get the redshift distribution for this tracer.\n Only available for some tracers (:class:`NumberCountsTracer` and\n :class:`WeakLensingTracer`).\n\n Args:\n z (float or array_like): redshift values.\n\n Returns:\n array_like: redshift distribution evaluated at the \\\n input values of `z`.\n \"\"\"\n return self._dndz(z)\n\n def get_kernel(self, chi):\n \"\"\"Get the radial kernels for all tracers contained\n in this `Tracer`.\n\n Args:\n chi (float or array_like): values of the comoving\n radial distance in increasing order and in Mpc.\n\n Returns:\n array_like: list of radial kernels for each tracer. \\\n The shape will be `(n_tracer, chi.size)`, where \\\n `n_tracer` is the number of tracers. The last \\\n dimension will be squeezed if the input is a \\\n scalar.\n \"\"\"\n if not hasattr(self, '_trc'):\n return []\n\n chi_use = np.atleast_1d(chi)\n kernels = []\n for t in self._trc:\n status = 0\n w, status = lib.cl_tracer_get_kernel(t, chi_use,\n chi_use.size,\n status)\n check(status)\n kernels.append(w)\n kernels = np.array(kernels)\n if np.ndim(chi) == 0:\n if kernels.shape != (0,):\n kernels = np.squeeze(kernels, axis=-1)\n return kernels\n\n def get_f_ell(self, ell):\n \"\"\"Get the ell-dependent prefactors for all tracers\n contained in this `Tracer`.\n\n Args:\n ell (float or array_like): angular multipole values.\n\n Returns:\n array_like: list of prefactors for each tracer. \\\n The shape will be `(n_tracer, ell.size)`, where \\\n `n_tracer` is the number of tracers. The last \\\n dimension will be squeezed if the input is a \\\n scalar.\n \"\"\"\n if not hasattr(self, '_trc'):\n return []\n\n ell_use = np.atleast_1d(ell)\n f_ells = []\n for t in self._trc:\n status = 0\n f, status = lib.cl_tracer_get_f_ell(t, ell_use,\n ell_use.size,\n status)\n check(status)\n f_ells.append(f)\n f_ells = np.array(f_ells)\n if np.ndim(ell) == 0:\n if f_ells.shape != (0,):\n f_ells = np.squeeze(f_ells, axis=-1)\n return f_ells\n\n def get_transfer(self, lk, a):\n \"\"\"Get the transfer functions for all tracers contained\n in this `Tracer`.\n\n Args:\n lk (float or array_like): values of the natural logarithm of\n the wave number (in units of inverse Mpc) in increasing\n order.\n a (float or array_like): values of the scale factor.\n\n Returns:\n array_like: list of transfer functions for each tracer. \\\n The shape will be `(n_tracer, lk.size, a.size)`, where \\\n `n_tracer` is the number of tracers. The other \\\n dimensions will be squeezed if the inputs are scalars.\n \"\"\"\n if not hasattr(self, '_trc'):\n return []\n\n lk_use = np.atleast_1d(lk)\n a_use = np.atleast_1d(a)\n transfers = []\n for t in self._trc:\n status = 0\n t, status = lib.cl_tracer_get_transfer(t, lk_use, a_use,\n lk_use.size * a_use.size,\n status)\n check(status)\n transfers.append(t.reshape([lk_use.size, a_use.size]))\n transfers = np.array(transfers)\n if transfers.shape != (0,):\n if np.ndim(a) == 0:\n transfers = np.squeeze(transfers, axis=-1)\n if np.ndim(lk) == 0:\n transfers = np.squeeze(transfers, axis=-1)\n else:\n if np.ndim(lk) == 0:\n transfers = np.squeeze(transfers, axis=-2)\n return transfers\n\n def get_bessel_derivative(self):\n \"\"\"Get Bessel function derivative orders for all tracers contained\n in this `Tracer`.\n\n Returns:\n array_like: list of Bessel derivative orders for each tracer.\n \"\"\"\n if not hasattr(self, '_trc'):\n return []\n\n return np.array([t.der_bessel for t in self._trc])\n\n def add_tracer(self, cosmo, kernel=None,\n transfer_ka=None, transfer_k=None, transfer_a=None,\n der_bessel=0, der_angles=0,\n is_logt=False, extrap_order_lok=0, extrap_order_hik=2):\n \"\"\"Adds one more tracer to the list contained in this `Tracer`.\n\n Args:\n cosmo (:class:`~pyccl.core.Cosmology`): cosmology object.\n kernel (tulple of arrays, optional): A tuple of arrays\n (`chi`, `w_chi`) describing the radial kernel of this\n tracer. `chi` should contain values of the comoving\n radial distance in increasing order, and `w_chi` should\n contain the values of the kernel at those values of the\n radial distance. The kernel will be assumed to be zero\n outside the range of distances covered by `chi`. If\n `kernel` is `None` a constant kernel w(chi)=1 will be\n assumed everywhere.\n transfer_ka (tuple of arrays, optional): a tuple of arrays\n (`a`,`lk`,`t_ka`) describing the most general transfer\n function for a tracer. `a` should be an array of scale\n factor values in increasing order. `lk` should be an\n array of values of the natural logarithm of the wave\n number (in units of inverse Mpc) in increasing order.\n `t_ka` should be an array of shape `(na,nk)`, where\n `na` and `nk` are the sizes of `a` and `lk` respectively.\n `t_ka` should hold the values of the transfer function at\n the corresponding values of `a` and `lk`. If your transfer\n function is factorizable (i.e. T(a,k) = A(a) * K(k)), it is\n more efficient to set this to `None` and use `transfer_k`\n and `transfer_a` to describe K and A respectively. The\n transfer function will be assumed continuous and constant\n outside the range of scale factors covered by `a`. It will\n be extrapolated using polynomials of order `extrap_order_lok`\n and `extrap_order_hik` below and above the range of\n wavenumbers covered by `lk` respectively. If this argument\n is not `None`, the values of `transfer_k` and `transfer_a`\n will be ignored.\n transfer_k (tuple of arrays, optional): a tuple of arrays\n (`lk`,`t_k`) describing the scale-dependent part of a\n factorizable transfer function. `lk` should be an\n array of values of the natural logarithm of the wave\n number (in units of inverse Mpc) in increasing order.\n `t_k ` should be an array of the same size holding the\n values of the k-dependent part of the transfer function\n at those wavenumbers. It will be extrapolated using\n polynomials of order `extrap_order_lok` and `extrap_order_hik`\n below and above the range of wavenumbers covered by `lk`\n respectively. If `None`, the k-dependent part of the transfer\n function will be set to 1 everywhere.\n transfer_a (tuple of arrays, optional): a tuple of arrays\n (`a`,`t_a`) describing the time-dependent part of a\n factorizable transfer function. `a` should be an array of\n scale factor values in increasing order. `t_a` should\n contain the time-dependent part of the transfer function\n at those values of the scale factor. The time dependence\n will be assumed continuous and constant outside the range\n covered by `a`. If `None`, the time-dependent part of the\n transfer function will be set to 1 everywhere.\n der_bessel (int): order of the derivative of the Bessel\n functions with which this tracer enters the calculation\n of the power spectrum. Allowed values are -1, 0, 1 and 2.\n 0, 1 and 2 correspond to the raw functions, their first\n derivatives or their second derivatives. -1 corresponds to\n the raw functions divided by the square of their argument.\n We enable this special value because this type of dependence\n is ubiquitous for many common tracers (lensing, IAs), and\n makes the corresponding transfer functions more stables\n for small k or chi.\n der_angles (int): integer describing the ell-dependent prefactor\n associated with this tracer. Allowed values are 0, 1 and 2.\n 0 means no prefactor. 1 means a prefactor ell*(ell+1),\n associated with the angular laplacian and used e.g. for\n lensing convergence and magnification. 2 means a prefactor\n sqrt((ell+2)!/(ell-2)!), associated with the angular\n derivatives of spin-2 fields (e.g. cosmic shear, IAs).\n is_logt (bool): if `True`, `transfer_ka`, `transfer_k` and\n `transfer_a` will contain the natural logarithm of the\n transfer function (or their factorizable parts). Default is\n `False`.\n extrap_order_lok (int): polynomial order used to extrapolate the\n transfer functions for low wavenumbers not covered by the\n input arrays.\n extrap_order_hik (int): polynomial order used to extrapolate the\n transfer functions for high wavenumbers not covered by the\n input arrays.\n \"\"\"\n is_factorizable = transfer_ka is None\n is_k_constant = (transfer_ka is None) and (transfer_k is None)\n is_a_constant = (transfer_ka is None) and (transfer_a is None)\n is_kernel_constant = kernel is None\n\n chi_s, wchi_s = _check_array_params(kernel, 'kernel')\n if is_factorizable:\n a_s, ta_s = _check_array_params(transfer_a, 'transfer_a')\n lk_s, tk_s = _check_array_params(transfer_k, 'transfer_k')\n tka_s = NoneArr\n if (not is_a_constant) and (a_s.shape != ta_s.shape):\n raise ValueError(\"Time-dependent transfer arrays \"\n \"should have the same shape\")\n if (not is_k_constant) and (lk_s.shape != tk_s.shape):\n raise ValueError(\"Scale-dependent transfer arrays \"\n \"should have the same shape\")\n else:\n a_s, lk_s, tka_s = _check_array_params(transfer_ka, 'transer_ka',\n arr3=True)\n if tka_s.shape != (len(a_s), len(lk_s)):\n raise ValueError(\"2D transfer array has inconsistent \"\n \"shape. Should be (na,nk)\")\n tka_s = tka_s.flatten()\n ta_s = NoneArr\n tk_s = NoneArr\n\n status = 0\n ret = lib.cl_tracer_t_new_wrapper(cosmo.cosmo,\n int(der_bessel),\n int(der_angles),\n chi_s, wchi_s,\n a_s, lk_s,\n tka_s, tk_s, ta_s,\n int(is_logt),\n int(is_factorizable),\n int(is_k_constant),\n int(is_a_constant),\n int(is_kernel_constant),\n int(extrap_order_lok),\n int(extrap_order_hik),\n status)\n self._trc.append(_check_returned_tracer(ret))\n\n def __del__(self):\n # Sometimes lib is freed before some Tracers, in which case, this\n # doesn't work.\n # So just check that lib.cl_tracer_t_free is still a real function.\n if hasattr(self, '_trc') and lib.cl_tracer_t_free is not None:\n for t in self._trc:\n lib.cl_tracer_t_free(t)\n\n\nclass NumberCountsTracer(Tracer):\n \"\"\"Specific `Tracer` associated to galaxy clustering with linear\n scale-independent bias, including redshift-space distortions and\n magnification.\n\n Args:\n cosmo (:class:`~pyccl.core.Cosmology`): Cosmology object.\n has_rsd (bool): Flag for whether the tracer has a\n redshift-space distortion term.\n dndz (tuple of arrays): A tuple of arrays (z, N(z))\n giving the redshift distribution of the objects. The units are\n arbitrary; N(z) will be normalized to unity.\n bias (tuple of arrays): A tuple of arrays (z, b(z))\n giving the galaxy bias. If `None`, this tracer won't include\n a term proportional to the matter density contrast.\n mag_bias (tuple of arrays, optional): A tuple of arrays (z, s(z))\n giving the magnification bias as a function of redshift. If\n `None`, the tracer is assumed to not have magnification bias\n terms. Defaults to None.\n \"\"\"\n def __init__(self, cosmo, has_rsd, dndz, bias, mag_bias=None):\n self._trc = []\n\n # we need the distance functions at the C layer\n cosmo.compute_distances()\n\n from scipy.interpolate import interp1d\n z_n, n = _check_array_params(dndz, 'dndz')\n self._dndz = interp1d(z_n, n, bounds_error=False,\n fill_value=0)\n\n kernel_d = None\n if bias is not None: # Has density term\n # Kernel\n if kernel_d is None:\n kernel_d = get_density_kernel(cosmo, dndz)\n # Transfer\n z_b, b = _check_array_params(bias, 'bias')\n # Reverse order for increasing a\n t_a = (1./(1+z_b[::-1]), b[::-1])\n self.add_tracer(cosmo, kernel=kernel_d, transfer_a=t_a)\n if has_rsd: # Has RSDs\n # Kernel\n if kernel_d is None:\n kernel_d = get_density_kernel(cosmo, dndz)\n # Transfer (growth rate)\n z_b, _ = _check_array_params(dndz, 'dndz')\n a_s = 1./(1+z_b[::-1])\n t_a = (a_s, -growth_rate(cosmo, a_s))\n self.add_tracer(cosmo, kernel=kernel_d,\n transfer_a=t_a, der_bessel=2)\n if mag_bias is not None: # Has magnification bias\n # Kernel\n chi, w = get_lensing_kernel(cosmo, dndz, mag_bias=mag_bias)\n # Multiply by -2 for magnification\n kernel_m = (chi, -2 * w)\n self.add_tracer(cosmo, kernel=kernel_m,\n der_bessel=-1, der_angles=1)\n\n\nclass WeakLensingTracer(Tracer):\n \"\"\"Specific `Tracer` associated to galaxy shape distortions including\n lensing shear and intrinsic alignments within the L-NLA model.\n\n Args:\n cosmo (:class:`~pyccl.core.Cosmology`): Cosmology object.\n dndz (tuple of arrays): A tuple of arrays (z, N(z))\n giving the redshift distribution of the objects. The units are\n arbitrary; N(z) will be normalized to unity.\n has_shear (bool): set to `False` if you want to omit the lensing shear\n contribution from this tracer.\n ia_bias (tuple of arrays, optional): A tuple of arrays\n (z, A_IA(z)) giving the intrinsic alignment amplitude A_IA(z).\n If `None`, the tracer is assumped to not have intrinsic\n alignments. Defaults to None.\n use_A_ia (bool): set to True to use the conventional IA\n normalization. Set to False to use the raw input amplitude,\n which will usually be 1 for use with PT IA modeling.\n Defaults to True.\n \"\"\"\n def __init__(self, cosmo, dndz, has_shear=True, ia_bias=None,\n use_A_ia=True):\n self._trc = []\n\n # we need the distance functions at the C layer\n cosmo.compute_distances()\n\n from scipy.interpolate import interp1d\n z_n, n = _check_array_params(dndz, 'dndz')\n self._dndz = interp1d(z_n, n, bounds_error=False,\n fill_value=0)\n\n if has_shear:\n # Kernel\n kernel_l = get_lensing_kernel(cosmo, dndz)\n self.add_tracer(cosmo, kernel=kernel_l,\n der_bessel=-1, der_angles=2)\n if ia_bias is not None: # Has intrinsic alignments\n z_a, tmp_a = _check_array_params(ia_bias, 'ia_bias')\n # Kernel\n kernel_i = get_density_kernel(cosmo, dndz)\n if use_A_ia:\n # Normalize so that A_IA=1\n D = growth_factor(cosmo, 1./(1+z_a))\n # Transfer\n # See Joachimi et al. (2011), arXiv: 1008.3491, Eq. 6.\n # and note that we use C_1= 5e-14 from arXiv:0705.0166\n rho_m = lib.cvar.constants.RHO_CRITICAL * cosmo['Omega_m']\n a = - tmp_a * 5e-14 * rho_m / D\n else:\n # use the raw input normalization. Normally, this will be 1\n # to allow nonlinear PT IA models, where normalization is\n # already applied to the power spectrum.\n a = tmp_a\n # Reverse order for increasing a\n t_a = (1./(1+z_a[::-1]), a[::-1])\n self.add_tracer(cosmo, kernel=kernel_i, transfer_a=t_a,\n der_bessel=-1, der_angles=2)\n\n\nclass CMBLensingTracer(Tracer):\n \"\"\"A Tracer for CMB lensing.\n\n Args:\n cosmo (:class:`~pyccl.core.Cosmology`): Cosmology object.\n z_source (float): Redshift of source plane for CMB lensing.\n nsamples (int, optional): number of samples over which the kernel\n is desired. These will be equi-spaced in radial distance.\n The kernel is quite smooth, so usually O(100) samples\n is enough.\n \"\"\"\n def __init__(self, cosmo, z_source, n_samples=100):\n self._trc = []\n\n # we need the distance functions at the C layer\n cosmo.compute_distances()\n\n kernel = get_kappa_kernel(cosmo, z_source, n_samples)\n self.add_tracer(cosmo, kernel=kernel, der_bessel=-1, der_angles=1)\n\n\nclass tSZTracer(Tracer):\n \"\"\"Specific :class:`Tracer` associated with the thermal Sunyaev Zel'dovich\n Compton-y parameter. The radial kernel for this tracer is simply given by\n\n .. math::\n W(\\\\chi) = \\\\frac{\\\\sigma_T}{m_ec^2} \\\\frac{1}{1+z},\n\n where :math:`\\\\sigma_T` is the Thomson scattering cross section and\n :math:`m_e` is the electron mass.\n\n Any angular power spectra computed with this tracer, should use\n a three-dimensional power spectrum involving the electron pressure\n in physical (non-comoving) units of :math:`eV\\\\,{\\\\rm cm}^{-3}`.\n\n Args:\n cosmo (:class:`~pyccl.core.Cosmology`): Cosmology object.\n zmax (float): maximum redshift up to which we define the\n kernel.\n n_chi (float): number of intervals in the radial comoving\n distance on which we sample the kernel.\n \"\"\"\n def __init__(self, cosmo, z_max=6., n_chi=1024):\n self.chi_max = comoving_radial_distance(cosmo, 1./(1+z_max))\n chi_arr = np.linspace(0, self.chi_max, n_chi)\n a_arr = scale_factor_of_chi(cosmo, chi_arr)\n # This is \\sigma_T / (m_e * c^2)\n prefac = 4.01710079e-06\n w_arr = prefac * a_arr\n\n self._trc = []\n self.add_tracer(cosmo, kernel=(chi_arr, w_arr))\n\n\ndef _check_returned_tracer(return_val):\n \"\"\"Wrapper to catch exceptions when tracers are spawned from C.\n \"\"\"\n if (isinstance(return_val, int)):\n check(return_val)\n tr = None\n else:\n tr, _ = return_val\n return tr\n", "import numpy as np\n\ntry:\n import classy\n HAVE_CLASS = True\nexcept ImportError:\n HAVE_CLASS = False\n\ntry:\n import camb\n import camb.model\n HAVE_CAMB = True\nexcept ImportError:\n HAVE_CAMB = False\n\ntry:\n import isitgr # noqa: F401\nexcept ImportError:\n pass # prevent nans from isitgr\n\nfrom . import ccllib as lib\nfrom .pyutils import check\nfrom .pk2d import Pk2D\nfrom .errors import CCLError\n\n\ndef get_camb_pk_lin(cosmo):\n \"\"\"Run CAMB and return the linear power spectrum.\n\n Args:\n cosmo (:class:`~pyccl.core.Cosmology`): Cosmological\n parameters. The cosmological parameters with\n which to run CAMB.\n\n Returns:\n :class:`~pyccl.pk2d.Pk2D`: Power spectrum \\\n object. The linear power spectrum.\n \"\"\"\n\n # Comment from Jarvis: TODO clean up this and other assert\n # anti-patterns in this file\n assert HAVE_CAMB, (\n \"You must have the `camb` python package \"\n \"installed to run CCL with CAMB!\")\n\n # z sampling from CCL parameters\n na = lib.get_pk_spline_na(cosmo.cosmo)\n status = 0\n a_arr, status = lib.get_pk_spline_a(cosmo.cosmo, na, status)\n check(status)\n a_arr = np.sort(a_arr)\n zs = 1.0 / a_arr - 1\n zs = np.clip(zs, 0, np.inf)\n\n # deal with normalization\n if np.isfinite(cosmo[\"A_s\"]):\n A_s_fid = cosmo[\"A_s\"]\n elif np.isfinite(cosmo[\"sigma8\"]):\n # in this case, CCL will internally normalize for us when we init\n # the linear power spectrum - so we just get close\n A_s_fid = 2.43e-9 * (cosmo[\"sigma8\"] / 0.87659)**2\n else:\n raise CCLError(\n \"Could not normalize the linear power spectrum! \"\n \"A_s = %f, sigma8 = %f\" % (\n cosmo['A_s'], cosmo['sigma8']))\n\n # init camb params\n cp = camb.model.CAMBparams()\n\n # turn some stuff off\n cp.WantCls = False\n cp.DoLensing = False\n cp.Want_CMB = False\n cp.Want_CMB_lensing = False\n cp.Want_cl_2D_array = False\n cp.WantTransfer = True\n\n # basic background stuff\n h2 = cosmo['h']**2\n cp.H0 = cosmo['h'] * 100\n cp.ombh2 = cosmo['Omega_b'] * h2\n cp.omch2 = cosmo['Omega_c'] * h2\n cp.omk = cosmo['Omega_k']\n\n # \"constants\"\n cp.TCMB = cosmo['T_CMB']\n\n # neutrinos\n # We maually setup the CAMB neutrinos to match the adjustments CLASS\n # makes to their temperatures.\n cp.share_delta_neff = False\n cp.omnuh2 = cosmo['Omega_nu_mass'] * h2\n cp.num_nu_massless = cosmo['N_nu_rel']\n cp.num_nu_massive = int(cosmo['N_nu_mass'])\n cp.nu_mass_eigenstates = int(cosmo['N_nu_mass'])\n\n delta_neff = cosmo['Neff'] - 3.046 # used for BBN YHe comps\n\n # CAMB defines a neutrino degeneracy factor as T_i = g^(1/4)*T_nu\n # where T_nu is the standard neutrino temperature from first order\n # computations\n # CLASS defines the temperature of each neutrino species to be\n # T_i_eff = TNCDM * T_cmb where TNCDM is a fudge factor to get the\n # total mass in terms of eV to match second-order computations of the\n # relationship between m_nu and Omega_nu.\n # We are trying to get both codes to use the same neutrino temperature.\n # thus we set T_i_eff = T_i = g^(1/4) * T_nu and solve for the right\n # value of g for CAMB. We get g = (TNCDM / (11/4)^(-1/3))^4\n g = np.power(\n lib.cvar.constants.TNCDM / np.power(11.0/4.0, -1.0/3.0),\n 4.0)\n\n if cosmo['N_nu_mass'] > 0:\n nu_mass_fracs = cosmo['m_nu'][:cosmo['N_nu_mass']]\n nu_mass_fracs = nu_mass_fracs / np.sum(nu_mass_fracs)\n\n cp.nu_mass_numbers = np.ones(cosmo['N_nu_mass'], dtype=np.int)\n cp.nu_mass_fractions = nu_mass_fracs\n cp.nu_mass_degeneracies = np.ones(int(cosmo['N_nu_mass'])) * g\n else:\n cp.nu_mass_numbers = []\n cp.nu_mass_fractions = []\n cp.nu_mass_degeneracies = []\n\n # get YHe from BBN\n cp.bbn_predictor = camb.bbn.get_predictor()\n cp.YHe = cp.bbn_predictor.Y_He(\n cp.ombh2 * (camb.constants.COBE_CMBTemp / cp.TCMB) ** 3,\n delta_neff)\n\n cp.set_classes(\n dark_energy_model=camb.dark_energy.DarkEnergyFluid\n )\n cp.DarkEnergy.set_params(\n w=cosmo['w0'],\n wa=cosmo['wa']\n )\n # cp.set_cosmology()\n cp.set_matter_power(\n redshifts=[_z for _z in zs],\n kmax=10,\n nonlinear=False)\n assert cp.NonLinear == camb.model.NonLinear_none\n\n cp.set_for_lmax(5000)\n cp.InitPower.set_params(\n As=A_s_fid,\n ns=cosmo['n_s'])\n\n # run CAMB and get results\n camb_res = camb.get_results(cp)\n k, z, pk = camb_res.get_linear_matter_power_spectrum(\n hubble_units=True, nonlinear=False)\n\n # convert to non-h inverse units\n k *= cosmo['h']\n pk /= (h2 * cosmo['h'])\n\n # now build interpolant\n nk = k.shape[0]\n lk_arr = np.log(k)\n a_arr = 1.0 / (1.0 + z)\n na = a_arr.shape[0]\n sinds = np.argsort(a_arr)\n a_arr = a_arr[sinds]\n ln_p_k_and_z = np.zeros((na, nk), dtype=np.float64)\n for i, sind in enumerate(sinds):\n ln_p_k_and_z[i, :] = np.log(pk[sind, :])\n\n pk_lin = Pk2D(\n pkfunc=None,\n a_arr=a_arr,\n lk_arr=lk_arr,\n pk_arr=ln_p_k_and_z,\n is_logp=True,\n extrap_order_lok=1,\n extrap_order_hik=2,\n cosmo=cosmo)\n\n return pk_lin\n\n\ndef get_isitgr_pk_lin(cosmo):\n \"\"\"Run ISiTGR-CAMB and return the linear power spectrum.\n\n Args:\n cosmo (:class:`~pyccl.core.Cosmology`): Cosmological\n parameters. The cosmological parameters with\n which to run ISiTGR-CAMB.\n\n Returns:\n :class:`~pyccl.pk2d.Pk2D`: Power spectrum \\\n object. The linear power spectrum.\n \"\"\"\n\n try:\n import isitgr # noqa: F811\n import isitgr.model\n except ImportError as e:\n e.args = (\n \"You must have the `isitgr` python package \"\n \"installed to run CCL with ISiTGR-CAMB!\",\n *e.args)\n raise\n\n # z sampling from CCL parameters\n na = lib.get_pk_spline_na(cosmo.cosmo)\n status = 0\n a_arr, status = lib.get_pk_spline_a(cosmo.cosmo, na, status)\n check(status)\n a_arr = np.sort(a_arr)\n zs = 1.0 / a_arr - 1\n zs = np.clip(zs, 0, np.inf)\n\n # deal with normalization\n if np.isfinite(cosmo[\"A_s\"]):\n A_s_fid = cosmo[\"A_s\"]\n elif np.isfinite(cosmo[\"sigma8\"]):\n # in this case, CCL will internally normalize for us when we init\n # the linear power spectrum - so we just get close\n A_s_fid = 2.43e-9 * (cosmo[\"sigma8\"] / 0.87659)**2\n else:\n raise CCLError(\n \"Could not normalize the linear power spectrum! \"\n \"A_s = %f, sigma8 = %f\" % (\n cosmo['A_s'], cosmo['sigma8']))\n\n # init isitgr params\n cp = isitgr.model.CAMBparams()\n\n # turn some stuff off\n cp.WantCls = False\n cp.DoLensing = False\n cp.Want_CMB = False\n cp.Want_CMB_lensing = False\n cp.Want_cl_2D_array = False\n cp.WantTransfer = True\n\n # basic background stuff\n h2 = cosmo['h']**2\n cp.H0 = cosmo['h'] * 100\n cp.ombh2 = cosmo['Omega_b'] * h2\n cp.omch2 = cosmo['Omega_c'] * h2\n cp.omk = cosmo['Omega_k']\n# cp.GR = 1 means GR modified!\n cp.GR = 1\n cp.ISiTGR_muSigma = True\n cp.mu0 = cosmo['mu_0']\n cp.Sigma0 = cosmo['sigma_0']\n\n # \"constants\"\n cp.TCMB = cosmo['T_CMB']\n\n # neutrinos\n # We maually setup the CAMB neutrinos to match the adjustments CLASS\n # makes to their temperatures.\n cp.share_delta_neff = False\n cp.omnuh2 = cosmo['Omega_nu_mass'] * h2\n cp.num_nu_massless = cosmo['N_nu_rel']\n cp.num_nu_massive = int(cosmo['N_nu_mass'])\n cp.nu_mass_eigenstates = int(cosmo['N_nu_mass'])\n\n delta_neff = cosmo['Neff'] - 3.046 # used for BBN YHe comps\n\n # ISiTGR built on CAMB which defines a neutrino degeneracy\n # factor as T_i = g^(1/4)*T_nu\n # where T_nu is the standard neutrino temperature from first order\n # computations\n # CLASS defines the temperature of each neutrino species to be\n # T_i_eff = TNCDM * T_cmb where TNCDM is a fudge factor to get the\n # total mass in terms of eV to match second-order computations of the\n # relationship between m_nu and Omega_nu.\n # We are trying to get both codes to use the same neutrino temperature.\n # thus we set T_i_eff = T_i = g^(1/4) * T_nu and solve for the right\n # value of g for CAMB. We get g = (TNCDM / (11/4)^(-1/3))^4\n g = np.power(\n lib.cvar.constants.TNCDM / np.power(11.0/4.0, -1.0/3.0),\n 4.0)\n\n if cosmo['N_nu_mass'] > 0:\n nu_mass_fracs = cosmo['m_nu'][:cosmo['N_nu_mass']]\n nu_mass_fracs = nu_mass_fracs / np.sum(nu_mass_fracs)\n\n cp.nu_mass_numbers = np.ones(cosmo['N_nu_mass'], dtype=np.int)\n cp.nu_mass_fractions = nu_mass_fracs\n cp.nu_mass_degeneracies = np.ones(int(cosmo['N_nu_mass'])) * g\n else:\n cp.nu_mass_numbers = []\n cp.nu_mass_fractions = []\n cp.nu_mass_degeneracies = []\n\n # get YHe from BBN\n cp.bbn_predictor = isitgr.bbn.get_predictor()\n cp.YHe = cp.bbn_predictor.Y_He(\n cp.ombh2 * (isitgr.constants.COBE_CMBTemp / cp.TCMB) ** 3,\n delta_neff)\n\n cp.set_classes(\n dark_energy_model=isitgr.dark_energy.DarkEnergyFluid\n )\n cp.DarkEnergy.set_params(\n w=cosmo['w0'],\n wa=cosmo['wa']\n )\n # cp.set_cosmology()\n cp.set_matter_power(\n redshifts=[_z for _z in zs],\n kmax=10,\n nonlinear=False)\n assert cp.NonLinear == isitgr.model.NonLinear_none\n\n cp.set_for_lmax(5000)\n cp.InitPower.set_params(\n As=A_s_fid,\n ns=cosmo['n_s'])\n\n # run ISITGR and get results\n isitgr_res = isitgr.get_results(cp)\n k, z, pk = isitgr_res.get_linear_matter_power_spectrum(\n hubble_units=True, nonlinear=False)\n\n # convert to non-h inverse units\n k *= cosmo['h']\n pk /= (h2 * cosmo['h'])\n\n # now build interpolant\n nk = k.shape[0]\n lk_arr = np.log(k)\n a_arr = 1.0 / (1.0 + z)\n na = a_arr.shape[0]\n sinds = np.argsort(a_arr)\n a_arr = a_arr[sinds]\n ln_p_k_and_z = np.zeros((na, nk), dtype=np.float64)\n for i, sind in enumerate(sinds):\n ln_p_k_and_z[i, :] = np.log(pk[sind, :])\n\n pk_lin = Pk2D(\n pkfunc=None,\n a_arr=a_arr,\n lk_arr=lk_arr,\n pk_arr=ln_p_k_and_z,\n is_logp=True,\n extrap_order_lok=1,\n extrap_order_hik=2,\n cosmo=cosmo)\n return pk_lin\n\n\ndef get_class_pk_lin(cosmo):\n \"\"\"Run CLASS and return the linear power spectrum.\n\n Args:\n cosmo (:class:`~pyccl.core.Cosmology`): Cosmological\n parameters. The cosmological parameters with\n which to run CLASS.\n\n Returns:\n :class:`~pyccl.pk2d.Pk2D`: Power spectrum object.\\\n The linear power spectrum.\n \"\"\"\n\n assert HAVE_CLASS, (\n \"You must have the python wrapper for CLASS \"\n \"installed to run CCL with CLASS!\")\n\n params = {\n \"output\": \"mPk\",\n \"non linear\": \"none\",\n \"P_k_max_1/Mpc\": cosmo.cosmo.spline_params.K_MAX_SPLINE,\n \"z_max_pk\": 1.0/cosmo.cosmo.spline_params.A_SPLINE_MINLOG_PK-1.0,\n \"modes\": \"s\",\n \"lensing\": \"no\",\n \"h\": cosmo[\"h\"],\n \"Omega_cdm\": cosmo[\"Omega_c\"],\n \"Omega_b\": cosmo[\"Omega_b\"],\n \"Omega_k\": cosmo[\"Omega_k\"],\n \"n_s\": cosmo[\"n_s\"]}\n\n # cosmological constant?\n # set Omega_Lambda = 0.0 if w !=-1 or wa != 0\n if cosmo['w0'] != -1 or cosmo['wa'] != 0:\n params[\"Omega_Lambda\"] = 0\n params['w0_fld'] = cosmo['w0']\n params['wa_fld'] = cosmo['wa']\n\n # neutrino parameters\n # massless neutrinos\n if cosmo[\"N_nu_rel\"] > 1e-4:\n params[\"N_ur\"] = cosmo[\"N_nu_rel\"]\n else:\n params[\"N_ur\"] = 0.0\n\n # massive neutrinos\n if cosmo[\"N_nu_mass\"] > 0:\n params[\"N_ncdm\"] = cosmo[\"N_nu_mass\"]\n masses = lib.parameters_get_nu_masses(cosmo._params, 3)\n params[\"m_ncdm\"] = \", \".join(\n [\"%g\" % m for m in masses[:cosmo[\"N_nu_mass\"]]])\n\n params[\"T_cmb\"] = cosmo[\"T_CMB\"]\n\n # if we have sigma8, we need to find A_s\n if np.isfinite(cosmo[\"A_s\"]):\n params[\"A_s\"] = cosmo[\"A_s\"]\n elif np.isfinite(cosmo[\"sigma8\"]):\n # in this case, CCL will internally normalize for us when we init\n # the linear power spectrum - so we just get close\n A_s_fid = 2.43e-9 * (cosmo[\"sigma8\"] / 0.87659)**2\n params[\"A_s\"] = A_s_fid\n else:\n raise CCLError(\n \"Could not normalize the linear power spectrum! \"\n \"A_s = %f, sigma8 = %f\" % (\n cosmo['A_s'], cosmo['sigma8']))\n\n model = None\n try:\n model = classy.Class()\n model.set(params)\n model.compute()\n\n # Set k and a sampling from CCL parameters\n nk = lib.get_pk_spline_nk(cosmo.cosmo)\n na = lib.get_pk_spline_na(cosmo.cosmo)\n status = 0\n a_arr, status = lib.get_pk_spline_a(cosmo.cosmo, na, status)\n check(status)\n\n # FIXME - getting the lowest CLASS k value from the python interface\n # appears to be broken - setting to 1e-5 which is close to the\n # old value\n lk_arr = np.log(np.logspace(\n -5,\n np.log10(cosmo.cosmo.spline_params.K_MAX_SPLINE), nk))\n\n # we need to cut this to the max value used for calling CLASS\n msk = lk_arr < np.log(cosmo.cosmo.spline_params.K_MAX_SPLINE)\n nk = int(np.sum(msk))\n lk_arr = lk_arr[msk]\n\n # now do interp by hand\n ln_p_k_and_z = np.zeros((na, nk), dtype=np.float64)\n for aind in range(na):\n z = max(1.0 / a_arr[aind] - 1, 1e-10)\n for kind in range(nk):\n ln_p_k_and_z[aind, kind] = np.log(\n model.pk_lin(np.exp(lk_arr[kind]), z))\n finally:\n if model is not None:\n model.struct_cleanup()\n model.empty()\n\n params[\"P_k_max_1/Mpc\"] = cosmo.cosmo.spline_params.K_MAX_SPLINE\n\n # make the Pk2D object\n pk_lin = Pk2D(\n pkfunc=None,\n a_arr=a_arr,\n lk_arr=lk_arr,\n pk_arr=ln_p_k_and_z,\n is_logp=True,\n extrap_order_lok=1,\n extrap_order_hik=2,\n cosmo=cosmo)\n\n return pk_lin\n" ]
[ [ "numpy.linspace", "numpy.squeeze", "numpy.atleast_1d", "numpy.ndim", "scipy.interpolate.interp1d", "numpy.array" ], [ "numpy.log", "numpy.isfinite", "numpy.clip", "numpy.power", "numpy.sort", "numpy.ones", "numpy.log10", "numpy.argsort", "numpy.exp", "numpy.zeros", "numpy.sum" ] ]
[ { "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": [] } ]
wilile26811249/ConvMixer
[ "e3a2bcbedb8e8c2b7b5f942ed0ae55473940d47c" ]
[ "utils.py" ]
[ "from typing import List, Optional\n\nimport numpy as np\nimport torch\nfrom torchvision import datasets\nfrom torchvision import transforms as T\n\nclass AverageMeter(object):\n def __init__(self,\n name: str,\n fmt: Optional[str] = ':f',\n ) -> None:\n self.name = name\n self.fmt = fmt\n self.reset()\n\n def reset(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n\n def update(self,\n val: float,\n n: Optional[int] = 1\n ) -> None:\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count\n\n def __str__(self):\n fmtstr = '{name}:{val' + self.fmt + '}({avg' + self.fmt + '})'\n return fmtstr.format(**self.__dict__)\n\n\nclass ProgressMeter(object):\n def __init__(self,\n num_batches: int,\n meters: List[AverageMeter],\n prefix: Optional[str] = \"\",\n batch_info: Optional[str] = \"\"\n ) -> None:\n self.batch_fmster = self._get_batch_fmster(num_batches)\n self.meters = meters\n self.prefix = prefix\n self.batch_info = batch_info\n\n def display(self, batch):\n self.info = [self.prefix + self.batch_info + self.batch_fmster.format(batch)]\n self.info += [str(meter) for meter in self.meters]\n print('\\t'.join(self.info))\n\n def _get_batch_fmster(self, num_batches):\n num_digits = len(str(num_batches // 1))\n fmt = '{:' + str(num_digits) + 'd}'\n return '[' + fmt + '/' + fmt.format(num_batches) + ']'\n\n\nclass EarlyStopping(object):\n \"\"\"\n Arg\n \"\"\"\n def __init__(self,\n patience: int = 7,\n verbose: Optional[bool] = False,\n delta: Optional[float] = 0.0,\n path: Optional[str] = \"checkpoint.pt\"\n ) -> None:\n self.patience = patience\n self.verbose = verbose\n self.counter = 0\n self.best_score = None\n self.early_stop_flag = False\n self.val_loss_min = np.Inf\n self.delta = delta\n self.verbose = verbose\n self.path = path\n\n def __call__(self, val_loss, model):\n score = abs(val_loss)\n if self.best_score is None:\n self.best_score = score\n self.save_model(val_loss, model)\n elif val_loss > self.val_loss_min + self.delta:\n self.counter += 1\n if self.verbose:\n print(f\"EarlyStopping Counter: {self.counter} out of {self.patience}\")\n print(f\"Best val loss: {self.val_loss_min} Current val loss: {score}\")\n if self.counter >= self.patience:\n self.early_stop_flag = True\n else:\n self.best_score = score\n self.save_model(val_loss, model)\n self.counter = 0\n\n def save_model(self, val_loss, model):\n if self.verbose:\n print(f'Validation loss decreased ({self.val_loss_min:.6f} --> {val_loss:.6f}). Saving model ...')\n torch.save(model.state_dict(), self.path)\n self.val_loss_min = val_loss\n\n\ndef accuracy(output, target, topk = (1,)):\n \"\"\"\n Computes the accuracy over the top k predictions\n \"\"\"\n with torch.no_grad():\n max_k = max(topk)\n batch_size = output.size(0)\n\n _, pred = output.topk(max_k,\n dim = 1,\n largest = True,\n sorted = True\n )\n pred = pred.t()\n correct = pred.eq(target.view(1, -1).expand_as(pred))\n\n result = []\n for k in topk:\n correct_k = correct[: k].contiguous().view(-1).float().sum(0, keepdim = True)\n result.append(correct_k.mul_(100.0 / batch_size))\n return result\n\n\ndef get_lr(optimizer):\n for param_group in optimizer.param_groups:\n return param_group['lr']\n\n\ndef get_cifar10_dataset(train_transform = None, test_transform = None):\n train_dataset = datasets.CIFAR10(\n root = './data',\n train = True,\n transform = train_transform,\n download = True\n )\n test_dataset = datasets.CIFAR10(\n root = './data',\n train = False,\n transform = test_transform,\n download = True\n )\n return train_dataset, test_dataset\n\n\ndef get_dataloader(\n train_transform,\n test_transform,\n img_size = 224,\n split = (0.8, 0.2),\n **kwargs\n ):\n assert len(split) == 2\n assert sum(split) == 1\n assert split[0] + split[1] == 1\n\n train_dataset, test_dataset = get_cifar10_dataset(train_transform, test_transform)\n train_size = int(len(train_dataset) * split[0])\n test_size = int(len(train_dataset) * split[1])\n train_dataset, val_dataset = torch.utils.data.random_split(\n train_dataset,\n (train_size, test_size)\n )\n\n train_loader = torch.utils.data.DataLoader(\n train_dataset,\n batch_size = kwargs['batch_size'],\n shuffle = True,\n num_workers = kwargs['num_workers'],\n pin_memory = True,\n drop_last = True,\n sampler = None\n )\n val_loader = torch.utils.data.DataLoader(\n val_dataset,\n batch_size = kwargs['batch_size'],\n shuffle = False,\n num_workers = kwargs['num_workers'],\n pin_memory = True,\n drop_last = False,\n sampler = None\n )\n test_loader = torch.utils.data.DataLoader(\n test_dataset,\n batch_size = kwargs['batch_size'],\n shuffle = False,\n num_workers = kwargs['num_workers'],\n pin_memory = True,\n drop_last = False,\n sampler = None\n )\n return train_loader, val_loader, test_loader" ]
[ [ "torch.no_grad", "torch.utils.data.random_split", "torch.utils.data.DataLoader" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
josesho/bootstrap-contrast
[ "94fa42a5dc4622be016e2e522d1f07b19ba23a8d" ]
[ "setup.py" ]
[ "from setuptools import setup, find_packages\nimport os\n# Taken from setup.py in seaborn.\n# temporarily redirect config directory to prevent matplotlib importing\n# testing that for writeable directory which results in sandbox error in\n# certain easy_install versions\nos.environ[\"MPLCONFIGDIR\"]=\".\"\n\n# Modified from from setup.py in seaborn.\ntry:\n from setuptools import setup\n _has_setuptools=True\nexcept ImportError:\n from distutils.core import setup\n\ndef check_dependencies():\n to_install=[]\n\n try:\n import numpy\n except ImportError:\n to_install.append('numpy>=1.13.1')\n try:\n import scipy\n except ImportError:\n to_install.append('scipy>=0.19.1')\n try:\n import matplotlib\n except ImportError:\n to_install.append('matplotlib>=2.0.2')\n try:\n import pandas\n if int(pandas.__version__.split('.')[1])<20:\n to_install.append('pandas>=0.20.1')\n except ImportError:\n to_install.append('pandas>=0.20.1')\n try:\n import seaborn\n except ImportError:\n to_install.append('seaborn>0.8')\n\n return to_install\n\nif __name__==\"__main__\":\n\n installs=check_dependencies()\n setup(name='bootstrap_contrast',\n author='Joses Ho',\n author_email='[email protected]',\n version=1.0,\n description='Calculation and Visualization of Confidence Intervals and Effect Sizes for Python.',\n packages=find_packages(),\n install_requires=installs,\n url='http://github.com/josesho/bootstrap_contrast',\n license='MIT'\n )\n" ]
[ [ "pandas.__version__.split" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
exenGT/pymatgen
[ "a8ffb820ab8fc3f60251099e38c8888f45eae618", "a8ffb820ab8fc3f60251099e38c8888f45eae618", "a8ffb820ab8fc3f60251099e38c8888f45eae618", "a8ffb820ab8fc3f60251099e38c8888f45eae618", "a8ffb820ab8fc3f60251099e38c8888f45eae618" ]
[ "pymatgen/analysis/piezo.py", "pymatgen/analysis/defects/tests/test_corrections.py", "pymatgen/io/lammps/outputs.py", "pymatgen/analysis/ewald.py", "pymatgen/analysis/defects/tests/test_core.py" ]
[ "# Copyright (c) Pymatgen Development Team.\n# Distributed under the terms of the MIT License.\n\n\n\"\"\"\nThis module provides classes for the Piezoelectric tensor\n\"\"\"\nimport warnings\n\nimport numpy as np\n\nfrom pymatgen.core.tensors import Tensor\n\n__author__ = \"Shyam Dwaraknath\"\n__copyright__ = \"Copyright 2016, The Materials Project\"\n__version__ = \"1.0\"\n__maintainer__ = \"Shyam Dwaraknath\"\n__email__ = \"[email protected]\"\n__status__ = \"Development\"\n__date__ = \"Feb, 2016\"\n\n\nclass PiezoTensor(Tensor):\n \"\"\"\n This class describes the 3x6 piezo tensor in Voigt-notation\n \"\"\"\n\n def __new__(cls, input_array, tol=1e-3):\n \"\"\"\n Create an PiezoTensor object. The constructor throws an error if\n the shape of the input_matrix argument is not 3x3x3, i. e. in true\n tensor notation. Note that the constructor uses __new__ rather than\n __init__ according to the standard method of subclassing numpy\n ndarrays.\n\n Args:\n input_matrix (3x3x3 array-like): the 3x6 array-like\n representing the piezo tensor\n \"\"\"\n obj = super().__new__(cls, input_array, check_rank=3)\n if not (obj - np.transpose(obj, (0, 2, 1)) < tol).all():\n warnings.warn(\"Input piezo tensor does not satisfy standard symmetries\")\n return obj.view(cls)\n\n @classmethod\n def from_vasp_voigt(cls, input_vasp_array):\n \"\"\"\n Args:\n input_vasp_array (nd.array): Voigt form of tensor.\n\n Returns:\n PiezoTensor\n \"\"\"\n voigt_map = [(0, 0), (1, 1), (2, 2), (0, 1), (1, 2), (0, 2)]\n input_vasp_array = np.array(input_vasp_array)\n rank = 3\n\n pt = np.zeros([rank, 3, 3])\n for dim in range(rank):\n for pos, val in enumerate(voigt_map):\n pt[dim][voigt_map[pos]] = input_vasp_array[dim][pos]\n pt[dim].T[voigt_map[pos]] = input_vasp_array[dim][pos]\n\n return cls(pt)\n", "# Copyright (c) Pymatgen Development Team.\n# Distributed under the terms of the MIT License.\n\n\nimport os\nimport unittest\n\nimport numpy as np\n\nfrom pymatgen.analysis.defects.core import DefectEntry, Vacancy\nfrom pymatgen.analysis.defects.corrections import (\n BandEdgeShiftingCorrection,\n BandFillingCorrection,\n FreysoldtCorrection,\n KumagaiCorrection,\n)\nfrom pymatgen.analysis.defects.utils import generate_R_and_G_vecs\nfrom pymatgen.core import Lattice\nfrom pymatgen.io.vasp import Outcar, Poscar, Vasprun\nfrom pymatgen.util.testing import PymatgenTest\n\n\nclass DefectsCorrectionsTest(PymatgenTest):\n def test_freysoldt(self):\n struc = PymatgenTest.get_structure(\"VO2\")\n struc.make_supercell(3)\n struc = struc\n vac = Vacancy(struc, struc.sites[0], charge=-3)\n ids = vac.generate_defect_structure(1)\n\n abc = struc.lattice.abc\n axisdata = [np.arange(0.0, lattval, 0.2) for lattval in abc]\n bldata = [np.array([1.0 for u in np.arange(0.0, lattval, 0.2)]) for lattval in abc]\n dldata = [\n np.array([(-1 - np.cos(2 * np.pi * u / lattval)) for u in np.arange(0.0, lattval, 0.2)]) for lattval in abc\n ]\n params = {\n \"axis_grid\": axisdata,\n \"bulk_planar_averages\": bldata,\n \"defect_planar_averages\": dldata,\n \"initial_defect_structure\": ids,\n \"defect_frac_sc_coords\": struc.sites[0].frac_coords,\n }\n fc = FreysoldtCorrection(15)\n\n # test electrostatic correction\n es_corr = fc.perform_es_corr(struc.lattice, -3)\n self.assertAlmostEqual(es_corr, 0.975893)\n\n # test potential alignment method\n pot_corr = fc.perform_pot_corr(axisdata[0], bldata[0], dldata[0], struc.lattice, -3, vac.site.coords, 0)\n self.assertAlmostEqual(pot_corr, 2.836369987722345)\n\n # test entry full correction method\n de = DefectEntry(vac, 0.0, corrections={}, parameters=params, entry_id=None)\n val = fc.get_correction(de)\n self.assertAlmostEqual(val[\"freysoldt_electrostatic\"], 0.975893)\n self.assertAlmostEqual(val[\"freysoldt_potential_alignment\"], 4.4700574)\n\n # test the freysoldt plotter\n for ax in range(3):\n fcp = fc.plot(axis=ax)\n self.assertTrue(fcp)\n\n # check that uncertainty metadata exists\n for ax in range(3):\n self.assertAlmostEqual(\n set(fc.metadata[\"pot_corr_uncertainty_md\"][ax].keys()),\n {\"potcorr\", \"stats\"},\n )\n\n # test a specified axis from entry\n fc = FreysoldtCorrection(15, axis=[1])\n val = fc.get_correction(de)\n self.assertAlmostEqual(val[\"freysoldt_potential_alignment\"], 5.2869010593283132)\n\n # test a different charge\n # for electrostatic correction\n es_corr = fc.perform_es_corr(struc.lattice, 2)\n self.assertAlmostEqual(es_corr, 0.43373)\n # for potential alignment method\n pot_corr = fc.perform_pot_corr(axisdata[0], bldata[0], dldata[0], struc.lattice, 2, vac.site.coords, 0)\n self.assertAlmostEqual(pot_corr, -2.1375685936497768)\n\n # test an input anisotropic dielectric constant\n fc = FreysoldtCorrection([[1.0, 2.0, 3.0], [0.0, 3.0, 5.0], [4.0, 10.0, 8.0]])\n self.assertAlmostEqual(fc.dielectric, 4.0)\n val = fc.get_correction(de)\n self.assertAlmostEqual(val[\"freysoldt_electrostatic\"], 3.659599)\n self.assertAlmostEqual(val[\"freysoldt_potential_alignment\"], 3.3605255195745087)\n\n # test potalign being added to defect entry\n self.assertAlmostEqual(de.parameters[\"potalign\"], 1.1201751731915028)\n\n # test that metadata entries exist in defect entry\n self.assertTrue(\"freysoldt_meta\" in de.parameters.keys())\n self.assertAlmostEqual(\n set(de.parameters[\"freysoldt_meta\"].keys()),\n {\"pot_plot_data\", \"pot_corr_uncertainty_md\"},\n )\n\n # test a charge of zero\n vac = Vacancy(struc, struc.sites[0], charge=0)\n de = DefectEntry(vac, 0.0, corrections={}, parameters=params, entry_id=None)\n val = fc.get_correction(de)\n self.assertAlmostEqual(val[\"freysoldt_electrostatic\"], 0.0)\n self.assertAlmostEqual(val[\"freysoldt_potential_alignment\"], 0.0)\n\n def test_kumagai(self):\n gamma = 0.19357221\n prec = 28\n lattice = Lattice([[4.692882, -8.12831, 0.0], [4.692882, 8.12831, 0.0], [0.0, 0.0, 10.03391]])\n\n # note that real/recip vector generation is not dependent on epsilon\n g_vecs, _, r_vecs, _ = generate_R_and_G_vecs(gamma, prec, lattice, 80.0 * np.identity(3))\n\n # test real space summation (bigger for large epsilon)\n kc_high_diel = KumagaiCorrection(80.0 * np.identity(3), gamma=gamma)\n real_sum = kc_high_diel.get_real_summation(gamma, r_vecs[0])\n self.assertAlmostEqual(real_sum, 0.00843104)\n\n # test recip space summation (bigger for small epsilon)\n kc_low_diel = KumagaiCorrection(0.1 * np.identity(3), gamma=gamma)\n recip_sum = kc_low_diel.get_recip_summation(gamma, g_vecs[0], lattice.volume)\n self.assertAlmostEqual(recip_sum, 0.31117099)\n\n # test self interaction\n si_corr = kc_low_diel.get_self_interaction(gamma)\n self.assertAlmostEqual(si_corr, -0.54965249)\n\n # test potenital shift interaction correction\n ps_corr = kc_low_diel.get_potential_shift(gamma, lattice.volume)\n self.assertAlmostEqual(ps_corr, -0.00871593)\n\n # \"\"\"Test Defect Entry approach to correction \"\"\"\n bulk_struc = Poscar.from_file(os.path.join(PymatgenTest.TEST_FILES_DIR, \"defect\", \"CONTCAR_bulk\")).structure\n bulk_out = Outcar(os.path.join(PymatgenTest.TEST_FILES_DIR, \"defect\", \"OUTCAR_bulk.gz\"))\n defect_out = Outcar(os.path.join(PymatgenTest.TEST_FILES_DIR, \"defect\", \"OUTCAR_vac_Ga_-3.gz\"))\n epsilon = 18.118 * np.identity(3)\n vac = Vacancy(bulk_struc, bulk_struc.sites[0], charge=-3)\n defect_structure = vac.generate_defect_structure()\n defect_frac_coords = [0.0, 0.0, 0.0]\n\n parameters = {\n \"bulk_atomic_site_averages\": bulk_out.electrostatic_potential,\n \"defect_atomic_site_averages\": defect_out.electrostatic_potential,\n \"site_matching_indices\": [[ind, ind - 1] for ind in range(len(bulk_struc))],\n \"initial_defect_structure\": defect_structure,\n \"defect_frac_sc_coords\": defect_frac_coords,\n }\n dentry = DefectEntry(vac, 0.0, parameters=parameters)\n kc = KumagaiCorrection(epsilon)\n kcorr = kc.get_correction(dentry)\n self.assertAlmostEqual(kcorr[\"kumagai_electrostatic\"], 0.88236299)\n self.assertAlmostEqual(kcorr[\"kumagai_potential_alignment\"], 2.09704862)\n\n # test ES correction\n high_diel_es_corr = kc_high_diel.perform_es_corr(gamma, prec, lattice, -3.0)\n self.assertAlmostEqual(high_diel_es_corr, 0.25176240)\n\n low_diel_es_corr = kc_low_diel.perform_es_corr(gamma, prec, lattice, -3.0)\n self.assertAlmostEqual(low_diel_es_corr, 201.28810966)\n\n # test pot correction\n site_list = []\n for bs_ind, ds_ind in dentry.parameters[\"site_matching_indices\"]:\n Vqb = -(defect_out.electrostatic_potential[ds_ind] - bulk_out.electrostatic_potential[bs_ind])\n site_list.append([defect_structure[ds_ind], Vqb])\n\n sampling_radius = dentry.parameters[\"kumagai_meta\"][\"sampling_radius\"]\n gamma = dentry.parameters[\"kumagai_meta\"][\"gamma\"]\n q = -3\n g_vecs, _, r_vecs, _ = generate_R_and_G_vecs(gamma, 28, defect_structure.lattice, np.identity(3))\n high_diel_pot_corr = kc_high_diel.perform_pot_corr(\n defect_structure,\n defect_frac_coords,\n site_list,\n sampling_radius,\n q,\n r_vecs[0],\n g_vecs[0],\n gamma,\n )\n self.assertAlmostEqual(high_diel_pot_corr, 2.35840716)\n low_diel_pot_corr = kc_low_diel.perform_pot_corr(\n defect_structure,\n defect_frac_coords,\n site_list,\n sampling_radius,\n q,\n r_vecs[0],\n g_vecs[0],\n gamma,\n )\n self.assertAlmostEqual(low_diel_pot_corr, -58.83598095)\n\n # test the kumagai plotter\n kcp = kc.plot()\n self.assertTrue(kcp)\n\n # check that uncertainty metadata exists\n self.assertAlmostEqual(\n set(kc.metadata[\"pot_corr_uncertainty_md\"].keys()),\n {\"number_sampled\", \"stats\"},\n )\n\n def test_bandfilling(self):\n v = Vasprun(os.path.join(PymatgenTest.TEST_FILES_DIR, \"vasprun.xml\"))\n eigenvalues = v.eigenvalues.copy()\n kptweights = v.actual_kpoints_weights\n potalign = 0.0\n vbm = v.eigenvalue_band_properties[2]\n cbm = v.eigenvalue_band_properties[1]\n defect_incar = v.incar\n params = {\n \"eigenvalues\": eigenvalues,\n \"kpoint_weights\": kptweights,\n \"potalign\": potalign,\n \"vbm\": vbm,\n \"cbm\": cbm,\n \"run_metadata\": {\"defect_incar\": defect_incar},\n }\n bfc = BandFillingCorrection()\n struc = PymatgenTest.get_structure(\"VO2\")\n struc.make_supercell(3)\n vac = Vacancy(struc, struc.sites[0], charge=-3)\n\n # test trivial performing bandfilling correction\n bf_corr = bfc.perform_bandfill_corr(eigenvalues, kptweights, potalign, vbm, cbm)\n self.assertAlmostEqual(bf_corr, 0.0)\n self.assertFalse(bfc.metadata[\"num_elec_cbm\"])\n self.assertFalse(bfc.metadata[\"num_hole_vbm\"])\n self.assertFalse(bfc.metadata[\"potalign\"])\n\n # test trivial full entry bandfill evaluation\n de = DefectEntry(vac, 0.0, corrections={}, parameters=params, entry_id=None)\n\n corr = bfc.get_correction(de)\n self.assertAlmostEqual(corr[\"bandfilling_correction\"], 0.0)\n\n # modify the eigenvalue list to have free holes\n hole_eigenvalues = {}\n for spinkey, spinset in eigenvalues.items():\n hole_eigenvalues[spinkey] = []\n for kptset in spinset:\n hole_eigenvalues[spinkey].append([])\n for eig in kptset:\n if (eig[0] < vbm) and (eig[0] > vbm - 0.8):\n hole_eigenvalues[spinkey][-1].append([eig[0], 0.5])\n else:\n hole_eigenvalues[spinkey][-1].append(eig)\n\n hole_bf_corr = bfc.perform_bandfill_corr(hole_eigenvalues, kptweights, potalign, vbm, cbm)\n self.assertAlmostEqual(hole_bf_corr, -0.41138336)\n self.assertAlmostEqual(bfc.metadata[\"num_hole_vbm\"], 0.8125000649)\n self.assertFalse(bfc.metadata[\"num_elec_cbm\"])\n\n # test case with only one spin and eigen-occupations are 1.\n one_spin_eigen = hole_eigenvalues.copy()\n del one_spin_eigen[list(eigenvalues.keys())[0]]\n bf_corr = bfc.perform_bandfill_corr(one_spin_eigen, kptweights, potalign, vbm, cbm)\n self.assertAlmostEqual(bf_corr, -0.14487501159000005)\n\n # test case with only one spin and eigen-occupations are 2.\n one_spin_eigen_twooccu = one_spin_eigen.copy()\n for kptset in one_spin_eigen_twooccu.values():\n for bandset in kptset:\n for occuset in bandset:\n if occuset[1] == 1.0:\n occuset[1] = 2.0\n elif occuset[1] == 0.5:\n occuset[1] = 1.0\n bf_corr = bfc.perform_bandfill_corr(one_spin_eigen_twooccu, kptweights, potalign, vbm, cbm)\n self.assertAlmostEqual(bf_corr, -0.14487501159000005)\n\n def test_bandedgeshifting(self):\n struc = PymatgenTest.get_structure(\"VO2\")\n struc.make_supercell(3)\n struc = struc\n vac = Vacancy(struc, struc.sites[0], charge=-3)\n\n besc = BandEdgeShiftingCorrection()\n params = {\"hybrid_cbm\": 1.0, \"hybrid_vbm\": -1.0, \"vbm\": -0.5, \"cbm\": 0.6}\n de = DefectEntry(vac, 0.0, corrections={}, parameters=params, entry_id=None)\n\n corr = besc.get_correction(de)\n self.assertEqual(corr[\"bandedgeshifting_correction\"], 1.5)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n", "# Copyright (c) Pymatgen Development Team.\n# Distributed under the terms of the MIT License.\n\n\"\"\"\nThis module implements classes and methods for processing LAMMPS output\nfiles (log and dump).\n\"\"\"\n\n\nimport glob\nimport re\nfrom io import StringIO\n\nimport numpy as np\nimport pandas as pd\nfrom monty.io import zopen\nfrom monty.json import MSONable\n\nfrom pymatgen.io.lammps.data import LammpsBox\n\n__author__ = \"Kiran Mathew, Zhi Deng\"\n__copyright__ = \"Copyright 2018, The Materials Virtual Lab\"\n__version__ = \"1.0\"\n__maintainer__ = \"Zhi Deng\"\n__email__ = \"[email protected]\"\n__date__ = \"Aug 1, 2018\"\n\n\nclass LammpsDump(MSONable):\n \"\"\"\n Object for representing dump data for a single snapshot.\n \"\"\"\n\n def __init__(self, timestep, natoms, box, data):\n \"\"\"\n Base constructor.\n\n Args:\n timestep (int): Current timestep.\n natoms (int): Total number of atoms in the box.\n box (LammpsBox): Simulation box.\n data (pd.DataFrame): Dumped atomic data.\n\n \"\"\"\n self.timestep = timestep\n self.natoms = natoms\n self.box = box\n self.data = data\n\n @classmethod\n def from_string(cls, string):\n \"\"\"\n Constructor from string parsing.\n\n Args:\n string (str): Input string.\n\n \"\"\"\n lines = string.split(\"\\n\")\n timestep = int(lines[1])\n natoms = int(lines[3])\n box_arr = np.loadtxt(StringIO(\"\\n\".join(lines[5:8])))\n bounds = box_arr[:, :2]\n tilt = None\n if \"xy xz yz\" in lines[4]:\n tilt = box_arr[:, 2]\n x = (0, tilt[0], tilt[1], tilt[0] + tilt[1])\n y = (0, tilt[2])\n bounds -= np.array([[min(x), max(x)], [min(y), max(y)], [0, 0]])\n box = LammpsBox(bounds, tilt)\n data_head = lines[8].replace(\"ITEM: ATOMS\", \"\").split()\n data = pd.read_csv(StringIO(\"\\n\".join(lines[9:])), names=data_head, delim_whitespace=True)\n return cls(timestep, natoms, box, data)\n\n @classmethod\n def from_dict(cls, d):\n \"\"\"\n Args:\n d (dict): Dict representation\n\n Returns:\n LammpsDump\n \"\"\"\n items = {\"timestep\": d[\"timestep\"], \"natoms\": d[\"natoms\"]}\n items[\"box\"] = LammpsBox.from_dict(d[\"box\"])\n items[\"data\"] = pd.read_json(d[\"data\"], orient=\"split\")\n return cls(**items)\n\n def as_dict(self):\n \"\"\"\n Returns: MSONable dict\n \"\"\"\n d = {}\n d[\"@module\"] = self.__class__.__module__\n d[\"@class\"] = self.__class__.__name__\n d[\"timestep\"] = self.timestep\n d[\"natoms\"] = self.natoms\n d[\"box\"] = self.box.as_dict()\n d[\"data\"] = self.data.to_json(orient=\"split\")\n return d\n\n\ndef parse_lammps_dumps(file_pattern):\n \"\"\"\n Generator that parses dump file(s).\n\n Args:\n file_pattern (str): Filename to parse. The timestep wildcard\n (e.g., dump.atom.'*') is supported and the files are parsed\n in the sequence of timestep.\n\n Yields:\n LammpsDump for each available snapshot.\n\n \"\"\"\n files = glob.glob(file_pattern)\n if len(files) > 1:\n pattern = r\"%s\" % file_pattern.replace(\"*\", \"([0-9]+)\")\n pattern = pattern.replace(\"\\\\\", \"\\\\\\\\\")\n files = sorted(files, key=lambda f: int(re.match(pattern, f).group(1)))\n\n for fname in files:\n with zopen(fname, \"rt\") as f:\n dump_cache = []\n for line in f:\n if line.startswith(\"ITEM: TIMESTEP\"):\n if len(dump_cache) > 0:\n yield LammpsDump.from_string(\"\".join(dump_cache))\n dump_cache = [line]\n else:\n dump_cache.append(line)\n yield LammpsDump.from_string(\"\".join(dump_cache))\n\n\ndef parse_lammps_log(filename=\"log.lammps\"):\n \"\"\"\n Parses log file with focus on thermo data. Both one and multi line\n formats are supported. Any incomplete runs (no \"Loop time\" marker)\n will not be parsed.\n\n Notes:\n SHAKE stats printed with thermo data are not supported yet.\n They are ignored in multi line format, while they may cause\n issues with dataframe parsing in one line format.\n\n Args:\n filename (str): Filename to parse.\n\n Returns:\n [pd.DataFrame] containing thermo data for each completed run.\n\n \"\"\"\n with zopen(filename, \"rt\") as f:\n lines = f.readlines()\n begin_flag = (\n \"Memory usage per processor =\",\n \"Per MPI rank memory allocation (min/avg/max) =\",\n )\n end_flag = \"Loop time of\"\n begins, ends = [], []\n for i, l in enumerate(lines):\n if l.startswith(begin_flag):\n begins.append(i)\n elif l.startswith(end_flag):\n ends.append(i)\n\n def _parse_thermo(lines):\n multi_pattern = r\"-+\\s+Step\\s+([0-9]+)\\s+-+\"\n # multi line thermo data\n if re.match(multi_pattern, lines[0]):\n timestep_marks = [i for i, l in enumerate(lines) if re.match(multi_pattern, l)]\n timesteps = np.split(lines, timestep_marks)[1:]\n dicts = []\n kv_pattern = r\"([0-9A-Za-z_\\[\\]]+)\\s+=\\s+([0-9eE\\.+-]+)\"\n for ts in timesteps:\n data = {}\n data[\"Step\"] = int(re.match(multi_pattern, ts[0]).group(1))\n data.update({k: float(v) for k, v in re.findall(kv_pattern, \"\".join(ts[1:]))})\n dicts.append(data)\n df = pd.DataFrame(dicts)\n # rearrange the sequence of columns\n columns = [\"Step\"] + [k for k, v in re.findall(kv_pattern, \"\".join(timesteps[0][1:]))]\n df = df[columns]\n # one line thermo data\n else:\n df = pd.read_csv(StringIO(\"\".join(lines)), delim_whitespace=True)\n return df\n\n runs = []\n for b, e in zip(begins, ends):\n runs.append(_parse_thermo(lines[b + 1 : e]))\n return runs\n", "# Copyright (c) Pymatgen Development Team.\n# Distributed under the terms of the MIT License.\n\n\"\"\"\nThis module provides classes for calculating the ewald sum of a structure.\n\"\"\"\n\nimport bisect\nfrom copy import copy, deepcopy\nfrom datetime import datetime\nfrom math import log, pi, sqrt\nfrom typing import Dict\nfrom warnings import warn\n\nimport numpy as np\nfrom monty.json import MSONable\nfrom scipy import constants\nfrom scipy.special import comb, erfc\n\nfrom pymatgen.core.structure import Structure\n\n__author__ = \"Shyue Ping Ong, William Davidson Richard\"\n__copyright__ = \"Copyright 2011, The Materials Project\"\n__credits__ = \"Christopher Fischer\"\n__version__ = \"1.0\"\n__maintainer__ = \"Shyue Ping Ong\"\n__email__ = \"[email protected]\"\n__status__ = \"Production\"\n__date__ = \"Aug 1 2012\"\n\n\nclass EwaldSummation(MSONable):\n \"\"\"\n Calculates the electrostatic energy of a periodic array of charges using\n the Ewald technique.\n\n\n Ref:\n Ewald summation techniques in perspective: a survey\n Abdulnour Y. Toukmaji and John A. Board Jr.\n DOI: 10.1016/0010-4655(96)00016-1\n URL: http://www.ee.duke.edu/~ayt/ewaldpaper/ewaldpaper.html\n\n This matrix can be used to do fast calculations of ewald sums after species\n removal.\n\n E = E_recip + E_real + E_point\n\n Atomic units used in the code, then converted to eV.\n \"\"\"\n\n # Converts unit of q*q/r into eV\n CONV_FACT = 1e10 * constants.e / (4 * pi * constants.epsilon_0)\n\n def __init__(\n self,\n structure,\n real_space_cut=None,\n recip_space_cut=None,\n eta=None,\n acc_factor=12.0,\n w=1 / sqrt(2),\n compute_forces=False,\n ):\n \"\"\"\n Initializes and calculates the Ewald sum. Default convergence\n parameters have been specified, but you can override them if you wish.\n\n Args:\n structure (Structure): Input structure that must have proper\n Species on all sites, i.e. Element with oxidation state. Use\n Structure.add_oxidation_state... for example.\n real_space_cut (float): Real space cutoff radius dictating how\n many terms are used in the real space sum. Defaults to None,\n which means determine automagically using the formula given\n in gulp 3.1 documentation.\n recip_space_cut (float): Reciprocal space cutoff radius.\n Defaults to None, which means determine automagically using\n the formula given in gulp 3.1 documentation.\n eta (float): The screening parameter. Defaults to None, which means\n determine automatically.\n acc_factor (float): No. of significant figures each sum is\n converged to.\n w (float): Weight parameter, w, has been included that represents\n the relative computational expense of calculating a term in\n real and reciprocal space. Default of 0.7 reproduces result\n similar to GULP 4.2. This has little effect on the total\n energy, but may influence speed of computation in large\n systems. Note that this parameter is used only when the\n cutoffs are set to None.\n compute_forces (bool): Whether to compute forces. False by\n default since it is usually not needed.\n \"\"\"\n self._s = structure\n self._charged = abs(structure.charge) > 1e-8\n self._vol = structure.volume\n self._compute_forces = compute_forces\n\n self._acc_factor = acc_factor\n # set screening length\n self._eta = eta if eta else (len(structure) * w / (self._vol ** 2)) ** (1 / 3) * pi\n self._sqrt_eta = sqrt(self._eta)\n\n # acc factor used to automatically determine the optimal real and\n # reciprocal space cutoff radii\n self._accf = sqrt(log(10 ** acc_factor))\n\n self._rmax = real_space_cut if real_space_cut else self._accf / self._sqrt_eta\n self._gmax = recip_space_cut if recip_space_cut else 2 * self._sqrt_eta * self._accf\n\n # The next few lines pre-compute certain quantities and store them.\n # Ewald summation is rather expensive, and these shortcuts are\n # necessary to obtain several factors of improvement in speedup.\n self._oxi_states = [compute_average_oxidation_state(site) for site in structure]\n\n self._coords = np.array(self._s.cart_coords)\n\n # Define the private attributes to lazy compute reciprocal and real\n # space terms.\n self._initialized = False\n self._recip = None\n self._real, self._point = None, None\n self._forces = None\n\n # Compute the correction for a charged cell\n self._charged_cell_energy = (\n -EwaldSummation.CONV_FACT / 2 * np.pi / structure.volume / self._eta * structure.charge ** 2\n )\n\n def compute_partial_energy(self, removed_indices):\n \"\"\"\n Gives total ewald energy for certain sites being removed, i.e. zeroed\n out.\n \"\"\"\n total_energy_matrix = self.total_energy_matrix.copy()\n for i in removed_indices:\n total_energy_matrix[i, :] = 0\n total_energy_matrix[:, i] = 0\n return sum(sum(total_energy_matrix))\n\n def compute_sub_structure(self, sub_structure, tol=1e-3):\n \"\"\"\n Gives total ewald energy for an sub structure in the same\n lattice. The sub_structure must be a subset of the original\n structure, with possible different charges.\n\n Args:\n substructure (Structure): Substructure to compute Ewald sum for.\n tol (float): Tolerance for site matching in fractional coordinates.\n\n Returns:\n Ewald sum of substructure.\n \"\"\"\n total_energy_matrix = self.total_energy_matrix.copy()\n\n def find_match(site):\n for test_site in sub_structure:\n frac_diff = abs(np.array(site.frac_coords) - np.array(test_site.frac_coords)) % 1\n frac_diff = [abs(a) < tol or abs(a) > 1 - tol for a in frac_diff]\n if all(frac_diff):\n return test_site\n return None\n\n matches = []\n for i, site in enumerate(self._s):\n matching_site = find_match(site)\n if matching_site:\n new_charge = compute_average_oxidation_state(matching_site)\n old_charge = self._oxi_states[i]\n scaling_factor = new_charge / old_charge\n matches.append(matching_site)\n else:\n scaling_factor = 0\n total_energy_matrix[i, :] *= scaling_factor\n total_energy_matrix[:, i] *= scaling_factor\n\n if len(matches) != len(sub_structure):\n output = [\"Missing sites.\"]\n for site in sub_structure:\n if site not in matches:\n output.append(f\"unmatched = {site}\")\n raise ValueError(\"\\n\".join(output))\n\n return sum(sum(total_energy_matrix))\n\n @property\n def reciprocal_space_energy(self):\n \"\"\"\n The reciprocal space energy.\n \"\"\"\n if not self._initialized:\n self._calc_ewald_terms()\n self._initialized = True\n return sum(sum(self._recip))\n\n @property\n def reciprocal_space_energy_matrix(self):\n \"\"\"\n The reciprocal space energy matrix. Each matrix element (i, j)\n corresponds to the interaction energy between site i and site j in\n reciprocal space.\n \"\"\"\n if not self._initialized:\n self._calc_ewald_terms()\n self._initialized = True\n return self._recip\n\n @property\n def real_space_energy(self):\n \"\"\"\n The real space space energy.\n \"\"\"\n if not self._initialized:\n self._calc_ewald_terms()\n self._initialized = True\n return sum(sum(self._real))\n\n @property\n def real_space_energy_matrix(self):\n \"\"\"\n The real space energy matrix. Each matrix element (i, j) corresponds to\n the interaction energy between site i and site j in real space.\n \"\"\"\n if not self._initialized:\n self._calc_ewald_terms()\n self._initialized = True\n return self._real\n\n @property\n def point_energy(self):\n \"\"\"\n The point energy.\n \"\"\"\n if not self._initialized:\n self._calc_ewald_terms()\n self._initialized = True\n return sum(self._point)\n\n @property\n def point_energy_matrix(self):\n \"\"\"\n The point space matrix. A diagonal matrix with the point terms for each\n site in the diagonal elements.\n \"\"\"\n if not self._initialized:\n self._calc_ewald_terms()\n self._initialized = True\n return self._point\n\n @property\n def total_energy(self):\n \"\"\"\n The total energy.\n \"\"\"\n if not self._initialized:\n self._calc_ewald_terms()\n self._initialized = True\n return sum(sum(self._recip)) + sum(sum(self._real)) + sum(self._point) + self._charged_cell_energy\n\n @property\n def total_energy_matrix(self):\n \"\"\"\n The total energy matrix. Each matrix element (i, j) corresponds to the\n total interaction energy between site i and site j.\n\n Note that this does not include the charged-cell energy, which is only important\n when the simulation cell is not charge balanced.\n \"\"\"\n if not self._initialized:\n self._calc_ewald_terms()\n self._initialized = True\n\n totalenergy = self._recip + self._real\n for i, energy in enumerate(self._point):\n totalenergy[i, i] += energy\n return totalenergy\n\n @property\n def forces(self):\n \"\"\"\n The forces on each site as a Nx3 matrix. Each row corresponds to a\n site.\n \"\"\"\n if not self._initialized:\n self._calc_ewald_terms()\n self._initialized = True\n\n if not self._compute_forces:\n raise AttributeError(\"Forces are available only if compute_forces is True!\")\n return self._forces\n\n def get_site_energy(self, site_index):\n \"\"\"Compute the energy for a single site in the structure\n\n Args:\n site_index (int): Index of site\n ReturnS:\n (float) - Energy of that site\"\"\"\n if not self._initialized:\n self._calc_ewald_terms()\n self._initialized = True\n\n if self._charged:\n warn(\"Per atom energies for charged structures not supported in EwaldSummation\")\n return np.sum(self._recip[:, site_index]) + np.sum(self._real[:, site_index]) + self._point[site_index]\n\n def _calc_ewald_terms(self):\n \"\"\"\n Calculates and sets all ewald terms (point, real and reciprocal)\n \"\"\"\n self._recip, recip_forces = self._calc_recip()\n self._real, self._point, real_point_forces = self._calc_real_and_point()\n if self._compute_forces:\n self._forces = recip_forces + real_point_forces\n\n def _calc_recip(self):\n \"\"\"\n Perform the reciprocal space summation. Calculates the quantity\n E_recip = 1/(2PiV) sum_{G < Gmax} exp(-(G.G/4/eta))/(G.G) S(G)S(-G)\n where\n S(G) = sum_{k=1,N} q_k exp(-i G.r_k)\n S(G)S(-G) = |S(G)|**2\n\n This method is heavily vectorized to utilize numpy's C backend for\n speed.\n \"\"\"\n numsites = self._s.num_sites\n prefactor = 2 * pi / self._vol\n erecip = np.zeros((numsites, numsites), dtype=np.float_)\n forces = np.zeros((numsites, 3), dtype=np.float_)\n coords = self._coords\n rcp_latt = self._s.lattice.reciprocal_lattice\n recip_nn = rcp_latt.get_points_in_sphere([[0, 0, 0]], [0, 0, 0], self._gmax)\n\n frac_coords = [fcoords for (fcoords, dist, i, img) in recip_nn if dist != 0]\n\n gs = rcp_latt.get_cartesian_coords(frac_coords)\n g2s = np.sum(gs ** 2, 1)\n expvals = np.exp(-g2s / (4 * self._eta))\n grs = np.sum(gs[:, None] * coords[None, :], 2)\n\n oxistates = np.array(self._oxi_states)\n\n # create array where q_2[i,j] is qi * qj\n qiqj = oxistates[None, :] * oxistates[:, None]\n\n # calculate the structure factor\n sreals = np.sum(oxistates[None, :] * np.cos(grs), 1)\n simags = np.sum(oxistates[None, :] * np.sin(grs), 1)\n\n for g, g2, gr, expval, sreal, simag in zip(gs, g2s, grs, expvals, sreals, simags):\n\n # Uses the identity sin(x)+cos(x) = 2**0.5 sin(x + pi/4)\n m = (gr[None, :] + pi / 4) - gr[:, None]\n np.sin(m, m)\n m *= expval / g2\n\n erecip += m\n\n if self._compute_forces:\n pref = 2 * expval / g2 * oxistates\n factor = prefactor * pref * (sreal * np.sin(gr) - simag * np.cos(gr))\n\n forces += factor[:, None] * g[None, :]\n\n forces *= EwaldSummation.CONV_FACT\n erecip *= prefactor * EwaldSummation.CONV_FACT * qiqj * 2 ** 0.5\n return erecip, forces\n\n def _calc_real_and_point(self):\n \"\"\"\n Determines the self energy -(eta/pi)**(1/2) * sum_{i=1}^{N} q_i**2\n \"\"\"\n fcoords = self._s.frac_coords\n forcepf = 2.0 * self._sqrt_eta / sqrt(pi)\n coords = self._coords\n numsites = self._s.num_sites\n ereal = np.empty((numsites, numsites), dtype=np.float_)\n\n forces = np.zeros((numsites, 3), dtype=np.float_)\n\n qs = np.array(self._oxi_states)\n\n epoint = -(qs ** 2) * sqrt(self._eta / pi)\n\n for i in range(numsites):\n nfcoords, rij, js, _ = self._s.lattice.get_points_in_sphere(\n fcoords, coords[i], self._rmax, zip_results=False\n )\n\n # remove the rii term\n inds = rij > 1e-8\n js = js[inds]\n rij = rij[inds]\n nfcoords = nfcoords[inds]\n\n qi = qs[i]\n qj = qs[js]\n\n erfcval = erfc(self._sqrt_eta * rij)\n new_ereals = erfcval * qi * qj / rij\n\n # insert new_ereals\n for k in range(numsites):\n ereal[k, i] = np.sum(new_ereals[js == k])\n\n if self._compute_forces:\n nccoords = self._s.lattice.get_cartesian_coords(nfcoords)\n\n fijpf = qj / rij ** 3 * (erfcval + forcepf * rij * np.exp(-self._eta * rij ** 2))\n forces[i] += np.sum(\n np.expand_dims(fijpf, 1) * (np.array([coords[i]]) - nccoords) * qi * EwaldSummation.CONV_FACT,\n axis=0,\n )\n\n ereal *= 0.5 * EwaldSummation.CONV_FACT\n epoint *= EwaldSummation.CONV_FACT\n return ereal, epoint, forces\n\n @property\n def eta(self):\n \"\"\"\n Returns: eta value used in Ewald summation.\n \"\"\"\n return self._eta\n\n def __str__(self):\n if self._compute_forces:\n output = [\n \"Real = \" + str(self.real_space_energy),\n \"Reciprocal = \" + str(self.reciprocal_space_energy),\n \"Point = \" + str(self.point_energy),\n \"Total = \" + str(self.total_energy),\n \"Forces:\\n\" + str(self.forces),\n ]\n else:\n output = [\n \"Real = \" + str(self.real_space_energy),\n \"Reciprocal = \" + str(self.reciprocal_space_energy),\n \"Point = \" + str(self.point_energy),\n \"Total = \" + str(self.total_energy),\n \"Forces were not computed\",\n ]\n return \"\\n\".join(output)\n\n def as_dict(self, verbosity: int = 0) -> Dict:\n \"\"\"\n Json-serialization dict representation of EwaldSummation.\n\n Args:\n verbosity (int): Verbosity level. Default of 0 only includes the\n matrix representation. Set to 1 for more details.\n \"\"\"\n\n d = {\n \"@module\": self.__class__.__module__,\n \"@class\": self.__class__.__name__,\n \"structure\": self._s.as_dict(),\n \"compute_forces\": self._compute_forces,\n \"eta\": self._eta,\n \"acc_factor\": self._acc_factor,\n \"real_space_cut\": self._rmax,\n \"recip_space_cut\": self._gmax,\n \"_recip\": None if self._recip is None else self._recip.tolist(),\n \"_real\": None if self._real is None else self._real.tolist(),\n \"_point\": None if self._point is None else self._point.tolist(),\n \"_forces\": None if self._forces is None else self._forces.tolist(),\n }\n\n return d\n\n @classmethod\n def from_dict(cls, d: Dict, fmt: str = None, **kwargs) -> \"EwaldSummation\":\n \"\"\"Create an EwaldSummation instance from JSON serialized dictionary.\n\n Args:\n d (Dict): Dictionary representation\n fmt (str, optional): Unused. Defaults to None.\n\n Returns:\n EwaldSummation: class instance\n \"\"\"\n summation = cls(\n structure=Structure.from_dict(d[\"structure\"]),\n real_space_cut=d[\"real_space_cut\"],\n recip_space_cut=d[\"recip_space_cut\"],\n eta=d[\"eta\"],\n acc_factor=d[\"acc_factor\"],\n compute_forces=d[\"compute_forces\"],\n )\n\n # set previously computed private attributes\n if d[\"_recip\"] is not None:\n summation._recip = np.array(d[\"_recip\"])\n summation._real = np.array(d[\"_real\"])\n summation._point = np.array(d[\"_point\"])\n summation._forces = np.array(d[\"_forces\"])\n summation._initialized = True\n\n return summation\n\n\nclass EwaldMinimizer:\n \"\"\"\n This class determines the manipulations that will minimize an ewald matrix,\n given a list of possible manipulations. This class does not perform the\n manipulations on a structure, but will return the list of manipulations\n that should be done on one to produce the minimal structure. It returns the\n manipulations for the n lowest energy orderings. This class should be used\n to perform fractional species substitution or fractional species removal to\n produce a new structure. These manipulations create large numbers of\n candidate structures, and this class can be used to pick out those with the\n lowest ewald sum.\n\n An alternative (possibly more intuitive) interface to this class is the\n order disordered structure transformation.\n\n Author - Will Richards\n \"\"\"\n\n ALGO_FAST = 0\n ALGO_COMPLETE = 1\n ALGO_BEST_FIRST = 2\n\n \"\"\"\n ALGO_TIME_LIMIT: Slowly increases the speed (with the cost of decreasing\n accuracy) as the minimizer runs. Attempts to limit the run time to\n approximately 30 minutes.\n \"\"\"\n ALGO_TIME_LIMIT = 3\n\n def __init__(self, matrix, m_list, num_to_return=1, algo=ALGO_FAST):\n \"\"\"\n Args:\n matrix: A matrix of the ewald sum interaction energies. This is stored\n in the class as a diagonally symmetric array and so\n self._matrix will not be the same as the input matrix.\n m_list: list of manipulations. each item is of the form\n (multiplication fraction, number_of_indices, indices, species)\n These are sorted such that the first manipulation contains the\n most permutations. this is actually evaluated last in the\n recursion since I'm using pop.\n num_to_return: The minimizer will find the number_returned lowest\n energy structures. This is likely to return a number of duplicate\n structures so it may be necessary to overestimate and then\n remove the duplicates later. (duplicate checking in this\n process is extremely expensive)\n \"\"\"\n # Setup and checking of inputs\n self._matrix = copy(matrix)\n # Make the matrix diagonally symmetric (so matrix[i,:] == matrix[:,j])\n for i in range(len(self._matrix)):\n for j in range(i, len(self._matrix)):\n value = (self._matrix[i, j] + self._matrix[j, i]) / 2\n self._matrix[i, j] = value\n self._matrix[j, i] = value\n\n # sort the m_list based on number of permutations\n self._m_list = sorted(m_list, key=lambda x: comb(len(x[2]), x[1]), reverse=True)\n\n for mlist in self._m_list:\n if mlist[0] > 1:\n raise ValueError(\"multiplication fractions must be <= 1\")\n self._current_minimum = float(\"inf\")\n self._num_to_return = num_to_return\n self._algo = algo\n if algo == EwaldMinimizer.ALGO_COMPLETE:\n raise NotImplementedError(\"Complete algo not yet implemented for EwaldMinimizer\")\n\n self._output_lists = []\n # Tag that the recurse function looks at at each level. If a method\n # sets this to true it breaks the recursion and stops the search.\n self._finished = False\n\n self._start_time = datetime.utcnow()\n\n self.minimize_matrix()\n\n self._best_m_list = self._output_lists[0][1]\n self._minimized_sum = self._output_lists[0][0]\n\n def minimize_matrix(self):\n \"\"\"\n This method finds and returns the permutations that produce the lowest\n ewald sum calls recursive function to iterate through permutations\n \"\"\"\n if self._algo in (EwaldMinimizer.ALGO_FAST, EwaldMinimizer.ALGO_BEST_FIRST):\n return self._recurse(self._matrix, self._m_list, set(range(len(self._matrix))))\n return None\n\n def add_m_list(self, matrix_sum, m_list):\n \"\"\"\n This adds an m_list to the output_lists and updates the current\n minimum if the list is full.\n \"\"\"\n if self._output_lists is None:\n self._output_lists = [[matrix_sum, m_list]]\n else:\n bisect.insort(self._output_lists, [matrix_sum, m_list])\n if self._algo == EwaldMinimizer.ALGO_BEST_FIRST and len(self._output_lists) == self._num_to_return:\n self._finished = True\n if len(self._output_lists) > self._num_to_return:\n self._output_lists.pop()\n if len(self._output_lists) == self._num_to_return:\n self._current_minimum = self._output_lists[-1][0]\n\n def best_case(self, matrix, m_list, indices_left):\n \"\"\"\n Computes a best case given a matrix and manipulation list.\n\n Args:\n matrix: the current matrix (with some permutations already\n performed)\n m_list: [(multiplication fraction, number_of_indices, indices,\n species)] describing the manipulation\n indices: Set of indices which haven't had a permutation\n performed on them.\n \"\"\"\n m_indices = []\n fraction_list = []\n for m in m_list:\n m_indices.extend(m[2])\n fraction_list.extend([m[0]] * m[1])\n\n indices = list(indices_left.intersection(m_indices))\n\n interaction_matrix = matrix[indices, :][:, indices]\n\n fractions = np.zeros(len(interaction_matrix)) + 1\n fractions[: len(fraction_list)] = fraction_list\n fractions = np.sort(fractions)\n\n # Sum associated with each index (disregarding interactions between\n # indices)\n sums = 2 * np.sum(matrix[indices], axis=1)\n sums = np.sort(sums)\n\n # Interaction corrections. Can be reduced to (1-x)(1-y) for x,y in\n # fractions each element in a column gets multiplied by (1-x), and then\n # the sum of the columns gets multiplied by (1-y) since fractions are\n # less than 1, there is no effect of one choice on the other\n step1 = np.sort(interaction_matrix) * (1 - fractions)\n step2 = np.sort(np.sum(step1, axis=1))\n step3 = step2 * (1 - fractions)\n interaction_correction = np.sum(step3)\n\n if self._algo == self.ALGO_TIME_LIMIT:\n elapsed_time = datetime.utcnow() - self._start_time\n speedup_parameter = elapsed_time.total_seconds() / 1800\n avg_int = np.sum(interaction_matrix, axis=None)\n avg_frac = np.average(np.outer(1 - fractions, 1 - fractions))\n average_correction = avg_int * avg_frac\n\n interaction_correction = average_correction * speedup_parameter + interaction_correction * (\n 1 - speedup_parameter\n )\n\n best_case = np.sum(matrix) + np.inner(sums[::-1], fractions - 1) + interaction_correction\n\n return best_case\n\n @classmethod\n def get_next_index(cls, matrix, manipulation, indices_left):\n \"\"\"\n Returns an index that should have the most negative effect on the\n matrix sum\n \"\"\"\n # pylint: disable=E1126\n f = manipulation[0]\n indices = list(indices_left.intersection(manipulation[2]))\n sums = np.sum(matrix[indices], axis=1)\n if f < 1:\n next_index = indices[sums.argmax(axis=0)]\n else:\n next_index = indices[sums.argmin(axis=0)]\n\n return next_index\n\n def _recurse(self, matrix, m_list, indices, output_m_list=[]):\n \"\"\"\n This method recursively finds the minimal permutations using a binary\n tree search strategy.\n\n Args:\n matrix: The current matrix (with some permutations already\n performed).\n m_list: The list of permutations still to be performed\n indices: Set of indices which haven't had a permutation\n performed on them.\n \"\"\"\n # check to see if we've found all the solutions that we need\n if self._finished:\n return\n\n # if we're done with the current manipulation, pop it off.\n while m_list[-1][1] == 0:\n m_list = copy(m_list)\n m_list.pop()\n # if there are no more manipulations left to do check the value\n if not m_list:\n matrix_sum = np.sum(matrix)\n if matrix_sum < self._current_minimum:\n self.add_m_list(matrix_sum, output_m_list)\n return\n\n # if we wont have enough indices left, return\n if m_list[-1][1] > len(indices.intersection(m_list[-1][2])):\n return\n\n if len(m_list) == 1 or m_list[-1][1] > 1:\n if self.best_case(matrix, m_list, indices) > self._current_minimum:\n return\n\n index = self.get_next_index(matrix, m_list[-1], indices)\n\n m_list[-1][2].remove(index)\n\n # Make the matrix and new m_list where we do the manipulation to the\n # index that we just got\n matrix2 = np.copy(matrix)\n m_list2 = deepcopy(m_list)\n output_m_list2 = copy(output_m_list)\n\n matrix2[index, :] *= m_list[-1][0]\n matrix2[:, index] *= m_list[-1][0]\n output_m_list2.append([index, m_list[-1][3]])\n indices2 = copy(indices)\n indices2.remove(index)\n m_list2[-1][1] -= 1\n\n # recurse through both the modified and unmodified matrices\n\n self._recurse(matrix2, m_list2, indices2, output_m_list2)\n self._recurse(matrix, m_list, indices, output_m_list)\n\n @property\n def best_m_list(self):\n \"\"\"\n Returns: Best m_list found.\n \"\"\"\n return self._best_m_list\n\n @property\n def minimized_sum(self):\n \"\"\"\n Returns: Minimized sum\n \"\"\"\n return self._minimized_sum\n\n @property\n def output_lists(self):\n \"\"\"\n Returns: output lists.\n \"\"\"\n return self._output_lists\n\n\ndef compute_average_oxidation_state(site):\n \"\"\"\n Calculates the average oxidation state of a site\n\n Args:\n site: Site to compute average oxidation state\n\n Returns:\n Average oxidation state of site.\n \"\"\"\n try:\n avg_oxi = sum(sp.oxi_state * occu for sp, occu in site.species.items() if sp is not None)\n return avg_oxi\n except AttributeError:\n pass\n try:\n return site.charge\n except AttributeError:\n raise ValueError(\n \"Ewald summation can only be performed on structures \"\n \"that are either oxidation state decorated or have \"\n \"site charges.\"\n )\n", "# Copyright (c) Pymatgen Development Team.\n# Distributed under the terms of the MIT License.\n\n\nimport os\nimport unittest\n\nimport numpy as np\n\nfrom pymatgen.analysis.defects.core import (\n DefectEntry,\n Interstitial,\n Substitution,\n Vacancy,\n create_saturated_interstitial_structure,\n)\nfrom pymatgen.core import Structure\nfrom pymatgen.core.sites import PeriodicSite\nfrom pymatgen.util.testing import PymatgenTest\n\n\nclass DefectsCoreTest(PymatgenTest):\n def test_supercell_lattice_mismatch(self):\n struct = Structure.from_file(os.path.join(self.TEST_FILES_DIR, \"POSCAR.CdS_HSE\"))\n\n import tempfile\n\n with tempfile.TemporaryDirectory() as tmpdir:\n struct.to(\"poscar\", os.path.join(tmpdir, \"POSCAR_copy\"))\n struct_copy = Structure.from_file(os.path.join(tmpdir, \"POSCAR_copy\"))\n self.assertEqual(struct.lattice, struct_copy.lattice)\n\n # The default lattice match doesn't work for supercells routinely\n # created in defects modeling especially with pymatgen's rounding\n # when writing structure objects to POSCAR files\n struct.make_supercell([4, 4, 2])\n struct_copy.make_supercell([4, 4, 2])\n self.assertNotEqual(struct.lattice, struct_copy.lattice)\n\n # Looser absolute tolerance for defect supercells\n lattice_match = np.allclose(struct.lattice.matrix, struct_copy.lattice.matrix, atol=1e-5)\n self.assertTrue(lattice_match)\n\n def test_vacancy(self):\n struc = PymatgenTest.get_structure(\"VO2\")\n V_index = struc.indices_from_symbol(\"V\")[0]\n vac = Vacancy(struc, struc[V_index])\n\n # test generation and super cell\n vac_struc = vac.generate_defect_structure(1)\n self.assertEqual(vac_struc.composition.as_dict(), {\"V\": 1, \"O\": 4})\n\n vac_struc = vac.generate_defect_structure(2)\n self.assertEqual(vac_struc.composition.as_dict(), {\"V\": 15, \"O\": 32})\n\n vac_struc = vac.generate_defect_structure(3)\n self.assertEqual(vac_struc.composition.as_dict(), {\"V\": 53, \"O\": 108})\n\n vac_struc = vac.generate_defect_structure([[2.0, 0, 0], [0, 0, -3.0], [0, 2.0, 0]])\n self.assertEqual(vac_struc.composition.as_dict(), {\"V\": 23, \"O\": 48})\n\n # test charge\n vac = Vacancy(struc, struc[V_index])\n vac_struc = vac.generate_defect_structure(1)\n self.assertEqual(vac_struc.charge, 0.0)\n\n vac = Vacancy(struc, struc[V_index], charge=1.0)\n vac_struc = vac.generate_defect_structure(1)\n self.assertEqual(vac_struc.charge, 1.0)\n\n vac = Vacancy(struc, struc[V_index], charge=-1.0)\n vac_struc = vac.generate_defect_structure(1)\n self.assertEqual(vac_struc.charge, -1.0)\n\n # test multiplicity\n vac = Vacancy(struc, struc[V_index])\n self.assertEqual(vac.multiplicity, 2)\n\n O_index = struc.indices_from_symbol(\"O\")[0]\n vac = Vacancy(struc, struc[O_index])\n self.assertEqual(vac.multiplicity, 4)\n\n # Test composition\n self.assertEqual(dict(vac.defect_composition.as_dict()), {\"V\": 2, \"O\": 3})\n\n # test lattice value error occurs for different lattices\n sc_scaled_struc = struc.copy()\n sc_scaled_struc.make_supercell(2)\n self.assertRaises(ValueError, Vacancy, struc, sc_scaled_struc[V_index])\n self.assertRaises(ValueError, Vacancy, sc_scaled_struc, struc[V_index])\n\n # test value error raised for site not in the structure\n non_site = PeriodicSite(\"V\", struc[V_index].frac_coords + [0.0, 0.0, 0.1], struc.lattice)\n self.assertRaises(ValueError, Vacancy, struc, non_site)\n\n def test_interstitial(self):\n struc = PymatgenTest.get_structure(\"VO2\")\n V_index = struc.indices_from_symbol(\"V\")[0]\n\n int_site = PeriodicSite(\"V\", struc[V_index].coords + [0.1, 0.1, 0.1], struc.lattice)\n interstitial = Interstitial(struc, int_site)\n\n # test generation and super cell\n int_struc = interstitial.generate_defect_structure(1)\n self.assertEqual(int_struc.composition.as_dict(), {\"V\": 3, \"O\": 4})\n # Ensure the site is in the right place\n self.assertEqual(int_site, int_struc.get_sites_in_sphere(int_site.coords, 0.1)[0][0])\n\n int_struc = interstitial.generate_defect_structure(2)\n self.assertEqual(int_struc.composition.as_dict(), {\"V\": 17, \"O\": 32})\n\n int_struc = interstitial.generate_defect_structure(3)\n self.assertEqual(int_struc.composition.as_dict(), {\"V\": 55, \"O\": 108})\n\n int_struc = interstitial.generate_defect_structure([[2.0, 0, 0], [0, 0, -3.0], [0, 2.0, 0]])\n self.assertEqual(int_struc.composition.as_dict(), {\"V\": 25, \"O\": 48})\n\n # test charge\n interstitial = Interstitial(struc, int_site)\n int_struc = interstitial.generate_defect_structure(1)\n self.assertEqual(int_struc.charge, 0.0)\n\n interstitial = Interstitial(struc, int_site, charge=1.0)\n int_struc = interstitial.generate_defect_structure(1)\n self.assertEqual(int_struc.charge, 1.0)\n\n interstitial = Interstitial(struc, int_site, charge=-1.0)\n int_struc = interstitial.generate_defect_structure(1)\n self.assertEqual(int_struc.charge, -1.0)\n\n # test multiplicity\n interstitial = Interstitial(struc, int_site)\n self.assertEqual(interstitial.multiplicity, 8.0)\n\n # test manual setting of multiplicity\n interstitial = Interstitial(struc, int_site, multiplicity=4.0)\n self.assertEqual(interstitial.multiplicity, 4.0)\n\n # Test composition\n self.assertEqual(dict(interstitial.defect_composition.as_dict()), {\"V\": 3, \"O\": 4})\n\n # test that structure generation doesn't break if velocities existed previously\n # (previously caused failures for structure printing)\n vel_struc = Structure(\n struc.lattice,\n struc.species,\n struc.frac_coords,\n site_properties={\"velocities\": [[0.0, 0.0, 0.0]] * len(struc)},\n )\n interstitial = Interstitial(vel_struc, int_site, charge=-1.0)\n int_struc = interstitial.generate_defect_structure(1)\n self.assertTrue(\"velocities\" not in int_struc.site_properties)\n\n def test_substitution(self):\n struc = PymatgenTest.get_structure(\"VO2\")\n V_index = struc.indices_from_symbol(\"V\")[0]\n\n sub_site = PeriodicSite(\"Sr\", struc[V_index].coords, struc.lattice, coords_are_cartesian=True)\n substitution = Substitution(struc, sub_site)\n\n # test generation and super cell\n sub_struc = substitution.generate_defect_structure(1)\n self.assertEqual(sub_struc.composition.as_dict(), {\"V\": 1, \"Sr\": 1, \"O\": 4})\n\n sub_struc = substitution.generate_defect_structure(2)\n self.assertEqual(sub_struc.composition.as_dict(), {\"V\": 15, \"Sr\": 1, \"O\": 32})\n\n sub_struc = substitution.generate_defect_structure(3)\n self.assertEqual(sub_struc.composition.as_dict(), {\"V\": 53, \"Sr\": 1, \"O\": 108})\n\n sub_struc = substitution.generate_defect_structure([[2.0, 0, 0], [0, 0, -3.0], [0, 2.0, 0]])\n self.assertEqual(sub_struc.composition.as_dict(), {\"V\": 23, \"O\": 48, \"Sr\": 1})\n\n # test charge\n substitution = Substitution(struc, sub_site)\n sub_struc = substitution.generate_defect_structure(1)\n self.assertEqual(sub_struc.charge, 0.0)\n\n substitution = Substitution(struc, sub_site, charge=1.0)\n sub_struc = substitution.generate_defect_structure(1)\n self.assertEqual(sub_struc.charge, 1.0)\n\n substitution = Substitution(struc, sub_site, charge=-1.0)\n sub_struc = substitution.generate_defect_structure(1)\n self.assertEqual(sub_struc.charge, -1.0)\n\n # test multiplicity\n substitution = Substitution(struc, sub_site)\n self.assertEqual(substitution.multiplicity, 2.0)\n\n O_index = struc.indices_from_symbol(\"O\")[0]\n sub_site = PeriodicSite(\"Sr\", struc[O_index].coords, struc.lattice, coords_are_cartesian=True)\n substitution = Substitution(struc, sub_site)\n self.assertEqual(substitution.multiplicity, 4)\n\n # Test composition\n self.assertEqual(dict(substitution.defect_composition.as_dict()), {\"V\": 2, \"Sr\": 1, \"O\": 3})\n\n # test that structure generation doesn't break if velocities existed previously\n # (previously caused failures for structure printing)\n vel_struc = Structure(\n struc.lattice,\n struc.species,\n struc.frac_coords,\n site_properties={\"velocities\": [[0.0, 0.0, 0.0]] * len(struc)},\n )\n substitution = Substitution(vel_struc, sub_site)\n sub_struc = substitution.generate_defect_structure(1)\n\n self.assertTrue(\"velocities\" not in sub_struc.site_properties)\n\n # test value error raised for site not in the structure\n non_site = PeriodicSite(\"Sr\", struc[V_index].frac_coords - [0.0, 0.0, 0.1], struc.lattice)\n self.assertRaises(ValueError, Substitution, struc, non_site)\n\n\nclass create_saturated_interstitial_structureTest(PymatgenTest):\n def test_sublattice_generation(self):\n struc = PymatgenTest.get_structure(\"CsCl\")\n sc_struc = struc.copy()\n sc_struc.make_supercell(3)\n\n # test for vacancy and sub (should not change structure)\n Cs_index = sc_struc.indices_from_symbol(\"Cs\")[0]\n cs_vac = Vacancy(sc_struc, sc_struc[Cs_index])\n decorated_cs_vac = create_saturated_interstitial_structure(cs_vac)\n self.assertEqual(len(decorated_cs_vac), len(sc_struc))\n\n Cl_index = sc_struc.indices_from_symbol(\"Cl\")[0]\n\n cl_vac = Vacancy(sc_struc, sc_struc[Cl_index])\n decorated_cl_vac = create_saturated_interstitial_structure(cl_vac)\n self.assertEqual(len(decorated_cl_vac), len(sc_struc))\n\n sub_site = PeriodicSite(\"Sr\", sc_struc[Cs_index].coords, sc_struc.lattice, coords_are_cartesian=True)\n\n sub = Substitution(sc_struc, sub_site)\n decorated_sub = create_saturated_interstitial_structure(sub)\n self.assertEqual(len(decorated_sub), len(sc_struc))\n\n # test interstitial in symmorphic structure type\n inter_site = PeriodicSite(\"H\", [0.0, 1.05225, 2.1045], struc.lattice, coords_are_cartesian=True) # voronoi type\n interstitial = Interstitial(struc, inter_site)\n decorated_inter = create_saturated_interstitial_structure(interstitial)\n self.assertEqual(len(decorated_inter), 14)\n\n inter_site = PeriodicSite(\n \"H\",\n [0.10021429, 0.10021429, 2.1045],\n struc.lattice,\n coords_are_cartesian=True,\n ) # InFit type\n interstitial = Interstitial(struc, inter_site)\n decorated_inter = create_saturated_interstitial_structure(interstitial)\n self.assertEqual(len(decorated_inter), 14)\n\n inter_site = PeriodicSite(\n \"H\",\n [4.10878571, 1.10235714, 2.1045],\n struc.lattice,\n coords_are_cartesian=True,\n ) # InFit type\n interstitial = Interstitial(struc, inter_site)\n decorated_inter = create_saturated_interstitial_structure(interstitial)\n self.assertEqual(len(decorated_inter), 26)\n\n inter_site = PeriodicSite(\n \"H\", [0.0, 0.0, 0.5], struc.lattice, coords_are_cartesian=False\n ) # a reasonable guess type\n interstitial = Interstitial(struc, inter_site)\n decorated_inter = create_saturated_interstitial_structure(interstitial)\n self.assertEqual(len(decorated_inter), 5)\n\n # test interstitial in non-symmorphic structure type\n # (voronoi and InFit generator of different types...)\n ns_struc = Structure.from_file(os.path.join(PymatgenTest.TEST_FILES_DIR, \"CuCl.cif\"))\n\n inter_site = PeriodicSite(\n \"H\",\n [0.45173594, 0.41157895, 5.6604067],\n ns_struc.lattice,\n coords_are_cartesian=True,\n ) # InFit type\n interstitial = Interstitial(ns_struc, inter_site)\n decorated_inter = create_saturated_interstitial_structure(interstitial)\n self.assertEqual(len(decorated_inter), 40)\n\n inter_site = PeriodicSite(\n \"H\",\n [0.47279906, 0.82845998, 5.62015285],\n ns_struc.lattice,\n coords_are_cartesian=True,\n ) # InFit type\n interstitial = Interstitial(ns_struc, inter_site)\n decorated_inter = create_saturated_interstitial_structure(interstitial)\n self.assertEqual(len(decorated_inter), 40)\n\n inter_site = PeriodicSite(\n \"H\",\n [0.70845255, 6.50298148, 5.16979425],\n ns_struc.lattice,\n coords_are_cartesian=True,\n ) # InFit type\n interstitial = Interstitial(ns_struc, inter_site)\n decorated_inter = create_saturated_interstitial_structure(interstitial)\n self.assertEqual(len(decorated_inter), 40)\n\n inter_site = PeriodicSite(\n \"H\",\n [0.98191329, 0.36460337, 4.64718203],\n ns_struc.lattice,\n coords_are_cartesian=True,\n ) # InFit type\n interstitial = Interstitial(ns_struc, inter_site)\n decorated_inter = create_saturated_interstitial_structure(interstitial)\n self.assertEqual(len(decorated_inter), 40)\n\n inter_site = PeriodicSite(\n \"H\",\n [0.39286561, 3.92702149, 1.05802631],\n ns_struc.lattice,\n coords_are_cartesian=True,\n ) # InFit type\n interstitial = Interstitial(ns_struc, inter_site)\n decorated_inter = create_saturated_interstitial_structure(interstitial)\n self.assertEqual(len(decorated_inter), 40)\n\n\nclass DefectEntryTest(PymatgenTest):\n def setUp(self):\n self.struc = PymatgenTest.get_structure(\"VO2\")\n V_index = self.struc.indices_from_symbol(\"V\")[0]\n sub_site = PeriodicSite(\n \"Sr\",\n self.struc[V_index].coords,\n self.struc.lattice,\n coords_are_cartesian=True,\n )\n self.substitution = Substitution(self.struc, sub_site)\n\n def test_init(self):\n entry = DefectEntry(self.substitution, 2.5)\n entry_doc = entry.as_dict()\n re_entry = DefectEntry.from_dict(entry_doc)\n self.assertNotEqual(re_entry, None)\n\n def test_corrections(self):\n entry = DefectEntry(self.substitution, 2.5)\n\n self.assertAlmostEqual(entry.energy, 2.5)\n\n entry.corrections[\"pot_corr\"] = -0.3\n self.assertAlmostEqual(entry.energy, 2.2)\n\n def test_formation_energy(self):\n entry = DefectEntry(self.substitution, 2.5, corrections={\"pot_corr\": -0.3})\n\n # Test chemical potentials on formation energy\n self.assertAlmostEqual(entry.formation_energy(), 2.2)\n self.assertAlmostEqual(entry.formation_energy({\"Sr\": 0.2}), 2.0)\n self.assertAlmostEqual(entry.formation_energy({\"V\": 0.2}), 2.4)\n self.assertAlmostEqual(entry.formation_energy({\"Sr\": 0.2, \"V\": 0.2}), 2.2)\n self.assertAlmostEqual(entry.formation_energy({\"Sr\": 0.2, \"V\": 0.2, \"O\": 2}), 2.2)\n\n # Test Fermi level on formation energy\n self.assertAlmostEqual(entry.formation_energy({\"Sr\": 0.2, \"V\": 0.2}, fermi_level=0.2), 2.2)\n entry.parameters[\"vbm\"] = 0\n self.assertAlmostEqual(entry.formation_energy({\"Sr\": 0.2, \"V\": 0.2}, fermi_level=0.2), 2.2)\n entry.defect._charge = 1\n self.assertAlmostEqual(entry.formation_energy({\"Sr\": 0.2, \"V\": 0.2}, fermi_level=0.2), 2.4)\n\n def test_defect_concentration(self):\n entry = DefectEntry(self.substitution, 0.5, corrections={})\n entry.defect._charge = -1\n\n chem_pots = {\"Sr\": 0.0, \"V\": 0.0, \"O\": 0.0}\n self.assertAlmostEqual(entry.defect_concentration(chem_pots) / 1.2878334860092098e14, 1)\n\n # #test temperature dependence\n self.assertAlmostEqual(\n entry.defect_concentration(chem_pots, temperature=600) / 2.0402099809985405e18,\n 1,\n )\n\n # test fermi level dependence\n self.assertAlmostEqual(\n entry.defect_concentration(chem_pots, fermi_level=0.3) / 1.411360305591838e19,\n 1,\n )\n\n\nif __name__ == \"__main__\":\n unittest.main()\n" ]
[ [ "numpy.array", "numpy.zeros", "numpy.transpose" ], [ "numpy.arange", "numpy.identity", "numpy.cos" ], [ "numpy.split", "pandas.read_json", "pandas.DataFrame" ], [ "numpy.expand_dims", "numpy.inner", "numpy.cos", "numpy.sort", "numpy.sin", "numpy.copy", "scipy.special.erfc", "numpy.outer", "numpy.array", "numpy.exp", "numpy.zeros", "numpy.sum", "numpy.empty" ], [ "numpy.allclose" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "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": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
j-lazo/lumen_segmentation
[ "442b6e642b4743e6b7bf56ab77e11e8e95062ed7" ]
[ "general/calculate_performance_dataset.py" ]
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jun 9 16:18:55 2020\n\n@author: jlazo\n\"\"\"\n\n#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 26 01:18:22 2020\n\n@author: jlazo\n\"\"\"\n\nimport os\nimport numpy as np\nimport cv2\nfrom glob import glob\nfrom sklearn.model_selection import train_test_split\nfrom os import listdir\nfrom matplotlib import pyplot as plt\n\nfrom sklearn.metrics import average_precision_score\nfrom sklearn.metrics import recall_score\nfrom sklearn.metrics import accuracy_score\n\nimport os.path\nfrom os import path\nfrom PIL import Image\nfrom os import listdir\nfrom os.path import isfile, join\nfrom datetime import datetime\nimport csv\n\nproject_folder = '/home/nearlab/Jorge/current_work/lumen_segmentation/' \\\n 'data/lumen_data/'\ngeneral_model = 'ResUNet'\nmodel_to_test = 'ResUnet_lr_1e-05_bs_16_rgb_27_04_2021_20_10'\nfolder_to_test = 'phantom_001_pt1'\n\n\ndef calculate_area_and_circunference(dir_folder):\n mask_list = sorted(os.listdir(dir_folder))\n\n list_areas = []\n list_circuference = []\n list_circularities = []\n\n size_x = []\n size_y = []\n\n for mask in mask_list[:]:\n name_mask = ''.join([dir_folder, mask])\n\n arc_len, area = findArc(name_mask)\n if area != 0:\n circulatiry = 1.0*(arc_len**2)/(4*np.pi*area)\n list_circularities.append(circulatiry)\n\n\n list_areas.append(area)\n list_circuference.append(arc_len)\n\n #size_x.append(np.amax(list_x_pixels) - np.amin(list_x_pixels))\n #size_y.append(np.amax(list_y_pixels) - np.amin(list_y_pixels))\n\n return list_areas, list_circuference, list_circularities\n\n\ndef calculateDistance(x1, y1, X, Y):\n\n dist_vector = []\n for index, x2, in enumerate(X):\n y2 = Y[index]\n dist = np.sqrt((x2 - x1)**2 + (y2 - y1)**2)\n dist_vector.append(dist)\n\n return dist_vector\n\n\ndef findArc(image, th=200):\n img = cv2.imread(image)\n res = img.copy()\n ## convert to gray\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n ## threshold the gray\n th, threshed = cv2.threshold(gray, th, 255, cv2.THRESH_BINARY)\n ## Find contours on the binary threshed image\n cnts = cv2.findContours(threshed, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[-2]\n\n\n ## calcualte\n for cnt in cnts:\n arclen = cv2.arcLength(cnt, True)\n area = cv2.contourArea(cnt)\n cv2.drawContours(res, [cnt], -1, (0,255,0), 3, cv2.LINE_AA)\n #print(\"Length: {:.3f}\\nArea: {:.3f}\".format(arclen, area))\n\n cnt = cnts[0]\n pnts_x = [point[0][0] for point in cnt]\n pnts_y = [point[0][1] for point in cnt]\n\n moments = cv2.moments(cnt)\n cx = int(moments['m10'] / moments['m00'])\n cy = int(moments['m01'] / moments['m00'])\n\n distances = calculateDistance(cx, cy, pnts_x, pnts_y)\n fig, ax = plt.subplots()\n ax.plot(cx, cy, 'ro')\n ax.add_artist(plt.Circle((cx, cy), np.min(distances), color='g', fill=False))\n ax.add_artist(plt.Circle((cx, cy), np.max(distances), color='b', fill=False))\n\n return arclen, area\n\n\ndef read_results_csv(file_path, row_id=0):\n dice_values = []\n with open(file_path, 'r') as file:\n reader = csv.reader(file)\n for row in reader:\n dice_values.append(float(row[row_id]))\n \n return dice_values\n\n\ndef read_results_csv_str(file_path, row_id=0):\n dice_values = []\n with open(file_path, 'r') as file:\n reader = csv.reader(file)\n for row in reader:\n dice_values.append(row[row_id])\n \n return dice_values\n\n\ndef calculate_rates(image_1, image_2):\n\n image_1 = np.asarray(image_1).astype(np.bool)\n image_2 = np.asarray(image_2).astype(np.bool)\n\n image_1 = image_1.flatten()\n image_2 = image_2.flatten()\n\n if image_1.shape != image_2.shape:\n raise ValueError(\"Shape mismatch: im1 and im2 must have the same shape.\")\n\n accuracy_value = accuracy_score(image_1, image_2)\n\n if (np.unique(image_1) == [False]).all() and (np.unique(image_1) == [False]).all():\n recall_value = 1.\n precision_value = 1.\n\n else:\n recall_value = recall_score(image_1, image_2)\n precision_value = average_precision_score(image_1, image_2)\n\n return precision_value, recall_value, accuracy_value\n \n\ndef dice(im1, im2,smooth=.001):\n\n im1 = np.asarray(im1).astype(np.bool)\n im2 = np.asarray(im2).astype(np.bool)\n \n if im1.shape != im2.shape:\n raise ValueError(\"Shape mismatch: im1 and im2 must have the same shape.\")\n\n # Compute Dice coefficient\n intersection = np.logical_and(im1, im2)\n return 2. * (intersection.sum() + smooth) / (im1.sum() + im2.sum() + smooth)\n\n\ndef read_img(dir_image):\n original_img = cv2.imread(dir_image)\n height, width, depth = original_img.shape\n img = cv2.resize(original_img, (256, 256))\n img = img / 255\n img = (img > 0.9) * 1.0\n return img\n\n# ------ --- aqui empieza lo mero bueno -----\n# ---------- save the resutls of the validation dataset in a CSV file\n\n\nground_truth_imgs_dir = project_folder + 'test/' + folder_to_test + '/label/'\nresult_mask_dir = ''.join([project_folder, 'results/', general_model, '/',\n model_to_test, '/predictions/', folder_to_test,\n '/'])\n\nground_truth_image_list = sorted([file for file in listdir(ground_truth_imgs_dir) if isfile(join(ground_truth_imgs_dir, file))])\nresults_image_list = sorted([file for file in listdir(result_mask_dir) if isfile(join(result_mask_dir, file))])\n\nname_images = []\nresults_dice = []\nresults_sensitivity = []\nresults_specificity = []\nresults_accuracy = []\n\nfor image in ground_truth_image_list[:]:\n #print(image in results_image_list)\n #result_image = [name for name in results_image_list if image[-12:] == name[-12:]][0]\n\n if image in results_image_list:\n result_image = image\n print(result_image)\n original_mask = read_img(''.join([ground_truth_imgs_dir, image]))\n predicted_mask = read_img(''.join([result_mask_dir, result_image]))\n dice_val = dice(original_mask, predicted_mask)\n name_images.append(result_image)\n results_dice.append(dice_val)\n \n sensitivity, specificity, accuracy = calculate_rates(original_mask, predicted_mask)\n results_sensitivity.append(sensitivity)\n results_specificity.append(specificity)\n results_accuracy.append(accuracy)\n \n #print(sensitivity, specificity)\n else:\n print(image, 'not found in results list')\n\n\nground_truth_image_list = [file for file in listdir(ground_truth_imgs_dir) if isfile(join(ground_truth_imgs_dir, file))]\nresults_image_list = [file for file in listdir(result_mask_dir) if isfile(join(result_mask_dir, file))]\n\nnow = datetime.now()\nname_test_csv_file = ''.join([project_folder, 'results/', general_model,\n '/', model_to_test, '/',\n 'results_evaluation_',\n folder_to_test, '_',\n model_to_test,\n '_new.csv'])\nprint('saved in :', name_test_csv_file)\n\nwith open(name_test_csv_file, mode='w') as results_file:\n results_file_writer = csv.writer(results_file, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n for i, file in enumerate(name_images):\n results_file_writer.writerow([str(i), file, \n results_dice[i], \n results_sensitivity[i], \n results_specificity[i], \n results_accuracy[i]])\n #arclen, circunference])" ]
[ [ "numpy.sqrt", "numpy.min", "numpy.asarray", "numpy.unique", "matplotlib.pyplot.subplots", "numpy.max", "sklearn.metrics.average_precision_score", "numpy.logical_and", "sklearn.metrics.recall_score", "sklearn.metrics.accuracy_score" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
mrawls/ELCtools
[ "7e15bf24c453ed4300c6f19f01cff74c041158b8" ]
[ "dnu_calculator.py" ]
[ "from __future__ import print_function\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom astropy import units as u\n'''\nMeredith Rawls, 2015\nTakes masses, radii, and chi2s from an ELC run and makes delta_nu distributions.\nAssumes a fixed temperature for each star.\n'''\ndir = '../../RG_ELCmodeling/9246715/demcmc001/'\n#dir = '../../RG_ELCmodeling/7037405/trial3/'\nstarparmfile = 'starparm.all'\nchifile = 'chi.all'\noutfile = 'deltanu_ELCcalc.txt'\nnplotbins = 100\n\nprint('Reading in giant files, be patient...')\nM1s, M2s, R1s, R2s = np.loadtxt(dir+starparmfile, usecols=(0,1,2,3), unpack=True)\nchi2s = np.genfromtxt(dir+chifile, usecols=(1,), unpack=True)\nprint('Finished reading in giant files!')\nT1 = 5000.\nT2 = 5000.\n\ndef calc_dnu(mass, radius, temp):\n density_sun = (1. * u.Msun) /(4./3. * np.pi * np.power((1. * u.Rsun),3))\n dnu_sun = 135.5 # muHz\n density = (mass * u.Msun) /(4./3. * np.pi * np.power((radius * u.Rsun),3))\n dnu = dnu_sun * np.sqrt(density/density_sun)\n return dnu\n\nprint('Calculating delta nu for each model, be patient...')\ndnu1s = []\ndnu2s = []\nfor M1, M2, R1, R2 in zip(M1s, M2s, R1s, R2s):\n dnu1s.append(calc_dnu(M1, R1, T1))\n dnu2s.append(calc_dnu(M2, R2, T2))\nprint('Finished calculating delta nus!')\n\nprint(np.median(dnu1s), np.std(dnu2s))\nprint(np.median(dnu2s), np.std(dnu2s))\ndelta_dnus = np.array(dnu1s) - np.array(dnu2s)\nprint(np.median(delta_dnus), np.std(delta_dnus))\n\nthreshold = 0.5 # muHz, typical mode width\ncount = 0 # tally for how many delta_dnus are within some threshold\nf1 = open(dir+outfile, 'w')\nfor chi2, dnu1, dnu2, delta_dnu in zip(chi2s, dnu1s, dnu2s, delta_dnus):\n print(chi2, dnu1, dnu2, delta_dnu, file=f1)\n if delta_dnu < threshold:\n count += 1\nf1.close()\n\nprint('Out of {0} models, {1} ({2}\\%) have a difference in dnu less than {3}.'.format \\\n (len(chi2s), count, float(count)/float(len(chi2s)), threshold))\n\n# Plot histograms of dnu1s, dnu2s, and the difference\nfig = plt.figure()\nax1 = fig.add_subplot(1, 3, 1)\nx1 = plt.xlabel('Delta nu 1')\nhistogram = plt.hist(dnu1s, nplotbins, histtype='stepfilled')\nax2 = fig.add_subplot(1, 3, 2)\nx2 = plt.xlabel('Delta nu 2')\nhistogram = plt.hist(dnu2s, nplotbins, histtype='stepfilled')\nax3 = fig.add_subplot(1, 3, 3)\nx3 = plt.xlabel('Delta nu 1 - Delta nu 2')\nhistogram = plt.hist(delta_dnus, nplotbins, histtype='stepfilled')\n\nplt.show()" ]
[ [ "numpy.sqrt", "numpy.power", "numpy.median", "numpy.genfromtxt", "numpy.std", "matplotlib.pyplot.xlabel", "numpy.array", "matplotlib.pyplot.show", "matplotlib.pyplot.hist", "numpy.loadtxt", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
canbakiskan/sparse_coding_frontend
[ "1f62b54824785aa441317ddab1baa3012f2fb401", "1f62b54824785aa441317ddab1baa3012f2fb401" ]
[ "src/utils/read_datasets.py", "src/plotting/correlation_plot.py" ]
[ "import torch\nfrom torchvision import datasets, transforms\n\nimport numpy as np\nfrom os.path import join\nfrom .namers import attack_file_namer\n\n\ndef tiny_imagenet(args):\n\n data_dir = join(args.directory, 'data')\n train_dir = join(data_dir, \"original_datasets\",\n \"tiny-imagenet-200\", \"train\")\n test_dir = join(data_dir, \"original_datasets\",\n \"tiny-imagenet-200\", \"val\")\n\n transform_train = transforms.Compose(\n [\n transforms.RandomCrop(64, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n ]\n )\n\n transform_test = transforms.Compose([transforms.ToTensor()])\n\n trainset = datasets.ImageFolder(train_dir, transform=transform_train)\n train_loader = torch.utils.data.DataLoader(\n trainset, batch_size=args.neural_net.train_batch_size, shuffle=True, num_workers=2\n )\n\n testset = datasets.ImageFolder(test_dir, transform=transform_test)\n test_loader = torch.utils.data.DataLoader(\n testset, batch_size=args.neural_net.test_batch_size, shuffle=False, num_workers=2\n )\n\n return train_loader, test_loader\n\n\ndef tiny_imagenet_from_file(args):\n use_cuda = args.use_gpu and torch.cuda.is_available()\n kwargs = {\"num_workers\": 1, \"pin_memory\": True} if use_cuda else {}\n\n # Read\n if args.adv_testing.method == \"transfer\":\n filepath = join(\n args.directory, 'data',\n 'attacked_datasets', args.dataset.name, args.adv_testing.transfer_file\n )\n\n else:\n filepath = attack_file_namer(args)\n\n test_images = np.load(filepath)\n\n data_dir = join(args.directory, 'data')\n test_dir = join(data_dir, \"original_datasets\",\n \"tiny-imagenet-200\", \"val\")\n transform_test = transforms.Compose([transforms.ToTensor()])\n testset = datasets.ImageFolder(test_dir, transform=transform_test)\n test_loader = torch.utils.data.DataLoader(\n testset, batch_size=args.neural_net.test_batch_size, shuffle=False, num_workers=2\n )\n\n tensor_x = torch.Tensor(test_images / np.max(test_images))\n tensor_y = torch.Tensor(test_loader.dataset.targets).long()\n\n tensor_data = torch.utils.data.TensorDataset(tensor_x, tensor_y)\n attack_loader = torch.utils.data.DataLoader(\n tensor_data, batch_size=args.neural_net.test_batch_size, shuffle=False, **kwargs\n )\n\n return attack_loader\n\n\ndef imagenette(args):\n\n data_dir = join(args.directory, 'data')\n train_dir = join(data_dir, \"original_datasets\",\n \"imagenette2-160\", \"train\")\n test_dir = join(data_dir, \"original_datasets\",\n \"imagenette2-160\", \"val\")\n\n use_cuda = args.use_gpu and torch.cuda.is_available()\n kwargs = {\"num_workers\": 4, \"pin_memory\": True} if use_cuda else {}\n\n transform_train = transforms.Compose(\n [\n transforms.RandomCrop((160), padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n ]\n )\n\n transform_test = transforms.Compose(\n [transforms.CenterCrop(160), transforms.ToTensor()]\n )\n\n trainset = datasets.ImageFolder(train_dir, transform=transform_train)\n train_loader = torch.utils.data.DataLoader(\n trainset, batch_size=args.neural_net.train_batch_size, shuffle=True, num_workers=2\n )\n\n testset = datasets.ImageFolder(test_dir, transform=transform_test)\n test_loader = torch.utils.data.DataLoader(\n testset, batch_size=args.neural_net.test_batch_size, shuffle=False, num_workers=2\n )\n\n return train_loader, test_loader\n\n\ndef imagenette_from_file(args):\n use_cuda = args.use_gpu and torch.cuda.is_available()\n kwargs = {\"num_workers\": 1, \"pin_memory\": True} if use_cuda else {}\n\n # Read\n if args.adv_testing.method == \"transfer\":\n filepath = join(\n args.directory, 'data', 'attacked_datasets', args.dataset.name, args.adv_testing.transfer_file\n )\n\n else:\n filepath = attack_file_namer(args)\n\n test_images = np.load(filepath)\n\n data_dir = join(args.directory, 'data')\n test_dir = join(data_dir, \"original_datasets\",\n \"imagenette2-160\", \"val\")\n transform_test = transforms.Compose([transforms.ToTensor()])\n testset = datasets.ImageFolder(test_dir, transform=transform_test)\n test_loader = torch.utils.data.DataLoader(\n testset, batch_size=args.neural_net.test_batch_size, shuffle=False, num_workers=2\n )\n\n tensor_x = torch.Tensor(test_images / np.max(test_images))\n tensor_y = torch.Tensor(test_loader.dataset.targets).long()\n\n tensor_data = torch.utils.data.TensorDataset(tensor_x, tensor_y)\n attack_loader = torch.utils.data.DataLoader(\n tensor_data, batch_size=args.neural_net.test_batch_size, shuffle=False, **kwargs\n )\n\n return attack_loader\n\n\ndef cifar10(args):\n\n use_cuda = args.use_gpu and torch.cuda.is_available()\n kwargs = {\"num_workers\": 4, \"pin_memory\": True} if use_cuda else {}\n\n transform_train = transforms.Compose(\n [\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n ]\n )\n\n transform_test = transforms.Compose([transforms.ToTensor()])\n\n trainset = datasets.CIFAR10(\n root=join(args.directory, 'data', 'original_datasets'),\n train=True,\n download=True,\n transform=transform_train,\n )\n train_loader = torch.utils.data.DataLoader(\n trainset, batch_size=args.neural_net.train_batch_size, shuffle=True, num_workers=2\n )\n\n testset = datasets.CIFAR10(\n root=join(args.directory, 'data', 'original_datasets'),\n train=False,\n download=True,\n transform=transform_test,\n )\n test_loader = torch.utils.data.DataLoader(\n testset, batch_size=args.neural_net.test_batch_size, shuffle=False, num_workers=2\n )\n\n return train_loader, test_loader\n\n\ndef cifar10_from_file(args):\n\n use_cuda = args.use_gpu and torch.cuda.is_available()\n kwargs = {\"num_workers\": 1, \"pin_memory\": True} if use_cuda else {}\n\n # Read\n if args.adv_testing.method == \"transfer\":\n filepath = join(\n args.directory, 'data', 'attacked_datasets', args.dataset.name, args.adv_testing.transfer_file\n )\n\n else:\n filepath = attack_file_namer(args)\n\n test_images = np.load(filepath)\n\n cifar10 = datasets.CIFAR10(\n join(args.directory, 'data', 'original_datasets'),\n train=False,\n transform=None,\n target_transform=None,\n download=False,\n )\n\n tensor_x = torch.Tensor(test_images / np.max(test_images))\n tensor_y = torch.Tensor(cifar10.targets).long()\n\n tensor_data = torch.utils.data.TensorDataset(tensor_x, tensor_y)\n attack_loader = torch.utils.data.DataLoader(\n tensor_data, batch_size=args.neural_net.test_batch_size, shuffle=False, **kwargs\n )\n\n return attack_loader\n\n\ndef imagenet(args):\n\n data_dir = join(args.directory, 'data')\n train_dir = join(data_dir, \"original_datasets\", \"imagenet\", \"train\")\n test_dir = join(data_dir, \"original_datasets\", \"imagenet\", \"val\")\n\n use_cuda = args.use_gpu and torch.cuda.is_available()\n kwargs = {\"num_workers\": 4, \"pin_memory\": True} if use_cuda else {}\n\n normalize = transforms.Normalize(\n mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]\n )\n\n transform_train = transforms.Compose(\n [\n transforms.RandomResizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n normalize,\n ]\n )\n\n transform_test = transforms.Compose(\n [\n transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n normalize,\n ]\n )\n\n trainset = datasets.ImageFolder(train_dir, transform=transform_train)\n train_loader = torch.utils.data.DataLoader(\n trainset,\n batch_size=args.neural_net.train_batch_size,\n shuffle=True,\n num_workers=4,\n pin_memory=True,\n )\n\n testset = datasets.ImageFolder(test_dir, transform=transform_test)\n test_loader = torch.utils.data.DataLoader(\n testset,\n batch_size=args.neural_net.test_batch_size,\n shuffle=False,\n num_workers=4,\n pin_memory=True,\n )\n\n return train_loader, test_loader\n\n\ndef read_dataset(args):\n\n if args.dataset.name == \"CIFAR10\":\n train_loader, test_loader = cifar10(args)\n elif args.dataset.name == \"Tiny-ImageNet\":\n train_loader, test_loader = tiny_imagenet(args)\n elif args.dataset.name == \"Imagenette\":\n train_loader, test_loader = imagenette(args)\n elif args.dataset.name == \"Imagenet\":\n train_loader, test_loader = imagenet(args)\n else:\n raise NotImplementedError\n\n return train_loader, test_loader\n\n\ndef read_test_dataset_from_file(args):\n\n if args.dataset.name == \"CIFAR10\":\n test_loader = cifar10_from_file(args)\n elif args.dataset.name == \"Tiny-ImageNet\":\n test_loader = tiny_imagenet_from_file(args)\n elif args.dataset.name == \"Imagenette\":\n test_loader = imagenette_from_file(args)\n else:\n raise NotImplementedError\n\n return test_loader\n", "from os.path import join\nimport matplotlib.pyplot as plt\nimport torch\nfrom ..models.resnet import ResNetWide\nfrom ..utils.read_datasets import cifar10\nfrom ..utils.plot_settings import *\nfrom ..utils.get_modules import load_frontend\nimport numpy as np\nfrom ..parameters import get_arguments\n\nargs = get_arguments()\n\ndevice = \"cuda\"\n\nclassifier = ResNetWide(num_outputs=10).to(device)\n\nclassifier.load_state_dict(\n torch.load(join(\n 'checkpoints', 'classifiers', 'CIFAR10', 'resnetwide_sgd_cyc_0.0500_NT_ep_100.pt'),\n map_location=torch.device(device),\n )\n)\nclassifier.to(device)\n\ntrain_loader, test_loader = cifar10(args)\nfrontend = load_frontend(args)\n\nplt.figure(figsize=(10, 10))\nweights = classifier.conv1.weight.clone().reshape(160, -1)\nweights /= torch.norm(weights, dim=1, keepdim=True)\nweights = weights.detach().cpu().numpy()\nasd = weights @ weights.transpose()\nplt.imshow(\n asd,\n cmap=cm,\n vmin=-np.abs(asd).max(),\n vmax=np.abs(asd).max(),\n interpolation=\"nearest\",\n)\nplt.xticks([])\nplt.yticks([])\nplt.savefig(join('figs', 'inner_cnn.pdf'))\nplt.close()\n\nplt.figure(figsize=(10, 5))\nplt.hist(asd.flatten(), 50)\nplt.savefig(join('figs', 'hist_cnn.pdf'))\nplt.close()\n\nnb_cols = 2\nnb_rows = 5\nplt.figure(figsize=(10 * nb_cols, 4 * nb_rows))\nfor i in range(nb_cols * nb_rows):\n plt.subplot(nb_rows, nb_cols, i + 1)\n img_index = np.random.choice(50000)\n print(f\"image: {img_index},\", end=\" \")\n img, _ = train_loader.dataset[img_index]\n img = img.to(device)\n\n classifier_out = classifier.norm(img.unsqueeze(0))\n classifier_out = classifier.conv1(classifier_out)\n # classifier_out = classifier.conv1(img.unsqueeze(0))\n\n classifier_out /= torch.norm(classifier.conv1.weight.view(160, -1), dim=1).view(\n 1, 160, 1, 1\n )\n\n frontend_out = frontend.encoder.conv(img.unsqueeze(0))\n # print(f\"===={out[0,0,0,0]}\")\n\n # xlims = [-2.6, 2.6]\n patch_index = (np.random.choice(range(1, 30, 2)),\n np.random.choice(range(1, 30, 2)))\n # patch_index = (22, 23)\n print(f\"patch: {patch_index}\")\n classifier_patch = classifier_out.squeeze().detach().cpu().numpy()[\n :, patch_index]\n frontend_patch = (\n frontend_out.squeeze()\n .detach()\n .cpu()\n .numpy()[:, patch_index[0] // 2, patch_index[1] // 2]\n )\n abs_max = max(np.abs(classifier_patch).max(), np.abs(frontend_patch).max())\n xlims = (-abs_max, abs_max)\n\n bin_edges = np.linspace(*xlims, 50)\n\n hist, _ = np.histogram(classifier_patch, bin_edges, density=True)\n # breakpoint()\n color, edgecolor = (\"orange\", \"darkorange\")\n\n plt.bar(\n bin_edges[:-1] + np.diff(bin_edges) / 2,\n hist,\n width=(bin_edges[1] - bin_edges[0]),\n alpha=0.5,\n edgecolor=\"none\",\n color=color,\n )\n plt.step(\n np.array([*bin_edges, bin_edges[-1] + (bin_edges[1] - bin_edges[0])]),\n np.array([0, *hist, 0]),\n label=r\"CNN $1^{st}$ layer\",\n where=\"pre\",\n color=edgecolor,\n )\n ax = plt.gca()\n ax.spines[\"right\"].set_visible(False)\n ax.spines[\"left\"].set_visible(False)\n ax.spines[\"top\"].set_visible(False)\n ax.get_yaxis().set_visible(False)\n\n # print(f\"===={out[0,0,0,0]}\")\n\n hist, _ = np.histogram(frontend_patch, bin_edges, density=True)\n\n # bin_edges, hist = np.histogram(out.squeeze().detach().cpu().numpy()[\n # :, np.random.choice(32), np.random.choice(32)], 50)\n\n color, edgecolor = (\"steelblue\", \"steelblue\")\n\n plt.bar(\n bin_edges[:-1] + np.diff(bin_edges) / 2,\n hist,\n width=(bin_edges[1] - bin_edges[0]),\n alpha=0.5,\n edgecolor=\"none\",\n color=color,\n )\n plt.step(\n np.array([*bin_edges, bin_edges[-1] + (bin_edges[1] - bin_edges[0])]),\n np.array([0, *hist, 0]),\n label=r\"Overcomplete dictionary\",\n where=\"pre\",\n color=edgecolor,\n )\n ax = plt.gca()\n ax.spines[\"right\"].set_visible(False)\n ax.spines[\"left\"].set_visible(False)\n ax.spines[\"top\"].set_visible(False)\n ax.get_yaxis().set_visible(False)\n\n\n# ax = plt.gca()\n\n# ax.xaxis.set_major_locator(ticker.MultipleLocator(18))\n# ax.xaxis.set_minor_locator(ticker.MultipleLocator(4.5))\n# ax.xaxis.set_major_formatter(ticker.PercentFormatter(xmax=225, decimals=0))\n# plt.gca().get_xaxis().set_major_formatter(\n# FuncFormatter(lambda x, p: format((x / 225), \".2\"))\n# )\n\n# fontsize = 21\n# plt.xlabel(\"Correlation value\", fontsize=fontsize)\n# plt.ylabel(\"Histogram density\", fontsize=fontsize)\n# plt.xlim(xlims)\n# plt.legend(loc=\"upper center\", fontsize=fontsize)\n\nplt.tight_layout()\n\nplt.savefig(join('figs', 'more_correlations_normalized.pdf'))\nplt.close()\n" ]
[ [ "torch.Tensor", "torch.utils.data.TensorDataset", "torch.utils.data.DataLoader", "numpy.max", "torch.cuda.is_available", "numpy.load" ], [ "matplotlib.pyplot.gca", "torch.norm", "matplotlib.pyplot.tight_layout", "numpy.abs", "numpy.linspace", "numpy.random.choice", "matplotlib.pyplot.subplot", "numpy.diff", "matplotlib.pyplot.close", "torch.device", "matplotlib.pyplot.yticks", "numpy.array", "numpy.histogram", "matplotlib.pyplot.xticks", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
man-vs-electron/datapanels
[ "d656bbd3c6071cc2d26bd27285001aee1fa7c82d" ]
[ "src/datapanels/gameoflife.py" ]
[ "\"\"\" DataPanels implementation of Conway's Game of Life\n\nSee https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life for details about\nthe game.\n\n\"\"\"\nimport random\nfrom typing import Tuple, Set, Optional, Union, List\nimport re\nimport numpy as np\nfrom kivy.lang.builder import Builder\nfrom kivy.properties import ListProperty, NumericProperty, ObjectProperty\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.uix.button import Button\nfrom kivy.uix.dropdown import DropDown\nfrom kivy.clock import Clock\nfrom kivy.app import App\nfrom kwidgets.uix.pixelatedgrid import PixelatedGrid\n\n\ndef translate(state: Set[Tuple[int, int]], x: int, y: int, additive: bool=False) -> Set[Tuple[int, int]]:\n \"\"\" Move the object the specified number of x and y values\n\n :param state: original state\n :param x: horizontal distance to move the object\n :param y: vertical distance to move the object\n :return: new, translated state\n \"\"\"\n return set([(t[0]+x, t[1]+y) for t in state]).union(state if additive else set())\n\n\ndef horizontal_flip(state: Set[Tuple[int, int]], additive: bool=False) -> Set[Tuple[int, int]]:\n \"\"\" Flip the object horizontally around the center\n\n :param state: original state\n :return: new modified state\n \"\"\"\n max_x = max([t[0] for t in state])\n min_x = min([t[0] for t in state])\n x_width = max_x-min_x\n\n return set([( x_width-t[0]+2*min_x, t[1] ) for t in state]).union(state if additive else set())\n\n\ndef vertical_flip(state: Set[Tuple[int, int]], additive: bool=False) -> Set[Tuple[int, int]]:\n \"\"\" Flip the object vertically around the center\n\n :param state: original state\n :return: new modified state\n \"\"\"\n max_y = max([t[1] for t in state])\n min_y = min([t[1] for t in state])\n y_width = max_y-min_y\n\n return set([( t[0], y_width-t[1]+2*min_y ) for t in state]).union(state if additive else set())\n\n\ndef rotate_90(state: Set[Tuple[int, int]], origin: Tuple[int, int], additive: bool=False) -> Set[Tuple[int, int]]:\n \"\"\" Rotate the object 90 degrees to the left with respect to the provide origin\n\n :param state: original state\n :param origin: The point of the rotation\n :return: new modified state\n \"\"\"\n return set([( origin[1]-t[1]+origin[0], t[0]-origin[0]+origin[1]) for t in state]).union(state if additive else set())\n\n\ndef multi_transform(state: Set[Tuple[int, int]], ops: List[Union[str, Tuple[str, int], Tuple[str, Tuple[int, int]]]], additive_final: bool=False) -> Set[Tuple[int, int]]:\n ans = set(state)\n for op in ops:\n if isinstance(op, tuple):\n if op[0].upper() == \"T\":\n ans = translate(ans, op[1], False)\n if op[0].upper() == \"R\":\n ans = rotate_90(ans, op[1], False)\n else:\n raise RuntimeError(\"Invalid syntax. Ops must be a list where each member is in the form (T, dist)|(R, (x,y)|H|V\")\n elif op.upper() == 'H':\n ans = horizontal_flip(ans, False)\n elif op.upper() == 'V':\n ans = vertical_flip(ans, False)\n else:\n raise RuntimeError(\"Invalid syntax. Ops must be a list where each member is in the form (T, dist)|(R, (x,y)|H|V\")\n return ans.union(state if additive_final else set())\n\n\ndef rle_decode(rle_text: str) -> Set[Tuple[int, int]]:\n \"\"\"\n Adapted from: https://github.com/Robert-Phan/python-conway/blob/master/main.py\n :param rle_text:\n :return:\n \"\"\"\n ans = []\n x=0\n y=0\n for g in re.findall(r\"\\d*b|\\d*o|\\d*\\$\", rle_text):\n num = 1 if len(g)==1 else int(g[:-1])\n code = g[-1]\n if code==\"$\":\n y += num\n x = 0\n if code==\"b\":\n x += num\n if code==\"o\":\n for j in range(0,num):\n ans.append((x,y))\n x += 1\n return set(ans)\n\n# Patterns taken from LifeWiki: https://conwaylife.com/wiki/Main_Page\n\nbasic_patterns = {\n \"glider\": rle_decode(\"bob$2bo$3o!\"),\n \"canada goose\": rle_decode(\"3o10b$o9b2ob$bo6b3obo$3b2o2b2o4b$4bo8b$8bo4b$4b2o3bo3b$3bobob2o4b$3bobo2bob2ob$2bo4b2o4b$2b2o9b$2b2o!\"),\n \"Copperhead\": rle_decode(\"b2o2b2o$3b2o$3b2o$obo2bobo$o6bo2$o6bo$b2o2b2o$2b4o2$3b2o$3b2o!\"),\n \"Coe Ship\": rle_decode(\"4b6o$2b2o5bo$2obo5bo$4bo3bob$6bo3b$6b2o2b$5b4ob$5b2ob2o$7b2o!\")\n}\n\n\ninitial_patterns = {\n \"R-pentomino\": ((1, 0), (0, 1), (1, 1), (1, 2), (2, 2)),\n \"Merzenich's p31\": rle_decode(\"7b2obo2bob2o7b$2o4bo2bo4bo2bo4b2o$2o5bobo4bobo5b2o$8bo6bo8b6$8bo6bo8b$2o5bobo4bobo5b2o$2o4bo2bo4bo2bo4b2o$7b2obo2bob2o!\"),\n \"68P16\": rle_decode(\"10b2o3b2o$10b2o3b2o$6bo$2o3b2o$2o2bo10bo$5bo3b2o2b2obo$5bo3bo6b2o2$2o$2o3bo7b2o$5b2o7bo3b2o$18b2o2$2b2o6bo3bo$3bob2o2b2o3bo$4bo10bo2b2o$13b2o3b2o$13bo$3b2o3b2o$3b2o3b2o!\"),\n \"65P48\": rle_decode(\"\"\"6bo3b2o$7b2ob2o$5bobo$6bo$2o2b3o5bobo2bo$2o9bob5o2$10bob4o$10bo5bo$11b2o2b2o$9bobobo3b2o$8bobo2b3o3bo$8bo2b2o4b2obo$7b2o4b3o3bo$13bo2b3o$16bo!\"\"\"),\n \"Traffic Circle\": rle_decode(\"\"\"21b2o4b2o19b$21bobo2bobo19b$23bo2bo21b$22b2o2b2o20b$21b3o2b3o19b$23bo\n2bo21b$31bo16b$30bob2o14b$34bo13b$26bo3bo2bobo12b$26bo5bo2bo12b$26bo6b\n2o13b$9b2o37b$8bo2bo10b3o3b3o17b$7bobobo36b$6b3obo15bo21b$6b3o17bo21b$\n26bo21b$12b3o33b$2o2bo16b3o24b$o2b2o5bo5bo31b$b5o4bo5bo2bo5bo17bo2b2o$\n10bo5bo2bo5bo17b2o2bo$19bo5bo7b3o6b5ob$b5o6b3o33b$o2b2o16b3o7bo5bo10b$\n2o2bo26bo5bo4b5ob$31bo5bo5b2o2bo$43bo2b2o$33b3o12b$39b2o7b$38b3o7b$37b\nob2o7b$36bobo9b$20b3o13bo2bo8b$37b2o9b$13b2o4bo2bo25b$12bo2bo32b$12bob\nobo31b$13bo2bo31b$17bo30b$14bobo31b$21bo2bo23b$19b3o2b3o21b$20b2o2b2o\n22b$21bo2bo23b$19bobo2bobo21b$19b2o4b2o!\"\"\"),\n \"Space Ship (160P10H2V0)\": rle_decode(\"\"\"7bobobo7b$6b7o6b$5bo7bo5b$b3ob3o3b3ob3ob$o17bo$bo7bo7bob$bob2o9b2obob\n2$2b3o9b3o2b$2b3o9b3o2b$5bo7bo5b$bo4bo5bo4bob$bobo11bobob$7bo3bo7b$7bo\n3bo7b$5bo2bobo2bo5b$5bo7bo5b$4bo9bo4b$4bobo5bobo4b$4b2obo3bob2o4b$5bob\n2ob2obo5b$7bobobo7b$8bobo8b$6bobobobo6b$5b2obobob2o5b$8bobo8b$7b2ob2o\n7b$4b3obobob3o4b$4bobobobobobo4b$4bo3bobo3bo4b$8bobo8b$4bo2b5o2bo4b$3b\n4o5b4o3b$b2o13b2ob$b2obo9bob2ob$2bobo4bo4bobo2b$4b2o7b2o!\"\"\"),\n \"Space Ship (Barge 2)\": rle_decode(\"\"\"14b3ob3o14b$13bo2bobo2bo13b$12bo3bobo3bo12b$7b3obo2bobobobo2bob3o7b$6b\no2bobo4bobo4bobo2bo6b$5bo3bobobobo3bobobobo3bo5b$5bo23bo5b$7bo19bo7b$\n4bobo21bobo4b$3b2obob3o13b3obob2o3b$2bobobo3bo13bo3bobobo2b$b2obo25bob\n2ob$o3bo5b2o11b2o5bo3bo2$2ob2o25b2ob2o!\"\"\"),\n}\n\n\nclass GameOfLifeEngine:\n \"\"\" Game of Life implementation\n\n This class implements the rules and mechanism for computing successive states. No graphical operations are\n conducted.\n\n The current state of the grid is stored in active_cells. This set of tuples contains the X,Y coordinates of all\n the live cells.\n\n The key idea here is that the state is simply the currently live cells. If a cell is going to change state, it\n either has to be a live cell or adjecent to a live cell. So only dealing with currently live cells and their\n neighbors reduces the amount of computation that has to be performed.\n\n \"\"\"\n x_max: int = 100\n y_max: int = 100\n active_cells: Set[Tuple[int, int]] = set()\n offsets: Set[Tuple[int, int]] = {(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)}\n\n def all_neighbors(self, x: int, y: int) -> List[Tuple[int, int]]:\n \"\"\" Get a list of the coordinates of all the neighbors of some cell.\n\n The coordinates (q,r) for the neighbors must be in the range (0<=q<=x_max, 0<=r<=y_max). Any coordinates\n outside this range are ignored. So if the neighbors for a cell at the edge of the board are rquested, only\n neighbors that are on the board are returned.\n\n :param x:\n :param y:\n :return: List of neighbors\n \"\"\"\n return [(x+xo, y+yo) for xo, yo in self.offsets if 0 <= (x + xo) <= self.x_max and 0 <= (y + yo) <= self.y_max]\n\n def is_active(self, x: int, y: int) -> int:\n \"\"\" Whether the indicated cell is alive\n\n :param x:\n :param y:\n :return: 1 if it is alive, 0 otherwise\n \"\"\"\n return 1 if (x, y) in self.active_cells else 0\n\n def num_active_neighbors(self, x, y) -> int:\n \"\"\" How many neighbors of (x,y) are alive\n\n :param x:\n :param y:\n :return:\n \"\"\"\n return sum([self.is_active(nx, ny) for nx, ny in self.all_neighbors(x, y)])\n\n def clear(self):\n \"\"\" Set active_cells to an empty set, indicating that no cells are alive\n\n :return:\n \"\"\"\n self.active_cells = set()\n\n def random(self, p: Union[float, int]):\n \"\"\" Set some cells randomly to being alive\n\n :param p: If in the range of 0 to 1, select that proportion of cells to make alive. Otherwise treat as the\n number of cells to make alive.\n :return:\n \"\"\"\n if p<1:\n numcells = int(self.x_max*self.y_max*p)\n else:\n numcells = int(p)\n self.active_cells.update(set([(np.random.randint(0, self.x_max), np.random.randint(0, self.y_max)) for _ in range(0, numcells)]))\n\n\n def step(self, x_max: Optional[int] = None, y_max: Optional[int] = None):\n \"\"\" Update the state.\n\n Run one generation.\n\n :param x_max: The largest x value for the visible board\n :param y_max: The largest y value for the visible board\n :return: In addition to setting the local active_cells variable, return the set of active cells.\n \"\"\"\n self.x_max = self.x_max if x_max is None else x_max\n self.y_max = self.y_max if y_max is None else y_max\n new_state = set()\n for c in self.active_cells:\n active_neighbors = self.num_active_neighbors(c[0], c[1])\n if active_neighbors == 2 or active_neighbors == 3:\n new_state.update([c])\n for neighbor in self.all_neighbors(c[0], c[1]):\n if neighbor not in self.active_cells and neighbor not in new_state:\n if self.num_active_neighbors(neighbor[0], neighbor[1]) == 3:\n new_state.update([neighbor])\n self.active_cells = new_state\n return self.active_cells\n\n\nBuilder.load_string('''\n<GameOfLifePanel>:\n orientation: 'vertical'\n BoxLayout:\n orientation: 'horizontal'\n size_hint: 1, None\n size: 0, 50\n Button:\n text: 'Random'\n on_press: root.new_random(.2)\n Button:\n text: 'Add 100 Random'\n on_press: root.gol.random(100)\n Button:\n text: 'Random Ship'\n on_press: root.random_small()\n Button:\n id: menu_btn\n text: 'Patterns'\n on_release: root.choose_patterns()\n PixelatedGrid:\n id: grid \n size_hint: 1,1 \n activated_color: root.activated_color\n background_color: root.background_color\n grid_color: root.grid_color\n cell_length: root.cell_length\n''')\n\n\nclass GameOfLifePanel(BoxLayout):\n \"\"\" The Kivy panel that displays the Game of Life, along with some controls.\n\n The user can randomize the screen with a button press, or add random live cells with another button press.\n\n Key Properties:\n * update_rate: number of seconds between each generation\n * random_cell_count: Either percentage of cells to make alive or the number of cells to make alive when randomizing.\n * background_color - RGBA list for the inactive cell color\n * grid_color - RGBA for the grid lines\n * activated_color - RGBA for the active cell color\n * cell_length - the length of the side of a cell (essentially cell size)\n\n \"\"\"\n gol: GameOfLifeEngine\n pattern_dropdown: ObjectProperty(None)\n activated_color = ListProperty([0, 1, 1, 1])\n background_color = ListProperty([0, 0, 0, 1])\n grid_color = ListProperty([47/255, 79/255, 79/255, 1])\n cell_length = NumericProperty(10)\n initialized = False\n update_event = None\n update_rate = NumericProperty(0.1)\n random_cell_count = NumericProperty(0.2)\n\n def __init__(self, **kwargs):\n \"\"\" Create a new GameOfLifePanel instance\n\n Creates a new engine instance.\n\n :param kwargs:\n \"\"\"\n super(GameOfLifePanel, self).__init__(**kwargs)\n self.gol = GameOfLifeEngine()\n self.pattern_dropdown = DropDown()\n for t in initial_patterns.keys():\n b = Button(text=t)\n b.size_hint_y = None\n b.height = 44\n b.bind(on_release = lambda btn: self.set_pattern(btn.text))\n self.pattern_dropdown.add_widget(b)\n\n def choose_patterns(self, *args):\n self.pattern_dropdown.open(self.ids.menu_btn)\n\n def random_small(self):\n k = np.random.choice(list(basic_patterns.keys()))\n pattern = basic_patterns[k]\n for _ in range(0,np.random.randint(0, 4)):\n pattern = rotate_90(pattern, (0,0))\n xt = np.random.randint(0, self.ids.grid.visible_width())\n yt = np.random.randint(0, self.ids.grid.visible_height())\n self.gol.active_cells = self.gol.active_cells.union(translate(pattern, xt, yt))\n\n\n\n def set_pattern(self, pattern_name):\n self.pattern_dropdown.select(None)\n self.gol.clear()\n pattern = initial_patterns[pattern_name]\n pattern_xt = int((self.ids.grid.visible_width()/2)-(max([p[0] for p in pattern])-min([p[0] for p in pattern]))/2)\n pattern_yt = int((self.ids.grid.visible_height()/2)-(max([p[1] for p in pattern])-min([p[1] for p in pattern]))/2)\n self.gol.active_cells = translate(initial_patterns[pattern_name], pattern_xt, pattern_yt)\n\n\n def gol_update(self, *args):\n \"\"\" Move the engine ahead one generation, passing in the current size of the grid\n\n :param args: Unused\n :return:\n \"\"\"\n new_state = self.gol.step(self.ids.grid.visible_width(), self.ids.grid.visible_height())\n self.ids.grid.activated_cells = new_state\n\n def new_random(self, p: Union[float, int], *args):\n \"\"\" Clear the grid and add a random number of living cells\n\n :param p: If in the range of 0 to 1, select that proportion of cells to make alive. Otherwise treat as the\n number of cells to make alive.\n :param args: Unused\n :return:\n \"\"\"\n self.gol.clear()\n self.gol.random(p)\n\n def dp_stop(self):\n \"\"\" Cancel the event that updates the grid.\n\n :return:\n \"\"\"\n if self.update_event is not None:\n self.update_event.cancel()\n self.update_event = None\n\n def dp_start(self):\n \"\"\" Start the event that updates the grid\n\n :return:\n \"\"\"\n if not self.initialized:\n self.gol.random(self.random_cell_count)\n self.initialized = True\n self.update_event = Clock.schedule_interval(self.gol_update, self.update_rate)\n\n\nclass GameOfLifeApp(App):\n \"\"\" For demonstration.\n\n \"\"\"\n\n def build(self):\n #panel = GameOfLifePanel()\n panel = Builder.load_string(\"\"\"\nGameOfLifePanel:\n cell_length: 5 \n\"\"\")\n panel.dp_start()\n return panel\n\n\nif __name__ == \"__main__\":\n GameOfLifeApp().run()\n" ]
[ [ "numpy.random.randint" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
chensjtu/poxture
[ "f6abea1216c987f0e4c628b250054d764eaecf2e", "f6abea1216c987f0e4c628b250054d764eaecf2e", "f6abea1216c987f0e4c628b250054d764eaecf2e" ]
[ "models/losses.py", "scripts/train/prepare_motionSynthetic_dataset.py", "lib/model/complete_net.py" ]
[ "# this code is for calculate the VGGloss, which also called percetual loss.\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torchvision import models\nfrom typing import Union\nimport math\n\nclass VGG19(nn.Module):\n \"\"\"\n Sequential(\n (0): Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n\n (1): ReLU(inplace)\n (2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n (3): ReLU(inplace)\n (4): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n (5): Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n\n (6): ReLU(inplace)\n (7): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n (8): ReLU(inplace)\n (9): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n (10): Conv2d(128, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n\n (11): ReLU(inplace)\n (12): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n (13): ReLU(inplace)\n (14): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n (15): ReLU(inplace)\n (16): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n (17): ReLU(inplace)\n (18): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n (19): Conv2d(256, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n\n (20): ReLU(inplace)\n (21): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n (22): ReLU(inplace)\n (23): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n (24): ReLU(inplace)\n (25): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n (26): ReLU(inplace)\n (27): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n (28): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n\n (29): ReLU(inplace)\n xxxx(30): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n xxxx(31): ReLU(inplace)\n xxxx(32): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n xxxx(33): ReLU(inplace)\n xxxx(34): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n xxxx(35): ReLU(inplace)\n xxxx(36): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n )\n \"\"\"\n\n def __init__(self, ckpt_path: Union[str, bool] = \"./extradata/assets/pretrains/vgg19-dcbb9e9d.pth\",\n requires_grad=False, before_relu=False):\n super(VGG19, self).__init__()\n\n if False:\n vgg_pretrained_features = models.vgg19(pretrained=False).features\n ckpt = torch.load(ckpt_path, map_location=\"cpu\")\n vgg_pretrained_features.load_state_dict(ckpt, strict=False)\n else:\n vgg_pretrained_features = models.vgg19(pretrained=True).features\n\n # print(f\"Loading vgg19 from {ckpt_path}...\")\n\n if before_relu:\n slice_ids = [1, 6, 11, 20, 29]\n else:\n slice_ids = [2, 7, 12, 21, 30]\n\n self.slice1 = torch.nn.Sequential()\n self.slice2 = torch.nn.Sequential()\n self.slice3 = torch.nn.Sequential()\n self.slice4 = torch.nn.Sequential()\n self.slice5 = torch.nn.Sequential()\n for x in range(slice_ids[0]):\n self.slice1.add_module(str(x), vgg_pretrained_features[x])\n for x in range(slice_ids[0], slice_ids[1]):\n self.slice2.add_module(str(x), vgg_pretrained_features[x])\n for x in range(slice_ids[1], slice_ids[2]):\n self.slice3.add_module(str(x), vgg_pretrained_features[x])\n for x in range(slice_ids[2], slice_ids[3]):\n self.slice4.add_module(str(x), vgg_pretrained_features[x])\n for x in range(slice_ids[3], slice_ids[4]):\n self.slice5.add_module(str(x), vgg_pretrained_features[x])\n\n if not requires_grad:\n for param in self.parameters():\n param.requires_grad = False\n\n def forward(self, X):\n h_out1 = self.slice1(X)\n h_out2 = self.slice2(h_out1)\n h_out3 = self.slice3(h_out2)\n h_out4 = self.slice4(h_out3)\n h_out5 = self.slice5(h_out4)\n out = [h_out1, h_out2, h_out3, h_out4, h_out5]\n return out\n\nclass VGG16(nn.Module):\n \"\"\"\n Sequential(\n (0): Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n\n (1): ReLU(inplace=True)\n (2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n (3): ReLU(inplace=True)\n (4): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n (5): Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n\n (6): ReLU(inplace=True)\n (7): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n (8): ReLU(inplace=True)\n (9): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n (10): Conv2d(128, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n\n (11): ReLU(inplace=True)\n (12): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n (13): ReLU(inplace=True)\n (14): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n (15): ReLU(inplace=True)\n (16): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n (17): Conv2d(256, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n\n (18): ReLU(inplace=True)\n (19): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n (20): ReLU(inplace=True)\n (21): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n (22): ReLU(inplace=True)\n (23): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n (24): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n\n (25): ReLU(inplace=True)\n xxxx(26): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n xxxx(27): ReLU(inplace=True)\n xxxx(28): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n xxxx(29): ReLU(inplace=True)\n xxxx(30): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n )\n \"\"\"\n\n def __init__(self, ckpt_path=False, requires_grad=False, before_relu=False):\n super(VGG16, self).__init__()\n vgg_pretrained_features = models.vgg16(pretrained=True).features\n print(\"loading vgg16 ...\")\n\n if before_relu:\n slice_ids = [1, 6, 11, 18, 25]\n else:\n slice_ids = [2, 7, 12, 19, 26]\n\n self.slice1 = torch.nn.Sequential()\n self.slice2 = torch.nn.Sequential()\n self.slice3 = torch.nn.Sequential()\n self.slice4 = torch.nn.Sequential()\n self.slice5 = torch.nn.Sequential()\n for x in range(slice_ids[0]):\n self.slice1.add_module(str(x), vgg_pretrained_features[x])\n for x in range(slice_ids[0], slice_ids[1]):\n self.slice2.add_module(str(x), vgg_pretrained_features[x])\n for x in range(slice_ids[1], slice_ids[2]):\n self.slice3.add_module(str(x), vgg_pretrained_features[x])\n for x in range(slice_ids[2], slice_ids[3]):\n self.slice4.add_module(str(x), vgg_pretrained_features[x])\n for x in range(slice_ids[3], slice_ids[4]):\n self.slice5.add_module(str(x), vgg_pretrained_features[x])\n\n if not requires_grad:\n for param in self.parameters():\n param.requires_grad = False\n\n def forward(self, X):\n h_out1 = self.slice1(X)\n h_out2 = self.slice2(h_out1)\n h_out3 = self.slice3(h_out2)\n h_out4 = self.slice4(h_out3)\n h_out5 = self.slice5(h_out4)\n out = [h_out1, h_out2, h_out3, h_out4, h_out5]\n return out\n\nclass VGG11(nn.Module):\n \"\"\"\n Sequential(\n (0): Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n\n (1): ReLU(inplace=True)\n (2): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n (3): Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n\n (4): ReLU(inplace=True)\n (5): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n (6): Conv2d(128, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n\n (7): ReLU(inplace=True)\n (8): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n (9): ReLU(inplace=True)\n (10): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n (11): Conv2d(256, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n\n (12): ReLU(inplace=True)\n (13): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n (14): ReLU(inplace=True)\n (15): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n (16): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n\n (17): ReLU(inplace=True)\n (18): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n ###(19): ReLU(inplace=True)\n ###(20): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n )\n\n \"\"\"\n def __init__(self, ckpt_path=False, requires_grad=False, before_relu=False):\n super(VGG11, self).__init__()\n vgg_pretrained_features = models.vgg11(pretrained=True).features\n print(\"loading vgg11 ...\")\n\n if before_relu:\n slice_ids = [1, 4, 7, 12, 17]\n else:\n slice_ids = [2, 5, 8, 13, 18]\n\n self.slice1 = torch.nn.Sequential()\n self.slice2 = torch.nn.Sequential()\n self.slice3 = torch.nn.Sequential()\n self.slice4 = torch.nn.Sequential()\n self.slice5 = torch.nn.Sequential()\n for x in range(slice_ids[0]):\n self.slice1.add_module(str(x), vgg_pretrained_features[x])\n for x in range(slice_ids[0], slice_ids[1]):\n self.slice2.add_module(str(x), vgg_pretrained_features[x])\n for x in range(slice_ids[1], slice_ids[2]):\n self.slice3.add_module(str(x), vgg_pretrained_features[x])\n for x in range(slice_ids[2], slice_ids[3]):\n self.slice4.add_module(str(x), vgg_pretrained_features[x])\n for x in range(slice_ids[3], slice_ids[4]):\n self.slice5.add_module(str(x), vgg_pretrained_features[x])\n\n if not requires_grad:\n for param in self.parameters():\n param.requires_grad = False\n\n def forward(self, X):\n h_out1 = self.slice1(X)\n h_out2 = self.slice2(h_out1)\n h_out3 = self.slice3(h_out2)\n h_out4 = self.slice4(h_out3)\n h_out5 = self.slice5(h_out4)\n out = [h_out1, h_out2, h_out3, h_out4, h_out5]\n return out\n\ndef gram_matrix(input):\n a, b, c, d = input.size() # a=batch size(=1)\n # b=number of feature maps\n # (c,d)=dimensions of a f. map (N=c*d)\n features = input.view(a * b, c * d) # resise F_XL into \\hat F_XL\n G = torch.mm(features, features.t()) # compute the gram product\n # we 'normalize' the values of the gram matrix\n # by dividing by the number of element in each feature maps.\n return G.div(a * b * c * d)\n\nclass Percetual_loss(nn.Module):\n def __init__(self, \n before_relu=False, slice_ids=(0, 1, 2, 3, 4), vgg_type=\"VGG19\", \n ckpt_path=False, resize=False, style_loss=False):\n super(Percetual_loss, self).__init__()\n self.device = torch.device('cuda')\n if vgg_type == \"VGG19\":\n self.vgg = VGG19(ckpt_path=ckpt_path, before_relu=before_relu).to(self.device)\n elif vgg_type == \"VGG16\":\n self.vgg = VGG16(ckpt_path=ckpt_path, before_relu=before_relu).to(self.device)\n else:\n self.vgg = VGG11(ckpt_path=ckpt_path, before_relu=before_relu).to(self.device)\n self.criterion = nn.L1Loss()\n # self.weights = [1.0/32, 1.0/16, 1.0/8, 1.0/4, 1.0]\n self.weights = [1.0, 1.0, 1.0, 1.0, 1.0]\n self.slice_ids = slice_ids\n self.style_loss = style_loss\n self.resize = resize\n\n def forward(self, x, y):\n '''\n x_vgg[i]: fake img\n y_vgg[i].detach(): ground_truth\n '''\n if self.resize:\n x = F.interpolate(x, size=(224, 224), mode=\"bilinear\", align_corners=True)\n y = F.interpolate(y, size=(224, 224), mode=\"bilinear\", align_corners=True)\n x_vgg, y_vgg = self.vgg(x), self.vgg(y)\n loss = 0\n style_loss = 0\n if self.style_loss:\n for i in self.slice_ids:\n style_loss += F.mse_loss(gram_matrix(x_vgg[i]), gram_matrix(y_vgg[i].detach()))\n\n for i in self.slice_ids:\n loss += self.weights[i] * self.criterion(x_vgg[i], y_vgg[i].detach())\n\n return loss+style_loss\n\n\nclass Style_loss(nn.Module):\n # not used.\n def __init__(self, target_feature):\n super(Style_loss, self).__init__()\n self.vgg = VGG19(ckpt_path=ckpt_path, before_relu=before_relu).to(self.device)\n self.target = gram_matrix(target_feature).detach()\n\n def forward(self, input):\n G = gram_matrix(input)\n self.loss = F.mse_loss(G, self.target)\n return input\n\n\nif __name__ == \"__main__\":\n # percetual_loss = Percetual_loss(ckpt_path='./extradata/assets/checkpoints/losses/vgg19-dcbb9e9d.pth')\n percetual_loss = Percetual_loss()\n # model = torch.hub.load('pytorch/vision:v0.6.0', 'vgg19', pretrained=True)\n # or any of these variants\n # model = torch.hub.load('pytorch/vision:v0.6.0', 'vgg11_bn', pretrained=True)\n # model = torch.hub.load('pytorch/vision:v0.6.0', 'vgg13', pretrained=True)\n # model = torch.hub.load('pytorch/vision:v0.6.0', 'vgg13_bn', pretrained=True)\n # model = torch.hub.load('pytorch/vision:v0.6.0', 'vgg16', pretrained=True)\n # model = torch.hub.load('pytorch/vision:v0.6.0', 'vgg16_bn', pretrained=True)\n # model = torch.hub.load('pytorch/vision:v0.6.0', 'vgg19', pretrained=True)\n # model = torch.hub.load('pytorch/vision:v0.6.0', 'vgg19_bn', pretrained=True)\n with torch.no_grad():\n for i in range(10):\n loss = percetual_loss(torch.zeros((4,3,256,256),device=0), torch.ones((4,3, 256, 256),device=0)) \n print(loss)\n print(\"lalala\")\n", "# Copyright (c) 2020-2021 impersonator.org authors (Wen Liu and Zhixin Piao). All rights reserved.\n\n\"\"\"\n\nAssume that we put the iPER data into $FashionVideo_root_dir\n\n1. Download the FashionVideo dataset, https://vision.cs.ubc.ca/datasets/fashion/\n 1.1 download the `fashion_train.txt` into $FashionVideo_root_dir:\n https://vision.cs.ubc.ca/datasets/fashion/resources/fashion_dataset/fashion_train.txt\n\n 1.2 download the `fashion_test.txt` into $FashionVideo_root_dir:\n https://vision.cs.ubc.ca/datasets/fashion/resources/fashion_dataset/fashion_test.txt\n\n 1.3 crawl each video in `fashion_train.txt`, as well as `fashion_test.txt` and\n save them into $FashionVideo_root_dir/videos\n\n The file structure of $FashionVideo_root_dir will be:\n\n $FashionVideo_root_dir:\n --fashion_train.txt\n --fashion_test.txt\n --videos:\n\n\n2. Preprocess all videos in $FashionVideo_root_dir/videos.\n\n\n3. Reorganize the processed data for evaluations, https://github.com/iPERDance/his_evaluators\n\n\n\"\"\"\n\nimport os\nimport argparse\nfrom tqdm import tqdm\nimport requests\nimport warnings\nimport math\nimport numpy as np\nimport torch\nfrom typing import List, Tuple\nimport cv2\nfrom concurrent.futures import ProcessPoolExecutor\n\nfrom iPERCore.services.options.meta_info import MetaInputInfo, MetaProcess\nfrom iPERCore.services.options.process_info import ProcessInfo\nfrom iPERCore.tools.utils.filesio.persistence import mkdir, load_pickle_file, write_pickle_file\nfrom iPERCore.tools.utils.filesio.cv_utils import read_cv2_img, save_cv2_img\nfrom iPERCore.tools.utils.multimedia.video import video2frames\nfrom iPERCore.tools.human_digitalizer.renders import SMPLRenderer\nfrom iPERCore.tools.human_digitalizer.bodynets import SMPL\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--output_dir\", type=str, required=True, help=\"the root directory of iPER dataset.\")\nparser.add_argument(\"--gpu_ids\", type=str, default=\"9\", help=\"the gpu ids.\")\n\nargs = parser.parse_args()\n\n# the render image size\nIMAGE_SIZE = 1080\nMotionSynthetic_root_dir = args.output_dir\nMotionSynthetic_video_dir = mkdir(os.path.join(MotionSynthetic_root_dir, \"videos\"))\nMotionSynthetic_poses_dir = mkdir(os.path.join(MotionSynthetic_root_dir, \"poses\"))\nMotionSynthetic_processed_dir = mkdir(os.path.join(MotionSynthetic_root_dir, \"primitives\"))\n\n\ndef download():\n pass\n\n\ndef render_mask(smpl, render, cams, poses, shapes, offsets,\n img_dir, image_names, parse_out_dir, visual_path):\n \"\"\"\n\n Args:\n smpl (SMPL):\n render (SMPLRenderer):\n cams:\n poses:\n shapes:\n offsets:\n img_dir:\n image_names:\n parse_out_dir:\n visual_path:\n\n Returns:\n\n \"\"\"\n\n global IMAGE_SIZE\n\n length = cams.shape[0]\n\n device = torch.device(\"cuda:0\")\n\n offsets = torch.tensor(offsets).float().to(device)\n textures = render.color_textures().to(device)[None]\n\n fourcc = cv2.VideoWriter_fourcc(*\"XVID\")\n videoWriter = cv2.VideoWriter(visual_path, fourcc, 25, (IMAGE_SIZE, IMAGE_SIZE))\n\n print(f\"Preprocessing {img_dir}\")\n for i in tqdm(range(length)):\n img_name = image_names[i]\n name = img_name.split(\".\")[0]\n\n image = read_cv2_img(os.path.join(img_dir, img_name))\n\n cam = torch.from_numpy(cams[i: i+1]).to(device)\n shape = torch.from_numpy(shapes[i: i+1]).to(device)\n pose = torch.from_numpy(poses[i: i+1]).to(device)\n\n verts, _, _ = smpl(shape, pose, offsets=offsets, get_skin=True)\n\n rd_imgs, _ = render.render(cam, verts, textures)\n mask = render.render_silhouettes(cam, verts)[0]\n mask.unsqueeze_(-1)\n\n # (h, w, 1)\n mask = mask.cpu().numpy()\n\n # (3, h, w)\n rd_imgs = rd_imgs.cpu().numpy()[0]\n\n # (h, w, 3)\n rd_imgs = np.transpose(rd_imgs, (1, 2, 0))\n rd_imgs = (rd_imgs + 1) / 2 * 255\n rd_imgs = rd_imgs.astype(np.uint8)\n overly_img = image * (1 - mask) + rd_imgs * mask\n\n parse_path = os.path.join(parse_out_dir, name + \"_alpha.png\")\n\n save_cv2_img(mask[:, :, 0] * 255, parse_path, transpose=False)\n\n overly_img = overly_img.astype(np.uint8)\n videoWriter.write(overly_img)\n\n videoWriter.release()\n\n\ndef prepare_process_info(vid_name):\n global MotionSynthetic_video_dir, MotionSynthetic_processed_dir\n\n vid_path = os.path.join(MotionSynthetic_video_dir, vid_name)\n\n name = vid_name.split(\".\")[0]\n meta_input = MetaInputInfo(\n path=vid_path,\n name=name\n )\n\n meta_process = MetaProcess(\n meta_input,\n root_primitives_dir=MotionSynthetic_processed_dir\n )\n\n process_info = ProcessInfo(meta_process)\n\n return process_info\n\n\ndef partition(gpu_ids):\n global MotionSynthetic_video_dir\n\n video_names = os.listdir(MotionSynthetic_video_dir)\n num_videos = len(video_names)\n num_gpus = len(gpu_ids)\n\n gpu_per_subs = int(math.ceil(num_videos / num_gpus))\n\n gpu_i = 0\n\n used_gpus = []\n all_process_partition = []\n for sub_i in range(0, num_videos, gpu_per_subs):\n sub_names_i = video_names[sub_i: sub_i + gpu_per_subs]\n\n single_gpu_process_partition = []\n for vid_name in sub_names_i:\n process_info = prepare_process_info(vid_name)\n single_gpu_process_partition.append(process_info)\n\n all_process_partition.append(single_gpu_process_partition)\n used_gpus.append(gpu_ids[gpu_i])\n\n gpu_i += 1\n\n return used_gpus, all_process_partition\n\n\ndef per_instance_func(smpl, render, process_info):\n \"\"\"\n\n Args:\n smpl (SMPL):\n render (SMPLRenderer):\n process_info (ProcessInfo):\n\n Returns:\n\n \"\"\"\n\n global MotionSynthetic_video_dir, MotionSynthetic_poses_dir\n\n # 1. dump video into frames and write indexes information into process_info[\"valid_img_info\"]\n input_info = process_info[\"input_info\"]\n name = input_info[\"meta_input\"][\"name\"]\n\n vid_path = input_info[\"meta_input\"][\"path\"]\n out_img_dir = process_info[\"out_img_dir\"]\n video2frames(vid_path=vid_path, out_dir=out_img_dir)\n\n img_names = os.listdir(out_img_dir)\n img_names.sort()\n\n img_ids = list(range(len(img_names)))\n\n process_info[\"valid_img_info\"][\"names\"] = img_names\n process_info[\"valid_img_info\"][\"ids\"] = img_ids\n process_info[\"valid_img_info\"][\"crop_ids\"] = img_ids\n process_info[\"valid_img_info\"][\"pose3d_ids\"] = img_ids\n process_info[\"valid_img_info\"][\"parse_ids\"] = img_ids\n process_info[\"valid_img_info\"][\"stage\"] = \"parser\"\n\n # 2. write the smpl information into process_info[\"processed_pose3d\"]\n smpl_path = os.path.join(MotionSynthetic_poses_dir, name, \"pose_shape.pkl\")\n\n \"\"\"\n The smpl_info contains:\n --cams (np.ndarray): (length, 3);\n --pose (np.ndarray): (length, 72);\n --shape (np.ndarray): (1, 10);\n --ft_ids (list): (4,);\n --bk_ids (list): (4,);\n --views (list): (8,) = [0, 45, 315, 90, 180, 135, 225, 270];\n --offsets (np.ndarray): (6890, 3)\n \"\"\"\n smpl_info = load_pickle_file(smpl_path)\n length = len(img_names)\n offsets = smpl_info[\"offsets\"]\n\n assert length == smpl_info[\"cams\"].shape[0], f\"{length} != {len(smpl_info['cams'])}\"\n\n # repeat (1, 10) to (length, 10)\n shape = np.tile(smpl_info[\"shape\"], (length, 1))\n process_info[\"processed_pose3d\"][\"cams\"] = smpl_info[\"cams\"]\n process_info[\"processed_pose3d\"][\"pose\"] = smpl_info[\"pose\"]\n process_info[\"processed_pose3d\"][\"shape\"] = shape\n\n # 3. write the frontal information into process_info[\"processed_front_info\"]\n process_info[\"processed_front_info\"][\"ft\"][\"ids\"] = smpl_info[\"ft_ids\"] + smpl_info[\"bk_ids\"]\n process_info[\"processed_front_info\"][\"bk\"][\"ids\"] = smpl_info[\"bk_ids\"] + smpl_info[\"ft_ids\"]\n\n # 4. render mask\n parse_out_dir = process_info[\"out_parse_dir\"]\n visual_path = process_info[\"out_visual_path\"]\n\n # render_mask(\n # smpl, render, smpl_info[\"cams\"], smpl_info[\"pose\"], shape, offsets,\n # out_img_dir, img_names, parse_out_dir, visual_path\n # )\n\n process_info[\"has_run_detector\"] = True\n process_info[\"has_run_cropper\"] = True\n process_info[\"has_run_3dpose\"] = True\n process_info[\"has_find_front\"] = True\n process_info[\"has_run_parser\"] = True\n process_info[\"has_run_inpaintor\"] = True\n process_info[\"has_run_deform\"] = True\n process_info[\"has_finished\"] = True\n\n process_info.serialize()\n\n\ndef process_func(gpu_id, process_info_list):\n\n os.environ[\"CUDA_DEVICES_ORDER\"] = \"PCI_BUS_ID\"\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = str(gpu_id)\n\n device = torch.device(\"cuda:0\")\n render = SMPLRenderer(image_size=IMAGE_SIZE).to(device)\n smpl = SMPL().to(device)\n\n print(f\"----------------------------gpu_id = {gpu_id}----------------------\")\n for process_info in process_info_list:\n print(gpu_id, process_info)\n per_instance_func(smpl, render, process_info)\n\n\ndef process_data():\n global args\n\n gpu_ids = args.gpu_ids\n gpu_ids = gpu_ids.split(\",\")\n\n used_gpus, all_process_partition = partition(gpu_ids=gpu_ids)\n\n with ProcessPoolExecutor(max_workers=min(len(gpu_ids), os.cpu_count())) as pool:\n pool.map(process_func, used_gpus, all_process_partition)\n\n # for gpu_id, process_info_list in zip(used_gpus, all_process_partition):\n # process_func(gpu_id, process_info_list)\n\n\ndef reorganize():\n # TODO\n pass\n\n\n# def copy_offsets_smpl_info():\n# global MotionSynthetic_root_dir, MotionSynthetic_poses_dir\n#\n# people_snapshot_dir = \"/p300/tpami/datasets/round-1-datasets/motionSynthetic/people_snapshot_public\"\n#\n# vid_names = os.listdir(MotionSynthetic_poses_dir)\n#\n# for vid_name in vid_names:\n# smpl_path = os.path.join(MotionSynthetic_poses_dir, vid_name, \"pose_shape.pkl\")\n# smpl_info = load_pickle_file(smpl_path)\n#\n# if vid_name.startswith(\"PeopleSnapshot\"):\n# people_snapshot_name = vid_name.split(\"_\")[1]\n# people_snapshot_vid_dir = os.path.join(people_snapshot_dir, people_snapshot_name)\n#\n# v_info = load_pickle_file(os.path.join(people_snapshot_vid_dir, \"consensus.pkl\"))\n# offsets = v_info[\"v_personal\"]\n#\n# smpl_info[\"offsets\"] = offsets\n# else:\n# smpl_info[\"offsets\"] = np.zeros((6890, 3), dtype=np.float32)\n#\n# write_pickle_file(smpl_path, smpl_info)\n#\n# print(smpl_path)\n\n\nif __name__ == \"__main__\":\n # download()\n process_data()\n # copy_offsets_smpl_info()\n", "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport functools\nfrom .SurfaceClassifier import conv1_1, period_loss\n# from .DepthNormalizer import DepthNormalizer\nfrom ..net_util import *\n# from iPERCore.models.networks.criterions import VGGLoss\nfrom lib.model.Models import NestedUNet\nimport numpy as np\n\n\nclass Pint_Model(nn.Module):\n def __init__(self, opt):\n super(Pint_Model, self).__init__()\n self.period_loss = period_loss()\n self.feat_uv_error = nn.SmoothL1Loss() # A feature with B uvmap\n self.opt = opt\n self.NUnet = NestedUNet(in_ch=3, out_ch=3)\n norm_type = get_norm_layer(norm_type=opt.norm_color)\n self.image_filter = ResnetFilter(opt, norm_layer=norm_type)\n # self.conv = conv1_1(input_layers=256, output_layers=16)\n init_net(self)\n\n def filter(self, images):\n '''\n Filter the input images\n store all intermediate features.\n :param images: [B, C, H, W] input images\n '''\n self.im_feat = self.image_filter(images)\n\n def forward(self, uv_A, uv_B, part_uv_B, index):\n '''\n this function is made for pint total train.\n '''\n complete_feat = self.NUnet(uv_A)\n complete_feat_B = self.NUnet(uv_B)\n \n # im_feat = self.image_filter(uv_A) # B C H W for 512 uv_B, B 256 128 128\n # complete_feat = self.conv(im_feat) # B 16 128 128 -> b 16 512 512 [0:3] loss\n\n # im_feat_B = self.image_filter(uv_B)\n # complete_feat_B = self.conv(im_feat_B)\n # A_feat = F.interpolate(complete_feat[:,0:3,:,:], scale_factor=4, mode='bilinear', align_corners=True) # in this param, A_feat means complete feature.\n\n # part_uv_B.requires_grad=True # to make uvb as one leaf\n # A_feat = complete_feat[:,0:3,:,:]\n # part_uv_B = F.interpolate(part_uv_B, scale_factor=0.25, mode='bilinear', align_corners=True)\n \n A_vis_feat = complete_feat[index==1]\n B_vis_uv = part_uv_B[index==1]\n\n loss1 = self.feat_uv_error(A_vis_feat, B_vis_uv.detach())\n # loss2 = self.vgg_loss(complete_feat[:,:3], complete_feat_B[:,:3].detach())\n # loss2 = self.period_loss(complete_feat, complete_feat_B.detach())\n loss2=0\n return complete_feat, complete_feat_B, loss1, loss2\n\n # def pint_forward(self, uv_A, uv_B):\n # '''\n # this function is made for pint total train.\n # '''\n # im_feat = self.image_filter(uv_A) # B C H W for 512 uv_B, B 256 128 128\n # self.complete_feat = self.conv(im_feat) # B 16 128 128 -> b 16 512 512 [0:3] loss\n\n # im_feat_B = self.image_filter(uv_B.squeeze(1))\n # complete_feat_B = self.conv(im_feat_B)\n # A_feat = F.interpolate(self.complete_feat[:,0:3,:,:], scale_factor=4, mode='bilinear', align_corners=True) # in this param, A_feat means complete feature.\n # uv_B_feat = uv_B.squeeze(1).expand_as(A_feat)\n # uv_B_feat.requires_grad=True # to make uvb as one leaf\n # A_vis_feat = A_feat[uv_B_feat != 0.0]\n # B_vis_uv = uv_B_feat[uv_B_feat != 0.0]\n # loss_content = self.feat_uv_error(A_vis_feat, B_vis_uv) * 100\n # loss_content1 = self.feat_uv_error(A_feat, uv_A)*100\n # # loss_feat = self.error_term(self.complete_feat, complete_feat_B)\n # return A_feat, A_vis_feat, B_vis_uv, self.complete_feat, complete_feat_B, loss_content+loss_content1\n\nclass ResnetBlock(nn.Module):\n \"\"\"Define a Resnet block\"\"\"\n\n def __init__(self, dim, padding_type, norm_layer, use_dropout, use_bias, last=False):\n \"\"\"Initialize the Resnet block\n A resnet block is a conv block with skip connections\n We construct a conv block with build_conv_block function,\n and implement skip connections in <forward> function.\n Original Resnet paper: https://arxiv.org/pdf/1512.03385.pdf\n \"\"\"\n super(ResnetBlock, self).__init__()\n self.conv_block = self.build_conv_block(dim, padding_type, norm_layer, use_dropout, use_bias, last)\n\n def build_conv_block(self, dim, padding_type, norm_layer, use_dropout, use_bias, last=False):\n \"\"\"Construct a convolutional block.\n Parameters:\n dim (int) -- the number of channels in the conv layer.\n padding_type (str) -- the name of padding layer: reflect | replicate | zero\n norm_layer -- normalization layer\n use_dropout (bool) -- if use dropout layers.\n use_bias (bool) -- if the conv layer uses bias or not\n Returns a conv block (with a conv layer, a normalization layer, and a non-linearity layer (ReLU))\n \"\"\"\n conv_block = []\n p = 0\n if padding_type == 'reflect':\n conv_block += [nn.ReflectionPad2d(1)]\n elif padding_type == 'replicate':\n conv_block += [nn.ReplicationPad2d(1)]\n elif padding_type == 'zero':\n p = 1\n else:\n raise NotImplementedError('padding [%s] is not implemented' % padding_type)\n\n conv_block += [nn.Conv2d(dim, dim, kernel_size=3, padding=p, bias=use_bias), norm_layer(dim), nn.ReLU(True)]\n if use_dropout:\n conv_block += [nn.Dropout(0.5)]\n\n p = 0\n if padding_type == 'reflect':\n conv_block += [nn.ReflectionPad2d(1)]\n elif padding_type == 'replicate':\n conv_block += [nn.ReplicationPad2d(1)]\n elif padding_type == 'zero':\n p = 1\n else:\n raise NotImplementedError('padding [%s] is not implemented' % padding_type)\n if last:\n conv_block += [nn.Conv2d(dim, dim, kernel_size=3, padding=p, bias=use_bias)]\n else:\n conv_block += [nn.Conv2d(dim, dim, kernel_size=3, padding=p, bias=use_bias), norm_layer(dim)]\n\n return nn.Sequential(*conv_block)\n\n def forward(self, x):\n \"\"\"Forward function (with skip connections)\"\"\"\n out = x + self.conv_block(x) # add skip connections\n return out\n\nclass ResnetFilter(nn.Module):\n \"\"\"Resnet-based generator that consists of Resnet blocks between a few downsampling/upsampling operations.\n We adapt Torch code and idea from Justin Johnson's neural style transfer project(https://github.com/jcjohnson/fast-neural-style)\n \"\"\"\n\n def __init__(self, opt, input_nc=3, output_nc=256, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False,\n n_blocks=6, padding_type='reflect'):\n \"\"\"Construct a Resnet-based generator\n Parameters:\n input_nc (int) -- the number of channels in input images\n output_nc (int) -- the number of channels in output images\n ngf (int) -- the number of filters in the last conv layer\n norm_layer -- normalization layer\n use_dropout (bool) -- if use dropout layers\n n_blocks (int) -- the number of ResNet blocks\n padding_type (str) -- the name of padding layer in conv layers: reflect | replicate | zero\n \"\"\"\n assert (n_blocks >= 0)\n super(ResnetFilter, self).__init__()\n if type(norm_layer) == functools.partial:\n use_bias = norm_layer.func == nn.InstanceNorm2d\n else:\n use_bias = norm_layer == nn.InstanceNorm2d\n\n model = [nn.ReflectionPad2d(3),\n nn.Conv2d(input_nc, ngf, kernel_size=7, padding=0, bias=use_bias),\n norm_layer(ngf),\n nn.ReLU(True)]\n\n n_downsampling = 2\n for i in range(n_downsampling): # add downsampling layers\n mult = 2 ** i\n model += [nn.Conv2d(ngf * mult, ngf * mult * 2, kernel_size=3, stride=2, padding=1, bias=use_bias),\n norm_layer(ngf * mult * 2),\n nn.ReLU(True)]\n\n mult = 2 ** n_downsampling\n for i in range(n_blocks): # add ResNet blocks\n if i == n_blocks - 1:\n model += [ResnetBlock(ngf * mult, padding_type=padding_type, norm_layer=norm_layer,\n use_dropout=use_dropout, use_bias=use_bias, last=True)]\n else:\n model += [ResnetBlock(ngf * mult, padding_type=padding_type, norm_layer=norm_layer,\n use_dropout=use_dropout, use_bias=use_bias)]\n\n if opt.use_tanh:\n model += [nn.Tanh()]\n \n self.model = nn.Sequential(*model)\n\n def forward(self, input):\n \"\"\"Standard forward\"\"\"\n return self.model(input)\n" ]
[ [ "torch.nn.Sequential", "torch.ones", "torch.load", "torch.zeros", "torch.nn.functional.mse_loss", "torch.no_grad", "torch.nn.functional.interpolate", "torch.device", "torch.nn.L1Loss" ], [ "torch.from_numpy", "numpy.tile", "torch.tensor", "numpy.transpose", "torch.device" ], [ "torch.nn.SmoothL1Loss", "torch.nn.Sequential", "torch.nn.Dropout", "torch.nn.ReflectionPad2d", "torch.nn.Conv2d", "torch.nn.Tanh", "torch.nn.ReLU", "torch.nn.ReplicationPad2d" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
dssg/babies-public
[ "0a03e95992bfd7b7b4c2f11b8a5e2c3961f193c6" ]
[ "webapp/proto.py" ]
[ "import pandas as pd\nimport numpy as np\nimport psycopg2\nfrom sqlalchemy import create_engine\nimport json\nimport sys\nfrom sklearn.externals import joblib\nimport os\n\ndef run_all():\n\n # connect to postgres \n params = json.load(open('/home/ipan/passwords/psql_psycopg2.password', 'r'))\n\n try:\n conn = psycopg2.connect(**params)\n conn.autocommit\n cur = conn.cursor()\n\n except:\n print('Unable to connect to database')\n\n # import from babysaver\n sys.path.insert(0, '/home/ipan/babies/')\n from babysaver import features\n from babysaver import models\n from babysaver.models import WeightedQuestions\n from sklearn.linear_model import LogisticRegression\n from babysaver import evaluation\n\n # specify dat configuration in a dictionary\n config_add1 = {'Features': None, \n 'Include 707G?': 'Y', \n '707G Questions': range(35,52), \n '707G Start Date': '2014-07-01', \n '707G End Date': None,\n 'Include 711?': 'N', \n '711 Questions': None, \n '711 Start Date': None, \n '711 End Date': None, \n 'Include FCM?': 'Y', \n 'Include BBO?': 'Y', \n 'Include other?': 'Y', \n 'Outcome': 'ADVB1_OTC'}\n\n # use config_writer to write dictionary to csv file \n features.config_writer(config_add1, '/home/ipan/configs/config_add1.csv')\n # then use that csv file to load in the data \n data_dct = features.data_getter('/home/ipan/configs/config_add1.csv', \n conn=conn, \n unique_identifier='UNI_PART_ID_I', \n impute='fill_mode',\n interactions=False)\n\n # specify hyperparameter lists\n c_list = [1e-4, 1e-3, 0.01, 0.1, 1, 10, 100, 1e3, 1e4, 1e20]\n penalties = ['l2']\n class_wgts = [None, 'auto']\n\n wgt_schemes = ['odds_ratio_relative', 'odds_ratio_absolute', \n 'marginal_effects', 'positive_coefs']\n\n # specify classifier dictionaries \n expand_wgt = {'clf': WeightedQuestions,\n 'param_dict': {'C': c_list,\n 'penalty': penalties, \n 'class_weight': class_wgts,\n 'weight_scheme': wgt_schemes,\n 'round_dec': [1]\n }\n }\n\n simple_wgt = {'clf': WeightedQuestions,\n 'param_dict': {'C': c_list,\n 'penalty': penalties, \n 'class_weight': class_wgts,\n 'weight_scheme': wgt_schemes,\n 'round_dec': [0]\n }\n }\n\n\n log_lib = {'clf': LogisticRegression,\n 'param_dict': {'C': c_list,\n 'penalty': penalties,\n 'class_weight': class_wgts\n }\n }\n\n # specify list of k for precision at k\n k_list = [0.05, 0.1, 0.15, 0.2, 0.25, 0.3]\n\n # train a bunch of classifiers for each type of classifier\n # I wanted to find the best one of each, so I did each one separately\n expand_evals, expand_pkls = models.machine_learner(data_dct, \n clf_library=expand_wgt,\n pkl_folder='e_pkls',\n cv='kfold_cv',\n k=k_list,\n n_folds=10)\n\n simple_evals, simple_pkls = models.machine_learner(data_dct,\n clf_library=simple_wgt,\n pkl_folder='s_pkls',\n cv='kfold_cv',\n k=k_list,\n n_folds=10)\n\n log_evals, log_pkls = models.machine_learner(data_dct,\n clf_library=log_lib,\n pkl_folder='log_pkls',\n cv='kfold_cv',\n k=k_list,\n n_folds=10)\n\n # concatenate all the dataframes into one dataframe using\n # output of machine learner \n expand_df = evaluation.dict_to_dataframe(expand_evals, expand_pkls)\n simple_df = evaluation.dict_to_dataframe(simple_evals, simple_pkls)\n log_df = evaluation.dict_to_dataframe(log_evals, log_pkls)\n\n # metric(s) to sort classifiers by \n sort_metrics = ['precision at 0.1 mean', 'precision at 0.15 mean']\n # mapping between question number and text\n map_file = '/home/ipan/707G_question_map.csv'\n\n # get a dataframe with weights and question text\n expand_wgts = evaluation.weight_mapper(data_dct, expand_df, \n sort_metrics, map_file, '707G')\n expand_wgts.columns = ['QID', 'Question', 'Expanded Weights']\n simple_wgts = evaluation.weight_mapper(data_dct, simple_df,\n sort_metrics, map_file, '707G')\n simple_wgts.columns = ['QID', 'Question', 'Simple Weights']\n log_wgts = evaluation.weight_mapper(data_dct, log_df, sort_metrics,\n map_file, '707G')\n \n all_wgts = log_wgts.join([expand_wgts['Expanded Weights'], \n simple_wgts['Simple Weights']])\n\n # load in models \n log_df = log_df.sort(sort_metrics, ascending=False)\n log_model = joblib.load(log_df['pickle_file'][0])\n ew_model = joblib.load(expand_df.sort(sort_metrics, ascending=False)['pickle_file'][0])\n sw_model = joblib.load(simple_df.sort(sort_metrics, ascending=False)['pickle_file'][0])\n\n df = data_dct['dataframe']\n feats = data_dct['features']\n log_scores = log_model.predict_proba(df[feats])[:,1]\n pd.DataFrame({'scores': log_scores}).to_csv('scores.csv', index=False)\n # calculate overall rate of adverse births\n baseline_rate = np.round(df[data_dct['outcome']].mean()*100,1)\n\n # calculate scores \n ew_scores = ew_model.predict_proba(df[feats])[:,1]\n sw_scores = sw_model.predict_proba(df[feats])[:,1]\n\n # get metrics for various values of k\n expand_mets = evaluation.metrics_getter(data_dct, expand_df,\n sort_metrics, map_file,\n k_list, ew_scores)\n simple_mets = evaluation.metrics_getter(data_dct, simple_df,\n sort_metrics, map_file, \n k_list, sw_scores)\n log_mets = evaluation.metrics_getter(data_dct, log_df,\n sort_metrics, map_file,\n k_list, log_scores, scale=True)\n\n if not os.path.exists('best_pkl/'):\n os.makedirs('best_pkl/')\n\n # pickle the best logistic regression model for webapp prediction tool\n joblib.dump(log_model, 'best_pkl/best_model.pkl')\n\n return evaluation.weight_html(all_wgts), log_mets.to_html(), expand_mets.to_html(), simple_mets.to_html(), baseline_rate\n" ]
[ [ "sklearn.externals.joblib.dump", "sklearn.externals.joblib.load", "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": [] } ]
MingSungChao/IPN-hand
[ "0b061e4438f159e3e312af4959cb424917b5c367", "0b061e4438f159e3e312af4959cb424917b5c367", "0b061e4438f159e3e312af4959cb424917b5c367" ]
[ "test.py", "utils/nv_json.py", "models/mobilenetv2.py" ]
[ "import torch\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\nimport time\nimport os\nimport sys\nimport json\nimport pdb\n\nfrom utils import AverageMeter\n\n\ndef calculate_video_results(output_buffer, video_id, test_results, class_names):\n video_outputs = torch.stack(output_buffer)\n average_scores = torch.mean(video_outputs, dim=0)\n sorted_scores, locs = torch.topk(average_scores, k=2)\n\n video_results = []\n for i in range(sorted_scores.size(0)):\n video_results.append({\n 'label': class_names[locs[i].item()],\n 'score': sorted_scores[i].item()\n })\n test_results['results'][video_id] = video_results\n\n\ndef test(data_loader, model, opt, class_names):\n print('test')\n\n model.eval()\n\n batch_time = AverageMeter()\n data_time = AverageMeter()\n\n end_time = time.time()\n output_buffer = []\n previous_video_id = ''\n test_results = {'results': {}}\n for i, (inputs, targets) in enumerate(data_loader):\n data_time.update(time.time() - end_time)\n \n \n with torch.no_grad():\n inputs = Variable(inputs)\n targets = Variable(targets)\n outputs = model(inputs)\n\n if not opt.no_softmax_in_test:\n outputs = F.softmax(outputs)\n\n for j in range(outputs.size(0)):\n if not (i == 0 and j == 0) and targets[j].item() != previous_video_id:\n calculate_video_results(output_buffer, previous_video_id,\n test_results, class_names)\n output_buffer = []\n output_buffer.append(outputs[j].data.cpu())\n previous_video_id = targets[j].item()\n\n if (i % 100) == 0:\n with open(\n os.path.join(opt.result_path, '{}.json'.format(\n opt.test_subset)), 'w') as f:\n json.dump(test_results, f)\n\n batch_time.update(time.time() - end_time)\n end_time = time.time()\n\n print('[{}/{}]\\t'\n 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\n 'Data {data_time.val:.3f} ({data_time.avg:.3f})\\t'.format(\n i + 1,\n len(data_loader),\n batch_time=batch_time,\n data_time=data_time))\n with open(\n os.path.join(opt.result_path, '{}.json'.format(opt.test_subset)),\n 'w') as f:\n json.dump(test_results, f)\n", "from __future__ import print_function, division\nimport os\nimport sys\nimport json\nimport pandas as pd\n\ndef convert_csv_to_dict(csv_path, subset, labels):\n data = pd.read_csv(csv_path, delimiter=' ', header=None)\n keys = []\n key_labels = []\n key_start_frame = []\n key_end_frame = []\n for i in range(data.shape[0]):\n row = data.ix[i, :]\n class_name = labels[row[1]-1]\n \n basename = str(row[0])\n start_frame = str(row[2])\n end_frame = str(row[3])\n\n keys.append(basename)\n key_labels.append(class_name)\n key_start_frame.append(start_frame)\n key_end_frame.append(end_frame)\n \n database = {}\n for i in range(len(keys)):\n key = keys[i] \n if key in database: # need this because I have the same folder 3 times\n key = key + '^' + str(i) \n database[key] = {}\n database[key]['subset'] = subset\n label = key_labels[i]\n start_frame = key_start_frame[i]\n end_frame = key_end_frame[i]\n\n database[key]['annotations'] = {'label': label, 'start_frame':start_frame, 'end_frame':end_frame}\n \n return database\n\ndef load_labels(label_csv_path):\n data = pd.read_csv(label_csv_path, delimiter=' ', header=None)\n labels = []\n for i in range(data.shape[0]):\n labels.append(str(data.ix[i, 1]))\n return labels\n\ndef convert_nv_csv_to_activitynet_json(label_csv_path, train_csv_path, \n val_csv_path, dst_json_path):\n labels = load_labels(label_csv_path)\n train_database = convert_csv_to_dict(train_csv_path, 'training', labels)\n val_database = convert_csv_to_dict(val_csv_path, 'validation', labels)\n \n dst_data = {}\n dst_data['labels'] = labels\n dst_data['database'] = {}\n dst_data['database'].update(train_database)\n dst_data['database'].update(val_database)\n with open(dst_json_path, 'w') as dst_file:\n json.dump(dst_data, dst_file)\n\nif __name__ == '__main__':\n csv_dir_path = sys.argv[1]\n sens = sys.argv[2]\n for class_type in ['all', 'all_but_None', 'binary']:\n\n if class_type == 'all':\n class_ind_file = 'classIndAll.txt'\n elif class_type == 'all_but_None':\n class_ind_file = 'classIndAllbutNone.txt'\n elif class_type == 'binary':\n class_ind_file = 'classIndBinary.txt'\n\n\n label_csv_path = os.path.join(csv_dir_path, class_ind_file)\n train_csv_path = os.path.join(csv_dir_path, 'trainlist'+ class_type + '_' + sens + '.txt')\n val_csv_path = os.path.join(csv_dir_path, 'vallist'+ class_type + '_' + sens + '.txt')\n dst_json_path = os.path.join(csv_dir_path, 'nv' + class_type + '_' + sens + '.json')\n\n convert_nv_csv_to_activitynet_json(label_csv_path, train_csv_path,\n val_csv_path, dst_json_path)\n print('Successfully wrote to json : ', dst_json_path)\n # HOW TO RUN:\n # python nv_json.py '../annotation_nvGesture'\n", "'''MobilenetV2 in PyTorch.\n\nSee the paper \"MobileNetV2: Inverted Residuals and Linear Bottlenecks\" for more details.\n'''\nimport torch\nimport math\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\n\n\n__all__ = ['MobilenetV2', 'mob_v2']\n\ndef conv_bn(inp, oup, stride):\n return nn.Sequential(\n nn.Conv3d(inp, oup, kernel_size=3, stride=stride, padding=(1,1,1), bias=False),\n nn.BatchNorm3d(oup),\n nn.ReLU6(inplace=True)\n )\n\n\ndef conv_1x1x1_bn(inp, oup):\n return nn.Sequential(\n nn.Conv3d(inp, oup, 1, 1, 0, bias=False),\n nn.BatchNorm3d(oup),\n nn.ReLU6(inplace=True)\n )\n\n\nclass InvertedResidual(nn.Module):\n def __init__(self, inp, oup, stride, expand_ratio):\n super(InvertedResidual, self).__init__()\n self.stride = stride\n\n hidden_dim = round(inp * expand_ratio)\n self.use_res_connect = self.stride == (1,1,1) and inp == oup\n\n if expand_ratio == 1:\n self.conv = nn.Sequential(\n # dw\n nn.Conv3d(hidden_dim, hidden_dim, 3, stride, 1, groups=hidden_dim, bias=False),\n nn.BatchNorm3d(hidden_dim),\n nn.ReLU6(inplace=True),\n # pw-linear\n nn.Conv3d(hidden_dim, oup, 1, 1, 0, bias=False),\n nn.BatchNorm3d(oup),\n )\n else:\n self.conv = nn.Sequential(\n # pw\n nn.Conv3d(inp, hidden_dim, 1, 1, 0, bias=False),\n nn.BatchNorm3d(hidden_dim),\n nn.ReLU6(inplace=True),\n # dw\n nn.Conv3d(hidden_dim, hidden_dim, 3, stride, 1, groups=hidden_dim, bias=False),\n nn.BatchNorm3d(hidden_dim),\n nn.ReLU6(inplace=True),\n # pw-linear\n nn.Conv3d(hidden_dim, oup, 1, 1, 0, bias=False),\n nn.BatchNorm3d(oup),\n )\n\n def forward(self, x):\n if self.use_res_connect:\n return x + self.conv(x)\n else:\n return self.conv(x)\n\n\nclass MobileNetV2(nn.Module):\n def __init__(self, num_classes=1000, sample_size=224, width_mult=1.):\n super(MobileNetV2, self).__init__()\n block = InvertedResidual\n input_channel = 32\n last_channel = 1280\n interverted_residual_setting = [\n # t, c, n, s\n [1, 16, 1, (1,1,1)],\n [6, 24, 2, (2,2,2)],\n [6, 32, 3, (2,2,2)],\n [6, 64, 4, (2,2,2)],\n [6, 96, 3, (1,1,1)],\n [6, 160, 3, (2,2,2)],\n [6, 320, 1, (1,1,1)],\n ]\n\n # building first layer\n assert sample_size % 16 == 0.\n input_channel = int(input_channel * width_mult)\n self.last_channel = int(last_channel * width_mult) if width_mult > 1.0 else last_channel\n self.features = [conv_bn(3, input_channel, (1,2,2))]\n # building inverted residual blocks\n for t, c, n, s in interverted_residual_setting:\n output_channel = int(c * width_mult)\n for i in range(n):\n stride = s if i == 0 else (1,1,1)\n self.features.append(block(input_channel, output_channel, stride, expand_ratio=t))\n input_channel = output_channel\n # building last several layers\n self.features.append(conv_1x1x1_bn(input_channel, self.last_channel))\n # make it nn.Sequential\n self.features = nn.Sequential(*self.features)\n\n # building classifier\n self.classifier = nn.Sequential(\n nn.Dropout(0.2),\n nn.Linear(self.last_channel, num_classes),\n )\n\n self._initialize_weights()\n\n def forward(self, x):\n x = self.features(x)\n x = F.avg_pool3d(x, x.data.size()[-3:])\n x = x.view(x.size(0), -1)\n x = self.classifier(x)\n return x\n\n def _initialize_weights(self):\n for m in self.modules():\n if isinstance(m, nn.Conv3d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.kernel_size[2] * m.out_channels\n m.weight.data.normal_(0, math.sqrt(2. / n))\n if m.bias is not None:\n m.bias.data.zero_()\n elif isinstance(m, nn.BatchNorm3d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n elif isinstance(m, nn.Linear):\n n = m.weight.size(1)\n m.weight.data.normal_(0, 0.01)\n m.bias.data.zero_()\n\n\ndef get_fine_tuning_parameters(model, ft_begin_index):\n if ft_begin_index == 0:\n return model.parameters()\n\n ft_module_names = []\n for i in range(ft_begin_index, 5):\n ft_module_names.append('layer{}'.format(i))\n ft_module_names.append('fc')\n\n parameters = []\n for k, v in model.named_parameters():\n for ft_module in ft_module_names:\n if ft_module in k:\n parameters.append({'params': v})\n break\n else:\n parameters.append({'params': v, 'lr': 0.0})\n\n return parameters\n\n \ndef mob_v2(**kwargs):\n \"\"\"\n Returns the model.\n \"\"\"\n model = MobileNetV2(**kwargs)\n return model\n\n\nif __name__ == \"__main__\":\n model = mob_v2(num_classes=600, sample_size=112, width_mult=1.)\n model = model.cuda()\n model = nn.DataParallel(model, device_ids=None)\n print(model)\n\n\n input_var = Variable(torch.randn(8, 3, 16, 112, 112))\n output = model(input_var)\n print(output.shape)\n\n\n" ]
[ [ "torch.mean", "torch.nn.functional.softmax", "torch.topk", "torch.no_grad", "torch.stack", "torch.autograd.Variable" ], [ "pandas.read_csv" ], [ "torch.nn.Sequential", "torch.nn.Dropout", "torch.nn.ReLU6", "torch.randn", "torch.nn.Linear", "torch.nn.Conv3d", "torch.nn.DataParallel", "torch.nn.BatchNorm3d" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
mehrdad-shokri/astropy
[ "abd73b51277694338c8eca7639da956dcd06f207", "abd73b51277694338c8eca7639da956dcd06f207", "8930a14f69360d4db115a85ff9e0f6efa80fa2e7", "abd73b51277694338c8eca7639da956dcd06f207", "abd73b51277694338c8eca7639da956dcd06f207", "abd73b51277694338c8eca7639da956dcd06f207", "abd73b51277694338c8eca7639da956dcd06f207" ]
[ "astropy/utils/data_info.py", "astropy/coordinates/tests/test_skyoffset_transformations.py", "astropy/uncertainty/distributions.py", "astropy/coordinates/angle_utilities.py", "astropy/time/tests/test_mask.py", "astropy/coordinates/funcs.py", "astropy/wcs/wcsapi/fitswcs.py" ]
[ "# -*- coding: utf-8 -*-\n# Licensed under a 3-clause BSD style license - see LICENSE.rst\n\n\"\"\"This module contains functions and methods that relate to the DataInfo class\nwhich provides a container for informational attributes as well as summary info\nmethods.\n\nA DataInfo object is attached to the Quantity, SkyCoord, and Time classes in\nastropy. Here it allows those classes to be used in Tables and uniformly carry\ntable column attributes such as name, format, dtype, meta, and description.\n\"\"\"\n\n# Note: these functions and classes are tested extensively in astropy table\n# tests via their use in providing mixin column info, and in\n# astropy/tests/test_info for providing table and column info summary data.\n\n\nimport os\nimport re\nimport sys\nimport weakref\nimport warnings\nfrom io import StringIO\nfrom copy import deepcopy\nfrom functools import partial\nfrom collections import OrderedDict\nfrom contextlib import contextmanager\n\nimport numpy as np\n\nfrom . import metadata\n\n\n__all__ = ['data_info_factory', 'dtype_info_name', 'BaseColumnInfo',\n 'DataInfo', 'MixinInfo', 'ParentDtypeInfo']\n\n# Tuple of filterwarnings kwargs to ignore when calling info\nIGNORE_WARNINGS = (dict(category=RuntimeWarning, message='All-NaN|'\n 'Mean of empty slice|Degrees of freedom <= 0|'\n 'invalid value encountered in sqrt'),)\n\nSTRING_TYPE_NAMES = {(False, 'S'): 'str', # not PY3\n (False, 'U'): 'unicode',\n (True, 'S'): 'bytes', # PY3\n (True, 'U'): 'str'}\n\n\n@contextmanager\ndef serialize_context_as(context):\n \"\"\"Set context for serialization.\n\n This will allow downstream code to understand the context in which a column\n is being serialized. Objects like Time or SkyCoord will have different\n default serialization representations depending on context.\n\n Parameters\n ----------\n context : str\n Context name, e.g. 'fits', 'hdf5', 'ecsv', 'yaml'\n \"\"\"\n old_context = BaseColumnInfo._serialize_context\n BaseColumnInfo._serialize_context = context\n yield\n BaseColumnInfo._serialize_context = old_context\n\n\ndef dtype_info_name(dtype):\n \"\"\"Return a human-oriented string name of the ``dtype`` arg.\n This can be use by astropy methods that present type information about\n a data object.\n\n The output is mostly equivalent to ``dtype.name`` which takes the form\n <type_name>[B] where <type_name> is like ``int`` or ``bool`` and [B] is an\n optional number of bits which gets included only for numeric types.\n\n For bytes, string and unicode types, the output is shown below, where <N>\n is the number of characters. This representation corresponds to the Python\n type that matches the dtype::\n\n Numpy S<N> U<N>\n Python bytes<N> str<N>\n\n Parameters\n ----------\n dtype : str, np.dtype, type\n Input dtype as an object that can be converted via np.dtype()\n\n Returns\n -------\n dtype_info_name : str\n String name of ``dtype``\n \"\"\"\n dtype = np.dtype(dtype)\n if dtype.kind in ('S', 'U'):\n length = re.search(r'(\\d+)', dtype.str).group(1)\n type_name = STRING_TYPE_NAMES[(True, dtype.kind)]\n out = type_name + length\n else:\n out = dtype.name\n\n return out\n\n\ndef data_info_factory(names, funcs):\n \"\"\"\n Factory to create a function that can be used as an ``option``\n for outputting data object summary information.\n\n Examples\n --------\n >>> from astropy.utils.data_info import data_info_factory\n >>> from astropy.table import Column\n >>> c = Column([4., 3., 2., 1.])\n >>> mystats = data_info_factory(names=['min', 'median', 'max'],\n ... funcs=[np.min, np.median, np.max])\n >>> c.info(option=mystats)\n min = 1.0\n median = 2.5\n max = 4.0\n n_bad = 0\n length = 4\n\n Parameters\n ----------\n names : list\n List of information attribute names\n funcs : list\n List of functions that compute the corresponding information attribute\n\n Returns\n -------\n func : function\n Function that can be used as a data info option\n \"\"\"\n def func(dat):\n outs = []\n for name, func in zip(names, funcs):\n try:\n if isinstance(func, str):\n out = getattr(dat, func)()\n else:\n out = func(dat)\n except Exception:\n outs.append('--')\n else:\n outs.append(str(out))\n\n return OrderedDict(zip(names, outs))\n return func\n\n\ndef _get_obj_attrs_map(obj, attrs):\n \"\"\"\n Get the values for object ``attrs`` and return as a dict. This\n ignores any attributes that are None and in Py2 converts any unicode\n attribute names or values to str. In the context of serializing the\n supported core astropy classes this conversion will succeed and results\n in more succinct and less python-specific YAML.\n \"\"\"\n out = {}\n for attr in attrs:\n val = getattr(obj, attr, None)\n\n if val is not None:\n out[attr] = val\n return out\n\n\ndef _get_data_attribute(dat, attr=None):\n \"\"\"\n Get a data object attribute for the ``attributes`` info summary method\n \"\"\"\n if attr == 'class':\n val = type(dat).__name__\n elif attr == 'dtype':\n val = dtype_info_name(dat.info.dtype)\n elif attr == 'shape':\n datshape = dat.shape[1:]\n val = datshape if datshape else ''\n else:\n val = getattr(dat.info, attr)\n if val is None:\n val = ''\n return str(val)\n\n\nclass InfoAttribute:\n def __init__(self, attr, default=None):\n self.attr = attr\n self.default = default\n\n def __get__(self, instance, owner_cls):\n if instance is None:\n return self\n\n return instance._attrs.get(self.attr, self.default)\n\n def __set__(self, instance, value):\n if instance is None:\n # This is an unbound descriptor on the class\n raise ValueError('cannot set unbound descriptor')\n\n instance._attrs[self.attr] = value\n\n\nclass ParentAttribute:\n def __init__(self, attr):\n self.attr = attr\n\n def __get__(self, instance, owner_cls):\n if instance is None:\n return self\n\n return getattr(instance._parent, self.attr)\n\n def __set__(self, instance, value):\n if instance is None:\n # This is an unbound descriptor on the class\n raise ValueError('cannot set unbound descriptor')\n\n setattr(instance._parent, self.attr, value)\n\n\nclass DataInfoMeta(type):\n def __new__(mcls, name, bases, dct):\n # Ensure that we do not gain a __dict__, which would mean\n # arbitrary attributes could be set.\n dct.setdefault('__slots__', [])\n return super().__new__(mcls, name, bases, dct)\n\n def __init__(cls, name, bases, dct):\n super().__init__(name, bases, dct)\n\n # Define default getters/setters for attributes, if needed.\n for attr in cls.attr_names:\n if attr not in dct:\n # If not defined explicitly for this class, did any of\n # its superclasses define it, and, if so, was this an\n # automatically defined look-up-on-parent attribute?\n cls_attr = getattr(cls, attr, None)\n if attr in cls.attrs_from_parent:\n # If the attribute is supposed to be stored on the parent,\n # and that is stated by this class yet it was not the case\n # on the superclass, override it.\n if 'attrs_from_parent' in dct and not isinstance(cls_attr, ParentAttribute):\n setattr(cls, attr, ParentAttribute(attr))\n elif not cls_attr or isinstance(cls_attr, ParentAttribute):\n # If the attribute is not meant to be stored on the parent,\n # and if it was not defined already or was previously defined\n # as an attribute on the parent, define a regular\n # look-up-on-info attribute\n setattr(cls, attr,\n InfoAttribute(attr, cls._attr_defaults.get(attr)))\n\n\nclass DataInfo(metaclass=DataInfoMeta):\n \"\"\"\n Descriptor that data classes use to add an ``info`` attribute for storing\n data attributes in a uniform and portable way. Note that it *must* be\n called ``info`` so that the DataInfo() object can be stored in the\n ``instance`` using the ``info`` key. Because owner_cls.x is a descriptor,\n Python doesn't use __dict__['x'] normally, and the descriptor can safely\n store stuff there. Thanks to http://nbviewer.ipython.org/urls/gist.github.com/ChrisBeaumont/5758381/raw/descriptor_writeup.ipynb\n for this trick that works for non-hashable classes.\n\n Parameters\n ----------\n bound : bool\n If True this is a descriptor attribute in a class definition, else it\n is a DataInfo() object that is bound to a data object instance. Default is False.\n \"\"\"\n _stats = ['mean', 'std', 'min', 'max']\n attrs_from_parent = set()\n attr_names = set(['name', 'unit', 'dtype', 'format', 'description', 'meta'])\n _attr_defaults = {'dtype': np.dtype('O')}\n _attrs_no_copy = set()\n _info_summary_attrs = ('dtype', 'shape', 'unit', 'format', 'description', 'class')\n __slots__ = ['_parent_cls', '_parent_ref', '_attrs']\n # This specifies the list of object attributes which must be stored in\n # order to re-create the object after serialization. This is independent\n # of normal `info` attributes like name or description. Subclasses will\n # generally either define this statically (QuantityInfo) or dynamically\n # (SkyCoordInfo). These attributes may be scalars or arrays. If arrays\n # that match the object length they will be serialized as an independent\n # column.\n _represent_as_dict_attrs = ()\n\n # This specifies attributes which are to be provided to the class\n # initializer as ordered args instead of keyword args. This is needed\n # for Quantity subclasses where the keyword for data varies (e.g.\n # between Quantity and Angle).\n _construct_from_dict_args = ()\n\n # This specifies the name of an attribute which is the \"primary\" data.\n # Then when representing as columns\n # (table.serialize._represent_mixin_as_column) the output for this\n # attribute will be written with the just name of the mixin instead of the\n # usual \"<name>.<attr>\".\n _represent_as_dict_primary_data = None\n\n def __init__(self, bound=False):\n # If bound to a data object instance then create the dict of attributes\n # which stores the info attribute values. Default of None for \"unset\"\n # except for dtype where the default is object.\n if bound:\n self._attrs = {}\n\n @property\n def _parent(self):\n try:\n parent = self._parent_ref()\n except AttributeError:\n return None\n\n if parent is None:\n raise AttributeError(\"\"\"\\\nfailed access \"info\" attribute on a temporary object.\n\nIt looks like you have done something like ``col[3:5].info``, i.e.\nyou accessed ``info`` from a temporary slice object ``col[3:5]`` that\nonly exists momentarily. This has failed because the reference to\nthat temporary object is now lost. Instead force a permanent\nreference with ``c = col[3:5]`` followed by ``c.info``.\"\"\")\n\n return parent\n\n def __get__(self, instance, owner_cls):\n if instance is None:\n # This is an unbound descriptor on the class\n self._parent_cls = owner_cls\n return self\n\n info = instance.__dict__.get('info')\n if info is None:\n info = instance.__dict__['info'] = self.__class__(bound=True)\n # We set _parent_ref on every call, since if one makes copies of\n # instances, 'info' will be copied as well, which will lose the\n # reference.\n info._parent_ref = weakref.ref(instance)\n return info\n\n def __set__(self, instance, value):\n if instance is None:\n # This is an unbound descriptor on the class\n raise ValueError('cannot set unbound descriptor')\n\n if isinstance(value, DataInfo):\n info = instance.__dict__['info'] = self.__class__(bound=True)\n for attr in info.attr_names - info.attrs_from_parent - info._attrs_no_copy:\n info._attrs[attr] = deepcopy(getattr(value, attr))\n\n else:\n raise TypeError('info must be set with a DataInfo instance')\n\n def __getstate__(self):\n return self._attrs\n\n def __setstate__(self, state):\n self._attrs = state\n\n def _represent_as_dict(self, attrs=None):\n \"\"\"Get the values for the parent ``attrs`` and return as a dict.\n\n By default, uses '_represent_as_dict_attrs'.\n \"\"\"\n if attrs is None:\n attrs = self._represent_as_dict_attrs\n return _get_obj_attrs_map(self._parent, attrs)\n\n def _construct_from_dict(self, map):\n args = [map.pop(attr) for attr in self._construct_from_dict_args]\n return self._parent_cls(*args, **map)\n\n info_summary_attributes = staticmethod(\n data_info_factory(names=_info_summary_attrs,\n funcs=[partial(_get_data_attribute, attr=attr)\n for attr in _info_summary_attrs]))\n\n # No nan* methods in numpy < 1.8\n info_summary_stats = staticmethod(\n data_info_factory(names=_stats,\n funcs=[getattr(np, 'nan' + stat)\n for stat in _stats]))\n\n def __call__(self, option='attributes', out=''):\n \"\"\"\n Write summary information about data object to the ``out`` filehandle.\n By default this prints to standard output via sys.stdout.\n\n The ``option`` argument specifies what type of information\n to include. This can be a string, a function, or a list of\n strings or functions. Built-in options are:\n\n - ``attributes``: data object attributes like ``dtype`` and ``format``\n - ``stats``: basic statistics: min, mean, and max\n\n If a function is specified then that function will be called with the\n data object as its single argument. The function must return an\n OrderedDict containing the information attributes.\n\n If a list is provided then the information attributes will be\n appended for each of the options, in order.\n\n Examples\n --------\n\n >>> from astropy.table import Column\n >>> c = Column([1, 2], unit='m', dtype='int32')\n >>> c.info()\n dtype = int32\n unit = m\n class = Column\n n_bad = 0\n length = 2\n\n >>> c.info(['attributes', 'stats'])\n dtype = int32\n unit = m\n class = Column\n mean = 1.5\n std = 0.5\n min = 1\n max = 2\n n_bad = 0\n length = 2\n\n Parameters\n ----------\n option : str, function, list of (str or function)\n Info option, defaults to 'attributes'.\n out : file-like object, None\n Output destination, defaults to sys.stdout. If None then the\n OrderedDict with information attributes is returned\n\n Returns\n -------\n info : OrderedDict if out==None else None\n \"\"\"\n if out == '':\n out = sys.stdout\n\n dat = self._parent\n info = OrderedDict()\n name = dat.info.name\n if name is not None:\n info['name'] = name\n\n options = option if isinstance(option, (list, tuple)) else [option]\n for option in options:\n if isinstance(option, str):\n if hasattr(self, 'info_summary_' + option):\n option = getattr(self, 'info_summary_' + option)\n else:\n raise ValueError('option={} is not an allowed information type'\n .format(option))\n\n with warnings.catch_warnings():\n for ignore_kwargs in IGNORE_WARNINGS:\n warnings.filterwarnings('ignore', **ignore_kwargs)\n info.update(option(dat))\n\n if hasattr(dat, 'mask'):\n n_bad = np.count_nonzero(dat.mask)\n else:\n try:\n n_bad = np.count_nonzero(np.isinf(dat) | np.isnan(dat))\n except Exception:\n n_bad = 0\n info['n_bad'] = n_bad\n\n try:\n info['length'] = len(dat)\n except (TypeError, IndexError):\n pass\n\n if out is None:\n return info\n\n for key, val in info.items():\n if val != '':\n out.write(f'{key} = {val}' + os.linesep)\n\n def __repr__(self):\n if self._parent is None:\n return super().__repr__()\n\n out = StringIO()\n self.__call__(out=out)\n return out.getvalue()\n\n\nclass BaseColumnInfo(DataInfo):\n \"\"\"\n Base info class for anything that can be a column in an astropy\n Table. There are at least two classes that inherit from this:\n\n ColumnInfo: for native astropy Column / MaskedColumn objects\n MixinInfo: for mixin column objects\n\n Note that this class is defined here so that mixins can use it\n without importing the table package.\n \"\"\"\n attr_names = DataInfo.attr_names.union(['parent_table', 'indices'])\n _attrs_no_copy = set(['parent_table'])\n\n # Context for serialization. This can be set temporarily via\n # ``serialize_context_as(context)`` context manager to allow downstream\n # code to understand the context in which a column is being serialized.\n # Typical values are 'fits', 'hdf5', 'ecsv', 'yaml'. Objects like Time or\n # SkyCoord will have different default serialization representations\n # depending on context.\n _serialize_context = None\n __slots__ = ['_format_funcs', '_copy_indices']\n\n @property\n def parent_table(self):\n value = self._attrs.get('parent_table')\n if callable(value):\n value = value()\n return value\n\n @parent_table.setter\n def parent_table(self, parent_table):\n if parent_table is None:\n self._attrs.pop('parent_table', None)\n else:\n parent_table = weakref.ref(parent_table)\n self._attrs['parent_table'] = parent_table\n\n def __init__(self, bound=False):\n super().__init__(bound=bound)\n\n # If bound to a data object instance then add a _format_funcs dict\n # for caching functions for print formatting.\n if bound:\n self._format_funcs = {}\n\n def iter_str_vals(self):\n \"\"\"\n This is a mixin-safe version of Column.iter_str_vals.\n \"\"\"\n col = self._parent\n if self.parent_table is None:\n from astropy.table.column import FORMATTER as formatter\n else:\n formatter = self.parent_table.formatter\n\n _pformat_col_iter = formatter._pformat_col_iter\n for str_val in _pformat_col_iter(col, -1, False, False, {}):\n yield str_val\n\n def adjust_indices(self, index, value, col_len):\n '''\n Adjust info indices after column modification.\n\n Parameters\n ----------\n index : slice, int, list, or ndarray\n Element(s) of column to modify. This parameter can\n be a single row number, a list of row numbers, an\n ndarray of row numbers, a boolean ndarray (a mask),\n or a column slice.\n value : int, list, or ndarray\n New value(s) to insert\n col_len : int\n Length of the column\n '''\n if not self.indices:\n return\n\n if isinstance(index, slice):\n # run through each key in slice\n t = index.indices(col_len)\n keys = list(range(*t))\n elif isinstance(index, np.ndarray) and index.dtype.kind == 'b':\n # boolean mask\n keys = np.where(index)[0]\n else: # single int\n keys = [index]\n\n value = np.atleast_1d(value) # turn array(x) into array([x])\n if value.size == 1:\n # repeat single value\n value = list(value) * len(keys)\n\n for key, val in zip(keys, value):\n for col_index in self.indices:\n col_index.replace(key, self.name, val)\n\n def slice_indices(self, col_slice, item, col_len):\n '''\n Given a sliced object, modify its indices\n to correctly represent the slice.\n\n Parameters\n ----------\n col_slice : Column or mixin\n Sliced object\n item : slice, list, or ndarray\n Slice used to create col_slice\n col_len : int\n Length of original object\n '''\n from astropy.table.sorted_array import SortedArray\n if not getattr(self, '_copy_indices', True):\n # Necessary because MaskedArray will perform a shallow copy\n col_slice.info.indices = []\n return col_slice\n elif isinstance(item, slice):\n col_slice.info.indices = [x[item] for x in self.indices]\n elif self.indices:\n if isinstance(item, np.ndarray) and item.dtype.kind == 'b':\n # boolean mask\n item = np.where(item)[0]\n threshold = 0.6\n # Empirical testing suggests that recreating a BST/RBT index is\n # more effective than relabelling when less than ~60% of\n # the total number of rows are involved, and is in general\n # more effective for SortedArray.\n small = len(item) <= 0.6 * col_len\n col_slice.info.indices = []\n for index in self.indices:\n if small or isinstance(index, SortedArray):\n new_index = index.get_slice(col_slice, item)\n else:\n new_index = deepcopy(index)\n new_index.replace_rows(item)\n col_slice.info.indices.append(new_index)\n\n return col_slice\n\n @staticmethod\n def merge_cols_attributes(cols, metadata_conflicts, name, attrs):\n \"\"\"\n Utility method to merge and validate the attributes ``attrs`` for the\n input table columns ``cols``.\n\n Note that ``dtype`` and ``shape`` attributes are handled specially.\n These should not be passed in ``attrs`` but will always be in the\n returned dict of merged attributes.\n\n Parameters\n ----------\n cols : list\n List of input Table column objects\n metadata_conflicts : str ('warn'|'error'|'silent')\n How to handle metadata conflicts\n name : str\n Output column name\n attrs : list\n List of attribute names to be merged\n\n Returns\n -------\n attrs : dict of merged attributes\n\n \"\"\"\n from astropy.table.np_utils import TableMergeError\n\n def warn_str_func(key, left, right):\n out = (\"In merged column '{}' the '{}' attribute does not match \"\n \"({} != {}). Using {} for merged output\"\n .format(name, key, left, right, right))\n return out\n\n def getattrs(col):\n return {attr: getattr(col.info, attr) for attr in attrs\n if getattr(col.info, attr, None) is not None}\n\n out = getattrs(cols[0])\n for col in cols[1:]:\n out = metadata.merge(out, getattrs(col), metadata_conflicts=metadata_conflicts,\n warn_str_func=warn_str_func)\n\n # Output dtype is the superset of all dtypes in in_cols\n out['dtype'] = metadata.common_dtype(cols)\n\n # Make sure all input shapes are the same\n uniq_shapes = set(col.shape[1:] for col in cols)\n if len(uniq_shapes) != 1:\n raise TableMergeError('columns have different shapes')\n out['shape'] = uniq_shapes.pop()\n\n # \"Merged\" output name is the supplied name\n if name is not None:\n out['name'] = name\n\n return out\n\n def get_sortable_arrays(self):\n \"\"\"\n Return a list of arrays which can be lexically sorted to represent\n the order of the parent column.\n\n The base method raises NotImplementedError and must be overridden.\n\n Returns\n -------\n arrays : list of ndarray\n \"\"\"\n raise NotImplementedError(f'column {self.name} is not sortable')\n\n\nclass MixinInfo(BaseColumnInfo):\n\n @property\n def name(self):\n return self._attrs.get('name')\n\n @name.setter\n def name(self, name):\n # For mixin columns that live within a table, rename the column in the\n # table when setting the name attribute. This mirrors the same\n # functionality in the BaseColumn class.\n if self.parent_table is not None:\n from astropy.table.np_utils import fix_column_name\n new_name = fix_column_name(name) # Ensure col name is numpy compatible\n self.parent_table.columns._rename_column(self.name, new_name)\n\n self._attrs['name'] = name\n\n\nclass ParentDtypeInfo(MixinInfo):\n \"\"\"Mixin that gets info.dtype from parent\"\"\"\n\n attrs_from_parent = set(['dtype']) # dtype and unit taken from parent\n", "# -*- coding: utf-8 -*-\n# Licensed under a 3-clause BSD style license - see LICENSE.rst\n\nimport pytest\nimport numpy as np\n\nfrom astropy import units as u\nfrom astropy.coordinates.distances import Distance\nfrom astropy.coordinates.builtin_frames import ICRS, FK5, Galactic, AltAz, SkyOffsetFrame\nfrom astropy.coordinates import SkyCoord, EarthLocation\nfrom astropy.time import Time\nfrom astropy.tests.helper import assert_quantity_allclose as assert_allclose\n\n\[email protected](\"inradec,expectedlatlon, tolsep\", [\n ((45, 45)*u.deg, (0, 0)*u.deg, .001*u.arcsec),\n ((45, 0)*u.deg, (0, -45)*u.deg, .001*u.arcsec),\n ((45, 90)*u.deg, (0, 45)*u.deg, .001*u.arcsec),\n ((46, 45)*u.deg, (1*np.cos(45*u.deg), 0)*u.deg, 16*u.arcsec),\n ])\ndef test_skyoffset(inradec, expectedlatlon, tolsep, originradec=(45, 45)*u.deg):\n origin = ICRS(*originradec)\n skyoffset_frame = SkyOffsetFrame(origin=origin)\n\n skycoord = SkyCoord(*inradec, frame=ICRS)\n skycoord_inaf = skycoord.transform_to(skyoffset_frame)\n assert hasattr(skycoord_inaf, 'lon')\n assert hasattr(skycoord_inaf, 'lat')\n expected = SkyCoord(*expectedlatlon, frame=skyoffset_frame)\n\n assert skycoord_inaf.separation(expected) < tolsep\n\n\ndef test_skyoffset_functional_ra():\n # we do the 12)[1:-1] business because sometimes machine precision issues\n # lead to results that are either ~0 or ~360, which mucks up the final\n # comparison and leads to spurious failures. So this just avoids that by\n # staying away from the edges\n input_ra = np.linspace(0, 360, 12)[1:-1]\n input_dec = np.linspace(-90, 90, 12)[1:-1]\n icrs_coord = ICRS(ra=input_ra*u.deg,\n dec=input_dec*u.deg,\n distance=1.*u.kpc)\n\n for ra in np.linspace(0, 360, 24):\n # expected rotation\n expected = ICRS(ra=np.linspace(0-ra, 360-ra, 12)[1:-1]*u.deg,\n dec=np.linspace(-90, 90, 12)[1:-1]*u.deg,\n distance=1.*u.kpc)\n expected_xyz = expected.cartesian.xyz\n\n # actual transformation to the frame\n skyoffset_frame = SkyOffsetFrame(origin=ICRS(ra*u.deg, 0*u.deg))\n actual = icrs_coord.transform_to(skyoffset_frame)\n actual_xyz = actual.cartesian.xyz\n\n # back to ICRS\n roundtrip = actual.transform_to(ICRS())\n roundtrip_xyz = roundtrip.cartesian.xyz\n\n # Verify\n assert_allclose(actual_xyz, expected_xyz, atol=1E-5*u.kpc)\n assert_allclose(icrs_coord.ra, roundtrip.ra, atol=1E-5*u.deg)\n assert_allclose(icrs_coord.dec, roundtrip.dec, atol=1E-5*u.deg)\n assert_allclose(icrs_coord.distance, roundtrip.distance, atol=1E-5*u.kpc)\n\n\ndef test_skyoffset_functional_dec():\n # we do the 12)[1:-1] business because sometimes machine precision issues\n # lead to results that are either ~0 or ~360, which mucks up the final\n # comparison and leads to spurious failures. So this just avoids that by\n # staying away from the edges\n input_ra = np.linspace(0, 360, 12)[1:-1]\n input_dec = np.linspace(-90, 90, 12)[1:-1]\n input_ra_rad = np.deg2rad(input_ra)\n input_dec_rad = np.deg2rad(input_dec)\n icrs_coord = ICRS(ra=input_ra*u.deg,\n dec=input_dec*u.deg,\n distance=1.*u.kpc)\n # Dec rotations\n # Done in xyz space because dec must be [-90,90]\n\n for dec in np.linspace(-90, 90, 13):\n # expected rotation\n dec_rad = -np.deg2rad(dec)\n expected_x = (-np.sin(input_dec_rad) * np.sin(dec_rad) +\n np.cos(input_ra_rad) * np.cos(input_dec_rad) * np.cos(dec_rad))\n expected_y = (np.sin(input_ra_rad) * np.cos(input_dec_rad))\n expected_z = (np.sin(input_dec_rad) * np.cos(dec_rad) +\n np.sin(dec_rad) * np.cos(input_ra_rad) * np.cos(input_dec_rad))\n expected = SkyCoord(x=expected_x,\n y=expected_y,\n z=expected_z, unit='kpc', representation_type='cartesian')\n expected_xyz = expected.cartesian.xyz\n\n # actual transformation to the frame\n skyoffset_frame = SkyOffsetFrame(origin=ICRS(0*u.deg, dec*u.deg))\n actual = icrs_coord.transform_to(skyoffset_frame)\n actual_xyz = actual.cartesian.xyz\n\n # back to ICRS\n roundtrip = actual.transform_to(ICRS())\n\n # Verify\n assert_allclose(actual_xyz, expected_xyz, atol=1E-5*u.kpc)\n assert_allclose(icrs_coord.ra, roundtrip.ra, atol=1E-5*u.deg)\n assert_allclose(icrs_coord.dec, roundtrip.dec, atol=1E-5*u.deg)\n assert_allclose(icrs_coord.distance, roundtrip.distance, atol=1E-5*u.kpc)\n\n\ndef test_skyoffset_functional_ra_dec():\n # we do the 12)[1:-1] business because sometimes machine precision issues\n # lead to results that are either ~0 or ~360, which mucks up the final\n # comparison and leads to spurious failures. So this just avoids that by\n # staying away from the edges\n input_ra = np.linspace(0, 360, 12)[1:-1]\n input_dec = np.linspace(-90, 90, 12)[1:-1]\n input_ra_rad = np.deg2rad(input_ra)\n input_dec_rad = np.deg2rad(input_dec)\n icrs_coord = ICRS(ra=input_ra*u.deg,\n dec=input_dec*u.deg,\n distance=1.*u.kpc)\n\n for ra in np.linspace(0, 360, 10):\n for dec in np.linspace(-90, 90, 5):\n # expected rotation\n dec_rad = -np.deg2rad(dec)\n ra_rad = np.deg2rad(ra)\n expected_x = (-np.sin(input_dec_rad) * np.sin(dec_rad) +\n np.cos(input_ra_rad) * np.cos(input_dec_rad) * np.cos(dec_rad) * np.cos(ra_rad) +\n np.sin(input_ra_rad) * np.cos(input_dec_rad) * np.cos(dec_rad) * np.sin(ra_rad))\n expected_y = (np.sin(input_ra_rad) * np.cos(input_dec_rad) * np.cos(ra_rad) -\n np.cos(input_ra_rad) * np.cos(input_dec_rad) * np.sin(ra_rad))\n expected_z = (np.sin(input_dec_rad) * np.cos(dec_rad) +\n np.sin(dec_rad) * np.cos(ra_rad) * np.cos(input_ra_rad) * np.cos(input_dec_rad) +\n np.sin(dec_rad) * np.sin(ra_rad) * np.sin(input_ra_rad) * np.cos(input_dec_rad))\n expected = SkyCoord(x=expected_x,\n y=expected_y,\n z=expected_z, unit='kpc', representation_type='cartesian')\n expected_xyz = expected.cartesian.xyz\n\n # actual transformation to the frame\n skyoffset_frame = SkyOffsetFrame(origin=ICRS(ra*u.deg, dec*u.deg))\n actual = icrs_coord.transform_to(skyoffset_frame)\n actual_xyz = actual.cartesian.xyz\n\n # back to ICRS\n roundtrip = actual.transform_to(ICRS())\n\n # Verify\n assert_allclose(actual_xyz, expected_xyz, atol=1E-5*u.kpc)\n assert_allclose(icrs_coord.ra, roundtrip.ra, atol=1E-4*u.deg)\n assert_allclose(icrs_coord.dec, roundtrip.dec, atol=1E-5*u.deg)\n assert_allclose(icrs_coord.distance, roundtrip.distance, atol=1E-5*u.kpc)\n\n\ndef test_skycoord_skyoffset_frame():\n m31 = SkyCoord(10.6847083, 41.26875, frame='icrs', unit=u.deg)\n m33 = SkyCoord(23.4621, 30.6599417, frame='icrs', unit=u.deg)\n\n m31_astro = m31.skyoffset_frame()\n m31_in_m31 = m31.transform_to(m31_astro)\n m33_in_m31 = m33.transform_to(m31_astro)\n\n assert_allclose([m31_in_m31.lon, m31_in_m31.lat], [0, 0]*u.deg, atol=1e-10*u.deg)\n assert_allclose([m33_in_m31.lon, m33_in_m31.lat], [11.13135175, -9.79084759]*u.deg)\n\n assert_allclose(m33.separation(m31),\n np.hypot(m33_in_m31.lon, m33_in_m31.lat),\n atol=.1*u.deg)\n\n\n# used below in the next parametrized test\nm31_sys = [ICRS, FK5, Galactic]\nm31_coo = [(10.6847929, 41.2690650), (10.6847929, 41.2690650), (121.1744050, -21.5729360)]\nm31_dist = Distance(770, u.kpc)\nconvert_precision = 1 * u.arcsec\nroundtrip_precision = 1e-4 * u.degree\ndist_precision = 1e-9 * u.kpc\n\nm31_params = []\nfor i in range(len(m31_sys)):\n for j in range(len(m31_sys)):\n if i < j:\n m31_params.append((m31_sys[i], m31_sys[j], m31_coo[i], m31_coo[j]))\n\n\[email protected](('fromsys', 'tosys', 'fromcoo', 'tocoo'), m31_params)\ndef test_m31_coord_transforms(fromsys, tosys, fromcoo, tocoo):\n \"\"\"\n This tests a variety of coordinate conversions for the Chandra point-source\n catalog location of M31 from NED, via SkyOffsetFrames\n \"\"\"\n from_origin = fromsys(fromcoo[0]*u.deg, fromcoo[1]*u.deg,\n distance=m31_dist)\n from_pos = SkyOffsetFrame(1*u.deg, 1*u.deg, origin=from_origin)\n to_origin = tosys(tocoo[0]*u.deg, tocoo[1]*u.deg, distance=m31_dist)\n\n to_astroframe = SkyOffsetFrame(origin=to_origin)\n target_pos = from_pos.transform_to(to_astroframe)\n\n assert_allclose(to_origin.separation(target_pos),\n np.hypot(from_pos.lon, from_pos.lat),\n atol=convert_precision)\n roundtrip_pos = target_pos.transform_to(from_pos)\n assert_allclose([roundtrip_pos.lon.wrap_at(180*u.deg), roundtrip_pos.lat],\n [1.0*u.deg, 1.0*u.deg], atol=convert_precision)\n\n\ndef test_altaz_attribute_transforms():\n \"\"\"Test transforms between AltAz frames with different attributes.\"\"\"\n el1 = EarthLocation(0*u.deg, 0*u.deg, 0*u.m)\n origin1 = AltAz(0 * u.deg, 0*u.deg, obstime=Time(\"2000-01-01T12:00:00\"),\n location=el1)\n frame1 = SkyOffsetFrame(origin=origin1)\n coo1 = SkyCoord(1 * u.deg, 1 * u.deg, frame=frame1)\n\n el2 = EarthLocation(0*u.deg, 0*u.deg, 0*u.m)\n origin2 = AltAz(0 * u.deg, 0*u.deg, obstime=Time(\"2000-01-01T11:00:00\"),\n location=el2)\n frame2 = SkyOffsetFrame(origin=origin2)\n coo2 = coo1.transform_to(frame2)\n coo2_expected = [1.22522446, 0.70624298] * u.deg\n assert_allclose([coo2.lon.wrap_at(180*u.deg), coo2.lat],\n coo2_expected, atol=convert_precision)\n\n el3 = EarthLocation(0*u.deg, 90*u.deg, 0*u.m)\n origin3 = AltAz(0 * u.deg, 90*u.deg, obstime=Time(\"2000-01-01T12:00:00\"),\n location=el3)\n frame3 = SkyOffsetFrame(origin=origin3)\n coo3 = coo2.transform_to(frame3)\n assert_allclose([coo3.lon.wrap_at(180*u.deg), coo3.lat],\n [1*u.deg, 1*u.deg], atol=convert_precision)\n\n\[email protected](\"rotation, expectedlatlon\", [\n (0*u.deg, [0, 1]*u.deg),\n (180*u.deg, [0, -1]*u.deg),\n (90*u.deg, [-1, 0]*u.deg),\n (-90*u.deg, [1, 0]*u.deg)\n ])\ndef test_rotation(rotation, expectedlatlon):\n origin = ICRS(45*u.deg, 45*u.deg)\n target = ICRS(45*u.deg, 46*u.deg)\n\n aframe = SkyOffsetFrame(origin=origin, rotation=rotation)\n trans = target.transform_to(aframe)\n\n assert_allclose([trans.lon.wrap_at(180*u.deg), trans.lat],\n expectedlatlon, atol=1e-10*u.deg)\n\n\[email protected](\"rotation, expectedlatlon\", [\n (0*u.deg, [0, 1]*u.deg),\n (180*u.deg, [0, -1]*u.deg),\n (90*u.deg, [-1, 0]*u.deg),\n (-90*u.deg, [1, 0]*u.deg)\n ])\ndef test_skycoord_skyoffset_frame_rotation(rotation, expectedlatlon):\n \"\"\"Test if passing a rotation argument via SkyCoord works\"\"\"\n origin = SkyCoord(45*u.deg, 45*u.deg)\n target = SkyCoord(45*u.deg, 46*u.deg)\n\n aframe = origin.skyoffset_frame(rotation=rotation)\n trans = target.transform_to(aframe)\n\n assert_allclose([trans.lon.wrap_at(180*u.deg), trans.lat],\n expectedlatlon, atol=1e-10*u.deg)\n\n\ndef test_skyoffset_names():\n origin1 = ICRS(45*u.deg, 45*u.deg)\n aframe1 = SkyOffsetFrame(origin=origin1)\n assert type(aframe1).__name__ == 'SkyOffsetICRS'\n\n origin2 = Galactic(45*u.deg, 45*u.deg)\n aframe2 = SkyOffsetFrame(origin=origin2)\n assert type(aframe2).__name__ == 'SkyOffsetGalactic'\n\n\ndef test_skyoffset_origindata():\n origin = ICRS()\n with pytest.raises(ValueError):\n SkyOffsetFrame(origin=origin)\n\n\ndef test_skyoffset_lonwrap():\n origin = ICRS(45*u.deg, 45*u.deg)\n sc = SkyCoord(190*u.deg, -45*u.deg, frame=SkyOffsetFrame(origin=origin))\n assert sc.lon < 180 * u.deg\n\n sc2 = SkyCoord(-10*u.deg, -45*u.deg, frame=SkyOffsetFrame(origin=origin))\n assert sc2.lon < 180 * u.deg\n\n sc3 = sc.realize_frame(sc.represent_as('cartesian'))\n assert sc3.lon < 180 * u.deg\n\n sc4 = sc2.realize_frame(sc2.represent_as('cartesian'))\n assert sc4.lon < 180 * u.deg\n\n\ndef test_skyoffset_velocity():\n c = ICRS(ra=170.9*u.deg, dec=-78.4*u.deg,\n pm_ra_cosdec=74.4134*u.mas/u.yr,\n pm_dec=-93.2342*u.mas/u.yr)\n skyoffset_frame = SkyOffsetFrame(origin=c)\n c_skyoffset = c.transform_to(skyoffset_frame)\n\n assert_allclose(c_skyoffset.pm_lon_coslat, c.pm_ra_cosdec)\n assert_allclose(c_skyoffset.pm_lat, c.pm_dec)\n\n\[email protected](\"rotation, expectedpmlonlat\", [\n (0*u.deg, [1, 2]*u.mas/u.yr),\n (45*u.deg, [-2**-0.5, 3*2**-0.5]*u.mas/u.yr),\n (90*u.deg, [-2, 1]*u.mas/u.yr),\n (180*u.deg, [-1, -2]*u.mas/u.yr),\n (-90*u.deg, [2, -1]*u.mas/u.yr)\n ])\ndef test_skyoffset_velocity_rotation(rotation, expectedpmlonlat):\n sc = SkyCoord(ra=170.9*u.deg, dec=-78.4*u.deg,\n pm_ra_cosdec=1*u.mas/u.yr,\n pm_dec=2*u.mas/u.yr)\n\n c_skyoffset0 = sc.transform_to(sc.skyoffset_frame(rotation=rotation))\n assert_allclose(c_skyoffset0.pm_lon_coslat, expectedpmlonlat[0])\n assert_allclose(c_skyoffset0.pm_lat, expectedpmlonlat[1])\n", "# -*- coding: utf-8 -*-\n# Licensed under a 3-clause BSD style license - see LICENSE.rst\n\n\"\"\"\nBuilt-in distribution-creation functions.\n\"\"\"\nfrom warnings import warn\n\nimport numpy as np\n\nfrom astropy import units as u\nfrom .core import Distribution\n\n__all__ = ['normal', 'poisson', 'uniform']\n\n\ndef normal(center, *, std=None, var=None, ivar=None, n_samples,\n cls=Distribution, **kwargs):\n \"\"\"\n Create a Gaussian/normal distribution.\n\n Parameters\n ----------\n center : `~astropy.units.Quantity`\n The center of this distribution\n std : `~astropy.units.Quantity` or `None`\n The standard deviation/σ of this distribution. Shape must match and unit\n must be compatible with ``center``, or be `None` (if ``var`` or ``ivar``\n are set).\n var : `~astropy.units.Quantity` or `None`\n The variance of this distribution. Shape must match and unit must be\n compatible with ``center``, or be `None` (if ``std`` or ``ivar`` are set).\n ivar : `~astropy.units.Quantity` or `None`\n The inverse variance of this distribution. Shape must match and unit\n must be compatible with ``center``, or be `None` (if ``std`` or ``var``\n are set).\n n_samples : int\n The number of Monte Carlo samples to use with this distribution\n cls : class\n The class to use to create this distribution. Typically a\n `Distribution` subclass.\n\n Remaining keywords are passed into the constructor of the ``cls``\n\n Returns\n -------\n distr : ``cls``, usually `Distribution`\n The sampled Gaussian distribution.\n \"\"\"\n center = np.asanyarray(center)\n if var is not None:\n if std is None:\n std = np.asanyarray(var)**0.5\n else:\n raise ValueError('normal cannot take both std and var')\n if ivar is not None:\n if std is None:\n std = np.asanyarray(ivar)**-0.5\n else:\n raise ValueError('normal cannot take both ivar and '\n 'and std or var')\n if std is None:\n raise ValueError('normal requires one of std, var, or ivar')\n else:\n std = np.asanyarray(std)\n\n randshape = np.broadcast(std, center).shape + (n_samples,)\n samples = center[..., np.newaxis] + np.random.randn(*randshape) * std[..., np.newaxis]\n return cls(samples, **kwargs)\n\n\nCOUNT_UNITS = (u.count, u.electron, u.dimensionless_unscaled, u.chan, u.bin, u.vox, u.bit, u.byte)\n\n\ndef poisson(center, n_samples, cls=Distribution, **kwargs):\n \"\"\"\n Create a Poisson distribution.\n\n Parameters\n ----------\n center : `~astropy.units.Quantity`\n The center value of this distribution (i.e., λ).\n n_samples : int\n The number of Monte Carlo samples to use with this distribution\n cls : class\n The class to use to create this distribution. Typically a\n `Distribution` subclass.\n\n Remaining keywords are passed into the constructor of the ``cls``\n\n Returns\n -------\n distr : ``cls``, usually `Distribution`\n The sampled poisson distribution.\n \"\"\"\n # we convert to arrays because np.random.poisson has trouble with quantities\n has_unit = False\n if hasattr(center, 'unit'):\n has_unit = True\n poissonarr = np.asanyarray(center.value)\n else:\n poissonarr = np.asanyarray(center)\n randshape = poissonarr.shape + (n_samples,)\n\n samples = np.random.poisson(poissonarr[..., np.newaxis], randshape)\n if has_unit:\n if center.unit == u.adu:\n warn('ADUs were provided to poisson. ADUs are not strictly count'\n 'units because they need the gain to be applied. It is '\n 'recommended you apply the gain to convert to e.g. electrons.')\n elif center.unit not in COUNT_UNITS:\n warn('Unit {} was provided to poisson, which is not one of {}, '\n 'and therefore suspect as a \"counting\" unit. Ensure you mean '\n 'to use Poisson statistics.'.format(center.unit, COUNT_UNITS))\n\n # re-attach the unit\n samples = samples * center.unit\n\n return cls(samples, **kwargs)\n\n\ndef uniform(*, lower=None, upper=None, center=None, width=None, n_samples,\n cls=Distribution, **kwargs):\n \"\"\"\n Create a Uniform distriution from the lower and upper bounds.\n\n Note that this function requires keywords to be explicit, and requires\n either ``lower``/``upper`` or ``center``/``width``.\n\n Parameters\n ----------\n lower : array_like\n The lower edge of this distribution. If a `~astropy.units.Quantity`, the\n distribution will have the same units as ``lower``.\n upper : `~astropy.units.Quantity`\n The upper edge of this distribution. Must match shape and if a\n `~astropy.units.Quantity` must have compatible units with ``lower``.\n center : array_like\n The center value of the distribution. Cannot be provided at the same\n time as ``lower``/``upper``.\n width : array_like\n The width of the distribution. Must have the same shape and compatible\n units with ``center`` (if any).\n n_samples : int\n The number of Monte Carlo samples to use with this distribution\n cls : class\n The class to use to create this distribution. Typically a\n `Distribution` subclass.\n\n Remaining keywords are passed into the constructor of the ``cls``\n\n Returns\n -------\n distr : ``cls``, usually `Distribution`\n The sampled uniform distribution.\n \"\"\"\n if center is None and width is None:\n lower = np.asanyarray(lower)\n upper = np.asanyarray(upper)\n if lower.shape != upper.shape:\n raise ValueError('lower and upper must have consistent shapes')\n elif upper is None and lower is None:\n center = np.asanyarray(center)\n width = np.asanyarray(width)\n lower = center - width/2\n upper = center + width/2\n else:\n raise ValueError('either upper/lower or center/width must be given '\n 'to uniform - other combinations are not valid')\n\n newshape = lower.shape + (n_samples,)\n if lower.shape == tuple() and upper.shape == tuple():\n width = upper - lower # scalar\n else:\n width = (upper - lower)[:, np.newaxis]\n lower = lower[:, np.newaxis]\n samples = lower + width * np.random.uniform(size=newshape)\n\n return cls(samples, **kwargs)\n", "# -*- coding: utf-8 -*-\n# Licensed under a 3-clause BSD style license - see LICENSE.rst\n\n# This module includes files automatically generated from ply (these end in\n# _lextab.py and _parsetab.py). To generate these files, remove them from this\n# folder, then build astropy and run the tests in-place:\n#\n# python setup.py build_ext --inplace\n# pytest astropy/coordinates\n#\n# You can then commit the changes to the re-generated _lextab.py and\n# _parsetab.py files.\n\n\"\"\"\nThis module contains utility functions that are for internal use in\nastropy.coordinates.angles. Mainly they are conversions from one format\nof data to another.\n\"\"\"\n\nimport os\nimport threading\nfrom warnings import warn\n\nimport numpy as np\n\nfrom .errors import (IllegalHourWarning, IllegalHourError,\n IllegalMinuteWarning, IllegalMinuteError,\n IllegalSecondWarning, IllegalSecondError)\nfrom astropy.utils import format_exception\nfrom astropy import units as u\n\nTAB_HEADER = \"\"\"# -*- coding: utf-8 -*-\n# Licensed under a 3-clause BSD style license - see LICENSE.rst\n\n# This file was automatically generated from ply. To re-generate this file,\n# remove it from this folder, then build astropy and run the tests in-place:\n#\n# python setup.py build_ext --inplace\n# pytest astropy/coordinates\n#\n# You can then commit the changes to this file.\n\n\"\"\"\n\n\nclass _AngleParser:\n \"\"\"\n Parses the various angle formats including:\n\n * 01:02:30.43 degrees\n * 1 2 0 hours\n * 1°2′3″\n * 1d2m3s\n * -1h2m3s\n * 1°2′3″N\n\n This class should not be used directly. Use `parse_angle`\n instead.\n \"\"\"\n # For safe multi-threaded operation all class (but not instance)\n # members that carry state should be thread-local. They are stored\n # in the following class member\n _thread_local = threading.local()\n\n def __init__(self):\n # TODO: in principle, the parser should be invalidated if we change unit\n # system (from CDS to FITS, say). Might want to keep a link to the\n # unit_registry used, and regenerate the parser/lexer if it changes.\n # Alternatively, perhaps one should not worry at all and just pre-\n # generate the parser for each release (as done for unit formats).\n # For some discussion of this problem, see\n # https://github.com/astropy/astropy/issues/5350#issuecomment-248770151\n if '_parser' not in _AngleParser._thread_local.__dict__:\n (_AngleParser._thread_local._parser,\n _AngleParser._thread_local._lexer) = self._make_parser()\n\n @classmethod\n def _get_simple_unit_names(cls):\n simple_units = set(\n u.radian.find_equivalent_units(include_prefix_units=True))\n simple_unit_names = set()\n # We filter out degree and hourangle, since those are treated\n # separately.\n for unit in simple_units:\n if unit != u.deg and unit != u.hourangle:\n simple_unit_names.update(unit.names)\n return sorted(simple_unit_names)\n\n @classmethod\n def _make_parser(cls):\n from astropy.extern.ply import lex, yacc\n\n # List of token names.\n tokens = (\n 'SIGN',\n 'UINT',\n 'UFLOAT',\n 'COLON',\n 'DEGREE',\n 'HOUR',\n 'MINUTE',\n 'SECOND',\n 'SIMPLE_UNIT',\n 'EASTWEST',\n 'NORTHSOUTH'\n )\n\n # NOTE THE ORDERING OF THESE RULES IS IMPORTANT!!\n # Regular expression rules for simple tokens\n def t_UFLOAT(t):\n r'((\\d+\\.\\d*)|(\\.\\d+))([eE][+-−]?\\d+)?'\n # The above includes Unicode \"MINUS SIGN\" \\u2212. It is\n # important to include the hyphen last, or the regex will\n # treat this as a range.\n t.value = float(t.value.replace('−', '-'))\n return t\n\n def t_UINT(t):\n r'\\d+'\n t.value = int(t.value)\n return t\n\n def t_SIGN(t):\n r'[+−-]'\n # The above include Unicode \"MINUS SIGN\" \\u2212. It is\n # important to include the hyphen last, or the regex will\n # treat this as a range.\n if t.value == '+':\n t.value = 1.0\n else:\n t.value = -1.0\n return t\n\n def t_EASTWEST(t):\n r'[EW]$'\n t.value = -1.0 if t.value == 'W' else 1.0\n return t\n\n def t_NORTHSOUTH(t):\n r'[NS]$'\n # We cannot use lower-case letters otherwise we'll confuse\n # s[outh] with s[econd]\n t.value = -1.0 if t.value == 'S' else 1.0\n return t\n\n def t_SIMPLE_UNIT(t):\n t.value = u.Unit(t.value)\n return t\n\n t_SIMPLE_UNIT.__doc__ = '|'.join(\n f'(?:{x})' for x in cls._get_simple_unit_names())\n\n t_COLON = ':'\n t_DEGREE = r'd(eg(ree(s)?)?)?|°'\n t_HOUR = r'hour(s)?|h(r)?|ʰ'\n t_MINUTE = r'm(in(ute(s)?)?)?|′|\\'|ᵐ'\n t_SECOND = r's(ec(ond(s)?)?)?|″|\\\"|ˢ'\n\n # A string containing ignored characters (spaces)\n t_ignore = ' '\n\n # Error handling rule\n def t_error(t):\n raise ValueError(\n f\"Invalid character at col {t.lexpos}\")\n\n lexer_exists = os.path.exists(os.path.join(os.path.dirname(__file__),\n 'angle_lextab.py'))\n\n # Build the lexer\n lexer = lex.lex(optimize=True, lextab='angle_lextab',\n outputdir=os.path.dirname(__file__))\n\n if not lexer_exists:\n cls._add_tab_header('angle_lextab')\n\n def p_angle(p):\n '''\n angle : sign hms eastwest\n | sign dms dir\n | sign arcsecond dir\n | sign arcminute dir\n | sign simple dir\n '''\n sign = p[1] * p[3]\n value, unit = p[2]\n if isinstance(value, tuple):\n p[0] = ((sign * value[0],) + value[1:], unit)\n else:\n p[0] = (sign * value, unit)\n\n def p_sign(p):\n '''\n sign : SIGN\n |\n '''\n if len(p) == 2:\n p[0] = p[1]\n else:\n p[0] = 1.0\n\n def p_eastwest(p):\n '''\n eastwest : EASTWEST\n |\n '''\n if len(p) == 2:\n p[0] = p[1]\n else:\n p[0] = 1.0\n\n def p_dir(p):\n '''\n dir : EASTWEST\n | NORTHSOUTH\n |\n '''\n if len(p) == 2:\n p[0] = p[1]\n else:\n p[0] = 1.0\n\n def p_ufloat(p):\n '''\n ufloat : UFLOAT\n | UINT\n '''\n p[0] = p[1]\n\n def p_colon(p):\n '''\n colon : UINT COLON ufloat\n | UINT COLON UINT COLON ufloat\n '''\n if len(p) == 4:\n p[0] = (p[1], p[3])\n elif len(p) == 6:\n p[0] = (p[1], p[3], p[5])\n\n def p_spaced(p):\n '''\n spaced : UINT ufloat\n | UINT UINT ufloat\n '''\n if len(p) == 3:\n p[0] = (p[1], p[2])\n elif len(p) == 4:\n p[0] = (p[1], p[2], p[3])\n\n def p_generic(p):\n '''\n generic : colon\n | spaced\n | ufloat\n '''\n p[0] = p[1]\n\n def p_hms(p):\n '''\n hms : UINT HOUR\n | UINT HOUR ufloat\n | UINT HOUR UINT MINUTE\n | UINT HOUR UFLOAT MINUTE\n | UINT HOUR UINT MINUTE ufloat\n | UINT HOUR UINT MINUTE ufloat SECOND\n | generic HOUR\n '''\n if len(p) == 3:\n p[0] = (p[1], u.hourangle)\n elif len(p) in (4, 5):\n p[0] = ((p[1], p[3]), u.hourangle)\n elif len(p) in (6, 7):\n p[0] = ((p[1], p[3], p[5]), u.hourangle)\n\n def p_dms(p):\n '''\n dms : UINT DEGREE\n | UINT DEGREE ufloat\n | UINT DEGREE UINT MINUTE\n | UINT DEGREE UFLOAT MINUTE\n | UINT DEGREE UINT MINUTE ufloat\n | UINT DEGREE UINT MINUTE ufloat SECOND\n | generic DEGREE\n '''\n if len(p) == 3:\n p[0] = (p[1], u.degree)\n elif len(p) in (4, 5):\n p[0] = ((p[1], p[3]), u.degree)\n elif len(p) in (6, 7):\n p[0] = ((p[1], p[3], p[5]), u.degree)\n\n def p_simple(p):\n '''\n simple : generic\n | generic SIMPLE_UNIT\n '''\n if len(p) == 2:\n p[0] = (p[1], None)\n else:\n p[0] = (p[1], p[2])\n\n def p_arcsecond(p):\n '''\n arcsecond : generic SECOND\n '''\n p[0] = (p[1], u.arcsecond)\n\n def p_arcminute(p):\n '''\n arcminute : generic MINUTE\n '''\n p[0] = (p[1], u.arcminute)\n\n def p_error(p):\n raise ValueError\n\n parser_exists = os.path.exists(os.path.join(os.path.dirname(__file__),\n 'angle_parsetab.py'))\n\n parser = yacc.yacc(debug=False, tabmodule='angle_parsetab',\n outputdir=os.path.dirname(__file__),\n optimize=True, write_tables=True)\n\n if not parser_exists:\n cls._add_tab_header('angle_parsetab')\n\n return parser, lexer\n\n @classmethod\n def _add_tab_header(cls, name):\n\n lextab_file = os.path.join(os.path.dirname(__file__), name + '.py')\n\n with open(lextab_file, 'r') as f:\n contents = f.read()\n\n with open(lextab_file, 'w') as f:\n f.write(TAB_HEADER)\n f.write(contents)\n\n def parse(self, angle, unit, debug=False):\n try:\n found_angle, found_unit = self._thread_local._parser.parse(\n angle, lexer=self._thread_local._lexer, debug=debug)\n except ValueError as e:\n if str(e):\n raise ValueError(\"{} in angle {!r}\".format(\n str(e), angle))\n else:\n raise ValueError(\n f\"Syntax error parsing angle {angle!r}\")\n\n if unit is None and found_unit is None:\n raise u.UnitsError(\"No unit specified\")\n\n return found_angle, found_unit\n\n\ndef _check_hour_range(hrs):\n \"\"\"\n Checks that the given value is in the range (-24, 24).\n \"\"\"\n if np.any(np.abs(hrs) == 24.):\n warn(IllegalHourWarning(hrs, 'Treating as 24 hr'))\n elif np.any(hrs < -24.) or np.any(hrs > 24.):\n raise IllegalHourError(hrs)\n\n\ndef _check_minute_range(m):\n \"\"\"\n Checks that the given value is in the range [0,60]. If the value\n is equal to 60, then a warning is raised.\n \"\"\"\n if np.any(m == 60.):\n warn(IllegalMinuteWarning(m, 'Treating as 0 min, +1 hr/deg'))\n elif np.any(m < -60.) or np.any(m > 60.):\n # \"Error: minutes not in range [-60,60) ({0}).\".format(min))\n raise IllegalMinuteError(m)\n\n\ndef _check_second_range(sec):\n \"\"\"\n Checks that the given value is in the range [0,60]. If the value\n is equal to 60, then a warning is raised.\n \"\"\"\n if np.any(sec == 60.):\n warn(IllegalSecondWarning(sec, 'Treating as 0 sec, +1 min'))\n elif sec is None:\n pass\n elif np.any(sec < -60.) or np.any(sec > 60.):\n # \"Error: seconds not in range [-60,60) ({0}).\".format(sec))\n raise IllegalSecondError(sec)\n\n\ndef check_hms_ranges(h, m, s):\n \"\"\"\n Checks that the given hour, minute and second are all within\n reasonable range.\n \"\"\"\n _check_hour_range(h)\n _check_minute_range(m)\n _check_second_range(s)\n return None\n\n\ndef parse_angle(angle, unit=None, debug=False):\n \"\"\"\n Parses an input string value into an angle value.\n\n Parameters\n ----------\n angle : str\n A string representing the angle. May be in one of the following forms:\n\n * 01:02:30.43 degrees\n * 1 2 0 hours\n * 1°2′3″\n * 1d2m3s\n * -1h2m3s\n\n unit : `~astropy.units.UnitBase` instance, optional\n The unit used to interpret the string. If ``unit`` is not\n provided, the unit must be explicitly represented in the\n string, either at the end or as number separators.\n\n debug : bool, optional\n If `True`, print debugging information from the parser.\n\n Returns\n -------\n value, unit : tuple\n ``value`` is the value as a floating point number or three-part\n tuple, and ``unit`` is a `Unit` instance which is either the\n unit passed in or the one explicitly mentioned in the input\n string.\n \"\"\"\n return _AngleParser().parse(angle, unit, debug=debug)\n\n\ndef degrees_to_dms(d):\n \"\"\"\n Convert a floating-point degree value into a ``(degree, arcminute,\n arcsecond)`` tuple.\n \"\"\"\n sign = np.copysign(1.0, d)\n\n (df, d) = np.modf(np.abs(d)) # (degree fraction, degree)\n (mf, m) = np.modf(df * 60.) # (minute fraction, minute)\n s = mf * 60.\n\n return np.floor(sign * d), sign * np.floor(m), sign * s\n\n\ndef dms_to_degrees(d, m, s=None):\n \"\"\"\n Convert degrees, arcminute, arcsecond to a float degrees value.\n \"\"\"\n\n _check_minute_range(m)\n _check_second_range(s)\n\n # determine sign\n sign = np.copysign(1.0, d)\n\n try:\n d = np.floor(np.abs(d))\n if s is None:\n m = np.abs(m)\n s = 0\n else:\n m = np.floor(np.abs(m))\n s = np.abs(s)\n except ValueError:\n raise ValueError(format_exception(\n \"{func}: dms values ({1[0]},{2[1]},{3[2]}) could not be \"\n \"converted to numbers.\", d, m, s))\n\n return sign * (d + m / 60. + s / 3600.)\n\n\ndef hms_to_hours(h, m, s=None):\n \"\"\"\n Convert hour, minute, second to a float hour value.\n \"\"\"\n\n check_hms_ranges(h, m, s)\n\n # determine sign\n sign = np.copysign(1.0, h)\n\n try:\n h = np.floor(np.abs(h))\n if s is None:\n m = np.abs(m)\n s = 0\n else:\n m = np.floor(np.abs(m))\n s = np.abs(s)\n except ValueError:\n raise ValueError(format_exception(\n \"{func}: HMS values ({1[0]},{2[1]},{3[2]}) could not be \"\n \"converted to numbers.\", h, m, s))\n\n return sign * (h + m / 60. + s / 3600.)\n\n\ndef hms_to_degrees(h, m, s):\n \"\"\"\n Convert hour, minute, second to a float degrees value.\n \"\"\"\n\n return hms_to_hours(h, m, s) * 15.\n\n\ndef hms_to_radians(h, m, s):\n \"\"\"\n Convert hour, minute, second to a float radians value.\n \"\"\"\n\n return u.degree.to(u.radian, hms_to_degrees(h, m, s))\n\n\ndef hms_to_dms(h, m, s):\n \"\"\"\n Convert degrees, arcminutes, arcseconds to an ``(hour, minute, second)``\n tuple.\n \"\"\"\n\n return degrees_to_dms(hms_to_degrees(h, m, s))\n\n\ndef hours_to_decimal(h):\n \"\"\"\n Convert any parseable hour value into a float value.\n \"\"\"\n from . import angles\n return angles.Angle(h, unit=u.hourangle).hour\n\n\ndef hours_to_radians(h):\n \"\"\"\n Convert an angle in Hours to Radians.\n \"\"\"\n\n return u.hourangle.to(u.radian, h)\n\n\ndef hours_to_hms(h):\n \"\"\"\n Convert an floating-point hour value into an ``(hour, minute,\n second)`` tuple.\n \"\"\"\n\n sign = np.copysign(1.0, h)\n\n (hf, h) = np.modf(np.abs(h)) # (degree fraction, degree)\n (mf, m) = np.modf(hf * 60.0) # (minute fraction, minute)\n s = mf * 60.0\n\n return (np.floor(sign * h), sign * np.floor(m), sign * s)\n\n\ndef radians_to_degrees(r):\n \"\"\"\n Convert an angle in Radians to Degrees.\n \"\"\"\n return u.radian.to(u.degree, r)\n\n\ndef radians_to_hours(r):\n \"\"\"\n Convert an angle in Radians to Hours.\n \"\"\"\n return u.radian.to(u.hourangle, r)\n\n\ndef radians_to_hms(r):\n \"\"\"\n Convert an angle in Radians to an ``(hour, minute, second)`` tuple.\n \"\"\"\n\n hours = radians_to_hours(r)\n return hours_to_hms(hours)\n\n\ndef radians_to_dms(r):\n \"\"\"\n Convert an angle in Radians to an ``(degree, arcminute,\n arcsecond)`` tuple.\n \"\"\"\n\n degrees = u.radian.to(u.degree, r)\n return degrees_to_dms(degrees)\n\n\ndef sexagesimal_to_string(values, precision=None, pad=False, sep=(':',),\n fields=3):\n \"\"\"\n Given an already separated tuple of sexagesimal values, returns\n a string.\n\n See `hours_to_string` and `degrees_to_string` for a higher-level\n interface to this functionality.\n \"\"\"\n\n # Check to see if values[0] is negative, using np.copysign to handle -0\n sign = np.copysign(1.0, values[0])\n # If the coordinates are negative, we need to take the absolute values.\n # We use np.abs because abs(-0) is -0\n # TODO: Is this true? (MHvK, 2018-02-01: not on my system)\n values = [np.abs(value) for value in values]\n\n if pad:\n if sign == -1:\n pad = 3\n else:\n pad = 2\n else:\n pad = 0\n\n if not isinstance(sep, tuple):\n sep = tuple(sep)\n\n if fields < 1 or fields > 3:\n raise ValueError(\n \"fields must be 1, 2, or 3\")\n\n if not sep: # empty string, False, or None, etc.\n sep = ('', '', '')\n elif len(sep) == 1:\n if fields == 3:\n sep = sep + (sep[0], '')\n elif fields == 2:\n sep = sep + ('', '')\n else:\n sep = ('', '', '')\n elif len(sep) == 2:\n sep = sep + ('',)\n elif len(sep) != 3:\n raise ValueError(\n \"Invalid separator specification for converting angle to string.\")\n\n # Simplify the expression based on the requested precision. For\n # example, if the seconds will round up to 60, we should convert\n # it to 0 and carry upwards. If the field is hidden (by the\n # fields kwarg) we round up around the middle, 30.0.\n if precision is None:\n rounding_thresh = 60.0 - (10.0 ** -4)\n else:\n rounding_thresh = 60.0 - (10.0 ** -precision)\n\n if fields == 3 and values[2] >= rounding_thresh:\n values[2] = 0.0\n values[1] += 1.0\n elif fields < 3 and values[2] >= 30.0:\n values[1] += 1.0\n\n if fields >= 2 and values[1] >= 60.0:\n values[1] = 0.0\n values[0] += 1.0\n elif fields < 2 and values[1] >= 30.0:\n values[0] += 1.0\n\n literal = []\n last_value = ''\n literal.append('{0:0{pad}.0f}{sep[0]}')\n if fields >= 2:\n literal.append('{1:02d}{sep[1]}')\n if fields == 3:\n if precision is None:\n last_value = '{:.4f}'.format(abs(values[2]))\n last_value = last_value.rstrip('0').rstrip('.')\n else:\n last_value = '{0:.{precision}f}'.format(\n abs(values[2]), precision=precision)\n if len(last_value) == 1 or last_value[1] == '.':\n last_value = '0' + last_value\n literal.append('{last_value}{sep[2]}')\n literal = ''.join(literal)\n return literal.format(np.copysign(values[0], sign),\n int(values[1]), values[2],\n sep=sep, pad=pad,\n last_value=last_value)\n\n\ndef hours_to_string(h, precision=5, pad=False, sep=('h', 'm', 's'),\n fields=3):\n \"\"\"\n Takes a decimal hour value and returns a string formatted as hms with\n separator specified by the 'sep' parameter.\n\n ``h`` must be a scalar.\n \"\"\"\n h, m, s = hours_to_hms(h)\n return sexagesimal_to_string((h, m, s), precision=precision, pad=pad,\n sep=sep, fields=fields)\n\n\ndef degrees_to_string(d, precision=5, pad=False, sep=':', fields=3):\n \"\"\"\n Takes a decimal hour value and returns a string formatted as dms with\n separator specified by the 'sep' parameter.\n\n ``d`` must be a scalar.\n \"\"\"\n d, m, s = degrees_to_dms(d)\n return sexagesimal_to_string((d, m, s), precision=precision, pad=pad,\n sep=sep, fields=fields)\n\n\ndef angular_separation(lon1, lat1, lon2, lat2):\n \"\"\"\n Angular separation between two points on a sphere.\n\n Parameters\n ----------\n lon1, lat1, lon2, lat2 : `~astropy.coordinates.Angle`, `~astropy.units.Quantity` or float\n Longitude and latitude of the two points. Quantities should be in\n angular units; floats in radians.\n\n Returns\n -------\n angular separation : `~astropy.units.Quantity` or float\n Type depends on input; `Quantity` in angular units, or float in\n radians.\n\n Notes\n -----\n The angular separation is calculated using the Vincenty formula [1]_,\n which is slightly more complex and computationally expensive than\n some alternatives, but is stable at at all distances, including the\n poles and antipodes.\n\n .. [1] https://en.wikipedia.org/wiki/Great-circle_distance\n \"\"\"\n\n sdlon = np.sin(lon2 - lon1)\n cdlon = np.cos(lon2 - lon1)\n slat1 = np.sin(lat1)\n slat2 = np.sin(lat2)\n clat1 = np.cos(lat1)\n clat2 = np.cos(lat2)\n\n num1 = clat2 * sdlon\n num2 = clat1 * slat2 - slat1 * clat2 * cdlon\n denominator = slat1 * slat2 + clat1 * clat2 * cdlon\n\n return np.arctan2(np.hypot(num1, num2), denominator)\n\n\ndef position_angle(lon1, lat1, lon2, lat2):\n \"\"\"\n Position Angle (East of North) between two points on a sphere.\n\n Parameters\n ----------\n lon1, lat1, lon2, lat2 : `~astropy.coordinates.Angle`, `~astropy.units.Quantity` or float\n Longitude and latitude of the two points. Quantities should be in\n angular units; floats in radians.\n\n Returns\n -------\n pa : `~astropy.coordinates.Angle`\n The (positive) position angle of the vector pointing from position 1 to\n position 2. If any of the angles are arrays, this will contain an array\n following the appropriate `numpy` broadcasting rules.\n\n \"\"\"\n from .angles import Angle\n\n deltalon = lon2 - lon1\n colat = np.cos(lat2)\n\n x = np.sin(lat2) * np.cos(lat1) - colat * np.sin(lat1) * np.cos(deltalon)\n y = np.sin(deltalon) * colat\n\n return Angle(np.arctan2(y, x), u.radian).wrap_at(360*u.deg)\n\n\ndef offset_by(lon, lat, posang, distance):\n \"\"\"\n Point with the given offset from the given point.\n\n Parameters\n ----------\n lon, lat, posang, distance : `~astropy.coordinates.Angle`, `~astropy.units.Quantity` or float\n Longitude and latitude of the starting point,\n position angle and distance to the final point.\n Quantities should be in angular units; floats in radians.\n Polar points at lat= +/-90 are treated as limit of +/-(90-epsilon) and same lon.\n\n Returns\n -------\n lon, lat : `~astropy.coordinates.Angle`\n The position of the final point. If any of the angles are arrays,\n these will contain arrays following the appropriate `numpy` broadcasting rules.\n 0 <= lon < 2pi.\n\n Notes\n -----\n \"\"\"\n from .angles import Angle\n\n # Calculations are done using the spherical trigonometry sine and cosine rules\n # of the triangle A at North Pole, B at starting point, C at final point\n # with angles A (change in lon), B (posang), C (not used, but negative reciprocal posang)\n # with sides a (distance), b (final co-latitude), c (starting colatitude)\n # B, a, c are knowns; A and b are unknowns\n # https://en.wikipedia.org/wiki/Spherical_trigonometry\n\n cos_a = np.cos(distance)\n sin_a = np.sin(distance)\n cos_c = np.sin(lat)\n sin_c = np.cos(lat)\n cos_B = np.cos(posang)\n sin_B = np.sin(posang)\n\n # cosine rule: Know two sides: a,c and included angle: B; get unknown side b\n cos_b = cos_c * cos_a + sin_c * sin_a * cos_B\n # sin_b = np.sqrt(1 - cos_b**2)\n # sine rule and cosine rule for A (using both lets arctan2 pick quadrant).\n # multiplying both sin_A and cos_A by x=sin_b * sin_c prevents /0 errors\n # at poles. Correct for the x=0 multiplication a few lines down.\n # sin_A/sin_a == sin_B/sin_b # Sine rule\n xsin_A = sin_a * sin_B * sin_c\n # cos_a == cos_b * cos_c + sin_b * sin_c * cos_A # cosine rule\n xcos_A = cos_a - cos_b * cos_c\n\n A = Angle(np.arctan2(xsin_A, xcos_A), u.radian)\n # Treat the poles as if they are infinitesimally far from pole but at given lon\n small_sin_c = sin_c < 1e-12\n if small_sin_c.any():\n # For south pole (cos_c = -1), A = posang; for North pole, A=180 deg - posang\n A_pole = (90*u.deg + cos_c*(90*u.deg-Angle(posang, u.radian))).to(u.rad)\n if A.shape:\n # broadcast to ensure the shape is like that of A, which is also\n # affected by the (possible) shapes of lat, posang, and distance.\n small_sin_c = np.broadcast_to(small_sin_c, A.shape)\n A[small_sin_c] = A_pole[small_sin_c]\n else:\n A = A_pole\n\n outlon = (Angle(lon, u.radian) + A).wrap_at(360.0*u.deg).to(u.deg)\n outlat = Angle(np.arcsin(cos_b), u.radian).to(u.deg)\n\n return outlon, outlat\n", "# Licensed under a 3-clause BSD style license - see LICENSE.rst\n\nimport functools\n\nimport numpy as np\nimport pytest\n\nfrom astropy.utils import iers\nfrom astropy.time import Time\nfrom astropy.table import Table\n\ntry:\n import h5py # pylint: disable=W0611 # noqa\nexcept ImportError:\n HAS_H5PY = False\nelse:\n HAS_H5PY = True\n\ntry:\n import yaml # pylint: disable=W0611 # noqa\n HAS_YAML = True\nexcept ImportError:\n HAS_YAML = False\n\nallclose_sec = functools.partial(np.allclose, rtol=2. ** -52,\n atol=2. ** -52 * 24 * 3600) # 20 ps atol\nis_masked = np.ma.is_masked\n\n\ndef test_simple():\n t = Time([1, 2, 3], format='cxcsec')\n assert t.masked is False\n assert np.all(t.mask == [False, False, False])\n\n # Before masking, format output is not a masked array (it is an ndarray\n # like always)\n assert not isinstance(t.value, np.ma.MaskedArray)\n assert not isinstance(t.unix, np.ma.MaskedArray)\n\n t[2] = np.ma.masked\n assert t.masked is True\n assert np.all(t.mask == [False, False, True])\n assert allclose_sec(t.value[:2], [1, 2])\n assert is_masked(t.value[2])\n assert is_masked(t[2].value)\n\n # After masking format output is a masked array\n assert isinstance(t.value, np.ma.MaskedArray)\n assert isinstance(t.unix, np.ma.MaskedArray)\n # Todo : test all formats\n\n\ndef test_scalar_init():\n t = Time('2000:001')\n assert t.masked is False\n assert t.mask == np.array(False)\n\n\ndef test_mask_not_writeable():\n t = Time('2000:001')\n with pytest.raises(AttributeError) as err:\n t.mask = True\n assert \"can't set attribute\" in str(err.value)\n\n t = Time(['2000:001'])\n with pytest.raises(ValueError) as err:\n t.mask[0] = True\n assert \"assignment destination is read-only\" in str(err.value)\n\n\ndef test_str():\n t = Time(['2000:001', '2000:002'])\n t[1] = np.ma.masked\n assert str(t) == \"['2000:001:00:00:00.000' --]\"\n assert repr(t) == \"<Time object: scale='utc' format='yday' value=['2000:001:00:00:00.000' --]>\"\n\n expected = [\"masked_array(data=['2000-01-01 00:00:00.000', --],\",\n ' mask=[False, True],',\n \" fill_value='N/A',\",\n \" dtype='<U23')\"]\n\n # Note that we need to take care to allow for big-endian platforms,\n # for which the dtype will be >U23 instead of <U23, which we do with\n # the call to replace().\n assert repr(t.iso).replace('>U23', '<U23').splitlines() == expected\n\n # Assign value to unmask\n t[1] = '2000:111'\n assert str(t) == \"['2000:001:00:00:00.000' '2000:111:00:00:00.000']\"\n assert t.masked is False\n\n\ndef test_transform():\n with iers.conf.set_temp('auto_download', False):\n t = Time(['2000:001', '2000:002'])\n t[1] = np.ma.masked\n\n # Change scale (this tests the ERFA machinery with masking as well)\n t_ut1 = t.ut1\n assert is_masked(t_ut1.value[1])\n assert not is_masked(t_ut1.value[0])\n assert np.all(t_ut1.mask == [False, True])\n\n # Change format\n t_unix = t.unix\n assert is_masked(t_unix[1])\n assert not is_masked(t_unix[0])\n assert np.all(t_unix.mask == [False, True])\n\n\ndef test_masked_input():\n v0 = np.ma.MaskedArray([[1, 2], [3, 4]]) # No masked elements\n v1 = np.ma.MaskedArray([[1, 2], [3, 4]],\n mask=[[True, False], [False, False]])\n v2 = np.ma.MaskedArray([[10, 20], [30, 40]],\n mask=[[False, False], [False, True]])\n\n # Init from various combinations of masked arrays\n t = Time(v0, format='cxcsec')\n assert np.ma.allclose(t.value, v0)\n assert np.all(t.mask == [[False, False], [False, False]])\n assert t.masked is False\n\n t = Time(v1, format='cxcsec')\n assert np.ma.allclose(t.value, v1)\n assert np.all(t.mask == v1.mask)\n assert np.all(t.value.mask == v1.mask)\n assert t.masked is True\n\n t = Time(v1, v2, format='cxcsec')\n assert np.ma.allclose(t.value, v1 + v2)\n assert np.all(t.mask == (v1 + v2).mask)\n assert t.masked is True\n\n t = Time(v0, v1, format='cxcsec')\n assert np.ma.allclose(t.value, v0 + v1)\n assert np.all(t.mask == (v0 + v1).mask)\n assert t.masked is True\n\n t = Time(0, v2, format='cxcsec')\n assert np.ma.allclose(t.value, v2)\n assert np.all(t.mask == v2.mask)\n assert t.masked is True\n\n # Init from a string masked array\n t_iso = t.iso\n t2 = Time(t_iso)\n assert np.all(t2.value == t_iso)\n assert np.all(t2.mask == v2.mask)\n assert t2.masked is True\n\n\ndef test_all_masked_input():\n \"\"\"Fix for #9612\"\"\"\n # Test with jd=0 and jd=np.nan. Both triggered an exception prior to #9624\n # due to astropy.utils.exceptions.ErfaError.\n for val in (0, np.nan):\n t = Time(np.ma.masked_array([val], mask=[True]), format='jd')\n assert str(t.iso) == '[--]'\n\n\ndef test_serialize_fits_masked(tmpdir):\n tm = Time([1, 2, 3], format='cxcsec')\n tm[1] = np.ma.masked\n\n fn = str(tmpdir.join('tempfile.fits'))\n t = Table([tm])\n t.write(fn)\n\n t2 = Table.read(fn, astropy_native=True)\n\n # Time FITS handling does not current round-trip format in FITS\n t2['col0'].format = tm.format\n\n assert t2['col0'].masked\n assert np.all(t2['col0'].mask == [False, True, False])\n assert np.all(t2['col0'].value == t['col0'].value)\n\n\[email protected](not HAS_YAML or not HAS_H5PY,\n reason='Need both h5py and yaml')\ndef test_serialize_hdf5_masked(tmpdir):\n tm = Time([1, 2, 3], format='cxcsec')\n tm[1] = np.ma.masked\n\n fn = str(tmpdir.join('tempfile.hdf5'))\n t = Table([tm])\n t.write(fn, path='root', serialize_meta=True)\n t2 = Table.read(fn)\n\n assert t2['col0'].masked\n assert np.all(t2['col0'].mask == [False, True, False])\n assert np.all(t2['col0'].value == t['col0'].value)\n\n\n# Ignore warning in MIPS https://github.com/astropy/astropy/issues/9750\[email protected]('not HAS_YAML')\[email protected]('ignore:invalid value encountered')\ndef test_serialize_ecsv_masked(tmpdir):\n tm = Time([1, 2, 3], format='cxcsec')\n tm[1] = np.ma.masked\n\n # Serializing in the default way for ECSV fails to round-trip\n # because it writes out a \"nan\" instead of \"\". But for jd1/jd2\n # this works OK.\n tm.info.serialize_method['ecsv'] = 'jd1_jd2'\n\n fn = str(tmpdir.join('tempfile.ecsv'))\n t = Table([tm])\n t.write(fn)\n t2 = Table.read(fn)\n\n assert t2['col0'].masked\n assert np.all(t2['col0'].mask == [False, True, False])\n # Serializing floats to ASCII loses some precision so use allclose\n # and 1e-7 seconds tolerance.\n assert np.allclose(t2['col0'].value, t['col0'].value, rtol=0, atol=1e-7)\n", "# Licensed under a 3-clause BSD style license - see LICENSE.rst\n\n\"\"\"\nThis module contains convenience functions for coordinate-related functionality.\n\nThis is generally just wrapping around the object-oriented coordinates\nframework, but it is useful for some users who are used to more functional\ninterfaces.\n\"\"\"\n\nimport warnings\nfrom collections.abc import Sequence\n\nimport numpy as np\nimport erfa\n\nfrom astropy import units as u\nfrom astropy.constants import c\nfrom astropy.io import ascii\nfrom astropy.utils import isiterable, data\nfrom .sky_coordinate import SkyCoord\nfrom .builtin_frames import GCRS, PrecessedGeocentric\nfrom .representation import SphericalRepresentation, CartesianRepresentation\nfrom .builtin_frames.utils import get_jd12\n\n__all__ = ['cartesian_to_spherical', 'spherical_to_cartesian', 'get_sun',\n 'get_constellation', 'concatenate_representations', 'concatenate']\n\n\ndef cartesian_to_spherical(x, y, z):\n \"\"\"\n Converts 3D rectangular cartesian coordinates to spherical polar\n coordinates.\n\n Note that the resulting angles are latitude/longitude or\n elevation/azimuthal form. I.e., the origin is along the equator\n rather than at the north pole.\n\n .. note::\n This function simply wraps functionality provided by the\n `~astropy.coordinates.CartesianRepresentation` and\n `~astropy.coordinates.SphericalRepresentation` classes. In general,\n for both performance and readability, we suggest using these classes\n directly. But for situations where a quick one-off conversion makes\n sense, this function is provided.\n\n Parameters\n ----------\n x : scalar, array_like, or `~astropy.units.Quantity`\n The first cartesian coordinate.\n y : scalar, array_like, or `~astropy.units.Quantity`\n The second cartesian coordinate.\n z : scalar, array_like, or `~astropy.units.Quantity`\n The third cartesian coordinate.\n\n Returns\n -------\n r : `~astropy.units.Quantity`\n The radial coordinate (in the same units as the inputs).\n lat : `~astropy.units.Quantity`\n The latitude in radians\n lon : `~astropy.units.Quantity`\n The longitude in radians\n \"\"\"\n if not hasattr(x, 'unit'):\n x = x * u.dimensionless_unscaled\n if not hasattr(y, 'unit'):\n y = y * u.dimensionless_unscaled\n if not hasattr(z, 'unit'):\n z = z * u.dimensionless_unscaled\n\n cart = CartesianRepresentation(x, y, z)\n sph = cart.represent_as(SphericalRepresentation)\n\n return sph.distance, sph.lat, sph.lon\n\n\ndef spherical_to_cartesian(r, lat, lon):\n \"\"\"\n Converts spherical polar coordinates to rectangular cartesian\n coordinates.\n\n Note that the input angles should be in latitude/longitude or\n elevation/azimuthal form. I.e., the origin is along the equator\n rather than at the north pole.\n\n .. note::\n This is a low-level function used internally in\n `astropy.coordinates`. It is provided for users if they really\n want to use it, but it is recommended that you use the\n `astropy.coordinates` coordinate systems.\n\n Parameters\n ----------\n r : scalar, array_like, or `~astropy.units.Quantity`\n The radial coordinate (in the same units as the inputs).\n lat : scalar, array_like, or `~astropy.units.Quantity`\n The latitude (in radians if array or scalar)\n lon : scalar, array_like, or `~astropy.units.Quantity`\n The longitude (in radians if array or scalar)\n\n Returns\n -------\n x : float or array\n The first cartesian coordinate.\n y : float or array\n The second cartesian coordinate.\n z : float or array\n The third cartesian coordinate.\n\n\n \"\"\"\n if not hasattr(r, 'unit'):\n r = r * u.dimensionless_unscaled\n if not hasattr(lat, 'unit'):\n lat = lat * u.radian\n if not hasattr(lon, 'unit'):\n lon = lon * u.radian\n\n sph = SphericalRepresentation(distance=r, lat=lat, lon=lon)\n cart = sph.represent_as(CartesianRepresentation)\n\n return cart.x, cart.y, cart.z\n\n\ndef get_sun(time):\n \"\"\"\n Determines the location of the sun at a given time (or times, if the input\n is an array `~astropy.time.Time` object), in geocentric coordinates.\n\n Parameters\n ----------\n time : `~astropy.time.Time`\n The time(s) at which to compute the location of the sun.\n\n Returns\n -------\n newsc : `~astropy.coordinates.SkyCoord`\n The location of the sun as a `~astropy.coordinates.SkyCoord` in the\n `~astropy.coordinates.GCRS` frame.\n\n\n Notes\n -----\n The algorithm for determining the sun/earth relative position is based\n on the simplified version of VSOP2000 that is part of ERFA. Compared to\n JPL's ephemeris, it should be good to about 4 km (in the Sun-Earth\n vector) from 1900-2100 C.E., 8 km for the 1800-2200 span, and perhaps\n 250 km over the 1000-3000.\n\n \"\"\"\n earth_pv_helio, earth_pv_bary = erfa.epv00(*get_jd12(time, 'tdb'))\n\n # We have to manually do aberration because we're outputting directly into\n # GCRS\n earth_p = earth_pv_helio['p']\n earth_v = earth_pv_bary['v']\n\n # convert barycentric velocity to units of c, but keep as array for passing in to erfa\n earth_v /= c.to_value(u.au/u.d)\n\n dsun = np.sqrt(np.sum(earth_p**2, axis=-1))\n invlorentz = (1-np.sum(earth_v**2, axis=-1))**0.5\n properdir = erfa.ab(earth_p/dsun.reshape(dsun.shape + (1,)),\n -earth_v, dsun, invlorentz)\n\n cartrep = CartesianRepresentation(x=-dsun*properdir[..., 0] * u.AU,\n y=-dsun*properdir[..., 1] * u.AU,\n z=-dsun*properdir[..., 2] * u.AU)\n return SkyCoord(cartrep, frame=GCRS(obstime=time))\n\n\n# global dictionary that caches repeatedly-needed info for get_constellation\n_constellation_data = {}\n\n\ndef get_constellation(coord, short_name=False, constellation_list='iau'):\n \"\"\"\n Determines the constellation(s) a given coordinate object contains.\n\n Parameters\n ----------\n coord : coordinate object\n The object to determine the constellation of.\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 ``coords`` contains a scalar coordinate, returns the name of the\n constellation. If it is an array coordinate object, it returns an array\n of names.\n\n Notes\n -----\n To determine which constellation a point on the sky is in, this precesses\n to B1875, and then uses the Delporte boundaries of the 88 modern\n constellations, as tabulated by\n `Roman 1987 <http://cdsarc.u-strasbg.fr/viz-bin/Cat?VI/42>`_.\n \"\"\"\n if constellation_list != 'iau':\n raise ValueError(\"only 'iau' us currently supported for constellation_list\")\n\n # read the data files and cache them if they haven't been already\n if not _constellation_data:\n cdata = data.get_pkg_data_contents('data/constellation_data_roman87.dat')\n ctable = ascii.read(cdata, names=['ral', 'rau', 'decl', 'name'])\n cnames = data.get_pkg_data_contents('data/constellation_names.dat', encoding='UTF8')\n cnames_short_to_long = dict([(l[:3], l[4:])\n for l in cnames.split('\\n')\n if not l.startswith('#')])\n cnames_long = np.array([cnames_short_to_long[nm] for nm in ctable['name']])\n\n _constellation_data['ctable'] = ctable\n _constellation_data['cnames_long'] = cnames_long\n else:\n ctable = _constellation_data['ctable']\n cnames_long = _constellation_data['cnames_long']\n\n isscalar = coord.isscalar\n\n # if it is geocentric, we reproduce the frame but with the 1875 equinox,\n # which is where the constellations are defined\n # this yields a \"dubious year\" warning because ERFA considers the year 1875\n # \"dubious\", probably because UTC isn't well-defined then and precession\n # models aren't precisely calibrated back to then. But it's plenty\n # sufficient for constellations\n with warnings.catch_warnings():\n warnings.simplefilter('ignore', erfa.ErfaWarning)\n constel_coord = coord.transform_to(PrecessedGeocentric(equinox='B1875'))\n if isscalar:\n rah = constel_coord.ra.ravel().hour\n decd = constel_coord.dec.ravel().deg\n else:\n rah = constel_coord.ra.hour\n decd = constel_coord.dec.deg\n\n constellidx = -np.ones(len(rah), dtype=int)\n\n notided = constellidx == -1 # should be all\n for i, row in enumerate(ctable):\n msk = (row['ral'] < rah) & (rah < row['rau']) & (decd > row['decl'])\n constellidx[notided & msk] = i\n notided = constellidx == -1\n if np.sum(notided) == 0:\n break\n else:\n raise ValueError('Could not find constellation for coordinates {}'.format(constel_coord[notided]))\n\n if short_name:\n names = ctable['name'][constellidx]\n else:\n names = cnames_long[constellidx]\n\n if isscalar:\n return names[0]\n else:\n return names\n\n\ndef _concatenate_components(reps_difs, names):\n \"\"\" Helper function for the concatenate function below. Gets and\n concatenates all of the individual components for an iterable of\n representations or differentials.\n \"\"\"\n values = []\n for name in names:\n unit0 = getattr(reps_difs[0], name).unit\n # Go via to_value because np.concatenate doesn't work with Quantity\n data_vals = [getattr(x, name).to_value(unit0) for x in reps_difs]\n concat_vals = np.concatenate(np.atleast_1d(*data_vals))\n concat_vals = concat_vals << unit0\n values.append(concat_vals)\n\n return values\n\n\ndef concatenate_representations(reps):\n \"\"\"\n Combine multiple representation objects into a single instance by\n concatenating the data in each component.\n\n Currently, all of the input representations have to be the same type. This\n properly handles differential or velocity data, but all input objects must\n have the same differential object type as well.\n\n Parameters\n ----------\n reps : sequence of representation objects\n The objects to concatenate\n\n Returns\n -------\n rep : `~astropy.coordinates.BaseRepresentation` subclass\n A single representation object with its data set to the concatenation of\n all the elements of the input sequence of representations.\n \"\"\"\n if not isinstance(reps, (Sequence, np.ndarray)):\n raise TypeError('Input must be a list or iterable of representation '\n 'objects.')\n\n # First, validate that the represenations are the same, and\n # concatenate all of the positional data:\n rep_type = type(reps[0])\n if any(type(r) != rep_type for r in reps):\n raise TypeError('Input representations must all have the same type.')\n\n # Construct the new representation with the concatenated data from the\n # representations passed in\n values = _concatenate_components(reps,\n rep_type.attr_classes.keys())\n new_rep = rep_type(*values)\n\n has_diff = any('s' in rep.differentials for rep in reps)\n if has_diff and any('s' not in rep.differentials for rep in reps):\n raise ValueError('Input representations must either all contain '\n 'differentials, or not contain differentials.')\n\n if has_diff:\n dif_type = type(reps[0].differentials['s'])\n\n if any('s' not in r.differentials or\n type(r.differentials['s']) != dif_type\n for r in reps):\n raise TypeError('All input representations must have the same '\n 'differential type.')\n\n values = _concatenate_components([r.differentials['s'] for r in reps],\n dif_type.attr_classes.keys())\n new_dif = dif_type(*values)\n new_rep = new_rep.with_differentials({'s': new_dif})\n\n return new_rep\n\n\ndef concatenate(coords):\n \"\"\"\n Combine multiple coordinate objects into a single\n `~astropy.coordinates.SkyCoord`.\n\n \"Coordinate objects\" here mean frame objects with data,\n `~astropy.coordinates.SkyCoord`, or representation objects. Currently,\n they must all be in the same frame, but in a future version this may be\n relaxed to allow inhomogenous sequences of objects.\n\n Parameters\n ----------\n coords : sequence of coordinate objects\n The objects to concatenate\n\n Returns\n -------\n cskycoord : SkyCoord\n A single sky coordinate with its data set to the concatenation of all\n the elements in ``coords``\n \"\"\"\n if getattr(coords, 'isscalar', False) or not isiterable(coords):\n raise TypeError('The argument to concatenate must be iterable')\n\n scs = [SkyCoord(coord, copy=False) for coord in coords]\n\n # Check that all frames are equivalent\n for sc in scs[1:]:\n if not sc.is_equivalent_frame(scs[0]):\n raise ValueError(\"All inputs must have equivalent frames: \"\n \"{} != {}\".format(sc, scs[0]))\n\n # TODO: this can be changed to SkyCoord.from_representation() for a speed\n # boost when we switch to using classmethods\n return SkyCoord(concatenate_representations([c.data for c in coords]),\n frame=scs[0].frame)\n", "# This file includes the definition of a mix-in class that provides the low-\n# and high-level WCS API to the astropy.wcs.WCS object. We keep this code\n# isolated in this mix-in class to avoid making the main wcs.py file too\n# long.\n\nimport warnings\n\nimport numpy as np\n\nfrom astropy import units as u\nfrom astropy.coordinates import SpectralCoord, Galactic, ICRS\nfrom astropy.coordinates.spectral_coordinate import update_differentials_to_match, attach_zero_velocities\nfrom astropy.utils.exceptions import AstropyUserWarning\nfrom astropy.constants import c\n\nfrom .low_level_api import BaseLowLevelWCS\nfrom .high_level_api import HighLevelWCSMixin\nfrom .wrappers import SlicedLowLevelWCS\n\n__all__ = ['custom_ctype_to_ucd_mapping', 'SlicedFITSWCS', 'FITSWCSAPIMixin']\n\nC_SI = c.si.value\n\nVELOCITY_FRAMES = {\n 'GEOCENT': 'gcrs',\n 'BARYCENT': 'icrs',\n 'HELIOCENT': 'hcrs',\n 'LSRK': 'lsrk',\n 'LSRD': 'lsrd'\n}\n\n# The spectra velocity frames below are needed for FITS spectral WCS\n# (see Greisen 06 table 12) but aren't yet defined as real\n# astropy.coordinates frames, so we instead define them here as instances\n# of existing coordinate frames with offset velocities. In future we should\n# make these real frames so that users can more easily recognize these\n# velocity frames when used in SpectralCoord.\n\n# This frame is defined as a velocity of 220 km/s in the\n# direction of l=90, b=0. The rotation velocity is defined\n# in:\n#\n# Kerr and Lynden-Bell 1986, Review of galactic constants.\n#\n# NOTE: this may differ from the assumptions of galcen_v_sun\n# in the Galactocentric frame - the value used here is\n# the one adopted by the WCS standard for spectral\n# transformations.\n\nVELOCITY_FRAMES['GALACTOC'] = Galactic(u=0 * u.km, v=0 * u.km, w=0 * u.km,\n U=0 * u.km / u.s, V=-220 * u.km / u.s, W=0 * u.km / u.s,\n representation_type='cartesian',\n differential_type='cartesian')\n\n# This frame is defined as a velocity of 300 km/s in the\n# direction of l=90, b=0. This is defined in:\n#\n# Transactions of the IAU Vol. XVI B Proceedings of the\n# 16th General Assembly, Reports of Meetings of Commissions:\n# Comptes Rendus Des Séances Des Commissions, Commission 28,\n# p201.\n#\n# Note that these values differ from those used by CASA\n# (308 km/s towards l=105, b=-7) but we use the above values\n# since these are the ones defined in Greisen et al (2006).\n\nVELOCITY_FRAMES['LOCALGRP'] = Galactic(u=0 * u.km, v=0 * u.km, w=0 * u.km,\n U=0 * u.km / u.s, V=-300 * u.km / u.s, W=0 * u.km / u.s,\n representation_type='cartesian',\n differential_type='cartesian')\n\n# This frame is defined as a velocity of 368 km/s in the\n# direction of l=263.85, b=48.25. This is defined in:\n#\n# Bennett et al. (2003), First-Year Wilkinson Microwave\n# Anisotropy Probe (WMAP) Observations: Preliminary Maps\n# and Basic Results\n#\n# Note that in that paper, the dipole is expressed as a\n# temperature (T=3.346 +/- 0.017mK)\n\nVELOCITY_FRAMES['CMBDIPOL'] = Galactic(l=263.85 * u.deg, b=48.25 * u.deg, distance=0 * u.km,\n radial_velocity=-(3.346e-3 / 2.725 * c).to(u.km/u.s))\n\n\n# Mapping from CTYPE axis name to UCD1\n\nCTYPE_TO_UCD1 = {\n\n # Celestial coordinates\n 'RA': 'pos.eq.ra',\n 'DEC': 'pos.eq.dec',\n 'GLON': 'pos.galactic.lon',\n 'GLAT': 'pos.galactic.lat',\n 'ELON': 'pos.ecliptic.lon',\n 'ELAT': 'pos.ecliptic.lat',\n 'TLON': 'pos.bodyrc.lon',\n 'TLAT': 'pos.bodyrc.lat',\n 'HPLT': 'custom:pos.helioprojective.lat',\n 'HPLN': 'custom:pos.helioprojective.lon',\n 'HGLN': 'custom:pos.heliographic.stonyhurst.lon',\n 'HGLT': 'custom:pos.heliographic.stonyhurst.lat',\n 'CRLN': 'custom:pos.heliographic.carrington.lon',\n 'CRLT': 'custom:pos.heliographic.carrington.lat',\n\n # Spectral coordinates (WCS paper 3)\n 'FREQ': 'em.freq', # Frequency\n 'ENER': 'em.energy', # Energy\n 'WAVN': 'em.wavenumber', # Wavenumber\n 'WAVE': 'em.wl', # Vacuum wavelength\n 'VRAD': 'spect.dopplerVeloc.radio', # Radio velocity\n 'VOPT': 'spect.dopplerVeloc.opt', # Optical velocity\n 'ZOPT': 'src.redshift', # Redshift\n 'AWAV': 'em.wl', # Air wavelength\n 'VELO': 'spect.dopplerVeloc', # Apparent radial velocity\n 'BETA': 'custom:spect.doplerVeloc.beta', # Beta factor (v/c)\n\n # Time coordinates (https://www.aanda.org/articles/aa/pdf/2015/02/aa24653-14.pdf)\n 'TIME': 'time',\n 'TAI': 'time',\n 'TT': 'time',\n 'TDT': 'time',\n 'ET': 'time',\n 'IAT': 'time',\n 'UT1': 'time',\n 'UTC': 'time',\n 'GMT': 'time',\n 'GPS': 'time',\n 'TCG': 'time',\n 'TCB': 'time',\n 'TDB': 'time',\n 'LOCAL': 'time'\n\n # UT() and TT() are handled separately in world_axis_physical_types\n\n}\n\n# Keep a list of additional custom mappings that have been registered. This\n# is kept as a list in case nested context managers are used\nCTYPE_TO_UCD1_CUSTOM = []\n\n\nclass custom_ctype_to_ucd_mapping:\n \"\"\"\n A context manager that makes it possible to temporarily add new CTYPE to\n UCD1+ mapping used by :attr:`FITSWCSAPIMixin.world_axis_physical_types`.\n\n Parameters\n ----------\n mapping : dict\n A dictionary mapping a CTYPE value to a UCD1+ value\n\n Examples\n --------\n\n Consider a WCS with the following CTYPE::\n\n >>> from astropy.wcs import WCS\n >>> wcs = WCS(naxis=1)\n >>> wcs.wcs.ctype = ['SPAM']\n\n By default, :attr:`FITSWCSAPIMixin.world_axis_physical_types` returns `None`,\n but this can be overridden::\n\n >>> wcs.world_axis_physical_types\n [None]\n >>> with custom_ctype_to_ucd_mapping({'SPAM': 'food.spam'}):\n ... wcs.world_axis_physical_types\n ['food.spam']\n \"\"\"\n\n def __init__(self, mapping):\n CTYPE_TO_UCD1_CUSTOM.insert(0, mapping)\n self.mapping = mapping\n\n def __enter__(self):\n pass\n\n def __exit__(self, type, value, tb):\n CTYPE_TO_UCD1_CUSTOM.remove(self.mapping)\n\n\nclass SlicedFITSWCS(SlicedLowLevelWCS, HighLevelWCSMixin):\n pass\n\n\nclass FITSWCSAPIMixin(BaseLowLevelWCS, HighLevelWCSMixin):\n \"\"\"\n A mix-in class that is intended to be inherited by the\n :class:`~astropy.wcs.WCS` class and provides the low- and high-level WCS API\n \"\"\"\n\n @property\n def pixel_n_dim(self):\n return self.naxis\n\n @property\n def world_n_dim(self):\n return len(self.wcs.ctype)\n\n @property\n def array_shape(self):\n if self.pixel_shape is None:\n return None\n else:\n return self.pixel_shape[::-1]\n\n @array_shape.setter\n def array_shape(self, value):\n if value is None:\n self.pixel_shape = None\n else:\n self.pixel_shape = value[::-1]\n\n @property\n def pixel_shape(self):\n if self._naxis == [0, 0]:\n return None\n else:\n return tuple(self._naxis)\n\n @pixel_shape.setter\n def pixel_shape(self, value):\n if value is None:\n self._naxis = [0, 0]\n else:\n if len(value) != self.naxis:\n raise ValueError(\"The number of data axes, \"\n \"{}, does not equal the \"\n \"shape {}.\".format(self.naxis, len(value)))\n self._naxis = list(value)\n\n @property\n def pixel_bounds(self):\n return self._pixel_bounds\n\n @pixel_bounds.setter\n def pixel_bounds(self, value):\n if value is None:\n self._pixel_bounds = value\n else:\n if len(value) != self.naxis:\n raise ValueError(\"The number of data axes, \"\n \"{}, does not equal the number of \"\n \"pixel bounds {}.\".format(self.naxis, len(value)))\n self._pixel_bounds = list(value)\n\n @property\n def world_axis_physical_types(self):\n types = []\n # TODO: need to support e.g. TT(TAI)\n for ctype in self.wcs.ctype:\n if ctype.upper().startswith(('UT(', 'TT(')):\n types.append('time')\n else:\n ctype_name = ctype.split('-')[0]\n for custom_mapping in CTYPE_TO_UCD1_CUSTOM:\n if ctype_name in custom_mapping:\n types.append(custom_mapping[ctype_name])\n break\n else:\n types.append(CTYPE_TO_UCD1.get(ctype_name.upper(), None))\n return types\n\n @property\n def world_axis_units(self):\n units = []\n for unit in self.wcs.cunit:\n if unit is None:\n unit = ''\n elif isinstance(unit, u.Unit):\n unit = unit.to_string(format='vounit')\n else:\n try:\n unit = u.Unit(unit).to_string(format='vounit')\n except u.UnitsError:\n unit = ''\n units.append(unit)\n return units\n\n @property\n def world_axis_names(self):\n return list(self.wcs.cname)\n\n @property\n def axis_correlation_matrix(self):\n\n # If there are any distortions present, we assume that there may be\n # correlations between all axes. Maybe if some distortions only apply\n # to the image plane we can improve this?\n if self.has_distortion:\n return np.ones((self.world_n_dim, self.pixel_n_dim), dtype=bool)\n\n # Assuming linear world coordinates along each axis, the correlation\n # matrix would be given by whether or not the PC matrix is zero\n matrix = self.wcs.get_pc() != 0\n\n # We now need to check specifically for celestial coordinates since\n # these can assume correlations because of spherical distortions. For\n # each celestial coordinate we copy over the pixel dependencies from\n # the other celestial coordinates.\n celestial = (self.wcs.axis_types // 1000) % 10 == 2\n celestial_indices = np.nonzero(celestial)[0]\n for world1 in celestial_indices:\n for world2 in celestial_indices:\n if world1 != world2:\n matrix[world1] |= matrix[world2]\n matrix[world2] |= matrix[world1]\n\n return matrix\n\n def pixel_to_world_values(self, *pixel_arrays):\n world = self.all_pix2world(*pixel_arrays, 0)\n return world[0] if self.world_n_dim == 1 else tuple(world)\n\n def world_to_pixel_values(self, *world_arrays):\n pixel = self.all_world2pix(*world_arrays, 0)\n return pixel[0] if self.pixel_n_dim == 1 else tuple(pixel)\n\n @property\n def world_axis_object_components(self):\n return self._get_components_and_classes()[0]\n\n @property\n def world_axis_object_classes(self):\n return self._get_components_and_classes()[1]\n\n @property\n def serialized_classes(self):\n return False\n\n def _get_components_and_classes(self):\n\n # The aim of this function is to return whatever is needed for\n # world_axis_object_components and world_axis_object_classes. It's easier\n # to figure it out in one go and then return the values and let the\n # properties return part of it.\n\n # Since this method might get called quite a few times, we need to cache\n # it. We start off by defining a hash based on the attributes of the\n # WCS that matter here (we can't just use the WCS object as a hash since\n # it is mutable)\n wcs_hash = (self.naxis,\n list(self.wcs.ctype),\n list(self.wcs.cunit),\n self.wcs.radesys,\n self.wcs.specsys,\n self.wcs.equinox,\n self.wcs.dateobs,\n self.wcs.lng,\n self.wcs.lat)\n\n # If the cache is present, we need to check that the 'hash' matches.\n if getattr(self, '_components_and_classes_cache', None) is not None:\n cache = self._components_and_classes_cache\n if cache[0] == wcs_hash:\n return cache[1]\n else:\n self._components_and_classes_cache = None\n\n # Avoid circular imports by importing here\n from astropy.wcs.utils import wcs_to_celestial_frame\n from astropy.coordinates import SkyCoord, EarthLocation\n from astropy.time.formats import FITS_DEPRECATED_SCALES\n from astropy.time import Time, TimeDelta\n\n components = [None] * self.naxis\n classes = {}\n\n # Let's start off by checking whether the WCS has a pair of celestial\n # components\n\n if self.has_celestial:\n\n try:\n celestial_frame = wcs_to_celestial_frame(self)\n except ValueError:\n # Some WCSes, e.g. solar, can be recognized by WCSLIB as being\n # celestial but we don't necessarily have frames for them.\n celestial_frame = None\n else:\n\n kwargs = {}\n kwargs['frame'] = celestial_frame\n kwargs['unit'] = u.deg\n\n classes['celestial'] = (SkyCoord, (), kwargs)\n\n components[self.wcs.lng] = ('celestial', 0, 'spherical.lon.degree')\n components[self.wcs.lat] = ('celestial', 1, 'spherical.lat.degree')\n\n # Next, we check for spectral components\n\n if self.has_spectral:\n\n # Find index of spectral coordinate\n ispec = self.wcs.spec\n ctype = self.wcs.ctype[ispec][:4]\n ctype = ctype.upper()\n\n kwargs = {}\n\n # Determine observer location and velocity\n\n # TODO: determine how WCS standard would deal with observer on a\n # spacecraft far from earth. For now assume the obsgeo parameters,\n # if present, give the geocentric observer location.\n\n if np.isnan(self.wcs.obsgeo[0]):\n observer = None\n else:\n\n earth_location = EarthLocation(*self.wcs.obsgeo[:3], unit=u.m)\n obstime = Time(self.wcs.mjdobs, format='mjd', scale='utc',\n location=earth_location)\n observer_location = SkyCoord(earth_location.get_itrs(obstime=obstime))\n\n if self.wcs.specsys in VELOCITY_FRAMES:\n frame = VELOCITY_FRAMES[self.wcs.specsys]\n observer = observer_location.transform_to(frame)\n if isinstance(frame, str):\n observer = attach_zero_velocities(observer)\n else:\n observer = update_differentials_to_match(observer_location,\n VELOCITY_FRAMES[self.wcs.specsys],\n preserve_observer_frame=True)\n elif self.wcs.specsys == 'TOPOCENT':\n observer = attach_zero_velocities(observer_location)\n else:\n raise NotImplementedError(f'SPECSYS={self.wcs.specsys} not yet supported')\n\n # Determine target\n\n # This is tricker. In principle the target for each pixel is the\n # celestial coordinates of the pixel, but we then need to be very\n # careful about SSYSOBS which is tricky. For now, we set the\n # target using the reference celestial coordinate in the WCS (if\n # any).\n\n if self.has_celestial and celestial_frame is not None:\n\n # NOTE: celestial_frame was defined higher up\n\n # NOTE: we set the distance explicitly to avoid warnings in SpectralCoord\n\n target = SkyCoord(self.wcs.crval[self.wcs.lng] * self.wcs.cunit[self.wcs.lng],\n self.wcs.crval[self.wcs.lat] * self.wcs.cunit[self.wcs.lat],\n frame=celestial_frame,\n distance=1000 * u.kpc)\n\n target = attach_zero_velocities(target)\n\n else:\n\n target = None\n\n # SpectralCoord does not work properly if either observer or target\n # are not convertible to ICRS, so if this is the case, we (for now)\n # drop the observer and target from the SpectralCoord and warn the\n # user.\n\n if observer is not None:\n try:\n observer.transform_to(ICRS())\n except Exception:\n warnings.warn('observer cannot be converted to ICRS, so will '\n 'not be set on SpectralCoord', AstropyUserWarning)\n observer = None\n\n if target is not None:\n try:\n target.transform_to(ICRS())\n except Exception:\n warnings.warn('target cannot be converted to ICRS, so will '\n 'not be set on SpectralCoord', AstropyUserWarning)\n target = None\n\n # NOTE: below we include Quantity in classes['spectral'] instead\n # of SpectralCoord - this is because we want to also be able to\n # accept plain quantities.\n\n if ctype == 'ZOPT':\n\n def spectralcoord_from_redshift(redshift):\n return SpectralCoord((redshift + 1) * self.wcs.restwav,\n unit=u.m, observer=observer, target=target)\n\n def redshift_from_spectralcoord(spectralcoord):\n # TODO: check target is consistent\n if observer is None:\n warnings.warn('No observer defined on WCS, SpectralCoord '\n 'will be converted without any velocity '\n 'frame change', AstropyUserWarning)\n return spectralcoord.to_value(u.m) / self.wcs.restwav - 1.\n else:\n return spectralcoord.in_observer_velocity_frame(observer).to_value(u.m) / self.wcs.restwav - 1.\n\n classes['spectral'] = (u.Quantity, (), {}, spectralcoord_from_redshift)\n components[self.wcs.spec] = ('spectral', 0, redshift_from_spectralcoord)\n\n elif ctype == 'BETA':\n\n def spectralcoord_from_beta(beta):\n return SpectralCoord(beta * C_SI,\n unit=u.m / u.s,\n doppler_convention='relativistic',\n doppler_rest=self.wcs.restwav * u.m,\n observer=observer, target=target)\n\n def beta_from_spectralcoord(spectralcoord):\n # TODO: check target is consistent\n doppler_equiv = u.doppler_relativistic(self.wcs.restwav * u.m)\n if observer is None:\n warnings.warn('No observer defined on WCS, SpectralCoord '\n 'will be converted without any velocity '\n 'frame change', AstropyUserWarning)\n return spectralcoord.to_value(u.m / u.s, doppler_equiv) / C_SI\n else:\n return spectralcoord.in_observer_velocity_frame(observer).to_value(u.m / u.s, doppler_equiv) / C_SI\n\n classes['spectral'] = (u.Quantity, (), {}, spectralcoord_from_beta)\n components[self.wcs.spec] = ('spectral', 0, beta_from_spectralcoord)\n\n else:\n\n kwargs['unit'] = self.wcs.cunit[ispec]\n\n if self.wcs.restfrq > 0:\n if ctype == 'VELO':\n kwargs['doppler_convention'] = 'relativistic'\n kwargs['doppler_rest'] = self.wcs.restfrq * u.Hz\n elif ctype == 'VRAD':\n kwargs['doppler_convention'] = 'radio'\n kwargs['doppler_rest'] = self.wcs.restfrq * u.Hz\n elif ctype == 'VOPT':\n kwargs['doppler_convention'] = 'optical'\n kwargs['doppler_rest'] = self.wcs.restwav * u.m\n\n def spectralcoord_from_value(value):\n return SpectralCoord(value, observer=observer, target=target, **kwargs)\n\n def value_from_spectralcoord(spectralcoord):\n # TODO: check target is consistent\n if observer is None:\n warnings.warn('No observer defined on WCS, SpectralCoord '\n 'will be converted without any velocity '\n 'frame change', AstropyUserWarning)\n return spectralcoord.to_value(**kwargs)\n else:\n return spectralcoord.in_observer_velocity_frame(observer).to_value(**kwargs)\n\n classes['spectral'] = (u.Quantity, (), {}, spectralcoord_from_value)\n components[self.wcs.spec] = ('spectral', 0, value_from_spectralcoord)\n\n # We can then make sure we correctly return Time objects where appropriate\n # (https://www.aanda.org/articles/aa/pdf/2015/02/aa24653-14.pdf)\n\n if 'time' in self.world_axis_physical_types:\n\n multiple_time = self.world_axis_physical_types.count('time') > 1\n\n for i in range(self.naxis):\n\n if self.world_axis_physical_types[i] == 'time':\n\n if multiple_time:\n name = f'time.{i}'\n else:\n name = 'time'\n\n # Initialize delta\n reference_time_delta = None\n\n # Extract time scale\n scale = self.wcs.ctype[i].lower()\n\n if scale == 'time':\n if self.wcs.timesys:\n scale = self.wcs.timesys.lower()\n else:\n scale = 'utc'\n\n # Drop sub-scales\n if '(' in scale:\n pos = scale.index('(')\n scale, subscale = scale[:pos], scale[pos+1:-1]\n warnings.warn(f'Dropping unsupported sub-scale '\n f'{subscale.upper()} from scale {scale.upper()}',\n UserWarning)\n\n # TODO: consider having GPS as a scale in Time\n # For now GPS is not a scale, we approximate this by TAI - 19s\n if scale == 'gps':\n reference_time_delta = TimeDelta(19, format='sec')\n scale = 'tai'\n\n elif scale.upper() in FITS_DEPRECATED_SCALES:\n scale = FITS_DEPRECATED_SCALES[scale.upper()]\n\n elif scale not in Time.SCALES:\n raise ValueError(f'Unrecognized time CTYPE={self.wcs.ctype[i]}')\n\n # Determine location\n trefpos = self.wcs.trefpos.lower()\n\n if trefpos.startswith('topocent'):\n # Note that some headers use TOPOCENT instead of TOPOCENTER\n if np.any(np.isnan(self.wcs.obsgeo[:3])):\n warnings.warn('Missing or incomplete observer location '\n 'information, setting location in Time to None',\n UserWarning)\n location = None\n else:\n location = EarthLocation(*self.wcs.obsgeo[:3], unit=u.m)\n elif trefpos == 'geocenter':\n location = EarthLocation(0, 0, 0, unit=u.m)\n elif trefpos == '':\n location = None\n else:\n # TODO: implement support for more locations when Time supports it\n warnings.warn(f\"Observation location '{trefpos}' is not \"\n \"supported, setting location in Time to None\", UserWarning)\n location = None\n\n reference_time = Time(np.nan_to_num(self.wcs.mjdref[0]),\n np.nan_to_num(self.wcs.mjdref[1]),\n format='mjd', scale=scale,\n location=location)\n\n if reference_time_delta is not None:\n reference_time = reference_time + reference_time_delta\n\n def time_from_reference_and_offset(offset):\n if isinstance(offset, Time):\n return offset\n return reference_time + TimeDelta(offset, format='sec')\n\n def offset_from_time_and_reference(time):\n return (time - reference_time).sec\n\n classes[name] = (Time, (), {}, time_from_reference_and_offset)\n components[i] = (name, 0, offset_from_time_and_reference)\n\n # Fallback: for any remaining components that haven't been identified, just\n # return Quantity as the class to use\n\n for i in range(self.naxis):\n if components[i] is None:\n name = self.wcs.ctype[i].split('-')[0].lower()\n if name == '':\n name = 'world'\n while name in classes:\n name += \"_\"\n classes[name] = (u.Quantity, (), {'unit': self.wcs.cunit[i]})\n components[i] = (name, 0, 'value')\n\n # Keep a cached version of result\n self._components_and_classes_cache = wcs_hash, (components, classes)\n\n return components, classes\n" ]
[ [ "numpy.isnan", "numpy.dtype", "numpy.atleast_1d", "numpy.count_nonzero", "numpy.where", "numpy.isinf" ], [ "numpy.linspace", "numpy.cos", "numpy.sin", "numpy.deg2rad", "numpy.hypot" ], [ "numpy.random.poisson", "numpy.broadcast", "numpy.asanyarray", "numpy.random.randn", "numpy.random.uniform" ], [ "numpy.abs", "numpy.arcsin", "numpy.cos", "numpy.sin", "numpy.modf", "numpy.arctan2", "numpy.copysign", "numpy.any", "numpy.floor", "numpy.broadcast_to", "numpy.hypot" ], [ "numpy.allclose", "numpy.ma.allclose", "numpy.all", "numpy.ma.masked_array", "numpy.array", "numpy.ma.MaskedArray" ], [ "numpy.atleast_1d", "numpy.array", "numpy.sum" ], [ "numpy.isnan", "numpy.nan_to_num", "numpy.nonzero", "numpy.ones" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [ "1.10", "1.12", "1.11", "1.19", "1.13", "1.16", "1.9", "1.18", "1.20", "1.7", "1.15", "1.14", "1.17", "1.8" ], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
zchvsre/TreeCorr
[ "825dc0a9d4754f9d98ebcf9c26dee9597915d650", "825dc0a9d4754f9d98ebcf9c26dee9597915d650" ]
[ "treecorr/binnedcorr3.py", "treecorr/util.py" ]
[ "# Copyright (c) 2003-2019 by Mike Jarvis\n#\n# TreeCorr is free software: redistribution and use in source and binary forms,\n# with or without modification, are permitted provided that the following\n# conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, this\n# list of conditions, and the disclaimer given in the accompanying LICENSE\n# file.\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions, and the disclaimer given in the documentation\n# and/or other materials provided with the distribution.\n\n\"\"\"\n.. module:: binnedcorr3\n\"\"\"\n\nimport math\nimport numpy as np\nimport sys\nimport coord\nimport treecorr\n\nclass BinnedCorr3(object):\n \"\"\"This class stores the results of a 3-point correlation calculation, along with some\n ancillary data.\n\n This is a base class that is not intended to be constructed directly. But it has a few\n helper functions that derived classes can use to help perform their calculations. See\n the derived classes for more details:\n\n - `NNNCorrelation` handles count-count-count correlation functions\n - `KKKCorrelation` handles kappa-kappa-kappa correlation functions\n - `GGGCorrelation` handles gamma-gamma-gamma correlation functions\n\n Three-point correlations are a bit more complicated than two-point, since the data need\n to be binned in triangles, not just the separation between two points. We characterize the\n triangles according to the following three parameters based on the three side lenghts\n of the triangle with d1 >= d2 >= d3.\n\n .. math::\n r &= d2 \\\\\\\\\n u &= \\\\frac{d3}{d2} \\\\\\\\\n v &= \\\\pm \\\\frac{(d1 - d2)}{d3} \\\\\\\\\n\n The orientation of the triangle is specified by the sign of v.\n Positive v triangles have the three sides d1,d2,d3 in counter-clockwise orientation.\n Negative v triangles have the three sides d1,d2,d3 in clockwise orientation.\n\n .. note::\n We always bin the same way for positive and negative v values, and the binning\n specification for v should just be for the positive values. E.g. if you specify\n min_v=0.2, max_v=0.6, then TreeCorr will also accumulate triangles with\n -0.6 < v < -0.2 in addition to those with 0.2 < v < 0.6.\n\n The constructor for all derived classes take a config dict as the first argument,\n since this is often how we keep track of parameters, but if you don't want to\n use one or if you want to change some parameters from what are in a config dict,\n then you can use normal kwargs, which take precedence over anything in the config dict.\n\n There are only two implemented definitions for the distance between two points for\n three-point corretions:\n\n - 'Euclidean' = straight line Euclidean distance between two points. For spherical\n coordinates (ra,dec without r), this is the chord distance between points on the\n unit sphere.\n - 'Arc' = the true great circle distance for spherical coordinates.\n - 'Periodic' = Like Euclidean, but with periodic boundaries. Note that the triangles\n for three-point correlations can become ambiguous if d1 > period/2, which means\n the maximum d2 (max_sep) should be less than period/4. This is not enforced.\n\n Similarly, we have so far only implemented one binning type for three-point correlations.\n\n - 'LogRUV' - The bin steps will be uniform in log(r) from log(min_sep) .. log(max_sep).\n The u and v values are binned linearly from min_u .. max_u and min_v .. max_v.\n\n\n Parameters:\n config (dict): A configuration dict that can be used to pass in the below kwargs if\n desired. This dict is allowed to have addition entries in addition\n to those listed below, which are ignored here. (default: None)\n logger: If desired, a logger object for logging. (default: None, in which case\n one will be built according to the config dict's verbose level.)\n\n Keyword Arguments:\n\n nbins (int): How many bins to use. (Exactly three of nbins, bin_size, min_sep,\n max_sep are required. If nbins is not given, it will be calculated from\n the values of the other three, rounding up to the next highest integer.\n In this case, bin_size will be readjusted to account for this rounding\n up.)\n bin_size (float): The width of the bins in log(separation). (Exactly three of nbins,\n bin_size, min_sep, max_sep are required. If bin_size is not given, it\n will be calculated from the values of the other three.)\n min_sep (float): The minimum separation in units of sep_units, if relevant. (Exactly\n three of nbins, bin_size, min_sep, max_sep are required. If min_sep is\n not given, it will be calculated from the values of the other three.)\n max_sep (float): The maximum separation in units of sep_units, if relevant. (Exactly\n three of nbins, bin_size, min_sep, max_sep are required. If max_sep is\n not given, it will be calculated from the values of the other three.\n\n sep_units (str): The units to use for the separation values, given as a string. This\n includes both min_sep and max_sep above, as well as the units of the\n output distance values. Valid options are arcsec, arcmin, degrees,\n hours, radians. (default: radians if angular units make sense, but for\n 3-d or flat 2-d positions, the default will just match the units of\n x,y[,z] coordinates)\n bin_slop (float): How much slop to allow in the placement of pairs in the bins.\n If bin_slop = 1, then the bin into which a particular pair is placed\n may be incorrect by at most 1.0 bin widths. (default: None, which\n means to use a bin_slop that gives a maximum error of 10% on any bin,\n which has been found to yield good results for most application.\n\n nubins (int): Analogous to nbins for the u values. (The default is to calculate from\n ubin_size = binsize, min_u = 0, max_u = 1, but this can be overridden\n by specifying up to 3 of these four parametes.)\n ubin_size (float): Analogous to bin_size for the u values. (default: bin_size)\n min_u (float): Analogous to min_sep for the u values. (default: 0)\n max_u (float): Analogous to max_sep for the u values. (default: 1)\n\n nvbins (int): Analogous to nbins for the positive v values. (The default is to\n calculate from vbin_size = binsize, min_v = 0, max_v = 1, but this can\n be overridden by specifying up to 3 of these four parametes.)\n vbin_size (float): Analogous to bin_size for the v values. (default: bin_size)\n min_v (float): Analogous to min_sep for the positive v values. (default: 0)\n max_v (float): Analogous to max_sep for the positive v values. (default: 1)\n\n brute (bool): Whether to use the \"brute force\" algorithm. (default: False) Options\n are:\n\n - False (the default): Stop at non-leaf cells whenever the error in\n the separation is compatible with the given bin_slop.\n - True: Go to the leaves for both catalogs.\n - 1: Always go to the leaves for cat1, but stop at non-leaf cells of\n cat2 when the error is compatible with the given bin_slop.\n - 2: Always go to the leaves for cat2, but stop at non-leaf cells of\n cat1 when the error is compatible with the given bin_slop.\n\n verbose (int): If no logger is provided, this will optionally specify a logging level\n to use:\n\n - 0 means no logging output\n - 1 means to output warnings only (default)\n - 2 means to output various progress information\n - 3 means to output extensive debugging information\n\n log_file (str): If no logger is provided, this will specify a file to write the logging\n output. (default: None; i.e. output to standard output)\n output_dots (boo): Whether to output progress dots during the calcualtion of the\n correlation function. (default: False unless verbose is given and >= 2,\n in which case True)\n\n split_method (str): How to split the cells in the tree when building the tree structure.\n Options are:\n\n - mean = Use the arithmetic mean of the coordinate being split.\n (default)\n - median = Use the median of the coordinate being split.\n - middle = Use the middle of the range; i.e. the average of the minimum\n and maximum value.\n - random: Use a random point somewhere in the middle two quartiles of\n the range.\n\n min_top (int): The minimum number of top layers to use when setting up the field.\n (default: 3)\n max_top (int): The maximum number of top layers to use when setting up the field.\n The top-level cells are where each calculation job starts. There will\n typically be of order 2^max_top top-level cells. (default: 10)\n precision (int): The precision to use for the output values. This specifies how many\n digits to write. (default: 4)\n\n metric (str): Which metric to use for distance measurements. Options are listed\n above. (default: 'Euclidean')\n bin_type (str): What type of binning should be used. Options are listed above.\n (default: 'LogRUV')\n min_rpar (float): Not currently supported for 3 point correlation. (default: None)\n max_rpar (float): Not currently supported for 3 point correlation. (default: None)\n period (float): For the 'Periodic' metric, the period to use in all directions.\n (default: None)\n xperiod (float): For the 'Periodic' metric, the period to use in the x direction.\n (default: period)\n yperiod (float): For the 'Periodic' metric, the period to use in the y direction.\n (default: period)\n zperiod (float): For the 'Periodic' metric, the period to use in the z direction.\n (default: period)\n\n num_threads (int): How many OpenMP threads to use during the calculation.\n (default: use the number of cpu cores; this value can also be given in\n the constructor in the config dict.) Note that this won't work if the\n system's C compiler cannot use OptnMP (e.g. clang prior to version 3.7.)\n \"\"\"\n _valid_params = {\n 'nbins' : (int, False, None, None,\n 'The number of output bins to use for sep dimension.'),\n 'bin_size' : (float, False, None, None,\n 'The size of the output bins in log(sep).'),\n 'min_sep' : (float, False, None, None,\n 'The minimum separation to include in the output.'),\n 'max_sep' : (float, False, None, None,\n 'The maximum separation to include in the output.'),\n 'sep_units' : (str, False, None, coord.AngleUnit.valid_names,\n 'The units to use for min_sep and max_sep. Also the units of the output distances'),\n 'bin_slop' : (float, False, None, None,\n 'The fraction of a bin width by which it is ok to let the pairs miss the correct bin.',\n 'The default is to use 1 if bin_size <= 0.1, or 0.1/bin_size if bin_size > 0.1.'),\n 'nubins' : (int, False, None, None,\n 'The number of output bins to use for u dimension.'),\n 'ubin_size' : (float, False, None, None,\n 'The size of the output bins in u.'),\n 'min_u' : (float, False, None, None,\n 'The minimum u to include in the output.'),\n 'max_u' : (float, False, None, None,\n 'The maximum u to include in the output.'),\n 'nvbins' : (int, False, None, None,\n 'The number of output bins to use for positive v values.'),\n 'vbin_size' : (float, False, None, None,\n 'The size of the output bins in v.'),\n 'min_v' : (float, False, None, None,\n 'The minimum |v| to include in the output.'),\n 'max_v' : (float, False, None, None,\n 'The maximum |v| to include in the output.'),\n 'brute' : (bool, False, False, [False, True],\n 'Whether to use brute-force algorithm'),\n 'verbose' : (int, False, 1, [0, 1, 2, 3],\n 'How verbose the code should be during processing. ',\n '0 = Errors Only, 1 = Warnings, 2 = Progress, 3 = Debugging'),\n 'log_file' : (str, False, None, None,\n 'If desired, an output file for the logging output.',\n 'The default is to write the output to stdout.'),\n 'output_dots' : (bool, False, None, None,\n 'Whether to output dots to the stdout during the C++-level computation.',\n 'The default is True if verbose >= 2 and there is no log_file. Else False.'),\n 'split_method' : (str, False, 'mean', ['mean', 'median', 'middle', 'random'],\n 'Which method to use for splitting cells.'),\n 'min_top' : (int, False, 3, None,\n 'The minimum number of top layers to use when setting up the field.'),\n 'max_top' : (int, False, 10, None,\n 'The maximum number of top layers to use when setting up the field.'),\n 'precision' : (int, False, 4, None,\n 'The number of digits after the decimal in the output.'),\n 'num_threads' : (int, False, None, None,\n 'How many threads should be used. num_threads <= 0 means auto based on num cores.'),\n 'metric': (str, False, 'Euclidean', ['Euclidean', 'Arc', 'Periodic'],\n 'Which metric to use for the distance measurements'),\n 'bin_type': (str, False, 'LogRUV', ['LogRUV'],\n 'Which type of binning should be used'),\n 'min_rpar': (float, False, None, None,\n 'The minimum difference in Rparallel for pairs to include'),\n 'max_rpar': (float, False, None, None,\n 'The maximum difference in Rparallel for pairs to include'),\n 'period': (float, False, None, None,\n 'The period to use for all directions for the Periodic metric'),\n 'xperiod': (float, False, None, None,\n 'The period to use for the x direction for the Periodic metric'),\n 'yperiod': (float, False, None, None,\n 'The period to use for the y direction for the Periodic metric'),\n 'zperiod': (float, False, None, None,\n 'The period to use for the z direction for the Periodic metric'),\n }\n\n def __init__(self, config=None, logger=None, **kwargs):\n self.config = treecorr.config.merge_config(config,kwargs,BinnedCorr3._valid_params)\n if logger is None:\n self.logger = treecorr.config.setup_logger(\n treecorr.config.get(self.config,'verbose',int,1),\n self.config.get('log_file',None))\n else:\n self.logger = logger\n\n if 'output_dots' in self.config:\n self.output_dots = treecorr.config.get(self.config,'output_dots',bool)\n else:\n self.output_dots = treecorr.config.get(self.config,'verbose',int,1) >= 2\n\n self.bin_type = self.config.get('bin_type', None)\n self._bintype = treecorr._lib.Log\n\n self.sep_units = self.config.get('sep_units','')\n self._sep_units = treecorr.config.get(self.config,'sep_units',str,'radians')\n self._log_sep_units = math.log(self._sep_units)\n if 'nbins' not in self.config:\n if 'max_sep' not in self.config:\n raise TypeError(\"Missing required parameter max_sep\")\n if 'min_sep' not in self.config:\n raise TypeError(\"Missing required parameter min_sep\")\n if 'bin_size' not in self.config:\n raise TypeError(\"Missing required parameter bin_size\")\n self.min_sep = float(self.config['min_sep'])\n self.max_sep = float(self.config['max_sep'])\n if self.min_sep >= self.max_sep:\n raise ValueError(\"max_sep must be larger than min_sep\")\n bin_size = float(self.config['bin_size'])\n self.nbins = int(math.ceil(math.log(self.max_sep/self.min_sep)/bin_size))\n # Update self.bin_size given this value of nbins\n self.bin_size = math.log(self.max_sep/self.min_sep)/self.nbins\n # Note in this case, bin_size is saved as the nominal bin_size from the config\n # file, and self.bin_size is the one for the radial bins. We'll use the nominal\n # bin_size as the default bin_size for u and v below.\n elif 'bin_size' not in self.config:\n if 'max_sep' not in self.config:\n raise TypeError(\"Missing required parameter max_sep\")\n if 'min_sep' not in self.config:\n raise TypeError(\"Missing required parameter min_sep\")\n self.min_sep = float(self.config['min_sep'])\n self.max_sep = float(self.config['max_sep'])\n if self.min_sep >= self.max_sep:\n raise ValueError(\"max_sep must be larger than min_sep\")\n self.nbins = int(self.config['nbins'])\n bin_size = self.bin_size = math.log(self.max_sep/self.min_sep)/self.nbins\n elif 'max_sep' not in self.config:\n if 'min_sep' not in self.config:\n raise TypeError(\"Missing required parameter min_sep\")\n self.min_sep = float(self.config['min_sep'])\n self.nbins = int(self.config['nbins'])\n bin_size = self.bin_size = float(self.config['bin_size'])\n self.max_sep = math.exp(self.nbins*bin_size)*self.min_sep\n else:\n if 'min_sep' in self.config:\n raise TypeError(\"Only 3 of min_sep, max_sep, bin_size, nbins are allowed.\")\n self.max_sep = float(self.config['max_sep'])\n self.nbins = int(self.config['nbins'])\n bin_size = self.bin_size = float(self.config['bin_size'])\n self.min_sep = self.max_sep*math.exp(-self.nbins*bin_size)\n if self.sep_units == '':\n self.logger.info(\"r: nbins = %d, min,max sep = %g..%g, bin_size = %g\",\n self.nbins,self.min_sep,self.max_sep,self.bin_size)\n else:\n self.logger.info(\"r: nbins = %d, min,max sep = %g..%g %s, bin_size = %g\",\n self.nbins,self.min_sep/self._sep_units,self.max_sep/self._sep_units,\n self.sep_units,self.bin_size)\n # The underscore-prefixed names are in natural units (radians for angles)\n self._min_sep = self.min_sep * self._sep_units\n self._max_sep = self.max_sep * self._sep_units\n self._bin_size = self.bin_size # There is not Linear, but if I add it, need to apply\n # units to _bin_size in that case as well.\n\n self.min_u = float(self.config.get('min_u', 0.))\n self.max_u = float(self.config.get('max_u', 1.))\n if self.min_u >= self.max_u:\n raise ValueError(\"max_u must be larger than min_u\")\n if self.min_u < 0. or self.max_u > 1.:\n raise ValueError(\"Invalid range for u: %f - %f\"%(self.min_u, self.max_u))\n self.ubin_size = float(self.config.get('ubin_size', bin_size))\n if 'nubins' not in self.config:\n self.nubins = int(math.ceil((self.max_u-self.min_u-1.e-10)/self.ubin_size))\n elif 'max_u' in self.config and 'min_u' in self.config and 'ubin_size' in self.config:\n raise TypeError(\"Only 3 of min_u, max_u, ubin_size, nubins are allowed.\")\n else:\n self.nubins = self.config['nubins']\n # Allow min or max u to be implicit from nubins and ubin_size\n if 'ubin_size' in self.config:\n if 'min_u' not in self.config:\n self.min_u = max(self.max_u - self.nubins * self.ubin_size, 0.)\n if 'max_u' not in self.config:\n self.max_u = min(self.min_u + self.nubins * self.ubin_size, 1.)\n # Adjust ubin_size given the other values\n self.ubin_size = (self.max_u-self.min_u)/self.nubins\n self.logger.info(\"u: nbins = %d, min,max = %g..%g, bin_size = %g\",\n self.nubins,self.min_u,self.max_u,self.ubin_size)\n\n self.min_v = float(self.config.get('min_v', 0.))\n self.max_v = float(self.config.get('max_v', 1.))\n if self.min_v >= self.max_v:\n raise ValueError(\"max_v must be larger than min_v\")\n if self.min_v < 0 or self.max_v > 1.:\n raise ValueError(\"Invalid range for |v|: %f - %f\"%(self.min_v, self.max_v))\n self.vbin_size = float(self.config.get('vbin_size', bin_size))\n if 'nvbins' not in self.config:\n self.nvbins = int(math.ceil((self.max_v-self.min_v-1.e-10)/self.vbin_size))\n elif 'max_v' in self.config and 'min_v' in self.config and 'vbin_size' in self.config:\n raise TypeError(\"Only 3 of min_v, max_v, vbin_size, nvbins are allowed.\")\n else:\n self.nvbins = self.config['nvbins']\n # Allow min or max v to be implicit from nvbins and vbin_size\n if 'vbin_size' in self.config:\n if 'max_v' not in self.config:\n self.max_v = min(self.min_v + self.nvbins * self.vbin_size, 1.)\n else: # min_v not in config\n self.min_v = max(self.max_v - self.nvbins * self.vbin_size, -1.)\n # Adjust vbin_size given the other values\n self.vbin_size = (self.max_v-self.min_v)/self.nvbins\n self.logger.info(\"v: nbins = %d, min,max = %g..%g, bin_size = %g\",\n self.nvbins,self.min_v,self.max_v,self.vbin_size)\n\n self.split_method = self.config.get('split_method','mean')\n self.logger.debug(\"Using split_method = %s\",self.split_method)\n\n self.min_top = treecorr.config.get(self.config,'min_top',int,3)\n self.max_top = treecorr.config.get(self.config,'max_top',int,10)\n\n self.bin_slop = treecorr.config.get(self.config,'bin_slop',float,-1.0)\n if self.bin_slop < 0.0:\n if self.bin_size <= 0.1:\n self.bin_slop = 1.0\n self.b = self.bin_size\n else:\n self.bin_slop = 0.1/self.bin_size # The stored bin_slop corresponds to lnr bins.\n self.b = 0.1\n if self.ubin_size <= 0.1:\n self.bu = self.ubin_size\n else:\n self.bu = 0.1\n if self.vbin_size <= 0.1:\n self.bv = self.vbin_size\n else:\n self.bv = 0.1\n else:\n self.b = self.bin_size * self.bin_slop\n self.bu = self.ubin_size * self.bin_slop\n self.bv = self.vbin_size * self.bin_slop\n\n if self.b > 0.100001: # Add some numerical slop\n self.logger.warning(\n \"Using bin_slop = %g, bin_size = %g\\n\"%(self.bin_slop,self.bin_size)+\n \"The b parameter is bin_slop * bin_size = %g\"%(self.b)+\n \" bu = %g, bv = %g\\n\"%(self.bu,self.bv)+\n \"It is generally recommended to use b <= 0.1 for most applications.\\n\"+\n \"Larger values of this b parameter may result in significant inaccuracies.\")\n else:\n self.logger.debug(\"Using bin_slop = %g, b = %g, bu = %g, bv = %g\",\n self.bin_slop,self.b,self.bu,self.bv)\n\n # This makes nbins evenly spaced entries in log(r) starting with 0 with step bin_size\n self.logr1d = np.linspace(start=0, stop=self.nbins*self.bin_size,\n num=self.nbins, endpoint=False)\n # Offset by the position of the center of the first bin.\n self.logr1d += math.log(self.min_sep) + 0.5*self.bin_size\n\n self.u1d = np.linspace(start=0, stop=self.nubins*self.ubin_size,\n num=self.nubins, endpoint=False)\n self.u1d += self.min_u + 0.5*self.ubin_size\n\n self.v1d = np.linspace(start=0, stop=self.nvbins*self.vbin_size,\n num=self.nvbins, endpoint=False)\n self.v1d += self.min_v + 0.5*self.vbin_size\n self.v1d = np.concatenate([-self.v1d[::-1],self.v1d])\n\n shape = (self.nbins, self.nubins, 2*self.nvbins)\n self.logr = np.tile(self.logr1d[:, np.newaxis, np.newaxis],\n (1, self.nubins, 2*self.nvbins))\n self.u = np.tile(self.u1d[np.newaxis, :, np.newaxis],\n (self.nbins, 1, 2*self.nvbins))\n self.v = np.tile(self.v1d[np.newaxis, np.newaxis, :],\n (self.nbins, self.nubins, 1))\n self.rnom = np.exp(self.logr)\n self.rnom1d = np.exp(self.logr1d)\n self.brute = treecorr.config.get(self.config,'brute',bool,False)\n if self.brute:\n self.logger.info(\"Doing brute force calculation.\",)\n self.coords = None\n self.metric = None\n self.min_rpar = treecorr.config.get(self.config,'min_rpar',float,-sys.float_info.max)\n self.max_rpar = treecorr.config.get(self.config,'max_rpar',float,sys.float_info.max)\n period = treecorr.config.get(self.config,'period',float,0)\n self.xperiod = treecorr.config.get(self.config,'xperiod',float,period)\n self.yperiod = treecorr.config.get(self.config,'yperiod',float,period)\n self.zperiod = treecorr.config.get(self.config,'zperiod',float,period)\n\n def _process_all_auto(self, cat1, metric, num_threads):\n # I'm not sure which of these is more intuitive, but both are correct...\n if True:\n for c1 in cat1:\n self.process_auto(c1, metric, num_threads)\n for c2 in cat1:\n if c2 is not c1:\n self.process_cross(c1,c1,c2, metric, num_threads)\n self.process_cross(c1,c2,c1, metric, num_threads)\n self.process_cross(c2,c1,c1, metric, num_threads)\n for c3 in cat1:\n if c3 is not c1 and c3 is not c2:\n self.process_cross(c1,c2,c3, metric, num_threads)\n else: # pragma: no cover\n for i,c1 in enumerate(cat1):\n self.process_auto(c1)\n for j,c2 in enumerate(cat1[i+1:]):\n self.process_cross(c1,c1,c2, metric, num_threads)\n self.process_cross(c1,c2,c1, metric, num_threads)\n self.process_cross(c2,c1,c1, metric, num_threads)\n self.process_cross(c1,c2,c2, metric, num_threads)\n self.process_cross(c2,c1,c2, metric, num_threads)\n self.process_cross(c2,c2,c1, metric, num_threads)\n for c3 in cat1[i+j+1:]:\n self.process_cross(c1,c2,c3, metric, num_threads)\n self.process_cross(c1,c3,c2, metric, num_threads)\n self.process_cross(c2,c1,c3, metric, num_threads)\n self.process_cross(c2,c3,c1, metric, num_threads)\n self.process_cross(c3,c1,c2, metric, num_threads)\n self.process_cross(c3,c2,c1, metric, num_threads)\n\n # These are not actually implemented yet.\n def _process_all_cross21(self, cat1, cat2, metric, num_threads): # pragma: no cover\n for c1 in cat1:\n for c2 in cat2:\n self.process_cross(c1,c1,c2, metric, num_threads)\n for c3 in cat1:\n if c3 is not c1:\n self.process_cross(c1,c3,c2, metric, num_threads)\n self.process_cross(c3,c1,c2, metric, num_threads)\n\n def _process_all_cross(self, cat1, cat2, cat3, metric, num_threads):\n for c1 in cat1:\n for c2 in cat2:\n for c3 in cat3:\n self.process_cross(c1,c2,c3, metric, num_threads)\n\n def _set_num_threads(self, num_threads):\n if num_threads is None:\n num_threads = self.config.get('num_threads',None)\n if num_threads is None:\n self.logger.debug('Set num_threads automatically from ncpu')\n else:\n self.logger.debug('Set num_threads = %d',num_threads)\n treecorr.set_omp_threads(num_threads, self.logger)\n\n def _set_metric(self, metric, coords1, coords2=None, coords3=None):\n if metric is None:\n metric = treecorr.config.get(self.config,'metric',str,'Euclidean')\n coords, metric = treecorr.util.parse_metric(metric, coords1, coords2, coords3)\n if self.coords != None or self.metric != None:\n if coords != self.coords:\n self.logger.warning(\"Detected a change in catalog coordinate systems. \"+\n \"This probably doesn't make sense!\")\n if metric != self.metric:\n self.logger.warning(\"Detected a change in metric. \"+\n \"This probably doesn't make sense!\")\n if metric == 'Periodic':\n if self.xperiod == 0 or self.yperiod == 0 or (coords=='3d' and self.zperiod == 0):\n raise ValueError(\"Periodic metric requires setting the period to use.\")\n else:\n if self.xperiod != 0 or self.yperiod != 0 or self.zperiod != 0:\n raise ValueError(\"period options are not valid for %s metric.\"%metric)\n self.coords = coords\n self.metric = metric\n self._coords = treecorr.util.coord_enum(coords)\n self._metric = treecorr.util.metric_enum(metric)\n\n def _apply_units(self, mask):\n if self.coords == 'spherical' and self.metric == 'Euclidean':\n # Then our distances are all angles. Convert from the chord distance to a real angle.\n # L = 2 sin(theta/2)\n self.meand1[mask] = 2. * np.arcsin(self.meand1[mask]/2.)\n self.meanlogd1[mask] = np.log(2.*np.arcsin(np.exp(self.meanlogd1[mask])/2.))\n self.meand2[mask] = 2. * np.arcsin(self.meand2[mask]/2.)\n self.meanlogd2[mask] = np.log(2.*np.arcsin(np.exp(self.meanlogd2[mask])/2.))\n self.meand3[mask] = 2. * np.arcsin(self.meand3[mask]/2.)\n self.meanlogd3[mask] = np.log(2.*np.arcsin(np.exp(self.meanlogd3[mask])/2.))\n\n self.meand1[mask] /= self._sep_units\n self.meanlogd1[mask] -= self._log_sep_units\n self.meand2[mask] /= self._sep_units\n self.meanlogd2[mask] -= self._log_sep_units\n self.meand3[mask] /= self._sep_units\n self.meanlogd3[mask] -= self._log_sep_units\n\n def _get_minmax_size(self):\n if self.metric == 'Euclidean':\n # The minimum separation we care about is that of the smallest size, which is\n # min_sep * min_u. Do the same calculation as for 2pt to get to min_size.\n b1 = min(self.b, self.bu, self.bv)\n min_size = self._min_sep * self.min_u * b1 / (2.+3.*b1)\n\n # This time, the maximum size is d1 * b. d1 can be as high as 2*max_sep.\n b2 = max(self.b, self.bu, self.bv)\n max_size = 2. * self._max_sep * b2\n return min_size, max_size\n else:\n return 0., 0.\n\n", "# Copyright (c) 2003-2019 by Mike Jarvis\n#\n# TreeCorr is free software: redistribution and use in source and binary forms,\n# with or without modification, are permitted provided that the following\n# conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, this\n# list of conditions, and the disclaimer given in the accompanying LICENSE\n# file.\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions, and the disclaimer given in the documentation\n# and/or other materials provided with the distribution.\n\n\"\"\"\n.. module:: util\n\"\"\"\n\nimport treecorr\nimport numpy as np\nimport os\nimport warnings\nimport coord\n\ndef ensure_dir(target):\n d = os.path.dirname(target)\n if d != '':\n if not os.path.exists(d):\n os.makedirs(d)\n\ndef gen_write(file_name, col_names, columns, params=None, precision=4, file_type=None, logger=None):\n \"\"\"Write some columns to an output file with the given column names.\n\n We do this basic functionality a lot, so put the code to do it in one place.\n\n :param file_name: The name of the file to write to.\n :param col_names: A list of columns names for the given columns.\n :param columns: A list of numpy arrays with the data to write.\n :param params: A dict of extra parameters to write at the top of the output file (for\n ASCII output) or in the header (for FITS output). (default: None)\n :param precision: Output precision for ASCII. (default: 4)\n :param file_type: Which kind of file to write to. (default: determine from the file_name\n extension)\n :param logger: If desired, a logger object for logging. (default: None)\n \"\"\"\n if len(col_names) != len(columns):\n raise ValueError(\"col_names and columns are not the same length.\")\n if len(columns) == 0:\n raise ValueError(\"len(columns) == 0\")\n for col in columns[1:]:\n if col.shape != columns[0].shape:\n raise ValueError(\"columns are not all the same shape\")\n columns = [ col.flatten() for col in columns ]\n\n ensure_dir(file_name)\n\n # Figure out which file type the catalog is\n if file_type is None:\n import os\n name, ext = os.path.splitext(file_name)\n if ext.lower().startswith('.fit'):\n file_type = 'FITS'\n else:\n file_type = 'ASCII'\n if logger: # pragma: no branch (We always provide a logger.)\n logger.info(\"file_type assumed to be %s from the file name.\",file_type)\n\n if file_type.upper() == 'FITS':\n try:\n import fitsio\n except ImportError:\n logger.error(\"Unable to import fitsio. Cannot write to %s\"%file_name)\n raise\n gen_write_fits(file_name, col_names, columns, params)\n elif file_type.upper() == 'ASCII':\n gen_write_ascii(file_name, col_names, columns, params, precision=precision)\n else:\n raise ValueError(\"Invalid file_type %s\"%file_type)\n\n\ndef gen_write_ascii(file_name, col_names, columns, params, precision=4):\n \"\"\"Write some columns to an output ASCII file with the given column names.\n\n :param file_name: The name of the file to write to.\n :param col_names: A list of columns names for the given columns. These will be written\n in a header comment line at the top of the output file.\n :param columns: A list of numpy arrays with the data to write.\n :param params: A dict of extra parameters to write at the top of the output file.\n :param precision: Output precision for ASCII. (default: 4)\n \"\"\"\n ncol = len(col_names)\n data = np.empty( (len(columns[0]), ncol) )\n for i,col in enumerate(columns):\n data[:,i] = col\n\n width = precision+8\n # Note: python 2.6 needs the numbers, so can't just do \"{:^%d}\"*ncol\n # Also, I have the first one be 1 shorter to allow space for the initial #.\n header_form = \"{0:^%d}\"%(width-1)\n for i in range(1,ncol):\n header_form += \" {%d:^%d}\"%(i,width)\n header = header_form.format(*col_names)\n fmt = '%%%d.%de'%(width,precision)\n ensure_dir(file_name)\n with open(file_name, 'wb') as fid:\n if params is not None:\n s = '## %r\\n'%(params)\n fid.write(s.encode())\n h = '#' + header + '\\n'\n fid.write(h.encode())\n np.savetxt(fid, data, fmt=fmt)\n\n\ndef gen_write_fits(file_name, col_names, columns, params):\n \"\"\"Write some columns to an output FITS file with the given column names.\n\n :param file_name: The name of the file to write to.\n :param col_names: A list of columns names for the given columns.\n :param columns: A list of numpy arrays with the data to write.\n :param params: A dict of extra parameters to write in the FITS header.\n \"\"\"\n import fitsio\n ensure_dir(file_name)\n data = np.empty(len(columns[0]), dtype=[ (name,'f8') for name in col_names ])\n for (name, col) in zip(col_names, columns):\n data[name] = col\n fitsio.write(file_name, data, header=params, clobber=True)\n\n\ndef gen_read(file_name, file_type=None, logger=None):\n \"\"\"Read some columns from an input file.\n\n We do this basic functionality a lot, so put the code to do it in one place.\n Note that the input file is expected to have been written by TreeCorr using the\n gen_write function, so we don't have a lot of flexibility in the input structure.\n\n :param file_name: The name of the file to read.\n :param file_type: Which kind of file to read. (default: determine from the file_name\n extension)\n :param logger: If desired, a logger object for logging. (default: None)\n\n :returns: (data, params), a numpy ndarray with named columns, and a dict of extra parameters.\n \"\"\"\n # Figure out which file type the catalog is\n if file_type is None:\n import os\n name, ext = os.path.splitext(file_name)\n if ext.lower().startswith('.fit'):\n file_type = 'FITS'\n else:\n file_type = 'ASCII'\n if logger: # pragma: no branch (We always provide a logger.)\n logger.info(\"file_type assumed to be %s from the file name.\",file_type)\n\n if file_type.upper() == 'FITS':\n try:\n import fitsio\n except ImportError:\n logger.error(\"Unable to import fitsio. Cannot read %s\"%file_name)\n raise\n data = fitsio.read(file_name)\n params = fitsio.read_header(file_name, 1)\n elif file_type.upper() == 'ASCII':\n with open(file_name) as fid:\n header = fid.readline()\n params = {}\n skip = 0\n if header[1] == '#': # pragma: no branch (All our files have this.)\n assert header[0] == '#'\n params = eval(header[2:].strip())\n header = fid.readline()\n skip = 1\n data = np.genfromtxt(file_name, names=True, skip_header=skip)\n else:\n raise ValueError(\"Invalid file_type %s\"%file_type)\n\n return data, params\n\n\nclass LRU_Cache:\n \"\"\" Simplified Least Recently Used Cache.\n Mostly stolen from http://code.activestate.com/recipes/577970-simplified-lru-cache/,\n but added a method for dynamic resizing. The least recently used cached item is\n overwritten on a cache miss.\n\n :param user_function: A python function to cache.\n :param maxsize: Maximum number of inputs to cache. [Default: 1024]\n\n Usage\n -----\n >>> def slow_function(*args) # A slow-to-evaluate python function\n >>> ...\n >>>\n >>> v1 = slow_function(*k1) # Calling function is slow\n >>> v1 = slow_function(*k1) # Calling again with same args is still slow\n >>> cache = galsim.utilities.LRU_Cache(slow_function)\n >>> v1 = cache(*k1) # Returns slow_function(*k1), slowly the first time\n >>> v1 = cache(*k1) # Returns slow_function(*k1) again, but fast this time.\n\n Methods\n -------\n >>> cache.resize(maxsize) # Resize the cache, either upwards or downwards. Upwards resizing\n # is non-destructive. Downwards resizing will remove the least\n # recently used items first.\n \"\"\"\n def __init__(self, user_function, maxsize=1024):\n # Link layout: [PREV, NEXT, KEY, RESULT]\n self.root = [None, None, None, None]\n self.user_function = user_function\n self.cache = {}\n\n last = self.root\n for i in range(maxsize):\n key = object()\n self.cache[key] = last[1] = last = [last, self.root, key, None]\n self.root[0] = last\n self.count = 0\n\n def __call__(self, *key, **kwargs):\n link = self.cache.get(key)\n if link is not None:\n # Cache hit: move link to last position\n link_prev, link_next, _, result = link\n link_prev[1] = link_next\n link_next[0] = link_prev\n last = self.root[0]\n last[1] = self.root[0] = link\n link[0] = last\n link[1] = self.root\n return result\n # Cache miss: evaluate and insert new key/value at root, then increment root\n # so that just-evaluated value is in last position.\n result = self.user_function(*key, **kwargs)\n self.root[2] = key\n self.root[3] = result\n oldroot = self.root\n self.root = self.root[1]\n self.root[2], oldkey = None, self.root[2]\n self.root[3], oldvalue = None, self.root[3]\n self.cache[key] = oldroot\n del self.cache[oldkey]\n if self.count < self.size: self.count += 1\n return result\n\n def values(self):\n \"\"\"Lists all items stored in the cache\"\"\"\n return list([v[3] for v in self.cache.values() if v[3] is not None])\n\n @property\n def last_value(self):\n \"\"\"Return the most recently used value\"\"\"\n return self.root[0][3]\n\n def resize(self, maxsize):\n \"\"\" Resize the cache. Increasing the size of the cache is non-destructive, i.e.,\n previously cached inputs remain in the cache. Decreasing the size of the cache will\n necessarily remove items from the cache if the cache is already filled. Items are removed\n in least recently used order.\n\n :param maxsize: The new maximum number of inputs to cache.\n \"\"\"\n oldsize = len(self.cache)\n if maxsize == oldsize:\n return\n else:\n if maxsize < 0:\n raise ValueError(\"Invalid maxsize\")\n elif maxsize < oldsize:\n for i in range(oldsize - maxsize):\n # Delete root.next\n current_next_link = self.root[1]\n new_next_link = self.root[1] = self.root[1][1]\n new_next_link[0] = self.root\n del self.cache[current_next_link[2]]\n self.count = min(self.count, maxsize)\n else: # maxsize > oldsize:\n for i in range(maxsize - oldsize):\n # Insert between root and root.next\n key = object()\n self.cache[key] = link = [self.root, self.root[1], key, None]\n self.root[1][0] = link\n self.root[1] = link\n\n def clear(self):\n \"\"\" Clear all items from the cache.\n \"\"\"\n maxsize = len(self.cache)\n self.cache.clear()\n last = self.root\n for i in range(maxsize):\n last[3] = None # Sever pointer to any existing result.\n key = object()\n self.cache[key] = last[1] = last = [last, self.root, key, None]\n self.root[0] = last\n self.count = 0\n\n @property\n def size(self):\n return len(self.cache)\n\n\ndef double_ptr(x):\n \"\"\"\n Cast x as a double* to pass to library C functions\n\n :param x: A numpy array assumed to have dtype = float.\n\n :returns: A version of the array that can be passed to cffi C functions.\n \"\"\"\n if x is None:\n return treecorr._ffi.cast('double*', 0)\n else:\n # This fails if x is read_only\n #return treecorr._ffi.cast('double*', treecorr._ffi.from_buffer(x))\n # This works, presumably by ignoring the numpy read_only flag. Although, I think it's ok.\n return treecorr._ffi.cast('double*', x.ctypes.data)\n\ndef long_ptr(x):\n \"\"\"\n Cast x as a long* to pass to library C functions\n\n :param x: A numpy array assumed to have dtype = int.\n\n :returns: A version of the array that can be passed to cffi C functions.\n \"\"\"\n if x is None: # pragma: no cover (I don't ever have x=None for this one.)\n return treecorr._ffi.cast('long*', 0)\n else:\n return treecorr._ffi.cast('long*', x.ctypes.data)\n\ndef parse_metric(metric, coords, coords2=None, coords3=None):\n \"\"\"\n Convert a string metric into the corresponding enum to pass to the C code.\n \"\"\"\n if coords2 is None:\n auto = True\n else:\n auto = False\n # Special Rlens doesn't care about the distance to the sources, so spherical is fine\n # for cat2, cat3 in that case.\n if metric == 'Rlens':\n if coords2 == 'spherical': coords2 = '3d'\n if coords3 == 'spherical': coords3 = '3d'\n\n if metric == 'Arc':\n # If all coords are 3d, then leave it 3d, but if any are spherical,\n # then convert to spherical.\n if all([c in [None, '3d'] for c in [coords, coords2, coords3]]):\n # Leave coords as '3d'\n pass\n elif any([c not in [None, 'spherical', '3d'] for c in [coords, coords2, coords3]]):\n raise ValueError(\"Arc metric is only valid for catalogs with spherical positions.\")\n elif any([c == 'spherical' for c in [coords, coords2, coords3]]):\n # Switch to spherical\n coords = 'spherical'\n else: # pragma: no cover\n # This is impossible now, but here in case we add additional coordinates.\n raise ValueError(\"Cannot correlate catalogs with different coordinate systems.\")\n else:\n if ( (coords2 != coords) or (coords3 is not None and coords3 != coords) ):\n raise ValueError(\"Cannot correlate catalogs with different coordinate systems.\")\n\n if coords not in ['flat', 'spherical', '3d']:\n raise ValueError(\"Invalid coords %s\"%coords)\n\n if metric not in ['Euclidean', 'Rperp', 'OldRperp', 'FisherRperp', 'Rlens', 'Arc', 'Periodic']:\n raise ValueError(\"Invalid metric %s\"%metric)\n\n if metric in ['Rperp', 'OldRperp', 'FisherRperp'] and coords != '3d':\n raise ValueError(\"%s metric is only valid for catalogs with 3d positions.\"%metric)\n if metric == 'Rlens' and auto:\n raise ValueError(\"Rlens metric is only valid for cross correlations.\")\n if metric == 'Rlens' and coords != '3d':\n raise ValueError(\"Rlens metric is only valid for catalogs with 3d positions.\")\n if metric == 'Arc' and coords not in ['spherical', '3d']:\n raise ValueError(\"Arc metric is only valid for catalogs with spherical positions.\")\n\n return coords, metric\n\ndef coord_enum(coords):\n \"\"\"Return the C++-layer enum for the given string value of coords.\n \"\"\"\n if coords == 'flat':\n return treecorr._lib.Flat\n elif coords == 'spherical':\n return treecorr._lib.Sphere\n elif coords == '3d':\n return treecorr._lib.ThreeD\n else:\n raise ValueError(\"Invalid coords %s\"%coords)\n\ndef metric_enum(metric):\n \"\"\"Return the C++-layer enum for the given string value of metric.\n \"\"\"\n if metric == 'Euclidean':\n return treecorr._lib.Euclidean\n elif metric == 'Rperp':\n return metric_enum(treecorr.Rperp_alias)\n elif metric == 'FisherRperp':\n return treecorr._lib.Rperp\n elif metric in ['OldRperp']:\n return treecorr._lib.OldRperp\n elif metric == 'Rlens':\n return treecorr._lib.Rlens\n elif metric == 'Arc':\n return treecorr._lib.Arc\n elif metric == 'Periodic':\n return treecorr._lib.Periodic\n else:\n raise ValueError(\"Invalid metric %s\"%metric)\n\ndef parse_xyzsep(args, kwargs, _coords):\n \"\"\"Parse the different options for passing a coordinate and separation.\n\n The allowed parameters are:\n\n 1. If _coords == Flat:\n\n :param x: The x coordinate of the location for which to count nearby points.\n :param y: The y coordinate of the location for which to count nearby points.\n :param sep: The separation distance\n\n 2. If _coords == ThreeD:\n\n Either\n :param x: The x coordinate of the location for which to count nearby points.\n :param y: The y coordinate of the location for which to count nearby points.\n :param z: The z coordinate of the location for which to count nearby points.\n :param sep: The separation distance\n\n Or\n :param ra: The right ascension of the location for which to count nearby points.\n :param dec: The declination of the location for which to count nearby points.\n :param r: The distance to the location for which to count nearby points.\n :param sep: The separation distance\n\n 3. If _coords == Sphere:\n\n :param ra: The right ascension of the location for which to count nearby points.\n :param dec: The declination of the location for which to count nearby points.\n :param sep: The separation distance as an angle\n\n For all angle parameters (ra, dec, sep), this quantity may be a coord.Angle instance, or\n units maybe be provided as ra_units, dec_units or sep_units respectively.\n\n Finally, in cases where ra, dec are allowed, a coord.CelestialCoord instance may be\n provided as the first argument.\n\n :returns: The effective (x, y, z, sep) as a tuple.\n \"\"\"\n radec = False\n if _coords == treecorr._lib.Flat:\n if len(args) == 0:\n if 'x' not in kwargs:\n raise TypeError(\"Missing required argument x\")\n if 'y' not in kwargs:\n raise TypeError(\"Missing required argument y\")\n if 'sep' not in kwargs:\n raise TypeError(\"Missing required argument sep\")\n x = kwargs.pop('x')\n y = kwargs.pop('y')\n sep = kwargs.pop('sep')\n elif len(args) == 1:\n raise TypeError(\"x,y should be given as either args or kwargs, not mixed.\")\n elif len(args) == 2:\n if 'sep' not in kwargs:\n raise TypeError(\"Missing required argument sep\")\n x,y = args\n sep = kwargs.pop('sep')\n elif len(args) == 3:\n x,y,sep = args\n else:\n raise TypeError(\"Too many positional args\")\n z = 0\n\n elif _coords == treecorr._lib.ThreeD:\n if len(args) == 0:\n if 'x' in kwargs:\n if 'y' not in kwargs:\n raise TypeError(\"Missing required argument y\")\n if 'z' not in kwargs:\n raise TypeError(\"Missing required argument z\")\n x = kwargs.pop('x')\n y = kwargs.pop('y')\n z = kwargs.pop('z')\n else:\n if 'ra' not in kwargs:\n raise TypeError(\"Missing required argument ra\")\n if 'dec' not in kwargs:\n raise TypeError(\"Missing required argument dec\")\n ra = kwargs.pop('ra')\n dec = kwargs.pop('dec')\n radec = True\n if 'r' not in kwargs:\n raise TypeError(\"Missing required argument r\")\n r = kwargs.pop('r')\n if 'sep' not in kwargs:\n raise TypeError(\"Missing required argument sep\")\n sep = kwargs.pop('sep')\n elif len(args) == 1:\n if not isinstance(args[0], coord.CelestialCoord):\n raise TypeError(\"Invalid unnamed argument %r\"%args[0])\n ra = args[0].ra\n dec = args[0].dec\n radec = True\n if 'r' not in kwargs:\n raise TypeError(\"Missing required argument r\")\n r = kwargs.pop('r')\n if 'sep' not in kwargs:\n raise TypeError(\"Missing required argument sep\")\n sep = kwargs.pop('sep')\n elif len(args) == 2:\n if isinstance(args[0], coord.CelestialCoord):\n ra = args[0].ra\n dec = args[0].dec\n radec = True\n r = args[1]\n else:\n ra, dec = args\n radec = True\n if 'r' not in kwargs:\n raise TypeError(\"Missing required argument r\")\n r = kwargs.pop('r')\n if 'sep' not in kwargs:\n raise TypeError(\"Missing required argument sep\")\n sep = kwargs.pop('sep')\n elif len(args) == 3:\n if isinstance(args[0], coord.CelestialCoord):\n ra = args[0].ra\n dec = args[0].dec\n radec = True\n r = args[1]\n sep = args[2]\n elif isinstance(args[0], coord.Angle):\n ra, dec, r = args\n radec = True\n if 'sep' not in kwargs:\n raise TypeError(\"Missing required argument sep\")\n sep = kwargs.pop('sep')\n elif 'ra_units' in kwargs or 'dec_units' in kwargs:\n ra, dec, r = args\n radec = True\n if 'sep' not in kwargs:\n raise TypeError(\"Missing required argument sep\")\n sep = kwargs.pop('sep')\n else:\n x, y, z = args\n if 'sep' not in kwargs:\n raise TypeError(\"Missing required argument sep\")\n sep = kwargs.pop('sep')\n elif len(args) == 4:\n if isinstance(args[0], coord.Angle):\n ra, dec, r, sep = args\n radec = True\n elif 'ra_units' in kwargs or 'dec_units' in kwargs:\n ra, dec, r, sep = args\n radec = True\n else:\n x, y, z, sep = args\n else:\n raise TypeError(\"Too many positional args\")\n\n else: # Sphere\n if len(args) == 0:\n if 'ra' not in kwargs:\n raise TypeError(\"Missing required argument ra\")\n if 'dec' not in kwargs:\n raise TypeError(\"Missing required argument dec\")\n ra = kwargs.pop('ra')\n dec = kwargs.pop('dec')\n radec = True\n if 'sep' not in kwargs:\n raise TypeError(\"Missing required argument sep\")\n sep = kwargs.pop('sep')\n elif len(args) == 1:\n if not isinstance(args[0], coord.CelestialCoord):\n raise TypeError(\"Invalid unnamed argument %r\"%args[0])\n ra = args[0].ra\n dec = args[0].dec\n radec = True\n if 'sep' not in kwargs:\n raise TypeError(\"Missing required argument sep\")\n sep = kwargs.pop('sep')\n elif len(args) == 2:\n if isinstance(args[0], coord.CelestialCoord):\n ra = args[0].ra\n dec = args[0].dec\n radec = True\n sep = args[1]\n else:\n ra, dec = args\n radec = True\n if 'sep' not in kwargs:\n raise TypeError(\"Missing required argument sep\")\n sep = kwargs.pop('sep')\n elif len(args) == 3:\n ra, dec, sep = args\n radec = True\n else:\n raise TypeError(\"Too many positional args\")\n if not isinstance(sep, coord.Angle):\n if 'sep_units' not in kwargs:\n raise TypeError(\"Missing required argument sep_units\")\n sep = sep * coord.AngleUnit.from_name(kwargs.pop('sep_units'))\n # We actually want the chord distance for this angle.\n sep = 2. * np.sin(sep/2.)\n\n if radec:\n if not isinstance(ra, coord.Angle):\n if 'ra_units' not in kwargs:\n raise TypeError(\"Missing required argument ra_units\")\n ra = ra * coord.AngleUnit.from_name(kwargs.pop('ra_units'))\n if not isinstance(dec, coord.Angle):\n if 'dec_units' not in kwargs:\n raise TypeError(\"Missing required argument dec_units\")\n dec = dec * coord.AngleUnit.from_name(kwargs.pop('dec_units'))\n x,y,z = coord.CelestialCoord(ra, dec).get_xyz()\n if _coords == treecorr._lib.ThreeD:\n x *= r\n y *= r\n z *= r\n if len(kwargs) > 0:\n raise TypeError(\"Invalid kwargs: %s\"%(kwargs))\n\n return float(x), float(y), float(z), float(sep)\n" ]
[ [ "numpy.linspace", "numpy.arcsin", "numpy.tile", "numpy.concatenate", "numpy.exp" ], [ "numpy.savetxt", "numpy.sin", "numpy.genfromtxt" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jmrozanec/features-generator
[ "0772394cf1c4a56a88c8a8faba2e5c84b4b2883f" ]
[ "features/feature_generator.py" ]
[ "from sklearn.base import BaseEstimator, TransformerMixin\nfrom feature_generation_strategy import MinFeatureGenerationStrategy, MaxFeatureGenerationStrategy, SumFeatureGenerationStrategy, DiffFeatureGenerationStrategy, ProdFeatureGenerationStrategy, DivFeatureGenerationStrategy, AvgFeatureGenerationStrategy, PCAFeatureGenerationStrategy, TSVDFeatureGenerationStrategy, ICAFeatureGenerationStrategy, GRPFeatureGenerationStrategy, SRPFeatureGenerationStrategy\n\nfrom sklearn.datasets import load_iris\nfrom sklearn.model_selection import train_test_split\nimport pandas as pd\nimport numpy as np\n\n\nclass FeatureGenerator(BaseEstimator, TransformerMixin):\n \"\"\"\n Feature generator: enables to create features using provided strategies.\n \"\"\"\n def __init__(self, key, strategies):\n self.key = key\n self.strategies = strategies\n\n def fit(self, X, y=None):\n return self\n\n def transform(self, X):\n return X[self.key]\n\n\n\n\n\n\n\niris = load_iris()\ndf = pd.DataFrame(data= np.c_[iris['data'], iris['target']], columns= iris['feature_names'] + ['target'])\ntrain, X_valtest, y_train, y_valtest = train_test_split(df[df.columns.difference(['target'])], df['target'], test_size=0.3)\nval, test, y_val, y_test = train_test_split(X_valtest, y_valtest, test_size=0.5)\n\ncolumn_names = train.columns.values\nminstrat = MinFeatureGenerationStrategy()\nmaxstrat = MaxFeatureGenerationStrategy()\nsumstrat = SumFeatureGenerationStrategy()\ndiffstrat = DiffFeatureGenerationStrategy()\nprodstrat = ProdFeatureGenerationStrategy()\ndivstrat = DivFeatureGenerationStrategy()\navgstrat = AvgFeatureGenerationStrategy()\npcastrat = PCAFeatureGenerationStrategy()\ntsvdstrat = TSVDFeatureGenerationStrategy()\nicastrat = ICAFeatureGenerationStrategy()\ngrpstrat = GRPFeatureGenerationStrategy()\nsrpstrat = SRPFeatureGenerationStrategy()\n\nstrategies1 = [minstrat, maxstrat, sumstrat, diffstrat, prodstrat, divstrat, avgstrat]\nstrategies2 = [pcastrat, tsvdstrat, icastrat, grpstrat, srpstrat]\n\ndef generate_features(train, val, test, colname1, colname2, strategies):\n\tfor strategy in strategies:\n\t\ttrain, val, test = strategy.generate(train, val, test, colname1, colname2)\n\treturn (train, val, test)\n\nfor colname1 in column_names:\n\tfor colname2 in column_names:\n\t\ttrain, val, test = generate_features(train, val, test, colname1, colname2, strategies1)\n\ntrain.fillna(0, inplace=True)\nval.fillna(0, inplace=True)\ntest.fillna(0, inplace=True)\n\nfor strategy in strategies2:\n\ttrain, val, test = strategy.generate(train, val, test, 10)\n\nnew_column_names = train.columns.values\nprint(\"original columns: {}\".format(\",\".join(column_names)))\nprint(\"new columns: {}\".format(\",\".join(new_column_names)))\n" ]
[ [ "sklearn.datasets.load_iris", "sklearn.model_selection.train_test_split", "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": [] } ]
FOLEFAC/InstantReact
[ "ba0e00ef4c84710accfe6b278000da06ee2d6438" ]
[ "test.py" ]
[ "\r\n# Imports\r\n\r\nimport torch\r\nfrom torchvision import datasets, models, transforms # All torchvision modules\r\nimport torch.nn as nn # All neural network modules, nn.Linear, nn.Conv2d, Loss functions,..\r\nimport torch.optim as optim # For all Optimization algorithms, SGD, Adam,...\r\nimport torch.nn.functional as F # All functions that don't have any parameters\r\nfrom torch.utils.data import (DataLoader,Dataset) # Gives easier dataset managment and creates mini batches\r\nimport torchvision.datasets as datasets # Has standard datasets we can import in a nice way\r\nimport torchvision.transforms as transforms # Transformations we can perform on our dataset\r\nimport torchtext # Makes it easy to work with sequence data \r\nfrom torchtext.data import get_tokenizer\r\n\r\nimport re # regex library\r\nimport os # Doing operating system operations\r\nimport cv2 # Computer vision tasks with OpenCV\r\nimport numpy as np # Powerful arrray computation library\r\nfrom PIL import Image # WOrking with image files\r\nimport pandas # Extracting data from csv\r\nimport math # Math package\r\nimport pickle # Saving variables for later usage.\r\n\r\nimport argparse\r\nfrom torchsummary import summary # Make understanding of models easier\r\nimport torch # PyTorch library\r\nfrom time import time # Using timer in code\r\n\r\n\r\nfrom utils import Utils\r\nfrom text_processor import TextProcessor\r\nfrom dataset import CustomDataset\r\nfrom models import Encoder_LSTM, Decoder_LSTM, Seq2Seq\r\n\r\nimport models as md\r\n\r\n# Set device\r\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") # Use Cuda if GPU available!\r\n\r\n\r\n\r\n\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument('--NUMBER_OF_FRAMES', type=int, default=40) \r\nparser.add_argument('--LEARNING_RATE', type=float, default=1e-3)\r\nparser.add_argument('--BATCH_SIZE', type=int, default=1) \r\nparser.add_argument('--EPOCH', type=int, default=10) \r\nparser.add_argument('--TRAINING_DEVICE', type=str, default='cuda') \r\nparser.add_argument('--VOCAB_SIZE', type=int, default=200) \r\nparser.add_argument('--NUMBER_OF_WORDS', type=int, default=10) \r\nparser.add_argument('--HIDDEN_SIZE', type=int, default=300) \r\nparser.add_argument('--INPUT_SIZE', type=int, default=4096) \r\nparser.add_argument('--NUMBER_OF_LAYERS', type=int, default=1) \r\nparser.add_argument('--video_file', type=str)\r\nparser.add_argument('--train_corpus', type=str)\r\nparser.add_argument('--load_weights', type=str)\r\n\r\nFLAGS = parser.parse_args()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef main(argv = None):\r\n\r\n \"\"\"\r\n Training.\r\n \"\"\"\r\n\r\n ### parametres\r\n\r\n LEARNING_RATE = FLAGS.LEARNING_RATE\r\n NUMBER_OF_FRAMES = FLAGS.NUMBER_OF_FRAMES\r\n BATCH_SIZE = FLAGS.BATCH_SIZE\r\n EPOCH = FLAGS.EPOCH\r\n TRAINING_DEVICE = FLAGS.TRAINING_DEVICE\r\n VOCAB_SIZE = FLAGS.VOCAB_SIZE\r\n NUMBER_OF_WORDS = FLAGS.NUMBER_OF_WORDS\r\n HIDDEN_SIZE = FLAGS.HIDDEN_SIZE\r\n INPUT_SIZE = FLAGS.INPUT_SIZE\r\n NUMBER_OF_LAYERS = FLAGS.NUMBER_OF_LAYERS\r\n tsfm = transforms.Compose([\r\n transforms.Resize([224, 224]),\r\n transforms.ToTensor(),\r\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),\r\n ])\r\n train_corpus = FLAGS.train_corpus\r\n utils = Utils()\r\n all_text = utils.output_text(train_corpus)\r\n text_processor = TextProcessor(freq_threshold = 10)\r\n dictionary = text_processor.vocab_creator(all_text)\r\n\r\n\r\n\r\n ### Model definition\r\n encoder = Encoder_LSTM(input_size = INPUT_SIZE, hidden_size = HIDDEN_SIZE , num_layers = NUMBER_OF_LAYERS)\r\n decoder = Decoder_LSTM(input_size = VOCAB_SIZE, hidden_size = HIDDEN_SIZE , num_layers = NUMBER_OF_LAYERS,number_of_words = NUMBER_OF_WORDS)\r\n model_seq_to_seq = Seq2Seq(encoder, decoder).to(device)\r\n model = model_seq_to_seq\r\n\r\n\r\n ### load the state_dict of model if model has been pretrained.\r\n model.load_state_dict(torch.load(FLAGS.load_weights))\r\n\r\n\r\n\r\n\r\n #### Model Testing\r\n model.eval();\r\n from random import randint\r\n import matplotlib.pyplot as plt\r\n\r\n utils = Utils()\r\n\r\n video_path = FLAGS.video_file\r\n\r\n video_pre_data = utils.video_to_frames(video_path,frame_number = NUMBER_OF_FRAMES, device = 'cuda', INPUT_SIZE = INPUT_SIZE , model = md.model_vgg, transform = tsfm)\r\n \r\n X_2 = torch.zeros([NUMBER_OF_WORDS,VOCAB_SIZE])\r\n\r\n for i in range(NUMBER_OF_WORDS):\r\n if (i == 0):\r\n \r\n X_2[i][2] = 1\r\n else:\r\n X_2[i][1] = 1\r\n\r\n input_data = video_pre_data.unsqueeze(0)\r\n\r\n final_sentence = []\r\n\r\n X_2 = X_2.unsqueeze(0)\r\n X_2 = X_2.to(device)\r\n input_data = input_data.to(device)\r\n\r\n\r\n\r\n\r\n for i in range(NUMBER_OF_WORDS-1):\r\n with torch.no_grad():\r\n predicted = model(input_data, X_2)\r\n predicted = predicted.squeeze(0)\r\n\r\n final_sentence.append(next((key for key, value in dictionary.items() if value == torch.argmax(predicted[i])), None))\r\n X_2[0][i+1][torch.argmax(predicted[i])] = 1\r\n X_2[0][i+1][1] = 0\r\n print(final_sentence)\r\n\r\n\r\n \r\n\r\nif __name__ == '__main__':\r\n main()" ]
[ [ "torch.load", "torch.zeros", "torch.no_grad", "torch.cuda.is_available", "torch.argmax" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
opengulf/nyc-directories-support-scripts
[ "e22582b8f4cb3c365e9aac1d860d9c36831277a5" ]
[ "py-hocr-detect-columns.py" ]
[ "import numpy as np\nfrom bs4 import BeautifulSoup\nfrom sklearn.cluster import KMeans\nfrom math import sqrt\nfrom statistics import mean\nfrom PIL import Image, ImageOps, ImageDraw\nimport re\nimport json\nimport argparse\nimport os\nimport uuid\nfrom cdparser import Classifier, Features, LabeledEntry, Utils\nimport sys\n\n\ndef build_manifest(main_path, entries_json):\n directory_uuid = entries_json[0]['directory_uuid']\n page_uuid = entries_json[0]['page_uuid']\n num_columns = max([int(entries_json[i]['col']) for i in entries_json])\n num_skipped_lines = len(\n [i for i in entries_json if entries_json[i]['skipped_line_after'] == '1'])\n if not os.path.exists(os.path.join(main_path, 'manifest')):\n os.makedirs(os.path.join(main_path, 'manifest'))\n manifest_path = os.path.join(\n main_path, 'manifest', directory_uuid + '_manifest.txt')\n with open(manifest_path, 'a') as f:\n f.write('directory_uuid:' + directory_uuid + '\\n')\n f.write('page_uuid:' + page_uuid + '\\n')\n f.write('number_extracted_entries:' + str(len(entries_json)) + '\\n')\n f.write('total_number_lines_hocr:' +\n entries_json[0]['total_lines_from_hocr'] + '\\n')\n f.write('number_extracted_columns:' + str(num_columns) + '\\n')\n f.write('number_skipped_lines:' + str(num_skipped_lines))\n f.write('\\n\\n')\n f.close()\n\n\ndef make_tsv(filepath, type):\n with open(filepath, 'w+') as f:\n f.write('\\t'.join(['directory_uuid', 'page_uuid',\n 'entry_uuid', type + '_count', 'offset_count', 'token']))\n f.write('\\n')\n f.close()\n\n\ndef build_entries_tsv(entries_json, dir_tsv, directory_uuid):\n if not os.path.exists(os.path.join(dir_tsv, directory_uuid + '_subjects.tsv')):\n make_tsv(os.path.join(dir_tsv, directory_uuid +\n '_subjects.tsv'), 'subject')\n with open(os.path.join(dir_tsv, directory_uuid + '_subjects.tsv'), 'a') as f:\n for rec in entries_json:\n subject_count = 0\n for subject in entries_json[rec]['labeled_entry']['subjects']:\n offset_count = 0\n for sub_token in subject.split():\n f.write(entries_json[rec]['directory_uuid'] + '\\t'\n + entries_json[rec]['page_uuid'] + '\\t'\n + entries_json[rec]['entry_uuid'] + '\\t')\n f.write(str(subject_count) + '\\t')\n f.write(str(offset_count) + '\\t')\n f.write(sub_token + '\\n')\n offset_count += 1\n subject_count += 1\n f.close()\n if not os.path.exists(os.path.join(dir_tsv, directory_uuid + '_occupations.tsv')):\n make_tsv(os.path.join(dir_tsv, directory_uuid +\n '_occupations.tsv'), 'occupation')\n with open(os.path.join(dir_tsv, directory_uuid + '_occupations.tsv'), 'a') as f:\n for rec in entries_json:\n occupation_count = 0\n for occupation in entries_json[rec]['labeled_entry']['occupations']:\n offset_count = 0\n for occ_token in occupation.split():\n f.write(entries_json[rec]['directory_uuid'] + '\\t'\n + entries_json[rec]['page_uuid'] + '\\t'\n + entries_json[rec]['entry_uuid'] + '\\t')\n f.write(str(occupation_count) + '\\t')\n f.write(str(offset_count) + '\\t')\n f.write(occ_token + '\\n')\n offset_count += 1\n occupation_count += 1\n f.close()\n if not os.path.exists(os.path.join(dir_tsv, directory_uuid + '_locations.tsv')):\n make_tsv(os.path.join(dir_tsv, directory_uuid +\n '_locations.tsv'), 'location')\n with open(os.path.join(dir_tsv, directory_uuid + '_locations.tsv'), 'a') as f:\n for rec in entries_json:\n location_count = 0\n for location in entries_json[rec]['labeled_entry']['locations']:\n offset_count = 0\n for loc_token in location['value'].split():\n f.write(entries_json[rec]['directory_uuid'] + '\\t'\n + entries_json[rec]['page_uuid'] + '\\t'\n + entries_json[rec]['entry_uuid'] + '\\t')\n f.write(str(location_count) + '\\t')\n f.write(str(offset_count) + '\\t')\n f.write(loc_token + '\\n')\n offset_count += 1\n location_count += 1\n f.close()\n\n\ndef imagebuilder(r, col_locations, image_filename, std1, gap_locations, page_uuid, output_directory):\n\n # It would appear that the incoming cropped jpegs are grayscale, necessitating a conversion to RGB to move forward\n # For the overlay, we use RGBA to enable opacity settings.\n\n pageimg = Image.open(image_filename).convert('RGB')\n overlay = ImageDraw.Draw(pageimg, 'RGBA')\n\n color = {0: (255, 0, 0, 90), 1: (0, 0, 255, 90), 2: (0, 255, 0, 90)}\n\n # Draw the hocr boxes\n for i in range(len(r)):\n overlay.polygon([(r[i:i+1, 1], r[i:i+1, 4]),\n (r[i:i+1, 1], r[i:i+1, 2]),\n (r[i:i+1, 3], r[i:i+1, 2]),\n (r[i:i+1, 3], r[i:i+1, 4])],\n fill=color[int(r[i:i+1, 5])], outline=color[int(r[i:i+1, 5])])\n\n # Draw the column bounds\n\n for loc in col_locations:\n\n overlay.polygon([(loc - std1, 0), (loc + std1, 0),\n (loc + std1, pageimg.size[1]),\n (loc - std1, pageimg.size[1])],\n fill=(255, 1, 255, 100))\n overlay.line([(loc, 0), (loc, pageimg.size[1])],\n fill=(0, 0, 0, 127), width=4)\n\n # Draw the gap lines\n\n for gap_location in gap_locations:\n overlay.line([(0, gap_location), (pageimg.size[0], gap_location)],\n fill=(0, 0, 0, 127), width=4)\n pageimg.save(os.path.join(output_directory, page_uuid + '.jpeg'), 'JPEG')\n\n\ndef json_from_hocr(line_array, page_html, page_uuid, directory_uuid):\n hocr_entries = {}\n entries_json = {}\n total_page_line_count = 0\n for line in page_html.html.body.div.find_all('span'):\n if line['class'][0] == 'ocr_line':\n total_page_line_count += 1\n id_num = int(line['id'].split('_')[2])\n words = ' '.join([word.string.replace('\\n', '').strip()\n for word in line.children])\n hocr_entries[id_num] = normalize_entry(words)\n entry_id = 0\n for keep_line in line_array:\n entry_uuid = uuid.uuid1()\n if keep_line[5] == 0:\n entries_json[entry_id] = {\n 'directory_uuid': directory_uuid,\n 'page_uuid': page_uuid,\n 'entry_uuid': entry_uuid.hex,\n 'total_lines_from_hocr': str(total_page_line_count),\n 'original_hocr_line_number': str(keep_line[0]),\n 'bbox': ' '.join([str(val) for val in keep_line[1:5]]),\n 'col': str(keep_line[6]),\n 'appended': 'no',\n 'skipped_line_after': str(keep_line[7]),\n 'complete_entry': hocr_entries[keep_line[0]]\n }\n entry_id += 1\n\n # Indents\n else:\n try:\n if entries_json[entry_id - 1]['skipped_line_after'] != \"1\":\n if entries_json[entry_id - 1]['complete_entry'][-1] == '-':\n entries_json[entry_id -\n 1]['complete_entry'] += hocr_entries[keep_line[0]]\n else:\n entries_json[entry_id - 1]['complete_entry'] += ' ' + \\\n hocr_entries[keep_line[0]]\n entries_json[entry_id - 1]['appended'] = 'yes'\n else:\n entries_json[entry_id] = {\n 'directory_uuid': directory_uuid,\n 'page_uuid': page_uuid,\n 'entry_uuid': entry_uuid.hex,\n 'total_lines_from_hocr': str(total_page_line_count),\n 'original_hocr_line_number': str(keep_line[0]),\n 'bbox': ' '.join([str(val) for val in keep_line[1:5]]),\n 'col': str(keep_line[6]),\n 'appended': 'no',\n 'skipped_line_after': str(keep_line[7]),\n 'complete_entry': hocr_entries[keep_line[0]]\n }\n entry_id += 1\n except:\n\n # Cases where an indent is the first line in page array and there is no preceding entry\n\n entries_json[entry_id] = {\n 'directory_uuid': directory_uuid,\n 'page_uuid': page_uuid,\n 'entry_uuid': entry_uuid.hex,\n 'total_lines_from_hocr': str(total_page_line_count),\n 'original_hocr_line_number': str(keep_line[0]),\n 'bbox': ' '.join([str(val) for val in keep_line[1:5]]),\n 'col': str(keep_line[6]),\n 'appended': 'no',\n 'skipped_line_after': str(keep_line[7]),\n 'complete_entry': hocr_entries[keep_line[0]]\n }\n entry_id += 1\n\n return entries_json\n\n\ndef load_hocr_lines(filepath):\n page_array = []\n rawhtml = BeautifulSoup(open(filepath, encoding='utf-8'), \"lxml\")\n for line in rawhtml.html.body.div.find_all('span'):\n line_list = []\n if line['class'][0] == 'ocr_line':\n line_list.append(int(line['id'].split('_')[2]))\n line_list += [int(i)\n for i in line['title'].split(';')[0].split(' ')[1:]]\n line_list += [0, 0, 0]\n page_array.append(line_list)\n return np.array(page_array), rawhtml\n\n\ndef normalize_entry(entry):\n replacements = [(\"‘\", \"'\"), (\"’\", \"'\"), (\" ay.\", \" av.\"),\n (\" ay,\", \" av,\"), (\"- \", \"-\"), (\" -\", \"-\"), (\"\\t\", ' ')]\n for swap in replacements:\n entry = entry.replace(swap[0], swap[1])\n return ' '.join(entry.split())\n\n\ndef remove_precede_space(entry):\n if re.search(r'\\s\\.|\\s\\,', entry):\n entry = entry.replace(' .', '.').replace(' ,', ',')\n return entry\n\n\ndef normalize_labeled_entry(labeled_entry_dict):\n new_subjects = []\n for subject in labeled_entry_dict['subjects']:\n new_subjects.append(remove_precede_space(subject))\n labeled_entry_dict['subjects'] = new_subjects\n new_occs = []\n for occ in labeled_entry_dict['occupations']:\n new_occs.append(remove_precede_space(occ))\n labeled_entry_dict['occupations'] = new_occs\n new_locations = []\n for loc_dict in labeled_entry_dict['locations']:\n new_loc_dict = {}\n new_loc_dict['value'] = remove_precede_space(loc_dict['value'])\n try:\n new_loc_dict['labels'] = loc_dict['labels']\n except:\n pass\n new_locations.append(new_loc_dict)\n labeled_entry_dict['locations'] = new_locations\n return labeled_entry_dict\n\n\ndef build_entries(args):\n \"\"\"\n Page Array Structure\n col 0 = ID number of line\n col 1-4 = bbbox x1, y1, x2, y2\n col 5 = 0:col line; 1: indent line; 2:kill line\n col 6 = 1:col 1; 2: col2 (column assignment)\n col 7 = 0:ok to append, 1: do not append (likely gap)\"\"\"\n\n root = '/'.join(args.path.split('/')[:-1])\n directory_uuid = root.split('/')[-1]\n hocr_files = [file for file in os.listdir(\n args.path) if file.endswith('.hocr')]\n\n print(\"Processing: \", directory_uuid)\n\n for hocr_file in hocr_files:\n\n try:\n page_uuid = hocr_file.replace('_rotated', '').replace(\n '_cropped', '').replace('.hocr', '')\n # try:\n raw_hocr_array, page_html = load_hocr_lines(\n os.path.join(args.path, hocr_file))\n\n # jpeg_path = os.path.join(\n # root, args.jpeg_directory, hocr_file.replace('.hocr', '.jpeg'))\n\n ##\n # Find our likely column locations\n ##\n\n if raw_hocr_array.size == 0:\n print(\"Empty HOCR file: \" + hocr_file)\n print(\"Passing: ----------------------------------\")\n continue\n\n kmeans = KMeans(n_clusters=8).fit(\n raw_hocr_array[:, 1].reshape(-1, 1))\n centroids = kmeans.cluster_centers_\n cands_cols = {}\n\n for j in range(len(centroids)):\n cands_cols[centroids[j, 0]] = 0\n std = sqrt(mean([((i - centroids[j, 0])**2)\n for i in raw_hocr_array[:, 1]]))\n for i in range(len(raw_hocr_array)):\n if abs(raw_hocr_array[i:i+1, 1] - centroids[j, 0]) > (std/16):\n pass\n else:\n cands_cols[centroids[j, 0]] += 1\n\n # We have our dict of possible column location along with the number of entries proximate to each\n # But in case our k-means clustering was compromised by a slanted column line (yielding double col locations)\n # we need to check for that and take an average of the resultant double col1 and double col2 locations\n\n halfway_page_rough = (max(raw_hocr_array[:, 1])/2)*.95\n lefthand_cands = [\n i for i in cands_cols.items() if i[0] < halfway_page_rough]\n righthand_cands = [\n i for i in cands_cols.items()if i[0] > halfway_page_rough]\n col1_xval_cands = sorted(\n lefthand_cands, key=lambda x: x[1], reverse=True)\n col2_xval_cands = sorted(\n righthand_cands, key=lambda x: x[1], reverse=True)\n\n # Now that we've split our candidate locations into what we think is roughly the col1 and col2 areas\n # we look for two closely proximate top candidates. If they exist, we average them out\n\n if abs(col1_xval_cands[0][0] - col1_xval_cands[1][0]) < 50:\n col1_xval = mean(\n [col1_xval_cands[0][0], col1_xval_cands[1][0]])\n else:\n col1_xval = col1_xval_cands[0][0]\n try:\n if abs(col2_xval_cands[0][0] - col2_xval_cands[1][0]) < 50:\n col2_xval = mean(\n [col2_xval_cands[0][0], col2_xval_cands[1][0]])\n else:\n col2_xval = col2_xval_cands[0][0]\n\n # For cases where we don't have multiple candidates for a second column,\n # possibly because Tesseract missed second column entirely:\n except:\n col2_xval = col2_xval_cands[0][0]\n\n ##\n # Pass to identify and keep lines that are at x-val of column edges\n ##\n\n std1 = sqrt(mean([((i - col1_xval)**2)\n for i in raw_hocr_array[:, 1]]))/16\n std2 = sqrt(mean([((i - col2_xval)**2)\n for i in raw_hocr_array[:, 1]]))/16\n for i in range(len(raw_hocr_array)):\n if abs(raw_hocr_array[i:i + 1, 1] - col1_xval) < std1 or abs(raw_hocr_array[i:i + 1, 1] - col2_xval) < std2:\n # Col 1 identification:\n if abs(raw_hocr_array[i:i + 1, 1] - col1_xval) < std1:\n raw_hocr_array[i:i + 1, 6] = 1\n # Col 2 identification:\n elif abs(raw_hocr_array[i:i + 1, 1] - col2_xval) < std2:\n raw_hocr_array[i:i + 1, 6] = 2\n # Id of indents and any potential chopped off lines to right of columns\n elif raw_hocr_array[i:i + 1, 1] - (col1_xval + std1) > 0 and raw_hocr_array[i:i + 1, 1] < col2_xval:\n # Col 1 indents identification\n raw_hocr_array[i:i + 1, 5] = 1\n raw_hocr_array[i:i + 1, 6] = 1\n elif raw_hocr_array[i:i + 1, 1] - (col2_xval + std2) > 0:\n # Col 2 indents identification\n raw_hocr_array[i:i + 1, 5] = 1\n raw_hocr_array[i:i + 1, 6] = 2\n # Eliminating anything to left of column 1\n if raw_hocr_array[i:i+1, 1] < (col1_xval - std1):\n raw_hocr_array[i:i + 1, 5] = 2\n # Eliminating anything to right of column 2 right edge\n if raw_hocr_array[i:i + 1, 1] > (col2_xval + (col2_xval - col1_xval)):\n raw_hocr_array[i:i + 1, 5] = 2\n\n ##\n # Pass to find lines flush with a column whose y vals make them unlikely to be in the page block for entries\n ##\n\n reduced_array = raw_hocr_array[raw_hocr_array[:, 5] != 2]\n sorted_y_array = np.sort(reduced_array.view(\n 'i8,i8,i8,i8,i8,i8,i8,i8'), order=['f2'], axis=0).view(np.int)\n\n # To find an appropriate vertical line density of all likely lines, we grab a sample at a point roughly 1/4\n # the way through our entries, then gather the line density at that point within a gap around that point\n # The gap is calculated at 0.5% of the highest yval (roughly 0.5% of the yval height of the page)\n\n quarter_page = len(sorted_y_array)//4\n gap = float(max(raw_hocr_array[:, 2]))*.05\n entry_density = len([i for i in sorted_y_array[:, 2] if abs(\n i - sorted_y_array[quarter_page:quarter_page+1, 2]) < gap/2])\n\n # We now examine the line density around every line in the page; if the density is low, we do a second check to make\n # sure the reason isn't that it is a first or last line; in those cases we check for gap density after/before the line\n # Anything that still fails we cut\n\n for i in range(len(sorted_y_array)):\n proximate_lines = [yval for yval in sorted_y_array[:, 2] if abs(\n yval - sorted_y_array[i:i+1, 2]) < gap/2]\n if len(proximate_lines) - 1 < entry_density/2:\n top_line_proximate_lines = [yval for yval in sorted_y_array[:, 2] if yval - sorted_y_array[i:i + 1, 2] < gap\n and yval - sorted_y_array[i:i + 1, 2] > 0]\n bottom_line_proximate_lines = [yval for yval in sorted_y_array[:, 2] if\n sorted_y_array[i:i + 1, 2] - yval < gap and sorted_y_array[i:i + 1, 2] - yval > 0]\n if len(top_line_proximate_lines) > entry_density or len(bottom_line_proximate_lines) > entry_density:\n pass\n else:\n sorted_y_array[i:i+1, 5] = 2\n\n ##\n # Pass to look for missing lines by finding no line with a yval that is 1.95% of the expected space\n # between lines; if a missing line is found, we mark the previous line to make sure an indent isn't appended to that line\n # Those indents following a gap will become a standalone line because their head-entry is missing\n ##\n\n line_only_array = sorted_y_array[sorted_y_array[:, 5] != 2]\n sorted_line_only_array = np.sort(line_only_array.view(\n 'i8,i8,i8,i8,i8,i8,i8,i8'), order=['f6', 'f2'], axis=0).view(np.int)\n sample_lines = sorted_line_only_array[sorted_line_only_array[:, 6] == 1]\n gaps = []\n\n for i in range(len(sample_lines)):\n try:\n gaps.append(\n int(sample_lines[i+1:i+2, 2] - sample_lines[i:i+1, 2]))\n except:\n pass\n\n average_line_gap = sum(gaps) // len(sample_lines)\n gap_locations = []\n for i in range(len(sorted_line_only_array)):\n try:\n if int(sorted_line_only_array[i + 1:i + 2, 2] - sorted_line_only_array[i:i + 1, 2]) > average_line_gap*1.95:\n sorted_line_only_array[i:i+1, 7] = 1\n gap_locations.append(\n sorted_line_only_array[i:i + 1, 2] + average_line_gap*1.5)\n except:\n pass\n\n # We can either build the image or return the json\n\n if args.make_image == 'True':\n imagebuilder(sorted_line_only_array, [\n col1_xval, col2_xval], jpeg_path, std1, gap_locations, page_uuid, os.path.join(root, args.bbox_location))\n entries_json = json_from_hocr(\n sorted_line_only_array, page_html, page_uuid, directory_uuid)\n build_manifest(root, entries_json)\n if args.mode == 'P':\n print(entries_json)\n outpath = os.path.join(\n args.path_out, os.path.splitext(hocr_file)[0] + \".json\")\n f = open(outpath, \"w\")\n f.write(json.dumps(entries_json))\n f.close()\n print(\"----------------------------------------\")\n else:\n classifier = Classifier.Classifier()\n classifier.load_training(args.crf_training_path)\n classifier.train()\n for rec in entries_json:\n entry = LabeledEntry.LabeledEntry(\n entries_json[rec]['complete_entry'])\n classifier.label(entry)\n final_entries = normalize_labeled_entry(entry.categories)\n entries_json[rec]['labeled_entry'] = final_entries\n if args.mode == 'CRF-print':\n print(entries_json[rec])\n if args.mode == 'CRF':\n with open(os.path.join(root, 'final-entries', page_uuid + '_labeled.json'), 'w') as f:\n for rec in sorted(entries_json.keys()):\n f.write(json.dumps(entries_json[rec]) + '\\n')\n f.close()\n if args.tsv_path != \"False\":\n build_entries_tsv(\n entries_json, args.tsv_path, directory_uuid)\n print(\"Completed processing of \", page_uuid)\n\n except Exception as exception:\n print(exception.__traceback__)\n print(\"Likely ad or problematic hocr in :\", hocr_file, \". Skipped.\")\n\n\ndef main():\n parser = argparse.ArgumentParser(\n description=\"Parse hocr files and return entries\")\n parser.add_argument(\"-in\", help=\"Full-path directory containing hocr files\",\n dest=\"path\", type=str, required=True)\n parser.add_argument(\"-build-image\", help=\"Set whether to make images (True/False)\",\n dest=\"make_image\", default=\"False\", type=str, required=True)\n parser.add_argument(\"-jpegs\", help=\"Name of directory (not path) containing jpegs\",\n dest=\"jpeg_directory\", type=str, required=False)\n parser.add_argument(\"-bbox-out\", help=\"Full path to directory to place output bbox images\",\n dest=\"bbox_location\", type=str, required=False)\n parser.add_argument(\"-mode\", help=\"Either (P)rint out extracted entries, apply (CRF-print) and print out entries, or (CRF) and save JSON entries in labeled-json directory\",\n dest=\"mode\", type=str, required=True)\n parser.add_argument(\"-path-training\", help=\"Path to the training files for CRF classifer\",\n dest=\"crf_training_path\", type=str, required=False)\n parser.add_argument(\"-path-out\", help=\"Path to the training files for CRF classifer\",\n dest=\"path_out\", type=str, required=False)\n parser.add_argument(\"-build-tsv\", help=\"(False) or path to directory where tsv will be made\",\n dest=\"tsv_path\", type=str, required=False)\n parser.set_defaults(func=build_entries)\n args = parser.parse_args()\n args.func(args)\n\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "numpy.array", "sklearn.cluster.KMeans" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Ben-Foxman/z-quantum-qcbm
[ "6e0aff5283f4a1b2b788317c3a12f8ef8c562a29" ]
[ "src/python/zquantum/qcbm/ansatz.py" ]
[ "import numpy as np\nimport sympy\nfrom zquantum.core.circuit import Circuit, Qubit, Gate, create_layer_of_gates\nfrom zquantum.core.interfaces.ansatz import Ansatz\nfrom zquantum.core.interfaces.ansatz_utils import (\n ansatz_property,\n invalidates_parametrized_circuit,\n)\nfrom typing import Optional, List\nfrom .ansatz_utils import get_entangling_layer\n\nfrom overrides import overrides\n\n\nclass QCBMAnsatz(Ansatz):\n\n supports_parametrized_circuits = True\n number_of_qubits = ansatz_property(\"number_of_qubits\")\n topology = ansatz_property(\"topology\")\n\n def __init__(\n self, number_of_layers: int, number_of_qubits: int, topology: str = \"all\",\n ):\n \"\"\"\n An ansatz implementation used for running the Quantum Circuit Born Machine.\n\n Args:\n number_of_layers (int): number of entangling layers in the circuit.\n number_of_qubits (int): number of qubits in the circuit.\n topology (str): the topology representing the connectivity of the qubits.\n\n Attributes:\n number_of_qubits (int): See Args\n number_of_layers (int): See Args\n topology (str): See Args\n number_of_params: number of the parameters that need to be set for the ansatz circuit.\n \"\"\"\n super().__init__(number_of_layers)\n self._number_of_qubits = number_of_qubits\n self._topology = topology\n if number_of_layers == 0:\n raise ValueError(\"QCBMAnsatz is only defined for number_of_layers > 0.\")\n\n @property\n def number_of_params(self) -> int:\n \"\"\"\n Returns number of parameters in the ansatz.\n \"\"\"\n return np.sum(self.get_number_of_parameters_by_layer())\n\n @property\n def n_params_per_ent_layer(self) -> int:\n if self.topology == \"all\":\n return int((self.number_of_qubits * (self.number_of_qubits - 1)) / 2)\n elif self.topology == \"line\":\n return self.number_of_qubits - 1\n else:\n raise RuntimeError(\"Topology {} is not supported\".format(self.topology))\n\n @overrides\n def _generate_circuit(self, params: Optional[np.ndarray] = None) -> Circuit:\n \"\"\"Builds a qcbm ansatz circuit, using the ansatz in https://advances.sciencemag.org/content/5/10/eaaw9918/tab-pdf (Fig.2 - top).\n\n Args:\n params (numpy.array): input parameters of the circuit (1d array).\n\n Returns:\n Circuit\n \"\"\"\n if params is None:\n params = np.asarray(\n [sympy.Symbol(\"theta_{}\".format(i)) for i in range(self.number_of_params)]\n )\n\n assert len(params) == self.number_of_params\n\n if self.number_of_layers == 1:\n # Only one layer, should be a single layer of rotations with Rx\n return create_layer_of_gates(self.number_of_qubits, \"Rx\", params)\n\n circuit = Circuit()\n parameter_index = 0\n for layer_index in range(self.number_of_layers):\n if layer_index == 0:\n # First layer is always 2 single qubit rotations on Rx Rz\n circuit += create_layer_of_gates(\n self.number_of_qubits,\n \"Rx\",\n params[parameter_index : parameter_index + self.number_of_qubits],\n )\n circuit += create_layer_of_gates(\n self.number_of_qubits,\n \"Rz\",\n params[\n parameter_index\n + self.number_of_qubits : parameter_index\n + 2 * self.number_of_qubits\n ],\n )\n parameter_index += 2 * self.number_of_qubits\n elif (\n self.number_of_layers % 2 == 1\n and layer_index == self.number_of_layers - 1\n ):\n # Last layer for odd number of layers is rotations on Rx Rz\n circuit += create_layer_of_gates(\n self.number_of_qubits,\n \"Rz\",\n params[parameter_index : parameter_index + self.number_of_qubits],\n )\n circuit += create_layer_of_gates(\n self.number_of_qubits,\n \"Rx\",\n params[\n parameter_index\n + self.number_of_qubits : parameter_index\n + 2 * self.number_of_qubits\n ],\n )\n parameter_index += 2 * self.number_of_qubits\n elif (\n self.number_of_layers % 2 == 0\n and layer_index == self.number_of_layers - 2\n ):\n # Even number of layers, second to last layer is 3 rotation layer with Rx Rz Rx\n circuit += create_layer_of_gates(\n self.number_of_qubits,\n \"Rx\",\n params[parameter_index : parameter_index + self.number_of_qubits],\n )\n circuit += create_layer_of_gates(\n self.number_of_qubits,\n \"Rz\",\n params[\n parameter_index\n + self.number_of_qubits : parameter_index\n + 2 * self.number_of_qubits\n ],\n )\n circuit += create_layer_of_gates(\n self.number_of_qubits,\n \"Rx\",\n params[\n parameter_index\n + 2 * self.number_of_qubits : parameter_index\n + 3 * self.number_of_qubits\n ],\n )\n parameter_index += 3 * self.number_of_qubits\n elif (\n self.number_of_layers % 2 == 1\n and layer_index == self.number_of_layers - 3\n ):\n # Odd number of layers, third to last layer is 3 rotation layer with Rx Rz Rx\n circuit += create_layer_of_gates(\n self.number_of_qubits,\n \"Rx\",\n params[parameter_index : parameter_index + self.number_of_qubits],\n )\n circuit += create_layer_of_gates(\n self.number_of_qubits,\n \"Rz\",\n params[\n parameter_index\n + self.number_of_qubits : parameter_index\n + 2 * self.number_of_qubits\n ],\n )\n circuit += create_layer_of_gates(\n self.number_of_qubits,\n \"Rx\",\n params[\n parameter_index\n + 2 * self.number_of_qubits : parameter_index\n + 3 * self.number_of_qubits\n ],\n )\n parameter_index += 3 * self.number_of_qubits\n elif layer_index % 2 == 1:\n # Currently on an entangling layer\n circuit += get_entangling_layer(\n params[\n parameter_index : parameter_index + self.n_params_per_ent_layer\n ],\n self.number_of_qubits,\n \"XX\",\n self.topology,\n )\n parameter_index += self.n_params_per_ent_layer\n else:\n # A normal single qubit rotation layer of Rx Rz\n circuit += create_layer_of_gates(\n self.number_of_qubits,\n \"Rx\",\n params[parameter_index : parameter_index + self.number_of_qubits],\n )\n circuit += create_layer_of_gates(\n self.number_of_qubits,\n \"Rz\",\n params[\n parameter_index\n + self.number_of_qubits : parameter_index\n + 2 * self.number_of_qubits\n ],\n )\n parameter_index += 2 * self.number_of_qubits\n\n return circuit\n\n def get_number_of_parameters_by_layer(self) -> np.ndarray:\n \"\"\"Determine the number of parameters needed for each layer in the ansatz\n\n Returns:\n A 1D array of integers \n \"\"\"\n if self.number_of_layers == 1:\n # If only one layer, then only need parameters for a single layer of Rx gates\n return np.asarray([self.number_of_qubits])\n\n num_params_by_layer = []\n for layer_index in range(self.number_of_layers):\n if layer_index == 0:\n # First layer is always 2 parameters per qubit for 2 single qubit rotations\n num_params_by_layer.append(self.number_of_qubits * 2)\n elif (\n self.number_of_layers % 2 == 1\n and layer_index == self.number_of_layers - 1\n ):\n # Last layer for odd number of layers is 2 layer rotations\n num_params_by_layer.append(self.number_of_qubits * 2)\n elif (\n self.number_of_layers % 2 == 0\n and layer_index == self.number_of_layers - 2\n ):\n # Even number of layers, second to last layer is 3 rotation layer\n num_params_by_layer.append(self.number_of_qubits * 3)\n elif (\n self.number_of_layers % 2 == 1\n and layer_index == self.number_of_layers - 3\n ):\n # Odd number of layers, third to last layer is 3 rotation layer\n num_params_by_layer.append(self.number_of_qubits * 3)\n elif layer_index % 2 == 1:\n # Currently on an entangling layer\n num_params_by_layer.append(self.n_params_per_ent_layer)\n else:\n # A normal single qubit rotation layer\n num_params_by_layer.append(self.number_of_qubits * 2)\n\n return np.asarray(num_params_by_layer)" ]
[ [ "numpy.asarray" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
EmilRyberg/P8LH7Grounding
[ "406fdf4ce9afd160df3d7105fedea563a284974b", "406fdf4ce9afd160df3d7105fedea563a284974b", "406fdf4ce9afd160df3d7105fedea563a284974b" ]
[ "webots/controllers/ur_controller/kinematics/kinematics.py", "webots/controllers/ur_controller/kinematics/inverse.py", "webots/controllers/ur_controller/ur_utils.py" ]
[ "import numpy as np\n\nfrom kinematics.dhparameters import DHParameters\n\n\nclass Kinematics:\n def __init__(self):\n self.joint1_dh = DHParameters(0, 0.1625, 0)\n self.joint2_dh = DHParameters(0, 0, np.pi / 2)\n self.joint3_dh = DHParameters(-0.425, 0, 0)\n self.joint4_dh = DHParameters(-0.39225, 0.1333, 0)\n self.joint5_dh = DHParameters(0, 0.0997, np.pi / 2)\n self.joint6_dh = DHParameters(0, 0.0996, -np.pi / 2)\n\n def compute_transformation_matrix(self, theta, dh_params):\n c = np.cos(theta)\n s = np.sin(theta)\n ca = np.cos(dh_params.alpha)\n sa = np.sin(dh_params.alpha)\n A = [[c, -s, 0, dh_params.a],\n [s*ca, c*ca, -sa, -sa*dh_params.d],\n [s*sa, c*sa, ca, ca*dh_params.d],\n [0, 0, 0, 1]]\n A = np.array(A)\n return A\n\n\n", "import math\n\nimport numpy as np\n\nfrom kinematics.forward import ForwardKinematics\nfrom kinematics.kinematics import Kinematics\nfrom kinematics.solution import InverseKinematicsShoulderSolution, InverseKinematicsSpecificSolution, \\\n InverseKinematicsSolution, InverseKinematicsWristSolution\n\n\nclass InverseKinematics(Kinematics):\n def __init__(self):\n super().__init__()\n self.forward_kinematics = ForwardKinematics()\n\n def __clamp_cos_sin_within_threshold(self, cos_or_sin):\n new_val = cos_or_sin\n if 1 < new_val <= 1.2:\n new_val = 1.0\n elif -1.2 <= new_val < -1:\n new_val = -1.0\n\n return new_val\n\n def __compute_solution_for_theta_1(self, T06, theta_1, debug=False):\n wrist_solution = InverseKinematicsWristSolution()\n\n # Theta 5\n P06 = T06[:, 3]\n theta_5_1 = None\n theta_5_2 = None\n\n theta_5_cos = (P06[0] * math.sin(theta_1) - P06[1] * np.cos(\n theta_1) - self.joint4_dh.d) / self.joint6_dh.d\n\n theta_5_cos = self.__clamp_cos_sin_within_threshold(theta_5_cos)\n\n if -1 <= theta_5_cos <= 1:\n theta_5_1 = math.acos(theta_5_cos)\n theta_5_2 = -math.acos(theta_5_cos)\n\n sigma = 0.00001\n\n if theta_5_1 is not None and not -sigma <= math.sin(theta_5_1) <= sigma:\n wrist_solution.solution_wrist_up = self.__compute_solution_for_wrist(theta_1, theta_5_1, T06)\n else:\n wrist_solution.solution_wrist_up.is_valid_solution = False\n if theta_5_2 is not None and not -sigma <= math.sin(theta_5_2) <= sigma:\n wrist_solution.solution_wrist_down = self.__compute_solution_for_wrist(theta_1, theta_5_2, T06)\n else:\n wrist_solution.solution_wrist_down.is_valid_solution = False\n if not wrist_solution.solution_wrist_up.is_valid_solution and not wrist_solution.solution_wrist_down.is_valid_solution:\n wrist_solution.is_valid_solution = False\n\n if debug:\n print(f\"Theta 5: {theta_5_1:.3f}, {theta_5_2:.3f}\")\n\n return wrist_solution\n\n def __compute_solution_for_wrist(self, theta_1, theta_5, T06, debug=False):\n shoulder_solution = InverseKinematicsShoulderSolution()\n\n # Theta 6\n T60 = np.linalg.inv(T06)\n X60 = T60[:, 0]\n Y60 = T60[:, 1]\n\n theta_6_cos = (X60[0] * math.sin(theta_1) - Y60[0] * math.cos(theta_1)) / math.sin(\n theta_5) # only using one of the theta 5's for now..\n theta_6_sin = (-X60[1] * math.sin(theta_1) + Y60[1] * math.cos(theta_1)) / math.sin(\n theta_5) # only using one of the theta 5's for now..\n theta_6 = math.atan2(theta_6_sin, theta_6_cos)\n\n if debug:\n print(f\"Theta 6: {theta_6:.3f}\")\n\n tm_dict = {}\n\n # Theta 3\n T01 = self.compute_transformation_matrix(theta_1, self.joint1_dh)\n T45 = self.compute_transformation_matrix(theta_5, self.joint5_dh)\n T56 = self.compute_transformation_matrix(theta_6, self.joint6_dh)\n T46 = np.matmul(T45, T56)\n T64 = np.linalg.inv(T46)\n T10 = np.linalg.inv(T01)\n T14 = np.matmul(np.matmul(T10, T06), T64)\n P14 = T14[:, 3]\n\n tm_dict[\"T06\"] = T06\n tm_dict[\"T01\"] = T01\n tm_dict[\"T45\"] = T45\n tm_dict[\"T56\"] = T56\n tm_dict[\"T64\"] = T64\n tm_dict[\"T10\"] = T10\n tm_dict[\"T14\"] = T14\n tm_dict[\"P14\"] = P14\n\n theta_3_cos = (math.sqrt(\n P14[0] ** 2 + P14[2] ** 2) ** 2 - self.joint3_dh.a ** 2 - self.joint4_dh.a ** 2) / (\n 2 * (-self.joint3_dh.a) * (-self.joint4_dh.a))\n if debug:\n print(\"theta3_cos: \", theta_3_cos)\n\n theta_3_cos = self.__clamp_cos_sin_within_threshold(theta_3_cos)\n\n if not -1 <= theta_3_cos <= 1:\n shoulder_solution.is_valid_solution = False\n return shoulder_solution\n\n theta_3_up = math.acos(theta_3_cos)\n theta_3_down = -math.acos(theta_3_cos)\n\n if debug:\n print(f\"Theta 3: Up: {theta_3_up:.3f} Down: {theta_3_down:.3f}\")\n\n shoulder_solution.solution_elbow_up = self.__compute_specific_solution(theta_1, theta_3_up, theta_5, theta_6, tm_dict)\n shoulder_solution.solution_elbow_down = self.__compute_specific_solution(theta_1, theta_3_down, theta_5, theta_6, tm_dict)\n\n return shoulder_solution\n\n def __compute_specific_solution(self, theta_1, theta_3, theta_5, theta_6, tm_dict, debug=False):\n specific_solution = InverseKinematicsSpecificSolution()\n\n P14 = tm_dict[\"P14\"]\n\n phi_1 = math.atan2(-P14[2], -P14[0])\n phi_2 = math.asin((-self.joint4_dh.a * math.sin(theta_3)) / math.sqrt(P14[0]**2 + P14[2]**2))\n theta_2 = phi_1 - phi_2\n\n if debug:\n print(f\"Theta 2: {theta_2:.3f}\")\n\n T01 = tm_dict[\"T01\"]\n T12 = self.compute_transformation_matrix(theta_2, self.joint2_dh)\n T23 = self.compute_transformation_matrix(theta_3, self.joint3_dh)\n T45 = tm_dict[\"T45\"]\n T56 = tm_dict[\"T56\"]\n T06 = tm_dict[\"T06\"]\n T03 = np.matmul(np.matmul(T01, T12), T23)\n T30 = np.linalg.inv(T03)\n T64 = tm_dict[\"T64\"]\n T34 = np.matmul(np.matmul(T30, T06), T64)\n X34 = T34[:, 0]\n\n theta_4 = math.atan2(X34[1], X34[0])\n\n if debug:\n print(f\"Theta 4: {theta_4:.3f}\")\n\n specific_solution.thetas = [theta_1, theta_2, theta_3, theta_4, theta_5, theta_6]\n\n return specific_solution\n\n def __print_all_solutions(self, solution):\n print(\"Inverse Solutions:\")\n if solution.solution_shoulder_left.is_valid_solution:\n if solution.solution_shoulder_left.solution_wrist_up.is_valid_solution:\n if solution.solution_shoulder_left.solution_wrist_up.solution_elbow_up.is_valid_solution:\n print(\n f\"Shoulder left, wrist up, elbow up: {solution.solution_shoulder_left.solution_wrist_up.solution_elbow_up.thetas}\")\n if solution.solution_shoulder_left.solution_wrist_up.solution_elbow_down.is_valid_solution:\n print(\n f\"Shoulder left, wrist up, elbow down: {solution.solution_shoulder_left.solution_wrist_up.solution_elbow_down.thetas}\")\n if solution.solution_shoulder_left.solution_wrist_down.is_valid_solution:\n if solution.solution_shoulder_left.solution_wrist_down.solution_elbow_up.is_valid_solution:\n print(\n f\"Shoulder left, wrist down, elbow up: {solution.solution_shoulder_left.solution_wrist_down.solution_elbow_up.thetas}\")\n if solution.solution_shoulder_left.solution_wrist_down.solution_elbow_down:\n print(\n f\"Shoulder left, wrist down, elbow down: {solution.solution_shoulder_left.solution_wrist_down.solution_elbow_down.thetas}\")\n if solution.solution_shoulder_right.is_valid_solution:\n if solution.solution_shoulder_right.solution_wrist_up.is_valid_solution:\n if solution.solution_shoulder_right.solution_wrist_up.solution_elbow_up.is_valid_solution:\n print(\n f\"Shoulder right, wrist up, elbow up: {solution.solution_shoulder_right.solution_wrist_up.solution_elbow_up.thetas}\")\n if solution.solution_shoulder_right.solution_wrist_up.solution_elbow_down.is_valid_solution:\n print(\n f\"Shoulder right, wrist up, elbow down: {solution.solution_shoulder_right.solution_wrist_up.solution_elbow_up.thetas}\")\n if solution.solution_shoulder_right.solution_wrist_down.is_valid_solution:\n if solution.solution_shoulder_right.solution_wrist_down.solution_elbow_up.is_valid_solution:\n print(\n f\"Shoulder right, wrist down, elbow up: {solution.solution_shoulder_right.solution_wrist_down.solution_elbow_up.thetas}\")\n if solution.solution_shoulder_right.solution_wrist_down.solution_elbow_down.is_valid_solution:\n print(\n f\"Shoulder right, wrist down, elbow down: {solution.solution_shoulder_right.solution_wrist_down.solution_elbow_up.thetas}\")\n\n def compute_joint_angles(self, T06, debug=False):\n solution = InverseKinematicsSolution()\n\n #Theta 1\n P05 = np.dot(T06, [0, 0, -self.joint6_dh.d, 1])\n phi_1 = math.atan2(P05[1], P05[0])\n phi_2_cos = self.joint4_dh.d / math.sqrt(P05[0]**2 + P05[1]**2)\n phi_2 = math.acos(phi_2_cos)\n theta_1_1 = phi_1 + phi_2 + (np.pi / 2)\n theta_1_2 = phi_1 - phi_2 + (np.pi / 2)\n\n if debug:\n print(f\"Theta 1: {theta_1_1:.3f}, {theta_1_2:.3f}\")\n\n if not math.isnan(theta_1_1):\n solution.solution_shoulder_left = self.__compute_solution_for_theta_1(T06, theta_1_1, debug)\n else:\n solution.solution_shoulder_left = InverseKinematicsWristSolution().is_valid_solution = False\n if not math.isnan(theta_1_2):\n solution.solution_shoulder_right = self.__compute_solution_for_theta_1(T06, theta_1_2, debug)\n else:\n solution.solution_shoulder_right = InverseKinematicsWristSolution().is_valid_solution = False\n\n if debug:\n self.__print_all_solutions(solution)\n\n return solution\n\n def get_solution_for_config_id(self, solution, config_id):\n if config_id == 0:\n return solution.solution_shoulder_left.solution_wrist_up.solution_elbow_up.thetas\n elif config_id == 1:\n return solution.solution_shoulder_left.solution_wrist_up.solution_elbow_down.thetas\n elif config_id == 2:\n return solution.solution_shoulder_left.solution_wrist_down.solution_elbow_up.thetas\n elif config_id == 3:\n return solution.solution_shoulder_left.solution_wrist_down.solution_elbow_down.thetas\n elif config_id == 4:\n return solution.solution_shoulder_right.solution_wrist_up.solution_elbow_up.thetas\n elif config_id == 5:\n return solution.solution_shoulder_right.solution_wrist_up.solution_elbow_down.thetas\n elif config_id == 6:\n return solution.solution_shoulder_right.solution_wrist_down.solution_elbow_up.thetas\n elif config_id == 7:\n return solution.solution_shoulder_right.solution_wrist_down.solution_elbow_down.thetas\n else:\n raise Exception(\"invalid config solution id\")\n\n def get_best_solution_for_config_id(self, T06, config_id):\n solution = self.compute_joint_angles(T06)\n if self.is_valid_solution_by_config_id(solution, config_id):\n return self.get_solution_for_config_id(solution, config_id)\n else:\n index = config_id + 1\n checked_all = False\n while not checked_all:\n if index >= 8:\n index = 0\n if index == config_id:\n print('Found no valid solutions..')\n return None\n if self.is_valid_solution_by_config_id(solution, index):\n return self.get_solution_for_config_id(solution, index)\n index += 1\n\n def is_valid_solution_by_config_id(self, solution, config_id):\n if 0 <= config_id < 4 and solution.solution_shoulder_left.is_valid_solution:\n if 0 <= config_id < 2 and solution.solution_shoulder_left.solution_wrist_up.is_valid_solution:\n if config_id == 0 and solution.solution_shoulder_left.solution_wrist_up.solution_elbow_up.is_valid_solution:\n return True\n if config_id == 1 and solution.solution_shoulder_left.solution_wrist_up.solution_elbow_down.is_valid_solution:\n return True\n if 2 <= config_id < 4 and solution.solution_shoulder_left.solution_wrist_down.is_valid_solution:\n if config_id == 2 and solution.solution_shoulder_left.solution_wrist_down.solution_elbow_up.is_valid_solution:\n return True\n if config_id == 3 and solution.solution_shoulder_left.solution_wrist_down.solution_elbow_down:\n return True\n if 4 <= config_id < 8 and solution.solution_shoulder_right.is_valid_solution:\n if 4 <= config_id < 6 and solution.solution_shoulder_right.solution_wrist_up.is_valid_solution:\n if config_id == 4 and solution.solution_shoulder_right.solution_wrist_up.solution_elbow_up.is_valid_solution:\n return True\n if config_id == 5 and solution.solution_shoulder_right.solution_wrist_up.solution_elbow_down.is_valid_solution:\n return True\n if 6 <= config_id < 8 and solution.solution_shoulder_right.solution_wrist_down.is_valid_solution:\n if config_id == 6 and solution.solution_shoulder_right.solution_wrist_down.solution_elbow_up.is_valid_solution:\n return True\n if config_id == 7 and solution.solution_shoulder_right.solution_wrist_down.solution_elbow_down.is_valid_solution:\n return True\n else:\n return False\n\n\n def get_current_configuration_id(self, joint_angles):\n T06 = self.forward_kinematics.compute_0_to_6_matrix(joint_angles)\n solution = self.compute_joint_angles(T06)\n differences = np.full(8, 1000)\n if solution.solution_shoulder_left.is_valid_solution:\n if solution.solution_shoulder_left.solution_wrist_up.is_valid_solution:\n if solution.solution_shoulder_left.solution_wrist_up.solution_elbow_up.is_valid_solution:\n differences[0] = 0\n if solution.solution_shoulder_left.solution_wrist_up.solution_elbow_down.is_valid_solution:\n differences[1] = 0\n if solution.solution_shoulder_left.solution_wrist_down.is_valid_solution:\n if solution.solution_shoulder_left.solution_wrist_down.solution_elbow_up.is_valid_solution:\n differences[2] = 0\n if solution.solution_shoulder_left.solution_wrist_down.solution_elbow_down:\n differences[3] = 0\n if solution.solution_shoulder_right.is_valid_solution:\n if solution.solution_shoulder_right.solution_wrist_up.is_valid_solution:\n if solution.solution_shoulder_right.solution_wrist_up.solution_elbow_up.is_valid_solution:\n differences[4] = 0\n if solution.solution_shoulder_right.solution_wrist_up.solution_elbow_down.is_valid_solution:\n differences[5] = 0\n if solution.solution_shoulder_right.solution_wrist_down.is_valid_solution:\n if solution.solution_shoulder_right.solution_wrist_down.solution_elbow_up.is_valid_solution:\n differences[6] = 0\n if solution.solution_shoulder_right.solution_wrist_down.solution_elbow_down.is_valid_solution:\n differences[7] = 0\n for i in range(6):\n if solution.solution_shoulder_left.is_valid_solution:\n if solution.solution_shoulder_left.solution_wrist_up.is_valid_solution:\n if solution.solution_shoulder_left.solution_wrist_up.solution_elbow_up.is_valid_solution:\n differences[0] += abs(joint_angles[i] - solution.solution_shoulder_left.solution_wrist_up.solution_elbow_up.thetas[i])\n if solution.solution_shoulder_left.solution_wrist_up.solution_elbow_down.is_valid_solution:\n differences[1] += abs(joint_angles[i] - solution.solution_shoulder_left.solution_wrist_up.solution_elbow_down.thetas[i])\n if solution.solution_shoulder_left.solution_wrist_down.is_valid_solution:\n if solution.solution_shoulder_left.solution_wrist_down.solution_elbow_up.is_valid_solution:\n differences[2] += abs(joint_angles[i] - solution.solution_shoulder_left.solution_wrist_down.solution_elbow_up.thetas[i])\n if solution.solution_shoulder_left.solution_wrist_down.solution_elbow_down:\n differences[3] += abs(joint_angles[i] - solution.solution_shoulder_left.solution_wrist_down.solution_elbow_down.thetas[i])\n if solution.solution_shoulder_right.is_valid_solution:\n if solution.solution_shoulder_right.solution_wrist_up.is_valid_solution:\n if solution.solution_shoulder_right.solution_wrist_up.solution_elbow_up.is_valid_solution:\n differences[4] += abs(joint_angles[i] - solution.solution_shoulder_right.solution_wrist_up.solution_elbow_up.thetas[i])\n if solution.solution_shoulder_right.solution_wrist_up.solution_elbow_down.is_valid_solution:\n differences[5] += abs(joint_angles[i] - solution.solution_shoulder_right.solution_wrist_up.solution_elbow_down.thetas[i])\n if solution.solution_shoulder_right.solution_wrist_down.is_valid_solution:\n if solution.solution_shoulder_right.solution_wrist_down.solution_elbow_up.is_valid_solution:\n differences[6] += abs(joint_angles[i] - solution.solution_shoulder_right.solution_wrist_down.solution_elbow_up.thetas[i])\n if solution.solution_shoulder_right.solution_wrist_down.solution_elbow_down.is_valid_solution:\n differences[7] += abs(joint_angles[i] - solution.solution_shoulder_right.solution_wrist_down.solution_elbow_down.thetas[i])\n print(differences)\n return np.argmin(differences)\n", "import numpy as np\nfrom scipy.spatial.transform import Rotation\n\nclass Utils:\n @staticmethod\n def tmat_to_trans_and_rot(tmat):\n rot_mat = np.array([[tmat[0][0], tmat[0][1], tmat[0][2]],\n [tmat[1][0], tmat[1][1], tmat[1][2]],\n [tmat[2][0], tmat[2][1], tmat[2][2]]])\n trans = np.array([tmat[0][3], tmat[1][3], tmat[2][3]])\n return (trans, Rotation.from_matrix(rot_mat))\n\n @staticmethod\n def trans_and_rot_to_tmat(trans, rot: Rotation):\n rot_mat = rot.as_matrix()\n tmat = [[rot_mat[0][0], rot_mat[0][1], rot_mat[0][2], trans[0]],\n [rot_mat[1][0], rot_mat[1][1], rot_mat[1][2], trans[1]],\n [rot_mat[2][0], rot_mat[2][1], rot_mat[2][2], trans[2]],\n [0, 0, 0, 1]]\n return np.array(tmat)\n\n @staticmethod\n def print_tmat(tmat, name='', format='rotvec'):\n if format == 'rotvec':\n trans, rot = Utils.tmat_to_trans_and_rot(tmat)\n if name != '':\n print(name)\n print(\" translation: \", trans)\n print(\" rotvec: \", rot.as_rotvec())\n elif format == 'matrix':\n if name != '':\n print(name)\n print(np.array(tmat))" ]
[ [ "numpy.array", "numpy.cos", "numpy.sin" ], [ "numpy.dot", "numpy.linalg.inv", "numpy.matmul", "numpy.cos", "numpy.full", "numpy.argmin" ], [ "numpy.array", "scipy.spatial.transform.Rotation.from_matrix" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "1.5", "1.4" ], "tensorflow": [] } ]
omkarudawant/ML-Service
[ "cb612585cbe9619b86c6ea44dd9069a1bc28a8f8" ]
[ "backend/server/apps/ml/income_classifier/extra_trees.py" ]
[ "import joblib\nimport pandas as pd\n\n\nclass ExtraTreesClassifier:\n def __init__(self):\n path_to_artifacts = \"../../research/\"\n self.values_fill_missing = joblib.load(path_to_artifacts +\n \"train_mode.joblib\")\n self.encoders = joblib.load(path_to_artifacts + \"encoders.joblib\")\n self.model = joblib.load(path_to_artifacts + \"extra_trees.joblib\")\n\n def preprocessing(self, input_data):\n # JSON to pandas DataFrame\n input_data = pd.DataFrame(input_data, index=[0])\n # fill missing values\n input_data.fillna(self.values_fill_missing)\n # convert categoricals\n for column in [\n \"workclass\",\n \"education\",\n \"marital-status\",\n \"occupation\",\n \"relationship\",\n \"race\",\n \"sex\",\n \"native-country\",\n ]:\n categorical_convert = self.encoders[column]\n input_data[column] = categorical_convert.transform(\n input_data[column])\n\n return input_data\n\n def predict(self, input_data):\n return self.model.predict_proba(input_data)\n\n def postprocessing(self, input_data):\n label = \"<=50K\"\n if input_data[1] > 0.5:\n label = \">50K\"\n return {\"probability\": input_data[1], \"label\": label, \"status\": \"OK\"}\n\n def compute_prediction(self, input_data):\n try:\n input_data = self.preprocessing(input_data)\n prediction = self.predict(input_data)[0] # only one sample\n prediction = self.postprocessing(prediction)\n except Exception as e:\n return {\"status\": \"Error\", \"message\": str(e)}\n\n return prediction" ]
[ [ "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": [] } ]
rlupat/moanna
[ "81e97b95033a2c1004429c17c41d1c660e62bc83" ]
[ "moanna/helper/SurvivalHelperFunctions.py" ]
[ "def map_label(df, column, mapping):\n df[column] = df[column].replace(mapping)\n return df\n\ndef map_mult_labels(df, columns, labels):\n for column in columns:\n df = map_label(df, labels[column][0], labels[column][1])\n \n return df\n\n#https://stackoverflow.com/questions/26886653/pandas-create-new-column-based-on-values-from-other-columns-apply-a-function-o\ndef surv_event(row, surv_year):\n if row['Event'] in [\"DECEASED\", \"Recurred/Progressed\", \"PROGRESSION\"]:\n if row['Time'] <= surv_year:\n return 1\n else:\n return 0\n else:\n return 0\n \ndef do_survival(clin_df, type_surv, labels_mapping, surv_year=120, filename=\"survival.png\"): #type=[OS, DFS, RFS]\n import pandas as pd\n import matplotlib.pyplot as plt\n\n \n #header = [\"ERStatus\", \"HER2Status\", \"Pam50Subtype\", \"Age\", \"Time\", \"Event\"]\n header = [\"Pam50Subtype\", \"Time\", \"Event\"]\n df_surv = pd.DataFrame(index=clin_df.index, columns=header)\n #df_surv.ERStatus = clin_df.loc[df_surv.index, ['ERStatus']]\n #df_surv.HER2Status = clin_df.loc[df_surv.index, ['HER2Status']]\n df_surv.Pam50Subtype = clin_df.loc[df_surv.index, ['Pam50Subtype']]\n #df_surv.Age = clin_df.loc[df_surv.index, ['Age']]\n if type_surv == \"OS\":\n df_surv.Time = clin_df.loc[df_surv.index, ['OS_MONTHS']]\n df_surv.Event = clin_df.loc[df_surv.index, ['OS_STATUS']]\n elif type_surv == \"DFS\":\n df_surv.Time = clin_df.loc[df_surv.index, ['DFS_MONTHS']]\n df_surv.Event = clin_df.loc[df_surv.index, ['DFS_STATUS']]\n elif type_surv == \"RFS\":\n df_surv.Time = clin_df.loc[df_surv.index, ['RFS_MONTHS']]\n df_surv.Event = clin_df.loc[df_surv.index, ['RFS_STATUS']] \n \n df_surv[\"SurvEvent\"]=df_surv.apply(lambda row: surv_event(row, surv_year), axis=1)\n df_surv.loc[df_surv['Time']>surv_year, 'SurvTime'] = surv_year\n df_surv.loc[df_surv['Time']<=surv_year, 'SurvTime'] = df_surv['Time']\n\n df_surv_final = df_surv.drop(['Time', 'Event'], axis=1)\n print (df_surv_final.shape)\n print (sum(df_surv_final.SurvTime.isna()))\n df_surv_final = df_surv_final[~df_surv_final.SurvTime.isna()]\n print (sum(df_surv_final.SurvTime.isna()))\n print (df_surv_final.shape)\n \n from lifelines import CoxPHFitter\n cph = CoxPHFitter()\n cph.fit(df_surv_final, duration_col='SurvTime', event_col='SurvEvent')\n cph.print_summary() \n \n #cph.plot()\n #cph.plot_covariate_groups('ERStatus', [3,2,1,0])\n \n from lifelines import KaplanMeierFitter\n kmf = KaplanMeierFitter()\n fig = plt.figure(figsize=(10,10))\n ax = plt.subplot(111)\n for name, grouped_df in df_surv_final.groupby('Pam50Subtype'):\n print (name)\n kmf.fit(grouped_df[\"SurvTime\"], grouped_df[\"SurvEvent\"], label=name)\n kmf.plot(ax=ax, ci_show=False, linewidth=4, color=['firebrick', 'hotpink', 'darkblue', 'aqua'][name])\n \n ax.legend(labels_mapping)\n plt.savefig(filename)\n return cph, kmf " ]
[ [ "matplotlib.pyplot.subplot", "matplotlib.pyplot.savefig", "pandas.DataFrame", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
ment911/entsoe-py
[ "67cb4386796c242c112512fbf1f50b68723c861a" ]
[ "entsoe/entsoe.py" ]
[ "import logging\nfrom functools import wraps\nfrom socket import gaierror\nfrom time import sleep\nfrom typing import Union, Optional, Dict\n\nimport pandas as pd\nfrom pandas.tseries.offsets import YearBegin, YearEnd\nimport pytz\nimport requests\nfrom bs4 import BeautifulSoup\n\nfrom entsoe.exceptions import InvalidPSRTypeError, InvalidBusinessParameterError\nfrom .exceptions import NoMatchingDataError, PaginationError\nfrom .mappings import Area, NEIGHBOURS, lookup_area\nfrom .misc import year_blocks, day_blocks\nfrom .parsers import parse_prices, parse_loads, parse_generation, \\\n parse_installed_capacity_per_plant, parse_crossborder_flows, \\\n parse_unavailabilities, parse_contracted_reserve, parse_imbalance_prices_zip, \\\n parse_netpositions, parse_procured_balancing_capacity\n\n__title__ = \"entsoe-py\"\n__version__ = \"0.3.8\"\n__author__ = \"EnergieID.be\"\n__license__ = \"MIT\"\n\nURL = 'https://transparency.entsoe.eu/api'\n\n\ndef retry(func):\n \"\"\"Catches connection errors, waits and retries\"\"\"\n\n @wraps(func)\n def retry_wrapper(*args, **kwargs):\n self = args[0]\n error = None\n for _ in range(self.retry_count):\n try:\n result = func(*args, **kwargs)\n except (requests.ConnectionError, gaierror) as e:\n error = e\n print(\"Connection Error, retrying in {} seconds\".format(\n self.retry_delay))\n sleep(self.retry_delay)\n continue\n else:\n return result\n else:\n raise error\n\n return retry_wrapper\n\n\nclass EntsoeRawClient:\n # noinspection LongLine\n \"\"\"\n Client to perform API calls and return the raw responses API-documentation:\n https://transparency.entsoe.eu/content/static_content/Static%20content/web%20api/Guide.html#_request_methods\n\n Attributions: Parts of the code for parsing Entsoe responses were copied\n from https://github.com/tmrowco/electricitymap\n \"\"\"\n\n def __init__(\n self, api_key: str, session: Optional[requests.Session] = None,\n retry_count: int = 1, retry_delay: int = 0,\n proxies: Optional[Dict] = None, timeout: Optional[int] = None):\n \"\"\"\n Parameters\n ----------\n api_key : str\n session : requests.Session\n retry_count : int\n number of times to retry the call if the connection fails\n retry_delay: int\n amount of seconds to wait between retries\n proxies : dict\n requests proxies\n timeout : int\n \"\"\"\n if api_key is None:\n raise TypeError(\"API key cannot be None\")\n self.api_key = api_key\n if session is None:\n session = requests.Session()\n self.session = session\n self.proxies = proxies\n self.retry_count = retry_count\n self.retry_delay = retry_delay\n self.timeout = timeout\n\n @retry\n def _base_request(self, params: Dict, start: pd.Timestamp,\n end: pd.Timestamp) -> requests.Response:\n \"\"\"\n Parameters\n ----------\n params : dict\n start : pd.Timestamp\n end : pd.Timestamp\n\n Returns\n -------\n requests.Response\n \"\"\"\n start_str = self._datetime_to_str(start)\n end_str = self._datetime_to_str(end)\n\n base_params = {\n 'securityToken': self.api_key,\n 'periodStart': start_str,\n 'periodEnd': end_str\n }\n params.update(base_params)\n\n logging.debug(f'Performing request to {URL} with params {params}')\n response = self.session.get(url=URL, params=params,\n proxies=self.proxies, timeout=self.timeout)\n try:\n response.raise_for_status()\n except requests.HTTPError as e:\n soup = BeautifulSoup(response.text, 'html.parser')\n text = soup.find_all('text')\n if len(text):\n error_text = soup.find('text').text\n if 'No matching data found' in error_text:\n raise NoMatchingDataError\n elif \"check you request against dependency tables\" in error_text:\n raise InvalidBusinessParameterError\n elif \"is not valid for this area\" in error_text:\n raise InvalidPSRTypeError\n elif 'amount of requested data exceeds allowed limit' in error_text:\n requested = error_text.split(' ')[-2]\n allowed = error_text.split(' ')[-5]\n raise PaginationError(\n f\"The API is limited to {allowed} elements per \"\n f\"request. This query requested for {requested} \"\n f\"documents and cannot be fulfilled as is.\")\n raise e\n else:\n return response\n\n @staticmethod\n def _datetime_to_str(dtm: pd.Timestamp) -> str:\n \"\"\"\n Convert a datetime object to a string in UTC\n of the form YYYYMMDDhh00\n\n Parameters\n ----------\n dtm : pd.Timestamp\n Recommended to use a timezone-aware object!\n If timezone-naive, UTC is assumed\n\n Returns\n -------\n str\n \"\"\"\n if dtm.tzinfo is not None and dtm.tzinfo != pytz.UTC:\n dtm = dtm.tz_convert(\"UTC\")\n fmt = '%Y%m%d%H00'\n ret_str = dtm.strftime(fmt)\n return ret_str\n\n def query_day_ahead_prices(self, country_code: Union[Area, str],\n start: pd.Timestamp, end: pd.Timestamp) -> str:\n \"\"\"\n Parameters\n ----------\n country_code : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n\n Returns\n -------\n str\n \"\"\"\n area = lookup_area(country_code)\n params = {\n 'documentType': 'A44',\n 'in_Domain': area.code,\n 'out_Domain': area.code\n }\n response = self._base_request(params=params, start=start, end=end)\n return response.text\n \n def query_net_position_dayahead(self, country_code: Union[Area, str],\n start: pd.Timestamp, end: pd.Timestamp) -> str:\n \"\"\"\n Parameters\n ----------\n country_code : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n\n Returns\n -------\n str\n \"\"\"\n area = lookup_area(country_code)\n params = {\n 'documentType': 'A25', # Allocation result document\n 'businessType': 'B09', # net position\n 'Contract_MarketAgreement.Type': 'A01', # daily\n 'in_Domain': area.code,\n 'out_Domain': area.code\n }\n response = self._base_request(params=params, start=start, end=end)\n return response.text\n\n def query_load(self, country_code: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp) -> str:\n \"\"\"\n Parameters\n ----------\n country_code : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n\n Returns\n -------\n str\n \"\"\"\n area = lookup_area(country_code)\n params = {\n 'documentType': 'A65',\n 'processType': 'A16',\n 'outBiddingZone_Domain': area.code,\n 'out_Domain': area.code\n }\n response = self._base_request(params=params, start=start, end=end)\n return response.text\n\n def query_load_forecast(\n self, country_code: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp, process_type: str = 'A01') -> str:\n \"\"\"\n Parameters\n ----------\n country_code : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n process_type : str\n\n Returns\n -------\n str\n \"\"\"\n area = lookup_area(country_code)\n params = {\n 'documentType': 'A65',\n 'processType': process_type,\n 'outBiddingZone_Domain': area.code,\n # 'out_Domain': domain\n }\n response = self._base_request(params=params, start=start, end=end)\n return response.text\n\n def query_generation_forecast(\n self, country_code: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp, process_type: str = 'A01') -> str:\n \"\"\"\n Parameters\n ----------\n country_code : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n process_type : str\n\n Returns\n -------\n str\n \"\"\"\n area = lookup_area(country_code)\n params = {\n 'documentType': 'A71',\n 'processType': process_type,\n 'in_Domain': area.code,\n }\n response = self._base_request(params=params, start=start, end=end)\n return response.text\n\n def query_wind_and_solar_forecast(\n self, country_code: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp, psr_type: Optional[str] = None,\n process_type: str = 'A01', **kwargs) -> str:\n \"\"\"\n Parameters\n ----------\n country_code : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n psr_type : str\n filter on a single psr type\n process_type : str\n\n Returns\n -------\n str\n \"\"\"\n area = lookup_area(country_code)\n params = {\n 'documentType': 'A69',\n 'processType': process_type,\n 'in_Domain': area.code,\n }\n if psr_type:\n params.update({'psrType': psr_type})\n response = self._base_request(params=params, start=start, end=end)\n return response.text\n\n def query_generation(\n self, country_code: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp, psr_type: Optional[str] = None, **kwargs) -> str:\n \"\"\"\n Parameters\n ----------\n country_code : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n psr_type : str\n filter on a single psr type\n\n Returns\n -------\n str\n \"\"\"\n area = lookup_area(country_code)\n params = {\n 'documentType': 'A75',\n 'processType': 'A16',\n 'in_Domain': area.code,\n }\n if psr_type:\n params.update({'psrType': psr_type})\n response = self._base_request(params=params, start=start, end=end)\n return response.text\n\n def query_generation_per_plant(\n self, country_code: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp, psr_type: Optional[str] = None, **kwargs) -> str:\n \"\"\"\n Parameters\n ----------\n country_code : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n psr_type : str\n filter on a single psr type\n\n Returns\n -------\n str\n \"\"\"\n area = lookup_area(country_code)\n params = {\n 'documentType': 'A73',\n 'processType': 'A16',\n 'in_Domain': area.code,\n }\n if psr_type:\n params.update({'psrType': psr_type})\n response = self._base_request(params=params, start=start, end=end)\n return response.text\n\n def query_installed_generation_capacity(\n self, country_code: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp, psr_type: Optional[str] = None) -> str:\n \"\"\"\n Parameters\n ----------\n country_code : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n psr_type : str\n filter query for a specific psr type\n\n Returns\n -------\n str\n \"\"\"\n area = lookup_area(country_code)\n params = {\n 'documentType': 'A68',\n 'processType': 'A33',\n 'in_Domain': area.code,\n }\n if psr_type:\n params.update({'psrType': psr_type})\n response = self._base_request(params=params, start=start, end=end)\n return response.text\n\n def query_installed_generation_capacity_per_unit(\n self, country_code: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp, psr_type: Optional[str] = None) -> str:\n \"\"\"\n Parameters\n ----------\n country_code : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n psr_type : str\n filter query for a specific psr type\n\n Returns\n -------\n str\n \"\"\"\n area = lookup_area(country_code)\n params = {\n 'documentType': 'A71',\n 'processType': 'A33',\n 'in_Domain': area.code,\n }\n if psr_type:\n params.update({'psrType': psr_type})\n response = self._base_request(params=params, start=start, end=end)\n return response.text\n\n def query_crossborder_flows(\n self, country_code_from: Union[Area, str],\n country_code_to: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp, **kwargs) -> str:\n \"\"\"\n Parameters\n ----------\n country_code_from : Area|str\n country_code_to : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n\n Returns\n -------\n str\n \"\"\"\n return self._query_crossborder(\n country_code_from=country_code_from,\n country_code_to=country_code_to, start=start, end=end,\n doctype=\"A11\", contract_marketagreement_type=None)\n\n def query_scheduled_exchanges(\n self, country_code_from: Union[Area, str],\n country_code_to: Union[Area, str],\n start: pd.Timestamp,\n end: pd.Timestamp,\n dayahead: bool = False,\n **kwargs) -> str:\n \"\"\"\n Parameters\n ----------\n country_code_from : Area|str\n country_code_to : Area|str\n dayahead : bool\n start : pd.Timestamp\n end : pd.Timestamp\n\n Returns\n -------\n str\n \"\"\"\n if dayahead:\n contract_marketagreement_type = \"A01\"\n else:\n contract_marketagreement_type = \"A05\"\n return self._query_crossborder(\n country_code_from=country_code_from,\n country_code_to=country_code_to, start=start, end=end,\n doctype=\"A09\", contract_marketagreement_type=contract_marketagreement_type)\n\n def query_net_transfer_capacity_dayahead(\n self, country_code_from: Union[Area, str],\n country_code_to: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp) -> str:\n \"\"\"\n Parameters\n ----------\n country_code_from : Area|str\n country_code_to : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n\n Returns\n -------\n str\n \"\"\"\n return self._query_crossborder(\n country_code_from=country_code_from,\n country_code_to=country_code_to, start=start, end=end,\n doctype=\"A61\", contract_marketagreement_type=\"A01\")\n\n def query_net_transfer_capacity_weekahead(\n self, country_code_from: Union[Area, str],\n country_code_to: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp) -> str:\n \"\"\"\n Parameters\n ----------\n country_code_from : Area|str\n country_code_to : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n\n Returns\n -------\n str\n \"\"\"\n return self._query_crossborder(\n country_code_from=country_code_from,\n country_code_to=country_code_to, start=start, end=end,\n doctype=\"A61\", contract_marketagreement_type=\"A02\")\n\n def query_net_transfer_capacity_monthahead(\n self, country_code_from: Union[Area, str],\n country_code_to: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp) -> str:\n \"\"\"\n Parameters\n ----------\n country_code_from : Area|str\n country_code_to : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n\n Returns\n -------\n str\n \"\"\"\n return self._query_crossborder(\n country_code_from=country_code_from,\n country_code_to=country_code_to, start=start, end=end,\n doctype=\"A61\", contract_marketagreement_type=\"A03\")\n\n def query_net_transfer_capacity_yearahead(\n self, country_code_from: Union[Area, str],\n country_code_to: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp) -> str:\n \"\"\"\n Parameters\n ----------\n country_code_from : Area|str\n country_code_to : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n\n Returns\n -------\n str\n \"\"\"\n return self._query_crossborder(\n country_code_from=country_code_from,\n country_code_to=country_code_to, start=start, end=end,\n doctype=\"A61\", contract_marketagreement_type=\"A04\")\n \n def query_intraday_offered_capacity(\n self, country_code_from: Union[Area, str],\n country_code_to: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp, implicit:bool = True,**kwargs) -> str:\n \"\"\"\n Parameters\n ----------\n country_code_from : Area|str\n country_code_to : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n implicit: bool (True = implicit - default for most borders. False = explicit - for instance BE-GB)\n\n Returns\n -------\n str\n \"\"\"\n return self._query_crossborder(\n country_code_from=country_code_from,\n country_code_to=country_code_to, start=start, end=end,\n doctype=\"A31\", contract_marketagreement_type=\"A07\",\n auction_type=(\"A01\" if implicit==True else \"A02\"))\n\n\n def _query_crossborder(\n self, country_code_from: Union[Area, str],\n country_code_to: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp, doctype: str,\n contract_marketagreement_type: Optional[str] = None,\n auction_type: Optional[str] = None) -> str:\n \"\"\"\n Generic function called by query_crossborder_flows, \n query_scheduled_exchanges, query_net_transfer_capacity_DA/WA/MA/YA and query_.\n\n Parameters\n ----------\n country_code_from : Area|str\n country_code_to : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n doctype: str\n contract_marketagreement_type: str\n\n Returns\n -------\n str\n \"\"\"\n area_in = lookup_area(country_code_to)\n area_out = lookup_area(country_code_from)\n\n params = {\n 'documentType': doctype,\n 'in_Domain': area_in.code,\n 'out_Domain': area_out.code\n }\n if contract_marketagreement_type is not None:\n params[\n 'contract_MarketAgreement.Type'] = contract_marketagreement_type\n if auction_type is not None:\n params[\n 'Auction.Type'] = auction_type\n\n response = self._base_request(params=params, start=start, end=end)\n return response.text\n\n def query_imbalance_prices(\n self, country_code: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp, psr_type: Optional[str] = None) -> bytes:\n \"\"\"\n Parameters\n ----------\n country_code : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n psr_type : str\n filter query for a specific psr type\n\n Returns\n -------\n bytes\n \"\"\"\n area = lookup_area(country_code)\n params = {\n 'documentType': 'A85',\n 'controlArea_Domain': area.code,\n }\n if psr_type:\n params.update({'psrType': psr_type})\n response = self._base_request(params=params, start=start, end=end)\n return response.content\n\n def query_procured_balancing_capacity(\n self, country_code: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp, process_type: str,\n type_marketagreement_type: Optional[str] = None) -> bytes:\n \"\"\"\n Activated Balancing Energy [17.1.E]\n Parameters\n ----------\n country_code : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n process_type : str\n A51 ... aFRR; A47 ... mFRR\n type_marketagreement_type : str\n type of contract (see mappings.MARKETAGREEMENTTYPE)\n\n Returns\n -------\n bytes\n \"\"\"\n if process_type not in ['A51', 'A47']:\n raise ValueError('processType allowed values: A51, A47')\n\n area = lookup_area(country_code)\n params = {\n 'documentType': 'A15',\n 'area_Domain': area.code,\n 'processType': process_type\n }\n if type_marketagreement_type:\n params.update({'type_MarketAgreement.Type': type_marketagreement_type})\n response = self._base_request(params=params, start=start, end=end)\n return response.content\n\n def query_activated_balancing_energy(\n self, country_code: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp, business_type: str, \n psr_type: Optional[str] = None) -> bytes:\n \"\"\"\n Activated Balancing Energy [17.1.E]\n Parameters\n ----------\n country_code : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n business_type : str\n type of contract (see mappings.BSNTYPE)\n psr_type : str\n filter query for a specific psr type\n\n Returns\n -------\n bytes\n \"\"\"\n area = lookup_area(country_code)\n params = {\n 'documentType': 'A83',\n 'controlArea_Domain': area.code,\n 'businessType': business_type\n }\n if psr_type:\n params.update({'psrType': psr_type})\n response = self._base_request(params=params, start=start, end=end)\n return response.content\n\n def query_contracted_reserve_prices(\n self, country_code: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp, type_marketagreement_type: str,\n psr_type: Optional[str] = None) -> str:\n \"\"\"\n Parameters\n ----------\n country_code : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n type_marketagreement_type : str\n type of contract (see mappings.MARKETAGREEMENTTYPE)\n psr_type : str\n filter query for a specific psr type\n\n Returns\n -------\n str\n \"\"\"\n area = lookup_area(country_code)\n params = {\n 'documentType': 'A89',\n 'controlArea_Domain': area.code,\n 'type_MarketAgreement.Type': type_marketagreement_type,\n }\n if psr_type:\n params.update({'psrType': psr_type})\n response = self._base_request(params=params, start=start, end=end)\n return response.text\n\n def query_contracted_reserve_amount(\n self, country_code: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp, type_marketagreement_type: str,\n psr_type: Optional[str] = None) -> str:\n \"\"\"\n Parameters\n ----------\n country_code : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n type_marketagreement_type : str\n type of contract (see mappings.MARKETAGREEMENTTYPE)\n psr_type : str\n filter query for a specific psr type\n\n Returns\n -------\n str\n \"\"\"\n area = lookup_area(country_code)\n params = {\n 'documentType': 'A81',\n 'controlArea_Domain': area.code,\n 'type_MarketAgreement.Type': type_marketagreement_type,\n }\n if psr_type:\n params.update({'psrType': psr_type})\n response = self._base_request(params=params, start=start, end=end)\n return response.text\n\n def _query_unavailability(\n self, country_code: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp, doctype: str, docstatus: Optional[str] = None,\n periodstartupdate: Optional[pd.Timestamp] = None,\n periodendupdate: Optional[pd.Timestamp] = None) -> bytes:\n \"\"\"\n Generic unavailibility query method.\n This endpoint serves ZIP files.\n The query is limited to 200 items per request.\n\n Parameters\n ----------\n country_code : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n doctype : str\n docstatus : str, optional\n periodstartupdate : pd.Timestamp, optional\n periodendupdate : pd.Timestamp, optional\n\n Returns\n -------\n bytes\n \"\"\"\n area = lookup_area(country_code)\n params = {\n 'documentType': doctype,\n 'biddingZone_domain': area.code\n # ,'businessType': 'A53 (unplanned) | A54 (planned)'\n }\n if docstatus:\n params['docStatus'] = docstatus\n if periodstartupdate and periodendupdate:\n params['periodStartUpdate'] = self._datetime_to_str(\n periodstartupdate)\n params['periodEndUpdate'] = self._datetime_to_str(periodendupdate)\n response = self._base_request(params=params, start=start, end=end)\n return response.content\n\n def query_unavailability_of_generation_units(\n self, country_code: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp, docstatus: Optional[str] = None,\n periodstartupdate: Optional[pd.Timestamp] = None,\n periodendupdate: Optional[pd.Timestamp] = None) -> bytes:\n \"\"\"\n This endpoint serves ZIP files.\n The query is limited to 200 items per request.\n\n Parameters\n ----------\n country_code : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n docstatus : str, optional\n periodstartupdate : pd.Timestamp, optional\n periodendupdate : pd.Timestamp, optional\n\n Returns\n -------\n bytes\n \"\"\"\n content = self._query_unavailability(\n country_code=country_code, start=start, end=end, doctype=\"A80\",\n docstatus=docstatus, periodstartupdate=periodstartupdate,\n periodendupdate=periodendupdate)\n return content\n\n def query_unavailability_of_production_units(\n self, country_code: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp, docstatus: Optional[str] = None,\n periodstartupdate: Optional[pd.Timestamp] = None,\n periodendupdate: Optional[pd.Timestamp] = None) -> bytes:\n \"\"\"\n This endpoint serves ZIP files.\n The query is limited to 200 items per request.\n\n Parameters\n ----------\n country_code : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n docstatus : str, optional\n periodstartupdate : pd.Timestamp, optional\n periodendupdate : pd.Timestamp, optional\n\n Returns\n -------\n bytes\n \"\"\"\n content = self._query_unavailability(\n country_code=country_code, start=start, end=end, doctype=\"A77\",\n docstatus=docstatus, periodstartupdate=periodstartupdate,\n periodendupdate=periodendupdate)\n return content\n\n def query_unavailability_transmission(\n self, country_code_from: Union[Area, str],\n country_code_to: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp, docstatus: Optional[str] = None,\n periodstartupdate: Optional[pd.Timestamp] = None,\n periodendupdate: Optional[pd.Timestamp] = None, **kwargs) -> bytes:\n \"\"\"\n Generic unavailibility query method.\n This endpoint serves ZIP files.\n The query is limited to 200 items per request.\n\n Parameters\n ----------\n country_code_from : Area|str\n country_code_to : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n docstatus : str, optional\n periodstartupdate : pd.Timestamp, optional\n periodendupdate : pd.Timestamp, optional\n\n Returns\n -------\n bytes\n \"\"\"\n area_in = lookup_area(country_code_to)\n area_out = lookup_area(country_code_from)\n params = {\n 'documentType': \"A78\",\n 'in_Domain': area_in.code,\n 'out_Domain': area_out.code\n }\n if docstatus:\n params['docStatus'] = docstatus\n if periodstartupdate and periodendupdate:\n params['periodStartUpdate'] = self._datetime_to_str(\n periodstartupdate)\n params['periodEndUpdate'] = self._datetime_to_str(periodendupdate)\n response = self._base_request(params=params, start=start, end=end)\n return response.content\n\n def query_withdrawn_unavailability_of_generation_units(\n self, country_code: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp) -> bytes:\n \"\"\"\n Parameters\n ----------\n country_code : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n\n Returns\n -------\n bytes\n \"\"\"\n content = self._query_unavailability(\n country_code=country_code, start=start, end=end,\n doctype=\"A80\", docstatus='A13')\n return content\n \n\n\ndef paginated(func):\n \"\"\"Catches a PaginationError, splits the requested period in two and tries\n again. Finally it concatenates the results\"\"\"\n\n @wraps(func)\n def pagination_wrapper(*args, start, end, **kwargs):\n try:\n df = func(*args, start=start, end=end, **kwargs)\n except PaginationError:\n pivot = start + (end - start) / 2\n df1 = pagination_wrapper(*args, start=start, end=pivot, **kwargs)\n df2 = pagination_wrapper(*args, start=pivot, end=end, **kwargs)\n df = pd.concat([df1, df2])\n return df\n\n return pagination_wrapper\n\n\ndef year_limited(func):\n \"\"\"Deals with calls where you cannot query more than a year, by splitting\n the call up in blocks per year\"\"\"\n\n @wraps(func)\n def year_wrapper(*args, start, end, **kwargs):\n blocks = year_blocks(start, end)\n frames = []\n for _start, _end in blocks:\n try:\n frame = func(*args, start=_start, end=_end, **kwargs)\n except NoMatchingDataError:\n logging.debug(f\"NoMatchingDataError: between {_start} and {_end}\")\n frame = None\n frames.append(frame)\n\n if sum([f is None for f in frames]) == len(frames):\n # All the data returned are void\n raise NoMatchingDataError\n\n df = pd.concat(frames, sort=True)\n df = df.loc[~df.index.duplicated(keep='first')]\n return df\n\n return year_wrapper\n\n\ndef day_limited(func):\n \"\"\"Deals with calls where you cannot query more than a year, by splitting\n the call up in blocks per year\"\"\"\n\n @wraps(func)\n def day_wrapper(*args, start, end, **kwargs):\n blocks = day_blocks(start, end)\n frames = []\n for _start, _end in blocks:\n try:\n frame = func(*args, start=_start, end=_end, **kwargs)\n except NoMatchingDataError:\n print(f\"NoMatchingDataError: between {_start} and {_end}\")\n frame = None\n frames.append(frame)\n\n if sum([f is None for f in frames]) == len(frames):\n # All the data returned are void\n raise NoMatchingDataError\n\n df = pd.concat(frames)\n return df\n\n return day_wrapper\n\n\nclass EntsoePandasClient(EntsoeRawClient):\n @year_limited\n def query_net_position_dayahead(self, country_code: Union[Area, str],\n start: pd.Timestamp, end: pd.Timestamp) -> pd.Series:\n \"\"\"\n\n Parameters\n ----------\n country_code\n start\n end\n\n Returns\n -------\n\n \"\"\"\n area = lookup_area(country_code)\n text = super(EntsoePandasClient, self).query_net_position_dayahead(\n country_code=area, start=start, end=end)\n series = parse_netpositions(text)\n series = series.tz_convert(area.tz)\n series = series.truncate(before=start, after=end)\n return series\n\n @year_limited\n def query_day_ahead_prices(\n self, country_code: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp) -> pd.Series:\n \"\"\"\n Parameters\n ----------\n country_code : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n\n Returns\n -------\n pd.Series\n \"\"\"\n area = lookup_area(country_code)\n text = super(EntsoePandasClient, self).query_day_ahead_prices(\n country_code=area, start=start, end=end)\n series = parse_prices(text)\n series = series.tz_convert(area.tz)\n series = series.truncate(before=start, after=end)\n return series\n\n @year_limited\n def query_load(self, country_code: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp) -> pd.Series:\n \"\"\"\n Parameters\n ----------\n country_code : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n\n Returns\n -------\n pd.Series\n \"\"\"\n area = lookup_area(country_code)\n text = super(EntsoePandasClient, self).query_load(\n country_code=area, start=start, end=end)\n series = parse_loads(text)\n series = series.tz_convert(area.tz)\n series = series.truncate(before=start, after=end)\n return series\n\n @year_limited\n def query_load_forecast(\n self, country_code: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp, process_type: str = 'A01') -> pd.DataFrame:\n \"\"\"\n Parameters\n ----------\n country_code : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n process_type : str\n\n Returns\n -------\n pd.DataFrame\n \"\"\"\n area = lookup_area(country_code)\n text = super(EntsoePandasClient, self).query_load_forecast(\n country_code=area, start=start, end=end, process_type=process_type)\n\n df = parse_loads(text, process_type=process_type)\n df = df.tz_convert(area.tz)\n df = df.truncate(before=start, after=end)\n return df\n\n\n @year_limited\n def query_generation_forecast(\n self, country_code: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp, process_type: str = 'A01',\n nett: bool = False) -> Union[pd.DataFrame, pd.Series]:\n \"\"\"\n Parameters\n ----------\n country_code : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n process_type : str\n nett : bool\n condense generation and consumption into a nett number\n\n Returns\n -------\n pd.DataFrame | pd.Series\n \"\"\"\n area = lookup_area(country_code)\n text = super(EntsoePandasClient, self).query_generation_forecast(\n country_code=area, start=start, end=end, process_type=process_type)\n df = parse_generation(text, nett=nett)\n df = df.tz_convert(area.tz)\n df = df.truncate(before=start, after=end)\n return df\n\n @year_limited\n def query_wind_and_solar_forecast(\n self, country_code: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp, psr_type: Optional[str] = None,\n process_type: str = 'A01', **kwargs) -> pd.DataFrame:\n \"\"\"\n Parameters\n ----------\n country_code : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n psr_type : str\n filter on a single psr type\n process_type : str\n\n Returns\n -------\n pd.DataFrame\n \"\"\"\n area = lookup_area(country_code)\n text = super(EntsoePandasClient, self).query_wind_and_solar_forecast(\n country_code=area, start=start, end=end, psr_type=psr_type,\n process_type=process_type)\n df = parse_generation(text, nett=True)\n df = df.tz_convert(area.tz)\n df = df.truncate(before=start, after=end)\n return df\n\n @year_limited\n def query_generation(\n self, country_code: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp, psr_type: Optional[str] = None,\n nett: bool = False, **kwargs) -> pd.DataFrame:\n \"\"\"\n Parameters\n ----------\n country_code : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n psr_type : str\n filter on a single psr type\n nett : bool\n condense generation and consumption into a nett number\n\n Returns\n -------\n pd.DataFrame\n \"\"\"\n area = lookup_area(country_code)\n text = super(EntsoePandasClient, self).query_generation(\n country_code=area, start=start, end=end, psr_type=psr_type)\n df = parse_generation(text, nett=nett)\n df = df.tz_convert(area.tz)\n df = df.truncate(before=start, after=end)\n return df\n\n @year_limited\n def query_installed_generation_capacity(\n self, country_code: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp, psr_type: Optional[str] = None) -> pd.DataFrame:\n \"\"\"\n Parameters\n ----------\n country_code : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n psr_type : str\n filter query for a specific psr type\n\n Returns\n -------\n pd.DataFrame\n \"\"\"\n area = lookup_area(country_code)\n text = super(\n EntsoePandasClient, self).query_installed_generation_capacity(\n country_code=area, start=start, end=end, psr_type=psr_type)\n df = parse_generation(text)\n df = df.tz_convert(area.tz)\n # Truncate to YearBegin and YearEnd, because answer is always year-based\n df = df.truncate(before=start - YearBegin(), after=end + YearEnd())\n return df\n\n @year_limited\n def query_installed_generation_capacity_per_unit(\n self, country_code: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp, psr_type: Optional[str] = None) -> pd.DataFrame:\n \"\"\"\n Parameters\n ----------\n country_code : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n psr_type : str\n filter query for a specific psr type\n\n Returns\n -------\n pd.DataFrame\n \"\"\"\n area = lookup_area(country_code)\n text = super(\n EntsoePandasClient,\n self).query_installed_generation_capacity_per_unit(\n country_code=area, start=start, end=end, psr_type=psr_type)\n df = parse_installed_capacity_per_plant(text)\n return df\n\n @year_limited\n def query_crossborder_flows(\n self, country_code_from: Union[Area, str],\n country_code_to: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp, **kwargs) -> pd.Series:\n \"\"\"\n Note: Result will be in the timezone of the origin country\n\n Parameters\n ----------\n country_code_from : Area|str\n country_code_to : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n\n Returns\n -------\n pd.Series\n \"\"\"\n area_to = lookup_area(country_code_to)\n area_from = lookup_area(country_code_from)\n text = super(EntsoePandasClient, self).query_crossborder_flows(\n country_code_from=area_from,\n country_code_to=area_to,\n start=start,\n end=end)\n ts = parse_crossborder_flows(text)\n ts = ts.tz_convert(area_from.tz)\n ts = ts.truncate(before=start, after=end)\n return ts\n\n @year_limited\n def query_scheduled_exchanges(\n self, country_code_from: Union[Area, str],\n country_code_to: Union[Area, str],\n start: pd.Timestamp,\n end: pd.Timestamp,\n dayahead: bool = False,\n **kwargs) -> pd.Series:\n \"\"\"\n Note: Result will be in the timezone of the origin country\n\n Parameters\n ----------\n country_code_from : Area|str\n country_code_to : Area|str\n dayahead : bool\n start : pd.Timestamp\n end : pd.Timestamp\n\n Returns\n -------\n pd.Series\n \"\"\"\n area_to = lookup_area(country_code_to)\n area_from = lookup_area(country_code_from)\n text = super(EntsoePandasClient, self).query_scheduled_exchanges(\n country_code_from=area_from,\n country_code_to=area_to,\n dayahead=dayahead,\n start=start,\n end=end)\n ts = parse_crossborder_flows(text)\n ts = ts.tz_convert(area_from.tz)\n ts = ts.truncate(before=start, after=end)\n return ts\n\n @year_limited\n def query_net_transfer_capacity_dayahead(\n self, country_code_from: Union[Area, str],\n country_code_to: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp, **kwargs) -> pd.Series:\n \"\"\"\n Note: Result will be in the timezone of the origin country\n\n Parameters\n ----------\n country_code_from : Area|str\n country_code_to : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n\n Returns\n -------\n pd.Series\n \"\"\"\n area_to = lookup_area(country_code_to)\n area_from = lookup_area(country_code_from)\n text = super(EntsoePandasClient, self).query_net_transfer_capacity_dayahead(\n country_code_from=area_from,\n country_code_to=area_to,\n start=start,\n end=end)\n ts = parse_crossborder_flows(text)\n ts = ts.tz_convert(area_from.tz)\n ts = ts.truncate(before=start, after=end)\n return ts\n\n @year_limited\n def query_net_transfer_capacity_weekahead(\n self, country_code_from: Union[Area, str],\n country_code_to: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp, **kwargs) -> pd.Series:\n \"\"\"\n Note: Result will be in the timezone of the origin country\n\n Parameters\n ----------\n country_code_from : Area|str\n country_code_to : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n\n Returns\n -------\n pd.Series\n \"\"\"\n area_to = lookup_area(country_code_to)\n area_from = lookup_area(country_code_from)\n text = super(EntsoePandasClient, self).query_net_transfer_capacity_weekahead(\n country_code_from=area_from,\n country_code_to=area_to,\n start=start,\n end=end)\n ts = parse_crossborder_flows(text)\n ts = ts.tz_convert(area_from.tz)\n ts = ts.truncate(before=start, after=end)\n return ts\n\n @year_limited\n def query_net_transfer_capacity_monthahead(\n self, country_code_from: Union[Area, str],\n country_code_to: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp, **kwargs) -> pd.Series:\n \"\"\"\n Note: Result will be in the timezone of the origin country\n\n Parameters\n ----------\n country_code_from : Area|str\n country_code_to : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n\n Returns\n -------\n pd.Series\n \"\"\"\n area_to = lookup_area(country_code_to)\n area_from = lookup_area(country_code_from)\n text = super(EntsoePandasClient, self).query_net_transfer_capacity_monthahead(\n country_code_from=area_from,\n country_code_to=area_to,\n start=start,\n end=end)\n ts = parse_crossborder_flows(text)\n ts = ts.tz_convert(area_from.tz)\n ts = ts.truncate(before=start, after=end)\n return ts\n \n @year_limited\n def query_net_transfer_capacity_yearahead(\n self, country_code_from: Union[Area, str],\n country_code_to: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp, **kwargs) -> pd.Series:\n \"\"\"\n Note: Result will be in the timezone of the origin country\n\n Parameters\n ----------\n country_code_from : Area|str\n country_code_to : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n\n Returns\n -------\n pd.Series\n \"\"\"\n area_to = lookup_area(country_code_to)\n area_from = lookup_area(country_code_from)\n text = super(EntsoePandasClient, self).query_net_transfer_capacity_yearahead(\n country_code_from=area_from,\n country_code_to=area_to,\n start=start,\n end=end)\n ts = parse_crossborder_flows(text)\n ts = ts.tz_convert(area_from.tz)\n ts = ts.truncate(before=start, after=end)\n return ts\n\n @year_limited\n def query_intraday_offered_capacity(\n self, country_code_from: Union[Area, str],\n country_code_to: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp, implicit:bool = True, **kwargs) -> pd.Series:\n \"\"\"\n Note: Result will be in the timezone of the origin country --> to check\n\n Parameters\n ----------\n country_code_from : Area|str\n country_code_to : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n implicit: bool (True = implicit - default for most borders. False = explicit - for instance BE-GB)\n Returns\n -------\n pd.Series\n \"\"\"\n area_to = lookup_area(country_code_to)\n area_from = lookup_area(country_code_from)\n text = super(EntsoePandasClient, self).query_intraday_offered_capacity(\n country_code_from=area_from,\n country_code_to=area_to,\n start=start,\n end=end,\n implicit=implicit)\n ts = parse_crossborder_flows(text)\n ts = ts.tz_convert(area_from.tz)\n ts = ts.truncate(before=start, after=end)\n return ts\n \n @year_limited\n def query_imbalance_prices(\n self, country_code: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp, psr_type: Optional[str] = None) -> pd.DataFrame:\n \"\"\"\n Parameters\n ----------\n country_code : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n psr_type : str\n filter query for a specific psr type\n\n Returns\n -------\n pd.DataFrame\n \"\"\"\n area = lookup_area(country_code)\n archive = super(EntsoePandasClient, self).query_imbalance_prices(\n country_code=area, start=start, end=end, psr_type=psr_type)\n df = parse_imbalance_prices_zip(zip_contents=archive)\n df = df.tz_convert(area.tz)\n df = df.truncate(before=start, after=end)\n return df\n\n @year_limited\n @paginated\n def query_procured_balancing_capacity(\n self, country_code: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp, process_type: str,\n type_marketagreement_type: Optional[str] = None) -> bytes:\n \"\"\"\n Activated Balancing Energy [17.1.E]\n Parameters\n ----------\n country_code : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n process_type : str\n A51 ... aFRR; A47 ... mFRR\n type_marketagreement_type : str\n type of contract (see mappings.MARKETAGREEMENTTYPE)\n\n Returns\n -------\n pd.DataFrame\n \"\"\"\n area = lookup_area(country_code)\n text = super(EntsoePandasClient, self).query_procured_balancing_capacity(\n country_code=area, start=start, end=end,\n process_type=process_type, type_marketagreement_type=type_marketagreement_type)\n df = parse_procured_balancing_capacity(text, area.tz)\n df = df.tz_convert(area.tz)\n df = df.truncate(before=start, after=end)\n return df\n\n @year_limited\n def query_activated_balancing_energy(\n self, country_code: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp, business_type: str, \n psr_type: Optional[str] = None) -> pd.DataFrame:\n \"\"\"\n Activated Balancing Energy [17.1.E]\n Parameters\n ----------\n country_code : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n business_type: str\n type of contract (see mappings.BSNTYPE)\n psr_type : str\n filter query for a specific psr type\n\n Returns\n -------\n pd.DataFrame\n \"\"\"\n area = lookup_area(country_code)\n text = super(EntsoePandasClient, self).query_activated_balancing_energy(\n country_code=area, start=start, end=end, \n business_type=business_type, psr_type=psr_type)\n df = parse_contracted_reserve(text, area.tz, \"quantity\")\n df = df.tz_convert(area.tz)\n df = df.truncate(before=start, after=end)\n return df\n \n @year_limited\n @paginated\n def query_contracted_reserve_prices(\n self, country_code: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp, type_marketagreement_type: str,\n psr_type: Optional[str] = None) -> pd.DataFrame:\n \"\"\"\n Parameters\n ----------\n country_code : Area, str\n start : pd.Timestamp\n end : pd.Timestamp\n type_marketagreement_type : str\n type of contract (see mappings.MARKETAGREEMENTTYPE)\n psr_type : str\n filter query for a specific psr type\n\n Returns\n -------\n pd.DataFrame\n \"\"\"\n area = lookup_area(country_code)\n text = super(EntsoePandasClient, self).query_contracted_reserve_prices(\n country_code=area, start=start, end=end,\n type_marketagreement_type=type_marketagreement_type,\n psr_type=psr_type)\n df = parse_contracted_reserve(text, area.tz, \"procurement_price.amount\")\n df = df.tz_convert(area.tz)\n df = df.truncate(before=start, after=end)\n return df\n\n @year_limited\n @paginated\n def query_contracted_reserve_amount(\n self, country_code: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp, type_marketagreement_type: str,\n psr_type: Optional[str] = None) -> pd.DataFrame:\n \"\"\"\n Parameters\n ----------\n country_code : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n type_marketagreement_type : str\n type of contract (see mappings.MARKETAGREEMENTTYPE)\n psr_type : str\n filter query for a specific psr type\n\n Returns\n -------\n pd.DataFrame\n \"\"\"\n area = lookup_area(country_code)\n text = super(EntsoePandasClient, self).query_contracted_reserve_amount(\n country_code=area, start=start, end=end,\n type_marketagreement_type=type_marketagreement_type,\n psr_type=psr_type)\n df = parse_contracted_reserve(text, area.tz, \"quantity\")\n df = df.tz_convert(area.tz)\n df = df.truncate(before=start, after=end)\n return df\n\n @year_limited\n @paginated\n def _query_unavailability(\n self, country_code: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp, doctype: str, docstatus: Optional[str] = None,\n periodstartupdate: Optional[pd.Timestamp] = None,\n periodendupdate: Optional[pd.Timestamp] = None) -> pd.DataFrame:\n \"\"\"\n Parameters\n ----------\n country_code : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n doctype : str\n docstatus : str, optional\n periodstartupdate : pd.Timestamp, optional\n periodendupdate : pd.Timestamp, optional\n\n Returns\n -------\n pd.DataFrame\n \"\"\"\n area = lookup_area(country_code)\n content = super(EntsoePandasClient, self)._query_unavailability(\n country_code=area, start=start, end=end, doctype=doctype,\n docstatus=docstatus, periodstartupdate=periodstartupdate,\n periodendupdate=periodendupdate)\n df = parse_unavailabilities(content, doctype)\n df = df.tz_convert(area.tz)\n df['start'] = df['start'].apply(lambda x: x.tz_convert(area.tz))\n df['end'] = df['end'].apply(lambda x: x.tz_convert(area.tz))\n df = df.truncate(before=start, after=end)\n return df\n\n def query_unavailability_of_generation_units(\n self, country_code: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp, docstatus: Optional[str] = None,\n periodstartupdate: Optional[pd.Timestamp] = None,\n periodendupdate: Optional[pd.Timestamp] = None) -> pd.DataFrame:\n \"\"\"\n Parameters\n ----------\n country_code : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n docstatus : str, optional\n periodstartupdate : pd.Timestamp, optional\n periodendupdate : pd.Timestamp, optional\n\n Returns\n -------\n pd.DataFrame\n \"\"\"\n df = self._query_unavailability(\n country_code=country_code, start=start, end=end, doctype=\"A80\",\n docstatus=docstatus, periodstartupdate=periodstartupdate,\n periodendupdate=periodendupdate)\n return df\n\n def query_unavailability_of_production_units(\n self, country_code: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp, docstatus: Optional[str] = None,\n periodstartupdate: Optional[pd.Timestamp] = None,\n periodendupdate: Optional[pd.Timestamp] = None) -> pd.DataFrame:\n \"\"\"\n Parameters\n ----------\n country_code : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n docstatus : str, optional\n periodstartupdate : pd.Timestamp, optional\n periodendupdate : pd.Timestamp, optional\n\n Returns\n -------\n pd.DataFrame\n \"\"\"\n df = self._query_unavailability(\n country_code=country_code, start=start, end=end, doctype=\"A77\",\n docstatus=docstatus, periodstartupdate=periodstartupdate,\n periodendupdate=periodendupdate)\n return df\n\n @paginated\n def query_unavailability_transmission(\n self, country_code_from: Union[Area, str],\n country_code_to: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp, docstatus: Optional[str] = None,\n periodstartupdate: Optional[pd.Timestamp] = None,\n periodendupdate: Optional[pd.Timestamp] = None,\n **kwargs) -> pd.DataFrame:\n \"\"\"\n Parameters\n ----------\n country_code_from : Area|str\n country_code_to : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n docstatus : str, optional\n periodstartupdate : pd.Timestamp, optional\n periodendupdate : pd.Timestamp, optional\n\n Returns\n -------\n pd.DataFrame\n \"\"\"\n area_to = lookup_area(country_code_to)\n area_from = lookup_area(country_code_from)\n content = super(EntsoePandasClient,\n self).query_unavailability_transmission(\n area_from, area_to, start, end, docstatus, periodstartupdate,\n periodendupdate)\n df = parse_unavailabilities(content, \"A78\")\n df = df.tz_convert(area_from.tz)\n df['start'] = df['start'].apply(lambda x: x.tz_convert(area_from.tz))\n df['end'] = df['end'].apply(lambda x: x.tz_convert(area_from.tz))\n df = df.truncate(before=start, after=end)\n return df\n\n def query_withdrawn_unavailability_of_generation_units(\n self, country_code: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp) -> pd.DataFrame:\n \"\"\"\n Parameters\n ----------\n country_code : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n\n Returns\n -------\n pd.DataFrame\n \"\"\"\n df = self.query_unavailability_of_generation_units(\n country_code=country_code, start=start, end=end, docstatus='A13')\n df = df.truncate(before=start, after=end)\n return df\n\n @day_limited\n def query_generation_per_plant(\n self, country_code: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp, psr_type: Optional[str] = None,\n include_eic: bool = False,\n nett: bool = False, **kwargs) -> pd.DataFrame:\n \"\"\"\n Parameters\n ----------\n country_code : Area|str\n start : pd.Timestamp\n end : pd.Timestamp\n psr_type : str\n filter on a single psr type\n nett : bool\n condense generation and consumption into a nett number\n include_eic: bool\n if True also include the eic code in the output\n\n Returns\n -------\n pd.DataFrame\n \"\"\"\n area = lookup_area(country_code)\n text = super(EntsoePandasClient, self).query_generation_per_plant(\n country_code=area, start=start, end=end, psr_type=psr_type)\n df = parse_generation(text, per_plant=True, include_eic=include_eic)\n df.columns = df.columns.set_levels(df.columns.levels[0].str.encode('latin-1').str.decode('utf-8'), level=0)\n df = df.tz_convert(area.tz)\n # Truncation will fail if data is not sorted along the index in rare\n # cases. Ensure the dataframe is sorted:\n df = df.sort_index(0)\n df = df.truncate(before=start, after=end)\n return df\n\n def query_import(self, country_code: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp) -> pd.DataFrame:\n \"\"\"\n Adds together all incoming cross-border flows to a country\n The neighbours of a country are given by the NEIGHBOURS mapping\n \"\"\"\n area = lookup_area(country_code)\n imports = []\n for neighbour in NEIGHBOURS[area.name]:\n try:\n im = self.query_crossborder_flows(country_code_from=neighbour,\n country_code_to=country_code,\n end=end,\n start=start,\n lookup_bzones=True)\n except NoMatchingDataError:\n continue\n im.name = neighbour\n imports.append(im)\n df = pd.concat(imports, axis=1)\n # drop columns that contain only zero's\n df = df.loc[:, (df != 0).any(axis=0)]\n df = df.tz_convert(area.tz)\n df = df.truncate(before=start, after=end)\n return df\n\n def query_generation_import(\n self, country_code: Union[Area, str], start: pd.Timestamp,\n end: pd.Timestamp) -> pd.DataFrame:\n \"\"\"Query the combination of both domestic generation and imports\"\"\"\n generation = self.query_generation(country_code=country_code, end=end,\n start=start, lookup_bzones=True)\n generation = generation.loc[:, (generation != 0).any(\n axis=0)] # drop columns that contain only zero's\n generation = generation.resample('H').sum()\n imports = self.query_import(country_code=country_code, start=start,\n end=end)\n\n data = {f'Generation': generation, f'Import': imports}\n df = pd.concat(data.values(), axis=1, keys=data.keys())\n df = df.truncate(before=start, after=end)\n return df\n\n" ]
[ [ "pandas.tseries.offsets.YearBegin", "pandas.concat", "pandas.tseries.offsets.YearEnd" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "0.19", "0.24", "0.20", "1.0", "0.25" ], "scipy": [], "tensorflow": [] } ]
noemiefedon/BELLA
[ "ca86e5cd6f593478235c64aa4d0409b0e78dbcbb", "ca86e5cd6f593478235c64aa4d0409b0e78dbcbb", "ca86e5cd6f593478235c64aa4d0409b0e78dbcbb" ]
[ "src/BELLA/results.py", "src/BELLA/save_set_up.py", "src/guidelines/test_10_percent_rule.py" ]
[ "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nClass for the results of an optimisation with BELLA\r\nwith several ply-drop layout\r\n\"\"\"\r\n__version__ = '2.0'\r\n__author__ = 'Noemie Fedon'\r\n\r\nimport numpy as np\r\n\r\n#import sys\r\n#sys.path.append(r'C:\\BELLA')\r\n#from src.divers.pretty_print import print_lampam, print_ss, print_list_ss\r\n\r\nclass BELLA_Results():\r\n \" An object for storing the results of an optimisation with BELLA\"\r\n\r\n def __init__(self, constraints, multipanel, parameters=None):\r\n \"Initialise the results of an optimisation with BELLA\"\r\n\r\n if parameters is None:\r\n n_ini_ply_drops = 1\r\n else:\r\n n_ini_ply_drops = parameters.n_ini_ply_drops\r\n\r\n self.penalty_spacing_tab = np.NaN*np.ones((\r\n n_ini_ply_drops,), dtype=float)\r\n\r\n self.obj_constraints_tab = np.NaN*np.ones((\r\n n_ini_ply_drops,), dtype=float)\r\n\r\n self.obj_no_constraints_tab = np.NaN*np.ones((\r\n n_ini_ply_drops, multipanel.n_panels), dtype=float)\r\n\r\n self.penalty_contig_tab = np.NaN*np.ones((\r\n n_ini_ply_drops, multipanel.n_panels), dtype=float)\r\n\r\n self.penalty_diso_tab = np.NaN*np.ones((\r\n n_ini_ply_drops, multipanel.n_panels), dtype=float)\r\n\r\n self.penalty_10_tab = np.NaN*np.ones((\r\n n_ini_ply_drops, multipanel.n_panels), dtype=float)\r\n\r\n self.penalty_bal_ipo_tab = np.NaN*np.ones((\r\n n_ini_ply_drops, multipanel.n_panels), dtype=float)\r\n\r\n self.penalty_oopo_tab = np.NaN*np.ones((\r\n n_ini_ply_drops, multipanel.n_panels), dtype=float)\r\n\r\n self.n_contig_tab = np.NaN*np.ones((\r\n n_ini_ply_drops, multipanel.n_panels), dtype=int)\r\n\r\n self.n_diso_tab = np.NaN*np.ones((\r\n n_ini_ply_drops, multipanel.n_panels), dtype=int)\r\n\r\n self.n_obj_func_calls_tab = np.NaN*np.ones((\r\n n_ini_ply_drops,), int)\r\n\r\n self.n_designs_last_level_tab = np.NaN*np.ones((\r\n n_ini_ply_drops,), int)\r\n\r\n self.n_designs_after_ss_ref_repair_tab = np.NaN*np.ones((\r\n n_ini_ply_drops,), int)\r\n\r\n self.n_designs_after_thick_to_thin_tab = np.NaN*np.ones((\r\n n_ini_ply_drops,), int)\r\n\r\n self.n_designs_after_thin_to_thick_tab = np.NaN*np.ones((\r\n n_ini_ply_drops,), int)\r\n\r\n self.n_designs_repaired_unique_tab = np.NaN*np.ones((\r\n n_ini_ply_drops,), int)\r\n\r\n self.lampam_tab_tab = np.NaN*np.zeros((\r\n multipanel.n_panels, n_ini_ply_drops, 12), float)\r\n\r\n self.n_plies_per_angle_tab = np.NaN*np.zeros((\r\n n_ini_ply_drops, multipanel.n_panels,\r\n constraints.n_set_of_angles), float)\r\n\r\n # Initialisation of the array storing all the best stacking sequence\r\n # solutions: ss_void\r\n ss_void = []\r\n for panel in multipanel.panels:\r\n ss_void.append(np.zeros((panel.n_plies,), dtype=int))\r\n # Initialisation of the array storing all the stacking sequence solutions:\r\n # ss_tab\r\n self.ss_tab = [[]]*(n_ini_ply_drops)\r\n for outer_step in range(n_ini_ply_drops):\r\n self.ss_tab[outer_step] = ss_void\r\n # Initialisation of the array storing all the stacking sequence tables:\r\n # ss_tab_tab\r\n if constraints.sym \\\r\n and multipanel.n_plies_max % 2 == 0 \\\r\n and sum([p.middle_ply_index for p in multipanel.panels]) != 0:\r\n self.ss_tab_tab = np.zeros((\r\n n_ini_ply_drops,\r\n multipanel.n_panels,\r\n multipanel.n_plies_max + 1), dtype=int)\r\n else:\r\n self.ss_tab_tab = np.zeros((\r\n n_ini_ply_drops,\r\n multipanel.n_panels,\r\n multipanel.n_plies_max), dtype=int)\r\n\r\n def update(self, outer_step, results_one_pdl):\r\n \"Update the results from an optimisation with one ply-drop layout\"\r\n if results_one_pdl is not None:\r\n self.ss_tab[outer_step] = results_one_pdl.ss\r\n self.ss_tab_tab[outer_step] = results_one_pdl.sst\r\n \r\n self.lampam_tab_tab[:, outer_step, :] = results_one_pdl.lampam\r\n \r\n self.obj_constraints_tab[\r\n outer_step] = results_one_pdl.obj_constraints\r\n self.obj_no_constraints_tab[\r\n outer_step] = results_one_pdl.obj_no_constraints\r\n \r\n self.penalty_spacing_tab[\r\n outer_step] = results_one_pdl.penalty_spacing\r\n self.penalty_diso_tab[\r\n outer_step] = results_one_pdl.penalty_diso\r\n self.penalty_contig_tab[\r\n outer_step] = results_one_pdl.penalty_contig\r\n self.penalty_10_tab[\r\n outer_step] = results_one_pdl.penalty_10\r\n self.penalty_bal_ipo_tab[\r\n outer_step] = results_one_pdl.penalty_bal_ipo\r\n self.penalty_oopo_tab[\r\n outer_step] = results_one_pdl.penalty_oopo\r\n self.n_diso_tab[outer_step] = results_one_pdl.n_diso\r\n self.n_contig_tab[outer_step] = results_one_pdl.n_contig\r\n \r\n self.n_plies_per_angle_tab[\r\n outer_step] = results_one_pdl.n_plies_per_angle\r\n \r\n self.n_obj_func_calls_tab[\r\n outer_step] = results_one_pdl.n_obj_func_calls\r\n self.n_designs_last_level_tab[\r\n outer_step] = results_one_pdl.n_designs_last_level\r\n self.n_designs_after_ss_ref_repair_tab[\r\n outer_step] = results_one_pdl.n_designs_after_ss_ref_repair\r\n self.n_designs_after_thick_to_thin_tab[\r\n outer_step] = results_one_pdl.n_designs_after_thick_to_thin\r\n self.n_designs_after_thin_to_thick_tab[\r\n outer_step] = results_one_pdl.n_designs_after_thin_to_thick\r\n self.n_designs_repaired_unique_tab[\r\n outer_step] = results_one_pdl.n_designs_repaired_unique\r\n\r\n def __repr__(self):\r\n \" Display object \"\r\n\r\n return '''\r\nResults with BELLA:\r\n '''\r\n\r\nclass BELLA_ResultsOnePdl():\r\n \" An object for storing the results of an optimisation with BELLA\"\r\n\r\n def __init__(self):\r\n \"Initialise the results of an optimisation with BELLA\"\r\n self.ss = None\r\n self.lampam = None\r\n self.n_plies_per_angle = None\r\n self.n_obj_func_calls = None\r\n self.obj_constraints = None\r\n self.obj_no_constraints = None\r\n self.penalty_diso = None\r\n self.penalty_contig = None\r\n self.penalty_10 = None\r\n self.penalty_bal_ipo = None\r\n self.penalty_oopo = None\r\n self.penalty_spacing = None\r\n self.sst = None\r\n self.pdl = None\r\n self.n_designs_last_level = 0\r\n self.n_designs_after_ss_ref_repair = 0\r\n self.n_designs_after_thick_to_thin = 0\r\n self.n_designs_after_thin_to_thick = 0\r\n self.n_designs_repaired_unique = 0\r\n\r\n\r\n def __repr__(self):\r\n \" Display object \"\r\n\r\n return f'''\r\nResults with BELLA:\r\n\r\n***\r\n'''\r\n", "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nFunction to save laminate design set-up\r\n\r\n- save_objective_function_BELLA:\r\n saves the objective function parameters on Sheet [Objective function]\r\n\r\n- save_multipanel:\r\n saves the data of the multipanel structure:\r\n - panel geometry\r\n - panel thickness targets\r\n - panel lamination parameter targets\r\n - lamination parameter first-level sensitivities\r\n - boundaries accross panels\r\n\r\n- save_constraints_BELLA\r\n save the design and manufacturing constraints on Sheet [Constraints]\r\n\r\n- save_parameters_BELLA\r\n saves the optimiser parameters on Sheet [Parameters]\r\n\r\n- save_materials\r\n saves the material properties on Sheet [Materials]\r\n\"\"\"\r\nimport sys\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\nsys.path.append(r'C:\\BELLA')\r\nfrom src.divers.excel import append_df_to_excel\r\nfrom src.CLA.lampam_functions import calc_lampam\r\nfrom src.BELLA.format_pdl import convert_sst_to_ss\r\nfrom src.guidelines.ipo_oopo import calc_penalty_ipo_oopo_mp\r\nfrom src.guidelines.contiguity import calc_penalty_contig_mp\r\nfrom src.guidelines.disorientation import calc_number_violations_diso_mp\r\nfrom src.guidelines.ten_percent_rule import calc_penalty_10_ss\r\nfrom src.guidelines.ply_drop_spacing import calc_penalty_spacing\r\nfrom src.buckling.buckling import buckling_factor\r\n\r\ndef save_materials(filename, materials):\r\n \"\"\"\r\n saves the material properties on Sheet [Materials]\r\n \"\"\"\r\n table_mat = pd.DataFrame()\r\n table_mat.loc[0, 'E11'] = materials.E11\r\n table_mat.loc[0, 'E22'] = materials.E22\r\n table_mat.loc[0, 'G12'] = materials.G12\r\n table_mat.loc[0, 'nu12'] = materials.nu12\r\n table_mat.loc[0, 'nu21'] = materials.nu21\r\n table_mat.loc[0, 'areal density'] = materials.density_area\r\n table_mat.loc[0, 'volumic density'] = materials.density_volume\r\n table_mat.loc[0, 'ply thickness'] = materials.ply_t\r\n\r\n table_mat.loc[0, 'Q11'] = materials.Q11\r\n table_mat.loc[0, 'Q12'] = materials.Q12\r\n table_mat.loc[0, 'Q22'] = materials.Q22\r\n table_mat.loc[0, 'Q66'] = materials.Q66\r\n\r\n table_mat.loc[0, 'U1'] = materials.U1\r\n table_mat.loc[0, 'U2'] = materials.U2\r\n table_mat.loc[0, 'U3'] = materials.U3\r\n table_mat.loc[0, 'U4'] = materials.U4\r\n table_mat.loc[0, 'U5'] = materials.U5\r\n\r\n table_mat = table_mat.transpose()\r\n\r\n append_df_to_excel(\r\n filename, table_mat, 'Materials', index=True, header=False)\r\n\r\n\r\ndef save_multipanel(\r\n filename, multipanel, obj_func_param, sst=None,\r\n calc_penalties=False, constraints=None, mat=None, save_buckling=False):\r\n \"\"\"\r\n saves the data of the multipanel structure:\r\n - panel geometry\r\n - panel thickness targets\r\n - panel lamination-parameter targets\r\n - lamination parameter first-level sensitivities\r\n - boundaries accross panels\r\n - constraints: design guidelines\r\n - sst: stacking sequence table\r\n \"\"\"\r\n table_mp = pd.DataFrame()\r\n table_mp.loc[0, 'Number of panels'] = multipanel.n_panels\r\n table_mp.loc[0, 'Number of plies max'] = multipanel.n_plies_max\r\n table_mp.loc[0, 'Area'] = multipanel.area_patches\r\n table_mp.loc[0, 'Area of all patches'] = multipanel.area_patches\r\n if mat is not None:\r\n table_mp.loc[0, 'Weight'] = multipanel.calc_weight(mat.density_area)\r\n table_mp.loc[0, 'Index of one thickest panel'] = multipanel.ind_thick\r\n table_mp.loc[0, 'Number of plies max'] = multipanel.n_plies_max\r\n\r\n if calc_penalties:\r\n # penalty_spacing\r\n penalty_spacing = calc_penalty_spacing(\r\n pdl=sst,\r\n multipanel=multipanel,\r\n constraints=constraints,\r\n on_blending_strip=False)\r\n table_mp.loc[0, 'Penalty spacing'] = penalty_spacing\r\n\r\n table_mp = table_mp.transpose()\r\n\r\n append_df_to_excel(\r\n filename, table_mp, 'Multipanel', index=True, header=False)\r\n\r\n table_p = pd.DataFrame()\r\n\r\n for ind_p, panel in enumerate(multipanel.panels):\r\n\r\n table_p.loc[ind_p, 'Panel ID'] = panel.ID\r\n table_p.loc[ind_p, 'Neighbour panel IDs'] \\\r\n = \" \".join(np.array(panel.neighbour_panels).astype(str))\r\n table_p.loc[ind_p, 'Number of plies'] = panel.n_plies\r\n\r\n table_p.loc[ind_p, 'Weighting in MP objective funtion'] = panel.weighting\r\n\r\n if panel.length_x and panel.length_y:\r\n table_p.loc[ind_p, 'Length_x'] = panel.length_x\r\n table_p.loc[ind_p, 'Length_y'] = panel.length_y\r\n table_p.loc[ind_p, 'Area'] = panel.area\r\n else:\r\n table_p.loc[ind_p, 'Area'] = panel.area\r\n\r\n if hasattr(panel, 'N_x'):\r\n table_p.loc[ind_p, 'N_x'] = panel.N_x\r\n table_p.loc[ind_p, 'N_y'] = panel.N_y\r\n\r\n if hasattr(panel, 'Weight'):\r\n table_p.loc[ind_p, 'Weight'] = panel.calc_weight(mat.density_area)\r\n\r\n for ind in range(12):\r\n table_p.loc[ind_p, 'lampam_target[' + str(ind + 1) + ']'] \\\r\n = panel.lampam_target[ind]\r\n for ind in range(12):\r\n table_p.loc[ind_p, 'lampam_weightings_ini[' + str(ind + 1) + ']'] \\\r\n = panel.lampam_weightings_ini[ind]\r\n for ind in range(12):\r\n table_p.loc[ind_p, 'lampam_weightings[' + str(ind + 1) + ']'] \\\r\n = panel.lampam_weightings[ind]\r\n\r\n if calc_penalties:\r\n ss = np.array(convert_sst_to_ss(sst))\r\n\r\n norm_diso_contig = np.array(\r\n [panel.n_plies for panel in multipanel.panels])\r\n n_diso = calc_number_violations_diso_mp(ss, constraints)\r\n if constraints.diso and n_diso.any():\r\n penalty_diso = n_diso / norm_diso_contig\r\n else:\r\n penalty_diso = np.zeros((multipanel.n_panels,))\r\n\r\n n_contig = calc_penalty_contig_mp(ss, constraints)\r\n if constraints.contig and n_contig.any():\r\n penalty_contig = n_contig / norm_diso_contig\r\n else:\r\n penalty_contig = np.zeros((multipanel.n_panels,))\r\n\r\n lampam = np.array([calc_lampam(ss[ind_panel]) \\\r\n for ind_panel in range(multipanel.n_panels)])\r\n\r\n if constraints.rule_10_percent and constraints.rule_10_Abdalla:\r\n penalty_10 = calc_penalty_10_ss(ss, constraints, lampam, mp=True)\r\n else:\r\n penalty_10 = calc_penalty_10_ss(ss, constraints, LPs=None)\r\n\r\n penalty_ipo, penalty_oopo = calc_penalty_ipo_oopo_mp(\r\n lampam, constraints)\r\n\r\n for ind_p, panel in enumerate(multipanel.panels):\r\n table_p.loc[ind_p, 'Penalty disorientation'] = penalty_diso[ind_p]\r\n table_p.loc[ind_p, 'Penalty contiguity'] = penalty_contig[ind_p]\r\n table_p.loc[ind_p, 'Penalty disorientation'] = penalty_diso[ind_p]\r\n table_p.loc[ind_p, 'Penalty contiguity'] = penalty_contig[ind_p]\r\n table_p.loc[ind_p, 'Penalty 10% rule'] = penalty_10[ind_p]\r\n table_p.loc[ind_p, 'Penalty balance'] = penalty_ipo[ind_p]\r\n table_p.loc[ind_p, 'Penalty out-of-plane orthotropy'] \\\r\n = penalty_oopo[ind_p]\r\n\r\n if save_buckling:\r\n for ind_p, panel in enumerate(multipanel.panels):\r\n table_p.loc[ind_p, 'lambda buckling'] = buckling_factor(\r\n lampam=panel.lampam_target,\r\n mat=mat,\r\n n_plies=panel.n_plies,\r\n N_x=panel.N_x,\r\n N_y=panel.N_y,\r\n length_x=panel.length_x,\r\n length_y=panel.length_y,\r\n n_modes=10)\r\n\r\n append_df_to_excel(\r\n filename, table_p, 'Panels', index=True, header=True)\r\n return 0\r\n\r\ndef save_constraints_BELLA(filename, constraints):\r\n \"\"\"\r\n saves the design and manufacturing constraints on Sheet [Constraints]\r\n \"\"\"\r\n table_const = pd.DataFrame()\r\n table_const.loc[0, 'symmetry'] = constraints.sym\r\n table_const.loc[0, 'balance'] = constraints.bal\r\n table_const.loc[0, 'out-of-plane orthotropy'] = constraints.oopo\r\n table_const.loc[0, 'damage tolerance'] = constraints.dam_tol\r\n table_const.loc[0, 'dam_tol_rule'] = constraints.dam_tol_rule\r\n table_const.loc[0, 'covering'] = constraints.covering\r\n table_const.loc[0, 'n_covering'] = constraints.n_covering\r\n table_const.loc[0, '10% rule'] = constraints.rule_10_percent\r\n table_const.loc[0, '10% rule applied on LPs'] \\\r\n = constraints.rule_10_percent and constraints.rule_10_Abdalla\r\n table_const.loc[0, '10% rule applied on ply percentages'] \\\r\n = constraints.rule_10_percent and not constraints.rule_10_Abdalla\r\n if constraints.rule_10_percent:\r\n table_const.loc[0, 'percentage limit when rule applied on LPs'] \\\r\n = constraints.percent_Abdalla * 100\r\n table_const.loc[0, 'percent_0'] = constraints.percent_0 * 100\r\n table_const.loc[0, 'percent_45'] = constraints.percent_45 * 100\r\n table_const.loc[0, 'percent_90'] = constraints.percent_90 * 100\r\n table_const.loc[0, 'percent_-45'] = constraints.percent_135 * 100\r\n table_const.loc[0, 'percent_+-45'] = constraints.percent_45_135 * 100\r\n else:\r\n table_const.loc[0, 'percentage limit when rule applied on LPs'] = 0\r\n table_const.loc[0, 'percent_0'] = 0\r\n table_const.loc[0, 'percent_45'] = 0\r\n table_const.loc[0, 'percent_90'] = 0\r\n table_const.loc[0, 'percent_-45'] = 0\r\n table_const.loc[0, 'percent_+-45'] = 0\r\n table_const.loc[0, 'diso'] = constraints.diso\r\n table_const.loc[0, 'delta_angle'] = constraints.delta_angle\r\n table_const.loc[0, 'contig'] = constraints.contig\r\n table_const.loc[0, 'n_contig'] = constraints.n_contig_c\r\n sets = np.array(constraints.set_of_angles, dtype=str)\r\n table_const.loc[0, 'fibre orientations'] = ' '.join(sets)\r\n table_const.loc[0, 'number fibre orientations'] \\\r\n = constraints.n_set_of_angles\r\n # table_const.loc[0, 'n_plies_min'] = constraints.n_plies_min\r\n # table_const.loc[0, 'n_plies_max'] = constraints.n_plies_max\r\n table_const.loc[0, 'ply drop spacing rule'] \\\r\n = constraints.pdl_spacing\r\n table_const.loc[0, 'minimum number of continuous plies between ply drops']\\\r\n = constraints.min_drop\r\n\r\n table_const = table_const.transpose()\r\n\r\n append_df_to_excel(\r\n filename, table_const, 'Constraints', index=True, header=False)\r\n\r\ndef save_parameters_BELLA(filename, parameters):\r\n \"\"\"\r\n saves the optimiser parameters on Sheet [Parameters]\r\n \"\"\"\r\n table_param = pd.DataFrame()\r\n\r\n # Parameters of BELLA step 2\r\n table_param.loc[0, 'number of initial ply drops'] \\\r\n = parameters.n_ini_ply_drops\r\n table_param.loc[0, 'minimum group size'] = parameters.group_size_min\r\n table_param.loc[0, 'maximum group size'] = parameters.group_size_max\r\n table_param.loc[0, 'time_limit_group_pdl'] = parameters.time_limit_group_pdl\r\n table_param.loc[0, 'time_limit_all_pdls'] = parameters.time_limit_all_pdls\r\n table_param.loc[0, 'global_node_limit'] \\\r\n = parameters.global_node_limit\r\n table_param.loc[0, 'global_node_limit_final'] \\\r\n = parameters.global_node_limit_final\r\n table_param.loc[0, 'local_node_limit'] \\\r\n = parameters.local_node_limit\r\n table_param.loc[0, 'local_node_limit_final'] \\\r\n = parameters.local_node_limit_final\r\n\r\n # Parameters of BELLA step 4.1\r\n table_param.loc[0, 'input number of plies in reference panel'] \\\r\n = parameters.n_plies_ref_panel\r\n table_param.loc[0, 'repair_membrane_switch'] \\\r\n = parameters.repair_membrane_switch\r\n table_param.loc[0, 'repair_flexural_switch'] \\\r\n = parameters.repair_flexural_switch\r\n table_param.loc[0, 'p_A'] \\\r\n = parameters.p_A\r\n table_param.loc[0, 'n_D1'] \\\r\n = parameters.n_D1\r\n table_param.loc[0, 'n_D2'] \\\r\n = parameters.n_D2\r\n table_param.loc[0, 'n_D3'] \\\r\n = parameters.n_D3\r\n\r\n # Parameters of BELLA step 4.2\r\n table_param.loc[0, 'global_node_limit2'] \\\r\n = parameters.global_node_limit2\r\n table_param.loc[0, 'local_node_limit2'] \\\r\n = parameters.local_node_limit2\r\n\r\n # Parameters of BELLA step 4.3\r\n table_param.loc[0, 'global_node_limit3'] \\\r\n = parameters.global_node_limit3\r\n table_param.loc[0, 'local_node_limit3'] \\\r\n = parameters.local_node_limit3\r\n\r\n table_param = table_param.transpose()\r\n\r\n append_df_to_excel(\r\n filename, table_param, 'Parameters', index=True, header=False)\r\n\r\n\r\ndef save_objective_function_BELLA(filename, obj_func_param):\r\n \"\"\"\r\n saves the objective function parameters on Sheet [Objective function]\r\n \"\"\"\r\n table_obj_func = pd.DataFrame()\r\n\r\n # General parameters of BELLA\r\n table_obj_func.loc[0, 'optimisation problem'] = \"LP matching\"\r\n\r\n# for ind in range(12):\r\n# table_obj_func.loc[0, 'lampam_weightings[' + str(ind + 1) + ']'] \\\r\n# = obj_func_param.lampam_weightings[ind]\r\n#\r\n# for ind_p in range(obj_func_param.panel_weightings_ini.size):\r\n# table_obj_func.loc[0, 'panel_weightings_ini[' + str(ind_p + 1) + ']'] \\\r\n# = obj_func_param.panel_weightings_ini[ind_p]\r\n\r\n # Penalty coefficients\r\n table_obj_func.loc[0, 'coeff_contig'] = obj_func_param.coeff_contig\r\n table_obj_func.loc[0, 'coeff_diso'] = obj_func_param.coeff_diso\r\n table_obj_func.loc[0, 'coeff_10'] = obj_func_param.coeff_10\r\n table_obj_func.loc[0, 'coeff_bal_ipo'] = obj_func_param.coeff_bal_ipo\r\n table_obj_func.loc[0, 'coeff_oopo'] = obj_func_param.coeff_oopo\r\n table_obj_func.loc[0, 'coeff_spacing'] = obj_func_param.coeff_spacing\r\n\r\n table_obj_func = table_obj_func.transpose()\r\n\r\n append_df_to_excel(filename, table_obj_func, 'Objective function',\r\n index=True, header=False)", "# - * - coding: utf - 8 - * -\r\n\"\"\"\r\nThis module test the functions for the 10% rule.\r\n\"\"\"\r\n__version__ = '1.0'\r\n__author__ = 'Noemie Fedon'\r\n\r\nimport sys\r\nimport numpy as np\r\nimport math as ma\r\nimport pytest\r\n\r\nsys.path.append(r'C:\\BELLA')\r\nfrom src.BELLA.constraints import Constraints\r\nfrom src.guidelines.ten_percent_rule import is_ten_percent_rule\r\nfrom src.guidelines.ten_percent_rule_Abdalla import calc_distance_2_points\r\nfrom src.guidelines.ten_percent_rule_Abdalla import calc_distance_Abdalla\r\n\r\[email protected](\r\n \"\"\"constraints, stack, ply_queue, n_plies_per_angle, equality_45_135,\r\nequality_0_90, expect\"\"\", [\r\n (Constraints(rule_10_percent=True, percent_0=50),\r\n np.array([0, 45, 90], int), [], None, False, False, False),\r\n (Constraints(rule_10_percent=True, percent_0=50),\r\n np.array([0, 45, 90], int), None, None, False, False, False),\r\n (Constraints(rule_10_percent=True, percent_0=50),\r\n np.array([0, 666, 666], int), [0, 45], None, False, False, True),\r\n (Constraints(rule_10_percent=True, percent_0=50),\r\n None, None, np.array([3, 0, 3, 0]), False, False, False),\r\n (Constraints(rule_10_percent=True, percent_0=50),\r\n None, None, np.array([0, 3, 0, 3]), False, False, True)\r\n ])\r\n\r\ndef test_is_ten_percent_rule(\r\n constraints, stack, ply_queue, n_plies_per_angle, equality_45_135,\r\n equality_0_90, expect):\r\n output = is_ten_percent_rule(\r\n constraints, stack, ply_queue, n_plies_per_angle, equality_45_135,\r\n equality_0_90)\r\n assert output == expect\r\n\r\[email protected](\r\n \"\"\"point1, point2, expect\"\"\", [\r\n (np.array([0, 0]), np.array([0, 0]), 0),\r\n (np.array([0, 0]), np.array([0, 2]), 2),\r\n (np.array([0, 0]), np.array([1, 1]), ma.sqrt(2)),\r\n ])\r\n\r\ndef test_calc_distance_2_points(point1, point2, expect):\r\n output = calc_distance_2_points(point1, point2)\r\n assert output == expect\r\n\r\n\r\[email protected](\r\n \"\"\"LPs, constraints, expect\"\"\", [\r\n (np.array([0, 0]), Constraints(rule_10_percent=True,\r\n rule_10_Abdalla=True, percent_Abdalla=10), 0),\r\n (np.array([0, 0.7]), Constraints(rule_10_percent=True,\r\n rule_10_Abdalla=True, percent_Abdalla=10), 0.1),\r\n ])\r\n\r\ndef test_calc_distance_Abdalla(LPs, constraints, expect):\r\n output = calc_distance_Abdalla(LPs, constraints)\r\n assert abs(output - expect) < 1e-5\r\n\r\n\r\n" ]
[ [ "numpy.zeros", "numpy.ones" ], [ "numpy.array", "numpy.zeros", "pandas.DataFrame" ], [ "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
lao-jiu/Facecluster
[ "1603c99ae9f1f1d1d37f60ea30b20dde6cd4568e" ]
[ "workflow/mtcnn_detector.py" ]
[ "# coding: utf-8\nimport os\nimport mxnet as mx\nimport numpy as np\nimport math\nimport cv2\nfrom multiprocessing import Pool\nfrom itertools import repeat\ntry:\n from itertools import izip\nexcept ImportError:\n izip = zip\n\nfrom helper import nms, adjust_input, generate_bbox, detect_first_stage_warpper\n\nclass MtcnnDetector(object):\n \"\"\"\n Joint Face Detection and Alignment using Multi-task Cascaded Convolutional Neural Networks\n see https://github.com/kpzhang93/MTCNN_face_detection_alignment\n this is a mxnet version\n \"\"\"\n def __init__(self,\n model_folder='.',\n minsize = 12,\n threshold = [0.6, 0.7, 0.8],\n factor = 0.709,\n num_worker = 1,\n accurate_landmark = False,\n ctx=mx.cpu()):\n \"\"\"\n Initialize the detector\n\n Parameters:\n ----------\n model_folder : string\n path for the models\n minsize : float number\n minimal face to detect\n threshold : float number\n detect threshold for 3 stages\n factor: float number\n scale factor for image pyramid\n num_worker: int number\n number of processes we use for first stage\n accurate_landmark: bool\n use accurate landmark localization or not\n\n \"\"\"\n self.num_worker = num_worker\n self.accurate_landmark = accurate_landmark\n\n # load 4 models from folder\n models = ['det1', 'det2', 'det3','det4']\n models = [ os.path.join(model_folder, f) for f in models]\n \n self.PNets = []\n for i in range(num_worker):\n workner_net = mx.model.FeedForward.load(models[0], 1, ctx=ctx)\n self.PNets.append(workner_net)\n\n #self.Pool = Pool(num_worker)\n\n self.RNet = mx.model.FeedForward.load(models[1], 1, ctx=ctx)\n self.ONet = mx.model.FeedForward.load(models[2], 1, ctx=ctx)\n self.LNet = mx.model.FeedForward.load(models[3], 1, ctx=ctx)\n\n self.minsize = float(minsize)\n self.factor = float(factor)\n self.threshold = threshold\n\n\n def convert_to_square(self, bbox):\n \"\"\"\n convert bbox to square\n\n Parameters:\n ----------\n bbox: numpy array , shape n x 5\n input bbox\n\n Returns:\n -------\n square bbox\n \"\"\"\n square_bbox = bbox.copy()\n\n h = bbox[:, 3] - bbox[:, 1] + 1\n w = bbox[:, 2] - bbox[:, 0] + 1\n max_side = np.maximum(h,w)\n square_bbox[:, 0] = bbox[:, 0] + w*0.5 - max_side*0.5\n square_bbox[:, 1] = bbox[:, 1] + h*0.5 - max_side*0.5\n square_bbox[:, 2] = square_bbox[:, 0] + max_side - 1\n square_bbox[:, 3] = square_bbox[:, 1] + max_side - 1\n return square_bbox\n\n def calibrate_box(self, bbox, reg):\n \"\"\"\n calibrate bboxes\n\n Parameters:\n ----------\n bbox: numpy array, shape n x 5\n input bboxes\n reg: numpy array, shape n x 4\n bboxex adjustment\n\n Returns:\n -------\n bboxes after refinement\n\n \"\"\"\n w = bbox[:, 2] - bbox[:, 0] + 1\n w = np.expand_dims(w, 1)\n h = bbox[:, 3] - bbox[:, 1] + 1\n h = np.expand_dims(h, 1)\n reg_m = np.hstack([w, h, w, h])\n aug = reg_m * reg\n bbox[:, 0:4] = bbox[:, 0:4] + aug\n return bbox\n\n \n def pad(self, bboxes, w, h):\n \"\"\"\n pad the the bboxes, alse restrict the size of it\n\n Parameters:\n ----------\n bboxes: numpy array, n x 5\n input bboxes\n w: float number\n width of the input image\n h: float number\n height of the input image\n Returns :\n ------s\n dy, dx : numpy array, n x 1\n start point of the bbox in target image\n edy, edx : numpy array, n x 1\n end point of the bbox in target image\n y, x : numpy array, n x 1\n start point of the bbox in original image\n ex, ex : numpy array, n x 1\n end point of the bbox in original image\n tmph, tmpw: numpy array, n x 1\n height and width of the bbox\n\n \"\"\"\n tmpw, tmph = bboxes[:, 2] - bboxes[:, 0] + 1, bboxes[:, 3] - bboxes[:, 1] + 1\n num_box = bboxes.shape[0]\n\n dx , dy= np.zeros((num_box, )), np.zeros((num_box, ))\n edx, edy = tmpw.copy()-1, tmph.copy()-1\n\n x, y, ex, ey = bboxes[:, 0], bboxes[:, 1], bboxes[:, 2], bboxes[:, 3]\n\n tmp_index = np.where(ex > w-1)\n edx[tmp_index] = tmpw[tmp_index] + w - 2 - ex[tmp_index]\n ex[tmp_index] = w - 1\n\n tmp_index = np.where(ey > h-1)\n edy[tmp_index] = tmph[tmp_index] + h - 2 - ey[tmp_index]\n ey[tmp_index] = h - 1\n\n tmp_index = np.where(x < 0)\n dx[tmp_index] = 0 - x[tmp_index]\n x[tmp_index] = 0\n\n tmp_index = np.where(y < 0)\n dy[tmp_index] = 0 - y[tmp_index]\n y[tmp_index] = 0\n\n return_list = [dy, edy, dx, edx, y, ey, x, ex, tmpw, tmph]\n return_list = [item.astype(np.int32) for item in return_list]\n\n return return_list\n\n def slice_index(self, number):\n \"\"\"\n slice the index into (n,n,m), m < n\n Parameters:\n ----------\n number: int number\n number\n \"\"\"\n def chunks(l, n):\n \"\"\"Yield successive n-sized chunks from l.\"\"\"\n for i in range(0, len(l), n):\n yield l[i:i + n]\n num_list = range(number)\n return list(chunks(num_list, self.num_worker))\n \n def detect_face_limited(self, img, det_type=2):\n height, width, _ = img.shape\n if det_type>=2:\n total_boxes = np.array( [ [0.0, 0.0, img.shape[1], img.shape[0], 0.9] ] ,dtype=np.float32)\n num_box = total_boxes.shape[0]\n\n # pad the bbox\n [dy, edy, dx, edx, y, ey, x, ex, tmpw, tmph] = self.pad(total_boxes, width, height)\n # (3, 24, 24) is the input shape for RNet\n input_buf = np.zeros((num_box, 3, 24, 24), dtype=np.float32)\n\n for i in range(num_box):\n tmp = np.zeros((tmph[i], tmpw[i], 3), dtype=np.uint8)\n tmp[dy[i]:edy[i]+1, dx[i]:edx[i]+1, :] = img[y[i]:ey[i]+1, x[i]:ex[i]+1, :]\n input_buf[i, :, :, :] = adjust_input(cv2.resize(tmp, (24, 24)))\n\n output = self.RNet.predict(input_buf)\n\n # filter the total_boxes with threshold\n passed = np.where(output[1][:, 1] > self.threshold[1])\n total_boxes = total_boxes[passed]\n\n if total_boxes.size == 0:\n return None\n\n total_boxes[:, 4] = output[1][passed, 1].reshape((-1,))\n reg = output[0][passed]\n\n # nms\n pick = nms(total_boxes, 0.7, 'Union')\n total_boxes = total_boxes[pick]\n total_boxes = self.calibrate_box(total_boxes, reg[pick])\n total_boxes = self.convert_to_square(total_boxes)\n total_boxes[:, 0:4] = np.round(total_boxes[:, 0:4])\n else:\n total_boxes = np.array( [ [0.0, 0.0, img.shape[1], img.shape[0], 0.9] ] ,dtype=np.float32)\n num_box = total_boxes.shape[0]\n [dy, edy, dx, edx, y, ey, x, ex, tmpw, tmph] = self.pad(total_boxes, width, height)\n # (3, 48, 48) is the input shape for ONet\n input_buf = np.zeros((num_box, 3, 48, 48), dtype=np.float32)\n\n for i in range(num_box):\n tmp = np.zeros((tmph[i], tmpw[i], 3), dtype=np.float32)\n tmp[dy[i]:edy[i]+1, dx[i]:edx[i]+1, :] = img[y[i]:ey[i]+1, x[i]:ex[i]+1, :]\n input_buf[i, :, :, :] = adjust_input(cv2.resize(tmp, (48, 48)))\n\n output = self.ONet.predict(input_buf)\n #print(output[2])\n\n # filter the total_boxes with threshold\n passed = np.where(output[2][:, 1] > self.threshold[2])\n total_boxes = total_boxes[passed]\n\n if total_boxes.size == 0:\n return None\n\n total_boxes[:, 4] = output[2][passed, 1].reshape((-1,))\n reg = output[1][passed]\n points = output[0][passed]\n\n # compute landmark points\n bbw = total_boxes[:, 2] - total_boxes[:, 0] + 1\n bbh = total_boxes[:, 3] - total_boxes[:, 1] + 1\n points[:, 0:5] = np.expand_dims(total_boxes[:, 0], 1) + np.expand_dims(bbw, 1) * points[:, 0:5]\n points[:, 5:10] = np.expand_dims(total_boxes[:, 1], 1) + np.expand_dims(bbh, 1) * points[:, 5:10]\n\n # nms\n total_boxes = self.calibrate_box(total_boxes, reg)\n pick = nms(total_boxes, 0.7, 'Min')\n total_boxes = total_boxes[pick]\n points = points[pick]\n \n if not self.accurate_landmark:\n return total_boxes, points\n\n #############################################\n # extended stage\n #############################################\n num_box = total_boxes.shape[0]\n patchw = np.maximum(total_boxes[:, 2]-total_boxes[:, 0]+1, total_boxes[:, 3]-total_boxes[:, 1]+1)\n patchw = np.round(patchw*0.25)\n\n # make it even\n patchw[np.where(np.mod(patchw,2) == 1)] += 1\n\n input_buf = np.zeros((num_box, 15, 24, 24), dtype=np.float32)\n for i in range(5):\n x, y = points[:, i], points[:, i+5]\n x, y = np.round(x-0.5*patchw), np.round(y-0.5*patchw)\n [dy, edy, dx, edx, y, ey, x, ex, tmpw, tmph] = self.pad(np.vstack([x, y, x+patchw-1, y+patchw-1]).T,\n width,\n height)\n for j in range(num_box):\n tmpim = np.zeros((tmpw[j], tmpw[j], 3), dtype=np.float32)\n tmpim[dy[j]:edy[j]+1, dx[j]:edx[j]+1, :] = img[y[j]:ey[j]+1, x[j]:ex[j]+1, :]\n input_buf[j, i*3:i*3+3, :, :] = adjust_input(cv2.resize(tmpim, (24, 24)))\n\n output = self.LNet.predict(input_buf)\n\n pointx = np.zeros((num_box, 5))\n pointy = np.zeros((num_box, 5))\n\n for k in range(5):\n # do not make a large movement\n tmp_index = np.where(np.abs(output[k]-0.5) > 0.35)\n output[k][tmp_index[0]] = 0.5\n\n pointx[:, k] = np.round(points[:, k] - 0.5*patchw) + output[k][:, 0]*patchw\n pointy[:, k] = np.round(points[:, k+5] - 0.5*patchw) + output[k][:, 1]*patchw\n\n points = np.hstack([pointx, pointy])\n points = points.astype(np.int32)\n\n return total_boxes, points\n\n def detect_face(self, img, det_type=0):\n \"\"\"\n detect face over img\n Parameters:\n ----------\n img: numpy array, bgr order of shape (1, 3, n, m)\n input image\n Retures:\n -------\n bboxes: numpy array, n x 5 (x1,y2,x2,y2,score)\n bboxes\n points: numpy array, n x 10 (x1, x2 ... x5, y1, y2 ..y5)\n landmarks\n \"\"\"\n\n # check input\n height, width, _ = img.shape\n if det_type==0:\n MIN_DET_SIZE = 12\n\n if img is None:\n return None\n\n # only works for color image\n if len(img.shape) != 3:\n return None\n\n # detected boxes\n total_boxes = []\n\n minl = min( height, width)\n\n # get all the valid scales\n scales = []\n m = MIN_DET_SIZE/self.minsize\n minl *= m\n factor_count = 0\n while minl > MIN_DET_SIZE:\n scales.append(m*self.factor**factor_count)\n minl *= self.factor\n factor_count += 1\n\n #############################################\n # first stage\n #############################################\n #for scale in scales:\n # return_boxes = self.detect_first_stage(img, scale, 0)\n # if return_boxes is not None:\n # total_boxes.append(return_boxes)\n \n sliced_index = self.slice_index(len(scales))\n total_boxes = []\n for batch in sliced_index:\n #local_boxes = self.Pool.map( detect_first_stage_warpper, \\\n # izip(repeat(img), self.PNets[:len(batch)], [scales[i] for i in batch], repeat(self.threshold[0])) )\n local_boxes = map( detect_first_stage_warpper, \\\n izip(repeat(img), self.PNets[:len(batch)], [scales[i] for i in batch], repeat(self.threshold[0])) )\n total_boxes.extend(local_boxes)\n \n # remove the Nones \n total_boxes = [ i for i in total_boxes if i is not None]\n\n if len(total_boxes) == 0:\n return None\n \n total_boxes = np.vstack(total_boxes)\n\n if total_boxes.size == 0:\n return None\n\n # merge the detection from first stage\n pick = nms(total_boxes[:, 0:5], 0.7, 'Union')\n total_boxes = total_boxes[pick]\n\n bbw = total_boxes[:, 2] - total_boxes[:, 0] + 1\n bbh = total_boxes[:, 3] - total_boxes[:, 1] + 1\n\n # refine the bboxes\n total_boxes = np.vstack([total_boxes[:, 0]+total_boxes[:, 5] * bbw,\n total_boxes[:, 1]+total_boxes[:, 6] * bbh,\n total_boxes[:, 2]+total_boxes[:, 7] * bbw,\n total_boxes[:, 3]+total_boxes[:, 8] * bbh,\n total_boxes[:, 4]\n ])\n\n total_boxes = total_boxes.T\n total_boxes = self.convert_to_square(total_boxes)\n total_boxes[:, 0:4] = np.round(total_boxes[:, 0:4])\n else:\n total_boxes = np.array( [ [0.0, 0.0, img.shape[1], img.shape[0], 0.9] ] ,dtype=np.float32)\n\n #############################################\n # second stage\n #############################################\n num_box = total_boxes.shape[0]\n\n # pad the bbox\n [dy, edy, dx, edx, y, ey, x, ex, tmpw, tmph] = self.pad(total_boxes, width, height)\n # (3, 24, 24) is the input shape for RNet\n input_buf = np.zeros((num_box, 3, 24, 24), dtype=np.float32)\n\n for i in range(num_box):\n tmp = np.zeros((tmph[i], tmpw[i], 3), dtype=np.uint8)\n tmp[dy[i]:edy[i]+1, dx[i]:edx[i]+1, :] = img[y[i]:ey[i]+1, x[i]:ex[i]+1, :]\n input_buf[i, :, :, :] = adjust_input(cv2.resize(tmp, (24, 24)))\n\n output = self.RNet.predict(input_buf)\n\n # filter the total_boxes with threshold\n passed = np.where(output[1][:, 1] > self.threshold[1])\n total_boxes = total_boxes[passed]\n\n if total_boxes.size == 0:\n return None\n\n total_boxes[:, 4] = output[1][passed, 1].reshape((-1,))\n reg = output[0][passed]\n\n # nms\n pick = nms(total_boxes, 0.7, 'Union')\n total_boxes = total_boxes[pick]\n total_boxes = self.calibrate_box(total_boxes, reg[pick])\n total_boxes = self.convert_to_square(total_boxes)\n total_boxes[:, 0:4] = np.round(total_boxes[:, 0:4])\n\n #############################################\n # third stage\n #############################################\n num_box = total_boxes.shape[0]\n\n # pad the bbox\n [dy, edy, dx, edx, y, ey, x, ex, tmpw, tmph] = self.pad(total_boxes, width, height)\n # (3, 48, 48) is the input shape for ONet\n input_buf = np.zeros((num_box, 3, 48, 48), dtype=np.float32)\n\n for i in range(num_box):\n tmp = np.zeros((tmph[i], tmpw[i], 3), dtype=np.float32)\n tmp[dy[i]:edy[i]+1, dx[i]:edx[i]+1, :] = img[y[i]:ey[i]+1, x[i]:ex[i]+1, :]\n input_buf[i, :, :, :] = adjust_input(cv2.resize(tmp, (48, 48)))\n\n output = self.ONet.predict(input_buf)\n\n # filter the total_boxes with threshold\n passed = np.where(output[2][:, 1] > self.threshold[2])\n total_boxes = total_boxes[passed]\n\n if total_boxes.size == 0:\n return None\n\n total_boxes[:, 4] = output[2][passed, 1].reshape((-1,))\n reg = output[1][passed]\n points = output[0][passed]\n\n # compute landmark points\n bbw = total_boxes[:, 2] - total_boxes[:, 0] + 1\n bbh = total_boxes[:, 3] - total_boxes[:, 1] + 1\n points[:, 0:5] = np.expand_dims(total_boxes[:, 0], 1) + np.expand_dims(bbw, 1) * points[:, 0:5]\n points[:, 5:10] = np.expand_dims(total_boxes[:, 1], 1) + np.expand_dims(bbh, 1) * points[:, 5:10]\n\n # nms\n total_boxes = self.calibrate_box(total_boxes, reg)\n pick = nms(total_boxes, 0.7, 'Min')\n total_boxes = total_boxes[pick]\n points = points[pick]\n \n if not self.accurate_landmark:\n return total_boxes, points\n\n #############################################\n # extended stage\n #############################################\n num_box = total_boxes.shape[0]\n patchw = np.maximum(total_boxes[:, 2]-total_boxes[:, 0]+1, total_boxes[:, 3]-total_boxes[:, 1]+1)\n patchw = np.round(patchw*0.25)\n\n # make it even\n patchw[np.where(np.mod(patchw,2) == 1)] += 1\n\n input_buf = np.zeros((num_box, 15, 24, 24), dtype=np.float32)\n for i in range(5):\n x, y = points[:, i], points[:, i+5]\n x, y = np.round(x-0.5*patchw), np.round(y-0.5*patchw)\n [dy, edy, dx, edx, y, ey, x, ex, tmpw, tmph] = self.pad(np.vstack([x, y, x+patchw-1, y+patchw-1]).T,\n width,\n height)\n for j in range(num_box):\n tmpim = np.zeros((tmpw[j], tmpw[j], 3), dtype=np.float32)\n tmpim[dy[j]:edy[j]+1, dx[j]:edx[j]+1, :] = img[y[j]:ey[j]+1, x[j]:ex[j]+1, :]\n input_buf[j, i*3:i*3+3, :, :] = adjust_input(cv2.resize(tmpim, (24, 24)))\n\n output = self.LNet.predict(input_buf)\n\n pointx = np.zeros((num_box, 5))\n pointy = np.zeros((num_box, 5))\n\n for k in range(5):\n # do not make a large movement\n tmp_index = np.where(np.abs(output[k]-0.5) > 0.35)\n output[k][tmp_index[0]] = 0.5\n\n pointx[:, k] = np.round(points[:, k] - 0.5*patchw) + output[k][:, 0]*patchw\n pointy[:, k] = np.round(points[:, k+5] - 0.5*patchw) + output[k][:, 1]*patchw\n\n points = np.hstack([pointx, pointy])\n points = points.astype(np.int32)\n\n return total_boxes, points\n\n\n\n def list2colmatrix(self, pts_list):\n \"\"\"\n convert list to column matrix\n Parameters:\n ----------\n pts_list:\n input list\n Retures:\n -------\n colMat: \n\n \"\"\"\n assert len(pts_list) > 0\n colMat = []\n for i in range(len(pts_list)):\n colMat.append(pts_list[i][0])\n colMat.append(pts_list[i][1])\n colMat = np.matrix(colMat).transpose()\n return colMat\n\n def find_tfrom_between_shapes(self, from_shape, to_shape):\n \"\"\"\n find transform between shapes\n Parameters:\n ----------\n from_shape: \n to_shape: \n Retures:\n -------\n tran_m:\n tran_b:\n \"\"\"\n assert from_shape.shape[0] == to_shape.shape[0] and from_shape.shape[0] % 2 == 0\n\n sigma_from = 0.0\n sigma_to = 0.0\n cov = np.matrix([[0.0, 0.0], [0.0, 0.0]])\n\n # compute the mean and cov\n from_shape_points = from_shape.reshape(from_shape.shape[0]/2, 2)\n to_shape_points = to_shape.reshape(to_shape.shape[0]/2, 2)\n mean_from = from_shape_points.mean(axis=0)\n mean_to = to_shape_points.mean(axis=0)\n\n for i in range(from_shape_points.shape[0]):\n temp_dis = np.linalg.norm(from_shape_points[i] - mean_from)\n sigma_from += temp_dis * temp_dis\n temp_dis = np.linalg.norm(to_shape_points[i] - mean_to)\n sigma_to += temp_dis * temp_dis\n cov += (to_shape_points[i].transpose() - mean_to.transpose()) * (from_shape_points[i] - mean_from)\n\n sigma_from = sigma_from / to_shape_points.shape[0]\n sigma_to = sigma_to / to_shape_points.shape[0]\n cov = cov / to_shape_points.shape[0]\n\n # compute the affine matrix\n s = np.matrix([[1.0, 0.0], [0.0, 1.0]])\n u, d, vt = np.linalg.svd(cov)\n\n if np.linalg.det(cov) < 0:\n if d[1] < d[0]:\n s[1, 1] = -1\n else:\n s[0, 0] = -1\n r = u * s * vt\n c = 1.0\n if sigma_from != 0:\n c = 1.0 / sigma_from * np.trace(np.diag(d) * s)\n\n tran_b = mean_to.transpose() - c * r * mean_from.transpose()\n tran_m = c * r\n\n return tran_m, tran_b\n\n def extract_image_chips(self, img, points, desired_size=256, padding=0):\n \"\"\"\n crop and align face\n Parameters:\n ----------\n img: numpy array, bgr order of shape (1, 3, n, m)\n input image\n points: numpy array, n x 10 (x1, x2 ... x5, y1, y2 ..y5)\n desired_size: default 256\n padding: default 0\n Retures:\n -------\n crop_imgs: list, n\n cropped and aligned faces \n \"\"\"\n crop_imgs = []\n for p in points:\n shape =[]\n for k in range(len(p)/2):\n shape.append(p[k])\n shape.append(p[k+5])\n\n if padding > 0:\n padding = padding\n else:\n padding = 0\n # average positions of face points\n mean_face_shape_x = [0.224152, 0.75610125, 0.490127, 0.254149, 0.726104]\n mean_face_shape_y = [0.2119465, 0.2119465, 0.628106, 0.780233, 0.780233]\n\n from_points = []\n to_points = []\n\n for i in range(len(shape)/2):\n x = (padding + mean_face_shape_x[i]) / (2 * padding + 1) * desired_size\n y = (padding + mean_face_shape_y[i]) / (2 * padding + 1) * desired_size\n to_points.append([x, y])\n from_points.append([shape[2*i], shape[2*i+1]])\n\n # convert the points to Mat\n from_mat = self.list2colmatrix(from_points)\n to_mat = self.list2colmatrix(to_points)\n\n # compute the similar transfrom\n tran_m, tran_b = self.find_tfrom_between_shapes(from_mat, to_mat)\n\n probe_vec = np.matrix([1.0, 0.0]).transpose()\n probe_vec = tran_m * probe_vec\n\n scale = np.linalg.norm(probe_vec)\n angle = 180.0 / math.pi * math.atan2(probe_vec[1, 0], probe_vec[0, 0])\n\n from_center = [(shape[0]+shape[2])/2.0, (shape[1]+shape[3])/2.0]\n to_center = [0, 0]\n to_center[1] = desired_size * 0.4\n to_center[0] = desired_size * 0.5\n\n ex = to_center[0] - from_center[0]\n ey = to_center[1] - from_center[1]\n\n rot_mat = cv2.getRotationMatrix2D((from_center[0], from_center[1]), -1*angle, scale)\n rot_mat[0][2] += ex\n rot_mat[1][2] += ey\n\n chips = cv2.warpAffine(img, rot_mat, (desired_size, desired_size))\n crop_imgs.append(chips)\n\n return crop_imgs\n\n" ]
[ [ "numpy.matrix", "numpy.hstack", "numpy.linalg.svd", "numpy.expand_dims", "numpy.maximum", "numpy.abs", "numpy.diag", "numpy.vstack", "numpy.linalg.norm", "numpy.round", "numpy.linalg.det", "numpy.mod", "numpy.array", "numpy.where", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
braineniac/adapt_kalman
[ "a29a0740420959d2221d548a414031c17fa25cf8" ]
[ "scripts/experiments.py" ]
[ "#!/usr/bin/env python\n\n# Copyright (c) 2019 Daniel Hammer. 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\nfrom matplotlib import pyplot as plt\n\nfrom kalman_estimator import KalmanFilter\nfrom kalman_estimator import SysIO, KalmanEstimator\nfrom kalman_estimator import StateEstimator, EstimationPlots\n\n\nclass Experiment(object):\n\n def __init__(self,\n sys_IO=None,\n kalman_filter=None,\n slice=(0, np.inf), legend=[]):\n if not isinstance(sys_IO, SysIO):\n raise ValueError(\"Passed bag_sys_IO not a BagSysIO!\")\n if not isinstance(kalman_filter, KalmanFilter):\n raise ValueError(\"Passed kalman_filter not a KalmanFilter!\")\n self._sys_IO = sys_IO\n self._kalman_filter = kalman_filter\n self._slice = slice\n self._legend = legend\n\n def _get_estimation(self):\n state_estimator = KalmanEstimator(self._kalman_filter)\n state_estimator.set_stamped_input(self._sys_IO.get_input())\n state_estimator.set_stamped_output(self._sys_IO.get_output())\n return state_estimator\n\n def get_estimation_plots(self):\n estimation = self._get_estimation()\n estimation_plotter = EstimationPlots(estimation,\n self._slice, self._legend)\n return estimation_plotter\n\n\nclass NoRotationExperiment(Experiment):\n def __init__(self,\n sys_io=None,\n kalman_filter=None,\n slice=(0, np.inf), legend=[]):\n super(NoRotationExperiment, self).__init__(sys_io,\n kalman_filter,\n slice, legend)\n\n def _get_estimation(self):\n state_estimator = KalmanEstimator(self._kalman_filter)\n state_estimator.set_stamped_input(self._sys_IO.get_input())\n state_estimator.set_stamped_output(self._sys_IO.get_output())\n state_estimator.set_u1y1_zero()\n return state_estimator\n\n\nclass SimExperiment(Experiment):\n\n def __init__(self,\n sim=None,\n slice=(0, np.inf), legend=[]):\n self._sim = sim\n self._slice = slice\n self._legend = legend\n\n def _get_estimation(self):\n state_estimator = StateEstimator()\n state_estimator.set_stamped_input(self._sim.get_input())\n state_estimator.set_stamped_output(self._sim.get_output())\n state_estimator.set_stamped_states(self._sim.get_states())\n state_estimator.set_stamped_Q(self._sim.get_Q())\n return state_estimator\n\n\nclass ExperimentSuite(object):\n\n def __init__(self, name=\"\"):\n self._name = name\n self._experiments = []\n\n def plot(self):\n experiment_plotter = ExperimentPlotter(self._experiments)\n experiment_plotter.plot()\n\n def export(self):\n for i in range(len(self._experiments)):\n estimation_plots = self._experiments[i].get_estimation_plots()\n estimation_plots.export_input(self._name + str(i) + \"_\")\n estimation_plots.export_output(self._name + str(i) + \"_\")\n estimation_plots.export_states(self._name + str(i) + \"_\")\n estimation_plots.export_x0x1(self._name + str(i) + \"_\")\n estimation_plots.export_Q(self._name + str(i) + \"_\")\n\n\nclass ExperimentPlotter(object):\n figure = 1\n\n @staticmethod\n def add_figure():\n plt.figure(ExperimentPlotter.figure)\n ExperimentPlotter.figure += 1\n\n @staticmethod\n def _add_plot(stamped_plot=None, dimension=None, option=None, legend=None):\n if not stamped_plot:\n raise ValueError\n else:\n t, plot = stamped_plot\n if dimension is not None:\n plot = plot[dimension]\n if not option or not legend:\n plt.plot(t, plot)\n else:\n plt.plot(t, plot, option, label=legend)\n plt.legend()\n\n def __init__(self, experiments=None):\n if not isinstance(experiments, list):\n raise ValueError(\"Pass a list of Experiment!\")\n if not all(isinstance(exp, Experiment) for exp in experiments):\n raise ValueError(\"Pass a list only containing Experiment!\")\n self._experiments = experiments\n self._all_estimation_plots = []\n self._options = [\"b\", \"r\", \"k\", \"m\", \"g\"]\n\n def plot(self):\n for experiment in self._experiments:\n estimation_plots = experiment.get_estimation_plots()\n self._all_estimation_plots.append(estimation_plots)\n self._plot_input_figure()\n self._plot_output_figure()\n self._plot_states_figure()\n self._plot_xy_state_figure()\n self._plot_Q_figure()\n plt.show()\n\n def _plot_input_figure(self):\n self.add_figure()\n input_titles = self._all_estimation_plots[0].get_input_titles()\n for i in range(len(input_titles)):\n plt.subplot(len(input_titles) * 100 + 10 + 1 + i)\n plt.ylabel(input_titles[i])\n plt.xlabel(\"Time [s]\")\n for estimation_plots, option in \\\n zip(self._all_estimation_plots, self._options):\n legend = estimation_plots.get_legend()\n self._add_plot(estimation_plots.get_input_plot(),\n i,\n option,\n legend)\n\n def _plot_output_figure(self):\n self.add_figure()\n output_titles = self._all_estimation_plots[0].get_output_titles()\n for i in range(len(output_titles)):\n plt.subplot(len(output_titles) * 100 + 10 + 1 + i)\n plt.ylabel(output_titles[i])\n plt.xlabel(\"Time [s]\")\n for estimation_plots, option in \\\n zip(self._all_estimation_plots, self._options):\n legend = estimation_plots.get_legend()\n self._add_plot(estimation_plots.get_output_plot(),\n i,\n option,\n legend)\n\n def _plot_states_figure(self):\n self.add_figure()\n states_titles = self._all_estimation_plots[0].get_states_titles()\n for i in range(len(states_titles)):\n plt.subplot(len(states_titles) * 100 + 10 + 1 + i)\n plt.ylabel(states_titles[i])\n plt.xlabel(\"Time [s]\")\n for estimation_plots, option in \\\n zip(self._all_estimation_plots, self._options):\n legend = estimation_plots.get_legend()\n self._add_plot(estimation_plots.get_states_plot(),\n i,\n option,\n legend)\n\n def _plot_xy_state_figure(self):\n self.add_figure()\n plt.xlabel(\"x\")\n plt.ylabel(\"y\")\n for estimation_plots, option in \\\n zip(self._all_estimation_plots, self._options):\n legend = estimation_plots.get_legend()\n self._add_plot(estimation_plots.get_x0x1_plot(),\n None,\n option,\n legend)\n\n def _plot_Q_figure(self):\n self.add_figure()\n Q_titles = self._all_estimation_plots[0].get_Q_titles()\n for i in range(len(Q_titles)):\n plt.subplot(len(Q_titles) * 100 + 10 + 1 + i)\n plt.xlabel(\"Time [s]\")\n plt.ylabel(Q_titles[i])\n for estimation_plots, option in \\\n zip(self._all_estimation_plots, self._options):\n legend = estimation_plots.get_legend()\n self._add_plot(estimation_plots.get_Q_plot(),\n i,\n option,\n legend)\n" ]
[ [ "matplotlib.pyplot.legend", "matplotlib.pyplot.figure", "matplotlib.pyplot.plot", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
gbmarc1/Ax
[ "9428fa64a621cf4562c7e2c63881a0ca2fa2780b", "9428fa64a621cf4562c7e2c63881a0ca2fa2780b", "9428fa64a621cf4562c7e2c63881a0ca2fa2780b" ]
[ "setup.py", "ax/plot/helper.py", "ax/benchmark/benchmark_runner.py" ]
[ "#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n\nimport subprocess\n\nimport numpy\nfrom Cython.Build import cythonize\nfrom setuptools import find_packages, setup\nfrom setuptools.extension import Extension\n\n\nEXTENSIONS = [\n Extension(\n \"ax.utils.stats.sobol\",\n [\"ax/utils/stats/sobol.pyx\"],\n include_dirs=[numpy.get_include()],\n )\n]\n\nREQUIRES = [\n \"botorch>=0.1.3\",\n \"jinja2\", # also a Plotly dep\n \"pandas\",\n \"scipy\",\n \"sklearn\",\n \"plotly\",\n]\n\n# pytest-cov requires pytest >= 3.6\nDEV_REQUIRES = [\n \"beautifulsoup4\",\n \"black\",\n \"flake8\",\n \"pytest>=3.6\",\n \"pytest-cov\",\n \"sphinx\",\n \"sphinx-autodoc-typehints\",\n]\n\nMYSQL_REQUIRES = [\"SQLAlchemy>=1.1.13\"]\n\nNOTEBOOK_REQUIRES = [\"jupyter\"]\n\n\ndef get_git_version(abbreviate: bool = False) -> str:\n \"\"\"Gets the latest Git tag (as a string), e.g. 0.1.2.\n\n Note that `git describe --tags` works as follows:\n - Finds the most recent tag that is reachable from a commit.\n - If the tag points to the commit, then only the tag is shown.\n - Otherwise, it suffixes the tag name with the number of additional commits\n on top of the tag, and the abbreviated name of the most recent commit,\n e.g. 0.1.2-9-g2118b21. If you add `--abbrev=0`, this suffix is removed.\n This behavior is controlled by the `abbrev` parameter.\n \"\"\"\n cmd = [\"git\", \"describe\", \"--tags\"]\n if abbreviate:\n cmd.append(\"--abbrev=0\")\n try:\n out = subprocess.check_output(cmd, stderr=subprocess.STDOUT)\n return out.strip().decode(\"ascii\")\n except (subprocess.SubprocessError, OSError):\n return \"Unknown\"\n\n\ndef write_version_py(version: str) -> None:\n \"\"\"Write the current package version to a Python file (ax/version.py)\n\n This file will be imported by ax/__init__.py, so that users can determine\n the current version by running `from ax import __version__`.\n \"\"\"\n content = \"\"\"#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n\n# THIS FILE IS GENERATED FROM AX SETUP.PY\n\nversion = \"%s\"\n\"\"\"\n f = open(\"ax/version.py\", \"w\")\n try:\n f.write(content % version)\n finally:\n f.close()\n return version\n\n\ndef setup_package() -> None:\n \"\"\"Used for installing the Ax package.\n\n First, we determine the current version by getting the latest tag from Git.\n We write this version to a file (ax/version.py), which is imported by\n __init__.py. We also pass this version to setuptools below.\n \"\"\"\n\n # Grab current version from Git\n # Abbreviated version (e.g. 0.1.2) will be used by setuptools\n # Unabbreviated version (e.g. 0.1.2-9-g2118b21) will be used by __init__.py\n abbreviated_version = get_git_version(abbreviate=True)\n version = get_git_version(abbreviate=False)\n\n # Write unabbreviated version to version.py\n write_version_py(version)\n\n with open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\n setup(\n name=\"ax-platform\",\n version=abbreviated_version,\n description=\"Adaptive Experimentation\",\n author=\"Facebook, Inc.\",\n license=\"MIT\",\n url=\"https://github.com/facebook/Ax\",\n keywords=[\"Experimentation\", \"Optimization\"],\n classifiers=[\n \"Development Status :: 4 - Beta\",\n \"Operating System :: POSIX :: Linux\",\n \"Operating System :: MacOS :: MacOS X\",\n \"Programming Language :: Python :: 3\",\n ],\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n python_requires=\">=3.6\",\n setup_requires=[\"cython\", \"numpy\"],\n install_requires=REQUIRES,\n packages=find_packages(),\n ext_modules=cythonize(EXTENSIONS),\n package_data={\n # include all js, css, and html files in the package\n \"\": [\"*.js\", \"*.css\", \"*.html\"]\n },\n extras_require={\n \"dev\": DEV_REQUIRES,\n \"mysql\": MYSQL_REQUIRES,\n \"notebook\": NOTEBOOK_REQUIRES,\n },\n )\n\n\nif __name__ == \"__main__\":\n setup_package()\n", "#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n\nimport math\nfrom collections import Counter\nfrom typing import Any, Dict, List, Optional, Set, Tuple, Union\n\nimport numpy as np\nfrom ax.core.generator_run import GeneratorRun\nfrom ax.core.observation import ObservationFeatures\nfrom ax.core.parameter import ChoiceParameter, FixedParameter, RangeParameter\nfrom ax.core.types import TParameterization\nfrom ax.modelbridge.base import ModelBridge\nfrom ax.modelbridge.transforms.ivw import IVW\nfrom ax.plot.base import DECIMALS, PlotData, PlotInSampleArm, PlotOutOfSampleArm, Z\nfrom ax.utils.common.logger import get_logger\n\n\nlogger = get_logger(name=\"PlotHelper\")\n\n# Typing alias\nRawData = List[Dict[str, Union[str, float]]]\n\nTNullableGeneratorRunsDict = Optional[Dict[str, GeneratorRun]]\n\n\ndef _format_dict(param_dict: TParameterization, name: str = \"Parameterization\") -> str:\n \"\"\"Format a dictionary for labels.\n\n Args:\n param_dict: Dictionary to be formatted\n name: String name of the thing being formatted.\n\n Returns: stringified blob.\n \"\"\"\n if len(param_dict) >= 10:\n blob = \"{} has too many items to render on hover ({}).\".format(\n name, len(param_dict)\n )\n else:\n blob = \"<br><em>{}:</em><br>{}\".format(\n name, \"<br>\".join(\"{}: {}\".format(n, v) for n, v in param_dict.items())\n )\n return blob\n\n\ndef _wrap_metric(metric_name: str) -> str:\n \"\"\"Put a newline on \"::\" for metric names.\n\n Args:\n metric_name: metric name.\n\n Returns: wrapped metric name.\n \"\"\"\n if \"::\" in metric_name:\n return \"<br>\".join(metric_name.split(\"::\"))\n else:\n return metric_name\n\n\ndef _format_CI(estimate: float, sd: float, relative: bool, zval: float = Z) -> str:\n \"\"\"Format confidence intervals given estimate and standard deviation.\n\n Args:\n estimate: point estimate.\n sd: standard deviation of point estimate.\n relative: if True, '%' is appended.\n zval: z-value associated with desired CI (e.g. 1.96 for 95% CIs)\n\n Returns: formatted confidence interval.\n \"\"\"\n return \"[{lb:.{digits}f}{perc}, {ub:.{digits}f}{perc}]\".format(\n lb=estimate - zval * sd,\n ub=estimate + zval * sd,\n digits=DECIMALS,\n perc=\"%\" if relative else \"\",\n )\n\n\ndef arm_name_to_tuple(arm_name: str) -> Union[Tuple[int, int], Tuple[int]]:\n tup = arm_name.split(\"_\")\n if len(tup) == 2:\n try:\n return (int(tup[0]), int(tup[1]))\n except ValueError:\n return (0,)\n return (0,)\n\n\ndef resize_subtitles(figure: Dict[str, Any], size: int):\n for ant in figure[\"layout\"][\"annotations\"]:\n ant[\"font\"].update(size=size)\n return figure\n\n\ndef _filter_dict(\n param_dict: TParameterization, subset_keys: List[str]\n) -> TParameterization:\n \"\"\"Filter a dictionary to keys present in a given list.\"\"\"\n return {k: v for k, v in param_dict.items() if k in subset_keys}\n\n\ndef _get_in_sample_arms(\n model: ModelBridge,\n metric_names: Set[str],\n fixed_features: Optional[ObservationFeatures] = None,\n) -> Tuple[Dict[str, PlotInSampleArm], RawData, Dict[str, TParameterization]]:\n \"\"\"Get in-sample arms from a model with observed and predicted values\n for specified metrics.\n\n Returns a PlotInSampleArm object in which repeated observations are merged\n with IVW, and a RawData object in which every observation is listed.\n\n Fixed features input can be used to override fields of the insample arms\n when making model predictions.\n\n Args:\n model: An instance of the model bridge.\n metric_names: Restrict predictions to these metrics. If None, uses all\n metrics in the model.\n\n Returns:\n A tuple containing\n\n - Map from arm name to PlotInSampleArm.\n - List of the data for each observation like::\n\n {'metric_name': 'likes', 'arm_name': '0_0', 'mean': 1., 'sem': 0.1}\n\n - Map from arm name to parameters\n \"\"\"\n observations = model.get_training_data()\n # Calculate raw data\n raw_data = []\n cond_name_to_parameters = {}\n for obs in observations:\n cond_name_to_parameters[obs.arm_name] = obs.features.parameters\n for j, metric_name in enumerate(obs.data.metric_names):\n if metric_name in metric_names:\n raw_data.append(\n {\n \"metric_name\": metric_name,\n \"arm_name\": obs.arm_name,\n \"mean\": obs.data.means[j],\n \"sem\": np.sqrt(obs.data.covariance[j, j]),\n }\n )\n\n # Check that we have one ObservationFeatures per arm name since we\n # key by arm name and the model is not Multi-task.\n # If \"TrialAsTask\" is present, one of the arms is also chosen.\n if (\"TrialAsTask\" not in model.transforms.keys()) and (\n len(cond_name_to_parameters) != len(observations)\n ):\n logger.error(\n \"Have observations of arms with different features but same\"\n \" name. Arbitrary one will be plotted.\"\n )\n\n # Merge multiple measurements within each Observation with IVW to get\n # un-modeled prediction\n t = IVW(None, [], [])\n obs_data = t.transform_observation_data([obs.data for obs in observations], [])\n # Start filling in plot data\n in_sample_plot: Dict[str, PlotInSampleArm] = {}\n for i, obs in enumerate(observations):\n if obs.arm_name is None:\n raise ValueError(\"Observation must have arm name for plotting.\")\n\n # Extract raw measurement\n obs_y = {}\n obs_se = {}\n # Use the IVW data, not obs.data\n for j, metric_name in enumerate(obs_data[i].metric_names):\n if metric_name in metric_names:\n obs_y[metric_name] = obs_data[i].means[j]\n obs_se[metric_name] = np.sqrt(obs_data[i].covariance[j, j])\n # Make a prediction.\n if model.training_in_design[i]:\n features = obs.features\n if fixed_features is not None:\n features.update_features(fixed_features)\n pred_y, pred_se = _predict_at_point(model, features, metric_names)\n else:\n # Use raw data for out-of-design points\n pred_y = obs_y\n pred_se = obs_se\n # pyre-fixme[6]: Expected `str` for 1st param but got `Optional[str]`.\n in_sample_plot[obs.arm_name] = PlotInSampleArm(\n # pyre-fixme[6]: Expected `str` for 1st param but got `Optional[str]`.\n name=obs.arm_name,\n y=obs_y,\n se=obs_se,\n parameters=obs.features.parameters,\n y_hat=pred_y,\n se_hat=pred_se,\n context_stratum=None,\n )\n return in_sample_plot, raw_data, cond_name_to_parameters\n\n\ndef _predict_at_point(\n model: ModelBridge, obsf: ObservationFeatures, metric_names: Set[str]\n) -> Tuple[Dict[str, float], Dict[str, float]]:\n \"\"\"Make a prediction at a point.\n\n Returns mean and standard deviation in format expected by plotting.\n\n Args:\n model: ModelBridge\n obsf: ObservationFeatures for which to predict\n metric_names: Limit predictions to these metrics.\n\n Returns:\n A tuple containing\n\n - Map from metric name to prediction.\n - Map from metric name to standard error.\n \"\"\"\n y_hat = {}\n se_hat = {}\n f_pred, cov_pred = model.predict([obsf])\n for metric_name in f_pred:\n if metric_name in metric_names:\n y_hat[metric_name] = f_pred[metric_name][0]\n se_hat[metric_name] = np.sqrt(cov_pred[metric_name][metric_name][0])\n return y_hat, se_hat\n\n\ndef _get_out_of_sample_arms(\n model: ModelBridge,\n generator_runs_dict: Dict[str, GeneratorRun],\n metric_names: Set[str],\n fixed_features: Optional[ObservationFeatures] = None,\n) -> Dict[str, Dict[str, PlotOutOfSampleArm]]:\n \"\"\"Get out-of-sample predictions from a model given a dict of generator runs.\n\n Fixed features input can be used to override fields of the candidate arms\n when making model predictions.\n\n Args:\n model: The model.\n generator_runs_dict: a mapping from generator run name to generator run.\n metric_names: metrics to include in the plot.\n\n Returns:\n A mapping from name to a mapping from arm name to plot.\n\n \"\"\"\n out_of_sample_plot: Dict[str, Dict[str, PlotOutOfSampleArm]] = {}\n for generator_run_name, generator_run in generator_runs_dict.items():\n out_of_sample_plot[generator_run_name] = {}\n for arm in generator_run.arms:\n # This assumes context is None\n obsf = ObservationFeatures.from_arm(arm)\n if fixed_features is not None:\n obsf.update_features(fixed_features)\n\n # Make a prediction\n try:\n pred_y, pred_se = _predict_at_point(model, obsf, metric_names)\n except Exception:\n # Check if it is an out-of-design arm.\n if not model.model_space.check_membership(obsf.parameters):\n # Skip this point\n continue\n else:\n # It should have worked\n raise\n arm_name = arm.name_or_short_signature\n out_of_sample_plot[generator_run_name][arm_name] = PlotOutOfSampleArm(\n name=arm_name,\n parameters=obsf.parameters,\n y_hat=pred_y,\n se_hat=pred_se,\n context_stratum=None,\n )\n return out_of_sample_plot\n\n\ndef get_plot_data(\n model: ModelBridge,\n generator_runs_dict: Dict[str, GeneratorRun],\n metric_names: Optional[Set[str]] = None,\n fixed_features: Optional[ObservationFeatures] = None,\n) -> Tuple[PlotData, RawData, Dict[str, TParameterization]]:\n \"\"\"Format data object with metrics for in-sample and out-of-sample\n arms.\n\n Calculate both observed and predicted metrics for in-sample arms.\n Calculate predicted metrics for out-of-sample arms passed via the\n `generator_runs_dict` argument.\n\n In PlotData, in-sample observations are merged with IVW. In RawData, they\n are left un-merged and given as a list of dictionaries, one for each\n observation and having keys 'arm_name', 'mean', and 'sem'.\n\n Args:\n model: The model.\n generator_runs_dict: a mapping from generator run name to generator run.\n metric_names: Restrict predictions to this set. If None, all metrics\n in the model will be returned.\n fixed_features: Fixed features to use when making model predictions.\n\n Returns:\n A tuple containing\n\n - PlotData object with in-sample and out-of-sample predictions.\n - List of observations like::\n\n {'metric_name': 'likes', 'arm_name': '0_1', 'mean': 1., 'sem': 0.1}.\n\n - Mapping from arm name to parameters.\n \"\"\"\n metrics_plot = model.metric_names if metric_names is None else metric_names\n in_sample_plot, raw_data, cond_name_to_parameters = _get_in_sample_arms(\n model=model, metric_names=metrics_plot, fixed_features=fixed_features\n )\n out_of_sample_plot = _get_out_of_sample_arms(\n model=model,\n generator_runs_dict=generator_runs_dict,\n metric_names=metrics_plot,\n fixed_features=fixed_features,\n )\n # pyre-fixme[16]: `Optional` has no attribute `arm_name`.\n status_quo_name = None if model.status_quo is None else model.status_quo.arm_name\n plot_data = PlotData(\n metrics=list(metrics_plot),\n in_sample=in_sample_plot,\n out_of_sample=out_of_sample_plot,\n status_quo_name=status_quo_name,\n )\n return plot_data, raw_data, cond_name_to_parameters\n\n\ndef get_range_parameter(model: ModelBridge, param_name: str) -> RangeParameter:\n \"\"\"\n Get the range parameter with the given name from the model.\n\n Throws if parameter doesn't exist or is not a range parameter.\n\n Args:\n model: The model.\n param_name: The name of the RangeParameter to be found.\n\n Returns: The RangeParameter named `param_name`.\n \"\"\"\n\n range_param = model.model_space.parameters.get(param_name)\n if range_param is None:\n raise ValueError(f\"Parameter `{param_name}` does not exist.\")\n if not isinstance(range_param, RangeParameter):\n raise ValueError(f\"{param_name} is not a RangeParameter\")\n\n return range_param\n\n\ndef get_range_parameters(model: ModelBridge) -> List[RangeParameter]:\n \"\"\"\n Get a list of range parameters from a model.\n\n Args:\n model: The model.\n\n Returns: List of RangeParameters.\n \"\"\"\n return [\n parameter\n for parameter in model.model_space.parameters.values()\n if isinstance(parameter, RangeParameter)\n ]\n\n\ndef get_grid_for_parameter(parameter: RangeParameter, density: int) -> np.ndarray:\n \"\"\"Get a grid of points along the range of the parameter.\n\n Will be a log-scale grid if parameter is log scale.\n\n Args:\n parameter: Parameter for which to generate grid.\n density: Number of points in the grid.\n \"\"\"\n is_log = parameter.log_scale\n if is_log:\n grid = np.linspace(\n np.log10(parameter.lower), np.log10(parameter.upper), density\n )\n grid = 10 ** grid\n else:\n grid = np.linspace(parameter.lower, parameter.upper, density)\n return grid\n\n\ndef get_fixed_values(\n model: ModelBridge, slice_values: Optional[Dict[str, Any]] = None\n) -> TParameterization:\n \"\"\"Get fixed values for parameters in a slice plot.\n\n If there is an in-design status quo, those values will be used. Otherwise,\n the mean of RangeParameters or the mode of ChoiceParameters is used.\n\n Any value in slice_values will override the above.\n\n Args:\n model: ModelBridge being used for plotting\n slice_values: Map from parameter name to value at which is should be\n fixed.\n\n Returns: Map from parameter name to fixed value.\n \"\"\"\n # Check if status_quo is in design\n if model.status_quo is not None and model.model_space.check_membership(\n # pyre-fixme[16]: `Optional` has no attribute `features`.\n model.status_quo.features.parameters\n ):\n setx = model.status_quo.features.parameters\n else:\n observations = model.get_training_data()\n setx = {}\n for p_name, parameter in model.model_space.parameters.items():\n # Exclude out of design status quo (no parameters)\n vals = [\n obs.features.parameters[p_name]\n for obs in observations\n if (\n len(obs.features.parameters) > 0\n and parameter.validate(obs.features.parameters[p_name])\n )\n ]\n if isinstance(parameter, FixedParameter):\n setx[p_name] = parameter.value\n elif isinstance(parameter, ChoiceParameter):\n setx[p_name] = Counter(vals).most_common(1)[0][0]\n elif isinstance(parameter, RangeParameter):\n setx[p_name] = parameter._cast(np.mean(vals))\n\n if slice_values is not None:\n # slice_values has type Dictionary[str, Any]\n setx.update(slice_values)\n return setx\n\n\n# Utility methods ported from JS\ndef contour_config_to_trace(config):\n # Load from config\n arm_data = config[\"arm_data\"]\n density = config[\"density\"]\n grid_x = config[\"grid_x\"]\n grid_y = config[\"grid_y\"]\n f = config[\"f\"]\n lower_is_better = config[\"lower_is_better\"]\n metric = config[\"metric\"]\n rel = config[\"rel\"]\n sd = config[\"sd\"]\n xvar = config[\"xvar\"]\n yvar = config[\"yvar\"]\n\n green_scale = config[\"green_scale\"]\n green_pink_scale = config[\"green_pink_scale\"]\n blue_scale = config[\"blue_scale\"]\n\n # format data\n res = relativize_data(f, sd, rel, arm_data, metric)\n f_final = res[0]\n sd_final = res[1]\n\n # calculate max of abs(outcome), used for colorscale\n f_absmax = max(abs(min(f_final)), max(f_final))\n\n # transform to nested array\n f_plt = []\n for ind in range(0, len(f_final), density):\n f_plt.append(f_final[ind : ind + density])\n sd_plt = []\n for ind in range(0, len(sd_final), density):\n sd_plt.append(sd_final[ind : ind + density])\n\n CONTOUR_CONFIG = {\n \"autocolorscale\": False,\n \"autocontour\": True,\n \"contours\": {\"coloring\": \"heatmap\"},\n \"hoverinfo\": \"x+y+z\",\n \"ncontours\": density / 2,\n \"type\": \"contour\",\n \"x\": grid_x,\n \"y\": grid_y,\n }\n\n if rel:\n f_scale = reversed(green_pink_scale) if lower_is_better else green_pink_scale\n else:\n f_scale = green_scale\n\n f_trace = {\n \"colorbar\": {\n \"x\": 0.45,\n \"y\": 0.5,\n \"ticksuffix\": \"%\" if rel else \"\",\n \"tickfont\": {\"size\": 8},\n },\n \"colorscale\": [(i / (len(f_scale) - 1), rgb(v)) for i, v in enumerate(f_scale)],\n \"xaxis\": \"x\",\n \"yaxis\": \"y\",\n \"z\": f_plt,\n # zmax and zmin are ignored if zauto is true\n \"zauto\": not rel,\n \"zmax\": f_absmax,\n \"zmin\": -f_absmax,\n }\n\n sd_trace = {\n \"colorbar\": {\n \"x\": 1,\n \"y\": 0.5,\n \"ticksuffix\": \"%\" if rel else \"\",\n \"tickfont\": {\"size\": 8},\n },\n \"colorscale\": [\n (i / (len(blue_scale) - 1), rgb(v)) for i, v in enumerate(blue_scale)\n ],\n \"xaxis\": \"x2\",\n \"yaxis\": \"y2\",\n \"z\": sd_plt,\n }\n\n f_trace.update(CONTOUR_CONFIG)\n sd_trace.update(CONTOUR_CONFIG)\n\n # get in-sample arms\n arm_text = list(arm_data[\"in_sample\"].keys())\n arm_x = [\n arm_data[\"in_sample\"][arm_name][\"parameters\"][xvar] for arm_name in arm_text\n ]\n arm_y = [\n arm_data[\"in_sample\"][arm_name][\"parameters\"][yvar] for arm_name in arm_text\n ]\n\n # configs for in-sample arms\n base_in_sample_arm_config = {\n \"hoverinfo\": \"text\",\n \"legendgroup\": \"In-sample\",\n \"marker\": {\"color\": \"black\", \"symbol\": 1, \"opacity\": 0.5},\n \"mode\": \"markers\",\n \"name\": \"In-sample\",\n \"text\": arm_text,\n \"type\": \"scatter\",\n \"x\": arm_x,\n \"y\": arm_y,\n }\n\n f_in_sample_arm_trace = {\"xaxis\": \"x\", \"yaxis\": \"y\"}\n\n sd_in_sample_arm_trace = {\"showlegend\": False, \"xaxis\": \"x2\", \"yaxis\": \"y2\"}\n\n f_in_sample_arm_trace.update(base_in_sample_arm_config)\n sd_in_sample_arm_trace.update(base_in_sample_arm_config)\n\n traces = [f_trace, sd_trace, f_in_sample_arm_trace, sd_in_sample_arm_trace]\n\n # iterate over out-of-sample arms\n for i, generator_run_name in enumerate(arm_data[\"out_of_sample\"].keys()):\n symbol = i + 2 # symbols starts from 2 for candidate markers\n\n ax = []\n ay = []\n atext = []\n\n for arm_name in arm_data[\"out_of_sample\"][generator_run_name].keys():\n ax.append(\n arm_data[\"out_of_sample\"][generator_run_name][arm_name][\"parameters\"][\n xvar\n ]\n )\n ay.append(\n arm_data[\"out_of_sample\"][generator_run_name][arm_name][\"parameters\"][\n yvar\n ]\n )\n atext.append(\"<em>Candidate \" + arm_name + \"</em>\")\n\n traces.append(\n {\n \"hoverinfo\": \"text\",\n \"legendgroup\": generator_run_name,\n \"marker\": {\"color\": \"black\", \"symbol\": symbol, \"opacity\": 0.5},\n \"mode\": \"markers\",\n \"name\": generator_run_name,\n \"text\": atext,\n \"type\": \"scatter\",\n \"xaxis\": \"x\",\n \"x\": ax,\n \"yaxis\": \"y\",\n \"y\": ay,\n }\n )\n traces.append(\n {\n \"hoverinfo\": \"text\",\n \"legendgroup\": generator_run_name,\n \"marker\": {\"color\": \"black\", \"symbol\": symbol, \"opacity\": 0.5},\n \"mode\": \"markers\",\n \"name\": \"In-sample\",\n \"showlegend\": False,\n \"text\": atext,\n \"type\": \"scatter\",\n \"x\": ax,\n \"xaxis\": \"x2\",\n \"y\": ay,\n \"yaxis\": \"y2\",\n }\n )\n\n return traces\n\n\ndef axis_range(grid: List[float], is_log: bool) -> List[float]:\n if is_log:\n return [math.log10(min(grid)), math.log10(max(grid))]\n else:\n return [min(grid), max(grid)]\n\n\ndef _relativize(m_t: float, sem_t: float, m_c: float, sem_c: float) -> List[float]:\n r_hat = (m_t - m_c) / abs(m_c) - sem_c ** 2 * m_t / abs(m_c) ** 3\n variance = (sem_t ** 2 + (m_t / m_c * sem_c) ** 2) / m_c ** 2\n return [r_hat, math.sqrt(variance)]\n\n\ndef relativize_data(\n f: List[float], sd: List[float], rel: bool, arm_data: Dict[Any, Any], metric: str\n) -> List[List[float]]:\n # if relative, extract status quo & compute ratio\n f_final = [] if rel else f\n sd_final = [] if rel else sd\n\n if rel:\n f_sq = arm_data[\"in_sample\"][arm_data[\"status_quo_name\"]][\"y\"][metric]\n sd_sq = arm_data[\"in_sample\"][arm_data[\"status_quo_name\"]][\"se\"][metric]\n\n for i in range(len(f)):\n res = _relativize(f[i], sd[i], f_sq, sd_sq)\n f_final.append(100 * res[0])\n sd_final.append(100 * res[1])\n\n return [f_final, sd_final]\n\n\ndef rgb(arr: List[int]) -> str:\n return \"rgb({},{},{})\".format(*arr)\n", "#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n\nimport logging\nfrom abc import abstractmethod\nfrom collections import defaultdict\nfrom typing import Dict, List, NamedTuple, Optional, Tuple\n\nimport numpy as np\nimport pandas as pd\nfrom ax.benchmark.benchmark_problem import BenchmarkProblem\nfrom ax.core.batch_trial import BatchTrial\nfrom ax.core.data import Data\nfrom ax.core.experiment import Experiment\nfrom ax.core.optimization_config import OptimizationConfig\nfrom ax.core.trial import Trial\nfrom ax.core.types import ComparisonOp\nfrom ax.modelbridge.generation_strategy import GenerationStrategy\nfrom ax.runners.synthetic import SyntheticRunner\nfrom ax.utils.common.logger import get_logger\n\n\nlogger: logging.Logger = get_logger(__name__)\n\nALLOWED_RUN_RETRIES = 5\nPROBLEM_METHOD_DELIMETER = \"_on_\"\nRUN_DELIMETER = \"_run_\"\n\n\nclass BenchmarkResult(NamedTuple):\n # {method_name -> [[best objective per trial] per benchmark run]}\n objective_at_true_best: Dict[str, np.ndarray]\n # {method_name -> trials where generation strategy changed}\n generator_changes: Dict[str, Optional[List[int]]]\n optimum: float\n # {method_name -> [total fit time per run]}\n fit_times: Dict[str, List[float]]\n # {method_name -> [total gen time per run]}\n gen_times: Dict[str, List[float]]\n\n\nclass BenchmarkSetup(Experiment):\n \"\"\"An extension of `Experiment`, specific to benchmarking. Contains\n additional data, such as the benchmarking problem, iterations to run per\n benchmarking method and problem combination, etc.\n\n Args:\n problem: description of the benchmarking problem for\n this setup\n total_iterations: how many optimization iterations to run\n batch_size: if this benchmark requires batch trials,\n batch size for those. Defaults to None\n \"\"\"\n\n problem: BenchmarkProblem\n total_iterations: int\n batch_size: int\n\n def __init__(\n self, problem: BenchmarkProblem, total_iterations: int = 20, batch_size: int = 1\n ) -> None:\n super().__init__(\n name=problem.name,\n search_space=problem.search_space,\n runner=SyntheticRunner(),\n optimization_config=problem.optimization_config,\n )\n self.problem = problem\n self.total_iterations = total_iterations\n self.batch_size = batch_size\n\n def clone_reset(self) -> \"BenchmarkSetup\":\n \"\"\"Create a clean copy of this benchmarking setup, with no run data\n attached to it.\"\"\"\n return BenchmarkSetup(self.problem, self.total_iterations, self.batch_size)\n\n\nclass BenchmarkRunner:\n \"\"\"Runner that keeps track of benchmark runs and failures encountered\n during benchmarking.\n \"\"\"\n\n _failed_runs: List[Tuple[str, str]]\n _runs: Dict[Tuple[str, str, int], BenchmarkSetup]\n _error_messages: List[str]\n _generator_changes: Dict[Tuple[str, str, int], Optional[List[int]]]\n\n def __init__(self) -> None:\n self._runs = {}\n self._failed_runs = []\n self._error_messages = []\n self._generator_changes = {}\n\n @abstractmethod\n def run_benchmark_run(\n self, setup: BenchmarkSetup, generation_strategy: GenerationStrategy\n ) -> BenchmarkSetup:\n \"\"\"Run a single full benchmark run of the given problem and method\n combination.\n \"\"\"\n pass # pragma: no cover\n\n def run_benchmark_test(\n self,\n setup: BenchmarkSetup,\n generation_strategy: GenerationStrategy,\n num_runs: int = 20,\n raise_all_errors: bool = False,\n ) -> Dict[Tuple[str, str, int], BenchmarkSetup]:\n \"\"\"Run full benchmark test for the given method and problem combination.\n A benchmark test consists of repeated full benchmark runs.\n\n Args:\n setup: setup, runs on which to execute; includes\n a benchmarking problem, total number of iterations, etc.\n generation strategy: generation strategy that defines which\n generation methods should be used in this benchmarking test\n num_runs: how many benchmark runs of given problem and method\n combination to run with the given setup for one benchmark test\n \"\"\"\n num_failures = 0\n benchmark_runs: Dict[Tuple[str, str, int], BenchmarkSetup] = {}\n logger.info(f\"Testing {generation_strategy.name} on {setup.name}:\")\n for run_idx in range(num_runs):\n logger.info(f\"Run {run_idx}\")\n run_key = (setup.name, generation_strategy.name, run_idx)\n # If this run has already been executed, log and skip it.\n if run_key in self._runs:\n self._error_messages.append( # pragma: no cover\n f\"Run {run_idx} of {generation_strategy.name} on {setup.name} \"\n \"has already been executed in this benchmarking suite.\"\n \"Check that this method + problem combination is not \"\n \"included in the benchmarking suite twice. Only the first \"\n \"run will be recorded.\"\n )\n continue\n\n # When number of failures in this test exceeds the allowed max,\n # we consider the whole run failed.\n while num_failures < ALLOWED_RUN_RETRIES:\n try:\n benchmark_runs[run_key] = self.run_benchmark_run(\n setup.clone_reset(), generation_strategy.clone_reset()\n )\n self._generator_changes[\n run_key\n ] = generation_strategy.generator_changes\n break\n except Exception as err: # pragma: no cover\n if raise_all_errors:\n raise err\n logger.exception(err)\n num_failures += 1\n self._error_messages.append(f\"Error in {run_key}: {err}\")\n\n if num_failures >= 5:\n self._error_messages.append(\n f\"Considering {generation_strategy.name} on {setup.name} failed\"\n )\n self._failed_runs.append((setup.name, generation_strategy.name))\n else:\n self._runs.update(benchmark_runs)\n return self._runs\n\n def aggregate_results(self) -> Dict[str, BenchmarkResult]:\n \"\"\"Pull results from each of the runs (BenchmarkSetups aka Experiments)\n and aggregate them into a BenchmarkResult for each problem.\n \"\"\"\n n_iters: Dict[Tuple[str, str], int] = {}\n optima: Dict[str, float] = {}\n # Results will be put in nested dictionaries problem -> method -> results\n objective_at_true_best: Dict[str, Dict[str, List[np.ndarray]]] = {}\n fit_times: Dict[str, Dict[str, List[float]]] = {}\n gen_times: Dict[str, Dict[str, List[float]]] = {}\n generator_changes: Dict[str, Dict[str, Optional[List[int]]]] = {}\n for (p, m, r), setup in self._runs.items():\n for res_dict in [\n objective_at_true_best,\n fit_times,\n gen_times,\n generator_changes,\n ]:\n if p not in res_dict:\n res_dict[p] = defaultdict(list)\n optima[p] = setup.problem.fbest\n generator_changes[p][m] = self._generator_changes[(p, m, r)]\n # Extract iterations for this pmr\n names = []\n for trial in setup.trials.values():\n for i, arm in enumerate(trial.arms):\n if isinstance(trial, BatchTrial):\n reps = int(trial.weights[i])\n else:\n reps = 1\n names.extend([arm.name] * reps)\n # Make sure every run has the same number of iterations, so we can safely\n # stack them in a matrix.\n if (p, m) in n_iters:\n if len(names) != n_iters[(p, m)]:\n raise ValueError( # pragma: no cover\n f\"Expected {n_iters[(p, m)]} iterations, got {len(names)}\"\n )\n else:\n n_iters[(p, m)] = len(names)\n # Get true values for every outcome for each iteration\n iters_df = pd.DataFrame({\"arm_name\": names})\n data_df = setup.fetch_data(noisy=False).df\n metrics = data_df[\"metric_name\"].unique()\n true_values = {}\n for metric in metrics:\n df_m = data_df[data_df[\"metric_name\"] == metric]\n # Get one row per arm\n df_m = df_m.groupby(\"arm_name\").first().reset_index()\n df_b = pd.merge(iters_df, df_m, how=\"left\", on=\"arm_name\")\n true_values[metric] = df_b[\"mean\"].values\n # Compute the things we care about\n # 1. True best objective value.\n objective_at_true_best[p][m].append(\n true_best_objective(\n optimization_config=setup.problem.optimization_config,\n true_values=true_values,\n )\n )\n # 2. Time\n fit_time, gen_time = get_model_times(setup)\n fit_times[p][m].append(fit_time)\n gen_times[p][m].append(gen_time)\n # 3. True objective value of model-predicted best (TODO)\n # 4. True feasiblity of model-predicted best (TODO)\n # 5. Model prediction MSE for each gen run (TODO)\n\n # Combine methods for each problem for the BenchmarkResult\n res: Dict[str, BenchmarkResult] = {}\n for p in objective_at_true_best:\n res[p] = BenchmarkResult(\n objective_at_true_best={\n m: np.array(v) for m, v in objective_at_true_best[p].items()\n },\n generator_changes=generator_changes[p],\n optimum=optima[p],\n fit_times=fit_times[p],\n gen_times=gen_times[p],\n )\n return res\n\n @property\n def errors(self) -> List[str]:\n \"\"\"Messages from errors encoutered while running benchmark test.\"\"\"\n return self._error_messages\n\n\nclass BanditBenchmarkRunner(BenchmarkRunner):\n def run_benchmark_run(\n self, setup: BenchmarkSetup, generation_strategy: GenerationStrategy\n ) -> BenchmarkSetup:\n pass # pragma: no cover TODO[drfreund]\n\n\nclass BOBenchmarkRunner(BenchmarkRunner):\n def run_benchmark_run(\n self, setup: BenchmarkSetup, generation_strategy: GenerationStrategy\n ) -> BenchmarkSetup:\n remaining_iterations = setup.total_iterations\n updated_trials = []\n while remaining_iterations > 0:\n num_suggestions = min(remaining_iterations, setup.batch_size)\n generator_run = generation_strategy.gen(\n experiment=setup,\n new_data=Data.from_multiple_data(\n [setup._fetch_trial_data(idx) for idx in updated_trials]\n ),\n n=setup.batch_size,\n )\n updated_trials = []\n if setup.batch_size > 1: # pragma: no cover\n trial = setup.new_batch_trial().add_generator_run(generator_run).run()\n else:\n trial = setup.new_trial(generator_run=generator_run).run()\n updated_trials.append(trial.index)\n remaining_iterations -= num_suggestions\n return setup\n\n\ndef true_best_objective(\n optimization_config: OptimizationConfig, true_values: Dict[str, np.ndarray]\n) -> np.ndarray:\n \"\"\"Compute the true best objective value found by each iteration.\n\n Args:\n optimization_config: Optimization config\n true_values: Dictionary from metric name to array of value at each\n iteration.\n\n Returns: Array of cumulative best feasible value.\n \"\"\"\n # Get objective at each iteration\n objective = optimization_config.objective\n f = true_values[objective.metric.name]\n # Set infeasible points to have inf bad values\n if objective.minimize:\n infeas_val = np.Inf\n else:\n infeas_val = -np.Inf\n for oc in optimization_config.outcome_constraints:\n if oc.relative:\n raise ValueError(\n \"Benchmark aggregation does not support relative constraints\"\n )\n g = true_values[oc.metric.name]\n if oc.op == ComparisonOp.LEQ:\n feas = g <= oc.bound\n else:\n feas = g >= oc.bound\n f[~feas] = infeas_val\n # Get cumulative best\n if objective.minimize:\n return np.minimum.accumulate(f)\n else:\n return np.maximum.accumulate(f)\n\n\ndef get_model_times(setup: BenchmarkSetup) -> Tuple[float, float]:\n fit_time = 0.0\n gen_time = 0.0\n for trial in setup.trials.values():\n if isinstance(trial, BatchTrial): # pragma: no cover\n gr = trial._generator_run_structs[0].generator_run\n elif isinstance(trial, Trial):\n gr = trial.generator_run\n else:\n raise ValueError(\"Unexpected trial type\") # pragma: no cover\n if gr is None: # for typing\n raise ValueError(\n \"Unexpected trial with no generator run\"\n ) # pragma: no cover\n if gr.fit_time is not None:\n # pyre-fixme[6]: Expected `float` for 1st param but got `Optional[float]`.\n fit_time += gr.fit_time\n if gr.gen_time is not None:\n # pyre-fixme[6]: Expected `float` for 1st param but got `Optional[float]`.\n gen_time += gr.gen_time\n return fit_time, gen_time\n" ]
[ [ "numpy.get_include" ], [ "numpy.log10", "numpy.mean", "numpy.sqrt", "numpy.linspace" ], [ "pandas.merge", "numpy.minimum.accumulate", "pandas.DataFrame", "numpy.maximum.accumulate", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "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": [] } ]
seralexger/fairlearn
[ "c3ee7b5a45eb3394fc1b8d17b991e3d970970c05" ]
[ "test/unit/metrics/test_metrics_engine_dicts.py" ]
[ "# Copyright (c) Microsoft Corporation and Fairlearn contributors.\n# Licensed under the MIT License.\n\nimport pytest\nimport numpy as np\n\nimport fairlearn.metrics as metrics\n\n# ======================================================\n\ny_true = [0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1]\ny_pred = [1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1]\nsf_binary = [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1]\n\nmetric_group_summary_results = {\n metrics.true_positive_rate_group_summary: {\n \"overall\": 0.75, \"by_group\": {0: 1, 1: 0.6}},\n metrics.true_negative_rate_group_summary: {\n \"overall\": 0.7, \"by_group\": {0: 0.66666667, 1: 0.75}},\n metrics.false_positive_rate_group_summary: {\n \"overall\": 0.3, \"by_group\": {0: 0.33333333, 1: 0.25}},\n metrics.false_negative_rate_group_summary: {\n \"overall\": 0.25, \"by_group\": {0: 0, 1: 0.4}},\n metrics._root_mean_squared_error_group_summary: {\n \"overall\": 0.52704628, \"by_group\": {0: 0.47140452, 1: 0.57735027}},\n metrics._balanced_root_mean_squared_error_group_summary: {\n \"overall\": 0.52386128, \"by_group\": {0: 0.28867513, 1: 0.56622777}},\n metrics.mean_prediction_group_summary: {\n \"overall\": 0.5, \"by_group\": {0: 0.55555556, 1: 0.44444444}},\n metrics.selection_rate_group_summary: {\n \"overall\": 0.5, \"by_group\": {0: 0.55555556, 1: 0.44444444}},\n metrics._mean_overprediction_group_summary: {\n \"overall\": 0.16666667, \"by_group\": {0: 0.22222222, 1: 0.11111111}},\n metrics._mean_underprediction_group_summary: {\n \"overall\": 0.11111111, \"by_group\": {0: -0, 1: 0.22222222}},\n metrics.accuracy_score_group_summary: {\n \"overall\": 0.72222222, \"by_group\": {0: 0.77777778, 1: 0.66666667}},\n metrics.balanced_accuracy_score_group_summary: {\n \"overall\": 0.725, \"by_group\": {0: 0.83333333, 1: 0.675}},\n metrics.confusion_matrix_group_summary: {\n 'overall': np.array([[7, 3], [2, 6]]),\n 'by_group': {0: np.array([[4, 2], [0, 3]]), 1: np.array([[3, 1], [2, 3]])}},\n metrics.precision_score_group_summary: {\n \"overall\": 0.66666667, \"by_group\": {0: 0.6, 1: 0.75}},\n metrics.recall_score_group_summary: {\n \"overall\": 0.75, \"by_group\": {0: 1, 1: 0.6}},\n metrics.roc_auc_score_group_summary: {\n \"overall\": 0.725, \"by_group\": {0: 0.83333333, 1: 0.675}},\n metrics.zero_one_loss_group_summary: {\n \"overall\": 0.27777778, \"by_group\": {0: 0.22222222, 1: 0.33333333}},\n metrics.mean_absolute_error_group_summary: {\n \"overall\": 0.27777778, \"by_group\": {0: 0.22222222, 1: 0.33333333}},\n metrics.mean_squared_error_group_summary: {\n \"overall\": 0.27777778, \"by_group\": {0: 0.22222222, 1: 0.33333333}},\n metrics.r2_score_group_summary: {\n \"overall\": -0.125, \"by_group\": {0: 0, 1: -0.35}},\n metrics.f1_score_group_summary: {\n \"overall\": 0.70588235, \"by_group\": {0: 0.75, 1: 0.66666666}},\n metrics.log_loss_group_summary: {\n \"overall\": 9.59423782, \"by_group\": {0: 7.67546133, 1: 11.51301430}},\n}\n\nderived_metric_results = {\n metrics.true_positive_rate_difference: 0.4,\n metrics.true_positive_rate_ratio: 0.6,\n metrics.true_negative_rate_difference: 0.083333333,\n metrics.true_negative_rate_ratio: 0.88888889,\n metrics.false_positive_rate_difference: 0.083333333,\n metrics.false_positive_rate_ratio: 0.75,\n metrics.false_negative_rate_difference: 0.4,\n metrics.false_negative_rate_ratio: 0,\n metrics.selection_rate_difference: 0.11111111,\n metrics.selection_rate_ratio: 0.8,\n metrics.accuracy_score_difference: 0.11111111,\n metrics.accuracy_score_ratio: 0.85714286,\n metrics.accuracy_score_group_min: 0.66666667,\n metrics.zero_one_loss_difference: 0.11111111,\n metrics.zero_one_loss_ratio: 0.66666667,\n metrics.zero_one_loss_group_max: 0.33333333,\n metrics.balanced_accuracy_score_group_min: 0.675,\n metrics.precision_score_group_min: 0.6,\n metrics.recall_score_group_min: 0.6,\n metrics.roc_auc_score_group_min: 0.675,\n metrics.mean_absolute_error_group_max: 0.33333333,\n metrics.mean_squared_error_group_max: 0.33333333,\n metrics.r2_score_group_min: -0.35,\n metrics.f1_score_group_max: 0.75,\n metrics.log_loss_group_min: 7.67546133,\n}\n\nmetric_group_summary_pos_label_keys = [\n metrics.true_positive_rate_group_summary,\n metrics.true_negative_rate_group_summary,\n metrics.false_positive_rate_group_summary,\n metrics.false_negative_rate_group_summary,\n metrics.selection_rate_group_summary,\n metrics.precision_score_group_summary,\n metrics.recall_score_group_summary,\n metrics.f1_score_group_summary,\n]\n\n\n# =======================================================\n\ndef test_dict_sizes():\n assert len(metrics._metric_group_summary_dict) == len(metric_group_summary_results)\n assert len(metrics._derived_metric_dict) == len(derived_metric_results)\n\n\[email protected](\"func\", metric_group_summary_results.keys())\ndef test_metric_group_summary_smoke(func):\n result = func(y_true, y_pred, sensitive_features=sf_binary)\n assert result.overall == pytest.approx(metric_group_summary_results[func][\"overall\"])\n assert len(result.by_group) == 2\n assert result.by_group[0] == pytest.approx(metric_group_summary_results[func][\"by_group\"][0])\n assert result.by_group[1] == pytest.approx(metric_group_summary_results[func][\"by_group\"][1])\n\n\[email protected](\"func\", derived_metric_results.keys())\ndef test_derived_metrics_smoke(func):\n result = func(y_true, y_pred, sensitive_features=sf_binary)\n assert result == pytest.approx(derived_metric_results[func])\n\n\[email protected](\"func\", metric_group_summary_pos_label_keys)\ndef test_metric_group_summary_pos_label_0(func):\n # We're going to set pos_label=0, so for simplicity invert the previous inputs\n y_true_invert = [1-y for y in y_true]\n y_pred_invert = [1-y for y in y_pred]\n result = func(y_true_invert, y_pred_invert, sensitive_features=sf_binary, pos_label=0)\n assert result.overall == pytest.approx(metric_group_summary_results[func][\"overall\"])\n assert len(result.by_group) == 2\n assert result.by_group[0] == pytest.approx(metric_group_summary_results[func][\"by_group\"][0])\n assert result.by_group[1] == pytest.approx(metric_group_summary_results[func][\"by_group\"][1])\n" ]
[ [ "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
j35tor/federated
[ "d92bfa6b8e3c9ebbac51ff7a3a180c2baaa08730", "d92bfa6b8e3c9ebbac51ff7a3a180c2baaa08730", "d92bfa6b8e3c9ebbac51ff7a3a180c2baaa08730", "d92bfa6b8e3c9ebbac51ff7a3a180c2baaa08730", "d92bfa6b8e3c9ebbac51ff7a3a180c2baaa08730", "d92bfa6b8e3c9ebbac51ff7a3a180c2baaa08730" ]
[ "tensorflow_federated/python/core/impl/tensorflow_context/tensorflow_serialization_test.py", "tensorflow_federated/python/simulation/datasets/client_data_test.py", "tensorflow_federated/python/aggregators/secure.py", "tensorflow_federated/python/core/api/test_case.py", "tensorflow_federated/python/simulation/baselines/cifar/resnet_models.py", "tensorflow_federated/python/core/impl/wrappers/computation_wrapper_instances_test.py" ]
[ "# Copyright 2018, The TensorFlow Federated Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport collections\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom tensorflow_federated.python.common_libs import serialization_utils\nfrom tensorflow_federated.python.common_libs import test_utils\nfrom tensorflow_federated.python.core.api import computation_types\nfrom tensorflow_federated.python.core.api import test_case\nfrom tensorflow_federated.python.core.impl.context_stack import context_stack_impl\nfrom tensorflow_federated.python.core.impl.tensorflow_context import tensorflow_serialization\nfrom tensorflow_federated.python.core.impl.types import type_serialization\n\n\ndef _tf_computation_serializer(fn, parameter_type, context):\n serializer = tensorflow_serialization.tf_computation_serializer(\n parameter_type, context)\n arg_to_fn = next(serializer)\n result = fn(arg_to_fn)\n return serializer.send(result)\n\n\nclass TensorFlowSerializationTest(test_case.TestCase):\n\n def test_serialize_tensorflow_with_no_parameter(self):\n comp, extra_type_spec = _tf_computation_serializer(\n lambda _: tf.constant(99), None, context_stack_impl.context_stack)\n self.assertEqual(\n str(type_serialization.deserialize_type(comp.type)), '( -> int32)')\n self.assertEqual(str(extra_type_spec), '( -> int32)')\n self.assertEqual(comp.WhichOneof('computation'), 'tensorflow')\n results = tf.compat.v1.Session().run(\n tf.import_graph_def(\n serialization_utils.unpack_graph_def(comp.tensorflow.graph_def),\n None, [comp.tensorflow.result.tensor.tensor_name]))\n self.assertEqual(results, [99])\n\n def test_serialize_tensorflow_with_table_no_variables(self):\n\n def table_lookup(word):\n table = tf.lookup.StaticVocabularyTable(\n tf.lookup.KeyValueTensorInitializer(['a', 'b', 'c'],\n np.arange(3, dtype=np.int64)),\n num_oov_buckets=1)\n return table.lookup(word)\n\n comp, extra_type_spec = _tf_computation_serializer(\n table_lookup,\n computation_types.TensorType(dtype=tf.string, shape=(None,)),\n context_stack_impl.context_stack)\n self.assertEqual(\n str(type_serialization.deserialize_type(comp.type)),\n '(string[?] -> int64[?])')\n self.assertEqual(str(extra_type_spec), '(string[?] -> int64[?])')\n self.assertEqual(comp.WhichOneof('computation'), 'tensorflow')\n\n with tf.Graph().as_default() as g:\n tf.import_graph_def(\n serialization_utils.unpack_graph_def(comp.tensorflow.graph_def),\n name='')\n with tf.compat.v1.Session(graph=g) as sess:\n sess.run(fetches=comp.tensorflow.initialize_op)\n results = sess.run(\n fetches=comp.tensorflow.result.tensor.tensor_name,\n feed_dict={\n comp.tensorflow.parameter.tensor.tensor_name: ['b', 'c', 'a']\n })\n self.assertAllEqual(results, [1, 2, 0])\n\n @test_utils.graph_mode_test\n def test_serialize_tensorflow_with_simple_add_three_lambda(self):\n comp, extra_type_spec = _tf_computation_serializer(\n lambda x: x + 3, computation_types.TensorType(tf.int32),\n context_stack_impl.context_stack)\n self.assertEqual(\n str(type_serialization.deserialize_type(comp.type)), '(int32 -> int32)')\n self.assertEqual(str(extra_type_spec), '(int32 -> int32)')\n self.assertEqual(comp.WhichOneof('computation'), 'tensorflow')\n parameter = tf.constant(1000)\n results = tf.compat.v1.Session().run(\n tf.import_graph_def(\n serialization_utils.unpack_graph_def(comp.tensorflow.graph_def),\n {comp.tensorflow.parameter.tensor.tensor_name: parameter},\n [comp.tensorflow.result.tensor.tensor_name]))\n self.assertEqual(results, [1003])\n\n @test_utils.graph_mode_test\n def test_serialize_tensorflow_with_structured_type_signature(self):\n batch_type = collections.namedtuple('BatchType', ['x', 'y'])\n output_type = collections.namedtuple('OutputType', ['A', 'B'])\n comp, extra_type_spec = _tf_computation_serializer(\n lambda z: output_type(2.0 * tf.cast(z.x, tf.float32), 3.0 * z.y),\n computation_types.StructWithPythonType([('x', tf.int32),\n ('y', (tf.float32, [2]))],\n batch_type),\n context_stack_impl.context_stack)\n self.assertEqual(\n str(type_serialization.deserialize_type(comp.type)),\n '(<x=int32,y=float32[2]> -> <A=float32,B=float32[2]>)')\n self.assertEqual(comp.WhichOneof('computation'), 'tensorflow')\n self.assertEqual(\n str(extra_type_spec),\n '(<x=int32,y=float32[2]> -> <A=float32,B=float32[2]>)')\n self.assertIsInstance(extra_type_spec.parameter,\n computation_types.StructWithPythonType)\n self.assertIs(extra_type_spec.parameter.python_container, batch_type)\n self.assertIsInstance(extra_type_spec.result,\n computation_types.StructWithPythonType)\n self.assertIs(extra_type_spec.result.python_container, output_type)\n\n @test_utils.graph_mode_test\n def test_serialize_tensorflow_with_data_set_sum_lambda(self):\n\n def _legacy_dataset_reducer_example(ds):\n return ds.reduce(np.int64(0), lambda x, y: x + y)\n\n comp, extra_type_spec = _tf_computation_serializer(\n _legacy_dataset_reducer_example,\n computation_types.SequenceType(tf.int64),\n context_stack_impl.context_stack)\n self.assertEqual(\n str(type_serialization.deserialize_type(comp.type)),\n '(int64* -> int64)')\n self.assertEqual(str(extra_type_spec), '(int64* -> int64)')\n self.assertEqual(comp.WhichOneof('computation'), 'tensorflow')\n parameter = tf.data.Dataset.range(5)\n results = tf.compat.v1.Session().run(\n tf.import_graph_def(\n serialization_utils.unpack_graph_def(comp.tensorflow.graph_def), {\n comp.tensorflow.parameter.sequence.variant_tensor_name:\n tf.data.experimental.to_variant(parameter)\n }, [comp.tensorflow.result.tensor.tensor_name]))\n self.assertEqual(results, [10])\n\n\nif __name__ == '__main__':\n test_case.main()\n", "# Copyright 2018, The TensorFlow Federated Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom absl.testing import absltest\nimport tensorflow as tf\n\nfrom tensorflow_federated.python.simulation.datasets import client_data as cd\n\n\nclass ConcreteClientDataTest(tf.test.TestCase, absltest.TestCase):\n\n def test_concrete_client_data(self):\n client_ids = [1, 2, 3]\n\n def create_dataset_fn(client_id):\n num_examples = client_id\n return tf.data.Dataset.range(num_examples)\n\n client_data = cd.ClientData.from_clients_and_fn(\n client_ids=client_ids,\n create_tf_dataset_for_client_fn=create_dataset_fn)\n\n self.assertEqual(client_data.element_type_structure,\n tf.TensorSpec(shape=(), dtype=tf.int64))\n\n def length(ds):\n return tf.data.experimental.cardinality(ds).numpy()\n\n for i in client_ids:\n self.assertEqual(\n length(client_data.create_tf_dataset_for_client(i)), int(i))\n\n # Preprocess to only take the first example from each client\n client_data = client_data.preprocess(lambda d: d.take(1))\n for i in client_ids:\n self.assertEqual(length(client_data.create_tf_dataset_for_client(i)), 1)\n\n # One example per client, so the whole dataset should be `num_clients` long.\n num_clients = len(\n list(iter(client_data.create_tf_dataset_from_all_clients())))\n self.assertLen(client_ids, num_clients)\n\n def get_test_client_data(self):\n\n def create_dataset_fn(client_id):\n num_examples = 1 if client_id % 2 == 0 else 0\n return tf.data.Dataset.range(num_examples)\n\n client_ids = list(range(10))\n return cd.ClientData.from_clients_and_fn(\n client_ids=client_ids,\n create_tf_dataset_for_client_fn=create_dataset_fn)\n\n def test_datasets_lists_all_elements(self):\n client_ids = [1, 2, 3]\n\n def create_dataset_fn(client_id):\n num_examples = client_id\n return tf.data.Dataset.range(num_examples)\n\n client_data = cd.ClientData.from_clients_and_fn(\n client_ids=client_ids,\n create_tf_dataset_for_client_fn=create_dataset_fn)\n\n def ds_iterable_to_list_set(datasets):\n return set(tuple(ds.as_numpy_iterator()) for ds in datasets)\n\n datasets = ds_iterable_to_list_set(client_data.datasets())\n expected = ds_iterable_to_list_set(\n (create_dataset_fn(cid) for cid in client_ids))\n self.assertEqual(datasets, expected)\n\n def test_datasets_is_lazy(self):\n client_ids = [1, 2, 3]\n\n # Note: this is called once on initialization of ClientData\n # with client_ids[0] in order to get the element type.\n # After that, it should be called lazily when `next` is called\n # on a `.datasets()` iterator.\n called_count = 0\n\n def only_call_me_thrice(client_id):\n nonlocal called_count\n called_count += 1\n if called_count == 1:\n self.assertEqual(client_id, client_ids[0])\n if called_count > 3:\n raise Exception('called too many times')\n num_examples = client_id\n return tf.data.Dataset.range(num_examples)\n\n client_data = cd.ClientData.from_clients_and_fn(\n client_ids=client_ids,\n create_tf_dataset_for_client_fn=only_call_me_thrice)\n\n datasets_iter = client_data.datasets()\n next(datasets_iter)\n next(datasets_iter)\n with self.assertRaisesRegex(Exception, 'called too many times'):\n next(datasets_iter)\n\n def test_datasets_limit_count(self):\n client_ids = [1, 2, 3]\n\n def create_dataset_fn(client_id):\n num_examples = client_id\n return tf.data.Dataset.range(num_examples)\n\n client_data = cd.ClientData.from_clients_and_fn(\n client_ids=client_ids,\n create_tf_dataset_for_client_fn=create_dataset_fn)\n\n ds = list(client_data.datasets(limit_count=1))\n self.assertLen(ds, 1)\n\n def test_datasets_doesnt_shuffle_client_ids_list(self):\n client_ids = [1, 2, 3]\n client_ids_copy = client_ids.copy()\n\n def create_dataset_fn(client_id):\n num_examples = client_id\n return tf.data.Dataset.range(num_examples)\n\n client_data = cd.ClientData.from_clients_and_fn(\n client_ids=client_ids,\n create_tf_dataset_for_client_fn=create_dataset_fn)\n\n client_data.datasets()\n self.assertEqual(client_ids, client_ids_copy)\n client_data.datasets()\n self.assertEqual(client_ids, client_ids_copy)\n client_data.datasets()\n self.assertEqual(client_ids, client_ids_copy)\n\n def test_create_tf_dataset_from_all_clients(self):\n client_ids = [1, 2, 3]\n\n def create_dataset_fn(client_id):\n return tf.data.Dataset.from_tensor_slices([client_id])\n\n client_data = cd.ClientData.from_clients_and_fn(\n client_ids=client_ids,\n create_tf_dataset_for_client_fn=create_dataset_fn)\n\n dataset = client_data.create_tf_dataset_from_all_clients()\n dataset_list = list(dataset.as_numpy_iterator())\n self.assertCountEqual(client_ids, dataset_list)\n\n def test_split_train_test_selects_nonempty_test_clients(self):\n # Only even client_ids have data:\n client_data = self.get_test_client_data()\n\n train, test = cd.ClientData.train_test_client_split(\n client_data, num_test_clients=3)\n # Test that all clients end up in one of the two ClientData:\n self.assertCountEqual(client_data.client_ids,\n train.client_ids + test.client_ids)\n self.assertLen(test.client_ids, 3)\n for client_id in test.client_ids:\n self.assertEqual(client_id % 2, 0)\n\n train, test = cd.ClientData.train_test_client_split(\n client_data, num_test_clients=5)\n self.assertLen(test.client_ids, 5)\n self.assertLen(train.client_ids, 5)\n\n def test_split_train_test_not_enough_nonempty_clients(self):\n client_data = self.get_test_client_data()\n with self.assertRaisesRegex(ValueError, 'too many clients with no data.'):\n cd.ClientData.train_test_client_split(client_data, num_test_clients=6)\n\n def test_split_train_test_too_few_clients(self):\n client_data = self.get_test_client_data()\n with self.assertRaisesRegex(ValueError, 'has only 10 clients.*11'):\n cd.ClientData.train_test_client_split(client_data, num_test_clients=11)\n\n def test_split_train_test_no_test_clients_requested(self):\n client_data = self.get_test_client_data()\n with self.assertRaisesRegex(ValueError, 'Please specify'):\n cd.ClientData.train_test_client_split(client_data, num_test_clients=0)\n\n def test_split_train_test_fixed_seed(self):\n client_data = self.get_test_client_data()\n\n train_0, test_0 = cd.ClientData.train_test_client_split(\n client_data, num_test_clients=3, seed=0)\n train_1, test_1 = cd.ClientData.train_test_client_split(\n client_data, num_test_clients=3, seed=0)\n\n self.assertEqual(train_0.client_ids, train_1.client_ids)\n self.assertEqual(test_0.client_ids, test_1.client_ids)\n\n\nif __name__ == '__main__':\n tf.test.main()\n", "# Copyright 2020, The TensorFlow Federated Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Factory for secure summation.\"\"\"\n\nimport collections\nimport enum\nimport math\nfrom typing import Optional, Union\nimport numpy as np\nimport tensorflow as tf\n\nfrom tensorflow_federated.python.aggregators import factory\nfrom tensorflow_federated.python.common_libs import py_typecheck\nfrom tensorflow_federated.python.core.api import computation_types\nfrom tensorflow_federated.python.core.api import computations\nfrom tensorflow_federated.python.core.api import intrinsics\nfrom tensorflow_federated.python.core.api import placements\nfrom tensorflow_federated.python.core.impl.types import type_analysis\nfrom tensorflow_federated.python.core.templates import aggregation_process\nfrom tensorflow_federated.python.core.templates import estimation_process\nfrom tensorflow_federated.python.core.templates import measured_process\nfrom tensorflow_federated.python.core.utils import federated_aggregations\n\nNORM_TF_TYPE = tf.float32\nCOUNT_TF_TYPE = tf.int32\n\nThresholdEstType = Union[int, float, np.ndarray,\n estimation_process.EstimationProcess]\n\n\n# Enum for internal tracking of configuration of `SecureSumFactory`.\nclass _Config(enum.Enum):\n INT = 1\n FLOAT = 2\n\n\ndef _check_bound_process(bound_process: estimation_process.EstimationProcess,\n name: str):\n \"\"\"Checks type properties for estimation process for bounds.\n\n The process must be an `EstimationProcess` with `next` function of type\n signature (<state@SERVER, NORM_TF_TYPE@CLIENTS> -> state@SERVER), and `report`\n with type signature (state@SERVER -> NORM_TF_TYPE@SERVER).\n\n Args:\n bound_process: A process to check.\n name: A string name for formatting error messages.\n \"\"\"\n py_typecheck.check_type(bound_process, estimation_process.EstimationProcess)\n\n next_parameter_type = bound_process.next.type_signature.parameter\n if not next_parameter_type.is_struct() or len(next_parameter_type) != 2:\n raise TypeError(f'`{name}.next` must take two arguments but found:\\n'\n f'{next_parameter_type}')\n\n float_type_at_clients = computation_types.at_clients(NORM_TF_TYPE)\n if not next_parameter_type[1].is_assignable_from(float_type_at_clients):\n raise TypeError(\n f'Second argument of `{name}.next` must be assignable from '\n f'{float_type_at_clients} but found {next_parameter_type[1]}')\n\n next_result_type = bound_process.next.type_signature.result\n if not bound_process.state_type.is_assignable_from(next_result_type):\n raise TypeError(f'Result type of `{name}.next` must consist of state only '\n f'but found result type:\\n{next_result_type}\\n'\n f'while the state type is:\\n{bound_process.state_type}')\n\n report_type = bound_process.report.type_signature.result\n estimated_value_type_at_server = computation_types.at_server(\n next_parameter_type[1].member)\n if not report_type.is_assignable_from(estimated_value_type_at_server):\n raise TypeError(\n f'Report type of `{name}.report` must be assignable from '\n f'{estimated_value_type_at_server} but found {report_type}.')\n\n\nclass SecureSumFactory(factory.UnweightedAggregationFactory):\n \"\"\"`AggregationProcess` factory for securely summing values.\n\n The created `tff.templates.AggregationProcess` uses the\n `tff.federated_secure_sum` operator for movement of all values from\n `tff.CLIENTS` to `tff.SERVER`.\n\n In order for values to be securely summed, their range needs to be known in\n advance and communicated to clients, so that clients can prepare the values in\n a form compatible with the `tff.federated_secure_sum` operator (that is,\n integers in range `[0, 2**b-1]` for some `b`), and for inverse mapping to be\n applied on the server. This will be done as specified by the\n `upper_bound_threshold` and `lower_bound_threshold` constructor arguments,\n with the following options:\n\n For integer values to be summed, these arguments must be `int` Python\n constants or integer Numpy scalars, and the values during execution will be\n clipped to these thresholds and then securely summed.\n\n For floating point values to be summed, the values during execution will be\n clipped to these thresholds, then uniformly quantized to integers in the range\n `[0, 2**32-1]`, and then securely summed.\n\n The `upper_bound_threshold` and `lower_bound_threshold` arguments can in this\n case be either `float` Python constants, float Numpy scalars, or instances of\n `tff.templates.EstimationProcess`, which adapts the thresholds between rounds\n of execution.\n\n In all cases, it is possible to specify only `upper_bound_threshold`, in which\n case this threshold will be treated as a bound on the absolute value of the\n value to be summed.\n\n For the case when floating point values are to be securely summed and more\n aggressive quantization is needed (i.e. less than 32 bits), the recommended\n pattern is to use `tff.aggregators.EncodedSumFactory` with this factory class\n as its inner aggregation factory.\n \"\"\"\n\n def __init__(self,\n upper_bound_threshold: ThresholdEstType,\n lower_bound_threshold: Optional[ThresholdEstType] = None):\n \"\"\"Initializes `SecureSumFactory`.\n\n Args:\n upper_bound_threshold: Either a `int` or `float` Python constant, a Numpy\n scalar, or a `tff.templates.EstimationProcess`, used for determining the\n upper bound before summation.\n lower_bound_threshold: Optional. Either a `int` or `float` Python\n constant, a Numpy scalar, or a `tff.templates.EstimationProcess`, used\n for determining the lower bound before summation. If specified, must be\n the same type as `upper_bound_threshold`.\n\n Raises:\n TypeError: If `upper_bound_threshold` and `lower_bound_threshold` are not\n instances of one of (`int`, `float` or\n `tff.templates.EstimationProcess`).\n ValueError: If `upper_bound_threshold` is provided as a negative constant.\n \"\"\"\n py_typecheck.check_type(upper_bound_threshold, ThresholdEstType.__args__)\n if lower_bound_threshold is not None:\n if not isinstance(lower_bound_threshold, type(upper_bound_threshold)):\n raise TypeError(\n f'Provided upper_bound_threshold and lower_bound_threshold '\n f'must have the same types, but found:\\n'\n f'type(upper_bound_threshold): {upper_bound_threshold}\\n'\n f'type(lower_bound_threshold): {lower_bound_threshold}')\n\n # Configuration specific for aggregating integer types.\n if _is_integer(upper_bound_threshold):\n self._config_mode = _Config.INT\n if lower_bound_threshold is None:\n _check_positive(upper_bound_threshold)\n lower_bound_threshold = -1 * upper_bound_threshold\n else:\n _check_upper_larger_than_lower(upper_bound_threshold,\n lower_bound_threshold)\n self._init_fn = _empty_state\n self._get_bounds_from_state = _create_get_bounds_const(\n upper_bound_threshold, lower_bound_threshold)\n self._update_state = lambda _, __, ___: _empty_state()\n self._secagg_bitwidth = math.ceil(\n math.log2(upper_bound_threshold - lower_bound_threshold))\n\n # Configuration specific for aggregating floating point types.\n else:\n self._config_mode = _Config.FLOAT\n if _is_float(upper_bound_threshold):\n # Bounds specified as Python constants.\n if lower_bound_threshold is None:\n _check_positive(upper_bound_threshold)\n lower_bound_threshold = -1.0 * upper_bound_threshold\n else:\n _check_upper_larger_than_lower(upper_bound_threshold,\n lower_bound_threshold)\n self._get_bounds_from_state = _create_get_bounds_const(\n upper_bound_threshold, lower_bound_threshold)\n self._init_fn = _empty_state\n self._update_state = lambda _, __, ___: _empty_state()\n else:\n # Bounds specified as an EstimationProcess.\n _check_bound_process(upper_bound_threshold, 'upper_bound_threshold')\n if lower_bound_threshold is None:\n self._get_bounds_from_state = _create_get_bounds_single_process(\n upper_bound_threshold)\n self._init_fn = upper_bound_threshold.initialize\n self._update_state = _create_update_state_single_process(\n upper_bound_threshold)\n else:\n _check_bound_process(lower_bound_threshold, 'lower_bound_threshold')\n self._get_bounds_from_state = _create_get_bounds_two_processes(\n upper_bound_threshold, lower_bound_threshold)\n self._init_fn = _create_initial_state_two_processes(\n upper_bound_threshold, lower_bound_threshold)\n self._update_state = _create_update_state_two_processes(\n upper_bound_threshold, lower_bound_threshold)\n\n def create(\n self,\n value_type: factory.ValueType) -> aggregation_process.AggregationProcess:\n self._check_value_type_compatible_with_config_mode(value_type)\n\n @computations.federated_computation(self._init_fn.type_signature.result,\n computation_types.FederatedType(\n value_type, placements.CLIENTS))\n def next_fn(state, value):\n # Server-side preparation.\n upper_bound, lower_bound = self._get_bounds_from_state(state)\n\n # Compute min and max *before* clipping and use it to update the state.\n value_max = intrinsics.federated_map(_reduce_nest_max, value)\n value_min = intrinsics.federated_map(_reduce_nest_min, value)\n new_state = self._update_state(state, value_min, value_max)\n\n # Clips value to [lower_bound, upper_bound] and securely sums it.\n summed_value = self._sum_securely(value, upper_bound, lower_bound)\n\n measurements = self._compute_measurements(upper_bound, lower_bound,\n value_max, value_min)\n return measured_process.MeasuredProcessOutput(new_state, summed_value,\n measurements)\n\n return aggregation_process.AggregationProcess(self._init_fn, next_fn)\n\n def _compute_measurements(self, upper_bound, lower_bound, value_max,\n value_min):\n \"\"\"Creates measurements to be reported. All values are summed securely.\"\"\"\n is_max_clipped = intrinsics.federated_map(\n computations.tf_computation(\n lambda bound, value: tf.cast(bound < value, COUNT_TF_TYPE)),\n (intrinsics.federated_broadcast(upper_bound), value_max))\n max_clipped_count = intrinsics.federated_secure_sum(\n is_max_clipped, bitwidth=1)\n is_min_clipped = intrinsics.federated_map(\n computations.tf_computation(\n lambda bound, value: tf.cast(bound > value, COUNT_TF_TYPE)),\n (intrinsics.federated_broadcast(lower_bound), value_min))\n min_clipped_count = intrinsics.federated_secure_sum(\n is_min_clipped, bitwidth=1)\n measurements = collections.OrderedDict(\n secure_upper_clipped_count=max_clipped_count,\n secure_lower_clipped_count=min_clipped_count,\n secure_upper_threshold=upper_bound,\n secure_lower_threshold=lower_bound)\n return intrinsics.federated_zip(measurements)\n\n def _sum_securely(self, value, upper_bound, lower_bound):\n \"\"\"Securely sums `value` placed at CLIENTS.\"\"\"\n if self._config_mode == _Config.INT:\n value = intrinsics.federated_map(\n _client_shift, (value, intrinsics.federated_broadcast(upper_bound),\n intrinsics.federated_broadcast(lower_bound)))\n value = intrinsics.federated_secure_sum(value, self._secagg_bitwidth)\n num_summands = intrinsics.federated_sum(_client_one())\n value = intrinsics.federated_map(_server_shift,\n (value, lower_bound, num_summands))\n return value\n elif self._config_mode == _Config.FLOAT:\n return federated_aggregations.secure_quantized_sum(\n value, lower_bound, upper_bound)\n else:\n raise ValueError(f'Unexpected internal config type: {self._config_mode}')\n\n def _check_value_type_compatible_with_config_mode(self, value_type):\n py_typecheck.check_type(value_type, factory.ValueType.__args__)\n\n if self._config_mode == _Config.INT:\n if not type_analysis.is_structure_of_integers(value_type):\n raise TypeError(\n f'The `SecureSumFactory` was configured to work with integer '\n f'dtypes. All values in provided `value_type` hence must be of '\n f'integer dtype. \\nProvided value_type: {value_type}')\n elif self._config_mode == _Config.FLOAT:\n if not type_analysis.is_structure_of_floats(value_type):\n raise TypeError(\n f'The `SecureSumFactory` was configured to work with floating '\n f'point dtypes. All values in provided `value_type` hence must be '\n f'of floating point dtype. \\nProvided value_type: {value_type}')\n else:\n raise ValueError(f'Unexpected internal config type: {self._config_mode}')\n\n\ndef _check_positive(value):\n if value <= 0:\n raise ValueError(\n f'If only `upper_bound_threshold` is specified as a Python constant, '\n f'it must be positive. Its negative will be used as a lower bound '\n f'which would be larger than the upper bound. \\n'\n f'Provided `upper_bound_threshold`: {value}')\n\n\ndef _check_upper_larger_than_lower(upper_bound_threshold,\n lower_bound_threshold):\n if upper_bound_threshold <= lower_bound_threshold:\n raise ValueError(\n f'The provided `upper_bound_threshold` must be larger than the '\n f'provided `lower_bound_threshold`, but received:\\n'\n f'`upper_bound_threshold`: {upper_bound_threshold}\\n'\n f'`lower_bound_threshold`: {lower_bound_threshold}\\n')\n\n\ndef _is_integer(value):\n is_py_int = isinstance(value, int)\n is_np_int = isinstance(value, np.ndarray) and bool(\n np.issubdtype(value.dtype, np.integer))\n return is_py_int or is_np_int\n\n\ndef _is_float(value):\n is_py_float = isinstance(value, float)\n is_np_float = isinstance(value, np.ndarray) and bool(\n np.issubdtype(value.dtype, np.floating))\n return is_py_float or is_np_float\n\n\[email protected]_computation()\ndef _reduce_nest_max(value):\n max_list = tf.nest.map_structure(tf.reduce_max, tf.nest.flatten(value))\n return tf.reduce_max(tf.stack(max_list))\n\n\[email protected]_computation()\ndef _reduce_nest_min(value):\n min_list = tf.nest.map_structure(tf.reduce_min, tf.nest.flatten(value))\n return tf.reduce_min(tf.stack(min_list))\n\n\[email protected]_computation()\ndef _client_shift(value, upper_bound, lower_bound):\n return tf.nest.map_structure(\n lambda v: tf.clip_by_value(v, lower_bound, upper_bound) - lower_bound,\n value)\n\n\[email protected]_computation()\ndef _server_shift(value, lower_bound, num_summands):\n return tf.nest.map_structure(\n lambda v: v + (lower_bound * tf.cast(num_summands, lower_bound.dtype)),\n value)\n\n\[email protected]_computation()\ndef _empty_state():\n return intrinsics.federated_value((), placements.SERVER)\n\n\ndef _client_one():\n return intrinsics.federated_eval(\n computations.tf_computation(lambda: tf.constant(1, tf.int32)),\n placements.CLIENTS)\n\n\ndef _create_initial_state_two_processes(upper_bound_process,\n lower_bound_process):\n\n @computations.federated_computation()\n def initial_state():\n return intrinsics.federated_zip(\n (upper_bound_process.initialize(), lower_bound_process.initialize()))\n\n return initial_state\n\n\ndef _create_get_bounds_const(upper_bound, lower_bound):\n\n def get_bounds(state):\n del state # Unused.\n return (intrinsics.federated_value(upper_bound, placements.SERVER),\n intrinsics.federated_value(lower_bound, placements.SERVER))\n\n return get_bounds\n\n\ndef _create_get_bounds_single_process(process):\n\n def get_bounds(state):\n upper_bound = process.report(state)\n lower_bound = intrinsics.federated_map(\n computations.tf_computation(lambda x: x * -1.0), upper_bound)\n return upper_bound, lower_bound\n\n return get_bounds\n\n\ndef _create_get_bounds_two_processes(upper_bound_process, lower_bound_process):\n\n def get_bounds(state):\n upper_bound = upper_bound_process.report(state[0])\n lower_bound = lower_bound_process.report(state[1])\n return upper_bound, lower_bound\n\n return get_bounds\n\n\ndef _create_update_state_single_process(process):\n\n def update_state(state, value_min, value_max):\n abs_max_fn = computations.tf_computation(\n lambda x, y: tf.maximum(tf.abs(x), tf.abs(y)))\n abs_value_max = intrinsics.federated_map(abs_max_fn, (value_min, value_max))\n return process.next(state, abs_value_max)\n\n return update_state\n\n\ndef _create_update_state_two_processes(upper_bound_process,\n lower_bound_process):\n\n def update_state(state, value_min, value_max):\n return intrinsics.federated_zip(\n (upper_bound_process.next(state[0], value_max),\n lower_bound_process.next(state[1], value_min)))\n\n return update_state\n", "# Copyright 2018, The TensorFlow Federated Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Base class for TFF test cases.\"\"\"\n\nfrom absl.testing import absltest\nimport tensorflow as tf\n\nfrom tensorflow_federated.python.core.api import computation_types\n\n\nclass TestCase(tf.test.TestCase, absltest.TestCase):\n \"\"\"Base class for TensroFlow Federated tests.\"\"\"\n\n def setUp(self):\n super().setUp()\n tf.keras.backend.clear_session()\n\n def assert_type_assignable_from(self, target_type, source_type):\n # Reraise the exception outside of `except` so as to avoid setting\n # the `.__cause__` on the final error (repeating everything).\n message = None\n try:\n target_type.check_assignable_from(source_type)\n except computation_types.TypeNotAssignableError as e:\n message = e.message\n if message is not None:\n self.fail(message)\n\n def assert_types_equivalent(self, first_type, second_type):\n message = None\n try:\n first_type.check_equivalent_to(second_type)\n except computation_types.TypesNotEquivalentError as e:\n message = e.message\n if message is not None:\n self.fail(message)\n\n def assert_types_identical(self, first_type, second_type):\n message = None\n try:\n first_type.check_identical_to(second_type)\n except computation_types.TypesNotIdenticalError as e:\n message = e.message\n if message is not None:\n self.fail(message)\n\n def assert_nested_struct_eq(self, x, y):\n \"\"\"Asserts that nested structures 'x' and 'y' are the same.\n\n Args:\n x: One nested structure.\n y: Another nested structure.\n\n Raises:\n ValueError: if the structures are not the same.\n \"\"\"\n try:\n tf.nest.assert_same_structure(x, y)\n except ValueError:\n self.fail('Expected structures to have the same shape.')\n xl = tf.nest.flatten(x)\n yl = tf.nest.flatten(y)\n if len(xl) != len(yl):\n self.fail('The sizes of structures {} and {} mismatch.'.format(\n str(len(xl)), str(len(yl))))\n for xe, ye in zip(xl, yl):\n if xe != ye:\n self.fail('Mismatching elements {} and {}.'.format(str(xe), str(ye)))\n\n\ndef main():\n \"\"\"Runs all unit tests with TF 2.0 features enabled.\n\n This function should only be used if TensorFlow code is being tested.\n \"\"\"\n tf.test.main()\n", "# Copyright 2019 Google LLC. 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\"\"\"ResNet v2 model for Keras using Batch or Group Normalization.\n\nRelated papers/blogs:\n- http://arxiv.org/pdf/1603.05027v2.pdf\n\n\"\"\"\nimport collections\nimport enum\nfrom typing import List, Optional, Tuple\n\nimport tensorflow as tf\nimport tensorflow_addons.layers.normalizations as tfa_norms\n\nBATCH_NORM_DECAY = 0.997\nBATCH_NORM_EPSILON = 1e-5\nL2_WEIGHT_DECAY = 1e-4\n\n\ndef _check_iterable_with_positive_ints(structure):\n if not isinstance(structure, collections.abc.Iterable):\n return False\n return all(isinstance(a, int) and a > 0 for a in structure)\n\n\nclass ResidualBlock(enum.Enum):\n basic = 'basic'\n bottleneck = 'bottleneck'\n\n\nclass NormLayer(enum.Enum):\n group_norm = 'group_norm'\n batch_norm = 'batch_norm'\n\n\ndef _norm_relu(input_tensor, norm):\n \"\"\"Applies normalization and ReLU activation to an input tensor.\n\n Args:\n input_tensor: The `tf.Tensor` to apply the block to.\n norm: A `NormLayer` specifying the type of normalization layer used.\n\n Returns:\n A `tf.Tensor`.\n \"\"\"\n if tf.keras.backend.image_data_format() == 'channels_last':\n channel_axis = 3\n else:\n channel_axis = 1\n\n if norm is NormLayer.group_norm:\n x = tfa_norms.GroupNormalization(axis=channel_axis)(input_tensor)\n elif norm is NormLayer.batch_norm:\n x = tf.keras.layers.BatchNormalization(\n axis=channel_axis,\n momentum=BATCH_NORM_DECAY,\n epsilon=BATCH_NORM_EPSILON)(\n input_tensor)\n else:\n raise ValueError('The norm argument must be of type `NormLayer`.')\n return tf.keras.layers.Activation('relu')(x)\n\n\ndef _conv_norm_relu(input_tensor, filters, kernel_size, norm, strides=(1, 1)):\n \"\"\"Applies convolution, normalization, and ReLU activation to an input tensor.\n\n These functions are applied to `input_tensor` in that exact order.\n\n Args:\n input_tensor: The `tf.Tensor` to apply the block to.\n filters: An integer specifying the number of filters in the convolutional\n layer.\n kernel_size: A tuple of specifying the kernel height and width\n (respectively) in the convolutional layer.\n norm: A `NormLayer` specifying the type of normalization layer used.\n strides: A tuple of two integers specifying the stride height and width\n (respectively) in the convolutional layers.\n\n Returns:\n A `tf.Tensor`.\n \"\"\"\n x = tf.keras.layers.Conv2D(\n filters,\n kernel_size,\n strides=strides,\n padding='same',\n use_bias=False,\n kernel_initializer='he_normal',\n kernel_regularizer=tf.keras.regularizers.l2(L2_WEIGHT_DECAY))(\n input_tensor)\n return _norm_relu(x, norm=norm)\n\n\ndef _norm_relu_conv(input_tensor, filters, kernel_size, norm, strides=(1, 1)):\n \"\"\"Applies normalization, ReLU activation, and convolution to an input tensor.\n\n These functions are applied to `input_tensor` in that exact order.\n\n Args:\n input_tensor: The `tf.Tensor` to apply the block to.\n filters: An integer specifying the number of filters in the convolutional\n layer.\n kernel_size: A tuple of specifying the kernel height and width\n (respectively) in the convolutional layer.\n norm: A `NormLayer` specifying the type of normalization layer used.\n strides: A tuple of two integers specifying the stride height and width\n (respectively) in the convolutional layers.\n\n Returns:\n A `tf.Tensor`.\n \"\"\"\n x = _norm_relu(input_tensor, norm=norm)\n x = tf.keras.layers.Conv2D(\n filters,\n kernel_size,\n strides=strides,\n padding='same',\n use_bias=False,\n kernel_initializer='he_normal',\n kernel_regularizer=tf.keras.regularizers.l2(L2_WEIGHT_DECAY))(x)\n return x\n\n\ndef _shortcut(input_tensor, residual, norm):\n \"\"\"Computes the output of a shortcut block between an input and residual.\n\n More specifically, this block takes `input` and adds it to `residual`. If\n `input` is not the same shape as `residual`, then we first apply an\n appropriately-sized convolutional layer to alter its shape to that of\n `residual` and normalize via `norm` before adding it to `residual`.\n\n Args:\n input_tensor: The `tf.Tensor` to apply the block to.\n residual: A `tf.Tensor` added to `input_tensor` after it has been passed\n through a convolution and normalization.\n norm: A `NormLayer` specifying the type of normalization layer used.\n\n Returns:\n A `tf.Tensor`.\n \"\"\"\n input_shape = tf.keras.backend.int_shape(input_tensor)\n residual_shape = tf.keras.backend.int_shape(residual)\n\n if tf.keras.backend.image_data_format() == 'channels_last':\n row_axis = 1\n col_axis = 2\n channel_axis = 3\n else:\n channel_axis = 1\n row_axis = 2\n col_axis = 3\n\n stride_width = int(round(input_shape[row_axis] / residual_shape[row_axis]))\n stride_height = int(round(input_shape[col_axis] / residual_shape[col_axis]))\n equal_channels = input_shape[channel_axis] == residual_shape[channel_axis]\n\n shortcut = input_tensor\n # Use a 1-by-1 kernel if the strides are greater than 1, or there the input\n # and residual tensors have different numbers of channels.\n if stride_width > 1 or stride_height > 1 or not equal_channels:\n shortcut = tf.keras.layers.Conv2D(\n filters=residual_shape[channel_axis],\n kernel_size=(1, 1),\n strides=(stride_width, stride_height),\n padding='valid',\n use_bias=False,\n kernel_initializer='he_normal',\n kernel_regularizer=tf.keras.regularizers.l2(L2_WEIGHT_DECAY))(\n shortcut)\n\n if norm is NormLayer.group_norm:\n shortcut = tfa_norms.GroupNormalization(axis=channel_axis)(shortcut)\n elif norm is NormLayer.batch_norm:\n shortcut = tf.keras.layers.BatchNormalization(\n axis=channel_axis,\n momentum=BATCH_NORM_DECAY,\n epsilon=BATCH_NORM_EPSILON)(shortcut)\n else:\n raise ValueError('The norm argument must be of type `NormLayer`.')\n\n return tf.keras.layers.add([shortcut, residual])\n\n\ndef _basic_block(input_tensor,\n filters,\n norm,\n strides=(1, 1),\n normalize_first=True):\n \"\"\"Computes the forward pass of an input tensor through a basic block.\n\n Specifically, the basic block consists of two convolutional layers with\n `filters` filters, with additional layers for ReLU activation and\n normalization layers. All kernels are of shape (3, 3). Finally, the output\n is passed through a shortcut block.\n\n Args:\n input_tensor: The `tf.Tensor` to apply the block to.\n filters: An integer specifying the number of filters in the convolutional\n layers.\n norm: A `NormLayer` specifying the type of normalization layer used.\n strides: A tuple of two integers specifying the stride height and width\n (respectively) in the convolutional layers.\n normalize_first: If set to `True`, normalization is performed before the\n first convolution. If `False`, no normalization is performed before the\n first convolutional layer.\n\n Returns:\n A `tf.Tensor`.\n \"\"\"\n if normalize_first:\n x = _norm_relu_conv(\n input_tensor,\n filters=filters,\n kernel_size=(3, 3),\n strides=strides,\n norm=norm)\n else:\n x = tf.keras.layers.Conv2D(\n filters=filters,\n kernel_size=(3, 3),\n strides=strides,\n padding='same',\n use_bias=False,\n kernel_initializer='he_normal',\n kernel_regularizer=tf.keras.regularizers.l2(L2_WEIGHT_DECAY))(\n input_tensor)\n\n x = _norm_relu_conv(\n x, filters=filters, kernel_size=(3, 3), strides=strides, norm=norm)\n return _shortcut(input_tensor, x, norm=norm)\n\n\ndef _bottleneck_block(input_tensor,\n filters,\n norm,\n strides=(1, 1),\n normalize_first=True):\n \"\"\"Applies a bottleneck convolutional block to a given input tensor.\n\n Specifically, this applies a sequence of 3 normalization, ReLU, and\n convolutional layers to the input tensor, followed by a shortcut block. The\n convolutions use filters of shape (1, 1), (3, 3), and (1, 1), respectively.\n\n Args:\n input_tensor: The `tf.Tensor` to apply the block to.\n filters: An integer specifying the number of filters in the first two\n convolutional layers. The third uses `4*filters`.\n norm: A `NormLayer` specifying the type of normalization layer used.\n strides: A tuple of two integers specifying the stride height and width\n (respectively) in the convolutional layers.\n normalize_first: If set to `True`, normalization is performed before the\n first convolution. If `False`, no normalization is performed before the\n first convolutional layer.\n\n Returns:\n A `tf.Tensor`.\n \"\"\"\n if normalize_first:\n x = _norm_relu_conv(\n input_tensor,\n filters=filters,\n kernel_size=(1, 1),\n strides=strides,\n norm=norm)\n else:\n x = tf.keras.layers.Conv2D(\n filters=filters,\n kernel_size=(1, 1),\n strides=strides,\n padding='same',\n use_bias=False,\n kernel_initializer='he_normal',\n kernel_regularizer=tf.keras.regularizers.l2(L2_WEIGHT_DECAY))(\n input_tensor)\n\n x = _norm_relu_conv(\n x, filters=filters, kernel_size=(3, 3), strides=strides, norm=norm)\n\n x = _norm_relu_conv(\n x, filters=filters * 4, kernel_size=(1, 1), strides=strides, norm=norm)\n return _shortcut(input_tensor, x, norm=norm)\n\n\ndef _residual_block(input_tensor,\n block_function,\n filters,\n num_blocks,\n norm,\n strides=(1, 1),\n is_first_layer=False):\n \"\"\"Builds a residual block with repeating bottleneck or basic blocks.\"\"\"\n x = input_tensor\n for i in range(num_blocks):\n if is_first_layer and i == 0:\n normalize_first = False\n else:\n normalize_first = True\n\n x = block_function(\n input_tensor=x,\n filters=filters,\n strides=strides,\n normalize_first=normalize_first,\n norm=norm)\n return x\n\n\ndef create_resnet(\n input_shape: Tuple[int, int, int],\n num_classes: int = 10,\n residual_block: ResidualBlock = ResidualBlock.bottleneck,\n repetitions: Optional[List[int]] = None,\n initial_filters: int = 64,\n initial_strides: Tuple[int, int] = (2, 2),\n initial_kernel_size: Tuple[int, int] = (7, 7),\n initial_max_pooling: bool = True,\n norm_layer: NormLayer = NormLayer.group_norm) -> tf.keras.Model:\n \"\"\"Creates a ResNet v2 model with batch or group normalization.\n\n Instantiates the architecture from http://arxiv.org/pdf/1603.05027v2.pdf.\n The ResNet contains stages of residual blocks, each with sequences of\n convolutional, ReLU, and normalization layers. The order depends on the\n choice of `block`, and the type of normalization is governed by `norm`.\n\n Args:\n input_shape: A length 3 tuple of positive integeres dictating the number of\n rows, columns, and channels of an input. Can be in channel-first or\n channel-last format.\n num_classes: A positive integer describing the number of output classes.\n residual_block: A `ResidualBlock` describing what type of residual block\n is used throughout the ResNet.\n repetitions: An optional list of integers describing the number of blocks\n within each stage. If None, defaults to the resnet50 repetitions of [3, 4,\n 6, 3].\n initial_filters: An integer specifying the number of filters in the initial\n convolutional layer.\n initial_strides: A tuple of two integers specifying the stride height and\n width (respectively) in the initial convolutional layer.\n initial_kernel_size: A tuple of two integers specifying the kernel height\n and width (respectively) in the initial convolutional layer.\n initial_max_pooling: Whether to use max pooling after the initial\n convolutional layer.\n norm_layer: A `NormLayer` describing which normalization layer is used\n in the resulting model.\n\n Returns:\n An uncompiled `tf.keras.Model`.\n\n Raises:\n ValueError: If `input_shape` is not a length three iterable with positive\n integer values, if `num_classes` is not a positive integer, if\n `residual_block` is not of type `ResidualBlock`, if `repetitions` is not\n `None` and is not an iterable with positive integer elements, if\n `initial_filters` is not positive, if `initial_strides` and\n `initial_kernel_size` are not length 2 iterables with positive integer\n elements, if `norm_layer` is not of type `NormLayer`.\n \"\"\"\n\n if not _check_iterable_with_positive_ints(\n input_shape) or len(input_shape) != 3:\n raise ValueError('input_shape must be an iterable of length 3 containing '\n 'only positive integers.')\n\n if num_classes < 1:\n raise ValueError('num_classes must be a positive integer.')\n\n if residual_block is ResidualBlock.basic:\n block_fn = _basic_block\n elif residual_block is ResidualBlock.bottleneck:\n block_fn = _bottleneck_block\n else:\n raise ValueError('residual_block must be of type `ResidualBlock`.')\n\n if not repetitions:\n repetitions = [3, 4, 6, 3]\n elif not _check_iterable_with_positive_ints(repetitions):\n raise ValueError(\n 'repetitions must be None or an iterable containing positive integers')\n\n if initial_filters < 1:\n raise ValueError('initial_filters must be a positive integer.')\n\n if not _check_iterable_with_positive_ints(\n initial_strides) or len(initial_strides) != 2:\n raise ValueError('initial_strides must be an iterable of length 2 '\n 'containing only positive integers.')\n\n if not _check_iterable_with_positive_ints(\n initial_kernel_size) or len(initial_kernel_size) != 2:\n raise ValueError('initial_kernel_size must be an iterable of length 2 '\n 'containing only positive integers.')\n\n if not isinstance(norm_layer, NormLayer):\n raise ValueError('norm_layer must be of type `NormLayer`.')\n\n img_input = tf.keras.layers.Input(shape=input_shape)\n x = _conv_norm_relu(\n img_input,\n filters=initial_filters,\n kernel_size=initial_kernel_size,\n strides=initial_strides,\n norm=norm_layer)\n\n if initial_max_pooling:\n x = tf.keras.layers.MaxPooling2D(\n pool_size=(3, 3), strides=initial_strides, padding='same')(x)\n\n filters = initial_filters\n\n for i, r in enumerate(repetitions):\n x = _residual_block(\n x,\n block_fn,\n filters=filters,\n num_blocks=r,\n is_first_layer=(i == 0),\n norm=norm_layer)\n filters *= 2\n\n # Final activation in the residual blocks\n x = _norm_relu(x, norm=norm_layer)\n\n # Classification block\n x = tf.keras.layers.GlobalAveragePooling2D()(x)\n\n x = tf.keras.layers.Dense(\n num_classes,\n activation='softmax',\n kernel_initializer=tf.keras.initializers.RandomNormal(stddev=0.01),\n kernel_regularizer=tf.keras.regularizers.l2(L2_WEIGHT_DECAY),\n bias_regularizer=tf.keras.regularizers.l2(L2_WEIGHT_DECAY))(x)\n\n model = tf.keras.models.Model(img_input, x)\n return model\n\n\ndef create_resnet18(\n input_shape: Tuple[int, int, int],\n num_classes: int,\n norm_layer: NormLayer = NormLayer.group_norm) -> tf.keras.Model:\n \"\"\"Creates a ResNet-18 with basic residual blocks.\n\n Args:\n input_shape: A length 3 tuple of positive integeres dictating the number of\n rows, columns, and channels of an input. Can be in channel-first or\n channel-last format.\n num_classes: A positive integer describing the number of output classes.\n norm_layer: A `NormLayer` describing which normalization layer is used\n in the resulting model.\n\n Returns:\n An uncompiled `tf.keras.Model`.\n \"\"\"\n return create_resnet(\n input_shape,\n num_classes,\n residual_block=ResidualBlock.basic,\n repetitions=[2, 2, 2, 2],\n norm_layer=norm_layer)\n\n\ndef create_resnet34(\n input_shape: Tuple[int, int, int],\n num_classes: int,\n norm_layer: NormLayer = NormLayer.group_norm) -> tf.keras.Model:\n \"\"\"Creates a ResNet-34 with basic residual blocks.\n\n Args:\n input_shape: A length 3 tuple of positive integeres dictating the number of\n rows, columns, and channels of an input. Can be in channel-first or\n channel-last format.\n num_classes: A positive integer describing the number of output classes.\n norm_layer: A `NormLayer` describing which normalization layer is used\n in the resulting model.\n\n Returns:\n An uncompiled `tf.keras.Model`.\n \"\"\"\n return create_resnet(\n input_shape,\n num_classes,\n residual_block=ResidualBlock.basic,\n repetitions=[3, 4, 6, 3],\n norm_layer=norm_layer)\n\n\ndef create_resnet50(\n input_shape: Tuple[int, int, int],\n num_classes: int,\n norm_layer: NormLayer = NormLayer.group_norm) -> tf.keras.Model:\n \"\"\"Creates a ResNet-50 model with bottleneck residual blocks.\n\n Args:\n input_shape: A length 3 tuple of positive integeres dictating the number of\n rows, columns, and channels of an input. Can be in channel-first or\n channel-last format.\n num_classes: A positive integer describing the number of output classes.\n norm_layer: A `NormLayer` describing which normalization layer is used\n in the resulting model.\n\n Returns:\n An uncompiled `tf.keras.Model`.\n \"\"\"\n return create_resnet(\n input_shape,\n num_classes,\n residual_block=ResidualBlock.bottleneck,\n repetitions=[3, 4, 6, 3],\n norm_layer=norm_layer)\n\n\ndef create_resnet101(\n input_shape: Tuple[int, int, int],\n num_classes: int,\n norm_layer: NormLayer = NormLayer.group_norm) -> tf.keras.Model:\n \"\"\"Creates a ResNet-101 model with bottleneck residual blocks.\n\n Args:\n input_shape: A length 3 tuple of positive integeres dictating the number of\n rows, columns, and channels of an input. Can be in channel-first or\n channel-last format.\n num_classes: A positive integer describing the number of output classes.\n norm_layer: A `NormLayer` describing which normalization layer is used\n in the resulting model.\n\n Returns:\n An uncompiled `tf.keras.Model`.\n \"\"\"\n return create_resnet(\n input_shape,\n num_classes,\n residual_block=ResidualBlock.bottleneck,\n repetitions=[3, 4, 23, 3],\n norm_layer=norm_layer)\n\n\ndef create_resnet152(\n input_shape: Tuple[int, int, int],\n num_classes: int,\n norm_layer: NormLayer = NormLayer.group_norm) -> tf.keras.Model:\n \"\"\"Creates a ResNet-152 model with bottleneck residual blocks.\n\n Args:\n input_shape: A length 3 tuple of positive integeres dictating the number of\n rows, columns, and channels of an input. Can be in channel-first or\n channel-last format.\n num_classes: A positive integer describing the number of output classes.\n norm_layer: A `NormLayer` describing which normalization layer is used\n in the resulting model.\n\n Returns:\n An uncompiled `tf.keras.Model`.\n \"\"\"\n return create_resnet(\n input_shape,\n num_classes,\n residual_block=ResidualBlock.bottleneck,\n repetitions=[3, 8, 36, 3],\n norm_layer=norm_layer)\n", "# Copyright 2018, The TensorFlow Federated Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport collections\n\nimport attr\nimport tensorflow as tf\n\nfrom tensorflow_federated.python.common_libs import golden\nfrom tensorflow_federated.python.core.api import computation_types\nfrom tensorflow_federated.python.core.api import test_case\nfrom tensorflow_federated.python.core.impl.compiler import building_blocks\nfrom tensorflow_federated.python.core.impl.computation import computation_impl\nfrom tensorflow_federated.python.core.impl.context_stack import get_context_stack\nfrom tensorflow_federated.python.core.impl.context_stack import runtime_error_context\nfrom tensorflow_federated.python.core.impl.types import placement_literals\nfrom tensorflow_federated.python.core.impl.wrappers import computation_wrapper\nfrom tensorflow_federated.python.core.impl.wrappers import computation_wrapper_instances\n\n\nclass TensorflowWrapperTest(test_case.TestCase):\n\n def test_invoke_with_typed_lambda(self):\n foo = lambda x: x > 10\n foo = computation_wrapper_instances.tensorflow_wrapper(foo, tf.int32)\n self.assertEqual(foo.type_signature.compact_representation(),\n '(int32 -> bool)')\n\n def test_invoke_with_polymorphic_lambda(self):\n foo = lambda x: x > 10\n foo = computation_wrapper_instances.tensorflow_wrapper(foo)\n\n concrete_fn = foo.fn_for_argument_type(\n computation_types.TensorType(tf.int32))\n self.assertEqual(concrete_fn.type_signature.compact_representation(),\n '(int32 -> bool)')\n concrete_fn = foo.fn_for_argument_type(\n computation_types.TensorType(tf.float32))\n self.assertEqual(concrete_fn.type_signature.compact_representation(),\n '(float32 -> bool)')\n\n def test_invoke_with_no_arg_lambda(self):\n foo = lambda: 10\n foo = computation_wrapper_instances.tensorflow_wrapper(foo)\n self.assertEqual(foo.type_signature.compact_representation(), '( -> int32)')\n\n def test_invoke_with_typed_fn(self):\n\n def foo(x):\n return x > 10\n\n foo = computation_wrapper_instances.tensorflow_wrapper(foo, tf.int32)\n self.assertEqual(foo.type_signature.compact_representation(),\n '(int32 -> bool)')\n\n def test_invoke_with_polymorphic_fn(self):\n\n def foo(x):\n return x > 10\n\n foo = computation_wrapper_instances.tensorflow_wrapper(foo)\n\n concrete_fn = foo.fn_for_argument_type(\n computation_types.TensorType(tf.int32))\n self.assertEqual(concrete_fn.type_signature.compact_representation(),\n '(int32 -> bool)')\n concrete_fn = foo.fn_for_argument_type(\n computation_types.TensorType(tf.float32))\n self.assertEqual(concrete_fn.type_signature.compact_representation(),\n '(float32 -> bool)')\n\n def test_invoke_with_no_arg_fn(self):\n\n def foo():\n return 10\n\n foo = computation_wrapper_instances.tensorflow_wrapper(foo)\n self.assertEqual(foo.type_signature.compact_representation(), '( -> int32)')\n\n def test_decorate_as_typed_fn(self):\n\n @computation_wrapper_instances.tensorflow_wrapper(tf.int32)\n def foo(x):\n return x > 10\n\n self.assertEqual(foo.type_signature.compact_representation(),\n '(int32 -> bool)')\n\n def test_decorate_as_polymorphic_fn(self):\n\n @computation_wrapper_instances.tensorflow_wrapper\n def foo(x):\n return x > 10\n\n concrete_fn = foo.fn_for_argument_type(\n computation_types.TensorType(tf.int32))\n self.assertEqual(concrete_fn.type_signature.compact_representation(),\n '(int32 -> bool)')\n concrete_fn = foo.fn_for_argument_type(\n computation_types.TensorType(tf.float32))\n self.assertEqual(concrete_fn.type_signature.compact_representation(),\n '(float32 -> bool)')\n\n def test_decorate_as_no_arg_fn(self):\n\n @computation_wrapper_instances.tensorflow_wrapper\n def foo():\n return 10\n\n self.assertEqual(foo.type_signature.compact_representation(), '( -> int32)')\n\n def test_invoke_with_typed_tf_function(self):\n\n @tf.function\n def foo(x):\n return x > 10\n\n foo = computation_wrapper_instances.tensorflow_wrapper(foo, tf.int32)\n self.assertEqual(foo.type_signature.compact_representation(),\n '(int32 -> bool)')\n\n def test_invoke_with_polymorphic_tf_function(self):\n\n @tf.function\n def foo(x):\n return x > 10\n\n foo = computation_wrapper_instances.tensorflow_wrapper(foo)\n\n concrete_fn = foo.fn_for_argument_type(\n computation_types.TensorType(tf.int32))\n self.assertEqual(concrete_fn.type_signature.compact_representation(),\n '(int32 -> bool)')\n concrete_fn = foo.fn_for_argument_type(\n computation_types.TensorType(tf.float32))\n self.assertEqual(concrete_fn.type_signature.compact_representation(),\n '(float32 -> bool)')\n\n def test_invoke_with_no_arg_tf_function(self):\n\n @tf.function\n def foo():\n return 10\n\n foo = computation_wrapper_instances.tensorflow_wrapper(foo)\n self.assertEqual(foo.type_signature.compact_representation(), '( -> int32)')\n\n def test_takes_tuple_typed(self):\n\n @tf.function\n def foo(t):\n return t[0] + t[1]\n\n foo = computation_wrapper_instances.tensorflow_wrapper(\n foo, (tf.int32, tf.int32))\n self.assertEqual(foo.type_signature.compact_representation(),\n '(<int32,int32> -> int32)')\n\n def test_takes_tuple_polymorphic(self):\n\n def foo(t):\n return t[0] + t[1]\n\n foo = computation_wrapper_instances.tensorflow_wrapper(foo)\n\n concrete_fn = foo.fn_for_argument_type(\n computation_types.StructType([\n computation_types.TensorType(tf.int32),\n computation_types.TensorType(tf.int32),\n ]))\n self.assertEqual(concrete_fn.type_signature.compact_representation(),\n '(<int32,int32> -> int32)')\n concrete_fn = foo.fn_for_argument_type(\n computation_types.StructType([\n computation_types.TensorType(tf.float32),\n computation_types.TensorType(tf.float32),\n ]))\n self.assertEqual(concrete_fn.type_signature.compact_representation(),\n '(<float32,float32> -> float32)')\n\n def test_takes_structured_tuple_typed(self):\n MyType = collections.namedtuple('MyType', ['x', 'y']) # pylint: disable=invalid-name\n\n @tf.function\n def foo(x, t, l, odict, my_type):\n self.assertIsInstance(x, tf.Tensor)\n self.assertIsInstance(t, tuple)\n self.assertIsInstance(l, list)\n self.assertIsInstance(odict, collections.OrderedDict)\n self.assertIsInstance(my_type, MyType)\n return x + t[0] + l[0] + odict['foo'] + my_type.x\n\n foo = computation_wrapper_instances.tensorflow_wrapper(\n foo, [\n tf.int32,\n (tf.int32, tf.int32),\n [tf.int32, tf.int32],\n collections.OrderedDict([('foo', tf.int32), ('bar', tf.int32)]),\n MyType(tf.int32, tf.int32),\n ])\n self.assertEqual(\n foo.type_signature.compact_representation(),\n '(<x=int32,t=<int32,int32>,l=<int32,int32>,odict=<foo=int32,bar=int32>,my_type=<x=int32,y=int32>> -> int32)'\n )\n\n def test_takes_structured_tuple_polymorphic(self):\n MyType = collections.namedtuple('MyType', ['x', 'y']) # pylint: disable=invalid-name\n\n @tf.function\n def foo(x, t, l, odict, my_type):\n self.assertIsInstance(x, tf.Tensor)\n self.assertIsInstance(t, tuple)\n self.assertIsInstance(l, list)\n self.assertIsInstance(odict, collections.OrderedDict)\n self.assertIsInstance(my_type, MyType)\n return x + t[0] + l[0] + odict['foo'] + my_type.x\n\n foo = computation_wrapper_instances.tensorflow_wrapper(foo)\n\n concrete_fn = foo.fn_for_argument_type(\n computation_types.to_type([\n tf.int32,\n (tf.int32, tf.int32),\n [tf.int32, tf.int32],\n collections.OrderedDict([('foo', tf.int32), ('bar', tf.int32)]),\n MyType(tf.int32, tf.int32),\n ]))\n self.assertEqual(\n concrete_fn.type_signature.compact_representation(),\n '(<int32,<int32,int32>,<int32,int32>,<foo=int32,bar=int32>,<x=int32,y=int32>> -> int32)'\n )\n concrete_fn = foo.fn_for_argument_type(\n computation_types.to_type([\n tf.float32,\n (tf.float32, tf.float32),\n [tf.float32, tf.float32],\n collections.OrderedDict([('foo', tf.float32), ('bar', tf.float32)]),\n MyType(tf.float32, tf.float32),\n ]))\n self.assertEqual(\n concrete_fn.type_signature.compact_representation(),\n '(<float32,<float32,float32>,<float32,float32>,<foo=float32,bar=float32>,<x=float32,y=float32>> -> float32)'\n )\n\n def test_returns_tuple_structured(self):\n MyType = collections.namedtuple('MyType', ['x', 'y']) # pylint: disable=invalid-name\n\n @tf.function\n def foo():\n return (\n 1,\n (2, 3.0),\n [4, 5.0],\n collections.OrderedDict([('foo', 6), ('bar', 7.0)]),\n MyType(True, False),\n )\n\n foo = computation_wrapper_instances.tensorflow_wrapper(foo)\n\n # pyformat: disable\n self.assertEqual(\n foo.type_signature.compact_representation(),\n '( -> <int32,<int32,float32>,<int32,float32>,<foo=int32,bar=float32>,<x=bool,y=bool>>)'\n )\n # pyformat: enable\n\n def test_takes_namedtuple_typed(self):\n MyType = collections.namedtuple('MyType', ['x', 'y']) # pylint: disable=invalid-name\n\n @tf.function\n def foo(x):\n self.assertIsInstance(x, MyType)\n return x.x + x.y\n\n foo = computation_wrapper_instances.tensorflow_wrapper(\n foo, MyType(tf.int32, tf.int32))\n self.assertEqual(foo.type_signature.compact_representation(),\n '(<x=int32,y=int32> -> int32)')\n\n def test_takes_namedtuple_polymorphic(self):\n MyType = collections.namedtuple('MyType', ['x', 'y']) # pylint: disable=invalid-name\n\n @tf.function\n def foo(t):\n self.assertIsInstance(t, MyType)\n return t.x + t.y\n\n foo = computation_wrapper_instances.tensorflow_wrapper(foo)\n\n concrete_fn = foo.fn_for_argument_type(\n computation_types.StructWithPythonType([('x', tf.int32),\n ('y', tf.int32)], MyType))\n self.assertEqual(concrete_fn.type_signature.compact_representation(),\n '(<x=int32,y=int32> -> int32)')\n concrete_fn = foo.fn_for_argument_type(\n computation_types.StructWithPythonType([('x', tf.float32),\n ('y', tf.float32)], MyType))\n self.assertEqual(concrete_fn.type_signature.compact_representation(),\n '(<x=float32,y=float32> -> float32)')\n\n def test_with_variable(self):\n v_slot = []\n\n @tf.function(autograph=False)\n def foo(x):\n if not v_slot:\n v_slot.append(tf.Variable(0))\n v = v_slot[0]\n v.assign(1)\n return v + x\n\n foo = computation_wrapper_instances.tensorflow_wrapper(foo, tf.int32)\n self.assertEqual(foo.type_signature.compact_representation(),\n '(int32 -> int32)')\n\n def test_does_not_raise_type_error_with_sequence_inputs_and_outputs(self):\n try:\n\n @computation_wrapper_instances.tensorflow_wrapper(\n computation_types.SequenceType(tf.int32))\n def foo(x): # pylint: disable=unused-variable\n return x\n\n except TypeError:\n self.fail('Raised TypeError unexpectedly.')\n\n def test_fails_with_bad_types(self):\n function = computation_types.FunctionType(\n None, computation_types.TensorType(tf.int32))\n federated = computation_types.FederatedType(tf.int32,\n placement_literals.CLIENTS)\n tuple_on_function = computation_types.StructType([federated, function])\n\n def foo(x): # pylint: disable=unused-variable\n del x # Unused.\n\n with self.assertRaisesRegex(\n TypeError,\n r'you have attempted to create one with the type {int32}@CLIENTS'):\n computation_wrapper_instances.tensorflow_wrapper(foo, federated)\n\n # pylint: disable=anomalous-backslash-in-string\n with self.assertRaisesRegex(\n TypeError,\n r'you have attempted to create one with the type \\( -> int32\\)'):\n computation_wrapper_instances.tensorflow_wrapper(foo, function)\n\n with self.assertRaisesRegex(\n TypeError, r'you have attempted to create one with the type placement'):\n computation_wrapper_instances.tensorflow_wrapper(\n foo, computation_types.PlacementType())\n\n with self.assertRaisesRegex(\n TypeError, r'you have attempted to create one with the type T'):\n computation_wrapper_instances.tensorflow_wrapper(\n foo, computation_types.AbstractType('T'))\n\n with self.assertRaisesRegex(\n TypeError,\n r'you have attempted to create one with the type <{int32}@CLIENTS,\\( '\n '-> int32\\)>'):\n computation_wrapper_instances.tensorflow_wrapper(foo, tuple_on_function)\n # pylint: enable=anomalous-backslash-in-string\n\n def test_stackframes_in_errors(self):\n\n class DummyError(RuntimeError):\n pass\n\n with golden.check_raises_traceback('tensorflow_wrapper_traceback.expected',\n DummyError):\n\n @computation_wrapper_instances.tensorflow_wrapper\n def _():\n raise DummyError()\n\n def test_stack_resets_on_none_returned(self):\n stack = get_context_stack.get_context_stack()\n self.assertIsInstance(stack.current,\n runtime_error_context.RuntimeErrorContext)\n\n try:\n\n @computation_wrapper_instances.tensorflow_wrapper()\n def _():\n pass\n\n except computation_wrapper.ComputationReturnedNoneError:\n self.assertIsInstance( # pylint: disable=g-assert-in-except\n stack.current, runtime_error_context.RuntimeErrorContext)\n\n\nclass FederatedComputationWrapperTest(test_case.TestCase):\n\n def test_federated_computation_wrapper(self):\n\n @computation_wrapper_instances.federated_computation_wrapper(\n (computation_types.FunctionType(tf.int32, tf.int32), tf.int32))\n def foo(f, x):\n return f(f(x))\n\n self.assertIsInstance(foo, computation_impl.ComputationImpl)\n self.assertEqual(\n str(foo.type_signature), '(<f=(int32 -> int32),x=int32> -> int32)')\n\n self.assertEqual(\n str(foo.to_building_block()),\n '(foo_arg -> (let fc_foo_symbol_0=foo_arg[0](foo_arg[1]),fc_foo_symbol_1=foo_arg[0](fc_foo_symbol_0) in fc_foo_symbol_1))'\n )\n\n def test_stackframes_in_errors(self):\n\n class DummyError(RuntimeError):\n pass\n\n with golden.check_raises_traceback(\n 'federated_computation_wrapper_traceback.expected', DummyError):\n\n @computation_wrapper_instances.federated_computation_wrapper\n def _():\n raise DummyError()\n\n def test_empty_tuple_arg(self):\n\n @computation_wrapper_instances.federated_computation_wrapper(\n computation_types.StructType([]))\n def foo(x):\n return x\n\n self.assertIsInstance(foo, computation_impl.ComputationImpl)\n self.assertEqual(str(foo.type_signature), '(<> -> <>)')\n\n self.assertEqual(str(foo.to_building_block()), '(foo_arg -> foo_arg)')\n\n def test_stack_resets_on_none_returned(self):\n stack = get_context_stack.get_context_stack()\n self.assertIsInstance(stack.current,\n runtime_error_context.RuntimeErrorContext)\n\n try:\n\n @computation_wrapper_instances.federated_computation_wrapper()\n def _():\n pass\n\n except computation_wrapper.ComputationReturnedNoneError:\n self.assertIsInstance( # pylint: disable=g-assert-in-except\n stack.current, runtime_error_context.RuntimeErrorContext)\n\n\nclass AssertReturnsTest(test_case.TestCase):\n\n def test_basic_non_tff_function_as_decorator_succeeds(self):\n\n @computation_wrapper_instances.check_returns_type(tf.int32)\n def f():\n return 5\n\n self.assertEqual(f(), 5)\n\n def test_basic_non_tff_function_as_decorator_fails(self):\n\n @computation_wrapper_instances.check_returns_type(tf.int32)\n def f():\n return [5]\n\n with self.assertRaises(TypeError):\n f()\n\n def test_basic_non_tff_function_as_nondecorator_succeeds(self):\n\n def f():\n return 5\n\n f_wrapped = computation_wrapper_instances.check_returns_type(f, tf.int32)\n self.assertEqual(f_wrapped(), 5)\n\n def test_basic_non_tff_function_as_nondecorator_fails(self):\n\n def f():\n return [5]\n\n f_wrapped = computation_wrapper_instances.check_returns_type(f, tf.int32)\n with self.assertRaises(TypeError):\n f_wrapped()\n\n def test_with_tensorflow_computation_succeeds(self):\n\n @computation_wrapper_instances.tensorflow_wrapper(tf.int32)\n @computation_wrapper_instances.check_returns_type(tf.int32)\n def _(x):\n return x\n\n def test_with_tensorflow_computation_fails(self):\n with self.assertRaises(TypeError): # pylint: disable=g-error-prone-assert-raises\n\n @computation_wrapper_instances.tensorflow_wrapper(tf.int32)\n @computation_wrapper_instances.check_returns_type(tf.int32)\n def _(x):\n return (x, x)\n\n def test_with_tensorflow_computation_picking_up_named_parameters(self):\n\n @computation_wrapper_instances.tensorflow_wrapper(tf.int32, tf.int32)\n @computation_wrapper_instances.check_returns_type(tf.int32)\n def f(a, b):\n del b\n return a\n\n self.assertEqual(\n f.type_signature,\n computation_types.FunctionType(\n collections.OrderedDict(a=tf.int32, b=tf.int32), tf.int32))\n\n def test_fails_with_mismatched_container_type(self):\n with golden.check_raises_traceback(\n 'returns_type_container_mismatch_traceback.expected', TypeError):\n # This test fails because it `check_returns_type` with a `tuple`,\n # but returns a `list`.\n @computation_wrapper_instances.tensorflow_wrapper(tf.int32)\n @computation_wrapper_instances.check_returns_type((tf.int32, tf.int32))\n def _(a):\n return [a, a]\n\n def test_fails_with_more_general_tensorspec(self):\n type_with_known_shape = computation_types.TensorType(tf.int32, [1])\n type_with_unknown_shape = computation_types.TensorType(tf.int32, [None])\n\n with self.assertRaises(TypeError): # pylint: disable=g-error-prone-assert-raises\n\n @computation_wrapper_instances.tensorflow_wrapper(type_with_known_shape)\n @computation_wrapper_instances.check_returns_type(type_with_unknown_shape)\n def _(a):\n return a\n\n def test_attrs_type(self):\n\n @attr.s(frozen=True, eq=False, slots=True)\n class MyAttrs:\n a = attr.ib()\n b = attr.ib()\n\n expected_return_type = MyAttrs(a=tf.int32, b=tf.int32)\n\n @computation_wrapper_instances.tensorflow_wrapper\n @computation_wrapper_instances.check_returns_type(expected_return_type)\n def _():\n return MyAttrs(a=0, b=0)\n\n\nclass ToComputationImplTest(test_case.TestCase):\n\n def test_raises_on_none(self):\n with self.assertRaises(TypeError):\n computation_wrapper_instances.building_block_to_computation(None)\n\n def test_converts_building_block_to_computation(self):\n lam = building_blocks.Lambda('x', tf.int32,\n building_blocks.Reference('x', tf.int32))\n computation_impl_lambda = computation_wrapper_instances.building_block_to_computation(\n lam)\n self.assertIsInstance(computation_impl_lambda,\n computation_impl.ComputationImpl)\n\n\nif __name__ == '__main__':\n test_case.main()\n" ]
[ [ "tensorflow.Graph", "tensorflow.constant", "numpy.arange", "tensorflow.cast", "tensorflow.data.experimental.to_variant", "tensorflow.compat.v1.Session", "numpy.int64", "tensorflow.data.Dataset.range" ], [ "tensorflow.data.Dataset.from_tensor_slices", "tensorflow.test.main", "tensorflow.data.Dataset.range", "tensorflow.data.experimental.cardinality", "tensorflow.TensorSpec" ], [ "tensorflow.clip_by_value", "tensorflow.constant", "tensorflow.stack", "numpy.issubdtype", "tensorflow.cast", "tensorflow.nest.flatten", "tensorflow.abs" ], [ "tensorflow.nest.assert_same_structure", "tensorflow.nest.flatten", "tensorflow.keras.backend.clear_session", "tensorflow.test.main" ], [ "tensorflow.keras.layers.Activation", "tensorflow.keras.layers.GlobalAveragePooling2D", "tensorflow.keras.backend.image_data_format", "tensorflow.keras.models.Model", "tensorflow.keras.backend.int_shape", "tensorflow.keras.regularizers.l2", "tensorflow.keras.initializers.RandomNormal", "tensorflow.keras.layers.BatchNormalization", "tensorflow.keras.layers.add", "tensorflow.keras.layers.MaxPooling2D", "tensorflow.keras.layers.Input" ], [ "tensorflow.function", "tensorflow.Variable" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.7", "2.6", "2.2", "1.13", "2.3", "2.4", "2.9", "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": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "2.7", "2.6", "2.4", "2.3", "2.9", "2.5", "2.2", "2.10" ] } ]
alessiomora/federated
[ "3b501067ed7062aaec3cc8830aaec0a7cf8f0942", "3b501067ed7062aaec3cc8830aaec0a7cf8f0942", "3b501067ed7062aaec3cc8830aaec0a7cf8f0942", "3b501067ed7062aaec3cc8830aaec0a7cf8f0942", "3b501067ed7062aaec3cc8830aaec0a7cf8f0942" ]
[ "tensorflow_federated/python/simulation/datasets/file_per_user_client_data.py", "tensorflow_federated/python/learning/optimizers/optimizer_test.py", "tensorflow_federated/python/aggregators/test_utils.py", "tensorflow_federated/python/core/impl/utils/tensorflow_utils.py", "tensorflow_federated/python/simulation/baselines/cifar/cifar_preprocessing_test.py" ]
[ "# Copyright 2018, The TensorFlow Federated Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Implementations of `ClientData` backed by a file system.\"\"\"\n\nimport collections\nimport os.path\nfrom typing import Callable, Mapping\n\nimport tensorflow as tf\n\nfrom tensorflow_federated.python.common_libs import py_typecheck\nfrom tensorflow_federated.python.simulation.datasets import client_data\nfrom tensorflow_federated.python.tensorflow_libs import tensor_utils\n\n\nclass FilePerUserClientData(client_data.SerializableClientData):\n \"\"\"A `tff.simulation.datasets.ClientData` that maps a set of files to a dataset.\n\n This mapping is restricted to one file per user.\n \"\"\"\n\n def __init__(self, client_ids_to_files: Mapping[str, str],\n dataset_fn: Callable[[str], tf.data.Dataset]):\n \"\"\"Constructs a `tff.simulation.datasets.ClientData` object.\n\n Args:\n client_ids_to_files: A mapping from string client IDs to filepaths\n containing the user's data.\n dataset_fn: A factory function that takes a filepath (must accept both\n strings and tensors) and returns a `tf.data.Dataset` corresponding to\n this path.\n \"\"\"\n py_typecheck.check_type(client_ids_to_files, collections.abc.Mapping)\n if not client_ids_to_files:\n raise ValueError('`client_ids` must have at least one client ID')\n py_typecheck.check_callable(dataset_fn)\n self._client_ids = sorted(client_ids_to_files.keys())\n\n # Creates a dataset in a manner that can be serialized by TF.\n def serializable_dataset_fn(client_id: str) -> tf.data.Dataset:\n client_ids_to_path = tf.lookup.StaticHashTable(\n tf.lookup.KeyValueTensorInitializer(\n list(client_ids_to_files.keys()),\n list(client_ids_to_files.values())), '')\n client_path = client_ids_to_path.lookup(client_id)\n return dataset_fn(client_path)\n\n self._serializable_dataset_fn = serializable_dataset_fn\n\n tf_dataset = serializable_dataset_fn(tf.constant(self._client_ids[0]))\n self._element_type_structure = tf_dataset.element_spec\n\n @property\n def serializable_dataset_fn(self):\n \"\"\"Creates a `tf.data.Dataset` for a client in a TF-serializable manner.\"\"\"\n return self._serializable_dataset_fn\n\n @property\n def client_ids(self):\n return self._client_ids\n\n def create_tf_dataset_for_client(self, client_id: str) -> tf.data.Dataset:\n \"\"\"Creates a new `tf.data.Dataset` containing the client training examples.\n\n This function will create a dataset for a given client if `client_id` is\n contained in the `client_ids` property of the `FilePerUserClientData`.\n Unlike `self.serializable_dataset_fn`, this method is not serializable.\n\n Args:\n client_id: The string identifier for the desired client.\n\n Returns:\n A `tf.data.Dataset` object.\n \"\"\"\n if client_id not in self.client_ids:\n raise ValueError(\n 'ID [{i}] is not a client in this ClientData. See '\n 'property `client_ids` for the list of valid ids.'.format(\n i=client_id))\n\n client_dataset = self.serializable_dataset_fn(tf.constant(client_id))\n tensor_utils.check_nested_equal(client_dataset.element_spec,\n self._element_type_structure)\n return client_dataset\n\n @property\n def element_type_structure(self):\n return self._element_type_structure\n\n @classmethod\n def create_from_dir(cls, path, create_tf_dataset_fn=tf.data.TFRecordDataset):\n \"\"\"Builds a `tff.simulation.datasets.FilePerUserClientData`.\n\n Iterates over all files in `path`, using the filename as the client ID. Does\n not recursively search `path`.\n\n Args:\n path: A directory path to search for per-client files.\n create_tf_dataset_fn: A callable that creates a `tf.data.Datasaet` object\n for a given file in the directory specified in `path`.\n\n Returns:\n A `tff.simulation.datasets.FilePerUserClientData` object.\n \"\"\"\n client_ids_to_paths_dict = {\n filename: os.path.join(path, filename)\n for filename in tf.io.gfile.listdir(path)\n }\n\n return FilePerUserClientData(client_ids_to_paths_dict, create_tf_dataset_fn)\n", "# Copyright 2021, The TensorFlow Federated Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom absl.testing import parameterized\nimport tensorflow as tf\n\nfrom tensorflow_federated.python.core.api import test_case\nfrom tensorflow_federated.python.learning.optimizers import optimizer\n\n\nclass OptimizerChecksTest(test_case.TestCase, parameterized.TestCase):\n\n @parameterized.named_parameters(\n ('zero', 0.0),\n ('negative', -1.0),\n ('none', None),\n ('not_float', '0.1'),\n )\n def test_check_learning_rate_raises(self, lr):\n with self.assertRaises((ValueError, TypeError)):\n optimizer.check_learning_rate(lr)\n\n @parameterized.named_parameters(\n ('zero', 0.0),\n ('negative', -1.0),\n ('one', 1.0),\n ('large', 42.0),\n ('none', None),\n ('not_float', '0.1'),\n )\n def test_check_momentum_raises(self, momentum):\n with self.assertRaises((ValueError, TypeError)):\n optimizer.check_momentum(momentum)\n\n @parameterized.named_parameters(\n ('bad_shape', tf.zeros([2], tf.float32), tf.zeros([3], tf.float32)),\n ('bad_dtype', tf.zeros([2], tf.float32), tf.zeros([2], tf.float64)),\n ('bad_structure', [tf.zeros([2]), tf.zeros([3])\n ], [tf.zeros([2]), [tf.zeros([3])]]),\n )\n def check_weights_gradients_match(self, weights, gradients):\n with self.assertRaises(ValueError):\n optimizer.check_weights_gradients_match(weights, gradients)\n\n\nif __name__ == '__main__':\n test_case.main()\n", "# Copyright 2020, The TensorFlow Federated Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Utilities for testing aggregation factories and processes.\"\"\"\n\nimport tensorflow as tf\n\nfrom tensorflow_federated.python.aggregators import factory\nfrom tensorflow_federated.python.common_libs import py_typecheck\nfrom tensorflow_federated.python.core.api import computations\nfrom tensorflow_federated.python.core.impl.federated_context import intrinsics\nfrom tensorflow_federated.python.core.impl.types import computation_types\nfrom tensorflow_federated.python.core.impl.types import placements\nfrom tensorflow_federated.python.core.templates import aggregation_process\nfrom tensorflow_federated.python.core.templates import measured_process\n\nMEASUREMENT_CONSTANT = 42\n\n\nclass SumPlusOneFactory(factory.UnweightedAggregationFactory):\n \"\"\"`UnweightedAggregationFactory` for \"sum + 1\".\n\n The created `tff.templates.AggregationProcess` will sum the values placed at\n `CLIENTS`, and add `1` to the sum. In the case of value of structured type,\n `1` will be added to each element. The `state` of the process is initialized\n as `0` and incremented by `1` in each iteration of `next`. The `measurements`\n are always equal to `42`.\n\n This factory is intended as a testing utility for testing aggregation\n factories which are optionally be parameterized by inner aggregation\n factories. Due to the relative simplicity of this specific aggregation, it\n should be easy to verify whether it was actually applied, when testing an\n outer aggregation factory.\n \"\"\"\n\n def create(\n self,\n value_type: factory.ValueType) -> aggregation_process.AggregationProcess:\n\n py_typecheck.check_type(value_type, factory.ValueType.__args__)\n\n @computations.federated_computation()\n def init_fn():\n return intrinsics.federated_value(0, placements.SERVER)\n\n @computations.federated_computation(init_fn.type_signature.result,\n computation_types.FederatedType(\n value_type, placements.CLIENTS))\n def next_fn(state, value):\n state = intrinsics.federated_map(\n computations.tf_computation(lambda x: x + 1), state)\n result = intrinsics.federated_map(\n computations.tf_computation(\n lambda x: tf.nest.map_structure(lambda y: y + 1, x)),\n intrinsics.federated_sum(value))\n measurements = intrinsics.federated_value(MEASUREMENT_CONSTANT,\n placements.SERVER)\n return measured_process.MeasuredProcessOutput(state, result, measurements)\n\n return aggregation_process.AggregationProcess(init_fn, next_fn)\n", "# Copyright 2018, The TensorFlow Federated Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Utilities for interacting with and manipulating TensorFlow graphs.\"\"\"\n\nimport collections\nimport functools\nimport itertools\nimport typing\n\nimport attr\nimport numpy as np\nimport tensorflow as tf\n\nfrom tensorflow_federated.proto.v0 import computation_pb2 as pb\nfrom tensorflow_federated.python.common_libs import py_typecheck\nfrom tensorflow_federated.python.common_libs import serialization_utils\nfrom tensorflow_federated.python.common_libs import structure\nfrom tensorflow_federated.python.core.impl.types import computation_types\nfrom tensorflow_federated.python.core.impl.types import type_analysis\nfrom tensorflow_federated.python.core.impl.types import type_conversions\nfrom tensorflow_federated.python.core.impl.types import type_serialization\n\nTENSOR_REPRESENTATION_TYPES = (\n # Python native types\n str,\n int,\n float,\n bool,\n bytes,\n\n # Numpy data types\n np.generic,\n np.ndarray,\n)\n\n\ndef stamp_parameter_in_graph(parameter_name, parameter_type, graph):\n \"\"\"Stamps a parameter of a given type in the given tf.Graph instance.\n\n Tensors are stamped as placeholders, sequences are stamped as data sets\n constructed from string tensor handles, and named tuples are stamped by\n independently stamping their elements.\n\n Args:\n parameter_name: The suggested (string) name of the parameter to use in\n determining the names of the graph components to construct. The names that\n will actually appear in the graph are not guaranteed to be based on this\n suggested name, and may vary, e.g., due to existing naming conflicts, but\n a best-effort attempt will be made to make them similar for ease of\n debugging.\n parameter_type: The type of the parameter to stamp. Must be either an\n instance of computation_types.Type (or convertible to it), or None.\n graph: The instance of tf.Graph to stamp in.\n\n Returns:\n A tuple (val, binding), where 'val' is a Python object (such as a dataset,\n a placeholder, or a `structure.Struct` that represents a named\n tuple) that represents the stamped parameter for use in the body of a Python\n function that consumes this parameter, and the 'binding' is an instance of\n TensorFlow.Binding that indicates how parts of the type signature relate\n to the tensors and ops stamped into the graph.\n\n Raises:\n TypeError: If the arguments are of the wrong computation_types.\n ValueError: If the parameter type cannot be stamped in a TensorFlow graph.\n \"\"\"\n py_typecheck.check_type(parameter_name, str)\n py_typecheck.check_type(graph, tf.Graph)\n if parameter_type is None:\n return (None, None)\n parameter_type = computation_types.to_type(parameter_type)\n if parameter_type.is_tensor():\n with graph.as_default():\n placeholder = tf.compat.v1.placeholder(\n dtype=parameter_type.dtype,\n shape=parameter_type.shape,\n name=parameter_name)\n binding = pb.TensorFlow.Binding(\n tensor=pb.TensorFlow.TensorBinding(tensor_name=placeholder.name))\n return (placeholder, binding)\n elif parameter_type.is_struct():\n # The parameter_type could be a StructTypeWithPyContainer, however, we\n # ignore that for now. Instead, the proper containers will be inserted at\n # call time by function_utils.wrap_as_zero_or_one_arg_callable.\n if not parameter_type:\n # Stamps whimsy element to \"populate\" graph, as TensorFlow does not\n # support empty graphs.\n whimsy_tensor = tf.no_op()\n del whimsy_tensor # Unused\n element_name_value_pairs = []\n element_bindings = []\n for e in structure.iter_elements(parameter_type):\n e_val, e_binding = stamp_parameter_in_graph(\n '{}_{}'.format(parameter_name, e[0]), e[1], graph)\n element_name_value_pairs.append((e[0], e_val))\n element_bindings.append(e_binding)\n return (structure.Struct(element_name_value_pairs),\n pb.TensorFlow.Binding(\n struct=pb.TensorFlow.StructBinding(element=element_bindings)))\n elif parameter_type.is_sequence():\n with graph.as_default():\n variant_tensor = tf.compat.v1.placeholder(tf.variant, shape=[])\n ds = make_dataset_from_variant_tensor(variant_tensor,\n parameter_type.element)\n return (ds,\n pb.TensorFlow.Binding(\n sequence=pb.TensorFlow.SequenceBinding(\n variant_tensor_name=variant_tensor.name)))\n else:\n raise ValueError(\n 'Parameter type component {!r} cannot be stamped into a TensorFlow '\n 'graph.'.format(parameter_type))\n\n\ndef make_dataset_from_variant_tensor(variant_tensor, type_spec):\n \"\"\"Constructs a `tf.data.Dataset` from a variant tensor and type spec.\n\n Args:\n variant_tensor: The variant tensor that represents the dataset.\n type_spec: The type spec of elements of the data set, either an instance of\n `types.Type` or something convertible to it.\n\n Returns:\n A corresponding instance of `tf.data.Dataset`.\n\n Raises:\n TypeError: If the arguments are of the wrong types.\n \"\"\"\n if not tf.is_tensor(variant_tensor):\n raise TypeError(\n 'Expected `variant_tensor` to be a tensor, found {}.'.format(\n py_typecheck.type_string(type(variant_tensor))))\n if variant_tensor.dtype != tf.variant:\n raise TypeError(\n 'Expected `variant_tensor` to be of a variant type, found {}.'.format(\n variant_tensor.dtype))\n return tf.data.experimental.from_variant(\n variant_tensor,\n structure=(type_conversions.type_to_tf_structure(\n computation_types.to_type(type_spec))))\n\n\ndef capture_result_from_graph(result, graph):\n \"\"\"Captures a result stamped into a tf.Graph as a type signature and binding.\n\n Args:\n result: The result to capture, a Python object that is composed of tensors,\n possibly nested within Python structures such as dictionaries, lists,\n tuples, or named tuples.\n graph: The instance of tf.Graph to use.\n\n Returns:\n A tuple (type_spec, binding), where 'type_spec' is an instance of\n computation_types.Type that describes the type of the result, and 'binding'\n is an instance of TensorFlow.Binding that indicates how parts of the result\n type relate to the tensors and ops that appear in the result.\n\n Raises:\n TypeError: If the argument or any of its parts are of an uexpected type.\n \"\"\"\n\n def _get_bindings_for_elements(name_value_pairs, graph, type_fn):\n \"\"\"Build `(type_spec, binding)` tuple for name value pairs.\"\"\"\n element_name_type_binding_triples = [\n ((k,) + capture_result_from_graph(v, graph))\n for k, v in name_value_pairs\n ]\n type_spec = type_fn([((e[0], e[1]) if e[0] else e[1])\n for e in element_name_type_binding_triples])\n binding = pb.TensorFlow.Binding(\n struct=pb.TensorFlow.StructBinding(\n element=[e[2] for e in element_name_type_binding_triples]))\n return type_spec, binding\n\n # TODO(b/113112885): The emerging extensions for serializing SavedModels may\n # end up introducing similar concepts of bindings, etc., we should look here\n # into the possibility of reusing some of that code when it's available.\n if isinstance(result, TENSOR_REPRESENTATION_TYPES):\n with graph.as_default():\n result = tf.constant(result)\n if tf.is_tensor(result):\n if hasattr(result, 'read_value'):\n # We have a tf.Variable-like result, get a proper tensor to fetch.\n with graph.as_default():\n result = result.read_value()\n else:\n # Otherwise we insert an identity. TensorFlow does not allow the same\n # tensor to appear in both feeds and fetches, which can occur if the\n # tff.Computation is only performing a selection from a structure.\n with graph.as_default():\n result = tf.identity(result)\n # `tf.is_tensor` returns true for some things that are not actually single\n # `tf.Tensor`s, including `tf.SparseTensor`s and `tf.RaggedTensor`s.\n if isinstance(result, tf.RaggedTensor):\n name_value_pairs = (('flat_values', result.flat_values),\n ('nested_row_splits', result.nested_row_splits))\n return _get_bindings_for_elements(\n name_value_pairs, graph,\n functools.partial(\n computation_types.StructWithPythonType,\n container_type=tf.RaggedTensor))\n elif isinstance(result, tf.SparseTensor):\n name_value_pairs = (('indices', result.indices),\n ('values', result.values), ('dense_shape',\n result.dense_shape))\n return _get_bindings_for_elements(\n name_value_pairs, graph,\n functools.partial(\n computation_types.StructWithPythonType,\n container_type=tf.SparseTensor))\n else:\n return (computation_types.TensorType(result.dtype.base_dtype,\n result.shape),\n pb.TensorFlow.Binding(\n tensor=pb.TensorFlow.TensorBinding(tensor_name=result.name)))\n elif py_typecheck.is_named_tuple(result):\n # Special handling needed for collections.namedtuples since they do not have\n # anything in the way of a shared base class. Note we don't want to rely on\n # the fact that collections.namedtuples inherit from 'tuple' because we'd be\n # failing to retain the information about naming of tuple members.\n # pylint: disable=protected-access\n name_value_pairs = result._asdict().items()\n # pylint: enable=protected-access\n return _get_bindings_for_elements(\n name_value_pairs, graph,\n functools.partial(\n computation_types.StructWithPythonType,\n container_type=type(result)))\n elif py_typecheck.is_attrs(result):\n name_value_pairs = attr.asdict(\n result, dict_factory=collections.OrderedDict, recurse=False)\n return _get_bindings_for_elements(\n name_value_pairs.items(), graph,\n functools.partial(\n computation_types.StructWithPythonType,\n container_type=type(result)))\n elif isinstance(result, structure.Struct):\n return _get_bindings_for_elements(\n structure.to_elements(result), graph, computation_types.StructType)\n elif isinstance(result, collections.abc.Mapping):\n if isinstance(result, collections.OrderedDict):\n name_value_pairs = result.items()\n else:\n name_value_pairs = sorted(result.items())\n return _get_bindings_for_elements(\n name_value_pairs, graph,\n functools.partial(\n computation_types.StructWithPythonType,\n container_type=type(result)))\n elif isinstance(result, (list, tuple)):\n element_type_binding_pairs = [\n capture_result_from_graph(e, graph) for e in result\n ]\n return (computation_types.StructWithPythonType(\n [e[0] for e in element_type_binding_pairs], type(result)),\n pb.TensorFlow.Binding(\n struct=pb.TensorFlow.StructBinding(\n element=[e[1] for e in element_type_binding_pairs])))\n elif isinstance(result, type_conversions.TF_DATASET_REPRESENTATION_TYPES):\n variant_tensor = tf.data.experimental.to_variant(result)\n element_structure = result.element_spec\n try:\n element_type = computation_types.to_type(element_structure)\n except TypeError as e:\n raise TypeError(\n 'Dataset has `element_spec` which is not a valid TFF type.\\n'\n f'Found `element_spec`: {element_structure}\\n'\n f'which is not a valid TFF type: {str(e)}') from None\n return (computation_types.SequenceType(element_type),\n pb.TensorFlow.Binding(\n sequence=pb.TensorFlow.SequenceBinding(\n variant_tensor_name=variant_tensor.name)))\n else:\n raise TypeError('Cannot capture a result of an unsupported type {}.'.format(\n py_typecheck.type_string(type(result))))\n\n\ndef compute_map_from_bindings(source, target):\n \"\"\"Computes a dictionary for renaming tensors from a matching bindings pair.\n\n Args:\n source: An instance of `pb.TensorFlow.Binding` that contains names of\n tensors that will form the keys in the dictionary.\n target: An instance of `pb.TensorFlow.Binding` that contains names of\n tensors that will form the values in the dictionary. The structure of this\n binding must be identical as that of the `source`.\n\n Returns:\n A dictionary mapping names of tensors in `source` to names of the\n tensors in the corresponding parts of `target`.\n\n Raises:\n TypeError: If the arguments are of the wrong computation_types.\n ValueError: If the bindings have mismatching structures.\n \"\"\"\n py_typecheck.check_type(source, pb.TensorFlow.Binding)\n py_typecheck.check_type(target, pb.TensorFlow.Binding)\n source_oneof = source.WhichOneof('binding')\n target_oneof = target.WhichOneof('binding')\n if source_oneof != target_oneof:\n raise ValueError(\n 'Source and target binding variants mismatch: {} vs. {}'.format(\n source_oneof, target_oneof))\n if source_oneof == 'tensor':\n return collections.OrderedDict([(str(source.tensor.tensor_name),\n str(target.tensor.tensor_name))])\n elif source_oneof == 'sequence':\n sequence_oneof = source.sequence.WhichOneof('binding')\n if target.sequence.WhichOneof('binding') != sequence_oneof:\n raise ValueError(\n 'Source and target sequence bindings mismatch: {} vs. {}'.format(\n sequence_oneof, target.sequence.WhichOneof('binding')))\n if sequence_oneof == 'variant_tensor_name':\n return collections.OrderedDict([\n (str(source.sequence.variant_tensor_name),\n str(target.sequence.variant_tensor_name)),\n ])\n else:\n raise ValueError('Unsupported sequence binding {}'.format(sequence_oneof))\n elif source_oneof == 'struct':\n if len(source.struct.element) != len(target.struct.element):\n raise ValueError(\n 'Source and target binding tuple lengths mismatch: {} vs. {}.'.format(\n len(source.struct.element), len(target.struct.element)))\n else:\n result = collections.OrderedDict()\n for source_element, target_element in zip(source.struct.element,\n target.struct.element):\n result.update(compute_map_from_bindings(source_element, target_element))\n return result\n else:\n raise ValueError('Unsupported type of binding \\'{}\\'.'.format(source_oneof))\n\n\ndef extract_tensor_names_from_binding(binding):\n \"\"\"Returns a list of tensor names extracted from a given binding.\n\n Args:\n binding: An instance of `pb.TensorFlow.Binding`.\n\n Returns:\n All tensor names that appear in `binding`.\n \"\"\"\n py_typecheck.check_type(binding, pb.TensorFlow.Binding)\n binding_oneof = binding.WhichOneof('binding')\n if binding_oneof == 'tensor':\n return [str(binding.tensor.tensor_name)]\n elif binding_oneof == 'sequence':\n sequence_oneof = binding.sequence.WhichOneof('binding')\n if sequence_oneof == 'variant_tensor_name':\n return [str(binding.sequence.variant_tensor_name)]\n else:\n raise ValueError('Unsupported sequence binding {}'.format(sequence_oneof))\n elif binding_oneof == 'struct':\n return list(\n itertools.chain.from_iterable([\n extract_tensor_names_from_binding(e) for e in binding.struct.element\n ]))\n else:\n raise ValueError(\n 'Unsupported type of binding \\'{}\\'.'.format(binding_oneof))\n\n\ndef assemble_result_from_graph(type_spec, binding, output_map):\n \"\"\"Assembles a result stamped into a `tf.Graph` given type signature/binding.\n\n This method does roughly the opposite of `capture_result_from_graph`, in that\n whereas `capture_result_from_graph` starts with a single structured object\n made up of tensors and computes its type and bindings, this method starts\n with the type/bindings and constructs a structured object made up of tensors.\n\n Args:\n type_spec: The type signature of the result to assemble, an instance of\n `types.Type` or something convertible to it.\n binding: The binding that relates the type signature to names of tensors in\n the graph, an instance of `pb.TensorFlow.Binding`.\n output_map: The mapping from tensor names that appear in the binding to\n actual stamped tensors (possibly renamed during import).\n\n Returns:\n The assembled result, a Python object that is composed of tensors, possibly\n nested within Python structures such as anonymous tuples.\n\n Raises:\n TypeError: If the argument or any of its parts are of an uexpected type.\n ValueError: If the arguments are invalid or inconsistent witch other, e.g.,\n the type and binding don't match, or the tensor is not found in the map.\n \"\"\"\n type_spec = computation_types.to_type(type_spec)\n py_typecheck.check_type(type_spec, computation_types.Type)\n py_typecheck.check_type(binding, pb.TensorFlow.Binding)\n py_typecheck.check_type(output_map, dict)\n for k, v in output_map.items():\n py_typecheck.check_type(k, str)\n if not tf.is_tensor(v):\n raise TypeError(\n 'Element with key {} in the output map is {}, not a tensor.'.format(\n k, py_typecheck.type_string(type(v))))\n\n binding_oneof = binding.WhichOneof('binding')\n if type_spec.is_tensor():\n if binding_oneof != 'tensor':\n raise ValueError(\n 'Expected a tensor binding, found {}.'.format(binding_oneof))\n elif binding.tensor.tensor_name not in output_map:\n raise ValueError('Tensor named {} not found in the output map.'.format(\n binding.tensor.tensor_name))\n else:\n return output_map[binding.tensor.tensor_name]\n elif type_spec.is_struct():\n if binding_oneof != 'struct':\n raise ValueError(\n 'Expected a struct binding, found {}.'.format(binding_oneof))\n else:\n type_elements = structure.to_elements(type_spec)\n if len(binding.struct.element) != len(type_elements):\n raise ValueError(\n 'Mismatching tuple sizes in type ({}) and binding ({}).'.format(\n len(type_elements), len(binding.struct.element)))\n result_elements = []\n for (element_name,\n element_type), element_binding in zip(type_elements,\n binding.struct.element):\n element_object = assemble_result_from_graph(element_type,\n element_binding, output_map)\n result_elements.append((element_name, element_object))\n if type_spec.python_container is None:\n return structure.Struct(result_elements)\n container_type = type_spec.python_container\n if (py_typecheck.is_named_tuple(container_type) or\n py_typecheck.is_attrs(container_type)):\n return container_type(**dict(result_elements))\n return container_type(result_elements)\n elif type_spec.is_sequence():\n if binding_oneof != 'sequence':\n raise ValueError(\n 'Expected a sequence binding, found {}.'.format(binding_oneof))\n else:\n sequence_oneof = binding.sequence.WhichOneof('binding')\n if sequence_oneof == 'variant_tensor_name':\n variant_tensor = output_map[binding.sequence.variant_tensor_name]\n return make_dataset_from_variant_tensor(variant_tensor,\n type_spec.element)\n else:\n raise ValueError(\n 'Unsupported sequence binding \\'{}\\'.'.format(sequence_oneof))\n else:\n raise ValueError('Unsupported type \\'{}\\'.'.format(type_spec))\n\n\ndef nested_structures_equal(x, y):\n \"\"\"Determines if nested structures `x` and `y` are equal.\n\n Args:\n x: A nested structure.\n y: Another nested structure.\n\n Returns:\n `True` iff `x` and `y` are equal, `False` otherwise.\n \"\"\"\n try:\n tf.nest.assert_same_structure(x, y)\n except ValueError:\n return False\n return tf.nest.flatten(x) == tf.nest.flatten(y)\n\n\ndef make_empty_list_structure_for_element_type_spec(type_spec):\n \"\"\"Creates a nested structure of empty Python lists for `type_spec`.\n\n This function prepares a nested structure made of `collections.OrderedDict`s\n and Python `tuple`s at the intermediate (non-leaf) levels, and that has empty\n Python `list`s at the leaf level, with the shape of the structure matching\n that of `type_spec`. This structure is used to accumulate elemnts of a data\n set for ingestion by `tf.data.Dataset.from_tensor_slices`.\n\n Args:\n type_spec: An instance of `tff.Type` or something convertible to it that\n consists of only tensor and named tuple types, and in which rach of the\n named tuples either have all or none of their elements named.\n\n Returns:\n The nested structure, as described above.\n\n Raises:\n TypeError: If the `type_spec` is not of a form described above.\n \"\"\"\n type_spec = computation_types.to_type(type_spec)\n py_typecheck.check_type(type_spec, computation_types.Type)\n if type_spec.is_tensor():\n return []\n elif type_spec.is_struct():\n elements = structure.to_elements(type_spec)\n if all(k is not None for k, _ in elements):\n return collections.OrderedDict([\n (k, make_empty_list_structure_for_element_type_spec(v))\n for k, v in elements\n ])\n elif all(k is None for k, _ in elements):\n return tuple([\n make_empty_list_structure_for_element_type_spec(v)\n for _, v in elements\n ])\n else:\n raise TypeError(\n 'Expected a named tuple type with either all elements named or all '\n 'unnamed, got {}.'.format(type_spec))\n else:\n raise TypeError(\n 'Expected a tensor or named tuple type, found {}.'.format(type_spec))\n\n\ndef make_whimsy_element_for_type_spec(type_spec, none_dim_replacement=0):\n \"\"\"Creates ndarray of zeros corresponding to `type_spec`.\n\n Returns a list containing this ndarray, whose type is *compatible* with, not\n necessarily equal to, `type_spec`. This is due to the fact that some\n dimensions of `type_spec` may be indeterminate, representing compatibility\n of `type_spec` with any number (e.g. leaving a batch dimension indeterminate\n to signify compatibility with batches of any size). However a concrete\n structure (like the ndarray) must have specified sizes for its dimensions.\n So we construct a whimsy element where any `None` dimensions of the shape\n of `type_spec` are replaced with the value `none_dim_replacement`.The\n default value of 0 therefore returns a whimsy element of minimal size which\n matches `type_spec`.\n\n Args:\n type_spec: Instance of `computation_types.Type`, or something convertible to\n one by `computation_types.to_type`.\n none_dim_replacement: `int` with which to replace any unspecified tensor\n dimensions.\n\n Returns:\n Returns possibly nested `numpy ndarray`s containing all zeros: a single\n `ndarray` if `type_spec` is a `computation_types.TensorType` and a list\n of such arrays if `type_spec` is `computation_types.StructType`.\n This data structure is of the minimal size necessary in order to be\n compatible with `type_spec`.\n \"\"\"\n type_spec = computation_types.to_type(type_spec)\n if not type_analysis.contains_only(type_spec,\n lambda t: t.is_struct() or t.is_tensor()):\n raise ValueError('Cannot construct array for TFF type containing anything '\n 'other than `computation_types.TensorType` or '\n '`computation_types.StructType`; you have passed the '\n 'type {}'.format(type_spec))\n py_typecheck.check_type(none_dim_replacement, int)\n if none_dim_replacement < 0:\n raise ValueError('Please pass nonnegative integer argument as '\n '`none_dim_replacement`.')\n\n def _handle_none_dimension(x):\n if x is None or (isinstance(x, tf.compat.v1.Dimension) and x.value is None):\n return none_dim_replacement\n return x\n\n if type_spec.is_tensor():\n whimsy_shape = [_handle_none_dimension(x) for x in type_spec.shape]\n if type_spec.dtype == tf.string:\n return np.empty(whimsy_shape, dtype=str)\n return np.zeros(whimsy_shape, type_spec.dtype.as_numpy_dtype)\n elif type_spec.is_struct():\n elements = structure.to_elements(type_spec)\n elem_list = []\n for _, elem_type in elements:\n elem_list.append(make_whimsy_element_for_type_spec(elem_type))\n return elem_list\n\n\ndef append_to_list_structure_for_element_type_spec(nested, value, type_spec):\n \"\"\"Adds an element `value` to `nested` lists for `type_spec`.\n\n This function appends tensor-level constituents of an element `value` to the\n lists created by `make_empty_list_structure_for_element_type_spec`. The\n nested structure of `value` must match that created by the above function,\n and consistent with `type_spec`.\n\n Args:\n nested: Output of `make_empty_list_structure_for_element_type_spec`.\n value: A value (Python object) that a hierarchical structure of dictionary,\n list, and other containers holding tensor-like items that matches the\n hierarchy of `type_spec`.\n type_spec: An instance of `tff.Type` or something convertible to it, as in\n `make_empty_list_structure_for_element_type_spec`.\n\n Raises:\n TypeError: If the `type_spec` is not of a form described above, or the value\n is not of a type compatible with `type_spec`.\n \"\"\"\n if value is None:\n return\n type_spec = computation_types.to_type(type_spec)\n # TODO(b/113116813): This could be made more efficient, but for now we won't\n # need to worry about it as this is an odd corner case.\n if isinstance(value, structure.Struct):\n elements = structure.to_elements(value)\n if all(k is not None for k, _ in elements):\n value = collections.OrderedDict(elements)\n elif all(k is None for k, _ in elements):\n value = tuple([v for _, v in elements])\n else:\n raise TypeError(\n 'Expected an anonymous tuple to either have all elements named or '\n 'all unnamed, got {}.'.format(value))\n if type_spec.is_tensor():\n py_typecheck.check_type(nested, list)\n # Convert the members to tensors to ensure that they are properly\n # typed and grouped before being passed to\n # tf.data.Dataset.from_tensor_slices.\n nested.append(tf.convert_to_tensor(value, type_spec.dtype))\n elif type_spec.is_struct():\n elements = structure.to_elements(type_spec)\n if isinstance(nested, collections.OrderedDict):\n if py_typecheck.is_named_tuple(value):\n # In Python 3.8 and later `_asdict` no longer return OrdereDict, rather\n # a regular `dict`.\n value = collections.OrderedDict(value._asdict())\n if isinstance(value, dict):\n if set(value.keys()) != set(k for k, _ in elements):\n raise TypeError('Value {} does not match type {}.'.format(\n value, type_spec))\n for elem_name, elem_type in elements:\n append_to_list_structure_for_element_type_spec(\n nested[elem_name], value[elem_name], elem_type)\n elif isinstance(value, (list, tuple)):\n if len(value) != len(elements):\n raise TypeError('Value {} does not match type {}.'.format(\n value, type_spec))\n for idx, (elem_name, elem_type) in enumerate(elements):\n append_to_list_structure_for_element_type_spec(\n nested[elem_name], value[idx], elem_type)\n else:\n raise TypeError('Unexpected type of value {} for TFF type {}.'.format(\n py_typecheck.type_string(type(value)), type_spec))\n elif isinstance(nested, tuple):\n py_typecheck.check_type(value, (list, tuple))\n if len(value) != len(elements):\n raise TypeError('Value {} does not match type {}.'.format(\n value, type_spec))\n for idx, (_, elem_type) in enumerate(elements):\n append_to_list_structure_for_element_type_spec(nested[idx], value[idx],\n elem_type)\n else:\n raise TypeError(\n 'Invalid nested structure, unexpected container type {}.'.format(\n py_typecheck.type_string(type(nested))))\n else:\n raise TypeError(\n 'Expected a tensor or named tuple type, found {}.'.format(type_spec))\n\n\ndef replace_empty_leaf_lists_with_numpy_arrays(lists, type_spec):\n \"\"\"Replaces empty leaf lists in `lists` with numpy arrays.\n\n This function is primarily used to ensure that an appropriate TF dtype is\n inferrable for a structure, even if no elements are actually present.\n\n Args:\n lists: Output of `make_empty_list_structure_for_element_type_spec`.\n type_spec: An instance of `tff.Type` or something convertible to it, as in\n `make_empty_list_structure_for_element_type_spec`.\n\n Returns:\n The transformed version of `structure`.\n\n Raises:\n TypeError: If the `type_spec` is not of a form described above, or if\n `lists` is not of a type compatible with `type_spec`.\n \"\"\"\n type_spec = computation_types.to_type(type_spec)\n py_typecheck.check_type(type_spec, computation_types.Type)\n if type_spec.is_tensor():\n py_typecheck.check_type(lists, list)\n if len(lists) > 0: # pylint: disable=g-explicit-length-test\n return lists\n else:\n return np.array([], dtype=type_spec.dtype.as_numpy_dtype)\n elif type_spec.is_struct():\n elements = structure.to_elements(type_spec)\n if isinstance(lists, collections.OrderedDict):\n to_return = []\n for elem_name, elem_type in elements:\n elem_val = replace_empty_leaf_lists_with_numpy_arrays(\n lists[elem_name], elem_type)\n to_return.append((elem_name, elem_val))\n return collections.OrderedDict(to_return)\n elif isinstance(lists, tuple):\n to_return = []\n for idx, (_, elem_type) in enumerate(elements):\n elem_val = replace_empty_leaf_lists_with_numpy_arrays(\n lists[idx], elem_type)\n to_return.append(elem_val)\n return tuple(to_return)\n else:\n raise TypeError(\n 'Invalid nested structure, unexpected container type {}.'.format(\n py_typecheck.type_string(type(lists))))\n else:\n raise TypeError(\n 'Expected a tensor or struct type, found {}.'.format(type_spec))\n\n\ndef make_data_set_from_elements(graph, elements, element_type):\n \"\"\"Creates a `tf.data.Dataset` in `graph` from explicitly listed `elements`.\n\n Note: The underlying implementation attempts to use the\n `tf.data.Dataset.from_tensor_slices() method to build the data set quickly,\n but this doesn't always work. The typical scenario where it breaks is one\n with data set being composed of unequal batches. Typically, only the last\n batch is odd, so on the first attempt, we try to construct two data sets,\n one from all elements but the last one, and one from the last element, then\n concatenate the two. In the unlikely case that this fails (e.g., because\n all data set elements are batches of unequal sizes), we revert to the slow,\n but reliable method of constructing data sets from singleton elements, and\n then concatenating them all.\n\n Args:\n graph: The graph in which to construct the `tf.data.Dataset`, or `None` if\n the construction is to happen in the eager context.\n elements: A list of elements.\n element_type: The type of elements.\n\n Returns:\n The constructed `tf.data.Dataset` instance.\n\n Raises:\n TypeError: If element types do not match `element_type`.\n ValueError: If the elements are of incompatible types and shapes, or if\n no graph was specified outside of the eager context.\n \"\"\"\n # Note: We allow the graph to be `None` to allow this function to be used in\n # the eager context.\n if graph is not None:\n py_typecheck.check_type(graph, tf.Graph)\n elif not tf.executing_eagerly():\n raise ValueError('Only in eager context may the graph be `None`.')\n py_typecheck.check_type(elements, list)\n element_type = computation_types.to_type(element_type)\n py_typecheck.check_type(element_type, computation_types.Type)\n\n def _make(element_subset):\n lists = make_empty_list_structure_for_element_type_spec(element_type)\n for el in element_subset:\n append_to_list_structure_for_element_type_spec(lists, el, element_type)\n tensor_slices = replace_empty_leaf_lists_with_numpy_arrays(\n lists, element_type)\n return tf.data.Dataset.from_tensor_slices(tensor_slices)\n\n def _work(): # pylint: disable=missing-docstring\n if not elements:\n # Just return an empty data set with the appropriate types.\n whimsy_element = make_whimsy_element_for_type_spec(element_type)\n ds = _make([whimsy_element]).take(0)\n elif len(elements) == 1:\n ds = _make(elements)\n else:\n try:\n # It is common for the last element to be a batch of a size different\n # from all the preceding batches. With this in mind, we proactively\n # single out the last element (optimizing for the common case).\n ds = _make(elements[0:-1]).concatenate(_make(elements[-1:]))\n except ValueError:\n # In case elements beyond just the last one are of unequal shapes, we\n # may have failed (the most likely cause), so fall back onto the slow\n # process of constructing and joining data sets from singletons. Not\n # optimizing this for now, as it's very unlikely in scenarios\n # we're targeting.\n #\n # Note: this will not remain `None` because `element`s is not empty.\n ds = None\n ds = typing.cast(tf.data.Dataset, ds)\n for i in range(len(elements)):\n singleton_ds = _make(elements[i:i + 1])\n ds = singleton_ds if ds is None else ds.concatenate(singleton_ds)\n ds_element_type = computation_types.to_type(ds.element_spec)\n if not element_type.is_assignable_from(ds_element_type):\n raise TypeError(\n 'Failure during data set construction, expected elements of type {}, '\n 'but the constructed data set has elements of type {}.'.format(\n element_type, ds_element_type))\n return ds\n\n if graph is not None:\n with graph.as_default():\n return _work()\n else:\n return _work()\n\n\ndef fetch_value_in_session(sess, value):\n \"\"\"Fetches `value` in `session`.\n\n Args:\n sess: The session in which to perform the fetch (as a single run).\n value: A Python object of a form analogous to that constructed by the\n function `assemble_result_from_graph`, made of tensors and anononymous\n tuples, or a `tf.data.Dataset`.\n\n Returns:\n A Python object with structure similar to `value`, but with tensors\n replaced with their values, and data sets replaced with lists of their\n elements, all fetched with a single call `session.run()`.\n\n Raises:\n ValueError: If `value` is not a `tf.data.Dataset` or not a structure of\n tensors and anonoymous tuples.\n \"\"\"\n py_typecheck.check_type(sess, tf.compat.v1.Session)\n # TODO(b/113123634): Investigate handling `list`s and `tuple`s of\n # `tf.data.Dataset`s and what the API would look like to support this.\n if isinstance(value, type_conversions.TF_DATASET_REPRESENTATION_TYPES):\n with sess.graph.as_default():\n iterator = tf.compat.v1.data.make_one_shot_iterator(value)\n next_element = iterator.get_next()\n elements = []\n while True:\n try:\n elements.append(sess.run(next_element))\n except tf.errors.OutOfRangeError:\n break\n return elements\n else:\n flattened_value = structure.flatten(value)\n dataset_results = {}\n flat_tensors = []\n for idx, v in enumerate(flattened_value):\n if isinstance(v, type_conversions.TF_DATASET_REPRESENTATION_TYPES):\n dataset_tensors = fetch_value_in_session(sess, v)\n if not dataset_tensors:\n # An empty list has been returned; we must pack the shape information\n # back in or the result won't typecheck.\n element_structure = v.element_spec\n whimsy_elem = make_whimsy_element_for_type_spec(element_structure)\n dataset_tensors = [whimsy_elem]\n dataset_results[idx] = dataset_tensors\n elif tf.is_tensor(v):\n flat_tensors.append(v)\n else:\n raise ValueError('Unsupported value type {}.'.format(v))\n # Note that `flat_tensors` could be an empty tuple, but it could also be a\n # list of empty tuples.\n if flat_tensors or any(x for x in flat_tensors):\n flat_computed_tensors = sess.run(flat_tensors)\n else:\n flat_computed_tensors = flat_tensors\n flattened_results = _interleave_dataset_results_and_tensors(\n dataset_results, flat_computed_tensors)\n\n def _to_unicode(v):\n if isinstance(v, bytes):\n return v.decode('utf-8')\n return v\n\n if tf.is_tensor(value) and value.dtype == tf.string:\n flattened_results = [_to_unicode(result) for result in flattened_results]\n return structure.pack_sequence_as(value, flattened_results)\n\n\ndef _interleave_dataset_results_and_tensors(dataset_results, flat_run_tensors):\n flattened_results = []\n for idx in range(len(dataset_results) + len(flat_run_tensors)):\n if dataset_results.get(idx):\n flattened_results.append(dataset_results[idx])\n else:\n flattened_results.append(flat_run_tensors.pop(0))\n return flattened_results\n\n\ndef to_node_name(name):\n \"\"\"Returns the name of a node in `graph_def` that `name` refers to.\n\n Args:\n name: A string.\n\n Returns:\n A stripped version of `name` without control dependency prefix or output\n suffix.\n\n Raises:\n ValueError: If `name` is not a valid name of a node or node input.\n \"\"\"\n py_typecheck.check_type(name, str)\n if not name:\n raise ValueError('The argument cannot be empty.')\n if name[0] == '^':\n name = name[1:]\n colon = name.rfind(':')\n if colon >= 0:\n return name[:colon]\n else:\n return name\n\n\ndef get_deps_for_graph_node(graph_def, node_name):\n \"\"\"Returns the set of node names that a node named `node_name` depends on.\n\n Args:\n graph_def: The input graph, an instance of `tf.compat.v1.GraphDef`.\n node_name: The node name, a string.\n\n Returns:\n An instance of `set()` containing string names of the nodes `node_name`\n depends on in `graph_def`.\n \"\"\"\n py_typecheck.check_type(graph_def, tf.compat.v1.GraphDef)\n py_typecheck.check_type(node_name, str)\n input_map = {}\n for node in graph_def.node:\n input_map[node.name] = set(to_node_name(x) for x in node.input)\n dependencies = set()\n initial_singleton = set([node_name])\n nodes_to_process = initial_singleton\n while nodes_to_process:\n dependencies.update(nodes_to_process)\n nodes_to_process = set.union(\n *[input_map[name]\n for name in nodes_to_process]).difference(dependencies)\n return dependencies.difference(initial_singleton)\n\n\ndef add_control_deps_for_init_op(graph_def, init_op):\n \"\"\"Adds control deps on `init_op` to `graph_def`.\n\n Args:\n graph_def: The input graph, an instance of `tf.compat.v1.GraphDef`.\n init_op: The init op name, a string.\n\n Returns:\n The updated graph, an instance of `tf.compat.v1.GraphDef`.\n \"\"\"\n py_typecheck.check_type(graph_def, tf.compat.v1.GraphDef)\n py_typecheck.check_type(init_op, str)\n init_op_str = to_node_name(init_op)\n init_op_control_dep = '^{}'.format(init_op_str)\n deps = get_deps_for_graph_node(graph_def,\n init_op_str).union(set([init_op_str]))\n new_graph_def = tf.compat.v1.GraphDef()\n new_graph_def.CopyFrom(graph_def)\n for new_node in new_graph_def.node:\n if new_node.name not in deps:\n node_inputs = set(new_node.input)\n if init_op_control_dep not in node_inputs:\n new_node.input.extend([init_op_control_dep])\n return new_graph_def\n\n\ndef coerce_dataset_elements_to_tff_type_spec(dataset, element_type):\n \"\"\"Map the elements of a dataset to a specified type.\n\n This is used to coerce a `tf.data.Dataset` that may have lost the ordering\n of dictionary keys back into a `collections.OrderedDict` (required by TFF).\n\n Args:\n dataset: a `tf.data.Dataset` instance.\n element_type: a `tff.Type` specifying the type of the elements of `dataset`.\n Must be a `tff.TensorType` or `tff.StructType`.\n\n Returns:\n A `tf.data.Dataset` whose output types are compatible with\n `element_type`.\n\n Raises:\n ValueError: if the elements of `dataset` cannot be coerced into\n `element_type`.\n \"\"\"\n py_typecheck.check_type(dataset,\n type_conversions.TF_DATASET_REPRESENTATION_TYPES)\n py_typecheck.check_type(element_type, computation_types.Type)\n if element_type.is_tensor():\n return dataset\n # This is a similar to `reference_context.to_representation_for_type`,\n # look for opportunities to consolidate?\n def _to_representative_value(type_spec, elements):\n \"\"\"Convert to a container to a type understood by TF and TFF.\"\"\"\n if type_spec.is_tensor():\n return elements\n elif type_spec.is_struct_with_python():\n if tf.is_tensor(elements):\n # In this case we have a singleton tuple tensor that may have been\n # unwrapped by tf.data.\n elements = [elements]\n py_type = computation_types.StructWithPythonType.get_container_type(\n type_spec)\n field_types = structure.iter_elements(type_spec)\n if (issubclass(py_type, collections.abc.Mapping) or\n py_typecheck.is_attrs(py_type)):\n values = collections.OrderedDict(\n (name, _to_representative_value(field_type, elements[name]))\n for name, field_type in field_types)\n return py_type(**values)\n else:\n values = [\n _to_representative_value(field_type, e)\n for (_, field_type), e in zip(field_types, elements)\n ]\n if py_typecheck.is_named_tuple(py_type):\n return py_type(*values)\n return py_type(values)\n elif type_spec.is_struct():\n field_types = structure.to_elements(type_spec)\n is_all_named = all([name is not None for name, _ in field_types])\n if is_all_named:\n if py_typecheck.is_named_tuple(elements):\n values = collections.OrderedDict(\n (name, _to_representative_value(field_type, e))\n for (name, field_type), e in zip(field_types, elements))\n return type(elements)(**values)\n else:\n values = [(name, _to_representative_value(field_type, elements[name]))\n for name, field_type in field_types]\n return collections.OrderedDict(values)\n else:\n return tuple(\n _to_representative_value(t, e) for t, e in zip(type_spec, elements))\n else:\n raise ValueError(\n 'Coercing a dataset with elements of expected type {!s}, '\n 'produced a value with incompatible type `{!s}. Value: '\n '{!s}'.format(type_spec, type(elements), elements))\n\n # tf.data.Dataset of tuples will unwrap the tuple in the `map()` call, so we\n # must pass a function taking *args. However, if the call was originally only\n # a single tuple, it is now \"double wrapped\" and must be unwrapped before\n # traversing.\n def _unwrap_args(*args):\n if len(args) == 1:\n return _to_representative_value(element_type, args[0])\n else:\n return _to_representative_value(element_type, args)\n\n return dataset.map(_unwrap_args)\n\n\ndef deserialize_and_call_tf_computation(computation_proto, arg, graph):\n \"\"\"Deserializes a TF computation and inserts it into `graph`.\n\n This method performs an action that can be considered roughly the opposite of\n what `tensorflow_serialization.tf_computation_serializer` does. At\n the moment, it simply imports the graph in the current context. A future\n implementation may rely on different mechanisms. The caller should not be\n concerned with the specifics of the implementation. At this point, the method\n is expected to only be used within the body of another TF computation (within\n an instance of `tensorflow_computation_context.TensorFlowComputationContext`\n at the top of the stack), and potentially also in certain types of interpreted\n execution contexts (TBD).\n\n Args:\n computation_proto: An instance of `pb.Computation` with the `computation`\n one of equal to `tensorflow` to be deserialized and called.\n arg: The argument to invoke the computation with, or None if the computation\n does not specify a parameter type and does not expects one.\n graph: The graph to stamp into.\n\n Returns:\n A tuple (init_op, result) where:\n init_op: String name of an op to initialize the graph.\n result: The results to be fetched from TensorFlow. Depending on\n the type of the result, this can be `tf.Tensor` or `tf.data.Dataset`\n instances, or a nested structure (such as an\n `structure.Struct`).\n\n Raises:\n TypeError: If the arguments are of the wrong types.\n ValueError: If `computation_proto` is not a TensorFlow computation proto.\n \"\"\"\n py_typecheck.check_type(computation_proto, pb.Computation)\n computation_oneof = computation_proto.WhichOneof('computation')\n if computation_oneof != 'tensorflow':\n raise ValueError(\n 'Expected a TensorFlow computation, got {}.'.format(computation_oneof))\n py_typecheck.check_type(graph, tf.Graph)\n with graph.as_default():\n type_spec = type_serialization.deserialize_type(computation_proto.type)\n if type_spec.parameter is None:\n if arg is None:\n input_map = None\n else:\n raise TypeError(\n 'The computation declared no parameters; encountered an unexpected '\n 'argument {}.'.format(arg))\n elif arg is None:\n raise TypeError(\n 'The computation declared a parameter of type {}, but the argument '\n 'was not supplied.'.format(type_spec.parameter))\n else:\n arg_type, arg_binding = capture_result_from_graph(arg, graph)\n if not type_spec.parameter.is_assignable_from(arg_type):\n raise TypeError(\n 'The computation declared a parameter of type {}, but the argument '\n 'is of a mismatching type {}.'.format(type_spec.parameter,\n arg_type))\n else:\n input_map = {\n k: graph.get_tensor_by_name(v)\n for k, v in compute_map_from_bindings(\n computation_proto.tensorflow.parameter, arg_binding).items()\n }\n return_elements = extract_tensor_names_from_binding(\n computation_proto.tensorflow.result)\n orig_init_op_name = computation_proto.tensorflow.initialize_op\n if orig_init_op_name:\n return_elements.append(orig_init_op_name)\n # Note: Unlike MetaGraphDef, the GraphDef alone contains no information\n # about collections, and hence, when we import a graph with Variables,\n # those Variables are not added to global collections, and hence\n # functions like tf.compat.v1.global_variables_initializers() will not\n # contain their initialization ops.\n output_tensors = tf.import_graph_def(\n serialization_utils.unpack_graph_def(\n computation_proto.tensorflow.graph_def),\n input_map,\n return_elements,\n # Note: It is very important not to return any names from the original\n # computation_proto.tensorflow.graph_def, those names might or might not\n # be valid in the current graph. Using a different scope makes the graph\n # somewhat more readable, since _N style de-duplication of graph\n # node names is less likely to be needed.\n name='subcomputation')\n\n output_map = {k: v for k, v in zip(return_elements, output_tensors)}\n new_init_op_name = output_map.pop(orig_init_op_name, None)\n return (\n new_init_op_name,\n assemble_result_from_graph(type_spec.result,\n computation_proto.tensorflow.result,\n output_map),\n )\n", "# Copyright 2019, Google LLC.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport collections\n\nfrom absl.testing import parameterized\nimport tensorflow as tf\n\nfrom tensorflow_federated.python.core.backends.native import execution_contexts\nfrom tensorflow_federated.python.simulation.baselines.cifar import cifar_preprocessing\n\n\nTEST_DATA = collections.OrderedDict(\n coarse_label=([tf.constant(1, dtype=tf.int64)]),\n image=([tf.zeros((32, 32, 3), dtype=tf.uint8)]),\n label=([tf.constant(1, dtype=tf.int64)]),\n)\n\n\ndef _compute_length_of_dataset(ds):\n return ds.reduce(0, lambda x, _: x + 1)\n\n\nclass PreprocessFnTest(tf.test.TestCase, parameterized.TestCase):\n\n def test_preprocess_fn_with_negative_epochs_raises(self):\n with self.assertRaisesRegex(ValueError,\n 'num_epochs must be a positive integer'):\n cifar_preprocessing.create_preprocess_fn(num_epochs=-2, batch_size=1)\n\n def test_raises_non_iterable_crop(self):\n with self.assertRaisesRegex(TypeError, 'crop_shape must be an iterable'):\n cifar_preprocessing.create_preprocess_fn(\n num_epochs=1, batch_size=1, crop_shape=32)\n\n def test_raises_iterable_length_2_crop(self):\n with self.assertRaisesRegex(ValueError,\n 'The crop_shape must have length 3'):\n cifar_preprocessing.create_preprocess_fn(\n num_epochs=1, batch_size=1, crop_shape=(32, 32))\n\n @parameterized.named_parameters(\n ('num_epochs_1_batch_size_1', 1, 1),\n ('num_epochs_4_batch_size_2', 4, 2),\n ('num_epochs_9_batch_size_3', 9, 3),\n ('num_epochs_12_batch_size_1', 12, 1),\n ('num_epochs_3_batch_size_5', 3, 5),\n ('num_epochs_7_batch_size_2', 7, 2),\n )\n def test_ds_length_is_ceil_num_epochs_over_batch_size(self, num_epochs,\n batch_size):\n ds = tf.data.Dataset.from_tensor_slices(TEST_DATA)\n preprocess_fn = cifar_preprocessing.create_preprocess_fn(\n num_epochs=num_epochs, batch_size=batch_size, shuffle_buffer_size=1)\n preprocessed_ds = preprocess_fn(ds)\n self.assertEqual(\n _compute_length_of_dataset(preprocessed_ds),\n tf.cast(tf.math.ceil(num_epochs / batch_size), tf.int32))\n\n @parameterized.named_parameters(\n ('crop_shape_1_no_distort', (32, 32, 3), False),\n ('crop_shape_2_no_distort', (28, 28, 3), False),\n ('crop_shape_3_no_distort', (24, 26, 3), False),\n ('crop_shape_1_distort', (32, 32, 3), True),\n ('crop_shape_2_distort', (28, 28, 3), True),\n ('crop_shape_3_distort', (24, 26, 3), True),\n )\n def test_preprocess_fn_returns_correct_element(self, crop_shape,\n distort_image):\n ds = tf.data.Dataset.from_tensor_slices(TEST_DATA)\n preprocess_fn = cifar_preprocessing.create_preprocess_fn(\n num_epochs=1,\n batch_size=1,\n shuffle_buffer_size=1,\n crop_shape=crop_shape,\n distort_image=distort_image)\n preprocessed_ds = preprocess_fn(ds)\n expected_element_spec_shape = (None,) + crop_shape\n self.assertEqual(\n preprocessed_ds.element_spec,\n (tf.TensorSpec(shape=expected_element_spec_shape, dtype=tf.float32),\n tf.TensorSpec(shape=(None,), dtype=tf.int64)))\n\n expected_element_shape = (1,) + crop_shape\n element = next(iter(preprocessed_ds))\n expected_element = (tf.zeros(\n shape=expected_element_shape,\n dtype=tf.float32), tf.ones(shape=(1,), dtype=tf.int32))\n self.assertAllClose(self.evaluate(element), expected_element)\n\n def test_preprocess_is_no_op_for_normalized_image(self):\n crop_shape = (1, 1, 3)\n x = tf.constant([[[1.0, -1.0, 0.0]]]) # Has shape (1, 1, 3), mean 0\n x = x / tf.math.reduce_std(x) # x now has variance 1\n simple_example = collections.OrderedDict(image=x, label=0)\n image_map = cifar_preprocessing.build_image_map(crop_shape, distort=False)\n cropped_example = image_map(simple_example)\n\n self.assertEqual(cropped_example[0].shape, crop_shape)\n self.assertAllClose(x, cropped_example[0], rtol=1e-03)\n self.assertEqual(cropped_example[1], 0)\n\n\nif __name__ == '__main__':\n execution_contexts.set_local_execution_context()\n tf.test.main()\n" ]
[ [ "tensorflow.constant", "tensorflow.io.gfile.listdir" ], [ "tensorflow.zeros" ], [ "tensorflow.nest.map_structure" ], [ "tensorflow.convert_to_tensor", "tensorflow.is_tensor", "tensorflow.nest.assert_same_structure", "tensorflow.constant", "tensorflow.executing_eagerly", "tensorflow.compat.v1.data.make_one_shot_iterator", "tensorflow.data.Dataset.from_tensor_slices", "tensorflow.identity", "tensorflow.data.experimental.to_variant", "tensorflow.compat.v1.placeholder", "tensorflow.no_op", "tensorflow.compat.v1.GraphDef", "tensorflow.nest.flatten", "numpy.array", "numpy.zeros", "numpy.empty" ], [ "tensorflow.constant", "tensorflow.zeros", "tensorflow.data.Dataset.from_tensor_slices", "tensorflow.test.main", "tensorflow.ones", "tensorflow.math.reduce_std", "tensorflow.math.ceil", "tensorflow.TensorSpec" ] ]
[ { "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": [] } ]
keuntaeklee/pytorch-PPUU
[ "0ba8c953df9cdb1e9937e301ed3384ac6b66ea73", "0ba8c953df9cdb1e9937e301ed3384ac6b66ea73" ]
[ "eval_fm.py", "map_lanker.py" ]
[ "import argparse\nimport os\nimport random\n\nimport numpy as np\nimport torch\nimport torch.nn.functional as fun\n\nimport utils\nfrom dataloader import DataLoader\n\nparser = argparse.ArgumentParser(fromfile_prefix_chars='@')\nparser.add_argument('-dataset', type=str, default='i80')\nparser.add_argument('-debug', action='store_true')\nparser.add_argument('-batch_size', type=int, default=4)\nparser.add_argument('-v', type=int, default=4)\nparser.add_argument('-display', type=int, default=0)\nparser.add_argument('-seed', type=int, default=9999)\nparser.add_argument('-lanes', type=int, default=8)\nparser.add_argument('-traffic_rate', type=int, default=15)\nparser.add_argument('-n_episodes', type=int, default=1)\nparser.add_argument('-ncond', type=int, default=20)\nparser.add_argument('-npred', type=int, default=200)\nparser.add_argument('-n_batches', type=int, default=200)\nparser.add_argument('-n_samples', type=int, default=10)\nparser.add_argument('-n_action_seq', type=int, default=5)\nparser.add_argument('-sampling', type=str, default='fp')\nparser.add_argument('-noise', type=float, default=0.0)\nparser.add_argument('-n_mixture', type=int, default=20)\nparser.add_argument('-graph_density', type=float, default=0.001)\nparser.add_argument('-model_dir', type=str, default='models/')\nM1 = 'model=fwd-cnn-layers=3-bsize=64-ncond=20-npred=20-lrt=0.0001-nfeature=256-dropout=0.1-gclip=5.0-' + \\\n 'warmstart=0-seed=1.step200000.model'\nM2 = 'model=fwd-cnn-vae-fp-layers=3-bsize=64-ncond=20-npred=20-lrt=0.0001-nfeature=256-dropout=0.1-nz=32-' + \\\n 'beta=1e-06-zdropout=0.0-gclip=5.0-warmstart=1-seed=1.step200000.model'\nM3 = 'model=fwd-cnn-vae-fp-layers=3-bsize=64-ncond=20-npred=20-lrt=0.0001-nfeature=256-dropout=0.1-nz=32-' + \\\n 'beta=1e-06-zdropout=0.5-gclip=5.0-warmstart=1-seed=1.step200000.model'\nM4 = 'model=fwd-cnn-ten3-layers=3-bsize=64-ncond=20-npred=20-lrt=0.0001-nfeature=256-nhidden=128-fgeom=1-' + \\\n 'zeroact=0-zmult=0-dropout=0.1-nz=32-beta=0.0-zdropout=0.5-gclip=5.0-warmstart=1-seed=1.step200000.model'\nparser.add_argument('-mfile', type=str, default=M3)\nparser.add_argument('-cuda', type=int, default=1)\nparser.add_argument('-save_video', type=int, default=1)\nopt = parser.parse_args()\n\nif 'zeroact=1' in opt.mfile:\n opt.zeroact = 1\nelse:\n opt.zeroact = 0\n\nrandom.seed(opt.seed)\nnp.random.seed(opt.seed)\ntorch.manual_seed(opt.seed)\n\nopt.save_video = (opt.save_video == 1)\nopt.eval_dir = opt.model_dir + f'eval/'\n\n\nprint(f'[loading {opt.model_dir + opt.mfile}]')\nmodel = torch.load(opt.model_dir + opt.mfile)\nif type(model) is dict: model = model['model']\nmodel = model.cuda()\nmodel.eval()\n# if opt.cuda == 1:\n # model.intype('gpu')\n\ndataloader = DataLoader(None, opt, opt.dataset)\n# model.opt.npred = opt.npred # instruct the model about how many predictions we want it to produce\nmodel.opt.alpha = 0\n\ndirname = f'{opt.eval_dir}{opt.mfile}-nbatches={opt.n_batches}-npred={opt.npred}-nsample={opt.n_samples}'\nif '-ten' in opt.mfile:\n dirname += f'-sampling={opt.sampling}'\n if opt.sampling == 'knn':\n dirname += f'-density={opt.graph_density}'\n elif opt.sampling == 'pdf':\n dirname += f'-nmixture={opt.n_mixture}'\n mfile_prior = f'{opt.model_dir}/{opt.mfile}-nfeature=128-lrt=0.0001-nmixture={opt.n_mixture}.prior'\n print(f'[loading prior model: {mfile_prior}]')\n model.prior = torch.load(mfile_prior).cuda()\n # load z vectors. Extract them if they are not already saved.\n pzfile = opt.model_dir + opt.mfile + '.pz'\n if os.path.isfile(pzfile):\n p_z = torch.load(pzfile)\n graph = torch.load(pzfile + '.graph')\n model.p_z = p_z\n model.knn_indx = graph.get('knn_indx')\n model.knn_dist = graph.get('knn_dist')\n model.opt.topz_sample = int(model.p_z.size(0) * opt.graph_density)\n else:\n model.compute_pz(dataloader, opt, 250)\n torch.save(model.p_z, pzfile)\n model.compute_z_graph()\n torch.save({'knn_dist': model.knn_dist, 'knn_indx': model.knn_indx}, pzfile + '.graph')\n print('[done]')\n\ndirname += '.eval'\nos.system('mkdir -p ' + dirname)\n\n# if opt.cuda == 1:\n# model.intype('gpu')\n\nloss_i = torch.zeros(opt.n_batches, opt.batch_size, opt.n_samples, opt.npred)\nloss_s = torch.zeros(opt.n_batches, opt.batch_size, opt.n_samples, opt.npred)\nloss_c = torch.zeros(opt.n_batches, opt.batch_size, opt.n_samples, opt.npred)\ntrue_costs = torch.zeros(opt.n_batches, opt.batch_size, opt.npred, 2)\npred_costs = torch.zeros(opt.n_batches, opt.batch_size, opt.n_samples, opt.npred, 2)\ntrue_states = torch.zeros(opt.n_batches, opt.batch_size, opt.npred, 4)\npred_states = torch.zeros(opt.n_batches, opt.batch_size, opt.n_samples, opt.npred, 4)\n\n\ndef compute_loss(targets, predictions, r=True):\n pred_images, pred_states, _ = predictions\n target_images, target_states, target_costs = targets\n loss_i = fun.mse_loss(pred_images, target_images, reduce=r)\n loss_s = fun.mse_loss(pred_states, target_states, reduce=r)\n loss_c = fun.mse_loss(pred_costs.cuda(), target_costs.cuda(), reduce=r)\n return loss_i, loss_s, loss_c\n\n\ndataloader.random.seed(12345)\n\nfor i in range(opt.n_batches):\n with torch.no_grad():\n torch.cuda.empty_cache()\n inputs, actions, targets, _, _ = dataloader.get_batch_fm('test', opt.npred)\n\n # save ground truth for the first 10 x batch_size samples\n if i < 10 and opt.save_video:\n for b in range(opt.batch_size):\n dirname_movie = f'{dirname}/videos/x{i * opt.batch_size + b:d}/y/'\n print(f'[saving ground truth video: {dirname_movie}]')\n utils.save_movie(dirname_movie, targets[0][b], targets[1][b], targets[2][b])\n\n for s in range(opt.n_samples):\n print(f'[batch {i}, sample {s}]', end=\"\\r\")\n\n if opt.zeroact == 1:\n actions.data.zero_()\n\n pred, _ = model(inputs, actions, targets, sampling=opt.sampling) # return as many predictions as actions\n pred_states[i, :, s].copy_(pred[1])\n true_states[i].copy_(targets[1])\n\n if i < 10 and s < 20 and opt.save_video:\n for b in range(opt.batch_size):\n dirname_movie = f'{dirname}/videos/sampled_z/true_actions/x{i * opt.batch_size + b:d}/z{s:d}/'\n print(f'[saving video: {dirname_movie}]', end=\"\\r\")\n utils.save_movie(dirname_movie, pred[0][b], pred[1][b]) # , pred_[2][b])\n # ^ images ^ position and velocity\n\n # rotate actions across the batch: a_{t} -> a_{t + 1}\n actions_rot = actions[(torch.arange(opt.batch_size) - 1) % opt.batch_size]\n\n # also generate videos with different action sequences\n pred_rot, _ = model(inputs, actions_rot, targets, sampling=opt.sampling)\n if i < 10 and s < 20 and opt.save_video:\n for b in range(opt.batch_size):\n dirname_movie = f'{dirname}/videos/sampled_z/rot_actions/x{i * opt.batch_size + b:d}/z{s:d}/'\n print('[saving video: {}]'.format(dirname_movie), end=\"\\r\")\n utils.save_movie(dirname_movie, pred_rot[0][b], pred_rot[1][b]) # , pred_perm[2][b])\n\n # also generate videos with true z vectors\n if s == 0:\n pred_true_z, _ = model(inputs, actions, targets)\n for b in range(opt.batch_size):\n dirname_movie = f'{dirname}/videos/true_z/true_actions/x{i * opt.batch_size + b:d}/z{s:d}/'\n print('[saving video: {}]'.format(dirname_movie), end=\"\\r\")\n utils.save_movie(dirname_movie, pred_true_z[0][b], pred_true_z[1][b]) # , pred_true_z[2][b])\n\n pred_true_z_rot, _ = model(inputs, actions_rot, targets)\n for b in range(opt.batch_size):\n dirname_movie = f'{dirname}/videos/true_z/rot_actions/x{i * opt.batch_size + b:d}/z{s:d}/'\n print('[saving video: {}]'.format(dirname_movie), end=\"\\r\")\n utils.save_movie(dirname_movie, pred_true_z_rot[0][b], pred_true_z_rot[1][b])\n # , pred_true_z_perm[2][b])\n\n # del inputs, actions, targets, pred\n\ntorch.save({'loss_i': loss_i,\n 'loss_s': loss_s,\n 'loss_c': loss_c,\n 'true_costs': true_costs,\n 'pred_costs': pred_costs,\n 'true_states': true_states,\n 'pred_states': pred_states},\n f'{dirname}/loss.pth')\n\nos.system(f'tar -cvf {dirname}.tgz {dirname}')\n", "from random import choice, randrange\n\nfrom custom_graphics import draw_dashed_line\nfrom map_i80 import I80, I80Car, colours\nfrom traffic_gym import Simulator\nimport pygame\nimport pandas as pd\nimport numpy as np\nimport pdb, random\nimport bisect\nimport pdb, pickle, os\n\n# Conversion LANE_W from real world to pixels\n# A US highway lane width is 3.7 metres, here 50 pixels\nLANE_W = 24 # pixels / 3.7 m, lane width\nSCALE = LANE_W / 3.7 # pixels per metre\nFOOT = 0.3048 # metres per foot\nX_OFFSET = -35 # horizontal offset (camera 2 leftmost view)\nMAX_SPEED = 130\n\n\nclass LankerCar(I80Car):\n # Global constants\n SCALE = SCALE\n LANE_W = LANE_W\n X_OFFSET = X_OFFSET\n max_b = 0.05 # set a looser max turning limitation\n\n @property\n def current_lane(self):\n # 1: left-most, 5: right-most, 6: auxiliary lane, 7: on-ramp, 8: off-ramp\n return 0\n\n\nclass Lankershim(I80):\n # Environment's car class\n EnvCar = LankerCar\n\n # Global constants\n SCALE = SCALE\n LANE_W = LANE_W\n X_OFFSET = X_OFFSET\n DUMP_NAME = 'data_lanker_v0'\n\n def __init__(self, **kwargs):\n kwargs['nb_lanes'] = 1\n kwargs['delta_t'] = 1/10\n super().__init__(**kwargs)\n\n self.screen_size = (560 + 760 + 648 + 912 + 328, 20 * self.LANE_W)\n # self.photos = (\n # pygame.image.load('Lankershim/cam1.png'),\n # pygame.image.load('Lankershim/cam2.png'),\n # pygame.image.load('Lankershim/cam3.png'),\n # pygame.image.load('Lankershim/cam4.png'),\n # pygame.image.load('Lankershim/cam5.png'),\n # )\n # self.photos_rect = (\n # self.photos[0].get_rect().move([0, 20]),\n # self.photos[1].get_rect().move([560, 20]),\n # self.photos[2].get_rect().move([560 + 760, 20]),\n # self.photos[3].get_rect().move([560 + 760 + 648, 20]),\n # self.photos[4].get_rect().move([560 + 760 + 648 + 912, 20]),\n # )\n if self.display: # if display is required\n self.screen = pygame.display.set_mode(self.screen_size) # set screen size\n # self.delta_t = 1 / 10 # simulation timing interval\n self._time_slots = (\n 'lanker/trajectories-0830am-0845am',\n 'lanker/trajectories-0845am-0900am',\n )\n self._t_slot = None\n self._black_list = {\n self._time_slots[0]:\n {128, 65, 995, 1124, 377, 810, 1003, 172, 335, 591, # off track (OT)\n 560, 1173, 1399, 1437, 153, 890, 1308, 1405, 413, 639, # OT\n 66, 112, 111, 94, 115, 122, 130, 170, 149, 152, 160, 210, 292, 261, 291, 339, # crash\n 300, 312, 306, 320, 391, 415, 434, 436, 472, 345, 432, 468, 397, 329, 528, 567, # crash\n 549, 468, 530, 585, 624, 737, 711, 716, 690, 753, 716, 762, 818, 904, 930, 887, # crash\n 964, 906, 931, 1005, 982, 989, 1000, 1433, 1037, 1189, 1155, 1221, 1260, 1258, # crash\n 1249, 1277, 1285, 1386, 1372, 1366, 1007, 1001}, # crash\n self._time_slots[1]:\n {1539, 772, 517, 267, 396, 1164, 1421, 1549, 530, 664, 1570, 1059, 804, 169, 812, 1453, 48, 53, # OT\n 1469, 1600, 1472, 1474, 451, 580, 1478, 584, 212, 1492, 1114, 228, 233, 625, 1394, 1268, 1023, # OT\n 58, 36, 129, 131, 74, 163, 122, 160, 296, 321, 330, 369, 395, 358, 322, 274, 481, 492, # crash\n 443, 490, 524, 437, 545, 600, 487, 730, 740, 628, 810, 753, 844, 716, 903, 672, 915, 936, # crash\n 809, 872, 967, 1075, 1069, 1109, 1098, 1075, 982, 986, 1069, 1109, 1180, 1155, 1103, 1232, # crash\n 1238, 1260, 1132, 1308, 1353, 1306, 1392, 1409, 1301, 1456, 1422, 1475, 1542, 1552, 1524, # crash\n 348, 521, 824, 911, 985, 1178}\n }\n self.df = None\n self.vehicles_history = None\n self.lane_occupancy = None\n # self._lane_surfaces = dict()\n # self.nb_lanes = 1\n self.smoothing_window = 15\n self.offset = 195\n\n @staticmethod\n def _get_data_frame(time_slot, x_max, x_offset):\n # TODO: need caching! See I-80\n file_name = f'traffic-data/xy-trajectories/{time_slot}.txt'\n print(f'Loading trajectories from {file_name}')\n df = pd.read_csv(file_name, sep=r'\\s+', header=None, names=(\n 'Vehicle ID',\n 'Frame ID',\n 'Total Frames',\n 'Global Time',\n 'Local X',\n 'Local Y',\n 'Global X',\n 'Global Y',\n 'Vehicle Length',\n 'Vehicle Width',\n 'Vehicle Class',\n 'Vehicle Velocity',\n 'Vehicle Acceleration',\n 'Lane Identification',\n 'Origin Zone',\n 'Destination Zone',\n 'Intersection',\n 'Section',\n 'Direction',\n 'Movement',\n 'Preceding Vehicle',\n 'Following Vehicle',\n 'Spacing',\n 'Headway'\n ))\n\n # Get valid x coordinate rows\n valid_x = (df['Local Y'] * FOOT * SCALE - x_offset).between(0, x_max).values\n\n # Restrict data frame to valid x coordinates\n return df[valid_x]\n\n def _draw_lanes(self, surface, mode='human', offset=0):\n\n if mode == 'human':\n\n # load lanes, if not already done so\n if mode not in self._lane_surfaces:\n self._lane_surfaces[mode] = pygame.image.load('Lankershim/lanes_human.png')\n\n surface.blit(self._lane_surfaces[mode], (0, 0))\n\n if mode == 'machine':\n\n # load lanes\n lanes_surface = pygame.image.load('Lankershim/lanes_machine.png')\n surface.blit(lanes_surface, (offset, offset))\n\n # save for later\n self._lane_surfaces[mode] = surface.copy()\n" ]
[ [ "numpy.random.seed", "torch.zeros", "torch.load", "torch.manual_seed", "torch.cuda.empty_cache", "torch.nn.functional.mse_loss", "torch.no_grad", "torch.arange", "torch.save" ], [ "pandas.read_csv" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
nils-werner/librosa
[ "3d57352e6f5b6da151a2dd5d303af985797800aa", "3d57352e6f5b6da151a2dd5d303af985797800aa" ]
[ "tests/test_features.py", "librosa/core/audio.py" ]
[ "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\nfrom __future__ import print_function\nimport warnings\nimport numpy as np\n\nimport pytest\n\nimport librosa\n\nfrom test_core import load, srand\n\n# Disable cache\nimport os\ntry:\n os.environ.pop('LIBROSA_CACHE_DIR')\nexcept KeyError:\n pass\n\n__EXAMPLE_FILE = os.path.join('tests', 'data', 'test1_22050.wav')\nwarnings.resetwarnings()\nwarnings.simplefilter('always')\nwarnings.filterwarnings('module', '.*', FutureWarning, 'scipy.*')\n\n\n# utils submodule\[email protected]('slope', np.linspace(-2, 2, num=6))\[email protected]('xin', [np.vstack([np.arange(100.0)] * 3)])\[email protected]('order', [1, pytest.mark.xfail(0)])\[email protected]('width, axis', [pytest.mark.xfail((-1, 0)),\n pytest.mark.xfail((-1, 1)),\n pytest.mark.xfail((0, 0)),\n pytest.mark.xfail((0, 1)),\n pytest.mark.xfail((1, 0)),\n pytest.mark.xfail((1, 1)),\n pytest.mark.xfail((2, 0)),\n pytest.mark.xfail((2, 1)),\n (3, 0), (3, 1),\n pytest.mark.xfail((4, 0)),\n pytest.mark.xfail((4, 1)),\n (5, 1), pytest.mark.xfail((5, 0)),\n pytest.mark.xfail((6, 0)),\n pytest.mark.xfail((6, 1)),\n pytest.mark.xfail((7, 0)), (7, 1)])\[email protected]('bias', [-10, 0, 10])\ndef test_delta(xin, width, slope, order, axis, bias):\n\n x = slope * xin + bias\n\n # Note: this test currently only checks first-order differences\n# if width < 3 or np.mod(width, 2) != 1 or width > x.shape[axis]:\n# pytest.raises(librosa.ParameterError)\n\n delta = librosa.feature.delta(x,\n width=width,\n order=order,\n axis=axis)\n\n # Check that trimming matches the expected shape\n assert x.shape == delta.shape\n\n # Once we're sufficiently far into the signal (ie beyond half_len)\n # (x + delta)[t] should approximate x[t+1] if x is actually linear\n slice_orig = [slice(None)] * x.ndim\n slice_out = [slice(None)] * delta.ndim\n slice_orig[axis] = slice(width//2 + 1, -width//2 + 1)\n slice_out[axis] = slice(width//2, -width//2)\n assert np.allclose((x + delta)[tuple(slice_out)], x[tuple(slice_orig)])\n\n\ndef test_stack_memory():\n\n def __test(n_steps, delay, data):\n data_stack = librosa.feature.stack_memory(data,\n n_steps=n_steps,\n delay=delay)\n\n # If we're one-dimensional, reshape for testing\n if data.ndim == 1:\n data = data.reshape((1, -1))\n\n d, t = data.shape\n\n assert data_stack.shape[0] == n_steps * d\n assert data_stack.shape[1] == t\n\n assert np.allclose(data_stack[0], data[0])\n\n for i in range(d):\n for step in range(1, n_steps):\n if delay > 0:\n assert np.allclose(data[i, :- step * delay],\n data_stack[step * d + i, step * delay:])\n else:\n assert np.allclose(data[i, -step * delay:],\n data_stack[step * d + i, :step * delay])\n\n srand()\n\n for ndim in [1, 2]:\n data = np.random.randn(* ([5] * ndim))\n\n for n_steps in [-1, 0, 1, 2, 3, 4]:\n for delay in [-4, -2, -1, 0, 1, 2, 4]:\n tf = __test\n if n_steps < 1:\n tf = pytest.mark.xfail(__test, raises=librosa.ParameterError)\n if delay == 0:\n tf = pytest.mark.xfail(__test, raises=librosa.ParameterError)\n yield tf, n_steps, delay, data\n\n\n# spectral submodule\ndef test_spectral_centroid_synthetic():\n\n k = 5\n\n def __test(S, freq, sr, n_fft):\n cent = librosa.feature.spectral_centroid(S=S, freq=freq)\n\n if freq is None:\n freq = librosa.fft_frequencies(sr=sr, n_fft=n_fft)\n\n assert np.allclose(cent, freq[k])\n\n srand()\n # construct a fake spectrogram\n sr = 22050\n n_fft = 1024\n S = np.zeros((1 + n_fft // 2, 10))\n\n S[k, :] = 1.0\n\n yield __test, S, None, sr, n_fft\n\n freq = librosa.fft_frequencies(sr=sr, n_fft=n_fft)\n yield __test, S, freq, sr, n_fft\n\n # And if we modify the frequencies\n freq *= 3\n yield __test, S, freq, sr, n_fft\n\n # Or if we make up random frequencies for each frame\n freq = np.random.randn(*S.shape)\n yield __test, S, freq, sr, n_fft\n\n\ndef test_spectral_centroid_errors():\n\n @pytest.mark.xfail(raises=librosa.ParameterError)\n def __test(S):\n librosa.feature.spectral_centroid(S=S)\n\n S = - np.ones((513, 10))\n yield __test, S\n\n S = - np.ones((513, 10)) * 1.j\n yield __test, S\n\n\ndef test_spectral_centroid_empty():\n\n def __test(y, sr, S):\n cent = librosa.feature.spectral_centroid(y=y, sr=sr, S=S)\n assert not np.any(cent)\n\n sr = 22050\n y = np.zeros(3 * sr)\n yield __test, y, sr, None\n\n S = np.zeros((1025, 10))\n yield __test, None, sr, S\n\n\ndef test_spectral_bandwidth_synthetic():\n # This test ensures that a signal confined to a single frequency bin\n # always achieves 0 bandwidth\n k = 5\n\n def __test(S, freq, sr, n_fft, norm, p):\n bw = librosa.feature.spectral_bandwidth(S=S, freq=freq, norm=norm, p=p)\n\n assert not np.any(bw)\n\n srand()\n # construct a fake spectrogram\n sr = 22050\n n_fft = 1024\n S = np.zeros((1 + n_fft // 2, 10))\n S[k, :] = 1.0\n\n for norm in [False, True]:\n for p in [1, 2]:\n # With vanilla frequencies\n yield __test, S, None, sr, n_fft, norm, p\n\n # With explicit frequencies\n freq = librosa.fft_frequencies(sr=sr, n_fft=n_fft)\n yield __test, S, freq, sr, n_fft, norm, p\n\n # And if we modify the frequencies\n freq = 3 * librosa.fft_frequencies(sr=sr, n_fft=n_fft)\n yield __test, S, freq, sr, n_fft, norm, p\n\n # Or if we make up random frequencies for each frame\n freq = np.random.randn(*S.shape)\n yield __test, S, freq, sr, n_fft, norm, p\n\n\ndef test_spectral_bandwidth_onecol():\n # This test checks for issue https://github.com/librosa/librosa/issues/552\n # failure when the spectrogram has a single column\n\n def __test(S, freq):\n bw = librosa.feature.spectral_bandwidth(S=S, freq=freq)\n\n assert bw.shape == (1, 1)\n\n k = 5\n\n srand()\n # construct a fake spectrogram\n sr = 22050\n n_fft = 1024\n S = np.zeros((1 + n_fft // 2, 1))\n S[k, :] = 1.0\n\n # With vanilla frequencies\n yield __test, S, None\n\n # With explicit frequencies\n freq = librosa.fft_frequencies(sr=sr, n_fft=n_fft)\n yield __test, S, freq\n\n # And if we modify the frequencies\n freq = 3 * librosa.fft_frequencies(sr=sr, n_fft=n_fft)\n yield __test, S, freq\n\n # Or if we make up random frequencies for each frame\n freq = np.random.randn(*S.shape)\n yield __test, S, freq\n\n\ndef test_spectral_bandwidth_errors():\n\n @pytest.mark.xfail(raises=librosa.ParameterError)\n def __test(S):\n librosa.feature.spectral_bandwidth(S=S)\n\n S = - np.ones((513, 10))\n yield __test, S\n\n S = - np.ones((513, 10)) * 1.j\n yield __test, S\n\n\ndef test_spectral_rolloff_synthetic():\n\n srand()\n\n sr = 22050\n n_fft = 2048\n\n def __test(S, freq, pct):\n\n rolloff = librosa.feature.spectral_rolloff(S=S, sr=sr, freq=freq,\n roll_percent=pct)\n\n if freq is None:\n freq = librosa.fft_frequencies(sr=sr, n_fft=n_fft)\n\n idx = np.floor(pct * freq.shape[0]).astype(int)\n assert np.allclose(rolloff, freq[idx])\n\n S = np.ones((1 + n_fft // 2, 10))\n\n for pct in [0.25, 0.5, 0.95]:\n # Implicit frequencies\n yield __test, S, None, pct\n\n # Explicit frequencies\n freq = librosa.fft_frequencies(sr=sr, n_fft=n_fft)\n yield __test, S, freq, pct\n\n # And time-varying frequencies\n freq = np.cumsum(np.abs(np.random.randn(*S.shape)), axis=0)\n yield __test, S, freq, pct\n\n\ndef test_spectral_rolloff_errors():\n\n @pytest.mark.xfail(raises=librosa.ParameterError)\n def __test(S, p):\n librosa.feature.spectral_rolloff(S=S, roll_percent=p)\n\n S = - np.ones((513, 10))\n yield __test, S, 0.95\n\n S = - np.ones((513, 10)) * 1.j\n yield __test, S, 0.95\n\n S = np.ones((513, 10))\n yield __test, S, -1\n\n S = np.ones((513, 10))\n yield __test, S, 2\n\n\ndef test_spectral_contrast_log():\n # We already have a regression test for linear energy difference\n # This test just does a sanity-check on the log-scaled version\n\n y, sr = librosa.load(__EXAMPLE_FILE)\n\n contrast = librosa.feature.spectral_contrast(y=y, sr=sr, linear=False)\n\n assert not np.any(contrast < 0)\n\n\ndef test_spectral_contrast_errors():\n\n @pytest.mark.xfail(raises=librosa.ParameterError)\n def __test(S, freq, fmin, n_bands, quantile):\n librosa.feature.spectral_contrast(S=S,\n freq=freq,\n fmin=fmin,\n n_bands=n_bands,\n quantile=quantile)\n\n S = np.ones((1025, 10))\n\n # ill-shaped frequency set: scalar\n yield __test, S, 0, 200, 6, 0.02\n\n # ill-shaped frequency set: wrong-length vector\n yield __test, S, np.zeros((S.shape[0]+1,)), 200, 6, 0.02\n\n # ill-shaped frequency set: matrix\n yield __test, S, np.zeros(S.shape), 200, 6, 0.02\n\n # negative fmin\n yield __test, S, None, -1, 6, 0.02\n\n # zero fmin\n yield __test, S, None, 0, 6, 0.02\n\n # negative n_bands\n yield __test, S, None, 200, -1, 0.02\n\n # bad quantile\n yield __test, S, None, 200, 6, -1\n\n # bad quantile\n yield __test, S, None, 200, 6, 2\n\n # bands exceed nyquist\n yield __test, S, None, 200, 7, 0.02\n\n\ndef test_spectral_flatness_synthetic():\n\n # to construct a spectrogram\n n_fft = 2048\n def __test(y, S, flatness_ref):\n flatness = librosa.feature.spectral_flatness(y=y,\n S=S,\n n_fft=2048,\n hop_length=512)\n assert np.allclose(flatness, flatness_ref)\n\n # comparison to a manual calculation result\n S = np.array([[1, 3], [2, 1], [1, 2]])\n flatness_ref = np.array([[0.7937005259, 0.7075558390]])\n yield __test, None, S, flatness_ref\n\n # ones\n S = np.ones((1 + n_fft // 2, 10))\n flatness_ones = np.ones((1, 10))\n yield __test, None, S, flatness_ones\n\n # zeros\n S = np.zeros((1 + n_fft // 2, 10))\n flatness_zeros = np.ones((1, 10))\n yield __test, None, S, flatness_zeros\n\n\ndef test_spectral_flatness_errors():\n\n @pytest.mark.xfail(raises=librosa.ParameterError)\n def __test(S, amin):\n librosa.feature.spectral_flatness(S=S,\n amin=amin)\n\n S = np.ones((1025, 10))\n\n # zero amin\n yield __test, S, 0\n\n # negative amin\n yield __test, S, -1\n\n\ndef test_rmse():\n\n def __test(n):\n S = np.ones((n, 5))\n\n # RMSE of an all-ones band is 1\n rmse = librosa.feature.rmse(S=S)\n\n assert np.allclose(rmse, np.ones_like(rmse))\n\n def __test_consistency(frame_length, hop_length, center):\n y, sr = librosa.load(__EXAMPLE_FILE, sr=None)\n\n # Ensure audio is divisible into frame size.\n y = librosa.util.fix_length(y, y.size - y.size % frame_length)\n assert y.size % frame_length == 0\n\n # STFT magnitudes with a constant windowing function and no centering.\n S = librosa.magphase(librosa.stft(y,\n n_fft=frame_length,\n hop_length=hop_length,\n window=np.ones,\n center=center))[0]\n\n # Try both RMS methods.\n rms1 = librosa.feature.rmse(S=S, frame_length=frame_length,\n hop_length=hop_length)\n rms2 = librosa.feature.rmse(y=y, frame_length=frame_length,\n hop_length=hop_length, center=center)\n\n assert rms1.shape == rms2.shape\n # Normalize envelopes.\n rms1 /= rms1.max()\n rms2 /= rms2.max()\n\n # Ensure results are similar.\n np.testing.assert_allclose(rms1, rms2, rtol=5e-2)\n\n for frame_length in [2048, 4096]:\n for hop_length in [128, 512, 1024]:\n for center in [False, True]:\n yield __test_consistency, frame_length, hop_length, center\n\n for n in range(10, 100, 10):\n yield __test, n\n\n\ndef test_zcr_synthetic():\n\n def __test_zcr(rate, y, frame_length, hop_length, center):\n zcr = librosa.feature.zero_crossing_rate(y,\n frame_length=frame_length,\n hop_length=hop_length,\n center=center)\n\n # We don't care too much about the edges if there's padding\n if center:\n zcr = zcr[:, frame_length//2:-frame_length//2]\n\n # We'll allow 1% relative error\n assert np.allclose(zcr, rate, rtol=1e-2)\n\n sr = 16384\n for period in [32, 16, 8, 4, 2]:\n y = np.ones(sr)\n y[::period] = -1\n # Every sign flip induces two crossings\n rate = 2./period\n # 1+2**k so that we get both sides of the last crossing\n for frame_length in [513, 2049]:\n for hop_length in [128, 256]:\n for center in [False, True]:\n yield __test_zcr, rate, y, frame_length, hop_length, center\n\n\ndef test_poly_features_synthetic():\n\n srand()\n sr = 22050\n n_fft = 2048\n\n def __test(S, coeffs, freq):\n\n order = coeffs.shape[0] - 1\n p = librosa.feature.poly_features(S=S, sr=sr, n_fft=n_fft,\n order=order, freq=freq)\n\n for i in range(S.shape[-1]):\n assert np.allclose(coeffs, p[::-1, i].squeeze())\n\n def __make_data(coeffs, freq):\n S = np.zeros_like(freq)\n for i, c in enumerate(coeffs):\n S = S + c * freq**i\n\n S = S.reshape((freq.shape[0], -1))\n return S\n\n for order in range(1, 3):\n freq = librosa.fft_frequencies(sr=sr, n_fft=n_fft)\n coeffs = np.atleast_1d(np.arange(1, 1+order))\n\n # First test: vanilla\n S = __make_data(coeffs, freq)\n yield __test, S, coeffs, None\n\n # And with explicit frequencies\n yield __test, S, coeffs, freq\n\n # And with alternate frequencies\n freq = freq**2.0\n S = __make_data(coeffs, freq)\n yield __test, S, coeffs, freq\n\n # And multi-dimensional\n freq = np.cumsum(np.abs(np.random.randn(1 + n_fft//2, 2)), axis=0)\n S = __make_data(coeffs, freq)\n yield __test, S, coeffs, freq\n\n\ndef test_tonnetz():\n y, sr = librosa.load(librosa.util.example_audio_file())\n tonnetz_chroma = np.load(os.path.join('tests', \"data\", \"feature-tonnetz-chroma.npy\"))\n tonnetz_msaf = np.load(os.path.join('tests', \"data\", \"feature-tonnetz-msaf.npy\"))\n\n # Use cqt chroma\n def __audio():\n tonnetz = librosa.feature.tonnetz(y=y, sr=sr)\n assert tonnetz.shape[0] == 6\n\n # Use pre-computed chroma\n def __stft():\n tonnetz = librosa.feature.tonnetz(chroma=tonnetz_chroma)\n assert tonnetz.shape[1] == tonnetz_chroma.shape[1]\n assert tonnetz.shape[0] == 6\n assert np.allclose(tonnetz_msaf, tonnetz)\n\n def __cqt():\n # Use high resolution cqt chroma\n chroma_cqt = librosa.feature.chroma_cqt(y=y, sr=sr, n_chroma=24)\n tonnetz = librosa.feature.tonnetz(chroma=chroma_cqt)\n assert tonnetz.shape[1] == chroma_cqt.shape[1]\n assert tonnetz.shape[0] == 6\n # Using stft chroma won't generally match cqt chroma\n # skip the equivalence check\n\n # Call the function with not enough parameters\n yield pytest.mark.xfail(librosa.feature.tonnetz, raises=librosa.ParameterError)\n yield __audio\n yield __stft\n yield __cqt\n\n\ndef test_tempogram_fail():\n\n @pytest.mark.xfail(raises=librosa.ParameterError)\n def __test(y, sr, onset_envelope, hop_length, win_length, center, window, norm):\n\n librosa.feature.tempogram(y=y,\n sr=sr,\n onset_envelope=onset_envelope,\n hop_length=hop_length,\n win_length=win_length,\n center=center,\n window=window,\n norm=norm)\n\n sr = 22050\n hop_length = 512\n duration = 10\n\n y = np.zeros(duration * sr)\n\n # Fail when no input is provided\n yield __test, None, sr, None, hop_length, 384, True, 'hann', np.inf\n\n # Fail when win_length is too small\n for win_length in [-384, -1, 0]:\n yield __test, y, sr, None, hop_length, win_length, True, 'hann', np.inf\n\n # Fail when len(window) != win_length\n yield __test, y, sr, None, hop_length, 384, True, np.ones(win_length + 1), np.inf\n\n\ndef test_tempogram_audio():\n\n def __test(y, sr, oenv, hop_length):\n\n # Get the tempogram from audio\n t1 = librosa.feature.tempogram(y=y, sr=sr,\n onset_envelope=None,\n hop_length=hop_length)\n\n # Get the tempogram from oenv\n t2 = librosa.feature.tempogram(y=None, sr=sr,\n onset_envelope=oenv,\n hop_length=hop_length)\n\n # Make sure it works when both are provided\n t3 = librosa.feature.tempogram(y=y, sr=sr,\n onset_envelope=oenv,\n hop_length=hop_length)\n\n # And that oenv overrides y\n t4 = librosa.feature.tempogram(y=0 * y, sr=sr,\n onset_envelope=oenv,\n hop_length=hop_length)\n\n assert np.allclose(t1, t2)\n assert np.allclose(t1, t3)\n assert np.allclose(t1, t4)\n\n y, sr = librosa.load(__EXAMPLE_FILE)\n\n for hop_length in [512, 1024]:\n oenv = librosa.onset.onset_strength(y=y,\n sr=sr,\n hop_length=hop_length)\n\n yield __test, y, sr, oenv, hop_length\n\n\ndef test_tempogram_odf():\n\n sr = 22050\n hop_length = 512\n duration = 8\n\n def __test_equiv(tempo, center):\n odf = np.zeros(duration * sr // hop_length)\n spacing = sr * 60. // (hop_length * tempo)\n odf[::int(spacing)] = 1\n\n odf_ac = librosa.autocorrelate(odf)\n\n tempogram = librosa.feature.tempogram(onset_envelope=odf,\n sr=sr,\n hop_length=hop_length,\n win_length=len(odf),\n window=np.ones,\n center=center,\n norm=None)\n\n idx = 0\n if center:\n idx = len(odf)//2\n\n assert np.allclose(odf_ac, tempogram[:, idx])\n\n # Generate a synthetic onset envelope\n def __test_peaks(tempo, win_length, window, norm):\n # Generate an evenly-spaced pulse train\n odf = np.zeros(duration * sr // hop_length)\n spacing = sr * 60. // (hop_length * tempo)\n odf[::int(spacing)] = 1\n\n tempogram = librosa.feature.tempogram(onset_envelope=odf,\n sr=sr,\n hop_length=hop_length,\n win_length=win_length,\n window=window,\n norm=norm)\n\n # Check the shape of the output\n assert tempogram.shape[0] == win_length\n\n assert tempogram.shape[1] == len(odf)\n\n # Mean over time to wash over the boundary padding effects\n idx = np.where(librosa.util.localmax(tempogram.max(axis=1)))[0]\n\n # Indices should all be non-zero integer multiples of spacing\n assert np.allclose(idx, spacing * np.arange(1, 1 + len(idx)))\n\n for tempo in [60, 90, 120, 160, 200]:\n for center in [False, True]:\n yield __test_equiv, tempo, center\n\n for win_length in [192, 384]:\n for window in ['hann', np.ones, np.ones(win_length)]:\n for norm in [None, 1, 2, np.inf]:\n yield __test_peaks, tempo, win_length, window, norm\n\n\ndef test_tempogram_odf_multi():\n\n sr = 22050\n hop_length = 512\n duration = 8\n\n # Generate a synthetic onset envelope\n def __test(center, win_length, window, norm):\n # Generate an evenly-spaced pulse train\n odf = np.zeros((10, duration * sr // hop_length))\n for i in range(10):\n spacing = sr * 60. // (hop_length * (60 + 12 * i))\n odf[i, ::int(spacing)] = 1\n\n tempogram = librosa.feature.tempogram(onset_envelope=odf,\n sr=sr,\n hop_length=hop_length,\n win_length=win_length,\n window=window,\n norm=norm)\n\n for i in range(10):\n tg_local = librosa.feature.tempogram(onset_envelope=odf[i],\n sr=sr,\n hop_length=hop_length,\n win_length=win_length,\n window=window,\n norm=norm)\n\n assert np.allclose(tempogram[i], tg_local)\n\n for center in [False, True]:\n for win_length in [192, 384]:\n for window in ['hann', np.ones, np.ones(win_length)]:\n for norm in [None, 1, 2, np.inf]:\n yield __test, center, win_length, window, norm\n\n\ndef test_cens():\n # load CQT data from Chroma Toolbox\n ct_cqt = load(os.path.join('tests', 'data', 'features-CT-cqt.mat'))\n\n fn_ct_chroma_cens = ['features-CT-CENS_9-2.mat',\n 'features-CT-CENS_21-5.mat',\n 'features-CT-CENS_41-1.mat']\n\n cens_params = [(9, 2), (21, 5), (41, 1)]\n\n for cur_test_case, cur_fn_ct_chroma_cens in enumerate(fn_ct_chroma_cens):\n win_len_smooth = cens_params[cur_test_case][0]\n downsample_smooth = cens_params[cur_test_case][1]\n\n # plug into librosa cens computation\n lr_chroma_cens = librosa.feature.chroma_cens(C=ct_cqt['f_cqt'],\n win_len_smooth=win_len_smooth,\n fmin=librosa.core.midi_to_hz(1),\n bins_per_octave=12,\n n_octaves=10)\n\n # leaving out frames to match chroma toolbox behaviour\n # lr_chroma_cens = librosa.resample(lr_chroma_cens, orig_sr=1, target_sr=1/downsample_smooth)\n lr_chroma_cens = lr_chroma_cens[:, ::downsample_smooth]\n\n # load CENS-41-1 features\n ct_chroma_cens = load(os.path.join('tests', 'data', cur_fn_ct_chroma_cens))\n\n maxdev = np.abs(ct_chroma_cens['f_CENS'] - lr_chroma_cens)\n assert np.allclose(ct_chroma_cens['f_CENS'], lr_chroma_cens, rtol=1e-15, atol=1e-15), maxdev\n\n\ndef test_mfcc():\n\n def __test(dct_type, norm, n_mfcc, S):\n\n E_total = np.sum(S, axis=0)\n\n mfcc = librosa.feature.mfcc(S=S, dct_type=dct_type, norm=norm, n_mfcc=n_mfcc)\n\n assert mfcc.shape[0] == n_mfcc\n assert mfcc.shape[1] == S.shape[1]\n\n # In type-2 mode, DC component should be constant over all frames\n if dct_type == 2:\n assert np.var(mfcc[0] / E_total) <= 1e-30\n\n S = librosa.power_to_db(np.random.randn(128, 100)**2, ref=np.max)\n\n for n_mfcc in [13, 20]:\n for dct_type in [1, 2, 3]:\n for norm in [None, 'ortho']:\n if dct_type == 1 and norm == 'ortho':\n tf = pytest.mark.xfail(__test, raises=NotImplementedError)\n else:\n tf = __test\n yield tf, dct_type, norm, n_mfcc, S\n", "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"Core IO, DSP and utility functions.\"\"\"\n\nimport os\nimport six\n\nimport audioread\nimport numpy as np\nimport scipy.signal\nimport scipy.fftpack as fft\nimport resampy\n\nfrom .time_frequency import frames_to_samples, time_to_samples\nfrom .. import cache\nfrom .. import util\nfrom ..util.exceptions import ParameterError\n\n__all__ = ['load', 'to_mono', 'resample', 'get_duration',\n 'autocorrelate', 'zero_crossings', 'clicks', 'tone', 'chirp']\n\n# Resampling bandwidths as percentage of Nyquist\nBW_BEST = resampy.filters.get_filter('kaiser_best')[2]\nBW_FASTEST = resampy.filters.get_filter('kaiser_fast')[2]\n\n\n# -- CORE ROUTINES --#\n# Load should never be cached, since we cannot verify that the contents of\n# 'path' are unchanged across calls.\ndef load(path, sr=22050, mono=True, offset=0.0, duration=None,\n dtype=np.float32, res_type='kaiser_best'):\n \"\"\"Load an audio file as a floating point time series.\n\n Audio will be automatically resampled to the given rate\n (default `sr=22050`).\n\n To preserve the native sampling rate of the file, use `sr=None`.\n\n Parameters\n ----------\n path : string\n path to the input file.\n\n Any format supported by `audioread` will work.\n\n sr : number > 0 [scalar]\n target sampling rate\n\n 'None' uses the native sampling rate\n\n mono : bool\n convert signal to mono\n\n offset : float\n start reading after this time (in seconds)\n\n duration : float\n only load up to this much audio (in seconds)\n\n dtype : numeric type\n data type of `y`\n\n res_type : str\n resample type (see note)\n\n .. note::\n By default, this uses `resampy`'s high-quality mode ('kaiser_best').\n\n To use a faster method, set `res_type='kaiser_fast'`.\n\n To use `scipy.signal.resample`, set `res_type='scipy'`.\n\n\n Returns\n -------\n y : np.ndarray [shape=(n,) or (2, n)]\n audio time series\n\n sr : number > 0 [scalar]\n sampling rate of `y`\n\n\n Examples\n --------\n >>> # Load a wav file\n >>> filename = librosa.util.example_audio_file()\n >>> y, sr = librosa.load(filename)\n >>> y\n array([ -4.756e-06, -6.020e-06, ..., -1.040e-06, 0.000e+00], dtype=float32)\n >>> sr\n 22050\n\n >>> # Load a wav file and resample to 11 KHz\n >>> filename = librosa.util.example_audio_file()\n >>> y, sr = librosa.load(filename, sr=11025)\n >>> y\n array([ -2.077e-06, -2.928e-06, ..., -4.395e-06, 0.000e+00], dtype=float32)\n >>> sr\n 11025\n\n >>> # Load 5 seconds of a wav file, starting 15 seconds in\n >>> filename = librosa.util.example_audio_file()\n >>> y, sr = librosa.load(filename, offset=15.0, duration=5.0)\n >>> y\n array([ 0.069, 0.1 , ..., -0.101, 0. ], dtype=float32)\n >>> sr\n 22050\n\n \"\"\"\n\n y = []\n with audioread.audio_open(os.path.realpath(path)) as input_file:\n sr_native = input_file.samplerate\n n_channels = input_file.channels\n\n s_start = int(np.round(sr_native * offset)) * n_channels\n\n if duration is None:\n s_end = np.inf\n else:\n s_end = s_start + (int(np.round(sr_native * duration))\n * n_channels)\n\n n = 0\n\n for frame in input_file:\n frame = util.buf_to_float(frame, dtype=dtype)\n n_prev = n\n n = n + len(frame)\n\n if n < s_start:\n # offset is after the current frame\n # keep reading\n continue\n\n if s_end < n_prev:\n # we're off the end. stop reading\n break\n\n if s_end < n:\n # the end is in this frame. crop.\n frame = frame[:s_end - n_prev]\n\n if n_prev <= s_start <= n:\n # beginning is in this frame\n frame = frame[(s_start - n_prev):]\n\n # tack on the current frame\n y.append(frame)\n\n if y:\n y = np.concatenate(y)\n\n if n_channels > 1:\n y = y.reshape((-1, n_channels)).T\n if mono:\n y = to_mono(y)\n\n if sr is not None:\n y = resample(y, sr_native, sr, res_type=res_type)\n\n else:\n sr = sr_native\n\n # Final cleanup for dtype and contiguity\n y = np.ascontiguousarray(y, dtype=dtype)\n\n return (y, sr)\n\n\n@cache(level=20)\ndef to_mono(y):\n '''Force an audio signal down to mono.\n\n Parameters\n ----------\n y : np.ndarray [shape=(2,n) or shape=(n,)]\n audio time series, either stereo or mono\n\n Returns\n -------\n y_mono : np.ndarray [shape=(n,)]\n `y` as a monophonic time-series\n\n Notes\n -----\n This function caches at level 20.\n\n Examples\n --------\n >>> y, sr = librosa.load(librosa.util.example_audio_file(), mono=False)\n >>> y.shape\n (2, 1355168)\n >>> y_mono = librosa.to_mono(y)\n >>> y_mono.shape\n (1355168,)\n\n '''\n\n # Validate the buffer. Stereo is ok here.\n util.valid_audio(y, mono=False)\n\n if y.ndim > 1:\n y = np.mean(y, axis=0)\n\n return y\n\n\n@cache(level=20)\ndef resample(y, orig_sr, target_sr, res_type='kaiser_best', fix=True, scale=False, **kwargs):\n \"\"\"Resample a time series from orig_sr to target_sr\n\n Parameters\n ----------\n y : np.ndarray [shape=(n,) or shape=(2, n)]\n audio time series. Can be mono or stereo.\n\n orig_sr : number > 0 [scalar]\n original sampling rate of `y`\n\n target_sr : number > 0 [scalar]\n target sampling rate\n\n res_type : str\n resample type (see note)\n\n .. note::\n By default, this uses `resampy`'s high-quality mode ('kaiser_best').\n\n To use a faster method, set `res_type='kaiser_fast'`.\n\n To use `scipy.signal.resample`, set `res_type='scipy'`.\n\n fix : bool\n adjust the length of the resampled signal to be of size exactly\n `ceil(target_sr * len(y) / orig_sr)`\n\n scale : bool\n Scale the resampled signal so that `y` and `y_hat` have approximately\n equal total energy.\n\n kwargs : additional keyword arguments\n If `fix==True`, additional keyword arguments to pass to\n `librosa.util.fix_length`.\n\n Returns\n -------\n y_hat : np.ndarray [shape=(n * target_sr / orig_sr,)]\n `y` resampled from `orig_sr` to `target_sr`\n\n\n See Also\n --------\n librosa.util.fix_length\n scipy.signal.resample\n resampy.resample\n\n Notes\n -----\n This function caches at level 20.\n\n Examples\n --------\n Downsample from 22 KHz to 8 KHz\n\n >>> y, sr = librosa.load(librosa.util.example_audio_file(), sr=22050)\n >>> y_8k = librosa.resample(y, sr, 8000)\n >>> y.shape, y_8k.shape\n ((1355168,), (491671,))\n\n \"\"\"\n\n # First, validate the audio buffer\n util.valid_audio(y, mono=False)\n\n if orig_sr == target_sr:\n return y\n\n ratio = float(target_sr) / orig_sr\n\n n_samples = int(np.ceil(y.shape[-1] * ratio))\n\n if res_type == 'scipy':\n y_hat = scipy.signal.resample(y, n_samples, axis=-1)\n else:\n y_hat = resampy.resample(y, orig_sr, target_sr, filter=res_type, axis=-1)\n\n if fix:\n y_hat = util.fix_length(y_hat, n_samples, **kwargs)\n\n if scale:\n y_hat /= np.sqrt(ratio)\n\n return np.ascontiguousarray(y_hat, dtype=y.dtype)\n\n\ndef get_duration(y=None, sr=22050, S=None, n_fft=2048, hop_length=512,\n center=True, filename=None):\n \"\"\"Compute the duration (in seconds) of an audio time series,\n feature matrix, or filename.\n\n Examples\n --------\n >>> # Load the example audio file\n >>> y, sr = librosa.load(librosa.util.example_audio_file())\n >>> librosa.get_duration(y=y, sr=sr)\n 61.45886621315193\n\n >>> # Or directly from an audio file\n >>> librosa.get_duration(filename=librosa.util.example_audio_file())\n 61.4\n\n >>> # Or compute duration from an STFT matrix\n >>> y, sr = librosa.load(librosa.util.example_audio_file())\n >>> S = librosa.stft(y)\n >>> librosa.get_duration(S=S, sr=sr)\n 61.44\n\n >>> # Or a non-centered STFT matrix\n >>> S_left = librosa.stft(y, center=False)\n >>> librosa.get_duration(S=S_left, sr=sr)\n 61.3471201814059\n\n Parameters\n ----------\n y : np.ndarray [shape=(n,), (2, n)] or None\n audio time series\n\n sr : number > 0 [scalar]\n audio sampling rate of `y`\n\n S : np.ndarray [shape=(d, t)] or None\n STFT matrix, or any STFT-derived matrix (e.g., chromagram\n or mel spectrogram).\n Durations calculated from spectrogram inputs are only accurate\n up to the frame resolution. If high precision is required,\n it is better to use the audio time series directly.\n\n n_fft : int > 0 [scalar]\n FFT window size for `S`\n\n hop_length : int > 0 [ scalar]\n number of audio samples between columns of `S`\n\n center : boolean\n - If `True`, `S[:, t]` is centered at `y[t * hop_length]`\n - If `False`, then `S[:, t]` begins at `y[t * hop_length]`\n\n filename : str\n If provided, all other parameters are ignored, and the\n duration is calculated directly from the audio file.\n Note that this avoids loading the contents into memory,\n and is therefore useful for querying the duration of\n long files.\n\n Returns\n -------\n d : float >= 0\n Duration (in seconds) of the input time series or spectrogram.\n\n Raises\n ------\n ParameterError\n if none of `y`, `S`, or `filename` are provided.\n\n Notes\n -----\n `get_duration` can be applied to a file (`filename`), a spectrogram (`S`),\n or audio buffer (`y, sr`). Only one of these three options should be\n provided. If you do provide multiple options (e.g., `filename` and `S`),\n then `filename` takes precedence over `S`, and `S` takes precedence over\n `(y, sr)`.\n \"\"\"\n\n if filename is not None:\n with audioread.audio_open(filename) as fdesc:\n return fdesc.duration\n\n if y is None:\n if S is None:\n raise ParameterError('At least one of (y, sr), S, or filename must be provided')\n\n n_frames = S.shape[1]\n n_samples = n_fft + hop_length * (n_frames - 1)\n\n # If centered, we lose half a window from each end of S\n if center:\n n_samples = n_samples - 2 * int(n_fft / 2)\n\n else:\n # Validate the audio buffer. Stereo is okay here.\n util.valid_audio(y, mono=False)\n if y.ndim == 1:\n n_samples = len(y)\n else:\n n_samples = y.shape[-1]\n\n return float(n_samples) / sr\n\n\n@cache(level=20)\ndef autocorrelate(y, max_size=None, axis=-1):\n \"\"\"Bounded auto-correlation\n\n Parameters\n ----------\n y : np.ndarray\n array to autocorrelate\n\n max_size : int > 0 or None\n maximum correlation lag.\n If unspecified, defaults to `y.shape[axis]` (unbounded)\n\n axis : int\n The axis along which to autocorrelate.\n By default, the last axis (-1) is taken.\n\n Returns\n -------\n z : np.ndarray\n truncated autocorrelation `y*y` along the specified axis.\n If `max_size` is specified, then `z.shape[axis]` is bounded\n to `max_size`.\n\n Notes\n -----\n This function caches at level 20.\n\n Examples\n --------\n Compute full autocorrelation of y\n\n >>> y, sr = librosa.load(librosa.util.example_audio_file(), offset=20, duration=10)\n >>> librosa.autocorrelate(y)\n array([ 3.226e+03, 3.217e+03, ..., 8.277e-04, 3.575e-04], dtype=float32)\n\n Compute onset strength auto-correlation up to 4 seconds\n\n >>> import matplotlib.pyplot as plt\n >>> odf = librosa.onset.onset_strength(y=y, sr=sr, hop_length=512)\n >>> ac = librosa.autocorrelate(odf, max_size=4* sr / 512)\n >>> plt.plot(ac)\n >>> plt.title('Auto-correlation')\n >>> plt.xlabel('Lag (frames)')\n\n \"\"\"\n\n if max_size is None:\n max_size = y.shape[axis]\n\n max_size = int(min(max_size, y.shape[axis]))\n\n # Compute the power spectrum along the chosen axis\n # Pad out the signal to support full-length auto-correlation.\n powspec = np.abs(fft.fft(y, n=2 * y.shape[axis] + 1, axis=axis))**2\n\n # Convert back to time domain\n autocorr = fft.ifft(powspec, axis=axis, overwrite_x=True)\n\n # Slice down to max_size\n subslice = [slice(None)] * autocorr.ndim\n subslice[axis] = slice(max_size)\n\n autocorr = autocorr[tuple(subslice)]\n\n if not np.iscomplexobj(y):\n autocorr = autocorr.real\n\n return autocorr\n\n\n@cache(level=20)\ndef zero_crossings(y, threshold=1e-10, ref_magnitude=None, pad=True,\n zero_pos=True, axis=-1):\n '''Find the zero-crossings of a signal `y`: indices `i` such that\n `sign(y[i]) != sign(y[j])`.\n\n If `y` is multi-dimensional, then zero-crossings are computed along\n the specified `axis`.\n\n\n Parameters\n ----------\n y : np.ndarray\n The input array\n\n threshold : float > 0 or None\n If specified, values where `-threshold <= y <= threshold` are\n clipped to 0.\n\n ref_magnitude : float > 0 or callable\n If numeric, the threshold is scaled relative to `ref_magnitude`.\n\n If callable, the threshold is scaled relative to\n `ref_magnitude(np.abs(y))`.\n\n pad : boolean\n If `True`, then `y[0]` is considered a valid zero-crossing.\n\n zero_pos : boolean\n If `True` then the value 0 is interpreted as having positive sign.\n\n If `False`, then 0, -1, and +1 all have distinct signs.\n\n axis : int\n Axis along which to compute zero-crossings.\n\n Returns\n -------\n zero_crossings : np.ndarray [shape=y.shape, dtype=boolean]\n Indicator array of zero-crossings in `y` along the selected axis.\n\n Notes\n -----\n This function caches at level 20.\n\n Examples\n --------\n >>> # Generate a time-series\n >>> y = np.sin(np.linspace(0, 4 * 2 * np.pi, 20))\n >>> y\n array([ 0.000e+00, 9.694e-01, 4.759e-01, -7.357e-01,\n -8.372e-01, 3.247e-01, 9.966e-01, 1.646e-01,\n -9.158e-01, -6.142e-01, 6.142e-01, 9.158e-01,\n -1.646e-01, -9.966e-01, -3.247e-01, 8.372e-01,\n 7.357e-01, -4.759e-01, -9.694e-01, -9.797e-16])\n >>> # Compute zero-crossings\n >>> z = librosa.zero_crossings(y)\n >>> z\n array([ True, False, False, True, False, True, False, False,\n True, False, True, False, True, False, False, True,\n False, True, False, True], dtype=bool)\n >>> # Stack y against the zero-crossing indicator\n >>> np.vstack([y, z]).T\n array([[ 0.000e+00, 1.000e+00],\n [ 9.694e-01, 0.000e+00],\n [ 4.759e-01, 0.000e+00],\n [ -7.357e-01, 1.000e+00],\n [ -8.372e-01, 0.000e+00],\n [ 3.247e-01, 1.000e+00],\n [ 9.966e-01, 0.000e+00],\n [ 1.646e-01, 0.000e+00],\n [ -9.158e-01, 1.000e+00],\n [ -6.142e-01, 0.000e+00],\n [ 6.142e-01, 1.000e+00],\n [ 9.158e-01, 0.000e+00],\n [ -1.646e-01, 1.000e+00],\n [ -9.966e-01, 0.000e+00],\n [ -3.247e-01, 0.000e+00],\n [ 8.372e-01, 1.000e+00],\n [ 7.357e-01, 0.000e+00],\n [ -4.759e-01, 1.000e+00],\n [ -9.694e-01, 0.000e+00],\n [ -9.797e-16, 1.000e+00]])\n >>> # Find the indices of zero-crossings\n >>> np.nonzero(z)\n (array([ 0, 3, 5, 8, 10, 12, 15, 17, 19]),)\n '''\n\n # Clip within the threshold\n if threshold is None:\n threshold = 0.0\n\n if six.callable(ref_magnitude):\n threshold = threshold * ref_magnitude(np.abs(y))\n\n elif ref_magnitude is not None:\n threshold = threshold * ref_magnitude\n\n if threshold > 0:\n y = y.copy()\n y[np.abs(y) <= threshold] = 0\n\n # Extract the sign bit\n if zero_pos:\n y_sign = np.signbit(y)\n else:\n y_sign = np.sign(y)\n\n # Find the change-points by slicing\n slice_pre = [slice(None)] * y.ndim\n slice_pre[axis] = slice(1, None)\n\n slice_post = [slice(None)] * y.ndim\n slice_post[axis] = slice(-1)\n\n # Since we've offset the input by one, pad back onto the front\n padding = [(0, 0)] * y.ndim\n padding[axis] = (1, 0)\n\n return np.pad((y_sign[tuple(slice_post)] != y_sign[tuple(slice_pre)]),\n padding,\n mode='constant',\n constant_values=pad)\n\n\ndef clicks(times=None, frames=None, sr=22050, hop_length=512,\n click_freq=1000.0, click_duration=0.1, click=None, length=None):\n \"\"\"Returns a signal with the signal `click` placed at each specified time\n\n Parameters\n ----------\n times : np.ndarray or None\n times to place clicks, in seconds\n\n frames : np.ndarray or None\n frame indices to place clicks\n\n sr : number > 0\n desired sampling rate of the output signal\n\n hop_length : int > 0\n if positions are specified by `frames`, the number of samples between frames.\n\n click_freq : float > 0\n frequency (in Hz) of the default click signal. Default is 1KHz.\n\n click_duration : float > 0\n duration (in seconds) of the default click signal. Default is 100ms.\n\n click : np.ndarray or None\n optional click signal sample to use instead of the default blip.\n\n length : int > 0\n desired number of samples in the output signal\n\n\n Returns\n -------\n click_signal : np.ndarray\n Synthesized click signal\n\n\n Raises\n ------\n ParameterError\n - If neither `times` nor `frames` are provided.\n - If any of `click_freq`, `click_duration`, or `length` are out of range.\n\n\n Examples\n --------\n >>> # Sonify detected beat events\n >>> y, sr = librosa.load(librosa.util.example_audio_file())\n >>> tempo, beats = librosa.beat.beat_track(y=y, sr=sr)\n >>> y_beats = librosa.clicks(frames=beats, sr=sr)\n\n >>> # Or generate a signal of the same length as y\n >>> y_beats = librosa.clicks(frames=beats, sr=sr, length=len(y))\n\n >>> # Or use timing instead of frame indices\n >>> times = librosa.frames_to_time(beats, sr=sr)\n >>> y_beat_times = librosa.clicks(times=times, sr=sr)\n\n >>> # Or with a click frequency of 880Hz and a 500ms sample\n >>> y_beat_times880 = librosa.clicks(times=times, sr=sr,\n ... click_freq=880, click_duration=0.5)\n\n Display click waveform next to the spectrogram\n\n >>> import matplotlib.pyplot as plt\n >>> plt.figure()\n >>> S = librosa.feature.melspectrogram(y=y, sr=sr)\n >>> ax = plt.subplot(2,1,2)\n >>> librosa.display.specshow(librosa.power_to_db(S, ref=np.max),\n ... x_axis='time', y_axis='mel')\n >>> plt.subplot(2,1,1, sharex=ax)\n >>> librosa.display.waveplot(y_beat_times, sr=sr, label='Beat clicks')\n >>> plt.legend()\n >>> plt.xlim(15, 30)\n >>> plt.tight_layout()\n \"\"\"\n\n # Compute sample positions from time or frames\n if times is None:\n if frames is None:\n raise ParameterError('either \"times\" or \"frames\" must be provided')\n\n positions = frames_to_samples(frames, hop_length=hop_length)\n else:\n # Convert times to positions\n positions = time_to_samples(times, sr=sr)\n\n if click is not None:\n # Check that we have a well-formed audio buffer\n util.valid_audio(click, mono=True)\n\n else:\n # Create default click signal\n if click_duration <= 0:\n raise ParameterError('click_duration must be strictly positive')\n\n if click_freq <= 0:\n raise ParameterError('click_freq must be strictly positive')\n\n angular_freq = 2 * np.pi * click_freq / float(sr)\n\n click = np.logspace(0, -10,\n num=int(np.round(sr * click_duration)),\n base=2.0)\n\n click *= np.sin(angular_freq * np.arange(len(click)))\n\n # Set default length\n if length is None:\n length = positions.max() + click.shape[0]\n else:\n if length < 1:\n raise ParameterError('length must be a positive integer')\n\n # Filter out any positions past the length boundary\n positions = positions[positions < length]\n\n # Pre-allocate click signal\n click_signal = np.zeros(length, dtype=np.float32)\n\n # Place clicks\n for start in positions:\n # Compute the end-point of this click\n end = start + click.shape[0]\n\n if end >= length:\n click_signal[start:] += click[:length - start]\n else:\n # Normally, just add a click here\n click_signal[start:end] += click\n\n return click_signal\n\n\ndef tone(frequency, sr=22050, length=None, duration=None, phi=None):\n \"\"\"Returns a pure tone signal. The signal generated is a cosine wave.\n\n Parameters\n ----------\n frequency : float > 0\n frequency\n\n sr : number > 0\n desired sampling rate of the output signal\n\n length : int > 0\n desired number of samples in the output signal. When both `duration` and `length` are defined, `length` would take priority.\n\n duration : float > 0\n desired duration in seconds. When both `duration` and `length` are defined, `length` would take priority.\n\n phi : float or None\n phase offset, in radians. If unspecified, defaults to `-np.pi * 0.5`.\n\n\n Returns\n -------\n tone_signal : np.ndarray [shape=(length,), dtype=float64]\n Synthesized pure sine tone signal\n\n\n Raises\n ------\n ParameterError\n - If `frequency` is not provided.\n - If neither `length` nor `duration` are provided.\n\n\n Examples\n --------\n >>> # Generate a pure sine tone A4\n >>> tone = librosa.tone(440, duration=1)\n\n >>> # Or generate the same signal using `length`\n >>> tone = librosa.tone(440, sr=22050, length=22050)\n\n Display spectrogram\n\n >>> import matplotlib.pyplot as plt\n >>> plt.figure()\n >>> S = librosa.feature.melspectrogram(y=tone)\n >>> librosa.display.specshow(librosa.power_to_db(S, ref=np.max),\n ... x_axis='time', y_axis='mel')\n \"\"\"\n\n if frequency is None:\n raise ParameterError('\"frequency\" must be provided')\n\n # Compute signal length\n if length is None:\n if duration is None:\n raise ParameterError('either \"length\" or \"duration\" must be provided')\n length = duration * sr\n\n if phi is None:\n phi = -np.pi * 0.5\n\n step = 1.0 / sr\n return np.cos(2 * np.pi * frequency * (np.arange(step * length, step=step)) + phi)\n\n\ndef chirp(fmin, fmax, sr=22050, length=None, duration=None, linear=False, phi=None):\n \"\"\"Returns a chirp signal that goes from frequency `fmin` to frequency `fmax`\n\n Parameters\n ----------\n fmin : float > 0\n initial frequency\n\n fmax : float > 0\n final frequency\n\n sr : number > 0\n desired sampling rate of the output signal\n\n length : int > 0\n desired number of samples in the output signal.\n When both `duration` and `length` are defined, `length` would take priority.\n\n duration : float > 0\n desired duration in seconds.\n When both `duration` and `length` are defined, `length` would take priority.\n\n linear : boolean\n - If `True`, use a linear sweep, i.e., frequency changes linearly with time\n - If `False`, use a exponential sweep.\n Default is `False`.\n\n phi : float or None\n phase offset, in radians.\n If unspecified, defaults to `-np.pi * 0.5`.\n\n\n Returns\n -------\n chirp_signal : np.ndarray [shape=(length,), dtype=float64]\n Synthesized chirp signal\n\n\n Raises\n ------\n ParameterError\n - If either `fmin` or `fmax` are not provided.\n - If neither `length` nor `duration` are provided.\n\n\n See Also\n --------\n scipy.signal.chirp\n\n\n Examples\n --------\n >>> # Generate a exponential chirp from A4 to A5\n >>> exponential_chirp = librosa.chirp(440, 880, duration=1)\n\n >>> # Or generate the same signal using `length`\n >>> exponential_chirp = librosa.chirp(440, 880, sr=22050, length=22050)\n\n >>> # Or generate a linear chirp instead\n >>> linear_chirp = librosa.chirp(440, 880, duration=1, linear=True)\n\n Display spectrogram for both exponential and linear chirps\n\n >>> import matplotlib.pyplot as plt\n >>> plt.figure()\n >>> S_exponential = librosa.feature.melspectrogram(y=exponential_chirp)\n >>> ax = plt.subplot(2,1,1)\n >>> librosa.display.specshow(librosa.power_to_db(S_exponential, ref=np.max),\n ... x_axis='time', y_axis='mel')\n >>> plt.subplot(2,1,2, sharex=ax)\n >>> S_linear = librosa.feature.melspectrogram(y=linear_chirp)\n >>> librosa.display.specshow(librosa.power_to_db(S_linear, ref=np.max),\n ... x_axis='time', y_axis='mel')\n >>> plt.tight_layout()\n \"\"\"\n\n if fmin is None or fmax is None:\n raise ParameterError('both \"fmin\" and \"fmax\" must be provided')\n\n # Compute signal duration\n period = 1.0 / sr\n if length is None:\n if duration is None:\n raise ParameterError('either \"length\" or \"duration\" must be provided')\n else:\n duration = period * length\n\n if phi is None:\n phi = -np.pi * 0.5\n\n method = 'linear' if linear else 'logarithmic'\n return scipy.signal.chirp(\n np.arange(duration, step=period),\n fmin,\n duration,\n fmax,\n method=method,\n phi=phi / np.pi * 180, # scipy.signal.chirp uses degrees for phase offset\n )\n" ]
[ [ "numpy.ones_like", "numpy.allclose", "numpy.linspace", "numpy.abs", "numpy.arange", "numpy.var", "numpy.ones", "numpy.random.randn", "numpy.any", "numpy.zeros_like", "numpy.testing.assert_allclose", "numpy.floor", "numpy.array", "numpy.zeros", "numpy.sum" ], [ "numpy.signbit", "scipy.fftpack.ifft", "numpy.sqrt", "numpy.abs", "numpy.ascontiguousarray", "numpy.arange", "numpy.concatenate", "numpy.ceil", "numpy.sign", "scipy.fftpack.fft", "numpy.mean", "numpy.round", "numpy.iscomplexobj", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "1.7", "1.0", "0.10", "1.2", "0.14", "0.19", "1.5", "0.12", "0.17", "0.13", "1.6", "1.4", "1.9", "1.3", "1.10", "0.15", "0.18", "0.16", "1.8" ], "tensorflow": [] } ]
oliviermailletglas/project_csi4103
[ "b426f4fb8d909909dd7d1d954fd10d97891c33cb" ]
[ "brachiograph.py" ]
[ "# coding=utf-8\n\nfrom time import sleep\nimport readchar\nimport math\nimport numpy\nimport json\nimport pigpio\nfrom turtle_draw import BrachioGraphTurtle\n\n\ntry:\n pigpio.exceptions = False\n rpi = pigpio.pi()\n rpi.set_PWM_frequency(18, 50)\n pigpio.exceptions = True\n force_virtual = False\n\nexcept:\n print(\"pigpio daemon is not available; running in virtual mode\")\n force_virtual = True\n\n\nimport tqdm\n\n\nclass BrachioGraph:\n\n def __init__(\n self,\n\n # ----------------- geometry of the plotter -----------------\n\n inner_arm=8, # the lengths of the arms\n outer_arm=8,\n\n bounds=[-8, 4, 6, 13], # the maximum rectangular drawing area\n\n # ----------------- naive calculation values -----------------\n\n servo_1_parked_pw=1500, # pulse-widths when parked\n servo_2_parked_pw=1500,\n\n servo_1_degree_ms=-10, # milliseconds pulse-width per degree\n servo_2_degree_ms=10, # reversed for the mounting of the shoulder servo\n\n servo_1_parked_angle=-90, # the arm angle in the parked position\n servo_2_parked_angle=90,\n\n # ----------------- hysteresis -----------------\n\n hysteresis_correction_1=0, # hardware error compensation\n hysteresis_correction_2=0,\n\n # ----------------- servo angles and pulse-widths in lists -----------------\n\n servo_1_angle_pws=[], # pulse-widths for various angles\n servo_2_angle_pws=[],\n\n # ----------------- servo angles and pulse-widths in lists (bi-directional) ------\n\n servo_1_angle_pws_bidi = [], # bi-directional pulse-widths for various angles\n servo_2_angle_pws_bidi = [],\n\n # ----------------- the pen -----------------\n\n pw_up=1500, # pulse-widths for pen up/down\n pw_down=1100,\n\n # ----------------- misc -----------------\n\n wait=None, # default wait time between operations\n\n virtual = False, # run in virtual mode\n turtle = False\n ):\n\n # set the geometry\n self.inner_arm = inner_arm\n self.outer_arm = outer_arm\n\n self.virtual = virtual or force_virtual\n\n self.turtle = turtle\n if self.turtle:\n self.reset_turtle()\n\n # the box bounds describe a rectangle that we can safely draw in\n self.bounds = bounds\n\n # if pulse-widths to angles are supplied for each servo, we will feed them to\n # numpy.polyfit(), to produce a function for each one. Otherwise, we will use a simple\n # approximation based on a centre of travel of 1500µS and 10µS per degree\n\n self.servo_1_parked_pw = servo_1_parked_pw\n self.servo_1_degree_ms = servo_1_degree_ms\n self.servo_1_parked_angle = servo_1_parked_angle\n self.hysteresis_correction_1 = hysteresis_correction_1\n\n self.servo_2_parked_pw = servo_2_parked_pw\n self.servo_2_degree_ms = servo_2_degree_ms\n self.servo_2_parked_angle = servo_2_parked_angle\n self.hysteresis_correction_2 = hysteresis_correction_2\n\n # set some initial values required for moving methods\n self.previous_pw_1 = self.previous_pw_2 = 0\n self.active_hysteresis_correction_1 = self.active_hysteresis_correction_2 = 0\n self.reset_report()\n\n # Set the x and y position state, so it knows its current x/y position.\n self.x = -self.inner_arm\n self.y = self.outer_arm\n\n if servo_1_angle_pws_bidi:\n servo_1_angle_pws = []\n differences = []\n for angle, pws in servo_1_angle_pws_bidi.items():\n pw = (pws['acw'] + pws['cw']) / 2\n servo_1_angle_pws.append([angle, pw])\n differences.append((pws['acw'] - pws['cw']) / 2)\n self.hysteresis_correction_1 = numpy.mean(differences)\n\n if servo_1_angle_pws:\n servo_1_array = numpy.array(servo_1_angle_pws)\n self.angles_to_pw_1 = numpy.poly1d(\n numpy.polyfit(\n servo_1_array[:,0],\n servo_1_array[:,1],\n 3\n )\n )\n\n else:\n self.angles_to_pw_1 = self.naive_angles_to_pulse_widths_1\n\n if servo_2_angle_pws_bidi:\n servo_2_angle_pws = []\n differences = []\n for angle, pws in servo_2_angle_pws_bidi.items():\n pw = (pws['acw'] + pws['cw']) / 2\n servo_2_angle_pws.append([angle, pw])\n differences.append((pws['acw'] - pws['cw']) / 2)\n self.hysteresis_correction_2 = numpy.mean(differences)\n print(servo_2_angle_pws)\n\n if servo_2_angle_pws:\n servo_2_array = numpy.array(servo_2_angle_pws)\n self.angles_to_pw_2 = numpy.poly1d(\n numpy.polyfit(\n servo_2_array[:,0],\n servo_2_array[:,1],\n 3\n )\n )\n\n else:\n self.angles_to_pw_2 = self.naive_angles_to_pulse_widths_2\n\n\n # create the pen object\n self.pen = Pen(bg=self, pw_up=pw_up, pw_down=pw_down, virtual=self.virtual)\n\n if self.virtual:\n\n print(\"Initialising virtual BrachioGraph\")\n\n self.virtual_pw_1 = self.angles_to_pw_1(-90)\n self.virtual_pw_2 = self.angles_to_pw_2(90)\n\n # by default in virtual mode, we use a wait factor of 0 for speed\n self.wait = wait or 0\n\n else:\n\n # instantiate this Raspberry Pi as a pigpio.pi() instance\n self.rpi = pigpio.pi()\n\n # the pulse frequency should be no higher than 100Hz - higher values could (supposedly) damage the servos\n self.rpi.set_PWM_frequency(14, 50)\n self.rpi.set_PWM_frequency(15, 50)\n\n # by default we use a wait factor of 0.1 for accuracy\n self.wait = wait or .1\n\n self.set_angles(-90, 90)\n\n if self.turtle:\n self.turtle.showturtle()\n\n self.status()\n\n # methods in this class:\n # drawing\n # line-processing\n # test patterns\n # pen-moving\n # angles-to-pulse-widths\n # hardware-related\n # trigonometric\n # calibration\n # manual driving\n # reporting\n\n # ----------------- drawing methods -----------------\n\n def plot_file(self, filename=\"\", wait=0, interpolate=10, bounds=None):\n \"\"\"Passes the lines in the supplied JSON file to ``plot_lines()``\"\"\"\n\n wait = wait or self.wait\n bounds = bounds or self.bounds\n\n if not bounds:\n return \"File plotting is only possible when BrachioGraph.bounds is set.\"\n\n with open(filename, \"r\") as line_file:\n lines = json.load(line_file)\n\n self.plot_lines(lines=lines, wait=wait, interpolate=interpolate, bounds=bounds, flip=True)\n\n\n def plot_lines(self, lines=[], wait=0, interpolate=10, rotate=False, flip=False, bounds=None):\n \"\"\"Passes each segment of each line in lines to ``draw_line()``\"\"\"\n\n wait = wait or self.wait\n bounds = bounds or self.bounds\n\n if not bounds:\n return \"Line plotting is only possible when BrachioGraph.bounds is set.\"\n\n lines = self.rotate_and_scale_lines(lines=lines, bounds=bounds, flip=True)\n\n for line in tqdm.tqdm(lines, desc=\"Lines\", leave=False):\n x, y = line[0]\n\n # only if we are not within 1mm of the start of the line, lift pen and go there\n if (round(self.x, 1), round(self.y, 1)) != (round(x, 1), round(y, 1)):\n self.xy(x, y, wait=wait, interpolate=interpolate)\n\n for point in tqdm.tqdm(line[1:], desc=\"Segments\", leave=False):\n x, y = point\n self.xy(x, y, wait=wait, interpolate=interpolate, draw=True)\n\n self.park()\n\n\n def draw_line(self, start=(0, 0), end=(0, 0), wait=0, interpolate=10, both=False):\n \"\"\"Draws a straight line between two points\"\"\"\n\n wait = wait or self.wait\n\n start_x, start_y = start\n end_x, end_y = end\n\n self.xy(x=start_x, y=start_y, wait=wait, interpolate=interpolate)\n\n self.xy(x=end_x, y=end_y, wait=wait, interpolate=interpolate, draw=True)\n\n if both:\n self.xy(x=start_x, y=start_y, wait=wait, interpolate=interpolate, draw=True)\n\n\n # ----------------- line-processing methods -----------------\n\n def rotate_and_scale_lines(self, lines=[], rotate=False, flip=False, bounds=None):\n\n rotate, x_mid_point, y_mid_point, box_x_mid_point, box_y_mid_point, divider = self.analyse_lines(\n lines=lines, rotate=rotate, bounds=bounds\n )\n\n for line in lines:\n\n for point in line:\n if rotate:\n point[0], point[1] = point[1], point[0]\n\n x = point[0]\n x = x - x_mid_point # shift x values so that they have zero as their mid-point\n x = x / divider # scale x values to fit in our box width\n\n\n if flip ^ rotate: # flip before moving back into drwaing pane\n x = -x\n\n x = x + box_x_mid_point # shift x values so that they have the box x midpoint as their endpoint\n\n\n y = point[1]\n y = y - y_mid_point\n y = y / divider\n y = y + box_y_mid_point\n\n point[0], point[1] = x, y\n\n return lines\n\n\n def analyse_lines(self, lines=[], rotate=False, bounds=None):\n\n # lines is a tuple itself containing a number of tuples, each of which contains a number of 2-tuples\n #\n # [ # |\n # [ # |\n # [3, 4], # | # |\n # [2, 4], # | # |\n # [1, 5], # a single point in a line # | a list of points defining a line # |\n # [3, 5], # | # |\n # [3, 7], # | # |\n # ], # |\n # [ # | all the lines\n # [...], # |\n # [...], # |\n # ], # |\n # [ # |\n # [...], # |\n # [...], # |\n # ], # |\n # ] # |\n\n # First, we create a pair of empty sets for all the x and y values in all of the lines of the plot data.\n\n x_values_in_lines = set()\n y_values_in_lines = set()\n\n # Loop over each line and all the points in each line, to get sets of all the x and y values:\n\n for line in lines:\n\n x_values_in_line, y_values_in_line = zip(*line)\n\n x_values_in_lines.update(x_values_in_line)\n y_values_in_lines.update(y_values_in_line)\n\n # Identify the minimum and maximum values.\n\n min_x, max_x = min(x_values_in_lines), max(x_values_in_lines)\n min_y, max_y = min(y_values_in_lines), max(y_values_in_lines)\n\n # Identify the range they span.\n\n x_range, y_range = max_x - min_x, max_y - min_y\n box_x_range, box_y_range = bounds[2] - bounds[0], bounds[3] - bounds[1]\n\n # And their mid-points.\n\n x_mid_point, y_mid_point = (max_x + min_x) / 2, (max_y + min_y) / 2\n box_x_mid_point, box_y_mid_point = (bounds[0] + bounds[2]) / 2, (bounds[1] + bounds[3]) / 2\n\n # Get a 'divider' value for each range - the value by which we must divide all x and y so that they will\n # fit safely inside the drawing range of the plotter.\n\n # If both image and box are in portrait orientation, or both in landscape, we don't need to rotate the plot.\n\n if (x_range >= y_range and box_x_range >= box_y_range) or (x_range <= y_range and box_x_range <= box_y_range):\n\n divider = max((x_range / box_x_range), (y_range / box_y_range))\n rotate = False\n\n else:\n\n divider = max((x_range / box_y_range), (y_range / box_x_range))\n rotate = True\n x_mid_point, y_mid_point = y_mid_point, x_mid_point\n\n return rotate, x_mid_point, y_mid_point, box_x_mid_point, box_y_mid_point, divider\n\n\n # ----------------- test pattern methods -----------------\n\n def test_pattern(self, bounds=None, lines=4, wait=0, interpolate=10, repeat=1, reverse=False, both=False):\n\n self.vertical_lines(\n bounds=bounds, lines=lines, wait=wait, interpolate=interpolate, repeat=repeat, reverse=reverse, both=both\n )\n self.horizontal_lines(\n bounds=bounds, lines=lines, wait=wait, interpolate=interpolate, repeat=repeat, reverse=reverse, both=both\n )\n\n\n def vertical_lines(self, bounds=None, lines=4, wait=0, interpolate=10, repeat=1, reverse=False, both=False):\n\n wait = wait or self.wait\n bounds = bounds or self.bounds\n\n if not bounds:\n return \"Plotting a test pattern is only possible when BrachioGraph.bounds is set.\"\n\n if not reverse:\n top_y = self.bounds[1]\n bottom_y = self.bounds[3]\n else:\n bottom_y = self.bounds[1]\n top_y = self.bounds[3]\n\n for n in range(repeat):\n step = (self.bounds[2] - self.bounds[0]) / lines\n x = self.bounds[0]\n while x <= self.bounds[2]:\n self.draw_line((x, top_y), (x, bottom_y), interpolate=interpolate, both=both)\n x = x + step\n\n self.park()\n\n\n def horizontal_lines(self, bounds=None, lines=4, wait=0, interpolate=10, repeat=1, reverse=False, both=False):\n\n wait = wait or self.wait\n bounds = bounds or self.bounds\n\n if not bounds:\n return \"Plotting a test pattern is only possible when BrachioGraph.bounds is set.\"\n\n if not reverse:\n min_x = self.bounds[0]\n max_x = self.bounds[2]\n else:\n max_x = self.bounds[0]\n min_x = self.bounds[2]\n\n for n in range(repeat):\n step = (self.bounds[3] - self.bounds[1]) / lines\n y = self.bounds[1]\n while y <= self.bounds[3]:\n self.draw_line((min_x, y), (max_x, y), interpolate=interpolate, both=both)\n y = y + step\n\n self.park()\n\n\n def box(self, bounds=None, wait=0, interpolate=10, repeat=1, reverse=False):\n \"\"\"Draw a box marked out by the ``bounds``.\"\"\"\n\n wait = wait or self.wait\n bounds = bounds or self.bounds\n\n if not bounds:\n return \"Box drawing is only possible when BrachioGraph.bounds is set.\"\n\n self.xy(bounds[0], bounds[1], wait, interpolate)\n\n for r in tqdm.tqdm(tqdm.trange(repeat), desc='Iteration', leave=False):\n\n if not reverse:\n\n self.xy(bounds[2], bounds[1], wait, interpolate, draw=True)\n self.xy(bounds[2], bounds[3], wait, interpolate, draw=True)\n self.xy(bounds[0], bounds[3], wait, interpolate, draw=True)\n self.xy(bounds[0], bounds[1], wait, interpolate, draw=True)\n\n else:\n\n self.xy(bounds[0], bounds[3], wait, interpolate, draw=True)\n self.xy(bounds[2], bounds[3], wait, interpolate, draw=True)\n self.xy(bounds[2], bounds[1], wait, interpolate, draw=True)\n self.xy(bounds[0], bounds[1], wait, interpolate, draw=True)\n\n self.park()\n\n\n def test_arcs(self):\n self.park()\n elbow_angle = 120\n self.move_angles(angle_2=elbow_angle)\n\n for angle_1 in range(-135, 15, 15):\n self.move_angles(angle_1=angle_1, draw=True)\n\n for angle_2 in range(elbow_angle, elbow_angle+16):\n self.move_angles(angle_2=angle_2, draw=True)\n for angle_2 in range(elbow_angle+16, elbow_angle-16, -1):\n self.move_angles(angle_2=angle_2, draw=True)\n for angle_2 in range(elbow_angle-16, elbow_angle+1):\n self.move_angles(angle_2=angle_2, draw=True)\n\n\n # ----------------- pen-moving methods -----------------\n\n def xy(self, x=None, y=None, wait=0, interpolate=10, draw=False):\n \"\"\"Moves the pen to the xy position; optionally draws while doing it.\"\"\"\n\n wait = wait or self.wait\n\n if draw:\n self.pen.down()\n else:\n self.pen.up()\n\n x = x or self.x\n y = y or self.y\n\n (angle_1, angle_2) = self.xy_to_angles(x, y)\n\n # calculate how many steps we need for this move, and the x/y length of each\n (x_length, y_length) = (x - self.x, y - self.y)\n\n length = math.sqrt(x_length ** 2 + y_length **2)\n\n no_of_steps = int(length * interpolate) or 1\n\n if no_of_steps < 100:\n disable_tqdm = True\n else:\n disable_tqdm = False\n\n (length_of_step_x, length_of_step_y) = (x_length/no_of_steps, y_length/no_of_steps)\n\n for step in tqdm.tqdm(range(no_of_steps), desc='Interpolation', leave=False, disable=disable_tqdm):\n\n self.x = self.x + length_of_step_x\n self.y = self.y + length_of_step_y\n\n angle_1, angle_2 = self.xy_to_angles(self.x, self.y)\n\n self.set_angles(angle_1, angle_2)\n\n if step + 1 < no_of_steps:\n sleep(length * wait/no_of_steps)\n\n sleep(length * wait/10)\n\n\n def move_angles(self, angle_1=None, angle_2=None, wait=0, interpolate=10, draw=False):\n \"\"\"Moves the servo motors to the specified angles step-by-step, calling set_angles() for each step.\"\"\"\n\n wait = wait or self.wait\n\n if draw:\n self.pen.down()\n else:\n self.pen.up()\n\n diff_1 = diff_2 = 0\n\n if angle_1 is not None:\n diff_1 = angle_1 - self.angle_1\n if angle_2 is not None:\n diff_2 = angle_2 - self.angle_2\n\n length = math.sqrt(diff_1 ** 2 + diff_2 **2)\n\n no_of_steps = int(length * interpolate) or 1\n\n if no_of_steps < 100:\n disable_tqdm = True\n else:\n disable_tqdm = False\n\n (length_of_step_1, length_of_step_2) = (diff_1/no_of_steps, diff_2/no_of_steps)\n\n for step in tqdm.tqdm(range(no_of_steps), desc='Interpolation', leave=False, disable=disable_tqdm):\n\n self.angle_1 = self.angle_1 + length_of_step_1\n self.angle_2 = self.angle_2 + length_of_step_2\n\n self.set_angles(self.angle_1, self.angle_2)\n\n if step + 1 < no_of_steps:\n sleep(length * wait/no_of_steps)\n\n sleep(length * wait/10)\n\n\n def set_angles(self, angle_1=None, angle_2=None):\n \"\"\"Moves the servo motors to the specified angles immediately. Relies upon getting accurate pulse-width\n values.\n\n Calls set_pulse_widths().\n\n Sets current_x, current_y.\n \"\"\"\n\n pw_1 = pw_2 = None\n\n if angle_1 is not None:\n pw_1 = self.angles_to_pw_1(angle_1)\n\n if pw_1 > self.previous_pw_1:\n self.active_hysteresis_correction_1 = self.hysteresis_correction_1\n elif pw_1 < self.previous_pw_1:\n self.active_hysteresis_correction_1 = - self.hysteresis_correction_1\n\n self.previous_pw_1 = pw_1\n\n pw_1 = pw_1 + self.active_hysteresis_correction_1\n\n self.angle_1 = angle_1\n self.angles_used_1.add(int(angle_1))\n self.pulse_widths_used_1.add(int(pw_1))\n\n if angle_2 is not None:\n pw_2 = self.angles_to_pw_2(angle_2)\n\n if pw_2 > self.previous_pw_2:\n self.active_hysteresis_correction_2 = self.hysteresis_correction_2\n elif pw_2 < self.previous_pw_2:\n self.active_hysteresis_correction_2 = - self.hysteresis_correction_2\n\n self.previous_pw_2 = pw_2\n\n pw_2 = pw_2 + self.active_hysteresis_correction_2\n\n self.angle_2 = angle_2\n self.angles_used_2.add(int(angle_2))\n self.pulse_widths_used_2.add(int(pw_2))\n\n if self.turtle:\n\n x, y = self.angles_to_xy(self.angle_1, self.angle_2)\n\n self.turtle.setx(x * self.turtle.multiplier)\n self.turtle.sety(y * self.turtle.multiplier)\n\n self.set_pulse_widths(pw_1, pw_2)\n self.x, self.y = self.angles_to_xy(self.angle_1, self.angle_2)\n\n\n # ----------------- angles-to-pulse-widths methods -----------------\n\n def naive_angles_to_pulse_widths_1(self, angle):\n return (angle - self.servo_1_parked_angle) * self.servo_1_degree_ms + self.servo_1_parked_pw\n\n def naive_angles_to_pulse_widths_2(self, angle):\n return (angle - self.servo_2_parked_angle) * self.servo_2_degree_ms + self.servo_2_parked_pw\n\n\n # ----------------- hardware-related methods -----------------\n\n def set_pulse_widths(self, pw_1=None, pw_2=None):\n \"\"\"Applies the supplied pulse-width values to the servos, or pretends to, if we're in virtual\n mode.\"\"\"\n\n if self.virtual:\n\n if pw_1:\n if 500 < pw_1 < 2500:\n self.virtual_pw_1 = pw_1\n else:\n raise ValueError\n\n if pw_2:\n if 500 < pw_2 < 2500:\n self.virtual_pw_2 = pw_2\n else:\n raise ValueError\n\n else:\n\n if pw_1:\n self.rpi.set_servo_pulsewidth(14, pw_1)\n if pw_2:\n self.rpi.set_servo_pulsewidth(15, pw_2)\n\n\n def get_pulse_widths(self):\n \"\"\"Returns the actual pulse-widths values; if in virtual mode, returns the nominal values - i.e. the\n values that they might be.\n \"\"\"\n\n if self.virtual:\n\n actual_pulse_width_1 = self.virtual_pw_1\n actual_pulse_width_2 = self.virtual_pw_2\n\n else:\n\n actual_pulse_width_1 = self.rpi.get_servo_pulsewidth(14)\n actual_pulse_width_2 = self.rpi.get_servo_pulsewidth(15)\n\n return (actual_pulse_width_1, actual_pulse_width_2)\n\n\n def park(self):\n \"\"\"Park the plotter with the inner arm at -90˚ and the outer arm at 90˚ to it.\n\n This corresponds to an x/y position:\n\n * x: ``-inner_arm``\n * y: ``outer_arm``\n \"\"\"\n\n if self.virtual:\n print(\"Parking\")\n\n self.pen.up()\n\n\n self.xy(-self.inner_arm, self.outer_arm)\n sleep(1)\n\n\n def quiet(self, servos=[14, 15, 18]):\n \"\"\"Stop sending pulses to the servos, so that they are no longer energised (and so that they\n stop buzzing).\n \"\"\"\n\n if self.virtual:\n print(\"Going quiet\")\n\n else:\n for servo in servos:\n self.rpi.set_servo_pulsewidth(servo, 0)\n\n\n # ----------------- trigonometric methods -----------------\n\n # Every x/y position of the plotter corresponds to a pair of angles of the arms. These methods\n # calculate:\n #\n # the angles required to reach any x/y position\n # the x/y position represented by any pair of angles\n\n def xy_to_angles(self, x=0, y=0):\n \"\"\"Return the servo angles required to reach any x/y position.\"\"\"\n\n hypotenuse = math.sqrt(x**2+y**2)\n\n if hypotenuse > self.inner_arm + self.outer_arm:\n raise Exception(f\"Cannot reach {hypotenuse}; total arm length is {self.inner_arm + self.outer_arm}\")\n\n hypotenuse_angle = math.asin(x/hypotenuse)\n\n inner_angle = math.acos(\n (hypotenuse**2+self.inner_arm**2-self.outer_arm**2)/(2*hypotenuse*self.inner_arm)\n )\n outer_angle = math.acos(\n (self.inner_arm**2+self.outer_arm**2-hypotenuse**2)/(2*self.inner_arm*self.outer_arm)\n )\n\n shoulder_motor_angle = hypotenuse_angle - inner_angle\n elbow_motor_angle = math.pi - outer_angle\n\n return (math.degrees(shoulder_motor_angle), math.degrees(elbow_motor_angle))\n\n\n def angles_to_xy(self, shoulder_motor_angle, elbow_motor_angle):\n \"\"\"Return the x/y co-ordinates represented by a pair of servo angles.\"\"\"\n\n elbow_motor_angle = math.radians(elbow_motor_angle)\n shoulder_motor_angle = math.radians(shoulder_motor_angle)\n\n hypotenuse = math.sqrt(\n (self.inner_arm ** 2 + self.outer_arm ** 2 - 2 * self.inner_arm * self.outer_arm * math.cos(\n math.pi - elbow_motor_angle)\n )\n )\n base_angle = math.acos(\n (hypotenuse ** 2 + self.inner_arm ** 2 - self.outer_arm ** 2) / (2 * hypotenuse * self.inner_arm)\n )\n inner_angle = base_angle + shoulder_motor_angle\n\n x = math.sin(inner_angle) * hypotenuse\n y = math.cos(inner_angle) * hypotenuse\n\n return(x, y)\n\n\n # ----------------- calibration -----------------\n\n def auto_calibrate(self):\n self.park()\n\n for elbow in range(90, 136):\n self.set_angles(None, elbow)\n sleep(.01)\n\n for shoulder in range(-90, -140, -1):\n self.set_angles(shoulder, None)\n sleep(.01)\n\n\n def calibrate(self, servo=1):\n\n pin = {1: 14, 2: 15}[servo]\n\n servo_centre = {1: self.servo_1_parked_pw, 2: self.servo_2_parked_pw}.get(servo)\n servo_angle_pws = []\n texts = {\n \"arm-name\": {1: \"inner\", 2: \"outer\"},\n \"nominal-centre\": {1: 0, 2: 90},\n \"mount-arm\": {\n 1: \"(straight ahead)\",\n 2: \"(i.e. to the right) to the inner arm)\"\n },\n \"safe-guess\": {1: -60, 2: 90}\n }\n\n pw = servo_centre\n\n print(f\"Calibrating servo {servo}, for the {texts['arm-name'][servo]} arm.\")\n print(f\"See https://brachiograph.art/how-to/calibrate.html\")\n print()\n self.rpi.set_servo_pulsewidth(pin, pw)\n print(f\"The servo is now at {pw}µS, in the centre of its range of movement.\")\n print(\"Attach the protractor to the base, with its centre at the axis of the servo.\")\n\n print(f\"Mount the arm at a position as close as possible to {texts['nominal-centre'][servo]}˚ {texts['mount-arm'][servo]}.\")\n\n print(\"Now drive the arm to a known angle, as marked on the protractor.\")\n print(\"When the arm reaches the angle, press 1 and record the angle. Do this for as many angles as possible.\")\n print()\n print(\"When you have done all the angles, press 2.\")\n print(\"Press 0 to exit at any time.\")\n\n while True:\n key = readchar.readchar()\n\n if key == \"0\":\n return\n elif key == \"1\":\n angle = float(input(\"Enter the angle: \"))\n servo_angle_pws.append([angle, pw])\n elif key == \"2\":\n break\n elif key==\"a\":\n pw = pw - 10\n elif key==\"s\":\n pw = pw + 10\n elif key==\"A\":\n pw = pw - 1\n elif key==\"S\":\n pw = pw + 1\n else:\n continue\n\n print(pw)\n\n self.rpi.set_servo_pulsewidth(pin, pw)\n\n print(f\"------------------------\")\n print(f\"Recorded angles servo {servo}\")\n print(f\"------------------------\")\n print(f\" angle | pulse-width \")\n print(f\"---------+--------------\")\n\n servo_angle_pws.sort()\n for [angle, pw] in servo_angle_pws:\n print(f\" {angle:>6.1f} | {pw:>4.0f}\")\n\n servo_array = numpy.array(servo_angle_pws)\n\n pw = int(numpy.poly1d(\n numpy.polyfit(\n servo_array[:,0],\n servo_array[:,1],\n 3\n )\n )(0))\n\n self.rpi.set_servo_pulsewidth(pin, pw)\n print()\n print(f\"The servo is now at {int(pw)}µS, which should correspond to {texts['nominal-centre'][servo]}˚.\")\n print(\"If necessary, remount the arm at the centre of its optimal sweep for your drawing area.\")\n print()\n print(f\"Alternatively as a rule of thumb, if the arms are of equal length, use the position closest to {texts['safe-guess'][servo]}˚.\")\n\n print(\"Carefully count how many spline positions you had to move the arm by to get it there.\")\n print(\"Multiply that by the number of degrees for each spline to get the angle by which you moved it.\")\n offset = float(input(\"Enter the angle by which you moved the arm (anti-clockwise is negative): \"))\n\n print(f\"---------------------------\")\n print(f\"Calculated angles {texts['arm-name'][servo]} arm\")\n print(f\"---------------------------\")\n print(f\" angle | pulse-width \")\n print(f\"----------+----------------\")\n\n servo_angle_including_offset_pws = []\n\n for [angle, pw] in servo_angle_pws:\n angle_including_offset = round(angle + offset, 1)\n servo_angle_including_offset_pws.append([angle_including_offset, pw])\n print(f\" {angle:>6.1f} | {pw:>4.0f}\")\n\n print()\n print(\"Use this list of angles and pulse-widths in your BrachioGraph definition:\")\n print()\n print(f\"servo_{servo}_angle_pws={servo_angle_including_offset_pws}\")\n\n\n # ----------------- manual driving methods -----------------\n\n def drive(self):\n\n # adjust the pulse-widths using the keyboard\n\n pw_1, pw_2 = self.get_pulse_widths()\n\n self.set_pulse_widths(pw_1, pw_2)\n\n while True:\n key = readchar.readchar()\n\n if key == \"0\":\n return\n elif key==\"a\":\n pw_1 = pw_1 - 10\n elif key==\"s\":\n pw_1 = pw_1 + 10\n elif key==\"A\":\n pw_1 = pw_1 - 2\n elif key==\"S\":\n pw_1 = pw_1 + 2\n elif key==\"k\":\n pw_2 = pw_2 - 10\n elif key==\"l\":\n pw_2 = pw_2 + 10\n elif key==\"K\":\n pw_2 = pw_2 - 2\n elif key==\"L\":\n pw_2 = pw_2 + 2\n\n print(pw_1, pw_2)\n\n self.set_pulse_widths(pw_1, pw_2)\n\n\n def drive_xy(self):\n\n # move the pen up/down and left/right using the keyboard\n\n while True:\n key = readchar.readchar()\n\n if key == \"0\":\n return\n elif key==\"a\":\n self.x = self.x - 1\n elif key==\"s\":\n self.x = self.x + 1\n elif key==\"A\":\n self.x = self.x - .1\n elif key==\"S\":\n self.x = self.x + .1\n elif key==\"k\":\n self.y = self.y - 1\n elif key==\"l\":\n self.y = self.y + 1\n elif key==\"K\":\n self.y = self.y - .1\n elif key==\"L\":\n self.y = self.y + .1\n\n print(self.x, self.y)\n\n self.xy(self.x, self.y)\n\n\n # ----------------- reporting methods -----------------\n\n def status(self):\n print(\"------------------------------------------\")\n print(\" | Servo 1 | Servo 2 \")\n print(\" | Shoulder| Elbow \")\n print(\"----------------------|---------|---------\")\n\n pw_1, pw_2 = self.get_pulse_widths()\n print(f\"{'pulse-width |':>23}\", f\"{pw_1:>7.0f}\", \"|\", f\"{pw_2:>7.0f}\")\n\n angle_1, angle_2 = self.angle_1, self.angle_2\n print(f\"{'angle |':>23}\", f\"{angle_1:>7.0f}\", \"|\", f\"{angle_2:>7.0f}\")\n\n h1, h2 = self.hysteresis_correction_1, self.hysteresis_correction_2\n print(f\"{'hysteresis correction |':>23}\", f\"{h1:>7.1f}\", \"|\", f\"{h2:>7.1f}\")\n print(\"------------------------------------------\")\n print(f\"{'x/y location |':>23}\", f\"{self.x:>7.1f}\", \"|\", f\"{self.y:>7.1f}\")\n print()\n print(\"------------------------------------------\")\n print(\"pen:\", self.pen.position)\n\n bl = self.bounds[0], self.bounds[1]\n tr = self.bounds[2], self.bounds[3]\n print(\"------------------------------------------\")\n print(\"bottom left:\", bl, \"top right:\", tr)\n print(\"------------------------------------------\")\n\n\n def report(self):\n\n print(f\" -----------------|-----------------\")\n print(f\" Servo 1 | Servo 2 \")\n print(f\" -----------------|-----------------\")\n\n h1, h2 = self.hysteresis_correction_1, self.hysteresis_correction_2\n print(f\"hysteresis {h1:>2.1f} | {h2:>2.1f}\")\n\n pw_1, pw_2 = self.get_pulse_widths()\n print(f\"pulse-width {pw_1:<4.0f} | {pw_2:<4.0f}\")\n\n angle_1, angle_2 = self.angle_1, self.angle_2\n\n if angle_1 and angle_2:\n\n print(f\" angle {angle_1:>4.0f} | {angle_2:>4.0f}\")\n\n print(f\" -----------------|-----------------\")\n print(f\" min max mid | min max mid\")\n print(f\" -----------------|-----------------\")\n\n if self.angles_used_1 and self.angles_used_2 and self.pulse_widths_used_1 and self.pulse_widths_used_2:\n\n min1 = min(self.pulse_widths_used_1)\n max1 = max(self.pulse_widths_used_1)\n mid1 = (min1 + max1) / 2\n min2 = min(self.pulse_widths_used_2)\n max2 = max(self.pulse_widths_used_2)\n mid2 = (min2 + max2) / 2\n\n print(f\"pulse-widths {min1:>4.0f} {max1:>4.0f} {mid1:>4.0f} | {min2:>4.0f} {max2:>4.0f} {mid2:>4.0f}\")\n\n min1 = min(self.angles_used_1)\n max1 = max(self.angles_used_1)\n mid1 = (min1 + max1) / 2\n min2 = min(self.angles_used_2)\n max2 = max(self.angles_used_2)\n mid2 = (min2 + max2) / 2\n\n print(f\" angles {min1:>4.0f} {max1:>4.0f} {mid1:>4.0f} | {min2:>4.0f} {max2:>4.0f} {mid2:>4.0f}\")\n\n else:\n\n print(\"No data recorded yet. Try calling the BrachioGraph.box() method first.\")\n\n\n def reset_report(self):\n\n self.angle_1 = self.angle_2 = None\n\n # Create sets for recording movement of the plotter.\n self.angles_used_1 = set()\n self.angles_used_2 = set()\n self.pulse_widths_used_1 = set()\n self.pulse_widths_used_2 = set()\n\n\n @property\n def bl(self):\n return (self.bounds[0], self.bounds[1])\n\n @property\n def tl(self):\n return (self.bounds[0], self.bounds[3])\n\n @property\n def tr(self):\n return (self.bounds[2], self.bounds[3])\n\n @property\n def br(self):\n return (self.bounds[2], self.bounds[1])\n\n\n def reset_turtle(self):\n self.turtle = BrachioGraphTurtle(\n inner_arm=self.inner_arm, # the length of the inner arm (blue)\n shoulder_centre_angle=-90, # the starting angle of the inner arm, relative to straight ahead\n shoulder_sweep=180, # the arc covered by the shoulder motor\n\n outer_arm=self.outer_arm, # the length of the outer arm (red)\n elbow_centre_angle=90, # the centre of the outer arm relative to the inner arm\n elbow_sweep=180, # the arc covered by the elbow motor\n\n window_size=800, # width and height of the turtle canvas\n speed=0, # how fast to draw\n )\n\n self.turtle.draw_grid()\n\n\nclass Pen:\n\n def __init__(self, bg, pw_up=1700, pw_down=1300, pin=18, transition_time=0.25, virtual=False):\n\n self.bg = bg\n self.pin = pin\n self.pw_up = pw_up\n self.pw_down = pw_down\n self.transition_time = transition_time\n self.virtual = virtual\n if self.virtual:\n\n print(\"Initialising virtual Pen\")\n\n else:\n\n self.rpi = pigpio.pi()\n self.rpi.set_PWM_frequency(self.pin, 50)\n\n self.up()\n sleep(0.3)\n self.down()\n sleep(0.3)\n self.up()\n sleep(0.3)\n\n\n def down(self):\n\n if self.virtual:\n self.virtual_pw = self.pw_down\n\n else:\n self.rpi.set_servo_pulsewidth(self.pin, self.pw_down)\n sleep(self.transition_time)\n\n if self.bg.turtle:\n self.bg.turtle.down()\n self.bg.turtle.color('blue')\n self.bg.turtle.width(1)\n\n self.position = \"down\"\n\n\n def up(self):\n\n if self.virtual:\n self.virtual_pw = self.pw_up\n\n else:\n self.rpi.set_servo_pulsewidth(self.pin, self.pw_up)\n sleep(self.transition_time)\n\n if self.bg.turtle:\n self.bg.turtle.up()\n\n self.position = \"up\"\n\n\n # for convenience, a quick way to set pen motor pulse-widths\n def pw(self, pulse_width):\n\n if self.virtual:\n self.virtual_pw = pulse_width\n\n else:\n self.rpi.set_servo_pulsewidth(self.pin, pulse_width)\n\n\n def calibrate(self):\n\n print(f\"Calibrating the pen-lifting servo.\")\n print(f\"See https://brachiograph.art/how-to/calibrate.html\")\n\n pw_1, pw_2 = self.bg.get_pulse_widths()\n pw_3 = self.pw_up\n\n while True:\n self.bg.set_pulse_widths(pw_1, pw_2)\n self.pw(pw_3)\n\n key = readchar.readchar()\n\n if key == \"0\":\n break\n elif key==\"a\":\n pw_1 = pw_1 - 10\n continue\n elif key==\"s\":\n pw_1 = pw_1 + 10\n continue\n elif key==\"k\":\n pw_2 = pw_2 - 10\n continue\n elif key==\"l\":\n pw_2 = pw_2 + 10\n continue\n\n elif key==\"t\":\n if pw_3 == self.pw_up:\n pw_3 = self.pw_down\n else:\n pw_3 = self.pw_up\n continue\n\n elif key==\"z\":\n pw_3 = pw_3 - 10\n print(pw_3)\n continue\n elif key==\"x\":\n pw_3 = pw_3 + 10\n print(pw_3)\n continue\n\n elif key==\"u\":\n self.pw_up = pw_3\n elif key==\"d\":\n self.pw_down = pw_3\n else:\n continue\n\n mid = (self.pw_up + self.pw_down) / 2\n print(f\"Pen-up pulse-width: {self.pw_up}µS, pen-down pulse-width: {self.pw_down}µS, mid-point: {mid}\")\n\n print()\n print(\"Use these values in your BrachioGraph definition:\")\n print()\n print(f\"pen_up={self.pw_up}, pen_down={self.pw_down}\")\n" ]
[ [ "numpy.polyfit", "numpy.array", "numpy.mean" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jackyhuynh/graph_traverse_using_networkx
[ "11988af1324cbd1520102c66776476d91c2d087e" ]
[ "truc_graph_traverse.py" ]
[ "# Required library\nimport matplotlib.pyplot as plt\nimport networkx as nx\n\n\"\"\"\n# openfile read input from textfile\n# In fact, I test the data on different jupiter notebook and come up with the shortest version\n\"\"\"\n\n\ndef openfile(filename):\n with open(filename, \"r\") as file_reader:\n all_lines = file_reader.readlines()\n return all_lines\n\n\n\"\"\"\ncreate_data(data): take parameter data, remove all the newline, space and then convert each line to a tuple\ncreate RoadDict dictionary and list of tuple clean_data\n\"\"\"\n\n\ndef create_data(data):\n clean_data = []\n road_dict = {}\n count = 0\n # Clean the data by using for loop\n for line in data:\n line = line.replace('\\n', '').replace(' ', '').split(',')\n road_dict[count] = {'citi1': line[0], 'citi2': line[1], 'distance': line[2]}\n clean_data.append((line[0], line[1], float(line[2])))\n return clean_data, road_dict\n\n\n\"\"\"\nSimple get the input from user, and validation, to make sure it not crash the application\n\"\"\"\n\n\ndef get_user_input(cities, purpose):\n user_input = input(f\"Please enter the {purpose} city: \").capitalize()\n while user_input not in cities:\n cities_display(cities)\n user_input = input(f\"Please enter the {purpose} city again: \").capitalize()\n\n return user_input\n\n\n\"\"\"\nPrint out the cities in the list\n\"\"\"\n\n\ndef cities_display(cities):\n print(\"Target city and Destination city must be:\")\n for citi in cities:\n print(citi, end=', ')\n\n print('')\n\n\nif __name__ == '__main__':\n # Preparation:\n # create RoadDict as requirement and graph_data to feed in networkx to create graphs\n graph_data, road_dict = create_data(openfile(\"frenchcities.txt\"))\n # create multi graph using networkx\n multi_graph = nx.MultiGraph()\n multi_graph.add_weighted_edges_from(graph_data)\n\n # Convert the graph to dictionary with weight\n multi_graph_dict = dict(multi_graph.degree(weight='weight'))\n # create the city list for validation only\n cities_list = list(multi_graph_dict)\n\n # Task 1: print out the data\n nx.draw(multi_graph, with_labels=True, font_weight='bold')\n plt.show()\n\n # Task 2:\n cities_display(cities_list)\n target = get_user_input(cities_list, \"target\")\n destination = get_user_input(cities_list, \"destination\")\n\n # Using Kilometer because it is the standard measurement in France:\n # Searching using Dijkstra Algorithm (Bread First Search)\n print(f\"BFS: Cities need to travel: {nx.dijkstra_path(multi_graph, target, destination)}, \"\n f\"total distance: {nx.dijkstra_path_length(multi_graph, target, destination)} Km\")\n # Searching using Bellman Forf Algorithm (Depth First Search)\n print(f\"DFS: Cities need to travel: {nx.bellman_ford_path(multi_graph, target, destination)}, \"\n f\"total distance: {nx.bellman_ford_path_length(multi_graph, target, destination)} Km\")\n" ]
[ [ "matplotlib.pyplot.show" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Oewyn/onnxmltools
[ "8dbd844dab77754971f59d4d533e6763ce0b03c2", "8dbd844dab77754971f59d4d533e6763ce0b03c2" ]
[ "onnxmltools/convert/common/shape_calculator.py", "tests/sklearn/test_SklearnDecisionTreeConverters.py" ]
[ "# -------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n# --------------------------------------------------------------------------\n\"\"\"\nCommon functions to convert any learner based on trees.\n\"\"\"\nimport numpy as np\nimport numbers\nimport six\nfrom ._registration import register_shape_calculator\nfrom .data_types import Int64TensorType, FloatTensorType, StringTensorType, DictionaryType, SequenceType\nfrom .utils import check_input_and_output_numbers, check_input_and_output_types, compare_strict_version\n\n\ndef calculate_linear_classifier_output_shapes(operator):\n '''\n This operator maps an input feature vector into a scalar label if the number of outputs is one. If two outputs\n appear in this operator's output list, we should further generate a map storing all classes' probabilities.\n\n Allowed input/output patterns are\n 1. [N, C] ---> [N, 1], A sequence of map\n\n Note that the second case is not allowed as long as ZipMap only produces dictionary.\n '''\n check_input_and_output_numbers(operator, input_count_range=1, output_count_range=[1, 2])\n check_input_and_output_types(operator, good_input_types=[FloatTensorType, Int64TensorType])\n\n if len(operator.inputs[0].type.shape) != 2:\n raise RuntimeError('Input must be a [N, C]-tensor')\n\n N = operator.inputs[0].type.shape[0]\n\n class_labels = operator.raw_operator.classes_\n if all(isinstance(i, np.ndarray) for i in class_labels):\n class_labels = np.concatenate(class_labels)\n if all(isinstance(i, (six.string_types, six.text_type)) for i in class_labels):\n operator.outputs[0].type = StringTensorType(shape=[N])\n if len(class_labels) > 2 or operator.type != 'SklearnLinearSVC':\n # For multi-class classifier, we produce a map for encoding the probabilities of all classes\n if compare_strict_version(operator.targeted_onnx_version, '1.2') < 0:\n operator.outputs[1].type = DictionaryType(StringTensorType([1]), FloatTensorType([1]))\n else:\n operator.outputs[1].type = SequenceType(DictionaryType(StringTensorType([]), FloatTensorType([])), N)\n else:\n # For binary classifier, we produce the probability of the positive class\n operator.outputs[1].type = FloatTensorType(shape=[N, 1])\n elif all(isinstance(i, (numbers.Real, bool, np.bool_)) for i in class_labels):\n operator.outputs[0].type = Int64TensorType(shape=[N])\n if len(class_labels) > 2 or operator.type != 'SklearnLinearSVC':\n # For multi-class classifier, we produce a map for encoding the probabilities of all classes\n if compare_strict_version(operator.targeted_onnx_version, '1.2') < 0:\n operator.outputs[1].type = DictionaryType(Int64TensorType([1]), FloatTensorType([1]))\n else:\n operator.outputs[1].type = SequenceType(DictionaryType(Int64TensorType([]), FloatTensorType([])), N)\n else:\n # For binary classifier, we produce the probability of the positive class\n operator.outputs[1].type = FloatTensorType(shape=[N, 1])\n else:\n raise ValueError('Unsupported or mixed label types')\n\n\ndef calculate_linear_regressor_output_shapes(operator):\n '''\n Allowed input/output patterns are\n 1. [N, C] ---> [N, 1]\n\n This operator produces a scalar prediction for every example in a batch. If the input batch size is N, the output\n shape may be [N, 1].\n '''\n check_input_and_output_numbers(operator, input_count_range=1, output_count_range=1)\n\n N = operator.inputs[0].type.shape[0]\n operator.outputs[0].type = FloatTensorType([N, 1])\n\n", "# -------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n# --------------------------------------------------------------------------\n\nimport unittest\nimport numpy\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.tree import DecisionTreeRegressor\nfrom onnxmltools.utils import dump_one_class_classification, dump_binary_classification, dump_multiple_classification\nfrom onnxmltools.utils import dump_multiple_regression, dump_single_regression\n\n\nclass TestSklearnDecisionTreeModels(unittest.TestCase):\n\n def test_decision_tree_classifier(self):\n model = DecisionTreeClassifier()\n dump_one_class_classification(model)\n dump_binary_classification(model)\n dump_multiple_classification(model)\n\n def test_decision_tree_regressor(self):\n model = DecisionTreeRegressor()\n dump_single_regression(model)\n dump_multiple_regression(model)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n" ]
[ [ "numpy.concatenate" ], [ "sklearn.tree.DecisionTreeClassifier", "sklearn.tree.DecisionTreeRegressor" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
omikabir/omEngin
[ "b8c04a5c2c12ffc3d0b67c2ceba9e5741d3f9195", "b8c04a5c2c12ffc3d0b67c2ceba9e5741d3f9195", "b8c04a5c2c12ffc3d0b67c2ceba9e5741d3f9195", "b8c04a5c2c12ffc3d0b67c2ceba9e5741d3f9195" ]
[ "Z_ALL_FILE/Jy1/1092020-80-XAQ-Untitled.py", "Z_ALL_FILE/Jy1/fnstr-checkpoint.py", "Z_ALL_FILE/Py/InsUpd._11262020-1848.py", "Z_ALL_FILE/Py/main.py" ]
[ "#!/usr/bin/env python\n# coding: utf-8\n\n# In[8]:\n\n\nimport pandas as pd\nimport numpy as np\nimport os\nimport sqlite3\n\npt = os.getcwd()\nalarm = pt + \"\\\\C.csv\"\n\n\ndef conv_2_list(ls1, ls2, ls3):\n ToDf = pd.DataFrame(zip(ls1, ls2, l3))\n print(Todf)\n \n\nl0 = [\"0\", \"1\", \"2\", \"3\", \"4\"]\nl1 = [\"Amar\", \"Barsha\", \"Carlos\", \"Tanmay\", \"Misbah\"] \nl2 = [\"Alpha\", \"Bravo\", \"Charlie\", \"Tango\", \"Mike\"] \n#conv_2_list(l0,l1,l2)\n\n\ndef concat(v1,v2):\n z = str(v1) + '-' + str(v2)\n return z\n\nCDCT = lambda x : x[:4] if (len(x) >= 6) else \"NF\"\n\ndef df_add_col(dff,nwcol):\n df = dff.replace(r'^\\s*$', np.NaN, regex=True)\n for i in range(len(df)):\n df.loc[i,nwcol] = concat(df.loc[i,\"CUSTOMATTR15\"],df.loc[i,\"SUMMARY\"])\n return df\n\n\n\n\ndf0 = pd.read_csv(alarm)\ndf1 = df0[['SERIAL','CUSTOMATTR15','SUMMARY','LASTOCCURRENCE','CLEARTIMESTAMP','CUSTOMATTR3']]\nx = df_add_col(df1,'scode')\nls = x.columns.to_list()\nprint(ls)\n#print(x)\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n", "#!/usr/bin/env python\n# coding: utf-8\n\n# In[38]:\n\n\nimport pandas as pd\nimport os\nimport numpy\nimport MySQLdb\n\nconn= MySQLdb.connect(\"localhost\",\"root\",\"admin\",\"omdb\")\nfile = os.getcwd() + \"\\\\\" + \"BK1.csv\"\n\nclass omstring:\n def __init__(self):\n print('x')\n def chk_rcut(self,txt,findchr):\n x = txt.find(findchr)\n ln = len(txt)\n if x != -1:\n return txt[x:ln]\n else:\n return '0'\n def chk_lcut(self,txt,findchr):\n x = txt.find(findchr)\n if x != -1:\n return txt[0:x]\n else:\n return '0'\n def midcut(self,txt,fromindx,toindx):\n return txt[fromindx : toindx]\n def instr(self,txt,chkchr):\n return txt.find(chkchr)\n def instrrev(self,txt,chkchr):\n return txt.rindex(chkchr)\n def str_split(self,txt,splitby):\n return txt.split(splitby)\n def str_chrocc(self,txt,chrchk):\n return txt.count(chrchk)\n def str_trim(self,txt):\n return txt.strip()\n def instr_st_end(self,txt,chkstr,st,end):\n return txt.find(chkstr, st, end)\n def isall_digit(self,txt):\n return txt.isdigit(self)\n def isall_alphabet(self,text):\n return txt.isalpha()\n def isall_number(self,text):\n return txt.isnumeric()\n def str_tolower(self,text):\n return txt.casefold()\n def str_toupper(self,txt):\n return txt.upper()\n def str_chktype(self,txt):\n return type(txt)\n \n\n\n\ndf_mysql = pd.read_sql(\"select * from sitedb\",conn)\ndf_csv = pd.read_csv(file)\nst = \"\"\"Close Notification:*13 3G & 11 4G Sites in Barisal are gradually up*\n Severity: C-3*FT: 14:36 to 14:47_26/04*RT: 18:31_26/04*DUR: 03:55*Link: SPZNR02-SPZNR04*\n Cause: VLAN missmatched at SPZNR02 during TNR CRQ000000224351\n (Slogan: NCCD Abis_oIP Project FE configure at VLAN Barishal zone)\"\"\"\ny = omstring()\nprint(y.instr(st,'VLAN'))\n\n\n# In[33]:\n\n\ny.chk_rcut(st,\"CRQ0\")\n\n\n# In[22]:\n\n\ny.midcut(st,3,10)\n\n\n# In[25]:\n\n\ny.instr(st,'VLAN')\n\n\n# In[42]:\n\n\ny.instrrev(st,'VLAN')\n\n\n# In[43]:\n\n\ny.midcut(st,0,21)\n\n\n# In[44]:\n\n\ny.midcut(st,y.instr(st,'VLAN'),y.instrrev(st,'VLAN'))\n\n\n# In[45]:\n\n\ny.str_chktype(st)\n\n\n# In[ ]:\n\n\n\n\n", "import pandas as pd\nimport os, datetime, time\nfrom datetime import *\n\n#user = 'root'\n#password = 'admin'\n#host = '127.0.0.1:3306'\n#db = 'omdb'\n#constr = 'mysql+mysqlconnector://' + user + ':' + password + '@' + host + '/' + db\n#engine = create_engine(constr, echo=False)\n#conn = engine.raw_connection()\n#cur = conn.cursor()\n\ndef prep_update(lscol,lsval):\n hp = ''\n if isinstance(lscol, list) and isinstance(lsval, list):\n if len(lscol) == len(lsval):\n for i in range(len(lscol)):\n x = str(lscol[i]) + \"='\" + str(lsval[i]) + \"'\"\n if hp == '':\n hp = x\n else:\n hp = hp + ',' + x\n else:\n print('num of col and value are not same')\n return hp\n elif isinstance(lscol, str) and isinstance(lsval, str):\n hp = \"\"\n comma = lsval.count(',')\n invertcomma = lsval.count(\"'\")\n if invertcomma == (comma+1)*2:\n x1 = lscol.split(',')\n x2 = lsval.split(',')\n print(x1,x2)\n for i in range(len(x1)):\n x = x1[i] + \"=\" + x2[i]\n if hp == '':\n hp = x\n else:\n hp = hp + ',' + x\n if invertcomma <= 2:\n x1 = lscol.split(',')\n x2 = lsval.split(',')\n for i in range(len(x1)):\n x = str(x1[i]) + \"='\" + str(x2[i]) + \"'\"\n if hp == '':\n hp = x\n else:\n hp = hp + ',' + x\n \n return hp\n\ndef prep_insert(lscol,lsval):\n hp = ''\n if isinstance(lscol, list) and isinstance(lsval, list):\n if len(lscol) == len(lsval):\n ls = []\n for i in range(len(lsval)):\n ls.append(\"'\" + str(lsval[i]) + \"'\")\n hp = '(' + str.join(',', lscol) + ') values (' + str.join(',', ls) + ')'\n else:\n hp = \"check list values for double color\"\n print('num of col and value are not same')\n return hp\n elif isinstance(lscol, str) and isinstance(lsval, str):\n hp1 = \"\"\n hp2 = \"\"\n hp = \"\"\n cnt = 0\n comma = lsval.count(',')\n invertcomma = lsval.count(\"'\")\n if invertcomma == (comma+1)*2:\n x1 = lscol.split(',')\n x2 = lsval.split(',')\n for i in range(len(x1)):\n if hp1 == '':\n hp1 = str(x1[i])\n hp2 = str(x2[i])\n cnt = cnt + 1\n else:\n hp1 = hp1 + \",\" + str(x1[i])\n hp2 = hp2 + \",\" + str(x2[i])\n cnt = cnt + 1\n hp = '(' + hp1 + ') values (' + hp2 + ')'\n return hp\n elif invertcomma <= 2:\n x1 = lscol.split(',')\n x2 = lsval.split(',')\n for i in range(len(x1)):\n if hp1 == '':\n hp1 = str(x1[i])\n hp2 = \"'\" + str(x2[i]) + \"'\"\n cnt = cnt + 1\n else:\n hp1 = hp1 + \",\" + str(x1[i])\n hp2 = hp2 + \",\" + \"'\" + str(x2[i]) + \"'\"\n cnt = cnt + 1\n hp = '(' + hp1 + ') values (' + hp2 + ')'\n return hp\n\ndef fetchone_read(rs):\n if isinstance(rs, list):\n print('fetchone readed called \\n ')\n ls = []\n cnt = 0\n for r in rs:\n ls1 = list(r)\n cnt = cnt + 1\n print(cnt , '.', ls1)\n ls.append(ls1)\n else:\n print('list type data required but passed data type is ', type(rs))\n\ndef get_key(my_dict, val):\n for value, key in my_dict.items():\n if value == val:\n return key\n\ndef dtype_match(db, table, conn, df):\n dbcols = []\n dbcolType = []\n try:\n qry = \"SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '\" + table + \"' ORDER BY ORDINAL_POSITION\"\n dfx = pd.read_sql(qry, con= conn)\n dbcols = dfx['COLUMN_NAME'].to_list()\n dbcolType = dfx['DATA_TYPE'].to_list()\n except:\n qry = 'EXPLAIN ' + db + '.' + table\n dfx = pd.read_sql(qry, con= conn)\n dbcols = dfx['Field'].to_list()\n dbcolType = dfx['Type'].to_list()\n dc= zip(dbcols, dbcolType)\n dic = dict(dc)\n dfcol = df.columns.to_list()\n dbcols.sort()\n dfcol.sort()\n st = \"\"\n q = 0\n if dbcols == dfcol:\n comment1 = 'column counts matched exactly'\n else:\n comment1 = 'column counts are not same'\n try:\n for i in range(len(dbcols)):\n dbty = get_key(dic, dbcols[i])\n st = dbcols[i]\n Y = 0\n try:\n xdf = df[st]\n Y = 1\n except:\n Y = 0\n if Y == 1:\n if 'int' in dbty:\n df[st] = df[st].astype(int)\n elif 'datetime' in dbty or 'timestamp' in dbty:\n df[st] = df.apply(lambda x : pd.to_datetime(x[st]).strftime(\"%Y-%m-%d %H:%M:%S\"), axis = 1)\n elif dbty == 'date':\n df[st] = df.apply(lambda x : pd.to_datetime(x[st]).strftime(\"%Y-%m-%d\"), axis = 1)\n q = q + 1\n return df\n except:\n print(comment1, '-', 'error occuruced for dbcols: ', st , ' at position ', q)\n\n#df1['LASTOCCURRENCE'] = pd.to_datetime(df1['LASTOCCURRENCE'],format=\"%d/%m/%y, %H:%M:%S\", errors='raise')\n#df1['LASTOCCURRENCE'] = df1.apply(lambda x : pd.to_datetime(x.LASTOCCURRENCE).strftime(\"%d-%m-%Y h:M\"), axis = 1)\n\ndef ExInsert(tbl, conn, df):\n colname = df.columns.to_list()\n q = 0\n cr = conn.cursor()\n for i in range(len(df)):\n lsval = []\n q = q + 1\n for j in df:\n lsval.append(df.loc[i,j])\n qry = \"insert into \" + tbl + ' ' + prep_insert(colname,lsval)\n print(qry)\n cr.execute(qry)\n else:\n conn.commit()\n print('row inserted: ' + str(q))\n return 'row inserted: ' + str(q)\n\ndef CheckExist(conn , tbl, colname, values):\n qry = \"select * from \" + tbl + \" where \" + colname + \"='\" + values + \"'\"\n dfx = pd.read_sql(qry, conn)\n rw = dfx.shape[0]\n return rw\n\ndef drop_cols(df, col2drop = []):\n if len(col2drop) > 0:\n cols = df.columns.to_list()\n ncols = []\n for i in range(len(cols)):\n match = 0\n for j in range(len(col2drop)):\n if cols[i] == col2drop[j]:\n match = 1\n if match == 0:\n ncols.append(cols[i])\n ndf = df[ncols]\n return ndf\n else:\n return df\n\ndef qrybuilt(tbl, ndf, bycol, oncols = False):\n dfx = drop_cols(ndf, bycol)\n ncols = dfx.columns.to_list()\n lsqry = []\n for i in range(len(ndf)):\n x = ''\n y = ''\n for j in range(len(bycol)):\n x1 = str(bycol[j]) + \"='\" + str(ndf.loc[i, bycol[j]]) + \"'\"\n if x == '':\n x = x1\n else:\n x = x + \" and \" + x1\n for n in range(len(ncols)):\n if oncols == False:\n a1 = str(ncols[n])\n a2 = \"'\" + str(ndf.loc[i, ncols[n]]) + \"'\"\n if y == '':\n y = a1 + '=' + a2\n else:\n y = y + \",\" + a1 + '=' + a2\n else:\n a1 = str(ncols[n])\n mat = 0\n for j in range(len(oncols)):\n if oncols[j] == a1:\n mat = 1\n break\n if mat == 1:\n a2 = \"'\" + str(ndf.loc[i, ncols[n]]) + \"'\"\n if y == '':\n y = a1 + '=' + a2\n else:\n y = y + \",\" + a1 + '=' + a2\n qry = \"update \" + tbl + ' set ' + y + ' Where ' + x\n lsqry.append(qry)\n return lsqry\n\n\ndef InsertUpdate(db, tbl, con, df, bycol = False, oncols = False):\n allcols = df.columns.to_list()\n ndf = dtype_match(db, tbl, con, df)\n if isinstance(ndf, pd.DataFrame):\n cr = con.cursor()\n if bycol == False:\n rv = ExInsert(tbl, con, ndf)\n else:\n if isinstance(bycol, list):\n if oncols != False:\n lsqry = qrybuilt(tbl, ndf, bycol, oncols)\n else:\n lsqry = qrybuilt(tbl, ndf, bycol)\n for i in range(len(lsqry)):\n qry = lsqry[i]\n try:\n cr.execute(qry)\n except:\n print(\"failed lsqry get from 'def qrybuilt' \", qry)\n con.commit()\n elif isinstance(bycol, str):\n dfx = ndf.drop(bycol, 1)\n colsname = dfx.columns.to_list()\n colscond = ndf[bycol].to_list()\n q = 0\n for i in range(len(colscond)):\n vl = colscond[i]\n chk = CheckExist(con, tbl, bycol, vl)\n ls = []\n qry = ''\n if chk != 0:\n for c1 in dfx:\n ls.append(dfx.loc[i,c1])\n qry = \"update \" + tbl + ' set ' + prep_update(colsname,ls) + ' where ' + bycol + \"='\" + vl + \"'\"\n else:\n for c1 in ndf:\n ls.append(ndf.loc[i,c1])\n qry = \"insert into \" + tbl + ' ' + prep_insert(allcols,ls)\n cr.execute(qry)\n q = q + 1\n if q <3:\n print(qry)\n con.commit()\n\ndef InsertUpdate_mod(db, tbl, con, df, bycol = False, oncols = False):\n allcols = []\n if oncols:\n allcols = oncols\n else:\n allcols = df.columns.to_list()\n ndf = dtype_match(db, tbl, con, df)\n if isinstance(ndf, pd.DataFrame):\n cr = con.cursor()\n if bycol == False:\n rv = ExInsert(tbl, con, ndf)\n else:\n if isinstance(bycol, str):\n dfx = ndf.drop(bycol, 1)\n colsname = dfx.columns.to_list()\n colscond = ndf[bycol].to_list()\n q = 0\n for i in range(len(colscond)):\n vl = colscond[i]\n chk = CheckExist(con, tbl, bycol, vl)\n ls = []\n qry = ''\n if chk != 0:\n for c1 in dfx:\n ls.append(dfx.loc[i,c1])\n qry = \"update \" + tbl + ' set ' + prep_update(colsname,ls) + ' where ' + bycol + \"='\" + vl + \"'\"\n else:\n for c1 in ndf:\n ls.append(ndf.loc[i,c1])\n qry = \"insert into \" + tbl + ' ' + prep_insert(allcols,ls)\n cr.execute(qry)\n q = q + 1\n if q <3:\n print(qry)\n con.commit()\n elif isinstance(bycol, list): # ndf, bycol\n dfx = drop_cols(ndf, bycol)\n ncols = dfx.columns.to_list()\n lsqry = []\n for i in range(len(ndf)):\n x = ''\n y = ''\n for j in range(len(bycol)):\n x1 = str(bycol[j]) + \"='\" + str(ndf.loc[i, bycol[j]]) + \"'\"\n if x == '':\n x = x1\n else:\n x = x + \" and \" + x1\n for n in range(len(ncols)):\n a1 = str(ncols[n])\n a2 = \"'\" + str(ndf.loc[i, ncols[n]]) + \"'\"\n if y == '':\n y = a1 + '=' + a2\n else:\n y = y + \",\" + a1 + '=' + a2\n qry = \"update \" + tbl + ' set ' + y + ' Where ' + x\n lsqry.append(qry)\n print('InsertUpdate_mod qry: ', qry)\n return lsqry\n", "import pandas as pd\nimport os, datetime, time, pyodbc\nfrom mysql import *\nfrom sqlalchemy import create_engine\nimport df_to_sql.df_to_sql as insupd\nimport create_table.tbl_mysql as myq\nimport create_table.tbl_mssql as msq\n#from conn_brocker import *\n\ndef mssql_115():\n cstr = \"Driver={SQL Server};SERVER=192.168.0.115;DATABASE=SOC_Roster;UID=sa;PWD=1q2w3eaz$\"\n conn = pyodbc.connect(cstr)\n return conn\n\ndef MsSql(user = 'root', password = 'admin', host = '127.0.0.1:3306', db = \"omdb\"):\n cstr = \"Driver={SQL Server};SERVER=\" + host + \";DATABASE=\" + db + \";UID=\" + user + \";PWD=\" + password\n conn = pyodbc.connect(cstr)\n return conn\n\ndef mysql_self(user = 'root', password = 'root', host = '127.0.0.1:3306', db = \"omdb\"):\n constr = 'mysql+mysqlconnector://' + user + ':' + password + '@' + host + '/' + db\n engine = create_engine(constr, echo=False)\n conn = engine.raw_connection()\n return engine\n\ndef MySql(user, password, host, db):\n constr = 'mysql+mysqlconnector://' + user + ':' + password + '@' + host + '/' + db\n engine = create_engine(constr, echo=False)\n conn = engine.raw_connection()\n return engine\n\ndef insert_data():\n pt = os.getcwd() + \"\\\\csv\\\\sclick.csv\"\n ndf = pd.read_csv(pt)\n conn = MySql('root','admin','127.0.0.1:3306','omdb')\n lser = insupd.df_to_sql(ndf, 'omdb', 'TAX1', conn, oncolumn = 'ALL')\n conn.close()\n\ndef update_by_condition():\n conn = MySql('root','admin','127.0.0.1:3306','omdb')\n pt = os.getcwd() + \"\\\\csv\\\\sclick.csv\"\n df = pd.read_csv(pt)\n lser = insupd.df_to_sql(df, 'omdb', 'TAX1', conn, bycolumn=['CustomAttr15'])\n conn.close()\n\ndef createtable():\n conn = MySql('root','admin','127.0.0.1:3306','omdb') \n pt = os.getcwd() + \"\\\\csv\\\\sclick.csv\"\n df = pd.read_csv(pt)\n x = myq.CreateTable_MYSQL(connection = conn, tablename = 'TAX2', df = df, table_col = False, table_col_datatype = False, space = '_')\n conn.close()\n\ndef sql2df(tbl):\n conn = MySql('root','admin','127.0.0.1:3306','omdb')\n qry = 'select * from '+ tbl\n df = pd.read_sql(qry, con = conn)\n return df\n\n#createtable()\n#conn = MySql('root','admin','127.0.0.1:3306','omdb')\npt = os.getcwd() + \"\\\\sclick2.csv\"\ndf = pd.read_csv(pt)\nconn = mssql_115()\n#df.to_sql(\"t12\", con = conn)\n#msq.CreateTable_MSSQL(df, \"t33\", conn)\n#lser = insupd.df_to_sql(df, 'SOC_Roster', 't22', conn, oncolumn = 'ALL')\n#conn.commit()\n#\n#dfx = pd.read_sql('select * from omtx2', con = conn)\n#print(dfx.columns, dfx.dtypes, df.shape[0])\ndfx = pd.read_sql(\"select * from t22\", con=conn)\nprint(dfx.columns, dfx)\n\n" ]
[ [ "pandas.read_csv" ], [ "pandas.read_csv", "pandas.read_sql" ], [ "pandas.to_datetime", "pandas.read_sql" ], [ "pandas.read_csv", "pandas.read_sql" ] ]
[ { "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.3", "1.1", "1.5", "1.2" ], "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": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] } ]
Chenzhoujia/Mobile_hand_tf-gnn-samples-master
[ "56236752bb06bcc60b4befb024cdd100aa9ce9ac" ]
[ "tasks/varmisuse_task.py" ]
[ "import re\nfrom collections import defaultdict\nfrom multiprocessing import Process, Queue, cpu_count\nfrom typing import Any, Dict, Iterable, List, NamedTuple, Set, Iterator\n\nimport tensorflow as tf\nimport numpy as np\nfrom dpu_utils.utils import RichPath\nfrom dpu_utils.codeutils import split_identifier_into_parts, get_language_keywords\n\nfrom .sparse_graph_task import Sparse_Graph_Task, DataFold, MinibatchData\nfrom utils import BIG_NUMBER\n\n\nALPHABET = \"abcdefghijklmnopqrstuvwxyz0123456789,;.!?:'\\\"/\\\\|_@#$%^&*~`+-=<>()[]{}\"\nALPHABET_DICT = {char: idx + 2 for (idx, char) in enumerate(ALPHABET)} # \"0\" is PAD, \"1\" is UNK\nALPHABET_DICT[\"PAD\"] = 0\nALPHABET_DICT[\"UNK\"] = 1\nUSES_SUBTOKEN_EDGE_NAME = \"UsesSubtoken\"\nSELF_LOOP_EDGE_NAME = \"SelfLoop\"\nBACKWARD_EDGE_TYPE_NAME_SUFFIX = \"_Bkwd\"\n__PROGRAM_GRAPH_EDGES_TYPES = [\"Child\", \"NextToken\", \"LastUse\", \"LastWrite\", \"LastLexicalUse\", \"ComputedFrom\",\n \"GuardedByNegation\", \"GuardedBy\", \"FormalArgName\", \"ReturnsTo\", USES_SUBTOKEN_EDGE_NAME]\n__PROGRAM_GRAPH_EDGES_TYPES_WITH_BKWD = \\\n __PROGRAM_GRAPH_EDGES_TYPES + [edge_type_name + BACKWARD_EDGE_TYPE_NAME_SUFFIX\n for edge_type_name in __PROGRAM_GRAPH_EDGES_TYPES]\nPROGRAM_GRAPH_EDGES_TYPES_VOCAB = {edge_type_name: idx\n for idx, edge_type_name in enumerate(__PROGRAM_GRAPH_EDGES_TYPES_WITH_BKWD)}\n\n\nclass GraphSample(NamedTuple):\n adjacency_lists: List[np.ndarray]\n type_to_node_to_num_incoming_edges: np.ndarray\n unique_labels_as_characters: np.ndarray\n node_labels_to_unique_labels: np.ndarray\n slot_node_id: int\n variable_candidate_nodes: np.ndarray\n variable_candidate_nodes_mask: np.ndarray\n\n\ndef _add_per_subtoken_nodes(unsplittable_node_names: Set[str], graph_dict: Dict[str, Any]) -> None:\n graph_node_labels = graph_dict['NodeLabels']\n subtoken_to_using_nodes = defaultdict(set)\n\n max_used_node_id = 0\n for node_id, node_label in graph_node_labels.items():\n node_id = int(node_id)\n max_used_node_id = max(node_id, max_used_node_id)\n\n # Skip AST nodes and punctuation:\n if node_label in unsplittable_node_names:\n continue\n\n for subtoken in split_identifier_into_parts(node_label):\n if re.search('[a-zA-Z0-9]', subtoken):\n subtoken_to_using_nodes[subtoken].add(node_id)\n\n subtoken_node_id = max_used_node_id\n new_edges = []\n for subtoken, using_nodes in subtoken_to_using_nodes.items():\n subtoken_node_id += 1\n graph_node_labels[str(subtoken_node_id)] = subtoken\n new_edges.extend([(using_node_id, subtoken_node_id)\n for using_node_id in using_nodes])\n\n graph_dict['Edges'][USES_SUBTOKEN_EDGE_NAME] = new_edges\n\n\ndef _load_single_sample(raw_sample: Dict[str, Any],\n unsplittable_node_names: Set[str],\n graph_node_label_max_num_chars: int,\n max_variable_candidates: int = 5,\n add_self_loop_edges: bool = False):\n _add_per_subtoken_nodes(unsplittable_node_names, raw_sample['ContextGraph'])\n num_nodes = len(raw_sample['ContextGraph']['NodeLabels'])\n\n node_label_chars = np.zeros(shape=(num_nodes, graph_node_label_max_num_chars),\n dtype=np.uint8)\n for (node, label) in raw_sample['ContextGraph']['NodeLabels'].items():\n for (char_idx, label_char) in enumerate(label[:graph_node_label_max_num_chars].lower()):\n node_label_chars[int(node), char_idx] = ALPHABET_DICT.get(label_char, 1)\n node_label_chars_unique, node_label_chars_indices = np.unique(node_label_chars,\n axis=0,\n return_inverse=True)\n\n # Split edges according to edge_type and count their numbers:\n num_edge_types = len(PROGRAM_GRAPH_EDGES_TYPES_VOCAB)\n adjacency_lists = [np.zeros((0, 2), dtype=np.int32) for _ in range(num_edge_types)]\n num_incoming_edges_per_type = np.zeros((num_edge_types, num_nodes), dtype=np.uint16)\n raw_edges = raw_sample['ContextGraph']['Edges']\n for e_type, e_type_edges in raw_edges.items():\n if len(e_type_edges) > 0:\n e_type_bkwd = e_type + BACKWARD_EDGE_TYPE_NAME_SUFFIX\n e_type_idx = PROGRAM_GRAPH_EDGES_TYPES_VOCAB[e_type]\n e_type_bkwd_idx = PROGRAM_GRAPH_EDGES_TYPES_VOCAB[e_type_bkwd]\n\n fwd_edges = np.array(e_type_edges, dtype=np.int32)\n bkwd_edges = np.flip(fwd_edges, axis=1)\n\n adjacency_lists[e_type_idx] = fwd_edges\n adjacency_lists[e_type_bkwd_idx] = bkwd_edges\n num_incoming_edges_per_type[e_type_idx, :] = \\\n np.bincount(adjacency_lists[e_type_idx][:, 1], minlength=num_nodes)\n num_incoming_edges_per_type[e_type_bkwd_idx, :] = \\\n np.bincount(adjacency_lists[e_type_bkwd_idx][:, 1], minlength=num_nodes)\n\n if add_self_loop_edges:\n self_loop_edge_type_idx = PROGRAM_GRAPH_EDGES_TYPES_VOCAB[SELF_LOOP_EDGE_NAME]\n adjacency_lists[self_loop_edge_type_idx] = \\\n np.stack([np.arange(num_nodes), np.arange(num_nodes)], axis=1)\n num_incoming_edges_per_type[self_loop_edge_type_idx, :] = \\\n np.ones(shape=(num_nodes,))\n\n # VarMisuse-specific things: Reorder symbol candidates so that correct one is first.\n correct_candidate_id = None\n distractor_candidate_ids = [] # type: List[int]\n for candidate in raw_sample['SymbolCandidates']:\n if candidate['IsCorrect']:\n correct_candidate_id = candidate['SymbolDummyNode']\n else:\n distractor_candidate_ids.append(candidate['SymbolDummyNode'])\n assert correct_candidate_id is not None\n candidate_node_ids = [correct_candidate_id] + distractor_candidate_ids[:max_variable_candidates - 1]\n # Pad symbol candidates up to max_variable_candidates:\n num_scope_padding = max_variable_candidates - len(candidate_node_ids)\n candidate_node_ids_mask = [True] * len(candidate_node_ids) + [False] * num_scope_padding\n candidate_node_ids = candidate_node_ids + [0] * num_scope_padding\n\n return GraphSample(adjacency_lists=adjacency_lists,\n type_to_node_to_num_incoming_edges=num_incoming_edges_per_type,\n unique_labels_as_characters=node_label_chars_unique,\n node_labels_to_unique_labels=node_label_chars_indices,\n slot_node_id=raw_sample['SlotDummyNode'],\n variable_candidate_nodes=np.array(candidate_node_ids),\n variable_candidate_nodes_mask=np.array(candidate_node_ids_mask),\n )\n\n\ndef _data_loading_worker(path_queue: Queue,\n result_queue: Queue,\n unsplittable_node_names: Set[str],\n graph_node_label_max_num_chars: int,\n max_variable_candidates: int,\n add_self_loop_edges: bool,\n ) -> None:\n while True:\n next_path = path_queue.get()\n if next_path is None: # Our signal that all files have been processed\n path_queue.put(None) # Signal to the other workers\n result_queue.put(None) # Signal to the controller that we are done\n break\n\n # Read the file and push examples out as soon as we get them:\n for raw_sample in next_path.read_by_file_suffix():\n result_queue.put(_load_single_sample(raw_sample,\n unsplittable_node_names,\n graph_node_label_max_num_chars,\n max_variable_candidates,\n add_self_loop_edges,\n ))\n\n\ndef _load_data(paths: List[RichPath],\n unsplittable_node_names: Set[str],\n graph_node_label_max_num_chars: int,\n max_variable_candidates: int,\n add_self_loop_edges: bool,\n no_parallel: bool = False,\n ) -> Iterable[GraphSample]:\n if no_parallel:\n return [_load_single_sample(raw_sample, unsplittable_node_names, graph_node_label_max_num_chars,\n max_variable_candidates, add_self_loop_edges)\n for path in paths\n for raw_sample in path.read_by_file_suffix()]\n\n path_queue = Queue(maxsize=len(paths) + 1)\n result_queue = Queue()\n\n # Set up list of work to do:\n for path in paths:\n path_queue.put(path)\n path_queue.put(None) # Signal for the end of the queue\n\n # Set up workers:\n workers = []\n for _ in range(cpu_count()):\n workers.append(Process(target=_data_loading_worker,\n args=(path_queue,\n result_queue,\n unsplittable_node_names,\n graph_node_label_max_num_chars,\n max_variable_candidates,\n add_self_loop_edges,\n )))\n workers[-1].start()\n\n # Consume the data:\n num_workers_terminated = 0\n while num_workers_terminated < len(workers):\n parsed_sample = result_queue.get()\n if parsed_sample is None:\n num_workers_terminated += 1 # Worker signaled that it's done\n else:\n yield parsed_sample\n\n # Clean up the workers:\n for worker in workers:\n worker.join()\n\n\nclass VarMisuse_Task(Sparse_Graph_Task):\n @classmethod\n def default_params(cls):\n params = super().default_params()\n params.update({\n 'max_variable_candidates': 5,\n 'graph_node_label_max_num_chars': 19,\n 'graph_node_label_representation_size': 64,\n 'slot_score_via_linear_layer': True,\n 'loss_function': 'max-likelihood', # max-likelihood or max-margin\n 'max-margin_loss_margin': 0.2,\n 'out_layer_dropout_rate': 0.2,\n 'add_self_loop_edges': False,\n # 'max_num_data_files': 3,\n })\n return params\n\n @staticmethod\n def name() -> str:\n return \"VarMisuse\"\n\n @staticmethod\n def default_data_path() -> str:\n return \"data/varmisuse\"\n\n def __init__(self, params: Dict[str, Any]):\n super().__init__(params)\n\n # If required, add the self-loop edge type to the vocab:\n if params.get('add_self_loop_edges'):\n if SELF_LOOP_EDGE_NAME not in PROGRAM_GRAPH_EDGES_TYPES_VOCAB:\n PROGRAM_GRAPH_EDGES_TYPES_VOCAB[SELF_LOOP_EDGE_NAME] = \\\n len(PROGRAM_GRAPH_EDGES_TYPES_VOCAB)\n\n def get_metadata(self) -> Dict[str, Any]:\n metadata = super().get_metadata()\n return metadata\n\n def restore_from_metadata(self, metadata: Dict[str, Any]) -> None:\n super().restore_from_metadata(metadata)\n\n @property\n def num_edge_types(self) -> int:\n return len(PROGRAM_GRAPH_EDGES_TYPES_VOCAB)\n\n @property\n def initial_node_feature_size(self) -> int:\n return self.params['graph_node_label_representation_size']\n\n # -------------------- Data Loading --------------------\n def load_data(self, path: RichPath) -> None:\n # Note that as __load_data produces a generator, we explicitly force loading\n # (and caching) here:\n self._loaded_data[DataFold.TRAIN] = \\\n list(self.__load_data(path.join(\"graphs-train\"), DataFold.TRAIN))\n self._loaded_data[DataFold.VALIDATION] = \\\n list(self.__load_data(path.join(\"graphs-valid\"), DataFold.VALIDATION))\n\n def load_eval_data_from_path(self, path: RichPath) -> Iterable[Any]:\n if path.path == self.default_data_path():\n path = path.join(\"graphs-test\")\n return iter(self.__load_data(path, DataFold.TEST))\n\n def __load_data(self, data_dir: RichPath, data_fold: DataFold) -> Iterator[GraphSample]:\n all_data_files = data_dir.iterate_filtered_files_in_dir(\"*.gz\")\n\n max_num_files = self.params.get('max_num_data_files', None)\n if max_num_files is not None:\n all_data_files = sorted(all_data_files)[:max_num_files]\n else:\n all_data_files = list(all_data_files)\n print(\" Loading VarMisuse data from %s [%i data files].\" % (data_dir, len(all_data_files)))\n\n unsplittable_keywords = get_language_keywords('csharp')\n return _load_data(all_data_files,\n unsplittable_keywords,\n self.params['graph_node_label_max_num_chars'],\n self.params['max_variable_candidates'],\n self.params['add_self_loop_edges'])\n\n # -------------------- Model Construction --------------------\n def make_task_input_model(self,\n placeholders: Dict[str, tf.Tensor],\n model_ops: Dict[str, tf.Tensor],\n ) -> None:\n node_label_char_length = self.params['graph_node_label_max_num_chars']\n placeholders['unique_labels_as_characters'] = \\\n tf.placeholder(dtype=tf.int32, shape=[None, node_label_char_length], name='unique_labels_as_characters')\n placeholders['node_labels_to_unique_labels'] = \\\n tf.placeholder(dtype=tf.int32, shape=[None], name='node_labels_to_unique_labels')\n placeholders['adjacency_lists'] = \\\n [tf.placeholder(dtype=tf.int32, shape=[None, 2], name='adjacency_e%s' % e)\n for e in range(self.num_edge_types)]\n placeholders['type_to_num_incoming_edges'] = \\\n tf.placeholder(dtype=tf.float32, shape=[self.num_edge_types, None], name='type_to_num_incoming_edges')\n\n model_ops['initial_node_features'] = \\\n self.__get_node_label_charcnn_embeddings(placeholders['unique_labels_as_characters'],\n placeholders['node_labels_to_unique_labels'])\n model_ops['adjacency_lists'] = placeholders['adjacency_lists']\n model_ops['type_to_num_incoming_edges'] = placeholders['type_to_num_incoming_edges']\n\n def __get_node_label_charcnn_embeddings(self,\n unique_labels_as_characters: tf.Tensor,\n node_labels_to_unique_labels: tf.Tensor,\n ) -> tf.Tensor:\n \"\"\"\n Compute representation of node labels using a 2-layer character CNN.\n\n Args:\n unique_labels_as_characters: int32 tensor of shape [U, C]\n representing the unique (node) labels occurring in a\n batch, where U is the number of such labels and C the\n maximal number of characters.\n node_labels_to_unique_labels: int32 tensor of shape [V],\n mapping each node in the batch to one of the unique\n labels.\n\n Returns:\n float32 tensor of shape [V, D] representing embedded node\n label information about each node.\n \"\"\"\n label_embedding_size = self.params['graph_node_label_representation_size'] # D\n # U ~ num unique labels\n # C ~ num characters (self.params['graph_node_label_max_num_chars'])\n # A ~ num characters in alphabet\n unique_label_chars_one_hot = tf.one_hot(indices=unique_labels_as_characters,\n depth=len(ALPHABET),\n axis=-1) # Shape: [U, C, A]\n\n # Choose kernel sizes such that there is a single value at the end:\n char_conv_l1_kernel_size = 5\n char_conv_l2_kernel_size = \\\n self.params['graph_node_label_max_num_chars'] - 2 * (char_conv_l1_kernel_size - 1)\n\n char_conv_l1 = \\\n tf.keras.layers.Conv1D(filters=16,\n kernel_size=char_conv_l1_kernel_size,\n activation=tf.nn.leaky_relu,\n )(unique_label_chars_one_hot) # Shape: [U, C - (char_conv_l1_kernel_size - 1), 16]\n char_pool_l1 = \\\n tf.keras.layers.MaxPool1D(pool_size=char_conv_l1_kernel_size,\n strides=1,\n )(inputs=char_conv_l1) # Shape: [U, C - 2*(char_conv_l1_kernel_size - 1), 16]\n char_conv_l2 = \\\n tf.keras.layers.Conv1D(filters=label_embedding_size,\n kernel_size=char_conv_l2_kernel_size,\n activation=tf.nn.leaky_relu,\n )(char_pool_l1) # Shape: [U, 1, D]\n unique_label_representations = tf.squeeze(char_conv_l2, axis=1) # Shape: [U, D]\n node_label_representations = tf.gather(params=unique_label_representations,\n indices=node_labels_to_unique_labels)\n return node_label_representations\n\n def make_task_output_model(self,\n placeholders: Dict[str, tf.Tensor],\n model_ops: Dict[str, tf.Tensor],\n ) -> None:\n placeholders['slot_node_ids'] = \\\n tf.placeholder(dtype=tf.int32, shape=[None], name='slot_node_ids')\n placeholders['candidate_node_ids'] = \\\n tf.placeholder(dtype=tf.int32, shape=[None, None], name='candidate_node_ids')\n placeholders['candidate_node_ids_mask'] = \\\n tf.placeholder(dtype=tf.float32, shape=[None, None], name='candidate_node_ids_mask')\n placeholders['out_layer_dropout_rate'] = \\\n tf.placeholder_with_default(0.0, shape=[], name='out_layer_dropout_rate')\n\n final_node_repr_size = model_ops['final_node_representations'].shape.as_list()[-1]\n num_candidate_vars = self.params['max_variable_candidates']\n\n final_node_states = \\\n tf.nn.dropout(model_ops['final_node_representations'],\n keep_prob=placeholders['out_layer_dropout_rate']) # Shape: [V, D]\n\n # --- (1) Collect representation of slots and candidates:\n slot_representations = \\\n tf.gather(params=final_node_states, indices=placeholders['slot_node_ids']) # Shape: [G, D]\n # Make things fit into 1D gather:\n candidate_node_ids = tf.reshape(placeholders['candidate_node_ids'], shape=[-1])\n candidate_representations = \\\n tf.gather(params=final_node_states, indices=candidate_node_ids) # Shape: [G * Cands, D]\n candidate_representations = \\\n tf.reshape(candidate_representations,\n shape=[-1, num_candidate_vars, final_node_repr_size]) # Shape: [G, Cands, D]\n\n # --- (2) Compute match between final candidate representations and slot representation:\n slot_candidate_inner_product = \\\n tf.einsum('sd,scd->sc', slot_representations, candidate_representations) # Shape: [G, Cands]\n\n if self.params['slot_score_via_linear_layer']:\n repeated_slots = tf.tile(tf.expand_dims(slot_representations, axis=1),\n multiples=[1, num_candidate_vars, 1]) # Shape: [G, Cands, D]\n slot_cand_comb = tf.concat([candidate_representations,\n repeated_slots,\n tf.expand_dims(slot_candidate_inner_product, -1)],\n axis=2) # Shape: [G, Cands, 2*D + 1]\n logits = tf.keras.layers.Dense(units=1,\n use_bias=False,\n activation=None,\n name='slot_score_linear_layer'\n )(slot_cand_comb) # Shape: [G, Cands, 1]\n logits = tf.squeeze(logits, axis=-1) # Shape: [G, Cands]\n else:\n logits = slot_candidate_inner_product\n\n logits += (1.0 - placeholders['candidate_node_ids_mask']) * -BIG_NUMBER\n\n # --- (3) Compute loss & metrics:\n loss_function = self.params['loss_function']\n # Note that by convention, the first candidate is always the correct one:\n correct_choices = tf.zeros([tf.shape(logits)[0]], dtype=tf.int32)\n if loss_function == 'max-likelihood':\n per_graph_loss = \\\n tf.nn.sparse_softmax_cross_entropy_with_logits(labels=correct_choices, logits=logits)\n elif loss_function == 'max-margin':\n log_probs = tf.nn.log_softmax(logits)\n correct_log_prob = log_probs[:, 0]\n max_wrong_log_prob = tf.reduce_max(log_probs[:, 1:], axis=1)\n per_graph_loss = \\\n tf.nn.relu(max_wrong_log_prob - correct_log_prob + self.parameters['loss_margin'])\n else:\n raise Exception('Invalid loss function option: \"%s\"' % loss_function)\n\n prediction_is_correct = tf.equal(tf.argmax(tf.nn.softmax(logits), 1, output_type=tf.int32),\n correct_choices)\n accuracy = tf.reduce_mean(tf.cast(prediction_is_correct, tf.float32))\n\n tf.summary.scalar('accuracy', accuracy)\n model_ops['task_metrics'] = {\n 'loss': tf.reduce_mean(per_graph_loss),\n 'total_loss': tf.reduce_sum(per_graph_loss),\n 'accuracy': accuracy,\n 'num_correct_predictions': tf.reduce_sum(tf.cast(prediction_is_correct, tf.int32)),\n }\n\n # -------------------- Minibatching and training loop --------------------\n def make_minibatch_iterator(self,\n data: Iterable[Any],\n data_fold: DataFold,\n model_placeholders: Dict[str, tf.Tensor],\n max_nodes_per_batch: int) \\\n -> Iterable[MinibatchData]:\n if data_fold == DataFold.TRAIN:\n np.random.shuffle(data)\n\n if isinstance(data, Iterator):\n data_iter = data\n else:\n data_iter = iter(data)\n\n def init_raw_batch_data_holder() -> Dict[str, Any]:\n return {\n 'adj_lists': [[] for _ in range(self.num_edge_types)],\n 'type_to_num_in_edges': [],\n 'uniq_labels_as_chars': [],\n 'node_labels_to_uniq_labels': [],\n 'slot_node_ids': [],\n 'candidate_node_ids': [],\n 'candidate_node_ids_mask': [],\n 'num_graphs': 0,\n 'node_offset': 0,\n 'unique_label_offset': 0,\n }\n\n def finalise_batch_data(raw_batch_data: Dict[str, Any]) -> MinibatchData:\n batch_feed_dict = {\n model_placeholders['unique_labels_as_characters']: np.concatenate(raw_batch_data['uniq_labels_as_chars'], axis=0),\n model_placeholders['node_labels_to_unique_labels']: np.concatenate(raw_batch_data['node_labels_to_uniq_labels'], axis=0),\n model_placeholders['type_to_num_incoming_edges']: np.concatenate(raw_batch_data['type_to_num_in_edges'], axis=1),\n model_placeholders['slot_node_ids']: raw_batch_data['slot_node_ids'],\n model_placeholders['candidate_node_ids']: raw_batch_data['candidate_node_ids'],\n model_placeholders['candidate_node_ids_mask']: raw_batch_data['candidate_node_ids_mask'],\n }\n\n if data_fold == DataFold.TRAIN:\n model_placeholders['out_layer_dropout_rate'] = self.params['out_layer_dropout_rate']\n\n # Merge adjacency lists:\n num_edges = 0\n for i in range(self.num_edge_types):\n if len(raw_batch_data['adj_lists'][i]) > 0:\n adj_list = np.concatenate(raw_batch_data['adj_lists'][i])\n else:\n adj_list = np.zeros((0, 2), dtype=np.int32)\n num_edges += adj_list.shape[0]\n batch_feed_dict[model_placeholders['adjacency_lists'][i]] = adj_list\n\n return MinibatchData(feed_dict=batch_feed_dict,\n num_graphs=raw_batch_data['num_graphs'],\n num_nodes=raw_batch_data['node_offset'],\n num_edges=num_edges)\n\n try:\n cur_batch_data = init_raw_batch_data_holder()\n while True:\n cur_graph = next(data_iter)\n # We pack until we cannot fit more graphs in the batch, yield, and continue:\n if cur_batch_data['node_offset'] + len(cur_graph.node_labels_to_unique_labels) >= max_nodes_per_batch:\n yield finalise_batch_data(cur_batch_data)\n cur_batch_data = init_raw_batch_data_holder()\n\n # Graph structure:\n for i in range(self.num_edge_types):\n cur_batch_data['adj_lists'][i].append(cur_graph.adjacency_lists[i] + cur_batch_data['node_offset'])\n cur_batch_data['type_to_num_in_edges'].append(cur_graph.type_to_node_to_num_incoming_edges)\n\n # Node labels:\n cur_batch_data['uniq_labels_as_chars'].append(cur_graph.unique_labels_as_characters)\n cur_batch_data['node_labels_to_uniq_labels'].append(\n cur_graph.node_labels_to_unique_labels + cur_batch_data['unique_label_offset'])\n cur_batch_data['unique_label_offset'] += cur_graph.unique_labels_as_characters.shape[0]\n\n # VarMisuse task bits:\n cur_batch_data['slot_node_ids'].append(cur_graph.slot_node_id + cur_batch_data['node_offset'])\n cur_batch_data['candidate_node_ids'].append(cur_graph.variable_candidate_nodes + cur_batch_data['node_offset'])\n cur_batch_data['candidate_node_ids_mask'].append(cur_graph.variable_candidate_nodes_mask)\n\n # Finally, update the offset we use to shift things during batch construction:\n cur_batch_data['num_graphs'] += 1\n cur_batch_data['node_offset'] += len(cur_graph.node_labels_to_unique_labels)\n except StopIteration:\n # Final batch, yield only if non-empty:\n if cur_batch_data['num_graphs'] > 0:\n yield finalise_batch_data(cur_batch_data)\n\n def early_stopping_metric(self, task_metric_results: List[Dict[str, np.ndarray]], num_graphs: int) -> float:\n # Early stopping based on accuracy; as we are trying to minimize, negate it:\n acc = sum([m['num_correct_predictions'] for m in task_metric_results]) / float(num_graphs)\n return -acc\n\n def pretty_print_epoch_task_metrics(self, task_metric_results: List[Dict[str, np.ndarray]], num_graphs: int) -> str:\n acc = sum([m['num_correct_predictions'] for m in task_metric_results]) / float(num_graphs)\n return \"Accuracy: %.3f\" % (acc,)\n" ]
[ [ "tensorflow.nn.log_softmax", "tensorflow.reduce_sum", "tensorflow.cast", "numpy.concatenate", "tensorflow.summary.scalar", "numpy.unique", "numpy.arange", "tensorflow.placeholder_with_default", "tensorflow.squeeze", "tensorflow.gather", "numpy.zeros", "tensorflow.nn.dropout", "tensorflow.shape", "tensorflow.keras.layers.Dense", "tensorflow.placeholder", "tensorflow.nn.sparse_softmax_cross_entropy_with_logits", "numpy.array", "numpy.flip", "tensorflow.nn.relu", "tensorflow.reduce_max", "tensorflow.nn.softmax", "tensorflow.keras.layers.MaxPool1D", "tensorflow.reduce_mean", "tensorflow.keras.layers.Conv1D", "tensorflow.reshape", "tensorflow.expand_dims", "numpy.random.shuffle", "numpy.ones", "tensorflow.einsum", "numpy.bincount" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
Mehrad0711/oslo
[ "873d771a68bc380903947010da0b66f58f60e496" ]
[ "oslo/pytorch/kernel_fusion/cuda/fused_normalization.py" ]
[ "import numbers\nfrom typing import Optional, Sequence\n\nimport torch\nfrom torch.nn import functional as F\nfrom torch.nn import init\nfrom torch.nn.parameter import Parameter\n\nfrom oslo.pytorch.kernel_fusion.cuda import CUDA\n\n\ndef _get_autocast_dtypes() -> Sequence[torch.dtype]:\n if torch.cuda.is_bf16_supported():\n return [torch.half, torch.bfloat16]\n return [torch.half]\n\n\ndef _get_current_dtype(dtype: Optional[torch.dtype] = None) -> torch.dtype:\n if not torch.is_autocast_enabled():\n return torch.float or dtype\n else:\n return torch.get_autocast_gpu_dtype()\n\n\ndef _cast_if_autocast_enabled(*args):\n if not torch.is_autocast_enabled():\n return args\n else:\n return torch.cuda.amp.autocast_mode._cast(args, torch.get_autocast_gpu_dtype())\n\n\nclass FusedLayerNormAffineFunction(torch.autograd.Function):\n @staticmethod\n def forward(ctx, input, weight, bias, normalized_shape, eps):\n ctx.normalized_shape = normalized_shape\n ctx.eps = eps\n input_ = input.contiguous()\n weight_ = weight.contiguous()\n bias_ = bias.contiguous()\n output, mean, invvar = CUDA.layer_norm_forward_affine(\n input_, ctx.normalized_shape, weight_, bias_, ctx.eps\n )\n ctx.save_for_backward(input_, weight_, bias_, mean, invvar)\n return output\n\n @staticmethod\n def backward(ctx, grad_output):\n input_, weight_, bias_, mean, invvar = ctx.saved_tensors\n grad_input = grad_weight = grad_bias = None\n grad_input, grad_weight, grad_bias = CUDA.layer_norm_backward_affine(\n grad_output.contiguous(),\n mean,\n invvar,\n input_,\n ctx.normalized_shape,\n weight_,\n bias_,\n ctx.eps,\n )\n return grad_input, grad_weight, grad_bias, None, None\n\n\nclass FusedRMSNormAffineFunction(torch.autograd.Function):\n @staticmethod\n def forward(ctx, input, weight, normalized_shape, eps):\n ctx.normalized_shape = normalized_shape\n ctx.eps = eps\n input_ = input.contiguous()\n weight_ = weight.contiguous()\n output, invvar = CUDA.rms_norm_forward_affine(\n input_, ctx.normalized_shape, weight_, ctx.eps\n )\n ctx.save_for_backward(input_, weight_, invvar)\n return output\n\n @staticmethod\n def backward(ctx, grad_output):\n input_, weight_, invvar = ctx.saved_tensors\n grad_input = grad_weight = None\n grad_input, grad_weight = CUDA.rms_norm_backward_affine(\n grad_output.contiguous(),\n invvar,\n input_,\n ctx.normalized_shape,\n weight_,\n ctx.eps,\n )\n return grad_input, grad_weight, None, None\n\n\nclass FusedLayerNormAffineMixedDtypesFunction(FusedLayerNormAffineFunction):\n @staticmethod\n def forward(ctx, input, weight, bias, normalized_shape, eps):\n ctx.normalized_shape = normalized_shape\n ctx.eps = eps\n input_ = input.contiguous()\n weight_ = weight.contiguous()\n bias_ = bias.contiguous()\n output, mean, invvar = CUDA.layer_norm_forward_affine_mixed_dtypes(\n input_, ctx.normalized_shape, weight_, bias_, ctx.eps\n )\n ctx.save_for_backward(input_, weight_, bias_, mean, invvar)\n return output\n\n\nclass FusedRMSNormAffineMixedDtypesFunction(FusedRMSNormAffineFunction):\n @staticmethod\n def forward(ctx, input, weight, normalized_shape, eps):\n ctx.normalized_shape = normalized_shape\n ctx.eps = eps\n input_ = input.contiguous()\n weight_ = weight.contiguous()\n output, invvar = CUDA.rms_norm_forward_affine_mixed_dtypes(\n input_, ctx.normalized_shape, weight_, ctx.eps\n )\n\n ctx.save_for_backward(input_, weight_, invvar)\n return output\n\n\nclass FusedLayerNormFunction(torch.autograd.Function):\n @staticmethod\n def forward(ctx, input, normalized_shape, eps):\n ctx.normalized_shape = normalized_shape\n ctx.eps = eps\n input_ = input.contiguous()\n output, mean, invvar = CUDA.layer_norm_forward(\n input_, ctx.normalized_shape, ctx.eps\n )\n ctx.save_for_backward(input_, mean, invvar)\n return output\n\n @staticmethod\n def backward(ctx, grad_output):\n input_, mean, invvar = ctx.saved_tensors\n grad_input = None\n grad_input = CUDA.layer_norm_backward(\n grad_output.contiguous(),\n mean,\n invvar,\n input_,\n ctx.normalized_shape,\n ctx.eps,\n )\n return grad_input, None, None\n\n\nclass FusedRMSNormFunction(torch.autograd.Function):\n @staticmethod\n def forward(ctx, input, normalized_shape, eps):\n ctx.normalized_shape = normalized_shape\n ctx.eps = eps\n input_ = input.contiguous()\n output, invvar = CUDA.rms_norm_forward(input_, ctx.normalized_shape, ctx.eps)\n ctx.save_for_backward(input_, invvar)\n return output\n\n @staticmethod\n def backward(ctx, grad_output):\n input_, invvar = ctx.saved_tensors\n grad_input = None\n grad_input = CUDA.rms_norm_backward(\n grad_output.contiguous(), invvar, input_, ctx.normalized_shape, ctx.eps\n )\n return grad_input, None, None\n\n\ndef fused_layer_norm_affine(input, weight, bias, normalized_shape, eps=1e-6):\n args = _cast_if_autocast_enabled(input, weight, bias, normalized_shape, eps)\n with torch.cuda.amp.autocast(enabled=False):\n return FusedLayerNormAffineFunction.apply(*args)\n\n\ndef fused_layer_norm(input, normalized_shape, eps=1e-6):\n args = _cast_if_autocast_enabled(input, normalized_shape, eps)\n with torch.cuda.amp.autocast(enabled=False):\n return FusedLayerNormFunction.apply(*args)\n\n\ndef mixed_dtype_fused_layer_norm_affine(\n input, weight, bias, normalized_shape, eps=1e-6\n):\n args = _cast_if_autocast_enabled(input, weight, bias, normalized_shape, eps)\n with torch.cuda.amp.autocast(enabled=False):\n return FusedLayerNormAffineMixedDtypesFunction.apply(*args)\n\n\ndef fused_rms_norm_affine(input, weight, normalized_shape, eps=1e-6):\n args = _cast_if_autocast_enabled(input, weight, normalized_shape, eps)\n with torch.cuda.amp.autocast(enabled=False):\n return FusedRMSNormAffineFunction.apply(*args)\n\n\ndef fused_rms_norm(input, normalized_shape, eps=1e-6):\n args = _cast_if_autocast_enabled(input, normalized_shape, eps)\n with torch.cuda.amp.autocast(enabled=False):\n return FusedRMSNormFunction.apply(*args)\n\n\ndef mixed_dtype_fused_rms_norm_affine(input, weight, normalized_shape, eps=1e-6):\n args = _cast_if_autocast_enabled(input, weight, normalized_shape, eps)\n with torch.cuda.amp.autocast(enabled=False):\n return FusedRMSNormAffineMixedDtypesFunction.apply(*args)\n\n\nclass FusedLayerNorm(torch.nn.Module):\n r\"\"\"Applies Layer Normalization over a mini-batch of inputs as described in\n the paper `Layer Normalization`_ .\n Currently only runs on cuda() tensors.\n .. math::\n y = \\frac{x - \\mathrm{E}[x]}{ \\sqrt{\\mathrm{Var}[x] + \\epsilon}} * \\gamma + \\beta\n The mean and standard-deviation are calculated separately over the last\n certain number dimensions which have to be of the shape specified by\n :attr:`normalized_shape`.\n :math:`\\gamma` and :math:`\\beta` are learnable affine transform parameters of\n :attr:`normalized_shape` if :attr:`elementwise_affine` is ``True``.\n .. note::\n Unlike Batch Normalization and Instance Normalization, which applies\n scalar scale and bias for each entire channel/plane with the\n :attr:`affine` option, Layer Normalization applies per-element scale and\n bias with :attr:`elementwise_affine`.\n This layer uses statistics computed from input data in both training and\n evaluation modes.\n Args:\n normalized_shape (int or list or torch.Size): input shape from an expected input\n of size\n .. math::\n [* \\times \\text{normalized}\\_\\text{shape}[0] \\times \\text{normalized}\\_\\text{shape}[1]\n \\times \\ldots \\times \\text{normalized}\\_\\text{shape}[-1]]\n If a single integer is used, it is treated as a singleton list, and this module will\n normalize over the last dimension which is expected to be of that specific size.\n eps: a value added to the denominator for numerical stability. Default: 1e-5\n elementwise_affine: a boolean value that when set to ``True``, this module\n has learnable per-element affine parameters initialized to ones (for weights)\n and zeros (for biases). Default: ``True``.\n Shape:\n - Input: :math:`(N, *)`\n - Output: :math:`(N, *)` (same shape as input)\n Examples::\n >>> input = torch.randn(20, 5, 10, 10)\n >>> # With Learnable Parameters\n >>> m = apex.normalization.FusedLayerNorm(input.size()[1:])\n >>> # Without Learnable Parameters\n >>> m = apex.normalization.FusedLayerNorm(input.size()[1:], elementwise_affine=False)\n >>> # Normalize over last two dimensions\n >>> m = apex.normalization.FusedLayerNorm([10, 10])\n >>> # Normalize over last dimension of size 10\n >>> m = apex.normalization.FusedLayerNorm(10)\n >>> # Activating the module\n >>> output = m(input)\n .. _`Layer Normalization`: https://arxiv.org/abs/1607.06450\n \"\"\"\n\n def __init__(self, normalized_shape, eps=1e-5, elementwise_affine=True):\n super().__init__()\n if isinstance(normalized_shape, numbers.Integral):\n normalized_shape = (normalized_shape,)\n self.normalized_shape = torch.Size(normalized_shape)\n self.eps = eps\n self.elementwise_affine = elementwise_affine\n if self.elementwise_affine:\n self.weight = Parameter(torch.Tensor(*normalized_shape))\n self.bias = Parameter(torch.Tensor(*normalized_shape))\n else:\n self.register_parameter(\"weight\", None)\n self.register_parameter(\"bias\", None)\n self.reset_parameters()\n\n def reset_parameters(self):\n if self.elementwise_affine:\n init.ones_(self.weight)\n init.zeros_(self.bias)\n\n def forward(self, input):\n if not input.is_cuda:\n return F.layer_norm(\n input, self.normalized_shape, self.weight, self.bias, self.eps\n )\n if self.elementwise_affine:\n return fused_layer_norm_affine(\n input, self.weight, self.bias, self.normalized_shape, self.eps\n )\n else:\n return fused_layer_norm(input, self.normalized_shape, self.eps)\n\n def extra_repr(self):\n return (\n \"{normalized_shape}, eps={eps}, \"\n \"elementwise_affine={elementwise_affine}\".format(**self.__dict__)\n )\n\n\nclass FusedRMSNorm(torch.nn.Module):\n r\"\"\"Applies RMS Normalization over a mini-batch of inputs\n Currently only runs on cuda() tensors.\n .. math::\n y = \\frac{x}{\\mathrm{RMS}[x]} * \\gamma\n The root-mean-square is calculated separately over the last\n certain number dimensions which have to be of the shape specified by\n :attr:`normalized_shape`.\n :math:`\\gamma` is a learnable affine transform parameter of\n :attr:`normalized_shape` if :attr:`elementwise_affine` is ``True``.\n `epsilon` is added to the mean-square, then the root of the sum is taken.\n .. note::\n Unlike Batch Normalization and Instance Normalization, which applies\n scalar scale and bias for each entire channel/plane with the\n :attr:`affine` option, RMS Normalization applies per-element scale\n with :attr:`elementwise_affine`.\n This layer uses statistics computed from input data in both training and\n evaluation modes.\n Args:\n normalized_shape (int or list or torch.Size): input shape from an expected input\n of size\n .. math::\n [* \\times \\text{normalized}\\_\\text{shape}[0] \\times \\text{normalized}\\_\\text{shape}[1]\n \\times \\ldots \\times \\text{normalized}\\_\\text{shape}[-1]]\n If a single integer is used, it is treated as a singleton list, and this module will\n normalize over the last dimension which is expected to be of that specific size.\n eps: a value added to the denominator for numerical stability. Default: 1e-5\n elementwise_affine: a boolean value that when set to ``True``, this module\n has learnable per-element affine parameters initialized to ones (for weights)\n and zeros (for biases). Default: ``True``.\n Shape:\n - Input: :math:`(N, *)`\n - Output: :math:`(N, *)` (same shape as input)\n Examples::\n >>> input = torch.randn(20, 5, 10, 10)\n >>> # With Learnable Parameters\n >>> m = apex.normalization.FusedRMSNorm(input.size()[1:])\n >>> # Without Learnable Parameters\n >>> m = apex.normalization.FusedRMSNorm(input.size()[1:], elementwise_affine=False)\n >>> # Normalize over last two dimensions\n >>> m = apex.normalization.FusedRMSNorm([10, 10])\n >>> # Normalize over last dimension of size 10\n >>> m = apex.normalization.FusedRMSNorm(10)\n >>> # Activating the module\n >>> output = m(input)\n .. _`Root Mean Square Layer Normalization`: https://arxiv.org/pdf/1910.07467.pdf\n \"\"\"\n\n def __init__(self, normalized_shape, eps=1e-5, elementwise_affine=True):\n super().__init__()\n if isinstance(normalized_shape, numbers.Integral):\n normalized_shape = (normalized_shape,)\n self.normalized_shape = torch.Size(normalized_shape)\n self.eps = eps\n self.elementwise_affine = elementwise_affine\n if self.elementwise_affine:\n self.weight = Parameter(torch.Tensor(*normalized_shape))\n else:\n self.register_parameter(\"weight\", None)\n self.reset_parameters()\n\n def reset_parameters(self):\n if self.elementwise_affine:\n init.ones_(self.weight)\n\n def manual_rms_norm(self, input, normalized_shape, weight, eps):\n # layer norm should always be calculated in float32\n dims = tuple(i for i in range(-1, -len(normalized_shape) - 1, -1))\n variance = input.to(torch.float32).pow(2).mean(dims, keepdim=True)\n input = input * torch.rsqrt(variance + eps)\n\n if weight is None:\n return input\n\n # convert into half-precision if necessary\n if weight.dtype in [torch.float16, torch.bfloat16]:\n input = input.to(self.weight.dtype)\n\n return weight * input\n\n def forward(self, input):\n if not input.is_cuda:\n return self.manual_rms_norm(\n input, self.normalized_shape, self.weight, self.eps\n )\n\n if self.elementwise_affine:\n return fused_rms_norm_affine(\n input, self.weight, self.normalized_shape, self.eps\n )\n else:\n return fused_rms_norm(input, self.normalized_shape, self.eps)\n\n def extra_repr(self):\n return (\n \"{normalized_shape}, eps={eps}, \"\n \"elementwise_affine={elementwise_affine}\".format(**self.__dict__)\n )\n\n\n# NOTE (mkozuki): Why \"mixed\"?\n# MixedFusedLayerNorm differs from FusedLayerNorm in that this layer norm uses parameter's dtype\n# as output tensor's dtype while FusedLayerNorm uses input tensor's dtype for output tensor's dtype.\n# See: `layer_norm_affine` and `layer_norm_affine_mixed_dtypes` in \"csrc/layer_norm_cuda.cpp\"\nclass MixedFusedLayerNorm(FusedLayerNorm):\n def __init__(self, normalized_shape, eps=1e-5, **kwargs):\n if \"elementwise_affine\" in kwargs:\n import warnings\n\n warnings.warn(\n \"MixedFusedLayerNorm does not support `elementwise_affine` argument\"\n )\n elementwise_affine = kwargs.pop(\"elementwise_affine\")\n if not elementwise_affine:\n raise RuntimeError(\n \"MixedFusedLayerNorm does not support `elementwise_affine = False`\"\n )\n\n super().__init__(\n normalized_shape=normalized_shape, eps=eps, elementwise_affine=True\n )\n\n def forward(self, input: torch.Tensor):\n # NOTE (mkozuki): CPU path is here mainly for unittest sake.\n if not input.is_cuda:\n return F.layer_norm(\n input, self.normalized_shape, self.weight, self.bias, self.eps\n )\n return mixed_dtype_fused_layer_norm_affine(\n input, self.weight, self.bias, self.normalized_shape, self.eps\n )\n\n\n# Reference implementation from Huggingface\n\n\n# MixedFusedLayerNorm differs from FusedLayerNorm in that this layer norm uses parameter's dtype\n# as output tensor's dtype while FusedLayerNorm uses input tensor's dtype for output tensor's dtype.\n# See: `layer_norm_affine` and `layer_norm_affine_mixed_dtypes` in \"csrc/layer_norm_cuda.cpp\"\nclass MixedFusedRMSNorm(FusedRMSNorm):\n def __init__(self, normalized_shape, eps=1e-5, **kwargs):\n if \"elementwise_affine\" in kwargs:\n import warnings\n\n warnings.warn(\n \"MixedFusedRMSNorm does not support `elementwise_affine` argument\"\n )\n elementwise_affine = kwargs.pop(\"elementwise_affine\")\n if not elementwise_affine:\n raise RuntimeError(\n \"MixedFusedRMSNorm does not support `elementwise_affine = False`\"\n )\n\n super().__init__(\n normalized_shape=normalized_shape, eps=eps, elementwise_affine=True\n )\n\n def manual_rms_norm(self, input, normalized_shape, weight, eps):\n # layer norm should always be calculated in float32\n dims = tuple(i for i in range(-1, -len(normalized_shape) - 1, -1))\n variance = input.to(torch.float32).pow(2).mean(dims, keepdim=True)\n input = input * torch.rsqrt(variance + eps)\n\n if weight is None:\n return input\n\n # convert into half-precision if necessary\n if weight.dtype in [torch.float16, torch.bfloat16]:\n input = input.to(self.weight.dtype)\n\n return weight * input\n\n def forward(self, input: torch.Tensor):\n # NOTE (mkozuki): CPU path is here mainly for unittest sake.\n # TODO Manual RMS Norm Implementation Here\n if not input.is_cuda:\n return self.manual_rms_norm(\n input, self.normalized_shape, self.weight, self.eps\n )\n return mixed_dtype_fused_rms_norm_affine(\n input, self.weight, self.normalized_shape, self.eps\n )\n" ]
[ [ "torch.nn.functional.layer_norm", "torch.Size", "torch.get_autocast_gpu_dtype", "torch.Tensor", "torch.cuda.amp.autocast", "torch.nn.init.ones_", "torch.is_autocast_enabled", "torch.rsqrt", "torch.nn.init.zeros_", "torch.cuda.is_bf16_supported" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
DataCanvasIO/YLearn
[ "d65b5afb83deed154c710de9096317165d95014a" ]
[ "tests/metalearner_test.py" ]
[ "from itertools import product\n\nimport pytest\nfrom sklearn import clone\nfrom sklearn.ensemble import GradientBoostingRegressor\nfrom sklearn.linear_model import LinearRegression\n\nfrom ylearn.estimator_model.meta_learner import SLearner, TLearner, XLearner\nfrom . import _dgp\nfrom ._common import validate_leaner\n\n_test_settings = {\n # data_generator: model\n _dgp.generate_data_x1b_y1: GradientBoostingRegressor(),\n _dgp.generate_data_x1b_y2: LinearRegression(),\n _dgp.generate_data_x1m_y1: GradientBoostingRegressor(),\n _dgp.generate_data_x1b_y1_w5v0: GradientBoostingRegressor(),\n _dgp.generate_data_x1b_y2_w5v0: LinearRegression(),\n _dgp.generate_data_x1m_y1_w5v0: GradientBoostingRegressor(),\n}\n\n_test_settings_x2b = {\n # data_generator: model\n _dgp.generate_data_x2b_y1: GradientBoostingRegressor(),\n _dgp.generate_data_x2b_y2: LinearRegression(),\n _dgp.generate_data_x2b_y1_w5v0: GradientBoostingRegressor(),\n _dgp.generate_data_x2b_y2_w5v0: LinearRegression(),\n # _dgp.generate_data_x2b_y2_w5v0: MultiTaskLasso(),\n _dgp.generate_data_x2mb_y1: GradientBoostingRegressor(),\n}\n\n\[email protected]('dg,combined', product(_test_settings.keys(), [True, False]))\ndef test_sleaner(dg, combined):\n model = _test_settings[dg]\n validate_leaner(dg, SLearner(model=clone(model)),\n fit_kwargs=dict(combined_treatment=combined),\n check_effect=dg.__name__.find('y2') < 0,\n )\n\n\[email protected]('dg,combined', product(_test_settings.keys(), [True, False]))\ndef test_sleaner_with_treat(dg, combined):\n model = _test_settings[dg]\n validate_leaner(dg, SLearner(model=clone(model)),\n fit_kwargs=dict(combined_treatment=combined, treat=1, control=0),\n check_effect=dg.__name__.find('y2') < 0,\n )\n\n\[email protected]('dg,combined', product(_test_settings_x2b.keys(), [True, False]))\ndef test_sleaner_x2b(dg, combined):\n model = _test_settings_x2b[dg]\n validate_leaner(dg, SLearner(model=clone(model)),\n fit_kwargs=dict(combined_treatment=combined, treat=[1, 1], control=[0, 0]),\n check_effect=dg.__name__.find('y2') < 0,\n )\n\n\ndef test_sleaner_with_treat_control():\n dg = _dgp.generate_data_x2b_y1\n model = GradientBoostingRegressor()\n validate_leaner(dg,\n TLearner(model=clone(model)),\n fit_kwargs=dict(combined_treatment=True, treat=[1, 1], control=[0, 0]),\n )\n\n\[email protected]('dg,combined', product(_test_settings.keys(), [True, False]))\ndef test_tlearner(dg, combined):\n model = _test_settings[dg]\n validate_leaner(dg, TLearner(model=clone(model)),\n fit_kwargs=dict(combined_treatment=combined),\n check_effect=dg.__name__.find('y2') < 0,\n )\n\n\[email protected]('dg,combined', product(_test_settings.keys(), [True, False]))\ndef test_tlearner_with_treat(dg, combined):\n model = _test_settings[dg]\n validate_leaner(dg, TLearner(model=clone(model)),\n fit_kwargs=dict(combined_treatment=combined, treat=1, control=0),\n check_effect=dg.__name__.find('y2') < 0,\n )\n\n\[email protected]('dg,combined', product(_test_settings_x2b.keys(), [True, False]))\ndef test_tlearner(dg, combined):\n model = _test_settings_x2b[dg]\n validate_leaner(dg, TLearner(model=clone(model)),\n fit_kwargs=dict(combined_treatment=combined, treat=[1, 1], control=[0, 0]),\n check_effect=dg.__name__.find('y2') < 0,\n )\n\n\[email protected]('dg,combined', product(_test_settings.keys(), [True, False]))\ndef test_xleaner(dg, combined):\n model = _test_settings[dg]\n validate_leaner(dg, XLearner(model=clone(model)),\n fit_kwargs=dict(combined_treatment=combined),\n check_effect=dg.__name__.find('y2') < 0,\n )\n\n\[email protected]('dg,combined', product(_test_settings.keys(), [True, False]))\ndef test_xleaner_with_treat(dg, combined):\n model = _test_settings[dg]\n validate_leaner(dg, XLearner(model=clone(model)),\n fit_kwargs=dict(combined_treatment=combined, treat=1, control=0),\n check_effect=dg.__name__.find('y2') < 0,\n )\n\n\[email protected]('dg,combined', product(_test_settings_x2b.keys(), [True, False]))\ndef test_xleaner_x2b(dg, combined):\n model = _test_settings_x2b[dg]\n validate_leaner(dg, XLearner(model=clone(model)),\n fit_kwargs=dict(combined_treatment=combined, treat=[1, 1], control=[0, 0]),\n check_effect=dg.__name__.find('y2') < 0,\n )\n" ]
[ [ "sklearn.clone", "sklearn.linear_model.LinearRegression", "sklearn.ensemble.GradientBoostingRegressor" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
stxxllbu/CS224n-winter-together
[ "eae158ed8e88dc7c8638e25bac4c4fc8eeddcc8c", "eae158ed8e88dc7c8638e25bac4c4fc8eeddcc8c" ]
[ "Assignments/assignment4/BobOfRivia/run.py", "Assignments/assignment5/Herais/nmt_model.py" ]
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nCS224N 2019-20: Homework 4\nrun.py: Run Script for Simple NMT Model\nPencheng Yin <[email protected]>\nSahil Chopra <[email protected]>\nVera Lin <[email protected]>\n\nUsage:\n run.py train --train-src=<file> --train-tgt=<file> --dev-src=<file> --dev-tgt=<file> --vocab=<file> [options]\n run.py decode [options] MODEL_PATH TEST_SOURCE_FILE OUTPUT_FILE\n run.py decode [options] MODEL_PATH TEST_SOURCE_FILE TEST_TARGET_FILE OUTPUT_FILE\n\nOptions:\n -h --help show this screen.\n --cuda use GPU\n --train-src=<file> train source file\n --train-tgt=<file> train target file\n --dev-src=<file> dev source file\n --dev-tgt=<file> dev target file\n --vocab=<file> vocab file\n --seed=<int> seed [default: 0]\n --batch-size=<int> batch size [default: 32]\n --embed-size=<int> embedding size [default: 256]\n --hidden-size=<int> hidden size [default: 256]\n --clip-grad=<float> gradient clipping [default: 5.0]\n --log-every=<int> log every [default: 10]\n --max-epoch=<int> max epoch [default: 30]\n --input-feed use input feeding\n --patience=<int> wait for how many iterations to decay learning rate [default: 5]\n --max-num-trial=<int> terminate training after how many trials [default: 5]\n --lr-decay=<float> learning rate decay [default: 0.5]\n --beam-size=<int> beam size [default: 5]\n --sample-size=<int> sample size [default: 5]\n --lr=<float> learning rate [default: 0.001]\n --uniform-init=<float> uniformly initialize all parameters [default: 0.1]\n --save-to=<file> model save path [default: model.bin]\n --valid-niter=<int> perform validation after how many iterations [default: 2000]\n --dropout=<float> dropout [default: 0.3]\n --max-decoding-time-step=<int> maximum number of decoding time steps [default: 70]\n\"\"\"\nimport math\nimport sys\nimport pickle\nimport time\n\n\nfrom docopt import docopt\nfrom nltk.translate.bleu_score import corpus_bleu, sentence_bleu, SmoothingFunction\nfrom nmt_model import Hypothesis, NMT\nimport numpy as np\nfrom typing import List, Tuple, Dict, Set, Union\nfrom tqdm import tqdm\nfrom utils import read_corpus, batch_iter\nfrom vocab import Vocab, VocabEntry\n\nimport torch\nimport torch.nn.utils\n\n\ndef evaluate_ppl(model, dev_data, batch_size=32):\n \"\"\" Evaluate perplexity on dev sentences\n @param model (NMT): NMT Model\n @param dev_data (list of (src_sent, tgt_sent)): list of tuples containing source and target sentence\n @param batch_size (batch size)\n @returns ppl (perplixty on dev sentences)\n \"\"\"\n was_training = model.training\n model.eval()\n\n cum_loss = 0.\n cum_tgt_words = 0.\n\n # no_grad() signals backend to throw away all gradients\n with torch.no_grad():\n for src_sents, tgt_sents in batch_iter(dev_data, batch_size):\n loss = -model(src_sents, tgt_sents).sum()\n\n cum_loss += loss.item()\n tgt_word_num_to_predict = sum(len(s[1:]) for s in tgt_sents) # omitting leading `<s>`\n cum_tgt_words += tgt_word_num_to_predict\n\n ppl = np.exp(cum_loss / cum_tgt_words)\n\n if was_training:\n model.train()\n\n return ppl\n\n\ndef compute_corpus_level_bleu_score(references: List[List[str]], hypotheses: List[Hypothesis]) -> float:\n \"\"\" Given decoding results and reference sentences, compute corpus-level BLEU score.\n @param references (List[List[str]]): a list of gold-standard reference target sentences\n @param hypotheses (List[Hypothesis]): a list of hypotheses, one for each reference\n @returns bleu_score: corpus-level BLEU score\n \"\"\"\n if references[0][0] == '<s>':\n references = [ref[1:-1] for ref in references]\n bleu_score = corpus_bleu([[ref] for ref in references],\n [hyp.value for hyp in hypotheses])\n return bleu_score\n\n\ndef train(args: Dict):\n \"\"\" Train the NMT Model.\n @param args (Dict): args from cmd line\n \"\"\"\n # args = {\n # '--train-src':'./en_es_data/train.es',\n # '--train-tgt':'./en_es_data/train.en',\n # '--dev-src':'./en_es_data/dev.es',\n # '--dev-tgt':'./en_es_data/dev.en',\n # '--vocab':'vocab.json'\n # }\n\n train_data_src = read_corpus(args['--train-src'], source='src')\n train_data_tgt = read_corpus(args['--train-tgt'], source='tgt')\n\n dev_data_src = read_corpus(args['--dev-src'], source='src')\n dev_data_tgt = read_corpus(args['--dev-tgt'], source='tgt')\n\n train_data = list(zip(train_data_src, train_data_tgt))\n dev_data = list(zip(dev_data_src, dev_data_tgt))\n\n train_batch_size = int(args['--batch-size'])\n clip_grad = float(args['--clip-grad'])\n valid_niter = int(args['--valid-niter'])\n log_every = int(args['--log-every'])\n model_save_path = args['--save-to']\n\n vocab = Vocab.load(args['--vocab'])\n\n model = NMT(embed_size=int(args['--embed-size']),\n hidden_size=int(args['--hidden-size']),\n dropout_rate=float(args['--dropout']),\n vocab=vocab)\n model.train()\n\n uniform_init = float(args['--uniform-init'])\n if np.abs(uniform_init) > 0.:\n print('uniformly initialize parameters [-%f, +%f]' % (uniform_init, uniform_init), file=sys.stderr)\n for p in model.parameters():\n p.data.uniform_(-uniform_init, uniform_init)\n\n vocab_mask = torch.ones(len(vocab.tgt))\n vocab_mask[vocab.tgt['<pad>']] = 0\n\n device = torch.device(\"cuda:0\" if args['--cuda'] else \"cpu\")\n print('use device: %s' % device, file=sys.stderr)\n\n model = model.to(device)\n\n optimizer = torch.optim.Adam(model.parameters(), lr=float(args['--lr']))\n\n num_trial = 0\n train_iter = patience = cum_loss = report_loss = cum_tgt_words = report_tgt_words = 0\n cum_examples = report_examples = epoch = valid_num = 0\n hist_valid_scores = []\n train_time = begin_time = time.time()\n print('begin Maximum Likelihood training')\n\n while True:\n epoch += 1\n\n for src_sents, tgt_sents in batch_iter(train_data, batch_size=train_batch_size, shuffle=True):\n train_iter += 1\n\n optimizer.zero_grad()\n\n batch_size = len(src_sents)\n\n example_losses = -model(src_sents, tgt_sents) # (batch_size,)\n batch_loss = example_losses.sum()\n loss = batch_loss / batch_size\n\n loss.backward()\n\n # clip gradient\n grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), clip_grad)\n\n optimizer.step()\n\n batch_losses_val = batch_loss.item()\n report_loss += batch_losses_val\n cum_loss += batch_losses_val\n\n tgt_words_num_to_predict = sum(len(s[1:]) for s in tgt_sents) # omitting leading `<s>`\n report_tgt_words += tgt_words_num_to_predict\n cum_tgt_words += tgt_words_num_to_predict\n report_examples += batch_size\n cum_examples += batch_size\n\n if train_iter % log_every == 0:\n print('epoch %d, iter %d, avg. loss %.2f, avg. ppl %.2f ' \\\n 'cum. examples %d, speed %.2f words/sec, time elapsed %.2f sec' % (epoch, train_iter,\n report_loss / report_examples,\n math.exp(report_loss / report_tgt_words),\n cum_examples,\n report_tgt_words / (time.time() - train_time),\n time.time() - begin_time), file=sys.stderr)\n\n train_time = time.time()\n report_loss = report_tgt_words = report_examples = 0.\n\n # perform validation\n if train_iter % valid_niter == 0:\n print('epoch %d, iter %d, cum. loss %.2f, cum. ppl %.2f cum. examples %d' % (epoch, train_iter,\n cum_loss / cum_examples,\n np.exp(cum_loss / cum_tgt_words),\n cum_examples), file=sys.stderr)\n\n cum_loss = cum_examples = cum_tgt_words = 0.\n valid_num += 1\n\n print('begin validation ...', file=sys.stderr)\n\n # compute dev. ppl and bleu\n dev_ppl = evaluate_ppl(model, dev_data, batch_size=128) # dev batch size can be a bit larger\n valid_metric = -dev_ppl\n\n print('validation: iter %d, dev. ppl %f' % (train_iter, dev_ppl), file=sys.stderr)\n\n is_better = len(hist_valid_scores) == 0 or valid_metric > max(hist_valid_scores)\n hist_valid_scores.append(valid_metric)\n\n if is_better:\n patience = 0\n print('save currently the best model to [%s]' % model_save_path, file=sys.stderr)\n model.save(model_save_path)\n\n # also save the optimizers' state\n torch.save(optimizer.state_dict(), model_save_path + '.optim')\n elif patience < int(args['--patience']):\n patience += 1\n print('hit patience %d' % patience, file=sys.stderr)\n\n if patience == int(args['--patience']):\n num_trial += 1\n print('hit #%d trial' % num_trial, file=sys.stderr)\n if num_trial == int(args['--max-num-trial']):\n print('early stop!', file=sys.stderr)\n exit(0)\n\n # decay lr, and restore from previously best checkpoint\n lr = optimizer.param_groups[0]['lr'] * float(args['--lr-decay'])\n print('load previously best model and decay learning rate to %f' % lr, file=sys.stderr)\n\n # load model\n params = torch.load(model_save_path, map_location=lambda storage, loc: storage)\n model.load_state_dict(params['state_dict'])\n model = model.to(device)\n\n print('restore parameters of the optimizers', file=sys.stderr)\n optimizer.load_state_dict(torch.load(model_save_path + '.optim'))\n\n # set new lr\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n\n # reset patience\n patience = 0\n\n if epoch == int(args['--max-epoch']):\n print('reached maximum number of epochs!', file=sys.stderr)\n exit(0)\n\n\ndef decode(args: Dict[str, str]):\n \"\"\" Performs decoding on a test set, and save the best-scoring decoding results.\n If the target gold-standard sentences are given, the function also computes\n corpus-level BLEU score.\n @param args (Dict): args from cmd line\n \"\"\"\n\n print(\"load test source sentences from [{}]\".format(args['TEST_SOURCE_FILE']), file=sys.stderr)\n test_data_src = read_corpus(args['TEST_SOURCE_FILE'], source='src')\n if args['TEST_TARGET_FILE']:\n print(\"load test target sentences from [{}]\".format(args['TEST_TARGET_FILE']), file=sys.stderr)\n test_data_tgt = read_corpus(args['TEST_TARGET_FILE'], source='tgt')\n\n print(\"load model from {}\".format(args['MODEL_PATH']), file=sys.stderr)\n model = NMT.load(args['MODEL_PATH'])\n\n if args['--cuda']:\n model = model.to(torch.device(\"cuda:0\"))\n\n hypotheses = beam_search(model, test_data_src,\n beam_size=int(args['--beam-size']),\n max_decoding_time_step=int(args['--max-decoding-time-step']))\n\n if args['TEST_TARGET_FILE']:\n top_hypotheses = [hyps[0] for hyps in hypotheses]\n bleu_score = compute_corpus_level_bleu_score(test_data_tgt, top_hypotheses)\n print('Corpus BLEU: {}'.format(bleu_score * 100), file=sys.stderr)\n\n with open(args['OUTPUT_FILE'], 'w') as f:\n for src_sent, hyps in zip(test_data_src, hypotheses):\n top_hyp = hyps[0]\n hyp_sent = ' '.join(top_hyp.value)\n f.write(hyp_sent + '\\n')\n\n\ndef beam_search(model: NMT, test_data_src: List[List[str]], beam_size: int, max_decoding_time_step: int) -> List[List[Hypothesis]]:\n \"\"\" Run beam search to construct hypotheses for a list of src-language sentences.\n @param model (NMT): NMT Model\n @param test_data_src (List[List[str]]): List of sentences (words) in source language, from test set.\n @param beam_size (int): beam_size (# of hypotheses to hold for a translation at every step)\n @param max_decoding_time_step (int): maximum sentence length that Beam search can produce\n @returns hypotheses (List[List[Hypothesis]]): List of Hypothesis translations for every source sentence.\n \"\"\"\n was_training = model.training\n model.eval()\n\n hypotheses = []\n with torch.no_grad():\n for src_sent in tqdm(test_data_src, desc='Decoding', file=sys.stdout):\n example_hyps = model.beam_search(src_sent, beam_size=beam_size, max_decoding_time_step=max_decoding_time_step)\n\n hypotheses.append(example_hyps)\n\n if was_training: model.train(was_training)\n\n return hypotheses\n\n\ndef main():\n \"\"\" Main func.\n \"\"\"\n\n args = docopt(__doc__)\n\n # Check pytorch version\n assert(torch.__version__ >= \"1.0.0\"), \"Please update your installation of PyTorch. You have {} and you should have version 1.0.0\".format(torch.__version__)\n\n # seed the random number generators\n seed = int(args['--seed'])\n torch.manual_seed(seed)\n if args['--cuda']:\n torch.cuda.manual_seed(seed)\n np.random.seed(seed * 13 // 7)\n\n if args['train']:\n train(args)\n elif args['decode']:\n decode(args)\n else:\n raise RuntimeError('invalid run mode')\n\n\nif __name__ == '__main__':\n main()\n", "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nCS224N 2019-20: Homework 5\nnmt_model.py: NMT Model\nPencheng Yin <[email protected]>\nSahil Chopra <[email protected]>\n\"\"\"\nfrom collections import namedtuple\nimport sys\nfrom typing import List, Tuple, Dict, Set, Union\nimport torch\nimport torch.nn as nn\nimport torch.nn.utils\nimport torch.nn.functional as F\nfrom torch.nn.utils.rnn import pad_packed_sequence, pack_padded_sequence\n\nfrom model_embeddings import ModelEmbeddings\nfrom char_decoder import CharDecoder\n\nHypothesis = namedtuple('Hypothesis', ['value', 'score'])\n\nimport random\n\n\nclass NMT(nn.Module):\n \"\"\" Simple Neural Machine Translation Model:\n - Bidrectional LSTM Encoder\n - Unidirection LSTM Decoder\n - Global Attention Model (Luong, et al. 2015)\n \"\"\"\n\n def __init__(self, word_embed_size, hidden_size, vocab, dropout_rate=0.3, no_char_decoder=False):\n \"\"\" Init NMT Model.\n\n @param word_embed_size (int): Embedding size (dimensionality) of word\n @param hidden_size (int): Hidden Size (dimensionality)\n @param vocab (Vocab): Vocabulary object containing src and tgt languages\n See vocab.py for documentation.\n @param dropout_rate (float): Dropout probability, for attention\n \"\"\"\n super(NMT, self).__init__()\n\n self.model_embeddings_source = ModelEmbeddings(word_embed_size, vocab.src)\n self.model_embeddings_target = ModelEmbeddings(word_embed_size, vocab.tgt)\n\n self.hidden_size = hidden_size\n self.dropout_rate = dropout_rate\n self.vocab = vocab\n\n ### COPY OVER YOUR CODE FROM ASSIGNMENT 4\n\n self.encoder = nn.LSTM(input_size=word_embed_size, hidden_size=self.hidden_size, bias=True, bidirectional=True)\n self.decoder = nn.LSTMCell(input_size=word_embed_size + self.hidden_size, hidden_size=self.hidden_size, bias=True)\n self.h_projection = nn.Linear(self.hidden_size*2, self.hidden_size, bias=False) # W_{h}\n self.c_projection = nn.Linear(self.hidden_size*2, self.hidden_size, bias=False) # W_{c}\n self.att_projection = nn.Linear(self.hidden_size*2, self.hidden_size, bias=False) # W_{attProj} \n self.combined_output_projection = nn.Linear(self.hidden_size*3, self.hidden_size , bias=False) # W_{u}\n self.target_vocab_projection = nn.Linear(self.hidden_size, len(self.vocab.tgt), bias=False) # W_vocab\n self.dropout = nn.Dropout(p=self.dropout_rate)\n \n ### END YOUR CODE FROM ASSIGNMENT 4\n\n if not no_char_decoder:\n self.charDecoder = CharDecoder(hidden_size, target_vocab=vocab.tgt)\n else:\n self.charDecoder = None\n\n def forward(self, source: List[List[str]], target: List[List[str]]) -> torch.Tensor:\n \"\"\" Take a mini-batch of source and target sentences, compute the log-likelihood of\n target sentences under the language models learned by the NMT system.\n\n @param source (List[List[str]]): list of source sentence tokens\n @param target (List[List[str]]): list of target sentence tokens, wrapped by `<s>` and `</s>`\n\n @returns scores (Tensor): a variable/tensor of one number representing the\n log-likelihood of generating the gold-standard target sentence for\n each example in the input batch. Here b = batch size.\n \"\"\"\n # Compute sentence lengths\n source_lengths = [len(s) for s in source]\n\n # Convert list of lists into tensors\n\n ### YOUR CODE HERE for part 1i\n ### TODO:\n ### Modify the code lines above as needed to fetch the character-level tensor\n ### to feed into encode() and decode(). You should:\n ### - Keep `target_padded` from A4 code above for predictions\n ### - Add `source_padded_chars` for character level padded encodings for source\n ### - Add `target_padded_chars` for character level padded encodings for target\n ### - Modify calls to encode() and decode() to use the character level encodings\n\n #source_padded = self.vocab.src.to_input_tensor(source, device=self.device) # [src_len, b] from A4\n target_padded = self.vocab.tgt.to_input_tensor(target, device=self.device) # [tgt_len, b]\n\n # tensor of [max_sentence_length, b, max_word_length]\n source_padded_chars = self.vocab.src.to_input_tensor_char(source, device=self.device) # [src_m_sent_len, b, src_m_word]\n target_padded_chars = self.vocab.tgt.to_input_tensor_char(target, device=self.device) # [tgt_m_sent_len, b, tgt_m_word]\n\n ### Run the network forward:\n ### 1. Apply the encoder to `source_padded` by calling `self.encode()`\n ### 2. Generate sentence masks for `source_padded` by calling `self.generate_sent_masks()`\n ### 3. Apply the decoder to compute combined-output by calling `self.decode()`\n ### 4. Compute log probability distribution over the target vocabulary using the\n ### combined_outputs returned by the `self.decode()` function.\n\n enc_hiddens, dec_init_state = self.encode(source_padded_chars, source_lengths)\n enc_masks = self.generate_sent_masks(enc_hiddens, source_lengths)\n combined_outputs = self.decode(enc_hiddens, enc_masks, dec_init_state, target_padded_chars)\n\n\n ### END YOUR CODE\n\n P = F.log_softmax(self.target_vocab_projection(combined_outputs), dim=-1)\n\n # Zero out, probabilities for which we have nothing in the target text\n target_masks = (target_padded != self.vocab.tgt['<pad>']).float()\n\n # Compute log probability of generating true target words\n target_gold_words_log_prob = torch.gather(P, index=target_padded[1:].unsqueeze(-1), dim=-1).squeeze(\n -1) * target_masks[1:]\n scores = target_gold_words_log_prob.sum() # mhahn2 Small modification from A4 code.\n\n if self.charDecoder is not None:\n max_word_len = target_padded_chars.shape[-1]\n\n target_words = target_padded[1:].contiguous().view(-1)\n target_chars = target_padded_chars[1:].view(-1, max_word_len)\n target_outputs = combined_outputs.view(-1, 256)\n\n target_chars_oov = target_chars # torch.index_select(target_chars, dim=0, index=oovIndices)\n rnn_states_oov = target_outputs # torch.index_select(target_outputs, dim=0, index=oovIndices)\n oovs_losses = self.charDecoder.train_forward(target_chars_oov.t().contiguous(),\n (rnn_states_oov.unsqueeze(0), rnn_states_oov.unsqueeze(0)))\n scores = scores - oovs_losses\n\n return scores\n\n def encode(self, source_padded: torch.Tensor, source_lengths: List[int]) -> Tuple[\n torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:\n \"\"\" Apply the encoder to source sentences to obtain encoder hidden states.\n Additionally, take the final states of the encoder and project them to obtain initial states for decoder.\n @param source_padded (Tensor): Tensor of padded source sentences with shape (src_len, b, max_word_length), where\n b = batch_size, src_len = maximum source sentence length. Note that\n these have already been sorted in order of longest to shortest sentence.\n @param source_lengths (List[int]): List of actual lengths for each of the source sentences in the batch\n @returns enc_hiddens (Tensor): Tensor of hidden units with shape (b, src_len, h*2), where\n b = batch size, src_len = maximum source sentence length, h = hidden size.\n @returns dec_init_state (tuple(Tensor, Tensor)): Tuple of tensors representing the decoder's initial\n hidden state and cell.\n \"\"\"\n enc_hiddens, dec_init_state = None, None\n\n ### COPY OVER YOUR CODE FROM ASSIGNMENT 4\n ### Except replace \"self.model_embeddings.source\" with \"self.model_embeddings_source\"\n\n X = self.model_embeddings_source(source_padded) # X.shape (src_len, b, e)\n X_packed = pack_padded_sequence(X, source_lengths) # X-packed.shape (src_len, b, e)\n enc_hiddens, (last_hidden, last_cell) = self.encoder(X_packed) # enc.hiddens.shape (src_len, b, h*2)\n enc_hiddens, len_pad = pad_packed_sequence(enc_hiddens, batch_first=True) # shape (b, src_len, h*2)\n init_decoder_hidden = self.h_projection(torch.cat((last_hidden[0], last_hidden[1]), 1)) # shape (b, 2*h)\n init_decoder_cell = self.c_projection(torch.cat((last_cell[0], last_cell[1]), 1)) # shape (b, 2*h)\n dec_init_state = (init_decoder_hidden, init_decoder_cell)\n\n ### END YOUR CODE FROM ASSIGNMENT 4\n\n return enc_hiddens, dec_init_state\n\n def decode(self, enc_hiddens: torch.Tensor, enc_masks: torch.Tensor,\n dec_init_state: Tuple[torch.Tensor, torch.Tensor], target_padded: torch.Tensor) -> torch.Tensor:\n \"\"\"Compute combined output vectors for a batch.\n @param enc_hiddens (Tensor): Hidden states (b, src_len, h*2), where\n b = batch size, src_len = maximum source sentence length, h = hidden size.\n @param enc_masks (Tensor): Tensor of sentence masks (b, src_len), where\n b = batch size, src_len = maximum source sentence length.\n @param dec_init_state (tuple(Tensor, Tensor)): Initial state and cell for decoder\n @param target_padded (Tensor): Gold-standard padded target sentences (tgt_len, b, max_word_length), where\n tgt_len = maximum target sentence length, b = batch size.\n @returns combined_outputs (Tensor): combined output tensor (tgt_len, b, h), where\n tgt_len = maximum target sentence length, b = batch_size, h = hidden size\n \"\"\"\n # Chop of the <END> token for max length sentences.\n target_padded = target_padded[:-1]\n\n # Initialize the decoder state (hidden and cell)\n dec_state = dec_init_state\n\n # Initialize previous combined output vector o_{t-1} as zeros\n batch_size = enc_hiddens.size(0)\n o_prev = torch.zeros(batch_size, self.hidden_size, device=self.device)\n\n # Initialize a list we will use to collect the combined output o_t on each step\n combined_outputs = []\n\n ### COPY OVER YOUR CODE FROM ASSIGNMENT 4\n ### Except replace \"self.model_embeddings.target\" with \"self.model_embeddings_target\"\n\n enc_hiddens_proj = self.att_projection(enc_hiddens) # shape (b, src_len, h)\n Y = self.model_embeddings_target(target_padded) # shape shape (tgt_len, b, e)\n for i in torch.split(Y, 1, dim=0): # torch.split(tensor, split_size_or_section, dim=0), Y_t.shape (1, b, e) \n Y_t = i.squeeze(0) # Y_t.shape (b, e), o_prev.shape (b, h), squeeze explicitly at location\n Ybar_t = torch.cat((Y_t, o_prev), dim=1) # Ybar_t.shape(b, e+h), torch.cat(tensors, dim=0, out=None)\n dec_state, o_t, e_t = self.step(Ybar_t, dec_state, enc_hiddens, enc_hiddens_proj, enc_masks) # dec_state, combined_output, e_t\n combined_outputs.append(o_t) # shape (b, h)\n o_prev = o_t\n combined_outputs = torch.stack(combined_outputs, dim=0) # (tgt_len, b, h)\n\n ### END YOUR CODE FROM ASSIGNMENT 4\n\n return combined_outputs\n\n def step(self, Ybar_t: torch.Tensor,\n dec_state: Tuple[torch.Tensor, torch.Tensor],\n enc_hiddens: torch.Tensor,\n enc_hiddens_proj: torch.Tensor,\n enc_masks: torch.Tensor) -> Tuple[Tuple, torch.Tensor, torch.Tensor]:\n \"\"\" Compute one forward step of the LSTM decoder, including the attention computation.\n @param Ybar_t (Tensor): Concatenated Tensor of [Y_t o_prev], with shape (b, e + h). The input for the decoder,\n where b = batch size, e = embedding size, h = hidden size.\n @param dec_state (tuple(Tensor, Tensor)): Tuple of tensors both with shape (b, h), where b = batch size, h = hidden size.\n First tensor is decoder's prev hidden state, second tensor is decoder's prev cell.\n @param enc_hiddens (Tensor): Encoder hidden states Tensor, with shape (b, src_len, h * 2), where b = batch size,\n src_len = maximum source length, h = hidden size.\n @param enc_hiddens_proj (Tensor): Encoder hidden states Tensor, projected from (h * 2) to h. Tensor is with shape (b, src_len, h),\n where b = batch size, src_len = maximum source length, h = hidden size.\n @param enc_masks (Tensor): Tensor of sentence masks shape (b, src_len),\n where b = batch size, src_len is maximum source length.\n @returns dec_state (tuple (Tensor, Tensor)): Tuple of tensors both shape (b, h), where b = batch size, h = hidden size.\n First tensor is decoder's new hidden state, second tensor is decoder's new cell.\n @returns combined_output (Tensor): Combined output Tensor at timestep t, shape (b, h), where b = batch size, h = hidden size.\n @returns e_t (Tensor): Tensor of shape (b, src_len). It is attention scores distribution.\n Note: You will not use this outside of this function.\n We are simply returning this value so that we can sanity check\n your implementation.\n \"\"\"\n\n combined_output = None\n\n ### COPY OVER YOUR CODE FROM ASSIGNMENT 4\n\n # dec_hidden.shape (b, h), dec_cell.shape (b, h)\n (dec_hidden, dec_cell) = self.decoder(Ybar_t, dec_state) \n dec_state = (dec_hidden, dec_cell)\n\n # torch.unsqueeze(input, dim), torch.squeeze(input, dim=None, out=None)\n # e_t.shape (b, src_len)\n # enc_hiddens_proj.shape (b, src_len, h), enc_hiddens_proj = apply W_{attProj} to h^enc\n # torch.bmm(input, mat2, out=None)\n e_t = torch.bmm(enc_hiddens_proj, dec_hidden.unsqueeze(2)).squeeze(2) \n # e_t.shape (b, src_len)\n\n ### END YOUR CODE FROM ASSIGNMENT 4\n\n # Set e_t to -inf where enc_masks has 1\n if enc_masks is not None:\n e_t.data.masked_fill_(enc_masks.bool(), -float('inf'))\n\n ### COPY OVER YOUR CODE FROM ASSIGNMENT 4\n\n # torch.nn.functional.softmax(input, dim=None, _stacklevel=3, dtype=None), e_t.shape (b, src_len)\n alpha_t = F.softmax(e_t, dim= 1) # alpha_t.shape (b, src_len)\n # enc_hiddens.shape (b, src_len, 2h)\n # torch.unsqueeze(input, dim), torch.squeeze(input, dim=None, out=None)\n # torch.bmm(input, mat2, out=None)\n a_t = torch.bmm(alpha_t.unsqueeze(1), enc_hiddens).squeeze(1) # a_t.shape (b, 2h)\n # dec_hidden.shape (b, h)\n U_t = torch.cat((dec_hidden, a_t), 1) # (b, 3h)\n # self.combined_output_projection = torch.nn.Linear(3h, h, bias=False)\n V_t = self.combined_output_projection(U_t) #(b, h, 3h)\n #self.dropout = nn.Dropout(p=self.dropout_rate)\n O_t = self.dropout(torch.tanh(V_t)) # O_t.shape (b, h)\n\n ### END YOUR CODE FROM ASSIGNMENT 4\n\n combined_output = O_t\n return dec_state, combined_output, e_t\n\n def generate_sent_masks(self, enc_hiddens: torch.Tensor, source_lengths: List[int]) -> torch.Tensor:\n \"\"\" Generate sentence masks for encoder hidden states.\n\n @param enc_hiddens (Tensor): encodings of shape (b, src_len, 2*h), where b = batch size,\n src_len = max source length, h = hidden size.\n @param source_lengths (List[int]): List of actual lengths for each of the sentences in the batch.\n\n @returns enc_masks (Tensor): Tensor of sentence masks of shape (b, src_len),\n where src_len = max source length, h = hidden size.\n \"\"\"\n enc_masks = torch.zeros(enc_hiddens.size(0), enc_hiddens.size(1), dtype=torch.float)\n for e_id, src_len in enumerate(source_lengths):\n enc_masks[e_id, src_len:] = 1\n return enc_masks.to(self.device)\n\n def beam_search(self, src_sent: List[str], beam_size: int = 5, max_decoding_time_step: int = 70) -> List[\n Hypothesis]:\n \"\"\" Given a single source sentence, perform beam search, yielding translations in the target language.\n @param src_sent (List[str]): a single source sentence (words)\n @param beam_size (int): beam size\n @param max_decoding_time_step (int): maximum number of time steps to unroll the decoding RNN\n @returns hypotheses (List[Hypothesis]): a list of hypothesis, each hypothesis has two fields:\n value: List[str]: the decoded target sentence, represented as a list of words\n score: float: the log-likelihood of the target sentence\n \"\"\"\n\n src_sents_var = self.vocab.src.to_input_tensor_char([src_sent], self.device)\n\n src_encodings, dec_init_vec = self.encode(src_sents_var, [len(src_sent)])\n src_encodings_att_linear = self.att_projection(src_encodings)\n\n h_tm1 = dec_init_vec\n att_tm1 = torch.zeros(1, self.hidden_size, device=self.device)\n\n eos_id = self.vocab.tgt['</s>']\n\n hypotheses = [['<s>']]\n hyp_scores = torch.zeros(len(hypotheses), dtype=torch.float, device=self.device)\n completed_hypotheses = []\n\n t = 0\n while len(completed_hypotheses) < beam_size and t < max_decoding_time_step:\n t += 1\n hyp_num = len(hypotheses)\n\n exp_src_encodings = src_encodings.expand(hyp_num,\n src_encodings.size(1),\n src_encodings.size(2))\n\n exp_src_encodings_att_linear = src_encodings_att_linear.expand(hyp_num,\n src_encodings_att_linear.size(1),\n src_encodings_att_linear.size(2))\n\n y_tm1 = self.vocab.tgt.to_input_tensor_char(list([hyp[-1]] for hyp in hypotheses), device=self.device)\n y_t_embed = self.model_embeddings_target(y_tm1)\n y_t_embed = torch.squeeze(y_t_embed, dim=0)\n\n x = torch.cat([y_t_embed, att_tm1], dim=-1)\n\n (h_t, cell_t), att_t, _ = self.step(x, h_tm1,\n exp_src_encodings, exp_src_encodings_att_linear, enc_masks=None)\n\n # log probabilities over target words\n log_p_t = F.log_softmax(self.target_vocab_projection(att_t), dim=-1)\n\n live_hyp_num = beam_size - len(completed_hypotheses)\n contiuating_hyp_scores = (hyp_scores.unsqueeze(1).expand_as(log_p_t) + log_p_t).view(-1)\n top_cand_hyp_scores, top_cand_hyp_pos = torch.topk(contiuating_hyp_scores, k=live_hyp_num)\n\n prev_hyp_ids = top_cand_hyp_pos / len(self.vocab.tgt)\n hyp_word_ids = top_cand_hyp_pos % len(self.vocab.tgt)\n\n new_hypotheses = []\n live_hyp_ids = []\n new_hyp_scores = []\n\n decoderStatesForUNKsHere = []\n for prev_hyp_id, hyp_word_id, cand_new_hyp_score in zip(prev_hyp_ids, hyp_word_ids, top_cand_hyp_scores):\n prev_hyp_id = prev_hyp_id.item()\n hyp_word_id = hyp_word_id.item()\n cand_new_hyp_score = cand_new_hyp_score.item()\n\n hyp_word = self.vocab.tgt.id2word[hyp_word_id]\n\n # Record output layer in case UNK was generated\n if hyp_word == \"<unk>\":\n hyp_word = \"<unk>\" + str(len(decoderStatesForUNKsHere))\n decoderStatesForUNKsHere.append(att_t[prev_hyp_id])\n\n new_hyp_sent = hypotheses[prev_hyp_id] + [hyp_word]\n if hyp_word == '</s>':\n completed_hypotheses.append(Hypothesis(value=new_hyp_sent[1:-1],\n score=cand_new_hyp_score))\n else:\n new_hypotheses.append(new_hyp_sent)\n live_hyp_ids.append(prev_hyp_id)\n new_hyp_scores.append(cand_new_hyp_score)\n\n if len(decoderStatesForUNKsHere) > 0 and self.charDecoder is not None: # decode UNKs\n decoderStatesForUNKsHere = torch.stack(decoderStatesForUNKsHere, dim=0)\n decodedWords = self.charDecoder.decode_greedy(\n (decoderStatesForUNKsHere.unsqueeze(0), decoderStatesForUNKsHere.unsqueeze(0)), max_length=21,\n device=self.device)\n assert len(decodedWords) == decoderStatesForUNKsHere.size()[0], \"Incorrect number of decoded words\"\n for hyp in new_hypotheses:\n if hyp[-1].startswith(\"<unk>\"):\n hyp[-1] = decodedWords[int(hyp[-1][5:])] # [:-1]\n\n if len(completed_hypotheses) == beam_size:\n break\n\n live_hyp_ids = torch.tensor(live_hyp_ids, dtype=torch.long, device=self.device)\n h_tm1 = (h_t[live_hyp_ids], cell_t[live_hyp_ids])\n att_tm1 = att_t[live_hyp_ids]\n\n hypotheses = new_hypotheses\n hyp_scores = torch.tensor(new_hyp_scores, dtype=torch.float, device=self.device)\n\n if len(completed_hypotheses) == 0:\n completed_hypotheses.append(Hypothesis(value=hypotheses[0][1:],\n score=hyp_scores[0].item()))\n\n completed_hypotheses.sort(key=lambda hyp: hyp.score, reverse=True)\n return completed_hypotheses\n\n @property\n def device(self) -> torch.device:\n \"\"\" Determine which device to place the Tensors upon, CPU or GPU.\n \"\"\"\n return self.att_projection.weight.device\n\n @staticmethod\n def load(model_path: str, no_char_decoder=False):\n \"\"\" Load the model from a file.\n @param model_path (str): path to model\n \"\"\"\n params = torch.load(model_path, map_location=lambda storage, loc: storage)\n args = params['args']\n model = NMT(vocab=params['vocab'], no_char_decoder=no_char_decoder, **args)\n model.load_state_dict(params['state_dict'])\n\n return model\n\n def save(self, path: str):\n \"\"\" Save the odel to a file.\n @param path (str): path to the model\n \"\"\"\n print('save model parameters to [%s]' % path, file=sys.stderr)\n\n params = {\n 'args': dict(word_embed_size=self.model_embeddings_source.word_embed_size, hidden_size=self.hidden_size,\n dropout_rate=self.dropout_rate),\n 'vocab': self.vocab,\n 'state_dict': self.state_dict()\n }\n\n torch.save(params, path)\n" ]
[ [ "numpy.abs", "numpy.random.seed", "torch.cuda.manual_seed", "torch.load", "torch.manual_seed", "torch.no_grad", "torch.device", "numpy.exp" ], [ "torch.nn.Dropout", "torch.nn.functional.softmax", "torch.nn.LSTM", "torch.zeros", "torch.cat", "torch.load", "torch.topk", "torch.nn.utils.rnn.pack_padded_sequence", "torch.tensor", "torch.nn.LSTMCell", "torch.nn.Linear", "torch.nn.utils.rnn.pad_packed_sequence", "torch.tanh", "torch.split", "torch.stack", "torch.squeeze", "torch.save" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
google-research/understanding-transfer-learning
[ "0e4df444f342784514d91028d0de332103343a94" ]
[ "third_party/fixup_resnet/fixup_resnet_imagenet.py" ]
[ "import torch\nimport torch.nn as nn\nimport numpy as np\n\n\n__all__ = ['FixupResNet', 'fixup_resnet18', 'fixup_resnet34', 'fixup_resnet50', 'fixup_resnet101', 'fixup_resnet152']\n\n\ndef conv3x3(in_planes, out_planes, stride=1):\n \"\"\"3x3 convolution with padding\"\"\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\n padding=1, bias=False)\n\n\ndef conv1x1(in_planes, out_planes, stride=1):\n \"\"\"1x1 convolution\"\"\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)\n\n\nclass FixupBasicBlock(nn.Module):\n expansion = 1\n\n def __init__(self, inplanes, planes, stride=1, downsample=None):\n super(FixupBasicBlock, self).__init__()\n # Both self.conv1 and self.downsample layers downsample the input when stride != 1\n self.bias1a = nn.Parameter(torch.zeros(1))\n self.conv1 = conv3x3(inplanes, planes, stride)\n self.bias1b = nn.Parameter(torch.zeros(1))\n self.relu = nn.ReLU(inplace=True)\n self.bias2a = nn.Parameter(torch.zeros(1))\n self.conv2 = conv3x3(planes, planes)\n self.scale = nn.Parameter(torch.ones(1))\n self.bias2b = nn.Parameter(torch.zeros(1))\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n identity = x\n\n out = self.conv1(x + self.bias1a)\n out = self.relu(out + self.bias1b)\n\n out = self.conv2(out + self.bias2a)\n out = out * self.scale + self.bias2b\n\n if self.downsample is not None:\n identity = self.downsample(x + self.bias1a)\n\n out += identity\n out = self.relu(out)\n\n return out\n\n\nclass FixupBottleneck(nn.Module):\n expansion = 4\n\n def __init__(self, inplanes, planes, stride=1, downsample=None):\n super(FixupBottleneck, self).__init__()\n # Both self.conv2 and self.downsample layers downsample the input when stride != 1\n self.bias1a = nn.Parameter(torch.zeros(1))\n self.conv1 = conv1x1(inplanes, planes)\n self.bias1b = nn.Parameter(torch.zeros(1))\n self.bias2a = nn.Parameter(torch.zeros(1))\n self.conv2 = conv3x3(planes, planes, stride)\n self.bias2b = nn.Parameter(torch.zeros(1))\n self.bias3a = nn.Parameter(torch.zeros(1))\n self.conv3 = conv1x1(planes, planes * self.expansion)\n self.scale = nn.Parameter(torch.ones(1))\n self.bias3b = nn.Parameter(torch.zeros(1))\n self.relu = nn.ReLU(inplace=True)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n identity = x\n\n out = self.conv1(x + self.bias1a)\n out = self.relu(out + self.bias1b)\n\n out = self.conv2(out + self.bias2a)\n out = self.relu(out + self.bias2b)\n\n out = self.conv3(out + self.bias3a)\n out = out * self.scale + self.bias3b\n\n if self.downsample is not None:\n identity = self.downsample(x + self.bias1a)\n\n out += identity\n out = self.relu(out)\n\n return out\n\n\nclass FixupResNet(nn.Module):\n\n def __init__(self, block, layers, num_classes=1000, zero_fc_init=True):\n super(FixupResNet, self).__init__()\n self.num_layers = sum(layers)\n self.inplanes = 64\n self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,\n bias=False)\n self.bias1 = nn.Parameter(torch.zeros(1))\n self.relu = nn.ReLU(inplace=True)\n self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n self.layer1 = self._make_layer(block, 64, layers[0])\n self.layer2 = self._make_layer(block, 128, layers[1], stride=2)\n self.layer3 = self._make_layer(block, 256, layers[2], stride=2)\n self.layer4 = self._make_layer(block, 512, layers[3], stride=2)\n self.avgpool = nn.AdaptiveAvgPool2d((1, 1))\n self.bias2 = nn.Parameter(torch.zeros(1))\n self.fc = nn.Linear(512 * block.expansion, num_classes)\n\n for m in self.modules():\n if isinstance(m, FixupBasicBlock):\n nn.init.normal_(m.conv1.weight, mean=0, std=np.sqrt(2 / (m.conv1.weight.shape[0] * np.prod(m.conv1.weight.shape[2:]))) * self.num_layers ** (-0.5))\n nn.init.constant_(m.conv2.weight, 0)\n if m.downsample is not None:\n nn.init.normal_(m.downsample.weight, mean=0, std=np.sqrt(2 / (m.downsample.weight.shape[0] * np.prod(m.downsample.weight.shape[2:]))))\n elif isinstance(m, FixupBottleneck):\n nn.init.normal_(m.conv1.weight, mean=0, std=np.sqrt(2 / (m.conv1.weight.shape[0] * np.prod(m.conv1.weight.shape[2:]))) * self.num_layers ** (-0.25))\n nn.init.normal_(m.conv2.weight, mean=0, std=np.sqrt(2 / (m.conv2.weight.shape[0] * np.prod(m.conv2.weight.shape[2:]))) * self.num_layers ** (-0.25))\n nn.init.constant_(m.conv3.weight, 0)\n if m.downsample is not None:\n nn.init.normal_(m.downsample.weight, mean=0, std=np.sqrt(2 / (m.downsample.weight.shape[0] * np.prod(m.downsample.weight.shape[2:]))))\n elif isinstance(m, nn.Linear) and zero_fc_init:\n nn.init.constant_(m.weight, 0)\n nn.init.constant_(m.bias, 0)\n\n def _make_layer(self, block, planes, blocks, stride=1):\n downsample = None\n if stride != 1 or self.inplanes != planes * block.expansion:\n downsample = conv1x1(self.inplanes, planes * block.expansion, stride)\n\n layers = []\n layers.append(block(self.inplanes, planes, stride, downsample))\n self.inplanes = planes * block.expansion\n for _ in range(1, blocks):\n layers.append(block(self.inplanes, planes))\n\n return nn.Sequential(*layers)\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.relu(x + self.bias1)\n x = self.maxpool(x)\n\n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n x = self.layer4(x)\n\n x = self.avgpool(x)\n x = x.view(x.size(0), -1)\n x = self.fc(x + self.bias2)\n\n return x\n\n\ndef fixup_resnet18(**kwargs):\n \"\"\"Constructs a Fixup-ResNet-18 model.\n\n \"\"\"\n model = FixupResNet(FixupBasicBlock, [2, 2, 2, 2], **kwargs)\n return model\n\n\ndef fixup_resnet34(**kwargs):\n \"\"\"Constructs a Fixup-ResNet-34 model.\n\n \"\"\"\n model = FixupResNet(FixupBasicBlock, [3, 4, 6, 3], **kwargs)\n return model\n\n\ndef fixup_resnet50(**kwargs):\n \"\"\"Constructs a Fixup-ResNet-50 model.\n\n \"\"\"\n model = FixupResNet(FixupBottleneck, [3, 4, 6, 3], **kwargs)\n return model\n\n\ndef fixup_resnet101(**kwargs):\n \"\"\"Constructs a Fixup-ResNet-101 model.\n\n \"\"\"\n model = FixupResNet(FixupBottleneck, [3, 4, 23, 3], **kwargs)\n return model\n\n\ndef fixup_resnet152(**kwargs):\n \"\"\"Constructs a Fixup-ResNet-152 model.\n\n \"\"\"\n model = FixupResNet(FixupBottleneck, [3, 8, 36, 3], **kwargs)\n return model\n" ]
[ [ "torch.nn.Sequential", "torch.ones", "torch.zeros", "torch.nn.init.constant_", "torch.nn.Conv2d", "torch.nn.Linear", "torch.nn.MaxPool2d", "torch.nn.AdaptiveAvgPool2d", "numpy.prod", "torch.nn.ReLU" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Lalala-xnk/Quasi-Attention-ABSA
[ "1eb694e832bbf9687aed719bbcaa657baf0323d3" ]
[ "code/scorer.py" ]
[ "import pandas as pd\nfrom tqdm import tqdm\nfrom model.QACGBERT import *\nfrom util.tokenization import *\nfrom torch.utils.data import DataLoader, TensorDataset\nimport random\nimport warnings\n\nwarnings.filterwarnings('ignore')\n\ncontext_id_map_fiqa = {'stock': 0,\n 'corporate': 1,\n 'market': 2,\n 'economy': 3}\n\n\nclass InputExample(object):\n def __init__(self, guid, text_a, text_b=None, label=None):\n self.guid = guid\n self.text_a = text_a\n self.text_b = text_b\n self.label = label\n\n\nclass InputFeatures(object):\n def __init__(self, input_ids, input_mask, segment_ids, score, seq_len, context_ids):\n self.input_ids = input_ids\n self.input_mask = input_mask\n self.segment_ids = segment_ids\n self.score = score\n self.seq_len = seq_len\n self.context_ids = context_ids\n\n\ndef convert_to_unicode(text):\n if six.PY3:\n if isinstance(text, str):\n return text\n elif isinstance(text, bytes):\n return text.decode(\"utf-8\", \"ignore\")\n else:\n raise ValueError(\"Unsupported string type: %s\" % (type(text)))\n else:\n raise ValueError(\"Not running on Python 3\")\n\n\ndef get_test_examples(path):\n test_data = pd.read_csv(path, header=None).values\n def _create_examples(lines, set_type):\n examples = []\n for (i, line) in enumerate(lines):\n guid = \"%s-%s\" % (set_type, i)\n text_a = convert_to_unicode(str(line[2]))\n text_b = convert_to_unicode(str(line[1]))\n label = float(0)\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))\n return examples\n return _create_examples(test_data, \"test\")\n\n\ndef truncate_seq_pair(tokens_a, tokens_b, max_length):\n while True:\n total_length = len(tokens_a) + len(tokens_b)\n if total_length <= max_length:\n break\n if len(tokens_a) > len(tokens_b):\n tokens_a.pop()\n else:\n tokens_b.pop()\n\n\ndef convert_examples_to_features(examples, max_seq_length,\n tokenizer, max_context_length,\n context_standalone, args):\n features = []\n for (ex_index, example) in enumerate(tqdm(examples)):\n tokens_a = tokenizer.tokenize(example.text_a)\n\n tokens_b = None\n if example.text_b:\n tokens_b = tokenizer.tokenize(example.text_b)\n tokens_context = None\n if example.text_b:\n tokens_context = tokenizer.tokenize(example.text_b)\n\n if tokens_b and not context_standalone:\n truncate_seq_pair(tokens_a, tokens_b, max_seq_length - 3)\n else:\n if len(tokens_a) > max_seq_length - 2:\n tokens_a = tokens_a[0:(max_seq_length - 2)]\n\n tokens = []\n segment_ids = []\n tokens.append(\"[CLS]\")\n segment_ids.append(0)\n for token in tokens_a:\n tokens.append(token)\n segment_ids.append(0)\n tokens.append(\"[SEP]\")\n segment_ids.append(0)\n\n if tokens_b and not context_standalone:\n for token in tokens_b:\n tokens.append(token)\n segment_ids.append(1)\n tokens.append(\"[SEP]\")\n segment_ids.append(1)\n\n input_ids = tokenizer.convert_tokens_to_ids(tokens)\n\n context_ids = []\n if tokens_context:\n context_ids = [context_id_map_fiqa[example.text_b]]\n\n # The mask has 1 for real tokens and 0 for padding tokens. Only real\n # tokens are attended to.\n input_mask = [1] * len(input_ids)\n\n # Zero-pad up to the sequence length.\n seq_len = len(input_ids)\n while len(input_ids) < max_seq_length:\n input_ids.append(0)\n input_mask.append(0)\n segment_ids.append(0)\n\n while len(context_ids) < max_context_length:\n context_ids.append(0)\n\n assert len(input_ids) == max_seq_length\n assert len(input_mask) == max_seq_length\n assert len(segment_ids) == max_seq_length\n assert len(context_ids) == max_context_length\n\n features.append(\n InputFeatures(\n input_ids=input_ids,\n input_mask=input_mask,\n segment_ids=segment_ids,\n score=example.label,\n seq_len=seq_len,\n context_ids=context_ids))\n\n return features\n\n\ndef get_model_and_tokenizer(vocab_file,\n bert_config_file=None, init_checkpoint=None,\n do_lower_case=True,\n init_lrp=False):\n tokenizer = FullTokenizer(\n vocab_file=vocab_file, do_lower_case=do_lower_case, pretrain=False)\n if bert_config_file is not None:\n bert_config = BertConfig.from_json_file(bert_config_file)\n else:\n bert_config = BertConfig(\n hidden_size=768,\n num_hidden_layers=12,\n num_attention_heads=12,\n intermediate_size=3072,\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 )\n bert_config.vocab_size = len(tokenizer.vocab)\n model = QACGBertForSequenceScore(\n bert_config,\n init_weight=True,\n init_lrp=init_lrp)\n\n if init_checkpoint is not None:\n if \"checkpoint\" in init_checkpoint:\n state_dict = torch.load(init_checkpoint, map_location='cpu')\n from collections import OrderedDict\n new_state_dict = OrderedDict()\n for k, v in state_dict.items():\n if k.startswith('module.'):\n name = k[7:]\n new_state_dict[name] = v\n else:\n new_state_dict[k] = v\n model.load_state_dict(new_state_dict)\n else:\n model.bert.load_state_dict(torch.load(init_checkpoint, map_location='cpu'), strict=False)\n return model, tokenizer\n\n\ndef system_setups(args):\n # system related setups\n if args.local_rank == -1 or args.no_cuda:\n device = torch.device(\"cuda\" if torch.cuda.is_available() and not args.no_cuda else \"cpu\")\n n_gpu = torch.cuda.device_count()\n else:\n device = torch.device(\"cuda\", args.local_rank)\n n_gpu = 1\n torch.distributed.init_process_group(backend='nccl')\n\n random.seed(args.seed)\n np.random.seed(args.seed)\n torch.manual_seed(args.seed)\n if n_gpu > 0:\n torch.cuda.manual_seed_all(args.seed)\n\n if args.bert_config_file is not None:\n bert_config = BertConfig.from_json_file(args.bert_config_file)\n if args.max_seq_length > bert_config.max_position_embeddings:\n raise ValueError(\n \"Cannot use sequence length {} because the BERT model was only trained up to sequence length {}\".format(\n args.max_seq_length, bert_config.max_position_embeddings))\n\n return device, n_gpu\n\n\ndef data_and_model_loader(device, n_gpu, args):\n model, tokenizer = get_model_and_tokenizer(vocab_file=args.vocab_file,\n bert_config_file=args.bert_config_file, init_checkpoint=args.init_checkpoint,\n do_lower_case=True,\n init_lrp=False)\n\n test_examples = get_test_examples(args.path)\n test_features = convert_examples_to_features(\n test_examples, args.max_seq_length,\n tokenizer, args.max_context_length,\n args.context_standalone, args)\n\n all_input_ids = torch.tensor([f.input_ids for f in test_features], dtype=torch.long)\n all_input_mask = torch.tensor([f.input_mask for f in test_features], dtype=torch.long)\n all_segment_ids = torch.tensor([f.segment_ids for f in test_features], dtype=torch.long)\n all_score = torch.tensor([f.score for f in test_features], dtype=torch.float)\n all_seq_len = torch.tensor([[f.seq_len] for f in test_features], dtype=torch.long)\n all_context_ids = torch.tensor([f.context_ids for f in test_features], dtype=torch.long)\n\n test_data = TensorDataset(all_input_ids, all_input_mask, all_segment_ids,\n all_score, all_seq_len, all_context_ids)\n test_dataloader = DataLoader(test_data, shuffle=False)\n\n if args.local_rank != -1:\n model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.local_rank],\n output_device=args.local_rank)\n elif n_gpu > 1:\n model = torch.nn.DataParallel(model)\n model.to(device)\n\n return model, test_dataloader\n\n\ndef pred(args):\n device, n_gpu = system_setups(args)\n model, test_dataloader = data_and_model_loader(device, n_gpu, args)\n\n model.eval()\n y_pred = []\n for batch in list(test_dataloader):\n if torch.cuda.is_available():\n torch.cuda.empty_cache()\n input_ids, input_mask, segment_ids, score, seq_lens, \\\n context_ids = batch\n max_seq_lens = max(seq_lens)[0]\n input_ids = input_ids[:, :max_seq_lens]\n input_mask = input_mask[:, :max_seq_lens]\n segment_ids = segment_ids[:, :max_seq_lens]\n\n input_ids = input_ids.to(device)\n input_mask = input_mask.to(device)\n segment_ids = segment_ids.to(device)\n score = score.to(device)\n seq_lens = seq_lens.to(device)\n context_ids = context_ids.to(device)\n\n _, pred_score, _, _, _, _ = \\\n model(input_ids, segment_ids, input_mask, seq_lens, device=device, labels=score,\n context_ids=context_ids)\n y_pred.append(pred_score.detach().numpy()[0][0])\n\n return y_pred\n\n\nif __name__ == '__main__':\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--path\")\n parser.add_argument(\"--max_seq_length\", default=128, type=int)\n parser.add_argument(\"--vocab_file\")\n parser.add_argument(\"--bert_config_file\")\n parser.add_argument(\"--init_checkpoint\")\n parser.add_argument('--local_rank', type=int, default=-1)\n parser.add_argument(\"--no_cuda\", default=False, action='store_true')\n parser.add_argument(\"--max_context_length\", default=1, type=int)\n parser.add_argument(\"--context_standalone\", default=False, action='store_true')\n parser.add_argument('--seed', type=int, default=123)\n args = parser.parse_args()\n\n pred_score = pred(args)\n print(pred_score)\n" ]
[ [ "torch.utils.data.TensorDataset", "pandas.read_csv", "torch.utils.data.DataLoader" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
bx3/perigee-bandit
[ "73771672abe9321edbb7d455a59bfb072fafa33f", "73771672abe9321edbb7d455a59bfb072fafa33f" ]
[ "sim/simple_model/loss_functions.py", "sim/sec_hop/experiment.py" ]
[ "import torch\nimport sys\n\nCONSTANT = 1e-10\n\nclass ClusterLoss(torch.nn.Module):\n def __init__(self):\n super().__init__()\n self.mse_fn = torch.nn.MSELoss(reduction='sum')\n self.softmax_func = torch.nn.Softmax(dim=0)\n\n # def forward(self, X, H, C, M, T, nM):\n # sim_loss = torch.tensor(0.0, dtype=torch.float32)\n # softmax_func = torch.nn.Softmax(dim=0)\n # for i in range(T):\n # row_loss = torch.tensor(0.0, dtype=torch.float32) \n # scores = torch.ones(T) * float(\"inf\")\n # for j in range(T):\n # if i != j:\n # if (M[i] != M[j]).any():\n # selected = torch.masked_select(X[i]-X[j], (M[i]*M[j]) >0)\n # scores[j] = torch.sqrt(torch.var(selected))\n\n # topk, topk_ind = torch.topk(scores, 1, largest=False)\n # weight = softmax_func(-1*topk)\n\n # for k in range(len(topk_ind)):\n # j = topk_ind[k]\n # row_loss += weight[k]*torch.norm(H[i]-H[j])\n # sim_loss += row_loss\n # loss = self.mse_fn(X*M, (H-C)*M) + sim_loss + 0.1*torch.norm(C)\n # return loss\n\n def forward(self, X, H, C, M, T, nM, row_scores, mc_rows):\n sim_loss = torch.tensor(0.0, dtype=torch.float32)\n for i in mc_rows:\n topk, topk_ind = torch.topk(row_scores[i], 3, largest=False)\n weight = self.softmax_func(-1*topk)\n\n for k in range(len(topk_ind)):\n j = topk_ind[k]\n sim_loss += weight[k]*torch.norm(H[i]-H[j])\n # print(i, j, H[i], H[j], weight, sim_loss, topk, topk_ind, row_scores[i])\n \n loss = self.mse_fn(X*M, (H-C)*M) + sim_loss + 0.1*torch.norm(C) + 0.1*torch.norm(H)\n return loss\n\n\n\nclass ElementLoss(torch.nn.Module):\n def __init__(self):\n super().__init__()\n\n def forward(self, X, A, C, easy_estimates_by_row, known_pos_by_row, element_peer_scores, tensor_ind_map, T):\n sim_loss = torch.tensor(0.0, dtype=torch.float32)\n for i in range(T):\n if i in easy_estimates_by_row:\n row_loss = torch.tensor(0.0, dtype=torch.float32)\n easy_unknown = easy_estimates_by_row[i]\n\n for j in easy_unknown:\n for weight, k, mask in element_peer_scores[(i,j)]:\n\n t = tensor_ind_map[(i,j)]\n a = (X[k] + C[k]) - (X[i] + C[i])\n a[j] -= (A[t] - C[i] ) # without - X[i,j], since it is 0\n b = torch.masked_select(a, mask)\n # print(i,j, 'close to', k, 'weight', weight, mask, a, b)\n # print(X[k]*max_time)\n # print(X[i]*max_time)\n\n row_loss += weight/float(len(easy_unknown))*torch.norm(b)\n\n sim_loss += row_loss\n \n return sim_loss + 1*torch.norm(C) + 1*torch.norm(A)\n\n\n\n# def forward(self, X, A, C, easy_estimates, known_pos_by_row, element_peer_scores, tensor_ind_map, indicators, N):\n # sim_loss = torch.tensor(0.0, dtype=torch.float32)\n # for i,j in easy_estimates:\n # ele_loss = torch.tensor(CONSTANT, dtype=torch.float32)\n # for weight, k in element_peer_scores[(i,j)]:\n # a = (X[k,j] + C[k] - A[tensor_ind_map[(i,j)]]) \n # ele_loss += weight*torch.square(a)\n # sim_loss += torch.sqrt(ele_loss)\n\n", "import sys\nimport pickle\nimport json\nimport os\nimport math\nimport networkx as nx\nfrom collections import defaultdict\n\nfrom net_init import load_network\nfrom net_init import generate_random_outs_conns_with_oracle as gen_rand_outs_with_oracle\nfrom network.sparse_table import SparseTable\nfrom network.communicator import Communicator\nfrom network import comm_network\nfrom network.oracle import SimpleOracle\nfrom sec_hop.selector import Selector\nfrom mat_complete.mat_comp_solver import construct_table\nimport random\nimport numpy as np\n\n\nclass Experiment:\n def __init__(self, topo, in_lim, out_lim, name, num_keep, num_2hop, num_rand, num_epoch, adapts, num_msg, churn_rate):\n self.in_lim = in_lim\n self.out_lim = out_lim\n self.num_out = out_lim\n self.outdir = os.path.dirname(name)\n\n self.loc, self.ld, self.roles, self.proc_delay, self.pub_prob = load_network(topo)\n self.num_node = len(self.loc) \n self.num_epoch = num_epoch\n self.num_msg = num_msg\n self.churn_rate = churn_rate\n\n self.selectors = {i: Selector(i, num_keep, num_rand, num_msg, self.num_node)\n for i in range(self.num_node)} \n # elf.num_cand = num_node # could be less if num_node is large\n\n self.snapshots = []\n # self.pools = Pool(processes=num_thread) \n\n self.directions = ['incoming', 'outgoing', 'bidirect']\n self.nodes = {i: Communicator(i, self.proc_delay[i], in_lim, out_lim, []) \n for i in range(self.num_node)}\n self.oracle = SimpleOracle(in_lim, out_lim, self.num_node)\n self.out_hist = []\n self.sparse_tables = {i: SparseTable(i) for i in range(self.num_node)}\n\n # self.conns_snapshot = []\n # self.broad_nodes = [] # hist of broadcasting node\n # self.timer = time.time()\n\n # self.pubs = [k for k,v in self.roles.items() if v=='PUB']\n\n\n\n self.adapts = adapts\n self.pub_hist = []\n self.dists_hist = defaultdict(list)\n self.dist_file = name \n\n # log setting\n # self.use_logger = use_logger \n # self.logdir = self.outdir + '/' + 'logs'\n # if not os.path.exists(self.logdir):\n # os.makedirs(self.logdir)\n # self.loggers = {}\n # self.init_logger()\n\n self.init_graph_conn = os.path.join(self.outdir, 'init.json')\n self.snapshot_dir = os.path.join(self.outdir, 'snapshots')\n self.snapshot_exploit_dir = os.path.join(self.outdir, 'snapshots-exploit')\n self.write_adapts_node(os.path.join(self.outdir, 'adapts'))\n\n if not os.path.exists(self.snapshot_dir):\n os.makedirs(self.snapshot_dir)\n if not os.path.exists(self.snapshot_dir):\n os.makedirs(self.snapshot_dir)\n\n\n self.num_keep = num_keep\n self.num_2hop = num_2hop\n self.num_rand = num_rand\n assert(num_keep + num_2hop + num_rand == self.out_lim)\n\n def construct_graph(self):\n G = nx.Graph()\n for i, node in self.nodes.items():\n for u in node.outs:\n delay = self.ld[i][u] + node.node_delay/2 + self.nodes[u].node_delay/2\n if i == u:\n print('self loop', i)\n sys.exit(1)\n G.add_edge(i, u, weight=delay)\n return G\n\n def construct_exploit_graph(self, curr_outs):\n G = nx.Graph()\n for i, node in self.nodes.items():\n out_peers = []\n if i in self.adapts:\n out_peers = curr_outs[i][:self.num_out-self.num_rand]\n else:\n out_peers = curr_outs[i]\n\n for u in out_peers:\n delay = self.ld[i][u] + node.node_delay/2 + self.nodes[u].node_delay/2\n if i == u:\n print('self loop', i)\n sys.exit(1)\n G.add_edge(i, u, weight=delay)\n return G\n\n def write_cost(self, outpath):\n G = self.construct_graph()\n with open(outpath, 'w') as w:\n length = dict(nx.all_pairs_dijkstra_path_length(G))\n for i in range(self.num_node):\n for j in range(self.num_node):\n cost = length[i][j] - self.proc_delay[i]/2.0 + self.proc_delay[j]/2.0\n w.write(str(cost) + ' ')\n w.write('\\n')\n\n def write_exploit_cost(self, outpath, curr_outs):\n G = self.construct_exploit_graph(curr_outs)\n with open(outpath, 'w') as w:\n length = dict(nx.all_pairs_dijkstra_path_length(G))\n for i in range(self.num_node):\n for j in range(self.num_node):\n cost = length[i][j] - self.proc_delay[i]/2.0 + self.proc_delay[j]/2.0\n w.write(str(cost) + ' ')\n w.write('\\n')\n\n def write_adapts_node(self, filename):\n with open(filename, 'w') as w:\n sorted_stars = sorted(self.adapts)\n for star in sorted_stars:\n w.write(str(star) + '\\n')\n\n def get_truth_distance(self, star_i, interested_peers, epoch):\n # construct graph\n G = nx.Graph()\n for i, node in self.nodes.items():\n if i == star_i:\n for u in interested_peers:\n # only connect interested edge from the interested node\n delay = self.ld[i][u] + node.node_delay/2 + self.nodes[u].node_delay/2\n if i == u:\n print('self loop', i)\n sys.exit(1)\n G.add_edge(i, u, weight=delay)\n else:\n for u in node.outs:\n # not connecting incoming edge to the interested node\n if u != star_i:\n delay = self.ld[i][u] + node.node_delay/2 + self.nodes[u].node_delay/2\n if i == u:\n print('self loop', i)\n sys.exit(1)\n G.add_edge(i, u, weight=delay)\n dists = {} # key is the target pub, value is the best peer and length\n\n pubs = [k for k,v in self.roles.items() if v=='PUB']\n for m in pubs:\n # the closest distance\n length, path = nx.single_source_dijkstra(G, source=star_i, target=m, weight='weight')\n assert(len(path)>=0) \n topo_length = None \n line_len = None\n j = None\n if len(path) == 1:\n # itself\n assert(star_i == m)\n topo_length = 0\n line_len = 0\n j = star_i\n else:\n j = path[1]\n topo_length = length - self.proc_delay[j]/2.0 + self.proc_delay[m]/2.0\n line_len = self.ld[star_i][m] + self.proc_delay[m]\n # line_len = (math.sqrt(\n # (self.loc[star_i][0]-self.loc[m][0])**2+\n # (self.loc[star_i][1]-self.loc[m][1])**2 ) +self.proc_delay[m])\n\n dists[m] = (j, round(topo_length, 3), round(line_len, 3))\n self.dists_hist[star_i].append((epoch, dists))\n\n def save_dists_hist(self):\n if self.dist_file == 'None':\n return\n with open(self.dist_file, 'wb') as w:\n pickle.dump(self.dists_hist, w)\n\n def write_init_graph(self):\n with open(self.init_graph_conn, 'w') as w:\n graph_json = []\n for u in range(self.num_node):\n node = self.nodes[u]\n outs = sorted([int(i) for i in node.outs])\n ins = sorted([int(i) for i in node.ins])\n peer = {\n 'node': int(u),\n 'outs': outs,\n 'ins': ins\n }\n graph_json.append(peer)\n json.dump(graph_json, w, indent=4)\n\n\n def take_snapshot(self, epoch, curr_outs):\n name = \"epoch\"+str(epoch)+\".txt\"\n outpath = os.path.join(self.snapshot_dir, name)\n self.write_cost(outpath)\n outpath_exploit = os.path.join(self.snapshot_exploit_dir, name)\n self.write_exploit_cost(outpath_exploit, curr_outs)\n\n\n # def init_selectors(self, out_conns, in_conns):\n # for u in range(self.num_node):\n # # if smaller then it is adv\n # if u in self.adversary.sybils:\n # self.selectors[u] = Selector(u, True, out_conns[u], in_conns[u], None)\n # else:\n # self.selectors[u] = Selector(u, False, out_conns[u], in_conns[u], None)\n\n def broadcast_msgs(self, num_msg):\n time_tables = {i:defaultdict(list) for i in range(self.num_node)}\n abs_time_tables = {i:defaultdict(list) for i in range(self.num_node)}\n broads = []\n\n pubs = []\n probs = []\n for k, v in self.pub_prob.items():\n pubs.append(k)\n probs.append(v)\n\n for _ in range(num_msg):\n # p = random.choice(self.pubs)\n p = np.random.choice(pubs, size=1, replace=False, p=probs)[0]\n self.pub_hist.append(p)\n broads.append(p)\n\n comm_network.broadcast_msg(\n p, \n self.nodes, \n self.ld, \n time_tables, \n abs_time_tables\n )\n for i in range(self.num_node):\n self.sparse_tables[i].append_time(abs_time_tables[i], num_msg, 'abs_time')\n self.sparse_tables[i].append_time(time_tables[i], num_msg, 'rel_time')\n\n return broads\n\n def update_selectors(self, outs_conns, ins_conn):\n for i in range(self.num_node):\n self.selectors[i].update(outs_conns[i], ins_conn[i])\n\n def get_curr_ins(self, curr_outs):\n curr_ins = defaultdict(list)\n for u in range(self.num_node):\n for o in curr_outs[u]:\n curr_ins[o].append(u)\n return curr_ins\n\n def setup_conn_graph(self, curr_outs):\n curr_ins = self.get_curr_ins(curr_outs)\n for u in range(self.num_node):\n self.nodes[u].update_conns(curr_outs[u], curr_ins[u])\n\n\n def run_2hop(self, adapt_i, curr_out, e): \n slots = self.sparse_tables[adapt_i].table[-self.num_msg:]\n incomplete_table,M,nM,max_time,ids,ids_direct = construct_table(slots, adapt_i, self.directions)\n selected, rands = self.selectors[adapt_i].run(self.oracle, curr_out, ids, slots)\n\n return selected + rands\n\n def run(self):\n curr_outs = gen_rand_outs_with_oracle(self.num_out, self.num_node, self.oracle)\n self.oracle.check(curr_outs)\n\n self.setup_conn_graph(curr_outs)\n self.write_init_graph()\n\n for e in range(self.num_epoch):\n self.take_snapshot(e, curr_outs)\n self.oracle.check(curr_outs)\n ps = self.broadcast_msgs(self.num_msg)\n churn_adapts = comm_network.get_network_churning_nodes(self.churn_rate, self.adapts)\n for adapt_i in np.random.permutation(churn_adapts):\n curr_outs[adapt_i] = self.run_2hop(adapt_i, curr_outs[adapt_i], e)\n self.setup_conn_graph(curr_outs)\n for adapt_i in self.adapts:\n self.get_truth_distance(adapt_i, curr_outs[adapt_i][:self.num_keep], e)\n\n self.save_dists_hist()\n\n\n\n\n\n # while True:\n # network_state.reset(self.num_node, self.in_lim)\n\n # if num_snapshot == len(record_epochs):\n # break\n\n # if self.method == 'mc':\n # outs_conns, start_mc = self.run_mc(max_epoch,record_epochs, num_msg, epoch, network_state)\n # self.conns_snapshot.append(outs_conns)\n\n # if epoch in record_epochs:\n # self.take_snapshot(epoch)\n # num_snapshot += 1\n\n # elif self.method == '2hop':\n # outs_conns = self.run_2hop(num_msg, epoch, network_state)\n # self.conns_snapshot.append(outs_conns)\n\n # if epoch in record_epochs:\n # self.take_snapshot(epoch)\n # num_snapshot += 1\n\n # epoch += 1\n\n # def select_nodes(nodes, ld, num_msg, selectors, oracle, update_nodes, time_tables, in_lim, out_lim, network_state, num_keep, num_2hop, num_random):\n # outs_neighbors = {} # output container\n # num_invalid_compose = 0\n # # direct peers\n # num_rand_1hop = 0\n # for i in update_nodes:\n # keep_candidates = list(nodes[i].outs | nodes[i].ins )\n\n # composes = comb_subset.get_config(\n # num_keep, \n # keep_candidates,\n # len(keep_candidates), \n # network_state,\n # i)\n \n # num_invalid_compose += math.comb(len(keep_candidates), num_keep) - len(composes)\n # if len(composes) == 0:\n # peers = selectors[i].select_random_peers(nodes, num_keep, network_state)\n # num_rand_1hop += 1\n # # oracle needs to know the connection\n # oracle.update_1_hop_peers(i, peers)\n # outs_neighbors[i] = peers\n # else:\n # for compose in composes:\n # if len(compose) != len(set(compose)):\n # print('repeat in compose')\n # print(i)\n # print('composes', compose)\n # print(keep_candidates)\n # print('in', list(nodes[i].outs))\n # print('out', list(nodes[i].ins))\n # sys.exit(1)\n\n # peers = selectors[i].select_1hops(time_tables[i], composes, num_msg, network_state)\n # # oracle needs to know the connection\n # oracle.update_1_hop_peers(i, peers)\n # outs_neighbors[i] = peers\n\n\n # num_added_2hop = 0\n # num_added_3hop = 0\n # num_added_random = 0\n # tot_not_seen = 0\n # random.shuffle(update_nodes)\n # # two hop peers\n # if num_2hop > 0:\n # for u in update_nodes:\n # peers_info = oracle.get_multi_hop_info(u)\n # peers, num_not_seen = selectors[u].select_peers(\n # config.num_2_hop, nodes, peers_info.two_hops, network_state)\n # oracle.update_2_hop_peers(u, peers)\n # outs_neighbors[u] += peers\n # num_added_2hop += len(peers)\n\n # tot_not_seen += num_not_seen\n \n # # add 3hops\n # if out_lim - len(outs_neighbors[u]) > num_random:\n # num_3_hop = out_lim - len(outs_neighbors[u]) - num_random\n # peers_info = oracle.get_multi_hop_info(u)\n # peers, num_not_seen = selectors[u].select_peers(num_3_hop, nodes, peers_info.three_hops, network_state)\n # oracle.update_3_hop_peers(u, peers)\n # outs_neighbors[u] += peers\n # num_added_3hop += len(peers) \n # tot_not_seen += num_not_seen\n \n # # add random\n # for u in update_nodes:\n # num_random = out_lim - len(outs_neighbors[u]) \n # num_added_random += num_random\n\n # peers = selectors[u].select_random_peers(nodes, num_random, network_state)\n # for p in peers:\n # if p in outs_neighbors[u]:\n # print(p, 'in neigbors', outs_neighbors[u])\n # sys.exit(1)\n # outs_neighbors[u] += peers\n\n # # debug\n # for u in update_nodes:\n # if len(set(outs_neighbors[u])) != out_lim:\n # print(u, \"has less out neighbors\")\n # print(outs_neighbors[u])\n # print(selectors[u].desc_conn)\n # sys.exit(1)\n # print('num_rand_1hop', num_rand_1hop,'num_invalid_compose', num_invalid_compose )\n # # print('Finish. num2hop', num_added_2hop, 'num3hop', num_added_3hop, 'num rand', num_added_random, 'num no seen', tot_not_seen)\n # return outs_neighbors\n\n" ]
[ [ "torch.nn.Softmax", "torch.norm", "torch.tensor", "torch.topk", "torch.masked_select", "torch.nn.MSELoss" ], [ "numpy.random.permutation", "numpy.random.choice" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
instadeepai/EGTA-NMARL
[ "544b2e0e4b5518edefc6819975f9de4573ff434c", "544b2e0e4b5518edefc6819975f9de4573ff434c" ]
[ "egta/envs/tragedy/tests/test_tragedy.py", "egta/agents/policies.py" ]
[ "import torch\n\nfrom ..env import Tragedy\n\ndef test_defaults():\n env = Tragedy(regen_properties={\"type\":\"constant\", \"rate\": 0.075})\n obs = env.reset()\n print(\"start\", obs)\n new_obs, reward, done, _ = env.step(torch.tensor([0,]*4))\n print(\"obs\", new_obs)\n print(\"reward\", reward)\n print(\"done\", done)\n new_obs, reward, done, _ = env.step(torch.tensor([1,]*4))\n print(\"obs\", new_obs)\n print(\"reward\", reward)\n print(\"done\", done)\n # new_obs, reward, done, _ = env.step(torch.tensor([2,]*6))\n # print(\"obs\", new_obs)\n # print(\"reward\", reward)\n # print(\"done\", done)\n\n for _ in range(2):\n new_obs, reward, done, _ = env.step(torch.tensor([0,] + [1,]*3))\n print(\"obs\", new_obs)\n print(\"reward\", reward)\n print(\"done\", done)\n\n # for _ in range(2):\n # new_obs, reward, done, _ = env.step(torch.tensor([2,] + [1,]*5))\n # print(\"obs\", new_obs)\n # print(\"reward\", reward)\n # print(\"done\", done)\n\n for _ in range(2):\n new_obs, reward, done, _ = env.step(torch.tensor([1, 0] + [1,]*2))\n print(\"obs\", new_obs)\n print(\"reward\", reward)\n print(\"done\", done)\n\n for _ in range(2):\n new_obs, reward, done, _ = env.step(torch.tensor([[0,]*3 + [1,]]))\n print(\"obs\", new_obs)\n print(\"reward\", reward)\n print(\"done\", done)\n\n # for _ in range(2):\n # new_obs, reward, done, _ = env.step(torch.tensor([1, 2,] + [1,]*4))\n # print(\"obs\", new_obs)\n # print(\"reward\", reward)\n # print(\"done\", done)\n\n assert False\n\n# def test_defaults_batch_env():\n# env = Tragedy()\n# obs = env.reset()\n# print(\"start\", obs)\n# new_obs, reward, done, _ = env.step(torch.tensor([[0.3, 0.3, 0.2], [0.3, 0.3, 0.4]]))\n# print(\"obs\", new_obs)\n# print(\"reward\", reward)\n# print(\"done\", done)\n# new_obs, reward, done, _ = env.step(torch.tensor([[0.3, 0.3, 0.3], [0.1, 0.1, 0.2]]))\n# print(\"obs\", new_obs)\n# print(\"reward\", reward)\n# print(\"done\", done)\n# new_obs, reward, done, _ = env.step(torch.tensor([[0.33, 0.33, 0.35], [0.34, 0.33, 0.32]]))\n# print(\"obs\", new_obs)\n# print(\"reward\", reward)\n# print(\"done\", done)\n# assert False\n\n# def test_discrete_binary_batch_env():\n# env = Tragedy(num_agents=3, batch_size=2, action_space=\"discrete\")\n# obs = env.reset()\n# print(\"start\", obs)\n# new_obs, reward, done, _ = env.step(torch.tensor([[0, 1, 0], [0, 0, 0]]))\n# print(\"obs\", new_obs)\n# print(\"reward\", reward)\n# print(\"done\", done)\n# new_obs, reward, done, _ = env.step(torch.tensor([[1, 0, 1], [1, 1, 1]]))\n# print(\"obs\", new_obs)\n# print(\"reward\", reward)\n# print(\"done\", done)\n# new_obs, reward, done, _ = env.step(torch.tensor([[1, 1, 0], [0, 0, 0]]))\n# print(\"obs\", new_obs)\n# print(\"reward\", reward)\n# print(\"done\", done)\n# assert False\n\n# def test_discrete_trinary_batch_env():\n# env = Tragedy(num_agents=3, batch_size=2, action_space=\"discrete\")\n# obs = env.reset()\n# print(\"start\", obs)\n\n# for _ in range(6):\n# new_obs, reward, done, _ = env.step(torch.tensor([[0, 0, 0], [0, 0, 0]]))\n# print(\"obs\", new_obs)\n# print(\"reward\", reward)\n# print(\"done\", done)\n\n# for _ in range(20):\n# new_obs, reward, done, _ = env.step(torch.tensor([[2, 2, 2], [2, 2, 2]]))\n# print(\"obs\", new_obs)\n# print(\"reward\", reward)\n# print(\"done\", done)\n\n# assert False", "import numpy as np\nimport tensorflow as tf\n\nfrom .utils import *\n\nclass Policy:\n def __init__(self, n_a, n_s, n_step, policy_name, agent_name, identical):\n self.name = policy_name\n if agent_name is not None:\n # for multi-agent system\n self.name += '_' + str(agent_name)\n self.n_a = n_a\n self.n_s = n_s\n self.n_step = n_step\n self.identical = identical\n\n def forward(self, ob, *_args, **_kwargs):\n raise NotImplementedError()\n\n def prepare_loss(self, v_coef, e_coef, max_grad_norm, alpha, epsilon, optimizer):\n self.A = tf.placeholder(tf.int32, [self.n_step])\n self.ADV = tf.placeholder(tf.float32, [self.n_step])\n self.R = tf.placeholder(tf.float32, [self.n_step])\n A_sparse = tf.one_hot(self.A, self.n_a)\n log_pi = tf.log(tf.clip_by_value(self.pi, 1e-10, 1.0))\n entropy = -tf.reduce_sum(self.pi * log_pi, axis=1)\n entropy_loss = -tf.reduce_mean(entropy) * e_coef\n policy_loss = -tf.reduce_mean(tf.reduce_sum(log_pi * A_sparse, axis=1) * self.ADV)\n value_loss = tf.reduce_mean(tf.square(self.R - self.v)) * 0.5 * v_coef\n self.loss = policy_loss + value_loss + entropy_loss\n\n wts = tf.trainable_variables(scope=self.name)\n grads = tf.gradients(self.loss, wts)\n if max_grad_norm > 0:\n grads, self.grad_norm = tf.clip_by_global_norm(grads, max_grad_norm)\n self.lr = tf.placeholder(tf.float32, [])\n\n if optimizer == \"nadam\":\n raise NotImplementedError(\"There are bugs in the Nadam implementation.\")\n self.optimizer = tf.keras.optimizers.Nadam(\n lr=self.lr, epsilon=epsilon,\n )\n elif optimizer == \"adam\":\n self.optimizer = tf.train.AdamOptimizer(\n learning_rate=self.lr, epsilon=epsilon,\n )\n elif optimizer == \"rmsprop\":\n self.optimizer = tf.train.RMSPropOptimizer(learning_rate=self.lr, decay=alpha,\n epsilon=epsilon)\n else:\n raise ValueError(\"not a valid argument for optimizer.\")\n\n self._train = self.optimizer.apply_gradients(list(zip(grads, wts)))\n # monitor training\n summaries = []\n summaries.append(tf.summary.scalar('loss/%s_entropy_loss' % self.name, entropy_loss))\n summaries.append(tf.summary.scalar('loss/%s_policy_loss' % self.name, policy_loss))\n summaries.append(tf.summary.scalar('loss/%s_value_loss' % self.name, value_loss))\n summaries.append(tf.summary.scalar('loss/%s_total_loss' % self.name, self.loss))\n summaries.append(tf.summary.scalar('train/%s_lr' % self.name, self.lr))\n summaries.append(tf.summary.scalar('train/%s_gradnorm' % self.name, self.grad_norm))\n self.summary = tf.summary.merge(summaries)\n\n def _build_actor_head(self, h, n_a=None, agent_name=None):\n name = 'pi'\n if agent_name is not None:\n name += '_' + str(agent_name)\n if n_a is None:\n n_a = self.n_a\n pi = fc(h, name, n_a, act=tf.nn.softmax)\n return pi\n\n def _build_critic_head(self, h, na, n_n=None, agent_name=None):\n name = 'v'\n if agent_name is not None:\n name += '_' + str(agent_name)\n if n_n is None:\n n_n = int(self.n_n)\n if n_n:\n if self.identical:\n na_sparse = tf.one_hot(na, self.n_a, axis=-1)\n na_sparse = tf.reshape(na_sparse, [-1, self.n_a*n_n])\n else:\n na_sparse = []\n na_ls = tf.split(axis=1, num_or_size_splits=n_n, value=na)\n for na_val, na_dim in zip(na_ls, self.na_dim_ls):\n na_sparse.append(tf.squeeze(tf.one_hot(na_val, na_dim, axis=-1), axis=1))\n na_sparse = tf.concat(na_sparse, 1)\n h = tf.concat([h, na_sparse], 1)\n v = fc(h, name, 1, act=lambda x: x)\n return v\n\n\nclass LstmPolicy(Policy):\n def __init__(self, n_s, n_a, n_n, n_step, n_fc=64, n_lstm=64, name=None,\n na_dim_ls=None, identical=True):\n \"\"\"\n class: an LSTM policy for a single agent\n ----------\n parameters\n ----------\n n_s, int or tupl: number of elements in state vector (cacc & ATCS) / shape of state tensor (cleanup & harvest)\n n_a, int: number of discrete actions allowed\n n_n, int: number of neighbors adjancet to the agent\n n_step, int: batch size for training\n n_fc, int: number of units in FC layer\n n_lstm, int: number of hidden units in LSTM cell\n\n \"\"\"\n super().__init__(n_a, n_s, n_step, 'lstm', name, identical)\n if not self.identical:\n self.na_dim_ls = na_dim_ls\n self.n_lstm = n_lstm\n self.n_fc = n_fc\n self.n_n = n_n\n\n # NEW ------------------------------------------------\n self.img_dims, self.vec_dims = n_s\n n_agents, features = self.img_dims[0], self.img_dims[1]\n # n_agents, h, w, n_c = self.img_dims[0], self.img_dims[1], self.img_dims[2], self.img_dims[3]\n self.ob_im_fw = tf.placeholder(tf.float32, [1, n_agents, features]) # img portion of obs (1, 15, 15, 3)\n # self.ob_im_fw = tf.placeholder(tf.float32, [1, n_agents, h, w, n_c]) # img portion of obs (1, 15, 15, 3)\n self.ob_im_bw = tf.placeholder(tf.float32, [n_step, n_agents, features])\n # self.ob_im_bw = tf.placeholder(tf.float32, [n_step, n_agents, h, w, n_c])\n self.ob_vec_fw = tf.placeholder(tf.float32, [1, self.vec_dims]) # other state info to be passed into model other than img (e.g. finger prints)\n self.ob_vec_bw = tf.placeholder(tf.float32, [n_step, self.vec_dims])\n # NEW -------------------------------------------------\n\n if self.n_n:\n self.naction_fw = tf.placeholder(tf.int32, [1, n_n]) # neighbor actions forward pass\n self.naction_bw = tf.placeholder(tf.int32, [n_step, n_n]) # neighbor actions packward pass\n\n self.done_fw = tf.placeholder(tf.float32, [1])\n self.done_bw = tf.placeholder(tf.float32, [n_step])\n self.states = tf.placeholder(tf.float32, [n_lstm * 2]) # hidden states in lstm\n\n with tf.variable_scope(self.name):\n self.pi_fw, self.v_fw, self.new_states = self._build_net('forward')\n with tf.variable_scope(self.name, reuse=True):\n self.pi, self.v, _ = self._build_net('backward')\n self._reset()\n\n def backward(self, sess, obs, nactions, acts, dones, Rs, Advs, cur_lr,\n summary_writer=None, global_step=None):\n # NEW ---------------------------------\n ob_im, ob_vec = obs[:,0], obs[:,1]\n ob_im = np.stack(ob_im, axis=0).astype(np.float32)\n ob_vec = np.stack(ob_vec, axis=0).astype(np.float32)\n\n if len(ob_im.shape) < 3:\n ob_im = ob_im[:, :, None]\n\n ins = {self.ob_im_bw: ob_im,\n self.ob_vec_bw: ob_vec,\n self.done_bw: dones,\n self.states: self.states_bw,\n self.A: acts,\n self.ADV: Advs,\n self.R: Rs,\n self.lr: cur_lr}\n # NEW ---------------------------------\n if self.n_n:\n ins[self.naction_bw] = nactions\n summary, _ = sess.run([self.summary, self._train], ins)\n self.states_bw = np.copy(self.states_fw)\n if summary_writer is not None:\n summary_writer.add_summary(summary, global_step=global_step)\n\n def forward(self, sess, ob, done, naction=None, out_type='p'):\n # update state only when p is called\n # NEW -----------------------------------------\n ob_im, ob_vec = ob[0], ob[1]\n if len(ob_im.shape) < 2:\n ob_im = ob_im[:, None]\n\n ins = {self.ob_im_fw: np.array([ob_im]),\n self.ob_vec_fw : np.array([ob_vec]),\n self.done_fw: np.array([done]),\n self.states: self.states_fw}\n # NEW -----------------------------------------\n if out_type.startswith('p'):\n outs = [self.pi_fw, self.new_states]\n else:\n outs = [self.v_fw]\n if self.n_n:\n ins[self.naction_fw] = np.array([naction])\n out_values = sess.run(outs, ins)\n out_value = out_values[0]\n if out_type.startswith('p'):\n self.states_fw = out_values[-1]\n return out_value\n\n def _build_net(self, in_type):\n if in_type == 'forward':\n ob_im = self.ob_im_fw\n ob_vec = self.ob_vec_fw # can ignore in ia2c\n done = self.done_fw\n naction = self.naction_fw if self.n_n else None\n else:\n ob_im = self.ob_im_bw\n ob_vec = self.ob_vec_bw # can ignore in ia2c\n done = self.done_bw\n naction = self.naction_bw if self.n_n else None\n\n # NEW ---------------------------------------------------------\n if self.n_n > 0:\n h = []\n for i in range(self.n_n): # each agent gets the local obs from its neighbours\n scope = '{}_conv_{}'.format(self.name, i)\n # h_i = conv_to_linear(x=ob_im[:,i], scope=scope, n_out=self.n_fc)\n h_i = fc(x=ob_im[:,i], scope=scope, n_out=self.n_fc)\n h.append(h_i)\n h = tf.concat(h, axis=1)\n h = fc(h, 'fc', self.n_fc)\n else:\n h = fc(ob_im[:,0], 'fc', self.n_fc)\n # NEW ---------------------------------------------------------\n\n h, new_states = lstm(h, done, self.states, 'lstm')\n pi = self._build_actor_head(h)\n v = self._build_critic_head(h, naction)\n return tf.squeeze(pi), tf.squeeze(v), new_states\n\n def _reset(self):\n # forget the cumulative states every cum_step\n self.states_fw = np.zeros(self.n_lstm * 2, dtype=np.float32)\n self.states_bw = np.zeros(self.n_lstm * 2, dtype=np.float32)\n\n\nclass FPPolicy(LstmPolicy):\n def __init__(self, n_s, n_a, n_n, n_step, n_fc=64, n_lstm=64, name=None,\n na_dim_ls=None, identical=True):\n \"\"\"\n n_s = dim(obs) + n_neighbours * n_actions\n \"\"\"\n super().__init__(n_s, n_a, n_n, n_step, n_fc, n_lstm, name,\n na_dim_ls, identical)\n\n def _build_net(self, in_type):\n if in_type == 'forward':\n ob_im = self.ob_im_fw\n ob_vec = self.ob_vec_fw\n done = self.done_fw\n naction = self.naction_fw if self.n_n else None\n else:\n ob_im = self.ob_im_bw\n ob_vec = self.ob_vec_bw\n done = self.done_bw\n naction = self.naction_bw if self.n_n else None\n # NEW ----------------------------------------------------------------------\n # pass img obs through conv_2_linear and through an fc layer\n h_im = []\n for i in range(self.n_n): # each agent gets the local obs from its neighbours\n scope = '{}_conv_{}'.format(self.name, i)\n # h_i = conv_to_linear(x=ob_im[:,i], scope=scope, n_out=self.n_fc)\n h_i = fc(x=ob_im[:,i], scope=scope, n_out=self.n_fc)\n h_im.append(h_i)\n h_im = tf.concat(h_im, axis=1)\n h_im = fc(h_im, 'fc', self.n_fc)\n\n # separately, pass finger print vector through fc layer (if agent has neighbours)\n if self.n_n:\n h = tf.concat([h_im, ob_vec], axis=1)\n else:\n h = h_im\n # NEW --------------------------------------------------------------------------\n h, new_states = lstm(h, done, self.states, 'lstm')\n pi = self._build_actor_head(h)\n v = self._build_critic_head(h, naction)\n return tf.squeeze(pi), tf.squeeze(v), new_states\n\n\nclass NCMultiAgentPolicy(Policy):\n \"\"\" Inplemented as a centralized meta-DNN. To simplify the implementation, all input\n and output dimensions are identical among all agents, and invalid values are casted as\n zeros during runtime.\"\"\"\n def __init__(self, n_s, n_a, n_agent, n_step, neighbor_mask, n_fc=64, n_h=64,\n n_s_ls=None, n_a_ls=None, identical=True):\n super().__init__(n_a, n_s, n_step, 'nc', None, identical)\n if not self.identical:\n self.n_s_ls = n_s_ls\n self.n_a_ls = n_a_ls\n self._init_policy(n_agent, neighbor_mask, n_h, n_fc)\n\n def backward(self, sess, obs, policies, acts, dones, Rs, Advs, cur_lr,\n summary_writer=None, global_step=None):\n\n if obs.shape == self.ob_bw.shape:\n summary, _ = sess.run([self.summary, self._train],\n {self.ob_bw: obs,\n self.policy_bw: policies,\n self.action_bw: acts,\n self.done_bw: dones,\n self.states: self.states_bw,\n self.ADV: Advs,\n self.R: Rs,\n self.lr: cur_lr})\n self.states_bw = np.copy(self.states_fw)\n if summary_writer is not None:\n summary_writer.add_summary(summary, global_step=global_step)\n\n def forward(self, sess, ob, done, policy, action=None, out_type='p'):\n # update state only when p is called\n # ins = {self.ob_fw: np.expand_dims(np.expand_dims(ob, axis=1), axis=1),\n ins = {self.ob_fw: np.expand_dims(ob, axis=1),\n self.done_fw: np.expand_dims(done, axis=1),\n self.policy_fw: np.expand_dims(policy, axis=1),\n self.states: self.states_fw}\n if out_type.startswith('p'):\n outs = [self.pi_fw, self.new_states]\n else:\n outs = [self.v_fw]\n ins[self.action_fw] = np.expand_dims(action, axis=1)\n out_values = sess.run(outs, ins)\n out_value = out_values[0]\n if out_type.startswith('p'):\n self.states_fw = out_values[-1]\n return out_value\n\n def prepare_loss(self, v_coef, e_coef, max_grad_norm, alpha, epsilon, optimizer):\n self.ADV = tf.placeholder(tf.float32, [self.n_agent, self.n_step])\n self.R = tf.placeholder(tf.float32, [self.n_agent, self.n_step])\n # all losses are averaged over steps but summed over agents\n if self.identical:\n A_sparse = tf.one_hot(self.action_bw, self.n_a)\n log_pi = tf.log(tf.clip_by_value(self.pi, 1e-10, 1.0))\n entropy = -tf.reduce_sum(self.pi * log_pi, axis=-1) # NxT\n prob_pi = tf.reduce_sum(log_pi * A_sparse, axis=-1) # NxT\n else:\n entropy = []\n prob_pi = []\n for i, pi_i in enumerate(self.pi):\n action_i = tf.slice(self.action_bw, [i, 0], [1, self.n_step])\n A_sparse_i = tf.one_hot(action_i, self.n_a_ls[i])\n log_pi_i = tf.log(tf.clip_by_value(pi_i, 1e-10, 1.0))\n entropy.append(tf.expand_dims(-tf.reduce_sum(pi_i * log_pi_i, axis=-1), axis=0))\n prob_pi.append(tf.expand_dims(tf.reduce_sum(log_pi_i * A_sparse_i, axis=-1), axis=0))\n entropy = tf.concat(entropy, axis=0)\n prob_pi = tf.concat(prob_pi, axis=0)\n entropy_loss = -tf.reduce_sum(tf.reduce_mean(entropy, axis=-1)) * e_coef\n policy_loss = -tf.reduce_sum(tf.reduce_mean(prob_pi * self.ADV, axis=-1))\n value_loss = tf.reduce_sum(tf.reduce_mean(tf.square(self.R - self.v), axis=-1)) * 0.5 * v_coef\n self.loss = policy_loss + value_loss + entropy_loss\n\n wts = tf.trainable_variables(scope=self.name)\n grads = tf.gradients(self.loss, wts)\n if max_grad_norm > 0:\n grads, self.grad_norm = tf.clip_by_global_norm(grads, max_grad_norm)\n self.lr = tf.placeholder(tf.float32, [])\n\n if optimizer == \"nadam\":\n raise NotImplementedError(\"There are bugs in the Nadam implementation.\")\n self.optimizer = tf.keras.optimizers.Nadam(\n lr=self.lr, epsilon=epsilon,\n )\n elif optimizer == \"adam\":\n self.optimizer = tf.train.AdamOptimizer(\n learning_rate=self.lr, epsilon=epsilon,\n )\n elif optimizer == \"rmsprop\":\n self.optimizer = tf.train.RMSPropOptimizer(learning_rate=self.lr, decay=alpha,\n epsilon=epsilon)\n else:\n raise ValueError(\"not a valid argument for optimizer.\")\n\n self._train = self.optimizer.apply_gradients(list(zip(grads, wts)))\n # monitor training\n summaries = []\n summaries.append(tf.summary.scalar('loss/%s_entropy_loss' % self.name, entropy_loss))\n summaries.append(tf.summary.scalar('loss/%s_policy_loss' % self.name, policy_loss))\n summaries.append(tf.summary.scalar('loss/%s_value_loss' % self.name, value_loss))\n summaries.append(tf.summary.scalar('loss/%s_total_loss' % self.name, self.loss))\n summaries.append(tf.summary.scalar('train/%s_lr' % self.name, self.lr))\n summaries.append(tf.summary.scalar('train/%s_gradnorm' % self.name, self.grad_norm))\n self.summary = tf.summary.merge(summaries)\n\n def _build_net(self, in_type):\n if in_type == 'forward':\n ob = self.ob_fw\n policy = self.policy_fw\n action = self.action_fw\n done = self.done_fw\n else:\n ob = self.ob_bw\n policy = self.policy_bw\n action = self.action_bw\n done = self.done_bw\n\n # NEW: Conv and FC layers -----------------------------------------\n h = []\n for i in range(self.n_agent):\n # conv_scope = 'conv_agent_{}'.format(i)\n fc_scope = 'fc_agent_{}'.format(i)\n # h_i = conv_to_linear(x=ob[i], scope=conv_scope, n_out=self.n_fc) # local state\n # h_i = fc(x=h_i, scope=fc_scope, n_out=self.n_fc)\n h_i = fc(x=ob[i], scope=fc_scope, n_out=self.n_fc)\n h.append(h_i)\n h = tf.reshape(tf.concat(h, axis=0), shape=[self.n_agent,-1,self.n_fc])\n # NEW: Conv and FC layers -----------------------------------------\n\n if self.identical:\n h, new_states = lstm_comm(h, policy, done, self.neighbor_mask, self.states, 'lstm_comm')\n else:\n h, new_states = lstm_comm_hetero(h, policy, done, self.neighbor_mask, self.states,\n self.n_s_ls, self.n_a_ls, 'lstm_comm')\n pi_ls = []\n v_ls = []\n for i in range(self.n_agent):\n h_i = h[i] # Txn_h\n if self.identical:\n pi = self._build_actor_head(h_i, agent_name='%d' % i)\n pi_ls.append(tf.expand_dims(pi, axis=0))\n n_n = int(np.sum(self.neighbor_mask[i]))\n else:\n pi = self._build_actor_head(h_i, n_a=self.n_a_ls[i], agent_name='%d' % i)\n pi_ls.append(tf.squeeze(pi))\n self.na_dim_ls = [self.n_a_ls[j] for j in np.where(self.neighbor_mask[i] == 1)[0]]\n n_n = len(self.na_dim_ls)\n if n_n:\n naction_i = tf.transpose(tf.boolean_mask(action, self.neighbor_mask[i])) # Txn_n\n else:\n naction_i = None\n v = self._build_critic_head(h_i, naction_i, n_n=n_n, agent_name='%d' % i)\n v_ls.append(tf.expand_dims(v, axis=0))\n if self.identical:\n pi_ls = tf.squeeze(tf.concat(pi_ls, axis=0))\n return pi_ls, tf.squeeze(tf.concat(v_ls, axis=0)), new_states\n\n def _init_policy(self, n_agent, neighbor_mask, n_h, n_fc):\n self.n_agent = n_agent\n self.neighbor_mask = neighbor_mask #n_agent x n_agent\n self.n_h = n_h # hidden units in LSTM\n # NEW ------------------------------------------------------------------------\n self.n_fc = n_fc\n _, features = self.n_s\n # _, height, width, channel = self.n_s\n self.ob_fw = tf.placeholder(tf.float32, [n_agent, 1, features]) # forward 1-step\n # self.ob_fw = tf.placeholder(tf.float32, [n_agent, 1, height, width, channel]) # forward 1-step\n # NEW ------------------------------------------------------------------------\n self.policy_fw = tf.placeholder(tf.float32, [n_agent, 1, self.n_a])\n self.action_fw = tf.placeholder(tf.int32, [n_agent, 1])\n self.done_fw = tf.placeholder(tf.float32, [1])\n # NEW ------------------------------------------------------------------------\n self.ob_bw = tf.placeholder(tf.float32, [n_agent, self.n_step, features]) # backward n-step\n # self.ob_bw = tf.placeholder(tf.float32, [n_agent, self.n_step, height, width, channel]) # backward n-step\n # NEW ------------------------------------------------------------------------\n self.policy_bw = tf.placeholder(tf.float32, [n_agent, self.n_step, self.n_a])\n self.action_bw = tf.placeholder(tf.int32, [n_agent, self.n_step])\n self.done_bw = tf.placeholder(tf.float32, [self.n_step])\n self.states = tf.placeholder(tf.float32, [n_agent, n_h * 2])\n\n with tf.variable_scope(self.name):\n self.pi_fw, self.v_fw, self.new_states = self._build_net('forward')\n with tf.variable_scope(self.name, reuse=True):\n self.pi, self.v, _ = self._build_net('backward')\n self._reset()\n\n def _reset(self):\n self.states_fw = np.zeros((self.n_agent, self.n_h * 2), dtype=np.float32)\n self.states_bw = np.zeros((self.n_agent, self.n_h * 2), dtype=np.float32)\n\n\nclass ConsensusPolicy(NCMultiAgentPolicy):\n def __init__(self, n_s, n_a, n_agent, n_step, neighbor_mask, n_fc=64, n_h=64,\n n_s_ls=None, n_a_ls=None, identical=True):\n Policy.__init__(self, n_a, n_s, n_step, 'cu', None, identical)\n if not self.identical:\n self.n_s_ls = n_s_ls\n self.n_a_ls = n_a_ls\n self.n_agent = n_agent\n self.n_h = n_h\n self.neighbor_mask = neighbor_mask\n self._init_policy(n_agent, neighbor_mask, n_h, n_fc)\n\n def backward(self, sess, obs, policies, acts, dones, Rs, Advs, cur_lr,\n summary_writer=None, global_step=None):\n super().backward(sess, obs, policies, acts, dones, Rs, Advs, cur_lr,\n summary_writer, global_step)\n sess.run(self._consensus_update)\n\n def prepare_loss(self, v_coef, e_coef, max_grad_norm, alpha, epsilon, optimizer):\n super().prepare_loss(v_coef, e_coef, max_grad_norm, alpha, epsilon, optimizer)\n consensus_update = []\n for i in range(self.n_agent):\n wt_from, wt_to = self._get_critic_wts(i)\n for w1, w2 in zip(wt_from, wt_to):\n consensus_update.append(w2.assign(w1))\n self._consensus_update = tf.group(*consensus_update)\n\n def _build_net(self, in_type):\n if in_type == 'forward':\n ob = self.ob_fw\n done = self.done_fw\n action = self.action_fw\n else:\n ob = self.ob_bw\n done = self.done_bw\n action = self.action_bw\n pi_ls = []\n v_ls = []\n new_states_ls = []\n for i in range(self.n_agent):\n # NEW -----------------------------------------------------------\n # h_i = conv_to_linear(x=ob[i], scope='conv_%da' % i, n_out=self.n_fc) # local state\n # NEW -------------------------------------------------------------\n # h_i = fc(x=ob_im[i], scope=scope, n_out=self.n_fc)\n h_i = fc(ob[i], 'fc_%da' % i, self.n_h)\n # h_i = fc(h_i, 'fc_%da' % i, self.n_h)\n h_i, new_states = lstm(h_i, done, self.states[i], 'lstm_%da' % i)\n if self.identical:\n pi = self._build_actor_head(h_i, agent_name='%d' % i)\n pi_ls.append(tf.expand_dims(pi, axis=0))\n n_n = int(np.sum(self.neighbor_mask[i]))\n else:\n pi = self._build_actor_head(h_i, n_a=self.n_a_ls[i], agent_name='%da' % i)\n pi_ls.append(tf.squeeze(pi))\n self.na_dim_ls = [self.n_a_ls[j] for j in np.where(self.neighbor_mask[i] == 1)[0]]\n n_n = len(self.na_dim_ls)\n if n_n:\n naction = tf.transpose(tf.boolean_mask(action, self.neighbor_mask[i]))\n else:\n naction = None\n v = self._build_critic_head(h_i, naction, n_n=n_n, agent_name='%da' % i)\n v_ls.append(tf.expand_dims(v, axis=0))\n new_states_ls.append(tf.expand_dims(new_states, axis=0))\n if self.identical:\n pi_ls = tf.squeeze(tf.concat(pi_ls, axis=0))\n v_ls = tf.squeeze(tf.concat(v_ls, axis=0))\n new_states_ls = tf.squeeze(tf.concat(new_states_ls, axis=0))\n return pi_ls, v_ls, new_states_ls\n\n def _get_critic_wts(self, agent_i):\n neighbor_mask = self.neighbor_mask[agent_i]\n agents = [agent_i] + list(np.where(neighbor_mask == 1)[0])\n wt_i = []\n wt_n = []\n for i in agents:\n critic_scope = [self.name + ('/lstm_%da' % i)]\n wt = []\n for scope in critic_scope:\n wt += tf.trainable_variables(scope=scope)\n if i == agent_i:\n wt_i = wt\n wt_n.append(wt)\n mean_wt_n = []\n n_n = len(wt_n)\n n_w = len(wt_n[0])\n for i in range(n_w):\n cur_wts = []\n for j in range(n_n):\n cur_wts.append(tf.expand_dims(wt_n[j][i], axis=-1))\n cur_wts = tf.concat(cur_wts, axis=-1)\n cur_wts = tf.reduce_mean(cur_wts, axis=-1)\n mean_wt_n.append(cur_wts)\n return mean_wt_n, wt_i\n\n# IC3 -> CommNet\nclass IC3MultiAgentPolicy(NCMultiAgentPolicy):\n \"\"\"Reference code: https://github.com/IC3Net/IC3Net/blob/master/comm.py.\n Note in IC3, the message is generated from hidden state only, so current state\n and neigbor policies are not included in the inputs.\"\"\"\n def __init__(self, n_s, n_a, n_agent, n_step, neighbor_mask, n_fc=64, n_h=64,\n n_s_ls=None, n_a_ls=None, identical=True):\n Policy.__init__(self, n_a, n_s, n_step, 'ic3', None, identical)\n if not self.identical:\n self.n_s_ls = n_s_ls\n self.n_a_ls = n_a_ls\n self._init_policy(n_agent, neighbor_mask, n_h, n_fc)\n\n def _build_net(self, in_type):\n if in_type == 'forward':\n ob = self.ob_fw\n action = self.action_fw\n done = self.done_fw\n else:\n ob = self.ob_bw\n action = self.action_bw\n done = self.done_bw\n\n # NEW: Conv and FC layers -----------------------------------------\n h = []\n for i in range(self.n_agent):\n # conv_scope = 'conv_agent_{}'.format(i)\n fc_scope = 'fc_agent_{}'.format(i)\n # h_i = conv_to_linear(x=ob[i], scope=conv_scope, n_out=self.n_fc) # local state\n # h_i = fc(x=h_i, scope=fc_scope, n_out=self.n_fc)\n h_i = fc(x=ob[i], scope=fc_scope, n_out=self.n_fc)\n h.append(h_i)\n h = tf.reshape(tf.concat(h, axis=0), shape=[self.n_agent,-1,self.n_fc])\n # NEW: Conv and FC layers -----------------------------------------\n\n if self.identical:\n h, new_states = lstm_ic3(h, done, self.neighbor_mask, self.states, 'lstm_ic3')\n else:\n h, new_states = lstm_ic3_hetero(h, done, self.neighbor_mask, self.states,\n self.n_s_ls, self.n_a_ls, 'lstm_ic3')\n pi_ls = []\n v_ls = []\n for i in range(self.n_agent):\n h_i = h[i] # Txn_h\n if self.identical:\n pi = self._build_actor_head(h_i, agent_name='%d' % i)\n pi_ls.append(tf.expand_dims(pi, axis=0))\n n_n = int(np.sum(self.neighbor_mask[i]))\n else:\n pi = self._build_actor_head(h_i, n_a=self.n_a_ls[i], agent_name='%d' % i)\n pi_ls.append(tf.squeeze(pi))\n self.na_dim_ls = [self.n_a_ls[j] for j in np.where(self.neighbor_mask[i] == 1)[0]]\n n_n = len(self.na_dim_ls)\n if n_n:\n naction_i = tf.transpose(tf.boolean_mask(action, self.neighbor_mask[i])) # Txn_n\n else:\n naction_i = None\n v = self._build_critic_head(h_i, naction_i, n_n=n_n, agent_name='%d' % i)\n v_ls.append(tf.expand_dims(v, axis=0))\n if self.identical:\n pi_ls = tf.squeeze(tf.concat(pi_ls, axis=0))\n return pi_ls, tf.squeeze(tf.concat(v_ls, axis=0)), new_states\n\n\nclass DIALMultiAgentPolicy(NCMultiAgentPolicy):\n def __init__(self, n_s, n_a, n_agent, n_step, neighbor_mask, n_fc=64, n_h=64,\n n_s_ls=None, n_a_ls=None, identical=True):\n Policy.__init__(self, n_a, n_s, n_step, 'dial', None, identical)\n if not self.identical:\n self.n_s_ls = n_s_ls\n self.n_a_ls = n_a_ls\n self._init_policy(n_agent, neighbor_mask, n_h, n_fc)\n\n def _build_net(self, in_type):\n if in_type == 'forward':\n ob = self.ob_fw\n policy = self.policy_fw\n action = self.action_fw\n done = self.done_fw\n else:\n ob = self.ob_bw\n policy = self.policy_bw\n action = self.action_bw\n done = self.done_bw\n\n # NEW: Conv and FC layers -----------------------------------------\n h = []\n for i in range(self.n_agent):\n # conv_scope = 'conv_agent_{}'.format(i)\n fc_scope = 'fc_agent_{}'.format(i)\n # h_i = conv_to_linear(x=ob[i], scope=conv_scope, n_out=self.n_fc) # local state\n # h_i = fc(x=h_i, scope=fc_scope, n_out=self.n_fc)\n h_i = fc(x=ob[i], scope=fc_scope, n_out=self.n_fc)\n h.append(h_i)\n h = tf.reshape(tf.concat(h, axis=0), shape=[self.n_agent,-1,self.n_fc])\n # NEW: Conv and FC layers -----------------------------------------\n\n if self.identical:\n h, new_states = lstm_dial(h, policy, done, self.neighbor_mask, self.states, 'lstm_comm')\n else:\n h, new_states = lstm_dial_hetero(h, policy, done, self.neighbor_mask, self.states,\n self.n_s_ls, self.n_a_ls, 'lstm_comm')\n pi_ls = []\n v_ls = []\n for i in range(self.n_agent):\n h_i = h[i] # Txn_h\n if self.identical:\n pi = self._build_actor_head(h_i, agent_name='%d' % i)\n pi_ls.append(tf.expand_dims(pi, axis=0))\n n_n = int(np.sum(self.neighbor_mask[i]))\n else:\n pi = self._build_actor_head(h_i, n_a=self.n_a_ls[i], agent_name='%d' % i)\n pi_ls.append(tf.squeeze(pi))\n self.na_dim_ls = [self.n_a_ls[j] for j in np.where(self.neighbor_mask[i] == 1)[0]]\n n_n = len(self.na_dim_ls)\n if n_n:\n naction_i = tf.transpose(tf.boolean_mask(action, self.neighbor_mask[i])) # Txn_n\n else:\n naction_i = None\n v = self._build_critic_head(h_i, naction_i, n_n=n_n, agent_name='%d' % i)\n v_ls.append(tf.expand_dims(v, axis=0))\n if self.identical:\n pi_ls = tf.squeeze(tf.concat(pi_ls, axis=0))\n return pi_ls, tf.squeeze(tf.concat(v_ls, axis=0)), new_states\n" ]
[ [ "torch.tensor" ], [ "numpy.expand_dims", "tensorflow.concat", "tensorflow.reduce_sum", "tensorflow.train.AdamOptimizer", "tensorflow.group", "tensorflow.summary.scalar", "numpy.where", "tensorflow.boolean_mask", "tensorflow.keras.optimizers.Nadam", "tensorflow.gradients", "tensorflow.squeeze", "numpy.stack", "numpy.copy", "tensorflow.square", "tensorflow.trainable_variables", "numpy.zeros", "tensorflow.train.RMSPropOptimizer", "tensorflow.placeholder", "tensorflow.one_hot", "tensorflow.split", "numpy.array", "tensorflow.summary.merge", "numpy.sum", "tensorflow.clip_by_value", "tensorflow.reduce_mean", "tensorflow.slice", "tensorflow.reshape", "tensorflow.expand_dims", "tensorflow.clip_by_global_norm", "tensorflow.variable_scope" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
BYUignite/ODT
[ "291d6ff9ae5813aed3135dc22525c9f0fc99282a", "291d6ff9ae5813aed3135dc22525c9f0fc99282a" ]
[ "post/coldJet/uucl_rxx0.py", "post/coldJet/intTKEdiss_xD.py" ]
[ "#plots U/UcL vs. r/(x-x0)\n#plot file directory/name at end of function definition\n\nfrom __future__ import division\nimport numpy as np\nfrom data_tools import get_inputFileParameter\nimport matplotlib\nmatplotlib.use('PDF') # or Agg (for png), SVG, PS\nimport matplotlib.pyplot as plt\nfrom data_tools import commentHdr\n\n#-------------------------------------------------------------------------------------\n\ndef uucl_rxx0(DI, profName=\"uvel\"): #use list of cases\n\n cases=[]\n #plotname=\"uucl_rxx0\"\n plotname=\"uucl_rxx0_xD\" #for plotting multiple distances\n \n matplotlib.rcParams.update({'font.size':20, 'figure.autolayout': True}) #, 'font.weight':'bold'})\n\n fig, axL = plt.subplots()\n color = {'coldJet_base':'k', 'coldJet_base_gDens60':'m','coldJet_base_gDens120':'b', 'coldJet_C_10_gDens120':'g', 'coldJet_C_10_ZLES_7_gDens120':'r', 'coldJet_LplanarTau_gDens60':'b--', 'coldJet_ZLES_7_gDens120':'c', 'coldJet__LPlanarTau_C_10_ZLES_7_gDens60':'r--'}\n #color['coldJet_LplanarTau_gDens60']='k' #use if plotting LPlanarTau cases at multiple distances\n #color['coldJet__LPlanarTau_C_10_ZLES_7_gDens60']='k' #use if plotting LPlanarTau cases at multiple distances\n\n for i in range(0,len(DI)):\n\n D = get_inputFileParameter(DI[i], (\"initParams\",\"djeti\"))\n mfile = DI[i]['pdir'] + \"/means_\" + profName + \".dat\"\n data = np.loadtxt(mfile, comments=commentHdr)\n times = get_inputFileParameter(DI[i], (\"dumpTimes\",))\n ua = get_inputFileParameter(DI[i], (\"initParams\",\"vel_min\"))\n\n npts = len(data[:,0])\n ntimes = len(times)\n rnorm = np.empty( (npts, ntimes) )\n U = data[:,1:]\n icl = int(npts/2)+1\n Ucl = U[icl,:]\n \n for j in range(ntimes):\n rnorm[:,j] = data[:,0]/(times[j] - 4.0*D) \n\n #if plotting several cases together, best not to plot multiple downstream distances\n #j = 2; axL.plot(rnorm[:,j], (U[:,j]-ua)/(Ucl[j]-ua), color[DI[i]['cn']]+':') #x/D=10\n #j = 4; axL.plot(rnorm[:,j], (U[:,j]-ua)/(Ucl[j]-ua), color[DI[i]['cn']]+'--') #x/D=20\n j = 10; axL.plot(rnorm[:,j], (U[:,j]-ua)/(Ucl[j]-ua), color[DI[i]['cn']]) #x/D=50\n \n #cases.append(DI[i]['cn'][8:]+', x=10D')\n #cases.append(DI[i]['cn'][8:]+', x=20D')\n cases.append(DI[i]['cn'][8:]+', x=50D')\n plotname+=\"__\"+DI[i]['cn'][8:]\n\n axL.set_ylim([0,1.2])\n axL.set_xlim([-0.25,0.25])\n axL.set_xlabel(r\"$r/(x-x_0)$\", fontsize=22)\n axL.set_ylabel(r\"$v/v_{cL}$\", fontsize=22)\n axL.set_title(\"coldJet\",fontsize=22)\n axL.legend(cases,loc=\"best\", frameon=False, fontsize=8)\n\n #plt.savefig('../../data/plots_coldJet/'+plotname.replace(\".\",\"o\"))\n plt.savefig('../../data/plots_coldJet/'+'uucl_rxx0__ALL'.replace(\".\",\"o\"))\n", "#plot of integral of TKEdiss times r with respect to r, vs. x/D\n#plot file directory/name at end of function definition\n\nfrom __future__ import division\nimport numpy as np\nfrom data_tools import get_inputFileParameter\nimport matplotlib\nmatplotlib.use('PDF') # or Agg (for png), SVG, PS\nimport matplotlib.pyplot as plt\nfrom data_tools import commentHdr\nfrom scipy import integrate\n\n#-------------------------------------------------------------------------------------\n\ndef intTKEdiss_xD(DI, profName=\"TKEdiss\"): #uses list of cases\n \n cases = []\n plotname = \"intTKEdiss_xD\"\n \n matplotlib.rcParams.update({'font.size':20, 'figure.autolayout': True}) #, 'font.weight':'bold'})\n\n fig, axL = plt.subplots()\n color = {'coldJet_base':'k','coldJet_base_gDens60':'m', 'coldJet_base_gDens120':'b', 'coldJet_C_10_gDens120':'g', 'coldJet_C_10_ZLES_7_gDens120':'r', 'coldJet_LplanarTau_gDens60':'b--', 'coldJet_ZLES_7_gDens120':'c', 'coldJet__LPlanarTau_C_10_ZLES_7_gDens60':'r--'}\n\n for i in range(0,len(DI)):\n\n D = get_inputFileParameter(DI[i],(\"initParams\",\"djeti\"))\n L = get_inputFileParameter(DI[i], (\"params\",\"domainLength\"))\n mfile = DI[i]['pdir']+\"/means_\"+profName+\".dat\"\n data = np.loadtxt(mfile, comments=commentHdr)\n times = get_inputFileParameter(DI[i],(\"dumpTimes\",))\n\n npts = len(data[:,0])\n ntimes = len(times)\n icl = int(npts/2)+1\n r = data[:,0]\n times = np.array(times)\n xD = times/D\n\n TKErdr = np.empty((npts-1,ntimes))\n\n TKEr = np.empty((npts,ntimes))\n TKE = data[:,1:]\n\n for ipt in range(npts):\n for itime in range(ntimes):\n TKEr[ipt,itime] = TKE[ipt,itime]*r[ipt]\n \n #integrated from centerline out to maximum positive radial distance\n for itime in range(ntimes):\n TKErdr[icl:,itime] = integrate.cumtrapz(TKEr[icl:,itime],r[icl:])\n \n \n axL.plot(xD, TKErdr[-1,:], color[DI[i]['cn']])\n \n cases.append(DI[i]['cn'][8:])\n plotname+=\"__\"+DI[i]['cn'][8:]\n\n axL.set_xlabel(r\"$x/D$\", fontsize=22)\n axL.set_ylabel(r\"$\\int \\epsilon rdr$\", fontsize=22)\n axL.set_title(\"coldJet\", fontsize=22)\n axL.legend(cases,loc='best', frameon=False, fontsize=8)\n #axL.set_xlim([-.3,.3])\n #axL.set_ylim([-0.05,0.4])\n\n #plt.savefig('../../data/plots_coldJet/'+plotname.replace(\".\",\"o\"))\n plt.savefig('../../data/plots_coldJet/'+'intTKEdiss_xD__ALL'.replace(\".\",\"o\"))\n" ]
[ [ "matplotlib.use", "matplotlib.pyplot.subplots", "numpy.loadtxt", "matplotlib.rcParams.update", "numpy.empty" ], [ "scipy.integrate.cumtrapz", "matplotlib.use", "matplotlib.pyplot.subplots", "numpy.empty", "matplotlib.rcParams.update", "numpy.array", "numpy.loadtxt" ] ]
[ { "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": [] } ]
mohantyk/srd
[ "4ca6573226edbde80ea3641f50637c53543e1edc", "4ca6573226edbde80ea3641f50637c53543e1edc" ]
[ "receiver.py", "equalization.py" ]
[ "import numpy as np\nfrom scipy import signal\n\nfrom wavegen import cosine_wave\nfrom utilities import power\n\n#-------------------------\n# Helper functions\ndef combine(iterator, num_elems):\n ''' Pairs up a fixed number of elements at a time '''\n window = [iter(iterator)]*num_elems\n for combo in zip(*window):\n yield combo\n\n#-------------------------\n# Receiver blocks\n\ndef pam2letters(symbols):\n '''\n inputs:\n symbols: list of pam symbols\n outputs:\n msg as a str\n '''\n symbol_to_bits = {3: '11', 1: '10', -1: '01', -3: '00'}\n bits = ''.join(symbol_to_bits[symbol] for symbol in symbols)\n msg = []\n for eight_bits in combine(bits, 8):\n ascii = int(''.join(eight_bits), 2)\n ch = chr(ascii)\n msg.append(ch)\n return ''.join(msg)\n\n\ndef demodulate(sig, fc, Ts, taps=50):\n '''\n Demodulate a carrier wave\n inputs:\n sig: analog signal\n fc : carrier wave frequency\n Ts : sampling duration of analog signal\n taps: number of taps for LPF\n '''\n # Downconvert\n duration = len(sig)*Ts\n _, carrier = cosine_wave(fc, duration, Ts)\n downconverted = sig * carrier\n # Low pass filter the downconverted signal\n Fs = 1/Ts\n band_edges = np.array([0, 0.1, 0.2, 1])*(Fs//2) # Cutoff at 0.2*Fs/2\n damps = [1, 0]\n b = signal.remez(taps, band_edges, damps, fs=Fs)\n # Scaling by 2 below to compensate for cos(x)**2 = (1/2)*[cos(2x) + 1]\n baseband = 2*signal.lfilter(b, 1, downconverted) # Baseband is still in 'analog' domain\n return baseband\n\n\ndef pulse_correlator(sig, M, shape=signal.hamming):\n '''\n inputs:\n sig: baseband signal\n M : oversampling factor\n shape: pulse shape function, should take a single parameter oversample_factor\n '''\n pulse = shape(M)\n # Normalize pulse so that correlation with another pulse gives coeff = 1\n pulse_normalized = pulse/(power(pulse)*len(pulse))\n # In 'full' mode, correlation of a pulse with itself gives an array of 2*M-1 elements\n # The peak is at index M - 1\n correlated = np.correlate(sig, pulse_normalized, 'full')\n return correlated\n\n\ndef quantalph(sig, alphabet):\n '''\n Quantize sig to nearest symbol in alphabet\n '''\n dist = (sig.reshape(-1,1) - alphabet.reshape(1, -1))**2\n idx = np.argmin(dist, axis=1)\n hard_decisions = alphabet[idx]\n return hard_decisions\n\n\ndef eye_diag(analog, n_eye=5, oversample_factor=10):\n '''\n inputs:\n analog: analog signal\n n_eye: number of symbols for eye\n oversample_factor: oversampling factor for analog signal\n output:\n 2D array, each row consists of n_eye symbols\n '''\n M = oversample_factor\n n_eye = 5 # Number of symbols in eye\n groups = len(analog)//(n_eye*M)\n eye_diag = analog[-n_eye*groups*M:].reshape(-1, n_eye*M)\n return eye_diag\n\n\n# Final receiver\ndef ideal_receiver(sig, fc=20, Ts=1/100):\n '''\n inputs:\n sig: received signal (numpy array)\n fc: carrier frequency\n Ts: sampling frequency (for analog signal)\n output:\n decoded msg (str)\n '''\n oversample_factor = int(1/Ts)\n # Demodulate the carrier wave\n taps = 50\n baseband = demodulate(sig, fc, Ts, taps)\n # Use correlation to extract pulse amplitudes\n correlated = pulse_correlator(baseband, oversample_factor)\n # Downsample to get soft decisions\n filter_delay = taps//2 # taps // 2\n correlator_delay = oversample_factor\n sampling_start_idx = filter_delay + correlator_delay - 1\n soft_decisions = correlated[sampling_start_idx::oversample_factor]\n # Quantize to get hard decisions\n alphabet = np.array([-3, -1, 1, 3])\n hard_decisions = quantalph(soft_decisions, alphabet)\n # Decode message\n decoded_msg = pam2letters(hard_decisions)\n return decoded_msg\n\n\n\n\n", "import numpy as np\nfrom scipy import signal\n\nfrom receiver import quantalph\n\ndef lms_equalizer(received, pilot, delay=2, taps=4, mu=0.01):\n '''\n LMS equalizer\n parameters:\n received: received signal\n pilot: transmitted pilot symbols\n delay: estimated symbol delay\n taps: number of filter taps\n mu: learning rate\n output:\n filter coefficients\n '''\n f = np.zeros(taps, float)\n for i in range(taps, len(received)):\n window = received[i:i-taps:-1]\n predicted = np.dot(f, window)\n err = pilot[i-delay] - predicted\n f = f + mu*err*window\n return f\n\n\ndef dd_equalizer(received, alphabet, taps=4, mu=0.1):\n '''\n Decision directed equalizer\n parameters:\n received: received signal\n alphabet: decision alphabet\n taps: number of filter taps\n mu: learning rate\n output:\n filter coefficients\n '''\n f = np.zeros(taps, float)\n f[len(f)//2] = 1 # Center-spike initialization\n for i in range(taps, len(received)):\n window = received[i:i-taps:-1]\n predicted = np.dot(f, window)\n decision = quantalph(np.array(predicted), alphabet)\n err = decision[0] - predicted\n f = f + mu*err*window\n return f\n\n\ndef evaluate_equalizer(channel, equalizer, alphabet=None, num_symbols=1000):\n '''\n Evaluates the quality of a equalizer by simulation with random samples\n parameters:\n channel : channel taps (numpy array)\n equalizer: linear equalizer (numpy array)\n alphabet: symbol alphabet (defaults to 4-PAM)\n num_symbols: number of test symbols to generate\n returns:\n numpy array with number of errors for every delay.\n errors[i] is the number of errors when delay = i\n '''\n if alphabet is None:\n alphabet = np.array([-3, -1, 1, 3]) # 4 - PAM\n symbols = np.random.choice(alphabet, num_symbols)\n received = signal.lfilter(channel, 1, symbols)\n equalized = signal.lfilter(equalizer, 1, received)\n decisions = quantalph(equalized, alphabet)\n\n errors = []\n n = len(equalizer)\n for delay in range(n):\n error = 0.5*np.sum( np.abs(decisions[delay:] - symbols[:num_symbols-delay]) )\n errors.append(error)\n\n return np.array(errors)" ]
[ [ "numpy.correlate", "numpy.argmin", "scipy.signal.lfilter", "numpy.array", "scipy.signal.remez" ], [ "numpy.dot", "numpy.abs", "numpy.random.choice", "scipy.signal.lfilter", "numpy.array", "numpy.zeros" ] ]
[ { "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": [ "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": [] } ]
luke-l7/IML.HUJI
[ "dfa440c0c258c4049a4801c6b240f788b98d4639" ]
[ "IMLearn/learners/regressors/polynomial_fitting.py" ]
[ "from __future__ import annotations\nfrom typing import NoReturn\nfrom . import LinearRegression\nfrom ...base import BaseEstimator\nimport numpy as np\n\n\nclass PolynomialFitting(LinearRegression):\n \"\"\"\n Polynomial Fitting using Least Squares estimation\n \"\"\"\n def __init__(self, k: int) -> PolynomialFitting:\n \"\"\"\n Instantiate a polynomial fitting estimator\n\n Parameters\n ----------\n k : int\n Degree of polynomial to fit\n \"\"\"\n super().__init__()\n self._k = k\n\n def _fit(self, X: np.ndarray, y: np.ndarray) -> NoReturn:\n \"\"\"\n Fit Least Squares model to polynomial transformed samples\n\n Parameters\n ----------\n X : ndarray of shape (n_samples, n_features)\n Input data to fit an estimator for\n\n y : ndarray of shape (n_samples, )\n Responses of input data to fit to\n \"\"\"\n super(PolynomialFitting, self)._fit(self.__transform(X),y)\n\n def _predict(self, X: np.ndarray) -> np.ndarray:\n \"\"\"\n Predict responses for given samples using fitted estimator\n\n Parameters\n ----------\n X : ndarray of shape (n_samples, n_features)\n Input data to predict responses for\n\n Returns\n -------\n responses : ndarray of shape (n_samples, )\n Predicted responses of given samples\n \"\"\"\n return super(PolynomialFitting, self)._predict(self.__transform(X))\n\n def _loss(self, X: np.ndarray, y: np.ndarray) -> float:\n \"\"\"\n Evaluate performance under MSE loss function\n\n Parameters\n ----------\n X : ndarray of shape (n_samples, n_features)\n Test samples\n\n y : ndarray of shape (n_samples, )\n True labels of test samples\n\n Returns\n -------\n loss : float\n Performance under MSE loss function\n \"\"\"\n return super(PolynomialFitting, self)._loss(X,y)\n\n def __transform(self, X: np.ndarray) -> np.ndarray:\n \"\"\"\n Transform given input according to the univariate polynomial transformation\n\n Parameters\n ----------\n X: ndarray of shape (n_samples,)\n\n Returns\n -------\n transformed: ndarray of shape (n_samples, k+1)\n Vandermonde matrix of given samples up to degree k\n \"\"\"\n vander = np.vander(X,self._k+1,increasing=True)\n return vander\n" ]
[ [ "numpy.vander" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
markr-fu-berlin/ParlAI
[ "29743cc7b47c413c2181f68c0b7ef40a6f06a40f" ]
[ "parlai/agents/mlb_vqa/loadstates.py" ]
[ "#!/usr/bin/env python3\n\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree. An additional grant\n# of patent rights can be found in the PATENTS file in the same directory.\n\nimport os\nimport numpy\n\nimport torch\n\nfrom collections import OrderedDict\n\nurls = {}\nurls['dictionary'] = 'http://www.cs.toronto.edu/~rkiros/models/dictionary.txt'\nurls['utable'] = 'http://www.cs.toronto.edu/~rkiros/models/utable.npy'\nurls['uni_skip'] = 'http://www.cs.toronto.edu/~rkiros/models/uni_skip.npz'\n\n\ndef load_dictionary(download_dir):\n path_dico = os.path.join(download_dir, 'dictionary.txt')\n if not os.path.exists(path_dico):\n os.system('mkdir -p ' + download_dir)\n os.system('wget {} -P {}'.format(urls['dictionary'], download_dir))\n with open(path_dico, 'r') as handle:\n dico_list = handle.readlines()\n dico = {word.strip(): idx for idx, word in enumerate(dico_list)}\n return dico\n\n\ndef load_emb_params(download_dir):\n table_name = 'utable'\n path_params = os.path.join(download_dir, table_name + '.npy')\n if not os.path.exists(path_params):\n os.system('mkdir -p ' + download_dir)\n os.system('wget {} -P {}'.format(urls[table_name], download_dir))\n params = numpy.load(path_params, encoding='latin1') # to load from python2\n return params\n\n\ndef load_rnn_params(download_dir):\n skip_name = 'uni_skip'\n path_params = os.path.join(download_dir, skip_name + '.npz')\n if not os.path.exists(path_params):\n os.system('mkdir -p ' + download_dir)\n os.system('wget {} -P {}'.format(urls[skip_name], download_dir))\n params = numpy.load(path_params, encoding='latin1') # to load from python2\n return params\n\n\ndef make_emb_state_dict(dictionary, parameters, vocab):\n weight = torch.zeros(len(vocab), 620)\n unknown_params = parameters[dictionary['UNK']]\n nb_unknown = 0\n for id_weight, word in enumerate(vocab):\n if word in dictionary:\n id_params = dictionary[word]\n params = parameters[id_params]\n else:\n # print('Warning: word `{}` not in dictionary'.format(word))\n params = unknown_params\n nb_unknown += 1\n weight[id_weight] = torch.from_numpy(params)\n state_dict = OrderedDict({'weight': weight})\n if nb_unknown > 0:\n print('Warning: {}/{} words are not in dictionary, thus set UNK'\n .format(nb_unknown, len(dictionary)))\n return state_dict\n\n\ndef make_gru_state_dict(p):\n s = OrderedDict()\n s['bias_ih_l0'] = torch.zeros(7200)\n s['bias_hh_l0'] = torch.zeros(7200) # must stay equal to 0\n s['weight_ih_l0'] = torch.zeros(7200, 620)\n s['weight_hh_l0'] = torch.zeros(7200, 2400)\n s['weight_ih_l0'][:4800] = torch.from_numpy(p['encoder_W']).t()\n s['weight_ih_l0'][4800:] = torch.from_numpy(p['encoder_Wx']).t()\n s['bias_ih_l0'][:4800] = torch.from_numpy(p['encoder_b'])\n s['bias_ih_l0'][4800:] = torch.from_numpy(p['encoder_bx'])\n s['weight_hh_l0'][:4800] = torch.from_numpy(p['encoder_U']).t()\n s['weight_hh_l0'][4800:] = torch.from_numpy(p['encoder_Ux']).t()\n return s\n\n\ndef make_bayesian_state_dict(p):\n s = OrderedDict()\n s['gru_cell.weight_ir.weight'] = torch.from_numpy(p['encoder_W']).t()[:2400]\n s['gru_cell.weight_ii.weight'] = torch.from_numpy(p['encoder_W']).t()[2400:]\n s['gru_cell.weight_in.weight'] = torch.from_numpy(p['encoder_Wx']).t()\n\n s['gru_cell.weight_ir.bias'] = torch.from_numpy(p['encoder_b'])[:2400]\n s['gru_cell.weight_ii.bias'] = torch.from_numpy(p['encoder_b'])[2400:]\n s['gru_cell.weight_in.bias'] = torch.from_numpy(p['encoder_bx'])\n\n s['gru_cell.weight_hr.weight'] = torch.from_numpy(p['encoder_U']).t()[:2400]\n s['gru_cell.weight_hi.weight'] = torch.from_numpy(p['encoder_U']).t()[2400:]\n s['gru_cell.weight_hn.weight'] = torch.from_numpy(p['encoder_Ux']).t()\n return s\n" ]
[ [ "numpy.load", "torch.from_numpy", "torch.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jsteggink/trankit
[ "61ef593999bfa29751990d0d4bcf259daed05db4", "61ef593999bfa29751990d0d4bcf259daed05db4", "61ef593999bfa29751990d0d4bcf259daed05db4" ]
[ "trankit/adapter_transformers/data/datasets/glue.py", "trankit/adapter_transformers/modeling_t5.py", "trankit/adapter_transformers/data/processors/utils.py" ]
[ "import logging\r\nimport os\r\nimport time\r\nfrom dataclasses import dataclass, field\r\nfrom enum import Enum\r\nfrom typing import List, Optional, Union\r\n\r\nimport torch\r\nfrom filelock import FileLock\r\nfrom torch.utils.data.dataset import Dataset\r\n\r\nfrom ...tokenization_roberta import RobertaTokenizer, RobertaTokenizerFast\r\nfrom ...tokenization_utils import PreTrainedTokenizer\r\nfrom ...tokenization_xlm_roberta import XLMRobertaTokenizer\r\nfrom ..processors.glue import glue_convert_examples_to_features, glue_output_modes, glue_processors\r\nfrom ..processors.utils import InputFeatures\r\n\r\n\r\nlogger = logging.getLogger(__name__)\r\n\r\n\r\n@dataclass\r\nclass GlueDataTrainingArguments:\r\n \"\"\"\r\n Arguments pertaining to what data we are going to input our model for training and eval.\r\n\r\n Using `HfArgumentParser` we can turn this class\r\n into argparse arguments to be able to specify them on\r\n the command line.\r\n \"\"\"\r\n\r\n task_name: str = field(metadata={\"help\": \"The name of the task to train on: \" + \", \".join(glue_processors.keys())})\r\n data_dir: str = field(\r\n metadata={\"help\": \"The input data dir. Should contain the .tsv files (or other data files) for the task.\"}\r\n )\r\n max_seq_length: int = field(\r\n default=128,\r\n metadata={\r\n \"help\": \"The maximum total input sequence length after tokenization. Sequences longer \"\r\n \"than this will be truncated, sequences shorter will be padded.\"\r\n },\r\n )\r\n overwrite_cache: bool = field(\r\n default=False, metadata={\"help\": \"Overwrite the cached training and evaluation sets\"}\r\n )\r\n\r\n def __post_init__(self):\r\n self.task_name = self.task_name.lower()\r\n\r\n\r\nclass Split(Enum):\r\n train = \"train\"\r\n dev = \"dev\"\r\n test = \"test\"\r\n\r\n\r\nclass GlueDataset(Dataset):\r\n \"\"\"\r\n This will be superseded by a framework-agnostic approach\r\n soon.\r\n \"\"\"\r\n\r\n args: GlueDataTrainingArguments\r\n output_mode: str\r\n features: List[InputFeatures]\r\n\r\n def __init__(\r\n self,\r\n args: GlueDataTrainingArguments,\r\n tokenizer: PreTrainedTokenizer,\r\n limit_length: Optional[int] = None,\r\n mode: Union[str, Split] = Split.train,\r\n ):\r\n self.args = args\r\n self.processor = glue_processors[args.task_name]()\r\n self.output_mode = glue_output_modes[args.task_name]\r\n if isinstance(mode, str):\r\n try:\r\n mode = Split[mode]\r\n except KeyError:\r\n raise KeyError(\"mode is not a valid split name\")\r\n # Load data features from cache or dataset file\r\n cached_features_file = os.path.join(\r\n args.data_dir,\r\n \"cached_{}_{}_{}_{}\".format(\r\n mode.value, tokenizer.__class__.__name__, str(args.max_seq_length), args.task_name,\r\n ),\r\n )\r\n label_list = self.processor.get_labels()\r\n if args.task_name in [\"mnli\", \"mnli-mm\"] and tokenizer.__class__ in (\r\n RobertaTokenizer,\r\n RobertaTokenizerFast,\r\n XLMRobertaTokenizer,\r\n ):\r\n # HACK(label indices are swapped in RoBERTa pretrained model)\r\n label_list[1], label_list[2] = label_list[2], label_list[1]\r\n self.label_list = label_list\r\n\r\n # Make sure only the first process in distributed training processes the dataset,\r\n # and the others will use the cache.\r\n lock_path = cached_features_file + \".lock\"\r\n with FileLock(lock_path):\r\n\r\n if os.path.exists(cached_features_file) and not args.overwrite_cache:\r\n start = time.time()\r\n self.features = torch.load(cached_features_file)\r\n logger.info(\r\n f\"Loading features from cached file {cached_features_file} [took %.3f s]\", time.time() - start\r\n )\r\n else:\r\n logger.info(f\"Creating features from dataset file at {args.data_dir}\")\r\n\r\n if mode == Split.dev:\r\n examples = self.processor.get_dev_examples(args.data_dir)\r\n elif mode == Split.test:\r\n examples = self.processor.get_test_examples(args.data_dir)\r\n else:\r\n examples = self.processor.get_train_examples(args.data_dir)\r\n if limit_length is not None:\r\n examples = examples[:limit_length]\r\n self.features = glue_convert_examples_to_features(\r\n examples,\r\n tokenizer,\r\n max_length=args.max_seq_length,\r\n label_list=label_list,\r\n output_mode=self.output_mode,\r\n )\r\n start = time.time()\r\n torch.save(self.features, cached_features_file)\r\n # ^ This seems to take a lot of time so I want to investigate why and how we can improve.\r\n logger.info(\r\n \"Saving features into cached file %s [took %.3f s]\", cached_features_file, time.time() - start\r\n )\r\n\r\n def __len__(self):\r\n return len(self.features)\r\n\r\n def __getitem__(self, i) -> InputFeatures:\r\n return self.features[i]\r\n\r\n def get_labels(self):\r\n return self.label_list\r\n", "# coding=utf-8\r\n# Copyright 2018 Mesh TensorFlow authors, T5 Authors and HuggingFace Inc. team.\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n\"\"\" PyTorch T5 model. \"\"\"\r\n\r\n\r\nimport copy\r\nimport logging\r\nimport math\r\nimport os\r\n\r\nimport torch\r\nimport torch.nn.functional as F\r\nfrom torch import nn\r\nfrom torch.nn import CrossEntropyLoss\r\n\r\nfrom .configuration_t5 import T5Config\r\nfrom .file_utils import DUMMY_INPUTS, DUMMY_MASK, add_start_docstrings, add_start_docstrings_to_callable\r\nfrom .modeling_utils import PreTrainedModel, prune_linear_layer\r\n\r\n\r\nlogger = logging.getLogger(__name__)\r\n\r\n####################################################\r\n# This dict contrains shortcut names and associated url\r\n# for the pretrained weights provided with the models\r\n####################################################\r\nT5_PRETRAINED_MODEL_ARCHIVE_LIST = [\r\n \"t5-small\",\r\n \"t5-base\",\r\n \"t5-large\",\r\n \"t5-3b\",\r\n \"t5-11b\",\r\n # See all T5 models at https://huggingface.co/models?filter=t5\r\n]\r\n\r\n\r\n####################################################\r\n# This is a conversion method from TF 1.0 to PyTorch\r\n# More details: https://medium.com/huggingface/from-tensorflow-to-pytorch-265f40ef2a28\r\n####################################################\r\ndef load_tf_weights_in_t5(model, config, tf_checkpoint_path):\r\n \"\"\" Load tf checkpoints in a pytorch model.\r\n \"\"\"\r\n try:\r\n import re\r\n import numpy as np\r\n import tensorflow as tf\r\n except ImportError:\r\n logger.error(\r\n \"Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see \"\r\n \"https://www.tensorflow.org/install/ for installation instructions.\"\r\n )\r\n raise\r\n tf_path = os.path.abspath(tf_checkpoint_path)\r\n logger.info(\"Converting TensorFlow checkpoint from {}\".format(tf_path))\r\n # Load weights from TF model\r\n init_vars = tf.train.list_variables(tf_path)\r\n names = []\r\n tf_weights = {}\r\n for name, shape in init_vars:\r\n logger.info(\"Loading TF weight {} with shape {}\".format(name, shape))\r\n array = tf.train.load_variable(tf_path, name)\r\n names.append(name)\r\n tf_weights[name] = array\r\n\r\n for txt_name in names:\r\n name = txt_name.split(\"/\")\r\n # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v\r\n # which are not required for using pretrained model\r\n if any(\r\n n in [\"adam_v\", \"adam_m\", \"AdamWeightDecayOptimizer\", \"AdamWeightDecayOptimizer_1\", \"global_step\"]\r\n for n in name\r\n ):\r\n logger.info(\"Skipping {}\".format(\"/\".join(name)))\r\n tf_weights.pop(txt_name, None)\r\n continue\r\n if \"_slot_\" in name[-1]:\r\n logger.info(\"Skipping {}\".format(\"/\".join(name)))\r\n tf_weights.pop(txt_name, None)\r\n continue\r\n pointer = model\r\n array = tf_weights[txt_name]\r\n for m_name in name:\r\n if re.fullmatch(r\"[A-Za-z]+_\\d+\", m_name):\r\n scope_names = re.split(r\"_(\\d+)\", m_name)\r\n else:\r\n scope_names = [m_name]\r\n if scope_names[0] in [\"kernel\", \"scale\", \"embedding\"]:\r\n pointer = getattr(pointer, \"weight\")\r\n # elif scope_names[0] == 'scale':\r\n # pointer = getattr(pointer, 'weight')\r\n # elif scope_names[0] == 'output_bias' or scope_names[0] == 'beta':\r\n # pointer = getattr(pointer, 'bias')\r\n # elif scope_names[0] == 'squad':\r\n # pointer = getattr(pointer, 'classifier')\r\n else:\r\n try:\r\n pointer = getattr(pointer, scope_names[0])\r\n except AttributeError:\r\n logger.info(\"Skipping {}\".format(\"/\".join(name)))\r\n continue\r\n if len(scope_names) >= 2:\r\n num = int(scope_names[1])\r\n pointer = pointer[num]\r\n if scope_names[0] not in [\"kernel\", \"scale\", \"embedding\"]:\r\n pointer = getattr(pointer, \"weight\")\r\n if scope_names[0] != \"embedding\":\r\n logger.info(\"Transposing numpy weight of shape {} for {}\".format(array.shape, name))\r\n array = np.transpose(array)\r\n try:\r\n assert pointer.shape == array.shape\r\n except AssertionError as e:\r\n e.args += (pointer.shape, array.shape)\r\n raise\r\n logger.info(\"Initialize PyTorch weight {}\".format(name))\r\n pointer.data = torch.from_numpy(array.astype(np.float32))\r\n tf_weights.pop(txt_name, None)\r\n\r\n logger.info(\"Weights not copied to PyTorch model: {}\".format(\", \".join(tf_weights.keys())))\r\n # logger.info(\"Weights not copied to PyTorch model: {}\".format(', '.join(tf_weights.keys())))\r\n return model\r\n\r\n\r\n####################################################\r\n# PyTorch Models are constructed by sub-classing\r\n# - torch.nn.Module for the layers and\r\n# - PreTrainedModel for the models (it-self a sub-class of torch.nn.Module)\r\n####################################################\r\n\r\n\r\nclass T5LayerNorm(nn.Module):\r\n def __init__(self, hidden_size, eps=1e-6):\r\n \"\"\" Construct a layernorm module in the T5 style\r\n No bias and no substraction of mean.\r\n \"\"\"\r\n super().__init__()\r\n self.weight = nn.Parameter(torch.ones(hidden_size))\r\n self.variance_epsilon = eps\r\n\r\n def forward(self, x):\r\n # layer norm should always be calculated in float32\r\n variance = x.to(torch.float32).pow(2).mean(-1, keepdim=True)\r\n x = x / torch.sqrt(variance + self.variance_epsilon)\r\n\r\n if self.weight.dtype == torch.float16:\r\n x = x.to(torch.float16)\r\n return self.weight * x\r\n\r\n\r\nclass T5DenseReluDense(nn.Module):\r\n def __init__(self, config):\r\n super().__init__()\r\n self.wi = nn.Linear(config.d_model, config.d_ff, bias=False)\r\n self.wo = nn.Linear(config.d_ff, config.d_model, bias=False)\r\n self.dropout = nn.Dropout(config.dropout_rate)\r\n\r\n def forward(self, hidden_states):\r\n h = self.wi(hidden_states)\r\n h = F.relu(h)\r\n h = self.dropout(h)\r\n h = self.wo(h)\r\n return h\r\n\r\n\r\nclass T5LayerFF(nn.Module):\r\n def __init__(self, config):\r\n super().__init__()\r\n self.DenseReluDense = T5DenseReluDense(config)\r\n self.layer_norm = T5LayerNorm(config.d_model, eps=config.layer_norm_epsilon)\r\n self.dropout = nn.Dropout(config.dropout_rate)\r\n\r\n def forward(self, hidden_states):\r\n norm_x = self.layer_norm(hidden_states)\r\n y = self.DenseReluDense(norm_x)\r\n layer_output = hidden_states + self.dropout(y)\r\n return layer_output\r\n\r\n\r\nclass T5Attention(nn.Module):\r\n def __init__(self, config: T5Config, has_relative_attention_bias=False):\r\n super().__init__()\r\n self.is_decoder = config.is_decoder\r\n self.has_relative_attention_bias = has_relative_attention_bias\r\n\r\n self.output_attentions = config.output_attentions\r\n self.relative_attention_num_buckets = config.relative_attention_num_buckets\r\n self.d_model = config.d_model\r\n self.d_kv = config.d_kv\r\n self.n_heads = config.num_heads\r\n self.dropout = config.dropout_rate\r\n self.inner_dim = self.n_heads * self.d_kv\r\n\r\n # Mesh TensorFlow initialization to avoid scaling before softmax\r\n self.q = nn.Linear(self.d_model, self.inner_dim, bias=False)\r\n self.k = nn.Linear(self.d_model, self.inner_dim, bias=False)\r\n self.v = nn.Linear(self.d_model, self.inner_dim, bias=False)\r\n self.o = nn.Linear(self.inner_dim, self.d_model, bias=False)\r\n\r\n if self.has_relative_attention_bias:\r\n self.relative_attention_bias = nn.Embedding(self.relative_attention_num_buckets, self.n_heads)\r\n self.pruned_heads = set()\r\n\r\n def prune_heads(self, heads):\r\n if len(heads) == 0:\r\n return\r\n mask = torch.ones(self.n_heads, self.d_kv)\r\n heads = set(heads) - self.pruned_heads\r\n for head in heads:\r\n head -= sum(1 if h < head else 0 for h in self.pruned_heads)\r\n mask[head] = 0\r\n mask = mask.view(-1).contiguous().eq(1)\r\n index = torch.arange(len(mask))[mask].long()\r\n # Prune linear layers\r\n self.q = prune_linear_layer(self.q, index)\r\n self.k = prune_linear_layer(self.k, index)\r\n self.v = prune_linear_layer(self.v, index)\r\n self.o = prune_linear_layer(self.o, index, dim=1)\r\n # Update hyper params\r\n self.n_heads = self.n_heads - len(heads)\r\n self.inner_dim = self.d_kv * self.n_heads\r\n self.pruned_heads = self.pruned_heads.union(heads)\r\n\r\n @staticmethod\r\n def _relative_position_bucket(relative_position, bidirectional=True, num_buckets=32, max_distance=128):\r\n \"\"\"\r\n Adapted from Mesh Tensorflow:\r\n https://github.com/tensorflow/mesh/blob/0cb87fe07da627bf0b7e60475d59f95ed6b5be3d/mesh_tensorflow/transformer/transformer_layers.py#L593\r\n\r\n Translate relative position to a bucket number for relative attention.\r\n The relative position is defined as memory_position - query_position, i.e.\r\n the distance in tokens from the attending position to the attended-to\r\n position. If bidirectional=False, then positive relative positions are\r\n invalid.\r\n We use smaller buckets for small absolute relative_position and larger buckets\r\n for larger absolute relative_positions. All relative positions >=max_distance\r\n map to the same bucket. All relative positions <=-max_distance map to the\r\n same bucket. This should allow for more graceful generalization to longer\r\n sequences than the model has been trained on.\r\n Args:\r\n relative_position: an int32 Tensor\r\n bidirectional: a boolean - whether the attention is bidirectional\r\n num_buckets: an integer\r\n max_distance: an integer\r\n Returns:\r\n a Tensor with the same shape as relative_position, containing int32\r\n values in the range [0, num_buckets)\r\n \"\"\"\r\n ret = 0\r\n n = -relative_position\r\n if bidirectional:\r\n num_buckets //= 2\r\n ret += (n < 0).to(torch.long) * num_buckets # mtf.to_int32(mtf.less(n, 0)) * num_buckets\r\n n = torch.abs(n)\r\n else:\r\n n = torch.max(n, torch.zeros_like(n))\r\n # now n is in the range [0, inf)\r\n\r\n # half of the buckets are for exact increments in positions\r\n max_exact = num_buckets // 2\r\n is_small = n < max_exact\r\n\r\n # The other half of the buckets are for logarithmically bigger bins in positions up to max_distance\r\n val_if_large = max_exact + (\r\n torch.log(n.float() / max_exact) / math.log(max_distance / max_exact) * (num_buckets - max_exact)\r\n ).to(torch.long)\r\n val_if_large = torch.min(val_if_large, torch.full_like(val_if_large, num_buckets - 1))\r\n\r\n ret += torch.where(is_small, n, val_if_large)\r\n return ret\r\n\r\n def compute_bias(self, qlen, klen):\r\n \"\"\" Compute binned relative position bias \"\"\"\r\n context_position = torch.arange(qlen, dtype=torch.long)[:, None]\r\n memory_position = torch.arange(klen, dtype=torch.long)[None, :]\r\n relative_position = memory_position - context_position # shape (qlen, klen)\r\n rp_bucket = self._relative_position_bucket(\r\n relative_position, # shape (qlen, klen)\r\n bidirectional=not self.is_decoder,\r\n num_buckets=self.relative_attention_num_buckets,\r\n )\r\n rp_bucket = rp_bucket.to(self.relative_attention_bias.weight.device)\r\n values = self.relative_attention_bias(rp_bucket) # shape (qlen, klen, num_heads)\r\n values = values.permute([2, 0, 1]).unsqueeze(0) # shape (1, num_heads, qlen, klen)\r\n return values\r\n\r\n def forward(\r\n self,\r\n input,\r\n mask=None,\r\n kv=None,\r\n position_bias=None,\r\n past_key_value_state=None,\r\n head_mask=None,\r\n query_length=None,\r\n use_cache=False,\r\n ):\r\n \"\"\"\r\n Self-attention (if kv is None) or attention over source sentence (provided by kv).\r\n \"\"\"\r\n # Input is (bs, qlen, dim)\r\n # Mask is (bs, klen) (non-causal) or (bs, klen, klen)\r\n # past_key_value_state[0] is (bs, n_heads, q_len - 1, dim_per_head)\r\n bs, qlen, dim = input.size()\r\n\r\n if past_key_value_state is not None:\r\n assert self.is_decoder is True, \"Encoder cannot cache past key value states\"\r\n assert (\r\n len(past_key_value_state) == 2\r\n ), \"past_key_value_state should have 2 past states: keys and values. Got {} past states\".format(\r\n len(past_key_value_state)\r\n )\r\n real_qlen = qlen + past_key_value_state[0].shape[2] if query_length is None else query_length\r\n else:\r\n real_qlen = qlen\r\n\r\n if kv is None:\r\n klen = real_qlen\r\n else:\r\n klen = kv.size(1)\r\n\r\n def shape(x):\r\n \"\"\" projection \"\"\"\r\n return x.view(bs, -1, self.n_heads, self.d_kv).transpose(1, 2)\r\n\r\n def unshape(x):\r\n \"\"\" compute context \"\"\"\r\n return x.transpose(1, 2).contiguous().view(bs, -1, self.inner_dim)\r\n\r\n q = shape(self.q(input)) # (bs, n_heads, qlen, dim_per_head)\r\n\r\n if kv is None:\r\n k = shape(self.k(input)) # (bs, n_heads, qlen, dim_per_head)\r\n v = shape(self.v(input)) # (bs, n_heads, qlen, dim_per_head)\r\n elif past_key_value_state is None:\r\n k = v = kv\r\n k = shape(self.k(k)) # (bs, n_heads, qlen, dim_per_head)\r\n v = shape(self.v(v)) # (bs, n_heads, qlen, dim_per_head)\r\n\r\n if past_key_value_state is not None:\r\n if kv is None:\r\n k_, v_ = past_key_value_state\r\n k = torch.cat([k_, k], dim=2) # (bs, n_heads, klen, dim_per_head)\r\n v = torch.cat([v_, v], dim=2) # (bs, n_heads, klen, dim_per_head)\r\n else:\r\n k, v = past_key_value_state\r\n\r\n if self.is_decoder and use_cache is True:\r\n present_key_value_state = ((k, v),)\r\n else:\r\n present_key_value_state = (None,)\r\n\r\n scores = torch.einsum(\"bnqd,bnkd->bnqk\", q, k) # (bs, n_heads, qlen, klen)\r\n\r\n if position_bias is None:\r\n if not self.has_relative_attention_bias:\r\n raise ValueError(\"No position_bias provided and no weights to compute position_bias\")\r\n position_bias = self.compute_bias(real_qlen, klen)\r\n\r\n # if key and values are already calculated\r\n # we want only the last query position bias\r\n if past_key_value_state is not None:\r\n position_bias = position_bias[:, :, -1:, :]\r\n\r\n if mask is not None:\r\n position_bias = position_bias + mask # (bs, n_heads, qlen, klen)\r\n\r\n scores += position_bias\r\n weights = F.softmax(scores.float(), dim=-1).type_as(scores) # (bs, n_heads, qlen, klen)\r\n weights = F.dropout(weights, p=self.dropout, training=self.training) # (bs, n_heads, qlen, klen)\r\n\r\n # Mask heads if we want to\r\n if head_mask is not None:\r\n weights = weights * head_mask\r\n\r\n context = torch.matmul(weights, v) # (bs, n_heads, qlen, dim_per_head)\r\n context = unshape(context) # (bs, qlen, dim)\r\n\r\n context = self.o(context)\r\n\r\n outputs = (context,) + present_key_value_state\r\n\r\n if self.output_attentions:\r\n outputs = outputs + (weights,)\r\n if self.has_relative_attention_bias:\r\n outputs = outputs + (position_bias,)\r\n return outputs\r\n\r\n\r\nclass T5LayerSelfAttention(nn.Module):\r\n def __init__(self, config, has_relative_attention_bias=False):\r\n super().__init__()\r\n self.SelfAttention = T5Attention(config, has_relative_attention_bias=has_relative_attention_bias)\r\n self.layer_norm = T5LayerNorm(config.d_model, eps=config.layer_norm_epsilon)\r\n self.dropout = nn.Dropout(config.dropout_rate)\r\n\r\n def forward(\r\n self,\r\n hidden_states,\r\n attention_mask=None,\r\n position_bias=None,\r\n head_mask=None,\r\n past_key_value_state=None,\r\n use_cache=False,\r\n ):\r\n norm_x = self.layer_norm(hidden_states)\r\n attention_output = self.SelfAttention(\r\n norm_x,\r\n mask=attention_mask,\r\n position_bias=position_bias,\r\n head_mask=head_mask,\r\n past_key_value_state=past_key_value_state,\r\n use_cache=use_cache,\r\n )\r\n y = attention_output[0]\r\n layer_output = hidden_states + self.dropout(y)\r\n outputs = (layer_output,) + attention_output[1:] # add attentions if we output them\r\n return outputs\r\n\r\n\r\nclass T5LayerCrossAttention(nn.Module):\r\n def __init__(self, config, has_relative_attention_bias=False):\r\n super().__init__()\r\n self.EncDecAttention = T5Attention(config, has_relative_attention_bias=has_relative_attention_bias)\r\n self.layer_norm = T5LayerNorm(config.d_model, eps=config.layer_norm_epsilon)\r\n self.dropout = nn.Dropout(config.dropout_rate)\r\n\r\n def forward(\r\n self,\r\n hidden_states,\r\n kv,\r\n attention_mask=None,\r\n position_bias=None,\r\n head_mask=None,\r\n past_key_value_state=None,\r\n use_cache=False,\r\n query_length=None,\r\n ):\r\n norm_x = self.layer_norm(hidden_states)\r\n attention_output = self.EncDecAttention(\r\n norm_x,\r\n mask=attention_mask,\r\n kv=kv,\r\n position_bias=position_bias,\r\n head_mask=head_mask,\r\n past_key_value_state=past_key_value_state,\r\n use_cache=use_cache,\r\n query_length=query_length,\r\n )\r\n y = attention_output[0]\r\n layer_output = hidden_states + self.dropout(y)\r\n outputs = (layer_output,) + attention_output[1:] # add attentions if we output them\r\n return outputs\r\n\r\n\r\nclass T5Block(nn.Module):\r\n def __init__(self, config, has_relative_attention_bias=False):\r\n super().__init__()\r\n self.is_decoder = config.is_decoder\r\n self.layer = nn.ModuleList()\r\n self.layer.append(T5LayerSelfAttention(config, has_relative_attention_bias=has_relative_attention_bias))\r\n if self.is_decoder:\r\n self.layer.append(T5LayerCrossAttention(config, has_relative_attention_bias=has_relative_attention_bias))\r\n\r\n self.layer.append(T5LayerFF(config))\r\n\r\n def forward(\r\n self,\r\n hidden_states,\r\n attention_mask=None,\r\n position_bias=None,\r\n encoder_hidden_states=None,\r\n encoder_attention_mask=None,\r\n encoder_decoder_position_bias=None,\r\n head_mask=None,\r\n past_key_value_state=None,\r\n use_cache=False,\r\n ):\r\n\r\n if past_key_value_state is not None:\r\n assert self.is_decoder, \"Only decoder can use `past_key_value_states`\"\r\n expected_num_past_key_value_states = 2 if encoder_hidden_states is None else 4\r\n\r\n error_message = \"There should be {} past states. 2 (past / key) for self attention.{} Got {} past key / value states\".format(\r\n expected_num_past_key_value_states,\r\n \"2 (past / key) for cross attention\" if expected_num_past_key_value_states == 4 else \"\",\r\n len(past_key_value_state),\r\n )\r\n assert len(past_key_value_state) == expected_num_past_key_value_states, error_message\r\n\r\n self_attn_past_key_value_state = past_key_value_state[:2]\r\n cross_attn_past_key_value_state = past_key_value_state[2:]\r\n else:\r\n self_attn_past_key_value_state, cross_attn_past_key_value_state = None, None\r\n\r\n self_attention_outputs = self.layer[0](\r\n hidden_states,\r\n attention_mask=attention_mask,\r\n position_bias=position_bias,\r\n head_mask=head_mask,\r\n past_key_value_state=self_attn_past_key_value_state,\r\n use_cache=use_cache,\r\n )\r\n hidden_states, present_key_value_state = self_attention_outputs[:2]\r\n attention_outputs = self_attention_outputs[2:] # Keep self-attention outputs and relative position weights\r\n\r\n if self.is_decoder and encoder_hidden_states is not None:\r\n # the actual query length is unknown for cross attention\r\n # if using past key value states. Need to inject it here\r\n if present_key_value_state is not None:\r\n query_length = present_key_value_state[0].shape[2]\r\n else:\r\n query_length = None\r\n\r\n cross_attention_outputs = self.layer[1](\r\n hidden_states,\r\n kv=encoder_hidden_states,\r\n attention_mask=encoder_attention_mask,\r\n position_bias=encoder_decoder_position_bias,\r\n head_mask=head_mask,\r\n past_key_value_state=cross_attn_past_key_value_state,\r\n query_length=query_length,\r\n use_cache=use_cache,\r\n )\r\n hidden_states = cross_attention_outputs[0]\r\n # Combine self attn and cross attn key value states\r\n if present_key_value_state is not None:\r\n present_key_value_state = present_key_value_state + cross_attention_outputs[1]\r\n\r\n # Keep cross-attention outputs and relative position weights\r\n attention_outputs = attention_outputs + cross_attention_outputs[2:]\r\n\r\n # Apply Feed Forward layer\r\n hidden_states = self.layer[-1](hidden_states)\r\n outputs = (hidden_states,)\r\n\r\n # Add attentions if we output them\r\n outputs = outputs + (present_key_value_state,) + attention_outputs\r\n return outputs # hidden-states, present_key_value_states, (self-attention weights), (self-attention position bias), (cross-attention weights), (cross-attention position bias)\r\n\r\n\r\nclass T5PreTrainedModel(PreTrainedModel):\r\n \"\"\" An abstract class to handle weights initialization and\r\n a simple interface for downloading and loading pretrained models.\r\n \"\"\"\r\n\r\n config_class = T5Config\r\n load_tf_weights = load_tf_weights_in_t5\r\n base_model_prefix = \"transformer\"\r\n\r\n @property\r\n def dummy_inputs(self):\r\n input_ids = torch.tensor(DUMMY_INPUTS)\r\n input_mask = torch.tensor(DUMMY_MASK)\r\n dummy_inputs = {\r\n \"decoder_input_ids\": input_ids,\r\n \"input_ids\": input_ids,\r\n \"decoder_attention_mask\": input_mask,\r\n }\r\n return dummy_inputs\r\n\r\n def _init_weights(self, module):\r\n \"\"\" Initialize the weights \"\"\"\r\n factor = self.config.initializer_factor # Used for testing weights initialization\r\n if isinstance(module, T5LayerNorm):\r\n module.weight.data.fill_(factor * 1.0)\r\n elif isinstance(module, (T5Model, T5ForConditionalGeneration)):\r\n # Mesh TensorFlow embeddings initialization\r\n # See https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/layers.py#L1624\r\n module.shared.weight.data.normal_(mean=0.0, std=factor * 1.0)\r\n elif isinstance(module, T5DenseReluDense):\r\n # Mesh TensorFlow FF initialization\r\n # See https://github.com/tensorflow/mesh/blob/master/mesh_tensorflow/transformer/transformer_layers.py#L56\r\n # and https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/layers.py#L89\r\n module.wi.weight.data.normal_(mean=0.0, std=factor * ((self.config.d_model) ** -0.5))\r\n if hasattr(module.wi, \"bias\") and module.wi.bias is not None:\r\n module.wi.bias.data.zero_()\r\n module.wo.weight.data.normal_(mean=0.0, std=factor * ((self.config.d_ff) ** -0.5))\r\n if hasattr(module.wo, \"bias\") and module.wo.bias is not None:\r\n module.wo.bias.data.zero_()\r\n elif isinstance(module, T5Attention):\r\n # Mesh TensorFlow attention initialization to avoid scaling before softmax\r\n # See https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/transformer/attention.py#L136\r\n d_model = self.config.d_model\r\n d_kv = self.config.d_kv\r\n n_heads = self.config.num_heads\r\n module.q.weight.data.normal_(mean=0.0, std=factor * ((d_model * d_kv) ** -0.5))\r\n module.k.weight.data.normal_(mean=0.0, std=factor * (d_model ** -0.5))\r\n module.v.weight.data.normal_(mean=0.0, std=factor * (d_model ** -0.5))\r\n module.o.weight.data.normal_(mean=0.0, std=factor * ((n_heads * d_kv) ** -0.5))\r\n if module.has_relative_attention_bias:\r\n module.relative_attention_bias.weight.data.normal_(mean=0.0, std=factor * ((d_model) ** -0.5))\r\n\r\n def _shift_right(self, input_ids):\r\n decoder_start_token_id = self.config.decoder_start_token_id\r\n pad_token_id = self.config.pad_token_id\r\n\r\n assert (\r\n decoder_start_token_id is not None\r\n ), \"self.model.config.decoder_start_token_id has to be defined. In T5 it is usually set to the pad_token_id. See T5 docs for more information\"\r\n\r\n # shift inputs to the right\r\n shifted_input_ids = input_ids.new_zeros(input_ids.shape)\r\n shifted_input_ids[..., 1:] = input_ids[..., :-1].clone()\r\n shifted_input_ids[..., 0] = decoder_start_token_id\r\n\r\n assert pad_token_id is not None, \"self.model.config.pad_token_id has to be defined.\"\r\n # replace possible -100 values in lm_labels by `pad_token_id`\r\n shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)\r\n\r\n assert torch.all(shifted_input_ids >= 0).item(), \"Verify that `lm_labels` has only positive values and -100\"\r\n\r\n return shifted_input_ids\r\n\r\n\r\nclass T5Stack(T5PreTrainedModel):\r\n def __init__(self, config, embed_tokens=None):\r\n super().__init__(config)\r\n self.output_attentions = config.output_attentions\r\n self.output_hidden_states = config.output_hidden_states\r\n\r\n self.embed_tokens = embed_tokens\r\n self.is_decoder = config.is_decoder\r\n\r\n self.block = nn.ModuleList(\r\n [T5Block(config, has_relative_attention_bias=bool(i == 0)) for i in range(config.num_layers)]\r\n )\r\n self.final_layer_norm = T5LayerNorm(config.d_model, eps=config.layer_norm_epsilon)\r\n self.dropout = nn.Dropout(config.dropout_rate)\r\n\r\n self.init_weights()\r\n\r\n def get_input_embeddings(self):\r\n return self.embed_tokens\r\n\r\n def get_output_embeddings(self):\r\n return self.embed_tokens\r\n\r\n def set_input_embeddings(self, new_embeddings):\r\n self.embed_tokens = new_embeddings\r\n\r\n def forward(\r\n self,\r\n input_ids=None,\r\n attention_mask=None,\r\n encoder_hidden_states=None,\r\n encoder_attention_mask=None,\r\n inputs_embeds=None,\r\n head_mask=None,\r\n past_key_value_states=None,\r\n use_cache=False,\r\n ):\r\n\r\n if input_ids is not None and inputs_embeds is not None:\r\n raise ValueError(\"You cannot specify both input_ids and inputs_embeds at the same time\")\r\n elif input_ids is not None:\r\n input_shape = input_ids.size()\r\n input_ids = input_ids.view(-1, input_shape[-1])\r\n elif inputs_embeds is not None:\r\n input_shape = inputs_embeds.size()[:-1]\r\n else:\r\n if self.is_decoder:\r\n raise ValueError(\"You have to specify either decoder_input_ids or decoder_inputs_embeds\")\r\n else:\r\n raise ValueError(\"You have to specify either input_ids or inputs_embeds\")\r\n\r\n if inputs_embeds is None:\r\n assert self.embed_tokens is not None, \"You have to intialize the model with valid token embeddings\"\r\n inputs_embeds = self.embed_tokens(input_ids)\r\n\r\n batch_size, seq_length = input_shape\r\n\r\n if past_key_value_states is not None:\r\n assert seq_length == 1, \"Input shape is {}, but should be {} when using past_key_value_sates\".format(\r\n input_shape, (batch_size, 1)\r\n )\r\n # required mask seq length can be calculated via length of past\r\n # key value states and seq_length = 1 for the last token\r\n mask_seq_length = past_key_value_states[0][0].shape[2] + seq_length\r\n else:\r\n mask_seq_length = seq_length\r\n\r\n if attention_mask is None:\r\n attention_mask = torch.ones(batch_size, mask_seq_length).to(inputs_embeds.device)\r\n if self.is_decoder and encoder_attention_mask is None and encoder_hidden_states is not None:\r\n encoder_seq_length = encoder_hidden_states.shape[1]\r\n encoder_attention_mask = torch.ones(\r\n batch_size, encoder_seq_length, device=inputs_embeds.device, dtype=torch.long\r\n )\r\n\r\n # initialize past_key_value_states with `None` if past does not exist\r\n if past_key_value_states is None:\r\n past_key_value_states = [None] * len(self.block)\r\n\r\n # ourselves in which case we just need to make it broadcastable to all heads.\r\n extended_attention_mask = self.get_extended_attention_mask(attention_mask, input_shape, inputs_embeds.device)\r\n\r\n if self.is_decoder and encoder_attention_mask is not None:\r\n encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)\r\n else:\r\n encoder_extended_attention_mask = None\r\n\r\n # Prepare head mask if needed\r\n head_mask = self.get_head_mask(head_mask, self.config.num_layers)\r\n present_key_value_states = ()\r\n all_hidden_states = ()\r\n all_attentions = ()\r\n position_bias = None\r\n encoder_decoder_position_bias = None\r\n\r\n hidden_states = self.dropout(inputs_embeds)\r\n\r\n for i, (layer_module, past_key_value_state) in enumerate(zip(self.block, past_key_value_states)):\r\n if self.output_hidden_states:\r\n all_hidden_states = all_hidden_states + (hidden_states,)\r\n\r\n layer_outputs = layer_module(\r\n hidden_states,\r\n attention_mask=extended_attention_mask,\r\n position_bias=position_bias,\r\n encoder_hidden_states=encoder_hidden_states,\r\n encoder_attention_mask=encoder_extended_attention_mask,\r\n encoder_decoder_position_bias=encoder_decoder_position_bias,\r\n head_mask=head_mask[i],\r\n past_key_value_state=past_key_value_state,\r\n use_cache=use_cache,\r\n )\r\n # layer_outputs is a tuple with:\r\n # hidden-states, key-value-states, (self-attention weights), (self-attention position bias), (cross-attention weights), (cross-attention position bias)\r\n hidden_states, present_key_value_state = layer_outputs[:2]\r\n\r\n if i == 0:\r\n # We share the position biases between the layers - the first layer store them\r\n # layer_outputs = hidden-states, key-value-states (self-attention weights), (self-attention position bias), (cross-attention weights), (cross-attention position bias)\r\n position_bias = layer_outputs[3 if self.output_attentions else 2]\r\n if self.is_decoder and encoder_hidden_states is not None:\r\n encoder_decoder_position_bias = layer_outputs[5 if self.output_attentions else 3]\r\n # append next layer key value states\r\n present_key_value_states = present_key_value_states + (present_key_value_state,)\r\n\r\n if self.output_attentions:\r\n all_attentions = all_attentions + (layer_outputs[2],) # We keep only self-attention weights for now\r\n\r\n hidden_states = self.final_layer_norm(hidden_states)\r\n hidden_states = self.dropout(hidden_states)\r\n\r\n # Add last layer\r\n if self.output_hidden_states:\r\n all_hidden_states = all_hidden_states + (hidden_states,)\r\n\r\n outputs = (hidden_states,)\r\n if use_cache is True:\r\n assert self.is_decoder, \"`use_cache` can only be set to `True` if {} is used as a decoder\".format(self)\r\n outputs = outputs + (present_key_value_states,)\r\n if self.output_hidden_states:\r\n outputs = outputs + (all_hidden_states,)\r\n if self.output_attentions:\r\n outputs = outputs + (all_attentions,)\r\n return outputs # last-layer hidden state, (presents,) (all hidden states), (all attentions)\r\n\r\n\r\nT5_START_DOCSTRING = r\"\"\" The T5 model was proposed in\r\n `Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer`_\r\n by Colin Raffel, Noam Shazeer, Adam Roberts, Katherine Lee, Sharan Narang, Michael Matena, Yanqi Zhou, Wei Li, Peter J. Liu.\r\n It's an encoder decoder transformer pre-trained in a text-to-text denoising generative setting.\r\n\r\n This model is a PyTorch `torch.nn.Module`_ sub-class. Use it as a regular PyTorch Module and\r\n refer to the PyTorch documentation for all matter related to general usage and behavior.\r\n\r\n .. _`Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer`:\r\n https://arxiv.org/abs/1910.10683\r\n\r\n .. _`torch.nn.Module`:\r\n https://pytorch.org/docs/stable/nn.html#module\r\n\r\n Parameters:\r\n config (:class:`~transformers.T5Config`): Model configuration class with all the parameters of the model.\r\n Initializing with a config file does not load the weights associated with the model, only the configuration.\r\n Check out the :meth:`~transformers.PreTrainedModel.from_pretrained` method to load the model weights.\r\n\"\"\"\r\n\r\nT5_INPUTS_DOCSTRING = r\"\"\"\r\n Args:\r\n input_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`):\r\n Indices of input sequence tokens in the vocabulary.\r\n T5 is a model with relative position embeddings so you should be able to pad the inputs on both the right and the left.\r\n Indices can be obtained using :class:`transformers.T5Tokenizer`.\r\n See :func:`transformers.PreTrainedTokenizer.encode` and\r\n :func:`transformers.PreTrainedTokenizer.convert_tokens_to_ids` for details.\r\n To know more on how to prepare :obj:`input_ids` for pre-training take a look at\r\n `T5 Training <./t5.html#training>`_ .\r\n attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`):\r\n Mask to avoid performing attention on padding token indices.\r\n Mask values selected in ``[0, 1]``:\r\n ``1`` for tokens that are NOT MASKED, ``0`` for MASKED tokens.\r\n encoder_outputs (:obj:`tuple(tuple(torch.FloatTensor)`, `optional`, defaults to :obj:`None`):\r\n Tuple consists of (`last_hidden_state`, `optional`: `hidden_states`, `optional`: `attentions`)\r\n `last_hidden_state` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`, defaults to :obj:`None`) is a sequence of hidden-states at the output of the last layer of the encoder.\r\n Used in the cross-attention of the decoder.\r\n decoder_input_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, target_sequence_length)`, `optional`, defaults to :obj:`None`):\r\n Provide for sequence to sequence training. T5 uses the pad_token_id as the starting token for decoder_input_ids generation.\r\n If `decoder_past_key_value_states` is used, optionally only the last `decoder_input_ids` have to be input (see `decoder_past_key_value_states`).\r\n To know more on how to prepare :obj:`decoder_input_ids` for pre-training take a look at\r\n `T5 Training <./t5.html#training>`_ .\r\n decoder_attention_mask (:obj:`torch.BoolTensor` of shape :obj:`(batch_size, tgt_seq_len)`, `optional`, defaults to :obj:`None`):\r\n Default behavior: generate a tensor that ignores pad tokens in decoder_input_ids. Causal mask will also be used by default.\r\n decoder_past_key_value_states (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):\r\n Contains pre-computed key and value hidden-states of the attention blocks.\r\n Can be used to speed up decoding.\r\n If `decoder_past_key_value_states` are used, the user can optionally input only the last `decoder_input_ids`\r\n (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)`\r\n instead of all `decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`.\r\n use_cache (:obj:`bool`, `optional`, defaults to :obj:`True`):\r\n If `use_cache` is True, `decoder_past_key_value_states` are returned and can be used to speed up decoding (see `decoder_past_key_value_states`).\r\n inputs_embeds (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`, defaults to :obj:`None`):\r\n Optionally, instead of passing :obj:`input_ids` you can choose to directly pass an embedded representation.\r\n This is useful if you want more control over how to convert `input_ids` indices into associated vectors\r\n than the model's internal embedding lookup matrix.\r\n decoder_inputs_embeds (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, target_sequence_length, hidden_size)`, `optional`, defaults to :obj:`None`):\r\n Optionally, instead of passing :obj:`decoder_input_ids` you can choose to directly pass an embedded representation.\r\n If `decoder_past_key_value_states` is used, optionally only the last `decoder_inputs_embeds` have to be input (see `decoder_past_key_value_states`).\r\n This is useful if you want more control over how to convert `decoder_input_ids` indices into associated vectors\r\n than the model's internal embedding lookup matrix.\r\n head_mask: (:obj:`torch.FloatTensor` of shape :obj:`(num_heads,)` or :obj:`(num_layers, num_heads)`, `optional`, defaults to :obj:`None`):\r\n Mask to nullify selected heads of the self-attention modules.\r\n Mask values selected in ``[0, 1]``:\r\n ``1`` indicates the head is **not masked**, ``0`` indicates the head is **masked**.\r\n\"\"\"\r\n\r\n\r\n@add_start_docstrings(\r\n \"The bare T5 Model transformer outputting raw hidden-states\" \"without any specific head on top.\",\r\n T5_START_DOCSTRING,\r\n)\r\nclass T5Model(T5PreTrainedModel):\r\n def __init__(self, config):\r\n super().__init__(config)\r\n self.shared = nn.Embedding(config.vocab_size, config.d_model)\r\n\r\n encoder_config = copy.deepcopy(config)\r\n self.encoder = T5Stack(encoder_config, self.shared)\r\n\r\n decoder_config = copy.deepcopy(config)\r\n decoder_config.is_decoder = True\r\n self.decoder = T5Stack(decoder_config, self.shared)\r\n\r\n self.init_weights()\r\n\r\n def get_input_embeddings(self):\r\n return self.shared\r\n\r\n def set_input_embeddings(self, new_embeddings):\r\n self.shared = new_embeddings\r\n self.encoder.set_input_embeddings(new_embeddings)\r\n self.decoder.set_input_embeddings(new_embeddings)\r\n\r\n def get_encoder(self):\r\n return self.encoder\r\n\r\n def get_decoder(self):\r\n return self.decoder\r\n\r\n def _prune_heads(self, heads_to_prune):\r\n \"\"\" Prunes heads of the model.\r\n heads_to_prune: dict of {layer_num: list of heads to prune in this layer}\r\n See base class PreTrainedModel\r\n \"\"\"\r\n for layer, heads in heads_to_prune.items():\r\n self.encoder.layer[layer].attention.prune_heads(heads)\r\n\r\n @add_start_docstrings_to_callable(T5_INPUTS_DOCSTRING)\r\n def forward(\r\n self,\r\n input_ids=None,\r\n attention_mask=None,\r\n encoder_outputs=None,\r\n decoder_input_ids=None,\r\n decoder_attention_mask=None,\r\n decoder_past_key_value_states=None,\r\n use_cache=True,\r\n inputs_embeds=None,\r\n decoder_inputs_embeds=None,\r\n head_mask=None,\r\n ):\r\n r\"\"\"\r\n Return:\r\n :obj:`tuple(torch.FloatTensor)` comprising various elements depending on the configuration (:class:`~transformers.T5Config`) and inputs.\r\n last_hidden_state (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`):\r\n Sequence of hidden-states at the output of the last layer of the model.\r\n If `decoder_past_key_value_states` is used only the last hidden-state of the sequences of shape :obj:`(batch_size, 1, hidden_size)` is output.\r\n decoder_past_key_value_states (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length, embed_size_per_head)`, `optional`, returned when ``use_cache=True``):\r\n Contains pre-computed key and value hidden-states of the attention blocks.\r\n Can be used to speed up sequential decoding (see `decoder_past_key_value_states` input).\r\n Note that when using `decoder_past_key_value_states`, the model only outputs the last `hidden-state` of the sequence of shape :obj:`(batch_size, 1, config.vocab_size)`.\r\n hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_hidden_states=True``):\r\n Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)\r\n of shape :obj:`(batch_size, sequence_length, hidden_size)`.\r\n\r\n Hidden-states of the model at the output of each layer plus the initial embedding outputs.\r\n attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_attentions=True``):\r\n Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape\r\n :obj:`(batch_size, num_heads, sequence_length, sequence_length)`.\r\n\r\n Attentions weights after the attention softmax, used to compute the weighted average in the self-attention\r\n heads.\r\n\r\n Examples::\r\n\r\n from transformers import T5Tokenizer, T5Model\r\n\r\n tokenizer = T5Tokenizer.from_pretrained('t5-small')\r\n model = T5Model.from_pretrained('t5-small')\r\n input_ids = tokenizer.encode(\"Hello, my dog is cute\", return_tensors=\"pt\") # Batch size 1\r\n outputs = model(input_ids=input_ids, decoder_input_ids=input_ids)\r\n last_hidden_states = outputs[0] # The last hidden-state is the first element of the output tuple\r\n\r\n \"\"\"\r\n\r\n # Encode if needed (training, first prediction pass)\r\n if encoder_outputs is None:\r\n encoder_outputs = self.encoder(\r\n input_ids=input_ids, attention_mask=attention_mask, inputs_embeds=inputs_embeds, head_mask=head_mask\r\n )\r\n\r\n hidden_states = encoder_outputs[0]\r\n\r\n # If decoding with past key value states, only the last tokens\r\n # should be given as an input\r\n if decoder_past_key_value_states is not None:\r\n if decoder_input_ids is not None:\r\n decoder_input_ids = decoder_input_ids[:, -1:]\r\n if decoder_inputs_embeds is not None:\r\n decoder_inputs_embeds = decoder_inputs_embeds[:, -1:]\r\n\r\n # Decode\r\n decoder_outputs = self.decoder(\r\n input_ids=decoder_input_ids,\r\n attention_mask=decoder_attention_mask,\r\n inputs_embeds=decoder_inputs_embeds,\r\n past_key_value_states=decoder_past_key_value_states,\r\n encoder_hidden_states=hidden_states,\r\n encoder_attention_mask=attention_mask,\r\n head_mask=head_mask,\r\n use_cache=use_cache,\r\n )\r\n\r\n if use_cache is True:\r\n past = ((encoder_outputs, decoder_outputs[1]),)\r\n decoder_outputs = decoder_outputs[:1] + past + decoder_outputs[2:]\r\n\r\n return decoder_outputs + encoder_outputs\r\n\r\n\r\n@add_start_docstrings(\"\"\"T5 Model with a `language modeling` head on top. \"\"\", T5_START_DOCSTRING)\r\nclass T5ForConditionalGeneration(T5PreTrainedModel):\r\n def __init__(self, config):\r\n super().__init__(config)\r\n self.model_dim = config.d_model\r\n\r\n self.shared = nn.Embedding(config.vocab_size, config.d_model)\r\n\r\n encoder_config = copy.deepcopy(config)\r\n self.encoder = T5Stack(encoder_config, self.shared)\r\n\r\n decoder_config = copy.deepcopy(config)\r\n decoder_config.is_decoder = True\r\n self.decoder = T5Stack(decoder_config, self.shared)\r\n\r\n self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False)\r\n\r\n self.init_weights()\r\n\r\n def get_input_embeddings(self):\r\n return self.shared\r\n\r\n def set_input_embeddings(self, new_embeddings):\r\n self.shared = new_embeddings\r\n self.encoder.set_input_embeddings(new_embeddings)\r\n self.decoder.set_input_embeddings(new_embeddings)\r\n\r\n def get_output_embeddings(self):\r\n return self.lm_head\r\n\r\n def get_encoder(self):\r\n return self.encoder\r\n\r\n def get_decoder(self):\r\n return self.decoder\r\n\r\n @add_start_docstrings_to_callable(T5_INPUTS_DOCSTRING)\r\n def forward(\r\n self,\r\n input_ids=None,\r\n attention_mask=None,\r\n encoder_outputs=None,\r\n decoder_input_ids=None,\r\n decoder_attention_mask=None,\r\n decoder_past_key_value_states=None,\r\n use_cache=True,\r\n lm_labels=None,\r\n inputs_embeds=None,\r\n decoder_inputs_embeds=None,\r\n head_mask=None,\r\n ):\r\n r\"\"\"\r\n lm_labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`, defaults to :obj:`None`):\r\n Labels for computing the sequence classification/regression loss.\r\n Indices should be in :obj:`[-100, 0, ..., config.vocab_size - 1]`.\r\n All labels set to ``-100`` are ignored (masked), the loss is only\r\n computed for labels in ``[0, ..., config.vocab_size]``\r\n\r\n Returns:\r\n :obj:`tuple(torch.FloatTensor)` comprising various elements depending on the configuration (:class:`~transformers.T5Config`) and inputs.\r\n loss (:obj:`torch.FloatTensor` of shape :obj:`(1,)`, `optional`, returned when :obj:`lm_label` is provided):\r\n Classification loss (cross entropy).\r\n prediction_scores (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, config.vocab_size)`)\r\n Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).\r\n If `past_key_value_states` is used only the last prediction_scores of the sequences of shape :obj:`(batch_size, 1, hidden_size)` is output.\r\n decoder_past_key_value_states (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length, embed_size_per_head)`, `optional`, returned when ``use_cache=True``):\r\n Contains pre-computed key and value hidden-states of the attention blocks.\r\n Can be used to speed up sequential decoding (see `decoder_past_key_value_states` input).\r\n Note that when using `decoder_past_key_value_states`, the model only outputs the last `prediction_score` of the sequence of shape :obj:`(batch_size, 1, config.vocab_size)`.\r\n hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_hidden_states=True``):\r\n Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)\r\n of shape :obj:`(batch_size, sequence_length, hidden_size)`.\r\n Hidden-states of the model at the output of each layer plus the initial embedding outputs.\r\n attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_attentions=True``):\r\n Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape\r\n :obj:`(batch_size, num_heads, sequence_length, sequence_length)`.\r\n Attentions weights after the attention softmax, used to compute the weighted average in the self-attention.\r\n\r\n Examples::\r\n\r\n from transformers import T5Tokenizer, T5ForConditionalGeneration\r\n\r\n tokenizer = T5Tokenizer.from_pretrained('t5-small')\r\n model = T5ForConditionalGeneration.from_pretrained('t5-small')\r\n input_ids = tokenizer.encode(\"Hello, my dog is cute\", return_tensors=\"pt\") # Batch size 1\r\n outputs = model(input_ids=input_ids, decoder_input_ids=input_ids, lm_labels=input_ids)\r\n loss, prediction_scores = outputs[:2]\r\n\r\n tokenizer = T5Tokenizer.from_pretrained('t5-small')\r\n model = T5ForConditionalGeneration.from_pretrained('t5-small')\r\n input_ids = tokenizer.encode(\"summarize: Hello, my dog is cute\", return_tensors=\"pt\") # Batch size 1\r\n outputs = model.generate(input_ids)\r\n \"\"\"\r\n\r\n # Encode if needed (training, first prediction pass)\r\n if encoder_outputs is None:\r\n # Convert encoder inputs in embeddings if needed\r\n encoder_outputs = self.encoder(\r\n input_ids=input_ids, attention_mask=attention_mask, inputs_embeds=inputs_embeds, head_mask=head_mask\r\n )\r\n\r\n hidden_states = encoder_outputs[0]\r\n\r\n if lm_labels is not None and decoder_input_ids is None and decoder_inputs_embeds is None:\r\n # get decoder inputs from shifting lm labels to the right\r\n decoder_input_ids = self._shift_right(lm_labels)\r\n\r\n # If decoding with past key value states, only the last tokens\r\n # should be given as an input\r\n if decoder_past_key_value_states is not None:\r\n assert lm_labels is None, \"Decoder should not use cached key value states when training.\"\r\n if decoder_input_ids is not None:\r\n decoder_input_ids = decoder_input_ids[:, -1:]\r\n if decoder_inputs_embeds is not None:\r\n decoder_inputs_embeds = decoder_inputs_embeds[:, -1:]\r\n\r\n # Decode\r\n decoder_outputs = self.decoder(\r\n input_ids=decoder_input_ids,\r\n attention_mask=decoder_attention_mask,\r\n inputs_embeds=decoder_inputs_embeds,\r\n past_key_value_states=decoder_past_key_value_states,\r\n encoder_hidden_states=hidden_states,\r\n encoder_attention_mask=attention_mask,\r\n head_mask=head_mask,\r\n use_cache=use_cache,\r\n )\r\n\r\n # insert decoder past at right place\r\n # to speed up decoding\r\n if use_cache is True:\r\n past = ((encoder_outputs, decoder_outputs[1]),)\r\n decoder_outputs = decoder_outputs[:1] + past + decoder_outputs[2:]\r\n\r\n sequence_output = decoder_outputs[0]\r\n # Rescale output before projecting on vocab\r\n # See https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/transformer/transformer.py#L586\r\n sequence_output = sequence_output * (self.model_dim ** -0.5)\r\n lm_logits = self.lm_head(sequence_output)\r\n\r\n decoder_outputs = (lm_logits,) + decoder_outputs[1:] # Add hidden states and attention if they are here\r\n if lm_labels is not None:\r\n loss_fct = CrossEntropyLoss(ignore_index=-100)\r\n loss = loss_fct(lm_logits.view(-1, lm_logits.size(-1)), lm_labels.view(-1))\r\n # TODO(thom): Add z_loss https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/layers.py#L666\r\n decoder_outputs = (loss,) + decoder_outputs\r\n\r\n return decoder_outputs + encoder_outputs\r\n\r\n def prepare_inputs_for_generation(self, input_ids, past, attention_mask, use_cache, **kwargs):\r\n assert past is not None, \"past has to be defined for encoder_outputs\"\r\n\r\n # first step\r\n if len(past) < 2:\r\n encoder_outputs, decoder_past_key_value_states = past, None\r\n else:\r\n encoder_outputs, decoder_past_key_value_states = past[0], past[1]\r\n\r\n return {\r\n \"decoder_input_ids\": input_ids,\r\n \"decoder_past_key_value_states\": decoder_past_key_value_states,\r\n \"encoder_outputs\": encoder_outputs,\r\n \"attention_mask\": attention_mask,\r\n \"use_cache\": use_cache,\r\n }\r\n\r\n def _reorder_cache(self, past, beam_idx):\r\n # if decoder past is not included in output\r\n # speedy decoding is disabled and no need to reorder\r\n if len(past) < 2:\r\n logger.warning(\"You might want to consider setting `use_cache=True` to speed up decoding\")\r\n return past\r\n\r\n decoder_past = past[1]\r\n past = (past[0],)\r\n reordered_decoder_past = ()\r\n for layer_past_states in decoder_past:\r\n # get the correct batch idx from layer past batch dim\r\n # batch dim of `past` is at 2nd position\r\n reordered_layer_past_states = ()\r\n for layer_past_state in layer_past_states:\r\n # need to set correct `past` for each of the four key / value states\r\n reordered_layer_past_states = reordered_layer_past_states + (\r\n layer_past_state.index_select(0, beam_idx),\r\n )\r\n\r\n assert reordered_layer_past_states[0].shape == layer_past_states[0].shape\r\n assert len(reordered_layer_past_states) == len(layer_past_states)\r\n\r\n reordered_decoder_past = reordered_decoder_past + (reordered_layer_past_states,)\r\n return past + (reordered_decoder_past,)\r\n", "# coding=utf-8\r\n# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.\r\n# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n\r\nimport csv\r\nimport dataclasses\r\nimport json\r\nimport logging\r\nfrom dataclasses import dataclass\r\nfrom typing import List, Optional, Union\r\n\r\nfrom ...file_utils import is_tf_available, is_torch_available\r\n\r\n\r\nlogger = logging.getLogger(__name__)\r\n\r\n\r\n@dataclass\r\nclass InputExample:\r\n \"\"\"\r\n A single training/test example for simple sequence classification.\r\n\r\n Args:\r\n guid: Unique id for the example.\r\n text_a: string. The untokenized text of the first sequence. For single\r\n sequence tasks, only this sequence must be specified.\r\n text_b: (Optional) string. The untokenized text of the second sequence.\r\n Only must be specified for sequence pair tasks.\r\n label: (Optional) string. The label of the example. This should be\r\n specified for train and dev examples, but not for test examples.\r\n \"\"\"\r\n\r\n guid: str\r\n text_a: str\r\n text_b: Optional[str] = None\r\n label: Optional[str] = None\r\n\r\n def to_json_string(self):\r\n \"\"\"Serializes this instance to a JSON string.\"\"\"\r\n return json.dumps(dataclasses.asdict(self), indent=2) + \"\\n\"\r\n\r\n\r\n@dataclass(frozen=True)\r\nclass InputFeatures:\r\n \"\"\"\r\n A single set of features of data.\r\n Property names are the same names as the corresponding inputs to a model.\r\n\r\n Args:\r\n input_ids: Indices of input sequence tokens in the vocabulary.\r\n attention_mask: Mask to avoid performing attention on padding token indices.\r\n Mask values selected in ``[0, 1]``:\r\n Usually ``1`` for tokens that are NOT MASKED, ``0`` for MASKED (padded) tokens.\r\n token_type_ids: (Optional) Segment token indices to indicate first and second\r\n portions of the inputs. Only some models use them.\r\n label: (Optional) Label corresponding to the input. Int for classification problems,\r\n float for regression problems.\r\n \"\"\"\r\n\r\n input_ids: List[int]\r\n attention_mask: Optional[List[int]] = None\r\n token_type_ids: Optional[List[int]] = None\r\n label: Optional[Union[int, float]] = None\r\n\r\n def to_json_string(self):\r\n \"\"\"Serializes this instance to a JSON string.\"\"\"\r\n return json.dumps(dataclasses.asdict(self)) + \"\\n\"\r\n\r\n\r\nclass DataProcessor:\r\n \"\"\"Base class for data converters for sequence classification data sets.\"\"\"\r\n\r\n def get_example_from_tensor_dict(self, tensor_dict):\r\n \"\"\"Gets an example from a dict with tensorflow tensors\r\n Args:\r\n tensor_dict: Keys and values should match the corresponding Glue\r\n tensorflow_dataset examples.\r\n \"\"\"\r\n raise NotImplementedError()\r\n\r\n def get_train_examples(self, data_dir):\r\n \"\"\"Gets a collection of `InputExample`s for the train set.\"\"\"\r\n raise NotImplementedError()\r\n\r\n def get_dev_examples(self, data_dir):\r\n \"\"\"Gets a collection of `InputExample`s for the dev set.\"\"\"\r\n raise NotImplementedError()\r\n\r\n def get_test_examples(self, data_dir):\r\n \"\"\"Gets a collection of `InputExample`s for the test set.\"\"\"\r\n raise NotImplementedError()\r\n\r\n def get_labels(self):\r\n \"\"\"Gets the list of labels for this data set.\"\"\"\r\n raise NotImplementedError()\r\n\r\n def tfds_map(self, example):\r\n \"\"\"Some tensorflow_datasets datasets are not formatted the same way the GLUE datasets are.\r\n This method converts examples to the correct format.\"\"\"\r\n if len(self.get_labels()) > 1:\r\n example.label = self.get_labels()[int(example.label)]\r\n return example\r\n\r\n @classmethod\r\n def _read_tsv(cls, input_file, quotechar=None):\r\n \"\"\"Reads a tab separated value file.\"\"\"\r\n with open(input_file, \"r\", encoding=\"utf-8-sig\") as f:\r\n return list(csv.reader(f, delimiter=\"\\t\", quotechar=quotechar))\r\n\r\n\r\nclass SingleSentenceClassificationProcessor(DataProcessor):\r\n \"\"\" Generic processor for a single sentence classification data set.\"\"\"\r\n\r\n def __init__(self, labels=None, examples=None, mode=\"classification\", verbose=False):\r\n self.labels = [] if labels is None else labels\r\n self.examples = [] if examples is None else examples\r\n self.mode = mode\r\n self.verbose = verbose\r\n\r\n def __len__(self):\r\n return len(self.examples)\r\n\r\n def __getitem__(self, idx):\r\n if isinstance(idx, slice):\r\n return SingleSentenceClassificationProcessor(labels=self.labels, examples=self.examples[idx])\r\n return self.examples[idx]\r\n\r\n @classmethod\r\n def create_from_csv(\r\n cls, file_name, split_name=\"\", column_label=0, column_text=1, column_id=None, skip_first_row=False, **kwargs\r\n ):\r\n processor = cls(**kwargs)\r\n processor.add_examples_from_csv(\r\n file_name,\r\n split_name=split_name,\r\n column_label=column_label,\r\n column_text=column_text,\r\n column_id=column_id,\r\n skip_first_row=skip_first_row,\r\n overwrite_labels=True,\r\n overwrite_examples=True,\r\n )\r\n return processor\r\n\r\n @classmethod\r\n def create_from_examples(cls, texts_or_text_and_labels, labels=None, **kwargs):\r\n processor = cls(**kwargs)\r\n processor.add_examples(texts_or_text_and_labels, labels=labels)\r\n return processor\r\n\r\n def add_examples_from_csv(\r\n self,\r\n file_name,\r\n split_name=\"\",\r\n column_label=0,\r\n column_text=1,\r\n column_id=None,\r\n skip_first_row=False,\r\n overwrite_labels=False,\r\n overwrite_examples=False,\r\n ):\r\n lines = self._read_tsv(file_name)\r\n if skip_first_row:\r\n lines = lines[1:]\r\n texts = []\r\n labels = []\r\n ids = []\r\n for (i, line) in enumerate(lines):\r\n texts.append(line[column_text])\r\n labels.append(line[column_label])\r\n if column_id is not None:\r\n ids.append(line[column_id])\r\n else:\r\n guid = \"%s-%s\" % (split_name, i) if split_name else \"%s\" % i\r\n ids.append(guid)\r\n\r\n return self.add_examples(\r\n texts, labels, ids, overwrite_labels=overwrite_labels, overwrite_examples=overwrite_examples\r\n )\r\n\r\n def add_examples(\r\n self, texts_or_text_and_labels, labels=None, ids=None, overwrite_labels=False, overwrite_examples=False\r\n ):\r\n assert labels is None or len(texts_or_text_and_labels) == len(labels)\r\n assert ids is None or len(texts_or_text_and_labels) == len(ids)\r\n if ids is None:\r\n ids = [None] * len(texts_or_text_and_labels)\r\n if labels is None:\r\n labels = [None] * len(texts_or_text_and_labels)\r\n examples = []\r\n added_labels = set()\r\n for (text_or_text_and_label, label, guid) in zip(texts_or_text_and_labels, labels, ids):\r\n if isinstance(text_or_text_and_label, (tuple, list)) and label is None:\r\n text, label = text_or_text_and_label\r\n else:\r\n text = text_or_text_and_label\r\n added_labels.add(label)\r\n examples.append(InputExample(guid=guid, text_a=text, text_b=None, label=label))\r\n\r\n # Update examples\r\n if overwrite_examples:\r\n self.examples = examples\r\n else:\r\n self.examples.extend(examples)\r\n\r\n # Update labels\r\n if overwrite_labels:\r\n self.labels = list(added_labels)\r\n else:\r\n self.labels = list(set(self.labels).union(added_labels))\r\n\r\n return self.examples\r\n\r\n def get_features(\r\n self,\r\n tokenizer,\r\n max_length=None,\r\n pad_on_left=False,\r\n pad_token=0,\r\n mask_padding_with_zero=True,\r\n return_tensors=None,\r\n ):\r\n \"\"\"\r\n Convert examples in a list of ``InputFeatures``\r\n\r\n Args:\r\n tokenizer: Instance of a tokenizer that will tokenize the examples\r\n max_length: Maximum example length\r\n task: GLUE task\r\n label_list: List of labels. Can be obtained from the processor using the ``processor.get_labels()`` method\r\n output_mode: String indicating the output mode. Either ``regression`` or ``classification``\r\n pad_on_left: If set to ``True``, the examples will be padded on the left rather than on the right (default)\r\n pad_token: Padding token\r\n mask_padding_with_zero: If set to ``True``, the attention mask will be filled by ``1`` for actual values\r\n and by ``0`` for padded values. If set to ``False``, inverts it (``1`` for padded values, ``0`` for\r\n actual values)\r\n\r\n Returns:\r\n If the ``examples`` input is a ``tf.data.Dataset``, will return a ``tf.data.Dataset``\r\n containing the task-specific features. If the input is a list of ``InputExamples``, will return\r\n a list of task-specific ``InputFeatures`` which can be fed to the model.\r\n\r\n \"\"\"\r\n if max_length is None:\r\n max_length = tokenizer.max_len\r\n\r\n label_map = {label: i for i, label in enumerate(self.labels)}\r\n\r\n all_input_ids = []\r\n for (ex_index, example) in enumerate(self.examples):\r\n if ex_index % 10000 == 0:\r\n logger.info(\"Tokenizing example %d\", ex_index)\r\n\r\n input_ids = tokenizer.encode(\r\n example.text_a, add_special_tokens=True, max_length=min(max_length, tokenizer.max_len),\r\n )\r\n all_input_ids.append(input_ids)\r\n\r\n batch_length = max(len(input_ids) for input_ids in all_input_ids)\r\n\r\n features = []\r\n for (ex_index, (input_ids, example)) in enumerate(zip(all_input_ids, self.examples)):\r\n if ex_index % 10000 == 0:\r\n logger.info(\"Writing example %d/%d\" % (ex_index, len(self.examples)))\r\n # The mask has 1 for real tokens and 0 for padding tokens. Only real\r\n # tokens are attended to.\r\n attention_mask = [1 if mask_padding_with_zero else 0] * len(input_ids)\r\n\r\n # Zero-pad up to the sequence length.\r\n padding_length = batch_length - len(input_ids)\r\n if pad_on_left:\r\n input_ids = ([pad_token] * padding_length) + input_ids\r\n attention_mask = ([0 if mask_padding_with_zero else 1] * padding_length) + attention_mask\r\n else:\r\n input_ids = input_ids + ([pad_token] * padding_length)\r\n attention_mask = attention_mask + ([0 if mask_padding_with_zero else 1] * padding_length)\r\n\r\n assert len(input_ids) == batch_length, \"Error with input length {} vs {}\".format(\r\n len(input_ids), batch_length\r\n )\r\n assert len(attention_mask) == batch_length, \"Error with input length {} vs {}\".format(\r\n len(attention_mask), batch_length\r\n )\r\n\r\n if self.mode == \"classification\":\r\n label = label_map[example.label]\r\n elif self.mode == \"regression\":\r\n label = float(example.label)\r\n else:\r\n raise ValueError(self.mode)\r\n\r\n if ex_index < 5 and self.verbose:\r\n logger.info(\"*** Example ***\")\r\n logger.info(\"guid: %s\" % (example.guid))\r\n logger.info(\"input_ids: %s\" % \" \".join([str(x) for x in input_ids]))\r\n logger.info(\"attention_mask: %s\" % \" \".join([str(x) for x in attention_mask]))\r\n logger.info(\"label: %s (id = %d)\" % (example.label, label))\r\n\r\n features.append(InputFeatures(input_ids=input_ids, attention_mask=attention_mask, label=label))\r\n\r\n if return_tensors is None:\r\n return features\r\n elif return_tensors == \"tf\":\r\n if not is_tf_available():\r\n raise RuntimeError(\"return_tensors set to 'tf' but TensorFlow 2.0 can't be imported\")\r\n import tensorflow as tf\r\n\r\n def gen():\r\n for ex in features:\r\n yield ({\"input_ids\": ex.input_ids, \"attention_mask\": ex.attention_mask}, ex.label)\r\n\r\n dataset = tf.data.Dataset.from_generator(\r\n gen,\r\n ({\"input_ids\": tf.int32, \"attention_mask\": tf.int32}, tf.int64),\r\n ({\"input_ids\": tf.TensorShape([None]), \"attention_mask\": tf.TensorShape([None])}, tf.TensorShape([])),\r\n )\r\n return dataset\r\n elif return_tensors == \"pt\":\r\n if not is_torch_available():\r\n raise RuntimeError(\"return_tensors set to 'pt' but PyTorch can't be imported\")\r\n import torch\r\n from torch.utils.data import TensorDataset\r\n\r\n all_input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long)\r\n all_attention_mask = torch.tensor([f.attention_mask for f in features], dtype=torch.long)\r\n if self.mode == \"classification\":\r\n all_labels = torch.tensor([f.label for f in features], dtype=torch.long)\r\n elif self.mode == \"regression\":\r\n all_labels = torch.tensor([f.label for f in features], dtype=torch.float)\r\n\r\n dataset = TensorDataset(all_input_ids, all_attention_mask, all_labels)\r\n return dataset\r\n else:\r\n raise ValueError(\"return_tensors should be one of 'tf' or 'pt'\")\r\n" ]
[ [ "torch.save", "torch.load" ], [ "torch.all", "torch.abs", "torch.nn.functional.dropout", "torch.cat", "torch.nn.Embedding", "torch.where", "torch.full_like", "torch.nn.Dropout", "torch.nn.CrossEntropyLoss", "torch.ones", "torch.sqrt", "torch.einsum", "torch.tensor", "torch.nn.functional.relu", "torch.arange", "tensorflow.train.list_variables", "torch.nn.ModuleList", "torch.zeros_like", "tensorflow.train.load_variable", "torch.nn.Linear", "numpy.transpose", "torch.matmul" ], [ "torch.utils.data.TensorDataset", "tensorflow.TensorShape", "torch.tensor" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.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" ] } ]
YeongHyeon/Context-Encoder
[ "30efe975a8970dca0dfa70c09c889efadf7c9c09" ]
[ "source/tf_process.py" ]
[ "import os, inspect, time, math\n\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom random import *\nfrom PIL import Image\nfrom sklearn.decomposition import PCA\n\nPACK_PATH = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))+\"/..\"\n\ndef make_dir(path):\n\n try: os.mkdir(path)\n except: pass\n\ndef gray2rgb(gray):\n\n rgb = np.ones((gray.shape[0], gray.shape[1], 3)).astype(np.float32)\n rgb[:, :, 0] = gray[:, :, 0]\n rgb[:, :, 1] = gray[:, :, 0]\n rgb[:, :, 2] = gray[:, :, 0]\n\n return rgb\n\ndef dat2canvas(data, height, width):\n\n numd = math.ceil(np.sqrt(data.shape[0]))\n [dn, dh, dw, dc] = data.shape\n canvas = np.ones((dh*numd, dw*numd, dc)).astype(np.float32)\n\n for y in range(numd):\n for x in range(numd):\n try: tmp = data[x+(y*numd)]\n except: pass\n else: canvas[(y*dh):(y*dh)+height, (x*dw):(x*dw)+width, :] = tmp\n if(dc == 1):\n canvas = gray2rgb(gray=canvas)\n\n return canvas\n\ndef save_img(contents, height, width, names=[\"\", \"\", \"\"], savename=\"\"):\n\n num_cont = len(contents)\n plt.figure(figsize=(5*num_cont+2, 5))\n\n for i in range(num_cont):\n plt.subplot(1,num_cont,i+1)\n plt.title(names[i])\n plt.imshow(dat2canvas(data=contents[i], height=height, width=width))\n\n plt.tight_layout()\n plt.savefig(savename)\n plt.close()\n\ndef discrete_cmap(N, base_cmap=None):\n\n base = plt.cm.get_cmap(base_cmap)\n color_list = base(np.linspace(0, 1, N))\n cmap_name = base.name + str(N)\n\n return base.from_list(cmap_name, color_list, N)\n\ndef latent_plot(latent, y, n, savename=\"\"):\n\n plt.figure(figsize=(6, 5))\n plt.scatter(latent[:, 0], latent[:, 1], c=y, \\\n marker='o', edgecolor='none', cmap=discrete_cmap(n, 'jet'))\n plt.colorbar(ticks=range(n))\n plt.grid()\n plt.tight_layout()\n plt.savefig(savename)\n plt.close()\n\ndef boxplot(contents, savename=\"\"):\n\n data, label = [], []\n for cidx, content in enumerate(contents):\n data.append(content)\n label.append(\"class-%d\" %(cidx))\n\n plt.clf()\n fig, ax1 = plt.subplots()\n bp = ax1.boxplot(data, showfliers=True, whis=3)\n ax1.set_xticklabels(label, rotation=45)\n\n plt.tight_layout()\n plt.savefig(savename)\n plt.close()\n\ndef histogram(contents, savename=\"\"):\n\n n1, _, _ = plt.hist(contents[0], bins=100, alpha=0.5, label='Normal')\n n2, _, _ = plt.hist(contents[1], bins=100, alpha=0.5, label='Abnormal')\n h_inter = np.sum(np.minimum(n1, n2)) / np.sum(n1)\n plt.xlabel(\"MSE\")\n plt.ylabel(\"Number of Data\")\n xmax = max(contents[0].max(), contents[1].max())\n plt.xlim(0, xmax)\n plt.text(x=xmax*0.01, y=max(n1.max(), n2.max()), s=\"Histogram Intersection: %.3f\" %(h_inter))\n plt.legend(loc='upper right')\n plt.savefig(savename)\n plt.close()\n\ndef generate_random_mask(x, height, width):\n\n h_s, w_s = randrange(height//2), randrange(width//2)\n h_d, w_d = randint(height//4, height//2), randint(width//4, width//2)\n h_e, w_e = h_s + h_d, w_s + w_d\n m = np.zeros_like(x)\n m[:, h_s:h_e, w_s:w_e, :] = 1\n\n return m\n\ndef generate_static_mask(x, height, width):\n\n h_d, w_d = height//3, width//3\n h_s, w_s = height//2 - h_d//2, width//2 - w_d//2\n h_e, w_e = h_s + h_d, w_s + w_d\n m = np.zeros_like(x)\n m[:, h_s:h_e, w_s:w_e, :] = 1\n\n return m\n\ndef training(sess, saver, neuralnet, dataset, epochs, batch_size, normalize=True):\n\n print(\"\\nTraining to %d epochs (%d of minibatch size)\" %(epochs, batch_size))\n\n summary_writer = tf.compat.v1.summary.FileWriter(PACK_PATH+'/Checkpoint', sess.graph)\n\n make_dir(path=\"training\")\n\n start_time = time.time()\n iteration = 0\n\n run_options = tf.compat.v1.RunOptions(trace_level=tf.compat.v1.RunOptions.FULL_TRACE)\n run_metadata = tf.compat.v1.RunMetadata()\n\n test_sq = 10\n test_size = test_sq**2\n for epoch in range(epochs):\n\n x_tr, _ = dataset.next_train(batch_size=test_size, fix=True)\n m_tr = generate_static_mask(x=x_tr, height=dataset.height, width=dataset.width)\n\n x_masked, x_restore = sess.run([neuralnet.drop, neuralnet.x_hat], \\\n feed_dict={neuralnet.x:x_tr, neuralnet.m:m_tr, neuralnet.batch_size:x_tr.shape[0]})\n\n save_img(contents=[x_tr, x_masked, x_masked + (x_restore * m_tr), (x_tr-x_restore)**2], \\\n height=dataset.height, width=dataset.width, \\\n names=[\"Input\\n(x)\", \"Masked\\n(from x)\", \"Restoration\\n(x to x-hat)\", \"Difference\"], \\\n savename=os.path.join(\"training\", \"%08d.png\" %(epoch)))\n\n while(True):\n x_tr, terminator = dataset.next_train(batch_size)\n m_tr = generate_random_mask(x=x_tr, height=dataset.height, width=dataset.width)\n\n _, summaries = sess.run([neuralnet.optimizer, neuralnet.summaries], \\\n feed_dict={neuralnet.x:x_tr, neuralnet.m:m_tr, neuralnet.batch_size:x_tr.shape[0]}, \\\n options=run_options, run_metadata=run_metadata)\n loss_rec, loss_adv, loss_tot = sess.run([neuralnet.loss_rec, neuralnet.loss_adv, neuralnet.loss_tot], \\\n feed_dict={neuralnet.x:x_tr, neuralnet.m:m_tr, neuralnet.batch_size:x_tr.shape[0]})\n summary_writer.add_summary(summaries, iteration)\n\n iteration += 1\n if(terminator): break\n\n print(\"Epoch [%d / %d] (%d iteration) Rec:%.3f, Adv:%.3f, Tot:%.3f\" \\\n %(epoch, epochs, iteration, loss_rec, loss_adv, loss_tot))\n saver.save(sess, PACK_PATH+\"/Checkpoint/model_checker\")\n summary_writer.add_run_metadata(run_metadata, 'epoch-%d' % epoch)\n\ndef test(sess, saver, neuralnet, dataset, batch_size):\n\n if(os.path.exists(PACK_PATH+\"/Checkpoint/model_checker.index\")):\n print(\"\\nRestoring parameters\")\n saver.restore(sess, PACK_PATH+\"/Checkpoint/model_checker\")\n\n print(\"\\nTest...\")\n\n make_dir(path=\"test\")\n\n while(True):\n x_te, terminator = dataset.next_test(1)\n m_te = generate_static_mask(x=x_te, height=dataset.height, width=dataset.width)\n\n x_masked, x_restore, restore_loss = sess.run([neuralnet.drop, neuralnet.x_hat, neuralnet.mse_r], \\\n feed_dict={neuralnet.x:x_te, neuralnet.m:m_te, neuralnet.batch_size:x_te.shape[0]})\n\n [h, w, c] = x_te[0].shape\n canvas = np.ones((h, w*3, c), np.float32)\n canvas[:, :w, :] = x_te[0]\n canvas[:, w:w*2, :] = x_masked[0]\n canvas[:, w*2:, :] = x_masked[0] + (x_restore[0] * m_te[0])\n\n result = Image.fromarray((canvas * 255).astype(np.uint8))\n result.save(os.path.join(\"test\", \"%08d.png\" %(dataset.idx_te)))\n\n if(terminator): break\n" ]
[ [ "matplotlib.pyplot.legend", "numpy.minimum", "numpy.sqrt", "numpy.linspace", "numpy.zeros_like", "matplotlib.pyplot.tight_layout", "matplotlib.pyplot.subplot", "matplotlib.pyplot.close", "matplotlib.pyplot.figure", "matplotlib.pyplot.cm.get_cmap", "matplotlib.pyplot.title", "matplotlib.pyplot.savefig", "tensorflow.compat.v1.RunOptions", "matplotlib.pyplot.hist", "numpy.sum", "matplotlib.pyplot.ylabel", "tensorflow.compat.v1.RunMetadata", "tensorflow.compat.v1.summary.FileWriter", "matplotlib.pyplot.subplots", "numpy.ones", "matplotlib.pyplot.xlim", "matplotlib.pyplot.clf", "matplotlib.pyplot.grid", "matplotlib.pyplot.xlabel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
sicara/mentat
[ "fbcfbbe71042740f05e0b1e368bb747c8e0d10ee" ]
[ "tf_explain/utils/image.py" ]
[ "\"\"\" Module for image operations \"\"\"\nimport numpy as np\nimport tensorflow as tf\n\n\ndef apply_grey_patch(image, top_left_x, top_left_y, patch_size):\n \"\"\"\n Replace a part of the image with a grey patch.\n\n Args:\n image (numpy.ndarray): Input image\n top_left_x (int): Top Left X position of the applied box\n top_left_y (int): Top Left Y position of the applied box\n patch_size (int): Size of patch to apply\n\n Returns:\n numpy.ndarray: Patched image\n \"\"\"\n patched_image = np.array(image, copy=True)\n patched_image[\n top_left_y : top_left_y + patch_size, top_left_x : top_left_x + patch_size, :\n ] = 127.5\n\n return patched_image\n\n\[email protected]\ndef transform_to_normalized_grayscale(tensor):\n \"\"\"\n Transform tensor over RGB axis to grayscale.\n\n Args:\n tensor (tf.Tensor): 4D-Tensor with shape (batch_size, H, W, 3)\n\n Returns:\n tf.Tensor: 4D-Tensor of grayscale tensor, with shape (batch_size, H, W, 1)\n \"\"\"\n grayscale_tensor = tf.reduce_sum(tensor, axis=-1)\n\n normalized_tensor = tf.cast(\n 255 * tf.image.per_image_standardization(grayscale_tensor), tf.uint8\n )\n\n return normalized_tensor\n" ]
[ [ "tensorflow.reduce_sum", "numpy.array", "tensorflow.image.per_image_standardization" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
jiaw-z/FCStereo
[ "f76c3317e0951986b49a3bb794028a8ae067d410" ]
[ "dmb/modeling/stereo/backbones/FC_PSMNet.py" ]
[ "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom dmb.modeling.stereo.layers.basic_layers import conv_bn, conv_bn_relu, BasicBlock\nfrom dmb.modeling.stereo.layers.basic_layers import conv_in_relu, BasicBlock_IN\n\nclass PSM_Encoder_Instance(nn.Module):\n \"\"\"\n Backbone proposed in PSMNet.\n Args:\n in_planes (int): the channels of input\n batch_norm (bool): whether use batch normalization layer, default True\n Inputs:\n l_img (Tensor): left image, in [BatchSize, 3, Height, Width] layout\n r_img (Tensor): right image, in [BatchSize, 3, Height, Width] layout\n Outputs:\n l_fms (Tensor): left image feature maps, in [BatchSize, 32, Height//4, Width//4] layout\n\n r_fms (Tensor): right image feature maps, in [BatchSize, 32, Height//4, Width//4] layout\n \"\"\"\n\n def __init__(self, in_planes=3, batch_norm=True):\n super(PSM_Encoder_Instance, self).__init__()\n self.in_planes = in_planes\n self.batch_norm = batch_norm\n\n self.firstconv = nn.Sequential(\n conv_in_relu(batch_norm, self.in_planes, 32, 3, 2, 1, 1, bias=False),\n conv_in_relu(batch_norm, 32, 32, 3, 1, 1, 1, bias=False),\n conv_in_relu(batch_norm, 32, 32, 3, 1, 1, 1, bias=False),\n )\n\n\n # For building Basic Block\n self.in_planes = 32\n\n # BasicBlock_IN\n self.layer1 = self._make_layer(batch_norm, BasicBlock_IN, 32, 3, 1, 1, 1)\n self.layer2 = self._make_layer(batch_norm, BasicBlock, 64, 16, 2, 1, 1)\n self.layer3 = self._make_layer(batch_norm, BasicBlock, 128, 3, 1, 1, 1)\n self.layer4 = self._make_layer(batch_norm, BasicBlock, 128, 3, 1, 2, 2)\n\n self.branch1 = nn.Sequential(\n nn.AvgPool2d((64, 64), stride=(64, 64)),\n conv_bn_relu(batch_norm, 128, 32, 1, 1, 0, 1, bias=False),\n )\n self.branch2 = nn.Sequential(\n nn.AvgPool2d((32, 32), stride=(32, 32)),\n conv_bn_relu(batch_norm, 128, 32, 1, 1, 0, 1, bias=False),\n )\n self.branch3 = nn.Sequential(\n nn.AvgPool2d((16, 16), stride=(16, 16)),\n conv_bn_relu(batch_norm, 128, 32, 1, 1, 0, 1, bias=False),\n )\n self.branch4 = nn.Sequential(\n nn.AvgPool2d((8, 8), stride=(8, 8)),\n conv_bn_relu(batch_norm, 128, 32, 1, 1, 0, 1, bias=False),\n )\n self.lastconv = nn.Sequential(\n conv_bn_relu(batch_norm, 320, 128, 3, 1, 1, 1, bias=False),\n nn.Conv2d(128, 32, kernel_size=1, padding=0, stride=1, dilation=1, bias=False)\n )\n\n def _make_layer(self, batch_norm, block, out_planes, blocks, stride, padding, dilation):\n downsample = None\n if stride != 1 or self.in_planes != out_planes * block.expansion:\n downsample = conv_bn(\n batch_norm, self.in_planes, out_planes * block.expansion,\n kernel_size=1, stride=stride, padding=0, dilation=1\n )\n\n layers = []\n layers.append(\n block(batch_norm, self.in_planes, out_planes, stride, downsample, padding, dilation)\n )\n self.in_planes = out_planes * block.expansion\n for i in range(1, blocks):\n layers.append(\n block(batch_norm, self.in_planes, out_planes, 1, None, padding, dilation)\n )\n\n return nn.Sequential(*layers)\n\n def _forward(self, x):\n w_arr = []\n for i in range(len(self.firstconv)):\n x = self.firstconv[i](x)\n w_arr.append(x)\n\n for i in range(len(self.layer1)):\n x = self.layer1[i](x)\n w_arr.append(x)\n \n output_2_1 = x\n output_4_0 = self.layer2(output_2_1)\n output_4_1 = self.layer3(output_4_0)\n output_8 = self.layer4(output_4_1)\n\n output_branch1 = self.branch1(output_8)\n output_branch1 = F.interpolate(\n output_branch1, (output_8.size()[2], output_8.size()[3]),\n mode='bilinear', align_corners=True\n )\n\n output_branch2 = self.branch2(output_8)\n output_branch2 = F.interpolate(\n output_branch2, (output_8.size()[2], output_8.size()[3]),\n mode='bilinear', align_corners=True\n )\n\n output_branch3 = self.branch3(output_8)\n output_branch3 = F.interpolate(\n output_branch3, (output_8.size()[2], output_8.size()[3]),\n mode='bilinear', align_corners=True\n )\n\n output_branch4 = self.branch4(output_8)\n output_branch4 = F.interpolate(\n output_branch4, (output_8.size()[2], output_8.size()[3]),\n mode='bilinear', align_corners=True\n )\n\n output_feature = torch.cat(\n (output_4_0, output_8, output_branch4, output_branch3, output_branch2, output_branch1), 1)\n output_feature = self.lastconv(output_feature)\n\n return output_feature, w_arr\n\n def forward(self, input):\n fms, w_arr = self._forward(input)\n\n return [fms, w_arr]\n\n\n\n\nclass FCPSMNetBackbone(nn.Module):\n \"\"\"\n Backbone proposed in PSMNet.\n Args:\n in_planes (int): the channels of input\n batch_norm (bool): whether use batch normalization layer, default True\n Inputs:\n l_img (Tensor): left image, in [BatchSize, 3, Height, Width] layout\n r_img (Tensor): right image, in [BatchSize, 3, Height, Width] layout\n Outputs:\n l_fms (Tensor): left image feature maps, in [BatchSize, 32, Height//4, Width//4] layout\n\n r_fms (Tensor): right image feature maps, in [BatchSize, 32, Height//4, Width//4] layout\n \"\"\"\n\n def __init__(self, in_planes=3, batch_norm=True, m=0.999):\n super(FCPSMNetBackbone, self).__init__() \n self.in_planes = in_planes\n self.m = m\n print('m:{}'.format(m))\n self.encoder_q = PSM_Encoder_Instance(in_planes, batch_norm)\n self.encoder_k = PSM_Encoder_Instance(in_planes, batch_norm)\n\n for param_q, param_k in zip(self.encoder_q.parameters(), self.encoder_k.parameters()):\n param_k.data.copy_(param_q.data) # initialize\n param_k.requires_grad = False # not update by gradient\n\n @torch.no_grad()\n def _momentum_update_key_encoder(self):\n \"\"\"\n Momentum update of the key encoder\n \"\"\"\n for param_q, param_k in zip(self.encoder_q.parameters(), self.encoder_k.parameters()):\n param_k.data = param_k.data * self.m + param_q.data * (1. - self.m)\n\n def forward(self, *input):\n if len(input) != 2:\n raise ValueError('expected input length 2 (got {} length input)'.format(len(input)))\n\n l_img, r_img = input\n\n l_fms, l_w_arr = self.encoder_q(l_img)\n\n if self.training:\n with torch.no_grad(): # no gradient to keys\n self._momentum_update_key_encoder() # update the key encoder\n r_fms, r_w_arr = self.encoder_k(r_img)\n if isinstance(r_fms, list):\n r_fms[0] = r_fms[0].detach()\n else:\n r_fms = r_fms.detach()\n else:\n r_fms, r_w_arr = self.encoder_q(r_img)\n\n return [l_fms, l_w_arr], [r_fms, r_w_arr]" ]
[ [ "torch.nn.Sequential", "torch.cat", "torch.nn.Conv2d", "torch.nn.AvgPool2d", "torch.no_grad" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Talendar/deep_learning_exercises
[ "4c375ac478434d085b4b67b7f631d43da9f8a4a1" ]
[ "3_comparison_mlp_and_rbf/rbf_net/RBFNetwork.py" ]
[ "\"\"\" Implementation of a Radial Basis Function (RBF) Network.\n\n@author Gabriel Nogueira (Talendar)\n@author Marcel Otoboni\n\"\"\"\n\nfrom mlp.multilayer_perceptron import MultilayerPerceptron\nimport numpy as np\nfrom sklearn.cluster import KMeans\n\n\nclass RBFNetwork:\n \"\"\" Implementation of a Radial Basis Function (RBF) Network. \"\"\"\n\n def __init__(self, num_output_neurons, num_clusters=8):\n \"\"\" Instantiates a new RBF network.\n\n :param num_output_neurons: number of neurons in the output layer.\n :param num_clusters: number of clusters to be considered by the k-means algorithm.\n \"\"\"\n self._num_clusters = num_clusters\n self._kmeans = None\n self._mlp = MultilayerPerceptron(num_clusters, layers_size=[num_output_neurons], layers_activation=\"linear\")\n\n def _gauss_rbf(self, data, breadth_param=1):\n \"\"\" Transforms the data using the Gaussian radial basis function. \"\"\"\n transformed = []\n for x in data:\n trans_x = np.zeros(self._num_clusters)\n for i, u in enumerate(self._kmeans.cluster_centers_): # iterate through centroids of the clusters\n v = np.linalg.norm(x - u) # distance between x and the centroid\n trans_x[i] = np.exp(-(v**2) / (2 * breadth_param**2)) # gaussian function\n transformed.append(trans_x)\n return np.array(transformed)\n\n def predict(self, x, just_one=False):\n \"\"\" Predicts the class of the given example. \"\"\"\n if just_one:\n x = np.array([x])\n return self._mlp.predict(self._gauss_rbf(x))\n\n def fit(self, data, labels, cost_function, epochs, learning_rate):\n \"\"\" Fits the model to the given data.\n\n :param data: numpy 2D-array in which each ROW represents an input sample vector.\n :param labels: numpy 2D-array in which each ROW represents a vector with the samples' labels.\n :param cost_function: cost function to be minimized.\n :param epochs: number of training epochs (iterations).\n :param learning_rate: learning rate of the model.\n \"\"\"\n self._kmeans = KMeans(n_clusters=self._num_clusters).fit(data)\n data = self._gauss_rbf(data)\n self._mlp.fit(data, labels, cost_function, epochs, learning_rate)\n" ]
[ [ "sklearn.cluster.KMeans", "numpy.linalg.norm", "numpy.array", "numpy.exp", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ls-2018/tips
[ "1f5f5195d7181b5dd4616db02166f7f92c97f1cd", "1f5f5195d7181b5dd4616db02166f7f92c97f1cd" ]
[ "AWS/get_data.py", "AWS/xxxxxxx.py" ]
[ "# encoding=utf-8\n\"\"\"\n@Time: 2019/7/8 10:09 \n@Author: liushuo\n@File: get_data.py \n@Desc: \n@Software: PyCharm\n\"\"\"\nimport boto3\nimport pandas as pd\n\n# s3 = boto3.resource('s3')\n# bucket = s3.Bucket('s3-billing')\n# data1 = data2 = None\n# for obj in bucket.objects.all():\n# if '936669166135-aws-billing-csv-2017-10.csv' == obj.key:\n# data1 = pd.read_csv(obj.get()['Body'])\n# if '936669166135-aws-billing-csv-2017-9.csv' == obj.key:\n# data2 = pd.read_csv(obj.get()['Body'])\n\n# if data1 and data2:\n# data1.append()\n\n\ndf1 = pd.DataFrame({'a': [1, 2, 3, 4, 5], 'b': [1, 2, 3, 5, 4], 'c': [1, 2, 3, 5, 4], 'd': [1, 2, 3, 5, 4]})\n\n# s = pd.Series([16, 17, 1, 2], index=df1.columns)\n# df = df1.append(s, )\n\n# s = pd.Series([16, 17, 18, 19], name='E', index=df.index)\n# df = pd.concat([df, s], axis=1)\ndf = pd.DataFrame({}).append([{'A': 16, 'B': 17, 'C': 18, 'D': 19}, {'A': 20, 'B': 21, 'C': 22, 'D': 23}],\n ignore_index=True)\n# df.loc[3] = [16, 17, 18, 19]\n\ndf2 = pd.DataFrame({}).append([{'A': 116, 'B': 117, 'C': 118, 'D': 191}, {'A': 210, 'B': 211, 'C': 122, 'D': 213}],\n ignore_index=True)\n\nfor k, v in enumerate(list(df2.index)):\n df1.loc[list(df1.index)[-1] + k] = list(df2.loc[k]) # df2.iloc[k]\n # print(v)\nprint(df1)\n\"\"\"\n A B C D\n0 16 17 18 19\n1 20 21 22 23\n3 16 17 18 19\n\"\"\"\n# df = df.append([1, 2, 3, 4], ignore_index=True)\n\"\"\"\n A B C D 0\n0 16.0 17.0 18.0 19.0 NaN\n1 20.0 21.0 22.0 23.0 NaN\n2 NaN NaN NaN NaN 1.0\n3 NaN NaN NaN NaN 2.0\n4 NaN NaN NaN NaN 3.0\n5 NaN NaN NaN NaN 4.0\n\"\"\"\n# s = pd.Series([16, 17, 18, 19])\n# df = pd.concat([df, s])\n", "# encoding=utf-8\n\nimport pandas as pd\nimport numpy as np\n\ndata = pd.read_csv(r'D:\\Destop\\123.csv', dtype={'LinkedAccountId': np.object})\n\nlink_user = '515743265704'\n# instance_name = 'dacproes2uatinstance' # 实例名字\n\ntag_name = 'user:' + 'appenv' # 标签名\ntag_value = 'dac-uat' # 标签名\n\n# user_unique = list(data['LinkedAccountId'].unique())\n# if user_unique[-1] == np.nan:\n# user_unique.remove(np.nan)\n\nuser_i = [True if i == link_user else False for i in list(data['LinkedAccountId'])]\ndata = data.loc[user_i]\n\n# instance_i = [True if i == instance_name else False for i in list(data['aws:cloudformation:logical-id'])]\n# data = data.loc[instance_i]\n\n\ntag_i = [True if i == tag_value else False for i in list(data[tag_name])]\ndata = data.loc[tag_i]\n\n# res = data[tag_name].notnull()\n# a = data.loc[res] # 这个标签有值的索引\n\n# 各服务名字 AmazonS3\n\n# ProductCode\nservice_list = list(data['ProductCode'].unique())\nfor service in service_list:\n service_i = [True if i == service else False for i in list(data['ProductCode'])]\n\n temp = dict()\n temp['CostBeforeTax'] = data.loc[service_i, 'CostBeforeTax'].sum()\n temp['Credits'] = data.loc[service_i, 'Credits'].sum()\n temp['TaxAmount'] = data.loc[service_i, 'TaxAmount'].sum()\n temp['UsageQuantity'] = data.loc[service_i, 'UsageQuantity'].sum()\n temp['TotalCost'] = data.loc[service_i, 'TotalCost'].sum()\n print(service, temp)\n" ]
[ [ "pandas.DataFrame" ], [ "pandas.read_csv" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
relacs/rlx2nix
[ "be66f02a78a225b01ee391dd706969c789ce28e8" ]
[ "rlx2nix/converter.py" ]
[ "# -*- coding: utf-8 -*-\n# Copyright © 2022, Neuroethology Lab Uni Tuebingen\n#\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted under the terms of the BSD License. See\n# LICENSE file in the root of the Project.\nimport re\nimport os\nimport glob\nimport odml\nimport logging\nimport subprocess\nimport numpy as np\nimport nixio as nix\n\nfrom .config import ConfigFile\nfrom .traces import EventTrace, RawTrace\nfrom .stimuli import StimuliDat\nfrom .util import parse_value, odml2nix, only_number\nfrom .stimdescription import parse_stimulus_description\n\nfrom IPython import embed\n\n\nclass Converter(object):\n\n def __init__(self, folder_name, output_name, force=False) -> None:\n if not os.path.exists(folder_name):\n logging.error(f\"{folder_name} does not exist!\")\n raise ValueError(\"File not found error!\")\n self._folder = folder_name\n self._output = output_name\n self._event_traces = None\n self._raw_traces = None\n self._raw_data_arrays = {}\n self._event_data_arrays = {}\n self._stimuli_dat = None\n self._force = force\n self._nixfile = None\n self._block = None\n self._repro_tags = {}\n self._stimulus_mtags = {}\n self.preflight()\n\n def preflight(self):\n logging.debug(f\"Pre-checking folder {self._folder}!\")\n self.check_output()\n self.check_folder()\n logging.debug(\"Pre-checking done.\")\n\n def check_output(self):\n logging.debug(f\"Checking output name: {self._output}!\")\n if os.path.exists(self._output):\n logging.warn(f\"Output file name {self._output} already exists!\")\n if self._force:\n logging.warn(f\"... force flag is set {self._force}, going to overwrite!\")\n else:\n logging.error(f\"Force flag is not set ({self._force}), abort!\")\n raise ValueError(\"Output file {self._output} already exists! If you want to overwrite it use the --force flag.\")\n logging.debug(f\"... ok!\")\n\n return True\n\n def unzip(self, tracename):\n if os.path.exists(tracename):\n logging.debug(f\"\\tunzip: {tracename}\")\n subprocess.check_call([\"gunzip\", tracename])\n\n def find_traces(self):\n event_traces = []\n raw_traces = []\n\n configuration = self.find_config_file()\n for et in self.find_event_traces():\n event_traces.append(EventTrace(et, configuration))\n\n for rt in self.find_raw_traces():\n raw_traces.append(RawTrace(rt, configuration))\n\n return raw_traces, event_traces\n\n def find_raw_traces(self):\n logging.debug(f\"Checking for raw traces!\")\n traces = sorted(glob.glob(os.path.join(self._folder, \"trace-*.raw*\")))\n for rt in traces:\n if rt.endswith(\".gz\") and rt.split(\".gz\")[0] not in traces:\n self.unzip(os.path.split(rt)[-1])\n\n traces = sorted(glob.glob(os.path.join(self._folder, \"trace-*.raw\")))\n logging.debug(f\"Found {len(traces)} raw traces. {[os.path.split(t)[-1] for t in traces]}\")\n\n return traces\n\n def find_event_traces(self):\n logging.debug(\"Discovering event traces!\")\n traces = sorted(glob.glob(os.path.join(self._folder, \"*-events.dat\")))\n logging.debug(f\"Found {len(traces)} event traces. {[os.path.split(t)[-1] for t in traces]}\")\n return traces\n\n def find_config_file(self):\n if not os.path.exists(os.path.join(self._folder, \"relacs.cfg\")):\n logging.error(\"Found no info file!\")\n raise ValueError(f\"No relacs.cfg file found in {self._folder}!\")\n configuration = ConfigFile(os.path.join(self._folder, \"relacs.cfg\"))\n return configuration\n\n def find_info(self):\n filename = os.path.join(self._folder, \"info.dat\")\n if not os.path.exists(filename):\n logging.error(\"Found no info file!\")\n raise ValueError(f\"No info file found in {self._folder}!\")\n return True\n\n def read_info_file(self):\n def looks_like_oldstyle(filename):\n with open(filename, 'r') as f:\n for l in f:\n if \"# Recording\" in l:\n oldtyle = not l.strip().endswith(\":\")\n break\n return oldtyle\n\n filename = os.path.join(self._folder, \"info.dat\")\n oldstyle = looks_like_oldstyle(filename)\n info = {}\n logging.info(\"Reading info file....\")\n try:\n with open(filename, 'r') as f:\n lines = f.readlines()\n except UnicodeDecodeError:\n logging.debug(\"Replacing experimenter...\")\n command = r\"sudo sed -i '/Experimenter/c\\# Experimenter: Anna Stoeckl' %s\" % filename\n subprocess.check_call(command, shell=True)\n with open(filename, 'r') as f:\n lines = f.readlines()\n for l in lines:\n if not l.startswith(\"#\"):\n continue\n l = l.strip(\"#\").strip()\n if len(l) == 0:\n continue\n if oldstyle:\n if not \":\" in l: # subsection\n sec = {}\n info[l[:-1] if l.endswith(\":\") else l] = sec\n else:\n parts = l.split(':')\n sec[parts[0].strip()] = parts[1].strip('\"').strip() if len(parts) > 1 else \"\"\n else:\n if l.endswith(\":\"): # subsection\n sec = {}\n info[l[:-1] if l.endswith(\":\") else l] = sec\n else:\n parts = l.split(': ')\n sec[parts[0].strip()] = parts[1].strip('\"').strip() if len(parts) > 1 else \"\"\n return info\n\n def read_channel_config(self):\n logging.info(\"Reading channel configuration ...\")\n ids = [f\"identifier{i}\" for i in range(1, len(self._raw_traces)+1)]\n units = [f\"unit{i}\" for i in range(1, len(self._raw_traces)+1)]\n sampling_intervals = [f\"sample interval{i}\" for i in range(1, len(self._raw_traces)+1)]\n sampling_rates = [f\"sampling rate{i}\" for i in range(1, len(self._raw_traces)+1)]\n\n channel_config = {}\n for i in range(1, len(self._raw_traces)+1):\n channel_config[i] = {}\n with open(os.path.join(self._folder, \"stimuli.dat\")) as f:\n for line in f:\n if \"#\" in line:\n line = line[1:]\n prop = line.strip().split(\":\")[0].strip()\n value = line.strip().split(\":\")[-1].strip()\n if prop in ids:\n index = int(prop[-1])\n channel_config[index][\"identifier\"] = value\n if prop in units:\n index = int(prop[-1])\n channel_config[index][\"unit\"] = value\n if prop in sampling_intervals:\n index = int(prop[-1])\n channel_config[index][\"sampling interval\"] = value\n if prop in sampling_rates:\n index = int(prop[-1])\n channel_config[index][\"sampling rates\"] = value\n\n if \"analog output traces\" in line: # end of channel configuration, we are done here\n break\n return channel_config\n\n def find_stimulus_info(self):\n logging.debug(\"Scanning stimuli.dat file!\")\n if not os.path.exists(os.path.join(self._folder, \"stimuli.dat\")):\n logging.error(\"Found no stimuli.dat file! Abort!\")\n raise ValueError(\"No stimuli.dat file found!\")\n\n def find_stimulus_descriptions(self):\n logging.debug(\"Scanning stimulus-descriptions.dat!\")\n filename = os.path.join(self._folder, \"stimulus-descriptions.dat\")\n if not os.path.exists(filename):\n logging.warning(\"Stimulus descriptions file {filename} does not exist!\")\n return False\n return True\n\n def check_folder(self):\n logging.debug(\"Checking folder structure: ...\")\n self._raw_traces, self._event_traces = self.find_traces()\n self.find_info()\n logging.debug(\"Found info file!\")\n self.find_stimulus_info()\n logging.debug(\"Found stimulus information!\")\n stim_descriptions_found = self.find_stimulus_descriptions()\n if stim_descriptions_found:\n logging.debug(\"Found stimulus descriptions!\")\n else:\n logging.debug(\"Did not find stimulus descriptions!\")\n return True\n\n def convert_dataset_info(self, metadata, parent_section=None):\n def split_list(value_str):\n results = None\n if len(value_str) == 0:\n return \" \"\n if \"|\" in value_str:\n results = list(map(str.strip, value_str.split(\"|\")))\n elif value_str[0] == \"[\" and \"]\" in value_str:\n results = list(map(str.strip, value_str[1:value_str.index(\"]\")].split(', ')))\n else: \n results = value_str\n return results\n\n if parent_section is not None:\n for k in metadata.keys():\n if isinstance(metadata[k], dict):\n sec = parent_section.create_section(k, k.lower())\n self.convert_dataset_info(metadata[k], sec)\n else: # is property\n value, unit = parse_value(metadata[k])\n if value is None:\n continue\n if isinstance(value, str):\n value = split_list(value)\n p = parent_section.create_property(k, value)\n if unit is not None:\n p.unit = unit\n\n def open_nix_file(self):\n info = self.read_info_file()\n logging.info(f\"Creating output file {self._output} ...\")\n self._nixfile = nix.File.open(self._output, nix.FileMode.Overwrite)\n dataset_name = os.path.split(self._output)[-1].strip(\".nix\")\n\n self._block = self._nixfile.create_block(dataset_name, \"relacs.recording\")\n sec = self._nixfile.create_section(dataset_name, \"relacs.recording\")\n self._block.metadata = sec\n sec.create_property(\"relacs-nix version\", 1.1)\n self.convert_dataset_info(info, sec)\n\n def convert_raw_traces(self, channel_config):\n logging.info(\"Converting raw traces, this may take a little while...\")\n\n for rt in self._raw_traces:\n logging.info(f\"... trace {rt._trace_no}: {rt.name}\")\n data = np.fromfile(os.path.join(self._folder, rt.filename), dtype=np.float32)\n da = self._block.create_data_array(rt.name, f\"relacs.data.sampled.{rt.name}\", dtype=nix.DataType.Float, data=data)\n da.unit = channel_config[rt._trace_no][\"unit\"]\n si = float(channel_config[rt._trace_no][\"sampling interval\"][:-2]) / 1000.\n da.append_sampled_dimension(si, unit=\"s\")\n self._raw_data_arrays[rt] = da\n\n def convert_event_traces(self):\n\n def read_event_data(filename):\n logging.info(f\"... reading event times from file {filename}...\")\n times = []\n with open(filename, 'r') as f:\n for l in f:\n if len(l.strip()) == 0 or \"#\" in l:\n continue\n times.append(float(l.strip().split()[0].strip()))\n\n return np.array(times)\n\n logging.info(\"Converting event traces...\")\n for et in self._event_traces:\n logging.info(f\"... trace {et.name}\")\n event_times = read_event_data(et._filename)\n da = self._block.create_data_array(et.name, f\"relacs.data.events.{et.name}\", data=event_times)\n da.unit = \"s\"\n da.append_range_dimension_using_self()\n da.definition = f\"Events detected in {et.inputtrace}\"\n self._event_data_arrays[et] = da\n\n def convert_stimuli(self):\n def stimulus_descriptions(repro_name, reprorun, sampleinterval):\n \n def skip_first_index(signals):\n skip = True\n for s in signals:\n skip = skip and s.data[0].strip() == \"-\"\n return skip\n\n def find_active_signal(signals, stimulus_no):\n for i, s in enumerate(signals):\n if s.data[stimulus_no].strip() != \"-\":\n return i\n\n def parse_parameter(parameter_str):\n props = []\n if parameter_str.strip().startswith(\"\\\"\"):\n parameter_str = parameter_str[1:-1]\n parts = parameter_str.split(\",\")\n for p in parts:\n name = p.split(\":\")[0].strip()\n value_str = p.split(\":\")[-1].strip()\n value, unit = parse_value(value_str)\n props.append(odml.Property(name=name, value=value, unit=unit))\n return props\n\n stimuli = []\n stimulus_columns = reprorun.table[\"stimulus\"]\n signals = stimulus_columns.columns_by_name(\"signal\")\n skip_first = skip_first_index(signals)\n index_col = reprorun.table.find_column(1)\n abstimes = stimulus_columns.columns_by_name(\"time\")[0]\n delays = stimulus_columns.columns_by_name(\"delay\")[0]\n durations = stimulus_columns.columns_by_name(\"duration\")\n amplitudes = stimulus_columns.columns_by_name(\"amplitude\")\n if len(amplitudes) == 0: # this is an attempt for very old pre 2011 files.\n amplitudes = stimulus_columns.columns_by_name(\"%6.3f\")\n \n parameters = stimulus_columns.columns_by_name(\"parameter\")\n for i in range(0 if not skip_first else 1, len(index_col)):\n start_time = index_col[i] * sampleinterval\n active = find_active_signal(signals, i)\n characteristics = odml.Section(f\"{repro_name}_{i}\")\n characteristics.create_property(\"signal\", signals[active].data[i])\n p = characteristics.create_property(\"start_time\", start_time)\n p.unit = \"s\"\n dur = float(durations[active].data[i]) / (1000 if durations[active].type_or_unit == \"ms\" else 1)\n p = characteristics.create_property(\"duration\", dur)\n p.unit = \"s\"\n p = characteristics.create_property(\"amplitude\", float(amplitudes[active].data[i]))\n p.unit = amplitudes[active].type_or_unit\n d = float(delays.data[i]) / (1000 if delays.type_or_unit == \"ms\" else 1)\n p = characteristics.create_property(\"delay\", d)\n p.unit = \"s\"\n at = float(abstimes.data[i]) / (1000 if abstimes.type_or_unit == \"ms\" else 1)\n p = characteristics.create_property(\"abs_time\", at)\n p.unit = \"s\"\n characteristics.create_property(\"repro_tag_id\", self._repro_tags[repro_name].id)\n if len(parameters) > 0:\n params = parse_parameter(parameters[active].data[i])\n for p in params:\n characteristics.append(p)\n stimuli.append(characteristics)\n return stimuli\n\n def stimuli(sampleinterval):\n stims = {}\n counter = {}\n stim_metadata = parse_stimulus_description(os.path.join(self._folder, \"stimulus-descriptions.dat\"))\n for rr in self._stimuli_dat.repro_runs:\n if rr is None or rr.name is None:\n print(rr)\n continue\n if rr.name in counter:\n counter[rr.name] += 1\n else:\n counter[rr.name] = 1\n if not rr.valid:\n continue\n if \"BaselineActivity\" in rr.name:\n continue # there are no stimulus presented during baseline\n repro_name = f\"{rr.name}_{counter[rr.name]}\"\n stims[repro_name] = stimulus_descriptions(repro_name, rr, sampleinterval)\n \n return stims, stim_metadata\n\n def store_stimuli(stims, stim_metadata):\n def store_features(signal, features):\n excluded_feats = [\"start_time\", \"duration\", \"signal\"]\n fixed_feats = [\"abs_time\", \"amplitude\", \"repro_tag_id\"]\n feats = {}\n for i, feat in enumerate(features):\n for p in feat:\n if p.name in excluded_feats:\n continue\n if p.name not in feats:\n if p.dtype == \"string\":\n feats[p.name] = np.empty(len(features), dtype=object)\n feats[p.name][i] = p.values[0]\n else:\n feats[p.name] = np.empty(len(features))\n else:\n feats[p.name][i] = p.values[0]\n for key in feats.keys():\n feat_name = f\"{signal}_{key}\"\n feat_type = f\"relacs.feature.{key if key in fixed_feats else 'mutable'}\"\n mtag = self._stimulus_mtags[signal]\n shape = (len(feats[key]), 1)\n data = np.reshape(feats[key], shape)\n dtype = nix.DataType.String if data.dtype == object else nix.DataType.Float\n feature_da = self._block.create_data_array(feat_name, feat_type, \n shape= shape, dtype=dtype,\n data=data)\n feature_da.append_set_dimension()\n mtag.create_feature(feature_da, nix.LinkType.Indexed)\n return None\n\n unique_signals = []\n signal_counts = {}\n signal_starts = {}\n signal_durations = {}\n signal_features = {}\n for repro_run in stims:\n for stim in stims[repro_run]:\n signal = stim.props[\"signal\"].values[0]\n if signal not in unique_signals:\n unique_signals.append(signal)\n signal_counts[signal] = 1\n signal_starts[signal] = [stim.props[\"start_time\"].values[0]]\n signal_durations[signal] = [stim.props[\"duration\"].values[0]]\n signal_features[signal] = [stim]\n else:\n signal_starts[signal].append(stim.props[\"start_time\"].values[0])\n signal_durations[signal].append(stim.props[\"duration\"].values[0])\n signal_counts[signal] += 1\n signal_features[signal].append(stim)\n\n excluded_refs = [\"restart\", \"recording\", \"stimulus\"]\n for signal in unique_signals:\n positions = self._block.create_data_array(f\"{signal}_onset_times\", \"relacs.stimulus.onset\",\n data=np.atleast_2d(signal_starts[signal]).T)\n positions.append_set_dimension()\n\n extents = self._block.create_data_array(f\"{signal}_durations\", \"relacs.stimulus.duration\",\n data=np.atleast_2d(signal_durations[signal]).T)\n extents.append_set_dimension()\n\n mtag = self._block.create_multi_tag(signal, \"relacs.stimulus.segment\", positions=positions, \n extents=extents)\n self._stimulus_mtags[signal] = mtag\n for et in self._event_data_arrays:\n if et not in excluded_refs:\n mtag.references.append(self._event_data_arrays[et])\n for rt in self._raw_data_arrays:\n mtag.references.append(self._raw_data_arrays[rt])\n\n if stim_metadata is not None and signal in stim_metadata.sections:\n metadata = stim_metadata[signal]\n mtag.metadata = self._nixfile.create_section(mtag.name, \"relacs.stimulus\")\n odml2nix(metadata, mtag.metadata)\n store_features(signal, signal_features[signal])\n\n return None\n\n sampleinterval = self._stimuli_dat.input_settings.props[\"sample interval1\"].values[0] /1000\n stims, metadata = stimuli(sampleinterval)\n store_stimuli(stims, metadata)\n\n return\n\n def convert_repro_runs(self):\n def repro_times(reprorun, sampleinterval):\n if reprorun.name is None:\n return None, None\n if not reprorun.valid:\n return None, None\n index_col = reprorun.table.find_column(1)\n if len(index_col) == 0:\n return None, None\n\n stimulus_grp = reprorun.table[\"stimulus\"]\n signals = stimulus_grp.columns_by_name(\"signal\")\n is_init = np.any(np.array([s[0] for s in signals], dtype=object) == \"init\")\n delay_cols = stimulus_grp.columns_by_name(\"delay\")\n delay = 0.0 if (len(delay_cols) == 0 or is_init) else delay_cols[0][0]\n start_time = index_col[0] * sampleinterval - delay / 1000.\n\n duration_cols = stimulus_grp.columns_by_name(\"duration\")\n duration = 0.0\n if \"BaselineActivity\" in reprorun.name:\n duration = 0.0\n end_time = start_time\n else:\n for d in duration_cols:\n dur = d[-1]\n if isinstance(dur, (int, float)):\n duration = dur / 1000\n break\n elif isinstance(dur, str) and only_number.search(dur) is not None:\n duration = float(dur) / 1000\n break\n end_time = index_col[-1] * sampleinterval + duration\n logging.debug(f\"Repro {reprorun.name} from {start_time} to {end_time}s\")\n return start_time, end_time\n\n def repro_runs():\n repro_names = []\n repro_starts = []\n repro_ends = []\n repro_durations = []\n repro_metadata = []\n sampleinterval = self._stimuli_dat.input_settings.props[\"sample interval1\"].values[0] /1000\n counter = {}\n for i, rr in enumerate(self._stimuli_dat.repro_runs):\n if rr.name in counter:\n counter[rr.name] += 1\n else:\n counter[rr.name] = 1\n \n if not rr.valid:\n continue\n start, end = repro_times(rr, sampleinterval)\n if start is None:\n logging.error(f\"RePro run: {rr.name} has no start/stop entries! It is ignored!\")\n continue\n \n repro_names.append(f\"{rr.name}_{counter[rr.name]}\")\n\n repro_starts.append(start)\n repro_durations.append(end - start)\n repro_ends.append(end)\n repro_metadata.append(rr.metadata)\n\n for i, (start, end , duration) in enumerate(zip(repro_starts, repro_ends, repro_durations)):\n logging.debug(f\"Duration {duration} for repro {repro_names[i]} and {i} < {len(repro_starts) - 1}\")\n if duration < sampleinterval and i < len(repro_starts) -1:\n repro_durations[i] = repro_starts[i+1] - start\n logging.debug(f\"\\t new duration: {repro_durations[i]}\")\n repro_ends[i] = repro_starts[i+1]\n\n return repro_names, repro_metadata, repro_starts, repro_durations\n\n def store_repro_runs(repro_names, repro_metadata, start_times, durations):\n excluded_refs = [\"restart\", \"recording\", \"stimulus\"]\n for name, metadata, start, duration in zip(repro_names, repro_metadata, start_times, durations):\n logging.debug(f\"... storing {name} which ran from {start} to {start + duration}.\")\n tag = self._block.create_tag(name, \"relacs.repro_run\", position=[start])\n tag.extent = [duration]\n for et in self._event_data_arrays:\n if et not in excluded_refs:\n tag.references.append(self._event_data_arrays[et])\n for rt in self._raw_data_arrays:\n tag.references.append(self._raw_data_arrays[rt])\n tag.metadata = self._nixfile.create_section(name, \"relacs.repro\")\n odml2nix(metadata, tag.metadata)\n self._repro_tags[name] = tag\n\n names, metadata, starts, durations = repro_runs()\n logging.info(\"Converting RePro runs...\")\n store_repro_runs(names, metadata, starts, durations)\n\n def convert(self):\n logging.info(f\"Converting dataset {self._folder} to nix file {self._output}!\")\n\n channel_config = self.read_channel_config()\n self.open_nix_file()\n self.convert_raw_traces(channel_config)\n self.convert_event_traces()\n\n self._stimuli_dat = StimuliDat(os.path.join(self._folder, \"stimuli.dat\"))\n self.convert_repro_runs()\n self.convert_stimuli()\n self._nixfile.close()\n" ]
[ [ "numpy.reshape", "numpy.atleast_2d", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
LinjianLi/Seq2Seq-PyTorch
[ "671bd10ac1a2620fb4d5ceaacdff9c0e9f4738a2" ]
[ "seq2seq/inputter/embedder.py" ]
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n################################################################################\n#\n# Copyright (c) 2019 Baidu.com, Inc. All Rights Reserved\n#\n################################################################################\n\"\"\"\nFile: source/encoders/embedder.py\n\"\"\"\n\nimport logging\nimport torch\nimport torch.nn as nn\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass Embedder(nn.Embedding):\n \"\"\"\n Embedder\n \"\"\"\n def load_embeddings(self, embeds, scale=0.05):\n \"\"\"\n load_embeddings\n \"\"\"\n assert len(embeds) == self.num_embeddings\n\n embeds = torch.tensor(embeds)\n num_known = 0\n for i in range(len(embeds)):\n # If no pretrained embedding for this token, randomly generate one.\n if len(embeds[i].nonzero()) == 0:\n nn.init.uniform_(embeds[i], -scale, scale)\n else:\n num_known += 1\n self.weight.data.copy_(embeds)\n logger.info(\"{} words have pretrained embeddings\"\n \" (coverage: {:.3f})\".format(\n num_known, num_known / self.num_embeddings))\n" ]
[ [ "torch.nn.init.uniform_", "torch.tensor" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
hoelzl/ML-Course
[ "efa7ccb7c6583753675bbcda569d3184d1ca98d2", "efa7ccb7c6583753675bbcda569d3184d1ca98d2" ]
[ "notebooks/nb074_ensembles.py", "notebooks/nb134_parameter_tuning.py" ]
[ "# ---\n# jupyter:\n# jupytext:\n# text_representation:\n# extension: .py\n# format_name: percent\n# format_version: '1.3'\n# jupytext_version: 1.13.7\n# kernelspec:\n# display_name: Python 3 (ipykernel)\n# language: python\n# name: python3\n# ---\n\n# %% [markdown] slideshow={\"slide_type\": \"slide\"}\n# # Ensembles\n\n# %% slideshow={\"slide_type\": \"subslide\"}\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.metrics import mean_absolute_error, mean_squared_error\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.tree import DecisionTreeRegressor\n\nsns.set_theme()\n\n# %% slideshow={\"slide_type\": \"subslide\"}\nrng = np.random.default_rng(42)\n\nx = rng.uniform(size=(150, 1), low=0.0, high=10.0)\nx_train, x_test = x[:100], x[100:]\n\nx_plot = np.linspace(0, 10, 500).reshape(-1, 1)\n\n\n# %% slideshow={\"slide_type\": \"subslide\"}\ndef lin(x):\n return 0.85 * x - 1.5\n\n\n# %% slideshow={\"slide_type\": \"-\"}\ndef fun(x):\n return 2 * np.sin(x) + 0.1 * x ** 2 - 2\n\n\n# %% slideshow={\"slide_type\": \"-\"}\ndef randomize(fun, x, scale=0.5):\n return fun(x) + rng.normal(size=x.shape, scale=scale)\n\n\n# %% slideshow={\"slide_type\": \"subslide\"}\ndef evaluate_non_random_regressor(reg_type, f_y, *args, **kwargs):\n reg = reg_type(*args, **kwargs)\n\n y_train = f_y(x_train).reshape(-1)\n y_test = f_y(x_test).reshape(-1)\n\n reg.fit(x_train, y_train)\n y_pred = reg.predict(x_test)\n\n x_plot = np.linspace(0, 10, 500).reshape(-1, 1)\n fig, ax = plt.subplots(figsize=(20, 8))\n sns.lineplot(x=x_plot[:, 0], y=reg.predict(x_plot), ax=ax)\n sns.lineplot(x=x_plot[:, 0], y=f_y(x_plot[:, 0]), ax=ax)\n sns.scatterplot(x=x_train[:, 0], y=y_train, ax=ax)\n plt.show()\n\n mae = mean_absolute_error(y_test, y_pred)\n mse = mean_squared_error(y_test, y_pred)\n rmse = np.sqrt(mean_squared_error(y_test, y_pred))\n print(\n \"\\nNo randomness: \" f\"MAE = {mae:.2f}, MSE = {mse:.2f}, RMSE = {rmse:.2f}\"\n )\n\n return reg\n\n\n# %% slideshow={\"slide_type\": \"subslide\"}\ndef plot_graphs(f_y, reg, reg_rand, reg_chaos, y_train, y_rand_train, y_chaos_train):\n x_plot = np.linspace(0, 10, 500).reshape(-1, 1)\n fig, ax = plt.subplots(figsize=(20, 12))\n sns.lineplot(x=x_plot[:, 0], y=reg.predict(x_plot), ax=ax)\n sns.scatterplot(x=x_train[:, 0], y=y_train, ax=ax)\n\n sns.lineplot(x=x_plot[:, 0], y=reg_rand.predict(x_plot), ax=ax)\n sns.scatterplot(x=x_train[:, 0], y=y_rand_train, ax=ax)\n\n sns.lineplot(x=x_plot[:, 0], y=reg_chaos.predict(x_plot), ax=ax)\n sns.scatterplot(x=x_train[:, 0], y=y_chaos_train, ax=ax)\n\n sns.lineplot(x=x_plot[:, 0], y=f_y(x_plot[:, 0]), ax=ax)\n plt.show() \n\n\n# %% slideshow={\"slide_type\": \"subslide\"}\ndef print_evaluation(y_test, y_pred, y_rand_test, y_rand_pred, y_chaos_test, y_chaos_pred):\n mae = mean_absolute_error(y_test, y_pred)\n mae_rand = mean_absolute_error(y_rand_test, y_rand_pred)\n mae_chaos = mean_absolute_error(y_chaos_test, y_chaos_pred)\n\n mse = mean_squared_error(y_test, y_pred)\n mse_rand = mean_squared_error(y_rand_test, y_rand_pred)\n mse_chaos = mean_squared_error(y_chaos_test, y_chaos_pred)\n\n rmse = np.sqrt(mean_squared_error(y_test, y_pred))\n rmse_rand = np.sqrt(mean_squared_error(y_rand_test, y_rand_pred))\n rmse_chaos = np.sqrt(mean_squared_error(y_chaos_test, y_chaos_pred))\n\n print(\n \"\\nNo randomness: \" f\"MAE = {mae:.2f}, MSE = {mse:.2f}, RMSE = {rmse:.2f}\"\n )\n print(\n \"Some randomness: \"\n f\"MAE = {mae_rand:.2f}, MSE = {mse_rand:.2f}, RMSE = {rmse_rand:.2f}\"\n )\n print(\n \"Lots of randomness: \"\n f\"MAE = {mae_chaos:.2f}, MSE = {mse_chaos:.2f}, RMSE = {rmse_chaos:.2f}\"\n )\n\n\n# %% slideshow={\"slide_type\": \"subslide\"}\ndef evaluate_regressor(reg_type, f_y, *args, **kwargs):\n reg = reg_type(*args, **kwargs)\n reg_rand = reg_type(*args, **kwargs)\n reg_chaos = reg_type(*args, **kwargs)\n \n y_train = f_y(x_train).reshape(-1)\n y_test = f_y(x_test).reshape(-1)\n y_pred = reg.fit(x_train, y_train).predict(x_test)\n \n y_rand_train = randomize(f_y, x_train).reshape(-1)\n y_rand_test = randomize(f_y, x_test).reshape(-1)\n y_rand_pred = reg_rand.fit(x_train, y_rand_train).predict(x_test)\n\n y_chaos_train = randomize(f_y, x_train, 1.5).reshape(-1)\n y_chaos_test = randomize(f_y, x_test, 1.5).reshape(-1)\n y_chaos_pred = reg_chaos.fit(x_train, y_chaos_train).predict(x_test)\n\n plot_graphs(f_y, reg, reg_rand, reg_chaos, y_train, y_rand_train, y_chaos_train)\n print_evaluation(y_test, y_pred, y_rand_test, y_rand_pred, y_chaos_test, y_chaos_pred)\n\n\n# %% [markdown] slideshow={\"slide_type\": \"slide\"}\n# # Ensembles, Random Forests, Gradient Boosted Trees\n\n# %% [markdown] slideshow={\"slide_type\": \"slide\"}\n# ## Ensemble Methods\n#\n# Idea: combine several estimators to improve their overal performance.\n#\n# - Averaging methods: \n# - Independent estimators, average predictions\n# - Reduces variance (overfitting)\n# - Bagging, random forests\n# - Boosting methods:\n# - Train estimators sequentially\n# - Each estimator is trained to reduce the bias of its (combined) predecessors\n\n# %% [markdown] slideshow={\"slide_type\": \"subslide\"}\n# ### Bagging\n#\n# - Averaging method: build several estimators of the same type, average their results\n# - Needs some way to introduce differences between estimators\n# - Otherwise variance is not reduced\n# - Train on random subsets of the training data\n# - Reduce overfitting\n# - Work best with strong estimators (e.g., decision trees with (moderately) large depth)\n\n# %% [markdown]\n# ### Random Forests\n#\n# - Bagging classifier/regressor using decision trees\n# - For each tree in the forest:\n# - Subset of training data\n# - Subset of features\n# - Often significant reduction in variance (overfitting)\n# - Sometimes increase in bias\n\n# %% slideshow={\"slide_type\": \"subslide\"}\nfrom sklearn.ensemble import RandomForestRegressor\n\n# %% slideshow={\"slide_type\": \"subslide\"}\nevaluate_non_random_regressor(RandomForestRegressor, lin, random_state=42);\n\n# %% slideshow={\"slide_type\": \"subslide\"}\nevaluate_non_random_regressor(RandomForestRegressor, fun, random_state=42);\n\n# %% slideshow={\"slide_type\": \"subslide\"}\nevaluate_non_random_regressor(\n RandomForestRegressor, fun, n_estimators=25, criterion=\"absolute_error\", random_state=42\n);\n\n# %% slideshow={\"slide_type\": \"subslide\"}\nevaluate_regressor(RandomForestRegressor, lin, random_state=42);\n\n# %% slideshow={\"slide_type\": \"subslide\"}\nevaluate_regressor(\n RandomForestRegressor, lin, n_estimators=500, max_depth=3, random_state=42\n)\n\n# %% slideshow={\"slide_type\": \"subslide\"}\nevaluate_regressor(\n RandomForestRegressor, lin, n_estimators=500, min_samples_leaf=6, random_state=42\n)\n\n# %% slideshow={\"slide_type\": \"subslide\"}\nevaluate_regressor(RandomForestRegressor, fun, random_state=42)\n\n# %% slideshow={\"slide_type\": \"subslide\"}\nevaluate_regressor(\n RandomForestRegressor,\n fun,\n n_estimators=1000,\n min_samples_leaf=6,\n random_state=43,\n n_jobs=-1,\n)\n\n# %% [markdown] slideshow={\"slide_type\": \"slide\"}\n# ## Gradient Boosted Trees\n#\n# - Boosting method for both regression and classification\n# - Requires differentiable loss function\n\n# %% slideshow={\"slide_type\": \"subslide\"}\nfrom sklearn.ensemble import GradientBoostingRegressor\n\n# %% slideshow={\"slide_type\": \"subslide\"}\nevaluate_non_random_regressor(GradientBoostingRegressor, lin);\n\n# %% slideshow={\"slide_type\": \"subslide\"}\nevaluate_non_random_regressor(GradientBoostingRegressor, fun);\n\n# %% slideshow={\"slide_type\": \"subslide\"}\nevaluate_regressor(GradientBoostingRegressor, lin);\n\n# %% slideshow={\"slide_type\": \"subslide\"}\nevaluate_regressor(GradientBoostingRegressor, lin, n_estimators=200, learning_rate=0.05, loss=\"absolute_error\");\n\n# %% slideshow={\"slide_type\": \"subslide\"}\nevaluate_regressor(GradientBoostingRegressor, lin, n_estimators=500, learning_rate=0.01,\n loss=\"absolute_error\", subsample=0.1, random_state=46);\n\n# %% slideshow={\"slide_type\": \"subslide\"}\nevaluate_regressor(GradientBoostingRegressor, fun, n_estimators=500, learning_rate=0.01,\n loss=\"absolute_error\", subsample=0.1, random_state=44);\n\n# %% [markdown] slideshow={\"slide_type\": \"slide\"}\n# ### Multiple Features\n\n# %% slideshow={\"slide_type\": \"subslide\"}\nfrom sklearn.datasets import make_regression\nfrom sklearn.model_selection import train_test_split\nnp.set_printoptions(precision=1)\n\n# %%\nx, y, coef = make_regression(n_samples=250, n_features=4, n_informative=1, coef=True, random_state=42)\nx.shape, y.shape, coef\n\n# %% slideshow={\"slide_type\": \"subslide\"}\nfig, axs = plt.subplots(ncols=2, nrows=2, figsize=(20, 12))\nfor i, ax in enumerate(axs.reshape(-1)):\n sns.scatterplot(x=x[:, i], y=y, ax=ax)\n\n# %% slideshow={\"slide_type\": \"subslide\"}\nx, y, coef = make_regression(n_samples=250, n_features=20, n_informative=10, coef=True, random_state=42)\nx.shape, y.shape, coef\n\n# %%\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.4)\nx_train.shape, x_test.shape, y_train.shape, y_test.shape\n\n# %% slideshow={\"slide_type\": \"subslide\"}\nfig, axs = plt.subplots(ncols=2, nrows=2, figsize=(20, 12))\nfor i in range(2):\n sns.scatterplot(x=x[:, i], y=y, ax=axs[0, i]);\nfor i in range(2):\n sns.scatterplot(x=x[:, i + 6], y=y, ax=axs[1, i]);\n\n# %% slideshow={\"slide_type\": \"subslide\"}\nlr_clf = LinearRegression()\nlr_clf.fit(x_train, y_train)\ny_lr_pred = lr_clf.predict(x_test)\n\nmean_absolute_error(y_test, y_lr_pred), mean_squared_error(y_test, y_lr_pred)\n\n# %%\nlr_clf.coef_.astype(np.int32), coef.astype(np.int32)\n\n# %% slideshow={\"slide_type\": \"subslide\"}\ndt_clf = DecisionTreeRegressor()\ndt_clf.fit(x_train, y_train)\ny_dt_pred = dt_clf.predict(x_test)\n\nmean_absolute_error(y_test, y_dt_pred), mean_squared_error(y_test, y_dt_pred)\n\n# %% slideshow={\"slide_type\": \"subslide\"}\nrf_clf = RandomForestRegressor()\nrf_clf.fit(x_train, y_train)\ny_rf_pred = rf_clf.predict(x_test)\n\nmean_absolute_error(y_test, y_rf_pred), mean_squared_error(y_test, y_rf_pred)\n\n# %% slideshow={\"slide_type\": \"subslide\"}\ngb_clf = GradientBoostingRegressor()\ngb_clf.fit(x_train, y_train)\ny_gb_pred = gb_clf.predict(x_test)\n\nmean_absolute_error(y_test, y_gb_pred), mean_squared_error(y_test, y_gb_pred)\n\n# %% slideshow={\"slide_type\": \"subslide\"}\nx, y, coef = make_regression(n_samples=250, n_features=20, n_informative=10, noise=100.0, coef=True, random_state=42)\nx.shape, y.shape, coef\n\n# %%\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.4)\nx_train.shape, x_test.shape, y_train.shape, y_test.shape\n\n# %% slideshow={\"slide_type\": \"subslide\"}\nlr_clf = LinearRegression()\nlr_clf.fit(x_train, y_train)\ny_lr_pred = lr_clf.predict(x_test)\n\nmean_absolute_error(y_test, y_lr_pred), mean_squared_error(y_test, y_lr_pred)\n\n# %% slideshow={\"slide_type\": \"subslide\"}\ndt_clf = DecisionTreeRegressor()\ndt_clf.fit(x_train, y_train)\ny_dt_pred = dt_clf.predict(x_test)\n\nmean_absolute_error(y_test, y_dt_pred), mean_squared_error(y_test, y_dt_pred)\n\n# %% slideshow={\"slide_type\": \"subslide\"}\nrf_clf = RandomForestRegressor()\nrf_clf.fit(x_train, y_train)\ny_rf_pred = rf_clf.predict(x_test)\n\nmean_absolute_error(y_test, y_rf_pred), mean_squared_error(y_test, y_rf_pred)\n\n# %% slideshow={\"slide_type\": \"subslide\"}\ngb_clf = GradientBoostingRegressor()\ngb_clf.fit(x_train, y_train)\ny_gb_pred = gb_clf.predict(x_test)\n\nmean_absolute_error(y_test, y_gb_pred), mean_squared_error(y_test, y_gb_pred)\n\n# %% slideshow={\"slide_type\": \"subslide\"}\nx, y, coef = make_regression(n_samples=250, n_features=20, n_informative=10, noise=100.0,\n coef=True, random_state=42)\ny += (20 * x[:, 1]) ** 2\nx.shape, y.shape, coef\n\n# %%\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.4)\nx_train.shape, x_test.shape, y_train.shape, y_test.shape\n\n# %% slideshow={\"slide_type\": \"subslide\"}\nfig, axs = plt.subplots(ncols=2, nrows=2, figsize=(20, 12))\nfor i in range(2):\n sns.scatterplot(x=x[:, i], y=y, ax=axs[0, i]);\nfor i in range(2):\n sns.scatterplot(x=x[:, i + 6], y=y, ax=axs[1, i]);\n\n# %% slideshow={\"slide_type\": \"subslide\"}\nlr_clf = LinearRegression()\nlr_clf.fit(x_train, y_train)\ny_lr_pred = lr_clf.predict(x_test)\n\nmean_absolute_error(y_test, y_lr_pred), mean_squared_error(y_test, y_lr_pred)\n\n# %% slideshow={\"slide_type\": \"subslide\"}\ndt_clf = DecisionTreeRegressor()\ndt_clf.fit(x_train, y_train)\ny_dt_pred = dt_clf.predict(x_test)\n\nmean_absolute_error(y_test, y_dt_pred), mean_squared_error(y_test, y_dt_pred)\n\n# %% slideshow={\"slide_type\": \"subslide\"}\nrf_clf = RandomForestRegressor()\nrf_clf.fit(x_train, y_train)\ny_rf_pred = rf_clf.predict(x_test)\n\nmean_absolute_error(y_test, y_rf_pred), mean_squared_error(y_test, y_rf_pred)\n\n# %% slideshow={\"slide_type\": \"subslide\"}\ngb_clf = GradientBoostingRegressor()\ngb_clf.fit(x_train, y_train)\ny_gb_pred = gb_clf.predict(x_test)\n\nmean_absolute_error(y_test, y_gb_pred), mean_squared_error(y_test, y_gb_pred)\n\n# %% [markdown] slideshow={\"slide_type\": \"slide\"}\n#\n# ## Feature Engineering\n\n# %% slideshow={\"slide_type\": \"subslide\"}\nx = rng.uniform(size=(150, 1), low=0.0, high=10.0)\nx_train, x_test = x[:100], x[100:]\nx_plot = np.linspace(0, 10, 500)\nx_train[:3]\n\n# %% slideshow={\"slide_type\": \"subslide\"}\ny_lin_train = lin(x_train).reshape(-1)\ny_lin_test = lin(x_test).reshape(-1)\ny_fun_train = fun(x_train.reshape(-1))\ny_fun_test = fun(x_test).reshape(-1)\n\n# %% slideshow={\"slide_type\": \"subslide\"}\nx_squares = x * x\nx_squares[:3]\n\n# %% slideshow={\"slide_type\": \"subslide\"}\nx_sins = np.sin(x)\nx_sins[:3]\n\n# %% slideshow={\"slide_type\": \"subslide\"}\nx_train_aug = np.concatenate([x_train, x_train * x_train, np.sin(x_train)], axis=1)\nx_train_aug[:3]\n\n# %% slideshow={\"slide_type\": \"subslide\"}\nx_test_aug = np.concatenate([x_test, x_test * x_test, np.sin(x_test)], axis=1)\n\n# %% slideshow={\"slide_type\": \"subslide\"}\n# from sklearn.linear_model import Ridge\n# lr_aug_lin = Ridge()\nlr_aug_lin = LinearRegression()\nlr_aug_lin.fit(x_train_aug, y_lin_train);\n\n# %% slideshow={\"slide_type\": \"subslide\"}\nlr_aug_lin.coef_, lr_aug_lin.intercept_\n\n\n# %% slideshow={\"slide_type\": \"subslide\"}\ny_aug_lin_pred = lr_aug_lin.predict(x_test_aug)\n\n# %% slideshow={\"slide_type\": \"subslide\"}\nmean_absolute_error(y_lin_test, y_aug_lin_pred), mean_squared_error(\n y_lin_test, y_aug_lin_pred\n)\n\n# %% slideshow={\"slide_type\": \"subslide\"}\nx_test.shape, x_plot.shape\n\n\n# %% slideshow={\"slide_type\": \"subslide\"}\ndef train_and_plot_aug(f_y, scale=0.5):\n y_plot = f_y(x_plot)\n \n f_r = lambda x: randomize(f_y, x, scale=scale)\n y_train = f_r(x_train_aug[:, 0])\n y_test = f_r(x_test)\n \n lr_aug = LinearRegression() # Try with Ridge() as well...\n lr_aug.fit(x_train_aug, y_train)\n y_pred_test = lr_aug.predict(\n np.concatenate([x_test, x_test * x_test, np.sin(x_test)], axis=1)\n )\n x_plot2 = x_plot.reshape(-1, 1)\n y_pred_plot = lr_aug.predict(\n np.concatenate([x_plot2, x_plot2 * x_plot2, np.sin(x_plot2)], axis=1)\n )\n \n fig, ax = plt.subplots(figsize=(12, 6))\n sns.scatterplot(x=x_plot2[:, 0], y=y_plot, color=\"orange\")\n sns.scatterplot(x=x_plot2[:, 0], y=y_pred_plot, color=\"red\")\n sns.scatterplot(x=x_train_aug[:, 0], y=y_train, color=\"green\")\n plt.show()\n\n mae_in = mean_absolute_error(y_test, y_pred_test)\n mse_in = mean_absolute_error(y_test, y_pred_test)\n rmse_in = np.sqrt(mse_in)\n\n y_nr = f_y(x_test)\n mae_true = mean_absolute_error(y_nr, y_pred_test)\n mse_true = mean_absolute_error(y_nr, y_pred_test)\n rmse_true = np.sqrt(mse_true)\n\n print(f\"Vs. input: MAE: {mae_in:.2f}, MSE: {mse_in:.2f}, RMSE: {rmse_in:.2f}\")\n print(f\"True: MAE: {mae_true:.2f}, MSE: {mse_true:.2f}, RMSE: {rmse_true:.2f}\")\n print(f\"Parameters: {lr_aug.coef_}, {lr_aug.intercept_}\")\n\n\n# %% slideshow={\"slide_type\": \"subslide\"}\ntrain_and_plot_aug(lin)\n\n# %% slideshow={\"slide_type\": \"subslide\"}\ntrain_and_plot_aug(fun, scale=0.0)\n\n# %% slideshow={\"slide_type\": \"subslide\"}\ntrain_and_plot_aug(fun, scale=0.5)\n\n# %% slideshow={\"slide_type\": \"subslide\"}\ntrain_and_plot_aug(fun, scale=1.5)\n\n# %% slideshow={\"slide_type\": \"subslide\"}\ntrain_and_plot_aug(fun, scale=3)\n\n\n# %%\ndef fun2(x): return 2.8 * np.sin(x) + 0.3 * x + 0.08 * x ** 2 - 2.5\n\ntrain_and_plot_aug(fun2, scale=1.5)\n\n# %%\ntrain_and_plot_aug(lambda x: np.select([x<=6, x>6], [-0.5, 3.5]))\n\n# %%\n", "# ---\n# jupyter:\n# jupytext:\n# text_representation:\n# extension: .py\n# format_name: percent\n# format_version: '1.3'\n# jupytext_version: 1.13.7\n# kernelspec:\n# display_name: Python 3 (ipykernel)\n# language: python\n# name: python3\n# ---\n\n# %% [markdown] slideshow={\"slide_type\": \"slide\"}\n# # MNIST with CNN\n\n# %%\nimport joblib\nimport numpy as np\nfrom pytorch_model_summary import summary\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision\nimport torchvision.transforms as transforms\nfrom mlcourse.config import Config\nfrom sklearn.metrics import classification_report\nfrom skorch import NeuralNetClassifier\nfrom skorch.helper import predefined_split\nfrom torchvision.transforms.functional import InterpolationMode\nfrom sklearn.model_selection import RandomizedSearchCV\n\n# %%\nconfig = Config()\n\n# %%\ninput_size = 28 * 28\nnum_classes = 10\nnum_epochs = 5\nbatch_size = 100\nlearning_rate = 0.005\ndevice = \"cuda:0\" if torch.cuda.is_available() else \"cpu\"\n\n# %% slideshow={\"slide_type\": \"subslide\"}\nmnist_transforms = transforms.Compose(\n [transforms.Resize((28, 28)), transforms.ToTensor()]\n)\n\n# %%\naugmented_transforms = transforms.Compose(\n [\n transforms.RandomApply(\n [\n transforms.Resize((56, 56)),\n transforms.RandomResizedCrop(\n 28, (0.8, 1.0), interpolation=InterpolationMode.BICUBIC\n ),\n transforms.RandomApply(\n [\n transforms.RandomAffine(\n degrees=15.0,\n translate=(0.08, 0.8),\n interpolation=InterpolationMode.BICUBIC,\n )\n ],\n 0.5,\n ),\n ]\n ),\n transforms.Resize((28, 28)),\n transforms.ToTensor(),\n ]\n)\n\n# %%\ntrain_dataset = torchvision.datasets.MNIST(\n root=\"./data\", train=True, transform=augmented_transforms, download=True\n)\ntest_dataset = torchvision.datasets.MNIST(\n root=\"./data\", train=False, transform=mnist_transforms, download=True\n)\n\n# %%\nif \"x_train\" not in globals() or \"y_train\" not in globals():\n x_train = np.stack([x.numpy() for x, _ in train_dataset])\n y_train = np.array([y for _, y in train_dataset], dtype=np.int64)\n\n# %%\ntype(x_train), type(y_train)\n\n# %%\nx_train.shape, y_train.shape\n\n# %%\nx_train.dtype, y_train.dtype\n\n# %%\ny_test = np.array([y for _, y in test_dataset])\n\n\n# %%\nclass ConvNet(nn.Module):\n def __init__(self, kernels_1=10, kernels_2=20, hidden=60):\n super().__init__()\n self.kernels_2 = kernels_2\n self.conv1 = nn.Conv2d(1, kernels_1, kernel_size=5, stride=(2, 2))\n self.conv2 = nn.Conv2d(kernels_1, kernels_2, kernel_size=5, stride=(2, 2))\n self.fc1 = nn.Linear(16 * kernels_2, hidden)\n self.fc2 = nn.Linear(hidden, 10)\n\n def forward(self, x):\n x = F.relu(self.conv1(x))\n x = F.relu(self.conv2(x))\n x = x.view(-1, 16 * self.kernels_2)\n x = F.relu(self.fc1(x))\n x = F.softmax(self.fc2(x), dim=1)\n return x\n\n\n# %%\nnet = ConvNet()\nprint(summary(net, torch.zeros((1, 1, 28, 28)), show_input=True))\nprint(summary(net, torch.zeros((1, 1, 28, 28)), show_input=False))\n\n\n# %%\nnet2 = ConvNet(kernels_1=25, kernels_2=40, hidden=128)\nprint(summary(net2, torch.zeros((1, 1, 28, 28)), show_input=True))\nprint(summary(net2, torch.zeros((1, 1, 28, 28)), show_input=False))\n\n# %%\ncnn_classifier = NeuralNetClassifier(\n ConvNet,\n # We added a softmax, so use NLLLoss instead of Cross Entropy\n # criterion=nn.CrossEntropyLoss,\n batch_size=100,\n max_epochs=10,\n optimizer=torch.optim.Adam,\n lr=1e-3,\n iterator_train__shuffle=True,\n train_split=predefined_split(test_dataset),\n device=device,\n verbose=False,\n)\n\n# %%\ncnn_classifier = NeuralNetClassifier(\n ConvNet,\n batch_size=100,\n max_epochs=10,\n lr=0.1,\n iterator_train__shuffle=True,\n device=device,\n verbose=False,\n)\n\n# %%\ncnn_classifier.fit(x_train, y_train)\n\n# %% [markdown]\n#\n# ## Parameter Search with Cross-validation\n#\n# `RandomizedSearchCV` and `GridSearchCV` are scikit-learn *estimators* that\n# perform a search for hyperparameters that lead to the best evaluation metrics.\n#\n# They use n-fold *cross-validation* to estimate the performance of each\n# setting.\n\n# %%\nsearch = RandomizedSearchCV(\n cnn_classifier,\n n_iter=3, # In reality this should be much higher...\n cv=2, # Use only two cross validation sets to save training time\n verbose=3,\n n_jobs=8,\n param_distributions=[\n {\n \"module__kernels_1\": [10, 20],\n \"module__kernels_2\": [30, 60],\n \"module__hidden\": [120, 180],\n },\n {\n \"module__kernels_1\": [30, 60],\n \"module__kernels_2\": [80, 120],\n \"module__hidden\": [360],\n },\n ],\n)\n\n# %%\nsearch.fit(x_train, y_train)\n\n# %%\nsearch.best_estimator_, search.best_params_\n\n# %%\ny_pred_search = search.predict(test_dataset)\n\n# %%\nprint(classification_report(y_test, y_pred_search))\n\n# %%\nmodel_file = config.model_dir_path / \"mnist_conv_randomized_search.pkl\"\n\n# %%\njoblib.dump(search, model_file)\n\n# %%\nsearch_loaded = joblib.load(model_file)\n\n# %%\ny_pred_loaded = search_loaded.predict(test_dataset)\n\n# %%\nprint(classification_report(y_test, y_pred_loaded))\n\n# %%\n" ]
[ [ "sklearn.ensemble.RandomForestRegressor", "sklearn.tree.DecisionTreeRegressor", "numpy.sqrt", "numpy.linspace", "numpy.set_printoptions", "sklearn.metrics.mean_absolute_error", "sklearn.model_selection.train_test_split", "matplotlib.pyplot.subplots", "sklearn.ensemble.GradientBoostingRegressor", "numpy.sin", "sklearn.datasets.make_regression", "sklearn.metrics.mean_squared_error", "sklearn.linear_model.LinearRegression", "numpy.select", "matplotlib.pyplot.show", "numpy.random.default_rng" ], [ "sklearn.model_selection.RandomizedSearchCV", "torch.zeros", "torch.nn.Conv2d", "torch.nn.Linear", "torch.cuda.is_available", "numpy.array", "sklearn.metrics.classification_report" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
MayankR/cmr
[ "6c898a5294954899334d430ec71e0a0692a0d99e", "6c898a5294954899334d430ec71e0a0692a0d99e" ]
[ "nnutils/loss_utils.py", "nnutils/mesh_net.py" ]
[ "\"\"\"\nLoss Utils.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport torch\nfrom . import geom_utils\nimport numpy as np\n\ndef mask_dt_loss(proj_verts, dist_transf):\n \"\"\"\n proj_verts: B x N x 2\n (In normalized coordinate [-1, 1])\n dist_transf: B x 1 x N x N\n\n Computes the distance transform at the points where vertices land.\n \"\"\"\n # Reshape into B x 1 x N x 2\n sample_grid = proj_verts.unsqueeze(1)\n # B x 1 x 1 x N\n dist_transf = torch.nn.functional.grid_sample(dist_transf, sample_grid, padding_mode='border')\n return dist_transf.mean()\n\n\ndef texture_dt_loss(texture_flow, dist_transf, vis_rend=None, cams=None, verts=None, tex_pred=None):\n \"\"\"\n texture_flow: B x F x T x T x 2\n (In normalized coordinate [-1, 1])\n dist_transf: B x 1 x N x N\n\n Similar to geom_utils.sample_textures\n But instead of sampling image, it samples dt values.\n \"\"\"\n # Reshape into B x F x T*T x 2\n T = texture_flow.size(-2)\n F = texture_flow.size(1)\n flow_grid = texture_flow.view(-1, F, T * T, 2)\n # B x 1 x F x T*T\n dist_transf = torch.nn.functional.grid_sample(dist_transf, flow_grid)\n\n if vis_rend is not None:\n # Visualize the error!\n # B x 3 x F x T*T\n dts = dist_transf.repeat(1, 3, 1, 1)\n # B x 3 x F x T x T\n dts = dts.view(-1, 3, F, T, T)\n # B x F x T x T x 3\n dts = dts.permute(0, 2, 3, 4, 1)\n dts = dts.unsqueeze(4).repeat(1, 1, 1, 1, T, 1) / dts.max()\n\n from ..utils import bird_vis\n for i in range(dist_transf.size(0)):\n rend_dt = vis_rend(verts[i], cams[i], dts[i])\n rend_img = bird_vis.tensor2im(tex_pred[i].data) \n import matplotlib.pyplot as plt\n plt.ion()\n fig=plt.figure(1)\n plt.clf()\n ax = fig.add_subplot(121)\n ax.imshow(rend_dt)\n ax = fig.add_subplot(122)\n ax.imshow(rend_img)\n import ipdb; ipdb.set_trace()\n\n return dist_transf.mean()\n\n\ndef texture_loss(img_pred, img_gt, mask_pred, mask_gt):\n \"\"\"\n Input:\n img_pred, img_gt: B x 3 x H x W\n mask_pred, mask_gt: B x H x W\n \"\"\"\n mask_pred = mask_pred.unsqueeze(1)\n mask_gt = mask_gt.unsqueeze(1)\n\n # masked_rend = (img_pred * mask)[0].data.cpu().numpy()\n # masked_gt = (img_gt * mask)[0].data.cpu().numpy()\n # import matplotlib.pyplot as plt\n # plt.ion()\n # plt.figure(1)\n # plt.clf()\n # fig = plt.figure(1)\n # ax = fig.add_subplot(121)\n # ax.imshow(np.transpose(masked_rend, (1, 2, 0)))\n # ax = fig.add_subplot(122)\n # ax.imshow(np.transpose(masked_gt, (1, 2, 0)))\n # import ipdb; ipdb.set_trace()\n\n return torch.nn.L1Loss()(img_pred * mask_pred, img_gt * mask_gt)\n\n\ndef camera_loss(cam_pred, cam_gt, margin):\n \"\"\"\n cam_* are B x 7, [sc, tx, ty, quat]\n Losses are in similar magnitude so one margin is ok.\n \"\"\"\n # CH: camera loss always 0\n return 0\n\n # CH: comment out old loss code\n# rot_pred = cam_pred[:, -4:]\n# rot_gt = cam_gt[:, -4:]\n\n# rot_loss = hinge_loss(quat_loss_geodesic(rot_pred, rot_gt), margin)\n# # Scale and trans.\n# st_loss = (cam_pred[:, :3] - cam_gt[:, :3])**2\n# st_loss = hinge_loss(st_loss.view(-1), margin)\n\n# return rot_loss.mean() + st_loss.mean()\n\ndef hinge_loss(loss, margin):\n # Only penalize if loss > margin\n zeros = torch.autograd.Variable(torch.zeros(1).cuda(), requires_grad=False)\n return torch.max(loss - margin, zeros)\n\n\ndef quat_loss_geodesic(q1, q2):\n '''\n Geodesic rotation loss.\n \n Args:\n q1: N X 4\n q2: N X 4\n Returns:\n loss : N x 1\n '''\n q1 = torch.unsqueeze(q1, 1)\n q2 = torch.unsqueeze(q2, 1)\n q2_conj = torch.cat([ q2[:, :, [0]] , -1*q2[:, :, 1:4] ], dim=-1)\n q_rel = geom_utils.hamilton_product(q1, q2_conj)\n q_loss = 1 - torch.abs(q_rel[:, :, 0])\n # we can also return q_loss*q_loss\n return q_loss\n \n\ndef quat_loss(q1, q2):\n '''\n Anti-podal squared L2 loss.\n \n Args:\n q1: N X 4\n q2: N X 4\n Returns:\n loss : N x 1\n '''\n q_diff_loss = (q1-q2).pow(2).sum(1)\n q_sum_loss = (q1+q2).pow(2).sum(1)\n q_loss, _ = torch.stack((q_diff_loss, q_sum_loss), dim=1).min(1)\n return q_loss\n\n\ndef triangle_loss(verts, edge2verts):\n \"\"\"\n Encourages dihedral angle to be 180 degrees.\n\n Args:\n verts: B X N X 3\n edge2verts: B X E X 4\n Returns:\n loss : scalar\n \"\"\"\n indices_repeat = torch.stack([edge2verts, edge2verts, edge2verts], dim=2) # B X E X 3 X 4\n\n verts_A = torch.gather(verts, 1, indices_repeat[:, :, :, 0])\n verts_B = torch.gather(verts, 1, indices_repeat[:, :, :, 1])\n verts_C = torch.gather(verts, 1, indices_repeat[:, :, :, 2])\n verts_D = torch.gather(verts, 1, indices_repeat[:, :, :, 3])\n\n # n1 = cross(ad, ab)\n # n2 = cross(ab, ac)\n n1 = geom_utils.cross_product(verts_D - verts_A, verts_B - verts_A)\n n2 = geom_utils.cross_product(verts_B - verts_A, verts_C - verts_A)\n\n n1 = torch.nn.functional.normalize(n1, dim=2)\n n2 = torch.nn.functional.normalize(n2, dim=2)\n\n dot_p = (n1 * n2).sum(2)\n loss = ((1 - dot_p)**2).mean()\n return loss\n\n\ndef deform_l2reg(V):\n \"\"\"\n l2 norm on V = B x N x 3\n \"\"\"\n V = V.view(-1, V.size(2))\n return torch.mean(torch.norm(V, p=2, dim=1))\n\n\ndef entropy_loss(A):\n \"\"\"\n Input is K x N\n Each column is a prob of vertices being the one for k-th keypoint.\n We want this to be sparse = low entropy.\n \"\"\"\n entropy = -torch.sum(A * torch.log(A), 1)\n # Return avg entropy over \n return torch.mean(entropy)\n\n\ndef kp_l2_loss(kp_pred, kp_gt):\n \"\"\"\n L2 loss between visible keypoints.\n\n \\Sum_i [0.5 * vis[i] * (kp_gt[i] - kp_pred[i])^2] / (|vis|)\n \"\"\"\n # CH: Do not consider keypoint loss\n return 0\n\n# criterion = torch.nn.MSELoss()\n\n# vis = (kp_gt[:, :, 2, None] > 0).float()\n\n# # This always has to be (output, target), not (target, output)\n# return criterion(vis * kp_pred, vis * kp_gt[:, :, :2])\n\n\ndef lsgan_loss(score_real, score_fake):\n \"\"\"\n DELETE ME.\n Label 0=fake, 1=real.\n score_real is B x 1, score for real samples\n score_fake is B x 1, score for fake samples\n\n Returns loss for discriminator and encoder.\n \"\"\"\n\n disc_loss_real = torch.mean((score_real - 1)**2)\n disc_loss_fake = torch.mean((score_fake)**2)\n disc_loss = disc_loss_real + disc_loss_fake\n\n enc_loss = torch.mean((score_fake - 1)**2)\n\n return disc_loss, enc_loss\n\n\nclass EdgeLoss(object):\n \"\"\"\n Edge length should not diverge from the original edge length.\n\n On initialization computes the current edge lengths.\n \"\"\"\n def __init__(self, verts, edges2verts, margin=2, use_bad_edge=False, use_l2=False):\n # Input:\n # verts: B x N x 3\n # edeges2verts: B x E x 4\n # (only using the first 2 columns)\n self.use_l2 = use_l2\n\n # B x E x 2\n edge_verts = edges2verts[:, :, :2]\n self.indices = torch.stack([edge_verts, edge_verts, edge_verts], dim=2)\n V_copy = torch.autograd.Variable(verts.data, requires_grad=False)\n if V_copy.dim() == 2:\n # N x 3 (mean shape) -> B x N x 3\n V_copy = V_copy.unsqueeze(0).repeat(edges2verts.size(0), 1, 1)\n\n if use_bad_edge:\n self.log_e0 = torch.log(self.compute_edgelength(V_copy))\n else:\n # e0 is the mean over all edge lengths!\n e0 = self.compute_edgelength(V_copy).mean(1).view(-1, 1)\n self.log_e0 = torch.log(e0)\n\n self.margin = np.log(margin)\n self.zeros = torch.autograd.Variable(torch.zeros(1).cuda(), requires_grad=False)\n\n # For visualization\n self.v1 = edges2verts[0, :, 0].data.cpu().numpy()\n self.v2 = edges2verts[0, :, 1].data.cpu().numpy()\n\n def __call__(self, verts):\n e1 = self.compute_edgelength(verts)\n if self.use_l2:\n dist = (torch.log(e1) - self.log_e0)**2\n self.dist = torch.max(dist - self.margin**2, self.zeros)\n else:\n dist = torch.abs(torch.log(e1) - self.log_e0)\n self.dist = torch.max(dist - self.margin, self.zeros)\n return self.dist.mean()\n\n def compute_edgelength(self, V):\n v1 = torch.gather(V, 1, self.indices[:, :, :, 0])\n v2 = torch.gather(V, 1, self.indices[:, :, :, 1])\n\n elengths = torch.sqrt(((v1 - v2)**2).sum(2))\n\n # B x E\n return elengths\n\n def visualize(self, verts, F_np, mv=None):\n from psbody.mesh import Mesh\n\n V = verts[0].data.cpu().numpy()\n mesh = Mesh(V, F_np)\n dist = self.dist[0].data.cpu().numpy()\n\n v_weights = np.zeros((V.shape[0]))\n for e_id, (v1_id, v2_id) in enumerate(zip(self.v1, self.v2)):\n v_weights[v1_id] += dist[e_id]\n v_weights[v2_id] += dist[e_id]\n\n mesh.set_vertex_colors_from_weights(v_weights)\n\n if mv is not None:\n mv.set_dynamic_meshes([mesh])\n else:\n mesh.show()\n import ipdb; ipdb.set_trace()\n\n\nclass LaplacianLoss(object):\n \"\"\"\n Encourages minimal mean curvature shapes.\n \"\"\"\n def __init__(self, faces):\n # Input:\n # faces: B x F x 3\n from ..nnutils.laplacian import Laplacian\n # V x V\n self.laplacian = Laplacian(faces)\n self.Lx = None\n\n def __call__(self, verts):\n self.Lx = self.laplacian(verts)\n # Reshape to BV x 3\n Lx = self.Lx.view(-1, self.Lx.size(2))\n loss = torch.norm(Lx, p=2, dim=1).mean()\n return loss\n\n def visualize(self, verts, mv=None):\n # Visualizes the laplacian.\n # Verts is B x N x 3 Variable\n Lx = self.Lx[0].data.cpu().numpy()\n\n V = verts[0].data.cpu().numpy()\n\n from psbody.mesh import Mesh\n F = self.laplacian.F_np[0]\n mesh = Mesh(V, F)\n\n weights = np.linalg.norm(Lx, axis=1)\n mesh.set_vertex_colors_from_weights(weights)\n\n if mv is not None:\n mv.set_dynamic_meshes([mesh])\n else:\n mesh.show()\n import ipdb; ipdb.set_trace()\n\n\nclass PerceptualTextureLoss(object):\n def __init__(self):\n from ..nnutils.perceptual_loss import PerceptualLoss\n self.perceptual_loss = PerceptualLoss()\n\n def __call__(self, img_pred, img_gt, mask_pred, mask_gt):\n \"\"\"\n Input:\n img_pred, img_gt: B x 3 x H x W\n mask_pred, mask_gt: B x H x W\n \"\"\"\n mask_pred = mask_pred.unsqueeze(1)\n mask_gt = mask_gt.unsqueeze(1)\n # masked_rend = (img_pred * mask_pred)[0].data.cpu().numpy()\n # masked_gt = (img_gt * mask_gt)[0].data.cpu().numpy()\n # import matplotlib.pyplot as plt\n # plt.ion()\n # plt.figure(1)\n # plt.clf()\n # fig = plt.figure(1)\n # ax = fig.add_subplot(121)\n # ax.imshow(np.transpose(masked_rend, (1, 2, 0)))\n # ax = fig.add_subplot(122)\n # ax.imshow(np.transpose(masked_gt, (1, 2, 0)))\n # import ipdb; ipdb.set_trace()\n\n # Only use mask_gt..\n dist = self.perceptual_loss(img_pred * mask_gt, img_gt * mask_gt)\n return dist.mean()\n", "\"\"\"\nMesh net model.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom absl import app\nfrom absl import flags\nimport os\nimport os.path as osp\nimport numpy as np\nimport torch\nimport torchvision\nimport torch.nn as nn\nfrom torch.autograd import Variable\n\nfrom ..utils import mesh\nfrom ..utils import geometry as geom_utils\nfrom . import net_blocks as nb\n\n#-------------- flags -------------#\n#----------------------------------#\nflags.DEFINE_boolean('symmetric', True, 'Use symmetric mesh or not')\nflags.DEFINE_integer('nz_feat', 200, 'Encoded feature size')\n\nflags.DEFINE_boolean('texture', True, 'if true uses texture!')\nflags.DEFINE_boolean('symmetric_texture', True, 'if true texture is symmetric!')\nflags.DEFINE_integer('tex_size', 6, 'Texture resolution per face')\n\nflags.DEFINE_integer('subdivide', 3, '# to subdivide icosahedron, 3=642verts, 4=2562 verts')\n\nflags.DEFINE_boolean('use_deconv', False, 'If true uses Deconv')\nflags.DEFINE_string('upconv_mode', 'bilinear', 'upsample mode')\n\nflags.DEFINE_boolean('only_mean_sym', False, 'If true, only the meanshape is symmetric')\nflags.DEFINE_boolean('deeper_shape_predictor', False, 'Use 2 layer shape deformation predictor')\n\n\n#------------- Modules ------------#\n#----------------------------------#\nclass ResNetConv(nn.Module):\n def __init__(self, n_blocks=4):\n super(ResNetConv, self).__init__()\n self.resnet = torchvision.models.resnet18(pretrained=True)\n self.n_blocks = n_blocks\n\n def forward(self, x):\n n_blocks = self.n_blocks\n x = self.resnet.conv1(x)\n x = self.resnet.bn1(x)\n x = self.resnet.relu(x)\n x = self.resnet.maxpool(x)\n\n if n_blocks >= 1:\n x = self.resnet.layer1(x)\n if n_blocks >= 2:\n x = self.resnet.layer2(x)\n if n_blocks >= 3:\n x = self.resnet.layer3(x)\n if n_blocks >= 4:\n x = self.resnet.layer4(x)\n return x\n\n\nclass Encoder(nn.Module):\n \"\"\"\n Current:\n Resnet with 4 blocks (x32 spatial dim reduction)\n Another conv with stride 2 (x64)\n This is sent to 2 fc layers with final output nz_feat.\n \"\"\"\n\n def __init__(self, input_shape, n_blocks=4, nz_feat=100, batch_norm=True):\n super(Encoder, self).__init__()\n self.resnet_conv = ResNetConv(n_blocks=4)\n self.enc_conv1 = nb.conv2d(batch_norm, 512, 256, stride=2, kernel_size=4)\n nc_input = 256 * (input_shape[0] // 64) * (input_shape[1] // 64)\n self.enc_fc = nb.fc_stack(nc_input, nz_feat, 2)\n\n nb.net_init(self.enc_conv1)\n\n def forward(self, img):\n resnet_feat = self.resnet_conv.forward(img)\n\n out_enc_conv1 = self.enc_conv1(resnet_feat)\n out_enc_conv1 = out_enc_conv1.view(img.size(0), -1)\n feat = self.enc_fc.forward(out_enc_conv1)\n\n return feat\n\n\nclass TexturePredictorUV(nn.Module):\n \"\"\"\n Outputs mesh texture\n \"\"\"\n\n def __init__(self, nz_feat, uv_sampler, opts, img_H=64, img_W=128, n_upconv=5, nc_init=256, predict_flow=False, symmetric=False, num_sym_faces=624):\n super(TexturePredictorUV, self).__init__()\n self.feat_H = img_H // (2 ** n_upconv)\n self.feat_W = img_W // (2 ** n_upconv)\n self.nc_init = nc_init\n self.symmetric = symmetric\n self.num_sym_faces = num_sym_faces\n self.F = uv_sampler.size(1)\n self.T = uv_sampler.size(2)\n self.predict_flow = predict_flow\n # B x F x T x T x 2 --> B x F x T*T x 2\n self.uv_sampler = uv_sampler.view(-1, self.F, self.T*self.T, 2)\n\n self.enc = nb.fc_stack(nz_feat, self.nc_init*self.feat_H*self.feat_W, 2)\n if predict_flow:\n nc_final=2\n else:\n nc_final=3\n self.decoder = nb.decoder2d(n_upconv, None, nc_init, init_fc=False, nc_final=nc_final, use_deconv=opts.use_deconv, upconv_mode=opts.upconv_mode)\n\n def forward(self, feat):\n # pdb.set_trace()\n uvimage_pred = self.enc.forward(feat)\n uvimage_pred = uvimage_pred.view(uvimage_pred.size(0), self.nc_init, self.feat_H, self.feat_W)\n # B x 2 or 3 x H x W\n self.uvimage_pred = self.decoder.forward(uvimage_pred)\n self.uvimage_pred = torch.nn.functional.tanh(self.uvimage_pred)\n\n tex_pred = torch.nn.functional.grid_sample(self.uvimage_pred, self.uv_sampler)\n tex_pred = tex_pred.view(uvimage_pred.size(0), -1, self.F, self.T, self.T).permute(0, 2, 3, 4, 1)\n\n if self.symmetric:\n # Symmetrize.\n tex_left = tex_pred[:, -self.num_sym_faces:]\n return torch.cat([tex_pred, tex_left], 1)\n else:\n # Contiguous Needed after the permute..\n return tex_pred.contiguous()\n\n\n\nclass ShapePredictor(nn.Module):\n \"\"\"\n Outputs mesh deformations\n \"\"\"\n\n def __init__(self, nz_feat, num_verts):\n super(ShapePredictor, self).__init__()\n # self.pred_layer = nb.fc(True, nz_feat, num_verts)\n self.pred_layer = nn.Linear(nz_feat, num_verts * 3)\n\n # Initialize pred_layer weights to be small so initial def aren't so big\n self.pred_layer.weight.data.normal_(0, 0.0001)\n\n def forward(self, feat):\n # pdb.set_trace()\n delta_v = self.pred_layer.forward(feat)\n # Make it B x num_verts x 3\n delta_v = delta_v.view(delta_v.size(0), -1, 3)\n # print('shape: ( Mean = {}, Var = {} )'.format(delta_v.mean().data[0], delta_v.var().data[0]))\n return delta_v\n\nclass DeeperShapePredictor(nn.Module):\n \"\"\"\n Outputs mesh deformations\n \"\"\"\n\n def __init__(self, nz_feat, num_verts):\n super(DeeperShapePredictor, self).__init__()\n # self.pred_layer = nb.fc(True, nz_feat, num_verts)\n self.hidden_layer = nn.Linear(nz_feat, num_verts)\n self.relu_act = nn.LeakyReLU(0.2,inplace=True)\n self.pred_layer = nn.Linear(num_verts, num_verts * 3)\n\n # Initialize pred_layer weights to be small so initial def aren't so big\n self.pred_layer.weight.data.normal_(0, 0.0001)\n\n def forward(self, feat):\n # pdb.set_trace()\n feat = self.hidden_layer.forward(feat)\n feat = self.relu_act(feat)\n delta_v = self.pred_layer.forward(feat)\n # Make it B x num_verts x 3\n delta_v = delta_v.view(delta_v.size(0), -1, 3)\n # print('shape: ( Mean = {}, Var = {} )'.format(delta_v.mean().data[0], delta_v.var().data[0]))\n return delta_v\n\nclass QuatPredictor(nn.Module):\n def __init__(self, nz_feat, nz_rot=4, classify_rot=False):\n super(QuatPredictor, self).__init__()\n self.pred_layer = nn.Linear(nz_feat, nz_rot)\n self.classify_rot = classify_rot\n\n def forward(self, feat):\n quat = self.pred_layer.forward(feat)\n if self.classify_rot:\n quat = torch.nn.functional.log_softmax(quat)\n else:\n quat = torch.nn.functional.normalize(quat)\n return quat\n\n\nclass ScalePredictor(nn.Module):\n def __init__(self, nz):\n super(ScalePredictor, self).__init__()\n self.pred_layer = nn.Linear(nz, 1)\n\n def forward(self, feat):\n scale = self.pred_layer.forward(feat) + 1 #biasing the scale to 1\n scale = torch.nn.functional.relu(scale) + 1e-12\n # print('scale: ( Mean = {}, Var = {} )'.format(scale.mean().data[0], scale.var().data[0]))\n return scale\n\n\nclass TransPredictor(nn.Module):\n \"\"\"\n Outputs [tx, ty] or [tx, ty, tz]\n \"\"\"\n\n def __init__(self, nz, orth=True):\n super(TransPredictor, self).__init__()\n if orth:\n self.pred_layer = nn.Linear(nz, 2)\n else:\n self.pred_layer = nn.Linear(nz, 3)\n\n def forward(self, feat):\n trans = self.pred_layer.forward(feat)\n # print('trans: ( Mean = {}, Var = {} )'.format(trans.mean().data[0], trans.var().data[0]))\n return trans\n\n\nclass CodePredictor(nn.Module):\n def __init__(self, nz_feat=100, num_verts=1000, deeper_shape_predictor=False):\n super(CodePredictor, self).__init__()\n# self.quat_predictor = QuatPredictor(nz_feat)\n if deeper_shape_predictor:\n print(\"Using deeper shape predictor\")\n self.shape_predictor = DeeperShapePredictor(nz_feat, num_verts=num_verts)\n else:\n print(\"Using shallow shape predictor\")\n self.shape_predictor = ShapePredictor(nz_feat, num_verts=num_verts)\n# self.scale_predictor = ScalePredictor(nz_feat)\n# self.trans_predictor = TransPredictor(nz_feat)\n\n def forward(self, feat):\n shape_pred = self.shape_predictor.forward(feat)\n scale_pred = 0 #self.scale_predictor.forward(feat)\n quat_pred = 0 #self.quat_predictor.forward(feat)\n trans_pred = 0 #self.trans_predictor.forward(feat)\n return shape_pred, scale_pred, trans_pred, quat_pred\n\n#------------ Mesh Net ------------#\n#----------------------------------#\nclass MeshNet(nn.Module):\n def __init__(self, input_shape, opts, nz_feat=100, num_kps=0, sfm_mean_shape=None):\n # Input shape is H x W of the image.\n super(MeshNet, self).__init__()\n self.opts = opts\n self.pred_texture = opts.texture\n self.symmetric = opts.symmetric\n self.symmetric_texture = opts.symmetric_texture\n\n # Mean shape.\n verts, faces = mesh.create_sphere(opts.subdivide)\n num_verts = verts.shape[0]\n\n if self.symmetric:\n verts, faces, num_indept, num_sym, num_indept_faces, num_sym_faces = mesh.make_symmetric(verts, faces)\n if sfm_mean_shape is not None:\n verts = geom_utils.project_verts_on_mesh(verts, sfm_mean_shape[0], sfm_mean_shape[1])\n\n num_sym_output = num_indept + num_sym\n if opts.only_mean_sym:\n print('Only the mean shape is symmetric!')\n self.num_output = num_verts\n else:\n self.num_output = num_sym_output\n self.num_sym = num_sym\n self.num_indept = num_indept\n self.num_indept_faces = num_indept_faces\n self.num_sym_faces = num_sym_faces\n # mean shape is only half.\n self.mean_v = nn.Parameter(torch.Tensor(verts[:num_sym_output]))\n\n # Needed for symmetrizing..\n self.flip = Variable(torch.ones(1, 3).cuda(), requires_grad=False)\n self.flip[0, 0] = -1\n else:\n if sfm_mean_shape is not None:\n verts = geom_utils.project_verts_on_mesh(verts, sfm_mean_shape[0], sfm_mean_shape[1]) \n self.mean_v = nn.Parameter(torch.Tensor(verts))\n self.num_output = num_verts\n\n verts_np = verts\n faces_np = faces\n self.og_faces = faces\n self.faces = Variable(torch.LongTensor(faces).cuda(), requires_grad=False)\n self.edges2verts = mesh.compute_edges2verts(verts, faces)\n\n# vert2kp_init = torch.Tensor(np.ones((num_kps, num_verts)) / float(num_verts))\n # Remember initial vert2kp (after softmax)\n# self.vert2kp_init = torch.nn.functional.softmax(Variable(vert2kp_init.cuda(), requires_grad=False), dim=1)\n# self.vert2kp = nn.Parameter(vert2kp_init)\n\n\n self.encoder = Encoder(input_shape, n_blocks=4, nz_feat=nz_feat)\n self.code_predictor = CodePredictor(nz_feat=nz_feat, num_verts=self.num_output, deeper_shape_predictor=opts.deeper_shape_predictor)\n\n if self.pred_texture:\n if self.symmetric_texture:\n num_faces = self.num_indept_faces + self.num_sym_faces\n else:\n num_faces = faces.shape[0]\n\n uv_sampler = mesh.compute_uvsampler(verts_np, faces_np[:num_faces], tex_size=opts.tex_size)\n # F' x T x T x 2\n uv_sampler = Variable(torch.FloatTensor(uv_sampler).cuda(), requires_grad=False)\n # B x F' x T x T x 2\n uv_sampler = uv_sampler.unsqueeze(0).repeat(self.opts.batch_size, 1, 1, 1, 1)\n img_H = int(2**np.floor(np.log2(np.sqrt(num_faces) * opts.tex_size)))\n img_W = 2 * img_H\n self.texture_predictor = TexturePredictorUV(\n nz_feat, uv_sampler, opts, img_H=img_H, img_W=img_W, predict_flow=True, symmetric=opts.symmetric_texture, num_sym_faces=self.num_sym_faces)\n nb.net_init(self.texture_predictor)\n\n def forward(self, img):\n img_feat = self.encoder.forward(img)\n codes_pred = self.code_predictor.forward(img_feat)\n if self.pred_texture:\n texture_pred = self.texture_predictor.forward(img_feat)\n return codes_pred, texture_pred\n else:\n return codes_pred\n\n def symmetrize(self, V):\n \"\"\"\n Takes num_indept+num_sym verts and makes it\n num_indept + num_sym + num_sym\n Is identity if model is not symmetric\n \"\"\"\n if self.symmetric:\n if V.dim() == 2:\n # No batch\n V_left = self.flip * V[-self.num_sym:]\n return torch.cat([V, V_left], 0)\n else:\n # With batch\n V_left = self.flip * V[:, -self.num_sym:]\n return torch.cat([V, V_left], 1)\n else:\n return V\n\n def get_mean_shape(self):\n return self.symmetrize(self.mean_v)\n" ]
[ [ "torch.mean", "torch.abs", "torch.max", "torch.cat", "torch.zeros", "torch.nn.L1Loss", "torch.autograd.Variable", "torch.norm", "numpy.zeros", "matplotlib.pyplot.figure", "numpy.log", "torch.unsqueeze", "torch.log", "torch.stack", "matplotlib.pyplot.ion", "torch.nn.functional.normalize", "numpy.linalg.norm", "matplotlib.pyplot.clf", "torch.nn.functional.grid_sample", "torch.gather" ], [ "torch.nn.functional.normalize", "torch.LongTensor", "torch.ones", "numpy.sqrt", "torch.nn.functional.log_softmax", "torch.cat", "torch.Tensor", "torch.nn.Linear", "torch.nn.functional.relu", "torch.nn.functional.grid_sample", "torch.nn.LeakyReLU", "torch.FloatTensor", "torch.nn.functional.tanh" ] ]
[ { "matplotlib": [], "numpy": [ "1.10", "1.12", "1.11", "1.19", "1.24", "1.13", "1.16", "1.9", "1.18", "1.23", "1.21", "1.22", "1.20", "1.7", "1.15", "1.14", "1.17", "1.8" ], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jlubo/memory-consolidation-stc
[ "f9934760e12de324360297d7fc7902623169cb4d", "f9934760e12de324360297d7fc7902623169cb4d" ]
[ "analysis/averageWeights.py", "analysis/averageFileColumnsAdvanced.py" ]
[ "######################################################\n### Averages early- and late-phase weight matrices ###\n######################################################\n\n### Copyright 2019-2021 Jannik Luboeinski\n### licensed under Apache-2.0 (http://www.apache.org/licenses/LICENSE-2.0)\n\nimport numpy as np\nfrom pathlib import Path\n\nnp.set_printoptions(threshold=1e10, linewidth=200) # extend console print range for numpy arrays\n\n# readWeightMatrixData\n# Reads complete weight matrix data from a file (modified from plotFunctions.py)\n# filename: name of the file to read the data from\n# Nl: number of neurons in one row/column\n# return: the adjacency matrix, the early-phase weight matrix, the late-phase weight matrix, the firing rate vector\ndef readWeightMatrixData(filename, Nl):\n\n\t# read weight matrices and firing rates from file\n\ttry:\n\t\twith open(filename) as f:\n\t\t\trawdata = f.read()\n\texcept OSError:\n\t\traise\n\n\trawdata = rawdata.split('\\n\\n')\n\trawmatrix_h = rawdata[0].split('\\n')\n\trawmatrix_z = rawdata[1].split('\\n')\n\trawmatrix_v = rawdata[2].split('\\n')\n\n\trows = len(rawmatrix_v)\n\n\tif (rows != len(rawmatrix_v[0].split('\\t\\t'))) or (rows != Nl):\n\t\traise ValueError(str(rows) + ' instead of ' + str(Nl) + ' lines in data file \"' + filename + '\"')\n\t\tf.close()\n\t\texit()\n\n\tv = np.zeros((Nl,Nl))\n\th = np.zeros((Nl**2,Nl**2))\n\tz = np.zeros((Nl**2,Nl**2))\n\n\tfor i in range(Nl**2):\n\t\tif i < Nl:\n\t\t\tvalue0 = rawmatrix_v[i].split('\\t\\t')\n\t\tvalue1 = rawmatrix_h[i].split('\\t\\t')\n\t\tvalue2 = rawmatrix_z[i].split('\\t\\t')\n\n\t\tfor j in range(Nl**2):\n\t\t\tif i < Nl and j < Nl:\n\t\t\t\tv[i][j] = float(value0[j])\n\t\t\th[i][j] = float(value1[j])\n\t\t\tz[i][j] = float(value2[j])\n\n\tf.close()\n\tconnections = (h > 0)\n\n\treturn connections, h, z, v\n\n# averageWeights\n# Averages early- and late-phase weight matrices over all trials that are available\n# (trial data must be given as *_net_* file in a given directory)\n# nppath: path to the directory to read the data from\n# Nl: the number of excitatory neurons in one line of a quadratic grid\n# time: the time that at which the weights shall be read out\ndef averageWeights(nppath, Nl, time):\n\n\n\tc = np.zeros((Nl**2,Nl**2))\n\th = np.zeros((Nl**2,Nl**2))\n\tz = np.zeros((Nl**2,Nl**2))\n\tv = np.zeros((Nl,Nl))\n\n\tcounter = 0\n\n\t# Looking for data files (\"*_net_*\")\n\trawpaths = Path(nppath)\n\n\tfor x in rawpaths.iterdir():\n\n\t\tpath = str(x)\n\n\t\tif (\"_net_\" + time + \".txt\") in path:\n\n\t\t\ttry:\n\t\t\t\tctmp, htmp, ztmp, vtmp = readWeightMatrixData(path, Nl)\n\t\t\texcept ValueError:\n\t\t\t\traise\n\t\t\texcept OSError:\n\t\t\t\traise\n\t\t\texcept:\n\t\t\t\tprint(\"Error in \" + path)\n\t\t\t\texit()\n\n\t\t\tc = c + ctmp\n\t\t\th = h + htmp\n\t\t\tz = z + ztmp\n\t\t\tv = v + vtmp\n\n\t\t\tcounter += 1\n\n\n\tprint(\"Averaged over \" + str(counter) + \" trials for t = \" + str(time) + \" s.\")\n\tc /= counter\n\th /= counter\n\tz /= counter\n\tv /= counter\n\n\t# write averaged _net_ file containing averaged early-/late-phase weights and firing rates\n\tf = open('net_' + time + '_averaged.txt','wb')\n\tnp.savetxt(f, h, fmt='%.6f', delimiter='\\t\\t')\n\tf.write(b'\\x0a')\n\tnp.savetxt(f, z, fmt='%.6f', delimiter='\\t\\t')\n\tf.write(b'\\x0a')\n\tnp.savetxt(f, v, fmt='%.6f', delimiter='\\t\\t')\n\tf.write(b'\\x0a\\x0a')\n\tf.close()\n\n\t# write averaged connectivity matrix (just for sanity check)\n\t#f = open('conn_' + time + '_averaged.txt','wb')\n\t#np.savetxt(f, c, fmt='%.0f', delimiter=' ')\n\t#f.close()\n\n#averageWeights(\".\", 40, \"10.0\")\naverageWeights(\".\", 40, \"20.0\")\n#averageWeights(\".\", 40, \"28810.0\")\n", "##############################################################################################\n### Script to average data from the same columns in data files stored in different folders ###\n##############################################################################################\n\n### Copyright 2017-2021 Jannik Luboeinski\n### licensed under Apache-2.0 (http://www.apache.org/licenses/LICENSE-2.0)\n\nimport numpy as np\nimport os\nfrom pathlib import Path\n\n# averageFileColumns\n# Averages specified data columns across data files located in directories which names contain a specific string\n# and computes the standard deviation\n# outname: name of the file to write the averaged data to\n# rootpath: path in which to look for data folders\n# protocol: string that the data folders have to contain\n# suffix: suffix in the filename of data files to be read\n# columns: list of numbers of the columns in the data file to be read and averaged (e.g., [1, 3] for first and third column)\n# first_column_par [optional]: indicates if first column is to be treated as parameter (e.g., time) - it is then added regardless of 'columns'\n# comment_line [optional]: if True, leaves out the first line\ndef averageFileColumns(outname, rootpath, protocol, suffix, columns, first_column_par=True, comment_line=False):\n\tprint(\"Averaging columns \" + str(columns) + \" from files matching '*\" + suffix + \"' in folders of the protocol '\" + protocol + \"'...\")\n\tsample_number = 0\n\tcol_sep = '\\t\\t' # character(s) separating the columns\n\n\t# find the folders with the protocol in their name\n\trawpaths = Path(rootpath)\n\tpaths = np.array([str(x) for x in rawpaths.iterdir() if x.is_dir() and protocol in os.path.split(str(x))[1]])\n\n\tif paths.size == 0:\n\t\traise FileNotFoundError(\"No folders found that contain the string '\" + protocol + \"' in their name.\")\n\tprint(\"According folders found:\\n\", paths)\n\n\t# read data and average\n\t# loop over directories\n\tfor i in range(paths.size):\n\n\t\t# find the files with the suffix in their name\n\t\tsubrawpaths = Path(paths[i])\n\t\tsubpaths = np.array([str(x) for x in subrawpaths.iterdir() if suffix in str(x) and str(x).find(suffix) >= len(str(x))-len(suffix)])\n\n\t\tif subpaths.size == 0:\n\t\t\traise FileNotFoundError(\"No files found matching '*\" + suffix + \"' in '\" + paths[i] + \"'.\")\n\n\t\tprint(\"According files found in '\" + paths[i] + \"':\\n\", subpaths)\n\t\tsample_number += subpaths.size\n\n\t\t# loop over files in each directory\n\t\tfor j in range(subpaths.size):\n\n\t\t\twith open(subpaths[j]) as f:\n\t\t\t\trawdata = f.read()\n\n\t\t\trawdata = rawdata.split('\\n')\n\t\t\tif comment_line:\n\t\t\t\tdel rawdata[0] # leave out comment line\n\t\t\tif rawdata[-1] == \"\":\n\t\t\t\tdel rawdata[-1] # delete empty line\n\n\t\t\tif i == 0 and j == 0: # first file found: read number of rows and create data arrays\n\t\t\t\tnum_rows = len(rawdata)\n\t\t\t\tnum_cols = len(columns)\n\t\t\t\ttime = np.zeros(num_rows)\n\t\t\t\tdata = np.zeros((num_rows, num_cols))\n\t\t\t\tdata_var = np.zeros((num_rows, num_cols))\n\t\t\telif num_rows != len(rawdata):\n\t\t\t\traise IndexError(\"In '\" + subpaths[j] + \"': wrong number of rows: \" + str(len(rawdata)-1) + \" (\" + str(num_rows) + \" expected).\")\n\n\t\t\tfor k in range(num_rows):\n\t\t\t\tvalues = rawdata[k].split(col_sep)\n\t\t\t\ttry:\n\t\t\t\t\ttime[k] += np.double(values[0]) # read first/parameter column\n\t\t\t\texcept:\n\t\t\t\t\tprint(\"Error computing mean: in line \" + str(k+1) + \", column 1\\n\\tin '\" + subpaths[j] + \"'.\")\n\t\t\t\tfor l in range(num_cols):\n\t\t\t\t\ttry:\n\t\t\t\t\t\tdata[k][l] += np.double(values[columns[l]-1]) # read data columns\n\t\t\t\t\texcept:\n\t\t\t\t\t\tprint(\"Error computing mean: in line \" + str(k+1) + \", column \" + str(columns[l]) + \"\\n\\tin '\" + subpaths[j] + \"'.\")\n\n\t\t\tf.close()\n\n\ttime = time / sample_number\n\tdata = data / sample_number\n\n\t# read data and compute variance\n\t# loop over directories\n\tfor i in range(paths.size):\n\n\t\t# loop over files in each directory\n\t\tfor j in range(subpaths.size):\n\n\t\t\twith open(subpaths[j]) as f:\n\t\t\t\trawdata = f.read()\n\n\t\t\trawdata = rawdata.split('\\n')\n\n\t\t\tif comment_line:\n\t\t\t\tdel rawdata[0] # leave out comment line\n\t\t\tif rawdata[-1] == \"\":\n\t\t\t\tdel rawdata[-1] # delete empty line\n\n\t\t\tfor k in range(num_rows):\n\t\t\t\tvalues = rawdata[k].split(col_sep)\n\t\t\t\tfor l in range(num_cols):\n\t\t\t\t\ttry:\n\t\t\t\t\t\tdata_var[k][l] += np.power(np.double(values[columns[l]-1])-data[k][l], 2) # read data columns\n\t\t\t\t\texcept:\n\t\t\t\t\t\tprint(\"Error computing variance: in line \" + str(k+1) + \", column \" + str(columns[l]) + \"\\n\\tin '\" + subpaths[j] + \"'.\")\n\n\t\t\tf.close()\n\n\tdata_stdev = np.sqrt(data_var / (sample_number - 1))\n\n\t# write averaged data\n\tfout = open(outname + '.txt', 'w')\n\tfor k in range(num_rows):\n\t\tif first_column_par:\n\t\t\tfout.write(str(time[k]) + \"\\t\\t\")\n\t\tfor l in range(num_cols):\n\t\t\tfout.write(str(data[k][l]) + \"\\t\\t\" + str(data_stdev[k][l]))\n\t\t\tif l < num_cols-1: # as long as last column is not yet reached\n\t\t\t\t fout.write(\"\\t\\t\")\n\t\t\telse: # after the last column\n\t\t\t\t fout.write(\"\\n\")\n\tfout.close()\n\n## average weight over time traces for standard plasticity-inducing protocols STET, WTET; SLFS; WLFS:\nsuffix = '_data.txt'\naverageFileColumns('averaged_STET', '.', 'STET', suffix, [8, 9, 10], comment_line=True)\naverageFileColumns('averaged_WTET', '.', 'WTET', suffix, [8, 9, 10], comment_line=True)\naverageFileColumns('averaged_SLFS', '.', 'SLFS', suffix, [8, 9, 10], comment_line=True)\naverageFileColumns('averaged_WLFS', '.', 'WLFS', suffix, [8, 9, 10], comment_line=True)\n\n" ]
[ [ "numpy.savetxt", "numpy.set_printoptions", "numpy.zeros" ], [ "numpy.double", "numpy.zeros", "numpy.sqrt" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
tgisaturday/PPAP
[ "bac203b2c98ab9dec7b96ec44fb61cd2d778ab22" ]
[ "image_PPAP/train_ppap.py" ]
[ "import tensorflow as tf\nimport numpy as np\nfrom utils.utils import *\nfrom model import *\nimport sys\nimport os\nimport math\nimport time\nfrom utils.data_helper import data_loader\nfrom model import xavier_init, he_normal_init\n\ndataset = sys.argv[1]\nmodel_name = sys.argv[2]\nprev_iter = int(sys.argv[3])\n\nmb_size, X_dim, width, height, channels,len_x_train, x_train, len_x_test, x_test = data_loader(dataset)\n \n \ngraph = tf.Graph()\nwith graph.as_default():\n session_conf = tf.ConfigProto(allow_soft_placement=True, log_device_placement=False)\n sess = tf.Session(config=session_conf)\n\n with sess.as_default():\n #input placeholder\n input_shape=[None, width, height, channels]\n filter_sizes=[5, 5, 5, 5, 5] \n hidden = 128\n z_dim = 128 \n\n if dataset == 'celebA' or dataset == 'lsun': \n n_filters=[channels, hidden, hidden*2, hidden*4, hidden*8]\n else: \n n_filters=[channels, hidden, hidden*2, hidden*4]\n \n X = tf.placeholder(tf.float32, shape=[None, width, height,channels])\n A_true_flat = X\n \n #autoencoder variables\n var_G = []\n var_H = []\n var_A = []\n #discriminator variables\n W1 = tf.Variable(he_normal_init([5,5,channels, hidden//2]))\n W2 = tf.Variable(he_normal_init([5,5, hidden//2,hidden]))\n W3 = tf.Variable(he_normal_init([5,5,hidden,hidden*2]))\n if dataset == 'celebA' or dataset == 'lsun':\n W4 = tf.Variable(he_normal_init([5,5,hidden*2,hidden*4]))\n W5 = tf.Variable(xavier_init([4*4*hidden*4, 1]))\n b5 = tf.Variable(tf.zeros(shape=[1]))\n var_D = [W1,W2,W3,W4,W5,b5] \n else:\n W4 = tf.Variable(xavier_init([4*4*hidden*2, 1]))\n b4 = tf.Variable(tf.zeros(shape=[1]))\n var_D = [W1,W2,W3,W4,b4] \n \n global_step = tf.Variable(0, name=\"global_step\", trainable=False) \n\n G_sample, latent_z = ppap_autoencoder(input_shape, n_filters, filter_sizes,z_dim, A_true_flat,var_A, var_G)\n G_hacked = hacker(input_shape, n_filters, filter_sizes,z_dim, G_sample, var_H)\n \n D_real_logits = discriminator(A_true_flat, var_D)\n D_fake_logits = discriminator(G_sample, var_D)\n \n gp = gradient_penalty(G_sample, A_true_flat, mb_size,var_D)\n D_loss = tf.reduce_mean(D_fake_logits) - tf.reduce_mean(D_real_logits) +10.0*gp \n\n privacy_gain = tf.reduce_mean(tf.pow(A_true_flat - G_hacked,2)) \n A_loss = tf.reduce_mean(tf.pow(A_true_flat - G_sample,2)) \n G_loss = -tf.reduce_mean(D_fake_logits) - privacy_gain\n H_loss = privacy_gain \n \n latent_max = tf.reduce_max(latent_z, axis = 0)\n latent_min = tf.reduce_min(latent_z, axis = 0)\n tf.summary.image('Original',A_true_flat) \n tf.summary.image('fake',G_sample)\n tf.summary.image('decoded_from_fake',G_hacked)\n tf.summary.scalar('D_loss', D_loss) \n tf.summary.scalar('G_loss',-tf.reduce_mean(D_fake_logits))\n tf.summary.scalar('A_loss', A_loss)\n tf.summary.scalar('privacy_gain',privacy_gain)\n merged = tf.summary.merge_all()\n\n num_batches_per_epoch = int((len_x_train-1)/mb_size) + 1\n \n A_solver = tf.train.AdamOptimizer(learning_rate=1e-4,beta1=0.5, beta2=0.9).minimize(A_loss,var_list=var_A, global_step=global_step) \n D_solver = tf.train.AdamOptimizer(learning_rate=1e-4,beta1=0.5, beta2=0.9).minimize(D_loss,var_list=var_D, global_step=global_step)\n G_solver = tf.train.AdamOptimizer(learning_rate=1e-4,beta1=0.5, beta2=0.9).minimize(G_loss,var_list=var_G, global_step=global_step)\n H_solver = tf.train.AdamOptimizer(learning_rate=1e-4,beta1=0.5, beta2=0.9).minimize(H_loss,var_list=var_H, global_step=global_step)\n \n timestamp = str(int(time.time()))\n if not os.path.exists('results/PPAP/'):\n os.makedirs('results/PPAP/') \n out_dir = os.path.abspath(os.path.join(os.path.curdir, \"results/PPAP/models/{}_\".format(dataset) +model_name))\n checkpoint_dir = os.path.abspath(os.path.join(out_dir, \"checkpoints\"))\n checkpoint_prefix = os.path.join(checkpoint_dir, \"model\")\n if not os.path.exists('results/PPAP/models/'):\n os.makedirs('results/PPAP/models/')\n if not os.path.exists(checkpoint_dir):\n os.makedirs(checkpoint_dir)\n saver = tf.train.Saver(tf.global_variables())\n if not os.path.exists('results/PPAP/dc_out_{}/'.format(dataset)):\n os.makedirs('results/PPAP/dc_out_{}/'.format(dataset)) \n\n train_writer = tf.summary.FileWriter('results/graphs/PPAP/{}'.format(dataset),sess.graph)\n saver = tf.train.Saver(tf.global_variables())\n sess.run(tf.global_variables_initializer())\n if prev_iter != 0:\n saver.restore(sess,tf.train.latest_checkpoint(checkpoint_dir)) \n i = prev_iter \n if prev_iter == 0:\n for idx in range(num_batches_per_epoch*10):\n if dataset == 'mnist':\n X_mb, _ = x_train.train.next_batch(mb_size)\n X_mb = np.reshape(X_mb,[-1,28,28,1])\n elif dataset == 'lsun':\n X_mb = x_train.next_batch(mb_size) \n else:\n X_mb = next_batch(mb_size, x_train) \n summary,_, A_loss_curr= sess.run([merged, A_solver, A_loss],feed_dict={X: X_mb})\n current_step = tf.train.global_step(sess, global_step)\n train_writer.add_summary(summary,current_step)\n if idx % 100 == 0:\n print('Iter: {}; A_loss: {:.4};'.format(idx,A_loss_curr))\n if idx % 1000 == 0: \n path = saver.save(sess, checkpoint_prefix, global_step=current_step)\n print('Saved model at {} at step {}'.format(path, current_step))\n for idx in range(num_batches_per_epoch):\n if dataset == 'mnist':\n X_mb, _ = x_train.train.next_batch(mb_size)\n X_mb = np.reshape(X_mb,[-1,28,28,1])\n elif dataset == 'lsun':\n X_mb = x_train.next_batch(mb_size) \n else:\n X_mb = next_batch(mb_size, x_train) \n max_curr, min_curr = sess.run([latent_max,latent_min], feed_dict ={X: X_mb})\n if idx == 0:\n z_max = max_curr\n z_min = min_curr\n else:\n z_max = np.maximum(z_max,max_curr)\n z_min = np.minimum(z_min,min_curr)\n z_sensitivity = np.abs(np.subtract(z_max,z_min))\n print(\"Approximated Global Sensitivity:\")\n print(z_sensitivity)\n if prev_iter == 0: \n sess.run(tf.variables_initializer(var_list=var_G))\n for it in range(num_batches_per_epoch*1000):\n for _ in range(5):\n if dataset == 'mnist':\n X_mb, _ = x_train.train.next_batch(mb_size)\n X_mb = np.reshape(X_mb,[-1,28,28,1])\n elif dataset == 'lsun':\n X_mb = x_train.next_batch(mb_size) \n else:\n X_mb = next_batch(mb_size, x_train)\n _, D_loss_curr = sess.run([D_solver, D_loss],feed_dict={X: X_mb}) \n \n _, H_loss_curr = sess.run([H_solver, H_loss],feed_dict={X: X_mb}) \n summary,_,G_loss_curr = sess.run([merged, G_solver, G_loss],feed_dict={X: X_mb})\n current_step = tf.train.global_step(sess, global_step)\n train_writer.add_summary(summary,current_step)\n \n if it % 100 == 0:\n print('Iter: {}; D_loss: {:.4}; G_loss: {:.4}; privacy_gain: {:.4};'.format(it,D_loss_curr, G_loss_curr,H_loss_curr))\n\n if it % 1000 == 0: \n Xt_mb = x_test[:mb_size]\n G_sample_curr,re_fake_curr = sess.run([G_sample, G_hacked], feed_dict={X: Xt_mb})\n samples_flat = tf.reshape(G_sample_curr,[-1,width,height,channels]).eval()\n img_set = np.append(Xt_mb[:256], samples_flat[:256], axis=0) \n samples_flat = tf.reshape(re_fake_curr,[-1,width,height,channels]).eval() \n img_set = np.append(img_set, samples_flat[:256], axis=0) \n\n fig = plot(img_set, width, height, channels)\n plt.savefig('results/PPAP/dc_out_{}/{}.png'.format(dataset,str(i).zfill(3)), bbox_inches='tight')\n plt.close(fig)\n i += 1\n path = saver.save(sess, checkpoint_prefix, global_step=current_step)\n print('Saved model at {} at step {}'.format(path, current_step))\n" ]
[ [ "tensorflow.train.global_step", "numpy.minimum", "tensorflow.zeros", "tensorflow.global_variables", "tensorflow.variables_initializer", "tensorflow.train.AdamOptimizer", "tensorflow.summary.scalar", "tensorflow.Graph", "tensorflow.Variable", "numpy.reshape", "tensorflow.summary.image", "numpy.subtract", "tensorflow.ConfigProto", "tensorflow.Session", "tensorflow.pow", "tensorflow.placeholder", "tensorflow.global_variables_initializer", "numpy.append", "tensorflow.summary.merge_all", "tensorflow.reduce_max", "tensorflow.train.latest_checkpoint", "numpy.maximum", "tensorflow.reduce_mean", "tensorflow.reshape", "tensorflow.reduce_min" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
Chutlhu/python_kickstart
[ "3fa7ee6830fa8c99b7e9887206d7fcda7361d292" ]
[ "src/models/train_model.py" ]
[ "from sklearn import svm\n\ndef train(data, target, C, gamma):\n clf = svm.SVC(C, 'rbf', gamma=gamma)\n clf.fit(data[:90],\n target[:90])\n return clf\n" ]
[ [ "sklearn.svm.SVC" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
THUDM/cogdl
[ "37359d559ae4f9f2c0c34d851abaa0a0950d120a", "37359d559ae4f9f2c0c34d851abaa0a0950d120a" ]
[ "cogdl/models/nn/agc.py", "cogdl/models/nn/gae.py" ]
[ "import torch\nimport numpy as np\nfrom sklearn.cluster import SpectralClustering\n\nfrom cogdl.utils import spmm\nfrom .. import BaseModel, register_model\n\n\n@register_model(\"agc\")\nclass AGC(BaseModel):\n r\"\"\"The AGC model from the `\"Attributed Graph Clustering via Adaptive Graph Convolution\"\n <https://arxiv.org/abs/1906.01210>`_ paper\n\n Args:\n num_clusters (int) : Number of clusters.\n max_iter (int) : Max iteration to increase k\n \"\"\"\n\n @staticmethod\n def add_args(parser):\n # fmt: off\n parser.add_argument(\"--num-clusters\", type=int, default=7)\n parser.add_argument(\"--max-iter\", type=int, default=10)\n # fmt: on\n\n @classmethod\n def build_model_from_args(cls, args):\n return cls(args.num_clusters, args.max_iter, args.cpu)\n\n def __init__(self, num_clusters, max_iter, cpu):\n super(AGC, self).__init__()\n\n self.num_clusters = num_clusters\n self.max_iter = max_iter\n\n self.device = \"cuda\" if torch.cuda.is_available() and not cpu else \"cpu\"\n\n def forward(self, data):\n data = data.to(self.device)\n self.num_nodes = data.x.shape[0]\n graph = data\n graph.add_remaining_self_loops()\n\n graph.sym_norm()\n graph.edge_weight = data.edge_weight * 0.5\n\n pre_intra = 1e27\n pre_feat = None\n for t in range(1, self.max_iter + 1):\n x = data.x\n for i in range(t):\n x = spmm(graph, x)\n k = torch.mm(x, x.t())\n w = (torch.abs(k) + torch.abs(k.t())) / 2\n clustering = SpectralClustering(\n n_clusters=self.num_clusters, assign_labels=\"discretize\", random_state=0\n ).fit(w.detach().cpu())\n clusters = clustering.labels_\n intra = self.compute_intra(x.cpu().numpy(), clusters)\n print(\"iter #%d, intra = %.4lf\" % (t, intra))\n if intra > pre_intra:\n features_matrix = pre_feat\n return features_matrix\n pre_intra = intra\n pre_feat = w\n features_matrix = w\n return features_matrix.cpu()\n\n def compute_intra(self, x, clusters):\n num_nodes = x.shape[0]\n intra = np.zeros(self.num_clusters)\n num_per_cluster = np.zeros(self.num_clusters)\n for i in range(num_nodes):\n for j in range(i + 1, num_nodes):\n if clusters[i] == clusters[j]:\n intra[clusters[i]] += np.sum((x[i] - x[j]) ** 2) ** 0.5\n num_per_cluster[clusters[i]] += 1\n intra = np.array(list(filter(lambda x: x > 0, intra)))\n num_per_cluster = np.array(list(filter(lambda x: x > 0, num_per_cluster)))\n return np.mean(intra / num_per_cluster)\n", "import torch\nimport torch.nn.functional as F\nfrom cogdl.layers import GCNLayer\n\nfrom .. import BaseModel, register_model\nfrom .gcn import TKipfGCN\n\n\n@register_model(\"gae\")\nclass GAE(TKipfGCN):\n @classmethod\n def build_model_from_args(cls, args):\n return cls(args.num_features, args.hidden_size, args.num_layers, args.dropout)\n\n def __init__(self, in_feats, hidden_size, num_layers, dropout):\n super(GAE, self).__init__(in_feats, hidden_size, 1, num_layers, dropout)\n\n def make_loss(self, data, adj):\n embeddings = self.embed(data)\n return (\n F.binary_cross_entropy(F.softmax(torch.mm(embeddings, embeddings.t())), adj, reduction=\"sum\")\n / data.x.shape[0]\n )\n\n def get_features(self, data):\n return self.embed(data).detach()\n\n\n@register_model(\"vgae\")\nclass VGAE(BaseModel):\n @staticmethod\n def add_args(parser):\n \"\"\"Add model-specific arguments to the parser.\"\"\"\n # fmt: off\n parser.add_argument(\"--num-features\", type=int)\n parser.add_argument(\"--hidden-size\", type=int, default=64)\n # fmt: on\n\n @classmethod\n def build_model_from_args(cls, args):\n return cls(args.num_features, args.hidden_size)\n\n def __init__(self, num_features, hidden_size):\n super(VGAE, self).__init__()\n self.num_features = num_features\n self.hidden_size = hidden_size\n self.conv1 = GCNLayer(self.num_features, self.hidden_size)\n self.conv2_mean = GCNLayer(self.hidden_size, self.hidden_size)\n self.conv2_var = GCNLayer(self.hidden_size, self.hidden_size)\n\n def reparameterize(self, mean, log_var):\n sigma = torch.exp(log_var)\n z = mean + torch.randn_like(log_var) * sigma\n return z\n\n def encode(self, graph):\n graph.add_remaining_self_loops()\n graph.sym_norm()\n\n h = graph.x\n h = self.conv1(graph, h)\n h = F.relu(h)\n mean = self.conv2_mean(graph, h)\n log_var = self.conv2_var(graph, h)\n return mean, log_var\n\n def decode(self, x):\n return torch.sigmoid(torch.matmul(x, x.t()))\n\n def forward(self, graph):\n mean, log_var = self.encode(graph)\n return self.reparameterize(mean, log_var)\n\n def get_features(self, graph):\n return self.forward(graph).detach()\n\n def make_loss(self, data, adj):\n mean, log_var = self.encode(data)\n z = self.reparameterize(mean, log_var)\n mat = self.decode(z)\n recon_loss = F.binary_cross_entropy(mat, adj, reduction=\"sum\")\n var = torch.exp(log_var)\n kl_loss = 0.5 * torch.mean(torch.sum(mean * mean + var - log_var - 1, dim=1))\n print(\"recon_loss = %.3f, kl_loss = %.3f\" % (recon_loss, kl_loss))\n return recon_loss + kl_loss\n" ]
[ [ "torch.abs", "sklearn.cluster.SpectralClustering", "numpy.mean", "torch.cuda.is_available", "numpy.zeros", "numpy.sum" ], [ "torch.randn_like", "torch.sum", "torch.exp", "torch.nn.functional.relu", "torch.nn.functional.binary_cross_entropy" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
zCFD/zutil
[ "aeccc9b3fa337ad68b03d6d21b720b5c1d0d06b8" ]
[ "zutil/__init__.py" ]
[ "\"\"\"\nCopyright (c) 2012-2017, Zenotech Ltd\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n * Neither the name of Zenotech Ltd nor the\n names of its contributors may be used to endorse or promote products\n derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL ZENOTECH LTD BE LIABLE FOR ANY\nDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\nON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\"\"\"\n\nfrom past.builtins import execfile\nfrom builtins import zip\nfrom builtins import str\nfrom builtins import range\nfrom past.utils import old_div\nimport math\nimport sys\nfrom os import path\nimport numpy as np\nimport imp\n\n\ndef get_parameters_from_file(filename):\n conf = filename\n mymodule = __import__(conf)\n # Force a reload just in case it has already been loaded\n imp.reload(mymodule)\n return getattr(sys.modules[conf], \"parameters\")\n\n\ndef include(filename):\n \"\"\"\n include a file by executing it. This imports everything including\n variables into the calling module\n \"\"\"\n if path.exists(filename):\n exec(compile(open(filename, \"rb\").read(), filename, \"exec\"))\n\n\ndef get_zone_info(module_name):\n try:\n # mymodule = __import__(module_name)\n # Force a reload just in case it has already been loaded\n # reload(mymodule)\n # return mymodule\n import importlib\n\n return importlib.import_module(module_name)\n except:\n print(\"Unexpected error:\", sys.exc_info()[0])\n return None\n\n\ndef get_default_zone_info():\n import inspect\n\n _, filename, linenumber, _, _, _ = inspect.stack()[1]\n return get_zone_info(path.split(path.splitext(filename)[0])[1] + \"_zone\")\n\n\ndef find_next_zone(parameters, zone_prefix):\n # Find next available\n found = False\n counter = 1\n while not found:\n key = zone_prefix + \"_\" + str(counter)\n if key in parameters:\n counter += 1\n else:\n found = True\n return key\n\n\ndef vector_from_wind_dir(wind_dir_degree, wind_speed=1.0):\n \"\"\"\n Return vector given a wind direction and wind speed\n Wind dir = 0.0 -> [0.0,-1.0,0.0]\n Wind dir = 90.0 -> [-1.0,0.0,0.0]\n\n Wind dir - Meteorological wind direction\n (direction from which wind is blowing)\n\n u -> Zone Velocity (Towards East)\n v -> Meridional Velocity (Towards North)\n\n \"\"\"\n\n return [\n -wind_speed * math.sin(math.radians(wind_dir_degree)),\n -wind_speed * math.cos(math.radians(wind_dir_degree)),\n 0.0,\n ]\n\n\ndef wind_direction(uvel, vvel):\n \"\"\"\n Calculate meteorological wind direction from velocity vector\n \"\"\"\n return math.degrees(math.atan2(-uvel, -vvel))\n\n\ndef vector_from_angle(alpha, beta, mag=1.0):\n \"\"\"\n Return vector given alpha and beta in degrees based on ESDU definition\n \"\"\"\n alpha = math.radians(alpha)\n beta = math.radians(beta)\n vec = [0.0, 0.0, 0.0]\n vec[0] = mag * math.cos(alpha) * math.cos(beta)\n vec[1] = mag * math.sin(beta)\n vec[2] = mag * math.sin(alpha) * math.cos(beta)\n return vec\n\n\ndef angle_from_vector(vec):\n \"\"\"\n Return vector given alpha and beta in degrees based on ESDU definition\n \"\"\"\n mag = math.sqrt(vec[0] * vec[0] + vec[1] * vec[1] + vec[2] * vec[2])\n\n beta = math.asin(old_div(vec[1], mag))\n alpha = math.acos(old_div(vec[0], (mag * math.cos(beta))))\n alpha = math.degrees(alpha)\n beta = math.degrees(beta)\n return (alpha, beta)\n\n\ndef rotate_vector(vec, alpha_degree, beta_degree):\n \"\"\"\n Rotate vector by alpha and beta based on ESDU definition\n \"\"\"\n alpha = math.radians(alpha_degree)\n beta = math.radians(beta_degree)\n rot = [0.0, 0.0, 0.0]\n rot[0] = (\n math.cos(alpha) * math.cos(beta) * vec[0]\n + math.sin(beta) * vec[1]\n + math.sin(alpha) * math.cos(beta) * vec[2]\n )\n rot[1] = (\n -math.cos(alpha) * math.sin(beta) * vec[0]\n + math.cos(beta) * vec[1]\n - math.sin(alpha) * math.sin(beta) * vec[2]\n )\n rot[2] = -math.sin(alpha) * vec[0] + math.cos(alpha) * vec[2]\n return rot\n\n\ndef feet_to_meters(val):\n return val * 0.3048\n\n\ndef pressure_from_alt(alt):\n \"\"\"\n Calculate pressure in Pa from altitude in m using standard atmospheric tables\n \"\"\"\n return 101325.0 * math.pow((1.0 - 2.25577e-5 * alt), 5.25588)\n\n\ndef to_kelvin(rankine):\n return rankine * 0.555555555\n\n\n# def non_dim_time(dim_time):\n# speed = 0.2 * math.sqrt(1.4 * 287.0 * 277.77)\n# non_dim_speed = 0.2 * math.sqrt(0.2)\n# return dim_time * speed / non_dim_speed\n\n\ndef dot(vec1, vec2):\n return vec1[0] * vec2[0] + vec1[1] * vec2[1] + vec1[2] * vec2[2]\n\n\ndef mag(vec):\n return math.sqrt(dot(vec, vec))\n\n\ndef R_2vect(R, vector_orig, vector_fin):\n \"\"\"Calculate the rotation matrix required to rotate from one vector to another.\n\n For the rotation of one vector to another, there are an infinit series of rotation matrices\n possible. Due to axially symmetry, the rotation axis can be any vector lying in the symmetry\n plane between the two vectors. Hence the axis-angle convention will be used to construct the\n matrix with the rotation axis defined as the cross product of the two vectors. The rotation\n angle is the arccosine of the dot product of the two unit vectors.\n\n Given a unit vector parallel to the rotation axis, w = [x, y, z] and the rotation angle a,\n the rotation matrix R is::\n\n | 1 + (1-cos(a))*(x*x-1) -z*sin(a)+(1-cos(a))*x*y y*sin(a)+(1-cos(a))*x*z |\n R = | z*sin(a)+(1-cos(a))*x*y 1 + (1-cos(a))*(y*y-1) -x*sin(a)+(1-cos(a))*y*z |\n | -y*sin(a)+(1-cos(a))*x*z x*sin(a)+(1-cos(a))*y*z 1 + (1-cos(a))*(z*z-1) |\n\n\n @param R: The 3x3 rotation matrix to update.\n @type R: 3x3 numpy array\n @param vector_orig: The unrotated vector defined in the reference frame.\n @type vector_orig: numpy array, len 3\n @param vector_fin: The rotated vector defined in the reference frame.\n @type vector_fin: numpy array, len 3\n \"\"\"\n # Python module imports.\n from math import acos, atan2, cos, pi, sin\n from numpy import array, cross, dot, float64, hypot, zeros\n from numpy.linalg import norm\n from random import gauss, uniform\n\n # Convert the vectors to unit vectors.\n vector_orig = old_div(vector_orig, norm(vector_orig))\n vector_fin = old_div(vector_fin, norm(vector_fin))\n\n # The rotation axis (normalised).\n axis = cross(vector_orig, vector_fin)\n axis_len = norm(axis)\n if axis_len != 0.0:\n axis = old_div(axis, axis_len)\n\n # Alias the axis coordinates.\n x = axis[0]\n y = axis[1]\n z = axis[2]\n\n # The rotation angle.\n angle = acos(dot(vector_orig, vector_fin))\n\n # Trig functions (only need to do this maths once!).\n ca = cos(angle)\n sa = sin(angle)\n\n # Calculate the rotation matrix elements.\n R[0, 0] = 1.0 + (1.0 - ca) * (x ** 2 - 1.0)\n R[0, 1] = -z * sa + (1.0 - ca) * x * y\n R[0, 2] = y * sa + (1.0 - ca) * x * z\n R[1, 0] = z * sa + (1.0 - ca) * x * y\n R[1, 1] = 1.0 + (1.0 - ca) * (y ** 2 - 1.0)\n R[1, 2] = -x * sa + (1.0 - ca) * y * z\n R[2, 0] = -y * sa + (1.0 - ca) * x * z\n R[2, 1] = x * sa + (1.0 - ca) * y * z\n R[2, 2] = 1.0 + (1.0 - ca) * (z ** 2 - 1.0)\n\n\ndef vector_vector_rotate(vec, axis, origin, theta):\n # Rotate vector\n temp = [0.0, 0.0, 0.0]\n\n temp[0] = (\n (\n origin[0] * (axis[1] * axis[1] + axis[2] * axis[2])\n - axis[0] * (origin[1] * axis[1] + origin[2] * axis[2] - dot(axis, vec))\n )\n * (1.0 - math.cos(theta))\n + vec[0] * math.cos(theta)\n + (\n -origin[2] * axis[1]\n + origin[1] * axis[2]\n - axis[2] * vec[1]\n + axis[1] * vec[2]\n )\n * math.sin(theta)\n )\n temp[1] = (\n (\n origin[1] * (axis[0] * axis[0] + axis[2] * axis[2])\n - axis[1] * (origin[0] * axis[0] + origin[2] * axis[2] - dot(axis, vec))\n )\n * (1.0 - math.cos(theta))\n + vec[1] * math.cos(theta)\n + (\n origin[2] * axis[0]\n - origin[0] * axis[2]\n + axis[2] * vec[0]\n - axis[0] * vec[2]\n )\n * math.sin(theta)\n )\n temp[2] = (\n (\n origin[2] * (axis[0] * axis[0] + axis[1] * axis[1])\n - axis[2] * (origin[0] * axis[0] + origin[1] * axis[1] - dot(axis, vec))\n )\n * (1.0 - math.cos(theta))\n + vec[2] * math.cos(theta)\n + (\n -origin[1] * axis[0]\n + origin[0] * axis[1]\n - axis[1] * vec[0]\n + axis[0] * vec[1]\n )\n * math.sin(theta)\n )\n\n return temp\n\n\ndef unit_vector(vector):\n return vector / np.linalg.norm(vector)\n\n\ndef angle_between(v1, v2):\n v1_u = unit_vector(v1)\n v2_u = unit_vector(v2)\n return np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))\n\n\ndef rotation_matrix(axis, theta):\n axis = np.asarray(axis)\n axis = axis / math.sqrt(np.dot(axis, axis))\n a = math.cos(theta / 2.0)\n b, c, d = -axis * math.sin(theta / 2.0)\n aa, bb, cc, dd = a * a, b * b, c * c, d * d\n bc, ad, ac, ab, bd, cd = b * c, a * d, a * c, a * b, b * d, c * d\n return np.array(\n [\n [aa + bb - cc - dd, 2 * (bc + ad), 2 * (bd - ac)],\n [2 * (bc - ad), aa + cc - bb - dd, 2 * (cd + ab)],\n [2 * (bd + ac), 2 * (cd - ab), aa + dd - bb - cc],\n ]\n )\n\n\ndef rotate(coord, axis, ang):\n c2 = np.dot(rotation_matrix(axis, ang), (coord[0], coord[1], coord[2]))\n return [c2[0], c2[1], c2[2]]\n\n\ndef turbine_thrust_interpolate(u_inf, thrust_coef_curve):\n wsc = np.zeros((2, len(thrust_coef_curve)))\n i = 0\n for t in thrust_coef_curve:\n wsc[0][i] = t[0]\n wsc[1][i] = t[1]\n i += 1\n\n tc = np.interp(u_inf, wsc[0], wsc[1])\n return tc\n\n\ndef turbine_speed_interpolate(u_inf, tip_speed_curve):\n wsc = np.zeros((2, len(tip_speed_curve)))\n i = 0\n for t in tip_speed_curve:\n wsc[0][i] = t[0]\n wsc[1][i] = t[1]\n i += 1\n\n ts = np.interp(u_inf, wsc[0], wsc[1])\n return ts\n\n\n# area of polygon specified as counter-clockwise vertices (x,y) where last = first\n\n\ndef polygon_area(x, y):\n a = 0.0\n for i in range(len(x) - 1):\n a += 0.5 * (x[i + 1] + x[i]) * (y[i + 1] - y[i])\n return a\n\n\ndef trapezoid(x, y):\n a = 0\n for i in range(len(x) - 1):\n a += 0.5 * (y[i + 1] + y[i]) * (x[i + 1] - x[i])\n return a\n\n\n# Optimal power coefficient as a function of (a function of) tip speed ratio\n# \"A Compact, Closed-form Solution for the Optimum, Ideal Wind Turbine\" (Peters, 2012)\n\n\ndef glauert_peters(y):\n p1 = 16.0 * (1.0 - 2.0 * y) / (27.0 * (1.0 + y / 4.0))\n p2 = old_div(\n (math.log(2.0 * y) + (1.0 - 2.0 * y) + 0.5 * (1.0 - 2.0 * y) ** 2),\n ((1.0 - 2.0 * y) ** 3),\n )\n p3 = (\n 1.0\n + (457.0 / 1280.0) * y\n + (51.0 / 640.0) * y ** 2\n + y ** 3 / 160.0\n + 3.0 / 2.0 * y * p2\n )\n power_coeff = p1 * p3\n return power_coeff\n\n\n# Golden section search: Given f with a single local max in [a,b], gss returns interval [c,d] with d-c <= tol.\n\n\ndef gss(f, a, b, tol=1e-5):\n invphi = old_div((math.sqrt(5) - 1), 2) # 1/phi\n invphi2 = old_div((3 - math.sqrt(5)), 2) # 1/phi^2\n (a, b) = (min(a, b), max(a, b))\n h = b - a\n if h <= tol:\n return (a, b)\n n = int(math.ceil(old_div(math.log(old_div(tol, h)), math.log(invphi))))\n c = a + invphi2 * h\n d = a + invphi * h\n yc = f(c)[0]\n yd = f(d)[0]\n for k in range(n - 1):\n if yc > yd:\n b = d\n d = c\n yd = yc\n h = invphi * h\n c = a + invphi2 * h\n yc = f(c)[0]\n else:\n a = c\n c = d\n yc = yd\n h = invphi * h\n d = a + invphi * h\n yd = f(d)[0]\n if yc > yd:\n return (a, d)\n else:\n return (c, b)\n\n\ndef create_annulus(turbine_zone_dict):\n from mpi4py import MPI\n from numpy import zeros, array, dot, linalg, cross\n\n if \"verbose\" in turbine_zone_dict:\n verbose = turbine_zone_dict[\"verbose\"]\n else:\n verbose = False\n\n if \"number of segments\" in turbine_zone_dict:\n number_of_segments = turbine_zone_dict[\"number of segments\"]\n else:\n if MPI.COMM_WORLD.Get_rank() == 0 and verbose:\n print(\"NO NUMBER OF SEGMENTS SPECIFIED - SETTING TO DEFAULT 12\")\n number_of_segments = 12\n\n if \"inner radius\" in turbine_zone_dict:\n ri = turbine_zone_dict[\"inner radius\"]\n else:\n if MPI.COMM_WORLD.Get_rank() == 0:\n print(\"NO INNER RADIUS SPECIFIED\")\n\n if \"outer radius\" in turbine_zone_dict:\n ro = turbine_zone_dict[\"outer radius\"]\n else:\n if MPI.COMM_WORLD.Get_rank() == 0:\n print(\"NO OUTER RADIUS SPECIFIED\")\n\n disc_centre = turbine_zone_dict[\"centre\"]\n disc_normal = turbine_zone_dict[\"normal\"]\n\n rotor_swept_area = (math.pi * ro * ro) - (math.pi * ri * ri)\n\n annulus = []\n dtheta = math.radians(360.0 / number_of_segments)\n theta = 0.0\n total_area = 0.0\n for i in range(number_of_segments):\n r = ri\n while r < ro:\n dr = dtheta * max(r,0.01*ro) / (1.0 - 0.5 * dtheta)\n max_r = r + dr\n if max_r > ro:\n dr = ro - r\n rp = r + 0.5 * dr\n da = dtheta * rp * dr\n disc_theta = i * dtheta + 0.5 * dtheta\n\n disc_pt = np.array(\n [rp * math.cos(disc_theta), rp * math.sin(disc_theta), 0.0]\n )\n\n # Rotate so that z points in the direction of the normal\n R = np.zeros((3, 3))\n vector_orig = np.array([0.0, 0.0, 1.0])\n vector_fin = np.zeros(3)\n for j in range(3):\n vector_fin[j] = disc_normal[j]\n R_2vect(R, vector_orig, vector_fin)\n\n disc_pt = dot(R, disc_pt)\n\n # translate to disc centre\n for j in range(3):\n disc_pt[j] += disc_centre[j]\n\n annulus.append(\n (r, dr, i * dtheta, dtheta, disc_pt[0], disc_pt[1], disc_pt[2])\n )\n total_area += da\n r = r + dr\n\n return annulus\n\n\ndef zone_default(dict, key, default_val, verbose=True):\n from mpi4py import MPI\n\n if key in dict:\n value = dict[key]\n else:\n value = default_val\n dict[key] = default_val\n if MPI.COMM_WORLD.Get_rank() == 0 and verbose:\n if \"name\" in dict:\n print(\n \"Turbine zone \"\n + str(dict[\"name\"])\n + \" missing: \"\n + str(key)\n + \" - setting to \"\n + str(default_val)\n )\n else:\n print(\n \"Turbine zone missing name and missing: \"\n + str(key)\n + \" - setting to \"\n + str(default_val)\n )\n return value\n\n\ndef calculate_aerofoil_section_area(tzd):\n upper = zone_default(\n tzd[\"aerofoil profile\"],\n \"upper surface\",\n [[0.0, 0.0], [0.5, 0.1], [1.0, 0.0]],\n True,\n )\n lower = zone_default(\n tzd[\"aerofoil profile\"],\n \"lower surface\",\n [[0.0, 0.0], [0.5, -0.1], [1.0, 0.0]],\n True,\n )\n x = np.concatenate((np.array(lower).T[0], np.array(upper).T[0][::-1][1:]))\n y = np.concatenate((np.array(lower).T[1], np.array(upper).T[1][::-1][1:]))\n aerofoil_section_area = polygon_area(x, y)\n tzd[\"aerofoil section area\"] = aerofoil_section_area\n return aerofoil_section_area\n\n\ndef calculate_rotor_moment(tzd):\n from mpi4py import MPI\n\n nblades = zone_default(tzd, \"number of blades\", 3, True)\n blade_material_density = zone_default(\n tzd, \"mean blade material density\", 200.0, True\n )\n if \"aerofoil section area\" in tzd:\n aerofoil_section_area = tzd[\"aerofoil section area\"]\n else:\n aerofoil_section_area = calculate_aerofoil_section_area(tzd)\n blade_chord = zone_default(tzd, \"blade chord\", [[0.0, 0.1], [1.0, 0.1]], True)\n ri = zone_default(tzd, \"inner radius\", 1.0, True)\n ro = zone_default(tzd, \"outer radius\", 30.0, True)\n rotor_moment = 0.0\n for r in np.linspace(ri, ro, 100):\n dr = (ro - ri) / 100.0\n c = (\n np.interp(r / ro, np.array(blade_chord).T[0], np.array(blade_chord).T[1])\n * ro\n )\n rotor_moment += r * r * c * c * dr\n rotor_moment = (\n rotor_moment * blade_material_density * aerofoil_section_area * nblades\n )\n tzd[\"rotor moment of inertia\"] = rotor_moment\n if MPI.COMM_WORLD.Get_rank() == 0:\n print(\"rotor moment of inertia = \" + str(rotor_moment))\n return rotor_moment\n\n\ndef create_turbine_segments(\n turbine_zone_dict,\n v0,\n v1,\n v2,\n density,\n turbine_name_dict={},\n turbine_name=\"\",\n annulusVel=None,\n annulusTi=None,\n):\n from mpi4py import MPI\n\n verbose = zone_default(turbine_zone_dict, \"verbose\", True, False)\n number_of_segments = zone_default(\n turbine_zone_dict, \"number of segments\", 12, verbose\n )\n rotation_direction = zone_default(\n turbine_zone_dict, \"rotation direction\", \"clockwise\", verbose\n ) # when viewed from the front\n ri = zone_default(turbine_zone_dict, \"inner radius\", 1.0, verbose)\n ro = zone_default(turbine_zone_dict, \"outer radius\", 30.0, verbose)\n rotor_swept_area = math.pi * (ro * ro - ri * ri)\n disc_normal = zone_default(turbine_zone_dict, \"normal\", [1.0, 0.0, 0.0], verbose)\n disc_centre = zone_default(turbine_zone_dict, \"centre\", [0.0, 0.0, 0.0], verbose)\n up = zone_default(turbine_zone_dict, \"up\", [0.0, 0.0, 1.0], verbose)\n yaw = zone_default(turbine_zone_dict, \"yaw\", 0.0, verbose)\n auto_yaw = zone_default(turbine_zone_dict, \"auto yaw\", False, verbose)\n tilt = zone_default(turbine_zone_dict, \"tilt\", 0.0, verbose)\n inertia = zone_default(turbine_zone_dict, \"inertia\", False, verbose)\n model = zone_default(turbine_zone_dict, \"model\", \"simple\", verbose)\n status = zone_default(turbine_zone_dict, \"status\", \"on\", verbose)\n use_glauert_power = zone_default(\n turbine_zone_dict, \"use glauert power\", False, verbose\n )\n if MPI.COMM_WORLD.Get_rank() == 0 and verbose:\n print(model)\n induction = \"induction\" in model\n bet = \"blade element theory\" in model\n simple = \"simple\" in model or \"direct\" in model\n bet_prop = \"blade element propellor\" in model\n if not (induction or bet or simple or bet_prop):\n if MPI.COMM_WORLD.Get_rank() == 0:\n print(\"NO MODEL SPECIFIED - DEFAULT TO SIMPLE MODEL\")\n simple = True\n\n annulus_metrics = create_annulus(turbine_zone_dict)\n global bet_kernel_calls\n\n if inertia:\n dt = zone_default(turbine_zone_dict, \"dt\", 0.1, verbose)\n if \"rotor moment of inertia\" in turbine_zone_dict:\n rotor_moment = turbine_zone_dict[\"rotor moment of inertia\"]\n else:\n rotor_moment = calculate_rotor_moment(turbine_zone_dict)\n\n if bet_prop:\n temp = np.reshape(annulusVel, (-1, 3)).T\n u_ref = math.sqrt(\n np.mean(temp[0]) ** 2 + np.mean(temp[1]) ** 2 + np.mean(temp[2]) ** 2\n )\n nblades = zone_default(turbine_zone_dict, \"number of blades\", 3, verbose)\n aerofoil_cl = zone_default(\n turbine_zone_dict, \"aerofoil cl\", [[-90.0, 0.0], [90.0, 0.0]], verbose\n )\n aerofoil_cd = zone_default(\n turbine_zone_dict, \"aerofoil cd\", [[-90.0, 1.0], [90.0, 1.0]], verbose\n )\n blade_chord = zone_default(\n turbine_zone_dict, \"blade chord\", [[0.0, 0.1], [1.0, 0.1]], verbose\n )\n blade_twist = zone_default(\n turbine_zone_dict, \"blade twist\", [[0.0, 25.0], [1.0, 0.0]], verbose\n ) # degrees\n omega = zone_default(turbine_zone_dict, \"omega\", 0.0, verbose)\n ts = omega * ro / u_ref\n tip_loss_correction = \"tip loss correction\" in turbine_zone_dict\n if tip_loss_correction:\n tip_loss_correction_model = zone_default(\n turbine_zone_dict, \"tip loss correction\", \"none\", verbose\n )\n tip_loss_correction_r = zone_default(\n turbine_zone_dict, \"tip loss correction radius\", 0.0, verbose\n )\n elif bet:\n bet_kernel_calls = 0\n temp = np.reshape(annulusVel, (-1, 3)).T\n u_ref = math.sqrt(\n np.mean(temp[0]) ** 2 + np.mean(temp[1]) ** 2 + np.mean(temp[2]) ** 2\n )\n nblades = zone_default(turbine_zone_dict, \"number of blades\", 3, verbose)\n aerofoil_cl = zone_default(\n turbine_zone_dict, \"aerofoil cl\", [[-90.0, 0.0], [90.0, 0.0]], verbose\n )\n aerofoil_cd = zone_default(\n turbine_zone_dict, \"aerofoil cd\", [[-90.0, 1.0], [90.0, 1.0]], verbose\n )\n blade_chord = zone_default(\n turbine_zone_dict, \"blade chord\", [[0.0, 0.1], [1.0, 0.1]], verbose\n )\n blade_twist = zone_default(\n turbine_zone_dict, \"blade twist\", [[0.0, 25.0], [1.0, 0.0]], verbose\n ) # degrees\n blade_pitch_range = zone_default(\n turbine_zone_dict, \"blade pitch range\", [-10.0, 10.0], verbose\n ) # degrees\n blade_pitch_step = zone_default(\n turbine_zone_dict, \"blade pitch step\", 1.0, verbose\n ) # degrees\n blade_pitch = zone_default(\n turbine_zone_dict, \"blade pitch\", 0.0, verbose\n ) # degrees\n blade_pitch_tol = zone_default(\n turbine_zone_dict, \"blade pitch tol\", 0.01, verbose\n ) # degrees\n dt = zone_default(turbine_zone_dict, \"dt\", 0.1, verbose) # seconds\n rated_power = zone_default(\n turbine_zone_dict, \"rated power\", 2.3e6, verbose\n ) # Watts\n # m/s environmental limit (2009)\n tip_speed_limit = zone_default(\n turbine_zone_dict, \"tip speed limit\", 80.0, verbose\n )\n # turbulence intensity range [0,1]\n damage_ti = zone_default(turbine_zone_dict, \"damage ti\", 0.15, verbose)\n damage_speed = zone_default(\n turbine_zone_dict, \"damage speed\", 10.0, verbose\n ) # m/s\n friction_loss = zone_default(\n turbine_zone_dict, \"friction loss\", 0.01, verbose\n ) # friction slow down\n cut_in_speed = zone_default(\n turbine_zone_dict, \"cut in speed\", 1.0, verbose\n ) # m/s\n cut_out_speed = zone_default(\n turbine_zone_dict, \"cut out speed\", 99.0, verbose\n ) # m/s\n thrust_factor = zone_default(turbine_zone_dict, \"thrust factor\", 1.0, verbose)\n omega = zone_default(turbine_zone_dict, \"omega\", 0.0, verbose)\n tip_loss_correction = \"tip loss correction\" in turbine_zone_dict\n if tip_loss_correction:\n tip_loss_correction_model = zone_default(\n turbine_zone_dict, \"tip loss correction\", \"none\", verbose\n )\n tip_loss_correction_r = zone_default(\n turbine_zone_dict, \"tip loss correction radius\", 0.0, verbose\n )\n if (u_ref < cut_in_speed) or (u_ref > cut_out_speed):\n omega = 0.0\n ts = omega * ro / u_ref\n if induction:\n if MPI.COMM_WORLD.Get_rank() == 0:\n print(\"CANNOT USE BLADE ELEMENT THEORY WITH INDUCTION MODEL\")\n induction = False\n else:\n power_model = zone_default(turbine_zone_dict, \"power model\", None, False)\n if power_model == \"glauert\":\n use_glauert_power = True\n u_ref = math.sqrt(v0 * v0 + v1 * v1 + v2 * v2)\n if \"thrust coefficient curve\" in turbine_zone_dict:\n tc = np.interp(\n u_ref,\n np.array(turbine_zone_dict[\"thrust coefficient curve\"]).T[0],\n np.array(turbine_zone_dict[\"thrust coefficient curve\"]).T[1],\n )\n elif \"thrust coefficient\" in turbine_zone_dict:\n tc = turbine_zone_dict[\"thrust coefficient\"]\n else:\n if MPI.COMM_WORLD.Get_rank() == 0:\n print(\"NO THRUST COEFFICIENT SPECIFIED\")\n\n if \"tip speed ratio curve\" in turbine_zone_dict:\n ts = np.interp(\n u_ref,\n np.array(turbine_zone_dict[\"tip speed ratio curve\"]).T[0],\n np.array(turbine_zone_dict[\"tip speed ratio curve\"]).T[1],\n )\n elif \"tip speed ratio\" in turbine_zone_dict:\n ts = turbine_zone_dict[\"tip speed ratio\"]\n else:\n if MPI.COMM_WORLD.Get_rank() == 0:\n print(\"NO TIP SPEED RATIO SPECIFIED\")\n omega = old_div(ts * u_ref, ro)\n\n if induction:\n u_infty = u_ref\n else:\n # Assuming 1D momentum theory and the Betz limit\n u_infty = (3.0 / 2.0) * u_ref\n\n betz_power = 0.5 * density * u_infty ** 3 * rotor_swept_area * (16.0 / 27.0)\n if use_glauert_power:\n if \"glauert power curve\" not in turbine_zone_dict:\n gp_curve = []\n ts_vals = np.arange(0.0, 20.0, 0.1)\n b_vals = np.arange(0.3334, 0.5, 0.0001)\n peters_lr_vals = []\n for b in b_vals:\n peters_lr_vals.append(\n old_div(\n math.sqrt(1.0 + b) * (1.0 - 2.0 * b), math.sqrt(3.0 * b - 1.0)\n )\n )\n for ts_val in ts_vals:\n b0 = np.interp(ts, peters_lr_vals[::-1], b_vals[::-1])\n y = 3.0 * b0 - 1.0\n gp = 0.5 * density * u_infty ** 3 * rotor_swept_area * glauert_peters(y)\n gp.append([ts_val, gp])\n turbine_zone_dict[\"glauert power curve\"] = gp\n glauert_power = np.interp(\n ts,\n turbine_zone_dict[\"glauert power curve\"].T[0],\n turbine_zone_dict[\"glauert power curve\"].T[1],\n )\n\n if verbose and (MPI.COMM_WORLD.Get_rank() == 0):\n print(\"tip speed ratio = \" + str(ts))\n print(\"rotational speed = \" + str(omega) + \" rad/s\")\n print(\"wind speed = \" + str(u_ref) + \" m/s\")\n print(\"rotor swept area = \" + str(rotor_swept_area) + \" m^2\")\n print(\"density = \" + str(density) + \" kg/m^3\")\n print(\"number of segments = \" + str(number_of_segments))\n\n if not bet_prop:\n\n def yaw_control(yaw, tilt, disc_normal, up, auto_yaw, annulusVel):\n if auto_yaw:\n temp = np.reshape(annulusVel, (-1, 3)).T\n u_normal = [-np.mean(temp[0]), -np.mean(temp[1]), -np.mean(temp[2])]\n ang = angle_between(u_normal, disc_normal)\n if np.degrees(ang) > 10.0:\n if MPI.COMM_WORLD.Get_rank() == 0:\n print(\n \"Auto_yaw: geometric disc normal and local flow angle too large: \"\n + str(np.degrees(ang))\n )\n else:\n if MPI.COMM_WORLD.Get_rank() == 0 and verbose:\n print(\n \"Auto-yaw: set disc normal to disc-averaged velocity normal\"\n )\n yaw = math.degrees(angle_between(disc_normal, u_normal))\n disc_normal = u_normal\n else:\n disc_normal = rotate(disc_normal, up, math.radians(yaw))\n tilt_axis = np.cross(disc_normal, up)\n disc_normal = rotate(disc_normal, tilt_axis, math.radians(tilt))\n if np.dot(disc_normal, up) < 0.0 and MPI.COMM_WORLD.Get_rank() == 0:\n print(\"Tilting wrong way!\")\n return yaw, unit_vector(disc_normal)\n\n yaw, disc_normal = yaw_control(yaw, tilt, disc_normal, up, auto_yaw, annulusVel)\n if (MPI.COMM_WORLD.Get_rank() == 0) and verbose:\n print(\"disc_normal = \" + str(disc_normal))\n\n if bet_prop:\n annulus = []\n theta = 0.0\n total_area = 0.0\n total_thrust = 0.0\n total_torque = 0.0\n angular_induction = 0.0\n\n avindex = 0\n # annulus_metrics = (r, dr, i * dtheta, dtheta, disc_pt[0], disc_pt[1], disc_pt[2])\n for am in annulus_metrics:\n rp = am[0] + 0.5 * am[1]\n da = am[3] * rp * am[1]\n ulocal = np.reshape(annulusVel, (-1, 3))[avindex]\n rvec = unit_vector(\n [am[4] - disc_centre[0], am[5] - disc_centre[1], am[6] - disc_centre[2]]\n )\n if rotation_direction == \"clockwise\":\n local_omega_vec = np.cross(rvec, disc_normal)\n else:\n local_omega_vec = np.cross(disc_normal, rvec)\n v_n = -np.dot(ulocal, disc_normal)\n v_r = np.dot(ulocal, local_omega_vec)\n if (abs((rp * omega) + v_r)) > 0.0:\n theta_rel = math.atan(v_n / ((rp * omega) - v_r))\n else:\n theta_rel = math.pi / 2.0\n urel = math.sqrt((rp * omega - v_r) ** 2 + v_n ** 2)\n beta_twist = np.interp(\n old_div(rp, ro), np.array(blade_twist).T[0], np.array(blade_twist).T[1]\n )\n chord = (\n np.interp(\n old_div(rp, ro),\n np.array(blade_chord).T[0],\n np.array(blade_chord).T[1],\n )\n * ro\n )\n beta = math.radians(beta_twist)\n alpha = beta - theta_rel\n cl = np.interp(\n math.degrees(alpha),\n np.array(aerofoil_cl).T[0],\n np.array(aerofoil_cl).T[1],\n )\n cd = np.interp(\n math.degrees(alpha),\n np.array(aerofoil_cd).T[0],\n np.array(aerofoil_cd).T[1],\n )\n if tip_loss_correction:\n rstar = tip_loss_correction_r * ro\n if rp > rstar:\n tip_loss_factor = math.sqrt(\n 1.0 - ((rp - rstar) / (ro - rstar)) ** 2\n )\n cl = cl * tip_loss_factor\n cd = cd * tip_loss_factor\n f_L = cl * 0.5 * density * urel ** 2 * chord\n f_D = cd * 0.5 * density * urel ** 2 * chord\n F_L = old_div(nblades, (2.0 * math.pi * rp)) * f_L\n F_D = old_div(nblades, (2.0 * math.pi * rp)) * f_D\n dt = -(F_L * math.cos(theta_rel) - F_D * math.sin(theta_rel)) * da\n dq = -(F_L * math.sin(theta_rel) + F_D * math.cos(theta_rel)) * da\n if rotation_direction == \"anticlockwise\":\n dq = -dq\n annulus.append((dt, dq, am[0], am[1], am[2], am[3]))\n total_area += da\n total_thrust += dt\n total_torque += math.fabs(dq * rp)\n avindex = avindex + 1\n total_power = total_torque * omega\n\n elif bet:\n bet_kernel_calls = 0\n\n # pre-populate the beta_twist and chord values\n for i in range(len(annulus_metrics)):\n rp = annulus_metrics[i][0] + 0.5 * annulus_metrics[i][1]\n beta_twist = np.interp(\n (rp / ro), np.array(blade_twist).T[0], np.array(blade_twist).T[1]\n )\n chord = (\n np.interp(\n (rp / ro), np.array(blade_chord).T[0], np.array(blade_chord).T[1]\n )\n * ro\n )\n annulus_metrics[i] = annulus_metrics[i] + (beta_twist, chord)\n\n annulus = len(annulus_metrics) * [(0.0, 0.0, 0.0, 0.0, 0.0, 0.0)]\n\n def bet_kernel(beta_pitch):\n global bet_kernel_calls\n bet_kernel_calls = bet_kernel_calls + 1\n total_area = 0.0\n total_thrust = 0.0\n total_torque = 0.0\n angular_induction = 0.0\n avindex = 0\n # check whether any segments are at negative angle of attack.\n alpha_positive = True\n # annulus_metrics = (r, dr, i * dtheta, dtheta, disc_pt[0], disc_pt[1], disc_pt[2], beta_twist, chord)\n for am in annulus_metrics:\n rp = am[0] + 0.5 * am[1]\n da = am[3] * rp * am[1]\n tilt_axis = np.cross(up, disc_normal)\n rvec0 = rotate(up, tilt_axis, math.radians(tilt))\n rvec = unit_vector(\n [\n am[4] - disc_centre[0],\n am[5] - disc_centre[1],\n am[6] - disc_centre[2],\n ]\n )\n ulocal = np.reshape(annulusVel, (-1, 3))[avindex]\n if rotation_direction == \"clockwise\":\n local_omega_vec = np.cross(rvec, disc_normal)\n else:\n local_omega_vec = np.cross(disc_normal, rvec)\n omega_air = np.dot(local_omega_vec, ulocal) / rp\n omega_rel = omega - omega_air\n u_ref_local = -np.dot(ulocal, disc_normal)\n urel = math.sqrt((rp * omega_rel) ** 2 + u_ref_local ** 2)\n if (rp * omega_rel) > 0.0:\n theta_rel = math.atan(old_div(u_ref_local, (rp * omega_rel)))\n else:\n theta_rel = math.pi / 2.0\n beta_twist = am[7]\n chord = am[8]\n beta = math.radians(beta_pitch + beta_twist)\n alpha = theta_rel - beta\n if alpha < 0.0:\n alpha_positive = False\n cl = np.interp(\n math.degrees(alpha),\n np.array(aerofoil_cl).T[0],\n np.array(aerofoil_cl).T[1],\n )\n if tip_loss_correction:\n if tip_loss_correction_model == \"elliptic\":\n tlc = math.sqrt(1.0 - (rp / ro) ** 2)\n elif tip_loss_correction_model == \"acos-fit\":\n tlc = (2.0 / math.pi) * math.acos(\n math.exp(-63.0 * (1.0 - (rp / ro) ** 2))\n )\n elif tip_loss_correction_model == \"acos shift-fit\":\n tlc = (2.0 / math.pi) * math.acos(\n math.exp(-48.0 * (1.0 - (rp / ro) ** 2) - 0.5)\n )\n elif tip_loss_correction_model == \"f-fit\":\n tlc = 1.0 - 2.5 * ((1.0 - (rp / ro) ** 2) ** 0.39) / (\n (2.0 - (rp / ro) ** 2) ** 64\n )\n else:\n tlc = 1.0\n cl = cl * tlc # only apply to lift, not drag.\n cd = np.interp(\n math.degrees(alpha),\n np.array(aerofoil_cd).T[0],\n np.array(aerofoil_cd).T[1],\n )\n f_L = cl * 0.5 * density * urel ** 2 * chord\n f_D = cd * 0.5 * density * urel ** 2 * chord\n F_L = old_div(nblades, (2.0 * math.pi * rp)) * f_L\n F_D = old_div(nblades, (2.0 * math.pi * rp)) * f_D\n dt = (\n (F_L * math.cos(theta_rel) + F_D * math.sin(theta_rel)) * da\n ) * thrust_factor\n dq = -(F_L * math.sin(theta_rel) - F_D * math.cos(theta_rel)) * da\n if rotation_direction == \"clockwise\":\n dq = -dq\n annulus[avindex] = (dt, dq, am[0], am[1], am[2], am[3])\n total_area += da\n total_thrust += dt\n total_torque += math.fabs(dq * rp)\n angular_induction += omega_air * da\n avindex = avindex + 1\n if not alpha_positive:\n if MPI.COMM_WORLD.Get_rank() == 0 and verbose:\n print(\"WARNING - negative angle of attack \")\n angular_induction = angular_induction / total_area\n return total_torque, total_area, total_thrust, angular_induction, annulus\n\n def turbine_controller(\n omega,\n rated_power,\n tip_speed_limit,\n damage_ti,\n damage_speed,\n status,\n u_ref,\n cut_in_speed,\n cut_out_speed,\n blade_pitch,\n blade_pitch_step,\n ):\n if status == \"off\":\n omega = 0.0\n if (u_ref < cut_in_speed) or (u_ref > cut_out_speed):\n omega = 0.0\n # Make sure we are not exceeding the blade tip speed limit\n omega = min(omega, tip_speed_limit / ro) * (1.0 - friction_loss)\n # work out whether we are feathering the blades to shed power:\n blade_pitch_low = max(blade_pitch - blade_pitch_step, blade_pitch_range[0])\n blade_pitch_high = min(blade_pitch + blade_pitch_step, blade_pitch_range[1])\n blade_pitch_opt = np.min(\n gss(bet_kernel, blade_pitch_low, blade_pitch_high, blade_pitch_tol)\n )\n if MPI.COMM_WORLD.Get_rank() == 0 and verbose:\n print(\"Blade pitch opt = \" + str(blade_pitch_opt))\n maximum_torque = bet_kernel(blade_pitch_opt)[0]\n if MPI.COMM_WORLD.Get_rank() == 0 and verbose:\n print(\"Maximum torque = \" + str(maximum_torque))\n if maximum_torque * omega > rated_power:\n if MPI.COMM_WORLD.Get_rank() == 0 and verbose:\n print(\"Feathering to reduce power below rated power\")\n # Construct a power curve against blade pitch for the current rate of rotation\n blade_pitch_curve = []\n for b in np.arange(blade_pitch_low, blade_pitch_opt, blade_pitch_tol):\n blade_pitch_curve.append([b, omega * bet_kernel(b)[0]])\n if (MPI.COMM_WORLD.Get_rank() == 0) and verbose:\n print(\n \"Points on blade pitch curve : \" + str(len(blade_pitch_curve))\n )\n if len(blade_pitch_curve) > 1:\n # Look up the blade pitch that recovers the rated power\n blade_pitch = np.interp(\n rated_power,\n np.array(blade_pitch_curve).T[1],\n np.array(blade_pitch_curve).T[0],\n )\n else:\n blade_pitch = blade_pitch_low\n if (MPI.COMM_WORLD.Get_rank() == 0) and verbose:\n print(\"Rated power blade pitch = : \" + str(blade_pitch))\n total_torque, total_area, total_thrust, angular_induction, annulus = bet_kernel(\n blade_pitch\n )\n torque_blades = 0.0\n else:\n # Use half of the available torque to accelerate the blades and half to provide power to the generator\n # unless this exceeds a 5% increase in the rate of rotation or the tip speed limit or the rated power.\n blade_pitch = blade_pitch_opt\n total_torque, total_area, total_thrust, angular_induction, annulus = bet_kernel(\n blade_pitch\n )\n torque_blades = total_torque / 2.0 # Completely arbitrary.\n # modfy the tip speed limit if there is an rpm ramp:\n if \"rpm ramp\" in turbine_zone_dict:\n rr = np.asarray(turbine_zone_dict[\"rpm ramp\"])\n if (u_ref > cut_in_speed) and (u_ref < rr[1][1]):\n tip_speed_limit = min(\n tip_speed_limit,\n ro\n * np.interp(u_ref, rr.T[0], rr.T[1])\n * 2.0\n * np.pi\n / 60.0,\n )\n if MPI.COMM_WORLD.Get_rank() == 0:\n print(\n \"RPM LIMIT: tip speed limit = \" + str(tip_speed_limit)\n )\n if rotor_moment > 0.0:\n if MPI.COMM_WORLD.Get_rank() == 0 and verbose:\n print(\"BET - Rotor Moment Model\")\n torque_blades = min(\n torque_blades,\n ((tip_speed_limit / ro) - omega) * rotor_moment / dt,\n )\n omega = omega + (torque_blades * dt) / rotor_moment\n else:\n if MPI.COMM_WORLD.Get_rank() == 0 and verbose:\n print(\"BET - USING ZERO INERTIA MODEL\")\n omega = omega * 1.1 # Limit the increase to 10%\n # Do not allow the rotor to over-speed\n omega = min(omega, tip_speed_limit / ro)\n torque_blades = 0.0\n # Do not exceed the (approximated) rated power\n torque_power = total_torque - torque_blades\n if torque_power > 0.0:\n omega = min(omega, rated_power / torque_power)\n # work out whether we are stowing the blades to prevent damage\n damage_alert = False\n if (MPI.COMM_WORLD.Get_rank() == 0) and verbose:\n print(\"Maximum onset TI: \" + str(np.max(annulusTi)))\n for aindex in range(len(np.reshape(annulusVel, (-1, 3)))):\n ulocal = np.reshape(annulusVel, (-1, 3))[aindex]\n ulocalmag = math.sqrt(ulocal[0] ** 2 + ulocal[1] ** 2 + ulocal[2] ** 2)\n tilocal = annulusTi[aindex]\n if (ulocalmag > damage_speed) and (tilocal > damage_ti):\n damage_alert = True\n if damage_alert:\n if MPI.COMM_WORLD.Get_rank() == 0 and verbose:\n print(\"Damage alert detected - stowing turbine\")\n if omega > 0.1:\n omega = omega * 0.9 # slow down the turbine\n else:\n omega = 0.0\n torque_blades = 0.0\n torque_power = total_torque - torque_blades\n return (\n blade_pitch,\n omega,\n torque_blades,\n torque_power,\n total_torque,\n total_area,\n total_thrust,\n angular_induction,\n annulus,\n )\n\n blade_pitch, omega, torque_blades, torque_power, total_torque, total_area, total_thrust, angular_induction, annulus = turbine_controller(\n omega,\n rated_power,\n tip_speed_limit,\n damage_ti,\n damage_speed,\n status,\n u_ref,\n cut_in_speed,\n cut_out_speed,\n blade_pitch,\n blade_pitch_step,\n )\n\n turbine_power = torque_power * math.fabs(omega)\n total_power = total_torque * omega\n\n turbine_zone_dict[\"omega\"] = omega\n turbine_zone_dict[\"blade pitch\"] = blade_pitch\n turbine_zone_dict[\"yaw\"] = yaw\n\n if MPI.COMM_WORLD.Get_rank() == 0:\n turbine_name_dict[turbine_name + \"_tilt\"] = tilt\n turbine_name_dict[turbine_name + \"_yaw\"] = yaw\n turbine_name_dict[turbine_name + \"_blade_pitch\"] = blade_pitch\n turbine_name_dict[turbine_name + \"_ang_ind\"] = angular_induction / omega\n turbine_name_dict[turbine_name + \"_thrust\"] = total_thrust\n\n if verbose:\n print(\"status = \" + str(status))\n print(\"rotation rate = \" + str(omega) + \" radians / sec\")\n print(\"blade pitch = \" + str(blade_pitch) + \" degrees\")\n print(\"torque power = \" + str(torque_power) + \" Joules/rad\")\n print(\"torque blades = \" + str(torque_blades) + \" Joules/rad\")\n print(\n \"angular induction = \"\n + str(100.0 * angular_induction / omega)\n + \"%\"\n )\n print(\"bet kernel calls = \" + str(bet_kernel_calls))\n\n # TODO - add turbulence source in wake of turbine.\n # TODO - add restart capability (read data from CSV report file)\n\n else:\n if power_model == \"betz\":\n power = betz_power\n elif power_model == \"glauert\":\n power = glauert_power\n elif \"turbine power curve\" in turbine_zone_dict:\n power = np.interp(\n u_ref,\n np.array(turbine_zone_dict[\"turbine power curve\"]).T[0],\n np.array(turbine_zone_dict[\"turbine power curve\"]).T[1],\n )\n elif \"turbine power\" in turbine_zone_dict:\n power = turbine_zone_dict[\"turbine power\"]\n else:\n if MPI.COMM_WORLD.Get_rank() == 0:\n print(\"NO POWER MODEL SPECIFIED - USING BETZ LIMIT\")\n power = betz_power\n annulus = []\n # Induction assumes that u_ref is u_inf. Direct (Simple) assumes that u_ref is at disk.\n if induction:\n # Momentum theory: Ct = 4 * a * ( 1 - a), Cp = 4 * a * ( 1 - a)^2, Betz Optimal rotor: a = 1/3\n if tc > 0.999:\n print(\"INDUCTION MODEL TC CANNOT EXCEED 1.0: \" + str(tc))\n ind_fac = old_div(\n (4.0 - math.sqrt(4.0 * 4.0 - 4.0 * 4.0 * tc)), (2.0 * 4.0)\n )\n if verbose and (MPI.COMM_WORLD.Get_rank() == 0):\n print(\"Induction factor: \", str(ind_fac))\n dtheta = math.radians(360.0 / number_of_segments)\n target_torque = old_div(power, omega)\n theta = 0.0\n total_area = 0.0\n total_thrust = 0.0\n total_torque = 0.0\n for i in range(number_of_segments):\n r = ri\n while r < ro:\n dr = old_div(dtheta * max(r,0.01*ro), (1.0 - 0.5 * dtheta))\n max_r = r + dr\n if max_r > ro:\n dr = ro - r\n rp = r + 0.5 * dr\n da = dtheta * rp * dr\n if induction:\n dt = (\n 0.5\n * density\n * u_ref\n * u_ref\n * da\n * 4.0\n * ind_fac\n * (1.0 - ind_fac)\n )\n lambda_r = old_div(rp * omega, u_ref)\n if lambda_r > 0.0:\n ang_ind_fac = -0.5 + math.sqrt(\n 0.25 + old_div(ind_fac * (1.0 - ind_fac), lambda_r ** 2)\n )\n else:\n ang_ind_fac = 0.0\n dq = (\n 4.0\n * ang_ind_fac\n * (1.0 - ind_fac)\n * 0.5\n * density\n * u_ref\n * omega\n * rp\n * rp\n * da\n / rp\n )\n else:\n dt = 0.5 * density * u_ref * u_ref * da * tc\n dq = old_div((target_torque * da), (rotor_swept_area * rp))\n if rotation_direction == \"anticlockwise\":\n dq = -dq\n annulus.append((dt, dq, r, dr, i * dtheta, dtheta))\n total_area += da\n total_thrust += dt\n total_torque += math.fabs(dq * rp)\n r = r + dr\n specified_thrust = 0.5 * rotor_swept_area * density * u_ref * u_ref * tc\n\n if MPI.COMM_WORLD.Get_rank() == 0:\n if verbose:\n print(\"thrust coefficient [specified] = \" + str(tc))\n print(\"thrust [specified] = \" + str(specified_thrust))\n print(\"model specified power = \" + str(power) + \" Watts\")\n print(\"target torque = \" + str(target_torque) + \" Joules/rad\")\n\n if MPI.COMM_WORLD.Get_rank() == 0:\n total_power = total_torque * omega\n turbine_name_dict[turbine_name + \"_power\"] = total_power\n turbine_name_dict[turbine_name + \"_uref\"] = u_ref\n turbine_name_dict[turbine_name + \"_omega\"] = omega\n turbine_name_dict[turbine_name + \"_thrust\"] = total_thrust\n\n if verbose:\n print(\"total area = \" + str(total_area) + \" m^2\")\n print(\"turbine power = \" + str(total_power) + \" Watts\")\n print(\"total thrust = \" + str(total_thrust) + \" Newtons\")\n print(\"total torque = \" + str(total_torque) + \" Joules/rad\")\n if not bet_prop:\n print(\n \"% of Betz limit power \"\n + str(old_div(100.0 * total_power, betz_power))\n + \"%\"\n )\n if use_glauert_power:\n print(\n \"% of Glauert optimal power \"\n + str(old_div(100.0 * total_power, glauert_power))\n + \"%\"\n )\n return annulus\n\n\ndef project_to_plane(pt, plane_point, plane_normal):\n from numpy import dot\n\n # print pt,plane_point,plane_normal\n return pt - dot(pt - plane_point, plane_normal) * plane_normal\n\n\n# def clockwise_angle(up_vector, pt_vector, plane_normal):\n# from numpy import zeros, array, dot, linalg, cross\n#\n# v_dot = dot(up_vector, pt_vector)\n# v_det = dot(plane_normal, cross(up_vector, pt_vector))\n#\n# r = math.atan2(v_det, v_dot)\n#\n# if r < 0:\n# r += 2.0 * math.pi\n#\n# return r\n\n\ndef convolution(\n disc,\n disc_centre,\n disc_radius,\n disc_normal,\n disc_up,\n cell_centre_list,\n cell_volume_list,\n):\n from mpi4py import MPI\n import libconvolution as cv\n from numpy import zeros, array, dot, linalg, cross, asarray, ndarray\n\n cell_centre_list_np = asarray(cell_centre_list)\n cell_volume_list_np = asarray(cell_volume_list)\n kernel_3d = False\n\n weighted_sum = np.zeros(len(disc))\n\n weighted_sum = cv.convolution_2dkernel_weights(\n disc,\n disc_centre,\n disc_radius,\n disc_normal,\n disc_up,\n cell_centre_list_np,\n cell_volume_list_np,\n )\n # Need to reduce weighted sum over all processes\n totals = np.zeros_like(weighted_sum)\n\n MPI.COMM_WORLD.Allreduce(weighted_sum, totals, op=MPI.SUM)\n weighted_sum = totals\n\n thrust_check_total = 0\n\n cell_force = np.zeros(len(cell_centre_list_np) * 3)\n thrust_check = cv.convolution_2dkernel_force(\n disc,\n disc_centre,\n disc_radius,\n disc_normal,\n disc_up,\n cell_centre_list_np,\n cell_volume_list_np,\n weighted_sum,\n cell_force,\n )\n\n thrust_check_array = np.array([thrust_check])\n thrust_check_total_array = np.array([0.0])\n\n MPI.COMM_WORLD.Allreduce(thrust_check_array, thrust_check_total_array, op=MPI.SUM)\n thrust_check_total = thrust_check_total_array[0]\n thrust_check = thrust_check_total\n\n # if MPI.COMM_WORLD.Get_rank() == 0:\n # print 'Convolved total thrust: ',thrust_check\n\n # thrust_check = 0.0\n total_thrust = 0.0\n for idx, w in enumerate(weighted_sum):\n segment = disc[idx]\n # if w > 0.0:\n # thrust_check += segment[0]\n total_thrust += segment[0]\n\n # if MPI.COMM_WORLD.Get_rank() == 0:\n # print 'Specified total thrust: ',total_thrust\n\n # Broken: Cell_force_scaled will have a different struct to cell_force\n if thrust_check > 0.0:\n thrust_factor = old_div(total_thrust, thrust_check)\n # if MPI.COMM_WORLD.Get_rank() == 0:\n # print 'Scaling thrust: ', thrust_factor\n cell_force_scaled = []\n for cell in range(old_div(len(cell_force), 3)):\n cell_force_scaled.append(\n (\n cell_force[cell * 3 + 0] * thrust_factor,\n cell_force[cell * 3 + 1] * thrust_factor,\n cell_force[cell * 3 + 2] * thrust_factor,\n )\n )\n return cell_force_scaled\n else:\n cell_force = ndarray.tolist(cell_force)\n cell_array = iter(cell_force)\n return list(zip(cell_array, cell_array, cell_array))\n\n cell_force = ndarray.tolist(cell_force)\n cell_array = iter(cell_force)\n return list(zip(cell_array, cell_array, cell_array))\n\n\ndef convolution2(\n disc,\n disc_centre,\n disc_radius,\n disc_normal,\n disc_up,\n cell_centre_list,\n cell_volume_list,\n):\n from mpi4py import MPI\n\n from numpy import zeros, array, dot, linalg, cross\n\n # from zutil import R_2vect\n\n cell_force = []\n\n thrust_check = 0.0\n\n # Transform disc points to actual location\n disc_pt_list = []\n for segment in disc:\n r = segment[2]\n dr = segment[3]\n theta = segment[4]\n dtheta = segment[5]\n\n disc_r = r + 0.5 * dr\n disc_theta = theta + 0.5 * dtheta\n\n disc_pt = array(\n [disc_r * math.cos(disc_theta), disc_r * math.sin(disc_theta), 0.0]\n )\n # print disc_pt\n # Rotate so that z points in the direction of the normal\n R = zeros((3, 3))\n vector_orig = array([0.0, 0.0, 1.0])\n vector_fin = zeros(3)\n for i in range(3):\n vector_fin[i] = disc_normal[i]\n R_2vect(R, vector_orig, vector_fin)\n\n disc_pt = dot(R, disc_pt)\n\n # translate to disc centre\n for i in range(3):\n disc_pt[i] += disc_centre[i]\n\n disc_pt_list.append(disc_pt)\n\n kernel_3d = False\n\n weighted_sum = np.zeros(len(disc))\n\n for cell_idx, cell_centre in enumerate(cell_centre_list):\n\n cell_dt = [0.0, 0.0, 0.0]\n cell_dq = [0.0, 0.0, 0.0]\n\n if kernel_3d:\n for idx, segment in enumerate(disc):\n dt = segment[0]\n dq = segment[1]\n r = segment[2]\n dr = segment[3]\n theta = segment[4]\n dtheta = segment[5]\n\n disc_r = r + 0.5 * dr\n disc_theta = theta + 0.5 * dtheta\n\n area = dtheta * disc_r * dr\n\n dt_per_area = old_div(dt, area)\n dq_per_area = old_div(dq, area)\n\n disc_pt = disc_pt_list[idx]\n # print disc_pt\n\n distance_vec = array(cell_centre) - disc_pt\n distance = math.sqrt(dot(distance_vec, distance_vec))\n unit_distance_vec = old_div(distance_vec, distance)\n\n epsilon = 2.0 * dr\n\n # 3D kernel\n eta = (\n 1.0\n / ((epsilon ** 2) * math.sqrt(math.pi) ** 3)\n * math.exp(-(old_div(distance, epsilon)) ** 2)\n )\n # /math.fabs(dot(disc_normal,unit_distance_vec))\n\n weighted_sum[idx] += max(1.0e-16, eta * cell_volume_list[cell_idx])\n\n # 1D kernel\n # eta = 1.0/(epsilon*math.sqrt(math.pi)) * math.exp(-(distance/epsilon)**2)\n\n # print eta,cell_centre,disc_pt\n\n # Set thrust force\n # for i in range(3):\n # cell_dt[i] += dt_per_area*disc_normal[i]*eta\n\n # Set torque force\n # Vector for centre to pt\n # disc_vec = disc_pt - array(disc_centre)\n # unit_disc_vec = disc_vec/linalg.norm(disc_vec)\n # torque_vector = cross(unit_disc_vec,disc_normal)\n\n # for i in range(3):\n # cell_dq[i] += dq_per_area*torque_vector[i]*eta\n else:\n # Need for find nearest segment\n\n plane_pt = project_to_plane(\n array(cell_centre), array(disc_centre), array(disc_normal)\n )\n\n # print 'Plane pt: ' + str(plane_pt)\n\n plane_pt_radius = linalg.norm(plane_pt - disc_centre)\n plane_pt_theta = 0.0\n if plane_pt_radius > 0.0:\n # plane_pt_theta = math.acos(dot([0.0,0.0,1.0],(plane_pt-disc_centre)/plane_pt_radius))\n plane_pt_theta = clockwise_angle(\n disc_up,\n old_div((plane_pt - disc_centre), plane_pt_radius),\n array(disc_normal),\n )\n\n min_index = -1\n for idx, segment in enumerate(disc):\n r = segment[2]\n dr = segment[3]\n theta = segment[4]\n dtheta = segment[5]\n\n if plane_pt_theta >= theta and plane_pt_theta <= theta + dtheta:\n if plane_pt_radius >= r and plane_pt_radius <= r + dr:\n min_index = idx\n break\n\n if min_index != -1:\n segment = disc[min_index]\n\n dt = segment[0]\n dq = segment[1]\n r = segment[2]\n dr = segment[3]\n theta = segment[4]\n dtheta = segment[5]\n\n disc_r = r + 0.5 * dr\n disc_theta = theta + 0.5 * dtheta\n\n area = dtheta * disc_r * dr\n\n dt_per_area = old_div(dt, area)\n dq_per_area = old_div(dq, area)\n\n distance_vec = array(cell_centre) - plane_pt\n distance = math.sqrt(dot(distance_vec, distance_vec))\n\n # epsilon = 2.0*dr\n epsilon = 0.2 * disc_radius\n\n # 1D kernel\n eta = (\n 1.0\n / (epsilon * math.sqrt(math.pi))\n * math.exp(-(old_div(distance, epsilon)) ** 2)\n )\n\n # Add max as eta may be zero due to underflow in the exponent\n # term\n weighted_sum[min_index] += max(\n 1.0e-16, eta * cell_volume_list[cell_idx]\n )\n\n # Need to reduce weighted sum over all processes\n totals = np.zeros_like(weighted_sum)\n\n MPI.COMM_WORLD.Allreduce(weighted_sum, totals, op=MPI.SUM)\n weighted_sum = totals\n\n for cell_idx, cell_centre in enumerate(cell_centre_list):\n\n cell_dt = [0.0, 0.0, 0.0]\n cell_dq = [0.0, 0.0, 0.0]\n\n if kernel_3d:\n for idx, segment in enumerate(disc):\n dt = segment[0]\n dq = segment[1]\n r = segment[2]\n dr = segment[3]\n theta = segment[4]\n dtheta = segment[5]\n\n disc_r = r + 0.5 * dr\n disc_theta = theta + 0.5 * dtheta\n\n area = dtheta * disc_r * dr\n\n dt_per_area = old_div(dt, area)\n dq_per_area = old_div(dq, area)\n\n disc_pt = disc_pt_list[idx]\n # print disc_pt\n\n distance_vec = array(cell_centre) - disc_pt\n distance = math.sqrt(dot(distance_vec, distance_vec))\n unit_distance_vec = old_div(distance_vec, distance)\n\n epsilon = 2.0 * dr\n\n # 3D kernel\n eta = (\n 1.0\n / ((epsilon ** 2) * math.sqrt(math.pi) ** 3)\n * math.exp(-(old_div(distance, epsilon)) ** 2)\n )\n # /math.fabs(dot(disc_normal,unit_distance_vec))\n\n redistribution_weight = weighted_sum[idx]\n\n # 1D kernel\n # eta = 1.0/(epsilon*math.sqrt(math.pi)) * math.exp(-(distance/epsilon)**2)\n\n # print eta,cell_centre,disc_pt\n\n # Set thrust force\n for i in range(3):\n cell_dt[i] += (\n old_div(dt_per_area * area, redistribution_weight)\n * disc_normal[i]\n * eta\n )\n\n # Set torque force\n # Vector for centre to pt\n disc_vec = disc_pt - array(disc_centre)\n disc_vec_mag = linalg.norm(disc_vec)\n unit_disc_vec = old_div(disc_vec, disc_vec_mag)\n torque_vector = cross(disc_normal, unit_disc_vec)\n\n # Note converting torque to a force\n for i in range(3):\n cell_dq[i] += old_div(\n dq_per_area * area, redistribution_weight\n ) * old_div(torque_vector[i] * eta / disc_vec_mag)\n else:\n # Need for find nearest segment\n\n plane_pt = project_to_plane(\n array(cell_centre), array(disc_centre), array(disc_normal)\n )\n\n # print 'Plane pt: ' + str(plane_pt)\n\n plane_pt_radius = linalg.norm(plane_pt - disc_centre)\n\n plane_pt_theta = 0.0\n if plane_pt_radius > 0.0:\n # plane_pt_theta = math.acos(dot([0.0,0.0,1.0],(plane_pt-disc_centre)/plane_pt_radius))\n plane_pt_theta = clockwise_angle(\n disc_up,\n old_div((plane_pt - disc_centre), plane_pt_radius),\n array(disc_normal),\n )\n\n min_index = -1\n for idx, segment in enumerate(disc):\n r = segment[2]\n dr = segment[3]\n theta = segment[4]\n dtheta = segment[5]\n\n if plane_pt_theta >= theta and plane_pt_theta <= theta + dtheta:\n if plane_pt_radius >= r and plane_pt_radius <= r + dr:\n min_index = idx\n break\n\n if min_index != -1:\n segment = disc[min_index]\n\n dt = segment[0]\n dq = segment[1]\n r = segment[2]\n dr = segment[3]\n theta = segment[4]\n dtheta = segment[5]\n\n disc_r = r + 0.5 * dr\n disc_theta = theta + 0.5 * dtheta\n\n area = dtheta * disc_r * dr\n\n dt_per_area = old_div(dt, area)\n dq_per_area = old_div(dq, area)\n\n distance_vec = array(cell_centre) - plane_pt\n distance = math.sqrt(dot(distance_vec, distance_vec))\n\n # epsilon = 2.0*dr\n epsilon = 0.2 * disc_radius\n\n # 1D kernel\n eta = (\n 1.0\n / (epsilon * math.sqrt(math.pi))\n * math.exp(-(old_div(distance, epsilon)) ** 2)\n )\n\n redistribution_weight = weighted_sum[min_index]\n\n # print redistribution_weight\n\n # print dt,eta,cell_centre,plane_pt\n\n # Set thrust force\n for i in range(3):\n cell_dt[i] += (\n old_div(dt_per_area * area, redistribution_weight)\n * disc_normal[i]\n * eta\n )\n\n # Set torque force\n # Vector for centre to pt\n disc_vec = plane_pt - array(disc_centre)\n disc_vec_mag = linalg.norm(disc_vec)\n unit_disc_vec = old_div(disc_vec, disc_vec_mag)\n torque_vector = cross(disc_normal, unit_disc_vec)\n\n # Note converting torque to force\n for i in range(3):\n cell_dq[i] += old_div(\n dq_per_area * area, redistribution_weight\n ) * old_div(torque_vector[i] * eta / disc_vec_mag)\n\n cell_force.append(\n (cell_dt[0] + cell_dq[0], cell_dt[1] + cell_dq[1], cell_dt[2] + cell_dq[2])\n )\n\n thrust_check += dot(cell_force[-1], disc_normal) * cell_volume_list[cell_idx]\n\n thrust_check_total = 0\n\n thrust_check_array = np.array([thrust_check])\n thrust_check_total_array = np.array([0.0])\n MPI.COMM_WORLD.Allreduce(thrust_check_array, thrust_check_total_array, op=MPI.SUM)\n thrust_check_total = thrust_check_total_array[0]\n thrust_check = thrust_check_total\n\n if MPI.COMM_WORLD.Get_rank() == 0:\n print(\"Convolved total thrust: \", thrust_check)\n\n # thrust_check = 0.0\n total_thrust = 0.0\n for idx, w in enumerate(weighted_sum):\n segment = disc[idx]\n # if w > 0.0:\n # thrust_check += segment[0]\n total_thrust += segment[0]\n\n if MPI.COMM_WORLD.Get_rank() == 0:\n print(\"Specified total thrust: \", total_thrust)\n\n if thrust_check > 0.0:\n thrust_factor = old_div(total_thrust, thrust_check)\n if MPI.COMM_WORLD.Get_rank() == 0:\n print(\"Scaling thrust: \", thrust_factor)\n cell_force_scaled = []\n for cell in cell_force:\n force = cell\n cell_force_scaled.append(\n (\n force[0] * thrust_factor,\n force[1] * thrust_factor,\n force[2] * thrust_factor,\n )\n )\n\n return cell_force_scaled\n else:\n return cell_force\n\n return cell_force\n\n\ndef test_convolution():\n a = create_turbine_segments(0.7, 0.1, 1.0, 6.0, 1, 1)\n b = convolution(a, (0, 0, 0), (1, 0, 0), [(0.0, 0.0, 1.5)], [1.0])\n b = convolution(a, (0, 0, 0), (1, 0, 0), [(0.0, 0.0, 0.99)], [1.0])\n b = convolution(a, (0, 0, 0), (1, 0, 0), [(2.0, 0.0, 0.5)], [1.0])\n\n print(b)\n" ]
[ [ "numpy.dot", "numpy.linspace", "numpy.asarray", "numpy.reshape", "numpy.arange", "numpy.degrees", "numpy.linalg.norm", "numpy.max", "numpy.zeros_like", "numpy.interp", "numpy.mean", "numpy.cross", "numpy.ndarray.tolist", "numpy.array", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
allen91wu/Cirq
[ "c33bd9bd6d08650f41b0db5cf69abb3daed72a8f", "c33bd9bd6d08650f41b0db5cf69abb3daed72a8f" ]
[ "cirq-core/cirq/optimizers/cphase_to_fsim.py", "cirq-core/cirq/ops/measurement_gate.py" ]
[ "# pylint: disable=wrong-or-nonexistent-copyright-notice\nfrom typing import Optional, Sequence, Tuple, TYPE_CHECKING\n\nimport numpy as np\n\nfrom cirq import devices, ops, protocols\n\nif TYPE_CHECKING:\n import cirq\n\n\ndef _asinsin(x: float) -> float:\n \"\"\"Computes arcsin(sin(x)) for any x. Return value in [-π/2, π/2].\"\"\"\n k = round(x / np.pi)\n if k % 2 == 0:\n return x - k * np.pi\n return k * np.pi - x\n\n\ndef compute_cphase_exponents_for_fsim_decomposition(\n fsim_gate: 'cirq.FSimGate',\n) -> Sequence[Tuple[float, float]]:\n \"\"\"Returns intervals of CZPowGate exponents valid for FSim decomposition.\n\n Ideal intervals associated with the constraints are closed, but due to\n numerical error the caller should not assume the endpoints themselves\n are valid for the decomposition. See `decompose_cphase_into_two_fsim`\n for details on how FSimGate parameters constrain the phase angle of\n CZPowGate.\n\n Args:\n fsim_gate: FSimGate into which CZPowGate would be decomposed.\n\n Returns:\n Sequence of 2-tuples each consisting of the minimum and maximum\n value of the exponent for which CZPowGate can be decomposed into\n two FSimGates. The intervals are cropped to [0, 2]. The function\n returns zero, one or two intervals.\n \"\"\"\n\n def nonempty_intervals(\n intervals: Sequence[Tuple[float, float]]\n ) -> Sequence[Tuple[float, float]]:\n return tuple((a, b) for a, b in intervals if a < b)\n\n # Each of the two FSimGate parameters sets a bound on phase angle.\n bound1 = abs(_asinsin(fsim_gate.theta))\n bound2 = abs(_asinsin(fsim_gate.phi / 2))\n\n # First potential interval corresponds to the left side of sine's \"hump\".\n min_exponent_1 = 4 * min(bound1, bound2) / np.pi\n max_exponent_1 = 4 * max(bound1, bound2) / np.pi\n assert min_exponent_1 <= max_exponent_1\n\n # Second potential interval corresponds to the right side of sine's \"hump\".\n min_exponent_2 = 2 - max_exponent_1\n max_exponent_2 = 2 - min_exponent_1\n assert min_exponent_2 <= max_exponent_2\n\n # Intervals are disjoint. Return both.\n if max_exponent_1 < min_exponent_2:\n return nonempty_intervals(\n [(min_exponent_1, max_exponent_1), (min_exponent_2, max_exponent_2)]\n )\n if max_exponent_2 < min_exponent_1:\n return nonempty_intervals(\n [(min_exponent_2, max_exponent_2), (min_exponent_1, max_exponent_1)]\n )\n\n # Intervals overlap. Merge.\n min_exponent = min(min_exponent_1, min_exponent_2)\n max_exponent = max(max_exponent_1, max_exponent_2)\n return nonempty_intervals([(min_exponent, max_exponent)])\n\n\ndef decompose_cphase_into_two_fsim(\n cphase_gate: 'cirq.CZPowGate',\n *,\n fsim_gate: 'cirq.FSimGate',\n qubits: Optional[Sequence['cirq.Qid']] = None,\n atol: float = 1e-8,\n) -> 'cirq.OP_TREE':\n \"\"\"Decomposes CZPowGate into two FSimGates.\n\n This function implements the decomposition described in section VII F I\n of https://arxiv.org/abs/1910.11333.\n\n The decomposition results in exactly two FSimGates and a few single-qubit\n rotations. It is feasible if and only if one of the following conditions\n is met:\n\n |sin(θ)| <= |sin(δ/4)| <= |sin(φ/2)|\n |sin(φ/2)| <= |sin(δ/4)| <= |sin(θ)|\n\n where:\n\n θ = fsim_gate.theta,\n φ = fsim_gate.phi,\n δ = -π * cphase_gate.exponent.\n\n Note that the gate parameterizations are non-injective. For the\n decomposition to be feasible it is sufficient that one of the\n parameter values which correspond to the provided gate satisfies\n the constraints. This function will find and use the appropriate\n value whenever it exists.\n\n The constraints above imply that certain FSimGates are not suitable\n for use in this decomposition regardless of the target CZPowGate. We\n reject such gates based on how close |sin(θ)| is to |sin(φ/2)|, see\n atol argument below.\n\n This implementation accounts for the global phase.\n\n Args:\n cphase_gate: The CZPowGate to synthesize.\n fsim_gate: The only two qubit gate that is permitted to appear in the\n output.\n qubits: The qubits to apply the resulting operations to. If not set,\n defaults `cirq.LineQubit.range(2)`.\n atol: Tolerance used to determine whether fsim_gate is valid. The gate\n is invalid if the squares of the sines of the theta angle and half\n the phi angle are too close.\n\n Returns:\n Operations equivalent to cphase_gate and consisting solely of two copies\n of fsim_gate and a few single-qubit rotations.\n\n Raises:\n ValueError: Under any of the following circumstances:\n * cphase_gate or fsim_gate is parametrized,\n * cphase_gate and fsim_gate do not satisfy the conditions above,\n * fsim_gate has invalid angles (see atol argument above),\n * incorrect number of qubits are provided.\n \"\"\"\n if protocols.is_parameterized(cphase_gate):\n raise ValueError('Cannot decompose a parametrized gate.')\n if protocols.is_parameterized(fsim_gate):\n raise ValueError('Cannot decompose into a parametrized gate.')\n if qubits is None:\n qubits = devices.LineQubit.range(2)\n if len(qubits) != 2:\n raise ValueError(f'Expected a pair of qubits, but got {qubits!r}.')\n q0, q1 = qubits\n\n theta = fsim_gate.theta\n phi = fsim_gate.phi\n\n sin_half_phi = np.sin(phi / 2)\n cos_half_phi = np.cos(phi / 2)\n sin_theta = np.sin(theta)\n cos_theta = np.cos(theta)\n\n #\n # Step 1: find alpha\n #\n denominator = (sin_theta - sin_half_phi) * (sin_theta + sin_half_phi)\n if abs(denominator) < atol:\n raise ValueError(\n f'{fsim_gate} cannot be used to decompose CZPowGate because '\n 'sin(theta)**2 is too close to sin(phi/2)**2 '\n f'(difference is {denominator}).'\n )\n\n # Parametrization of CZPowGate by a real angle is a non-injective function\n # with the preimage of cphase_gate infinite. However, it is sufficient to\n # check just two of the angles against the constraints of the decomposition.\n canonical_delta = -np.pi * (cphase_gate.exponent % 2)\n for delta in (canonical_delta, canonical_delta + 2 * np.pi):\n sin_quarter_delta = np.sin(delta / 4)\n numerator = (sin_quarter_delta - sin_half_phi) * (sin_quarter_delta + sin_half_phi)\n sin_alpha_squared = numerator / denominator\n if 0 <= sin_alpha_squared <= 1:\n break\n else:\n intervals = compute_cphase_exponents_for_fsim_decomposition(fsim_gate)\n raise ValueError(\n f'{cphase_gate} cannot be decomposed into two {fsim_gate}. Valid '\n f'intervals for canonical exponent of CZPowGate: {intervals}.'\n )\n assert 0 <= sin_alpha_squared <= 1\n alpha = np.arcsin(np.sqrt(sin_alpha_squared))\n\n #\n # Step 2: find xi and eta\n #\n tan_alpha = np.tan(alpha)\n xi = np.arctan2(tan_alpha * cos_theta, cos_half_phi)\n eta = np.arctan2(tan_alpha * sin_theta, sin_half_phi)\n if delta < 0:\n eta += np.pi\n\n #\n # Step 3: synthesize output circuit\n #\n return (\n # Local X rotations to convert Γ1⊗I − iZ⊗Γ2 into exp(-i Z⊗Z δ/4)\n ops.rx(xi).on(q0),\n ops.rx(eta).on(q1),\n # Y(θ, φ) := exp(-i X⊗X θ/2) exp(-i Y⊗Y θ/2) exp(-i Z⊗Z φ/4)\n fsim_gate.on(q0, q1),\n ops.rz(phi / 2).on(q0),\n ops.rz(phi / 2).on(q1),\n ops.global_phase_operation(np.exp(1j * phi / 4)),\n # exp(i X1 α)\n ops.rx(-2 * alpha).on(q0),\n # Y(-θ, φ) := exp(i X⊗X θ/2) exp(i Y⊗Y θ/2) exp(-i Z⊗Z φ/4)\n ops.Z(q0),\n fsim_gate.on(q0, q1),\n ops.rz(phi / 2).on(q0),\n ops.rz(phi / 2).on(q1),\n ops.global_phase_operation(np.exp(1j * phi / 4)),\n ops.Z(q0),\n # Local X rotations to convert Γ1⊗I − iZ⊗Γ2 into exp(-i Z⊗Z δ/4)\n ops.rx(-eta).on(q1),\n ops.rx(xi).on(q0),\n # Local Z rotations to convert exp(-i Z⊗Z δ/4) into desired CPhase.\n ops.rz(-delta / 2).on(q0),\n ops.rz(-delta / 2).on(q1),\n ops.global_phase_operation(np.exp(-1j * delta / 4)),\n )\n", "# Copyright 2018 The Cirq Developers\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\nfrom typing import Any, Dict, Iterable, Optional, Tuple, Sequence, TYPE_CHECKING, Union\n\nimport numpy as np\n\nfrom cirq import protocols, value\nfrom cirq.ops import raw_types\n\nif TYPE_CHECKING:\n import cirq\n\n\[email protected]_equality\nclass MeasurementGate(raw_types.Gate):\n \"\"\"A gate that measures qubits in the computational basis.\n\n The measurement gate contains a key that is used to identify results\n of measurements.\n \"\"\"\n\n def __init__(\n self,\n num_qubits: Optional[int] = None,\n key: Union[str, value.MeasurementKey] = '',\n invert_mask: Tuple[bool, ...] = (),\n qid_shape: Tuple[int, ...] = None,\n ) -> None:\n \"\"\"Inits MeasurementGate.\n\n Args:\n num_qubits: The number of qubits to act upon.\n key: The string key of the measurement.\n invert_mask: A list of values indicating whether the corresponding\n qubits should be flipped. The list's length must not be longer\n than the number of qubits, but it is permitted to be shorter.\n Qubits with indices past the end of the mask are not flipped.\n qid_shape: Specifies the dimension of each qid the measurement\n applies to. The default is 2 for every qubit.\n\n Raises:\n ValueError: If the length of invert_mask is greater than num_qubits.\n or if the length of qid_shape doesn't equal num_qubits.\n \"\"\"\n if qid_shape is None:\n if num_qubits is None:\n raise ValueError('Specify either the num_qubits or qid_shape argument.')\n qid_shape = (2,) * num_qubits\n elif num_qubits is None:\n num_qubits = len(qid_shape)\n if num_qubits == 0:\n raise ValueError('Measuring an empty set of qubits.')\n self._qid_shape = qid_shape\n if len(self._qid_shape) != num_qubits:\n raise ValueError('len(qid_shape) != num_qubits')\n self.key = key # type: ignore\n self.invert_mask = invert_mask or ()\n if self.invert_mask is not None and len(self.invert_mask) > self.num_qubits():\n raise ValueError('len(invert_mask) > num_qubits')\n\n @property\n def key(self) -> str:\n return str(self.mkey)\n\n @key.setter\n def key(self, key: Union[str, value.MeasurementKey]):\n if isinstance(key, value.MeasurementKey):\n self.mkey = key\n else:\n self.mkey = value.MeasurementKey(name=key)\n\n def _qid_shape_(self) -> Tuple[int, ...]:\n return self._qid_shape\n\n def with_key(self, key: Union[str, value.MeasurementKey]) -> 'MeasurementGate':\n \"\"\"Creates a measurement gate with a new key but otherwise identical.\"\"\"\n if key == self.key:\n return self\n return MeasurementGate(\n self.num_qubits(), key=key, invert_mask=self.invert_mask, qid_shape=self._qid_shape\n )\n\n def _with_key_path_(self, path: Tuple[str, ...]):\n return self.with_key(self.mkey._with_key_path_(path))\n\n def _with_key_path_prefix_(self, prefix: Tuple[str, ...]):\n return self.with_key(self.mkey._with_key_path_prefix_(prefix))\n\n def _with_measurement_key_mapping_(self, key_map: Dict[str, str]):\n return self.with_key(protocols.with_measurement_key_mapping(self.mkey, key_map))\n\n def with_bits_flipped(self, *bit_positions: int) -> 'MeasurementGate':\n \"\"\"Toggles whether or not the measurement inverts various outputs.\"\"\"\n old_mask = self.invert_mask or ()\n n = max(len(old_mask) - 1, *bit_positions) + 1\n new_mask = [k < len(old_mask) and old_mask[k] for k in range(n)]\n for b in bit_positions:\n new_mask[b] = not new_mask[b]\n return MeasurementGate(\n self.num_qubits(), key=self.key, invert_mask=tuple(new_mask), qid_shape=self._qid_shape\n )\n\n def full_invert_mask(self):\n \"\"\"Returns the invert mask for all qubits.\n\n If the user supplies a partial invert_mask, this returns that mask\n padded by False.\n\n Similarly if no invert_mask is supplies this returns a tuple\n of size equal to the number of qubits with all entries False.\n \"\"\"\n mask = self.invert_mask or self.num_qubits() * (False,)\n deficit = self.num_qubits() - len(mask)\n mask += (False,) * deficit\n return mask\n\n def _is_measurement_(self) -> bool:\n return True\n\n def _measurement_key_name_(self) -> str:\n return self.key\n\n def _measurement_key_obj_(self) -> value.MeasurementKey:\n return self.mkey\n\n def _kraus_(self):\n size = np.prod(self._qid_shape, dtype=np.int64)\n\n def delta(i):\n result = np.zeros((size, size))\n result[i][i] = 1\n return result\n\n return tuple(delta(i) for i in range(size))\n\n def _has_kraus_(self):\n return True\n\n def _circuit_diagram_info_(\n self, args: 'cirq.CircuitDiagramInfoArgs'\n ) -> 'cirq.CircuitDiagramInfo':\n symbols = ['M'] * self.num_qubits()\n\n # Show which output bits are negated.\n if self.invert_mask:\n for i, b in enumerate(self.invert_mask):\n if b:\n symbols[i] = '!M'\n\n # Mention the measurement key.\n label_map = args.label_map or {}\n if not args.known_qubits or self.key != _default_measurement_key(args.known_qubits):\n if self.key not in label_map:\n symbols[0] += f\"('{self.key}')\"\n if self.key in label_map:\n symbols += '@'\n\n return protocols.CircuitDiagramInfo(symbols)\n\n def _qasm_(self, args: 'cirq.QasmArgs', qubits: Tuple['cirq.Qid', ...]) -> Optional[str]:\n if not all(d == 2 for d in self._qid_shape):\n return NotImplemented\n args.validate_version('2.0')\n invert_mask = self.invert_mask\n if len(invert_mask) < len(qubits):\n invert_mask = invert_mask + (False,) * (len(qubits) - len(invert_mask))\n lines = []\n for i, (qubit, inv) in enumerate(zip(qubits, invert_mask)):\n if inv:\n lines.append(args.format('x {0}; // Invert the following measurement\\n', qubit))\n lines.append(args.format('measure {0} -> {1:meas}[{2}];\\n', qubit, self.key, i))\n if inv:\n lines.append(args.format('x {0}; // Undo the inversion\\n', qubit))\n return ''.join(lines)\n\n def _quil_(\n self, qubits: Tuple['cirq.Qid', ...], formatter: 'cirq.QuilFormatter'\n ) -> Optional[str]:\n if not all(d == 2 for d in self._qid_shape):\n return NotImplemented\n invert_mask = self.invert_mask\n if len(invert_mask) < len(qubits):\n invert_mask = invert_mask + (False,) * (len(qubits) - len(invert_mask))\n lines = []\n for i, (qubit, inv) in enumerate(zip(qubits, invert_mask)):\n if inv:\n lines.append(\n formatter.format('X {0} # Inverting for following measurement\\n', qubit)\n )\n lines.append(formatter.format('MEASURE {0} {1:meas}[{2}]\\n', qubit, self.key, i))\n return ''.join(lines)\n\n def _op_repr_(self, qubits: Sequence['cirq.Qid']) -> str:\n args = list(repr(q) for q in qubits)\n if self.key != _default_measurement_key(qubits):\n args.append(f'key={self.mkey!r}')\n if self.invert_mask:\n args.append(f'invert_mask={self.invert_mask!r}')\n arg_list = ', '.join(args)\n return f'cirq.measure({arg_list})'\n\n def __repr__(self):\n qid_shape_arg = ''\n if any(d != 2 for d in self._qid_shape):\n qid_shape_arg = f', {self._qid_shape!r}'\n return (\n f'cirq.MeasurementGate('\n f'{self.num_qubits()!r}, '\n f'{self.mkey!r}, '\n f'{self.invert_mask}'\n f'{qid_shape_arg})'\n )\n\n def _value_equality_values_(self) -> Any:\n return self.key, self.invert_mask, self._qid_shape\n\n def _json_dict_(self) -> Dict[str, Any]:\n other = {}\n if not all(d == 2 for d in self._qid_shape):\n other['qid_shape'] = self._qid_shape\n return {\n 'num_qubits': len(self._qid_shape),\n 'key': self.key,\n 'invert_mask': self.invert_mask,\n **other,\n }\n\n @classmethod\n def _from_json_dict_(cls, num_qubits, key, invert_mask, qid_shape=None, **kwargs):\n return cls(\n num_qubits=num_qubits,\n key=value.MeasurementKey.parse_serialized(key),\n invert_mask=tuple(invert_mask),\n qid_shape=None if qid_shape is None else tuple(qid_shape),\n )\n\n def _has_stabilizer_effect_(self) -> Optional[bool]:\n return True\n\n def _act_on_(self, args: 'cirq.OperationTarget', qubits: Sequence['cirq.Qid']) -> bool:\n from cirq.sim import ActOnArgs\n\n if not isinstance(args, ActOnArgs):\n return NotImplemented\n args.measure(qubits, self.key, self.full_invert_mask())\n return True\n\n\ndef _default_measurement_key(qubits: Iterable[raw_types.Qid]) -> str:\n return ','.join(str(q) for q in qubits)\n" ]
[ [ "numpy.sqrt", "numpy.cos", "numpy.sin", "numpy.tan", "numpy.arctan2", "numpy.exp" ], [ "numpy.zeros", "numpy.prod" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
JamesPerlman/Dain-App
[ "f589abdca8309cfdb6dd106da7c7c4613d152c72", "f589abdca8309cfdb6dd106da7c7c4613d152c72" ]
[ "Resblock/BasicBlock.py", "networks/DAIN.py" ]
[ "import torch.nn as nn\nimport math\nimport torch.utils.model_zoo as model_zoo\nimport torch.nn.init as weight_init\nimport torch\n__all__ = ['MultipleBasicBlock','MultipleBasicBlock_4']\ndef conv3x3(in_planes, out_planes, dilation = 1, stride=1):\n \"3x3 convolution with padding\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\n padding=int(dilation*(3-1)/2), dilation=dilation, bias=False)\nclass BasicBlock(nn.Module):\n expansion = 1\n\n def __init__(self, inplanes, planes, dilation = 1, stride=1, downsample=None):\n super(BasicBlock, self).__init__()\n self.conv1 = conv3x3(inplanes, planes,dilation, stride)\n # self.bn1 = nn.BatchNorm2d(planes)\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = conv3x3(planes, planes)\n # self.bn2 = nn.BatchNorm2d(planes)\n self.downsample = downsample\n self.stride = stride\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, math.sqrt(2. / n))\n # weight_init.xavier_normal()\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n\n def forward(self, x):\n residual = 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 residual = self.downsample(x)\n\n out += residual\n out = self.relu(out)\n\n return out\nclass MultipleBasicBlock(nn.Module):\n\n def __init__(self,input_feature,\n block, num_blocks,\n intermediate_feature = 64, dense = True):\n super(MultipleBasicBlock, self).__init__()\n self.dense = dense\n self.num_block = num_blocks\n self.intermediate_feature = intermediate_feature\n\n self.block1= nn.Sequential(*[\n nn.Conv2d(input_feature, intermediate_feature,\n kernel_size=7, stride=1, padding=3, bias=False),\n nn.ReLU(inplace=True)\n ])\n\n # for i in range(1, num_blocks):\n self.block2 = block(intermediate_feature, intermediate_feature, dilation = 1) if num_blocks>=2 else None\n self.block3 = block(intermediate_feature, intermediate_feature, dilation = 1) if num_blocks>=3 else None\n self.block4 = block(intermediate_feature, intermediate_feature, dilation = 1) if num_blocks>=4 else None\n self.block5 = nn.Sequential(*[nn.Conv2d(intermediate_feature, 3 , (3, 3), 1, (1, 1))])\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, math.sqrt(2. / n))\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n\n def forward(self, x):\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 return x\n\ndef MultipleBasicBlock_4(input_feature,intermediate_feature = 64):\n model = MultipleBasicBlock(input_feature,\n BasicBlock,4 ,\n intermediate_feature)\n return model\n\n\nif __name__ == '__main__':\n\n # x= Variable(torch.randn(2,3,224,448))\n # model = S2DF(BasicBlock,3,True)\n # y = model(x)\n model = MultipleBasicBlock(200, BasicBlock,4)\n model = BasicBlock(64,64,1)\n # y = model(x)\n exit(0)", "# -*- coding: utf-8 -*-\nimport torch\nimport torch.nn as nn\nfrom torch.nn import functional as F\n\nfrom my_package.FilterInterpolation import FilterInterpolationModule\nfrom my_package.FlowProjection import FlowProjectionModule #,FlowFillholeModule\nfrom my_package.DepthFlowProjection import DepthFlowProjectionModule\n\nfrom Stack import Stack\n\nimport PWCNet\nimport S2D_models\nimport Resblock\nimport MegaDepth\nimport time\nimport RenderData\nimport cv2\nimport numpy as np\nimport time\nimport datetime as dt\n\nfrom MotionBlur import BlurIt\n\n\nSHOW_TIMING = False\nTIMER = None\ndef SetTiming(tag):\n global TIMER, SHOW_TIMING\n if TIMER == None:\n TIMER = time.time()\n if SHOW_TIMING:\n print(\"\\nStarting DAIN Timer: \" + tag)\n if SHOW_TIMING:\n torch.cuda.synchronize()\n print(\"\\nDAIN \"+tag + \": --- %s seconds ---\" % (time.time() - TIMER))\n TIMER = time.time()\n\n\n\nclass DAIN(torch.nn.Module):\n def __init__(self,\n channel = 3,\n filter_size = 4,\n timestep=0.5,\n training=True,\n useAnimationMethod = 0,\n shareMemory = False,\n cuda = True, iSize = [2048, 1024], batch_size = 1, padding = (0,0,0,0),\n depadding = (0,0,0,0),\n is_half = False):\n\n # base class initialization\n super(DAIN, self).__init__()\n \n \n self.filter_size = filter_size\n self.training = training\n self.timestep = timestep\n self.useAnimationMethod = useAnimationMethod\n assert (timestep == 0.5) # TODO: or else the WeigtedFlowProjection should also be revised... Really Tedious work.\n self.numFrames =int(1.0/timestep) - 1\n self.use_cuda = cuda\n self.iSize = iSize\n self.padding = padding\n self.depadding = depadding\n self.is_half = is_half\n\n i=0\n self.initScaleNets_filter,self.initScaleNets_filter1,self.initScaleNets_filter2 = \\\n self.get_MonoNet5(channel if i == 0 else channel + filter_size * filter_size, filter_size * filter_size, \"filter\")\n\n self.ctxNet = S2D_models.__dict__['S2DF_3dense']()\n\n self.ctx_ch = 3 * 64 + 3\n\n self.rectifyNet = Resblock.__dict__['MultipleBasicBlock_4'](3 + 3 + 3 +2*1+ 2*2 +16*2+ 2 * self.ctx_ch, 128)\n\n if self.is_half:\n self.ctxNet = self.ctxNet.half()\n self.rectifyNet = self.rectifyNet.half()\n self.initScaleNets_filter = self.initScaleNets_filter.half()\n self.initScaleNets_filter1 = self.initScaleNets_filter1.half()\n self.initScaleNets_filter2 = self.initScaleNets_filter2.half()\n else:\n self.ctxNet = self.ctxNet.float()\n self.rectifyNet = self.rectifyNet.float()\n self.initScaleNets_filter = self.initScaleNets_filter.float()\n self.initScaleNets_filter1 = self.initScaleNets_filter1.float()\n self.initScaleNets_filter2 = self.initScaleNets_filter2.float()\n\n if self.use_cuda:\n self.ctxNet = self.ctxNet.cuda()\n self.initScaleNets_filter = self.initScaleNets_filter.cuda()\n self.initScaleNets_filter1 = self.initScaleNets_filter1.cuda()\n self.initScaleNets_filter2 = self.initScaleNets_filter2.cuda()\n self.rectifyNet = self.rectifyNet.cuda()\n else:\n self.ctxNet = self.ctxNet.cpu()\n self.initScaleNets_filter = self.initScaleNets_filter.cpu()\n self.initScaleNets_filter1 = self.initScaleNets_filter1.cpu()\n self.initScaleNets_filter2 = self.initScaleNets_filter2.cpu()\n self.rectifyNet = self.rectifyNet.cpu()\n\n\n #self._initialize_weights()\n\n if self.training:\n self.flownets = PWCNet.__dict__['pwc_dc_net'](\"PWCNet/pwc_net.pth.tar\")\n else:\n self.flownets = PWCNet.__dict__['pwc_dc_net'](None, self.use_cuda, iSize, batch_size)\n\n if self.is_half:\n self.flownets = self.flownets.half()\n else:\n self.flownets = self.flownets.float()\n\n if self.use_cuda:\n self.flownets = self.flownets.cuda()\n else:\n self.flownets = self.flownets.cpu()\n\n\n self.div_flow = 20.0\n\n if useAnimationMethod == 0:\n #extract depth information\n if self.training:\n self.depthNet=MegaDepth.__dict__['HourGlass'](\"MegaDepth/checkpoints/test_local/best_generalization_net_G.pth\")\n else:\n self.depthNet=MegaDepth.__dict__['HourGlass']()\n \n if self.is_half:\n self.depthNet = self.depthNet.half()\n else:\n self.depthNet = self.depthNet.float()\n \n if self.use_cuda:\n self.depthNet=self.depthNet.cuda()\n else:\n self.depthNet=self.depthNet.cpu()\n\n\n self.filterModule = FilterInterpolationModule.__dict__['interpolation']()\n\n if self.is_half:\n self.filterModule = self.filterModule.half()\n\n if self.use_cuda:\n self.filterModule = self.filterModule.cuda()\n else:\n self.filterModule = self.filterModule.cpu()\n\n return\n\n def _initialize_weights(self):\n count = 0\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n count+=1\n nn.init.xavier_uniform_(m.weight.data)\n # weight_init.kaiming_uniform(m.weight.data, a = 0, mode='fan_in')\n if m.bias is not None:\n m.bias.data.zero_()\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n elif isinstance(m, nn.Linear):\n m.weight.data.normal_(0, 0.01)\n m.bias.data.zero_()\n # else:\n # print(m)\n\n\n def forward(self, input_0, input_2, padding, flow_force, flow_smooth, flow_share, convert, rectify):\n\n SetTiming(\"Starting Foward\")\n\n losses = []\n offsets= []\n filters = []\n occlusions = []\n\n\n alpha = False \n\n torch.cuda.synchronize()\n if input_0.size(1) == 4:\n alpha = True\n\n #print(\"There is an alpha channel\")\n input_0_alpha = input_0[:,3:4,:,:]\n input_0 = input_0[:,0:3,:,:]\n input_2_alpha = input_2[:,3:4,:,:]\n input_2 = input_2[:,0:3,:,:]\n\n if self.use_cuda:\n input_0_alpha = input_0_alpha.cuda()\n input_0 = input_0.cuda()\n input_2_alpha = input_2_alpha.cuda()\n input_2 = input_2.cuda()\n\n \n if self.is_half:\n input_0_alpha = input_0_alpha.half()\n input_2_alpha = input_2_alpha.half()\n input_0 = input_0.half()\n input_2 = input_2.half()\n\n elif input_0.size(1) == 3:\n if self.use_cuda:\n input_0 = input_0.cuda()\n input_2 = input_2.cuda()\n\n if self.is_half:\n input_0 = input_0.half()\n input_2 = input_2.half()\n\n else:\n print(\"Bug??\")\n\n torch.cuda.synchronize()\n\n downscaler = nn.Upsample(scale_factor=0.5, mode='bilinear', align_corners=True)\n upscaler = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)\n \n SetTiming(\"Starting Cat\")\n\n SetTiming(\"Ending Cat / Start Depth\")\n\n if self.useAnimationMethod == 1 or self.useAnimationMethod == 2:\n #print(str(input_0.shape) +\" \"+ str(input_2.shape))\n temp = torch.cat((input_0, input_2),dim=0)\n temp = temp[:, 1:2, :, :]\n else:\n torch.cuda.synchronize()\n temp = self.depthNet(torch.cat((input_0, input_2),dim=0))\n if self.is_half:\n temp *= -1\n \n \n log_depth = [temp[:input_0.size(0)], temp[input_2.size(0):]]\n SetTiming(\"End Depth / Start Filter 01\")\n\n if self.useAnimationMethod == 1:\n log_depth[0].fill_(1)\n log_depth[1].fill_(1)\n if self.useAnimationMethod == 2:\n log_depth = [d for d in log_depth]\n\n if self.useAnimationMethod == 1:\n depth_inv = log_depth \n #depth_inv = [None , None] \n else:\n if self.is_half:\n depth_inv = [(1e-6 + 1 / torch.exp(d.float())).half() for d in log_depth]\n else:\n depth_inv = [1e-6 + 1 / torch.exp(d) for d in log_depth]\n\n SetTiming(\"End Calculations\")\n\n s1 = torch.cuda.current_stream()\n s2 = torch.cuda.current_stream()\n \n fSingle = self.forward_singlePath(self.initScaleNets_filter, torch.cat((input_0, input_2), dim=1), 'filter')\n with torch.cuda.stream(s1):\n \n cur_offset_outputs0 = self.forward_flownets(self.flownets, input_0, input_2, 0.5, 20, 0)\n \n offset1 = self.FlowProject(cur_offset_outputs0, depth_inv[0])[0]\n if flow_smooth == 0:\n del cur_offset_outputs0\n\n filter1 = self.forward_singlePath(self.initScaleNets_filter1, fSingle, name=None)\n \n if rectify:\n cur_ctx_output0 = torch.cat((self.ctxNet(input_0), log_depth[0]), dim=1)\n ctx0 = self.filterModule(cur_ctx_output0, offset1, filter1)\n del cur_ctx_output0\n ref0 = self.filterModule(input_0, offset1, filter1) * 0.5\n if alpha:\n alpha0 = self.filterModule(input_0_alpha *1.1 , offset1, filter1) * 0.5\n with torch.cuda.stream(s2):\n \n cur_offset_outputs1 = self.forward_flownets(self.flownets, input_2, input_0, 0.5, 20, 0) \n \n offset2 = self.FlowProject(cur_offset_outputs1,depth_inv[1])[0]\n if flow_smooth == 0:\n del cur_offset_outputs1\n\n filter2 = self.forward_singlePath(self.initScaleNets_filter2, fSingle, name=None)\n \n if rectify:\n cur_ctx_output1 = torch.cat((self.ctxNet(input_2), log_depth[1]), dim=1)\n ctx2 = self.filterModule(cur_ctx_output1, offset2, filter2)\n del cur_ctx_output1\n ref2 = self.filterModule(input_2, offset2, filter2) * 0.5\n if alpha:\n alpha2 = self.filterModule(input_2_alpha *1.1 , offset2, filter2) * 0.5\n\n torch.cuda.synchronize()\n\n del fSingle\n cur_output = ref0 + ref2\n if alpha:\n alpha_output = (alpha0 + alpha2).cpu().float()\n\n if not rectify:\n return [None, cur_output],None,None\n\n del log_depth\n del depth_inv\n del input_0\n del input_2\n\n SetTiming(\"End forward_singlePath 2\")\n\n\n torch.cuda.synchronize()\n\n if flow_smooth != 0:\n one = torch.abs(cur_offset_outputs0[0][:, 0, :,:]) + torch.abs(cur_offset_outputs0[0][:, 1, :,:])\n two = torch.abs(cur_offset_outputs1[0][:, 0, :,:]) + torch.abs(cur_offset_outputs1[0][:, 1, :,:])\n\n mem1 = cur_offset_outputs0[0][:, :, :,:]\n mem2 = cur_offset_outputs1[0][:, :, :,:]\n\n one -= 1\n two -= 1\n\n one = torch.clamp(one, min = 0, max=10) / 10\n two = torch.clamp(two, min = 0, max=10) / 10\n\n bigger = torch.max(one, two)\n del two\n\n bigger = bigger.unsqueeze(0)\n one = one.unsqueeze(0)\n\n\n SetTiming(\"End Flow 01 / Start Flow 02\")\n\n depadding = self.depadding\n\n if alpha and convert:\n alpha_output = alpha_output[:, :, depadding[2]:depadding[3], depadding[0]: depadding[1]]\n\n cur_output = cur_output[:, :, depadding[2]:depadding[3], depadding[0]: depadding[1]]\n ref0 = ref0[:, :, depadding[2]:depadding[3], depadding[0]: depadding[1]]\n ref2 = ref2[:, :, depadding[2]:depadding[3], depadding[0]: depadding[1]]\n offset1 = offset1[:, :, depadding[2]:depadding[3], depadding[0]: depadding[1]]\n offset2 = offset2[:, :, depadding[2]:depadding[3], depadding[0]: depadding[1]]\n filter1 = filter1[:, :, depadding[2]:depadding[3], depadding[0]: depadding[1]]\n filter2 = filter2[:, :, depadding[2]:depadding[3], depadding[0]: depadding[1]]\n ctx0 = ctx0[:, :, depadding[2]:depadding[3], depadding[0]: depadding[1]]\n ctx2 = ctx2[:, :, depadding[2]:depadding[3], depadding[0]: depadding[1]]\n\n\n rectify_input = torch.cat((cur_output, ref0),dim =1)\n del ref0\n rectify_input = torch.cat((rectify_input, ref2),dim =1)\n del ref2\n rectify_input = torch.cat((rectify_input, offset1, offset2),dim =1)\n del offset1\n del offset2\n rectify_input = torch.cat((rectify_input, filter1, filter2),dim =1)\n del filter1\n del filter2\n rectify_input = torch.cat((rectify_input, ctx0),dim =1)\n del ctx0\n rectify_input = torch.cat((rectify_input, ctx2),dim =1)\n del ctx2\n \n torch.cuda.synchronize()\n SetTiming(\"End Clean Cache / Start Rectify\")\n \n \n cur_output_rectified = self.rectifyNet(rectify_input) + cur_output\n\n SetTiming(\"End Rectify / Start Ending\")\n \n cur_output_rectified = cur_output_rectified.cpu().float()\n \n if not convert:\n cur_output_rectified = torch.nn.functional.pad(cur_output_rectified, (self.padding[0], self.padding[1] , self.padding[2], self.padding[3]), mode='replicate', value=0)\n \n if flow_smooth != 0:\n \n breetingRoom = flow_force\n\n for flen in range(0, cur_output_rectified.size(0)):\n \n onlyMax = torch.clamp(torch.max(-mem1[flen,:,:,:], mem2[flen,:,:,:]) - breetingRoom, min=0, max=50)\n onlyMin = -torch.clamp(torch.max(mem1[flen,:,:,:], -mem2[flen,:,:,:]) - breetingRoom, min=0, max=50)\n\n onlyAll = (onlyMax + onlyMin)\n\n if self.is_half:\n onlyAll = onlyAll.float()\n\n blurInput = np.transpose(cur_output_rectified[flen,:,:,:].numpy(), (2, 1, 0))\n blurFlow = np.transpose(onlyAll.cpu().numpy(), (2, 1, 0))\n\n \n \n blurred = BlurIt(\n blurInput, blurFlow, flow_smooth / 10.0\n )\n\n cur_output_rectified[flen, :,:,:] = torch.from_numpy(np.transpose(blurred, (2, 1, 0)))\n\n if alpha:\n cur_output_rectified = torch.cat((cur_output_rectified, alpha_output),dim=1) \n cur_outputs = [None, cur_output_rectified]\n else:\n cur_outputs = [None, cur_output_rectified]\n\n SetTiming(\"Finish Ending\")\n return cur_outputs,None,None\n\n def displace(self, im, disp_map):\n im = np.asarray(im)\n disp_map = np.asarray(disp_map)\n grid = np.ogrid[list(map(slice, disp_map.shape[:-1]))]\n result = np.zeros_like(im)\n np.add.at(result, tuple((g + disp_map[..., i]) % im.shape[i]\n for i, g in enumerate(grid)), im)\n return result\n\n \n def forward_flownets(self, model, input1, input2, time_offsets, flow_force, flow_smooth):\n\n if time_offsets == None :\n time_offsets = [0.5]\n elif type(time_offsets) == float:\n time_offsets = [time_offsets]\n elif type(time_offsets) == list:\n pass\n\n\n flow = [nn.Upsample(scale_factor=4, mode='bilinear', align_corners=True)(temp) for temp in [flow_force * model(input1, input2) * 0.5]]\n \n return flow\n \n\n # Each pair of values represents the number of rows and columns\n # that each element will be displaced\n\n '''keep this function'''\n def forward_singlePath(self, modulelist, input, name):\n stack = Stack()\n\n k = 0\n temp = []\n for layers in modulelist: # self.initScaleNets_offset:\n # print(type(layers).__name__)\n # print(k)\n # if k == 27:\n # print(k)\n # pass\n # use the pop-pull logic, looks like a stack.\n if k == 0:\n temp = layers(input)\n else:\n # met a pooling layer, take its input\n if isinstance(layers, nn.AvgPool2d) or isinstance(layers,nn.MaxPool2d):\n stack.push(temp)\n\n temp = layers(temp)\n\n # met a unpooling layer, take its output\n if isinstance(layers, nn.Upsample):\n if name == 'offset':\n temp = torch.cat((temp,stack.pop()),dim=1) # short cut here, but optical flow should concat instead of add\n else:\n temp += stack.pop() # short cut here, but optical flow should concat instead of add\n k += 1\n return temp\n\n '''keep this funtion'''\n def get_MonoNet5(self, channel_in, channel_out, name):\n\n '''\n Generally, the MonoNet is aimed to provide a basic module for generating either offset, or filter, or occlusion.\n\n :param channel_in: number of channels that composed of multiple useful information like reference frame, previous coarser-scale result\n :param channel_out: number of output the offset or filter or occlusion\n :param name: to distinguish between offset, filter and occlusion, since they should use different activations in the last network layer\n\n :return: output the network model\n '''\n model = []\n\n # block1\n model += self.conv_relu(channel_in * 2, 16, (3, 3), (1, 1))\n model += self.conv_relu_maxpool(16, 32, (3, 3), (1, 1), (2, 2)) # THE OUTPUT No.5\n # block2\n model += self.conv_relu_maxpool(32, 64, (3, 3), (1, 1), (2, 2)) # THE OUTPUT No.4\n # block3\n model += self.conv_relu_maxpool(64, 128, (3, 3), (1, 1), (2, 2)) # THE OUTPUT No.3\n # block4\n model += self.conv_relu_maxpool(128, 256, (3, 3), (1, 1), (2, 2)) # THE OUTPUT No.2\n # block5\n model += self.conv_relu_maxpool(256, 512, (3, 3), (1, 1), (2, 2))\n\n # intermediate block5_5\n model += self.conv_relu(512, 512, (3, 3), (1, 1))\n\n # block 6\n model += self.conv_relu_unpool(512, 256, (3, 3), (1, 1), 2) # THE OUTPUT No.1 UP\n # block 7\n model += self.conv_relu_unpool(256, 128, (3, 3), (1, 1), 2) # THE OUTPUT No.2 UP\n # block 8\n model += self.conv_relu_unpool(128, 64, (3, 3), (1, 1), 2) # THE OUTPUT No.3 UP\n\n # block 9\n model += self.conv_relu_unpool(64, 32, (3, 3), (1, 1), 2) # THE OUTPUT No.4 UP\n\n # block 10\n model += self.conv_relu_unpool(32, 16, (3, 3), (1, 1), 2) # THE OUTPUT No.5 UP\n\n # output our final purpose\n branch1 = []\n branch2 = []\n branch1 += self.conv_relu_conv(16, channel_out, (3, 3), (1, 1))\n branch2 += self.conv_relu_conv(16, channel_out, (3, 3), (1, 1))\n\n return (nn.ModuleList(model), nn.ModuleList(branch1), nn.ModuleList(branch2))\n\n '''keep this function'''\n @staticmethod\n def FlowProject(inputs, depth = None):\n if depth is not None:\n outputs = [DepthFlowProjectionModule(input.requires_grad)(input,depth) for input in inputs]\n else:\n outputs = [ FlowProjectionModule(input.requires_grad)(input) for input in inputs]\n return outputs\n\n\n\n '''keep this function'''\n @staticmethod\n def conv_relu_conv(input_filter, output_filter, kernel_size,\n padding):\n\n # we actually don't need to use so much layer in the last stages.\n layers = nn.Sequential(\n nn.Conv2d(input_filter, input_filter, kernel_size, 1, padding),\n nn.ReLU(inplace=True),\n nn.Conv2d(input_filter, output_filter, kernel_size, 1, padding),\n # nn.ReLU(inplace=False),\n # nn.Conv2d(output_filter, output_filter, kernel_size, 1, padding),\n # nn.ReLU(inplace=False),\n # nn.Conv2d(output_filter, output_filter, kernel_size, 1, padding),\n )\n return layers\n\n\n '''keep this fucntion'''\n @staticmethod\n def conv_relu(input_filter, output_filter, kernel_size,\n padding):\n layers = nn.Sequential(*[\n nn.Conv2d(input_filter,output_filter,kernel_size,1, padding),\n\n nn.ReLU(inplace=True)\n ])\n return layers\n\n '''keep this function'''\n @staticmethod\n def conv_relu_maxpool(input_filter, output_filter, kernel_size,\n padding,kernel_size_pooling):\n\n layers = nn.Sequential(*[\n nn.Conv2d(input_filter,output_filter,kernel_size,1, padding),\n\n nn.ReLU(inplace=True),\n\n # nn.BatchNorm2d(output_filter),\n\n nn.MaxPool2d(kernel_size_pooling)\n ])\n return layers\n\n '''klkeep this function'''\n @staticmethod\n def conv_relu_unpool(input_filter, output_filter, kernel_size,\n padding,unpooling_factor):\n\n layers = nn.Sequential(*[\n\n nn.Upsample(scale_factor=unpooling_factor, mode='bilinear' , align_corners=True),\n\n nn.Conv2d(input_filter,output_filter,kernel_size,1, padding),\n\n nn.ReLU(inplace=True),\n\n # nn.BatchNorm2d(output_filter),\n\n\n # nn.UpsamplingBilinear2d(unpooling_size,scale_factor=unpooling_size[0])\n ])\n return layers\n" ]
[ [ "torch.nn.ReLU", "torch.nn.Conv2d" ], [ "torch.abs", "torch.cuda.synchronize", "torch.clamp", "torch.max", "torch.cat", "numpy.asarray", "torch.cuda.current_stream", "torch.nn.ModuleList", "torch.nn.Conv2d", "numpy.transpose", "torch.exp", "torch.nn.MaxPool2d", "torch.nn.init.xavier_uniform_", "torch.nn.Upsample", "numpy.zeros_like", "torch.cuda.stream", "torch.nn.ReLU", "torch.nn.functional.pad" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
qualichat/qualitube
[ "6d1b9b67cc3a6cc41f5d3a6ecfd2d66b3f65c72e" ]
[ "qualitube/video.py" ]
[ "\"\"\"\nMIT License\n\nCopyright (c) 2021 Vítor Mussa\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\"\"\"\n\nfrom typing import Dict, Any, Optional, List\n\nfrom pandas import DataFrame\n\n\n__all__ = ('Video',)\n\n\ndef _try_parse_int(value: Optional[str]) -> Optional[int]:\n if value is None:\n return None\n\n return int(value)\n\n\nclass Video:\n \"\"\"Represents a dataset from a video returned by the Google API.\"\"\"\n\n __slots__ = (\n 'id', 'title', 'description', 'tags', 'view_count', 'like_count',\n 'dislike_count', 'favorite_count', 'comment_count'\n )\n\n def __init__(self, payload: Dict[str, Any]) -> None:\n self.id: Optional[str] = payload.get('id', None)\n\n snippets = payload.get('snippet', {})\n self.title: Optional[str] = snippets.get('title', None)\n self.description: Optional[str] = snippets.get('description', None)\n self.tags: Optional[List[str]] = snippets.get('tags', None)\n\n # Statistics\n statistics = payload.get('statistics', {})\n\n view_count = _try_parse_int(statistics.get('viewCount'))\n self.view_count: Optional[int] = view_count\n\n like_count = _try_parse_int(statistics.get('likeCount'))\n self.like_count = like_count\n\n dislike_count = _try_parse_int(statistics.get('dislikeCount'))\n self.dislike_count = dislike_count\n\n favorite_count = _try_parse_int(statistics.get('favoriteCount'))\n self.favorite_count = favorite_count\n\n comment_count = _try_parse_int(statistics.get('commentCount'))\n self.comment_count = comment_count\n\n def __repr__(self) -> str:\n return f'<Video id={self.id!r}>'\n\n\nclass VideosResponse:\n \"\"\"Represents a response from a Google API video dataset.\"\"\"\n\n __slots__ = ('videos')\n\n def __init__(self, videos: List[Video]) -> None:\n self.videos: List[Video] = videos\n\n def __repr__(self) -> str:\n return f'<VideosResponse videos={self.videos}>'\n\n def to_dataframe(self) -> DataFrame:\n \"\"\"Transforms the video dataset into a dataframe.\"\"\"\n rows: List[List[Any]] = []\n columns = Video.__slots__\n\n for video in self.videos:\n rows.append([\n video.id, video.title, video.description, video.tags, video.view_count,\n video.like_count, video.dislike_count, video.favorite_count,\n video.comment_count\n ])\n \n return DataFrame(rows, columns=columns) # type: ignore\n" ]
[ [ "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": [] } ]
MikhailKitikov/DrivingMonitor
[ "0b698d1ba644ce74e1c7d88c3e18a1ef997aabc0", "0b698d1ba644ce74e1c7d88c3e18a1ef997aabc0", "0b698d1ba644ce74e1c7d88c3e18a1ef997aabc0", "0b698d1ba644ce74e1c7d88c3e18a1ef997aabc0" ]
[ "road situation analysis/research/road/state estimation/sdc/linear_movement_model.py", "road situation analysis/research/road/state estimation/sdc/kalman_filter.py", "driver state analysis/dev/src/drowsiness/eye_blink_service.py", "road situation analysis/research/vehicles/3d detection/FrustumPointnets/frustum_pointnets_detector.py" ]
[ "# -*- coding: utf-8 -*-\nimport numpy as np\nfrom .timestamp import Timestamp\nfrom .movement_model_base import MovementModelBase\n\n\nclass LinearMovementModel(MovementModelBase):\n \"\"\"Продвигает автомобиль вперед с его текущей скоростью\"\"\"\n def __init__(self, *args, **kwargs):\n super(LinearMovementModel, self).__init__(*args, **kwargs)\n\n def _move(self, dt):\n assert isinstance(dt, Timestamp)\n self._car._state = self.move_state(self._car._state, dt)\n self._car._time = self._car._time + dt\n\n def move_state(self, state, dt):\n assert isinstance(dt, Timestamp)\n car = self._car\n state_size = self._car._state_size\n assert state.shape[0] == state_size\n dt_sec = dt.to_seconds()\n x = state[car.POS_X_INDEX]\n y = state[car.POS_Y_INDEX]\n yaw = state[car.YAW_INDEX]\n vel = state[car.VEL_INDEX]\n omega = state[car.OMEGA_INDEX]\n new_state = np.zeros_like(state)\n new_state[car.POS_X_INDEX] = x + vel * np.cos(yaw) * dt_sec\n new_state[car.POS_Y_INDEX] = y + vel * np.sin(yaw) * dt_sec\n new_state[car.YAW_INDEX] = yaw + omega * dt_sec\n new_state[car.VEL_INDEX] = vel\n new_state[car.OMEGA_INDEX] = omega\n return new_state\n", "# -*- coding: utf-8 -*-\nimport numpy as np\n\n\ndef kalman_transit_covariance(S, A, R):\n \"\"\"\n :param S: Current covariance matrix\n :param A: Either transition matrix or jacobian matrix\n :param R: Current noise covariance matrix\n \"\"\"\n state_size = S.shape[0]\n assert S.shape == (state_size, state_size)\n assert A.shape == (state_size, state_size)\n assert R.shape == (state_size, state_size)\n new_S = np.dot(np.dot(A, S), A.T) + R\n return new_S\n\n\ndef kalman_process_observation(mu, S, observation, C, Q):\n \"\"\"\n Performs processing of an observation coming from the model: z = C * x + noise\n :param mu: Current mean\n :param S: Current covariance matrix\n :param observation: Vector z\n :param C: Observation matrix\n :param Q: Noise covariance matrix (with zero mean)\n \"\"\"\n state_size = mu.shape[0]\n observation_size = observation.shape[0]\n assert S.shape == (state_size, state_size)\n assert observation_size == C.shape[0]\n assert observation_size == Q.shape[0]\n H = np.linalg.inv(np.dot(np.dot(C, S), C.T) + Q)\n K = np.dot(np.dot(S, C.T), H)\n new_mu = mu + np.dot(K, observation - np.dot(C, mu))\n new_S = np.dot(np.eye(state_size) - np.dot(K, C), S)\n # Избавляемся от маленьких чисел. Из-за них могут быть мнимые числа в собственных значениях\n new_S[np.abs(new_S) < 1e-16] = 0\n return new_mu, new_S\n", "import tkinter\nfrom tkinter import *\nimport cv2\nimport PIL.Image, PIL.ImageTk\nimport time\nimport argparse\nimport os\nfrom keras import backend as K\nimport tensorflow as tf\nfrom scipy.spatial import distance as dist\nfrom imutils.video import VideoStream\nfrom imutils import face_utils\nfrom threading import Thread\nimport numpy as np\nimport playsound\nimport argparse\nimport imutils\nimport time\nimport dlib\nimport cv2\nimport pyttsx3\nfrom tensorflow.keras.applications.mobilenet_v2 import preprocess_input\nfrom collections import deque\nfrom scipy.spatial import distance as dist\nimport argparse\nimport imutils\nimport time\nimport dlib\nimport cv2\n\n \nclass EyeBlinkService:\n\n\tdef __init__(self, args):\n\n\t\t# build model\n\n\t\tself.face_model = args['face_model']\n\n\t\tprint(\"[INFO] loading face detector...\")\n\t\tif self.face_model == 'CNN':\n\t\t\tself.detector = dlib.cnn_face_detection_model_v1(\"models/mmod_human_face_detector.dat\")\n\t\telse:\n\t\t\tself.detector = dlib.get_frontal_face_detector()\n\n\t\tprint(\"[INFO] loading landmark detector...\")\n\t\tif self.face_model == 'CNN':\n\t\t\tself.predictor = dlib.shape_predictor(\"models/shape_predictor_5_face_landmarks.dat\")\n\t\telse:\n\t\t\tself.predictor = dlib.shape_predictor(\"models/shape_predictor_68_face_landmarks.dat\")\n\t\t\n\t\t# variables\n\n\t\tself.EYE_AR_THRESH = 0.3\n\t\tself.EYE_AR_CONSEC_FRAMES = 48\n\n\t\tself.ear_states = deque(maxlen=50)\n\t\tself.danger_scale_value_ear = 1\n\n\t\t(self.lStart, self.lEnd) = face_utils.FACIAL_LANDMARKS_IDXS[\"left_eye\"]\n\t\t(self.rStart, self.rEnd) = face_utils.FACIAL_LANDMARKS_IDXS[\"right_eye\"]\n\n \n\tdef process(self, args):\n\n\t\tframe = args['frame']\n\t\tALARM_ON = args['ALARM_ON']\n\t\tdanger_value_threshold = args['danger_value_threshold']\n\n\t\tear = self.calculate_ear(frame)\n\t\tear = ear if ear is not None else 0\n\t\tself.ear_states.append(int(ear < self.EYE_AR_THRESH))\n\n\t\tif len(self.ear_states) >= self.ear_states.maxlen:\n\t\t\tclosed_eyes_frac = np.mean(self.ear_states)\n\t\t\tself.danger_scale_value_ear = max(1, min(10, int(round(closed_eyes_frac * 10))))\n\t\t\tALARM_ON = (self.danger_scale_value_ear > danger_value_threshold) & (not ALARM_ON)\n\n\t\treturn {\n\t\t\t'frame': frame,\n\t\t\t'ear': round(ear * 100, 2),\n\t\t\t'danger_scale_value': self.danger_scale_value_ear,\n\t\t\t'ALARM_ON': ALARM_ON,\n\t\t\t'sound_text': \"Please! Watch the road!\"\n\t\t}\n\n\n\tdef calculate_ear(self, frame):\n\n\t\t# convert to gray\n\t\tgray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n\t\t# detect faces\n\t\trects = self.detector(gray, 0)\n\t\tif not rects:\n\t\t\treturn None\n\t\trect = rects[0]\n\n\t\t# detect landmarks\n\t\tif self.face_model == 'CNN':\n\t\t\trect = rect.rect\n\n\t\t# draw face boundaries\n\t\tpt1 = (rect.left(), rect.top())\n\t\tpt2 = (rect.right(), rect.bottom())\n\t\tcv2.rectangle(frame, pt1, pt2, (255, 255, 255), 1)\n\n\t\t# get keypoints\n\t\tshape = self.predictor(gray, rect)\n\t\tshape = face_utils.shape_to_np(shape)\n\n\t\t# visualize keypoints\n\t\tfor (x, y) in shape:\n\t\t\tcv2.circle(frame, (x, y), 1, (255, 255, 255), 2)\n\t\t\n\t\t# extract eye coordinates\n\t\tleftEye = shape[self.lStart: self.lEnd]\n\t\trightEye = shape[self.rStart: self.rEnd]\n\t\t\n\t\t# compute average eye aspect ratio\n\t\tear = (self.eye_aspect_ratio(leftEye) + self.eye_aspect_ratio(rightEye)) / 2\n\t\t\n\t\t# visualize eyes\n\t\tcv2.drawContours(frame, [cv2.convexHull(leftEye)], -1, (0, 255, 0), 1)\n\t\tcv2.drawContours(frame, [cv2.convexHull(rightEye)], -1, (0, 255, 0), 1)\n\n\t\treturn ear\n\n\n\tdef eye_aspect_ratio(self, eye):\n\n\t\tA = dist.euclidean(eye[1], eye[5])\n\t\tB = dist.euclidean(eye[2], eye[4])\n\t\tC = dist.euclidean(eye[0], eye[3])\n\n\t\treturn (A + B) / (2.0 * C)\n\n\n\tdef rotate_image(self, image, angle):\n\n\t\timage_center = tuple(np.array(image.shape[:2]) / 2)\n\t\trot_mat = cv2.getRotationMatrix2D(image_center, angle, 1.0)\n\t\tresult = cv2.warpAffine(image, rot_mat, image.shape[:2], flags=cv2.INTER_CUBIC)\n\n\t\treturn result\n ", "import warnings\nwarnings.filterwarnings(\"ignore\")\n\nimport os\nimport sys\nimport glob\nfrom tqdm import tqdm\nfrom collections import namedtuple\nimport numpy as np\nimport cv2\nimport pickle\nfrom matplotlib import pyplot as plt\n\nsys.path.insert(0, os.path.abspath('frustum_pointnets\\\\train'))\nsys.path.insert(0, os.path.abspath('frustum_pointnets\\\\train\\\\test_mod'))\nsys.path.insert(0, os.path.abspath('frustum_pointnets\\\\kitti'))\n\nfrom ssd import SSD\nimport provider\nfrom test_mod import inference, get_session_and_ops\nfrom kitti_util import Calibration\nfrom kitti_object import get_lidar_in_image_fov, kitti_object\n\n\nDetection = namedtuple('Detection', ['xyz', 'angle', 'lwh', 'confidence'])\nScene = namedtuple('Scene', ['detections'])\n\nclass FrustumPointnetsDetector(object):\n\n\tdef __init__(self, ssd_detector, ssd_threshold, frustum_pointnet, frustum_batch_size, frustum_num_pts):\n\t\t\n\t\tself.ssd_detector = ssd_detector\n\t\tself.ssd_threshold = ssd_threshold\n\t\t\n\t\tself.frustum_pointnet = frustum_pointnet\n\t\tself.frustum_batch_size = frustum_batch_size\n\t\tself.frustum_num_pts = frustum_num_pts\n\t\tself.frustum_sess, self.frustum_ops = get_session_and_ops(self.frustum_batch_size, self.frustum_num_pts)\n\n \n\tdef predict(self, velo_pts, image, calib):\n\n\t\tdetection = self.ssd_detector.predict(image)\n\t\tvehicle_idx = np.where(detection['detection_classes'] == 1)\n\t\tconf_idx = np.where(detection['detection_scores'] >= self.ssd_threshold)\n\t\tfinal_idx = np.intersect1d(vehicle_idx, conf_idx)\n\t\tbbox = detection['detection_boxes'][final_idx] \n\t\tdetection_conf = detection['detection_scores'][final_idx]\n\n\t\trect_pts = np.zeros_like(velo_pts)\n\t\trect_pts[:, :3] = calib.project_velo_to_rect(velo_pts[:, :3].copy())\n\t\trect_pts[:, 3] = velo_pts[:, 3]\n\t\t\n\t\timg_height, img_width, _= image.shape\n\t\t_, img_pts, in_img_mask = get_lidar_in_image_fov(velo_pts[:, :3].copy(), calib, 0, 0, img_width, img_height, return_more=True)\n\t\t \n\t\tfrustum_examples = []\n\t\tfrustum_angles = []\n\t\tscene = Scene([])\n\n\t\tfor box in bbox:\n\t\t\tbox = (box.reshape((2, 2)) * image.shape[:2]).astype(int)\n\t\t\t(ul_y, ul_x), (lr_y, lr_x) = box\n\t\t\tbox_mask = (img_pts[:, 1] < lr_y) * (img_pts[:, 1] >= ul_y) * (img_pts[:, 0] < lr_x) * (img_pts[:, 0] >= ul_x) \n\t\t\t\n\t\t\tmask = in_img_mask & box_mask\n\t\t\trect_pts_masked = rect_pts[mask] \n\n\t\t\tif len(rect_pts_masked):\n\t\t\t\tbox2d_center = np.array([(ul_x + lr_x) / 2.0, (ul_y + ul_y) / 2.0])\n\t\t\t\tuvdepth = np.zeros((1, 3))\n\t\t\t\tuvdepth[0, :2], uvdepth[0, 2] = box2d_center, 10\n\t\t\t\tbox2d_center_rect = calib.project_image_to_rect(uvdepth)\n\t\t\t\tfrustum_angle = -1 * np.arctan2(box2d_center_rect[0, 2], box2d_center_rect[0, 0])\n\t\t\t\tfrustum_angle += np.pi / 2.0\n\t\t\t\t\n\t\t\t\tnp.random.seed()\n\t\t\t\tpoint_cloud = provider.rotate_pc_along_y(rect_pts_masked.copy(), frustum_angle)\n\t\t\t\tidx = np.random.choice(len(point_cloud), size=self.frustum_num_pts, replace=True)\n\t\t\t\tpoint_cloud = point_cloud[idx]\n\t\t\t\t\n\t\t\t\tfrustum_angles.append(frustum_angle)\n\t\t\t\tfrustum_examples.append(point_cloud)\n\t\t\t\n\t\tif len(frustum_examples):\n\t\t\tone_hot_batch = np.array([[1, 0, 0],] * len(frustum_examples)).reshape(-1, 3) \n\n\t\t\tpredictions = self.frustum_pointnet(\n\t\t\t\tself.frustum_sess, self.frustum_ops, np.array(frustum_examples), one_hot_batch, self.frustum_batch_size)\n\t\t\t_, centers, heading_cls, heading_res, size_cls, size_res, _ = predictions\n\n\t\t\tfor i, _ in enumerate(heading_cls): \n\t\t\t\th, w, l, tx, ty, tz, ry = provider.from_prediction_to_label_format(\n\t\t\t\t\tcenters[i], heading_cls[i], heading_res[i], size_cls[i], size_res[i], frustum_angles[i])\n\t\t\t\tdetection = Detection(xyz=np.array((tx, ty, tz)), angle=ry, lwh=np.array((l, w, h)), confidence=detection_conf[i])\n\t\t\t\tscene.detections.append(detection)\n\n\t\t\treturn scene\n\n\nif __name__ == '__main__':\n\n\tssd = SSD('')\n\tdetector = FrustumPointnetsDetector(\n\t\tssd_detector=ssd, ssd_threshold=0.3, frustum_pointnet=inference, frustum_batch_size=1, frustum_num_pts=256)\n\n\tdataset = kitti_object(root_dir='kitti_hw_dataset')\n\n\tidx = 8\n\timg = dataset.get_image(idx)\n\tlidar = dataset.get_lidar(idx)\n\tcalib = dataset.get_calibration(idx)\n\tlabels = dataset.get_label_objects(idx)\n\n\tresult = detector.predict(lidar, img, calib)\n\tprint(result)\n" ]
[ [ "numpy.zeros_like", "numpy.cos", "numpy.sin" ], [ "numpy.dot", "numpy.eye", "numpy.abs" ], [ "numpy.array", "numpy.mean", "scipy.spatial.distance.euclidean" ], [ "numpy.random.seed", "numpy.arctan2", "numpy.intersect1d", "numpy.zeros_like", "numpy.array", "numpy.where", "numpy.zeros" ] ]
[ { "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", "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": [] } ]
ErlingLie/cvat
[ "f053d14955b1e48bf6498466949f4beb1833fe8e" ]
[ "utils/auto_upload/track_on_videos.py" ]
[ "import numpy as np\nimport sys\nimport time\nimport os\nimport json\nimport argparse\n\nfrom sort.sort import Sort\n\ndef track_from_detections(detection_path, output_path, num_classes):\n '''\n Runs tracking on detections and saves result to a json file on form list(class_db)\n Where each class_db is on the form:\n - track id\n - list of bboxes on form [x0, y0, x1, y1, frame_nmbr]\n '''\n trackers = []\n #Instanciate one tracker per class\n for i in range(num_classes):\n tracker = Sort(5,1)\n trackers.append(tracker)\n\n with open(detection_path, \"r\") as json_file:\n data = json.load(json_file)\n tracks = [{} for i in range(num_classes)]\n for frame_nmbr, frame_detections in data.items():\n frame_nmbr = int(frame_nmbr)\n for class_id, class_detections in frame_detections.items():\n class_id = int(class_id)\n class_tracks = trackers[class_id].update(np.array(class_detections))\n for track in class_tracks: #Tracks are on form [x0, y0, x1, y1, id]\n if int(track[-1]) in tracks[class_id].keys():\n tracks[class_id][int(track[-1])].append(track[:4].tolist() + [frame_nmbr])\n else:\n tracks[class_id][int(track[-1])] = [track[:4].tolist() + [frame_nmbr]]\n\n with open(output_path, \"w\") as json_file:\n json.dump(tracks, json_file)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Interface for running detection on videos\")\n parser.add_argument(\"input\", type=str, help = \"Directory for input jsons\")\n parser.add_argument(\"output\", type=str, help = \"Directory for output jsons\")\n parser.add_argument(\"--num_classes\", default=1, type=int, help=\"Number of classes in dataset\")\n args = parser.parse_args()\n\n if not os.path.exists(args.output):\n os.mkdir(args.output)\n print(\"Directory\" , args.output , \"Created \")\n detections = os.listdir(args.input)\n for detection in detections:\n output_path = os.path.join(args.output, detection)\n input_path = os.path.join(args.input, detection)\n print(\"Starting tracking on file: \" + output_path)\n track_from_detections(input_path, output_path, args.num_classes)" ]
[ [ "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Koomook/nsmc
[ "64fb83769072be3822f663383d0855dd66c92855", "64fb83769072be3822f663383d0855dd66c92855" ]
[ "code/partition.py", "classifier/trainer.py" ]
[ "#! /usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport numpy as np; np.random.seed(1234)\nimport pandas as pd\n\n\nntrain = 150000\n\ndata = pd.read_csv('../ratings.txt', sep='\\t', quoting=3)\ndata = pd.DataFrame(np.random.permutation(data))\ntrn, tst = data[:ntrain], data[ntrain:]\n\nheader = 'id document label'.split()\ntrn.to_csv('../ratings_train.txt', sep='\\t', index=False, header=header)\ntst.to_csv('../ratings_test.txt', sep='\\t', index=False, header=header)\n", "import tensorflow as tf\nimport numpy as np\n\nimport os, json\nimport logging\nfrom datetime import datetime\nfrom tensorflow.python.tools import freeze_graph\n\n\nclass StepBasedTrainer():\n \"\"\"A optimizer that takes batch generator\n\n Attibutes:\n optimizer: A optimizer produced by a optimizer\n loss: model's loss equation\n placeholders: model's input placeholders\n learning_rate: a tensor holding current learning rate (produced by optimizer)\n batch_size: number of examples to train per one step\n checkpoint_dir: directory to store tensorflow checkpoints\n model_filename: filename of model in checkpoints\n checkpoint_path: filepath of tensorflow checkpoint\n saver: to save model\n session: tensorflow session\n \"\"\"\n\n def __init__(self, \n optimizer, \n loss, \n acc, \n placeholders,\n keep_prob_placeholder,\n keep_prob, \n lr_placeholder, \n model_channel,\n max_step=100000, \n print_step=100, \n save_step=1000, \n warmup_step=None,\n project_name='temp', \n model_filename='model_ckpt'\n ):\n \"\"\"Initialize generator-based optimizer runner\n\n Args:\n project_name: name of your project (must be unique)\n optimizer: tensorflow optimizer\n \"\"\"\n\n self.optimizer = optimizer\n self.loss = loss\n self.acc = acc\n self.placeholders = placeholders\n self.keep_prob_placeholder = keep_prob_placeholder\n self.keep_prob = keep_prob\n self.lr_placeholder = lr_placeholder\n\n self.scaled_channel = model_channel**(-0.5)\n self.max_step = max_step\n self.print_step = print_step\n self.save_step = save_step\n \n if warmup_step:\n self.warmup_step = warmup_step\n else:\n self.warmup_step = 4000 # default value is 4000 warmupstep per 100000 steps\n\n self.session = tf.Session()\n self.saver = tf.train.Saver(max_to_keep=10)\n\n self.project_name = project_name\n self.checkpoint_dir = os.path.join('checkpoints', self.project_name)\n if not os.path.isdir(self.checkpoint_dir):\n print('new training start : {}'.format(project_name))\n os.mkdir(self.checkpoint_dir)\n tf.global_variables_initializer().run(session=self.session)\n# self.session.graph.finalize()\n self.step = 1\n else:\n try:\n latest_path = tf.train.latest_checkpoint(self.checkpoint_dir)\n self.saver.restore(self.session, latest_path)\n self.step = int(latest_path.split('-')[-1])\n except:\n print('something')\n tf.global_variables_initializer().run(session=self.session)\n# self.session.graph.finalize()\n self.step = 1\n\n self.model_filename = model_filename\n self.checkpoint_path = os.path.join(self.checkpoint_dir, self.model_filename)\n\n self.loss_list = []\n self.acc_list = []\n\n logging.basicConfig(level=logging.INFO,\n format='%(asctime)s | %(message)s',\n datefmt='%m-%d %H:%M:%S',\n filename='{}/{}.log'.format(\n self.checkpoint_dir, datetime.now()),\n filemode='a'\n )\n\n consoleHandler = logging.StreamHandler(os.sys.stdout)\n consoleTitle = logging.StreamHandler()\n logging.getLogger().addHandler(consoleHandler)\n\n self.logger = logging.getLogger()\n\n def run(self, train_batch_producer, valid_batch_producer):\n \"\"\"Run optimizer with given training and validation dataset\n This prints training logs and save the model during the training\n\n Args:\n train_batch_producer: a generator that produces training data to feed model\n valid_batch_producer: a generator that produces valid data to feed model\n \"\"\"\n print('It runs')\n lr = min(self.step**(-0.5), self.step*self.warmup_step**(-1.5))*self.scaled_channel\n while self.step < self.max_step+1:\n # set learning rate\n if self.step < self.warmup_step:\n b = self.step*(self.warmup_step**(-1.5))\n else:\n b = self.step**(-0.5)\n lr = self.scaled_channel * b\n\n data_batch = next(train_batch_producer)\n self.feed_dict = {}\n zipped = zip(self.placeholders, data_batch)\n self.feed_dict.update(zipped)\n self.feed_dict.update({self.keep_prob_placeholder:self.keep_prob})\n self.feed_dict.update({self.lr_placeholder:lr})\n \n _, loss_value, acc = self.session.run([self.optimizer, self.loss, self.acc], feed_dict=self.feed_dict)\n self.loss_list.append(loss_value)\n self.acc_list.append(acc)\n\n if self.step % self.print_step == 0:\n\n average_loss = np.mean(self.loss_list)\n average_acc = np.mean(self.acc_list)\n\n valid_batch = next(valid_batch_producer)\n valid_dict = {}\n zipped = zip(self.placeholders, valid_batch)\n valid_dict.update(zipped)\n valid_dict.update({self.keep_prob_placeholder:1.0})\n valid_loss, valid_acc = self.session.run([self.loss, self.acc], feed_dict=valid_dict)\n # Leave log\n base_message = (\"Step: {step:<6d} \"\n \" Training Loss: {train_loss:<.6}\"\n \" Valid Loss: {valid_loss:<.6}\"\n \" Training Accuracy: {train_acc:<.3}\"\n \" Valid Accuracy: {valid_acc:<.3}\"\n \" Learning rate: {learning_rate:<.6} \")\n\n message = base_message.format(\n step=self.step,\n train_loss=average_loss,\n valid_loss=valid_loss,\n train_acc=average_acc,\n valid_acc=valid_acc,\n learning_rate=lr\n )\n\n self.logger.info(message)\n\n self.loss_list = [] # initialize\n self.acc_list = []\n\n # Save\n if self.step % self.save_step == 0:\n self.saver.save(self.session, self.checkpoint_path, global_step=self.step)\n\n self.step += 1\n print('done')" ]
[ [ "numpy.random.permutation", "pandas.read_csv", "numpy.random.seed" ], [ "tensorflow.train.latest_checkpoint", "tensorflow.global_variables_initializer", "numpy.mean", "tensorflow.Session", "tensorflow.train.Saver" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]