repo_name
stringlengths
6
130
hexsha
list
file_path
list
code
list
apis
list
JyotiJanai/test
[ "c4d536a208c10e6465864f1029ee90f371991276" ]
[ "modules/python/test/tests_common.py" ]
[ "#!/usr/bin/env python\n\nfrom __future__ import print_function\n\nimport unittest\nimport sys\nimport hashlib\nimport os\nimport numpy as np\nimport cv2\nimport cv2.cv as cv\n\n# Python 3 moved urlopen to urllib.requests\ntry:\n from urllib.request import urlopen\nexcept ImportError:\n from urllib import urlopen\n\nclass OpenCVTests(unittest.TestCase):\n\n # path to local repository folder containing 'samples' folder\n repoPath = None\n # github repository url\n repoUrl = 'https://raw.github.com/opencv/opencv/2.4'\n # path to local folder containing 'camera_calibration.tar.gz'\n dataPath = None\n # data url\n dataUrl = 'http://docs.opencv.org/data'\n\n depths = [ cv.IPL_DEPTH_8U, cv.IPL_DEPTH_8S, cv.IPL_DEPTH_16U, cv.IPL_DEPTH_16S, cv.IPL_DEPTH_32S, cv.IPL_DEPTH_32F, cv.IPL_DEPTH_64F ]\n\n mat_types = [\n cv.CV_8UC1,\n cv.CV_8UC2,\n cv.CV_8UC3,\n cv.CV_8UC4,\n cv.CV_8SC1,\n cv.CV_8SC2,\n cv.CV_8SC3,\n cv.CV_8SC4,\n cv.CV_16UC1,\n cv.CV_16UC2,\n cv.CV_16UC3,\n cv.CV_16UC4,\n cv.CV_16SC1,\n cv.CV_16SC2,\n cv.CV_16SC3,\n cv.CV_16SC4,\n cv.CV_32SC1,\n cv.CV_32SC2,\n cv.CV_32SC3,\n cv.CV_32SC4,\n cv.CV_32FC1,\n cv.CV_32FC2,\n cv.CV_32FC3,\n cv.CV_32FC4,\n cv.CV_64FC1,\n cv.CV_64FC2,\n cv.CV_64FC3,\n cv.CV_64FC4,\n ]\n mat_types_single = [\n cv.CV_8UC1,\n cv.CV_8SC1,\n cv.CV_16UC1,\n cv.CV_16SC1,\n cv.CV_32SC1,\n cv.CV_32FC1,\n cv.CV_64FC1,\n ]\n\n def depthsize(self, d):\n return { cv.IPL_DEPTH_8U : 1,\n cv.IPL_DEPTH_8S : 1,\n cv.IPL_DEPTH_16U : 2,\n cv.IPL_DEPTH_16S : 2,\n cv.IPL_DEPTH_32S : 4,\n cv.IPL_DEPTH_32F : 4,\n cv.IPL_DEPTH_64F : 8 }[d]\n\n def get_sample(self, filename, iscolor = cv.CV_LOAD_IMAGE_COLOR):\n if not filename in self.image_cache:\n filedata = None\n if OpenCVTests.repoPath is not None:\n candidate = OpenCVTests.repoPath + '/' + filename\n if os.path.isfile(candidate):\n with open(candidate, 'rb') as f:\n filedata = f.read()\n if filedata is None:\n filedata = urllib.urlopen(OpenCVTests.repoUrl + '/' + filename).read()\n imagefiledata = cv.CreateMatHeader(1, len(filedata), cv.CV_8UC1)\n cv.SetData(imagefiledata, filedata, len(filedata))\n self.image_cache[filename] = cv.DecodeImageM(imagefiledata, iscolor)\n return self.image_cache[filename]\n\n def get_data(self, filename, urlbase):\n if (not os.path.isfile(filename)):\n if OpenCVTests.dataPath is not None:\n candidate = OpenCVTests.dataPath + '/' + filename\n if os.path.isfile(candidate):\n return candidate\n urllib.urlretrieve(urlbase + '/' + filename, filename)\n return filename\n\n def setUp(self):\n self.image_cache = {}\n\n def snap(self, img):\n self.snapL([img])\n\n def snapL(self, L):\n for i,img in enumerate(L):\n cv.NamedWindow(\"snap-%d\" % i, 1)\n cv.ShowImage(\"snap-%d\" % i, img)\n cv.WaitKey()\n cv.DestroyAllWindows()\n\n def hashimg(self, im):\n \"\"\" Compute a hash for an image, useful for image comparisons \"\"\"\n return hashlib.md5(im.tostring()).digest()\n\n\nclass NewOpenCVTests(unittest.TestCase):\n\n # path to local repository folder containing 'samples' folder\n repoPath = None\n extraTestDataPath = None\n # github repository url\n repoUrl = 'https://raw.github.com/opencv/opencv/master'\n\n def get_sample(self, filename, iscolor = cv2.IMREAD_COLOR):\n if not filename in self.image_cache:\n filedata = None\n if NewOpenCVTests.repoPath is not None:\n candidate = NewOpenCVTests.repoPath + '/' + filename\n if os.path.isfile(candidate):\n with open(candidate, 'rb') as f:\n filedata = f.read()\n if NewOpenCVTests.extraTestDataPath is not None:\n candidate = NewOpenCVTests.extraTestDataPath + '/' + filename\n if os.path.isfile(candidate):\n with open(candidate, 'rb') as f:\n filedata = f.read()\n if filedata is None:\n return None#filedata = urlopen(NewOpenCVTests.repoUrl + '/' + filename).read()\n self.image_cache[filename] = cv2.imdecode(np.fromstring(filedata, dtype=np.uint8), iscolor)\n return self.image_cache[filename]\n\n def setUp(self):\n cv2.setRNGSeed(10)\n self.image_cache = {}\n\n def hashimg(self, im):\n \"\"\" Compute a hash for an image, useful for image comparisons \"\"\"\n return hashlib.md5(im.tostring()).hexdigest()\n\n if sys.version_info[:2] == (2, 6):\n def assertLess(self, a, b, msg=None):\n if not a < b:\n self.fail('%s not less than %s' % (repr(a), repr(b)))\n\n def assertLessEqual(self, a, b, msg=None):\n if not a <= b:\n self.fail('%s not less than or equal to %s' % (repr(a), repr(b)))\n\n def assertGreater(self, a, b, msg=None):\n if not a > b:\n self.fail('%s not greater than %s' % (repr(a), repr(b)))\n\ndef intersectionRate(s1, s2):\n\n x1, y1, x2, y2 = s1\n s1 = np.array([[x1, y1], [x2,y1], [x2, y2], [x1, y2]])\n\n x1, y1, x2, y2 = s2\n s2 = np.array([[x1, y1], [x2,y1], [x2, y2], [x1, y2]])\n\n area, intersection = cv2.intersectConvexConvex(s1, s2)\n return 2 * area / (cv2.contourArea(s1) + cv2.contourArea(s2))\n\ndef isPointInRect(p, rect):\n if rect[0] <= p[0] and rect[1] <=p[1] and p[0] <= rect[2] and p[1] <= rect[3]:\n return True\n else:\n return False\n" ]
[ [ "numpy.array", "numpy.fromstring" ] ]
patricialarsen/descqa
[ "5b9b168751238b2c36a59a4339872c85730181a4" ]
[ "descqa/SizeDistribution.py" ]
[ "import os\nimport numpy as np\nfrom itertools import count\nimport re\nfrom .base import BaseValidationTest, TestResult\nfrom .plotting import plt\nfrom .utils import get_opt_binpoints\n\n__all__ = ['SizeDistribution']\n\nclass SizeDistribution(BaseValidationTest):\n \"\"\"\n validation test to check the slope of the size distribution at small sizes.\n \"\"\"\n\n #plotting constants\n validation_color = 'black'\n validation_marker = 'o'\n default_markers = ['v', 's', 'd', 'H', '^', 'D', 'h', '<', '>', '.']\n msize = 4 #marker-size\n yaxis_xoffset = 0.02\n yaxis_yoffset = 0.5\n\n def __init__(self, **kwargs):\n #pylint: disable=W0231\n #validation data\n validation_filepath = os.path.join(self.data_dir, kwargs['data_filename'])\n self.validation_data = np.loadtxt(validation_filepath)\n \n self.acceptable_keys = kwargs['possible_size_fields']\n self.acceptable_mag_keys = kwargs['possible_mag_fields']\n self.fontsize = kwargs.get('fontsize', 15)\n self.lgnd_fontsize = kwargs.get('lgnd_fontsize', 12)\n self.truncate_cat_name = kwargs.get('truncate_cat_name', True)\n self.truncate_key_name = kwargs.get('truncate_key_name', True)\n \n self._color_iterator = ('C{}'.format(i) for i in count())\n\n def run_on_single_catalog(self, catalog_instance, catalog_name, output_dir):\n # update color and marker to preserve catalog colors and markers across tests\n catalog_color = next(self._color_iterator)\n\n # check catalog data for required quantities\n key = catalog_instance.first_available(*self.acceptable_keys)\n if not key:\n summary = 'Missing required quantity' + ' or '.join(['{}']*len(self.acceptable_keys))\n return TestResult(skipped=True, summary=summary.format(*self.acceptable_keys))\n mag_key = catalog_instance.first_available(*self.acceptable_mag_keys)\n if not mag_key:\n summary = 'Missing required quantity' + ' or '.join(['{}']*len(self.acceptable_mag_keys))\n return TestResult(skipped=True, summary=summary.format(*self.acceptable_mag_keys))\n\n # get data\n catalog_data = catalog_instance.get_quantities([key, mag_key])\n sizes = catalog_data[key][catalog_data[mag_key]<25.2]\n good_data_mask = np.logical_not(np.logical_or(np.isinf(sizes), np.isnan(sizes)))\n sizes = sizes[good_data_mask]\n non_neg_mask = sizes > 0\n if np.sum(non_neg_mask) > 0:\n print('Warning: some sizes were negative or zero; these are being masked')\n sizes = sizes[non_neg_mask]\n min_sizes = np.min(sizes)\n max_sizes = np.max(sizes)\n\n if self.truncate_cat_name:\n catalog_name = re.split('_', catalog_name)[0]\n \n # Compute N(size) and its slope at the small end.\n # Things seem to be roughly linear where N(size)>0.5*Ntot so use those points.\n # Get ~20 points for the line fit, but compute the whole graph\n median = np.median(sizes)\n n_bins = int(20*(max_sizes-min_sizes)/(median-min_sizes))\n N, bin_edges = np.histogram(sizes, bins=n_bins)\n sumM = np.histogram(sizes, weights=sizes, bins=bin_edges)[0]\n sumM2 = np.histogram(sizes, weights=sizes**2, bins=bin_edges)[0]\n size_pts = get_opt_binpoints(N, sumM, sumM2, bin_edges)\n diff = size_pts[1:] - size_pts[:-1]\n if not np.all(diff >= 0):\n # Sparsely populated bins sometimes cause problems for\n # get_opt_binpoints; replace with the dumb solution\n size_pts = 0.5*(bin_edges[:-1]+bin_edges[1:])\n\n mask = size_pts < median\n\n # Normalize so we can compare datasets of different sizes\n cumul_N_norm = np.array(\n [1.0*np.sum(N[-i-1:]) for i in range(len(N))], dtype=float\n )[::-1]/np.sum(N)\n data_slope, data_intercept = np.polyfit(size_pts[mask], cumul_N_norm[mask], 1)\n \n # Compute the slope for the validation dataset in this size range.\n # Copy the validation dataset so we can play with it\n validation_data = self.validation_data.copy()\n validation_mask = (validation_data[:, 0] > min_sizes) & (validation_data[:, 0] < median)\n validation_data[:, 1] /= validation_data[validation_mask, 1][0]\n validation_slope, _ = np.polyfit(validation_data[validation_mask, 0],\n validation_data[validation_mask, 1], 1)\n\n # plot a histogram of sizes. This is easier to see as log(sizes) so do that.\n fig, (hist_ax, cumul_ax) = plt.subplots(1, 2)\n fig.subplots_adjust(wspace=0.4)\n xname = key if not self.truncate_key_name else re.split('_', key)[0]\n hist_ax.hist(np.log10(sizes), color=catalog_color, edgecolor='black', alpha=0.75,\n density=True, bins=20)\n hist_ax.set_xlabel(\"$\\\\log_{{10}}(\\\\rm{{{}/arcsec}})$\".format(xname), fontsize=self.fontsize)\n hist_ax.set_ylabel(\"$dN/d\\\\log_{{10}}(\\\\rm{{{}/arcsec}})$\".format(xname), fontsize=self.fontsize)\n \n # plot the CDF and the line fit\n cumul_ax.plot(np.log10(size_pts), cumul_N_norm,\n color=catalog_color, label='{}: ${:.2f}$'.format(catalog_name, data_slope))\n cumul_ax.plot(np.log10(size_pts[mask]), (data_intercept+data_slope*size_pts[mask]), color='gray',\n label='COSMOS: ${:.2f}$'.format(validation_slope))\n #cumul_ax.set_xscale('log')\n #cumul_ax.text(0.95, 0.96,\n # 'COSMOS: ${:.2f}$\\n{}: ${:.2f}$'.format(validation_slope, catalog_name, data_slope),\n # horizontalalignment='right', verticalalignment='top',\n # transform=cumul_ax.transAxes)\n cumul_ax.set_xlabel(\"$\\\\log_{{10}}(\\\\rm{{{}/arcsec}})$\".format(xname), fontsize=self.fontsize)\n cumul_ax.set_ylabel(\"$N(\\\\rm{{{}}}$)\".format(xname), fontsize=self.fontsize)\n cumul_ax.legend(loc='upper right', title='Slopes', fontsize=self.lgnd_fontsize)\n cumul_ax.set_ylim(-0.05, 1.4) #force room for legend\n \n with open(os.path.join(output_dir, 'size_distribution_{}.txt'.format(catalog_name)), 'w'\n ) as f:\n f.write(\"# Slope, intercept\\n\")\n f.write(\"%7f %9f\\n\"%(data_slope, data_intercept))\n\n fig.savefig(os.path.join(output_dir, 'size_distribution_{}.png'.format(catalog_name)))\n plt.close(fig)\n return TestResult(score=data_slope/validation_slope,\n passed=(0.5<=(data_slope/validation_slope)<=2.0))\n\n\n" ]
[ [ "numpy.max", "numpy.histogram", "numpy.isinf", "numpy.isnan", "numpy.median", "numpy.sum", "numpy.min", "numpy.loadtxt", "numpy.polyfit", "numpy.all", "numpy.log10" ] ]
samehkamaleldin/libkge
[ "e1204cb78bb91ffe3126df62d2d14b20da950694", "e1204cb78bb91ffe3126df62d2d14b20da950694" ]
[ "libkge/io/base.py", "tests/libkge/util/test_kg.py" ]
[ "# -*- coding: utf-8 -*-\n\nimport gzip\nimport bz2\nimport numpy as np\n\n\ndef advanced_open(filepath, *args, **kwargs):\n \"\"\" Open function interface for files with different extensions.\n\n Parameters\n ----------\n filepath: str\n File path with extension.\n args: list\n Non-key arguments\n kwargs: dict\n Key arguments\n\n Returns\n -------\n\n \"\"\"\n open_fn = open\n if filepath.endswith('.gz'):\n open_fn = gzip.open\n elif filepath.endswith('.bz2'):\n open_fn = bz2.open\n\n return open_fn(filepath, mode=\"rt\", *args, **kwargs)\n\n\ndef load_kg_file(filepath, separator=\"\\t\", as_stream=False):\n \"\"\" Import knowledge graph from file\n\n Parameters\n ----------\n filepath: str\n File path\n separator: str\n File column separator\n\n Returns\n -------\n iterator\n The knowledge graph triplets obtained from the files with size [?, 3]\n \"\"\"\n\n kg_triples = []\n with advanced_open(filepath) as file_content:\n for line in file_content:\n kg_triples.append(line.strip().split(separator))\n return np.array(kg_triples)\n\n\ndef load_kg_file_as_stream(filepath, separator=\"\\t\"):\n \"\"\" Import knowledge graph from file as a stream\n\n Parameters\n ----------\n filepath: str\n File path\n separator: str\n File column separator\n\n Returns\n -------\n generator\n The knowledge graph triplets obtained from the files with size [?, 3]\n \"\"\"\n\n with advanced_open(filepath) as file_content:\n for line in file_content:\n yield line.strip().split(separator)", "# -*- coding: utf-8 -*-\n\nfrom libkge.util import KgDataset\nimport numpy as np\n\ntriples = np.array([\n ['a', 'friend-of', 'b'],\n ['a', 'parent-of', 'c'],\n ['k', 'brother-of', 'c'],\n ['a', 'parent-of', 'k'],\n ['k', 'friend-of', 'k'],\n ['k', 'friend-of', 'c'],\n ['b', 'friend-of', 'c'],\n])\n\n\ndef test_load_triplets():\n \"\"\"\n\n \"\"\"\n dataset = KgDataset()\n dataset.load_triples(triples)\n\n assert dataset.data[\"default\"].shape == triples.shape\n\n dataset.load_triples(triples, \"train\")\n assert dataset.data[\"train\"].shape == triples.shape\n\n\ndef test_conversion():\n \"\"\"\n\n \"\"\"\n dataset = KgDataset()\n dataset.load_triples(triples)\n\n triples_idx = dataset.data[\"default\"]\n triples_labels = dataset.indices2labels(triples_idx)\n triples_labels2idx = dataset.labels2indices(triples_labels)\n assert (triples_labels == triples).all()\n assert (triples_labels2idx == triples_idx).all()\n\n\ndef test_ent_rel_counts():\n \"\"\"\n\n \"\"\"\n dataset = KgDataset()\n dataset.load_triples(triples)\n\n ent_count = dataset.get_ents_count()\n rel_count = dataset.get_rels_count()\n\n assert ent_count == 4\n assert rel_count == 3\n\n" ]
[ [ "numpy.array" ], [ "numpy.array" ] ]
lgrcia/prose
[ "bf5482f775eb8cfee261620901cebafb6edb650a", "bf5482f775eb8cfee261620901cebafb6edb650a" ]
[ "prose/blocks/psf.py", "prose/io/io.py" ]
[ "from scipy.optimize import minimize\nimport warnings\nimport numpy as np\nfrom astropy.io import fits\nfrom astropy.table import Table\nfrom astropy.nddata import NDData\nfrom photutils.psf import extract_stars\nfrom astropy.stats import gaussian_sigma_to_fwhm\nfrom ..core import Block\nimport matplotlib.pyplot as plt\nfrom collections import OrderedDict\nfrom ..utils import fast_binning\n\ndef image_psf(image, stars, size=15, normalize=False, return_cutouts=False):\n \"\"\"\n Get global psf from image using photutils routines\n\n Parameters\n ----------\n image: np.ndarray or path\n stars: np.ndarray\n stars positions with shape (n,2)\n size: int\n size of the cuts around stars (in pixels)\n normalize: bool, optional\n weather to normalize the cutout, default is False\n\n Returns\n -------\n np.ndarray of shape (size, size)\n\n \"\"\"\n _, cuts = cutouts(image, stars, size=size)\n cuts = cuts.data\n if normalize:\n cuts = [c/np.sum(c) for c in cuts]\n if return_cutouts:\n return np.median(cuts, axis=0), cuts\n else:\n return np.median(cuts, axis=0)\n\n\ndef cutouts(image, stars, size=15):\n \"\"\"Custom version to extract stars cutouts\n\n Parameters\n ----------\n Parameters\n ----------\n image: np.ndarray or path\n stars: np.ndarray\n stars positions with shape (n,2)\n size: int\n size of the cuts around stars (in pixels), by default 15\n\n Returns\n -------\n np.ndarray of shape (size, size)\n \n \"\"\"\n if isinstance(image, str):\n image = fits.getdata(image)\n\n warnings.simplefilter(\"ignore\")\n if np.shape(stars) > (1,2):\n stars_tbl = Table(\n [stars[:, 0], stars[:, 1], np.arange(len(stars))],\n names=[\"x\", \"y\", \"id\"])\n stars = extract_stars(NDData(data=image), stars_tbl, size=size)\n idxs = np.array([s.id_label for s in stars])\n return idxs, stars\n else:\n stars_tbl = Table(\n data=np.array([stars[0][0], stars[0][1]]),\n names=[\"x\", \"y\"])\n stars = extract_stars(NDData(data=image), stars_tbl, size=size)\n return stars\n\n\ndef good_cutouts(image, xy, r=30, upper=40000, lower=1000, trim=100):\n idxs, _cuts = cutouts(image, xy, r)\n cuts = OrderedDict(zip(idxs, _cuts))\n peaks = [cutout.data.max() for cutout in cuts.values()]\n\n for i, cutout in cuts.copy().items():\n if i in cuts:\n peak = cutout.data.max()\n center = cutout.center\n\n # removing saturated and faint stars\n if peak > upper or peak < lower:\n del cuts[i]\n\n # removing stars on borders\n elif np.any(center < [trim, trim]) or np.any(center > np.array(image.shape) - trim):\n del cuts[i]\n\n # removing close stars\n closest = idxs[np.nonzero(np.linalg.norm(center - xy[idxs], axis=1) < r)[0]]\n if len(closest) > 1:\n for j in closest:\n if j in cuts:\n del cuts[j]\n\n return cuts\n\n\ndef moments(data):\n \"\"\"Returns (height, x, y, width_x, width_y)\n the gaussian parameters of a 2D distribution by calculating its\n moments \"\"\"\n height = data.max()\n background = data.min()\n data = data-np.min(data)\n total = data.sum()\n x, y = np.indices(data.shape)\n x = (x * data).sum() / total\n y = (y * data).sum() / total\n col = data[:, int(y)]\n width_x = np.sqrt(abs((np.arange(col.size) - y) ** 2 * col).sum() / col.sum())\n row = data[int(x), :]\n width_y = np.sqrt(abs((np.arange(row.size) - x) ** 2 * row).sum() / row.sum())\n width_x /= gaussian_sigma_to_fwhm\n width_y /= gaussian_sigma_to_fwhm\n return height, x, y, width_x, width_y, 0.0, background\n\n\nclass PSFModel(Block):\n\n def __init__(self, cutout_size=21, save_cutouts=False, **kwargs):\n super().__init__(**kwargs)\n self.cutout_size = cutout_size\n self.save_cutouts = save_cutouts\n self.x, self.y = np.indices((self.cutout_size, self.cutout_size))\n self.epsf = None\n\n @property\n def optimized_model(self):\n return self.model(*self.optimized_params)\n\n def build_epsf(self, image, stars):\n return image_psf(image, stars.copy(), size=self.cutout_size, return_cutouts=self.save_cutouts)\n\n def model(self):\n raise NotImplementedError(\"\")\n\n def nll(self, p):\n ll = np.sum(np.power((self.model(*p) - self.epsf), 2) * self.epsf)\n return ll if np.isfinite(ll) else 1e25\n \n def optimize(self):\n raise NotImplementedError(\"\")\n\n def sigma_to_fwhm(self, *args):\n return gaussian_sigma_to_fwhm\n\n def run(self, image):\n if self.save_cutouts:\n self.epsf, image.cutouts = self.build_epsf(image.data, image.stars_coords)\n else:\n self.epsf = self.build_epsf(image.data, image.stars_coords)\n image.fwhmx, image.fwhmy, image.theta = self.optimize()\n image.fwhm = np.mean([image.fwhmx, image.fwhmy])\n image.psf_sigma_x = image.fwhmx / self.sigma_to_fwhm()\n image.psf_sigma_y = image.fwhmy / self.sigma_to_fwhm()\n image.header[\"FWHM\"] = image.fwhm\n image.header[\"FWHMX\"] = image.fwhmx\n image.header[\"FWHMY\"] = image.fwhmy\n image.header[\"PSFANGLE\"] = image.theta\n image.header[\"FWHMALG\"] = self.__class__.__name__\n\n def show_residuals(self):\n plt.imshow(self.epsf - self.optimized_model)\n plt.colorbar()\n ax = plt.gca()\n plt.text(0.05, 0.05, \"$\\Delta f=$ {:.2f}%\".format(100*np.sum(np.abs(self.epsf - self.optimized_model))/np.sum(self.epsf)), \n fontsize=14, horizontalalignment='left', verticalalignment='bottom', transform=ax.transAxes, c=\"w\")\n\n def __call__(self, data):\n self.epsf = data\n return self.optimize()\n\n\nclass FWHM(PSFModel):\n \"\"\"\n Fast empirical FWHM (based on Arielle Bertrou-Cantou's idea)\n \"\"\"\n\n def __init__(self, cutout_size=51, **kwargs):\n super().__init__(cutout_size=cutout_size, **kwargs)\n Y, X = np.indices((self.cutout_size,self.cutout_size))\n x = y = self.cutout_size/2\n self.radii = (np.sqrt((X - x) ** 2 + (Y - y) ** 2)).flatten()\n\n def optimize(self):\n psf = self.epsf.copy()\n psf -= np.min(psf)\n pixels = psf.flatten()\n binned_radii, binned_pixels, _ = fast_binning(self.radii, pixels, bins=1)\n fwhm = 2*binned_radii[np.flatnonzero(binned_pixels > np.max(binned_pixels)/2)[-1]]\n return fwhm, fwhm, 0\n\nclass FastGaussian(PSFModel):\n \"\"\"\n Fit a symetric 2D Gaussian model to an image effective PSF\n \"\"\"\n def __init__(self, cutout_size=21, **kwargs):\n super().__init__(cutout_size=cutout_size, **kwargs)\n\n def model(self, height, s, m):\n dx = self.x - self.cutout_size/2\n dy = self.y - self.cutout_size/2\n psf = height * np.exp(-((dx/(2*s))**2 + (dy/(2*s))**2))\n return psf + m\n\n def optimize(self):\n p0 = [np.max(self.epsf), 4, np.min(self.epsf)]\n min_sigma = 0.5\n bounds = [\n (0, np.infty),\n (min_sigma, np.infty),\n (0, np.mean(self.epsf)),\n ]\n\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n params = minimize(self.nll, p0, bounds=bounds).x\n self.optimized_params = params\n return params[1]*self.sigma_to_fwhm(), params[1]*self.sigma_to_fwhm(), 0\n\n def citations(self):\n return \"scipy\", \"photutils\"\n\n\nclass Gaussian2D(PSFModel):\n \"\"\"\n Fit an elliptical 2D Gaussian model to an image effective PSF\n \"\"\"\n def __init__(self, cutout_size=21, **kwargs):\n super().__init__(cutout_size=cutout_size, **kwargs)\n\n def model(self, height, xo, yo, sx, sy, theta, m):\n dx = self.x - xo\n dy = self.y - yo\n a = (np.cos(theta)**2)/(2*sx**2) + (np.sin(theta)**2)/(2*sy**2)\n b = -(np.sin(2*theta))/(4*sx**2) + (np.sin(2*theta))/(4*sy**2)\n c = (np.sin(theta)**2)/(2*sx**2) + (np.cos(theta)**2)/(2*sy**2)\n psf = height * np.exp(-(a * dx ** 2 + 2 * b * dx * dy + c * dy ** 2))\n return psf + m\n\n def optimize(self):\n p0 = moments(self.epsf)\n x0, y0 = p0[1], p0[2]\n min_sigma = 0.5\n bounds = [\n (0, np.infty),\n (x0 - 3, x0 + 3),\n (y0 - 3, y0 + 3),\n (min_sigma, np.infty),\n (min_sigma, np.infty),\n (0, 4),\n (0, np.mean(self.epsf)),\n ]\n\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n params = minimize(self.nll, p0, bounds=bounds).x\n self.optimized_params = params\n return params[3]*self.sigma_to_fwhm(), params[4]*self.sigma_to_fwhm(), params[-2]\n\n def citations(self):\n return \"scipy\", \"photutils\"\n\n\nclass Moffat2D(PSFModel):\n \"\"\"\n Fit an elliptical 2D Moffat model to an image effective PSF\n \"\"\"\n def __init__(self, cutout_size=21, **kwargs):\n super().__init__(cutout_size=cutout_size, **kwargs)\n\n def model(self, a, x0, y0, sx, sy, theta, b, beta):\n # https://pixinsight.com/doc/tools/DynamicPSF/DynamicPSF.html\n dx_ = self.x - x0\n dy_ = self.y - y0\n dx = dx_*np.cos(theta) + dy_*np.sin(theta)\n dy = -dx_*np.sin(theta) + dy_*np.cos(theta)\n \n return b + a / np.power(1 + (dx/sx)**2 + (dy/sy)**2, beta) \n\n def sigma_to_fwhm(self):\n return 2*np.sqrt(np.power(2, 1/self.optimized_params[-1]) - 1)\n \n def optimize(self):\n p0 = list(moments(self.epsf))\n p0.append(1)\n x0, y0 = p0[1], p0[2]\n min_sigma = 0.5\n bounds = [\n (0, np.infty),\n (x0 - 3, x0 + 3),\n (y0 - 3, y0 + 3),\n (min_sigma, np.infty),\n (min_sigma, np.infty),\n (0, 4),\n (0, np.mean(self.epsf)),\n (1, 8),\n ]\n\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n params = minimize(self.nll, p0, bounds=bounds).x\n self.optimized_params = params\n sm = self.sigma_to_fwhm()\n return params[3]*sm, params[4]*sm, params[-2]\n\n def citations(self):\n return \"scipy\", \"photutils\"\n\n\nclass KeepGoodStars(Block):\n\n def __init__(self, n=-1, **kwargs):\n super().__init__(**kwargs)\n self.n = n\n\n def run(self, image, n=-1):\n good_stars = self(image.data, image.stars_coords)\n image.stars_coords = good_stars\n\n def __call__(self, data, stars):\n i, _stars = cutouts(data, stars, size=21)\n #good = np.array([shapiro(s.data).statistic for s in _stars]) > 0.33\n good = np.array([np.std(s.data) for s in _stars]) > 1000\n return stars[i][np.argwhere(good).squeeze()][0:self.n]", "import glob\nfrom os import path\nimport pandas as pd\nimport numpy as np\nfrom ..telescope import Telescope\nfrom datetime import timedelta\nfrom astropy.io import fits\nfrom tqdm import tqdm\nfrom astropy.time import Time\nimport os\nimport zipfile\n\n\ndef phot2dict(filename):\n hdu = fits.open(filename)\n dictionary = {h.name.lower(): h.data for h in hdu}\n dictionary[\"header\"] = hdu[0].header\n\n return dictionary\n\n\ndef get_files(\n ext,\n folder,\n depth=0,\n return_folders=False,\n single_list_removal=False,\n none_for_empty=False,\n):\n \"\"\"\n\n Return files of specific extension in the specified folder and sub-folders\n\n Parameters\n ----------\n folder : str\n Folder to be analyzed\n depth : int\n Number how sub-folder layer to look into.\n 0 (default) will look into current folder\n 1 will look into current folder and its sub-folders\n 2 will look into current folder, its sub-folders and their sub-folders\n ... etc\n\n Returns\n -------\n list of fits files\n\n \"\"\"\n files = []\n for depth in range(depth + 1):\n files += glob.iglob(\n path.join(folder, \"*/\" * depth + f\"*{ext}\"), recursive=False\n )\n\n files = [path.abspath(f) for f in files if path.isfile(f)]\n\n if return_folders:\n folders = [path.dirname(file) for file in files]\n if single_list_removal and len(folders) == 1:\n return folders[0]\n else:\n return folders\n else:\n if single_list_removal and len(files) == 1:\n return files[0]\n elif len(files) == 0 and none_for_empty:\n return None\n else:\n return files\n\n\ndef set_hdu(hdu_list, value):\n key = value.name\n if key in hdu_list:\n hdu_list[key] = value\n else:\n hdu_list.append(value)\n\n\ndef fits_to_df(files, telescope_kw=\"TELESCOP\", verbose=True, hdu=0):\n assert len(files) > 0, \"Files not provided\"\n\n last_telescope = \"_\"\n telescopes_seen = []\n telescope = None\n df_list = []\n\n def progress(x):\n return tqdm(x) if verbose else x\n\n for i in progress(files):\n header = fits.getheader(i, hdu)\n telescope_name = header.get(telescope_kw, \"\")\n if telescope_name not in telescopes_seen:\n telescopes_seen.append(telescope_name)\n verbose = True\n else:\n verbose = False\n\n if telescope_name != last_telescope:\n telescope = Telescope.from_name(telescope_name, verbose=verbose)\n last_telescope = telescope_name\n\n df_list.append(dict(\n path=i,\n date=telescope.date(header),\n telescope=telescope.name,\n type=telescope.image_type(header),\n target=header.get(telescope.keyword_object, \"\"),\n filter=header.get(telescope.keyword_filter, \"\"),\n dimensions=(header.get(\"NAXIS1\", 1), header.get(\"NAXIS2\", 1)),\n flip=header.get(telescope.keyword_flip, \"\"),\n jd=header.get(telescope.keyword_jd, \"\"),\n ))\n\n df = pd.DataFrame(df_list)\n\n df.type.loc[df.type.str.lower().str.contains(telescope.keyword_light_images.lower())] = \"light\"\n df.type.loc[df.type.str.lower().str.contains(telescope.keyword_dark_images.lower())] = \"dark\"\n df.type.loc[df.type.str.lower().str.contains(telescope.keyword_bias_images.lower())] = \"bias\"\n df.type.loc[df.type.str.lower().str.contains(telescope.keyword_flat_images.lower())] = \"flat\"\n df.telescope.loc[df.telescope.str.lower().str.contains(\"unknown\")] = np.nan\n df.date = pd.to_datetime(df.date)\n\n if (df.jd == \"\").all(): # jd empty then convert from date\n df.jd = Time(df.date, scale=\"utc\").to_value('jd') + telescope.mjd\n\n # We want dates that correspond to same observations but night might be over 2 days (before and after midnight)\n # So we remove 15 hours to be sure the date year-month-day are consistent with single observations\n df.date = (df.date - timedelta(hours=15)).apply(lambda x: x.strftime('%Y-%m-%d'))\n\n return df.replace(\"\", np.nan)\n\n\ndef get_new_fits(current_df, folder, depth=3):\n dirs = np.array(os.listdir(folder))\n new_dirs = dirs[\n np.argwhere(pd.to_datetime(dirs, errors='coerce') > pd.to_datetime(current_df.date).max()).flatten()]\n return np.hstack([get_files(\"*.f*ts\", path.join(folder, f), depth=depth) for f in new_dirs])\n\ndef convert_old_index(df):\n new_df = df[[\"date\", \"path\", \"telescope\", \"type\", \"target\", \"filter\", \"dimensions\", \"flip\", \"jd\"]]\n new_df.dimensions = new_df.dimensions.apply(\n lambda x: tuple(np.array(x.split(\"x\")).astype(int) if x != np.nan else x)\n )\n return new_df\n\n\ndef is_zip(filename):\n return zipfile.is_zipfile(filename) or \".Z\" in filename\n" ]
[ [ "numpy.median", "numpy.min", "numpy.mean", "numpy.exp", "numpy.cos", "numpy.max", "matplotlib.pyplot.colorbar", "numpy.sin", "numpy.linalg.norm", "numpy.arange", "numpy.isfinite", "numpy.sqrt", "matplotlib.pyplot.gca", "scipy.optimize.minimize", "numpy.array", "numpy.shape", "numpy.std", "numpy.power", "numpy.argwhere", "numpy.sum", "numpy.any", "numpy.abs", "numpy.indices", "matplotlib.pyplot.imshow" ], [ "pandas.to_datetime", "pandas.DataFrame" ] ]
yasserglez/kaggle_titanic
[ "7a4857ec9a99c31eb53a91dda3ad9ecd5b647278" ]
[ "gendered-pronoun-resolution/data.py" ]
[ "import csv\nimport logging\nimport random\nimport re\nfrom collections import OrderedDict\nfrom enum import IntEnum\nfrom pathlib import Path\nfrom typing import Optional, Tuple, List\n\nimport attr\nfrom torch.utils.data import Dataset\nfrom syntok import segmenter\nfrom sklearn.model_selection import train_test_split\n\n\nlogger = logging.getLogger(__name__)\n\n\nDATA_DIR = Path(__file__).parent / 'data'\n\n\nPRONOUNS = {'she', 'her', 'hers', 'he', 'him', 'his'}\n\nPRONOUNS_GENDER = {'she': 'F', 'her': 'F', 'hers': 'F', 'he': 'M', 'him': 'M', 'his': 'M'}\n\n\nclass GAPLabel(IntEnum):\n A, B, NEITHER = 0, 1, 2\n\n\n@attr.s(auto_attribs=True)\nclass GAPExample(object):\n id: str\n url: str\n tokens: List[str]\n pronoun_index: int\n a_start: int\n a_end: int # exclusive\n b_start: int\n b_end: int # exclusive\n label: Optional[GAPLabel]\n\n\ndef load_train_val_examples(random_seed, train_size=0.9) -> Tuple[List[GAPExample], List[GAPExample]]:\n examples = []\n for tsv_file in ('gap-development.tsv', 'gap-validation.tsv', 'gap-test.tsv'):\n examples.extend(_load_gap(DATA_DIR / tsv_file))\n examples_gender = [PRONOUNS_GENDER[e.tokens[e.pronoun_index].lower()] for e in examples]\n train_examples, val_examples = train_test_split(\n examples, random_state=random_seed, train_size=train_size,\n shuffle=True, stratify=examples_gender)\n return train_examples, val_examples\n\n\ndef load_test_examples(tsv_path: Path = DATA_DIR / 'test_stage_2.tsv') -> List[GAPExample]:\n examples = _load_gap(tsv_path)\n return examples\n\n\ndef _load_gap(tsv_path: Path) -> List[GAPExample]:\n examples: List[GAPExample] = []\n with tsv_path.open() as f:\n reader = csv.DictReader(f, delimiter='\\t')\n for row in reader:\n examples.append(_create_example(row))\n logger.info('Loaded %d examples from %s', len(examples), tsv_path)\n return examples\n\n\ndef _create_example(row: OrderedDict):\n label = None\n a_coref, b_coref = map(lambda x: row.get(f'{x}-coref', '').upper(), 'AB')\n if a_coref == 'TRUE' and b_coref == 'FALSE':\n label = GAPLabel.A\n elif b_coref == 'TRUE' and a_coref == 'FALSE':\n label = GAPLabel.B\n elif a_coref == 'FALSE' and b_coref == 'FALSE':\n label = GAPLabel.NEITHER\n\n tokens = _word_tokenizer(row['Text'])\n\n pronoun_index = _char_to_token_offset(\n row['Text'], row['Pronoun'], int(row['Pronoun-offset']), tokens)\n assert tokens[pronoun_index].lower() in PRONOUNS\n\n a_start = _char_to_token_offset(\n row['Text'], row['A'], int(row['A-offset']), tokens)\n a_end = a_start + len(_word_tokenizer(row['A'])) # exclusive\n\n b_start = _char_to_token_offset(\n row['Text'], row['B'], int(row['B-offset']), tokens)\n b_end = b_start + len(_word_tokenizer(row['B'])) # exclusive\n\n example = GAPExample(\n id=row['ID'],\n url=row['URL'],\n tokens=tokens,\n pronoun_index=pronoun_index,\n a_start=a_start,\n a_end=a_end,\n b_start=b_start,\n b_end=b_end,\n label=label)\n return example\n\n\ndef _word_tokenizer(text: str) -> List[str]:\n tokens: List[str] = []\n for paragraph in segmenter.analyze(text):\n for sentence in paragraph:\n for token in sentence:\n # Split tokens on additional characters not handled by syntok\n token_value = token.value\n for c in ('/', r'\\*', \"'\", r'\\.', '--', ':'):\n token_value = re.sub(rf'({c})', r' \\1 ', token_value)\n tokens.extend(token_value.split())\n return tokens\n\n\ndef _char_to_token_offset(\n text: str,\n mention: str,\n char_offset: int,\n text_tokens: List[str]) -> int:\n char_index = token_index = 0\n while char_index < char_offset:\n if text[char_index:].startswith(text_tokens[token_index]):\n char_index += len(text_tokens[token_index])\n token_index += 1\n else:\n char_index += 1 # whitespace\n return token_index\n\n\nclass GAPDataset(Dataset):\n\n def __init__(self, examples: List[GAPExample], flip_prob: float = 0.0) -> None:\n super().__init__()\n self._examples = examples\n assert 0.0 <= flip_prob <= 1.0\n self._flip_prob = flip_prob\n\n def __getitem__(self, index: int) -> GAPExample:\n example = self._examples[index]\n if (self._flip_prob == 1.0 or\n (self._flip_prob > 0.0 and\n random.random() <= self._flip_prob)):\n example = self._flip_example(example)\n return example\n\n def __len__(self) -> int:\n return len(self._examples)\n\n def _flip_example(self, example: GAPExample) -> GAPExample:\n new_label = example.label\n if example.label == GAPLabel.A:\n new_label = GAPLabel.B\n elif example.label == GAPLabel.B:\n new_label = GAPLabel.A\n new_example = GAPExample(\n id=example.id,\n url=example.url,\n tokens=example.tokens,\n pronoun_index=example.pronoun_index,\n a_start=example.b_start,\n a_end=example.b_end,\n b_start=example.a_start,\n b_end=example.a_end,\n label=new_label)\n return new_example\n" ]
[ [ "sklearn.model_selection.train_test_split" ] ]
ChenyanWu/seg_super_pixel
[ "dfa4334bc229094fa26fb67594a00965fbdf0bfd" ]
[ "dataloaders/datasets/pascal.py" ]
[ "from __future__ import print_function, division\nimport os\nfrom PIL import Image\nimport numpy as np\nfrom torch.utils.data import Dataset\nfrom mypath import Path\nfrom torchvision import transforms\nfrom dataloaders import custom_transforms as tr\nfrom dataloaders import sp_transforms as tr_sp\n\nclass VOCSegmentation(Dataset):\n \"\"\"\n PascalVoc dataset\n \"\"\"\n NUM_CLASSES = 21\n\n def __init__(self,\n args,\n base_dir=Path.db_root_dir('pascal'),\n split='train',\n ):\n \"\"\"\n :param base_dir: path to VOC dataset directory\n :param split: train/val\n :param transform: transform to apply\n \"\"\"\n super().__init__()\n self._base_dir = base_dir\n self._image_dir = os.path.join(self._base_dir, 'JPEGImages')\n self._cat_dir = os.path.join(self._base_dir, 'SegmentationClass')\n self._sp_dir = os.path.join(self._base_dir, 'super_pixel')\n\n if isinstance(split, str):\n self.split = [split]\n else:\n split.sort()\n self.split = split\n\n self.args = args\n\n _splits_dir = os.path.join(self._base_dir, 'ImageSets', 'Segmentation')\n\n self.im_ids = []\n self.images = []\n self.categories = []\n self.super_pixel = []\n\n for splt in self.split:\n with open(os.path.join(os.path.join(_splits_dir, splt + '.txt')), \"r\") as f:\n lines = f.read().splitlines()\n\n for ii, line in enumerate(lines):\n _image = os.path.join(self._image_dir, line + \".jpg\")\n _cat = os.path.join(self._cat_dir, line + \".png\")\n _sp = os.path.join(self._sp_dir, line + \".ppm.jpg\")\n assert os.path.isfile(_image)\n assert os.path.isfile(_cat)\n assert os.path.isfile(_sp)\n self.im_ids.append(line)\n self.images.append(_image)\n self.categories.append(_cat)\n self.super_pixel.append(_sp)\n\n assert (len(self.images) == len(self.categories))\n\n # Display stats\n print('Number of images in {}: {:d}'.format(split, len(self.images)))\n\n def __len__(self):\n return len(self.images)\n\n\n def __getitem__(self, index):\n _img, _target, _sp = self._make_img_gt_point_pair(index)\n sample = {'image': _img, 'label': _target, 'super_pixel':_sp}\n\n for split in self.split:\n if split == \"train\":\n return self.transform_tr(sample)\n elif split == 'val':\n return self.transform_val(sample)\n\n\n def _make_img_gt_point_pair(self, index):\n _img = Image.open(self.images[index]).convert('RGB')\n _target = Image.open(self.categories[index])\n _sp = Image.open(self.super_pixel[index])\n\n return _img, _target, _sp\n\n def transform_tr(self, sample):\n if len(sample) == 2:\n composed_transforms = transforms.Compose([\n tr.RandomHorizontalFlip(),\n tr.RandomScaleCrop(base_size=self.args.base_size, crop_size=self.args.crop_size),\n tr.RandomGaussianBlur(),\n tr.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),\n tr.ToTensor()])\n\n return composed_transforms(sample)\n else:\n composed_transforms = transforms.Compose([\n tr_sp.RandomHorizontalFlip(),\n tr_sp.RandomScaleCrop(base_size=self.args.base_size, crop_size=self.args.crop_size),\n tr_sp.RandomGaussianBlur(),\n tr_sp.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),\n tr_sp.ToTensor()])\n\n return composed_transforms(sample)\n\n def transform_val(self, sample):\n if len(sample) == 2:\n composed_transforms = transforms.Compose([\n tr.FixScaleCrop(crop_size=self.args.crop_size),\n tr.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),\n tr.ToTensor()])\n\n return composed_transforms(sample)\n else:\n composed_transforms = transforms.Compose([\n tr_sp.FixScaleCrop(crop_size=self.args.crop_size),\n tr_sp.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),\n tr_sp.ToTensor()])\n\n return composed_transforms(sample)\n\n def __str__(self):\n return 'VOC2012(split=' + str(self.split) + ')'\n\n\nif __name__ == '__main__':\n from dataloaders.utils import decode_segmap\n from torch.utils.data import DataLoader\n import matplotlib.pyplot as plt\n import argparse\n\n parser = argparse.ArgumentParser()\n args = parser.parse_args()\n args.base_size = 513\n args.crop_size = 513\n\n voc_train = VOCSegmentation(args, split='train')\n\n dataloader = DataLoader(voc_train, batch_size=5, shuffle=True, num_workers=0)\n\n for ii, sample in enumerate(dataloader):\n for jj in range(sample[\"image\"].size()[0]):\n img = sample['image'].numpy()\n gt = sample['label'].numpy()\n sps = sample['super_pixel'].numpy()\n tmp = np.array(gt[jj]).astype(np.uint8)\n segmap = decode_segmap(tmp, dataset='pascal')\n img_tmp = np.transpose(img[jj], axes=[1, 2, 0])\n img_tmp *= (0.229, 0.224, 0.225)\n img_tmp += (0.485, 0.456, 0.406)\n img_tmp *= 255.0\n img_tmp = img_tmp.astype(np.uint8)\n sp = np.array(sps[jj])\n sp *= 255.0\n sp = sp.astype(np.uint8)\n plt.figure()\n plt.title('display')\n plt.subplot(211)\n plt.imshow(img_tmp)\n plt.subplot(212)\n plt.imshow(sp)\n\n if ii == 1:\n break\n\n plt.show(block=True)\n\n\n" ]
[ [ "numpy.array", "matplotlib.pyplot.title", "matplotlib.pyplot.figure", "numpy.transpose", "torch.utils.data.DataLoader", "matplotlib.pyplot.show", "matplotlib.pyplot.imshow", "matplotlib.pyplot.subplot" ] ]
geoffbacon/does-bert-agree
[ "9ece52d01f30352a200ad841efb6162e7597f0e4", "9ece52d01f30352a200ad841efb6162e7597f0e4" ]
[ "src/experiment.py", "src/bylemmata.py" ]
[ "\"\"\"Run experiment.\n\nThis module is intended to be run as a script:\n $ python src/experiment.py\n\n\"\"\"\nimport os\n\nimport pandas as pd\n\nfrom bert import BERT\nfrom constants import LANGUAGES, MASK, MISSING\nfrom filenames import CLOZE_DIR, EXPERIMENTS_DIR, FEATURES_DIR\nfrom utils import refresh\n\nENGLISH_MODEL = \"bert-base-cased\"\nMULTILINGUAL_MODEL = \"bert-base-multilingual-cased\"\n\n\ndef index_of_masked_word(sentence, bert):\n \"\"\"Return index of the masked word in `sentence` using `bert`'s' tokenizer.\n\n We use this function to calculate the linear distance between the target\n and controller as BERT sees it.\n\n Parameters\n ----------\n sentence : str\n\n Returns\n -------\n int\n\n \"\"\"\n tokens = bert.tokenize(sentence)\n try:\n return tokens.index(MASK)\n except ValueError: # MASK not in sentence\n return -1\n\n\ndef run(language, force_multilingual=False, fold_case=True, gpu=True):\n \"\"\"Run the experiment for `language`.\n\n Parameters\n ----------\n language : str\n force_multilingual : bool\n Whether to use the multilingual model even on English\n fold_case : bool\n Whether to ignore caseing differences after making predictions\n gpu : bool\n Whether to run on GPU or not (useful for debugging)\n\n Returns\n -------\n pd.DataFrame\n\n \"\"\"\n if (language == \"English\") and (not force_multilingual):\n bert = BERT(ENGLISH_MODEL, gpu=gpu)\n else:\n bert = BERT(MULTILINGUAL_MODEL, gpu=gpu)\n vocab = bert.vocab\n if fold_case:\n vocab = [word.lower() for word in vocab]\n code = LANGUAGES[language]\n cloze = pd.read_csv(os.path.join(CLOZE_DIR, f\"{code}.csv\"))\n num_examples = len(cloze) * 2 # because we mask out both words\n print(f\"\\n\\nNumber of examples for {language}: {num_examples}\")\n print_every = num_examples // 100\n features = pd.read_csv(\n os.path.join(FEATURES_DIR, f\"{code}.csv\"), dtype={\"person\": str}\n )\n # remove any words that aren't in the vocab\n features = features[features[\"word\"].isin(vocab)]\n # if we are masking out the controller, we know that the masked word is\n # also a noun or a pronoun, so we can remove everything else from features\n # features = features[features['pos'].isin(['NOUN', 'PRON'])]\n cols = [\"number\", \"gender\", \"case\", \"person\"]\n result = []\n count, total = 0, 0\n for _, example in cloze.iterrows():\n for mask in [\"masked\", \"other_masked\"]:\n try:\n predictions = bert.predict(example[mask], fold_case)\n except ValueError: # MASK not in sentence\n continue\n predictions = features.merge(\n predictions, how=\"left\", left_on=\"word\", right_index=True\n )\n # only keep words of the same POS category as the masked word\n predictions = predictions[predictions[\"pos\"] == example[\"pos\"]]\n # A word is correct if all its features are identical with the features\n # of the masked word.\n predictions[\"correct\"] = (predictions[cols] == example[cols]).all(axis=1)\n # If a word form has multiple feature bundles and at least one of them\n # is correct, then we count that word form as correct. The values of\n # 'p' for the differently valued but identical word forms will be\n # identical (because BERT predicts word forms). I want to include the\n # 'p' in the resulting dataframe so I just take the first value.\n predictions = predictions.groupby(\"word\").agg(\n {\"correct\": any, \"p\": \"first\"}\n )\n # we compute the average (unnormalized) probability of all the word\n # forms BERT got correct and all it got incorrect.\n mean = predictions.groupby(\"correct\")[\"p\"].mean()\n try:\n example[\"correct\"] = mean[True]\n except KeyError:\n example[\"correct\"] = 0.0\n try:\n example[\"incorrect\"] = mean[False]\n except KeyError:\n example[\"incorrect\"] = 0.0\n # add in the linear distance between masked and other word\n masked_index = index_of_masked_word(example[\"masked\"], bert)\n other_index = index_of_masked_word(example[\"other_masked\"], bert)\n example[\"distance\"] = abs(masked_index - other_index)\n result.append(example)\n if example[\"correct\"] > example[\"incorrect\"]:\n count += 1\n total += 1\n if total % print_every == 0:\n percent_correct = round(100 * (count / total), 3)\n percent_done = round(100 * (total / num_examples), 3)\n print(f\"{percent_correct}% correct with {percent_done}% done\")\n result = pd.DataFrame(result)\n result[\"right\"] = result[\"correct\"] > result[\"incorrect\"]\n file_name = os.path.join(EXPERIMENTS_DIR, f\"{code}.csv\")\n result.to_csv(file_name, index=False)\n return result\n\n\nif __name__ == \"__main__\":\n # # # refresh(EXPERIMENTS_DIR) # don't uncomment me!\n # # run experiments for languages with fewer cloze examples first\n # ORDER = {\n # language: len(pd.read_csv(os.path.join(CLOZE_DIR, f'{code}.csv')))\n # for language, code in LANGUAGES.items()\n # }\n ORDER = {\"Czech\": 0, \"German\": 1}\n for language in sorted(ORDER, key=ORDER.get):\n try:\n result = run(language)\n proportion_correct = result[\"right\"].value_counts(normalize=True)[True]\n print(language, round(proportion_correct, 2))\n except: # noqa\n print(f\"Error with {language}\")\n", "\"\"\"Second quick script to analyze the original method of evaluating agreement predictions.\"\"\"\n\nimport os\n\nimport numpy as np\nimport pandas as pd\nfrom tqdm import tqdm\n\nfrom filenames import CLOZE_DIR, FEATURES_DIR, PROBABILITIES_DIR\n\ncols = [\"number\", \"gender\", \"case\", \"person\"]\nlanguages = os.listdir(PROBABILITIES_DIR)\nfor lg in [\"hun\", \"gle\", \"fin\"]: # already done\n languages.remove(lg)\nfor lg in languages:\n results = []\n print(lg)\n features_filename = os.path.join(FEATURES_DIR, f\"{lg}.csv\")\n features = pd.read_csv(features_filename, dtype={\"person\": str})\n cloze_filename = os.path.join(CLOZE_DIR, f\"{lg}.csv\")\n cloze = pd.read_csv(cloze_filename)\n for _, row in tqdm(cloze.iterrows()):\n uid = row[\"uid\"]\n pos = row[\"pos\"]\n probabilities_filename = os.path.join(PROBABILITIES_DIR, lg, f\"{uid}.csv\")\n try: # we may have skipped this cloze example\n probs = pd.read_csv(probabilities_filename)\n lemma = row[\"lemma\"]\n correct_form = row[\"correct_form\"]\n p_correct_form = probs[probs[\"word\"] == correct_form][\"p\"].max()\n if np.isnan(\n p_correct_form\n ): # the correct form didn't appear in the lexicon\n continue\n else:\n is_same_pos = features[\"pos\"] == pos\n is_different_lemma = features[\"lemma\"] != lemma\n other_lemmata = features[is_same_pos & is_different_lemma]\n if (\n other_lemmata.empty\n ): # we don't have feature data on any other lemmata\n continue\n else:\n num_lemmata = len(other_lemmata[\"lemma\"].unique())\n merged = pd.merge(\n probs, other_lemmata, left_on=[\"word\"], right_on=[\"word\"]\n )\n merged[\"correct\"] = (merged[cols] == row[cols]).all(axis=1)\n incorrect_forms = merged[~merged[\"correct\"]]\n lemmata = incorrect_forms[\"lemma\"]\n grouped = merged[merged[\"lemma\"].isin(lemmata)].groupby(\"lemma\")\n count = 0\n for _, group in grouped:\n try:\n p_correct = group[group[\"correct\"]][\"p\"].max()\n try:\n p_incorrect = group[~group[\"correct\"]][\"p\"].max()\n if p_incorrect >= p_correct:\n count += 1\n except KeyError:\n continue\n except KeyError:\n continue\n example = {\n \"lg\": lg,\n \"uid\": uid,\n \"lemma\": lemma,\n \"correct_form\": correct_form,\n \"num_incorrect_lemmata\": count,\n \"num_lemmata\": num_lemmata,\n }\n results.append(example)\n except FileNotFoundError:\n continue\n results = pd.DataFrame(results)\n results[\"percentage\"] = 100 * (\n results[\"num_incorrect_lemmata\"] / results[\"num_lemmata\"]\n )\n results.to_csv(f\"data/bylemmata/{lg}.csv\", index=False)\n" ]
[ [ "pandas.DataFrame" ], [ "pandas.DataFrame", "pandas.read_csv", "numpy.isnan", "pandas.merge" ] ]
winni2k/tskit
[ "92fe9c04a27385401732a698843756aa797bacdd" ]
[ "python/tskit/drawing.py" ]
[ "# MIT License\n#\n# Copyright (c) 2018-2019 Tskit Developers\n# Copyright (c) 2015-2017 University of Oxford\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nModule responsible for visualisations.\n\"\"\"\nimport collections\nimport numbers\n\nimport svgwrite\nimport numpy as np\n\nfrom _tskit import NULL\n\nLEFT = \"left\"\nRIGHT = \"right\"\nTOP = \"top\"\nBOTTOM = \"bottom\"\n\n\ndef check_orientation(orientation):\n if orientation is None:\n orientation = TOP\n else:\n orientation = orientation.lower()\n orientations = [LEFT, RIGHT, TOP, BOTTOM]\n if orientation not in orientations:\n raise ValueError(\n \"Unknown orientiation: choose from {}\".format(orientations))\n return orientation\n\n\ndef check_max_tree_height(max_tree_height, allow_numeric=True):\n if max_tree_height is None:\n max_tree_height = \"tree\"\n is_numeric = isinstance(max_tree_height, numbers.Real)\n if max_tree_height not in [\"tree\", \"ts\"] and not allow_numeric:\n raise ValueError(\"max_tree_height must be 'tree' or 'ts'\")\n if max_tree_height not in [\"tree\", \"ts\"] and (allow_numeric and not is_numeric):\n raise ValueError(\n \"max_tree_height must be a numeric value or one of 'tree' or 'ts'\")\n return max_tree_height\n\n\ndef check_tree_height_scale(tree_height_scale):\n if tree_height_scale is None:\n tree_height_scale = \"time\"\n if tree_height_scale not in [\"time\", \"log_time\", \"rank\"]:\n raise ValueError(\"tree_height_scale must be 'time', 'log_time' or 'rank'\")\n return tree_height_scale\n\n\ndef check_format(format):\n if format is None:\n format = \"SVG\"\n fmt = format.lower()\n supported_formats = [\"svg\", \"ascii\", \"unicode\"]\n if fmt not in supported_formats:\n raise ValueError(\"Unknown format '{}'. Supported formats are {}\".format(\n format, supported_formats))\n return fmt\n\n\ndef draw_tree(\n tree, width=None, height=None, node_labels=None, node_colours=None,\n mutation_labels=None, mutation_colours=None, format=None, edge_colours=None,\n tree_height_scale=None, max_tree_height=None):\n\n # See tree.draw() for documentation on these arguments.\n fmt = check_format(format)\n if fmt == \"svg\":\n if width is None:\n width = 200\n if height is None:\n height = 200\n\n def remap(original_map, new_key, none_value):\n if original_map is None:\n return None\n new_map = {}\n for key, value in original_map.items():\n if value is None:\n new_map[key] = none_value\n else:\n new_map[key] = {new_key: value}\n return new_map\n\n # Old semantics were to not draw the node if colour is None.\n # Setting opacity to zero has the same effect.\n node_attrs = remap(node_colours, \"fill\", {'opacity': 0})\n edge_attrs = remap(edge_colours, \"stroke\", {'opacity': 0})\n mutation_attrs = remap(mutation_colours, \"fill\", {'opacity': 0})\n\n node_label_attrs = None\n tree = SvgTree(\n tree, (width, height),\n node_labels=node_labels,\n mutation_labels=mutation_labels,\n tree_height_scale=tree_height_scale,\n max_tree_height=max_tree_height,\n node_attrs=node_attrs, edge_attrs=edge_attrs,\n node_label_attrs=node_label_attrs,\n mutation_attrs=mutation_attrs)\n return tree.drawing.tostring()\n\n else:\n if width is not None:\n raise ValueError(\"Text trees do not support width\")\n if height is not None:\n raise ValueError(\"Text trees do not support height\")\n if mutation_labels is not None:\n raise ValueError(\"Text trees do not support mutation_labels\")\n if mutation_colours is not None:\n raise ValueError(\"Text trees do not support mutation_colours\")\n if node_colours is not None:\n raise ValueError(\"Text trees do not support node_colours\")\n if edge_colours is not None:\n raise ValueError(\"Text trees do not support edge_colours\")\n if tree_height_scale is not None:\n raise ValueError(\"Text trees do not support tree_height_scale\")\n\n use_ascii = fmt == \"ascii\"\n text_tree = VerticalTextTree(\n tree, node_labels=node_labels, max_tree_height=max_tree_height,\n use_ascii=use_ascii, orientation=TOP)\n return str(text_tree)\n\n\nclass SvgTreeSequence(object):\n \"\"\"\n Draw a TreeSequence in SVG.\n \"\"\"\n def __init__(\n self, ts, size=None, tree_height_scale=None, max_tree_height=None,\n node_labels=None, mutation_labels=None,\n node_attrs=None, edge_attrs=None, node_label_attrs=None):\n self.ts = ts\n if size is None:\n size = (200 * ts.num_trees, 200)\n self.image_size = size\n self.drawing = svgwrite.Drawing(size=self.image_size, debug=True)\n self.node_labels = {u: str(u) for u in range(ts.num_nodes)}\n # TODO add general padding arguments following matplotlib's terminology.\n self.axes_x_offset = 15\n self.axes_y_offset = 10\n self.treebox_x_offset = self.axes_x_offset + 5\n self.treebox_y_offset = self.axes_y_offset + 5\n x = self.treebox_x_offset\n treebox_width = size[0] - 2 * self.treebox_x_offset\n treebox_height = size[1] - 2 * self.treebox_y_offset\n tree_width = treebox_width / ts.num_trees\n svg_trees = [\n SvgTree(\n tree, (tree_width, treebox_height),\n max_tree_height=\"ts\",\n node_labels=node_labels,\n mutation_labels=mutation_labels,\n tree_height_scale=tree_height_scale,\n node_attrs=node_attrs, edge_attrs=edge_attrs,\n node_label_attrs=node_label_attrs)\n for tree in ts.trees()]\n\n ticks = []\n y = self.treebox_y_offset\n defs = self.drawing.defs\n\n for tree, svg_tree in zip(ts.trees(), svg_trees):\n defs.add(svg_tree.root_group)\n\n for tree in ts.trees():\n tree_id = \"#tree_{}\".format(tree.index)\n use = self.drawing.use(tree_id, (x, y))\n self.drawing.add(use)\n ticks.append((x, tree.interval[0]))\n x += tree_width\n ticks.append((x, ts.sequence_length))\n\n dwg = self.drawing\n\n # # Debug --- draw the tree and axes boxes\n # w = self.image_size[0] - 2 * self.treebox_x_offset\n # h = self.image_size[1] - 2 * self.treebox_y_offset\n # dwg.add(dwg.rect((self.treebox_x_offset, self.treebox_y_offset), (w, h),\n # fill=\"white\", fill_opacity=0, stroke=\"black\", stroke_dasharray=\"15,15\"))\n # w = self.image_size[0] - 2 * self.axes_x_offset\n # h = self.image_size[1] - 2 * self.axes_y_offset\n # dwg.add(dwg.rect((self.axes_x_offset, self.axes_y_offset), (w, h),\n # fill=\"white\", fill_opacity=0, stroke=\"black\", stroke_dasharray=\"5,5\"))\n\n axes_left = self.treebox_x_offset\n axes_right = self.image_size[0] - self.treebox_x_offset\n y = self.image_size[1] - 2 * self.axes_y_offset\n dwg.add(dwg.line((axes_left, y), (axes_right, y), stroke=\"black\"))\n for x, genome_coord in ticks:\n delta = 5\n dwg.add(dwg.line((x, y - delta), (x, y + delta), stroke=\"black\"))\n dwg.add(dwg.text(\n \"{:.2f}\".format(genome_coord), (x, y + 20),\n font_size=14, text_anchor=\"middle\", font_weight=\"bold\"))\n\n\nclass SvgTree(object):\n \"\"\"\n An SVG representation of a single tree.\n\n TODO should provide much more SVG structure which we document fully\n to that the SVG elements can be manipulated directly by the user.\n For example, every edge should be given an SVG ID so that it can\n be referred to and modified.\n\n \"\"\"\n def __init__(\n self, tree, size=None, node_labels=None, mutation_labels=None,\n tree_height_scale=None, max_tree_height=None,\n node_attrs=None, edge_attrs=None, node_label_attrs=None,\n mutation_attrs=None, mutation_label_attrs=None):\n self.tree = tree\n if size is None:\n size = (200, 200)\n self.image_size = size\n self.setup_drawing()\n self.treebox_x_offset = 10\n self.treebox_y_offset = 10\n self.treebox_width = size[0] - 2 * self.treebox_x_offset\n self.assign_y_coordinates(tree_height_scale, max_tree_height)\n self.node_x_coord_map = self.assign_x_coordinates(\n tree, self.treebox_x_offset, self.treebox_width)\n\n self.edge_attrs = {}\n self.node_attrs = {}\n self.node_label_attrs = {}\n for u in tree.nodes():\n self.edge_attrs[u] = {}\n if edge_attrs is not None and u in edge_attrs:\n self.edge_attrs[u].update(edge_attrs[u])\n self.node_attrs[u] = {\"r\": 3}\n if node_attrs is not None and u in node_attrs:\n self.node_attrs[u].update(node_attrs[u])\n label = \"\"\n if node_labels is None:\n label = str(u)\n elif u in node_labels:\n label = str(node_labels[u])\n self.node_label_attrs[u] = {\"text\": label}\n if node_label_attrs is not None and u in node_label_attrs:\n self.node_label_attrs[u].update(node_label_attrs[u])\n\n self.mutation_attrs = {}\n self.mutation_label_attrs = {}\n for site in tree.sites():\n for mutation in site.mutations:\n m = mutation.id\n # We need to offset the rectangle so that it's centred\n self.mutation_attrs[m] = {\n \"size\": (6, 6), \"transform\": \"translate(-3, -3)\"}\n if mutation_attrs is not None and m in mutation_attrs:\n self.mutation_attrs[m].update(mutation_attrs[m])\n label = \"\"\n if mutation_labels is None:\n label = str(m)\n elif mutation.id in mutation_labels:\n label = str(mutation_labels[m])\n self.mutation_label_attrs[m] = {\"text\": label}\n if mutation_label_attrs is not None and m in mutation_label_attrs:\n self.mutation_label_attrs[m].update(mutation_label_attrs[m])\n\n self.draw()\n\n def setup_drawing(self):\n self.drawing = svgwrite.Drawing(size=self.image_size, debug=True)\n dwg = self.drawing\n self.root_group = dwg.add(dwg.g(id='tree_{}'.format(self.tree.index)))\n self.edges = self.root_group.add(dwg.g(id='edges', stroke=\"black\", fill=\"none\"))\n self.symbols = self.root_group.add(dwg.g(id='symbols'))\n self.nodes = self.symbols.add(dwg.g(class_='nodes'))\n self.mutations = self.symbols.add(dwg.g(class_='mutations', fill=\"red\"))\n self.labels = self.root_group.add(dwg.g(id='labels', font_size=14))\n self.node_labels = self.labels.add(dwg.g(class_='nodes'))\n self.mutation_labels = self.labels.add(\n dwg.g(class_='mutations', font_style=\"italic\"))\n self.left_labels = self.node_labels.add(dwg.g(text_anchor=\"start\"))\n self.mid_labels = self.node_labels.add(dwg.g(text_anchor=\"middle\"))\n self.right_labels = self.node_labels.add(dwg.g(text_anchor=\"end\"))\n self.mutation_left_labels = self.mutation_labels.add(dwg.g(text_anchor=\"start\"))\n self.mutation_right_labels = self.mutation_labels.add(dwg.g(text_anchor=\"end\"))\n\n def assign_y_coordinates(self, tree_height_scale, max_tree_height):\n tree_height_scale = check_tree_height_scale(tree_height_scale)\n max_tree_height = check_max_tree_height(\n max_tree_height, tree_height_scale != \"rank\")\n ts = self.tree.tree_sequence\n node_time = ts.tables.nodes.time\n\n if tree_height_scale == \"rank\":\n assert tree_height_scale == \"rank\"\n if max_tree_height == \"tree\":\n # We only rank the times within the tree in this case.\n t = np.zeros_like(node_time) + node_time[self.tree.left_root]\n for u in self.tree.nodes():\n t[u] = node_time[u]\n node_time = t\n depth = {t: 2 * j for j, t in enumerate(np.unique(node_time))}\n node_height = [depth[node_time[u]] for u in range(ts.num_nodes)]\n max_tree_height = max(depth.values())\n else:\n assert tree_height_scale in [\"time\", \"log_time\"]\n if max_tree_height == \"tree\":\n max_tree_height = max(self.tree.time(root) for root in self.tree.roots)\n elif max_tree_height == \"ts\":\n max_tree_height = ts.max_root_time\n\n if tree_height_scale == \"log_time\":\n # add 1 so that don't reach log(0) = -inf error.\n # just shifts entire timeset by 1 year so shouldn't affect anything\n node_height = np.log(ts.tables.nodes.time + 1)\n elif tree_height_scale == \"time\":\n node_height = node_time\n\n assert float(max_tree_height) == max_tree_height\n\n # In pathological cases, all the roots are at 0\n if max_tree_height == 0:\n max_tree_height = 1\n\n # TODO should make this a parameter somewhere. This is padding to keep the\n # node labels within the treebox\n label_padding = 10\n y_padding = self.treebox_y_offset + 2 * label_padding\n mutations_over_root = any(\n any(tree.parent(mut.node) == NULL for mut in tree.mutations())\n for tree in ts.trees())\n root_branch_length = 0\n height = self.image_size[1]\n if mutations_over_root:\n # Allocate a fixed about of space to show the mutations on the\n # 'root branch'\n root_branch_length = height / 10 # FIXME just draw branch??\n # y scaling\n padding_numerator = (height - root_branch_length - 2 * y_padding)\n if tree_height_scale == \"log_time\":\n # again shift time by 1 in log(max_tree_height), so consistent\n y_scale = padding_numerator / (np.log(max_tree_height + 1))\n else:\n y_scale = padding_numerator / max_tree_height\n self.node_y_coord_map = [\n height - y_scale * node_height[u] - y_padding\n for u in range(ts.num_nodes)]\n\n def assign_x_coordinates(self, tree, x_start, width):\n num_leaves = len(list(tree.leaves()))\n x_scale = width / (num_leaves + 1)\n node_x_coord_map = {}\n leaf_x = x_start\n for root in tree.roots:\n for u in tree.nodes(root, order=\"postorder\"):\n if tree.is_leaf(u):\n leaf_x += x_scale\n node_x_coord_map[u] = leaf_x\n else:\n child_coords = [node_x_coord_map[c] for c in tree.children(u)]\n if len(child_coords) == 1:\n node_x_coord_map[u] = child_coords[0]\n else:\n a = min(child_coords)\n b = max(child_coords)\n assert b - a > 1\n node_x_coord_map[u] = a + (b - a) / 2\n return node_x_coord_map\n\n def draw(self):\n dwg = self.drawing\n node_x_coord_map = self.node_x_coord_map\n node_y_coord_map = self.node_y_coord_map\n tree = self.tree\n\n node_mutations = collections.defaultdict(list)\n for site in tree.sites():\n for mutation in site.mutations:\n node_mutations[mutation.node].append(mutation)\n\n for u in tree.nodes():\n pu = node_x_coord_map[u], node_y_coord_map[u]\n node_id = \"node_{}_{}\".format(tree.index, u)\n self.nodes.add(dwg.circle(id=node_id, center=pu, **self.node_attrs[u]))\n dx = 0\n dy = -5\n labels = self.mid_labels\n if tree.is_leaf(u):\n dy = 20\n elif tree.parent(u) != NULL:\n dx = 5\n if tree.left_sib(u) == NULL:\n dx *= -1\n labels = self.right_labels\n else:\n labels = self.left_labels\n # TODO add ID to node label text.\n # TODO get rid of these manual positioning tweaks and add them\n # as offsets the user can access via a transform or something.\n labels.add(dwg.text(\n insert=(pu[0] + dx, pu[1] + dy), **self.node_label_attrs[u]))\n v = tree.parent(u)\n if v != NULL:\n edge_id = \"edge_{}_{}\".format(tree.index, u)\n pv = node_x_coord_map[v], node_y_coord_map[v]\n path = dwg.path(\n [(\"M\", pu), (\"V\", pv[1]), (\"H\", pv[0])], id=edge_id,\n **self.edge_attrs[u])\n self.edges.add(path)\n else:\n # FIXME this is pretty crappy for spacing mutations over a root.\n pv = (pu[0], pu[1] - 20)\n\n num_mutations = len(node_mutations[u])\n delta = (pv[1] - pu[1]) / (num_mutations + 1)\n x = pu[0]\n y = pv[1] - delta\n # TODO add mutation IDs\n for mutation in reversed(node_mutations[u]):\n self.mutations.add(dwg.rect(\n insert=(x, y),\n **self.mutation_attrs[mutation.id]))\n dx = 5\n if tree.left_sib(mutation.node) == NULL:\n dx *= -1\n labels = self.mutation_right_labels\n else:\n labels = self.mutation_left_labels\n # TODO get rid of these manual positioning tweaks and add them\n # as offsets the user can access via a transform or something.\n dy = 4\n labels.add(dwg.text(\n insert=(x + dx, y + dy),\n **self.mutation_label_attrs[mutation.id]))\n y -= delta\n\n\nclass TextTreeSequence(object):\n \"\"\"\n Draw a tree sequence as horizontal line of trees.\n \"\"\"\n def __init__(\n self, ts, node_labels=None, use_ascii=False, time_label_format=None,\n position_label_format=None):\n self.ts = ts\n\n time_label_format = (\n \"{:.2f}\" if time_label_format is None else time_label_format)\n position_label_format = (\n \"{:.2f}\" if position_label_format is None else position_label_format)\n\n time = ts.tables.nodes.time\n time_scale_labels = [\n time_label_format.format(time[u]) for u in range(ts.num_nodes)]\n position_scale_labels = [\n position_label_format.format(x) for x in ts.breakpoints()]\n trees = [\n VerticalTextTree(\n tree, max_tree_height=\"ts\", node_labels=node_labels,\n use_ascii=use_ascii)\n for tree in self.ts.trees()]\n\n self.height = 1 + max(tree.height for tree in trees)\n self.width = sum(tree.width + 2 for tree in trees) - 1\n max_time_scale_label_len = max(map(len, time_scale_labels))\n self.width += 3 + max_time_scale_label_len + len(position_scale_labels[-1]) // 2\n\n self.canvas = np.zeros((self.height, self.width), dtype=str)\n self.canvas[:] = \" \"\n\n vertical_sep = \"|\" if use_ascii else \"┊\"\n x = 0\n time_position = trees[0].time_position\n for u, label in enumerate(map(to_np_unicode, time_scale_labels)):\n y = time_position[u]\n self.canvas[y, 0: label.shape[0]] = label\n self.canvas[:, max_time_scale_label_len] = vertical_sep\n x = 2 + max_time_scale_label_len\n\n for j, tree in enumerate(trees):\n pos_label = to_np_unicode(position_scale_labels[j])\n k = len(pos_label)\n label_x = max(x - k // 2 - 2, 0)\n self.canvas[-1, label_x: label_x + k] = pos_label\n h, w = tree.canvas.shape\n self.canvas[-h - 1: -1, x: x + w - 1] = tree.canvas[:, :-1]\n x += w\n self.canvas[:, x] = vertical_sep\n x += 2\n\n pos_label = to_np_unicode(position_scale_labels[-1])\n k = len(pos_label)\n label_x = max(x - k // 2 - 2, 0)\n self.canvas[-1, label_x: label_x + k] = pos_label\n self.canvas[:, -1] = \"\\n\"\n\n def __str__(self):\n return \"\".join(self.canvas.reshape(self.width * self.height))\n\n\ndef to_np_unicode(string):\n \"\"\"\n Converts the specified string to a numpy unicode array.\n \"\"\"\n # TODO: what's the clean of doing this with numpy?\n # It really wants to create a zero-d Un array here\n # which breaks the assignment below and we end up\n # with n copies of the first char.\n n = len(string)\n np_string = np.zeros(n, dtype=\"U\")\n for j in range(n):\n np_string[j] = string[j]\n return np_string\n\n\ndef closest_left_node(tree, u):\n \"\"\"\n Returns the node that closest to u in a left-to-right sense.\n \"\"\"\n ret = NULL\n while u != NULL and ret == NULL:\n ret = tree.left_sib(u)\n u = tree.parent(u)\n return ret\n\n\ndef node_time_depth(tree, min_branch_length=None, max_tree_height=\"tree\"):\n \"\"\"\n Returns a dictionary mapping nodes in the specified tree to their depth\n in the specified tree (from the root direction). If min_branch_len is\n provided, it specifies the minimum length of each branch. If not specified,\n default to 1.\n \"\"\"\n if min_branch_length is None:\n min_branch_length = {u: 1 for u in range(tree.tree_sequence.num_nodes)}\n time_node_map = collections.defaultdict(list)\n current_depth = 0\n depth = {}\n # TODO this is basically the same code for the two cases. Refactor so that\n # we use the same code.\n if max_tree_height == \"tree\":\n for u in tree.nodes():\n time_node_map[tree.time(u)].append(u)\n for t in sorted(time_node_map.keys()):\n for u in time_node_map[t]:\n for v in tree.children(u):\n current_depth = max(current_depth, depth[v] + min_branch_length[v])\n for u in time_node_map[t]:\n depth[u] = current_depth\n current_depth += 2\n for root in tree.roots:\n current_depth = max(current_depth, depth[root] + min_branch_length[root])\n else:\n assert max_tree_height == \"ts\"\n ts = tree.tree_sequence\n for node in ts.nodes():\n time_node_map[node.time].append(node.id)\n node_edges = collections.defaultdict(list)\n for edge in ts.edges():\n node_edges[edge.parent].append(edge)\n\n for t in sorted(time_node_map.keys()):\n for u in time_node_map[t]:\n for edge in node_edges[u]:\n v = edge.child\n current_depth = max(current_depth, depth[v] + min_branch_length[v])\n for u in time_node_map[t]:\n depth[u] = current_depth\n current_depth += 2\n\n return depth, current_depth\n\n\nclass TextTree(object):\n \"\"\"\n Draws a reprentation of a tree using unicode drawing characters written\n to a 2D array.\n \"\"\"\n def __init__(\n self, tree, node_labels=None, max_tree_height=None, use_ascii=False,\n orientation=None):\n self.tree = tree\n self.max_tree_height = check_max_tree_height(\n max_tree_height, allow_numeric=False)\n self.use_ascii = use_ascii\n self.orientation = check_orientation(orientation)\n self.horizontal_line_char = '━'\n self.vertical_line_char = '┃'\n if use_ascii:\n self.horizontal_line_char = '-'\n self.vertical_line_char = '|'\n # These are set below by the placement algorithms.\n self.width = None\n self.height = None\n self.canvas = None\n # Placement of nodes in the 2D space. Nodes are positioned in one\n # dimension based on traversal ordering and by their time in the\n # other dimension. These are mapped to x and y coordinates according\n # to the orientation.\n self.traversal_position = {} # Position of nodes in traversal space\n self.time_position = {}\n # Labels for nodes\n self.node_labels = {}\n\n # Set the node labels\n for u in tree.nodes():\n if node_labels is None:\n # If we don't specify node_labels, default to node ID\n self.node_labels[u] = str(u)\n else:\n # If we do specify node_labels, default an empty line\n self.node_labels[u] = self.default_node_label\n if node_labels is not None:\n for node, label in node_labels.items():\n self.node_labels[node] = label\n\n self._assign_time_positions()\n self._assign_traversal_positions()\n self.canvas = np.zeros((self.height, self.width), dtype=str)\n self.canvas[:] = \" \"\n self._draw()\n self.canvas[:, -1] = \"\\n\"\n\n def __str__(self):\n return \"\".join(self.canvas.reshape(self.width * self.height))\n\n\nclass VerticalTextTree(TextTree):\n \"\"\"\n Text tree rendering where root nodes are at the top and time goes downwards\n into the present.\n \"\"\"\n @property\n def default_node_label(self):\n return self.vertical_line_char\n\n def _assign_time_positions(self):\n tree = self.tree\n # TODO when we add mutations to the text tree we'll need to take it into\n # account here. Presumably we need to get the maximum number of mutations\n # per branch.\n self.time_position, total_depth = node_time_depth(\n tree, max_tree_height=self.max_tree_height)\n self.height = total_depth - 1\n\n def _assign_traversal_positions(self):\n self.label_x = {}\n x = 0\n for root in self.tree.roots:\n for u in self.tree.nodes(root, order=\"postorder\"):\n label_size = len(self.node_labels[u])\n if self.tree.is_leaf(u):\n self.traversal_position[u] = x + label_size // 2\n self.label_x[u] = x\n x += label_size + 1\n else:\n coords = [self.traversal_position[c] for c in self.tree.children(u)]\n if len(coords) == 1:\n self.traversal_position[u] = coords[0]\n else:\n a = min(coords)\n b = max(coords)\n child_mid = int(round((a + (b - a) / 2)))\n self.traversal_position[u] = child_mid\n self.label_x[u] = self.traversal_position[u] - label_size // 2\n sib_x = -1\n sib = closest_left_node(self.tree, u)\n if sib != NULL:\n sib_x = self.traversal_position[sib]\n self.label_x[u] = max(sib_x + 1, self.label_x[u])\n x = max(x, self.label_x[u] + label_size + 1)\n assert self.label_x[u] >= 0\n x += 1\n self.width = x - 1\n\n def _draw(self):\n if self.use_ascii:\n left_child = \"+\"\n right_child = \"+\"\n mid_parent = \"+\"\n mid_parent_child = \"+\"\n mid_child = \"+\"\n elif self.orientation == TOP:\n left_child = \"┏\"\n right_child = \"┓\"\n mid_parent = \"┻\"\n mid_parent_child = \"╋\"\n mid_child = \"┳\"\n else:\n left_child = \"┗\"\n right_child = \"┛\"\n mid_parent = \"┳\"\n mid_parent_child = \"╋\"\n mid_child = \"┻\"\n\n for u in self.tree.nodes():\n xu = self.traversal_position[u]\n yu = self.time_position[u]\n label = to_np_unicode(self.node_labels[u])\n label_len = label.shape[0]\n label_x = self.label_x[u]\n assert label_x >= 0\n self.canvas[yu, label_x: label_x + label_len] = label\n children = self.tree.children(u)\n if len(children) > 0:\n if len(children) == 1:\n yv = self.time_position[children[0]]\n self.canvas[yv: yu, xu] = self.vertical_line_char\n else:\n left = min(self.traversal_position[v] for v in children)\n right = max(self.traversal_position[v] for v in children)\n y = yu - 1\n self.canvas[y, left + 1: right] = self.horizontal_line_char\n self.canvas[y, xu] = mid_parent\n for v in children:\n xv = self.traversal_position[v]\n yv = self.time_position[v]\n self.canvas[yv: yu, xv] = self.vertical_line_char\n mid_char = mid_parent_child if xv == xu else mid_child\n self.canvas[y, xv] = mid_char\n self.canvas[y, left] = left_child\n self.canvas[y, right] = right_child\n # print(self.canvas)\n if self.orientation == TOP:\n self.canvas = np.flip(self.canvas, axis=0)\n # Reverse the time positions so that we can use them in the tree\n # sequence drawing as well.\n flipped_time_position = {\n u: self.height - y - 1 for u, y in self.time_position.items()}\n self.time_position = flipped_time_position\n\n\nclass HorizontalTextTree(TextTree):\n \"\"\"\n Text tree rendering where root nodes are at the left and time goes\n rightwards into the present.\n \"\"\"\n\n @property\n def default_node_label(self):\n return self.horizontal_line_char\n\n def _assign_time_positions(self):\n # TODO when we add mutations to the text tree we'll need to take it into\n # account here. Presumably we need to get the maximum number of mutations\n # per branch.\n self.time_position, total_depth = node_time_depth(\n self.tree, {u: 1 + len(self.node_labels[u]) for u in self.tree.nodes()})\n self.width = total_depth\n\n def _assign_traversal_positions(self):\n y = 0\n for root in self.tree.roots:\n for u in self.tree.nodes(root, order=\"postorder\"):\n if self.tree.is_leaf(u):\n self.traversal_position[u] = y\n y += 2\n else:\n coords = [self.traversal_position[c] for c in self.tree.children(u)]\n if len(coords) == 1:\n self.traversal_position[u] = coords[0]\n else:\n a = min(coords)\n b = max(coords)\n child_mid = int(round((a + (b - a) / 2)))\n self.traversal_position[u] = child_mid\n y += 1\n self.height = y - 2\n\n def _draw(self):\n if self.use_ascii:\n top_across = \"+\"\n bot_across = \"+\"\n mid_parent = \"+\"\n mid_parent_child = \"+\"\n mid_child = \"+\"\n elif self.orientation == LEFT:\n top_across = \"┏\"\n bot_across = \"┗\"\n mid_parent = \"┫\"\n mid_parent_child = \"╋\"\n mid_child = \"┣\"\n else:\n top_across = \"┓\"\n bot_across = \"┛\"\n mid_parent = \"┣\"\n mid_parent_child = \"╋\"\n mid_child = \"┫\"\n\n # Draw in root-right mode as the coordinates go in the expected direction.\n for u in self.tree.nodes():\n yu = self.traversal_position[u]\n xu = self.time_position[u]\n label = to_np_unicode(self.node_labels[u])\n if self.orientation == LEFT:\n # We flip the array at the end so need to reverse the label.\n label = label[::-1]\n label_len = label.shape[0]\n self.canvas[yu, xu: xu + label_len] = label\n children = self.tree.children(u)\n if len(children) > 0:\n if len(children) == 1:\n xv = self.time_position[children[0]]\n self.canvas[yu, xv: xu] = self.horizontal_line_char\n else:\n bot = min(self.traversal_position[v] for v in children)\n top = max(self.traversal_position[v] for v in children)\n x = xu - 1\n self.canvas[bot + 1: top, x] = self.vertical_line_char\n self.canvas[yu, x] = mid_parent\n for v in children:\n yv = self.traversal_position[v]\n xv = self.time_position[v]\n self.canvas[yv, xv: x] = self.horizontal_line_char\n mid_char = mid_parent_child if yv == yu else mid_child\n self.canvas[yv, x] = mid_char\n self.canvas[bot, x] = top_across\n self.canvas[top, x] = bot_across\n if self.orientation == LEFT:\n self.canvas = np.flip(self.canvas, axis=1)\n # Move the padding to the left.\n self.canvas[:, :-1] = self.canvas[:, 1:]\n self.canvas[:, -1] = \" \"\n # print(self.canvas)\n" ]
[ [ "numpy.zeros_like", "numpy.log", "numpy.zeros", "numpy.unique", "numpy.flip" ] ]
lemay-ai/lazyTextPredict
[ "e7bdb31c63978b8c1bb01476720571838a565623" ]
[ "lazytextpredict/basic_classification.py" ]
[ "import pandas as pd\nimport gc\nimport transformers\nfrom transformers import BertForSequenceClassification, BertTokenizerFast, Trainer, TrainingArguments\nfrom nlp import load_dataset, Dataset\nimport torch\nimport numpy as np\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.metrics import accuracy_score, precision_recall_fscore_support, classification_report, hamming_loss\nfrom sklearn.model_selection import train_test_split, GridSearchCV\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.pipeline import Pipeline\nfrom random import sample, choices\nfrom joblib import dump, load\ndef string_labels_to_int(Y): \n keys={}\n new_Y=[]\n for item in Y:\n if item in keys:\n new_Y.append(keys[item])\n else:\n keys.update({item:len(keys)+1})\n new_Y.append(keys[item])\n return new_Y, keys\n\ndef int_labels_to_list(Y,keys):\n new_Y=[]\n for item in Y:\n sublist=[0] * len(keys)\n sublist[item-1]=1\n sublist=torch.tensor(sublist)\n new_Y.append(sublist)\n return new_Y\n\n\n\nclass LTP:\n\tdef __init__ (self, Xdata=None, Ydata=None, csv=None,xlsx=None,x_col='X',y_col='Y',models='all',test_frac=0.1,train_frac=0.9):\n\t\tif models=='all':\n\t\t\tself.model_list = [\n\t\t\t\t'bert-base-uncased',\n 'albert-base-v2',\n 'roberta-base',\n 'linear_SVM',\n 'multinomial_naive_bayesian',]\n\t\telif models=='count-vectorizer':\n\t\t\tself.model_list = [\n 'linear_SVM',\n 'multinomial_naive_bayesian',]\n\t\telif models=='transformers':\n\t\t\tself.model_list = [\n 'bert-base-uncased',\n 'albert-base-v2',\n 'roberta-base',]\n\t\telse:\n\t\t\tprint('Models not recognized, the available options are currently \"all\", \"count-vectorizer\", and \"transformers\"')\n\t\t\treturn\n\t\tif csv!=None and xlsx!= None and Xdata!=None:\n\t\t\tprint(\"You have provided too much data, give just x and y data, or a csv or xlsx file!\")\n\t\t\treturn\n\t\tif csv!=None:\n\t\t\tcsv_data=pd.read_csv(csv)\n\t\t\tXdata=csv_data[x_col]\n\t\t\tYdata=csv_data[y_col]\n\t\tif xlsx!=None:\n\t\t\txlsx_data=pd.read_excel(xlsx)\n\t\t\tXdata=xlsx_data[x_col]\n\t\t\tYdata=xlsx_data[y_col]\n\t\tif isinstance(Xdata, pd.Series):\n\t\t\tprint('converting pandas series to list')\n\t\t\tXdata=list(Xdata)\n\t\tif isinstance(Ydata, pd.Series):\n\t\t\tprint('converting pandas series to list')\n\t\t\tYdata=list(Ydata)\n\n\t\tif Xdata==Ydata==None or (Xdata==None and Ydata!=None) or (Xdata!=None and Ydata==None):\n\t\t\tprint('Either you have not put in your own data, or you have only put in X or Y data, loading default dataset...')\n\t\t\tself.train_dataset_raw, self.test_dataset_raw = load_dataset('imdb', split=['train', 'test'])\n\t\t\tX=self.train_dataset_raw['text']+self.test_dataset_raw['text']\n\t\t\tXdata = X\n\t\t\tY=self.train_dataset_raw['label']+self.test_dataset_raw['label']\n\t\t\tYdata = Y\n\t\t\tkeys=set(Y)\n\t\telse:\n\t\t\tX=Xdata\n\t\t\tY=Ydata\n\t\t\tif all(isinstance(n, int) for n in Y):\n\t\t\t\tkeys=set(Y)\n\t\t\telse:\n\t\t\t\tY,keys=string_labels_to_int(Y)\n #add method to make min label 0\n\t\t\tif min(Y)>=1:\n\t\t\t\tY=[y-min(Y) for y in Y]\n\t\tif len(Xdata)<20:\n\t\t print('dataset is really small, using default test/train split (0.25)')\n\t\t test_frac=None\n\t\t train_frac=None\n\t\tif len(Xdata)<8:\n\t\t print('dataset is really too small, using default test/train split (0.5)')\n\t\t test_frac=0.5\n\t\t train_frac=0.5\n\n\t\tif len(Xdata)!=len(Ydata):\n\t\t print('ERROR: X data and Y data lengths are not the same size, they need to be!')\n\t\t return\n\n\t\tX_train, X_test, Y_train, Y_test = train_test_split(X, Y,\n stratify=Y, \n test_size=test_frac,\n train_size=train_frac)\n\t\tself.num_labels=len(keys)\n\t\t#self.train_dataset_raw_CNN = TensorDataset(X_train, int_labels_to_list(Y_train,keys))\n\t\t#self.test_dataset_raw_CNN = TensorDataset(X_test, int_labels_to_list(Y_test,keys))\n\t\tprint('X_train length: ' + str(len(X_train)))\n\t\tprint('X_test length: ' + str(len(X_test)))\n\t\tprint('Y_train length: ' + str(len(Y_train)))\n\t\tprint('Y_test length: ' + str(len(Y_test))) \n\t\tself.train_dataset_raw = Dataset.from_pandas(pd.DataFrame({'text':X_train, 'labels': Y_train}))\n\t\tself.test_dataset_raw = Dataset.from_pandas(pd.DataFrame({'text':X_test, 'labels': Y_test}))\t\n\t\tself.all_metrics = {}\n\n\n\n\tdef compute_metrics(self, pred):\n\t\tlabels = pred.label_ids\n\t\tpreds = pred.predictions.argmax(-1)\n\t\tprecision, recall, f1, _ = precision_recall_fscore_support(labels, preds, average='weighted')\n\t\tfull_report = classification_report(labels, preds, output_dict=True)\n\t\tacc = accuracy_score(labels, preds)\n\t\treturn {\n\t\t\t'accuracy': acc,\n\t\t\t'f1': f1,\n\t\t\t'precision': precision,\n\t\t\t'recall': recall,\n\t\t\t'full_report': full_report\n\t\t\t}\n\n\n\tdef get_metrics(self):\n\t\treturn self.all_metrics\n\n\tdef get_metrics_df(self):\n\t\tdic = self.get_metrics()\n\t\tdf = pd.DataFrame.from_dict(dic)\n\t\tdf = df.rename_axis(\"model_name\", axis=\"columns\").T\n\t\tdf.reset_index(inplace=True)\n\t\tdf.rename_axis()\n\t\treturn df\n\n\tdef print_metrics_table(self):\n\t\tdic = self.get_metrics()\n\t\tprint(\"{:>25} {:>15} {:>15} {:>15} {:>15} {:>15}\".format('Model', 'loss', 'accuracy', 'f1', 'precision', 'recall'))\n\t\tfor k, v in dic.items():\n\t\t\tprint(\"{:>25} {:15.5} {:15.5} {:15.5} {:15.5} {:15.5}\".format(k, v['eval_loss'], v['eval_accuracy'], v['eval_f1'], v['eval_precision'], v['eval_recall']))\n\n\n\tdef run(self, focused=False, focused_model=None, training_epochs=5):\n\t\tif focused==True:\n\t\t\tself.model_list=[focused_model]\n\t\telse:\n\t\t\tpass\n\t\tfor model_name in self.model_list:\n\n\t\t\ttraining_args = TrainingArguments(\n\t\t\toutput_dir='./results/'+model_name,\n\t\t\tnum_train_epochs=training_epochs,\n\t\t\tper_device_train_batch_size=16,\n\t\t\tper_device_eval_batch_size=64,\n\t\t\twarmup_steps=500,\n\t\t\tweight_decay=0.01,\n\t\t\t#evaluate_during_training=True,\n\t\t\tlogging_dir='./logs/'+model_name,\n\t\t\t)\n\n\t\t\tmodel = None\n\t\t\ttokenizer = None\n\t\t\tprint('Training on a dataset with ' +str(self.num_labels)+ ' labels')\n\t\t\tif model_name == \"bert-base-uncased\":\n\t\t\t\tmodel = BertForSequenceClassification.from_pretrained(model_name, num_labels=self.num_labels)\n\t\t\t\ttokenizer = BertTokenizerFast.from_pretrained(model_name)\n\t\t\telif model_name == \"albert-base-v2\":\n\t\t\t\ttokenizer = transformers.AlbertTokenizer.from_pretrained('albert-base-v2')\n\t\t\t\tmodel = transformers.AlbertForSequenceClassification.from_pretrained('albert-base-v2', return_dict=True, num_labels=self.num_labels)\n\t\t\telif model_name == \"roberta-base\":\n\t\t\t\ttokenizer = transformers.RobertaTokenizer.from_pretrained('roberta-base')\n\t\t\t\tmodel = transformers.RobertaForSequenceClassification.from_pretrained('roberta-base', return_dict=True, num_labels=self.num_labels)\n\t\t\telif model_name == \"linear_SVM\":\n\t\t\t\ttokenizer = None\n\t\t\t\tmodel = 'linear_SVM'\n\t\t\t\tparameters={\n\t\t\t\t 'vect__ngram_range': [(1, 1), (1, 2)],\n\t\t\t \t'tfidf__use_idf': (True, False),\n\t\t\t\t 'clf__alpha': (5e-2, 1e-2,5e-3, 1e-3,5e-3),\n\t\t\t \t'clf__penalty': ('l2', 'l1', 'elasticnet')\n\t\t\t\t}\n\t\t\t\tclassifier=SGDClassifier(loss='hinge',random_state=42,max_iter=5,tol=None)\n\t\t\telif model_name == \"multinomial_naive_bayesian\":\n\t\t\t\ttokenizer = None\n\t\t\t\tmodel = 'multinomial_naive_bayesian'\n\t\t\t\tparameters= {\n\t\t\t\t 'vect__ngram_range': [(1, 1), (1, 2)],\n\t\t\t\t 'tfidf__use_idf': (True, False),\n\t\t\t\t 'clf__alpha': (1,1e-1,1e-2, 1e-3,1e-4),\n\t\t\t\t 'clf__fit_prior': (True, False),\n\t\t\t\t}\n\t\t\t\tclassifier=MultinomialNB()\n\n\n\t\t\tif not model or not tokenizer: #use 'assert' here instead?\n\t\t\t\tprint(\"ERROR\")\n\n\n\t\t\tdef tokenize(batch):\n\t\t\t\treturn tokenizer(batch['text'], padding='max_length', truncation=True)\n\n\t\t\tif tokenizer is not None:\n\n\t\t\t\ttrain_dataset = self.train_dataset_raw.map(tokenize, batched=True, batch_size=len(self.train_dataset_raw))\n\t\t\t\ttest_dataset = self.test_dataset_raw.map(tokenize, batched=True, batch_size=len(self.train_dataset_raw))\n\t\t\t\ttrain_dataset.set_format('torch', columns=['input_ids', 'attention_mask', 'labels'])\n\t\t\t\ttest_dataset.set_format('torch', columns=['input_ids', 'attention_mask', 'labels'])\n\t\t\telse:\n\t\t\t\ttrain_dataset = self.train_dataset_raw\n\t\t\t\ttest_dataset = self.test_dataset_raw\n\n\n\t\t\tif model_name== \"linear_SVM\" or model_name== \"multinomial_naive_bayesian\":\n\t\t\t\ttrainer=None\n\t\t\t\tpipeline = Pipeline([('vect', CountVectorizer()),\n ('tfidf', TfidfTransformer()),\n ('clf', classifier),\n ])\n\t\t\t\tgs_clf = GridSearchCV(pipeline, parameters, cv=5, n_jobs=-1)\n\t\t\t\tif len(train_dataset['labels'])<25:\n\t\t\t\t print('not enough data to use a count vectorizer, sorry!')\n\t\t\t\telse:\n\t\t\t\t gs_ind=int(len(train_dataset['labels'])/10)\t#use a tenth of the training dataset to do gridsearch\n\t\t\t\t gs_clf = gs_clf.fit(train_dataset['text'][:gs_ind], train_dataset['labels'][:gs_ind])\n\t\t\t\t best_params=gs_clf.best_params_\n\t\t\t\t pipeline.set_params(**best_params)\n\t\t\t\t pipeline.fit(train_dataset['text'], train_dataset['labels'])\n\t\t\t\t prediction=pipeline.predict(test_dataset['text'])\n\t\t\t\t precision, recall, f1, _ = precision_recall_fscore_support(test_dataset['labels'], prediction, average=None)\n\t\t\t\t full_report=classification_report(test_dataset['labels'], prediction)\n\t\t\t\t acc = accuracy_score(test_dataset['labels'], prediction)\n\t\t\t\t loss=hamming_loss(test_dataset['labels'], prediction)\n\t\t\t\t curr_metrics={\n 'eval_loss': loss,\n 'eval_accuracy': np.mean(acc),\n 'eval_f1': np.mean(f1),\n 'eval_precision': np.mean(precision),\n 'eval_recall': np.mean(recall),\n 'eval_full_report': full_report\n }\n\t\t\t\t dump(pipeline, model_name + \"_model.joblib\")\n\t\t\t\t print('best parameters are:')\n\t\t\t\t print(best_params)\n\n\t\t\telse:\n\t\t\t\ttrainer = Trainer(model=model,\n\t\t\t\t args=training_args,\n\t\t\t\t compute_metrics=self.compute_metrics,\n\t\t\t\t train_dataset=train_dataset,\n\t\t\t\t eval_dataset=test_dataset\n\t\t\t\t)\n\t\t\t\ttrainer.train()\n\t\t\t\tcurr_metrics = trainer.evaluate()\n\t\t\t\ttrainer.save_model(model_name+\"_model\")\n\n\t\t\tself.all_metrics[model_name] = curr_metrics\n\t\t\tprint(curr_metrics)\n\n\n\n\t\t\t# adding this fully solves the out of memory (OOM) error; https://github.com/huggingface/transformers/issues/1742\n\t\t\tdel model, tokenizer, trainer\n\n\t\t\t# these 2 lines may not be needed\n\t\t\tgc.collect()\n\t\t\ttorch.cuda.empty_cache()\n \n\n \n\tdef predict(self,model_name=None,focused=False,text=None):\n\t\tif text == None:\n\t\t\tprint('you did not enter any text to classify, sorry')\n\t\t\treturn\n\t\tif focused==True:\n\t\t\tif model_name == \"linear_SVM\" or model_name == \"multinomial_naive_bayesian\":\n\t\t\t\tclf = load('/content/'+model_name+'_model.joblib')\n\t\t\t\ty=clf.predict([text])\n\t\t\telse:\n\t\t\t\tif model_name == \"bert-base-uncased\":\n\t\t\t\t\tmodel=BertForSequenceClassification.from_pretrained('/content/bert-base-uncased_model')\n\t\t\t\t\ttokenizer=BertTokenizerFast.from_pretrained('bert-base-uncased')\n\t\t\t\t\ttext_classification= transformers.pipeline('sentiment-analysis', model=model, tokenizer=tokenizer)\n\t\t\t\t\ty=text_classification(text)[0]\n\t\t\t\telif model_name == \"albert-base-v2\":\n\t\t\t\t\tmodel=transformers.AlbertForSequenceClassification.from_pretrained('/content/albert-base-v2_model')\n\t\t\t\t\ttokenizer=transformers.AlbertTokenizer.from_pretrained('albert-base-v2')\n\t\t\t\t\ttext_classification= transformers.pipeline('sentiment-analysis', model=model, tokenizer=tokenizer)\n\t\t\t\t\ty=text_classification(text)[0]\n\t\t\t\telif model_name == \"roberta-base\":\n\t\t\t\t\tmodel=transformers.RobertaForSequenceClassification.from_pretrained('/content/roberta-base_model')\n\t\t\t\t\ttokenizer=transformers.RobertaTokenizer.from_pretrained('roberta-base')\n\t\t\t\t\ttext_classification= transformers.pipeline('sentiment-analysis', model=model, tokenizer=tokenizer)\n\t\t\t\t\ty=text_classification(text)[0]\n\t\t\tprint(model_name)\n\t\t\tprint(y)\n\t\telse:\n\t\t\tfor model_name in self.model_list:\n\t\t\t\tif model_name == \"linear_SVM\" or model_name == \"multinomial_naive_bayesian\":\n\t\t\t\t\tclf = load('/content/'+model_name+'_model.joblib')\n\t\t\t\t\ty=clf.predict([text])\n\t\t\t\telse:\n\t\t\t\t\tif model_name == \"bert-base-uncased\":\n\t\t\t\t\t\tmodel=BertForSequenceClassification.from_pretrained('/content/bert-base-uncased_model')\n\t\t\t\t\t\ttokenizer=BertTokenizerFast.from_pretrained('bert-base-uncased')\n\t\t\t\t\t\ttext_classification= transformers.pipeline('sentiment-analysis', model=model, tokenizer=tokenizer)\n\t\t\t\t\t\ty=text_classification(text)[0]\n\t\t\t\t\telif model_name == \"albert-base-v2\":\n\t\t\t\t\t\tmodel=transformers.AlbertForSequenceClassification.from_pretrained('/content/albert-base-v2_model')\n\t\t\t\t\t\ttokenizer=transformers.AlbertTokenizer.from_pretrained('albert-base-v2')\n\t\t\t\t\t\ttext_classification= transformers.pipeline('sentiment-analysis', model=model, tokenizer=tokenizer)\n\t\t\t\t\t\ty=text_classification(text)[0]\n\t\t\t\t\telif model_name == \"roberta-base\":\n\t\t\t\t\t\tmodel=transformers.RobertaForSequenceClassification.from_pretrained('/content/roberta-base_model')\n\t\t\t\t\t\ttokenizer=transformers.RobertaTokenizer.from_pretrained('roberta-base')\n\t\t\t\t\t\ttext_classification= transformers.pipeline('sentiment-analysis', model=model, tokenizer=tokenizer)\n\t\t\t\t\t\ty=text_classification(text)[0]\n\t\t\t\tprint(model_name)\n\t\t\t\tprint(y)\n" ]
[ [ "pandas.DataFrame.from_dict", "pandas.DataFrame", "pandas.read_excel", "sklearn.model_selection.GridSearchCV", "sklearn.metrics.hamming_loss", "numpy.mean", "sklearn.metrics.accuracy_score", "sklearn.metrics.classification_report", "sklearn.metrics.precision_recall_fscore_support", "torch.cuda.empty_cache", "sklearn.linear_model.SGDClassifier", "torch.tensor", "sklearn.feature_extraction.text.CountVectorizer", "sklearn.naive_bayes.MultinomialNB", "sklearn.model_selection.train_test_split", "pandas.read_csv", "sklearn.feature_extraction.text.TfidfTransformer" ] ]
flyingleafe/asteroid
[ "1c3c68ffc83f4b0bf7b00893083e4eff1f577b88" ]
[ "notebooks/train_tasnet.py" ]
[ "import torch\nimport os\nimport os.path\nimport shutil\nimport numpy as np\nimport soundfile as sf\n\nfrom pathlib import PurePath\nfrom torch import nn\nfrom torch.utils.data import DataLoader, random_split\nfrom asteroid.data import TimitDataset\nfrom asteroid.data.utils import CachedWavSet, RandomMixtureSet, FixedMixtureSet\nfrom tqdm import tqdm\n\nfrom torch import optim\nfrom pytorch_lightning import Trainer, seed_everything, loggers as pl_loggers\nfrom pytorch_lightning.callbacks.early_stopping import EarlyStopping\nfrom pytorch_lightning.callbacks import ModelCheckpoint\nfrom asteroid_filterbanks.transforms import mag\nfrom asteroid.engine import System\nfrom asteroid.losses import singlesrc_neg_sisdr\n\nfrom egs.whamr.TasNet.model import TasNet\n\nBATCH_SIZE = 8 # could be more on cluster, test if larger one work\nSAMPLE_RATE = 8000 # as agreed upon\nCROP_LEN = 24000 # average track len in TIMIT\nSEED = 42 # magic number :)\n\ndef sisdr_loss_wrapper(est_target, target):\n return singlesrc_neg_sisdr(est_target.squeeze(1), target).mean()\n\ndef train_val_split(ds, val_fraction=0.1, random_seed=SEED):\n assert val_fraction > 0 and val_fraction < 0.5\n len_train = int(len(ds) * (1 - val_fraction))\n len_val = len(ds) - len_train\n return random_split(ds, [len_train, len_val], generator=torch.Generator().manual_seed(random_seed))\n\nDRONE_NOISE_DIR = '/jmain01/home/JAD007/txk02/aaa18-txk02/Datasets/noises-train-drones'\n# fixed SNRs for validation set\nTRAIN_SNRS = [-25, -20, -15, -10, -5]\n\n\nTIMIT_DIR = PurePath('/jmain01/home/JAD007/txk02/aaa18-txk02/Datasets/TIMIT')\nTIMIT_DIR_8kHZ = PurePath('/jmain01/home/JAD007/txk02/aaa18-txk02/Datasets/TIMIT_8kHZ')\n\n# Reproducibility - fix all random seeds\nseed_everything(SEED)\n\n# Load noises, resample and save into the memory\nnoises = CachedWavSet(DRONE_NOISE_DIR, sample_rate=SAMPLE_RATE, precache=True)\n\n# Load clean data and split it into train and val\ntimit = TimitDataset(TIMIT_DIR_8kHZ, subset='train', sample_rate=SAMPLE_RATE, with_path=False)\ntimit_train, timit_val = train_val_split(timit, val_fraction=0.1, random_seed=SEED)\n\n# Training data mixes crops randomly on the fly with random SNR in range (effectively infinite training data)\n# `repeat_factor=20` means that the dataset contains 20 copies of itself - it is the easiest way to make the epoch longer\ntimit_train = RandomMixtureSet(timit_train, noises, random_seed=SEED, snr_range=(-25, -5),\n crop_length=CROP_LEN, repeat_factor=30)\n\n# Validation data is fixed (for stability): mix every clean clip with all the noises in the folder\n# Argument `mixtures_per_clean` regulates with how many different noise files each clean file will be mixed\ntimit_val = FixedMixtureSet(timit_val, noises, snrs=TRAIN_SNRS, random_seed=SEED,\n mixtures_per_clean=5, crop_length=CROP_LEN)\n\nNUM_WORKERS = 5\ntrain_loader = DataLoader(timit_train, shuffle=True, batch_size=BATCH_SIZE,\n num_workers=NUM_WORKERS, drop_last=True)\nval_loader = DataLoader(timit_val, batch_size=BATCH_SIZE,\n num_workers=NUM_WORKERS, drop_last=True)\n\n# some random parameters, does it look sensible?\nLR = 1e-3\nREDUCE_LR_PATIENCE = 5\nEARLY_STOP_PATIENCE = 20\nMAX_EPOCHS = 20\n\n# the model here should be constructed in the script accordingly to the passed config (including the model type)\n# most of the models accept `sample_rate` parameter for encoders, which is important (default is 16000, override)\nmodel = TasNet(fb_conf={'n_filters': 512, 'kernel_size': 40, 'stride': 20},\n mask_conf ={'n_layers': 4, 'n_units': 500, 'dropout': 0.3, \"n_src\": 1})\n\noptimizer = optim.Adam(model.parameters(), lr=LR)\nscheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, patience=REDUCE_LR_PATIENCE)\nearly_stopping = EarlyStopping(monitor='val_loss', patience=EARLY_STOP_PATIENCE)\ncheckpoint = ModelCheckpoint(\n filename='{epoch:02d}-{val_loss:.2f}',\n monitor=\"val_loss\",\n mode=\"min\",\n save_top_k=5,\n verbose=True\n )\n\n# Probably we also need to subclass `System`, in order to log the target metrics on the validation set (PESQ/STOI)\nsystem = System(model, optimizer, sisdr_loss_wrapper, train_loader, val_loader, scheduler)\n\n# log dir and model name are also part of the config, of course\nLOG_DIR = 'logs'\nlogger = pl_loggers.TensorBoardLogger(LOG_DIR, name='TIMIT-drones-TasNet-random_test', version=1)\n\n# choose the proper accelerator for JADE, probably `ddp` (also, `auto_select_gpus=True` might be useful)\ntrainer = Trainer(max_epochs=MAX_EPOCHS, gpus=-1,\n logger=logger, callbacks=[early_stopping, checkpoint], deterministic=True, gradient_clip_val=5.0,)\n\ntrainer.fit(system)\n#torch.save(model.serialize(), 'tasnet_model.pt')\n" ]
[ [ "torch.optim.lr_scheduler.ReduceLROnPlateau", "torch.Generator", "torch.utils.data.DataLoader" ] ]
eightlay/SudokuSolver
[ "6e79d2ab752ee059fa62c77da913cd1b9215ee4b" ]
[ "src/model_train.py" ]
[ "# Import packages\nimport os\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.datasets import mnist\nfrom sklearn.preprocessing import LabelBinarizer\n\n# Import model builder from model_build.py\nfrom model_build import DRbuild\n\n# Load MNIST dataset\n((trainData, trainLabels), (testData, testLabels)) = mnist.load_data()\n\n# Add grayscale channel dimension\ntrainData = trainData.reshape((trainData.shape[0], 28, 28, 1))\ntestData = testData.reshape((testData.shape[0], 28, 28, 1))\n\n# Scale data to [0, 1] range\ntrainData = trainData.astype(\"float32\") / 255.0\ntestData = testData.astype(\"float32\") / 255.0\n\n# Enconde label to vector\nle = LabelBinarizer()\ntrainLabels = le.fit_transform(trainLabels)\ntestLabels = le.transform(testLabels)\n\n# starting learning rate\nLR = 1e-3\n# Epochs to train\nEPOCHS = 10\n# Batch size\nBS = 128\n\n# Compile model\nopt = Adam(lr=LR)\nmodel = DRbuild(width=28, height=28, depth=1, classes=10)\nmodel.compile(loss=\"categorical_crossentropy\", optimizer=opt,\n metrics=[\"accuracy\"])\n\n# Train model\nH = model.fit(\n trainData, trainLabels,\n validation_data=(testData, testLabels),\n batch_size=BS,\n epochs=EPOCHS,\n verbose=1)\n\n# Evaluate model\npredictions = model.predict(testData)\n\n# Serialize model\npath = os.getcwd()\npath = path[:path.rfind('\\\\') + 1]\npath = path + r'models\\digit_classifier.h5'\nmodel.save(path, save_format=\"h5\")\n" ]
[ [ "tensorflow.keras.datasets.mnist.load_data", "sklearn.preprocessing.LabelBinarizer", "tensorflow.keras.optimizers.Adam" ] ]
yuzheyyyy/Pytorch_Retinaface
[ "ef9812819026b766f2d1196770c74d17f22f3da9" ]
[ "data/data_augment.py" ]
[ "from torch.nn.functional import pad\nimport cv2\nimport numpy as np\nimport random\n\nimport imgaug as ia\nimport imgaug.augmenters as iaa\nfrom utils.box_utils import matrix_iof\n\n\ndef _crop(image, boxes, labels, landm, angles, visible, img_dim):\n height, width, _ = image.shape\n pad_image_flag = True\n\n for _ in range(250):\n \"\"\"\n if random.uniform(0, 1) <= 0.2:\n scale = 1.0\n else:\n scale = random.uniform(0.3, 1.0)\n \"\"\"\n PRE_SCALES = [0.3, 0.45, 0.6, 0.8, 1.0]\n scale = random.choice(PRE_SCALES)\n short_side = min(width, height)\n w = int(scale * short_side)\n h = w\n\n if width == w:\n l = 0\n else:\n l = random.randrange(width - w)\n if height == h:\n t = 0\n else:\n t = random.randrange(height - h)\n roi = np.array((l, t, l + w, t + h))\n\n value = matrix_iof(boxes, roi[np.newaxis])\n flag = (value >= 1.0)\n if not flag.any():\n continue\n\n centers = (boxes[:, :2] + boxes[:, 2:]) / 2\n mask_a = np.logical_and(roi[:2] < centers, centers < roi[2:]).all(axis=1)\n boxes_t = boxes[mask_a].copy()\n labels_t = labels[mask_a].copy()\n landms_t = landm[mask_a].copy()\n landms_t = landms_t.reshape([-1, 5, 2])\n angles_t = angles[mask_a].copy()\n visible_t = visible[mask_a].copy()\n\n if boxes_t.shape[0] == 0:\n continue\n\n image_t = image[roi[1]:roi[3], roi[0]:roi[2]]\n\n boxes_t[:, :2] = np.maximum(boxes_t[:, :2], roi[:2])\n boxes_t[:, :2] -= roi[:2]\n boxes_t[:, 2:] = np.minimum(boxes_t[:, 2:], roi[2:])\n boxes_t[:, 2:] -= roi[:2]\n if np.any(boxes_t<0):\n print('fail')\n # print('box {}'.format(np.any(boxes_t<0)))\n # landm\n\n \n mask1 = np.any(landms_t < roi[:2], axis=-1)# mask for those invisible landmarks, both original (-1,-1) and (landmark < roi)\n mask2 = np.any(landms_t > roi[2:], axis=-1)\n mask = np.logical_or(mask1, mask2)\n\n landms_t[:, :, :2] = landms_t[:, :, :2] - roi[:2]\n landms_t[:, :, :2] = np.maximum(landms_t[:, :, :2], np.array([0, 0]))\n landms_t[:, :, :2] = np.minimum(landms_t[:, :, :2], roi[2:] - roi[:2])\n landms_t[mask] = -1\n landms_t = landms_t.reshape([-1, 10])\n\n\n\t# make sure that the cropped image contains at least one face > 16 pixel at training image scale\n b_w_t = (boxes_t[:, 2] - boxes_t[:, 0] + 1) / w * img_dim\n b_h_t = (boxes_t[:, 3] - boxes_t[:, 1] + 1) / h * img_dim\n mask_b = np.minimum(b_w_t, b_h_t) > 0.0\n boxes_t = boxes_t[mask_b]\n labels_t = labels_t[mask_b]\n landms_t = landms_t[mask_b]\n angles_t = angles_t[mask_b]\n visible_t = visible_t[mask_b]\n\n if boxes_t.shape[0] == 0:\n continue\n\n pad_image_flag = False\n\n return image_t, boxes_t, labels_t, landms_t, angles_t, visible_t, pad_image_flag\n return image, boxes, labels, landm, angles, visible, pad_image_flag\n\n\n\n\ndef _distort(image):\n\n def _convert(image, alpha=1, beta=0):\n tmp = image.astype(float) * alpha + beta\n tmp[tmp < 0] = 0\n tmp[tmp > 255] = 255\n image[:] = tmp\n\n image = image.copy()\n\n if random.randrange(2):\n\n #brightness distortion\n if random.randrange(2):\n _convert(image, beta=random.uniform(-32, 32))\n\n #contrast distortion\n if random.randrange(2):\n _convert(image, alpha=random.uniform(0.5, 1.5))\n\n image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\n\n #saturation distortion\n if random.randrange(2):\n _convert(image[:, :, 1], alpha=random.uniform(0.5, 1.5))\n\n #hue distortion\n if random.randrange(2):\n tmp = image[:, :, 0].astype(int) + random.randint(-18, 18)\n tmp %= 180\n image[:, :, 0] = tmp\n\n image = cv2.cvtColor(image, cv2.COLOR_HSV2BGR)\n\n else:\n\n #brightness distortion\n if random.randrange(2):\n _convert(image, beta=random.uniform(-32, 32))\n\n image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\n\n #saturation distortion\n if random.randrange(2):\n _convert(image[:, :, 1], alpha=random.uniform(0.5, 1.5))\n\n #hue distortion\n if random.randrange(2):\n tmp = image[:, :, 0].astype(int) + random.randint(-18, 18)\n tmp %= 180\n image[:, :, 0] = tmp\n\n image = cv2.cvtColor(image, cv2.COLOR_HSV2BGR)\n\n #contrast distortion\n if random.randrange(2):\n _convert(image, alpha=random.uniform(0.5, 1.5))\n\n return image\n\n\ndef _expand(image, boxes, fill, p):\n if random.randrange(2):\n return image, boxes\n\n height, width, depth = image.shape\n\n scale = random.uniform(1, p)\n w = int(scale * width)\n h = int(scale * height)\n\n left = random.randint(0, w - width)\n top = random.randint(0, h - height)\n\n boxes_t = boxes.copy()\n boxes_t[:, :2] += (left, top)\n boxes_t[:, 2:] += (left, top)\n expand_image = np.empty(\n (h, w, depth),\n dtype=image.dtype)\n expand_image[:, :] = fill\n expand_image[top:top + height, left:left + width] = image\n image = expand_image\n\n return image, boxes_t\n\n\ndef _mirror(image, boxes, landms):\n _, width, _ = image.shape\n if random.randrange(2):\n image = image[:, ::-1]\n boxes = boxes.copy()\n boxes[:, 0::2] = width - boxes[:, 2::-2]\n\n # landm\n landms = landms.copy()\n landms = landms.reshape([-1, 5, 2])\n # mask = np.any(landms < 0, axis=-1)\n landms[:, :, 0] = width - landms[:, :, 0]\n # landms[mask] = -1\n tmp = landms[:, 1, :].copy()\n landms[:, 1, :] = landms[:, 0, :]\n landms[:, 0, :] = tmp\n tmp1 = landms[:, 4, :].copy()\n landms[:, 4, :] = landms[:, 3, :]\n landms[:, 3, :] = tmp1\n landms = landms.reshape([-1, 10])\n\n return image, boxes, landms\n\n\ndef _pad_to_square(image, rgb_mean, pad_image_flag):\n if not pad_image_flag:\n return image\n height, width, _ = image.shape\n long_side = max(width, height)\n image_t = np.empty((long_side, long_side, 3), dtype=image.dtype)\n image_t[:, :] = rgb_mean\n image_t[0:0 + height, 0:0 + width] = image\n return image_t\n\n\ndef _resize_subtract_mean(image, insize, rgb_mean):\n interp_methods = [cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_NEAREST, cv2.INTER_LANCZOS4]\n interp_method = interp_methods[random.randrange(5)]\n image = cv2.resize(image, (insize, insize), interpolation=interp_method)\n image = image.astype(np.float32)\n image -= rgb_mean\n # image /= 128.\n return image.transpose(2, 0, 1)\n\n\n\nclass Cutout(object):\n \"\"\"Randomly mask out one or more patches from an image.\n Args:\n n_holes (int): Number of patches to cut out of each image.\n length (int): The length (in pixels) of each square patch.\n \"\"\"\n def __init__(self, n_holes, length):\n self.n_holes = n_holes\n self.length = length\n\n def __call__(self, img):\n \"\"\"\n Args:\n img (Tensor): Tensor image of size (C, H, W).\n Returns:\n Tensor: Image with n_holes of dimension length x length cut out of it.\n \"\"\"\n w, h = img.shape[-2:]\n\n mask = np.ones((h, w), np.float32)\n\n for n in range(self.n_holes):\n y = np.random.randint(h)\n x = np.random.randint(w)\n\n y1 = np.clip(y - self.length // 2, 0, h)\n y2 = np.clip(y + self.length // 2, 0, h)\n x1 = np.clip(x - self.length // 2, 0, w)\n x2 = np.clip(x + self.length // 2, 0, w)\n\n mask[y1: y2, x1: x2] = 0.\n\n mask = mask[np.newaxis, ...].repeat(3, axis=0)\n img = img * mask\n\n return img\n\n\ndef _transformation(image, boxes, landm):\n h, w, _ = image.shape\n num = np.shape(boxes)[0]\n boxes_all = np.hstack((boxes, boxes[:, [0, 3, 1, 2]]))\n points_all = np.hstack((boxes_all, landm)).reshape(1, -1, 2)\n\n\n seq = iaa.Sequential([\n iaa.Affine(\n # scale={\"x\": (0.8, 1.2), \"y\": (0.8, 1.2)}, # scale images to 80-120% of their size, individually per axis\n # translate_percent={\"x\": (-0.2, 0.2), \"y\": (-0.2, 0.2)}, # translate by -20 to +20 percent (per axis)\n rotate=(-25, 25), # rotate by -45 to +45 degrees\n shear=(-16, 16), # shear by -16 to +16 degrees\n order=[0, 1], # use nearest neighbour or bilinear interpolation (fast)\n # cval=(0, 255), # if mode is constant, use a cval between 0 and 255\n mode= \"constant\" # use any of scikit-image's warping modes (see 2nd image from the top for examples)\n ), \n iaa.PerspectiveTransform(scale=(0.1, 0.15), keep_size=True)])\n \n img_aug, points_aug = seq(image=image, keypoints=points_all)\n points_aug = points_aug.reshape([-1, 2])\n for i in range(num):\n\n # box\n box1 = np.min(points_aug[9*i:9*i+4, :], axis=0).reshape(2)\n mask1 = (box1 < 0.)\n box1[mask1] = 0.\n box2 = np.max(points_aug[9*i:9*i+4, :], axis=0).reshape(2)\n mask2 = (box2 > np.array([w, h]))\n box2[mask2] = np.array([w, h])[mask2]\n boxes[i, :2] = box1\n boxes[i, 2:] = box2\n\n # landmarks\n lm = points_aug[9*i+4:9*(i+1), :]\n mask1 = np.any(lm < 0, axis=1)\n mask2 = np.any(lm > np.array([w, h]), axis=1)\n mask = np.logical_or(mask1, mask2)\n lm[mask] = -1\n lm = lm.reshape(10)\n landm[i, :] = lm\n \n return img_aug, boxes, landm\n\n\nclass preproc(object):\n\n def __init__(self, img_dim, rgb_means):\n self.img_dim = img_dim\n self.rgb_means = rgb_means\n\n def __call__(self, image, targets, own):\n assert targets.shape[0] > 0, \"this image does not have gt\"\n\n '''\n for label with visible\n '''\n boxes = targets[:, :4].copy()\n labels = targets[:, -7].copy()\n landm = targets[:, 4:-7].copy()\n angle = targets[:, -6].copy()\n visible = targets[:, -5:].copy()\n\n\n # with visible\n image_t, boxes_t, labels_t, landm_t, angles_t, visible_t, pad_image_flag = _crop(image, boxes, labels, landm, angle, visible, self.img_dim)\n\n image_t = _distort(image_t)\n image_t = _pad_to_square(image_t,self.rgb_means, pad_image_flag)\n\n image_t, boxes_t, landm_t = _mirror(image_t, boxes_t, landm_t) \n height, width, _ = image_t.shape\n # print('self rgb {}'.format(self.rgb_means))\n image_t = _resize_subtract_mean(image_t, self.img_dim, self.rgb_means)\n if own[:4] == '/opt':\n rand = np.random.rand()\n if rand < 0.5:\n cutout = Cutout(n_holes=2, length=40)\n image_t = cutout(image_t)\n boxes_t[:, 0::2] /= width\n boxes_t[:, 1::2] /= height\n landm_t[:, 0::2] /= width\n landm_t[:, 1::2] /= height\n\n \n labels_t = np.expand_dims(labels_t, 1)\n\n '''visible'''\n angles_t = np.expand_dims(angles_t, 1)\n\n targets_t = np.hstack((boxes_t, landm_t, labels_t, angles_t, visible_t))\n\n return image_t, targets_t" ]
[ [ "numpy.max", "numpy.logical_or", "numpy.array", "numpy.empty", "numpy.random.rand", "numpy.minimum", "numpy.ones", "numpy.min", "numpy.shape", "numpy.logical_and", "numpy.any", "numpy.random.randint", "numpy.clip", "numpy.hstack", "numpy.expand_dims", "numpy.maximum" ] ]
iCGY96/APR
[ "72557dfbd496f6088f002e26ac96d11534beed2f" ]
[ "main.py" ]
[ "import os\nimport sys\nimport argparse\nimport datetime\nimport time\nimport csv\nimport os.path as osp\nimport numpy as np\nimport warnings\nimport importlib\nimport pandas as pd\nwarnings.filterwarnings('ignore')\n\nimport torch\nimport torch.nn as nn\nfrom torch.optim import lr_scheduler\nimport torch.backends.cudnn as cudnn\nimport torchvision\nfrom datasets import CIFAR10D, CIFAR100D\nfrom utils.utils import AverageMeter, Logger, save_networks, load_networks\nfrom core import train, test, test_robustness\n\nparser = argparse.ArgumentParser(\"Training\")\n\n# dataset\nparser.add_argument('--data', type=str, default='./data')\nparser.add_argument('--outf', type=str, default='./results')\n\nparser.add_argument('-d', '--dataset', type=str, default='cifar10')\nparser.add_argument('--workers', default=8, type=int, help=\"number of data loading workers (default: 4)\")\n\n# optimization\nparser.add_argument('--batch-size', type=int, default=128)\nparser.add_argument('--lr', type=float, default=0.1, help=\"learning rate for model\")\nparser.add_argument('--max-epoch', type=int, default=200)\nparser.add_argument('--stepsize', type=int, default=30)\nparser.add_argument('--aug', type=str, default='none', help='none, aprs')\n\n# model\nparser.add_argument('--model', type=str, default='wider_resnet_28_10')\n\n# misc\nparser.add_argument('--eval-freq', type=int, default=10)\nparser.add_argument('--print-freq', type=int, default=100)\nparser.add_argument('--gpu', type=str, default='0')\nparser.add_argument('--seed', type=int, default=0)\nparser.add_argument('--use-cpu', action='store_true')\nparser.add_argument('--eval', action='store_true', help=\"Eval\", default=False)\n\n# parameters for generating adversarial examples\nparser.add_argument('--epsilon', '-e', type=float, default=0.0157,\n help='maximum perturbation of adversaries (4/255=0.0157)')\nparser.add_argument('--alpha', '-a', type=float, default=0.00784,\n help='movement multiplier per iteration when generating adversarial examples (2/255=0.00784)')\nparser.add_argument('--k', '-k', type=int, default=10,\n help='maximum iteration when generating adversarial examples')\nparser.add_argument('--perturbation_type', '-p', choices=['linf', 'l2'], default='linf',\n help='the type of the perturbation (linf or l2)')\n\nargs = parser.parse_args()\noptions = vars(args)\n\nif not os.path.exists(options['outf']):\n os.makedirs(options['outf'])\n\nif not os.path.exists(options['data']):\n os.makedirs(options['data'])\n\nsys.stdout = Logger(osp.join(options['outf'], 'logs.txt'))\n\ndef main():\n torch.manual_seed(options['seed'])\n os.environ['CUDA_VISIBLE_DEVICES'] = options['gpu']\n use_gpu = torch.cuda.is_available()\n if options['use_cpu']: use_gpu = False\n\n options.update({'use_gpu': use_gpu})\n\n if use_gpu:\n print(\"Currently using GPU: {}\".format(options['gpu']))\n cudnn.benchmark = True\n torch.cuda.manual_seed_all(options['seed'])\n else:\n print(\"Currently using CPU\")\n\n if 'cifar10' == options['dataset']:\n Data = CIFAR10D(dataroot=options['data'], batch_size=options['batch_size'], _transforms=options['aug'], _eval=options['eval'])\n OODData = CIFAR100D(dataroot=options['data'], batch_size=options['batch_size'], _transforms=options['aug'])\n else:\n Data = CIFAR100D(dataroot=options['data'], batch_size=options['batch_size'], _transforms=options['aug'], _eval=options['eval'])\n OODData = CIFAR10D(dataroot=options['data'], batch_size=options['batch_size'], _transforms=options['aug'])\n \n trainloader, testloader, outloader = Data.train_loader, Data.test_loader, OODData.test_loader\n num_classes = Data.num_classes\n\n print(\"Creating model: {}\".format(options['model']))\n if 'wide_resnet' in options['model']:\n print('wide_resnet')\n from model.wide_resnet import WideResNet\n net = WideResNet(40, num_classes, 2, 0.0)\n elif 'allconv' in options['model']:\n print('allconv')\n from model.allconv import AllConvNet\n net = AllConvNet(num_classes)\n elif 'densenet' in options['model']:\n print('densenet')\n from model.densenet import densenet\n net = densenet(num_classes=num_classes)\n elif 'resnext' in options['model']:\n print('resnext29')\n from model.resnext import resnext29\n net = resnext29(num_classes)\n else:\n print('resnet18')\n from model.resnet import ResNet18\n net = ResNet18(num_classes=num_classes)\n\n # define loss function (criterion) and optimizer\n criterion = nn.CrossEntropyLoss().cuda()\n\n if use_gpu:\n net = nn.DataParallel(net, device_ids=[i for i in range(len(options['gpu'].split(',')))]).cuda()\n criterion = criterion.cuda()\n\n file_name = '{}_{}_{}'.format(options['model'], options['dataset'], options['aug'])\n\n if options['eval']:\n net, criterion = load_networks(net, options['outf'], file_name, criterion=criterion)\n outloaders = Data.out_loaders\n results = test(net, criterion, testloader, outloader, epoch=0, **options)\n acc = results['ACC']\n res = dict()\n res['ACC'] = dict()\n acc_res = []\n for key in Data.out_keys:\n results = test_robustness(net, criterion, outloaders[key], epoch=0, label=key, **options)\n print('{} (%): {:.3f}\\t'.format(key, results['ACC']))\n res['ACC'][key] = results['ACC']\n acc_res.append(results['ACC'])\n print('Mean ACC:', np.mean(acc_res))\n print('Mean Error:', 100-np.mean(acc_res))\n\n return\n\n params_list = [{'params': net.parameters()},\n {'params': criterion.parameters()}]\n\n\n optimizer = torch.optim.SGD(params_list, lr=options['lr'], momentum=0.9, nesterov=True, weight_decay=5e-4)\n scheduler = lr_scheduler.MultiStepLR(optimizer, gamma=0.2, milestones=[60, 120, 160, 190])\n\n start_time = time.time()\n\n best_acc = 0.0\n for epoch in range(options['max_epoch']):\n print(\"==> Epoch {}/{}\".format(epoch+1, options['max_epoch']))\n\n train(net, criterion, optimizer, trainloader, epoch=epoch, **options)\n\n if options['eval_freq'] > 0 and (epoch+1) % options['eval_freq'] == 0 or (epoch+1) == options['max_epoch'] or epoch > 160:\n print(\"==> Test\")\n results = test(net, criterion, testloader, outloader, epoch=epoch, **options)\n\n if best_acc < results['ACC']:\n best_acc = results['ACC']\n print(\"Best Acc (%): {:.3f}\\t\".format(best_acc))\n \n save_networks(net, options['outf'], file_name, criterion=criterion)\n\n scheduler.step()\n\n elapsed = round(time.time() - start_time)\n elapsed = str(datetime.timedelta(seconds=elapsed))\n print(\"Finished. Total elapsed time (h:m:s): {}\".format(elapsed))\n\nif __name__ == '__main__':\n main()\n\n" ]
[ [ "torch.cuda.manual_seed_all", "torch.optim.SGD", "numpy.mean", "torch.optim.lr_scheduler.MultiStepLR", "torch.manual_seed", "torch.cuda.is_available", "torch.nn.CrossEntropyLoss" ] ]
gilbert2002/dlib
[ "7eac06947dc07cc34ca095c934d8cb1722d372a7" ]
[ "tools/python/test/test_numpy_returns.py" ]
[ "import sys\nimport pickle\n\nimport dlib\nimport pytest\n\nimport utils\n\n# Paths are relative to dlib root\nimage_path = \"examples/faces/Tom_Cruise_avp_2014_4.jpg\"\nshape_path = \"tools/python/test/shape.pkl\"\nface_chip_path = \"tools/python/test/test_face_chip.npy\"\n\ndef get_test_image_and_shape():\n img = dlib.load_rgb_image(image_path)\n shape = utils.load_pickled_compatible(shape_path)\n return img, shape\n \ndef get_test_face_chips():\n rgb_img, shape = get_test_image_and_shape()\n shapes = dlib.full_object_detections()\n shapes.append(shape)\n return dlib.get_face_chips(rgb_img, shapes)\n\ndef get_test_face_chip():\n rgb_img, shape = get_test_image_and_shape()\n return dlib.get_face_chip(rgb_img, shape)\n\n# The tests below will be skipped if Numpy is not installed\n@pytest.mark.skipif(not utils.is_numpy_installed(), reason=\"requires numpy\")\ndef test_get_face_chip():\n import numpy\n face_chip = get_test_face_chip()\n expected = numpy.load(face_chip_path)\n assert numpy.array_equal(face_chip, expected)\n\n@pytest.mark.skipif(not utils.is_numpy_installed(), reason=\"requires numpy\")\ndef test_get_face_chips():\n import numpy\n face_chips = get_test_face_chips()\n expected = numpy.load(face_chip_path)\n assert numpy.array_equal(face_chips[0], expected)\n\n@pytest.mark.skipif(not utils.is_numpy_installed(), reason=\"requires numpy\")\ndef test_regression_issue_1220_get_face_chip():\n \"\"\"\n Memory leak in Python get_face_chip\n https://github.com/davisking/dlib/issues/1220\n \"\"\"\n face_chip = get_test_face_chip()\n # we expect two references:\n # 1.) the local variable \n # 2.) the temporary passed to getrefcount\n assert sys.getrefcount(face_chip) == 2\n\n@pytest.mark.skipif(not utils.is_numpy_installed(), reason=\"requires numpy\")\ndef test_regression_issue_1220_get_face_chips():\n \"\"\"\n Memory leak in Python get_face_chip\n https://github.com/davisking/dlib/issues/1220\n \"\"\"\n face_chips = get_test_face_chips()\n count = sys.getrefcount(face_chips)\n assert count == 2\n count = sys.getrefcount(face_chips[0])\n assert count == 2" ]
[ [ "numpy.load", "numpy.array_equal" ] ]
yashrsharma44/sunpy
[ "f1dda2e188e5384eec472ceefceb2ed0f9781e75" ]
[ "sunpy/timeseries/timeseriesbase.py" ]
[ "\"\"\"\nTimeSeries is a generic time series class from which all other TimeSeries\nclasses inherit from.\n\"\"\"\nimport copy\nimport warnings\nfrom collections import OrderedDict\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nimport astropy\nimport astropy.units as u\nfrom astropy.table import Table, Column\n\nfrom sunpy import config\nfrom sunpy.time import TimeRange\nfrom sunpy.timeseries import TimeSeriesMetaData\nfrom sunpy.util.metadata import MetaDict\nfrom sunpy.util.exceptions import SunpyUserWarning\n\n# define and register a new unit, needed for RHESSI\ndet = u.def_unit('detector')\nu.add_enabled_units([det])\n\nTIME_FORMAT = config.get(\"general\", \"time_format\")\n\n\nclass GenericTimeSeries:\n \"\"\"\n A generic time series object.\n\n Parameters\n ----------\n data : `~pandas.DataFrame`\n A pandas DataFrame representing one or more fields as a function\n of time.\n meta : `~sunpy.timeseries.metadata.TimeSeriesMetaData`, optional\n The metadata giving details about the time series data/instrument.\n units : dict, optional\n A mapping from column names in *data* to the physical units of\n that column.\n\n Attributes\n ----------\n data : `~pandas.DataFrame`\n A pandas DataFrame representing one or more fields as a function\n of time.\n meta : `~sunpy.timeseries.metadata.TimeSeriesMetaData`\n The metadata giving details about the time series data/instrument.\n units : dict\n A mapping from column names in *data* to the physical units of\n that column.\n\n Examples\n --------\n >>> from sunpy.timeseries import TimeSeries\n >>> from sunpy.time import parse_time\n >>> import datetime\n >>> from astropy.time import TimeDelta\n >>> import numpy as np\n >>> import pandas as pd\n >>> base = parse_time(datetime.datetime.today())\n >>> times = base - TimeDelta(np.arange(24 * 60)*u.minute)\n >>> intensity = np.sin(np.arange(0, 12 * np.pi, step=(12 * np.pi) / (24 * 60)))\n >>> df = pd.DataFrame(intensity, index=times, columns=['intensity'])\n >>> ts = TimeSeries(df)\n >>> ts.peek() # doctest: +SKIP\n\n References\n ----------\n * `Pandas Documentation <https://pandas.pydata.org/pandas-docs/stable/>`_\n\n \"\"\"\n\n # Class attribute used to specify the source class of the TimeSeries.\n _source = None\n _registry = dict()\n\n def __init_subclass__(cls, **kwargs):\n \"\"\"\n An __init_subclass__ hook initializes all of the subclasses of a given class.\n So for each subclass, it will call this block of code on import.\n This replicates some metaclass magic without the need to be aware of metaclasses.\n Here we use this to register each subclass in a dict that has the `is_datasource_for`\n attribute. This is then passed into the TimeSeries Factory so we can register them.\n \"\"\"\n super().__init_subclass__(**kwargs)\n if hasattr(cls, 'is_datasource_for'):\n cls._registry[cls] = cls.is_datasource_for\n\n def __init__(self, data, meta=None, units=None, **kwargs):\n self.data = data\n tr = self.time_range\n # Check metadata input\n if meta is None:\n # No meta given, so default\n self.meta = TimeSeriesMetaData(MetaDict(), tr, list(self.data.columns.values))\n elif isinstance(meta, (dict, OrderedDict, MetaDict)):\n # Given the values for metadata (dict) and infer timerange and colnames from the data\n self.meta = TimeSeriesMetaData(meta, tr, list(self.data.columns.values))\n elif isinstance(meta, tuple):\n # Given the values all in a tuple\n self.meta = TimeSeriesMetaData(meta, tr, list(self.data.columns.values))\n else:\n # Should have a list of 3-tuples giving a complex metadata list.\n self.meta = meta\n\n if units is None:\n self.units = {}\n else:\n self.units = units\n\n # Validate input data\n # self._validate_meta()\n # self._validate_units()\n\n# #### Attribute definitions #### #\n\n @property\n def source(self):\n \"\"\"\n A string/object used to specify the source class of the TimeSeries.\n \"\"\"\n return self._source\n\n @property\n def columns(self):\n \"\"\"A list of all the names of the columns in the data.\"\"\"\n return list(self.data.columns.values)\n\n @property\n def index(self):\n \"\"\"The time index of the data.\"\"\"\n return self.data.index\n\n @property\n def time_range(self):\n \"\"\"\n The start and end times of the TimeSeries as a `~sunpy.time.TimeRange`\n object\n \"\"\"\n if len(self.data)>0:\n return TimeRange(self.data.index.min(), self.data.index.max())\n else:\n return None\n\n# #### Data Access, Selection and Organisation Methods #### #\n\n def quantity(self, colname, **kwargs):\n \"\"\"\n Return a `~astropy.units.quantity.Quantity` for the given column.\n\n Parameters\n ----------\n colname : `str`\n The heading of the column you want output.\n\n Returns\n -------\n quantity : `~astropy.units.quantity.Quantity`\n \"\"\"\n values = self.data[colname].values\n unit = self.units[colname]\n return u.Quantity(values, unit)\n\n def add_column(self, colname, quantity, unit=False, overwrite=True, **kwargs):\n \"\"\"\n Return an new TimeSeries with the given column added or updated.\n\n Parameters\n ----------\n colname : `str`\n The heading of the column you want output.\n\n quantity : `~astropy.units.quantity.Quantity` or `~numpy.ndarray`\n The values to be placed within the column.\n If updating values only then a numpy array is permitted.\n\n overwrite : `bool`, optional, default:True\n Set to true to allow the method to overwrite a column already present\n in the TimeSeries.\n\n Returns\n -------\n newts : TimeSeries\n\n \"\"\"\n # Get the expected units from the quantity if required\n if not unit and isinstance(quantity, astropy.units.quantity.Quantity):\n unit = quantity.unit\n elif not unit:\n unit = u.dimensionless_unscaled\n\n # Make a copy of all the TimeSeries components.\n data = copy.copy(self.data)\n meta = TimeSeriesMetaData(copy.copy(self.meta.metadata))\n units = copy.copy(self.units)\n\n # Add the unit to the units dictionary if already there.\n if not (colname in self.data.columns):\n units[colname] = unit\n\n # Convert the given quantity into values for given units if necessary.\n values = quantity\n if isinstance(values, astropy.units.quantity.Quantity) and overwrite:\n values = values.to(units[colname]).value\n\n # Update or add the data.\n if not (colname in self.data.columns) or overwrite:\n data[colname] = values\n\n # Return a new TimeSeries with the given updated/added column.\n return self.__class__(data, meta, units)\n\n def sort_index(self, **kwargs):\n \"\"\"Returns a sorted version of the TimeSeries object.\n Generally this shouldn't be necessary as most TimeSeries operations sort\n the data anyway to ensure consistent behaviour when truncating.\n\n Returns\n -------\n newts : `~sunpy.timeseries.TimeSeries`\n A new time series in ascending chronological order.\n \"\"\"\n return GenericTimeSeries(self.data.sort_index(**kwargs),\n TimeSeriesMetaData(copy.copy(self.meta.metadata)),\n copy.copy(self.units))\n\n def truncate(self, a, b=None, int=None):\n \"\"\"Returns a truncated version of the TimeSeries object.\n\n Parameters\n ----------\n a : `sunpy.time.TimeRange`, `str` or `int`\n Either a time range to truncate to, or a start time in some format\n recognised by pandas, or a index integer.\n\n b : `str` or `int`\n If specified, the end time of the time range in some format\n recognised by pandas, or a index integer.\n\n int : `int`\n If specified, the integer indicating the slicing intervals.\n\n Returns\n -------\n newts : `~sunpy.timeseries.TimeSeries`\n A new time series with only the selected times.\n \"\"\"\n # Evaluate inputs\n # If given strings, then use to create a sunpy.time.timerange.TimeRange\n # for the SunPy text date parser.\n if isinstance(a, str) and isinstance(b, str):\n a = TimeRange(a, b)\n if isinstance(a, TimeRange):\n # If we have a TimeRange, extract the values\n start = a.start.datetime\n end = a.end.datetime\n else:\n # Otherwise we already have the values\n start = a\n end = b\n\n # If an interval integer was given then use in truncation.\n truncated_data = self.data.sort_index()[start:end:int]\n\n # Truncate the metadata\n # Check there is data still\n truncated_meta = TimeSeriesMetaData([])\n if len(truncated_data) > 0:\n tr = TimeRange(truncated_data.index.min(), truncated_data.index.max())\n truncated_meta = TimeSeriesMetaData(copy.deepcopy(self.meta.metadata))\n truncated_meta._truncate(tr)\n\n # Build similar TimeSeries object and sanatise metadata and units.\n object = self.__class__(truncated_data.sort_index(), truncated_meta, copy.copy(self.units))\n object._sanitize_metadata()\n object._sanitize_units()\n return object\n\n def extract(self, column_name):\n \"\"\"Returns a new time series with the chosen column.\n\n Parameters\n ----------\n column_name : `str`\n A valid column name.\n\n Returns\n -------\n newts : `~sunpy.timeseries.TimeSeries`\n A new time series with only the selected column.\n \"\"\"\n \"\"\"\n # TODO allow the extract function to pick more than one column\n if isinstance(self, pandas.Series):\n return self\n else:\n return GenericTimeSeries(self.data[column_name], TimeSeriesMetaData(self.meta.metadata.copy()))\n \"\"\"\n # Extract column and remove empty rows\n data = self.data[[column_name]].dropna()\n\n # Build generic TimeSeries object and sanatise metadata and units.\n object = GenericTimeSeries(data.sort_index(),\n TimeSeriesMetaData(copy.copy(self.meta.metadata)),\n copy.copy(self.units))\n object._sanitize_metadata()\n object._sanitize_units()\n return object\n\n def concatenate(self, otherts, **kwargs):\n \"\"\"Concatenate with another TimeSeries. This function will check and\n remove any duplicate times. It will keep the column values from the\n original time series to which the new time series is being added.\n\n Parameters\n ----------\n otherts : `~sunpy.timeseries.TimeSeries`\n Another time series.\n\n same_source : `bool` Optional\n Set to true to check if the sources of the time series match.\n\n Returns\n -------\n newts : `~sunpy.timeseries.TimeSeries`\n A new time series.\n\n Debate: decide if we want to be able to concatenate multiple time series\n at once.\n \"\"\"\n\n # check to see if nothing needs to be done\n if self == otherts:\n return self\n\n # Check the sources match if specified.\n same_source = kwargs.get('same_source', False)\n if same_source and not (isinstance(otherts, self.__class__)):\n raise TypeError(\"TimeSeries classes must match if specified.\")\n\n # Concatenate the metadata and data\n meta = self.meta.concatenate(otherts.meta)\n data = pd.concat([self.data.copy(), otherts.data], **kwargs)\n\n # Add all the new units to the dictionary.\n units = OrderedDict()\n units.update(self.units)\n units.update(otherts.units)\n\n # If sources match then build similar TimeSeries.\n if self.__class__ == otherts.__class__:\n object = self.__class__(data.sort_index(), meta, units)\n else:\n # Build generic time series if the sources don't match.\n object = GenericTimeSeries(data.sort_index(), meta, units)\n\n # Sanatise metadata and units\n object._sanitize_metadata()\n object._sanitize_units()\n return object\n\n# #### Plotting Methods #### #\n\n def plot(self, axes=None, **plot_args):\n \"\"\"Plot a plot of the time series\n\n Parameters\n ----------\n axes : `~matplotlib.axes.Axes` or None\n If provided the image will be plotted on the given axes. Otherwise\n the current axes will be used.\n\n **plot_args : `dict`\n Any additional plot arguments that should be used\n when plotting.\n\n Returns\n -------\n axes : `~matplotlib.axes.Axes`\n The plot axes.\n \"\"\"\n\n # Get current axes\n if axes is None:\n axes = plt.gca()\n\n axes = self.data.plot(ax=axes, **plot_args)\n\n return axes\n\n def peek(self, **kwargs):\n \"\"\"Displays the time series in a new figure.\n\n Parameters\n ----------\n **kwargs : `dict`\n Any additional plot arguments that should be used when plotting.\n \"\"\"\n # Check we have a timeseries valid for plotting\n self._validate_data_for_ploting()\n\n # Now make the plot\n figure = plt.figure()\n self.plot(**kwargs)\n figure.show()\n\n def _validate_data_for_ploting(self):\n \"\"\"Raises an exception if the timeseries is invalid for plotting.\n To be added into all the peek methods in all source sup-classes.\n Currently only checks if we have an empty timeseries, where:\n len(self.data) == 0\n\n \"\"\"\n # Check we have a valid TS\n if len(self.data) == 0:\n raise ValueError(\"The timeseries can't be plotted as it has no data present. \"\n \"(len(self.data) == 0)\")\n\n# #### Miscellaneous #### #\n\n def _validate_meta(self):\n \"\"\"\n Validates the meta-information associated with a TimeSeries.\n\n This method includes very basic validation checks which apply to\n all of the kinds of files that SunPy can read. Datasource-specific\n validation should be handled in the relevant file in the\n sunpy.timeseries.sources package.\n\n Allows for default unit assignment for:\n COL_UNITS\n\n \"\"\"\n\n warnings.simplefilter('always', Warning)\n\n for meta_property in ('cunit1', 'cunit2', 'waveunit'):\n if (self.meta.get(meta_property) and\n u.Unit(self.meta.get(meta_property),\n parse_strict='silent').physical_type == 'unknown'):\n\n warnings.warn(f\"Unknown value for {meta_property.upper()}.\", SunpyUserWarning)\n\n def _validate_units(self, units, **kwargs):\n \"\"\"\n Validates the astropy unit-information associated with a TimeSeries.\n\n This method includes very basic validation checks which apply to\n all of the kinds of files that SunPy can read. Datasource-specific\n validation should be handled in the relevant file in the\n sunpy.timeseries.sources package.\n\n Allows for default unit assignment for:\n COL_UNITS\n\n \"\"\"\n\n warnings.simplefilter('always', Warning)\n\n result = True\n for key in units:\n if not isinstance(units[key], astropy.units.UnitBase):\n # If this is not a unit then this can't be a valid units dict.\n result = False\n warnings.warn(f\"Invalid unit given for {key}.\", SunpyUserWarning)\n\n return result\n\n def _sanitize_units(self, **kwargs):\n \"\"\"\n Sanitises the collections.OrderedDict used to store the units.\n Primarily this method will:\n\n Remove entries that don't match up to a column,\n Add unitless entries for columns with no units defined.\n Re-arrange the order of the dictionary to match the columns.\n \"\"\"\n warnings.simplefilter('always', Warning)\n\n # Populate unspecified units:\n for column in set(self.data.columns.tolist()) - set(self.units.keys()):\n # For all columns not present in the units dictionary.\n self.units[column] = u.dimensionless_unscaled\n warnings.warn(f\"Unknown units for {column}.\", SunpyUserWarning)\n\n # Re-arrange so it's in the same order as the columns and removed unused.\n units = OrderedDict()\n for column in self.data.columns.tolist():\n units.update({column:self.units[column]})\n\n # Now use the amended units Ordered Dictionary\n self.units = units\n\n def _sanitize_metadata(self, **kwargs):\n \"\"\"\n Sanitises the TimeSeriesMetaData object used to store the metadata.\n Primarily this method will:\n\n Remove entries outside of the datas TimeRange or truncate TimeRanges\n if the metadata overflows past the data,\n Remove column references in the metadata that don't match to a column\n in the data.\n Remove metadata entries that have no columns matching the data.\n \"\"\"\n warnings.simplefilter('always', Warning)\n\n # Truncate the metadata\n self.meta._truncate(self.time_range)\n\n # Remove non-existant columns\n redundant_cols = list(set(self.meta.columns) - set(self.columns))\n self.meta._remove_columns(redundant_cols)\n\n# #### Export/Output Methods #### #\n\n def to_table(self, **kwargs):\n \"\"\"\n Return an Astropy Table of the give TimeSeries object.\n\n Returns\n -------\n newtable : `~astrpy.table`\n A new astropy table containing the data from the time series.\n The table will include units where relevant.\n \"\"\"\n # ToDo: Table.from_pandas(df) doesn't include the index column. Add request?\n # Get data columns\n table = Table.from_pandas(self.data)\n\n # Get index column and add to table.\n index_col = Column(self.data.index.values, name='date')\n table.add_column(index_col, index=0)\n\n # Add in units.\n for key in self.units:\n table[key].unit = self.units[key]\n\n # Output the table\n return table\n\n def to_dataframe(self, **kwargs):\n \"\"\"\n Return a Pandas DataFrame of the give TimeSeries object.\n\n Returns\n -------\n newdf : `~pandas.core.frame.DataFrame`\n A Pandas Dataframe containing the data.\n \"\"\"\n return self.data\n\n def to_array(self, columns=None):\n \"\"\"\n Return a numpy array of the give TimeSeries object.\n\n Parameters\n ----------\n columns: `list`, optional, default:None\n If None, return all columns minus the index, otherwise, returns\n specified columns.\n\n Returns\n -------\n values : `~numpy.ndarray`\n If the caller is heterogeneous and contains booleans or objects,\n the result will be of dtype=object. See Notes.\n \"\"\"\n if columns:\n return self.data.values[columns]\n else:\n return self.data.values\n\n def __eq__(self, other):\n \"\"\"\n Check two TimeSeries objects are the same, they have matching type, data,\n metadata and units entries.\n\n Parameters\n ----------\n other : `~sunpy.timeseries.GenericTimeSeries`\n The second TimeSeries object to compare with.\n\n Returns\n -------\n result : `bool`\n \"\"\"\n match = True\n if isinstance(other, type(self)):\n if ((not self.data.equals(other.data)) or\n (self.meta != other.meta) or\n (self.units != other.units)):\n match = False\n else:\n match = False\n return match\n\n def __ne__(self, other):\n \"\"\"\n Check two TimeSeries objects are not the same, they don't have matching\n type, data, metadata and/or units entries.\n\n Parameters\n ----------\n other : `~sunpy.timeseries.GenericTimeSeries`\n The second TimeSeries object to compare with.\n\n Returns\n -------\n result : `bool`\n \"\"\"\n return not self == other\n\n @classmethod\n def _parse_file(cls, filepath):\n \"\"\"Parses a file - to be implemented in any subclass that may use files\"\"\"\n return NotImplemented\n" ]
[ [ "matplotlib.pyplot.gca", "matplotlib.pyplot.figure" ] ]
nmstreethran/WindTurbineClassification
[ "b0ea6de909ccd5bb425cee291ca3c252c11df4eb" ]
[ "scripts/plot/powercurves-filter-T1.py" ]
[ "\"\"\"Plot power curves for turbine 1 with data filters\n\n\"\"\"\n\n# import libraries\nimport pandas as pd\nimport numpy as np\nimport itertools\nimport matplotlib.pyplot as plt\n\n# import data\ndf = pd.read_csv('data/SCADA_downtime_merged.csv', skip_blank_lines=True)\n\n# list of turbines to plot (just 1)\nlist1 = [1]\n# list of categories to plot\nlist2 = list(df['TurbineCategory_id'].unique())\n# remove NaN from list\nlist2 = [g for g in list2 if g >= 0]\n# round from float to integer\nlist2 = [a.astype(np.int64) for a in list2]\n# sort categories in ascending order\nlist2 = sorted(list2, key=int)\n# categories to remove from plot\nlist2 = [b for b in list2 if b not in (1, 12, 13, 14, 15, 17, 21, 22)]\nlist3 = list(itertools.product(list1, list2))\n\n# filter only data for turbine x and plot\nfor (x, y) in list3:\n df2x = df[(df['turbine_id'] == x)].copy()\n # sort values by timestamp in descending order\n df2x = df2x.sort_values(by='timestamp', ascending=False)\n\n # copying fault to new column (mins)\n # (fault when turbine category id is y)\n def f(c):\n if c['TurbineCategory_id'] == y:\n return 0\n else:\n return 1\n df2x['mins'] = df2x.apply(f, axis=1)\n # reset index\n df2x.reset_index(drop=True, inplace=True)\n # assigning value to first cell if it's not 0\n if df2x.loc[0, 'mins'] == 0:\n df2x.set_value(0, 'mins', 0)\n else:\n df2x.set_value(0, 'mins', 999999999)\n\n # using previous value's row to evaluate time\n for i, e in enumerate(df2x['mins']):\n if e == 1:\n df2x.at[i, 'mins'] = df2x.at[i-1, 'mins'] + 10\n\n # sort in ascending order\n df2x = df2x.sort_values(by='timestamp')\n # reset index\n df2x.reset_index(drop=True, inplace=True)\n\n # convert to hours and round to nearest hour\n df2x['hours'] = df2x['mins'].astype(np.int64)\n df2x['hours'] = df2x['hours']/60\n df2x['hours'] = round(df2x['hours']).astype(np.int64)\n\n # > 48 hours - label as normal (9999)\n def f1(c):\n if c['hours'] > 48:\n return 9999\n else:\n return c['hours']\n df2x['hours'] = df2x.apply(f1, axis=1)\n\n # filter out curtailment - curtailed when turbine is pitching\n # outside 0 deg <= normal <= 3.5 deg\n def f2(c):\n if 0 <= c['pitch'] <= 3.5 or c['hours'] != 9999 or (\n (c['pitch'] > 3.5 or c['pitch'] < 0) and\n (c['ap_av'] <= (.1 * df2x['ap_av'].max()) or\n c['ap_av'] >= (.9 * df2x['ap_av'].max()))):\n return 'normal'\n else:\n return 'curtailed'\n df2x['curtailment'] = df2x.apply(f2, axis=1)\n\n # filter unusual readings, i.e., for normal operation, power <= 0 in\n # operating wind speeds, power > 100 before cut-in, runtime < 600\n def f3(c):\n if c['hours'] == 9999 and (\n (3 < c['ws_av'] < 25 and (\n c['ap_av'] <= 0 or c['runtime'] < 600 or\n c['EnvironmentalCategory_id'] > 1 or\n c['GridCategory_id'] > 1 or\n c['InfrastructureCategory_id'] > 1 or\n c['AvailabilityCategory_id'] == 2 or\n 12 <= c['TurbineCategory_id'] <= 15 or\n 21 <= c['TurbineCategory_id'] <= 22)) or\n (c['ws_av'] < 3 and c['ap_av'] > 100)):\n return 'unusual'\n else:\n return 'normal'\n df2x['unusual'] = df2x.apply(f3, axis=1)\n\n # filter data for plots\n # normal w/ curtailment (all data)\n df3 = df2x[df2x.hours == 9999]\n # before fault\n df4 = df2x[df2x.hours != 9999]\n df4 = df4[df4.hours != 0]\n # fault\n df5 = df2x[df2x.hours == 0]\n # normal w/o curtailment\n df6 = df3[df3.curtailment == 'normal']\n # normal w/o curtailment and unusual readings\n df7 = df6[df6.unusual == 'normal']\n\n # get x and y coordinates\n # normal w/ curtailment\n x1 = df3['ws_av']\n y1 = df3['ap_av']\n # before fault\n x2 = df4['ws_av']\n y2 = df4['ap_av']\n # faulty\n x3 = df5['ws_av']\n y3 = df5['ap_av']\n # normal w/o curtailment\n x4 = df6['ws_av']\n y4 = df6['ap_av']\n # normal w/o curtailment and unusual readings\n x5 = df7['ws_av']\n y5 = df7['ap_av']\n\n fig = plt.figure(figsize=(18.5, 4.5), dpi=1500)\n\n ax1 = fig.add_subplot(131)\n ax1.scatter(x1, y1, c='#098A63', label='normal', marker='.')\n ax1.scatter(x2, y2, c='#3F2B78', label='before fault', marker='.')\n ax1.scatter(x3, y3, c='c', label='faulty', marker='.')\n ax1.legend()\n plt.xlabel('Wind speed (m/s)')\n plt.ylabel('Average active power (kW)')\n plt.title('all data points')\n\n ax2 = fig.add_subplot(132)\n ax2.scatter(x4, y4, c='#098A63', marker='.')\n ax2.scatter(x2, y2, c='#3F2B78', marker='.')\n ax2.scatter(x3, y3, c='c', marker='.')\n plt.xlabel('Wind speed (m/s)')\n plt.ylabel('Average active power (kW)')\n plt.title('w/o curtailment')\n\n ax3 = fig.add_subplot(133)\n ax3.scatter(x5, y5, c='#098A63', marker='.')\n ax3.scatter(x2, y2, c='#3F2B78', marker='.')\n ax3.scatter(x3, y3, c='c', marker='.')\n plt.xlabel('Wind speed (m/s)')\n plt.ylabel('Average active power (kW)')\n plt.title('w/o curtailment and anomalies')\n\n fig.suptitle(\n 'Power curves for turbine %s' % x + ' with turbine category %s' % y)\n plt.tight_layout()\n plt.subplots_adjust(top=0.88)\n plt.show()\n" ]
[ [ "matplotlib.pyplot.xlabel", "matplotlib.pyplot.title", "matplotlib.pyplot.figure", "matplotlib.pyplot.tight_layout", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.show", "pandas.read_csv", "matplotlib.pyplot.subplots_adjust" ] ]
valschmidt/vgrid
[ "7e52937d9959984b370f0bab885b8d27eb78e14a" ]
[ "VGRID/vgrid.py" ]
[ "#!/usr/bin/env python\n#\n# ---- VGRID ----\n# A Class for Incremental Gridding\n#\n# Val Schmidt\n# Center for Coastal and Ocean Mapping\n# Univeristy of New Hampshire\n# Copyright, 2018-2019\n# All Rights Reserved\n\n\nimport numpy as np\nfrom line_profiler import LineProfiler\nimport sys\nimport scipy.spatial as spatial\nfrom matplotlib import pyplot as plt\nimport numba\n\n\nclass vgrid():\n ''' A class for gridding of x,y,z data.\n \n See vgrid.add() for details on usage.\n '''\n\n def __init__(self, cs=1.0, cinf=1.0, type='mean'):\n\n self.cs = cs # cell size\n self.cinf = cinf # cell influence\n self.type = type # grid type\n\n self.xx = None # x (Easting) coordinates of grid\n self.yy = None # y (Nothing) coordinates of grid\n self.zw = None # Sum of the product of the gridded values and their weights for the grid cell.\n self.ww = None # Sum of weights\n self.nn = None # Number of points contributing to grid cell\n\n self.varw = None # Sum of the square of the difference of the gridded values and the estimated mean, times their weights.\n self.Z = None # Sequential estimator of depth for scalar (CUBE) or platlet methods.\n self.CZ = None\n \n ### Utility variables used internally. ###\n # New values to incorporate into grid.\n self._x = None\n self._y = None\n self._z = None\n self._w = None\n self._II = None # Indices of values to add for node under consideration.\n # (These are not used as class variables currently.)\n self._idx = None # row grid node indiex for node under consideration.\n self._jdx = None # column grid node indiex for node under consideation.\n self._I = None # table of index lists for data to add for each grid node\n\n def zz(self):\n ''' Calculate the z values for the grid.'''\n return self.zw / self.ww\n\n def mean_wholegrid(self):\n ''' Calculate mean values for the whole grid.'''\n # Fancy list comprehension to execute a double loop concisely.\n [self.mean(idx, jdx)\n for idx in range(self.yy.size)\n for jdx in range(self.xx.size)\n if self._I[idx][jdx] is not None]\n\n def median_wholegrid(self):\n ''' Calculate median values for the whole grid.'''\n # Fancy list comprehension to execute a double loop concisely.\n [self.median(idx, jdx)\n for idx in range(self.yy.size)\n for jdx in range(self.xx.size)\n if self._I[idx][jdx] is not None]\n\n def mean(self, idx, jdx):\n '''Mean gridding algorithm.\n\n vgrid implemnets incremental gridding where possible.\n To do this, the sum of the product of the weights and z values are\n retained in addition to the sum of the weights. Then method zz()\n calculates the quotient of the two to obtain the actual weighted\n mean z values. Note that when all weights are one, (or if w is set to\n 1 for shorthand), a standard mean is calculated.\n\n Variance is calcualted in a similar way. In this case the sum of\n w*(z_i - mu)^2 is calculated and stored for each grid node, where\n z_i is the value to be gridded and mu is the mean of the grid node\n calculated thus far. Then this sum is divided by the sum of the\n weights to get the final estimated variance. As the mean of the grid\n node approaches the true mean, this value should approach the true\n variance.\n '''\n\n self._II = self._I[idx][jdx]\n\n # Non-weighted gridding.\n if self._w.size == 1:\n self.zw[idx, jdx] = np.nansum(np.concatenate((self._z[self._II], [self.zw[idx, jdx]])))\n self.ww[idx, jdx] = self.nn[idx, jdx]\n self.varw[idx, jdx] = np.nansum(np.concatenate((np.power( (self._z[self._II] - self.zw[idx,jdx]/self.nn[idx,jdx]), 2),[self.varw[idx, jdx]])))\n else:\n # Weighted gridding. Sum of value times the weight divided by the \n # sum of the weights.\n # The strategy taken here is to retain the sum of the values times the weights, and also\n # the sum of the weights. Then when the weighted mean is requested the calling function \n # divides the these two values. This strategy allows incremental addition of data to the grid.\n #\n # The coding strategy below is to append the new points to the existing point in a list\n # and then call nansum to add them up. \n #\n # Q: Note: A dot-product might be quicker, but there is no dot-product that will produce a\n # non-nan result if one of the values is nan, which is desired here.\n self.zw[idx, jdx] = np.nansum(np.append(self.zw[idx, jdx], self._z[self._II] * self._w[self._II]))\n self.ww[idx, jdx] = np.nansum(np.append(self.ww[idx, jdx], self._w[self._II]))\n self.varw[idx, jdx] = np.nansum(np.append(np.power( (self._z[self._II] - self.zw[idx,jdx]/self.ww[idx,jdx]),2)\n , self.varw[idx, jdx] ))\n\n def var(self):\n ''' Calculate the variance'''\n return self.varw/self.ww\n\n def std(self):\n '''Calculate the standard deviation'''\n return np.sqrt(self.var())\n\n def meanwithoutlierrejection(self):\n ''' TO DO: Calculate the mean, rejecting values that exceed 3-sigma\n from existing estimate.'''\n pass\n\n def median(self, idx, jdx):\n ''' Calculate the median value in each grid cell.\n \n The method used here to provide a \"running median\" is for each add(),\n calculate the average of the existing value with the median of the\n new points. This method works reasonably well, but can produce\n inferior results if a single add() contains only outliers and their\n are insufficient additional adds to constrain it.'''\n self.zw[idx, jdx] = np.nanmean(\n np.append(self.zw[idx, jdx], np.nanmedian(self._z[self._II])))\n self.ww[idx, jdx] = 1\n self.varw[idx, jdx] = np.nansum(np.append(\n np.power((self._z[self._II] - self.zw[idx, jdx]/self.ww[idx, jdx]),\n 2),\n self.varw[idx, jdx]))\n pass\n\n def gridsizesanitycheck(self, M):\n '''Check to see if the grid size is going to be REALLY large. '''\n if M.__len__() > 1e4:\n return False\n else:\n return True\n \n def create_new_grid(self):\n ''' Create a new empty grid.'''\n \n self.xx = np.arange(min(self._x), max(self._x)+self.cs, self.cs)\n self.yy = np.arange(min(self._y), max(self._y)+self.cs, self.cs)\n\n if not (self.gridsizesanitycheck(self.xx) and\n self.gridsizesanitycheck(self.yy)):\n print('Grid size is too large.')\n return\n \n # Initialize grid.\n self.zw = np.empty((self.yy.size, self.xx.size))\n self.zw.fill(np.nan)\n self.nn = np.copy(self.zw)\n self.ww = np.copy(self.zw)\n self.varw = np.copy(self.zw)\n \n def expand_grid(self):\n minx = min(self._x)\n miny = min(self._y)\n maxx = max(self._x)\n maxy = max(self._y)\n\n if minx < self.xx[0]:\n dx = np.arange(minx, self.xx[0] - self.cs, self.cs)\n self.xx = np.concatenate((dx,self.xx))\n # Create new space\n tmp = np.empty((self.yy.size,dx.size))\n tmp.fill(np.nan)\n # Tack it on.\n self.zw = np.concatenate((np.copy(tmp), self.zw), axis=1)\n self.nn = np.concatenate((np.copy(tmp), self.nn), axis=1)\n self.ww = np.concatenate((np.copy(tmp), self.ww), axis=1)\n self.varw = np.concatenate((np.copy(tmp), self.varw), axis=1)\n\n # FIX: Support depth/platelet estimates here, tbd\n\n if maxx > self.xx[-1]:\n dx = np.arange(self.xx[-1]+self.cs,maxx,self.cs)\n self.xx = np.concatenate((self.xx,dx))\n # Create new space\n tmp = np.empty((self.yy.size,dx.size))\n tmp.fill(np.nan)\n # Tack it on.\n self.zw = np.concatenate((self.zw,np.copy(tmp)),axis=1)\n self.nn = np.concatenate((self.nn,np.copy(tmp)),axis=1)\n self.ww = np.concatenate((self.ww,np.copy(tmp)),axis=1)\n self.varw = np.concatenate((self.varw,np.copy(tmp)),axis=1)\n\n if miny < self.yy[0]:\n dy = np.arange(miny,self.yy[0]-self.cs,self.cs)\n self.yy = np.concatenate((dy,self.yy))\n tmp = np.empty((dy.size,self.xx.size))\n tmp.fill(np.nan)\n self.zw = np.concatenate((np.copy(tmp), self.zw),axis=0)\n self.nn = np.concatenate((np.copy(tmp), self.nn),axis=0)\n self.ww = np.concatenate((np.copy(tmp), self.ww),axis=0)\n self.varw = np.concatenate((np.copy(tmp), self.varw),axis=0)\n\n if maxy > self.yy[-1]:\n dy = np.arange(self.yy[-1] + self.cs,maxy, self.cs)\n self.yy = np.concatenate((self.yy, dy))\n tmp = np.empty((dy.size, self.xx.size))\n tmp.fill(np.nan)\n self.zw = np.concatenate((self.zw, np.copy(tmp)), axis=0)\n self.nn = np.concatenate((self.nn, np.copy(tmp)), axis=0)\n self.ww = np.concatenate((self.ww, np.copy(tmp)), axis=0)\n self.varw = np.concatenate((self.varw, np.copy(tmp)), axis=0)\n\n def add(self, x, y, z, w):\n ''' An incremental gridding function\n\n Arguments:\n x: x-coordinates\n y: y-coordiantes\n z: z-scalar values to grid\n w: w-weight applied to each point (size of x or 1 for no weighting)\n When 'type' = Nlowerthan or Ngreaterthan, w is the threshold value\n When 'type' = distance weighted mean, distance = R^w\n cs: grid cell size\n cinf: cell influence\n type: type of grid (see below)\n\n Output:\n g.xx: vector of grid cell x coordinates.\n g.yy: vector of grid cell y coordiantes.\n g.zz: 2D matrix of grided values times their weights.\n g.nn: 2D matrix containing the number of points in each grid cell.\n g.ww: sum of weights of items in the grid cell\n\n %\n % Grid types:\n % mean:\n % Average of the values. When w != 1, the mean is calculated by\n % multipying each value in the cell by its weight divided by the sum\n % of the weights in that cell.\n %\n % median:\n % Calculates the median value for each grid cell.\n %\n % mode:\n % Calculates the mode of the values for each grid cell.\n %\n % shoalest:\n % Calculates the minimum value for each grid cell.\n %\n % deepest:\n % Calculates the maximum value for each grid cell.\n %\n % stddev:\n % Calculates the standard deviation of the values in each grid cell.\n %\n % stderr:\n % Calculates the standard error of the values in each grid cell\n % (stddev/N, where stddev is the standard deviation and N is the number\n % of points falling in the cell)\n %\n % dwm:\n % Calculates the distance weighted mean where each value in the cell is\n % inversely weighted by the square if it's distance to the cell node.\n %\n % Nlowerthan:\n % Calculates the number of points in the grid cell lower than some value,\n % w.\n %\n % Ngreaterthan:\n % Calculates the number of points greater than some value w.\n %\n % To Do:\n % - Rewrite mean function as a matrix operation to simplify the propagation\n % of uncertainty calcualtion. Actually this might be make more general such\n % that your pass a list of values, their uncertainty and weighting factors\n % and get back a mean and propagated uncertainty. This would allow\n % relatively simple incorporation of things like range weighting, footprint\n % weighting, gaussian weighting, etc.\n % - Add uncertainty to z input and propagate these through the\n % calculations.\n % - Add uncertainty to x and y inputs and propagate these through the\n % calculations (more difficult)\n % Rewrite a C mex function.\n %\n % Val Schmidt\n % CCOM/JHC\n % 2018, 2019\n '''\n\n # Force everything to match.\n if np.isscalar(x) or np.isscalar(y) or np.isscalar(z):\n print('X, Y, or Z is scalar - must be numpy array.')\n sys.exit()\n\n self._x = x.ravel()\n self._y = y.ravel()\n self._z = z.ravel()\n if not np.isscalar(w):\n self._w = w.ravel()\n else:\n self._w = np.array(w)\n\n # Weight cannot be zero.\n if self._w.size != 1:\n if sum(self._w == 0):\n print(\"Found zero weights. Weights cannot be zero.\")\n print(\"Setting to 1e-20.\")\n self._w[self._w == 0] = 1e-20\n\n # Set up new grid, or extend the existing grid if necessary.\n if self.zw is None:\n self.create_new_grid()\n else:\n self.expand_grid()\n\n grows = self.yy.size\n gcols = self.xx.size\n\n doindices = 0\n\n #self.sort_data()\n self.sort_data_kdtree()\n \n # Peform the gridding calculations. \n if self.type == 'dwm':\n # Calculate distance between points and grid node for distance-weighted mean.\n # In the case, w is the exponent.\n #R = ((self.xx[jdx] - self._x(self.II))**2 +\n # (self.yy[jdx]-self._y[self.II])**2)**(self._w/2.0)\n print(\"Not yet supported.\")\n\n if self.type == 'mean':\n self.mean_wholegrid()\n\n if self.type == \"median\":\n self.median_wholegrid()\n\n def sort_data_kdtree(self):\n ''' A sorting of the data into grid cells using KDtrees.'''\n\n tree = spatial.cKDTree(list(zip(self._x.ravel(), self._y.ravel())), leafsize=1e7)\n xxx,yyy = np.meshgrid(self.xx,self.yy)\n indexes = tree.query_ball_point(np.vstack((xxx.ravel(), yyy.ravel())).T,\n r=self.cinf,\n p=2,\n n_jobs=-1).reshape(xxx.shape)\n self._I = indexes\n\n def sort_data(self):\n ''' Determine which data contributes to each grid node.\n The list of indices is populated in self._I[n][m], where n and m\n indicate the grid node.'''\n\n # Initilize the 2D list of index lists.\n self._I = [x[:] for x in\n [[None] * self.xx.size] * self.yy.size]\n\n cinf2 = self.cinf**2\n\n # Go through the rows of the grid..\n for idx in np.arange(0, self.yy.size, dtype='uint32'):\n '''\n We need to search through all the data efficiently to determine\n indices for points that will contribute to a grid node. Those that\n contribute are ones that fall within the \"cell influence\" (cinf).\n Thse are the ones that meet the criteria:\n\n sqrt( (x-xo).^2 + (y-yo).^2 ) < cinf\n\n Squaring both sides....\n\n (x-xo)^2 + (y-yo)^2 < cinf^2\n\n This will never be true when either term of the lhs is >= cinf^2.\n So we reduce the search by doing these piece-meal. '''\n\n # Here we find the y data values within cinf of the grid node\n ddy = (self._y - self.yy[idx])**2\n yidx = np.flatnonzero(ddy < cinf2)\n\n # If there are none, then don't bother with further calculations.\n if yidx.size == 0:\n continue\n\n # Then go through each cell of that row, and look for x - values\n # that also are in the cell. But first pre-calculate a vector of\n # terms that will be needed for every evaluation.\n xtest = cinf2 - ddy[yidx]\n for jdx in np.arange(0, self.xx.size, dtype='uint32'):\n xidx = np.flatnonzero((self._x[yidx] - self.xx[jdx])**2\n < xtest)\n # If there are none of these then there is nothing to do.\n if xidx.size == 0:\n continue\n\n # Retain the list of indices contributing to the node.\n self._I[idx][jdx] = yidx[xidx]\n\n # Keep running count of the number of values.\n self.nn[idx,jdx] = np.nansum(np.append(self.nn[idx, jdx], \n xidx.size))\n \n\n def numba_add(self, x, y, z, w, chnksize=100000):\n \"\"\"\n An attempt at running self.add with numba. Key here is to chunk the points so that the numba compiled function\n _numba_add runs multiple times, where the first run is slow as it compiles. _numba_add is not within the class,\n as classes aren't supported. There is this new thing numba.jitclass, but it appears to still be experimental.\n\n On my test dataset containing about 4.5 million soundings, I got the following results:\n - existing add = 55.8 seconds\n - numba_add (chunksize, time) = (100, 55.2), (1000, 21.2), (10000, 17.9), (100000, 16.6), (150000, 16.2),\n (200000, 15.7), (1000000, 18.0)\n \"\"\"\n\n # Force everything to match.\n if np.isscalar(x) or np.isscalar(y) or np.isscalar(z):\n print('X, Y, or Z is scalar - must be numpy array.')\n sys.exit()\n\n self._x = x.ravel()\n self._y = y.ravel()\n self._z = z.ravel()\n if not np.isscalar(w):\n self._w = w.ravel()\n else:\n self._w = np.array(w)\n\n # Weight cannot be zero.\n if self._w.size != 1:\n if sum(self._w == 0):\n print(\"Found zero weights. Weights cannot be zero.\")\n print(\"Setting to 1e-20.\")\n self._w[self._w == 0] = 1e-20\n\n # Set up new grid, or extend the existing grid if necessary.\n if self.zw is None:\n self.create_new_grid()\n else:\n self.expand_grid()\n\n ptlen = len(self._x)\n chnks = [[i * chnksize, min((i + 1) * chnksize, ptlen)] for i in range(int(ptlen / chnksize) + 1)]\n\n for chnk in chnks:\n chnk_idx = slice(chnk[0], chnk[1])\n if self._w.size != 1:\n chunk_w = self._w[chnk_idx]\n else:\n chunk_w = self._w\n self.zw, self.ww, self.varw, self.nn = _numba_add(self.xx, self.yy, self.nn, self.cinf, self._x[chnk_idx],\n self._y[chnk_idx], self._z[chnk_idx], chunk_w,\n self.type, self.zw, self.varw, self.ww)\n\n def rotate(self):\n pass\n\n def pcolor(self,*kwargs):\n plt.pcolor(self.xx,self.yy,self.zz(),*kwargs)\n #plt.colorbar()\n plt.ion()\n plt.show()\n #plt.draw()\n plt.pause(0.001)\n\n\n@numba.jit(nopython=True, nogil=True, parallel=True)\ndef _numba_add(xx, yy, nn, cinf, x, y, z, w, typ, zw, varw, ww):\n \"\"\"\n numba jit compiled add function\n\n - Numba compiles this function, ensure that no classes/functions are within unless they are also numba-ized\n - Numba.prange forces numba to parallelize, generates exception when parallelism fails, helping you figure out\n what needs to be fixed. Otherwise parallel=True can fail silently\n - nopython=True, this function operates entirely outside of the python interpreter\n - nogil=True, will not use the python GIL (this might be redundant with nopython)\n\n \"\"\"\n grows = yy.size\n gcols = xx.size\n doindices = 0\n cinf2 = cinf ** 2\n\n # Go through the rows of the grid..\n for idx in numba.prange(grows):\n # Here we find the y data values within cinf of the grid node\n ddy = (y - yy[idx]) ** 2\n yidx = np.flatnonzero(ddy < cinf2)\n\n # If there are none, then don't bother with further calculations.\n if yidx.size == 0:\n continue\n\n # Then go through each cell of that row, and look for x - values that also are in the cell.\n # But first pre-calculate a vector of terms that will be needed for every evaluation.\n xtest = cinf2 - ddy[yidx]\n for jdx in numba.prange(gcols):\n xidx = np.flatnonzero((x[yidx] - xx[jdx]) ** 2 < xtest)\n\n # If there are none of these then there is nothing to do to the grid node.\n if xidx.size == 0:\n continue\n\n # Set the indices of the values to be add to this grid node.\n II = yidx[xidx]\n\n if typ == 'dwm':\n # Calculate distance between points and grid node for distance-weighted mean.\n # In the case, w is the exponent.\n if w.size != 1:\n R = ((xx[jdx] - x[II]) ** 2 + (yy[idx] - y[II]) ** 2) ** (w[II] / 2.0)\n else:\n R = ((xx[jdx] - x[II]) ** 2 + (yy[idx] - y[II]) ** 2) ** (w / 2.0)\n\n if not doindices:\n nn[idx, jdx] = np.nansum(np.array([nn[idx, jdx], xidx.size]))\n else:\n nn[idx, jdx] = idx * (gcols - 1) + jdx\n\n if w.size != 1:\n chunk_w = w[II]\n else:\n chunk_w = w\n if typ == 'mean':\n zw[idx, jdx], ww[idx, jdx], varw[idx, jdx] = _numba_mean_by_cell(zw[idx, jdx], ww[idx, jdx],\n varw[idx, jdx], nn[idx, jdx], z[II],\n chunk_w)\n elif typ == \"median\":\n zw[idx, jdx], ww[idx, jdx], varw[idx, jdx] = _numba_median_by_cell(zw[idx, jdx], ww[idx, jdx],\n varw[idx, jdx], z[II])\n return zw, ww, varw, nn\n\n\n@numba.jit(nopython=True)\ndef _numba_mean_by_cell(zw_cell, ww_cell, varw_cell, nn_cell, z, w):\n # Non-weighted gridding.\n if w.size == 1:\n zw = np.nansum(np.concatenate((z, np.array([zw_cell]))))\n ww = nn_cell\n varw = np.nansum(np.concatenate((((z - zw / nn_cell) ** 2), np.array([varw_cell]))))\n else:\n # Weighted gridding. Sum of value times the weight divided by the\n # sum of the weights.\n # The strategy taken here is to retain the sum of the values times the weights, and also\n # the sum of the weights. Then when the weighted mean is requested the calling function\n # divides the these two values. This strategy allows incremental addition of data to the grid.\n #\n # The coding strategy below is to append the new points to the existing point in a list\n # and then call nansum to add them up.\n #\n # Q: Note: A dot-product might be quicker, but there is no dot-product that will produce a\n # non-nan result if one of the values is nan, which is desired here.\n zw = np.nansum(np.append(zw_cell, z * w))\n ww = np.nansum(np.append(ww_cell, w))\n varw = np.nansum(np.append(((z - zw_cell / ww_cell) ** 2), varw_cell))\n return zw, ww, varw\n\n\n@numba.jit(nopython=True)\ndef _numba_median_by_cell(zw_cell, ww_cell, varw_cell, z):\n ''' Calculate the median value in each grid cell.\n\n The method used here to provide a \"running median\" is for each add(),\n calculate the average of the existing value with the median of the\n new points. This method works reasonably well, but can produce\n inferior results if a single add() contains only outliers and their\n are insufficient additional adds to constrain it.'''\n zw = np.nanmean(np.append(zw_cell, np.nanmedian(z)))\n ww = 1\n varw = np.nansum(np.append((z - zw_cell / ww_cell ** 2), varw_cell))\n return zw, ww, varw\n\n\nif __name__=='__main__':\n profileON = True\n\n def gridTest(N = 2, ProfileON = False):\n ''' Method to test gridding.'''\n\n print(\"N=%d\" % N)\n # Generate data. \n x = np.random.random((N,1))*100\n y = np.random.random((N,1))*100\n z = np.exp( np.sqrt((x-50.)**2 + (y-50.)**2)/50)\n\n # Generate grid.\n G = vgrid(1,1,'mean')\n if profileON:\n print(\"Profiling on.\")\n lp = LineProfiler()\n GAddProfiled = lp(G.add)\n lp.add_function(G.mean)\n GAddProfiled(x,y,z,1)\n return (G,lp)\n else:\n G.add(x,y,z,1)\n return G\n \n ## Gridding test script:\n\n for N in [1000, 5000, 10000, 20000, 50000, 100000, 1000000]:\n if profileON:\n GG,LP = gridTest(N,True)\n LP.print_stats()\n else:\n GG = gridTest(N,False) \n\n # Plot test.\n GG.pcolor()\n\n\n\n" ]
[ [ "numpy.concatenate", "matplotlib.pyplot.ion", "numpy.array", "numpy.empty", "numpy.copy", "numpy.random.random", "numpy.arange", "matplotlib.pyplot.pause", "numpy.isscalar", "numpy.append", "numpy.power", "matplotlib.pyplot.show", "numpy.sqrt", "numpy.meshgrid", "numpy.nanmedian", "numpy.flatnonzero" ] ]
gaochangfeng/pykaldi2
[ "5e988e5968aa9a5867f8179e6c53ea715ac46bdc" ]
[ "bin/train_se.py" ]
[ "\"\"\" \nCopyright (c) 2019 Microsoft Corporation. All rights reserved. \n \nMIT License \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 yaml\nimport argparse\nimport numpy as np\nimport os\nimport sys\nimport time\nimport json\nimport pickle\n\nimport torch as th\nimport torch.nn as nn\nimport horovod.torch as hvd\n\n#import pykaldi related modules\nimport kaldi.fstext as kaldi_fst\nimport kaldi.hmm as kaldi_hmm\nimport kaldi.matrix as kaldi_matrix\nimport kaldi.lat as kaldi_lat\nimport kaldi.decoder as kaldi_decoder\nimport kaldi.util as kaldi_util\nfrom kaldi.asr import MappedLatticeFasterRecognizer\nfrom kaldi.decoder import LatticeFasterDecoderOptions\n\nfrom data import SpeechDataset, SeqDataloader\nfrom models import LSTMStack, NnetAM\nfrom ops import ops\nfrom utils import utils\n\ndef main():\n parser = argparse.ArgumentParser() \n parser.add_argument(\"-config\") \n parser.add_argument(\"-data\", help=\"data yaml file\")\n parser.add_argument(\"-data_path\", default='', type=str, help=\"path of data files\") \n parser.add_argument(\"-seed_model\", help=\"the seed nerual network model\") \n parser.add_argument(\"-exp_dir\", help=\"the directory to save the outputs\")\n parser.add_argument(\"-transform\", help=\"feature transformation matrix or mvn statistics\") \n parser.add_argument(\"-criterion\", type=str, choices=[\"mmi\", \"mpfe\", \"smbr\"], help=\"set the sequence training crtierion\") \n parser.add_argument(\"-trans_model\", help=\"the HMM transistion model, used for lattice generation\") \n parser.add_argument(\"-prior_path\", help=\"the prior for decoder, usually named as final.occs in kaldi setup\")\n parser.add_argument(\"-den_dir\", help=\"the decoding graph directory to find HCLG and words.txt files\")\n parser.add_argument(\"-lr\", type=float, help=\"set the learning rate\")\n parser.add_argument(\"-ce_ratio\", default=0.1, type=float, help=\"the ratio for ce regularization\")\n parser.add_argument(\"-momentum\", default=0, type=float, help=\"set the momentum\") \n parser.add_argument(\"-batch_size\", default=32, type=int, help=\"Override the batch size in the config\") \n parser.add_argument(\"-data_loader_threads\", default=0, type=int, help=\"number of workers for data loading\")\n parser.add_argument(\"-max_grad_norm\", default=5, type=float, help=\"max_grad_norm for gradient clipping\") \n parser.add_argument(\"-sweep_size\", default=100, type=float, help=\"process n hours of data per sweep (default:60)\")\n parser.add_argument(\"-num_epochs\", default=1, type=int, help=\"number of training epochs (default:1)\") \n parser.add_argument('-print_freq', default=10, type=int, metavar='N', help='print frequency (default: 10)')\n parser.add_argument('-save_freq', default=1000, type=int, metavar='N', help='save model frequency (default: 1000)')\n\n args = parser.parse_args()\n\n with open(args.config) as f:\n config = yaml.safe_load(f)\n\n config['data_path'] = args.data_path\n\n config[\"sweep_size\"] = args.sweep_size\n\n print(\"pytorch version:{}\".format(th.__version__))\n\n with open(args.data) as f:\n data = yaml.safe_load(f)\n config[\"source_paths\"] = [j for i, j in data['clean_source'].items()]\n\n print(\"Experiment starts with config {}\".format(json.dumps(config, sort_keys=True, indent=4)))\n\n # Initialize Horovod\n hvd.init()\n\n th.cuda.set_device(hvd.local_rank())\n\n print(\"Run experiments with world size {}\".format(hvd.size()))\n\n dataset = SpeechDataset(config)\n transform=None\n if args.transform is not None and os.path.isfile(args.transform):\n with open(args.transform, 'rb') as f:\n transform = pickle.load(f)\n dataset.transform = transform\n\n train_dataloader = SeqDataloader(dataset,\n batch_size=args.batch_size,\n num_workers = args.data_loader_threads,\n distributed=True,\n test_only=False)\n\n print(\"Data loader set up successfully!\")\n print(\"Number of minibatches: {}\".format(len(train_dataloader)))\n\n if not os.path.isdir(args.exp_dir):\n os.makedirs(args.exp_dir)\n\n # ceate model\n model_config = config[\"model_config\"]\n lstm = LSTMStack(model_config[\"feat_dim\"], model_config[\"hidden_size\"], model_config[\"num_layers\"], model_config[\"dropout\"], True)\n model = NnetAM(lstm, model_config[\"hidden_size\"]*2, model_config[\"label_size\"])\n\n model.cuda()\n\n # setup the optimizer\n optimizer = th.optim.SGD(model.parameters(), lr=args.lr, momentum=args.momentum)\n\n # Broadcast parameters and opterimizer state from rank 0 to all other processes.\n hvd.broadcast_parameters(model.state_dict(), root_rank=0)\n hvd.broadcast_optimizer_state(optimizer, root_rank=0)\n\n # Add Horovod Distributed Optimizer\n optimizer = hvd.DistributedOptimizer(optimizer, named_parameters=model.named_parameters())\n\n if os.path.isfile(args.seed_model):\n checkpoint = th.load(args.seed_model) \n state_dict = checkpoint['model'] \n model.load_state_dict(state_dict) \n print(\"=> loaded checkpoint '{}' \".format(args.seed_model)) \n else:\n sys.stderr.write('ERROR: The model file %s does not exist!\\n'%(model_file))\n sys.exit(0) \n\n HCLG = args.den_dir + \"/HCLG.fst\"\n words_txt = args.den_dir + \"/words.txt\"\n silence_phones = args.den_dir + \"/phones/silence.csl\"\n\n if not os.path.isfile(HCLG):\n sys.stderr.write('ERROR: The HCLG file %s does not exist!\\n'%(HCLG))\n sys.exit(0)\n \n if not os.path.isfile(words_txt):\n sys.stderr.write('ERROR: The words.txt file %s does not exist!\\n'%(words_txt))\n sys.exit(0)\n \n if not os.path.isfile(silence_phones):\n sys.stderr.write('ERROR: The silence phone file %s does not exist!\\n'%(silence_phones))\n sys.exit(0)\n with open(silence_phones) as f:\n silence_ids = [int(i) for i in f.readline().strip().split(':')]\n f.close()\n\n if os.path.isfile(args.trans_model):\n trans_model = kaldi_hmm.TransitionModel()\n with kaldi_util.io.xopen(args.trans_model) as ki:\n trans_model.read(ki.stream(), ki.binary)\n else:\n sys.stderr.write('ERROR: The trans_model %s does not exist!\\n'%(args.trans_model))\n sys.exit(0)\n \n # now we can setup the decoder\n decoder_opts = LatticeFasterDecoderOptions()\n decoder_opts.beam = config[\"decoder_config\"][\"beam\"]\n decoder_opts.lattice_beam = config[\"decoder_config\"][\"lattice_beam\"]\n decoder_opts.max_active = config[\"decoder_config\"][\"max_active\"]\n acoustic_scale = config[\"decoder_config\"][\"acoustic_scale\"]\n decoder_opts.determinize_lattice = False #To produce raw state-level lattice instead of compact lattice\n asr_decoder = MappedLatticeFasterRecognizer.from_files(\n args.trans_model, HCLG, words_txt,\n acoustic_scale=acoustic_scale, decoder_opts=decoder_opts)\n\n prior = kaldi_util.io.read_matrix(args.prior_path).numpy()\n log_prior = th.tensor(np.log(prior[0]/np.sum(prior[0])), dtype=th.float)\n\n model.train()\n for epoch in range(args.num_epochs): \n\n run_train_epoch(model, optimizer,\n log_prior.cuda(), \n train_dataloader, \n epoch, \n asr_decoder, \n trans_model,\n silence_ids,\n args)\n\n # save model\n if hvd.rank() == 0:\n checkpoint={}\n checkpoint['model']=model.state_dict()\n checkpoint['optimizer']=optimizer.state_dict()\n checkpoint['epoch']=epoch\n output_file=args.exp_dir + '/model.se.'+ str(epoch) +'.tar'\n th.save(checkpoint, output_file)\n\ndef run_train_epoch(model, optimizer, log_prior, dataloader, epoch, asr_decoder, trans_model, silence_ids, args):\n batch_time = utils.AverageMeter('Time', ':6.3f')\n losses = utils.AverageMeter('Loss', ':.4e')\n grad_norm = utils.AverageMeter('grad_norm', ':.4e')\n progress = utils.ProgressMeter(len(dataloader), batch_time, losses, grad_norm, \n prefix=\"Epoch: [{}]\".format(epoch))\n\n ce_criterion = nn.CrossEntropyLoss(ignore_index=-100, reduction='sum')\n \n if args.criterion == \"mmi\":\n se_criterion = ops.MMIFunction.apply\n else:\n se_criterion = ops.sMBRFunction.apply\n\n end = time.time()\n for i, batch in enumerate(dataloader, 0):\n feat = batch[\"x\"] \n label = batch[\"y\"] #pdf-ids for ce loss\n num_frs = batch[\"num_frs\"] \n utt_ids = batch[\"utt_ids\"] \n aux = batch[\"aux\"] #trans_ids for se loss\n\n x = feat.to(th.float32) \n y = label.long() \n x = x.cuda() \n y = y.cuda()\n \n prediction = model(x) \n ce_loss = ce_criterion(prediction.view(-1, prediction.shape[2]), y.view(-1))\n \n se_loss = 0.0 \n for j in range(len(num_frs)): \n log_like_j=prediction[j,:,:] \n log_like_j= log_like_j[:num_frs[j],:] \n log_like_j = log_like_j - log_prior\n #trans_id = label[j, :num_frs[j], 0].tolist()\n trans_id = th.from_numpy(aux[j][0][0].astype(int)).tolist()\n # print(len(trans_id), num_frs[j])\n \n if args.criterion == \"mmi\":\n se_loss += se_criterion(log_like_j, asr_decoder, trans_model, trans_id)\n else:\n se_loss += se_criterion(log_like_j, asr_decoder, trans_model, trans_id, args.criterion, silence_ids)\n\n loss = se_loss.cuda() + args.ce_ratio * ce_loss\n optimizer.zero_grad()\n loss.backward()\n\n # Gradient Clipping (th 5.0)\n norm = nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm)\n optimizer.step()\n\n grad_norm.update(norm)\n\n # update loss\n tot_frs = np.array(num_frs).sum()\n losses.update(loss.item()/tot_frs)\n\n # measure elapsed time\n batch_time.update(time.time() - end)\n\n # save model\n if hvd.rank() == 0 and i % args.save_freq == 0:\n checkpoint={}\n checkpoint['model']=model.state_dict()\n checkpoint['optimizer']=optimizer.state_dict()\n output_file=args.exp_dir + '/model.se.'+ str(i) +'.tar'\n th.save(checkpoint, output_file)\n\n if hvd.rank() == 0 and i % args.print_freq == 0:\n progress.print(i)\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "numpy.array", "numpy.sum", "torch.save", "torch.load", "torch.nn.CrossEntropyLoss" ] ]
Soula09/fuelcell
[ "cf2a726c78d2b87f8b212e4c0f791d1d5e12009a" ]
[ "fuelcell/model.py" ]
[ "import numpy as np\nimport pandas as pd\nimport os\nimport re\nimport fuelcell as fc\n\nclass Datum():\n\tdef __init__(self, name, data):\n\t\t# data\n\t\tself.name = name\n\t\tself.raw_data = data\n\t\tself.label = name\n\t\tself.processed_data = None\n\t\tself.expt_type = None\n\t\t\n\t\t# processed values\n\t\tself.current_data = None\n\t\tself.potential_data = None\n\t\tself.overpotential_data = None\n\t\tself.logcurrent_data = None\n\t\tself.realcurrent_data = None\n\t\tself.imagcurrent_data = None\n\t\tself.error_data = None\n\n\t\t# misc parameters\n\t\tself.area = 1\n\t\tself.refelec = 0\n\t\tself.thermo_potential = 0\n\n\t\t# tafel\n\t\tself.tafel_slope = None\n\t\tself.exchg_curr = None\n\t\tself.tafel_rsq = None\n\n\t\t# eis\n\t\tself.semicircle_params = None\n\t\tself.linearfit_params = None\n\t\tself.hfr = None\n\t\tself.hfr_linear = None\n\t\tself.lfr = None\n\t\tself.eis_current = None\n\n\t\t# visualization\n\t\tself.line = None\n\t\tself.errcaps = None\n\t\tself.errbars = None\n\n\t### accessors ###\n\tdef get_name(self):\n\t\treturn self.name\n\n\tdef get_raw_data(self):\n\t\tif self.raw_data is not None:\n\t\t\treturn self.raw_data.copy()\n\t\treturn None\n\t\n\tdef get_label(self):\n\t\treturn self.label\n\n\tdef get_processed_data(self):\n\t\tif self.processed_data is not None:\n\t\t\treturn self.processed_data.copy()\n\t\treturn None\n\n\tdef get_expt_type(self):\n\t\treturn self.expt_type\n\n\tdef get_current_data(self):\n\t\treturn self.current_data\n\n\tdef get_potential_data(self):\n\t\treturn self.potential_data\n\n\tdef get_overpotential_data(self):\n\t\treturn self.overpotential_data\n\n\tdef get_logcurrent_data(self):\n\t\treturn self.logcurrent_data\n\n\tdef get_realcurrent_data(self):\n\t\treturn self.realcurrent_data\n\n\tdef get_imagcurrent_data(self):\n\t\treturn self.imagcurrent_data\n\n\tdef get_error_data(self):\n\t\treturn self.error_data\n\t\n\tdef get_area(self):\n\t\treturn self.area\n\n\tdef get_refelec(self):\n\t\treturn self.refelec\n\n\tdef get_thermo_potential(self):\n\t\treturn self.thermo_potential\n\t\n\tdef get_tafel_slope(self):\n\t\treturn self.tafel_slope\n\n\tdef get_exchg_curr(self):\n\t\treturn self.exchg_curr\n\n\tdef get_tafel_rsq(self):\n\t\treturn self.tafel_rsq\n\n\tdef get_semicircle_params(self):\n\t\tpopt = self.semicircle_params\n\t\tr, h, k = popt[0], popt[1], popt[2]\n\t\treturn r, h, k\n\n\tdef get_linearfit_params(self):\n\t\tpopt = self.linearfit_params\n\t\tm, b = popt[0], popt[1]\n\t\treturn m, b\n\n\tdef get_hfr(self):\n\t\treturn self.hfr\n\t\n\tdef get_hfr_linear(self):\n\t\treturn self.hfr_linear\n\n\tdef get_lfr(self):\n\t\treturn self.lfr\n\n\tdef get_eis_current(self):\n\t\treturn self.eis_current\n\n\tdef get_line(self):\n\t\treturn self.line\n\n\tdef get_errcaps(self):\n\t\treturn self.errcaps\n\n\tdef get_errbars(self):\n\t\treturn self.errbars\n\n\t### modifiers ###\n\tdef set_label(self, new_label):\n\t\tself.label = new_label\n\n\tdef set_processed_data(self, new_data):\n\t\tself.processed_data = new_data\n\n\tdef set_expt_type(self, new_type):\n\t\tself.expt_type = new_type.lower()\n\n\tdef set_current_data(self, new_vals):\n\t\tself.current_data = np.asarray(new_vals)\n\n\tdef set_potential_data(self, new_vals):\n\t\tself.potential_data = np.asarray(new_vals)\n\n\tdef set_overpotential_data(self, new_vals):\n\t\tself.overpotential_data = np.asarray(new_vals)\n\n\tdef set_logcurrent_data(self, new_vals):\n\t\tself.logcurrent_data = np.asarray(new_vals)\n\n\tdef set_realcurrent_data(self, new_vals):\n\t\tself.realcurrent_data = np.asarray(new_vals)\n\n\tdef set_imagcurrent_data(self, new_vals):\n\t\tself.imagcurrent_data = np.asarray(new_vals)\n\n\tdef set_error_data(self, new_vals):\n\t\tself.error_data = np.asarray(new_vals)\n\t\n\tdef set_area(self, new_val):\n\t\tself.area = new_val\n\n\tdef set_refelec(self, new_val):\n\t\tself.refelec = new_val\n\n\tdef set_thermo_potential(self, new_val):\n\t\tself.thermo_potential = new_val\n\t\n\tdef set_tafel_slope(self, new_val):\n\t\tself.tafel_slope = new_val\n\n\tdef set_exchg_curr(self, new_val):\n\t\tself.exchg_curr = new_val\n\n\tdef set_tafel_rsq(self, new_val):\n\t\tself.tafel_rsq = new_val\n\n\tdef set_semicircle_params(self, new_params):\n\t\tself.semicircle_params = new_params\n\n\tdef set_linearfit_params(self, new_params):\n\t\tself.linearfit_params = new_params\n\n\tdef set_hfr(self, new_val):\n\t\tself.hfr = new_val\n\t\n\tdef set_hfr_linear(self, new_val):\n\t\tself.hfr_linear = new_val\n\n\tdef set_lfr(self, new_val):\n\t\tself.lfr = new_val\n\n\tdef set_eis_current(self, new_val):\n\t\tself.eis_current = new_val\n\n\tdef set_line(self, new_val):\n\t\tself.line = new_val\n\n\tdef set_errcaps(self, new_val):\n\t\tself.errcaps = new_val\n\n\tdef set_errbars(self, new_val):\n\t\tself.errbars = new_val" ]
[ [ "numpy.asarray" ] ]
ferdinand-popp/BIDD
[ "ada79c6033687662ddecdc96740e747f3eb8d7cf" ]
[ "app.py" ]
[ "import streamlit as st\nimport pandas as pd\nfrom PIL import Image\nimport subprocess\nimport os\nimport base64\nimport pickle\n\n# Molecular descriptor calculator\ndef desc_calc():\n # Performs the descriptor calculation\n bashCommand = \"java -Xms2G -Xmx2G -Djava.awt.headless=true -jar ./PaDEL-Descriptor/PaDEL-Descriptor.jar -removesalt -standardizenitro -fingerprints -descriptortypes ./PaDEL-Descriptor/PubchemFingerprinter.xml -dir ./ -file descriptors_output.csv\"\n process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)\n output, error = process.communicate()\n os.remove('molecule.smi')\n\n# File download\ndef filedownload(df):\n csv = df.to_csv(index=False)\n b64 = base64.b64encode(csv.encode()).decode() # strings <-> bytes conversions\n href = f'<a href=\"data:file/csv;base64,{b64}\" download=\"prediction.csv\">Download Predictions</a>'\n return href\n\n# Model building\ndef build_model(input_data):\n # Reads in saved regression model\n load_model = pickle.load(open('acetylcholinesterase_model.pkl', 'rb'))\n # Apply model to make predictions\n prediction = load_model.predict(input_data)\n st.header('**Prediction output**')\n prediction_output = pd.Series(prediction, name='pIC50')\n molecule_name = pd.Series(load_data[1], name='molecule_name')\n df = pd.concat([molecule_name, prediction_output], axis=1)\n st.write(df)\n st.markdown(filedownload(df), unsafe_allow_html=True)\n\n\n# Page title\nst.markdown(\"\"\"\n# Bioactivity Prediction App\nThis app allows you to predict the bioactivity of molecules as SMILES towards inhibting the target enzyme Acetylcholinesterase with a QSAR model.\n\n**Credits**\n- App built in `Python` + `Streamlit` \n- Descriptor calculated using [PaDEL-Descriptor](http://www.yapcwsoft.com/dd/padeldescriptor/) [[Read the Paper]](https://doi.org/10.1002/jcc.21707).\n---\n\"\"\")\n\n# Sidebar\nwith st.sidebar.header('1. Upload your CSV data'):\n uploaded_file = st.sidebar.file_uploader(\"Upload your input file\", type=['txt'])\n st.sidebar.markdown(\"\"\"\n[Example input file](https://raw.githubusercontent.com/dataprofessor/bioactivity-prediction-app/main/example_acetylcholinesterase.txt)\n\"\"\")\n\nif st.sidebar.button('Predict'):\n load_data = pd.read_table(uploaded_file, sep=' ', header=None)\n load_data.to_csv('molecule.smi', sep = '\\t', header = False, index = False)\n\n st.header('**Original input data**')\n st.write(load_data)\n\n with st.spinner(\"Calculating descriptors...\"):\n desc_calc()\n\n # Read in calculated descriptors and display the dataframe\n st.header('**Calculated molecular descriptors**')\n desc = pd.read_csv('descriptors_output.csv')\n st.write(desc)\n st.write(desc.shape)\n\n # Read descriptor list used in previously built model\n st.header('**Subset of descriptors from previously built models**')\n Xlist = list(pd.read_csv('descriptor_list.csv').columns)\n desc_subset = desc[Xlist]\n st.write(desc_subset)\n st.write(desc_subset.shape)\n\n # Apply trained model to make prediction on query compounds\n build_model(desc_subset)\nelse:\n st.info('Upload input data in the sidebar to start!')\n" ]
[ [ "pandas.concat", "pandas.read_table", "pandas.read_csv", "pandas.Series" ] ]
nilsvu/spectre
[ "1455b9a8d7e92db8ad600c66f54795c29c3052ee", "1455b9a8d7e92db8ad600c66f54795c29c3052ee", "9350d61830b360e2d5b273fdd176dcc841dbefb0" ]
[ "tests/Unit/Evolution/Systems/CurvedScalarWave/BoundaryConditions/ConstraintPreservingSphericalRadiation.py", "tests/Unit/Evolution/Systems/NewtonianEuler/BoundaryConditions/Outflow.py", "tests/Unit/Evolution/Systems/GrMhd/ValenciaDivClean/BoundaryCorrections/Rusanov.py" ]
[ "# Distributed under the MIT License.\n# See LICENSE.txt for details.\n\nimport numpy as np\nfrom Evolution.Systems.CurvedScalarWave.Characteristics import (\n char_speed_vpsi, char_speed_vzero, char_speed_vplus, char_speed_vminus)\n\n\ndef error(face_mesh_velocity, normal_covector, normal_vector, psi, phi,\n inertial_coords, gamma1, gamma2, lapse, shift, dt_psi, dt_pi, dt_phi,\n d_psi, d_phi):\n return None\n\n\ndef dt_psi_constraint_preserving_spherical_radiation(\n face_mesh_velocity, normal_covector, normal_vector, psi, phi,\n inertial_coords, gamma1, gamma2, lapse, shift, dt_psi, dt_pi, dt_phi,\n d_psi, d_phi):\n char_speed_psi = char_speed_vpsi(gamma1, lapse, shift, normal_covector)\n\n if face_mesh_velocity is not None:\n char_speed_psi -= np.dot(normal_covector, face_mesh_velocity)\n\n return np.dot(normal_vector, d_psi - phi) * min(0., char_speed_psi)\n\n\ndef dt_phi_constraint_preserving_spherical_radiation(\n face_mesh_velocity, normal_covector, normal_vector, psi, phi,\n inertial_coords, gamma1, gamma2, lapse, shift, dt_psi, dt_pi, dt_phi,\n d_psi, d_phi):\n char_speed_zero = char_speed_vzero(gamma1, lapse, shift, normal_covector)\n if face_mesh_velocity is not None:\n char_speed_zero -= np.dot(normal_covector, face_mesh_velocity)\n return 0.5 * np.einsum(\"ij,j\", d_phi.T - d_phi, normal_vector) * min(\n 0, char_speed_zero)\n\n\ndef dt_pi_constraint_preserving_spherical_radiation(\n face_mesh_velocity, normal_covector, normal_vector, psi, phi,\n inertial_coords, gamma1, gamma2, lapse, shift, dt_psi, dt_pi, dt_phi,\n d_psi, d_phi):\n dt_psi_correction = dt_psi_constraint_preserving_spherical_radiation(\n face_mesh_velocity, normal_covector, normal_vector, psi, phi,\n inertial_coords, gamma1, gamma2, lapse, shift, dt_psi, dt_pi, dt_phi,\n d_psi, d_phi)\n inv_radius = 1. / np.linalg.norm(inertial_coords)\n bc_dt_pi = (2. * inv_radius**2 * psi + 4. * inv_radius * dt_psi +\n 4. * inv_radius * np.dot(normal_vector, phi) +\n 2. * np.dot(normal_vector, dt_phi) + np.dot(shift, dt_phi) +\n np.einsum(\"i,j,ij\", normal_vector, normal_vector, d_phi))\n bc_dt_pi /= lapse\n return bc_dt_pi - dt_pi + gamma2 * dt_psi_correction\n", "# Distributed under the MIT License.\n# See LICENSE.txt for details.\n\nimport numpy as np\n\n\ndef error(face_mesh_velocity, normal_covector, int_mass_density, int_velocity,\n int_specific_internal_energy, use_polytropic_eos):\n\n if use_polytropic_eos:\n polytropic_constant = 1.4\n polytropic_exponent = 5.0 / 3.0\n sound_speed = np.sqrt(polytropic_constant * polytropic_exponent *\n pow(int_mass_density, polytropic_exponent - 1.0))\n else:\n adiabatic_index = 1.3\n chi = int_specific_internal_energy * (adiabatic_index - 1.0)\n kappa_times_p_over_rho_squared = ((adiabatic_index - 1.0)**2 *\n int_specific_internal_energy)\n sound_speed = np.sqrt(chi + kappa_times_p_over_rho_squared)\n\n normal_dot_velocity = np.einsum(\"i,i\", int_velocity, normal_covector)\n\n if face_mesh_velocity is None:\n min_char_speed = normal_dot_velocity - sound_speed\n else:\n normal_dot_mesh_velocity = np.einsum(\"i,i\", face_mesh_velocity,\n normal_covector)\n\n min_char_speed = normal_dot_velocity \\\n - normal_dot_mesh_velocity - sound_speed\n\n if min_char_speed < 0.0:\n return \"Outflow boundary condition violated\"\n\n return None\n", "# Distributed under the MIT License.\n# See LICENSE.txt for details.\n\nimport numpy as np\n\n\ndef dg_package_data_tilde_d(tilde_d, tilde_tau, tilde_s, tilde_b, tilde_phi,\n flux_tilde_d, flux_tilde_tau, flux_tilde_s,\n flux_tilde_b, flux_tilde_phi, lapse, shift,\n normal_covector, normal_vector, mesh_velocity,\n normal_dot_mesh_velocity):\n return tilde_d\n\n\ndef dg_package_data_tilde_tau(tilde_d, tilde_tau, tilde_s, tilde_b, tilde_phi,\n flux_tilde_d, flux_tilde_tau, flux_tilde_s,\n flux_tilde_b, flux_tilde_phi, lapse, shift,\n normal_covector, normal_vector, mesh_velocity,\n normal_dot_mesh_velocity):\n return tilde_tau\n\n\ndef dg_package_data_tilde_s(tilde_d, tilde_tau, tilde_s, tilde_b, tilde_phi,\n flux_tilde_d, flux_tilde_tau, flux_tilde_s,\n flux_tilde_b, flux_tilde_phi, lapse, shift,\n normal_covector, normal_vector, mesh_velocity,\n normal_dot_mesh_velocity):\n return tilde_s\n\n\ndef dg_package_data_tilde_b(tilde_d, tilde_tau, tilde_s, tilde_b, tilde_phi,\n flux_tilde_d, flux_tilde_tau, flux_tilde_s,\n flux_tilde_b, flux_tilde_phi, lapse, shift,\n normal_covector, normal_vector, mesh_velocity,\n normal_dot_mesh_velocity):\n return tilde_b\n\n\ndef dg_package_data_tilde_phi(tilde_d, tilde_tau, tilde_s, tilde_b, tilde_phi,\n flux_tilde_d, flux_tilde_tau, flux_tilde_s,\n flux_tilde_b, flux_tilde_phi, lapse, shift,\n normal_covector, normal_vector, mesh_velocity,\n normal_dot_mesh_velocity):\n return tilde_phi\n\n\ndef dg_package_data_normal_dot_flux_tilde_d(\n tilde_d, tilde_tau, tilde_s, tilde_b, tilde_phi, flux_tilde_d,\n flux_tilde_tau, flux_tilde_s, flux_tilde_b, flux_tilde_phi, lapse, shift,\n normal_covector, normal_vector, mesh_velocity, normal_dot_mesh_velocity):\n return np.dot(flux_tilde_d, normal_covector)\n\n\ndef dg_package_data_normal_dot_flux_tilde_tau(\n tilde_d, tilde_tau, tilde_s, tilde_b, tilde_phi, flux_tilde_d,\n flux_tilde_tau, flux_tilde_s, flux_tilde_b, flux_tilde_phi, lapse, shift,\n normal_covector, normal_vector, mesh_velocity, normal_dot_mesh_velocity):\n return np.dot(flux_tilde_tau, normal_covector)\n\n\ndef dg_package_data_normal_dot_flux_tilde_s(\n tilde_d, tilde_tau, tilde_s, tilde_b, tilde_phi, flux_tilde_d,\n flux_tilde_tau, flux_tilde_s, flux_tilde_b, flux_tilde_phi, lapse, shift,\n normal_covector, normal_vector, mesh_velocity, normal_dot_mesh_velocity):\n return np.einsum(\"ij,i->j\", flux_tilde_s, normal_covector)\n\n\ndef dg_package_data_normal_dot_flux_tilde_b(\n tilde_d, tilde_tau, tilde_s, tilde_b, tilde_phi, flux_tilde_d,\n flux_tilde_tau, flux_tilde_s, flux_tilde_b, flux_tilde_phi, lapse, shift,\n normal_covector, normal_vector, mesh_velocity, normal_dot_mesh_velocity):\n return np.einsum(\"ij,i->j\", flux_tilde_b, normal_covector)\n\n\ndef dg_package_data_normal_dot_flux_tilde_phi(\n tilde_d, tilde_tau, tilde_s, tilde_b, tilde_phi, flux_tilde_d,\n flux_tilde_tau, flux_tilde_s, flux_tilde_b, flux_tilde_phi, lapse, shift,\n normal_covector, normal_vector, mesh_velocity, normal_dot_mesh_velocity):\n return np.dot(flux_tilde_phi, normal_covector)\n\n\ndef dg_package_data_abs_char_speed(tilde_d, tilde_tau, tilde_s, tilde_b,\n tilde_phi, flux_tilde_d, flux_tilde_tau,\n flux_tilde_s, flux_tilde_b, flux_tilde_phi,\n lapse, shift, normal_covector,\n normal_vector, mesh_velocity,\n normal_dot_mesh_velocity):\n if normal_dot_mesh_velocity is None:\n return np.maximum(np.abs(lapse - np.dot(shift, normal_covector)),\n np.abs(-lapse - np.dot(shift, normal_covector)))\n else:\n return np.maximum(\n np.abs(lapse - np.dot(shift, normal_covector) -\n normal_dot_mesh_velocity),\n np.abs(-lapse - np.dot(shift, normal_covector) -\n normal_dot_mesh_velocity))\n\n\ndef dg_boundary_terms_tilde_d(\n interior_tilde_d, interior_tilde_tau, interior_tilde_s, interior_tilde_b,\n interior_tilde_phi, interior_normal_dot_flux_tilde_d,\n interior_normal_dot_flux_tilde_tau, interior_normal_dot_flux_tilde_s,\n interior_normal_dot_flux_tilde_b, interior_normal_dot_flux_tilde_phi,\n interior_abs_char_speed, exterior_tilde_d, exterior_tilde_tau,\n exterior_tilde_s, exterior_tilde_b, exterior_tilde_phi,\n exterior_normal_dot_flux_tilde_d, exterior_normal_dot_flux_tilde_tau,\n exterior_normal_dot_flux_tilde_s, exterior_normal_dot_flux_tilde_b,\n exterior_normal_dot_flux_tilde_phi, exterior_abs_char_speed,\n use_strong_form):\n if use_strong_form:\n return -0.5 * (interior_normal_dot_flux_tilde_d +\n exterior_normal_dot_flux_tilde_d) - 0.5 * np.maximum(\n interior_abs_char_speed, exterior_abs_char_speed\n ) * (exterior_tilde_d - interior_tilde_d)\n else:\n return 0.5 * (interior_normal_dot_flux_tilde_d -\n exterior_normal_dot_flux_tilde_d) - 0.5 * np.maximum(\n interior_abs_char_speed, exterior_abs_char_speed) * (\n exterior_tilde_d - interior_tilde_d)\n\n\ndef dg_boundary_terms_tilde_tau(\n interior_tilde_d, interior_tilde_tau, interior_tilde_s, interior_tilde_b,\n interior_tilde_phi, interior_normal_dot_flux_tilde_d,\n interior_normal_dot_flux_tilde_tau, interior_normal_dot_flux_tilde_s,\n interior_normal_dot_flux_tilde_b, interior_normal_dot_flux_tilde_phi,\n interior_abs_char_speed, exterior_tilde_d, exterior_tilde_tau,\n exterior_tilde_s, exterior_tilde_b, exterior_tilde_phi,\n exterior_normal_dot_flux_tilde_d, exterior_normal_dot_flux_tilde_tau,\n exterior_normal_dot_flux_tilde_s, exterior_normal_dot_flux_tilde_b,\n exterior_normal_dot_flux_tilde_phi, exterior_abs_char_speed,\n use_strong_form):\n if use_strong_form:\n return -0.5 * (interior_normal_dot_flux_tilde_tau +\n exterior_normal_dot_flux_tilde_tau) - 0.5 * np.maximum(\n interior_abs_char_speed, exterior_abs_char_speed\n ) * (exterior_tilde_tau - interior_tilde_tau)\n else:\n return 0.5 * (interior_normal_dot_flux_tilde_tau -\n exterior_normal_dot_flux_tilde_tau) - 0.5 * np.maximum(\n interior_abs_char_speed, exterior_abs_char_speed) * (\n exterior_tilde_tau - interior_tilde_tau)\n\n\ndef dg_boundary_terms_tilde_s(\n interior_tilde_d, interior_tilde_tau, interior_tilde_s, interior_tilde_b,\n interior_tilde_phi, interior_normal_dot_flux_tilde_d,\n interior_normal_dot_flux_tilde_tau, interior_normal_dot_flux_tilde_s,\n interior_normal_dot_flux_tilde_b, interior_normal_dot_flux_tilde_phi,\n interior_abs_char_speed, exterior_tilde_d, exterior_tilde_tau,\n exterior_tilde_s, exterior_tilde_b, exterior_tilde_phi,\n exterior_normal_dot_flux_tilde_d, exterior_normal_dot_flux_tilde_tau,\n exterior_normal_dot_flux_tilde_s, exterior_normal_dot_flux_tilde_b,\n exterior_normal_dot_flux_tilde_phi, exterior_abs_char_speed,\n use_strong_form):\n if use_strong_form:\n return -0.5 * (interior_normal_dot_flux_tilde_s +\n exterior_normal_dot_flux_tilde_s) - 0.5 * np.maximum(\n interior_abs_char_speed, exterior_abs_char_speed\n ) * (exterior_tilde_s - interior_tilde_s)\n else:\n return 0.5 * (interior_normal_dot_flux_tilde_s -\n exterior_normal_dot_flux_tilde_s) - 0.5 * np.maximum(\n interior_abs_char_speed, exterior_abs_char_speed) * (\n exterior_tilde_s - interior_tilde_s)\n\n\ndef dg_boundary_terms_tilde_b(\n interior_tilde_d, interior_tilde_tau, interior_tilde_s, interior_tilde_b,\n interior_tilde_phi, interior_normal_dot_flux_tilde_d,\n interior_normal_dot_flux_tilde_tau, interior_normal_dot_flux_tilde_s,\n interior_normal_dot_flux_tilde_b, interior_normal_dot_flux_tilde_phi,\n interior_abs_char_speed, exterior_tilde_d, exterior_tilde_tau,\n exterior_tilde_s, exterior_tilde_b, exterior_tilde_phi,\n exterior_normal_dot_flux_tilde_d, exterior_normal_dot_flux_tilde_tau,\n exterior_normal_dot_flux_tilde_s, exterior_normal_dot_flux_tilde_b,\n exterior_normal_dot_flux_tilde_phi, exterior_abs_char_speed,\n use_strong_form):\n if use_strong_form:\n return -0.5 * (interior_normal_dot_flux_tilde_b +\n exterior_normal_dot_flux_tilde_b) - 0.5 * np.maximum(\n interior_abs_char_speed, exterior_abs_char_speed\n ) * (exterior_tilde_b - interior_tilde_b)\n else:\n return 0.5 * (interior_normal_dot_flux_tilde_b -\n exterior_normal_dot_flux_tilde_b) - 0.5 * np.maximum(\n interior_abs_char_speed, exterior_abs_char_speed) * (\n exterior_tilde_b - interior_tilde_b)\n\n\ndef dg_boundary_terms_tilde_phi(\n interior_tilde_d, interior_tilde_tau, interior_tilde_s, interior_tilde_b,\n interior_tilde_phi, interior_normal_dot_flux_tilde_d,\n interior_normal_dot_flux_tilde_tau, interior_normal_dot_flux_tilde_s,\n interior_normal_dot_flux_tilde_b, interior_normal_dot_flux_tilde_phi,\n interior_abs_char_speed, exterior_tilde_d, exterior_tilde_tau,\n exterior_tilde_s, exterior_tilde_b, exterior_tilde_phi,\n exterior_normal_dot_flux_tilde_d, exterior_normal_dot_flux_tilde_tau,\n exterior_normal_dot_flux_tilde_s, exterior_normal_dot_flux_tilde_b,\n exterior_normal_dot_flux_tilde_phi, exterior_abs_char_speed,\n use_strong_form):\n if use_strong_form:\n return -0.5 * (interior_normal_dot_flux_tilde_phi +\n exterior_normal_dot_flux_tilde_phi) - 0.5 * np.maximum(\n interior_abs_char_speed, exterior_abs_char_speed\n ) * (exterior_tilde_phi - interior_tilde_phi)\n else:\n return 0.5 * (interior_normal_dot_flux_tilde_phi -\n exterior_normal_dot_flux_tilde_phi) - 0.5 * np.maximum(\n interior_abs_char_speed, exterior_abs_char_speed) * (\n exterior_tilde_phi - interior_tilde_phi)\n" ]
[ [ "numpy.dot", "numpy.einsum", "numpy.linalg.norm" ], [ "numpy.einsum", "numpy.sqrt" ], [ "numpy.dot", "numpy.einsum", "numpy.maximum" ] ]
fcakyon/tensorflow-yolov4
[ "3d31292cefba198b1528a90b3f435204efe7be73" ]
[ "py_src/yolov4/tf/dataset/keras_sequence.py" ]
[ "\"\"\"\nMIT License\n\nCopyright (c) 2019 YangYun\nCopyright (c) 2020 Việt Hùng\nCopyright (c) 2020-2021 Hyeonki Hong <hhk7734@gmail.com>\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\"\"\"\nfrom typing import List\n\nimport cv2\nimport numpy as np\nfrom tensorflow.keras.utils import Sequence\n\nfrom .augmentation import mosaic\nfrom ...common import (\n media,\n convert_dataset_to_ground_truth as _convert_dataset_to_ground_truth,\n)\nfrom ...common.config import YOLOConfig\nfrom ...common.parser import parse_dataset\n\n_AUGMETATION_CACHE_SIZE = 50\n\n\nclass YOLODataset(Sequence):\n def __init__(\n self,\n config: YOLOConfig,\n dataset_list: str,\n dataset_type: str = \"converted_coco\",\n image_path_prefix: str = \"\",\n training: bool = True,\n ):\n self.dataset = parse_dataset(\n dataset_list=dataset_list,\n dataset_type=dataset_type,\n image_path_prefix=image_path_prefix,\n )\n self._metayolos = []\n if config.layer_count[\"yolo\"] > 0:\n for i in range(config.layer_count[\"yolo\"]):\n self._metayolos.append(config.find_metalayer(\"yolo\", i))\n elif config.layer_count[\"yolo_tpu\"] > 0:\n for i in range(config.layer_count[\"yolo_tpu\"]):\n self._metayolos.append(config.find_metalayer(\"yolo_tpu\", i))\n else:\n raise RuntimeError(\n \"YOLODataset: model does not have a yolo or yolo_tpu layer\"\n )\n\n self._metanet = config.net\n self._metayolos_np = np.zeros(\n (len(self._metayolos), 7 + len(self._metayolos[-1].mask)),\n dtype=np.float32,\n )\n for i, metayolo in enumerate(self._metayolos):\n self._metayolos_np[i, 0] = metayolo.height\n self._metayolos_np[i, 1] = metayolo.width\n self._metayolos_np[i, 2] = metayolo.channels\n self._metayolos_np[i, 3] = metayolo.classes\n self._metayolos_np[i, 4] = metayolo.label_smooth_eps\n self._metayolos_np[i, 5] = metayolo.max\n self._metayolos_np[i, 6] = metayolo.iou_thresh\n for j, mask in enumerate(metayolo.mask):\n self._metayolos_np[i, 7 + j] = mask\n\n self._anchors_np = np.zeros(\n len(self._metayolos[-1].anchors) * 2, dtype=np.float32\n )\n for i, anchor in enumerate(self._metayolos[-1].anchors):\n self._anchors_np[2 * i] = anchor[0] / self._metanet.width\n self._anchors_np[2 * i + 1] = anchor[1] / self._metanet.height\n\n # Data augmentation ####################################################\n\n self._augmentation: List[str] = []\n if config.net.mosaic:\n self._augmentation.append(\"mosaic\")\n\n if training and len(self._augmentation) > 0:\n self._augmentation_batch = int(config.net.batch * 0.3)\n self._training = True\n else:\n self._augmentation_batch = 0\n self._training = False\n\n self._augmentation_cache = [\n self._get_dataset(i) for i in range(_AUGMETATION_CACHE_SIZE)\n ]\n self._augmentation_cache_index = 0\n\n def _convert_dataset_to_ground_truth(self, dataset_bboxes):\n \"\"\"\n @param `dataset_bboxes`: [[b_x, b_y, b_w, b_h, class_id], ...]\n\n @return `groud_truth_one`:\n [Dim(yolo.h, yolo.w, yolo.c + len(mask))] * len(yolo)\n \"\"\"\n return _convert_dataset_to_ground_truth(\n dataset_bboxes, self._metayolos_np, self._anchors_np\n )\n\n def _convert_dataset_to_image_and_bboxes(self, dataset):\n \"\"\"\n @param dataset: [image_path, [[x, y, w, h, class_id], ...]]\n\n @return image, bboxes\n image: 0.0 ~ 1.0, Dim(1, height, width, channels)\n \"\"\"\n # pylint: disable=bare-except\n try:\n image = cv2.imread(dataset[0])\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n except:\n return None, None\n\n resized_image, resized_bboxes = media.resize_image(\n image,\n target_shape=self._metanet.input_shape,\n ground_truth=dataset[1],\n )\n resized_image = np.expand_dims(resized_image / 255.0, axis=0)\n\n return resized_image, resized_bboxes\n\n def _get_dataset(self, index: int):\n offset = 0\n for offset in range(5):\n image, bboxes = self._convert_dataset_to_image_and_bboxes(\n self.dataset[(index + offset) % len(self.dataset)]\n )\n if image is None:\n offset += 1\n else:\n return image, bboxes\n\n raise FileNotFoundError(\"Failed to find images\")\n\n def __getitem__(self, index):\n \"\"\"\n @return\n `images`: Dim(batch, height, width, channels)\n `groud_truth_one`:\n [Dim(batch, yolo.h, yolo.w, yolo.c + len(mask))] * len(yolo)\n \"\"\"\n\n batch_x = []\n # [[gt_one, gt_one, ...],\n # [gt_one, gt_one, ...], ...]\n batch_y = [[] for _ in range(len(self._metayolos))]\n\n start_index = index * self._metanet.batch\n\n for i in range(self._metanet.batch - self._augmentation_batch):\n image, bboxes = self._get_dataset(start_index + i)\n self._augmentation_cache[self._augmentation_cache_index] = (\n image,\n bboxes,\n )\n self._augmentation_cache_index = (\n self._augmentation_cache_index + 1\n ) % _AUGMETATION_CACHE_SIZE\n\n batch_x.append(image)\n ground_truth = self._convert_dataset_to_ground_truth(bboxes)\n for j in range(len(self._metayolos)):\n batch_y[j].append(ground_truth[j])\n\n for i in range(self._augmentation_batch):\n augmentation = self._augmentation[\n np.random.randint(0, len(self._augmentation))\n ]\n\n image = None\n bboxes = None\n if augmentation == \"mosaic\":\n image, bboxes = mosaic(\n *[\n self._augmentation_cache[\n np.random.randint(\n 0,\n _AUGMETATION_CACHE_SIZE,\n )\n ]\n for _ in range(4)\n ]\n )\n\n batch_x.append(image)\n ground_truth = self._convert_dataset_to_ground_truth(bboxes)\n for j in range(len(self._metayolos)):\n batch_y[j].append(ground_truth[j])\n\n return np.concatenate(batch_x, axis=0), [\n np.stack(y, axis=0) for y in batch_y\n ]\n\n def __len__(self):\n return len(self.dataset) // (\n self._metanet.batch - self._augmentation_batch\n )\n" ]
[ [ "numpy.concatenate", "numpy.stack", "numpy.random.randint", "numpy.expand_dims" ] ]
johnjasa/WISDEM
[ "a4571e71cb5b9869c81790f8abb1bb7fba8fdb02", "a4571e71cb5b9869c81790f8abb1bb7fba8fdb02" ]
[ "wisdem/test/test_drivetrainse/test_gearbox.py", "wisdem/drivetrainse/layout.py" ]
[ "import unittest\n\nimport numpy as np\nimport numpy.testing as npt\nimport wisdem.drivetrainse.gearbox as gb\n\n\nclass TestGearbox(unittest.TestCase):\n def setUp(self):\n self.inputs = {}\n self.outputs = {}\n self.discrete_inputs = {}\n self.discrete_outputs = {}\n\n # 5MW inputs\n self.discrete_inputs[\"gear_configuration\"] = \"eep\"\n self.discrete_inputs[\"shaft_factor\"] = \"normal\"\n self.discrete_inputs[\"planet_numbers\"] = [3, 3, 0]\n self.inputs[\"gear_ratio\"] = 97.0\n self.inputs[\"rotor_diameter\"] = 126.0\n self.inputs[\"rated_torque\"] = 3946e3\n self.inputs[\"machine_rating\"] = 5e3\n\n self.myobj = gb.Gearbox(direct_drive=False)\n\n def testDirectDrive(self):\n self.myobj = gb.Gearbox(direct_drive=True)\n self.myobj.compute(self.inputs, self.outputs, self.discrete_inputs, self.discrete_outputs)\n\n npt.assert_equal(self.outputs[\"stage_ratios\"], 0.0)\n self.assertEqual(self.outputs[\"gearbox_mass\"], 0.0)\n npt.assert_equal(self.outputs[\"gearbox_I\"], 0.0)\n self.assertEqual(self.outputs[\"L_gearbox\"], 0.0)\n self.assertEqual(self.outputs[\"D_gearbox\"], 0.0)\n\n def testEEP(self):\n self.myobj.compute(self.inputs, self.outputs, self.discrete_inputs, self.discrete_outputs)\n\n print(\"eep\", self.outputs[\"stage_ratios\"], self.outputs[\"gearbox_mass\"])\n self.assertAlmostEqual(np.prod(self.outputs[\"stage_ratios\"]), self.inputs[\"gear_ratio\"], 1)\n # self.assertEqual(self.outputs['gearbox_mass'], 0.0)\n npt.assert_equal(\n self.outputs[\"gearbox_I\"][0], 0.5 * self.outputs[\"gearbox_mass\"] * 0.25 * self.outputs[\"D_gearbox\"] ** 2\n )\n npt.assert_almost_equal(\n self.outputs[\"gearbox_I\"][1:],\n self.outputs[\"gearbox_mass\"]\n * (0.75 * self.outputs[\"D_gearbox\"] ** 2 + self.outputs[\"L_gearbox\"] ** 2)\n / 12.0,\n )\n self.assertEqual(self.outputs[\"L_gearbox\"], 0.012 * 126.0)\n self.assertEqual(self.outputs[\"D_gearbox\"], 0.75 * 0.015 * 126.0)\n\n def testEEP3(self):\n self.discrete_inputs[\"gear_configuration\"] = \"eep_3\"\n self.myobj.compute(self.inputs, self.outputs, self.discrete_inputs, self.discrete_outputs)\n\n print(\"eep3\", self.outputs[\"stage_ratios\"], self.outputs[\"gearbox_mass\"])\n self.assertAlmostEqual(np.prod(self.outputs[\"stage_ratios\"]), self.inputs[\"gear_ratio\"], 1)\n self.assertEqual(self.outputs[\"stage_ratios\"][-1], 3.0)\n # self.assertEqual(self.outputs['gearbox_mass'], 0.0)\n npt.assert_equal(\n self.outputs[\"gearbox_I\"][0], 0.5 * self.outputs[\"gearbox_mass\"] * 0.25 * self.outputs[\"D_gearbox\"] ** 2\n )\n npt.assert_almost_equal(\n self.outputs[\"gearbox_I\"][1:],\n self.outputs[\"gearbox_mass\"]\n * (0.75 * self.outputs[\"D_gearbox\"] ** 2 + self.outputs[\"L_gearbox\"] ** 2)\n / 12.0,\n )\n self.assertEqual(self.outputs[\"L_gearbox\"], 0.012 * 126.0)\n self.assertEqual(self.outputs[\"D_gearbox\"], 0.75 * 0.015 * 126.0)\n\n def testEEP2(self):\n self.discrete_inputs[\"gear_configuration\"] = \"eep_2\"\n self.myobj.compute(self.inputs, self.outputs, self.discrete_inputs, self.discrete_outputs)\n\n print(\"eep2\", self.outputs[\"stage_ratios\"], self.outputs[\"gearbox_mass\"])\n self.assertAlmostEqual(np.prod(self.outputs[\"stage_ratios\"]), self.inputs[\"gear_ratio\"], 1)\n self.assertEqual(self.outputs[\"stage_ratios\"][-1], 2.0)\n # self.assertEqual(self.outputs['gearbox_mass'], 0.0)\n npt.assert_equal(\n self.outputs[\"gearbox_I\"][0], 0.5 * self.outputs[\"gearbox_mass\"] * 0.25 * self.outputs[\"D_gearbox\"] ** 2\n )\n npt.assert_almost_equal(\n self.outputs[\"gearbox_I\"][1:],\n self.outputs[\"gearbox_mass\"]\n * (0.75 * self.outputs[\"D_gearbox\"] ** 2 + self.outputs[\"L_gearbox\"] ** 2)\n / 12.0,\n )\n self.assertEqual(self.outputs[\"L_gearbox\"], 0.012 * 126.0)\n self.assertEqual(self.outputs[\"D_gearbox\"], 0.75 * 0.015 * 126.0)\n\n def testEEP_planet4_1(self):\n self.discrete_inputs[\"gear_configuration\"] = \"eep\"\n self.discrete_inputs[\"planet_numbers\"] = [4, 3, 0]\n self.myobj.compute(self.inputs, self.outputs, self.discrete_inputs, self.discrete_outputs)\n\n print(\"eep_4-1\", self.outputs[\"stage_ratios\"], self.outputs[\"gearbox_mass\"])\n self.assertAlmostEqual(np.prod(self.outputs[\"stage_ratios\"]), self.inputs[\"gear_ratio\"], 1)\n # self.assertEqual(self.outputs['gearbox_mass'], 0.0)\n npt.assert_equal(\n self.outputs[\"gearbox_I\"][0], 0.5 * self.outputs[\"gearbox_mass\"] * 0.25 * self.outputs[\"D_gearbox\"] ** 2\n )\n npt.assert_almost_equal(\n self.outputs[\"gearbox_I\"][1:],\n self.outputs[\"gearbox_mass\"]\n * (0.75 * self.outputs[\"D_gearbox\"] ** 2 + self.outputs[\"L_gearbox\"] ** 2)\n / 12.0,\n )\n self.assertEqual(self.outputs[\"L_gearbox\"], 0.012 * 126.0)\n self.assertEqual(self.outputs[\"D_gearbox\"], 0.75 * 0.015 * 126.0)\n\n def testEEP_planet4_2(self):\n self.discrete_inputs[\"gear_configuration\"] = \"eep\"\n self.discrete_inputs[\"planet_numbers\"] = [3, 4, 0]\n self.myobj.compute(self.inputs, self.outputs, self.discrete_inputs, self.discrete_outputs)\n\n print(\"eep_4-2\", self.outputs[\"stage_ratios\"], self.outputs[\"gearbox_mass\"])\n self.assertAlmostEqual(np.prod(self.outputs[\"stage_ratios\"]), self.inputs[\"gear_ratio\"], 1)\n # self.assertEqual(self.outputs['gearbox_mass'], 0.0)\n npt.assert_equal(\n self.outputs[\"gearbox_I\"][0], 0.5 * self.outputs[\"gearbox_mass\"] * 0.25 * self.outputs[\"D_gearbox\"] ** 2\n )\n npt.assert_almost_equal(\n self.outputs[\"gearbox_I\"][1:],\n self.outputs[\"gearbox_mass\"]\n * (0.75 * self.outputs[\"D_gearbox\"] ** 2 + self.outputs[\"L_gearbox\"] ** 2)\n / 12.0,\n )\n self.assertEqual(self.outputs[\"L_gearbox\"], 0.012 * 126.0)\n self.assertEqual(self.outputs[\"D_gearbox\"], 0.75 * 0.015 * 126.0)\n\n def testEPP(self):\n self.discrete_inputs[\"gear_configuration\"] = \"epp\"\n self.myobj.compute(self.inputs, self.outputs, self.discrete_inputs, self.discrete_outputs)\n\n print(\"epp\", self.outputs[\"stage_ratios\"], self.outputs[\"gearbox_mass\"])\n self.assertAlmostEqual(np.prod(self.outputs[\"stage_ratios\"]), self.inputs[\"gear_ratio\"], 1)\n # self.assertEqual(self.outputs['gearbox_mass'], 0.0)\n npt.assert_equal(\n self.outputs[\"gearbox_I\"][0], 0.5 * self.outputs[\"gearbox_mass\"] * 0.25 * self.outputs[\"D_gearbox\"] ** 2\n )\n npt.assert_almost_equal(\n self.outputs[\"gearbox_I\"][1:],\n self.outputs[\"gearbox_mass\"]\n * (0.75 * self.outputs[\"D_gearbox\"] ** 2 + self.outputs[\"L_gearbox\"] ** 2)\n / 12.0,\n )\n self.assertEqual(self.outputs[\"L_gearbox\"], 0.012 * 126.0)\n self.assertEqual(self.outputs[\"D_gearbox\"], 0.75 * 0.015 * 126.0)\n\n def testLargeMachine(self):\n self.inputs[\"gear_ratio\"] = 200.0\n self.inputs[\"rotor_diameter\"] = 200.0\n self.inputs[\"rotor_torque\"] = 10e3\n self.myobj.compute(self.inputs, self.outputs, self.discrete_inputs, self.discrete_outputs)\n\n print(\"large\", self.outputs[\"stage_ratios\"], self.outputs[\"gearbox_mass\"])\n self.assertAlmostEqual(np.prod(self.outputs[\"stage_ratios\"]), self.inputs[\"gear_ratio\"], 1)\n # self.assertEqual(self.outputs['gearbox_mass'], 0.0)\n npt.assert_equal(\n self.outputs[\"gearbox_I\"][0], 0.5 * self.outputs[\"gearbox_mass\"] * 0.25 * self.outputs[\"D_gearbox\"] ** 2\n )\n npt.assert_almost_equal(\n self.outputs[\"gearbox_I\"][1:],\n self.outputs[\"gearbox_mass\"]\n * (0.75 * self.outputs[\"D_gearbox\"] ** 2 + self.outputs[\"L_gearbox\"] ** 2)\n / 12.0,\n )\n self.assertEqual(self.outputs[\"L_gearbox\"], 0.012 * 200.0)\n self.assertEqual(self.outputs[\"D_gearbox\"], 0.75 * 0.015 * 200.0)\n\n\ndef suite():\n suite = unittest.TestSuite()\n suite.addTest(unittest.makeSuite(TestGearbox))\n return suite\n\n\nif __name__ == \"__main__\":\n result = unittest.TextTestRunner().run(suite())\n\n if result.wasSuccessful():\n exit(0)\n else:\n exit(1)\n", "#!/usr/bin/env python\n# encoding: utf-8\n\nimport numpy as np\nimport openmdao.api as om\nimport wisdem.commonse.utilities as util\nfrom scipy.special import ellipeinc\nfrom wisdem.commonse.cross_sections import IBeam\n\n\ndef rod_prop(s, Di, ti, rho):\n L = s.max() - s.min()\n\n def equal_pts(xi):\n if len(xi) < len(s) and len(xi) == 2:\n x = np.interp((s - s.min()) / L, [0, 1], xi)\n elif len(xi) == len(s):\n x = xi\n else:\n raise ValueError(\"Unknown grid of input\", str(xi))\n return x\n\n D = equal_pts(Di)\n t = equal_pts(ti)\n y = 0.25 * rho * np.pi * (D ** 2 - (D - 2 * t) ** 2)\n m = np.trapz(y, s)\n cm = np.trapz(y * s, s) / m\n Dm = D.mean()\n tm = t.mean()\n I = np.array(\n [\n 0.5 * 0.25 * (Dm ** 2 + (Dm - 2 * tm) ** 2),\n (1.0 / 12.0) * (3 * 0.25 * (Dm ** 2 + (Dm - 2 * tm) ** 2) + L ** 2),\n (1.0 / 12.0) * (3 * 0.25 * (Dm ** 2 + (Dm - 2 * tm) ** 2) + L ** 2),\n ]\n )\n return m, cm, m * I\n\n\nclass Layout(om.ExplicitComponent):\n \"\"\"\n Calculate lengths, heights, and diameters of key drivetrain components in a\n direct drive system (valid for upwind or downwind).\n\n Parameters\n ----------\n upwind : boolean\n Flag whether the design is upwind or downwind\n L_12 : float, [m]\n Length from bearing #1 to bearing #2\n L_h1 : float, [m]\n Length from hub / start of lss to bearing #1\n L_generator : float, [m]\n Generator stack width\n overhang : float, [m]\n Overhang of rotor from tower along x-axis in yaw-aligned c.s.\n drive_height : float, [m]\n Hub height above tower top\n tilt : float, [deg]\n Angle of drivetrain lss tilt\n lss_diameter : numpy array[2], [m]\n LSS outer diameter from hub to bearing 2\n lss_wall_thickness : numpy array[2], [m]\n LSS wall thickness\n hub_diameter : float, [m]\n Diameter of hub\n D_top : float, [m]\n Tower top outer diameter\n lss_rho : float, [kg/m**3]\n material density\n bedplate_rho : float, [kg/m**3]\n material density\n\n Returns\n -------\n L_lss : float, [m]\n Length of nose\n L_drive : float, [m]\n Length of drivetrain from bedplate to hub flang\n s_lss : numpy array[5], [m]\n LSS discretized s-coordinates\n lss_mass : float, [kg]\n LSS mass\n lss_cm : float, [m]\n LSS center of mass along lss axis from bedplate\n lss_I : numpy array[3], [kg*m**2]\n LSS moment of inertia around cm in axial (hub-aligned) c.s.\n L_bedplate : float, [m]\n Length of bedplate\n H_bedplate : float, [m]\n height of bedplate\n bedplate_mass : float, [kg]\n Bedplate mass\n bedplate_cm : numpy array[3], [m]\n Bedplate center of mass\n bedplate_I : numpy array[6], [kg*m**2]\n Bedplate mass moment of inertia about base\n s_mb1 : float, [m]\n Bearing 1 s-coordinate along drivetrain, measured from bedplate\n s_mb2 : float, [m]\n Bearing 2 s-coordinate along drivetrain, measured from bedplate\n s_gearbox : float, [m]\n Overall gearbox cm\n s_generator : float, [m]\n Overall generator cm\n constr_length : float, [m]\n Margin for drivetrain length and desired overhang distance (should be > 0)\n constr_height : float, [m]\n Margin for drivetrain height and desired hub height (should be > 0)\n\n \"\"\"\n\n def setup(self):\n self.add_discrete_input(\"upwind\", True)\n self.add_input(\"L_12\", 0.0, units=\"m\")\n self.add_input(\"L_h1\", 0.0, units=\"m\")\n self.add_input(\"L_generator\", 0.0, units=\"m\")\n self.add_input(\"overhang\", 0.0, units=\"m\")\n self.add_input(\"drive_height\", 0.0, units=\"m\")\n self.add_input(\"tilt\", 0.0, units=\"deg\")\n self.add_input(\"lss_diameter\", np.zeros(2), units=\"m\")\n self.add_input(\"lss_wall_thickness\", np.zeros(2), units=\"m\")\n self.add_input(\"D_top\", 0.0, units=\"m\")\n self.add_input(\"hub_diameter\", val=0.0, units=\"m\")\n self.add_input(\"lss_rho\", val=0.0, units=\"kg/m**3\")\n self.add_input(\"bedplate_rho\", val=0.0, units=\"kg/m**3\")\n\n self.add_output(\"L_lss\", 0.0, units=\"m\")\n self.add_output(\"L_drive\", 0.0, units=\"m\")\n self.add_output(\"s_lss\", val=np.zeros(5), units=\"m\")\n self.add_output(\"lss_mass\", val=0.0, units=\"kg\")\n self.add_output(\"lss_cm\", val=0.0, units=\"m\")\n self.add_output(\"lss_I\", val=np.zeros(3), units=\"kg*m**2\")\n self.add_output(\"L_bedplate\", 0.0, units=\"m\")\n self.add_output(\"H_bedplate\", 0.0, units=\"m\")\n self.add_output(\"bedplate_mass\", val=0.0, units=\"kg\")\n self.add_output(\"bedplate_cm\", val=np.zeros(3), units=\"m\")\n self.add_output(\"bedplate_I\", val=np.zeros(6), units=\"kg*m**2\")\n self.add_output(\"s_mb1\", val=0.0, units=\"m\")\n self.add_output(\"s_mb2\", val=0.0, units=\"m\")\n self.add_output(\"s_gearbox\", val=0.0, units=\"m\")\n self.add_output(\"s_generator\", val=0.0, units=\"m\")\n self.add_output(\"hss_mass\", val=0.0, units=\"kg\")\n self.add_output(\"hss_cm\", val=0.0, units=\"m\")\n self.add_output(\"hss_I\", val=np.zeros(3), units=\"kg*m**2\")\n self.add_output(\"constr_length\", 0.0, units=\"m\")\n self.add_output(\"constr_height\", 0.0, units=\"m\")\n\n\nclass DirectLayout(Layout):\n \"\"\"\n Calculate lengths, heights, and diameters of key drivetrain components in a\n direct drive system (valid for upwind or downwind).\n\n Parameters\n ----------\n access_diameter : float, [m]\n Minimum diameter required for maintenance access\n nose_diameter : numpy array[2], [m]\n Nose outer diameter from bearing 1 to bedplate\n nose_wall_thickness : numpy array[2], [m]\n Nose wall thickness\n bedplate_wall_thickness : numpy array[4], [m]\n Bedplate wall thickness\n\n Returns\n -------\n L_nose : float, [m]\n Length of nose\n D_bearing1 : float, [m]\n Diameter of bearing #1 (closer to hub)\n D_bearing2 : float, [m]\n Diameter of bearing #2 (closer to tower)\n s_nose : numpy array[5], [m]\n Nose discretized hub-aligned s-coordinates\n nose_mass : float, [kg]\n Nose mass\n nose_cm : float, [m]\n Nose center of mass along nose axis from bedplate\n nose_I : numpy array[3], [kg*m**2]\n Nose moment of inertia around cm in axial (hub-aligned) c.s.\n x_bedplate : numpy array[12], [m]\n Bedplate centerline x-coordinates\n z_bedplate : numpy array[12], [m]\n Bedplate centerline z-coordinates\n x_bedplate_inner : numpy array[12], [m]\n Bedplate lower curve x-coordinates\n z_bedplate_inner : numpy array[12], [m]\n Bedplate lower curve z-coordinates\n x_bedplate_outer : numpy array[12], [m]\n Bedplate outer curve x-coordinates\n z_bedplate_outer : numpy array[12], [m]\n Bedplate outer curve z-coordinates\n D_bedplate : numpy array[12], [m]\n Bedplate diameters\n t_bedplate : numpy array[12], [m]\n Bedplate wall thickness (mirrors input)\n s_stator : float, [m]\n Generator stator attachment to nose s-coordinate\n s_rotor : float, [m]\n Generator rotor attachment to lss s-coordinate\n constr_access : numpy array[2], [m]\n Margin for allowing maintenance access (should be > 0)\n constr_ecc : float, [m]\n Margin for bedplate ellipse eccentricity (should be > 0)\n \"\"\"\n\n def setup(self):\n super().setup()\n\n self.add_input(\"access_diameter\", 0.0, units=\"m\")\n self.add_input(\"nose_diameter\", np.zeros(2), units=\"m\")\n self.add_input(\"nose_wall_thickness\", np.zeros(2), units=\"m\")\n self.add_input(\"bedplate_wall_thickness\", np.zeros(4), units=\"m\")\n\n self.add_output(\"L_nose\", 0.0, units=\"m\")\n self.add_output(\"D_bearing1\", 0.0, units=\"m\")\n self.add_output(\"D_bearing2\", 0.0, units=\"m\")\n self.add_output(\"s_nose\", val=np.zeros(5), units=\"m\")\n self.add_output(\"nose_mass\", val=0.0, units=\"kg\")\n self.add_output(\"nose_cm\", val=0.0, units=\"m\")\n self.add_output(\"nose_I\", val=np.zeros(3), units=\"kg*m**2\")\n self.add_output(\"x_bedplate\", val=np.zeros(12), units=\"m\")\n self.add_output(\"z_bedplate\", val=np.zeros(12), units=\"m\")\n self.add_output(\"x_bedplate_inner\", val=np.zeros(12), units=\"m\")\n self.add_output(\"z_bedplate_inner\", val=np.zeros(12), units=\"m\")\n self.add_output(\"x_bedplate_outer\", val=np.zeros(12), units=\"m\")\n self.add_output(\"z_bedplate_outer\", val=np.zeros(12), units=\"m\")\n self.add_output(\"D_bedplate\", val=np.zeros(12), units=\"m\")\n self.add_output(\"t_bedplate\", val=np.zeros(12), units=\"m\")\n self.add_output(\"s_stator\", val=0.0, units=\"m\")\n self.add_output(\"s_rotor\", val=0.0, units=\"m\")\n self.add_output(\"constr_access\", np.zeros((2, 2)), units=\"m\")\n self.add_output(\"constr_ecc\", 0.0, units=\"m\")\n\n def compute(self, inputs, outputs, discrete_inputs, discrete_outputs):\n\n # Unpack inputs\n L_12 = float(inputs[\"L_12\"])\n L_h1 = float(inputs[\"L_h1\"])\n L_generator = float(inputs[\"L_generator\"])\n L_overhang = float(inputs[\"overhang\"])\n H_drive = float(inputs[\"drive_height\"])\n tilt = float(np.deg2rad(inputs[\"tilt\"]))\n D_access = float(inputs[\"access_diameter\"])\n D_nose = inputs[\"nose_diameter\"]\n D_lss = inputs[\"lss_diameter\"]\n D_top = float(inputs[\"D_top\"])\n D_hub = float(inputs[\"hub_diameter\"])\n t_nose = inputs[\"nose_wall_thickness\"]\n t_lss = inputs[\"lss_wall_thickness\"]\n t_bed = inputs[\"bedplate_wall_thickness\"]\n upwind = discrete_inputs[\"upwind\"]\n lss_rho = float(inputs[\"lss_rho\"])\n bedplate_rho = float(inputs[\"bedplate_rho\"])\n\n # ------- Discretization ----------------\n L_grs = 0.5 * L_h1\n L_gsn = L_generator - L_grs - L_12\n L_2n = 2.0 * L_gsn\n\n # Length of lss and nose\n L_lss = L_12 + L_h1\n L_nose = L_12 + L_2n\n outputs[\"L_lss\"] = L_lss\n outputs[\"L_nose\"] = L_nose\n\n # Total length from bedplate to hub flange\n ds = 0.5 * np.ones(2)\n s_drive = np.cumsum(np.r_[0.0, L_2n * ds, L_12 * ds, L_h1 * ds])\n L_drive = s_drive[-1]\n outputs[\"L_drive\"] = L_drive\n\n # From Overhang input (dist from center of tower measured in yaw-aligned\n # c.s.-parallel to ground), compute bedplate length and height\n L_bedplate = L_overhang - (L_drive + 0.5 * D_hub) * np.cos(tilt)\n constr_Ldrive = L_bedplate - 0.5 * D_top # Should be > 0\n if constr_Ldrive < 0:\n L_bedplate = 0.5 * D_top\n H_bedplate = H_drive - (L_drive + 0.5 * D_hub) * np.sin(tilt) # Keep eccentricity under control\n outputs[\"L_bedplate\"] = L_bedplate\n outputs[\"H_bedplate\"] = H_bedplate\n\n # Discretize the drivetrain from bedplate to hub\n s_mb1 = s_drive[4]\n s_mb2 = s_drive[2]\n s_rotor = s_drive[-2]\n s_stator = s_drive[1]\n s_nose = s_drive[:5]\n s_lss = s_drive[2:]\n\n # Store outputs\n # outputs['s_drive'] = np.sort(s_drive)\n outputs[\"s_rotor\"] = s_rotor\n outputs[\"s_stator\"] = s_stator\n outputs[\"s_nose\"] = s_nose\n outputs[\"s_lss\"] = s_lss\n outputs[\"s_generator\"] = 0.5 * (s_rotor + s_stator)\n outputs[\"s_mb1\"] = s_mb1\n outputs[\"s_mb2\"] = s_mb2\n # ------------------------------------\n\n # ------------ Bedplate geometry and coordinates -------------\n # Define reference/centroidal axis\n # Origin currently set like standard ellipse eqns, but will shift below to being at tower top\n # The end point of 90 deg isn't exactly right for non-zero tilt, but leaving that for later\n n_points = 12\n if upwind:\n rad = np.linspace(0.0, 0.5 * np.pi, n_points)\n else:\n rad = np.linspace(np.pi, 0.5 * np.pi, n_points)\n\n # Make sure we have the right number of bedplate thickness points\n t_bed = np.interp(rad, np.linspace(rad[0], rad[-1], len(t_bed)), t_bed)\n\n # Centerline\n x_c = L_bedplate * np.cos(rad)\n z_c = H_bedplate * np.sin(rad)\n\n # Points on the outermost ellipse\n x_outer = (L_bedplate + 0.5 * D_top) * np.cos(rad)\n z_outer = (H_bedplate + 0.5 * D_nose[0]) * np.sin(rad)\n\n # Points on the innermost ellipse\n x_inner = (L_bedplate - 0.5 * D_top) * np.cos(rad)\n z_inner = (H_bedplate - 0.5 * D_nose[0]) * np.sin(rad)\n\n # Cross-sectional properties\n D_bed = np.sqrt((z_outer - z_inner) ** 2 + (x_outer - x_inner) ** 2)\n r_bed_o = 0.5 * D_bed\n r_bed_i = r_bed_o - t_bed\n A_bed = np.pi * (r_bed_o ** 2 - r_bed_i ** 2)\n\n # This finds the central angle (rad2) given the parametric angle (rad)\n rad2 = np.arctan(L_bedplate / H_bedplate * np.tan(rad))\n\n # arc length from eccentricity of the centroidal ellipse using incomplete elliptic integral of the second kind\n if L_bedplate >= H_bedplate:\n ecc = np.sqrt(1 - (H_bedplate / L_bedplate) ** 2)\n arc = L_bedplate * np.diff(ellipeinc(rad2, ecc))\n else:\n ecc = np.sqrt(1 - (L_bedplate / H_bedplate) ** 2)\n arc = H_bedplate * np.diff(ellipeinc(rad2, ecc))\n\n # Mass and MoI properties\n x_c_sec = util.nodal2sectional(x_c)[0]\n z_c_sec = util.nodal2sectional(z_c)[0]\n # R_c_sec = np.sqrt( x_c_sec**2 + z_c_sec**2 ) # unnecesary\n mass = util.nodal2sectional(A_bed)[0] * arc * bedplate_rho\n mass_tot = mass.sum()\n cm = np.array([np.sum(mass * x_c_sec), 0.0, np.sum(mass * z_c_sec)]) / mass_tot\n # For I, could do integral over sectional I, rotate axes by rad2, and then parallel axis theorem\n # we simplify by assuming lumped point mass. TODO: Find a good way to check this? Torus shell?\n I_bed = util.assembleI(np.zeros(6))\n for k in range(len(mass)):\n r_bed_o_k = 0.5 * (r_bed_o[k] + r_bed_o[k + 1])\n r_bed_i_k = 0.5 * (r_bed_i[k] + r_bed_i[k + 1])\n I_sec = mass[k] * np.array(\n [\n 0.5 * (r_bed_o_k ** 2 + r_bed_i_k ** 2),\n (1.0 / 12.0) * (3 * (r_bed_o_k ** 2 + r_bed_i_k ** 2) + arc[k] ** 2),\n (1.0 / 12.0) * (3 * (r_bed_o_k ** 2 + r_bed_i_k ** 2) + arc[k] ** 2),\n ]\n )\n I_sec_rot = util.rotateI(I_sec, 0.5 * np.pi - rad2[k], axis=\"y\")\n R_k = np.array([x_c_sec[k] - x_c[0], 0.0, z_c_sec[k]])\n I_bed += util.assembleI(I_sec_rot) + mass[k] * (np.dot(R_k, R_k) * np.eye(3) - np.outer(R_k, R_k))\n\n # Now shift origin to be at tower top\n cm[0] -= x_c[0]\n x_inner -= x_c[0]\n x_outer -= x_c[0]\n x_c -= x_c[0]\n\n outputs[\"bedplate_mass\"] = mass_tot\n outputs[\"bedplate_cm\"] = cm\n outputs[\"bedplate_I\"] = util.unassembleI(I_bed)\n\n # Geometry outputs\n outputs[\"x_bedplate\"] = x_c\n outputs[\"z_bedplate\"] = z_c\n outputs[\"x_bedplate_inner\"] = x_inner\n outputs[\"z_bedplate_inner\"] = z_inner\n outputs[\"x_bedplate_outer\"] = x_outer\n outputs[\"z_bedplate_outer\"] = z_outer\n outputs[\"D_bedplate\"] = D_bed\n outputs[\"t_bedplate\"] = t_bed\n # ------------------------------------\n\n # ------- Constraints ----------------\n outputs[\"constr_access\"] = np.c_[D_lss - 2 * t_lss - D_nose - 0.25 * D_access, D_nose - 2 * t_nose - D_access]\n outputs[\"constr_length\"] = constr_Ldrive # Should be > 0\n outputs[\"constr_height\"] = H_bedplate # Should be > 0\n outputs[\"constr_ecc\"] = L_bedplate - H_bedplate # Should be > 0\n # ------------------------------------\n\n # ------- Nose, lss, and bearing properties ----------------\n # Now is a good time to set bearing diameters\n outputs[\"D_bearing1\"] = D_lss[-1] - t_lss[-1] - D_nose[0]\n outputs[\"D_bearing2\"] = D_lss[-1] - t_lss[-1] - D_nose[-1]\n\n # Compute center of mass based on area\n m_nose, cm_nose, I_nose = rod_prop(s_nose, D_nose, t_nose, bedplate_rho)\n outputs[\"nose_mass\"] = m_nose\n outputs[\"nose_cm\"] = cm_nose\n outputs[\"nose_I\"] = I_nose\n\n m_lss, cm_lss, I_lss = rod_prop(s_lss, D_lss, t_lss, lss_rho)\n outputs[\"lss_mass\"] = m_lss\n outputs[\"lss_cm\"] = cm_lss\n outputs[\"lss_I\"] = I_lss\n\n\nclass GearedLayout(Layout):\n \"\"\"\n Calculate lengths, heights, and diameters of key drivetrain components in a\n geared drive system (valid for upwind or downwind).\n\n |_Lgen|_Lhss|Lgear|dl|_L12_|_Lh1_|\n |_____Llss_____|\n |--|--|--|--|--|--|--|--|--|--|--|\n 0 1 2 3 4 5 6 7 8 9 10 11 (indices)\n mb2 mb1\n\n Parameters\n ----------\n hss_diameter : numpy array[2], [m]\n HSS outer diameter from hub to bearing 2\n hss_wall_thickness : numpy array[2], [m]\n HSS wall thickness\n bedplate_flange_width : float, [m]\n Bedplate is two parallel I beams, this is the flange width\n bedplate_flange_thickness : float, [m]\n Bedplate is two parallel I beams, this is the flange thickness\n bedplate_web_thickness : float, [m]\n Bedplate is two parallel I beams, this is the web thickness\n bedplate_web_height : float, [m]\n Bedplate is two parallel I beams, this is the web height\n hss_rho : float, [kg/m**3]\n material density\n\n Returns\n -------\n s_drive : numpy array[12], [m]\n Discretized, hub-aligned s-coordinates of the drivetrain starting at\n generator and ending at hub flange\n s_hss : numpy array[5], [m]\n HSS discretized s-coordinates\n hss_mass : float, [kg]\n HSS mass\n hss_cm : float, [m]\n HSS center of mass along hss axis from bedplate\n hss_I : numpy array[3], [kg*m**2]\n HSS moment of inertia around cm in axial (hub-aligned) c.s.\n s_gearbox : float, [m]\n Gearbox (centroid) position in s-coordinates\n s_generator : float, [m]\n Generator (centroid) position in s-coordinates\n\n \"\"\"\n\n def setup(self):\n super().setup()\n\n self.add_input(\"L_hss\", 0.0, units=\"m\")\n self.add_input(\"L_gearbox\", 0.0, units=\"m\")\n self.add_input(\"hss_diameter\", np.zeros(2), units=\"m\")\n self.add_input(\"hss_wall_thickness\", np.zeros(2), units=\"m\")\n self.add_input(\"hss_rho\", val=0.0, units=\"kg/m**3\")\n self.add_input(\"bedplate_flange_width\", val=0.0, units=\"m\")\n self.add_input(\"bedplate_flange_thickness\", val=0.0, units=\"m\")\n self.add_input(\"bedplate_web_thickness\", val=0.0, units=\"m\")\n\n self.add_output(\"s_drive\", val=np.zeros(12), units=\"m\")\n self.add_output(\"s_hss\", val=np.zeros(3), units=\"m\")\n self.add_output(\"bedplate_web_height\", val=0.0, units=\"m\")\n\n def compute(self, inputs, outputs, discrete_inputs, discrete_outputs):\n\n # Unpack inputs\n upwind = discrete_inputs[\"upwind\"]\n Cup = -1.0 if upwind else 1.0\n\n L_12 = float(inputs[\"L_12\"])\n L_h1 = float(inputs[\"L_h1\"])\n L_hss = float(inputs[\"L_hss\"])\n L_gearbox = float(inputs[\"L_gearbox\"])\n L_generator = float(inputs[\"L_generator\"])\n L_overhang = float(inputs[\"overhang\"])\n H_drive = float(inputs[\"drive_height\"])\n\n tilt = float(np.deg2rad(inputs[\"tilt\"]))\n\n D_lss = inputs[\"lss_diameter\"]\n t_lss = inputs[\"lss_wall_thickness\"]\n D_hss = inputs[\"hss_diameter\"]\n t_hss = inputs[\"hss_wall_thickness\"]\n\n D_top = float(inputs[\"D_top\"])\n D_hub = float(inputs[\"hub_diameter\"])\n\n bed_w_flange = float(inputs[\"bedplate_flange_width\"])\n bed_t_flange = float(inputs[\"bedplate_flange_thickness\"])\n # bed_h_web = float(inputs['bedplate_web_height'])\n bed_t_web = float(inputs[\"bedplate_web_thickness\"])\n\n lss_rho = float(inputs[\"lss_rho\"])\n hss_rho = float(inputs[\"hss_rho\"])\n bedplate_rho = float(inputs[\"bedplate_rho\"])\n\n # ------- Discretization ----------------\n # Length of lss and drivetrain length\n delta = 0.1 # separation between MB2 and gearbox attachment\n L_lss = L_12 + L_h1 + delta\n L_drive = L_lss + L_gearbox + L_hss + L_generator\n ds = 0.5 * np.ones(2)\n s_drive = np.cumsum(np.r_[0.0, L_generator * ds, L_hss * ds, L_gearbox * ds, delta, L_12 * ds, L_h1 * ds])\n L_drive = s_drive[-1] - s_drive[0]\n outputs[\"L_drive\"] = L_drive\n outputs[\"L_lss\"] = L_lss\n\n # Put tower at 0 position\n s_tower = s_drive[-1] + 0.5 * D_hub - L_overhang / np.cos(tilt)\n s_drive -= s_tower\n outputs[\"s_drive\"] = s_drive\n\n # Discretize the drivetrain from generator to hub\n s_generator = s_drive[1]\n s_mb1 = s_drive[9]\n s_mb2 = s_drive[7]\n s_gearbox = s_drive[5]\n s_lss = s_drive[6:]\n s_lss = np.r_[s_lss[:-2], s_lss[-1]] # Need to stick to 5 points\n s_hss = s_drive[2:5]\n\n # Store outputs\n outputs[\"s_generator\"] = s_generator\n outputs[\"s_gearbox\"] = s_gearbox\n outputs[\"s_mb1\"] = s_mb1\n outputs[\"s_mb2\"] = s_mb2\n # ------------------------------------\n\n # ------- hss, lss, and bearing properties ----------------\n # Compute center of mass based on area\n m_hss, cm_hss, I_hss = rod_prop(s_hss, D_hss, t_hss, hss_rho)\n outputs[\"hss_mass\"] = m_hss\n outputs[\"hss_cm\"] = cm_hss\n outputs[\"hss_I\"] = I_hss\n outputs[\"s_hss\"] = s_hss\n\n m_lss, cm_lss, I_lss = rod_prop(s_lss, D_lss, t_lss, lss_rho)\n outputs[\"lss_mass\"] = m_lss\n outputs[\"lss_cm\"] = cm_lss\n outputs[\"lss_I\"] = I_lss\n outputs[\"s_lss\"] = s_lss\n\n # ------- Bedplate I-beam properties ----------------\n L_bedplate = L_drive * np.cos(tilt)\n H_bedplate = H_drive - (L_drive + 0.5 * D_hub) * np.sin(tilt) # Subtract thickness of platform plate\n outputs[\"L_bedplate\"] = L_bedplate\n outputs[\"H_bedplate\"] = H_bedplate\n bed_h_web = H_bedplate - 2 * bed_t_flange - 0.05 # Leave some extra room for plate?\n\n yoff = 0.25 * D_top\n myI = IBeam(bed_w_flange, bed_t_flange, bed_h_web, bed_t_web)\n m_bedplate = myI.Area * L_bedplate * bedplate_rho\n cg_bedplate = np.r_[Cup * (L_overhang - 0.5 * L_bedplate), 0.0, myI.CG] # from tower top\n I_bedplate = (\n bedplate_rho * L_bedplate * np.r_[myI.Jxx, myI.Iyy, myI.Izz]\n + m_bedplate * L_bedplate ** 2 / 12.0 * np.r_[0.0, 1.0, 1.0]\n + m_bedplate * yoff ** 2 * np.r_[1.0, 0.0, 1.0]\n )\n outputs[\"bedplate_web_height\"] = bed_h_web\n outputs[\"bedplate_mass\"] = 2 * m_bedplate\n outputs[\"bedplate_cm\"] = cg_bedplate\n outputs[\"bedplate_I\"] = 2 * np.r_[I_bedplate, np.zeros(3)]\n\n # ------- Constraints ----------------\n outputs[\"constr_length\"] = (L_drive + 0.5 * D_hub) * np.cos(tilt) - L_overhang - 0.5 * D_top # Should be > 0\n outputs[\"constr_height\"] = H_bedplate # Should be > 0\n # ------------------------------------\n" ]
[ [ "numpy.testing.assert_almost_equal", "numpy.prod", "numpy.testing.assert_equal" ], [ "numpy.array", "numpy.sin", "numpy.dot", "numpy.zeros", "numpy.sum", "numpy.ones", "numpy.tan", "numpy.eye", "scipy.special.ellipeinc", "numpy.outer", "numpy.trapz", "numpy.sqrt", "numpy.cumsum", "numpy.deg2rad", "numpy.cos", "numpy.linspace" ] ]
ygrepo/fastMRI
[ "cb9a2019f1833bfffe4969023113189abcbad0f7" ]
[ "models/mri_model.py" ]
[ "\"\"\"\nCopyright (c) Facebook, Inc. and its affiliates.\n\nThis source code is licensed under the MIT license found in the\nLICENSE file in the root directory of this source tree.\n\"\"\"\n\nfrom collections import defaultdict\nfrom pathlib import Path\n\nimport numpy as np\nimport pandas as pd\nimport pytorch_lightning as pl\nimport torch\nimport torchvision\nfrom PIL import Image\nfrom torch.utils.data import DataLoader\nfrom torch.utils.data.sampler import RandomSampler\n\nfrom common import evaluate\nfrom common.utils import save_reconstructions\nfrom data.mri_data import SliceData\n\n\nclass MRIModel(pl.LightningModule):\n \"\"\"\n Abstract super class for Deep Learning based reconstruction models.\n This is a subclass of the LightningModule class from pytorch_lightning, with\n some additional functionality specific to fastMRI:\n - fastMRI data loaders\n - Evaluating reconstructions\n - Visualization\n - Saving test reconstructions\n\n To implement a new reconstruction model, inherit from this class and implement the\n following methods:\n - train_data_transform, val_data_transform, test_data_transform:\n Create and return data transformer objects for each data split\n - training_step, validation_step, test_step:\n Define what happens in one step of training, validation and testing respectively\n - configure_optimizers:\n Create and return the optimizers\n Other methods from LightningModule can be overridden as needed.\n \"\"\"\n\n def __init__(self, hparams):\n super().__init__()\n self.hparams = hparams\n\n def _create_data_loader(self, data_transform, data_partition, sample_rate=None):\n sample_rate = sample_rate or self.hparams.sample_rate\n dataset = SliceData(\n root=self.hparams.data_path / f'{self.hparams.challenge}_{data_partition}',\n transform=data_transform,\n sample_rate=sample_rate,\n challenge=self.hparams.challenge\n )\n sampler = RandomSampler(dataset)\n # sampler = DistributedSampler(dataset)\n return DataLoader(\n dataset=dataset,\n batch_size=self.hparams.batch_size,\n num_workers=4,\n pin_memory=False,\n sampler=sampler,\n )\n\n def train_data_transform(self):\n raise NotImplementedError\n\n @pl.data_loader\n def train_dataloader(self):\n return self._create_data_loader(self.train_data_transform(), data_partition='train')\n\n def val_data_transform(self):\n raise NotImplementedError\n\n @pl.data_loader\n def val_dataloader(self):\n return self._create_data_loader(self.val_data_transform(), data_partition='val')\n\n def test_data_transform(self):\n raise NotImplementedError\n\n @pl.data_loader\n def test_dataloader(self):\n return self._create_data_loader(self.test_data_transform(), data_partition='test', sample_rate=1.)\n\n def _evaluate(self, val_logs):\n losses = []\n outputs = defaultdict(list)\n targets = defaultdict(list)\n for log in val_logs:\n losses.append(log['val_loss'].cpu().numpy())\n for i, (fname, slice) in enumerate(zip(log['fname'], log['slice'])):\n outputs[fname].append((slice, log['output'][i]))\n targets[fname].append((slice, log['target'][i]))\n metrics = dict(val_loss=losses, nmse=[], ssim=[], psnr=[])\n for fname in outputs:\n output = np.stack([out for _, out in sorted(outputs[fname])])\n target = np.stack([tgt for _, tgt in sorted(targets[fname])])\n metrics['nmse'].append(evaluate.nmse(target, output))\n metrics['ssim'].append(evaluate.ssim(target, output))\n metrics['psnr'].append(evaluate.psnr(target, output))\n metrics = {metric: np.mean(values) for metric, values in metrics.items()}\n print(metrics, '\\n')\n # save the metrics data\n metric_file_path = Path(self.hparams.exp_dir) / self.hparams.exp / \"validation_metrics\"\n metric_file_path.mkdir(parents=True, exist_ok=True)\n metric_file_path = metric_file_path / \"metrics.csv\"\n df = pd.DataFrame([metrics])\n if metric_file_path.exists():\n df.to_csv(metric_file_path, mode=\"a\", header=False, index=False)\n else:\n df.to_csv(metric_file_path, mode=\"w\", header=True, index=False)\n return dict(log=metrics, **metrics)\n\n def _visualize(self, val_logs):\n def _normalize(image):\n image = image[np.newaxis]\n image -= image.min()\n return image / image.max()\n\n def _save_image(image, tag):\n grid = torchvision.utils.make_grid(torch.Tensor(image), nrow=4, pad_value=1)\n grid_path = Path(self.hparams.exp_dir) / self.hparams.exp / \"image_validation_step\"\n grid_path.mkdir(parents=True, exist_ok=True)\n grid_path = grid_path / tag\n grid_np = grid.mul_(255).add_(0.5).clamp_(0, 255).permute(1, 2, 0).to('cpu', torch.uint8).numpy()\n grid_pil = Image.fromarray(grid_np)\n try:\n grid_pil.save(grid_path, format=\"PNG\")\n except ValueError as e:\n print(e)\n\n # Only process first size to simplify visualization.\n visualize_size = val_logs[0]['output'].shape\n val_logs = [x for x in val_logs if x['output'].shape == visualize_size]\n num_logs = len(val_logs)\n num_viz_images = 16\n step = (num_logs + num_viz_images - 1) // num_viz_images\n outputs, targets = [], []\n for i in range(0, num_logs, step):\n outputs.append(_normalize(val_logs[i]['output'][0]))\n targets.append(_normalize(val_logs[i]['target'][0]))\n outputs = np.stack(outputs)\n targets = np.stack(targets)\n _save_image(targets, 'Target')\n _save_image(outputs, 'Reconstruction')\n _save_image(np.abs(targets - outputs), 'Error')\n\n def validation_epoch_end(self, val_logs):\n self._visualize(val_logs)\n return self._evaluate(val_logs)\n\n def test_epoch_end(self, test_logs):\n outputs = defaultdict(list)\n for log in test_logs:\n for i, (fname, slice) in enumerate(zip(log['fname'], log['slice'])):\n outputs[fname].append((slice, log['output'][i]))\n for fname in outputs:\n outputs[fname] = np.stack([out for _, out in sorted(outputs[fname])])\n save_reconstructions(outputs, self.hparams.exp_dir / self.hparams.exp / 'reconstructions')\n return dict()\n" ]
[ [ "torch.utils.data.sampler.RandomSampler", "pandas.DataFrame", "numpy.mean", "numpy.stack", "torch.utils.data.DataLoader", "numpy.abs", "torch.Tensor" ] ]
airbert-vln/bnb-dataset
[ "2f7b7181bab6084d0bcf60407939556e89fdd551" ]
[ "scripts/detect_room.py" ]
[ "\"\"\"\nGet attributes about images\nInspired by https://github.com/CSAILVision/places365/blob/master/run_placesCNN_unified.py\n\"\"\"\nfrom pathlib import Path\nimport argparse\nfrom typing import List, Iterator, Tuple, Optional, Union, Dict\nimport hashlib\nimport json\nfrom multiprocessing import Pool\nimport urllib.request\nimport sys\nimport csv\nfrom tqdm.auto import tqdm\nimport torch\nfrom torchvision import transforms as trn\nfrom torch import nn\nfrom torch.utils.data._utils.collate import default_collate\nfrom torch.nn import functional as F\nimport numpy as np\nimport cv2\nfrom PIL import Image\nimport argtyped\nfrom torch.utils.data import Dataset, DataLoader\nimport scripts.wideresnet as wideresnet\n\n\ncsv.field_size_limit(sys.maxsize)\n\nTSV_FIELDNAMES = [\n \"listing_id\",\n \"photo_id\",\n \"category\",\n \"attributes\",\n \"is_indoor\",\n]\n\n\nclass Arguments(argtyped.Arguments, underscore=True):\n outfile: Path = Path(\"places365/detect.tsv\")\n images: Path = Path(\"images\")\n batch_size: int = 100\n visualize: bool = False\n num_cat: int = 5\n num_attr: int = 10\n num_splits: int = 1\n start: int = 0\n num_workers: int = -1\n\n\n# hacky way to deal with the Pytorch 1.0 update\ndef recursion_change_bn(module: nn.Module) -> nn.Module:\n if isinstance(module, nn.BatchNorm2d):\n module.track_running_stats = 1 # type: ignore\n else:\n for i, (name, module1) in enumerate(module._modules.items()): # type: ignore\n module1 = recursion_change_bn(module1)\n return module\n\n\ndef download_url(url, cache_dir):\n stem = hashlib.sha1(str(url).encode())\n filename = cache_dir / stem.hexdigest()\n if not filename.is_file():\n urllib.request.urlretrieve(url, filename)\n return filename\n\n\ndef load_labels(\n cache_dir: Union[Path, str]\n) -> Tuple[Tuple[str, ...], np.ndarray, List[str], np.ndarray]:\n \"\"\"\n prepare all the labels\n \"\"\"\n\n # indoor and outdoor relevant\n filename_io = download_url(\n \"https://raw.githubusercontent.com/csailvision/places365/master/IO_places365.txt\",\n cache_dir,\n )\n with open(filename_io) as f:\n lines = f.readlines()\n labels_IO = []\n for line in lines:\n items = line.rstrip().split()\n labels_IO.append(int(items[-1]) - 1) # 0 is indoor, 1 is outdoor\n labels_IO = np.array(labels_IO)\n\n # scene category relevant\n filename_category = download_url(\n \"https://raw.githubusercontent.com/csailvision/places365/master/categories_places365.txt\",\n cache_dir,\n )\n _classes = list()\n with open(filename_category) as class_file:\n for line in class_file:\n _classes.append(line.strip().split(\" \")[0][3:])\n classes = tuple(_classes)\n\n # scene attribute relevant\n filename_attribute = download_url(\n \"https://raw.githubusercontent.com/csailvision/places365/master/labels_sunattribute.txt\",\n cache_dir,\n )\n with open(filename_attribute) as f:\n lines = f.readlines()\n labels_attribute = [item.rstrip() for item in lines]\n\n filename_W = download_url(\n \"http://places2.csail.mit.edu/models_places365/W_sceneattribute_wideresnet18.npy\",\n cache_dir,\n )\n W_attribute = np.load(filename_W)\n\n return classes, labels_IO, labels_attribute, W_attribute\n\n\ndef get_tf():\n # load the image transformer\n tf = trn.Compose(\n [\n trn.Resize((224, 224)),\n trn.ToTensor(),\n trn.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),\n ]\n )\n return tf\n\n\nclass NormalizeInverse(trn.Normalize):\n \"\"\"\n Undoes the normalization and returns the reconstructed images in the input domain.\n \"\"\"\n\n def __init__(self, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]):\n mean = torch.tensor(mean)\n std = torch.tensor(std)\n std_inv = 1 / (std + 1e-7) # type: ignore\n mean_inv = -mean * std_inv\n super().__init__(mean=mean_inv, std=std_inv)\n\n def __call__(self, array: np.ndarray):\n tensor = torch.tensor(array)\n tensor = super().__call__(tensor.clone())\n array = np.transpose(np.uint8(255 * tensor.numpy()), (1, 2, 0))\n\n return array\n\n\nclass Hooker:\n def __init__(self, model: nn.Module, features_names=(\"layer4\", \"avgpool\")):\n self.features: List[np.ndarray] = []\n\n # this is the last conv layer of the resnet\n for name in features_names:\n model._modules.get(name).register_forward_hook(self) # type: ignore\n\n def __call__(self, module: nn.Module, input, output):\n self.features.append(output.data.cpu().numpy())\n\n def reset(self):\n self.features = []\n\n\n# load the model\ndef load_model(cache_dir: Union[Path, str]) -> nn.Module:\n # this model has a last conv feature map as 14x14\n\n model_file = download_url(\n \"http://places2.csail.mit.edu/models_places365/wideresnet18_places365.pth.tar\",\n cache_dir,\n )\n\n model = wideresnet.resnet18(num_classes=365)\n checkpoint = torch.load(model_file, map_location=lambda storage, loc: storage)\n state_dict = {\n str.replace(k, \"module.\", \"\"): v for k, v in checkpoint[\"state_dict\"].items()\n }\n model.load_state_dict(state_dict)\n\n # hacky way to deal with the upgraded batchnorm2D and avgpool layers...\n for i, (name, module) in enumerate(model._modules.items()): # type: ignore\n module = recursion_change_bn(model) # type: ignore\n model.avgpool = torch.nn.AvgPool2d(kernel_size=14, stride=1, padding=0) # type: ignore\n\n model.eval()\n return model\n\n\ndef search_locations(image_folder: Path) -> List[Path]:\n return [f for f in image_folder.iterdir() if f.is_dir()]\n\n\ndef load_photo_paths(locations: List[Path]) -> Iterator[Path]:\n for location in tqdm(locations):\n for photo in location.glob(\"*.jpg\"):\n yield photo\n\n\ndef load_photos(images: Path, cache_dir: Union[Path, str]) -> List[Union[str, Path]]:\n photo_cache = Path(cache_dir) / \"photos.txt\"\n\n if photo_cache.is_file():\n with open(photo_cache, \"r\") as fid:\n photos: List[Union[str, Path]] = [l.strip() for l in fid.readlines()]\n else:\n print(\"Preloading every images\")\n photos = list(images.rglob(\"*.jpg\"))\n with open(photo_cache, \"w\") as fid:\n fid.writelines(f\"{l}\\n\" for l in photos)\n\n return photos\n\n\nclass ImageDataset(Dataset):\n def __init__(self, photos: List[Union[Path, str]]):\n self.photos = photos\n self.tf = get_tf() # image transformer\n\n def __len__(self):\n return len(self.photos)\n\n def __getitem__(\n self, index: int\n ) -> Optional[Tuple[torch.Tensor, torch.Tensor, torch.Tensor]]:\n path = Path(self.photos[index])\n\n try:\n image = Image.open(path)\n image = image.convert(\"RGB\")\n except:\n return None\n tensor = self.tf(image)\n\n listing_id, photo_id = map(int, path.stem.split(\"-\"))\n return torch.tensor(listing_id), torch.tensor(photo_id), tensor\n\n\ndef collate_fn(batch: Tuple):\n batch = tuple([b for b in batch if b is not None])\n\n if not batch:\n return None\n\n return default_collate(batch)\n\n\ndef class_activation_map(\n feature_conv: np.ndarray, weight_softmax: np.ndarray, class_idx: List[int]\n):\n # generate the class activation maps upsample to 256x256\n size_upsample = (256, 256)\n nc, h, w = feature_conv.shape\n output_cam = []\n for _ in class_idx:\n cam = weight_softmax[class_idx].dot(feature_conv.reshape((nc, h * w)))\n cam = cam.reshape(h, w)\n cam = cam - np.min(cam)\n cam_img = cam / np.max(cam)\n cam_img = np.uint8(255 * cam_img)\n output_cam.append(cv2.resize(cam_img, size_upsample)) # type: ignore\n return output_cam\n\n\ndef get_key(listing_id, photo_id) -> str:\n return f\"{listing_id}_{photo_id}\"\n\n\ndef is_indoor(idx, labels_io):\n # vote for the indoor or outdoor\n io_image = np.mean(labels_io[idx[:10]])\n ans = bool(io_image < 0.5)\n return io_image, ans\n\n\ndef softmax(x):\n \"\"\"Compute softmax values for each sets of scores in x.\"\"\"\n e_x = np.exp(x - np.max(x))\n return e_x / e_x.sum(axis=0) # type: ignore\n\n\n@torch.no_grad()\ndef run_model(\n batch: List[torch.Tensor],\n model,\n hook,\n classes: Tuple[str, ...],\n labels_IO: np.ndarray,\n labels_attribute: List[str],\n W_attribute: np.ndarray,\n num_cat: int,\n num_attr: int,\n weight_softmax: Optional[np.ndarray] = None,\n) -> List[Dict]:\n listing_ids, photo_ids, input_img = batch\n\n # forward pass\n logit = model.forward(input_img.cuda())\n h_x = F.softmax(logit, 1)\n\n detections = []\n\n for i, p in enumerate(h_x): # type: ignore\n listing_id = int(listing_ids[i])\n photo_id = int(photo_ids[i])\n key = get_key(listing_id, photo_id)\n\n probs, idx = p.sort(0, True) # type: ignore\n probs = probs.detach().cpu().numpy()\n idx = idx.detach().cpu().numpy()\n\n # scene category\n category = [(probs[j], classes[idx[j]]) for j in range(0, num_cat)]\n\n # output the scene attributes\n ft = [np.squeeze(f[i]) for f in hook.features]\n responses_attribute = softmax(W_attribute.dot(ft[1]))\n idx_a = np.argsort(responses_attribute)\n attributes = [\n (responses_attribute[idx_a[j]], labels_attribute[idx_a[j]])\n for j in range(-1, -num_attr, -1)\n ]\n\n detections.append(\n {\n \"listing_id\": listing_id,\n \"photo_id\": photo_id,\n \"category\": category,\n \"attributes\": attributes,\n \"is_indoor\": is_indoor(idx, labels_IO),\n }\n )\n\n # generate class activation mapping\n if weight_softmax is not None:\n ca_map = class_activation_map(ft[0], weight_softmax, [idx[0]])[0]\n\n # render the CAM and output\n img = NormalizeInverse()(input_img[i])\n height, width, _ = img.shape # type: ignore\n heatmap = cv2.applyColorMap( # type: ignore\n cv2.resize(ca_map, (width, height)), cv2.COLORMAP_JET # type: ignore\n )\n result = heatmap * 0.4 + img * 0.5 # type: ignore\n cv2.imwrite(f\"examples/{key}-heatmap.jpg\", result) # type: ignore\n cv2.imwrite(f\"examples/{key}-image.jpg\", img[:, :, ::-1]) # type: ignore\n\n hook.reset()\n\n return detections\n\n\nclass NumpyEncoder(json.JSONEncoder):\n \"\"\" Special json encoder for numpy types \"\"\"\n\n def default(self, obj):\n if isinstance(obj, np.integer):\n return int(obj)\n elif isinstance(obj, np.floating):\n return float(obj)\n elif isinstance(obj, np.ndarray):\n return obj.tolist()\n return json.JSONEncoder.default(self, obj)\n\n\ndef save_json(data, filename: Union[str, Path]):\n with open(filename, \"w\") as fid:\n json.dump(data, fid, indent=2, cls=NumpyEncoder)\n\n\ndef detection(args: Arguments, proc_id: int, cache_dir: Union[Path, str]):\n # load the labels\n classes, labels_IO, labels_attribute, W_attribute = load_labels(cache_dir)\n\n model = load_model(cache_dir)\n hook = Hooker(model)\n # load the transformer\n # get the softmax weight\n params = list(model.parameters())\n\n if args.visualize:\n weight_softmax = params[-2].data.numpy()\n weight_softmax[weight_softmax < 0] = 0\n else:\n weight_softmax = None\n\n photos = load_photos(args.images, cache_dir)\n print(\"The dataset contains a total of\", len(photos))\n photos = photos[proc_id :: args.num_splits]\n print(\"The split\", proc_id, \"over\", args.num_splits, \"contains\", len(photos), \"photos\")\n\n dataset = ImageDataset(photos)\n dataloader = DataLoader(\n dataset,\n batch_size=args.batch_size,\n num_workers=args.num_workers,\n collate_fn=collate_fn, # type: ignore\n )\n\n model = model.cuda()\n\n filename = args.outfile.parent / f\"{args.outfile.stem}.{proc_id}.tsv\"\n print(f\"Start split {proc_id} on {len(dataset)} photos\")\n with open(filename, \"wt\") as tsvfile:\n writer = csv.DictWriter(tsvfile, delimiter=\"\\t\", fieldnames=TSV_FIELDNAMES)\n for batch in tqdm(dataloader):\n if batch is None:\n continue\n detections = run_model(\n batch,\n model,\n hook,\n classes,\n labels_IO,\n labels_attribute,\n W_attribute,\n num_cat=args.num_cat,\n num_attr=args.num_attr,\n weight_softmax=weight_softmax,\n )\n for d in detections:\n writer.writerow(d)\n\n\nif __name__ == \"__main__\":\n args = Arguments()\n print(args.to_string())\n\n cache_dir = Path.home() / \".cache\" / args.outfile.parent.name\n cache_dir.mkdir(exist_ok=True, parents=True)\n\n\n start = max(local_rank, 0) + args.start\n detection(args, start, cache_dir)\n" ]
[ [ "numpy.max", "numpy.array", "numpy.uint8", "torch.nn.AvgPool2d", "torch.no_grad", "torch.utils.data._utils.collate.default_collate", "numpy.load", "numpy.min", "numpy.mean", "torch.tensor", "torch.utils.data.DataLoader", "torch.load", "torch.nn.functional.softmax", "numpy.argsort", "numpy.squeeze" ] ]
tacaswell/mpl-qtthread
[ "68ebb73394e6aa5550c16abf954a36a8ad3a4de6" ]
[ "UAT.py" ]
[ "import threading\nimport time\nimport mpl_qtthread.backend\nimport matplotlib\nimport matplotlib.backends.backend_qt\nimport matplotlib.pyplot as plt\nfrom matplotlib.backends.qt_compat import QtWidgets, QtCore\n\n\n# set up the teleporter\nmpl_qtthread.backend.initialize_qt_teleporter()\n# tell Matplotlib to use this backend\nmatplotlib.use(\"module://mpl_qtthread.backend_agg\")\n\n# suppress (now) spurious warnings for mpl3.3+\nmpl_qtthread.monkeypatch_pyplot()\n\napp = matplotlib.backends.backend_qt.qApp\n\n# button to exit early and to make sure qapp does not quit!\nbt = QtWidgets.QPushButton(\"Quit\")\nbt.pressed.connect(app.quit)\nbt.show()\n\ntot_time = 15\n\n# stop UAT in 12s\ntimer = QtCore.QTimer()\ntimer.setSingleShot(True)\ntimer.timeout.connect(app.quit)\ntimer.start(tot_time * 1000) # this is in ms\n\n\ndef background():\n # make a figure and plot some data\n fig, ax = plt.subplots()\n plt.show(block=False)\n (ln,) = ax.plot(range(5))\n thread_start_time = start_time = time.monotonic()\n fig.canvas.flush_events()\n # periodically update the figure\n for j in range(5):\n print(\n f\"starting block {j} at Δt {time.monotonic() - start_time:.3f} \"\n f\"(expected ~{j})\"\n )\n ln.set_color(f\"C{j}\")\n ax.set_title(f\"cycle {j}\")\n fig.set_size_inches(1 + j, 1 + j)\n fig.canvas.draw_idle()\n print(f\"line should now be color 'C{j}'\")\n time.sleep(1)\n\n plt.close(fig)\n print(\"figure is now closed, take a 1s nap\")\n time.sleep(1)\n fig2 = plt.figure()\n fig2.show()\n print(\"New figure!\")\n start_time = time.monotonic()\n for j in range(4):\n time.sleep(1)\n fig2.canvas.manager.full_screen_toggle()\n fig2.canvas.manager.set_window_title(f\"toggled {j}\")\n print(f\"toggled Δt {time.monotonic() - start_time:.3f} (expected ~{j+1})\")\n\n fig3, _ = plt.subplots(3, 1)\n fig3.show()\n print(\"figure is small again and there are two figures.\")\n print(\"take 1s nap\")\n time.sleep(1)\n plt.close(\"all\")\n print(\n f\"all figures should be closed\"\n f\"app will exit in {12 - (time.monotonic() - thread_start_time)}s on hit quit.\"\n )\n\n\n# start the thread\nthreading.Thread(target=background, daemon=True).start()\n\n\n# start the QApplication main loop\napp.exec()\n" ]
[ [ "matplotlib.use", "matplotlib.backends.qt_compat.QtWidgets.QPushButton", "matplotlib.backends.qt_compat.QtCore.QTimer", "matplotlib.pyplot.close", "matplotlib.pyplot.subplots", "matplotlib.pyplot.figure", "matplotlib.pyplot.show" ] ]
mmagnuski/mne-python
[ "8b4aa6731b828430453b6e36405313e1bea3d701", "8b4aa6731b828430453b6e36405313e1bea3d701", "8b4aa6731b828430453b6e36405313e1bea3d701" ]
[ "mne/decoding/tests/test_transformer.py", "mne/viz/tests/test_misc.py", "mne/decoding/base.py" ]
[ "# Author: Mainak Jas <mainak@neuro.hut.fi>\n# Romain Trachel <trachelr@gmail.com>\n#\n# License: BSD (3-clause)\n\nimport warnings\nimport os.path as op\nimport numpy as np\n\nfrom nose.tools import assert_true, assert_raises\nfrom numpy.testing import assert_array_equal\n\nfrom mne import io, read_events, Epochs, pick_types\nfrom mne.decoding import Scaler, FilterEstimator\nfrom mne.decoding import PSDEstimator, EpochsVectorizer\n\nwarnings.simplefilter('always') # enable b/c these tests throw warnings\n\ntmin, tmax = -0.2, 0.5\nevent_id = dict(aud_l=1, vis_l=3)\nstart, stop = 0, 8\n\ndata_dir = op.join(op.dirname(__file__), '..', '..', 'io', 'tests', 'data')\nraw_fname = op.join(data_dir, 'test_raw.fif')\nevent_name = op.join(data_dir, 'test-eve.fif')\n\n\ndef test_scaler():\n \"\"\"Test methods of Scaler\n \"\"\"\n raw = io.read_raw_fif(raw_fname, preload=False)\n events = read_events(event_name)\n picks = pick_types(raw.info, meg=True, stim=False, ecg=False,\n eog=False, exclude='bads')\n picks = picks[1:13:3]\n\n epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks,\n baseline=(None, 0), preload=True)\n epochs_data = epochs.get_data()\n scaler = Scaler(epochs.info)\n y = epochs.events[:, -1]\n\n # np invalid divide value warnings\n with warnings.catch_warnings(record=True):\n X = scaler.fit_transform(epochs_data, y)\n assert_true(X.shape == epochs_data.shape)\n X2 = scaler.fit(epochs_data, y).transform(epochs_data)\n\n assert_array_equal(X2, X)\n\n # Test inverse_transform\n with warnings.catch_warnings(record=True): # invalid value in mult\n Xi = scaler.inverse_transform(X, y)\n assert_array_equal(epochs_data, Xi)\n\n # Test init exception\n assert_raises(ValueError, scaler.fit, epochs, y)\n assert_raises(ValueError, scaler.transform, epochs, y)\n\n\ndef test_filterestimator():\n \"\"\"Test methods of FilterEstimator\n \"\"\"\n raw = io.read_raw_fif(raw_fname, preload=False)\n events = read_events(event_name)\n picks = pick_types(raw.info, meg=True, stim=False, ecg=False,\n eog=False, exclude='bads')\n picks = picks[1:13:3]\n epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks,\n baseline=(None, 0), preload=True)\n epochs_data = epochs.get_data()\n\n # Add tests for different combinations of l_freq and h_freq\n filt = FilterEstimator(epochs.info, l_freq=1, h_freq=40)\n y = epochs.events[:, -1]\n with warnings.catch_warnings(record=True): # stop freq attenuation warning\n X = filt.fit_transform(epochs_data, y)\n assert_true(X.shape == epochs_data.shape)\n assert_array_equal(filt.fit(epochs_data, y).transform(epochs_data), X)\n\n filt = FilterEstimator(epochs.info, l_freq=0, h_freq=40)\n y = epochs.events[:, -1]\n with warnings.catch_warnings(record=True): # stop freq attenuation warning\n X = filt.fit_transform(epochs_data, y)\n\n filt = FilterEstimator(epochs.info, l_freq=1, h_freq=1)\n y = epochs.events[:, -1]\n with warnings.catch_warnings(record=True): # stop freq attenuation warning\n assert_raises(ValueError, filt.fit_transform, epochs_data, y)\n\n filt = FilterEstimator(epochs.info, l_freq=1, h_freq=None)\n with warnings.catch_warnings(record=True): # stop freq attenuation warning\n X = filt.fit_transform(epochs_data, y)\n\n # Test init exception\n assert_raises(ValueError, filt.fit, epochs, y)\n assert_raises(ValueError, filt.transform, epochs, y)\n\n\ndef test_psdestimator():\n \"\"\"Test methods of PSDEstimator\n \"\"\"\n raw = io.read_raw_fif(raw_fname, preload=False)\n events = read_events(event_name)\n picks = pick_types(raw.info, meg=True, stim=False, ecg=False,\n eog=False, exclude='bads')\n picks = picks[1:13:3]\n epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks,\n baseline=(None, 0), preload=True)\n epochs_data = epochs.get_data()\n psd = PSDEstimator(2 * np.pi, 0, np.inf)\n y = epochs.events[:, -1]\n X = psd.fit_transform(epochs_data, y)\n\n assert_true(X.shape[0] == epochs_data.shape[0])\n assert_array_equal(psd.fit(epochs_data, y).transform(epochs_data), X)\n\n # Test init exception\n assert_raises(ValueError, psd.fit, epochs, y)\n assert_raises(ValueError, psd.transform, epochs, y)\n\n\ndef test_epochs_vectorizer():\n \"\"\"Test methods of EpochsVectorizer\n \"\"\"\n raw = io.read_raw_fif(raw_fname, preload=False)\n events = read_events(event_name)\n picks = pick_types(raw.info, meg=True, stim=False, ecg=False,\n eog=False, exclude='bads')\n picks = picks[1:13:3]\n with warnings.catch_warnings(record=True):\n epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks,\n baseline=(None, 0), preload=True)\n epochs_data = epochs.get_data()\n vector = EpochsVectorizer(epochs.info)\n y = epochs.events[:, -1]\n X = vector.fit_transform(epochs_data, y)\n\n # Check data dimensions\n assert_true(X.shape[0] == epochs_data.shape[0])\n assert_true(X.shape[1] == epochs_data.shape[1] * epochs_data.shape[2])\n\n assert_array_equal(vector.fit(epochs_data, y).transform(epochs_data), X)\n\n # Check if data is preserved\n n_times = epochs_data.shape[2]\n assert_array_equal(epochs_data[0, 0, 0:n_times], X[0, 0:n_times])\n\n # Check inverse transform\n Xi = vector.inverse_transform(X, y)\n assert_true(Xi.shape[0] == epochs_data.shape[0])\n assert_true(Xi.shape[1] == epochs_data.shape[1])\n assert_array_equal(epochs_data[0, 0, 0:n_times], Xi[0, 0, 0:n_times])\n\n # check if inverse transform works with different number of epochs\n Xi = vector.inverse_transform(epochs_data[0], y)\n assert_true(Xi.shape[1] == epochs_data.shape[1])\n assert_true(Xi.shape[2] == epochs_data.shape[2])\n\n # Test init exception\n assert_raises(ValueError, vector.fit, epochs, y)\n assert_raises(ValueError, vector.transform, epochs, y)\n", "# Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>\n# Denis Engemann <denis.engemann@gmail.com>\n# Martin Luessi <mluessi@nmr.mgh.harvard.edu>\n# Eric Larson <larson.eric.d@gmail.com>\n# Cathy Nangini <cnangini@gmail.com>\n# Mainak Jas <mainak@neuro.hut.fi>\n#\n# License: Simplified BSD\n\nimport os.path as op\nimport warnings\n\nimport numpy as np\nfrom numpy.testing import assert_raises\n\nfrom mne import (io, read_events, read_cov, read_source_spaces, read_evokeds,\n read_dipole, SourceEstimate)\nfrom mne.datasets import testing\nfrom mne.minimum_norm import read_inverse_operator\nfrom mne.viz import (plot_bem, plot_events, plot_source_spectrogram,\n plot_snr_estimate)\nfrom mne.utils import requires_nibabel, run_tests_if_main, slow_test\n\n# Set our plotters to test mode\nimport matplotlib\nmatplotlib.use('Agg') # for testing don't use X server\n\nwarnings.simplefilter('always') # enable b/c these tests throw warnings\n\ndata_path = testing.data_path(download=False)\nsubjects_dir = op.join(data_path, 'subjects')\ninv_fname = op.join(data_path, 'MEG', 'sample',\n 'sample_audvis_trunc-meg-eeg-oct-4-meg-inv.fif')\nevoked_fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis-ave.fif')\ndip_fname = op.join(data_path, 'MEG', 'sample',\n 'sample_audvis_trunc_set1.dip')\nbase_dir = op.join(op.dirname(__file__), '..', '..', 'io', 'tests', 'data')\nraw_fname = op.join(base_dir, 'test_raw.fif')\ncov_fname = op.join(base_dir, 'test-cov.fif')\nevent_fname = op.join(base_dir, 'test-eve.fif')\n\n\ndef _get_raw():\n return io.read_raw_fif(raw_fname, preload=True)\n\n\ndef _get_events():\n return read_events(event_fname)\n\n\ndef test_plot_cov():\n \"\"\"Test plotting of covariances\n \"\"\"\n raw = _get_raw()\n cov = read_cov(cov_fname)\n with warnings.catch_warnings(record=True): # bad proj\n fig1, fig2 = cov.plot(raw.info, proj=True, exclude=raw.ch_names[6:])\n\n\n@testing.requires_testing_data\n@requires_nibabel()\ndef test_plot_bem():\n \"\"\"Test plotting of BEM contours\n \"\"\"\n assert_raises(IOError, plot_bem, subject='bad-subject',\n subjects_dir=subjects_dir)\n assert_raises(ValueError, plot_bem, subject='sample',\n subjects_dir=subjects_dir, orientation='bad-ori')\n plot_bem(subject='sample', subjects_dir=subjects_dir,\n orientation='sagittal', slices=[25, 50])\n\n\ndef test_plot_events():\n \"\"\"Test plotting events\n \"\"\"\n event_labels = {'aud_l': 1, 'aud_r': 2, 'vis_l': 3, 'vis_r': 4}\n color = {1: 'green', 2: 'yellow', 3: 'red', 4: 'c'}\n raw = _get_raw()\n events = _get_events()\n plot_events(events, raw.info['sfreq'], raw.first_samp)\n plot_events(events, raw.info['sfreq'], raw.first_samp, equal_spacing=False)\n # Test plotting events without sfreq\n plot_events(events, first_samp=raw.first_samp)\n warnings.simplefilter('always', UserWarning)\n with warnings.catch_warnings(record=True):\n plot_events(events, raw.info['sfreq'], raw.first_samp,\n event_id=event_labels)\n plot_events(events, raw.info['sfreq'], raw.first_samp,\n color=color)\n plot_events(events, raw.info['sfreq'], raw.first_samp,\n event_id=event_labels, color=color)\n assert_raises(ValueError, plot_events, events, raw.info['sfreq'],\n raw.first_samp, event_id={'aud_l': 1}, color=color)\n assert_raises(ValueError, plot_events, events, raw.info['sfreq'],\n raw.first_samp, event_id={'aud_l': 111}, color=color)\n\n\n@testing.requires_testing_data\ndef test_plot_source_spectrogram():\n \"\"\"Test plotting of source spectrogram\n \"\"\"\n sample_src = read_source_spaces(op.join(subjects_dir, 'sample',\n 'bem', 'sample-oct-6-src.fif'))\n\n # dense version\n vertices = [s['vertno'] for s in sample_src]\n n_times = 5\n n_verts = sum(len(v) for v in vertices)\n stc_data = np.ones((n_verts, n_times))\n stc = SourceEstimate(stc_data, vertices, 1, 1)\n plot_source_spectrogram([stc, stc], [[1, 2], [3, 4]])\n assert_raises(ValueError, plot_source_spectrogram, [], [])\n assert_raises(ValueError, plot_source_spectrogram, [stc, stc],\n [[1, 2], [3, 4]], tmin=0)\n assert_raises(ValueError, plot_source_spectrogram, [stc, stc],\n [[1, 2], [3, 4]], tmax=7)\n\n\n@slow_test\n@testing.requires_testing_data\ndef test_plot_snr():\n \"\"\"Test plotting SNR estimate\n \"\"\"\n inv = read_inverse_operator(inv_fname)\n evoked = read_evokeds(evoked_fname, baseline=(None, 0))[0]\n plot_snr_estimate(evoked, inv)\n\n\n@testing.requires_testing_data\ndef test_plot_dipole_amplitudes():\n \"\"\"Test plotting dipole amplitudes\n \"\"\"\n dipoles = read_dipole(dip_fname)\n dipoles.plot_amplitudes(show=False)\n\nrun_tests_if_main()\n", "\"\"\"Base class copy from sklearn.base\"\"\"\n# Authors: Gael Varoquaux <gael.varoquaux@normalesup.org>\n# Romain Trachel <trachelr@gmail.com>\n# Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>\n#\n# License: BSD (3-clause)\n\nimport warnings\nimport numpy as np\n\nfrom ..externals.six import iteritems\nfrom ..fixes import _get_args\n\n\nclass BaseEstimator(object):\n \"\"\"Base class for all estimators in scikit-learn\n Notes\n -----\n All estimators should specify all the parameters that can be set\n at the class level in their ``__init__`` as explicit keyword\n arguments (no ``*args`` or ``**kwargs``).\n \"\"\"\n\n @classmethod\n def _get_param_names(cls):\n \"\"\"Get parameter names for the estimator\"\"\"\n # fetch the constructor or the original constructor before\n # deprecation wrapping if any\n init = getattr(cls.__init__, 'deprecated_original', cls.__init__)\n if init is object.__init__:\n # No explicit constructor to introspect\n return []\n\n # introspect the constructor arguments to find the model parameters\n # to represent\n args, varargs = _get_args(init, varargs=True)\n if varargs is not None:\n raise RuntimeError(\"scikit-learn estimators should always \"\n \"specify their parameters in the signature\"\n \" of their __init__ (no varargs).\"\n \" %s doesn't follow this convention.\"\n % (cls, ))\n # Remove 'self'\n # XXX: This is going to fail if the init is a staticmethod, but\n # who would do this?\n args.pop(0)\n args.sort()\n return args\n\n def get_params(self, deep=True):\n \"\"\"Get parameters for this estimator.\n\n Parameters\n ----------\n deep : boolean, optional\n If True, will return the parameters for this estimator and\n contained subobjects that are estimators.\n\n Returns\n -------\n params : mapping of string to any\n Parameter names mapped to their values.\n \"\"\"\n out = dict()\n for key in self._get_param_names():\n # We need deprecation warnings to always be on in order to\n # catch deprecated param values.\n # This is set in utils/__init__.py but it gets overwritten\n # when running under python3 somehow.\n warnings.simplefilter(\"always\", DeprecationWarning)\n try:\n with warnings.catch_warnings(record=True) as w:\n value = getattr(self, key, None)\n if len(w) and w[0].category == DeprecationWarning:\n # if the parameter is deprecated, don't show it\n continue\n finally:\n warnings.filters.pop(0)\n\n # XXX: should we rather test if instance of estimator?\n if deep and hasattr(value, 'get_params'):\n deep_items = value.get_params().items()\n out.update((key + '__' + k, val) for k, val in deep_items)\n out[key] = value\n return out\n\n def set_params(self, **params):\n \"\"\"Set the parameters of this estimator.\n The method works on simple estimators as well as on nested objects\n (such as pipelines). The former have parameters of the form\n ``<component>__<parameter>`` so that it's possible to update each\n component of a nested object.\n Returns\n -------\n self\n \"\"\"\n if not params:\n # Simple optimisation to gain speed (inspect is slow)\n return self\n valid_params = self.get_params(deep=True)\n for key, value in iteritems(params):\n split = key.split('__', 1)\n if len(split) > 1:\n # nested objects case\n name, sub_name = split\n if name not in valid_params:\n raise ValueError('Invalid parameter %s for estimator %s. '\n 'Check the list of available parameters '\n 'with `estimator.get_params().keys()`.' %\n (name, self))\n sub_object = valid_params[name]\n sub_object.set_params(**{sub_name: value})\n else:\n # simple objects case\n if key not in valid_params:\n raise ValueError('Invalid parameter %s for estimator %s. '\n 'Check the list of available parameters '\n 'with `estimator.get_params().keys()`.' %\n (key, self.__class__.__name__))\n setattr(self, key, value)\n return self\n\n def __repr__(self):\n class_name = self.__class__.__name__\n return '%s(%s)' % (class_name, _pprint(self.get_params(deep=False),\n offset=len(class_name),),)\n\n\n###############################################################################\ndef _pprint(params, offset=0, printer=repr):\n \"\"\"Pretty print the dictionary 'params'\n\n Parameters\n ----------\n params: dict\n The dictionary to pretty print\n offset: int\n The offset in characters to add at the beginning of each line.\n printer:\n The function to convert entries to strings, typically\n the builtin str or repr\n\n \"\"\"\n # Do a multi-line justified repr:\n options = np.get_printoptions()\n np.set_printoptions(precision=5, threshold=64, edgeitems=2)\n params_list = list()\n this_line_length = offset\n line_sep = ',\\n' + (1 + offset // 2) * ' '\n for i, (k, v) in enumerate(sorted(iteritems(params))):\n if type(v) is float:\n # use str for representing floating point numbers\n # this way we get consistent representation across\n # architectures and versions.\n this_repr = '%s=%s' % (k, str(v))\n else:\n # use repr of the rest\n this_repr = '%s=%s' % (k, printer(v))\n if len(this_repr) > 500:\n this_repr = this_repr[:300] + '...' + this_repr[-100:]\n if i > 0:\n if (this_line_length + len(this_repr) >= 75 or '\\n' in this_repr):\n params_list.append(line_sep)\n this_line_length = len(line_sep)\n else:\n params_list.append(', ')\n this_line_length += 2\n params_list.append(this_repr)\n this_line_length += len(this_repr)\n\n np.set_printoptions(**options)\n lines = ''.join(params_list)\n # Strip trailing space to avoid nightmare in doctests\n lines = '\\n'.join(l.rstrip(' ') for l in lines.split('\\n'))\n return lines\n\n\nclass LinearModel(BaseEstimator):\n \"\"\"\n This object clones a Linear Model from scikit-learn\n and updates the attributes for each fit. The linear model coefficients\n (filters) are used to extract discriminant neural sources from\n the measured data. This class implements the computation of patterns\n which provides neurophysiologically interpretable information [1],\n in the sense that significant nonzero weights are only observed at channels\n where activity is related to discriminant neural sources.\n\n Parameters\n ----------\n model : object | None\n A linear model from scikit-learn with a fit method\n that updates a coef_ attribute.\n If None the model will be LogisticRegression\n\n Attributes\n ----------\n filters_ : ndarray\n If fit, the filters used to decompose the data, else None.\n patterns_ : ndarray\n If fit, the patterns used to restore M/EEG signals, else None.\n\n Notes\n -----\n .. versionadded:: 0.10\n\n See Also\n --------\n ICA\n CSP\n xDawn\n\n References\n ----------\n [1] Haufe, S., Meinecke, F., Gorgen, K., Dahne, S., Haynes, J.-D.,\n Blankertz, B., & Biebmann, F. (2014). On the interpretation of\n weight vectors of linear models in multivariate neuroimaging.\n NeuroImage, 87, 96-110.\n \"\"\"\n def __init__(self, model=None):\n if model is None:\n from sklearn.linear_model import LogisticRegression\n model = LogisticRegression()\n\n self.model = model\n self.patterns_ = None\n self.filters_ = None\n\n def fit(self, X, y):\n \"\"\"Estimate the coefficients of the linear model.\n Save the coefficients in the attribute filters_ and\n computes the attribute patterns_ using [1].\n\n Parameters\n ----------\n X : array, shape (n_epochs, n_features)\n The data to estimate the coeffiscient.\n y : array, shape (n_epochs,)\n The class for each epoch.\n\n Returns\n -------\n self : instance of LinearModel\n Returns the modified instance.\n\n References\n ----------\n \"\"\"\n # fit the Model\n self.model.fit(X, y)\n # computes the patterns\n assert hasattr(self.model, 'coef_'), \\\n \"model needs a coef_ attribute to compute the patterns\"\n self.patterns_ = np.dot(X.T, np.dot(X, self.model.coef_.T))\n self.filters_ = self.model.coef_\n\n return self\n\n def transform(self, X, y=None):\n \"\"\"Transform the data using the linear model.\n\n Parameters\n ----------\n X : array, shape (n_epochs, n_features)\n The data to transform.\n y : array, shape (n_epochs,)\n The class for each epoch.\n\n Returns\n -------\n y_pred : array, shape (n_epochs,)\n Predicted class label per epoch.\n\n \"\"\"\n return self.model.transform(X)\n\n def fit_transform(self, X, y):\n \"\"\"Fit the data and transform it using the linear model.\n\n Parameters\n ----------\n X : array, shape (n_epochs, n_features)\n The data to transform.\n y : array, shape (n_epochs,)\n The class for each epoch.\n\n Returns\n -------\n y_pred : array, shape (n_epochs,)\n Predicted class label per epoch.\n\n \"\"\"\n return self.fit(X, y).transform(X)\n\n def predict(self, X):\n \"\"\"Computes predictions of y from X.\n\n Parameters\n ----------\n X : array, shape (n_epochs, n_features)\n The data used to compute the predictions.\n\n Returns\n -------\n y_pred : array, shape (n_epochs,)\n The predictions.\n \"\"\"\n return self.model.predict(X)\n\n def score(self, X, y):\n \"\"\"\n Returns the score of the linear model computed\n on the given test data.\n\n Parameters\n ----------\n X : array, shape (n_epochs, n_features)\n The data to transform.\n y : array, shape (n_epochs,)\n The class for each epoch.\n\n Returns\n -------\n score : float\n Score of the linear model\n\n \"\"\"\n return self.model.score(X, y)\n\n def plot_patterns(self, info, times=None, ch_type=None, layout=None,\n vmin=None, vmax=None, cmap='RdBu_r', sensors=True,\n colorbar=True, scale=None, scale_time=1e3, unit='a.u.',\n res=64, size=1, cbar_fmt='%3.1f',\n name_format='%01d ms', proj=False, show=True,\n show_names=False, title=None, mask=None,\n mask_params=None, outlines='head', contours=6,\n image_interp='bilinear', average=None, head_pos=None):\n \"\"\"\n Plot topographic patterns of the linear model.\n The patterns explain how the measured data was generated\n from the neural sources (a.k.a. the forward model).\n\n Parameters\n ----------\n info : instance of Info\n Info dictionary of the epochs used to fit the linear model.\n If not possible, consider using ``create_info``.\n times : float | array of floats | None.\n The time point(s) to plot. If None, the number of ``axes``\n determines the amount of time point(s). If ``axes`` is also None,\n 10 topographies will be shown with a regular time spacing between\n the first and last time instant.\n ch_type : 'mag' | 'grad' | 'planar1' | 'planar2' | 'eeg' | None\n The channel type to plot. For 'grad', the gradiometers are\n collected in pairs and the RMS for each pair is plotted.\n If None, then first available channel type from order given\n above is used. Defaults to None.\n layout : None | Layout\n Layout instance specifying sensor positions (does not need to be\n specified for Neuromag data). If possible, the correct layout file\n is inferred from the data; if no appropriate layout file was found\n the layout is automatically generated from the sensor locations.\n vmin : float | callable\n The value specfying the lower bound of the color range.\n If None, and vmax is None, -vmax is used. Else np.min(data).\n If callable, the output equals vmin(data).\n vmax : float | callable\n The value specfying the upper bound of the color range.\n If None, the maximum absolute value is used. If vmin is None,\n but vmax is not, defaults to np.min(data).\n If callable, the output equals vmax(data).\n cmap : matplotlib colormap | (colormap, bool) | 'interactive' | None\n Colormap to use. If tuple, the first value indicates the colormap\n to use and the second value is a boolean defining interactivity. In\n interactive mode the colors are adjustable by clicking and dragging\n the colorbar with left and right mouse button. Left mouse button\n moves the scale up and down and right mouse button adjusts the\n range. Hitting space bar resets the range. Up and down arrows can\n be used to change the colormap. If None, 'Reds' is used for all\n positive data, otherwise defaults to 'RdBu_r'. If 'interactive',\n translates to (None, True). Defaults to 'RdBu_r'.\n\n .. warning:: Interactive mode works smoothly only for a small\n amount of topomaps.\n\n sensors : bool | str\n Add markers for sensor locations to the plot. Accepts matplotlib\n plot format string (e.g., 'r+' for red plusses). If True,\n a circle will be used (via .add_artist). Defaults to True.\n colorbar : bool\n Plot a colorbar.\n scale : dict | float | None\n Scale the data for plotting. If None, defaults to 1e6 for eeg, 1e13\n for grad and 1e15 for mag.\n scale_time : float | None\n Scale the time labels. Defaults to 1e3.\n unit : dict | str | None\n The unit of the channel type used for colorbar label. If\n scale is None the unit is automatically determined.\n res : int\n The resolution of the topomap image (n pixels along each side).\n size : float\n Side length per topomap in inches.\n cbar_fmt : str\n String format for colorbar values.\n name_format : str\n String format for topomap values. Defaults to \"%03f ms\"\n proj : bool | 'interactive'\n If true SSP projections are applied before display.\n If 'interactive', a check box for reversible selection\n of SSP projection vectors will be show.\n show : bool\n Show figure if True.\n show_names : bool | callable\n If True, show channel names on top of the map. If a callable is\n passed, channel names will be formatted using the callable; e.g.,\n to delete the prefix 'MEG ' from all channel names, pass the\n function lambda x: x.replace('MEG ', ''). If `mask` is not None,\n only significant sensors will be shown.\n title : str | None\n Title. If None (default), no title is displayed.\n mask : ndarray of bool, shape (n_channels, n_times) | None\n The channels to be marked as significant at a given time point.\n Indices set to `True` will be considered. Defaults to None.\n mask_params : dict | None\n Additional plotting parameters for plotting significant sensors.\n Default (None) equals::\n\n dict(marker='o', markerfacecolor='w', markeredgecolor='k',\n linewidth=0, markersize=4)\n\n outlines : 'head' | 'skirt' | dict | None\n The outlines to be drawn. If 'head', the default head scheme will\n be drawn. If 'skirt' the head scheme will be drawn, but sensors are\n allowed to be plotted outside of the head circle. If dict, each key\n refers to a tuple of x and y positions, the values in 'mask_pos'\n will serve as image mask, and the 'autoshrink' (bool) field will\n trigger automated shrinking of the positions due to points outside\n the outline. Alternatively, a matplotlib patch object can be passed\n for advanced masking options, either directly or as a function that\n returns patches (required for multi-axis plots). If None, nothing\n will be drawn. Defaults to 'head'.\n contours : int | False | None\n The number of contour lines to draw.\n If 0, no contours will be drawn.\n image_interp : str\n The image interpolation to be used.\n All matplotlib options are accepted.\n average : float | None\n The time window around a given time to be used for averaging\n (seconds). For example, 0.01 would translate into window that\n starts 5 ms before and ends 5 ms after a given time point.\n Defaults to None, which means no averaging.\n head_pos : dict | None\n If None (default), the sensors are positioned such that they span\n the head circle. If dict, can have entries 'center' (tuple) and\n 'scale' (tuple) for what the center and scale of the head\n should be relative to the electrode locations.\n\n Returns\n -------\n fig : instance of matplotlib.figure.Figure\n The figure.\n \"\"\"\n\n from .. import EvokedArray\n\n if times is None:\n tmin = 0\n times = 'auto'\n else:\n tmin = times[0]\n\n # create an evoked\n patterns = EvokedArray(self.patterns_.reshape(info['nchan'], -1),\n info, tmin=tmin)\n # the call plot_topomap\n return patterns.plot_topomap(times=times, ch_type=ch_type,\n layout=layout, vmin=vmin, vmax=vmax,\n cmap=cmap, colorbar=colorbar, res=res,\n cbar_fmt=cbar_fmt, sensors=sensors,\n scale=scale, scale_time=scale_time,\n time_format=name_format, size=size,\n show_names=show_names, unit=unit,\n mask_params=mask_params,\n mask=mask, outlines=outlines,\n contours=contours, title=title,\n image_interp=image_interp, show=show,\n head_pos=head_pos)\n\n def plot_filters(self, info, times=None, ch_type=None, layout=None,\n vmin=None, vmax=None, cmap='RdBu_r', sensors=True,\n colorbar=True, scale=None, scale_time=1e3, unit='a.u.',\n res=64, size=1, cbar_fmt='%3.1f',\n name_format='%01d ms', proj=False, show=True,\n show_names=False, title=None, mask=None,\n mask_params=None, outlines='head', contours=6,\n image_interp='bilinear', average=None, head_pos=None):\n \"\"\"\n Plot topographic filters of the linear model.\n The filters are used to extract discriminant neural sources from\n the measured data (a.k.a. the backward model).\n\n Parameters\n ----------\n info : instance of Info\n Info dictionary of the epochs used to fit the linear model.\n If not possible, consider using ``create_info``.\n times : float | array of floats | None.\n The time point(s) to plot. If None, the number of ``axes``\n determines the amount of time point(s). If ``axes`` is also None,\n 10 topographies will be shown with a regular time spacing between\n the first and last time instant.\n ch_type : 'mag' | 'grad' | 'planar1' | 'planar2' | 'eeg' | None\n The channel type to plot. For 'grad', the gradiometers are\n collected in pairs and the RMS for each pair is plotted.\n If None, then first available channel type from order given\n above is used. Defaults to None.\n layout : None | Layout\n Layout instance specifying sensor positions (does not need to be\n specified for Neuromag data). If possible, the correct layout file\n is inferred from the data; if no appropriate layout file was found\n the layout is automatically generated from the sensor locations.\n vmin : float | callable\n The value specfying the lower bound of the color range.\n If None, and vmax is None, -vmax is used. Else np.min(data).\n If callable, the output equals vmin(data).\n vmax : float | callable\n The value specfying the upper bound of the color range.\n If None, the maximum absolute value is used. If vmin is None,\n but vmax is not, defaults to np.min(data).\n If callable, the output equals vmax(data).\n cmap : matplotlib colormap | (colormap, bool) | 'interactive' | None\n Colormap to use. If tuple, the first value indicates the colormap\n to use and the second value is a boolean defining interactivity. In\n interactive mode the colors are adjustable by clicking and dragging\n the colorbar with left and right mouse button. Left mouse button\n moves the scale up and down and right mouse button adjusts the\n range. Hitting space bar resets the range. Up and down arrows can\n be used to change the colormap. If None, 'Reds' is used for all\n positive data, otherwise defaults to 'RdBu_r'. If 'interactive',\n translates to (None, True). Defaults to 'RdBu_r'.\n\n .. warning:: Interactive mode works smoothly only for a small\n amount of topomaps.\n\n sensors : bool | str\n Add markers for sensor locations to the plot. Accepts matplotlib\n plot format string (e.g., 'r+' for red plusses). If True,\n a circle will be used (via .add_artist). Defaults to True.\n colorbar : bool\n Plot a colorbar.\n scale : dict | float | None\n Scale the data for plotting. If None, defaults to 1e6 for eeg, 1e13\n for grad and 1e15 for mag.\n scale_time : float | None\n Scale the time labels. Defaults to 1e3.\n unit : dict | str | None\n The unit of the channel type used for colorbar label. If\n scale is None the unit is automatically determined.\n res : int\n The resolution of the topomap image (n pixels along each side).\n size : float\n Side length per topomap in inches.\n cbar_fmt : str\n String format for colorbar values.\n name_format : str\n String format for topomap values. Defaults to \"%03f ms\"\n proj : bool | 'interactive'\n If true SSP projections are applied before display.\n If 'interactive', a check box for reversible selection\n of SSP projection vectors will be show.\n show : bool\n Show figure if True.\n show_names : bool | callable\n If True, show channel names on top of the map. If a callable is\n passed, channel names will be formatted using the callable; e.g.,\n to delete the prefix 'MEG ' from all channel names, pass the\n function lambda x: x.replace('MEG ', ''). If `mask` is not None,\n only significant sensors will be shown.\n title : str | None\n Title. If None (default), no title is displayed.\n mask : ndarray of bool, shape (n_channels, n_times) | None\n The channels to be marked as significant at a given time point.\n Indices set to `True` will be considered. Defaults to None.\n mask_params : dict | None\n Additional plotting parameters for plotting significant sensors.\n Default (None) equals::\n\n dict(marker='o', markerfacecolor='w', markeredgecolor='k',\n linewidth=0, markersize=4)\n\n outlines : 'head' | 'skirt' | dict | None\n The outlines to be drawn. If 'head', the default head scheme will\n be drawn. If 'skirt' the head scheme will be drawn, but sensors are\n allowed to be plotted outside of the head circle. If dict, each key\n refers to a tuple of x and y positions, the values in 'mask_pos'\n will serve as image mask, and the 'autoshrink' (bool) field will\n trigger automated shrinking of the positions due to points outside\n the outline. Alternatively, a matplotlib patch object can be passed\n for advanced masking options, either directly or as a function that\n returns patches (required for multi-axis plots). If None, nothing\n will be drawn. Defaults to 'head'.\n contours : int | False | None\n The number of contour lines to draw.\n If 0, no contours will be drawn.\n image_interp : str\n The image interpolation to be used.\n All matplotlib options are accepted.\n average : float | None\n The time window around a given time to be used for averaging\n (seconds). For example, 0.01 would translate into window that\n starts 5 ms before and ends 5 ms after a given time point.\n Defaults to None, which means no averaging.\n head_pos : dict | None\n If None (default), the sensors are positioned such that they span\n the head circle. If dict, can have entries 'center' (tuple) and\n 'scale' (tuple) for what the center and scale of the head\n should be relative to the electrode locations.\n\n Returns\n -------\n fig : instance of matplotlib.figure.Figure\n The figure.\n \"\"\"\n\n from .. import EvokedArray\n\n if times is None:\n tmin = 0\n times = 'auto'\n else:\n tmin = times[0]\n\n # create an evoked\n filters = EvokedArray(self.filters_.T.reshape(info['nchan'], -1),\n info, tmin=tmin)\n # the call plot_topomap\n return filters.plot_topomap(times=times, ch_type=ch_type,\n layout=layout, vmin=vmin, vmax=vmax,\n cmap=cmap, colorbar=colorbar, res=res,\n cbar_fmt=cbar_fmt, sensors=sensors,\n scale=scale, scale_time=scale_time,\n time_format=name_format, size=size,\n show_names=show_names, unit=unit,\n mask_params=mask_params,\n mask=mask, outlines=outlines,\n contours=contours, title=title,\n image_interp=image_interp, show=show,\n head_pos=head_pos)\n" ]
[ [ "numpy.testing.assert_array_equal" ], [ "matplotlib.use", "numpy.testing.assert_raises", "numpy.ones" ], [ "numpy.get_printoptions", "numpy.set_printoptions", "numpy.dot", "sklearn.linear_model.LogisticRegression" ] ]
dcmartin/digits
[ "4a16aef47226413eba232e268049678816281c7d" ]
[ "digits/extensions/data/objectDetection/utils.py" ]
[ "# Copyright (c) 2016-2017, NVIDIA CORPORATION. All rights reserved.\n\nimport csv\nimport os\n\nimport numpy as np\nimport PIL.Image\n\n\nclass ObjectType:\n\n Dontcare, Car, Van, Truck, Bus, Pickup, VehicleWithTrailer, SpecialVehicle,\\\n Person, Person_fa, Person_unsure, People, Cyclist, Tram, Person_Sitting,\\\n Misc = range(16)\n\n def __init__(self):\n pass\n\n\nclass Bbox:\n\n def __init__(self, x_left=0, y_top=0, x_right=0, y_bottom=0):\n self.xl = x_left\n self.yt = y_top\n self.xr = x_right\n self.yb = y_bottom\n\n def area(self):\n return (self.xr - self.xl) * (self.yb - self.yt)\n\n def width(self):\n return self.xr - self.xl\n\n def height(self):\n return self.yb - self.yt\n\n def get_array(self):\n return [self.xl, self.yt, self.xr, self.yb]\n\n\nclass GroundTruthObj:\n\n \"\"\" This class is the data ground-truth\n\n #Values Name Description\n ----------------------------------------------------------------------------\n 1 type Class ID\n 1 truncated Float from 0 (non-truncated) to 1 (truncated), where\n truncated refers to the object leaving image boundaries.\n -1 corresponds to a don't care region.\n 1 occluded Integer (-1,0,1,2) indicating occlusion state:\n -1 = unknown, 0 = fully visible,\n 1 = partly occluded, 2 = largely occluded\n 1 alpha Observation angle of object, ranging [-pi..pi]\n 4 bbox 2D bounding box of object in the image (0-based index):\n contains left, top, right, bottom pixel coordinates\n 3 dimensions 3D object dimensions: height, width, length (in meters)\n 3 location 3D object location x,y,z in camera coordinates (in meters)\n 1 rotation_y Rotation ry around Y-axis in camera coordinates [-pi..pi]\n 1 score Only for results: Float, indicating confidence in\n detection, needed for p/r curves, higher is better.\n\n Here, 'DontCare' labels denote regions in which objects have not been labeled,\n for example because they have been too far away from the laser scanner.\n \"\"\"\n\n # default class mappings\n OBJECT_TYPES = {\n 'bus': ObjectType.Bus,\n 'car': ObjectType.Car,\n 'cyclist': ObjectType.Cyclist,\n 'pedestrian': ObjectType.Person,\n 'people': ObjectType.People,\n 'person': ObjectType.Person,\n 'person_sitting': ObjectType.Person_Sitting,\n 'person-fa': ObjectType.Person_fa,\n 'person?': ObjectType.Person_unsure,\n 'pickup': ObjectType.Pickup,\n 'misc': ObjectType.Misc,\n 'special-vehicle': ObjectType.SpecialVehicle,\n 'tram': ObjectType.Tram,\n 'truck': ObjectType.Truck,\n 'van': ObjectType.Van,\n 'vehicle-with-trailer': ObjectType.VehicleWithTrailer}\n\n def __init__(self):\n self.stype = ''\n self.truncated = 0\n self.occlusion = 0\n self.angle = 0\n self.height = 0\n self.width = 0\n self.length = 0\n self.locx = 0\n self.locy = 0\n self.locz = 0\n self.roty = 0\n self.bbox = Bbox()\n self.object = ObjectType.Dontcare\n\n @classmethod\n def lmdb_format_length(cls):\n \"\"\"\n width of an LMDB datafield returned by the gt_to_lmdb_format function.\n :return:\n \"\"\"\n return 16\n\n def gt_to_lmdb_format(self):\n \"\"\"\n For storage of a bbox ground truth object into a float32 LMDB.\n Sort-by attribute is always the last value in the array.\n \"\"\"\n result = [\n # bbox in x,y,w,h format:\n self.bbox.xl,\n self.bbox.yt,\n self.bbox.xr - self.bbox.xl,\n self.bbox.yb - self.bbox.yt,\n # alpha angle:\n self.angle,\n # class number:\n self.object,\n 0,\n # Y axis rotation:\n self.roty,\n # bounding box attributes:\n self.truncated,\n self.occlusion,\n # object dimensions:\n self.length,\n self.width,\n self.height,\n self.locx,\n self.locy,\n # depth (sort-by attribute):\n self.locz,\n ]\n assert(len(result) is self.lmdb_format_length())\n return result\n\n def set_type(self):\n self.object = self.OBJECT_TYPES.get(self.stype, ObjectType.Dontcare)\n\n\nclass GroundTruth:\n \"\"\"\n this class loads the ground truth\n \"\"\"\n\n def __init__(self,\n label_dir,\n label_ext='.txt',\n label_delimiter=' ',\n min_box_size=None,\n class_mappings=None):\n self.label_dir = label_dir\n self.label_ext = label_ext # extension of label files\n self.label_delimiter = label_delimiter # space is used as delimiter in label files\n self._objects_all = dict() # positive bboxes across images\n self.min_box_size = min_box_size\n\n if class_mappings is not None:\n GroundTruthObj.OBJECT_TYPES = class_mappings\n\n def update_objects_all(self, _key, _bboxes):\n if _bboxes:\n self._objects_all[_key] = _bboxes\n else:\n self._objects_all[_key] = []\n\n def load_gt_obj(self):\n \"\"\" load bbox ground truth from files either via the provided label directory or list of label files\"\"\"\n files = os.listdir(self.label_dir)\n files = list(filter(lambda x: x.endswith(self.label_ext), files))\n if len(files) == 0:\n raise RuntimeError('error: no label files found in %s' % self.label_dir)\n for label_file in files:\n objects_per_image = list()\n with open(os.path.join(self.label_dir, label_file), 'rt') as flabel:\n for row in csv.reader(flabel, delimiter=self.label_delimiter):\n if len(row) == 0:\n # This can happen when you open an empty file\n continue\n if len(row) < 15:\n raise ValueError('Invalid label format in \"%s\"'\n % os.path.join(self.label_dir, label_file))\n\n # load data\n gt = GroundTruthObj()\n gt.stype = row[0].lower()\n gt.truncated = float(row[1])\n gt.occlusion = int(row[2])\n gt.angle = float(row[3])\n gt.bbox.xl = float(row[4])\n gt.bbox.yt = float(row[5])\n gt.bbox.xr = float(row[6])\n gt.bbox.yb = float(row[7])\n gt.height = float(row[8])\n gt.width = float(row[9])\n gt.length = float(row[10])\n gt.locx = float(row[11])\n gt.locy = float(row[12])\n gt.locz = float(row[13])\n gt.roty = float(row[14])\n gt.set_type()\n box_dimensions = [gt.bbox.xr - gt.bbox.xl, gt.bbox.yb - gt.bbox.yt]\n if self.min_box_size is not None:\n if not all(x >= self.min_box_size for x in box_dimensions):\n # object is smaller than threshold => set to \"DontCare\"\n gt.stype = ''\n gt.object = ObjectType.Dontcare\n objects_per_image.append(gt)\n key = os.path.splitext(label_file)[0]\n self.update_objects_all(key, objects_per_image)\n\n @property\n def objects_all(self):\n return self._objects_all\n\n# return the # of pixels remaining in a\n\n\ndef pad_bbox(arr, max_bboxes=64, bbox_width=16):\n if arr.shape[0] > max_bboxes:\n raise ValueError(\n 'Too many bounding boxes (%d > %d)' % arr.shape[0], max_bboxes\n )\n # fill remainder with zeroes:\n data = np.zeros((max_bboxes + 1, bbox_width), dtype='float')\n # number of bounding boxes:\n data[0][0] = arr.shape[0]\n # width of a bounding box:\n data[0][1] = bbox_width\n # bounding box data. Merge nothing if no bounding boxes exist.\n if arr.shape[0] > 0:\n data[1:1 + arr.shape[0]] = arr\n\n return data\n\n\ndef bbox_to_array(arr, label=0, max_bboxes=64, bbox_width=16):\n \"\"\"\n Converts a 1-dimensional bbox array to an image-like\n 3-dimensional array CHW array\n \"\"\"\n arr = pad_bbox(arr, max_bboxes, bbox_width)\n return arr[np.newaxis, :, :]\n\n\ndef bbox_overlap(abox, bbox):\n # the abox box\n x11 = abox[0]\n y11 = abox[1]\n x12 = abox[0] + abox[2] - 1\n y12 = abox[1] + abox[3] - 1\n\n # the closer box\n x21 = bbox[0]\n y21 = bbox[1]\n x22 = bbox[0] + bbox[2] - 1\n y22 = bbox[1] + bbox[3] - 1\n\n overlap_box_x2 = min(x12, x22)\n overlap_box_x1 = max(x11, x21)\n overlap_box_y2 = min(y12, y22)\n overlap_box_y1 = max(y11, y21)\n\n # make sure we preserve any non-bbox components\n overlap_box = list(bbox)\n overlap_box[0] = overlap_box_x1\n overlap_box[1] = overlap_box_y1\n overlap_box[2] = overlap_box_x2 - overlap_box_x1 + 1\n overlap_box[3] = overlap_box_y2 - overlap_box_y1 + 1\n\n xoverlap = max(0, overlap_box_x2 - overlap_box_x1)\n yoverlap = max(0, overlap_box_y2 - overlap_box_y1)\n overlap_pix = xoverlap * yoverlap\n\n return overlap_pix, overlap_box\n\n\ndef pad_image(img, padding_image_height, padding_image_width):\n \"\"\"\n pad a single image to the specified dimensions\n \"\"\"\n src_width = img.size[0]\n src_height = img.size[1]\n\n if padding_image_width < src_width:\n raise ValueError(\"Source image width %d is greater than padding width %d\" % (src_width, padding_image_width))\n\n if padding_image_height < src_height:\n raise ValueError(\"Source image height %d is greater than padding height %d\" %\n (src_height, padding_image_height))\n\n padded_img = PIL.Image.new(\n img.mode,\n (padding_image_width, padding_image_height),\n \"black\")\n padded_img.paste(img, (0, 0)) # copy to top-left corner\n\n return padded_img\n\n\ndef resize_bbox_list(bboxlist, rescale_x=1, rescale_y=1):\n # this is expecting x1,y1,w,h:\n bboxListNew = []\n for bbox in bboxlist:\n abox = bbox\n abox[0] *= rescale_x\n abox[1] *= rescale_y\n abox[2] *= rescale_x\n abox[3] *= rescale_y\n bboxListNew.append(abox)\n return bboxListNew\n" ]
[ [ "numpy.zeros" ] ]
jbburt/jburt
[ "7745491214ef2b665ca8d1fc526bc802a36985ff" ]
[ "jburt/mask.py" ]
[ "from typing import List\n\nimport numpy as np\n\n\ndef mask_nan(arrays: List[np.ndarray]) -> List[np.ndarray]:\n \"\"\"\n Drop indices from equal-sized arrays if the element at that index is NaN in\n any of the input arrays.\n\n Parameters\n ----------\n arrays : List[np.ndarray]\n list of ndarrays containing NaNs, to be masked\n\n Returns\n -------\n List[np.ndarray]\n masked arrays (free of NaNs)\n\n Notes\n -----\n This function find the indices where one or more elements is NaN in one or\n more of the input arrays, then drops those indices from all arrays.\n For example:\n >> a = np.array([0, 1, np.nan, 3])\n >> b = np.array([np.nan, 5, np.nan, 7])\n >> c = np.array([8, 9, 10, 11])\n >> mask_nan([a, b, c])\n [array([ 1., 3.]), array([ 5., 7.]), array([ 9, 11])]\n\n \"\"\"\n n = arrays[0].size\n assert all(a.size == n for a in arrays[1:])\n mask = np.array([False] * n)\n for arr in arrays:\n mask = np.logical_or(mask, np.isnan(arr))\n return [arr[np.where(~mask)[0]] for arr in arrays]\n" ]
[ [ "numpy.where", "numpy.array", "numpy.isnan" ] ]
LastRemote/amazon-sagemaker-examples
[ "e9adcb67289f5c177701e0bc8f1aea0c0910cdc7" ]
[ "reinforcement_learning/rl_deepracer_robomaker_coach_gazebo/src/markov/agent_ctrl/obstacles_agent_ctrl.py" ]
[ "'''This module implements concrete agent controllers for the rollout worker'''\nimport numpy as np\nimport os\nimport random\nimport rospkg\nimport rospy\n\nfrom gazebo_msgs.msg import ModelState\nfrom gazebo_msgs.srv import SetModelState, SpawnModel\nfrom markov.agent_ctrl.constants import ConfigParams, BOT_CAR_Z, OBSTACLE_Z\nfrom markov.track_geom.constants import SET_MODEL_STATE, SPAWN_SDF_MODEL, SPAWN_URDF_MODEL, ObstacleDimensions\nfrom markov.track_geom.track_data import TrackData\nfrom markov.agent_ctrl.agent_ctrl_interface import AgentCtrlInterface\nfrom markov.rospy_wrappers import ServiceProxyWrapper\nfrom markov import utils\nfrom markov.reset.constants import AgentInfo\nfrom markov.domain_randomizations.randomizer_manager import RandomizerManager\nfrom markov.domain_randomizations.visual.model_visual_randomizer import ModelVisualRandomizer\nfrom markov.domain_randomizations.constants import ModelRandomizerType\n\nclass ObstaclesCtrl(AgentCtrlInterface):\n def __init__(self):\n # Read ros parameters\n # OBJECT_POSITIONS will overwrite NUMBER_OF_OBSTACLES and RANDOMIZE_OBSTACLE_LOCATIONS\n self.object_locations = rospy.get_param(\"OBJECT_POSITIONS\", [])\n self.num_obstacles = int(rospy.get_param(\"NUMBER_OF_OBSTACLES\", 0)) \\\n if not self.object_locations else len(self.object_locations)\n self.min_obstacle_dist = float(rospy.get_param(\"MIN_DISTANCE_BETWEEN_OBSTACLES\", 2.0))\n self.randomize = utils.str2bool(rospy.get_param(\"RANDOMIZE_OBSTACLE_LOCATIONS\", False))\n self.use_bot_car = utils.str2bool(rospy.get_param(\"IS_OBSTACLE_BOT_CAR\", False))\n self.obstacle_names = [\"obstacle_{}\".format(i) for i in range(self.num_obstacles)]\n self.obstacle_dimensions = ObstacleDimensions.BOT_CAR_DIMENSION if self.use_bot_car \\\n else ObstacleDimensions.BOX_OBSTACLE_DIMENSION\n\n # track data\n self.track_data = TrackData.get_instance()\n\n # Wait for ros services\n rospy.wait_for_service(SET_MODEL_STATE)\n rospy.wait_for_service(SPAWN_SDF_MODEL)\n rospy.wait_for_service(SPAWN_URDF_MODEL)\n self.set_model_state = ServiceProxyWrapper(SET_MODEL_STATE, SetModelState)\n self.spawn_sdf_model = ServiceProxyWrapper(SPAWN_SDF_MODEL, SpawnModel)\n self.spawn_urdf_model = ServiceProxyWrapper(SPAWN_URDF_MODEL, SpawnModel)\n\n # Load the obstacle sdf/urdf\n obstacle_model_folder = \"bot_car\" if self.use_bot_car else \"box_obstacle\"\n rospack = rospkg.RosPack()\n deepracer_path = rospack.get_path(\"deepracer_simulation_environment\")\n obstacle_sdf_path = os.path.join(deepracer_path, \"models\", obstacle_model_folder, \"model.sdf\")\n with open(obstacle_sdf_path, \"r\") as fp:\n self.obstacle_sdf = fp.read()\n\n # Set obstacle poses and spawn the obstacles\n self.obstacle_poses = self._compute_obstacle_poses()\n self._spawn_obstacles()\n\n self._configure_randomizer()\n\n def _configure_randomizer(self):\n '''configure domain randomizer\n '''\n for obstacle_names in self.obstacle_names:\n RandomizerManager.get_instance().add(ModelVisualRandomizer(model_name=obstacle_names,\n model_randomizer_type=ModelRandomizerType.MODEL))\n\n def _compute_obstacle_poses(self):\n obstacle_dists = []\n obstacle_lanes = []\n lane_choices = (self.track_data.inner_lane, self.track_data.outer_lane)\n # use fix obstacle locations\n if self.object_locations:\n for object_location in self.object_locations:\n # index 0 is obstacle_ndist and index 1 is obstacle_lane\n object_location = object_location.split(\",\")\n obstacle_dists.append(float(object_location[0]) * \\\n self.track_data.center_line.length)\n # Inner lane is 1, outer lane is -1. If True, use outer lane\n obstacle_lanes.append(lane_choices[int(object_location[1]) == -1])\n else:\n # Start with equally spaced\n obstacle_start_dist = self.min_obstacle_dist\n obstacle_end_dist = self.track_data.center_line.length - 1.0\n obstacle_dists = np.linspace(obstacle_start_dist, obstacle_end_dist, self.num_obstacles)\n # Perturb to achieve randomness\n if self.randomize:\n i_obstacle = list(range(self.num_obstacles))\n random.shuffle(i_obstacle)\n for i in i_obstacle:\n lo = obstacle_start_dist if (i == 0) \\\n else obstacle_dists[i-1] + self.min_obstacle_dist\n hi = obstacle_end_dist if (i == self.num_obstacles-1) \\\n else obstacle_dists[i+1] - self.min_obstacle_dist\n if lo < hi:\n obstacle_dists[i] = random.uniform(lo, hi)\n\n # Select a random lane for each obstacle\n for _ in obstacle_dists:\n use_outer_lane = random.choice((False, True))\n obstacle_lanes.append(lane_choices[use_outer_lane])\n else:\n # Alternate between lanes for each obstacle\n use_outer_lane = False\n for _ in obstacle_dists:\n obstacle_lanes.append(lane_choices[use_outer_lane])\n use_outer_lane = not use_outer_lane\n\n # Compute the obstacle poses\n obstacle_poses = []\n for obstacle_dist, obstacle_lane in zip(obstacle_dists, obstacle_lanes):\n obstacle_pose = obstacle_lane.interpolate_pose(\n obstacle_lane.project(self.track_data.center_line.interpolate(obstacle_dist)))\n if self.use_bot_car:\n obstacle_pose.position.z = BOT_CAR_Z\n else:\n obstacle_pose.position.z = OBSTACLE_Z\n obstacle_poses.append(obstacle_pose)\n\n # Return the poses\n return obstacle_poses\n\n def _spawn_obstacles(self):\n for obstacle_name, obstacle_pose in zip(self.obstacle_names, self.obstacle_poses):\n self.spawn_sdf_model(obstacle_name, self.obstacle_sdf, '/{}'.format(obstacle_name),\n obstacle_pose, '')\n self.track_data.initialize_object(obstacle_name, obstacle_pose,\n self.obstacle_dimensions)\n\n def _reset_obstacles(self):\n for obstacle_name, obstacle_pose in zip(self.obstacle_names, self.obstacle_poses):\n obstacle_state = ModelState()\n obstacle_state.model_name = obstacle_name\n obstacle_state.pose = obstacle_pose\n obstacle_state.twist.linear.x = 0\n obstacle_state.twist.linear.y = 0\n obstacle_state.twist.linear.z = 0\n obstacle_state.twist.angular.x = 0\n obstacle_state.twist.angular.y = 0\n obstacle_state.twist.angular.z = 0\n self.set_model_state(obstacle_state)\n self.track_data.reset_object(obstacle_name, obstacle_pose)\n\n @property\n def action_space(self):\n return None\n\n def reset_agent(self):\n self.obstacle_poses = self._compute_obstacle_poses()\n self._reset_obstacles()\n\n def send_action(self, action):\n pass\n\n def update_agent(self, action):\n return {}\n\n def judge_action(self, agents_info_map):\n for agent_name, agent_info in agents_info_map.items():\n # check racecar crash with a obstacle\n crashed_object_name = agent_info[AgentInfo.CRASHED_OBJECT_NAME.value] \\\n if AgentInfo.CRASHED_OBJECT_NAME.value in agent_info else ''\n # only trainable racecar agent has 'obstacle' as possible crashed object\n if 'obstacle' in crashed_object_name:\n self._reset_obstacles()\n break\n return None, None, None\n\n def finish_episode(self):\n pass\n" ]
[ [ "numpy.linspace" ] ]
zhaojunz/tensorflow
[ "d1415bdc03fcdb090752ab0c91ee529dc09eb4ee", "4ac9c09d5ca57a03b8daa5fb9e295947b1619854", "4ac9c09d5ca57a03b8daa5fb9e295947b1619854" ]
[ "tensorflow/python/kernel_tests/batch_matmul_op_test.py", "tensorflow/python/ops/script_ops.py", "tensorflow/python/saved_model/saved_model_test.py" ]
[ "# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for tensorflow.ops.tf.BatchMatMul.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import gradient_checker\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.platform import test\n\n\nclass BatchMatmulOpTest(test.TestCase):\n\n # Uses numpy to compute batch_matmul(x, y, adjoint_a, adjoint_b).\n def _npBatchMatmul(self, x, y, adjoint_a, adjoint_b):\n # output's shape depends on adj[0] and adj[1]\n d0 = x.shape[-2] if not adjoint_a else x.shape[-1]\n d2 = y.shape[-1] if not adjoint_b else y.shape[-2]\n batch_dims = x.shape[:-2]\n num = np.prod(batch_dims)\n z = np.empty(list(batch_dims) + [d0, d2], dtype=x.dtype)\n xr = x.reshape([num, x.shape[-2], x.shape[-1]])\n yr = y.reshape([num, y.shape[-2], y.shape[-1]])\n zr = z.reshape([num, z.shape[-2], z.shape[-1]])\n for i in range(num):\n a = np.matrix(xr[i, :, :])\n if adjoint_a:\n a = a.transpose().conj()\n b = np.matrix(yr[i, :, :])\n if adjoint_b:\n b = b.transpose().conj()\n zr[i, :, :] = a * b\n return z\n\n # Test _npBatchMatMul works.\n def testNpVersion(self):\n x = np.array([0., 1., 2., 3.]).reshape([1, 2, 2])\n y = np.array([1., 2., 3., 4.]).reshape([1, 2, 2])\n z0 = self._npBatchMatmul(x, y, False, False)\n z1 = np.array([3., 4., 11., 16.]).reshape([1, 2, 2])\n self.assertTrue(np.array_equal(z0, z1))\n\n x = np.array([1., (1j), (-1.), (-1j)]).reshape([1, 2, 2])\n y = x * np.complex(1, 1) # rotate x 90 degree\n z0 = self._npBatchMatmul(x, y, False, False)\n z1 = np.array([2., (2.j), -2., (-2.j)]).reshape([1, 2, 2])\n self.assertTrue(np.array_equal(z0, z1))\n\n z0 = self._npBatchMatmul(x, y, False, True)\n z1 = np.array([(2. - 2.j), (-2. + 2.j), (-2. + 2.j), (2. - 2.j)]).reshape(\n [1, 2, 2])\n self.assertTrue(np.array_equal(z0, z1))\n\n z0 = self._npBatchMatmul(x, y, True, False)\n z1 = np.array([(2. + 2.j), (-2. + 2.j), (2. - 2.j), (2. + 2.j)]).reshape(\n [1, 2, 2])\n self.assertTrue(np.array_equal(z0, z1))\n\n # Compares _tfpBatchMatmul(x, y, alpha, adj) and _npBatchMatMul(x, y, alpha,\n # adj)\n def _compare(self, x_in, y_in, adjoint_a, adjoint_b, static_shape=True):\n x_t_shape = x_in.shape[:-2] + (x_in.shape[-1], x_in.shape[-2])\n y_t_shape = y_in.shape[:-2] + (y_in.shape[-1], y_in.shape[-2])\n x = x_in if not adjoint_a else x_in.reshape(x_t_shape)\n y = y_in if not adjoint_b else y_in.reshape(y_t_shape)\n is_floating = x.dtype != np.int32\n tol = 100 * np.finfo(x.dtype).eps if is_floating else 0\n with self.test_session(use_gpu=is_floating) as sess:\n if static_shape:\n z0 = math_ops.matmul(x, y, adjoint_a=adjoint_a, adjoint_b=adjoint_b)\n z0_val = z0.eval()\n else:\n x_ph = array_ops.placeholder(x.dtype)\n y_ph = array_ops.placeholder(y.dtype)\n z0 = math_ops.matmul(\n x_ph, y_ph, adjoint_a=adjoint_a, adjoint_b=adjoint_b)\n z0_val = sess.run(z0, feed_dict={x_ph: x, y_ph: y})\n z1 = self._npBatchMatmul(x, y, adjoint_a, adjoint_b)\n self.assertAllClose(z0_val, z1, rtol=tol, atol=tol)\n\n def _rand(self, shape, dtype):\n vals = np.array(np.random.normal(-10, 10, np.prod(shape)), dtype=dtype)\n if dtype in (np.complex64, np.complex128):\n imag = np.array(np.random.normal(-10, 10, np.prod(shape)), dtype=dtype)\n vals += 1j * imag\n return vals.reshape(shape)\n\n def _testNonEmpty(self, dtype, adjoint_a, adjoint_b, use_static_shape):\n\n def compareNonEmpty(self, a_shape, b_shape):\n self._compare(\n self._rand(a_shape, dtype),\n self._rand(b_shape, dtype), adjoint_a, adjoint_b, use_static_shape)\n\n compareNonEmpty(self, [1, 2, 3], [1, 3, 5])\n compareNonEmpty(self, [1, 2, 3], [1, 3, 1])\n compareNonEmpty(self, [1, 2, 3], [1, 3, 5])\n compareNonEmpty(self, [7, 1, 3], [7, 3, 5])\n compareNonEmpty(self, [7, 2, 3], [7, 3, 1])\n compareNonEmpty(self, [7, 2, 3], [7, 3, 5])\n compareNonEmpty(self, [10, 64, 75], [10, 75, 30])\n compareNonEmpty(self, [5, 7, 2, 3], [5, 7, 3, 5])\n\n def _testEmpty(self, dtype, adjoint_a, adjoint_b, use_static_shape):\n\n def compareEmpty(self, a_shape, b_shape):\n self._compare(\n np.zeros(a_shape).astype(dtype),\n np.zeros(b_shape).astype(dtype), adjoint_a, adjoint_b,\n use_static_shape)\n\n compareEmpty(self, [0, 3, 2], [0, 2, 4])\n compareEmpty(self, [3, 0, 2], [3, 2, 5])\n compareEmpty(self, [3, 3, 2], [3, 2, 0])\n\n\ndef _GetBatchMatmulOpTest(dtype, adjoint_a, adjoint_b, use_static_shape):\n\n def Test(self):\n np.random.seed(42)\n self._testNonEmpty(dtype, adjoint_a, adjoint_b, use_static_shape)\n self._testEmpty(dtype, adjoint_a, adjoint_b, use_static_shape)\n\n return Test\n\n\nclass BatchMatmulGradientTest(test.TestCase):\n\n # loss = sum(batch_matmul(x, y)). Verify dl/dx and dl/dy via the\n # gradient checker.\n def _checkGrad(self, x_in, y_in, adjoint_a, adjoint_b):\n x_t_shape = x_in.shape[:-2] + (x_in.shape[-1], x_in.shape[-2])\n y_t_shape = y_in.shape[:-2] + (y_in.shape[-1], y_in.shape[-2])\n x = x_in if not adjoint_a else x_in.reshape(x_t_shape)\n y = y_in if not adjoint_b else y_in.reshape(y_t_shape)\n epsilon = np.finfo(x.dtype).eps\n delta = epsilon**(1.0 / 3.0)\n with self.test_session(use_gpu=True):\n inx = constant_op.constant(x)\n iny = constant_op.constant(y)\n z = math_ops.matmul(inx, iny, adjoint_a, adjoint_b)\n loss = math_ops.reduce_sum(z)\n ((x_jacob_t, x_jacob_n),\n (y_jacob_t, y_jacob_n)) = gradient_checker.compute_gradient(\n [inx, iny], [x.shape, y.shape],\n loss, [1],\n x_init_value=[x, y],\n delta=delta)\n tol = 20 * delta\n self.assertAllClose(x_jacob_t, x_jacob_n, rtol=tol, atol=tol)\n self.assertAllClose(y_jacob_t, y_jacob_n, rtol=tol, atol=tol)\n\n # Tests a batched matmul of x, and y: x is a 3D tensor of shape [b,\n # n, k] y is a 3D tensor of shape [b, k, m] the batched matmul\n # computes z of shape [b, n, m], where z[i, :, :] = x[i, :, :]\n # matmul y[i, :, :]\n def _compare(self, b, n, k, m, dtype, adjoint_a, adjoint_b):\n np.random.seed(42)\n x = np.random.normal(0, 1, b * n * k).astype(dtype).reshape([b, n, k])\n if dtype in (np.complex64, np.complex128):\n x.imag = np.random.normal(0, 1,\n b * n * k).astype(dtype).reshape([b, n, k])\n y = np.random.normal(0, 1, b * k * m).astype(dtype).reshape([b, k, m])\n if dtype in (np.complex64, np.complex128):\n y.imag = np.random.normal(0, 1,\n b * k * m).astype(dtype).reshape([b, k, m])\n self._checkGrad(x, y, adjoint_a, adjoint_b)\n\n\ndef _GetBatchMatmulGradientTest(dtype, adjoint_a, adjoint_b):\n\n def Test(self):\n self._compare(1, 2, 3, 5, dtype, adjoint_a, adjoint_b)\n self._compare(3, 4, 7, 10, dtype, adjoint_a, adjoint_b)\n\n return Test\n\n\nif __name__ == \"__main__\":\n for dtype_ in [\n np.float16, np.float32, np.float64, np.complex64, np.complex128, np.int32\n ]:\n for adjoint_a_ in False, True:\n for adjoint_b_ in False, True:\n name = \"%s_%s_%s\" % (dtype_.__name__, adjoint_a_, adjoint_b_)\n for use_static_shape in True, False:\n setattr(BatchMatmulOpTest,\n \"testBatchMatmulOp_\" + name + (\"_%s\" % use_static_shape),\n _GetBatchMatmulOpTest(dtype_, adjoint_a_, adjoint_b_,\n use_static_shape))\n if dtype_ is not np.int32:\n setattr(BatchMatmulGradientTest, \"testBatchMatmulGradient_\" + name,\n _GetBatchMatmulGradientTest(dtype_, adjoint_a_, adjoint_b_))\n test.main()\n", "# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"Script Language Operators. See the @{python/script_ops} guide.\n\n@@py_func\n\"\"\"\n\n# pylint: disable=g-bad-name\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport threading\n\nimport numpy as np\n\nfrom tensorflow.python import pywrap_tensorflow\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import gen_script_ops\n\n\nclass FuncRegistry(object):\n \"\"\"A helper class to keep track of registered py functions.\n\n FuncRegistry keeps a map from unique tokens (string) to python\n functions, which takes numpy arrays and outputs numpy arrays.\n \"\"\"\n\n def __init__(self):\n self._lock = threading.Lock()\n self._unique_id = 0 # GUARDED_BY(self._lock)\n self._funcs = {}\n\n def insert(self, func):\n \"\"\"Registers `func` and returns a unique token for this entry.\"\"\"\n token = self._next_unique_token()\n self._funcs[token] = func\n return token\n\n def remove(self, token):\n \"\"\"Removes the registered function corresponding to `token`.\"\"\"\n self._funcs.pop(token, None)\n\n @staticmethod\n def _convert(value):\n \"\"\"Converts an arg to numpy, avoiding dangerous string and unicode dtypes.\n\n Numpy pads with zeros when using string and unicode dtypes if different\n components of a tensor have different lengths. This is bad: ignoring the\n padding is wrong for text data, and removing the padding is wrong for binary\n data. To avoid this bug, we redo the conversion using an object dtype.\n\n Args:\n value: Value to convert to a numpy array.\n\n Returns:\n A numpy array.\n \"\"\"\n result = np.asarray(value, order=\"C\")\n if result.dtype.char in \"SU\" and result is not value:\n return np.asarray(value, order=\"C\", dtype=object)\n return result\n\n def __call__(self, token, args):\n \"\"\"Calls the registered function for `token` with args.\"\"\"\n func = self._funcs[token]\n if func is None:\n raise ValueError(\"callback %s is not found\" % token)\n ret = func(*args)\n # Ensures that we return either a single numpy array or a list of numpy\n # arrays.\n if isinstance(ret, (tuple, list)):\n return [self._convert(x) for x in ret]\n else:\n return self._convert(ret)\n\n def size(self):\n \"\"\"Returns how many functions are currently registered.\"\"\"\n return len(self._funcs)\n\n def _next_unique_token(self):\n \"\"\"Returns a unique token.\"\"\"\n with self._lock:\n uid = self._unique_id\n self._unique_id += 1\n return \"pyfunc_%d\" % uid\n\n# Global registry for py functions.\n_py_funcs = FuncRegistry()\n\npywrap_tensorflow.InitializePyTrampoline(_py_funcs)\n\n\nclass CleanupFunc(object):\n \"\"\"A helper class to remove a registered function from _py_funcs.\"\"\"\n\n def __init__(self, token):\n self._token = token\n\n def __del__(self):\n _py_funcs.remove(self._token)\n\n\ndef py_func(func, inp, Tout, stateful=True, name=None):\n \"\"\"Wraps a python function and uses it as a TensorFlow op.\n\n Given a python function `func`, which takes numpy arrays as its\n inputs and returns numpy arrays as its outputs, wrap this function as an\n operation in a TensorFlow graph. The following snippet constructs a simple\n TensorFlow graph that invokes the `np.sinh()` NumPy function as a operation\n in the graph:\n\n ```python\n def my_func(x):\n # x will be a numpy array with the contents of the placeholder below\n return np.sinh(x)\n inp = tf.placeholder(tf.float32)\n y = tf.py_func(my_func, [inp], tf.float32)\n ```\n\n **N.B.** The `tf.py_func()` operation has the following known limitations:\n\n * The body of the function (i.e. `func`) will not be serialized in a\n `GraphDef`. Therefore, you should not use this function if you need to\n serialize your model and restore it in a different environment.\n\n * The operation must run in the same address space as the Python program\n that calls `tf.py_func()`. If you are using distributed TensorFlow, you\n must run a `tf.train.Server` in the same process as the program that calls\n `tf.py_func()` and you must pin the created operation to a device in that\n server (e.g. using `with tf.device():`).\n\n Args:\n func: A Python function, which accepts a list of NumPy `ndarray` objects\n having element types that match the corresponding `tf.Tensor` objects\n in `inp`, and returns a list of `ndarray` objects (or a single `ndarray`)\n having element types that match the corresponding values in `Tout`.\n inp: A list of `Tensor` objects.\n Tout: A list or tuple of tensorflow data types or a single tensorflow data\n type if there is only one, indicating what `func` returns.\n stateful: (Boolean.) If True, the function should be considered stateful.\n If a function is stateless, when given the same input it will return the\n same output and have no observable side effects. Optimizations such as\n common subexpression elimination are only performed on stateless\n operations.\n name: A name for the operation (optional).\n\n Returns:\n A list of `Tensor` or a single `Tensor` which `func` computes.\n \"\"\"\n token = _py_funcs.insert(func)\n # We tie the registered function's life-time with the current\n # default graph. I.e., when the current graph is destroyed, we\n # should remove its py funcs.\n cleanup = CleanupFunc(token)\n g = ops.get_default_graph()\n # pylint: disable=protected-access\n #\n # TODO(zhifengc): Consider adding a Graph method to collect\n # `cleanup` objects in one of its member.\n if not hasattr(g, \"_cleanup_py_funcs_used_in_graph\"):\n g._cleanup_py_funcs_used_in_graph = []\n\n # When g is destroyed, elements in _cleanup_py_funcs_used_in_graph\n # will be destroyed and their __del__ will remove the 'token' from\n # the funcs registry.\n g._cleanup_py_funcs_used_in_graph.append(cleanup)\n\n if isinstance(Tout, (list, tuple)):\n is_list_or_tuple = True\n else:\n Tout = [Tout]\n is_list_or_tuple = False\n if stateful:\n result = gen_script_ops._py_func(\n input=inp, token=token, Tout=Tout, name=name)\n # pylint: enable=protected-access\n else:\n result = gen_script_ops._py_func_stateless(\n input=inp, token=token, Tout=Tout, name=name)\n # pylint: enable=protected-access\n return result if is_list_or_tuple else result[0]\n\n\nops.NotDifferentiable(\"PyFunc\")\nops.NotDifferentiable(\"PyFuncStateless\")\n", "## Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for SavedModel.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\n\nfrom tensorflow.core.framework import types_pb2\nfrom tensorflow.core.protobuf import config_pb2\nfrom tensorflow.core.protobuf import meta_graph_pb2\nfrom tensorflow.python.client import session\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.lib.io import file_io\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import state_ops\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.platform import test\nfrom tensorflow.python.saved_model import builder as saved_model_builder\nfrom tensorflow.python.saved_model import constants\nfrom tensorflow.python.saved_model import loader\nfrom tensorflow.python.saved_model import main_op\nfrom tensorflow.python.saved_model import signature_def_utils\nfrom tensorflow.python.saved_model import tag_constants\nfrom tensorflow.python.util import compat\n\nSAVED_MODEL_PATH = (\"cc/saved_model/testdata/half_plus_two/00000123\")\n\n\ndef tearDownModule():\n file_io.delete_recursively(test.get_temp_dir())\n\n\nclass SavedModelTest(test.TestCase):\n\n def _init_and_validate_variable(self, sess, variable_name, variable_value):\n v = variables.Variable(variable_value, name=variable_name)\n sess.run(variables.global_variables_initializer())\n self.assertEqual(variable_value, v.eval())\n\n def _build_asset_collection(self, asset_file_name, asset_file_contents,\n asset_file_tensor_name):\n asset_filepath = os.path.join(\n compat.as_bytes(test.get_temp_dir()), compat.as_bytes(asset_file_name))\n file_io.write_string_to_file(asset_filepath, asset_file_contents)\n asset_file_tensor = constant_op.constant(\n asset_filepath, name=asset_file_tensor_name)\n ops.add_to_collection(ops.GraphKeys.ASSET_FILEPATHS, asset_file_tensor)\n asset_collection = ops.get_collection(ops.GraphKeys.ASSET_FILEPATHS)\n return asset_collection\n\n def _validate_asset_collection(self, export_dir, graph_collection_def,\n expected_asset_file_name,\n expected_asset_file_contents,\n expected_asset_tensor_name):\n assets_any = graph_collection_def[constants.ASSETS_KEY].any_list.value\n asset = meta_graph_pb2.AssetFileDef()\n assets_any[0].Unpack(asset)\n assets_path = os.path.join(\n compat.as_bytes(export_dir),\n compat.as_bytes(constants.ASSETS_DIRECTORY),\n compat.as_bytes(expected_asset_file_name))\n actual_asset_contents = file_io.read_file_to_string(assets_path)\n self.assertEqual(expected_asset_file_contents,\n compat.as_text(actual_asset_contents))\n self.assertEqual(expected_asset_file_name, asset.filename)\n self.assertEqual(expected_asset_tensor_name, asset.tensor_info.name)\n\n def _validate_inputs_tensor_info(self, builder, tensor_info):\n with self.test_session(graph=ops.Graph()) as sess:\n self._init_and_validate_variable(sess, \"v\", 42)\n\n foo_signature = signature_def_utils.build_signature_def({\n \"foo_inputs\": tensor_info\n }, dict(), \"foo\")\n self.assertRaises(\n AssertionError,\n builder.add_meta_graph_and_variables,\n sess, [\"foo\"],\n signature_def_map={\"foo_key\": foo_signature})\n\n def _validate_outputs_tensor_info(self, builder, tensor_info):\n with self.test_session(graph=ops.Graph()) as sess:\n self._init_and_validate_variable(sess, \"v\", 42)\n\n foo_signature = signature_def_utils.build_signature_def(\n dict(), {\"foo_outputs\": tensor_info}, \"foo\")\n self.assertRaises(\n AssertionError,\n builder.add_meta_graph_and_variables,\n sess, [\"foo\"],\n signature_def_map={\"foo_key\": foo_signature})\n\n def testMaybeSavedModelDir(self):\n base_path = test.test_src_dir_path(\"/python/saved_model\")\n self.assertFalse(loader.maybe_saved_model_directory(base_path))\n base_path = test.test_src_dir_path(SAVED_MODEL_PATH)\n self.assertTrue(loader.maybe_saved_model_directory(base_path))\n base_path = \"complete_garbage\"\n self.assertFalse(loader.maybe_saved_model_directory(base_path))\n\n def testBadSavedModelFileFormat(self):\n export_dir = os.path.join(test.get_temp_dir(),\n \"test_bad_saved_model_file_format\")\n # Attempt to load a SavedModel from an export directory that does not exist.\n with self.test_session(graph=ops.Graph()) as sess:\n with self.assertRaisesRegexp(IOError,\n \"SavedModel file does not exist at: %s\" %\n export_dir):\n loader.load(sess, [\"foo\"], export_dir)\n\n os.makedirs(export_dir)\n # Write an invalid binary proto to saved_model.pb.\n path_to_pb = os.path.join(export_dir, constants.SAVED_MODEL_FILENAME_PB)\n with open(path_to_pb, \"w\") as f:\n f.write(\"invalid content\")\n with self.test_session(graph=ops.Graph()) as sess:\n with self.assertRaisesRegexp(IOError, \"Cannot parse file.*%s\" %\n constants.SAVED_MODEL_FILENAME_PB):\n loader.load(sess, [\"foo\"], export_dir)\n\n # Cleanup the directory and start again.\n file_io.delete_recursively(export_dir)\n\n os.makedirs(export_dir)\n # Write an invalid text proto to saved_model.pbtxt\n path_to_pbtxt = os.path.join(export_dir,\n constants.SAVED_MODEL_FILENAME_PBTXT)\n with open(path_to_pbtxt, \"w\") as f:\n f.write(\"invalid content\")\n with self.test_session(graph=ops.Graph()) as sess:\n with self.assertRaisesRegexp(IOError, \"Cannot parse file.*%s\" %\n constants.SAVED_MODEL_FILENAME_PBTXT):\n loader.load(sess, [\"foo\"], export_dir)\n\n def testSequence(self):\n export_dir = os.path.join(test.get_temp_dir(), \"test_sequence\")\n builder = saved_model_builder.SavedModelBuilder(export_dir)\n\n # Expect an assertion error since add_meta_graph_and_variables() should be\n # invoked before any add_meta_graph() calls.\n with self.test_session(graph=ops.Graph()) as sess:\n self.assertRaises(AssertionError, builder.add_meta_graph, [\"foo\"])\n\n # Expect an assertion error for multiple calls of\n # add_meta_graph_and_variables() since weights should be saved exactly once.\n with self.test_session(graph=ops.Graph()) as sess:\n self._init_and_validate_variable(sess, \"v\", 42)\n builder.add_meta_graph_and_variables(sess, [\"bar\"])\n self.assertRaises(AssertionError, builder.add_meta_graph_and_variables,\n sess, [\"baz\"])\n\n def testTags(self):\n export_dir = os.path.join(test.get_temp_dir(), \"test_tags\")\n builder = saved_model_builder.SavedModelBuilder(export_dir)\n\n # Graph with a single variable. SavedModel invoked to:\n # - add with weights.\n # - a single tag (from predefined constants).\n with self.test_session(graph=ops.Graph()) as sess:\n self._init_and_validate_variable(sess, \"v\", 42)\n builder.add_meta_graph_and_variables(sess, [tag_constants.TRAINING])\n\n # Graph that updates the single variable. SavedModel invoked to:\n # - simply add the model (weights are not updated).\n # - a single tag (from predefined constants).\n with self.test_session(graph=ops.Graph()) as sess:\n self._init_and_validate_variable(sess, \"v\", 43)\n builder.add_meta_graph([tag_constants.SERVING])\n\n # Graph that updates the single variable. SavedModel is invoked:\n # - to add the model (weights are not updated).\n # - multiple custom tags.\n with self.test_session(graph=ops.Graph()) as sess:\n self._init_and_validate_variable(sess, \"v\", 44)\n builder.add_meta_graph([\"foo\", \"bar\"])\n\n # Save the SavedModel to disk.\n builder.save()\n\n # Restore the graph with a single predefined tag whose variables were saved.\n with self.test_session(graph=ops.Graph()) as sess:\n loader.load(sess, [tag_constants.TRAINING], export_dir)\n self.assertEqual(\n 42, ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES)[0].eval())\n\n # Restore the graph with a single predefined tag whose variables were not\n # saved.\n with self.test_session(graph=ops.Graph()) as sess:\n loader.load(sess, [tag_constants.SERVING], export_dir)\n self.assertEqual(\n 42, ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES)[0].eval())\n\n # Restore the graph with multiple tags. Provide duplicate tags to test set\n # semantics.\n with self.test_session(graph=ops.Graph()) as sess:\n loader.load(sess, [\"foo\", \"bar\", \"foo\"], export_dir)\n self.assertEqual(\n 42, ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES)[0].eval())\n\n # Try restoring a graph with a non-existent tag. This should yield a runtime\n # error.\n with self.test_session(graph=ops.Graph()) as sess:\n self.assertRaises(RuntimeError, loader.load, sess, [\"INVALID\"],\n export_dir)\n\n # Try restoring a graph where a subset of the tags match. Since tag matching\n # for meta graph defs follows \"all\" semantics, this should yield a runtime\n # error.\n with self.test_session(graph=ops.Graph()) as sess:\n self.assertRaises(RuntimeError, loader.load, sess, [\"foo\", \"baz\"],\n export_dir)\n\n def testVariables(self):\n export_dir = os.path.join(test.get_temp_dir(), \"test_variables\")\n builder = saved_model_builder.SavedModelBuilder(export_dir)\n\n # Graph with two variables. SavedModel invoked to:\n # - add with weights.\n with self.test_session(graph=ops.Graph()) as sess:\n self._init_and_validate_variable(sess, \"v1\", 1)\n self._init_and_validate_variable(sess, \"v2\", 2)\n builder.add_meta_graph_and_variables(sess, [\"foo\"])\n\n # Graph with a single variable (subset of the variables from the previous\n # graph whose weights were saved). SavedModel invoked to:\n # - simply add the model (weights are not updated).\n with self.test_session(graph=ops.Graph()) as sess:\n self._init_and_validate_variable(sess, \"v2\", 3)\n builder.add_meta_graph([\"bar\"])\n\n # Graph with a single variable (disjoint set of variables from the previous\n # graph whose weights were saved). SavedModel invoked to:\n # - simply add the model (weights are not updated).\n with self.test_session(graph=ops.Graph()) as sess:\n self._init_and_validate_variable(sess, \"v3\", 4)\n builder.add_meta_graph([\"baz\"])\n\n # Save the SavedModel to disk.\n builder.save()\n\n # Restore the graph with tag \"foo\", whose variables were saved.\n with self.test_session(graph=ops.Graph()) as sess:\n loader.load(sess, [\"foo\"], export_dir)\n collection_vars = ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES)\n self.assertEqual(len(collection_vars), 2)\n self.assertEqual(1, collection_vars[0].eval())\n self.assertEqual(2, collection_vars[1].eval())\n\n # Restore the graph with tag \"bar\", whose variables were not saved. Only the\n # subset of the variables added to the graph will be restored with the\n # checkpointed value.\n with self.test_session(graph=ops.Graph()) as sess:\n loader.load(sess, [\"bar\"], export_dir)\n collection_vars = ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES)\n self.assertEqual(len(collection_vars), 1)\n self.assertEqual(2, collection_vars[0].eval())\n\n # Try restoring the graph with tag \"baz\", whose variables were not saved.\n # Since this graph has a disjoint set of variables from the set that was\n # saved, this should raise an error.\n with self.test_session(graph=ops.Graph()) as sess:\n self.assertRaises(errors.NotFoundError, loader.load, sess, [\"baz\"],\n export_dir)\n\n def testGraphWithoutVariables(self):\n export_dir = os.path.join(test.get_temp_dir(), \"test_graph_has_variables\")\n builder = saved_model_builder.SavedModelBuilder(export_dir)\n\n # Graph with no variables.\n with self.test_session(graph=ops.Graph()) as sess:\n constant_5_name = constant_op.constant(5.0).name\n builder.add_meta_graph_and_variables(sess, [\"foo\"])\n\n # Second graph with no variables\n with self.test_session(graph=ops.Graph()) as sess:\n constant_6_name = constant_op.constant(6.0).name\n builder.add_meta_graph([\"bar\"])\n\n # Save the SavedModel to disk.\n builder.save()\n\n # Restore the graph with tag \"foo\".\n with self.test_session(graph=ops.Graph()) as sess:\n loader.load(sess, [\"foo\"], export_dir)\n # Read the constant a from the graph.\n a = ops.get_default_graph().get_tensor_by_name(constant_5_name)\n b = constant_op.constant(6.0)\n c = a * b\n self.assertEqual(30.0, sess.run(c))\n\n # Restore the graph with tag \"bar\".\n with self.test_session(graph=ops.Graph()) as sess:\n loader.load(sess, [\"bar\"], export_dir)\n # Read the constant a from the graph.\n a = ops.get_default_graph().get_tensor_by_name(constant_6_name)\n b = constant_op.constant(5.0)\n c = a * b\n self.assertEqual(30.0, sess.run(c))\n\n def testNoOverwrite(self):\n export_dir = os.path.join(test.get_temp_dir(), \"test_no_overwrite\")\n builder = saved_model_builder.SavedModelBuilder(export_dir)\n\n # Graph with a single variable. SavedModel invoked to:\n # - add with weights.\n with self.test_session(graph=ops.Graph()) as sess:\n self._init_and_validate_variable(sess, \"v\", 42)\n builder.add_meta_graph_and_variables(sess, [\"foo\"])\n\n # Save the SavedModel to disk in text format.\n builder.save(as_text=True)\n\n # Restore the graph with tag \"foo\", whose variables were saved.\n with self.test_session(graph=ops.Graph()) as sess:\n loader.load(sess, [\"foo\"], export_dir)\n self.assertEqual(\n 42, ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES)[0].eval())\n\n # An attempt to create another builder with the same export directory should\n # result in an assertion error.\n self.assertRaises(AssertionError, saved_model_builder.SavedModelBuilder,\n export_dir)\n\n def testSaveAsText(self):\n export_dir = os.path.join(test.get_temp_dir(), \"test_astext\")\n builder = saved_model_builder.SavedModelBuilder(export_dir)\n\n # Graph with a single variable. SavedModel invoked to:\n # - add with weights.\n with self.test_session(graph=ops.Graph()) as sess:\n self._init_and_validate_variable(sess, \"v\", 42)\n builder.add_meta_graph_and_variables(sess, [\"foo\"])\n\n # Graph with the same single variable. SavedModel invoked to:\n # - simply add the model (weights are not updated).\n with self.test_session(graph=ops.Graph()) as sess:\n self._init_and_validate_variable(sess, \"v\", 43)\n builder.add_meta_graph([\"bar\"])\n\n # Save the SavedModel to disk in text format.\n builder.save(as_text=True)\n\n # Restore the graph with tag \"foo\", whose variables were saved.\n with self.test_session(graph=ops.Graph()) as sess:\n loader.load(sess, [\"foo\"], export_dir)\n self.assertEqual(\n 42, ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES)[0].eval())\n\n # Restore the graph with tag \"bar\", whose variables were not saved.\n with self.test_session(graph=ops.Graph()) as sess:\n loader.load(sess, [\"bar\"], export_dir)\n self.assertEqual(\n 42, ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES)[0].eval())\n\n def testCollections(self):\n export_dir = os.path.join(test.get_temp_dir(), \"test_collections\")\n builder = saved_model_builder.SavedModelBuilder(export_dir)\n\n # Graph with a single variable added to a collection. SavedModel invoked to:\n # - add with weights.\n with self.test_session(graph=ops.Graph()) as sess:\n v = variables.Variable(42, name=\"v\")\n ops.add_to_collection(\"foo_vars\", v)\n sess.run(variables.global_variables_initializer())\n self.assertEqual(42, v.eval())\n builder.add_meta_graph_and_variables(sess, [\"foo\"])\n\n # Graph with the same single variable added to a different collection.\n # SavedModel invoked to:\n # - simply add the model (weights are not updated).\n with self.test_session(graph=ops.Graph()) as sess:\n v = variables.Variable(43, name=\"v\")\n ops.add_to_collection(\"bar_vars\", v)\n sess.run(variables.global_variables_initializer())\n self.assertEqual(43, v.eval())\n builder.add_meta_graph([\"bar\"])\n\n # Save the SavedModel to disk.\n builder.save()\n\n # Restore the graph with tag \"foo\", whose variables were saved. The\n # collection 'foo_vars' should contain a single element. The collection\n # 'bar_vars' should not be found.\n with self.test_session(graph=ops.Graph()) as sess:\n loader.load(sess, [\"foo\"], export_dir)\n collection_foo_vars = ops.get_collection(\"foo_vars\")\n self.assertEqual(len(collection_foo_vars), 1)\n self.assertEqual(42, collection_foo_vars[0].eval())\n\n self.assertEqual(len(ops.get_collection(\"bar_vars\")), 0)\n\n # Restore the graph with tag \"bar\", whose variables were not saved. The\n # collection-def exported as part of the meta graph def is updated to\n # reflect the new collection. The value of the variable in the\n # collection-def corresponds to the saved value (from the previous graph\n # with tag \"foo\").\n with self.test_session(graph=ops.Graph()) as sess:\n loader.load(sess, [\"bar\"], export_dir)\n collection_bar_vars = ops.get_collection(\"bar_vars\")\n self.assertEqual(len(collection_bar_vars), 1)\n self.assertEqual(42, collection_bar_vars[0].eval())\n\n self.assertEqual(len(ops.get_collection(\"foo_vars\")), 0)\n\n def testSignatureDefs(self):\n export_dir = os.path.join(test.get_temp_dir(), \"test_signature_defs\")\n builder = saved_model_builder.SavedModelBuilder(export_dir)\n\n # Graph with a single variable and a single entry in the signature def map.\n # SavedModel is invoked to add with weights.\n with self.test_session(graph=ops.Graph()) as sess:\n self._init_and_validate_variable(sess, \"v\", 42)\n # Build and populate an empty SignatureDef for testing.\n foo_signature = signature_def_utils.build_signature_def(dict(),\n dict(), \"foo\")\n builder.add_meta_graph_and_variables(\n sess, [\"foo\"], signature_def_map={\"foo_key\": foo_signature})\n\n # Graph with the same single variable and multiple entries in the signature\n # def map. No weights are saved by SavedModel.\n with self.test_session(graph=ops.Graph()) as sess:\n self._init_and_validate_variable(sess, \"v\", 43)\n # Build and populate a different SignatureDef for testing.\n bar_signature = signature_def_utils.build_signature_def(dict(),\n dict(), \"bar\")\n # Also, build a different SignatureDef corresponding to \"foo_key\" defined\n # in the previous graph.\n foo_new_signature = signature_def_utils.build_signature_def(dict(),\n dict(),\n \"foo_new\")\n builder.add_meta_graph(\n [\"bar\"],\n signature_def_map={\n \"bar_key\": bar_signature,\n \"foo_key\": foo_new_signature\n })\n\n # Save the SavedModel to disk.\n builder.save()\n\n # Restore the graph with tag \"foo\". The single entry in the SignatureDef map\n # corresponding to \"foo_key\" should exist.\n with self.test_session(graph=ops.Graph()) as sess:\n foo_graph = loader.load(sess, [\"foo\"], export_dir)\n self.assertEqual(\n 42, ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES)[0].eval())\n\n foo_signature = foo_graph.signature_def\n self.assertEqual(len(foo_signature), 1)\n self.assertEqual(\"foo\", foo_signature[\"foo_key\"].method_name)\n\n # Restore the graph with tag \"bar\". The SignatureDef map should have two\n # entries. One corresponding to \"bar_key\" and another corresponding to the\n # new value of \"foo_key\".\n with self.test_session(graph=ops.Graph()) as sess:\n bar_graph = loader.load(sess, [\"bar\"], export_dir)\n self.assertEqual(\n 42, ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES)[0].eval())\n\n bar_signature = bar_graph.signature_def\n self.assertEqual(len(bar_signature), 2)\n self.assertEqual(\"bar\", bar_signature[\"bar_key\"].method_name)\n self.assertEqual(\"foo_new\", bar_signature[\"foo_key\"].method_name)\n\n def testSignatureDefValidation(self):\n export_dir = os.path.join(test.get_temp_dir(),\n \"test_signature_def_validation\")\n builder = saved_model_builder.SavedModelBuilder(export_dir)\n\n tensor_without_name = meta_graph_pb2.TensorInfo()\n tensor_without_name.dtype = types_pb2.DT_FLOAT\n self._validate_inputs_tensor_info(builder, tensor_without_name)\n self._validate_outputs_tensor_info(builder, tensor_without_name)\n\n tensor_without_dtype = meta_graph_pb2.TensorInfo()\n tensor_without_dtype.name = \"x\"\n self._validate_inputs_tensor_info(builder, tensor_without_dtype)\n self._validate_outputs_tensor_info(builder, tensor_without_dtype)\n\n tensor_empty = meta_graph_pb2.TensorInfo()\n self._validate_inputs_tensor_info(builder, tensor_empty)\n self._validate_outputs_tensor_info(builder, tensor_empty)\n\n def testAssets(self):\n export_dir = os.path.join(test.get_temp_dir(), \"test_assets\")\n builder = saved_model_builder.SavedModelBuilder(export_dir)\n\n with self.test_session(graph=ops.Graph()) as sess:\n self._init_and_validate_variable(sess, \"v\", 42)\n\n # Build an asset collection.\n ignored_filepath = os.path.join(\n compat.as_bytes(test.get_temp_dir()), compat.as_bytes(\"ignored.txt\"))\n file_io.write_string_to_file(ignored_filepath, \"will be ignored\")\n\n asset_collection = self._build_asset_collection(\"hello42.txt\",\n \"foo bar baz\",\n \"asset_file_tensor\")\n\n builder.add_meta_graph_and_variables(\n sess, [\"foo\"], assets_collection=asset_collection)\n\n # Save the SavedModel to disk.\n builder.save()\n\n with self.test_session(graph=ops.Graph()) as sess:\n foo_graph = loader.load(sess, [\"foo\"], export_dir)\n self._validate_asset_collection(export_dir, foo_graph.collection_def,\n \"hello42.txt\", \"foo bar baz\",\n \"asset_file_tensor:0\")\n ignored_asset_path = os.path.join(\n compat.as_bytes(export_dir),\n compat.as_bytes(constants.ASSETS_DIRECTORY),\n compat.as_bytes(\"ignored.txt\"))\n self.assertFalse(file_io.file_exists(ignored_asset_path))\n\n def testCustomMainOp(self):\n export_dir = os.path.join(test.get_temp_dir(), \"test_main_op\")\n builder = saved_model_builder.SavedModelBuilder(export_dir)\n\n with self.test_session(graph=ops.Graph()) as sess:\n # Add `v1` and `v2` variables to the graph.\n v1 = variables.Variable(1, name=\"v1\")\n ops.add_to_collection(\"v\", v1)\n v2 = variables.Variable(2, name=\"v2\")\n ops.add_to_collection(\"v\", v2)\n\n # Initialize another variable `v3` to 42.\n v3 = variables.Variable(42, name=\"v3\")\n ops.add_to_collection(\"v\", v3)\n\n # Set up an assignment op to be run as part of the main_op.\n with ops.control_dependencies([main_op.main_op()]):\n add_v1_v2 = math_ops.add(v1._ref(), v2._ref())\n custom_main_op = control_flow_ops.group(state_ops.assign(v3, add_v1_v2))\n\n sess.run(custom_main_op)\n builder.add_meta_graph_and_variables(\n sess, [\"foo\"], main_op=custom_main_op)\n\n # Save the SavedModel to disk.\n builder.save()\n\n with self.test_session(graph=ops.Graph()) as sess:\n loader.load(sess, [\"foo\"], export_dir)\n self.assertEqual(1, ops.get_collection(\"v\")[0].eval())\n self.assertEqual(2, ops.get_collection(\"v\")[1].eval())\n # Evaluates to the sum of the first two variables and assigned as part of\n # the main_op, following a restore.\n self.assertEqual(3, ops.get_collection(\"v\")[2].eval())\n\n def testLegacyInitOp(self):\n export_dir = os.path.join(test.get_temp_dir(), \"test_legacy_init_op\")\n builder = saved_model_builder.SavedModelBuilder(export_dir)\n\n with self.test_session(graph=ops.Graph()) as sess:\n # Add `v1` and `v2` variables to the graph.\n v1 = variables.Variable(1, name=\"v1\")\n ops.add_to_collection(\"v\", v1)\n v2 = variables.Variable(2, name=\"v2\")\n ops.add_to_collection(\"v\", v2)\n\n # Initialize another variable `v3` to 42.\n v3 = variables.Variable(42, name=\"v3\", trainable=False, collections=[])\n ops.add_to_collection(\"v\", v3)\n\n # Set up an assignment op to be run as part of the legacy_init_op.\n assign_v3 = state_ops.assign(v3, math_ops.add(v1, v2))\n legacy_init_op = control_flow_ops.group(assign_v3, name=\"legacy_init_op\")\n\n sess.run(variables.global_variables_initializer())\n builder.add_meta_graph_and_variables(\n sess, [\"foo\"], legacy_init_op=legacy_init_op)\n\n # Save the SavedModel to disk.\n builder.save()\n\n with self.test_session(graph=ops.Graph()) as sess:\n loader.load(sess, [\"foo\"], export_dir)\n self.assertEqual(1, ops.get_collection(\"v\")[0].eval())\n self.assertEqual(2, ops.get_collection(\"v\")[1].eval())\n # Evaluates to the sum of the first two variables and assigned as part of\n # the legacy_init_op, following a restore.\n self.assertEqual(3, ops.get_collection(\"v\")[2].eval())\n\n def testMultipleAssets(self):\n export_dir = os.path.join(test.get_temp_dir(), \"test_multiple_assets\")\n builder = saved_model_builder.SavedModelBuilder(export_dir)\n\n with self.test_session(graph=ops.Graph()) as sess:\n self._init_and_validate_variable(sess, \"v\", 42)\n\n # Build an asset collection specific to `foo` graph.\n asset_collection = self._build_asset_collection(\"foo.txt\", \"content_foo\",\n \"asset_file_tensor\")\n\n # Add the asset collection as part of the graph with tag \"foo\".\n builder.add_meta_graph_and_variables(\n sess, [\"foo\"], assets_collection=asset_collection)\n\n with self.test_session(graph=ops.Graph()) as sess:\n self._init_and_validate_variable(sess, \"v\", 42)\n\n # Build an asset collection specific to `bar` graph.\n asset_collection = self._build_asset_collection(\"bar.txt\", \"content_bar\",\n \"asset_file_tensor\")\n\n # Add the asset collection as part of the graph with tag \"bar\".\n builder.add_meta_graph([\"bar\"], assets_collection=asset_collection)\n\n # Save the SavedModel to disk.\n builder.save()\n\n # Check assets restored for graph with tag \"foo\".\n with self.test_session(graph=ops.Graph()) as sess:\n foo_graph = loader.load(sess, [\"foo\"], export_dir)\n self._validate_asset_collection(export_dir, foo_graph.collection_def,\n \"foo.txt\", \"content_foo\",\n \"asset_file_tensor:0\")\n\n # Check assets restored for graph with tag \"bar\".\n with self.test_session(graph=ops.Graph()) as sess:\n bar_graph = loader.load(sess, [\"bar\"], export_dir)\n self._validate_asset_collection(export_dir, bar_graph.collection_def,\n \"bar.txt\", \"content_bar\",\n \"asset_file_tensor:0\")\n\n def testDuplicateAssets(self):\n export_dir = os.path.join(test.get_temp_dir(), \"test_duplicate_assets\")\n builder = saved_model_builder.SavedModelBuilder(export_dir)\n\n with self.test_session(graph=ops.Graph()) as sess:\n self._init_and_validate_variable(sess, \"v\", 42)\n\n # Build an asset collection with `foo.txt` that has `foo` specific\n # content.\n asset_collection = self._build_asset_collection(\"foo.txt\", \"content_foo\",\n \"asset_file_tensor\")\n\n # Add the asset collection as part of the graph with tag \"foo\".\n builder.add_meta_graph_and_variables(\n sess, [\"foo\"], assets_collection=asset_collection)\n\n with self.test_session(graph=ops.Graph()) as sess:\n self._init_and_validate_variable(sess, \"v\", 42)\n\n # Build an asset collection with `foo.txt` that has `bar` specific\n # content.\n asset_collection = self._build_asset_collection(\"foo.txt\", \"content_bar\",\n \"asset_file_tensor\")\n\n # Add the asset collection as part of the graph with tag \"bar\".\n builder.add_meta_graph([\"bar\"], assets_collection=asset_collection)\n\n # Save the SavedModel to disk.\n builder.save()\n\n # Check assets restored for graph with tag \"foo\".\n with self.test_session(graph=ops.Graph()) as sess:\n foo_graph = loader.load(sess, [\"foo\"], export_dir)\n self._validate_asset_collection(export_dir, foo_graph.collection_def,\n \"foo.txt\", \"content_foo\",\n \"asset_file_tensor:0\")\n\n # Check assets restored for graph with tag \"bar\".\n with self.test_session(graph=ops.Graph()) as sess:\n bar_graph = loader.load(sess, [\"bar\"], export_dir)\n\n # Validate the assets for `bar` graph. `foo.txt` should contain the\n # original contents corresponding to `foo` graph since an asset with the\n # same name across multiple graphs is only stored the first time\n self._validate_asset_collection(export_dir, bar_graph.collection_def,\n \"foo.txt\", \"content_foo\",\n \"asset_file_tensor:0\")\n\n def testOp(self):\n export_dir = os.path.join(test.get_temp_dir(), \"test_op\")\n builder = saved_model_builder.SavedModelBuilder(export_dir)\n\n with session.Session(\n graph=ops.Graph(),\n config=config_pb2.ConfigProto(device_count={\"CPU\": 2})) as sess:\n with sess.graph.device(\"/cpu:0\"):\n v1 = variables.Variable(1, name=\"v1\")\n with sess.graph.device(\"/cpu:1\"):\n v2 = variables.Variable(2, name=\"v2\")\n\n # v3 is an unsaved variable derived from v1 and v2. It is used to\n # exercise the ability to run an init op when restoring a graph.\n v3 = variables.Variable(1, name=\"v3\", trainable=False, collections=[])\n assign_v3 = state_ops.assign(v3, math_ops.add(v1, v2))\n init_op = control_flow_ops.group(assign_v3, name=\"init_op\")\n\n ops.add_to_collection(\"v\", v1)\n ops.add_to_collection(\"v\", v2)\n ops.add_to_collection(\"v\", v3)\n ops.add_to_collection(\"init_op\", init_op)\n\n sess.run(variables.global_variables_initializer())\n self.assertEqual(1, ops.get_collection(\"v\")[0].eval())\n self.assertEqual(2, ops.get_collection(\"v\")[1].eval())\n\n builder.add_meta_graph_and_variables(sess, [\"foo\"])\n\n # Save the SavedModel to disk.\n builder.save()\n\n with session.Session(\n graph=ops.Graph(),\n config=config_pb2.ConfigProto(device_count={\"CPU\": 2})) as sess:\n loader.load(sess, [\"foo\"], export_dir)\n\n # Validate variables, run the init op and verify result.\n self.assertEqual(1, ops.get_collection(\"v\")[0].eval())\n self.assertEqual(2, ops.get_collection(\"v\")[1].eval())\n ops.get_collection(\"init_op\")[0].run()\n self.assertEqual(3, ops.get_collection(\"v\")[2].eval())\n\n def testClearDevices(self):\n export_dir = os.path.join(test.get_temp_dir(), \"test_clear_devices\")\n builder = saved_model_builder.SavedModelBuilder(export_dir)\n\n # Specify a device and save a variable.\n ops.reset_default_graph()\n with session.Session(\n target=\"\",\n config=config_pb2.ConfigProto(device_count={\"CPU\": 2})) as sess:\n with sess.graph.device(\"/cpu:0\"):\n self._init_and_validate_variable(sess, \"v\", 42)\n builder.add_meta_graph_and_variables(\n sess, [tag_constants.TRAINING], clear_devices=True)\n\n # Save the SavedModel to disk.\n builder.save()\n\n # Restore the graph with a single predefined tag whose variables were saved\n # without any device information.\n with self.test_session(graph=ops.Graph()) as sess:\n loader.load(sess, [tag_constants.TRAINING], export_dir)\n self.assertEqual(\n 42, ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES)[0].eval())\n\n\nif __name__ == \"__main__\":\n test.main()\n" ]
[ [ "numpy.random.normal", "numpy.matrix", "numpy.array", "numpy.array_equal", "numpy.zeros", "numpy.random.seed", "tensorflow.python.ops.math_ops.matmul", "tensorflow.python.ops.gradient_checker.compute_gradient", "tensorflow.python.framework.constant_op.constant", "tensorflow.python.ops.math_ops.reduce_sum", "numpy.finfo", "numpy.prod", "tensorflow.python.ops.array_ops.placeholder", "numpy.complex", "tensorflow.python.platform.test.main" ], [ "numpy.asarray", "tensorflow.python.framework.ops.NotDifferentiable", "tensorflow.python.ops.gen_script_ops._py_func", "tensorflow.python.framework.ops.get_default_graph", "tensorflow.python.ops.gen_script_ops._py_func_stateless", "tensorflow.python.pywrap_tensorflow.InitializePyTrampoline" ], [ "tensorflow.python.ops.variables.Variable", "tensorflow.core.protobuf.config_pb2.ConfigProto", "tensorflow.python.platform.test.test_src_dir_path", "tensorflow.python.ops.state_ops.assign", "tensorflow.python.framework.ops.get_collection", "tensorflow.python.platform.test.main", "tensorflow.python.saved_model.loader.maybe_saved_model_directory", "tensorflow.python.util.compat.as_text", "tensorflow.python.saved_model.loader.load", "tensorflow.python.platform.test.get_temp_dir", "tensorflow.python.framework.ops.reset_default_graph", "tensorflow.python.saved_model.builder.SavedModelBuilder", "tensorflow.python.ops.math_ops.add", "tensorflow.python.ops.variables.global_variables_initializer", "tensorflow.python.framework.ops.Graph", "tensorflow.python.saved_model.main_op.main_op", "tensorflow.core.protobuf.meta_graph_pb2.TensorInfo", "tensorflow.python.lib.io.file_io.write_string_to_file", "tensorflow.python.lib.io.file_io.file_exists", "tensorflow.python.lib.io.file_io.read_file_to_string", "tensorflow.python.lib.io.file_io.delete_recursively", "tensorflow.python.ops.control_flow_ops.group", "tensorflow.python.framework.constant_op.constant", "tensorflow.python.framework.ops.add_to_collection", "tensorflow.python.framework.ops.get_default_graph", "tensorflow.core.protobuf.meta_graph_pb2.AssetFileDef", "tensorflow.python.util.compat.as_bytes" ] ]
rajegannathan/grasp-lift-eeg-cat-dog-solution-updated
[ "ee45bee6f96cdb6d91184abc16f41bba1546c943" ]
[ "python-packages/mne-python-0.10/mne/tests/test_evoked.py" ]
[ "# Author: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>\n# Denis Engemann <denis.engemann@gmail.com>\n# Andrew Dykstra <andrew.r.dykstra@gmail.com>\n# Mads Jensen <mje.mads@gmail.com>\n#\n# License: BSD (3-clause)\n\nimport os.path as op\nfrom copy import deepcopy\nimport warnings\n\nimport numpy as np\nfrom scipy import fftpack\nfrom numpy.testing import (assert_array_almost_equal, assert_equal,\n assert_array_equal, assert_allclose)\nfrom nose.tools import assert_true, assert_raises, assert_not_equal\n\nfrom mne import (equalize_channels, pick_types, read_evokeds, write_evokeds,\n grand_average, combine_evoked)\nfrom mne.evoked import _get_peak, EvokedArray\nfrom mne.epochs import EpochsArray\n\nfrom mne.utils import _TempDir, requires_pandas, slow_test, requires_version\n\nfrom mne.io.meas_info import create_info\nfrom mne.externals.six.moves import cPickle as pickle\n\nwarnings.simplefilter('always')\n\nfname = op.join(op.dirname(__file__), '..', 'io', 'tests', 'data',\n 'test-ave.fif')\nfname_gz = op.join(op.dirname(__file__), '..', 'io', 'tests', 'data',\n 'test-ave.fif.gz')\n\n\n@requires_version('scipy', '0.14')\ndef test_savgol_filter():\n \"\"\"Test savgol filtering\n \"\"\"\n h_freq = 10.\n evoked = read_evokeds(fname, 0)\n freqs = fftpack.fftfreq(len(evoked.times), 1. / evoked.info['sfreq'])\n data = np.abs(fftpack.fft(evoked.data))\n match_mask = np.logical_and(freqs >= 0, freqs <= h_freq / 2.)\n mismatch_mask = np.logical_and(freqs >= h_freq * 2, freqs < 50.)\n assert_raises(ValueError, evoked.savgol_filter, evoked.info['sfreq'])\n evoked.savgol_filter(h_freq)\n data_filt = np.abs(fftpack.fft(evoked.data))\n # decent in pass-band\n assert_allclose(np.mean(data[:, match_mask], 0),\n np.mean(data_filt[:, match_mask], 0),\n rtol=1e-4, atol=1e-2)\n # suppression in stop-band\n assert_true(np.mean(data[:, mismatch_mask]) >\n np.mean(data_filt[:, mismatch_mask]) * 5)\n\n\ndef test_hash_evoked():\n \"\"\"Test evoked hashing\n \"\"\"\n ave = read_evokeds(fname, 0)\n ave_2 = read_evokeds(fname, 0)\n assert_equal(hash(ave), hash(ave_2))\n # do NOT use assert_equal here, failing output is terrible\n assert_true(pickle.dumps(ave) == pickle.dumps(ave_2))\n\n ave_2.data[0, 0] -= 1\n assert_not_equal(hash(ave), hash(ave_2))\n\n\n@slow_test\ndef test_io_evoked():\n \"\"\"Test IO for evoked data (fif + gz) with integer and str args\n \"\"\"\n tempdir = _TempDir()\n ave = read_evokeds(fname, 0)\n\n write_evokeds(op.join(tempdir, 'evoked-ave.fif'), ave)\n ave2 = read_evokeds(op.join(tempdir, 'evoked-ave.fif'))[0]\n\n # This not being assert_array_equal due to windows rounding\n assert_true(np.allclose(ave.data, ave2.data, atol=1e-16, rtol=1e-3))\n assert_array_almost_equal(ave.times, ave2.times)\n assert_equal(ave.nave, ave2.nave)\n assert_equal(ave._aspect_kind, ave2._aspect_kind)\n assert_equal(ave.kind, ave2.kind)\n assert_equal(ave.last, ave2.last)\n assert_equal(ave.first, ave2.first)\n assert_true(repr(ave))\n\n # test compressed i/o\n ave2 = read_evokeds(fname_gz, 0)\n assert_true(np.allclose(ave.data, ave2.data, atol=1e-16, rtol=1e-8))\n\n # test str access\n condition = 'Left Auditory'\n assert_raises(ValueError, read_evokeds, fname, condition, kind='stderr')\n assert_raises(ValueError, read_evokeds, fname, condition,\n kind='standard_error')\n ave3 = read_evokeds(fname, condition)\n assert_array_almost_equal(ave.data, ave3.data, 19)\n\n # test read_evokeds and write_evokeds\n types = ['Left Auditory', 'Right Auditory', 'Left visual', 'Right visual']\n aves1 = read_evokeds(fname)\n aves2 = read_evokeds(fname, [0, 1, 2, 3])\n aves3 = read_evokeds(fname, types)\n write_evokeds(op.join(tempdir, 'evoked-ave.fif'), aves1)\n aves4 = read_evokeds(op.join(tempdir, 'evoked-ave.fif'))\n for aves in [aves2, aves3, aves4]:\n for [av1, av2] in zip(aves1, aves):\n assert_array_almost_equal(av1.data, av2.data)\n assert_array_almost_equal(av1.times, av2.times)\n assert_equal(av1.nave, av2.nave)\n assert_equal(av1.kind, av2.kind)\n assert_equal(av1._aspect_kind, av2._aspect_kind)\n assert_equal(av1.last, av2.last)\n assert_equal(av1.first, av2.first)\n assert_equal(av1.comment, av2.comment)\n\n # test warnings on bad filenames\n with warnings.catch_warnings(record=True) as w:\n warnings.simplefilter('always')\n fname2 = op.join(tempdir, 'test-bad-name.fif')\n write_evokeds(fname2, ave)\n read_evokeds(fname2)\n assert_true(len(w) == 2)\n\n\ndef test_shift_time_evoked():\n \"\"\" Test for shifting of time scale\n \"\"\"\n tempdir = _TempDir()\n # Shift backward\n ave = read_evokeds(fname, 0)\n ave.shift_time(-0.1, relative=True)\n write_evokeds(op.join(tempdir, 'evoked-ave.fif'), ave)\n\n # Shift forward twice the amount\n ave_bshift = read_evokeds(op.join(tempdir, 'evoked-ave.fif'), 0)\n ave_bshift.shift_time(0.2, relative=True)\n write_evokeds(op.join(tempdir, 'evoked-ave.fif'), ave_bshift)\n\n # Shift backward again\n ave_fshift = read_evokeds(op.join(tempdir, 'evoked-ave.fif'), 0)\n ave_fshift.shift_time(-0.1, relative=True)\n write_evokeds(op.join(tempdir, 'evoked-ave.fif'), ave_fshift)\n\n ave_normal = read_evokeds(fname, 0)\n ave_relative = read_evokeds(op.join(tempdir, 'evoked-ave.fif'), 0)\n\n assert_true(np.allclose(ave_normal.data, ave_relative.data,\n atol=1e-16, rtol=1e-3))\n assert_array_almost_equal(ave_normal.times, ave_relative.times, 10)\n\n assert_equal(ave_normal.last, ave_relative.last)\n assert_equal(ave_normal.first, ave_relative.first)\n\n # Absolute time shift\n ave = read_evokeds(fname, 0)\n ave.shift_time(-0.3, relative=False)\n write_evokeds(op.join(tempdir, 'evoked-ave.fif'), ave)\n\n ave_absolute = read_evokeds(op.join(tempdir, 'evoked-ave.fif'), 0)\n\n assert_true(np.allclose(ave_normal.data, ave_absolute.data,\n atol=1e-16, rtol=1e-3))\n assert_equal(ave_absolute.first, int(-0.3 * ave.info['sfreq']))\n\n\ndef test_evoked_resample():\n \"\"\"Test for resampling of evoked data\n \"\"\"\n tempdir = _TempDir()\n # upsample, write it out, read it in\n ave = read_evokeds(fname, 0)\n sfreq_normal = ave.info['sfreq']\n ave.resample(2 * sfreq_normal)\n write_evokeds(op.join(tempdir, 'evoked-ave.fif'), ave)\n ave_up = read_evokeds(op.join(tempdir, 'evoked-ave.fif'), 0)\n\n # compare it to the original\n ave_normal = read_evokeds(fname, 0)\n\n # and compare the original to the downsampled upsampled version\n ave_new = read_evokeds(op.join(tempdir, 'evoked-ave.fif'), 0)\n ave_new.resample(sfreq_normal)\n\n assert_array_almost_equal(ave_normal.data, ave_new.data, 2)\n assert_array_almost_equal(ave_normal.times, ave_new.times)\n assert_equal(ave_normal.nave, ave_new.nave)\n assert_equal(ave_normal._aspect_kind, ave_new._aspect_kind)\n assert_equal(ave_normal.kind, ave_new.kind)\n assert_equal(ave_normal.last, ave_new.last)\n assert_equal(ave_normal.first, ave_new.first)\n\n # for the above to work, the upsampling just about had to, but\n # we'll add a couple extra checks anyway\n assert_true(len(ave_up.times) == 2 * len(ave_normal.times))\n assert_true(ave_up.data.shape[1] == 2 * ave_normal.data.shape[1])\n\n\ndef test_evoked_detrend():\n \"\"\"Test for detrending evoked data\n \"\"\"\n ave = read_evokeds(fname, 0)\n ave_normal = read_evokeds(fname, 0)\n ave.detrend(0)\n ave_normal.data -= np.mean(ave_normal.data, axis=1)[:, np.newaxis]\n picks = pick_types(ave.info, meg=True, eeg=True, exclude='bads')\n assert_true(np.allclose(ave.data[picks], ave_normal.data[picks],\n rtol=1e-8, atol=1e-16))\n\n\n@requires_pandas\ndef test_to_data_frame():\n \"\"\"Test evoked Pandas exporter\"\"\"\n ave = read_evokeds(fname, 0)\n assert_raises(ValueError, ave.to_data_frame, picks=np.arange(400))\n df = ave.to_data_frame()\n assert_true((df.columns == ave.ch_names).all())\n df = ave.to_data_frame(index=None).reset_index('time')\n assert_true('time' in df.columns)\n assert_array_equal(df.values[:, 1], ave.data[0] * 1e13)\n assert_array_equal(df.values[:, 3], ave.data[2] * 1e15)\n\n\ndef test_evoked_proj():\n \"\"\"Test SSP proj operations\n \"\"\"\n for proj in [True, False]:\n ave = read_evokeds(fname, condition=0, proj=proj)\n assert_true(all(p['active'] == proj for p in ave.info['projs']))\n\n # test adding / deleting proj\n if proj:\n assert_raises(ValueError, ave.add_proj, [],\n {'remove_existing': True})\n assert_raises(ValueError, ave.del_proj, 0)\n else:\n projs = deepcopy(ave.info['projs'])\n n_proj = len(ave.info['projs'])\n ave.del_proj(0)\n assert_true(len(ave.info['projs']) == n_proj - 1)\n ave.add_proj(projs, remove_existing=False)\n assert_true(len(ave.info['projs']) == 2 * n_proj - 1)\n ave.add_proj(projs, remove_existing=True)\n assert_true(len(ave.info['projs']) == n_proj)\n\n ave = read_evokeds(fname, condition=0, proj=False)\n data = ave.data.copy()\n ave.apply_proj()\n assert_allclose(np.dot(ave._projector, data), ave.data)\n\n\ndef test_get_peak():\n \"\"\"Test peak getter\n \"\"\"\n\n evoked = read_evokeds(fname, condition=0, proj=True)\n assert_raises(ValueError, evoked.get_peak, ch_type='mag', tmin=1)\n assert_raises(ValueError, evoked.get_peak, ch_type='mag', tmax=0.9)\n assert_raises(ValueError, evoked.get_peak, ch_type='mag', tmin=0.02,\n tmax=0.01)\n assert_raises(ValueError, evoked.get_peak, ch_type='mag', mode='foo')\n assert_raises(RuntimeError, evoked.get_peak, ch_type=None, mode='foo')\n assert_raises(ValueError, evoked.get_peak, ch_type='misc', mode='foo')\n\n ch_idx, time_idx = evoked.get_peak(ch_type='mag')\n assert_true(ch_idx in evoked.ch_names)\n assert_true(time_idx in evoked.times)\n\n ch_idx, time_idx = evoked.get_peak(ch_type='mag',\n time_as_index=True)\n assert_true(time_idx < len(evoked.times))\n\n data = np.array([[0., 1., 2.],\n [0., -3., 0]])\n\n times = np.array([.1, .2, .3])\n\n ch_idx, time_idx = _get_peak(data, times, mode='abs')\n assert_equal(ch_idx, 1)\n assert_equal(time_idx, 1)\n\n ch_idx, time_idx = _get_peak(data * -1, times, mode='neg')\n assert_equal(ch_idx, 0)\n assert_equal(time_idx, 2)\n\n ch_idx, time_idx = _get_peak(data, times, mode='pos')\n assert_equal(ch_idx, 0)\n assert_equal(time_idx, 2)\n\n assert_raises(ValueError, _get_peak, data + 1e3, times, mode='neg')\n assert_raises(ValueError, _get_peak, data - 1e3, times, mode='pos')\n\n\ndef test_drop_channels_mixin():\n \"\"\"Test channels-dropping functionality\n \"\"\"\n evoked = read_evokeds(fname, condition=0, proj=True)\n drop_ch = evoked.ch_names[:3]\n ch_names = evoked.ch_names[3:]\n\n ch_names_orig = evoked.ch_names\n dummy = evoked.drop_channels(drop_ch, copy=True)\n assert_equal(ch_names, dummy.ch_names)\n assert_equal(ch_names_orig, evoked.ch_names)\n assert_equal(len(ch_names_orig), len(evoked.data))\n\n evoked.drop_channels(drop_ch)\n assert_equal(ch_names, evoked.ch_names)\n assert_equal(len(ch_names), len(evoked.data))\n\n\ndef test_pick_channels_mixin():\n \"\"\"Test channel-picking functionality\n \"\"\"\n evoked = read_evokeds(fname, condition=0, proj=True)\n ch_names = evoked.ch_names[:3]\n\n ch_names_orig = evoked.ch_names\n dummy = evoked.pick_channels(ch_names, copy=True)\n assert_equal(ch_names, dummy.ch_names)\n assert_equal(ch_names_orig, evoked.ch_names)\n assert_equal(len(ch_names_orig), len(evoked.data))\n\n evoked.pick_channels(ch_names)\n assert_equal(ch_names, evoked.ch_names)\n assert_equal(len(ch_names), len(evoked.data))\n\n evoked = read_evokeds(fname, condition=0, proj=True)\n assert_true('meg' in evoked)\n assert_true('eeg' in evoked)\n evoked.pick_types(meg=False, eeg=True)\n assert_true('meg' not in evoked)\n assert_true('eeg' in evoked)\n assert_true(len(evoked.ch_names) == 60)\n\n\ndef test_equalize_channels():\n \"\"\"Test equalization of channels\n \"\"\"\n evoked1 = read_evokeds(fname, condition=0, proj=True)\n evoked2 = evoked1.copy()\n ch_names = evoked1.ch_names[2:]\n evoked1.drop_channels(evoked1.ch_names[:1])\n evoked2.drop_channels(evoked2.ch_names[1:2])\n my_comparison = [evoked1, evoked2]\n equalize_channels(my_comparison)\n for e in my_comparison:\n assert_equal(ch_names, e.ch_names)\n\n\ndef test_evoked_arithmetic():\n \"\"\"Test evoked arithmetic\n \"\"\"\n ev = read_evokeds(fname, condition=0)\n ev1 = EvokedArray(np.ones_like(ev.data), ev.info, ev.times[0], nave=20)\n ev2 = EvokedArray(-np.ones_like(ev.data), ev.info, ev.times[0], nave=10)\n\n # combine_evoked([ev1, ev2]) should be the same as ev1 + ev2:\n # data should be added according to their `nave` weights\n # nave = ev1.nave + ev2.nave\n ev = ev1 + ev2\n assert_equal(ev.nave, ev1.nave + ev2.nave)\n assert_allclose(ev.data, 1. / 3. * np.ones_like(ev.data))\n ev = ev1 - ev2\n assert_equal(ev.nave, ev1.nave + ev2.nave)\n assert_equal(ev.comment, ev1.comment + ' - ' + ev2.comment)\n assert_allclose(ev.data, np.ones_like(ev1.data))\n\n # default comment behavior if evoked.comment is None\n old_comment1 = ev1.comment\n old_comment2 = ev2.comment\n ev1.comment = None\n with warnings.catch_warnings(record=True):\n warnings.simplefilter('always')\n ev = ev1 - ev2\n assert_equal(ev.comment, 'unknown')\n ev1.comment = old_comment1\n ev2.comment = old_comment2\n\n # equal weighting\n ev = combine_evoked([ev1, ev2], weights='equal')\n assert_allclose(ev.data, np.zeros_like(ev1.data))\n\n # combine_evoked([ev1, ev2], weights=[1, 0]) should yield the same as ev1\n ev = combine_evoked([ev1, ev2], weights=[1, 0])\n assert_equal(ev.nave, ev1.nave)\n assert_allclose(ev.data, ev1.data)\n\n # simple subtraction (like in oddball)\n ev = combine_evoked([ev1, ev2], weights=[1, -1])\n assert_allclose(ev.data, 2 * np.ones_like(ev1.data))\n\n assert_raises(ValueError, combine_evoked, [ev1, ev2], weights='foo')\n assert_raises(ValueError, combine_evoked, [ev1, ev2], weights=[1])\n\n # grand average\n evoked1, evoked2 = read_evokeds(fname, condition=[0, 1], proj=True)\n ch_names = evoked1.ch_names[2:]\n evoked1.info['bads'] = ['EEG 008'] # test interpolation\n evoked1.drop_channels(evoked1.ch_names[:1])\n evoked2.drop_channels(evoked2.ch_names[1:2])\n gave = grand_average([evoked1, evoked2])\n assert_equal(gave.data.shape, [len(ch_names), evoked1.data.shape[1]])\n assert_equal(ch_names, gave.ch_names)\n assert_equal(gave.nave, 2)\n\n\ndef test_array_epochs():\n \"\"\"Test creating evoked from array\n \"\"\"\n tempdir = _TempDir()\n\n # creating\n rng = np.random.RandomState(42)\n data1 = rng.randn(20, 60)\n sfreq = 1e3\n ch_names = ['EEG %03d' % (i + 1) for i in range(20)]\n types = ['eeg'] * 20\n info = create_info(ch_names, sfreq, types)\n evoked1 = EvokedArray(data1, info, tmin=-0.01)\n\n # save, read, and compare evokeds\n tmp_fname = op.join(tempdir, 'evkdary-ave.fif')\n evoked1.save(tmp_fname)\n evoked2 = read_evokeds(tmp_fname)[0]\n data2 = evoked2.data\n assert_allclose(data1, data2)\n assert_allclose(evoked1.times, evoked2.times)\n assert_equal(evoked1.first, evoked2.first)\n assert_equal(evoked1.last, evoked2.last)\n assert_equal(evoked1.kind, evoked2.kind)\n assert_equal(evoked1.nave, evoked2.nave)\n\n # now compare with EpochsArray (with single epoch)\n data3 = data1[np.newaxis, :, :]\n events = np.c_[10, 0, 1]\n evoked3 = EpochsArray(data3, info, events=events, tmin=-0.01).average()\n assert_allclose(evoked1.data, evoked3.data)\n assert_allclose(evoked1.times, evoked3.times)\n assert_equal(evoked1.first, evoked3.first)\n assert_equal(evoked1.last, evoked3.last)\n assert_equal(evoked1.kind, evoked3.kind)\n assert_equal(evoked1.nave, evoked3.nave)\n\n # test match between channels info and data\n ch_names = ['EEG %03d' % (i + 1) for i in range(19)]\n types = ['eeg'] * 19\n info = create_info(ch_names, sfreq, types)\n assert_raises(ValueError, EvokedArray, data1, info, tmin=-0.01)\n\n\ndef test_add_channels():\n \"\"\"Test evoked splitting / re-appending channel types\n \"\"\"\n evoked = read_evokeds(fname, condition=0)\n evoked.info['buffer_size_sec'] = None\n evoked_eeg = evoked.pick_types(meg=False, eeg=True, copy=True)\n evoked_meg = evoked.pick_types(meg=True, copy=True)\n evoked_stim = evoked.pick_types(meg=False, stim=True, copy=True)\n evoked_eeg_meg = evoked.pick_types(meg=True, eeg=True, copy=True)\n evoked_new = evoked_meg.add_channels([evoked_eeg, evoked_stim], copy=True)\n assert_true(all(ch in evoked_new.ch_names\n for ch in evoked_stim.ch_names + evoked_meg.ch_names))\n evoked_new = evoked_meg.add_channels([evoked_eeg], copy=True)\n\n assert_true(ch in evoked_new.ch_names for ch in evoked.ch_names)\n assert_array_equal(evoked_new.data, evoked_eeg_meg.data)\n assert_true(all(ch not in evoked_new.ch_names\n for ch in evoked_stim.ch_names))\n\n # Now test errors\n evoked_badsf = evoked_eeg.copy()\n evoked_badsf.info['sfreq'] = 3.1415927\n evoked_eeg = evoked_eeg.crop(-.1, .1)\n\n assert_raises(RuntimeError, evoked_meg.add_channels, [evoked_badsf])\n assert_raises(AssertionError, evoked_meg.add_channels, [evoked_eeg])\n assert_raises(ValueError, evoked_meg.add_channels, [evoked_meg])\n assert_raises(AssertionError, evoked_meg.add_channels, evoked_badsf)\n" ]
[ [ "numpy.testing.assert_allclose", "numpy.array", "numpy.dot", "numpy.ones_like", "numpy.zeros_like", "numpy.testing.assert_equal", "numpy.random.RandomState", "numpy.testing.assert_array_equal", "numpy.logical_and", "numpy.mean", "numpy.testing.assert_array_almost_equal", "numpy.allclose", "scipy.fftpack.fft", "numpy.arange" ] ]
Opendigitalradio/ODR-StaticPrecorrection
[ "984c14bf46ebd7dc66954a653c8f17212ed97efb" ]
[ "src/tcp_sync.py" ]
[ "\"\"\"Tcp client for synchronous uhd message tcp port\"\"\"\n\nimport threading\nimport Queue\nimport time\nimport socket\nimport struct\nimport numpy as np\n\nclass _TcpSyncClient(threading.Thread):\n \"\"\"Thead for message polling\"\"\"\n queue = Queue.Queue()\n q_quit = Queue.Queue()\n\n ip_address = None\n port = None\n\n def __init__(self, ip_address, port, packet_size, packet_type):\n super(_TcpSyncClient, self).__init__()\n self.ip_address = ip_address\n self.port = port\n self.packet_size = packet_size\n self.packet_type = packet_type\n\n def __exit__(self):\n self.stop()\n\n def run(self):\n \"\"\"connect and poll messages to queue\"\"\"\n\n #Establish connection\n sock = None\n print(\"Connecting to synchronous uhd message tcp port \" + str(self.port))\n while self.q_quit.empty():\n try:\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.connect((self.ip_address, self.port))\n break\n except socket.error:\n print(\"connecting to synchronous uhd message tcp port \" + str(self.port))\n #traceback.print_exc()\n sock.close()\n time.sleep(0.5)\n print(\"Connected to synchronous uhd message tcp port \" + str(self.port))\n\n #Read messages\n sock.settimeout(None)\n s = \"\"\n while self.q_quit.empty():\n try:\n\n #concatenate to one package\n while self.q_quit.empty():\n s += sock.recv(self.packet_size)\n if (len(s)) >= self.packet_size:\n break\n res_tuple = struct.unpack( self.packet_type, s[:self.packet_size])\n s = s[self.packet_size:]\n self.queue.put(res_tuple)\n except socket.timeout:\n self.stop()\n traceback.print_exc()\n pass\n\n sock.close()\n\n def stop(self):\n \"\"\"stop thread\"\"\"\n print(\"stop tcp_sync uhd message tcp thread\")\n self.q_quit.put(\"end\")\n\n\nclass UhdSyncMsg(object):\n \"\"\"Creates a thread to connect to the synchronous uhd messages tcp port\"\"\"\n\n def __init__(self, ip_address = \"127.0.0.1\", port = 47009, packet_size = 3, packet_type = \"fff\"):\n self.tcpa = _TcpSyncClient(ip_address, port, packet_size, packet_type)\n self.tcpa.start()\n\n def __exit__(self):\n self.tcpa.stop()\n\n def stop(self):\n \"\"\"stop tcp thread\"\"\"\n self.tcpa.stop()\n\n def get_msgs(self, num):\n \"\"\"get received messages as string of integer\"\"\"\n out = []\n while len(out) < num:\n out.append(self.tcpa.queue.get())\n return out\n\n def get_msgs_fft(self, num):\n \"\"\"\n get received messages as string of integer\n apply fftshift to message\n \"\"\"\n out = []\n while len(out) < num:\n out.append(self.tcpa.queue.get())\n return [np.fft.fftshift(np.array(o)) for o in out]\n\n def get_res(self):\n \"\"\"get received messages as string of integer\"\"\"\n out = []\n while not self.tcpa.queue.empty():\n out.append(self.tcpa.queue.get())\n return out\n\n def has_msg(self):\n \"\"\"Checks if one or more messages were received and empties the message queue\"\"\"\n return self.get_res() != \"\"\n" ]
[ [ "numpy.array" ] ]
wennieWN/endernewton_tf-faster-rcnn
[ "463d1be4d6be1d1b095df0fa41040de70d217c7f" ]
[ "lib/roi_data_layer/minibatch.py" ]
[ "# --------------------------------------------------------\n# Fast R-CNN\n# Copyright (c) 2015 Microsoft\n# Licensed under The MIT License [see LICENSE for details]\n# Written by Ross Girshick and Xinlei Chen\n# --------------------------------------------------------\n\n\"\"\"Compute minibatch blobs for training a Fast R-CNN network.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport numpy.random as npr\nimport cv2\nfrom model.config import cfg\nfrom utils.blob import prep_im_for_blob, im_list_to_blob\nimport os\n# import tensorflow as tf\n\n\ndef get_minibatch(roidb, num_classes):\n \"\"\"Given a roidb, construct a minibatch sampled from it.\"\"\"\n num_images = len(roidb)\n # Sample random scales to use for each image in this batch\n random_scale_inds = npr.randint(0, high=len(cfg.TRAIN.SCALES),\n size=num_images)\n assert(cfg.TRAIN.BATCH_SIZE % num_images == 0), \\\n 'num_images ({}) must divide BATCH_SIZE ({})'. \\\n format(num_images, cfg.TRAIN.BATCH_SIZE)\n\n # Get the input image blob, formatted for caffe\n im_blob, im_scales = _get_image_blob(roidb, random_scale_inds)\n\n blobs = {'data': im_blob}\n\n assert len(im_scales) == 1, \"Single batch only\"\n assert len(roidb) == 1, \"Single batch only\"\n\n # todo: get cls_filter blobs['clp_filter']\n # wn modified\n # 1. get file path\n sep = '/'\n clp_file_format = '.npy'\n clp_file_store = 'CloudPoints'\n\n img_path = roidb[0]['image']\n img_path_arr = img_path.split(sep)\n prefix = img_path_arr[:-2]\n file_name = img_path_arr[-1].split('.')[0] + clp_file_format\n clp_path = os.path.join(sep.join(prefix), clp_file_store, file_name)\n\n # 2. get cls data [?, 2]\n valid_points= np.load(clp_path) # [?, 2]\n # todo: width & height is not fixed\n width_ori = roidb[0]['height'] # 322\n height_ori = roidb[0]['width'] # 500\n\n clp_ori = np.zeros([width_ori, height_ori], dtype=np.float32) # 初始化\n clp_ori[tuple((valid_points.T[1, :], valid_points.T[0, :]))] = 1 # 设置存在点云的网格值为1 [322,500]\n\n # 3.resize cls [322,500] =》[600,932] (同图片的操作)\n clp_reshape = np.empty([width_ori, height_ori, 3], dtype=np.float32)\n for i in range(3):\n clp_reshape[0:width_ori, 0:height_ori, i] = clp_ori\n clp_res = cv2.resize(clp_reshape, None, None, fx=im_scales[0], fy=im_scales[0], interpolation=cv2.INTER_LINEAR)\n clp_res = clp_res[:, :, 0] # [600,932]\n clp_res[clp_res > 0] = 1 # >0的值均设置成1\n\n width = clp_res.shape[0]\n height = clp_res.shape[1]\n clp_res = clp_res.reshape([1, width, height, 1])\n\n blobs['clp_info'] = clp_res # [1,600,932,1]\n\n # 4. Max pooling\n # width = clp_res.shape[0] # 600\n # height = clp_res.shape[1] # 932\n # clp_res = clp_res.reshape([1, width, height, 1])\n # clp_filter = tf.constant(clp_res)\n # clp_filter_reshape = tf.reshape(clp_filter, [1, width, height, 1])\n #\n # clp_pooling = tf.nn.max_pool(clp_filter_reshape, [1, 16, 16, 1], [1, 16, 16, 1], padding='SAME') # self._feat_stride[0] = 16\n # clp_pooling = clp_pooling[0, :, :, 0]\n # print(\"pooling: \" + str(clp_pooling.shape))\n # blobs['clp_filter'] = clp_pooling # [38, 59] (同特征图net_conv尺寸一致)\n\n \n # gt boxes: (x1, y1, x2, y2, cls)\n if cfg.TRAIN.USE_ALL_GT:\n # Include all ground truth boxes\n gt_inds = np.where(roidb[0]['gt_classes'] != 0)[0]\n else:\n # For the COCO ground truth boxes, exclude the ones that are ''iscrowd'' \n gt_inds = np.where(roidb[0]['gt_classes'] != 0 & np.all(roidb[0]['gt_overlaps'].toarray() > -1.0, axis=1))[0]\n gt_boxes = np.empty((len(gt_inds), 5), dtype=np.float32)\n gt_boxes[:, 0:4] = roidb[0]['boxes'][gt_inds, :] * im_scales[0]\n gt_boxes[:, 4] = roidb[0]['gt_classes'][gt_inds]\n blobs['gt_boxes'] = gt_boxes\n blobs['im_info'] = np.array(\n [im_blob.shape[1], im_blob.shape[2], im_scales[0]],\n dtype=np.float32)\n\n return blobs\n\ndef _get_image_blob(roidb, scale_inds):\n \"\"\"Builds an input blob from the images in the roidb at the specified\n scales.\n \"\"\"\n num_images = len(roidb)\n processed_ims = []\n im_scales = []\n for i in range(num_images):\n im = cv2.imread(roidb[i]['image'])\n if roidb[i]['flipped']:\n im = im[:, ::-1, :]\n target_size = cfg.TRAIN.SCALES[scale_inds[i]]\n im, im_scale = prep_im_for_blob(im, cfg.PIXEL_MEANS, target_size,\n cfg.TRAIN.MAX_SIZE)\n im_scales.append(im_scale)\n processed_ims.append(im)\n\n # Create a blob to hold the input images\n blob = im_list_to_blob(processed_ims)\n\n return blob, im_scales\n" ]
[ [ "numpy.array", "numpy.empty", "numpy.zeros", "numpy.load", "numpy.where" ] ]
jhunkeler/tweakwcs
[ "6a7f5153850474e1c0ecc2dfe1ec1af76fcf5fd2" ]
[ "tweakwcs/linearfit.py" ]
[ "# Licensed under a 3-clause BSD style license - see LICENSE.rst\n\"\"\"\nA module that provides algorithms for performing linear fit between\nsets of 2D points.\n\n:Authors: Mihai Cara, Warren Hack\n\n:License: :doc:`../LICENSE`\n\n\"\"\"\nimport logging\nimport numbers\nimport numpy as np\n\nfrom .linalg import inv\nfrom . import __version__ # noqa: F401\n\n__author__ = 'Mihai Cara, Warren Hack'\n\n__all__ = ['iter_linear_fit', 'build_fit_matrix']\n\n\nlog = logging.getLogger(__name__)\nlog.setLevel(logging.DEBUG)\n\n\nclass SingularMatrixError(Exception):\n \"\"\" An error class used to report when a singular matrix is encountered.\"\"\"\n pass\n\n\nclass NotEnoughPointsError(Exception):\n \"\"\"\n An error class used to report when there are not enough points to\n find parameters of a linear transformation.\n \"\"\"\n pass\n\n\ndef iter_linear_fit(xy, uv, wxy=None, wuv=None,\n fitgeom='general', center=None,\n nclip=3, sigma=(3.0, 'rmse'), clip_accum=False):\n r\"\"\"\n Compute linear transformation parameters that \"best\" (in the sense of\n minimizing residuals) transform ``uv`` source position to ``xy``\n sources iteratively using sigma-clipping.\n\n More precisely, this functions attempts to find a ``2x2`` matrix ``F`` and\n a shift vector ``s`` that minimize the residuals between the *transformed*\n reference source coordinates ``uv``\n\n .. math::\n \\mathbf{xy}'_k = \\mathbf{F}\\cdot(\\mathbf{uv}_k-\\mathbf{c})+\\\n \\mathbf{s} + \\mathbf{c}\n :label: ilf1\n\n and the \"observed\" source positions ``xy``:\n\n .. math::\n \\epsilon^2 = \\Sigma_k w_k \\|\\mathbf{xy}_k-\\mathbf{xy}'_k\\|^2.\n :label: ilf2\n\n In the above equations, :math:`\\mathbf{F}` is a ``2x2`` matrix while\n :math:`\\mathbf{xy}_k` and :math:`\\mathbf{uv}_k` are the position\n coordinates of the ``k``-th source (row in input ``xy`` and ``uv`` arrays).\n\n One of the two catalogs (``xy`` or ``uv``) contains what we refer to as\n \"image\" source positions and the other one as \"reference\" source positions.\n The meaning assigned to ``xy`` and ``uv`` parameters are up to the\n caller of this function.\n\n Parameters\n ----------\n xy: numpy.ndarray\n A ``(N, 2)``-shaped array of source positions (one 2-coordinate\n position per line).\n\n uv: numpy.ndarray\n A ``(N, 2)``-shaped array of source positions (one 2-coordinate\n position per line). This array *must have* the same length (shape)\n as the ``xy`` array.\n\n wxy: numpy.ndarray, None, optional\n A 1-dimensional array of weights of the same length (``N``)\n as ``xy`` array indicating how much a given coordinate should be\n weighted in the fit. If not provided or set to `None`, all positions\n will be contribute equally to the fit if ``wuv`` is also set to `None`.\n See ``Notes`` section for more details.\n\n wuv: numpy.ndarray, None, optional\n A 1-dimensional array of weights of the same length (``N``)\n as ``xy`` array indicating how much a given coordinate should be\n weighted in the fit. If not provided or set to `None`, all positions\n will be contribute equally to the fit if ``wxy`` is also set to `None`.\n See ``Notes`` section for more details.\n\n fitgeom: {'shift', 'rscale', 'general'}, optional\n The fitting geometry to be used in fitting the matched object lists.\n This parameter is used in fitting the shifts (offsets), rotations\n and/or scale changes from the matched object lists. The 'general'\n fit geometry allows for independent scale and rotation for each axis.\n\n center: tuple, list, numpy.ndarray, None, optional\n A list-like container with two ``X``- and ``Y``-positions of the center\n (origin) of rotations in the ``uv`` and ``xy`` coordinate frames.\n If not provided, ``center`` is estimated as a (weighted) mean position\n in the ``uv`` frame.\n\n nclip: int, None, optional\n Number (a non-negative integer) of clipping iterations in fit.\n Clipping will be turned off if ``nclip`` is either `None` or 0.\n\n sigma: float, tuple of the form (float, str), optional\n When a tuple is provided, first value (a positive number)\n indicates the number of \"fit error estimates\" to use for clipping.\n The second value (a string) indicates the statistic to be\n used for \"fit error estimate\". Currently the following values are\n supported: ``'rmse'``, ``'mae'``, and ``'std'``\n - see ``Notes`` section for more details.\n\n When ``sigma`` is a single number, it must be a positive number and\n the default error estimate ``'rmse'`` is assumed.\n\n This parameter is ignored when ``nclip`` is either `None` or 0.\n\n clip_accum: bool, optional\n Indicates whether or not to reset the list of \"bad\" (clipped out)\n sources after each clipping iteration. When set to `True` the list\n only grows with each iteration as \"bad\" positions never re-enter the\n pool of available position for the fit. By default the list of\n \"bad\" source positions is purged at each iteration.\n\n Returns\n -------\n fit: dict\n - ``'shift'``: A ``numpy.ndarray`` with two components of the\n computed shift.\n - ``'shift_ld'``: A ``numpy.ndarray`` with two components of the\n computed shift of type ``numpy.longdouble``.\n - ``'matrix'``: A ``2x2`` ``numpy.ndarray`` with the computed\n generalized rotation matrix.\n - ``'matrix_ld'``: A ``2x2`` ``numpy.ndarray`` with the computed\n generalized rotation matrix of type ``numpy.longdouble``.\n - ``'proper_rot'``: Rotation angle (degree) as if the rotation is\n proper.\n - ``'rot'``: A tuple of ``(rotx, roty)`` - the rotation angles with\n regard to the ``X`` and ``Y`` axes.\n - ``'<rot>'``: *Arithmetic mean* of the angles of rotation around\n ``X`` and ``Y`` axes.\n - ``'scale'``: A tuple of ``(sx, sy)`` - scale change in the direction\n of the ``X`` and ``Y`` axes.\n - ``'<scale>'``: *Geometric mean* of scales ``sx`` and ``sy``.\n - ``'skew'``: Computed skew.\n - ``'proper'``: a boolean indicating whether the rotation is proper.\n - ``'fitgeom'``: Fit geometry (allowed transformations) used for\n fitting data (to minimize residuals). This is copy of the input\n argument ``fitgeom``.\n - ``'center'``: Center of rotation\n - ``'center_ld'``: Center of rotation as a ``numpy.longdouble``.\n - ``'fitmask'``: A boolean array indicating which source positions\n where used for fitting (`True`) and which were clipped out\n (`False`). **NOTE** For weighted fits, positions with zero\n weights are automatically excluded from the fits.\n - ``'eff_nclip'``: Effective number of clipping iterations\n - ``'rmse'``: Root-Mean-Square Error\n - ``'mae'``: Mean Absolute Error\n - ``'std'``: Standard Deviation of the residuals\n - ``'resids'``: An array of residuals of the fit.\n **NOTE:** Only the residuals for the \"valid\" points are reported\n here. Therefore the length of this array may be smaller than the\n length of input arrays of positions.\n\n Notes\n -----\n **Weights**\n\n Weights can be provided for both \"image\" source positions and \"reference\"\n source positions. When no weights are given, all positions are weighted\n equally. When only one set of positions have weights (i.e., either ``wxy``\n or ``wuv`` is not `None`) then weights in :eq:`ilf2` are set to be equal\n to the provided set of weights. When weights for *both* \"image\" source\n positions and \"reference\" source positions are provided, then the\n combined weight that is used in :eq:`ilf2` is computed as:\n\n .. math::\n 1/w = 1/w_{xy} + 1/w_{uv}.\n\n **Statistics for clipping**\n\n Several statistics are available for clipping iterations and all of them\n are reported in the returned ``fit`` dictionary regardless of the\n setting in ``sigma``:\n\n .. math::\n \\mathrm{RMSE} = \\sqrt{\\Sigma_k w_k \\|\\mathbf{r}_k\\|^2}\n\n .. math::\n \\mathrm{MAE} = \\sqrt{\\Sigma_k w_k \\|\\mathbf{r}_k\\|}\n\n .. math::\n \\mathrm{STD} = \\sqrt{\\Sigma_k w_k \\|\\mathbf{r}_k - \\\n \\mathbf{\\overline{r}}\\|^2}/(1-V_2)\n\n where :math:`\\mathbf{r}_k=\\mathbf{xy}_k-\\mathbf{xy}'_k`,\n :math:`\\Sigma_k w_k = 1`, and :math:`V_2=\\Sigma_k w_k^2`.\n\n \"\"\"\n if fitgeom == 'general':\n linear_fit = fit_general\n elif fitgeom == 'rscale':\n linear_fit = fit_rscale\n elif fitgeom == 'shift':\n linear_fit = fit_shifts\n else:\n raise ValueError(\"Unsupported 'fitgeom' value: '{}'\".format(fitgeom))\n\n minobj_per_fitgeom = {'shift': 1, 'rscale': 2, 'general': 3}\n minobj = minobj_per_fitgeom[fitgeom]\n\n xy = np.array(xy, dtype=np.longdouble)\n uv = np.array(uv, dtype=np.longdouble)\n\n if len(xy.shape) != 2 or xy.shape[1] != 2 or uv.shape != xy.shape:\n raise ValueError(\"Input coordinate arrays 'xy' and 'uv' must be of \"\n \"shape (N, 2) where N is the number of coordinate \"\n \"points.\")\n\n wmask = np.ones(len(xy), dtype=np.bool_)\n\n if wxy is not None:\n wxy = np.asarray(wxy)\n if len(wxy.shape) != 1 or wxy.shape[0] != xy.shape[0]:\n raise ValueError(\"Weights 'wxy' must be a 1-dimensional vector \"\n \"of lengths equal to the number of input points.\")\n wmask *= wxy > 0.0\n\n if wuv is not None:\n wuv = np.asarray(wuv)\n if len(wuv.shape) != 1 or wuv.shape[0] != xy.shape[0]:\n raise ValueError(\"Weights 'wuv' must be a 1-dimensional vector \"\n \"of lengths equal to the number of input points.\")\n wmask *= wuv > 0.0\n\n mask = wmask\n\n if sigma is None and nclip is not None and nclip > 0:\n raise ValueError(\"Argument 'sigma' cannot be None when 'nclip' is \"\n \"a positive number.\")\n\n if isinstance(sigma, numbers.Number):\n sigstat = 'rmse' # default value\n nsigma = float(sigma)\n\n elif sigma is not None:\n nsigma = float(sigma[0])\n sigstat = sigma[1]\n if sigstat not in ['rmse', 'mae', 'std']:\n raise ValueError(\"Unsupported sigma statistics value.\")\n\n if sigma is not None and nsigma <= 0.0:\n raise ValueError(\"The value of sigma for clipping iterations must be \"\n \"positive.\")\n\n if nclip is None:\n nclip = 0\n else:\n if nclip < 0:\n raise ValueError(\"Argument 'nclip' must be non-negative.\")\n nclip = int(nclip)\n\n if np.count_nonzero(mask) == minobj:\n log.warning(\"The number of sources for the fit is smaller than the \"\n \"minimum number of sources necessary for the requested \"\n \"'fitgeom'.\")\n log.warning(\"Resetting number of clipping iterations to 0.\")\n nclip = 0\n\n if center is None:\n center_ld = uv[mask].mean(axis=0, dtype=np.longdouble)\n center = center_ld.astype(np.double)\n else:\n center_ld = np.longdouble(center)\n\n xy[mask] -= center_ld\n uv[mask] -= center_ld\n\n log.info(\"Performing '{:s}' fit\".format(fitgeom))\n\n # initial fit:\n wmxy = None if wxy is None else wxy[mask]\n wmuv = None if wuv is None else wuv[mask]\n fit = linear_fit(xy[mask], uv[mask], wmxy, wmuv)\n\n # clipping iterations:\n effective_nclip = 0\n for n in range(nclip):\n resids = fit['resids']\n\n # redefine what pixels will be included in next iteration\n cutoff = nsigma * fit[sigstat]\n\n nonclipped = np.linalg.norm(resids, axis=1) < cutoff\n if np.count_nonzero(nonclipped) < minobj or nonclipped.all():\n break\n\n effective_nclip += 1\n\n prev_mask = mask\n if not clip_accum:\n mask = np.array(wmask)\n mask[prev_mask] *= nonclipped\n\n wmxy = None if wxy is None else wxy[mask]\n wmuv = None if wuv is None else wuv[mask]\n fit = linear_fit(xy[mask], uv[mask], wmxy, wmuv)\n\n fit['center'] = center\n fit['center_ld'] = center_ld\n fit['fitmask'] = mask\n fit['eff_nclip'] = effective_nclip\n return fit\n\n\ndef _compute_stat(fit, residuals, weights):\n if weights is None:\n fit['rmse'] = float(np.sqrt(np.mean(2 * residuals**2)))\n fit['mae'] = float(np.mean(np.linalg.norm(residuals, axis=1)))\n fit['std'] = float(np.linalg.norm(residuals.std(axis=0)))\n else:\n # assume all weights > 0 (this should be insured by the caller => no\n # need to repeat the check here)\n npts = len(weights)\n wt = np.sum(weights)\n if npts == 0 or wt == 0.0:\n fit['rmse'] = float('nan')\n fit['mae'] = float('nan')\n fit['std'] = float('nan')\n return\n\n w = weights / wt\n fit['rmse'] = float(np.sqrt(np.sum(np.dot(w, residuals**2))))\n fit['mae'] = float(np.dot(w, np.linalg.norm(residuals, axis=1)))\n\n if npts == 1:\n fit['std'] = 0.0\n else:\n # see:\n # https://en.wikipedia.org/wiki/Weighted_arithmetic_mean#Reliability_weights_2\n wmean = np.dot(w, residuals)\n fit['std'] = float(\n np.sqrt(np.sum(np.dot(w, (residuals - wmean)**2) /\n (1.0 - np.sum(w**2))))\n )\n\n\ndef fit_shifts(xy, uv, wxy=None, wuv=None):\n \"\"\" Fits (non-iteratively and without sigma-clipping) a displacement\n transformation only between input lists of positions ``xy`` and ``uv``.\n When weights are provided, a weighted fit is performed. Parameter\n descriptions and return values are identical to those in `iter_linear_fit`,\n except returned ``fit`` dictionary does not contain the following\n keys irrelevant to this function: ``'center'``, ``'fitmask'``, and\n ``'eff_nclip'``.\n\n \"\"\"\n if xy.size == 0:\n raise NotEnoughPointsError(\n \"At least one point is required to find shifts.\"\n )\n\n diff_pts = np.subtract(xy, uv, dtype=np.longdouble)\n\n if wxy is None and wuv is None:\n # no weighting\n w = None\n\n meanx = diff_pts[:, 0].mean(dtype=np.longdouble)\n meany = diff_pts[:, 1].mean(dtype=np.longdouble)\n\n else:\n if wxy is None:\n w = np.array(wuv, dtype=np.longdouble)\n elif wuv is None:\n w = np.array(wxy, dtype=np.longdouble)\n else:\n # 1/w = sigma**2 = sigma_xy**2 + sigma_uv**2 = 1/wxy + 1/wuv\n wuv = np.array(wuv, dtype=np.longdouble)\n wxy = np.array(wxy, dtype=np.longdouble)\n m = np.logical_and(wuv > 0, wxy > 0)\n w = np.zeros_like(wuv)\n w[m] = wxy[m] * wuv[m] / (wxy[m] + wuv[m])\n\n if np.any(w < 0.0):\n raise ValueError(\"Invalid weights: weights must be non-negative.\")\n\n if not np.sum(w > 0, dtype=np.int):\n raise ValueError(\"Not enough valid data for 'shift' fit: \"\n \"too many weights are zero!\")\n\n w /= np.sum(w, dtype=np.longdouble)\n\n meanx = np.dot(w, diff_pts[:, 0])\n meany = np.dot(w, diff_pts[:, 1])\n\n p = np.array([1.0, 0.0, meanx], dtype=np.longdouble)\n q = np.array([0.0, 1.0, meany], dtype=np.longdouble)\n\n fit = _build_fit(p, q, 'shift')\n resids = diff_pts - fit['shift']\n fit['resids'] = resids.astype(np.double)\n _compute_stat(fit, residuals=resids, weights=w)\n return fit\n\n\n# Implementation of geomap 'rscale' fitting based on 'lib/geofit.x'\n# by Warren Hack. Support for axis flips added by Mihai Cara.\ndef fit_rscale(xy, uv, wxy=None, wuv=None):\n \"\"\" Fits (non-iteratively and without sigma-clipping) a displacement,\n rotation and scale transformations between input lists of positions\n ``xy`` and ``uv``. When weights are provided, a weighted fit is performed.\n Parameter descriptions and return values are identical to those\n in `iter_linear_fit`, except returned ``fit`` dictionary does not contain\n the following keys irrelevant to this function: ``'center'``,\n ``'fitmask'``, and ``'eff_nclip'``.\n\n \"\"\"\n if len(xy) < 2:\n raise NotEnoughPointsError(\n \"At least two points are required to find shifts, rotation, and \"\n \"scale.\"\n )\n\n x = np.array(xy[:, 0], dtype=np.longdouble)\n y = np.array(xy[:, 1], dtype=np.longdouble)\n u = np.array(uv[:, 0], dtype=np.longdouble)\n v = np.array(uv[:, 1], dtype=np.longdouble)\n\n if wxy is None and wuv is None:\n # no weighting\n w = None\n\n xm = np.mean(x)\n ym = np.mean(y)\n um = np.mean(u)\n vm = np.mean(v)\n\n x -= xm\n y -= ym\n u -= um\n v -= vm\n\n su2 = np.dot(u, u)\n sv2 = np.dot(v, v)\n sxv = np.dot(x, v)\n syu = np.dot(y, u)\n sxu = np.dot(x, u)\n syv = np.dot(y, v)\n su2v2 = su2 + sv2\n\n else:\n if wxy is None:\n w = np.array(wuv, dtype=np.longdouble)\n elif wuv is None:\n w = np.array(wxy, dtype=np.longdouble)\n else:\n # 1/w = sigma**2 = sigma_xy**2 + sigma_uv**2 = 1/wxy + 1/wuv\n wuv = np.array(wuv, dtype=np.longdouble)\n wxy = np.array(wxy, dtype=np.longdouble)\n m = np.logical_and(wuv > 0, wxy > 0)\n w = np.zeros_like(wuv)\n w[m] = wxy[m] * wuv[m] / (wxy[m] + wuv[m])\n\n if np.any(w < 0.0):\n raise ValueError(\"Invalid weights: weights must be non-negative.\")\n\n if np.sum(w > 0) < 2:\n raise ValueError(\"Not enough valid data for 'rscale' fit: \"\n \"too many weights are zero!\")\n\n w /= np.sum(w, dtype=np.longdouble)\n xm = np.dot(w, x)\n ym = np.dot(w, y)\n um = np.dot(w, u)\n vm = np.dot(w, v)\n\n x -= xm\n y -= ym\n u -= um\n v -= vm\n\n su2 = np.dot(w, u**2)\n sv2 = np.dot(w, v**2)\n sxv = np.dot(w, x * v)\n syu = np.dot(w, y * u)\n sxu = np.dot(w, x * u)\n syv = np.dot(w, y * v)\n su2v2 = su2 + sv2\n\n det = sxu * syv - sxv * syu\n if det < 0:\n rot_num = sxv + syu\n rot_denom = sxu - syv\n else:\n rot_num = sxv - syu\n rot_denom = sxu + syv\n\n if rot_num == rot_denom:\n theta = 0.0\n else:\n theta = np.rad2deg(np.arctan2(rot_num, rot_denom))\n if theta < 0:\n theta += 360.0\n\n ctheta = np.cos(np.deg2rad(theta))\n stheta = np.sin(np.deg2rad(theta))\n s_num = rot_denom * ctheta + rot_num * stheta\n\n if su2v2 > 0.0:\n mag = s_num / su2v2\n else:\n raise SingularMatrixError(\n \"Singular matrix: suspected colinear points.\"\n )\n\n if det < 0:\n # \"flip\" y-axis (reflection about x-axis *after* rotation)\n # NOTE: keep in mind that 'matrix' is the transposed rotation matrix.\n sthetax = -mag * stheta\n cthetay = -mag * ctheta\n else:\n sthetax = mag * stheta\n cthetay = mag * ctheta\n\n cthetax = mag * ctheta\n sthetay = mag * stheta\n\n sdet = np.sign(det)\n xshift = xm - um * cthetax - sdet * vm * sthetax\n yshift = ym + sdet * um * sthetay - vm * cthetay\n\n p = np.array([cthetax, sthetay, xshift], dtype=np.longdouble)\n q = np.array([-sthetax, cthetay, yshift], dtype=np.longdouble)\n\n # Return the shift, rotation, and scale changes\n fit = _build_fit(p, q, fitgeom='rscale')\n resids = xy - np.dot(uv, fit['matrix_ld'].T) - fit['shift_ld']\n fit['resids'] = resids.astype(np.double)\n _compute_stat(fit, residuals=resids, weights=w)\n return fit\n\n\ndef fit_general(xy, uv, wxy=None, wuv=None):\n \"\"\" Fits (non-iteratively and without sigma-clipping) a displacement,\n rotation, scale, and skew transformations (i.e., the full ``2x2``\n transformation matrix) between input lists of positions\n ``xy`` and ``uv``. When weights are provided, a weighted fit is performed.\n Parameter descriptions and return values are identical to those\n in `iter_linear_fit`, except returned ``fit`` dictionary does not contain\n the following keys irrelevant to this function: ``'center'``,\n ``'fitmask'``, and ``'eff_nclip'``.\n\n \"\"\"\n if len(xy) < 3:\n raise NotEnoughPointsError(\n \"At least three points are required to find 6-parameter linear \"\n \"affine transformations.\"\n )\n\n x = np.array(xy[:, 0], dtype=np.longdouble)\n y = np.array(xy[:, 1], dtype=np.longdouble)\n u = np.array(uv[:, 0], dtype=np.longdouble)\n v = np.array(uv[:, 1], dtype=np.longdouble)\n\n if wxy is None and wuv is None:\n # no weighting\n w = None\n\n # Set up products used for computing the fit\n sw = float(x.size)\n sx = x.sum()\n sy = y.sum()\n su = u.sum()\n sv = v.sum()\n\n sxu = np.dot(x, u)\n syu = np.dot(y, u)\n sxv = np.dot(x, v)\n syv = np.dot(y, v)\n suu = np.dot(u, u)\n svv = np.dot(v, v)\n suv = np.dot(u, v)\n\n else:\n if wxy is None:\n w = np.array(wuv, dtype=np.longdouble)\n elif wuv is None:\n w = np.array(wxy, dtype=np.longdouble)\n else:\n # 1/w = sigma**2 = sigma_xy**2 + sigma_uv**2 = 1/wxy + 1/wuv\n wuv = np.array(wuv, dtype=np.longdouble)\n wxy = np.array(wxy, dtype=np.longdouble)\n m = np.logical_and(wuv > 0, wxy > 0)\n w = np.zeros_like(wuv)\n w[m] = wxy[m] * wuv[m] / (wxy[m] + wuv[m])\n\n if np.any(w < 0.0):\n raise ValueError(\"Invalid weights: weights must be non-negative.\")\n\n if np.sum(w > 0) < 3:\n raise ValueError(\"Not enough valid data for 'general' fit: \"\n \"too many weights are zero!\")\n\n # Set up products used for computing the fit\n sw = np.sum(w, dtype=np.longdouble)\n sx = np.dot(w, x)\n sy = np.dot(w, y)\n su = np.dot(w, u)\n sv = np.dot(w, v)\n\n sxu = np.dot(w, x * u)\n syu = np.dot(w, y * u)\n sxv = np.dot(w, x * v)\n syv = np.dot(w, y * v)\n suu = np.dot(w, u * u)\n svv = np.dot(w, v * v)\n suv = np.dot(w, u * v)\n\n m = np.array([[su, sv, sw], [suu, suv, su], [suv, svv, sv]],\n dtype=np.longdouble)\n a = np.array([sx, sxu, sxv], dtype=np.longdouble)\n b = np.array([sy, syu, syv], dtype=np.longdouble)\n\n try:\n inv_m = inv(m)\n except np.linalg.LinAlgError:\n raise SingularMatrixError(\n \"Singular matrix: suspected colinear points.\"\n )\n\n p = np.dot(inv_m, a)\n q = np.dot(inv_m, b)\n if not (np.all(np.isfinite(p)) and np.all(np.isfinite(q))):\n raise SingularMatrixError(\n \"Singular matrix: suspected colinear points.\"\n ) # pragma: no cover\n\n # Return the shift, rotation, and scale changes\n fit = _build_fit(p, q, 'general')\n resids = xy - np.dot(uv, fit['matrix_ld'].T) - fit['shift_ld']\n fit['resids'] = resids.astype(np.double)\n _compute_stat(fit, residuals=resids, weights=w)\n return fit\n\n\ndef _build_fit(p, q, fitgeom):\n # Build fit matrix:\n fit_matrix = np.vstack((p[:2], q[:2]))\n\n # determinant of the transformation\n det = p[0] * q[1] - p[1] * q[0]\n sdet = np.sign(det)\n proper = sdet >= 0\n\n # Create a working copy (no reflections) for computing transformation\n # parameters (scale, rotation angle, skew):\n wfit = fit_matrix.copy()\n\n # Skew is zero for all fitgeom except 'general':\n skew = 0.0\n\n if fitgeom == 'shift':\n fit = {\n 'shift': np.array([p[2], q[2]], dtype=np.double),\n 'shift_ld': np.array([p[2], q[2]], dtype=np.longdouble),\n 'matrix': np.array(fit_matrix, dtype=np.double),\n 'matrix_ld': np.array(fit_matrix, dtype=np.longdouble),\n 'proper_rot': 0.0,\n 'rot': (0.0, 0.0),\n '<rot>': 0.0,\n 'scale': (1.0, 1.0),\n '<scale>': 1.0,\n 'skew': 0.0,\n 'proper': proper,\n 'fitgeom': 'shift'\n }\n\n return fit\n\n # Compute average scale:\n s = np.sqrt(np.abs(det))\n # Compute scales for each axis:\n if fitgeom == 'general':\n sx, sy = np.sqrt(p[:2]**2 + q[:2]**2)\n else:\n sx = s\n sy = s\n\n # Remove scale from the transformation matrix:\n wfit[:, 0] /= sx\n wfit[:, 1] /= sy\n\n # Compute rotation angle as if we have a proper rotation.\n # This will also act as *some sort* of \"average rotation\" even for\n # transformations with different rot_x and rot_y:\n prop_rot = np.rad2deg(\n np.arctan2(wfit[0, 1] - sdet * wfit[1, 0],\n wfit[0, 0] + sdet * wfit[1, 1])\n )\n\n if proper and fitgeom == 'rscale':\n rotx = prop_rot\n roty = prop_rot\n rot = prop_rot\n\n else:\n rotx = np.rad2deg(np.arctan2(-wfit[1, 0], wfit[0, 0]))\n roty = np.rad2deg(np.arctan2(wfit[0, 1], wfit[1, 1]))\n rot = 0.5 * (rotx + roty)\n skew = np.mod(roty - rotx - 180.0, 360.0) - 180.0\n\n fit = {\n 'shift': np.array([p[2], q[2]], dtype=np.double),\n 'shift_ld': np.array([p[2], q[2]], dtype=np.longdouble),\n 'matrix': np.array(fit_matrix, dtype=np.double),\n 'matrix_ld': np.array(fit_matrix, dtype=np.longdouble),\n 'proper_rot': float(prop_rot),\n 'rot': (float(rotx), float(roty)),\n '<rot>': float(rot),\n 'scale': (float(sx), float(sy)),\n '<scale>': float(s),\n 'skew': float(skew),\n 'proper': proper,\n 'fitgeom': fitgeom\n }\n\n return fit\n\n\ndef build_fit_matrix(rot, scale=1):\n r\"\"\"\n Create an affine transformation matrix (2x2) from the provided rotation\n angle(s) and scale(s):\n\n .. math::\n\n M = \\begin{bmatrix}\n s_x \\cos(\\theta_x) & s_y \\sin(\\theta_y) \\\\\n -s_x \\sin(\\theta_x) & s_y \\cos(\\theta_y)\n \\end{bmatrix}\n\n Parameters\n ----------\n rot: tuple, float, optional\n Rotation angle in degrees. Two values (one for each axis) can be\n provided as a tuple.\n\n scale: tuple, float, optional\n Scale of the liniar transformation. Two values (one for each axis)\n can be provided as a tuple.\n\n Returns\n -------\n matrix: numpy.ndarray\n A 2x2 `numpy.ndarray` containing coefficients of a liniear\n transformation.\n\n \"\"\"\n if hasattr(rot, '__iter__'):\n rx, ry = map(np.deg2rad, rot)\n else:\n rx = ry = np.deg2rad(float(rot))\n\n if hasattr(scale, '__iter__'):\n sx, sy = scale\n else:\n sx = sy = float(scale)\n\n matrix = np.array([[sx * np.cos(rx), sy * np.sin(ry)],\n [-sx * np.sin(rx), sy * np.cos(ry)]])\n\n return matrix\n" ]
[ [ "numpy.dot", "numpy.mean", "numpy.sign", "numpy.cos", "numpy.deg2rad", "numpy.count_nonzero", "numpy.linalg.norm", "numpy.zeros_like", "numpy.sin", "numpy.logical_and", "numpy.sqrt", "numpy.isfinite", "numpy.mod", "numpy.vstack", "numpy.array", "numpy.subtract", "numpy.arctan2", "numpy.asarray", "numpy.sum", "numpy.any", "numpy.abs", "numpy.longdouble" ] ]
times-software/Corvus
[ "d220e2db28743ecb6748e2a245eb3992daa554c1" ]
[ "corvus/mbconv.py" ]
[ "from corvus.structures import Handler, Exchange, Loop, Update\nimport corvutils.pyparsing as pp\nimport os, sys, subprocess, shutil #, resource\nimport re\nfrom scipy.interpolate import CubicSpline\nfrom scipy.integrate import quad\nfrom scipy.signal import convolve\nimport numpy as np\n# Debug: FDV\nimport pprint\n\npp_debug = pprint.PrettyPrinter(indent=4)\n\n\n# Define dictionary of implemented calculations\nimplemented = {}\nstrlistkey = lambda L:','.join(sorted(L))\nsubs = lambda L:[{L[j] for j in range(len(L)) if 1<<j&k} for k in range(1,1<<len(L))]\n#for s in subs(['cell_vectors', 'cell_struct_xyz_red', 'cell_scaling_iso', 'cell_scaling_abc', 'number_density']):\n# key = strlistkey(s)\n# autodesc = 'Get ' + ', '.join(s) + ' using cif2cell'\n# cost = 10\n# implemented[key] = {'type':'Exchange','out':list(s),'req':['cif_input'],\n# 'desc':autodesc,'cost':cost}\n\nimplemented['mbxanes'] = {'type':'Exchange','out':['mbxanes'],'cost':0,\n 'req':['xanes_cfavg','spectralFunction'],'desc':'Calculate many-body xanes from xanes and spectral function.'}\n#'req':['xanes','spectal_function'],'desc':'Calculate supercell from cif input.'}\n\n\n\nclass mbconv(Handler):\n def __str__(self):\n return 'mbconv Handler'\n\n @staticmethod\n def canProduce(output):\n if isinstance(output, list) and output and isinstance(output[0], str):\n return strlistkey(output) in implemented\n elif isinstance(output, str):\n return output in implemented\n else:\n raise TypeError('Output should be token or list of tokens')\n\n @staticmethod\n def requiredInputFor(output):\n if isinstance(output, list) and output and isinstance(output[0], str):\n unresolved = {o for o in output if not mbconv.canProduce(o)}\n canProduce = (o for o in output if mbconv.canProduce(o))\n additionalInput = (set(implemented[o]['req']) for o in canProduce)\n return list(set.union(unresolved,*additionalInput))\n elif isinstance(output, str):\n if output in implemented:\n return implemented[output]['req']\n else:\n return [output]\n else:\n raise TypeError('Output should be token or list of tokens')\n\n @staticmethod\n def cost(output):\n if isinstance(output, list) and output and isinstance(output[0], str):\n key = strlistkey(output)\n elif isinstance(output, str):\n key = output\n else:\n raise TypeError('Output should be token or list of tokens')\n if key not in implemented:\n raise LookupError('Corvus cannot currently produce ' + key + ' using FEFF')\n return implemented[key]['cost']\n\n @staticmethod\n def sequenceFor(output,inp=None):\n if isinstance(output, list) and output and isinstance(output[0], str):\n key = strlistkey(output)\n elif isinstance(output, str):\n key = output\n else:\n raise TypeError('Output should be token of list of tokens')\n if key not in implemented:\n raise LookupError('Corvus cannot currently produce ' + key + ' using FEFF')\n f = lambda subkey : implemented[key][subkey]\n required = f('req')\n # JJK - Need to add requirements of internal workflow here.\n if 'mbconv' in list(inp.keys()):\n required.extend()\n\n if f('type') is 'Exchange':\n return Exchange(mbconv, f('req'), f('out'), cost=f('cost'), desc=f('desc'))\n\n @staticmethod\n def prep(config):\n subdir = config['pathprefix'] + str(config['xcIndex']) + '_MBXANES'\n xcDir = os.path.join(config['cwd'], subdir)\n # Make new output directory if if doesn't exist\n if not os.path.exists(xcDir):\n os.mkdir(xcDir)\n # Store current Exchange directory in configuration\n config['xcDir'] = xcDir\n\n #@staticmethod\n #def setDefaults(input,target):\n\n @staticmethod\n def run(config, input, output):\n\n\n \n # Loop over targets in output.\n if 'mbxanes' in output:\n # In future use file_reader handler to read in XANES and spectral function if already calculated.\n w = np.array(input.get('xanes_cfavg')[0])\n mu0= np.array(input.get('xanes_cfavg')[1])\n wsf= np.flip(-1.0*np.array(input.get('spectralFunction')[0]))\n sf = np.flip(np.array(input.get('spectralFunction')[1]))\n # Interpolate both XANES and spectral function onto an even grid\n #w, mu0 = np.loadtxt('xanes.dat',usecols = (0,1)).T\n #wsf,sf = np.loadtxt('spfcn.dat',usecols = (0,1)).T\n min_diff = np.amin(np.ediff1d(w))\n min_diff = min(min_diff,np.amin(np.ediff1d(wsf)))\n \n mu0_cs = CubicSpline(w,mu0)\n spfcn_cs = CubicSpline(wsf,sf)\n # Use larger of two ranges to specify range\n w_terp = np.arange(w[0],w[-1],min_diff)\n wsf_terp = np.arange(wsf[0],wsf[-1],min_diff)\n mu0_terp = mu0_cs(w_terp)\n spfcn_terp = spfcn_cs(wsf_terp)\n \n mu_mb = convolve(mu0_terp,spfcn_terp,mode='full')*min_diff\n\n # If extra broadening is requested, perform a convolution of that as well.\n if 'mbconv.extra_broadening' in input:\n gam = input['mbconv.extra_broadening'][0][0]\n A_br = gam/np.pi*1.0/(wsf_terp**2 + gam**2)\n mu_mb = np.convolve(mu_mb,A_br,mode='same')*min_diff\n \n scale=w_terp[-1] - w_terp[0] + wsf_terp[-1] - wsf_terp[0]\n first = w_terp[0] + wsf_terp[0]\n w_terp = np.linspace(0.0,scale,mu_mb.size) \n w_terp = w_terp + first\n mu0_terp = mu0_cs(w_terp)\n output['mbxanes'] = [w_terp,mu_mb]\n np.savetxt('mbxanes.dat',np.array([w_terp, mu_mb, mu0_terp]).transpose())\n\n\n\n @staticmethod\n def cleanup(config):\n pass\n\n\n\n\n\n" ]
[ [ "numpy.array", "numpy.convolve", "scipy.interpolate.CubicSpline", "numpy.ediff1d", "numpy.arange", "numpy.linspace", "scipy.signal.convolve" ] ]
shaun95/google-research
[ "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5", "d41bbaca1eb9bfd980ec2b3fd201c3ddb4d1f2e5" ]
[ "widget_caption/widget_caption_model.py", "graph_embedding/slaq/slaq.py", "extreme_memorization/cifar100_dataset.py", "social_rl/gym_multigrid/envs/tag.py", "fairness_teaching/rl/train.py", "reset_free_learning/test_script.py", "readtwice/layers/recompute_grad.py", "routing_transformer/sparse_image_transformer.py", "vatt/modeling/backbones/text/factory.py", "uflow/misc/convert_video_to_dataset_test.py", "task_set/registry_test.py", "policy_eval/dual_dice.py", "infinite_nature/loss_impl.py", "kws_streaming/models_sub/tflite_utils.py", "representation_batch_rl/representation_batch_rl/cssc_pixels.py", "smu/pipeline_test.py", "muzero/atari/network.py", "snlds/forward_backward_algo.py", "darc/darc_envs.py", "poem/tools/gen_train_tfrecords.py", "hal/labeler/answering_model/train_answering_model.py", "blur/blur.py", "sgk/sparse/connectors.py", "graph_compression/compression_lib/examples/cifar10/cifar10_compression.py", "ieg/models/model.py", "graph_embedding/persona/splitter.py", "tf3d/data_provider.py" ]
[ "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Widget captioning model.\"\"\"\nimport collections\nimport os\n\nfrom absl import app\nfrom absl import flags\nfrom absl import logging\nimport numpy as np\nimport tensorflow as tf\n\nfrom widget_caption import widget_caption_config\nfrom widget_caption import widget_caption_eval\nfrom widget_caption import widget_caption_input as input_utils\nfrom tensorflow_models.official.legacy.transformer import model_params\nfrom tensorflow_models.official.legacy.transformer import model_utils\nfrom tensorflow_models.official.legacy.transformer import optimizer\nfrom tensorflow_models.official.legacy.transformer import transformer as nlp_transformer\nfrom tensorflow_models.official.nlp.modeling import layers\nfrom tensorflow_models.official.nlp.modeling import ops\n\nflags.DEFINE_string('experiment', 'debug',\n 'Experiment name defined in widget_caption_config.py.')\n\nflags.DEFINE_string('model_dir', None, 'Model dir')\n\nflags.DEFINE_string('ckpt_filepath', None,\n 'Checkpoint path for saving weights of every epoch.')\n\nFLAGS = flags.FLAGS\n\n\ndef create_hparams(experiment):\n \"\"\"Creates the hyper parameters.\"\"\"\n hparams = {}\n\n # General parameters.\n hparams['batch_size'] = 64\n hparams['eval_batch_size'] = 64\n hparams['learning_rate_warmup_steps'] = 2000\n hparams['learning_rate_constant'] = 1\n hparams['learning_rate'] = 0.001\n hparams['train_epoches'] = 20\n hparams['steps_per_epoch'] = 30\n hparams['train_steps'] = 100 * 1000\n hparams['eval_steps'] = 100\n hparams['caption_optimizer'] = 't2t'\n hparams['clip_norm'] = 5.0\n hparams['widget_encoder_checkpoint'] = ''\n hparams['train_files'] = ''\n hparams['eval_files'] = ''\n hparams['train_buffer_size'] = 2000\n hparams['eval_buffer_size'] = 500\n hparams['train_pixel_encoder'] = True\n hparams['debug'] = False\n hparams['distribution_strategy'] = 'mirrored'\n\n # Train model using decoding task, classification task, or both.\n hparams['decoding_task'] = True\n hparams['classification_task'] = False\n # Whether to use decoding for phrase classification: <START> phrase_id <EOS>.\n hparams['use_decoding_for_classification'] = False\n\n # Weight for the classification loss.\n hparams['classification_loss_weight'] = 1\n hparams['train_with_one_node'] = False\n\n # Embedding parameters.\n hparams['embedding_file'] = ''\n hparams['word_vocab_path'] = ''\n hparams['glove_trainable'] = True\n hparams['vocab_size'] = 10000\n hparams['phrase_vocab_size'] = 10000\n\n # View hierarchy encoder parameters.\n hparams['max_pixel_pos'] = 100\n hparams['max_dom_pos'] = 500\n hparams['screen_encoder'] = 'gcn'\n hparams['screen_embedding_feature'] = ['text', 'type', 'pos', 'click', 'dom']\n hparams['obj_text_aggregation'] = 'max'\n hparams['synthetic_screen_noise'] = 0.\n # Whether to add pixel encoding as input to view hierarchy encoder.\n hparams['encode_screen_with_context'] = False\n # Whether to add a residual link for pixel encoding.\n hparams['add_pixel_skip_link'] = False\n\n # General parameters.\n hparams['num_hidden_layers'] = 2\n hparams['hidden_size'] = 2\n hparams['filter_size'] = 2\n hparams['num_heads'] = 2\n hparams['dropout'] = 0.2\n hparams['layer_prepostprocess_dropout'] = 0.2\n hparams['attention_dropout'] = 0.2\n hparams['relu_dropout'] = 0.2\n\n transformer_hparams = model_params.BASE_PARAMS\n\n # Add parameters from transformer model.\n hparams.update(transformer_hparams)\n\n # Rewrite all the parameters from command-line flags.\n config = widget_caption_config.experiments[experiment]\n hparams.update(config)\n\n return hparams\n\n\ndef load_embed(file_name, vocab_size):\n \"\"\"Loads a pre-trained embedding matrix.\n\n Args:\n file_name: the file name of the embedding file.\n vocab_size: if > 0, only load embedding weights for vocab_size words.\n\n Returns:\n vocab: a list of tokens.\n embeds: a numpy array of embeddings for each token plus an OOV embedding.\n depth: the depth of the embedding.\n Raises:\n ValueError: embeddings have different depths.\n \"\"\"\n\n with tf.io.gfile.GFile(file_name, 'r') as embed_file:\n vocab = []\n embeds = []\n depth = -1\n for index, line in enumerate(embed_file):\n if vocab_size > 0 and index >= vocab_size:\n break\n line = line.strip()\n tokens = line.strip().split(' ')\n word = tokens[0]\n vocab.append(word)\n if depth == -1:\n embed = [float(token) for token in tokens[1:]]\n else:\n embed = [float(token) for token in tokens[-depth:]]\n d = len(embed)\n if depth == -1:\n depth = d\n if d != depth:\n raise ValueError('Inconsistent embedding sizes')\n embeds.append(embed)\n\n embeds = np.stack(embeds)\n\n return vocab, embeds, depth\n\n\ndef compute_score(predictions, references, vocab=None):\n \"\"\"Computes the bleu score.\n\n Args:\n predictions: a numpy arrary in the shape of [batch_size, max_phrase_length]\n references: a numpy array in the shape of [batch_size, 7, 10]\n vocab: the vocabulary file.\n\n Returns:\n a scalar value for the corpus level bleu score.\n \"\"\"\n assert np.rank(predictions) == 2\n assert predictions.shape[0] == references.shape[0]\n batch_size = predictions.shape[0]\n predictions = tf.make_ndarray(tf.make_tensor_proto(predictions)).tolist()\n references = tf.make_ndarray(tf.make_tensor_proto(references)).tolist()\n hypotheses_list = []\n references_list = []\n for index in range(batch_size):\n h = predictions[index]\n try:\n eos_index = h.index(input_utils.EOS)\n except ValueError:\n eos_index = len(h)\n hypotheses_list.append(h[:eos_index])\n\n ref = references[index].decode().split('|')\n ref_list = [r.strip().split(' ') for r in ref if r.strip()]\n references_list.append(ref_list)\n\n all_scores = collections.defaultdict(list)\n for hypothesis, references in zip(hypotheses_list, references_list):\n if vocab is not None and len(vocab):\n # Skip PADDING, UNK, EOS, START (0-3).\n hypothesis = [\n vocab[word_id].numpy().decode()\n for word_id in hypothesis\n if word_id > 3\n ]\n logging.info('hypothesis: %s', str(hypothesis))\n logging.info('references: %s', str(references))\n\n h_str = ' '.join(str(e) for e in hypothesis)\n r_str = [' '.join(str(e) for e in ref) for ref in references]\n\n scores = widget_caption_eval.coco_evaluate(r_str, h_str)\n for key, score in scores.items():\n all_scores[key].append(score)\n\n score_names = [\n 'BLEU-1', 'BLEU-2', 'BLEU-3', 'BLEU-4', 'ROUGE-1-f1-mean',\n 'ROUGE-1-f1-min', 'ROUGE-1-f1-max', 'ROUGE-2-f1-mean', 'ROUGE-2-f1-min',\n 'ROUGE-2-f1-max', 'ROUGE-L-f1-mean', 'ROUGE-L-f1-min', 'ROUGE-L-f1-max'\n ]\n return [np.array(all_scores[name], dtype=np.float32) for name in score_names]\n\n\nclass EmbeddingLayer(tf.keras.layers.Layer):\n \"\"\"Embedding layer.\"\"\"\n\n def __init__(self,\n name,\n vocab_size,\n embedding_dim,\n embedding_file=None,\n hidden_dim=None,\n trainable=True):\n super(EmbeddingLayer, self).__init__(name=name)\n self._vocab_size = vocab_size\n self._hidden_dim = hidden_dim\n self._embedding_dim = embedding_dim\n self._embedding_file = embedding_file\n self._trainable = trainable\n\n def build(self, input_shape):\n if self._embedding_file:\n logging.info('Load embedding file for %s of vocab size %s: %s',\n self._name, self._vocab_size, self._embedding_file)\n _, embedding_weights, depth = load_embed(\n file_name=self._embedding_file, vocab_size=self._vocab_size)\n self._embedding_dim = depth\n initializer = tf.constant_initializer(\n embedding_weights[:self._vocab_size, :])\n else:\n logging.info('Create random embedding matrix for %s of size %s',\n self._name, self._vocab_size)\n initializer = tf.keras.initializers.RandomNormal(\n mean=0.0, stddev=0.1, seed=None)\n\n self.embeddings = self.add_weight(\n name='{}_weights'.format(self._name),\n shape=(self._vocab_size, self._embedding_dim),\n initializer=initializer,\n trainable=self._trainable,\n dtype='float32')\n\n if self._hidden_dim:\n self._project_layer = tf.keras.layers.Dense(self._hidden_dim)\n\n def call(self, inputs):\n embeddings = tf.nn.embedding_lookup(self.embeddings, inputs)\n if self._hidden_dim:\n embeddings = self._project_layer(embeddings)\n return embeddings\n\n\nclass PixelEncoderLayer(tf.keras.layers.Layer):\n \"\"\"Pixel encoding layer (ResNet).\"\"\"\n\n def __init__(self, name, filters, kernel_sizes):\n super(PixelEncoderLayer, self).__init__(name=name)\n self._filters = filters\n self._kernel_sizes = kernel_sizes\n\n def build(self, input_shape):\n self._conv_layer_1 = tf.keras.layers.Conv2D(\n filters=self._filters[0],\n kernel_size=self._kernel_sizes[0],\n strides=1,\n padding='same')\n self._conv_layer_2 = tf.keras.layers.Conv2D(\n filters=self._filters[1],\n kernel_size=self._kernel_sizes[1],\n strides=1,\n padding='same')\n self._conv_layer_3 = tf.keras.layers.Conv2D(\n filters=self._filters[2],\n kernel_size=self._kernel_sizes[2],\n strides=2,\n padding='same')\n\n self._batch_norm_layer_1 = tf.keras.layers.BatchNormalization()\n self._batch_norm_layer_2 = tf.keras.layers.BatchNormalization()\n self._batch_norm_layer_3 = tf.keras.layers.BatchNormalization()\n\n def call(self, input_tensor, training, dropout=0.0):\n \"\"\"Defines a single encoding layer.\"\"\"\n x = input_tensor\n skip = x\n\n x = self._conv_layer_1(x)\n x = self._batch_norm_layer_1(x, training=training)\n x = tf.nn.relu(x)\n if training:\n x = tf.nn.dropout(x, rate=dropout)\n\n x = self._conv_layer_2(x)\n x = self._batch_norm_layer_2(x, training=training)\n x += skip\n x = tf.nn.relu(x)\n if training:\n x = tf.nn.dropout(x, rate=dropout)\n\n x = self._conv_layer_3(x)\n x = self._batch_norm_layer_3(x, training=training)\n x = tf.nn.relu(x)\n if training:\n x = tf.nn.dropout(x, rate=dropout)\n\n return x\n\n\nclass EncoderLayer(tf.keras.layers.Layer):\n \"\"\"Generates encoder outputs for both the pixels and view hierarchy.\"\"\"\n\n def __init__(self, hparams, word_embedding_layer):\n super(EncoderLayer, self).__init__(name='dual_encoder')\n self._hparams = hparams\n self._word_embedding_layer = word_embedding_layer\n\n def build(self, input_shape):\n self._type_embedding_layer = EmbeddingLayer(\n name='object_type',\n vocab_size=100,\n embedding_dim=self._hparams['hidden_size'])\n self._clickable_embedding_layer = EmbeddingLayer(\n name='object_clickable',\n vocab_size=2,\n embedding_dim=self._hparams['hidden_size'])\n self._pos_embedding_layers = [\n EmbeddingLayer(\n name='object_pos_0',\n vocab_size=self._hparams['max_pixel_pos'],\n embedding_dim=self._hparams['hidden_size']),\n EmbeddingLayer(\n name='object_pos_1',\n vocab_size=self._hparams['max_pixel_pos'],\n embedding_dim=self._hparams['hidden_size']),\n EmbeddingLayer(\n name='object_pos_2',\n vocab_size=self._hparams['max_pixel_pos'],\n embedding_dim=self._hparams['hidden_size']),\n EmbeddingLayer(\n name='object_pos_3',\n vocab_size=self._hparams['max_pixel_pos'],\n embedding_dim=self._hparams['hidden_size'],\n )\n ]\n self._dom_embedding_layers = [\n EmbeddingLayer(\n name='object_dom_pos_0',\n vocab_size=self._hparams['max_dom_pos'],\n embedding_dim=self._hparams['hidden_size']),\n EmbeddingLayer(\n name='object_dom_pos_1',\n vocab_size=self._hparams['max_dom_pos'],\n embedding_dim=self._hparams['hidden_size']),\n EmbeddingLayer(\n name='object_dom_pos_2',\n vocab_size=self._hparams['max_dom_pos'],\n embedding_dim=self._hparams['hidden_size'])\n ]\n\n self._final_layer = tf.keras.layers.Dense(\n self._hparams['hidden_size'], activation=None)\n self._vh_final_layer = tf.keras.layers.Dense(\n self._hparams['hidden_size'], activation=tf.nn.tanh)\n self._pixel_layers = self._get_encoder3(initial_channel_size=1)\n self._transformer_encoder = nlp_transformer.EncoderStack(self._hparams)\n\n def call(self, features, object_selector, training):\n # Compute encoding\n with tf.name_scope('encoder'):\n pixel_encoding = self._encode_pixel(features, object_selector, training)\n vh_encoding, obj_embedding = self._encode_view_hierarchy(\n features, object_selector, training)\n\n logging.info('Screen encoder: %s', self._hparams['screen_encoder'])\n if self._hparams['screen_encoder'] == 'pixel_only':\n combined_output = pixel_encoding\n elif self._hparams['screen_encoder'] == 'pixel_transformer':\n combined_output = tf.concat([pixel_encoding, vh_encoding], -1)\n elif self._hparams['screen_encoder'] == 'pixel_mlp':\n combined_output = tf.concat([pixel_encoding, obj_embedding], -1)\n else:\n raise ValueError\n\n # [valid_obj, hidden_size]\n logits = self._final_layer(combined_output)\n logits = tf.nn.relu(logits)\n if training:\n logits = tf.nn.dropout(logits, rate=self._hparams['dropout'])\n # Add the length dimension.\n logits = tf.expand_dims(logits, 1)\n return logits\n\n def _encode_pixel(self, features, object_selector, training):\n # Flatten object pixels.\n obj_pixels = tf.reshape(features['obj_pixels'], [-1, 64, 64, 1])\n # Otherwise, we just encode worker nodes' pixels.\n valid_obj_pixels = tf.gather(obj_pixels, object_selector)\n\n thumbnail_encoding = valid_obj_pixels\n for layer in self._pixel_layers:\n thumbnail_encoding = layer(\n thumbnail_encoding,\n training=training,\n dropout=self._hparams['dropout'])\n\n # [worker_node, 256]\n thumbnail_encoding = tf.reshape(thumbnail_encoding, [-1, 256])\n\n return thumbnail_encoding\n\n def _get_encoder3(self, initial_channel_size=3):\n \"\"\"Defines the encoding model with a pre-defined filter/kernel sizes.\"\"\"\n pixel_layers = []\n filter_groups = [[initial_channel_size, initial_channel_size, 4],\n [4, 4, 16], [16, 16, 32], [32, 32, 64], [64, 64, 128],\n [128, 128, 256]]\n kernel_size_groups = [[5, 3, 5], [5, 3, 3], [3, 3, 3], [3, 3, 3], [3, 3, 3],\n [3, 3, 3]]\n\n for index, (filters, kernel_sizes) in enumerate(\n zip(filter_groups, kernel_size_groups)):\n assert len(filters) == len(kernel_sizes)\n name = 'pixel_encoder_{}'.format(index)\n layer = PixelEncoderLayer(name, filters, kernel_sizes)\n pixel_layers.append(layer)\n\n return pixel_layers\n\n def _embed_composite_feature(self, features, embedding_layers):\n \"\"\"Embed a position feature.\"\"\"\n embedding_list = []\n for i in range(len(embedding_layers)):\n embedding_list.append(embedding_layers[i](features[:, :, i]))\n embedding = tf.add_n(embedding_list)\n return embedding\n\n def _encode_view_hierarchy(self, features, object_selector, training):\n \"\"\"Encodes view hierarchy.\"\"\"\n logging.info('Using Transformer screen encoder')\n\n # obj_text only contain the first phrase if multiple exist.\n # [batch, node_num, 10, hidden_size]\n developer_embeddings = self._word_embedding_layer(\n features['developer_token_id'])\n resource_embeddings = self._word_embedding_layer(\n features['resource_token_id'])\n\n developer_embeddings = self._aggregate_text_embedding(\n features['developer_token_id'], developer_embeddings)\n resource_embeddings = self._aggregate_text_embedding(\n features['resource_token_id'], resource_embeddings)\n\n type_embedding = self._type_embedding_layer(\n tf.maximum(features['obj_type'], 0))\n clickable_embedding = self._clickable_embedding_layer(\n features['obj_clickable'])\n\n object_info = []\n if 'text' in self._hparams['screen_embedding_feature']:\n object_info.append(developer_embeddings)\n object_info.append(resource_embeddings)\n if 'type' in self._hparams['screen_embedding_feature']:\n object_info.append(type_embedding)\n if 'pos' in self._hparams['screen_embedding_feature']:\n pos_embedding = self._embed_composite_feature(features['obj_screen_pos'],\n self._pos_embedding_layers)\n object_info.append(pos_embedding)\n if 'click' in self._hparams['screen_embedding_feature']:\n object_info.append(clickable_embedding)\n if 'dom' in self._hparams['screen_embedding_feature']:\n dom_embedding = self._embed_composite_feature(features['obj_dom_pos'],\n self._dom_embedding_layers)\n object_info.append(dom_embedding)\n\n object_embed = tf.concat(object_info, -1)\n object_embed = self._vh_final_layer(object_embed)\n\n # [batch, obj_num]\n object_mask = tf.cast(tf.not_equal(features['obj_type'], -1), tf.float32)\n # [batch, obj_num, hidden_dim]\n object_embed = object_embed * tf.expand_dims(object_mask, -1)\n att_bias = model_utils.get_padding_bias(object_mask)\n\n if training:\n object_embed = tf.nn.dropout(object_embed, rate=self._hparams['dropout'])\n\n encoder_output = self._transformer_encoder(\n object_embed,\n attention_bias=att_bias,\n inputs_padding=None, # not used in EncoderStack.\n training=training)\n\n object_embed = tf.reshape(object_embed, [-1, self._hparams['hidden_size']])\n encoder_output = tf.reshape(encoder_output,\n [-1, self._hparams['hidden_size']])\n valid_object_embed = tf.gather(object_embed, object_selector)\n valid_screen_encoding = tf.gather(encoder_output, object_selector)\n return valid_screen_encoding, valid_object_embed\n\n def _aggregate_text_embedding(self, token_ids, embeddings):\n \"\"\"Aggregate text embedding for a UI element.\"\"\"\n if self._hparams['obj_text_aggregation'] == 'max':\n # Find valid tokens (not PADDING/EOS/UNK/START).\n valid_token_mask = tf.greater_equal(token_ids, 4)\n # Use large negative bias for invalid tokens.\n invalid_token_bias = tf.cast(\n tf.logical_not(valid_token_mask), tf.float32) * -1e9\n # [batch, node_num, word_num, hidden_size]\n embeddings = embeddings + tf.expand_dims(invalid_token_bias, axis=-1)\n # Max value for each dimension, [batch, node_num, hidden_size].\n embeddings = tf.reduce_max(embeddings, axis=-2)\n # For objects with no text, use 0.\n valid_object_mask = tf.cast(\n tf.reduce_any(valid_token_mask, axis=-1), tf.float32)\n embeddings = embeddings * tf.expand_dims(valid_object_mask, axis=-1)\n\n elif self._hparams['obj_text_aggregation'] == 'sum':\n # [batch, step, #max_obj, #max_token] 0 for padded tokens\n real_objects = tf.cast(tf.greater_equal(token_ids, 4), tf.float32)\n # [batch, step, #max_obj, hidden] 0s for padded objects\n embeddings = tf.reduce_sum(\n input_tensor=embeddings * tf.expand_dims(real_objects, 3), axis=-2)\n\n else:\n raise ValueError('Unrecognized token aggregation %s' %\n (self._hparams['obj_text_aggregation']))\n return embeddings\n\n\nclass DecoderLayer(tf.keras.layers.Layer):\n \"\"\"Captioning decoder layer.\"\"\"\n\n def __init__(self, hparams, word_embedding_layer, position_embedding_layer):\n super(DecoderLayer, self).__init__(name='decoder')\n self._hparams = hparams\n self._word_embedding_layer = word_embedding_layer\n self._position_embedding_layer = position_embedding_layer\n\n def build(self, inputs):\n self._transformer_decoder = nlp_transformer.DecoderStack(self._hparams)\n\n def call(self,\n decoder_inputs,\n encoder_outputs,\n decoder_self_attention_bias,\n attention_bias,\n training,\n cache=None):\n \"\"\"Return the output of the decoder layer stacks.\n\n Args:\n decoder_inputs: A tensor with shape [batch_size, target_length,\n hidden_size].\n encoder_outputs: A tensor with shape [batch_size, input_length,\n hidden_size]\n decoder_self_attention_bias: A tensor with shape [1, 1, target_len,\n target_length], the bias for decoder self-attention layer.\n attention_bias: A tensor with shape [batch_size, 1, 1, input_length], the\n bias for encoder-decoder attention layer.\n training: A bool, whether in training mode or not.\n cache: (Used for fast decoding) A nested dictionary storing previous\n decoder self-attention values. The items are:\n {layer_n: {\"k\": A tensor with shape [batch_size, i, key_channels],\n \"v\": A tensor with shape [batch_size, i, value_channels]},\n ...}\n\n Returns:\n Output of decoder layer stack.\n float32 tensor with shape [batch_size, target_length, hidden_size]\n \"\"\"\n # Run values\n outputs = self._transformer_decoder(\n decoder_inputs,\n encoder_outputs,\n decoder_self_attention_bias,\n attention_bias,\n training=training,\n cache=cache)\n return outputs\n\n\nclass WidgetCaptionModel(tf.keras.Model):\n \"\"\"Widget Captioning Model.\"\"\"\n _SCORE_NAMES = [\n 'BLEU-1', 'BLEU-2', 'BLEU-3', 'BLEU-4', 'ROUGE-1-f1-mean',\n 'ROUGE-1-f1-min', 'ROUGE-1-f1-max', 'ROUGE-2-f1-mean', 'ROUGE-2-f1-min',\n 'ROUGE-2-f1-max', 'ROUGE-L-f1-mean', 'ROUGE-L-f1-min', 'ROUGE-L-f1-max'\n ]\n\n # 10 words + EOS symbol.\n _MAX_DECODE_LENGTH = 11\n\n def __init__(self, hparams):\n super(WidgetCaptionModel, self).__init__()\n self._hparams = hparams\n with tf.name_scope('captioning'):\n self._word_embedding_layer = EmbeddingLayer(\n name='word',\n hidden_dim=self._hparams['hidden_size'],\n embedding_file=self._hparams['embedding_file'],\n vocab_size=self._hparams['vocab_size'],\n embedding_dim=self._hparams['hidden_size'], # not used\n trainable=self._hparams['glove_trainable'])\n self._position_embedding_layer = layers.RelativePositionEmbedding(\n hidden_size=self._hparams['hidden_size'])\n\n self._encoder = EncoderLayer(self._hparams, self._word_embedding_layer)\n self._decoder = DecoderLayer(self._hparams, self._word_embedding_layer,\n self._position_embedding_layer)\n self._word_layer = tf.keras.layers.Dense(\n units=self._hparams['vocab_size'])\n\n self.model_metrics = {\n 'loss': tf.keras.metrics.Mean(name='loss'),\n 'global_norm': tf.keras.metrics.Mean(name='global_norm'),\n }\n\n self.caption_metrics = {}\n for score_name in self._SCORE_NAMES:\n scoped_name = 'COCO/{}'.format(score_name)\n self.caption_metrics[scoped_name] = tf.keras.metrics.Mean(\n name=scoped_name)\n\n self._word_vocab = []\n with tf.io.gfile.GFile(self._hparams['word_vocab_path']) as f:\n for index, line in enumerate(f):\n if index >= self._hparams['vocab_size']:\n break\n self._word_vocab.append(line.strip())\n\n def call(self, inputs, training):\n features, targets = inputs\n\n object_selector = self._caption_object_selector(features)\n\n encoder_outputs = self._encoder(features, object_selector, training)\n if self._hparams['decoding_task']:\n if targets is None:\n return self.predict(encoder_outputs, training)\n else:\n return self.decode(targets, encoder_outputs, training)\n\n def _caption_object_selector(self, features):\n worker = tf.reshape(tf.equal(features['label_flag'], 0), [-1])\n # [worker_node] indices into [BxN] vector for valid worker node.\n worker_position = tf.reshape(tf.where(worker), [-1])\n return worker_position\n\n def _caption_loss(self, targets, logits):\n per_example_loss = tf.nn.sparse_softmax_cross_entropy_with_logits(\n labels=targets, logits=logits)\n\n # Create non-padding mask and only compute loss for non-padding positions.\n non_padding = tf.greater(targets, input_utils.PADDING)\n mask = tf.cast(non_padding, tf.float32)\n per_example_loss = per_example_loss * mask\n avg_loss = tf.reduce_sum(per_example_loss) / tf.reduce_sum(mask)\n avg_loss = tf.cond(tf.math.is_nan(avg_loss), lambda: 0.0, lambda: avg_loss)\n return avg_loss\n\n def train_step(self, data):\n targets, _ = self.compute_targets(data)\n\n with tf.GradientTape() as tape:\n logits = self([data, targets], training=True)\n\n if self._hparams['decoding_task']:\n avg_loss = self._caption_loss(targets, logits)\n\n trainable_vars = self.trainable_variables\n gradients = tape.gradient(avg_loss, trainable_vars)\n gradients, global_norm = tf.clip_by_global_norm(\n gradients, self._hparams['clip_norm'])\n\n # Update weights\n self.optimizer.apply_gradients(zip(gradients, trainable_vars))\n\n self.model_metrics['loss'].update_state(avg_loss)\n self.model_metrics['global_norm'].update_state(global_norm)\n train_metrics = ['loss', 'global_norm']\n return {m: self.model_metrics[m].result() for m in train_metrics}\n\n def test_step(self, data):\n targets, references = self.compute_targets(data)\n logits = self([data, targets], training=False)\n avg_loss = self._caption_loss(targets, logits)\n decoded = self([data, None], training=False)\n self.compute_caption_metrics(decoded, references)\n\n self.model_metrics['loss'].update_state(avg_loss)\n return {m.name: m.result() for m in self.model_metrics.values()}\n\n def compute_caption_metrics(self, predictions, references):\n \"\"\"Computes the eval metrics for decoding.\"\"\"\n py_types = [tf.float32] * len(self._SCORE_NAMES)\n scores = tf.py_function(compute_score,\n (predictions, references, self._word_vocab),\n py_types)\n for name, score in zip(self._SCORE_NAMES, scores):\n scoped_name = 'COCO/{}'.format(name)\n self.caption_metrics[scoped_name].update_state(score)\n self.model_metrics[scoped_name] = self.caption_metrics[scoped_name]\n\n def decode(self, targets, encoder_outputs, training):\n \"\"\"Generate logits for each value in the target sequence.\n\n Args:\n targets: target values for the output sequence. int tensor with shape\n [batch_size, target_length]\n encoder_outputs: continuous representation of input sequence. float tensor\n with shape [batch_size, input_length, hidden_size]\n training: boolean, whether in training mode or not.\n\n Returns:\n float32 tensor with shape [batch_size, target_length, vocab_size]\n \"\"\"\n with tf.name_scope('decode'):\n length = tf.shape(targets)[1]\n decoder_self_attention_bias = model_utils.get_decoder_self_attention_bias(\n length)\n encoder_shape = tf.shape(encoder_outputs)\n # [batch, 1] as there is only one object as input for decoding.\n mask = tf.ones([encoder_shape[0], encoder_shape[1]])\n # In mask, 1 = valid object, 0 = padding, attn_bias will have -NEG_INF for\n # paddings and 0 for valid objects.\n attention_bias = model_utils.get_padding_bias(mask)\n\n # Prepare inputs to decoder layers by shifting targets, adding positional\n # encoding and applying dropout.\n targets = tf.pad(\n targets, [[0, 0], [1, 0]], constant_values=input_utils.START)\n # Remove last element.\n targets = targets[:, :-1]\n decoder_inputs = self._word_embedding_layer(targets)\n\n # No need to shift, use START above to shift.\n # with tf.name_scope('shift_targets'):\n # # Shift targets to the right, and remove the last element\n # decoder_inputs = tf.pad(decoder_inputs,\n # [[0, 0], [1, 0], [0, 0]])[:, :-1, :]\n\n with tf.name_scope('add_pos_encoding'):\n pos_encoding = self._position_embedding_layer(decoder_inputs)\n decoder_inputs += pos_encoding\n\n if training:\n decoder_inputs = tf.nn.dropout(\n decoder_inputs, rate=self._hparams['layer_postprocess_dropout'])\n\n decoder_outputs = self._decoder(\n decoder_inputs,\n encoder_outputs,\n decoder_self_attention_bias,\n attention_bias,\n training=training)\n logits = self._word_layer(decoder_outputs)\n return logits\n\n def predict(self, encoder_outputs, training):\n \"\"\"Return predicted sequence.\"\"\"\n batch_size = tf.shape(encoder_outputs)[0]\n # input_length = tf.shape(encoder_outputs)[1]\n # 10 words + EOS symbol\n symbols_to_logits_fn = self._get_symbols_to_logits_fn(\n max_decode_length=self._MAX_DECODE_LENGTH, training=training)\n\n # Create initial set of IDs that will be passed into symbols_to_logits_fn.\n initial_ids = tf.ones([batch_size], dtype=tf.int32) * input_utils.START\n\n # Create cache storing decoder attention values for each layer.\n # pylint: disable=g-complex-comprehension\n init_decode_length = 0\n num_heads = self._hparams['num_heads']\n dim_per_head = self._hparams['hidden_size'] // num_heads\n cache = {\n 'layer_%d' % layer: {\n 'k':\n tf.zeros(\n [batch_size, init_decode_length, num_heads, dim_per_head]),\n 'v':\n tf.zeros(\n [batch_size, init_decode_length, num_heads, dim_per_head])\n } for layer in range(self._hparams['num_hidden_layers'])\n }\n # pylint: enable=g-complex-comprehension\n\n # Add encoder output and attention bias to the cache.\n encoder_shape = tf.shape(encoder_outputs)\n # [batch, 1] as there is only one object as input for decoding.\n mask = tf.ones([encoder_shape[0], encoder_shape[1]])\n # In mask, 1 = valid object, 0 = padding, attn_bias will have -NEG_INF for\n # paddings and 0 for valid objects.\n attention_bias = model_utils.get_padding_bias(mask)\n\n cache['encoder_outputs'] = encoder_outputs\n cache['encoder_decoder_attention_bias'] = attention_bias\n\n # Use beam search to find the top beam_size sequences and scores.\n decoded_ids, _ = ops.beam_search.sequence_beam_search(\n symbols_to_logits_fn=symbols_to_logits_fn,\n initial_ids=initial_ids,\n initial_cache=cache,\n vocab_size=self._hparams['vocab_size'],\n beam_size=self._hparams['beam_size'],\n alpha=1,\n max_decode_length=self._MAX_DECODE_LENGTH,\n eos_id=input_utils.EOS)\n\n # Get the top sequence for each batch element and remove START symbol.\n top_decoded_ids = decoded_ids[:, 0, 1:]\n # top_scores = scores[:, 0]\n return top_decoded_ids\n\n def compute_targets(self, features):\n \"\"\"Compute the target token ids and phrase ids.\"\"\"\n batch_size = tf.shape(features['label_flag'])[0]\n num_objects = tf.shape(features['label_flag'])[1]\n\n worker_position = self._caption_object_selector(features)\n\n # [worker_node, 1]: retrieve the reference captions.\n valid_references = tf.gather(\n tf.reshape(features['reference'], [-1]), worker_position)\n\n # [worker_node, seq_len]: retrieve reference phrases.\n target_phrase = features['caption_token_id']\n target_phrase = tf.reshape(\n target_phrase, [batch_size * num_objects, self._MAX_DECODE_LENGTH])\n valid_target_phrase = tf.gather(target_phrase, worker_position)\n\n return valid_target_phrase, valid_references\n\n def _get_symbols_to_logits_fn(self, max_decode_length, training):\n \"\"\"Returns a decoding function that calculates logits of the next tokens.\"\"\"\n timing_signal = self._position_embedding_layer(\n inputs=None, length=max_decode_length)\n decoder_self_attention_bias = model_utils.get_decoder_self_attention_bias(\n max_decode_length)\n\n def symbols_to_logits_fn(ids, i, cache):\n \"\"\"Generate logits for next potential IDs.\n\n Args:\n ids: Current decoded sequences. int tensor with shape [batch_size *\n beam_size, i + 1].\n i: Loop index.\n cache: dictionary of values storing the encoder output, encoder-decoder\n attention bias, and previous decoder attention values.\n\n Returns:\n Tuple of\n (logits with shape [batch_size * beam_size, vocab_size],\n updated cache values)\n \"\"\"\n # Set decoder input to the last generated IDs. The previous ids attention\n # key/value are already stored in the cache.\n decoder_input = ids[:, -1:]\n\n # Preprocess decoder input by getting embeddings and adding timing signal.\n decoder_input = self._word_embedding_layer(decoder_input)\n decoder_input += timing_signal[i:i + 1]\n self_attention_bias = decoder_self_attention_bias[:, :, i:i + 1, :i + 1]\n\n decoder_outputs = self._decoder(\n decoder_input,\n cache.get('encoder_outputs'),\n self_attention_bias,\n cache.get('encoder_decoder_attention_bias'),\n training=training,\n cache=cache)\n\n # Only use the last decoded state.\n decoder_outputs = decoder_outputs[:, -1, :]\n logits = self._word_layer(decoder_outputs)\n return logits, cache\n\n return symbols_to_logits_fn\n\n\nclass TensorBoardCallBack(tf.keras.callbacks.TensorBoard):\n \"\"\"Learning rate log callback.\"\"\"\n\n def on_train_batch_begin(self, batch, logs=None):\n super(TensorBoardCallBack, self).on_train_batch_begin(batch, logs)\n try:\n lr = self.model.optimizer.learning_rate(batch)\n except TypeError:\n lr = self.model.optimizer.learning_rate\n if batch % 100 == 0:\n try:\n with self.writer.as_default():\n tf.summary.scalar('learning rate', tensor=lr)\n self.writer.flush()\n except AttributeError:\n logging.info('TensorBoard not init yet')\n\n\ndef init_resnet(hparams, model):\n \"\"\"Init resnet weights from a TF model if provided.\"\"\"\n if not hparams['widget_encoder_checkpoint']:\n return\n\n reader = tf.train.load_checkpoint(hparams['widget_encoder_checkpoint'])\n\n # Initialize model weights.\n init_set = input_utils.input_fn(\n hparams['train_files'],\n 1,\n hparams['vocab_size'],\n hparams['max_pixel_pos'],\n hparams['max_dom_pos'],\n epoches=1,\n buffer_size=1)\n init_features = next(iter(init_set))\n init_target = model.compute_targets(init_features)\n model([init_features, init_target[0]], training=True)\n\n weight_value_tuples = []\n for layer in model._encoder._pixel_layers: # pylint: disable=protected-access\n for param in layer.weights:\n if 'batch_normalization' in param.name:\n continue\n sublayer, varname = param.name.replace(':0', '').split('/')[-2:]\n var_name = 'encoder/{}/{}'.format(sublayer, varname)\n if reader.has_tensor(var_name):\n logging.info('Found pretrained weights: %s %s, %s %s', param.name,\n param.shape, var_name,\n reader.get_tensor(var_name).shape)\n weight_value_tuples.append((param, reader.get_tensor(var_name)))\n logging.info('Load pretrained %s weights', len(weight_value_tuples))\n tf.keras.backend.batch_set_value(weight_value_tuples)\n\n\ndef main(argv=None):\n del argv\n\n hparams = create_hparams(FLAGS.experiment)\n\n if hparams['distribution_strategy'] == 'multi_worker_mirrored':\n strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()\n elif hparams['distribution_strategy'] == 'mirrored':\n strategy = tf.distribute.MirroredStrategy()\n else:\n raise ValueError('Only `multi_worker_mirrored` is supported strategy '\n 'in Keras MNIST example at this time. Strategy passed '\n 'in is %s' % hparams['distribution_strategy'])\n\n # Build the train and eval datasets from the MNIST data.\n train_set = input_utils.input_fn(\n hparams['train_files'],\n hparams['batch_size'],\n hparams['vocab_size'],\n hparams['max_pixel_pos'],\n hparams['max_dom_pos'],\n epoches=1,\n buffer_size=hparams['train_buffer_size'])\n\n dev_set = input_utils.input_fn(\n hparams['eval_files'],\n hparams['eval_batch_size'],\n hparams['vocab_size'],\n hparams['max_pixel_pos'],\n hparams['max_dom_pos'],\n epoches=100,\n buffer_size=hparams['eval_buffer_size'])\n\n # Create and compile the model under Distribution strategy scope.\n # `fit`, `evaluate` and `predict` will be distributed based on the strategy\n # model was compiled with.\n with strategy.scope():\n model = WidgetCaptionModel(hparams)\n lr_schedule = optimizer.LearningRateSchedule(\n hparams['learning_rate_constant'], hparams['hidden_size'],\n hparams['learning_rate_warmup_steps'])\n opt = tf.keras.optimizers.Adam(\n lr_schedule,\n hparams['optimizer_adam_beta1'],\n hparams['optimizer_adam_beta2'],\n epsilon=hparams['optimizer_adam_epsilon'])\n model.compile(optimizer=opt)\n\n init_resnet(hparams, model)\n\n callbacks = [tf.keras.callbacks.TerminateOnNaN()]\n if FLAGS.model_dir:\n ckpt_filepath = os.path.join(FLAGS.model_dir, 'saved/{epoch:04d}')\n backup_dir = os.path.join(FLAGS.model_dir, 'backup')\n tensorboard_callback = TensorBoardCallBack(log_dir=FLAGS.model_dir)\n callbacks.append(tensorboard_callback)\n model_checkpoint_callback = tf.keras.callbacks.ModelCheckpoint(\n filepath=ckpt_filepath, save_weights_only=True)\n callbacks.append(model_checkpoint_callback)\n if tf.executing_eagerly():\n callbacks.append(\n tf.keras.callbacks.experimental.BackupAndRestore(\n backup_dir=backup_dir))\n\n # Train the model with the train dataset.\n history = model.fit(\n x=train_set,\n epochs=hparams['train_epoches'],\n validation_data=dev_set,\n validation_steps=10,\n callbacks=callbacks)\n\n logging.info('Training ends successfully. `model.fit()` result: %s',\n history.history)\n\n\nif __name__ == '__main__':\n logging.set_verbosity(logging.INFO)\n app.run(main)\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Lint as: python3\n\"\"\"Main SLaQ interface for approximating graph descritptors NetLSD and VNGE.\"\"\"\nimport numpy as np\nfrom scipy.sparse.base import spmatrix\nfrom graph_embedding.slaq.slq import slq\nfrom graph_embedding.slaq.util import laplacian\n\n\ndef _slq_red_var_netlsd(matrix, lanczos_steps, nvectors,\n timescales):\n \"\"\"Computes unnormalized NetLSD signatures of a given matrix.\n\n Uses the control variates method to reduce the variance of NetLSD estimation.\n\n Args:\n matrix (sparse matrix): Input adjacency matrix of a graph.\n lanczos_steps (int): Number of Lanczos steps.\n nvectors (int): Number of random vectors for stochastic estimation.\n timescales (np.ndarray): Timescale parameter for NetLSD computation. Default\n value is the one used in both NetLSD and SLaQ papers.\n\n Returns:\n np.ndarray: Approximated NetLSD descriptors.\n \"\"\"\n functions = [np.exp, lambda x: x]\n traces = slq(matrix, lanczos_steps, nvectors, functions, -timescales)\n subee = traces[0, :] - traces[1, :] / np.exp(timescales)\n sub = -timescales * matrix.shape[0] / np.exp(timescales)\n return np.array(subee + sub)\n\n\ndef _slq_red_var_vnge(matrix, lanczos_steps,\n nvectors):\n \"\"\"Approximates Von Neumann Graph Entropy (VNGE) of a given matrix.\n\n Uses the control variates method to reduce the variance of VNGE estimation.\n\n Args:\n matrix (sparse matrix): Input adjacency matrix of a graph.\n lanczos_steps (int): Number of Lanczos steps.\n nvectors (int): Number of random vectors for stochastic estimation.\n\n Returns:\n float: Approximated von Neumann graph entropy.\n \"\"\"\n functions = [lambda x: -np.where(x > 0, x * np.log(x), 0), lambda x: x]\n traces = slq(matrix, lanczos_steps, nvectors, functions).ravel()\n return traces[0] - traces[1] + 1\n\n\ndef vnge(adjacency,\n lanczos_steps = 10,\n nvectors = 100):\n \"\"\"Computes Von Neumann Graph Entropy (VNGE) using SLaQ.\n\n Args:\n adjacency (scipy.sparse.base.spmatrix): Input adjacency matrix of a graph.\n lanczos_steps (int): Number of Lanczos steps. Setting lanczos_steps=10 is\n the default from SLaQ.\n nvectors (int): Number of random vectors for stochastic estimation. Setting\n nvectors=10 is the default values from the SLaQ paper.\n\n Returns:\n float: Approximated VNGE.\n \"\"\"\n if adjacency.nnz == 0: # By convention, if x=0, x*log(x)=0.\n return 0\n density = laplacian(adjacency, False)\n density.data /= np.sum(density.diagonal()).astype(np.float32)\n return _slq_red_var_vnge(density, lanczos_steps, nvectors)\n\n\ndef netlsd(adjacency,\n timescales = np.logspace(-2, 2, 256),\n lanczos_steps = 10,\n nvectors = 100,\n normalization = None):\n \"\"\"Computes NetLSD descriptors using SLaQ.\n\n Args:\n adjacency (sparse matrix): Input adjacency matrix of a graph.\n timescales (np.ndarray): Timescale parameter for NetLSD computation. Default\n value is the one used in both NetLSD and SLaQ papers.\n lanczos_steps (int): Number of Lanczos steps. Setting lanczos_steps=10 is\n the default from SLaQ.\n nvectors (int): Number of random vectors for stochastic estimation. Setting\n nvectors=10 is the default values from the SLaQ paper.\n normalization (str): Normalization type for NetLSD.\n\n Returns:\n np.ndarray: Approximated NetLSD descriptors.\n \"\"\"\n lap = laplacian(adjacency, True)\n hkt = _slq_red_var_netlsd(lap, lanczos_steps, nvectors,\n timescales) # Approximated Heat Kernel Trace (hkt).\n if normalization is None:\n return hkt\n n = lap.shape[0]\n if normalization == 'empty':\n return hkt / n\n elif normalization == 'complete':\n return hkt / (1 + (n - 1) * np.exp(-timescales))\n elif normalization is None:\n return hkt\n else:\n raise ValueError(\n \"Unknown normalization type: expected one of [None, 'empty', 'complete'], got\",\n normalization)\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"tf.data.Dataset interface to the CIFAR100 0dataset.\"\"\"\n\nfrom absl import logging\nimport tensorflow as tf\n\n\nIMG_DIM = 32\nNUM_CHANNELS = 3\nNUM_LABELS = 100\n\n\ndef dataset_randomized(pattern):\n \"\"\"tf.data.Dataset object for CIFAR-100 training data.\"\"\"\n filenames = tf.io.gfile.glob(pattern)\n logging.info('*** Input Files ***')\n for input_file in filenames:\n logging.info(' %s', input_file)\n\n ds_filenames = tf.data.Dataset.from_tensor_slices(tf.constant(filenames))\n ds_filenames = ds_filenames.shuffle(buffer_size=len(filenames))\n\n dataset = tf.data.TFRecordDataset(ds_filenames)\n\n # Create a description of the features.\n feature_description = {\n 'image/class/label': tf.io.FixedLenFeature([], tf.int64),\n 'image/class/shuffled_label': tf.io.FixedLenFeature([], tf.int64),\n 'image/encoded': tf.io.FixedLenFeature([], tf.string),\n }\n\n def decode_image(image):\n image = tf.io.decode_png(image)\n image = tf.cast(image, tf.float32)\n image = tf.image.per_image_standardization(image)\n image = tf.reshape(image, [IMG_DIM * IMG_DIM * NUM_CHANNELS])\n return image\n\n def parse_function(example_proto):\n # Parse the input tf.Example proto using the dictionary above.\n features = tf.parse_single_example(example_proto, feature_description)\n features['image/encoded'] = decode_image(features['image/encoded'])\n return features\n\n dataset = dataset.map(parse_function)\n return dataset\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Lint as: python3\n\"\"\"Implements a minigrid tag environment.\n\nThe agents are split into two teams, where one team is rewarded for being\nnear the other team and the other team has a symmetric penalty.\n\"\"\"\nimport gym_minigrid.minigrid as minigrid\nimport numpy as np\nfrom social_rl.gym_multigrid import multigrid\nfrom social_rl.gym_multigrid.register import register\n\n\nclass TagEnv(multigrid.MultiGridEnv):\n \"\"\"Tag grid environment with obstacles, sparse reward.\"\"\"\n\n def __init__(self,\n size=15,\n hide_agents=1,\n seek_agents=1,\n n_clutter=25,\n max_steps=250,\n **kwargs):\n \"\"\"Constructor for multi-agent gridworld environment generator.\n\n Args:\n size: Number of tiles for the width and height of the square grid.\n hide_agents: The number of agents hiding.\n seek_agents: The number of agents seeking.\n n_clutter: The number of blocking objects in the environment.\n max_steps: Number of environment steps before the episode end (max episode\n length).\n **kwargs: See superclass.\n \"\"\"\n self.n_clutter = n_clutter\n self.hide_agents = hide_agents\n self.seek_agents = seek_agents\n super().__init__(\n grid_size=size,\n max_steps=max_steps,\n n_agents=hide_agents + seek_agents,\n fully_observed=True,\n **kwargs)\n\n def _gen_grid(self, width, height):\n self.grid = multigrid.Grid(width, height)\n self.grid.wall_rect(0, 0, width, height)\n\n for _ in range(self.n_clutter):\n self.place_obj(minigrid.Wall(), max_tries=100)\n\n self.place_agent()\n\n self.mission = 'Play tag'\n\n def step(self, action):\n obs, _, done, info = multigrid.MultiGridEnv.step(self, action)\n reward = [0] * self.n_agents\n for i in range(self.hide_agents):\n for j in range(self.hide_agents, self.hide_agents + self.seek_agents):\n if np.sum(np.abs(self.agent_pos[i] - self.agent_pos[j])) == 1:\n reward[i] -= 10.0\n reward[j] += 10.0\n return obs, reward, done, info\n\n\nclass RandomTagEnv6x6(TagEnv):\n\n def __init__(self, **kwargs):\n super().__init__(\n size=6, hide_agents=1, seek_agents=1, n_clutter=5, **kwargs)\n\n\nclass RandomTagEnv8x8(TagEnv):\n\n def __init__(self, **kwargs):\n super().__init__(\n size=8, hide_agents=2, seek_agents=3, n_clutter=10, **kwargs)\n\n\nif hasattr(__loader__, 'name'):\n module_path = __loader__.name\nelif hasattr(__loader__, 'fullname'):\n module_path = __loader__.fullname\n\nregister(env_id='MultiGrid-Tag-v0', entry_point=module_path + ':TagEnv')\n\nregister(\n env_id='MultiGrid-Tag-Random-6x6-v0',\n entry_point=module_path + ':RandomTagEnv6x6')\n\nregister(\n env_id='MultiGrid-Tag-Random-8x8-v0',\n entry_point=module_path + ':RandomTagEnv8x8')\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\nimport sys\nimport argparse\nimport numpy as np\nimport tensorflow as tf\nimport data\nimport model\n\n# pylint: skip-file\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--gpu', type=str, default='0', help='GPU to use [default: GPU 0]')\nparser.add_argument('--real_path', default='../data/resize128')\nparser.add_argument('--fake_path', default='../data/fake')\nparser.add_argument('--train_label', default='../data/annotations/train_label.txt')\nparser.add_argument('--test_label', default='../data/annotations/test_label.txt')\nparser.add_argument('--valid_label', default='../data/annotations/val_label.txt')\nparser.add_argument('--log_dir', default='log', help='Log dir [default: log]')\nparser.add_argument('--n_episode', type=int, default=500, help='Epoch to run [default: 50]')\nparser.add_argument('--batch_size', type=int, default=64, help='Batch size during training [default: 64]')\nparser.add_argument('--n_class', type=int, default=2, help='Number of class [default: 2]')\nparser.add_argument('--n_action', type=int, default=2, help='Number of action [default: 2]')\nparser.add_argument('--lr', type=float, default=0.1, help='Initial learning rate [default: 0.1]')\nparser.add_argument('--momentum', type=float, default=0.9, help='Initial learning rate [default: 0.9]')\nparser.add_argument('--optimizer', default='momentum', help='adam or momentum [default: momentum]')\nFLAGS = parser.parse_args()\n\n##################### config #####################\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=FLAGS.gpu\ntf.set_random_seed(100) # tf.set_random_seed(0)# 0 for 512\nREAL_PATH = FLAGS.real_path\nFAKE_PATH = FLAGS.fake_path\nTRAIN_LABEL = FLAGS.train_label\nTEST_LABEL = FLAGS.test_label\nVALID_LABEL = FLAGS.valid_label\nBATCH_SIZE = FLAGS.batch_size\nN_EPISODE = FLAGS.n_episode\nN_CLASS = FLAGS.n_class\nN_ACTION = FLAGS.n_action\nLR = FLAGS.lr\nMOMENTUM = FLAGS.momentum\nROOT_PATH = os.path.dirname(os.path.realpath(__file__))\nLOG_PATH = os.path.join(ROOT_PATH, FLAGS.log_dir)\nif not os.path.exists(LOG_PATH): os.mkdir(LOG_PATH)\nacc_count = 0\nwhile True:\n if os.path.exists(os.path.join(LOG_PATH, 'log_%02d.txt' % acc_count)): acc_count += 1\n else: break\nLOG_FNAME = 'log_%02d.txt' % acc_count\nLOG_FOUT = open(os.path.join(LOG_PATH, LOG_FNAME), 'w')\n\n(train_images, train_labels, train_att), train_iters = data.data_train(REAL_PATH, TRAIN_LABEL, BATCH_SIZE)\n(fake_images, fake_labels, fake_att), fake_iters = data.data_train(FAKE_PATH, TRAIN_LABEL, BATCH_SIZE)\n(valid_images, valid_labels, valid_att), valid_iters = data.data_test(REAL_PATH, VALID_LABEL, BATCH_SIZE)\n(test_images, test_labels, test_att), test_iters = data.data_test(REAL_PATH, TEST_LABEL, BATCH_SIZE)\n\n####################################################\n\ndef log_string(out_str):\n LOG_FOUT.write(out_str+'\\n')\n LOG_FOUT.flush()\n print(out_str)\n\ndef choose_action(prob_actions):\n actions = []\n for i in range(prob_actions.shape[0]):\n action = np.random.choice(range(prob_actions.shape[1]), p=prob_actions[i])\n actions.append(action)\n return np.array(actions)\n\ndef vgg_graph(sess, phs):\n VGG = model.VGG()\n Y_score = VGG.build(phs['batch_images'], N_CLASS, phs['is_training_ph'])\n\n Y_hat = tf.nn.softmax(Y_score)\n Y_pred = tf.argmax(Y_hat, 1)\n Y_label = tf.to_float(tf.one_hot(phs['batch_labels'], N_CLASS))\n\n cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits = Y_score, labels = Y_label)\n loss_op = tf.reduce_mean(cross_entropy)\n correct_prediction = tf.equal(tf.argmax(Y_hat, 1), tf.argmax(Y_label, 1))\n acc_op = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n\n update_op = tf.train.MomentumOptimizer(LR, MOMENTUM).minimize(loss_op, var_list=VGG.vars)\n\n return loss_op, acc_op, cross_entropy, Y_hat, update_op, Y_pred, VGG.vars\n\ndef rl_graph(sess, phrl):\n Actor = model.Actor()\n Y_score = Actor.build(phrl['states_rl'], N_ACTION, phrl['is_training_rl'])\n Y_prob =tf.nn.softmax(Y_score)\n\n\n neg_log_prob = tf.nn.sparse_softmax_cross_entropy_with_logits(logits = Y_score, labels = phrl['actions_rl'])\n loss_op = tf.reduce_mean(neg_log_prob*phrl['values_rl'])\n\n # update_op = tf.train.MomentumOptimizer(LR, MOMENTUM).minimize(loss_op, var_list=Actor.vars)\n update_op = tf.train.AdamOptimizer(1e-3).minimize(loss_op, var_list=Actor.vars)\n\n return loss_op, Y_prob, update_op, Actor.vars\n\ndef train():\n batch_images = tf.placeholder(tf.float32,[None,128,128,3])\n batch_labels = tf.placeholder(tf.int32,[None,])\n is_training_ph = tf.placeholder(tf.bool)\n lr_ph = tf.placeholder(tf.float32)\n\n states_rl = tf.placeholder(tf.float32,[None,11])\n actions_rl = tf.placeholder(tf.int32,[None,])\n values_rl = tf.placeholder(tf.float32,[None,])\n is_training_rl = tf.placeholder(tf.bool)\n lr_rl = tf.placeholder(tf.float32)\n\n phs = {'batch_images': batch_images,\n 'batch_labels': batch_labels,\n 'is_training_ph': is_training_ph,\n 'lr_ph': lr_ph}\n\n phrl = {'states_rl': states_rl,\n 'actions_rl': actions_rl,\n 'values_rl': values_rl,\n 'is_training_rl': is_training_rl,\n 'lr_rl': lr_rl}\n\n with tf.Session() as sess:\n # tf.reset_default_graph()\n vgg_loss, vgg_acc, vgg_ce, vgg_prob, vgg_update, vgg_pred, vgg_vars = vgg_graph(sess, phs)\n rl_loss, rl_prob, rl_update, rl_vars = rl_graph(sess, phrl)\n vgg_init = tf.variables_initializer(var_list=vgg_vars)\n saver = tf.train.Saver(vgg_vars)\n all_saver = tf.train.Saver()\n init = tf.global_variables_initializer()\n sess.run(init)\n\n ##################### pre-train student model #####################\n for epoch in range(4):\n for t in range(train_iters):\n if t % 50==0: print(\"pretrain:\", t)\n tr_images, tr_labels = sess.run([train_images,train_labels])\n pre_dict = {phs['batch_images']: tr_images,\n phs['batch_labels']: tr_labels,\n phs['is_training_ph']: True}\n sess.run(vgg_update, feed_dict=pre_dict)\n saver.save(sess,LOG_PATH+'/vgg.ckpt')\n valid_acc = 0.0\n y_pred =[]\n y_label = []\n y_att = []\n for k in range(valid_iters):\n va_images, va_labels, va_att = sess.run([valid_images, valid_labels, valid_att])\n valid_dict = {phs['batch_images']: va_images,\n phs['batch_labels']: va_labels,\n phs['is_training_ph']: False}\n batch_acc, batch_pred = sess.run([vgg_acc,vgg_pred], feed_dict=valid_dict)\n valid_acc += batch_acc\n y_pred += batch_pred.tolist()\n y_label += va_labels.tolist()\n y_att += va_att.tolist()\n valid_acc = valid_acc / float(valid_iters)\n valid_eo = data.cal_eo(y_att, y_label, y_pred)\n log_string('====pretrain: valid_acc=%.4f, valid_eo=%.4f' % (valid_acc, valid_eo[-1]))\n print(valid_eo)\n\n\n ##################### train teacher model #####################\n for i in range(N_EPISODE):\n # sess.run(vgg_init)\n saver.restore(sess,LOG_PATH+'/vgg.ckpt')\n state_list = []\n action_list = []\n reward_list = []\n for j in range(train_iters*20):\n tr_images, tr_labels, tr_att = sess.run([train_images,train_labels, train_att])\n fa_images, fa_labels, fa_att = sess.run([fake_images,fake_labels, fake_att])\n # va_images, va_labels, va_att = sess.run([valid_images,valid_labels, valid_att])\n\n ##################### generate state info from student model & data #####################\n train_dict = {phs['batch_images']: tr_images,\n phs['batch_labels']: tr_labels,\n phs['is_training_ph']: False}\n ce, acc, prob, pred = sess.run([vgg_ce, vgg_acc, vgg_prob, vgg_pred], feed_dict=train_dict)\n ce = np.clip(ce, 0, 10)/10.0\n model_stat = list(data.cal_eo(tr_att, tr_labels, pred))\n model_stat.append(np.mean(ce))\n model_stat = np.tile(model_stat,(BATCH_SIZE,1))\n state = np.concatenate((tr_labels[:, np.newaxis], tr_att[:, np.newaxis], prob, ce[:, np.newaxis], model_stat), axis=1)\n state_list.append(state)\n\n ##################### sample action for this batch #####################\n rl_dict = {phrl['states_rl']: state,\n phrl['is_training_rl']: False}\n action = choose_action(sess.run(rl_prob, feed_dict=rl_dict))\n action_list.append(action)\n bool_train = list(map(bool,action))\n bool_fake = list(map(bool,1-action))\n co_images = np.concatenate((tr_images[bool_train],fa_images[bool_fake]),axis=0)\n co_labels = np.concatenate((tr_labels[bool_train],fa_labels[bool_fake]),axis=0)\n\n ##################### update student model with new data #####################\n update_dict = {phs['batch_images']: co_images,\n phs['batch_labels']: co_labels,\n phs['is_training_ph']: True}\n _, ce, acc = sess.run([vgg_update, vgg_ce, vgg_acc], feed_dict=update_dict)\n\n\n if j % 100 == 0:\n print('====epoch_%d====iter_%d: loss=%.4f, train_acc=%.4f' % (i, j, np.mean(ce), acc))\n print(action, np.sum(action))\n\n ##################### generate terminal reward after 20 epoch of student training #####################\n valid_acc = 0.0\n y_pred =[]\n y_label = []\n y_att = []\n for k in range(valid_iters):\n va_images, va_labels, va_att = sess.run([valid_images, valid_labels, valid_att])\n valid_dict = {phs['batch_images']: va_images,\n phs['batch_labels']: va_labels,\n phs['is_training_ph']: False}\n batch_acc, batch_pred = sess.run([vgg_acc,vgg_pred], feed_dict=valid_dict)\n valid_acc += batch_acc\n y_pred += batch_pred.tolist()\n y_label += va_labels.tolist()\n y_att += va_att.tolist()\n valid_acc = valid_acc / float(valid_iters)\n valid_eo = data.cal_eo(y_att, y_label, y_pred)\n log_string('====epoch_%d: valid_acc=%.4f, valid_eo=%.4f' % (i, valid_acc, valid_eo[-1]))\n print('eo: ',valid_eo[0],valid_eo[1])\n print('eo: ',valid_eo[2],valid_eo[3])\n\n if valid_acc<0.72:\n value = -5\n else:\n value = -np.log(valid_eo[-1]+1e-4)\n\n if valid_acc>0.7 and valid_eo[-1]<0.2:\n all_saver.save(sess,LOG_PATH+'/all.ckpt')\n\n ##################### update teacher model #####################\n if i == 0:\n base = value\n else:\n base = base * 0.99 + value * 0.01\n reward = value - base\n print('reward: ',reward)\n\n final_state = np.reshape(state_list, (-1,11))\n final_action = np.reshape(action_list, (-1))\n final_reward = np.repeat(reward, final_state.shape[0])\n learn_dict = {phrl['states_rl']: final_state,\n phrl['actions_rl']: final_action,\n phrl['values_rl']: final_reward,\n phrl['is_training_rl']: True}\n sess.run(rl_update, feed_dict=learn_dict)\n\n\nif __name__ == \"__main__\":\n train()\n LOG_FOUT.close()\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Test script.\"\"\"\n\nimport os\nimport time\n\nfrom gym.wrappers.monitor import Monitor # pylint: disable=unused-import\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom tf_agents.environments import tf_py_environment\nfrom tf_agents.environments.suite_gym import wrap_env\nfrom tf_agents.policies import random_tf_policy\nfrom tf_agents.replay_buffers import tf_uniform_replay_buffer\nfrom tf_agents.trajectories import trajectory\nfrom tf_agents.utils import common, nest_utils # pylint: disable=g-multiple-import\n\nfrom reset_free_learning.envs import kitchen\nfrom reset_free_learning.envs import playpen\nfrom reset_free_learning.envs import playpen_reduced\nfrom reset_free_learning.envs import point_mass\nfrom reset_free_learning.envs import point_mass_full_goal\nfrom reset_free_learning.envs import pusher2d_simple\nfrom reset_free_learning.envs import sawyer_door_close\nfrom reset_free_learning.envs import sawyer_object\nfrom reset_free_learning.reset_free_wrapper import GoalTerminalResetFreeWrapper # pylint: disable=unused-import\nfrom reset_free_learning.reset_free_wrapper import GoalTerminalResetWrapper\nfrom reset_free_learning.reset_free_wrapper import ResetFreeWrapper # pylint: disable=unused-import\n\n\ndef print_initial_state(step):\n obs_strings = [str(step.observation[idx]) for idx in range(74 // 2)]\n obs_to_string = '[' + ','.joing(obs_strings) + ']'\n print(obs_to_string)\n\n\ndef get_env(name='sawyer_object', **env_kwargs):\n if name == 'sawyer_object':\n env = sawyer_object.SawyerObject( # pylint: disable=redefined-outer-name\n random_init=True,\n task_type='push',\n obs_type='with_goal',\n goal_low=(-0.1, 0.8, 0.05),\n goal_high=(0.1, 0.9, 0.3),\n liftThresh=0.04,\n sampleMode='equal',\n rewMode='orig',\n rotMode='fixed')\n env.set_camera_view(view='topview')\n env.set_max_path_length(int(1e8))\n if name == 'pusher2d_simple':\n env = pusher2d_simple.PusherEnv()\n if name == 'point_mass':\n env = point_mass.PointMassEnv(**env_kwargs)\n if name == 'point_mass_full_goal':\n env = point_mass_full_goal.PointMassEnv(**env_kwargs)\n if name == 'sawyer_door':\n env = sawyer_door_close.SawyerDoor(random_init=True, obs_type='with_goal')\n env.set_camera_view(view='topview')\n env.set_max_path_length(int(1e8))\n if name == 'kitchen':\n env = kitchen.Kitchen()\n if name == 'playpen':\n env = playpen.ContinuousPlayPen(**env_kwargs)\n if name == 'playpen_reduced':\n env = playpen_reduced.ContinuousPlayPen(**env_kwargs)\n return env\n\n\ndef copy_replay_buffer(small_buffer, big_buffer):\n \"\"\"Copy small buffer into the big buffer.\"\"\"\n all_data = nest_utils.unbatch_nested_tensors(small_buffer.gather_all())\n for trajectory in nest_utils.unstack_nested_tensors( # pylint: disable=redefined-outer-name\n all_data, big_buffer.data_spec):\n big_buffer.add_batch(trajectory)\n\n\ndef data_multiplier(offline_data, reward_fn): # pylint: disable=redefined-outer-name\n \"\"\"Offline data multiplication.\"\"\"\n np.set_printoptions(precision=2, suppress=True)\n\n def _custom_print(some_traj): # pylint: disable=unused-variable\n np.set_printoptions(precision=2, suppress=True)\n print('step', some_traj.step_type.numpy(), 'obs',\n some_traj.observation.numpy(), 'action', some_traj.action.numpy(),\n 'reward', some_traj.reward.numpy(), 'next_step',\n some_traj.next_step_type.numpy(), 'discount',\n some_traj.discount.numpy())\n\n all_data = nest_utils.unbatch_nested_tensors(offline_data.gather_all())\n all_trajs = nest_utils.unstack_nested_tensors(all_data,\n offline_data.data_spec)\n\n for idx, traj in enumerate(all_trajs):\n print('index:', idx)\n if traj.step_type.numpy() == 0:\n ep_start_idx = idx\n print('\\n\\n\\nnew start index:', ep_start_idx)\n elif idx in [12, 24, 36, 48, 60, 72, 84, 96, 108]:\n print('adding new trajectory')\n obs_dim = traj.observation.shape[0] // 2\n relabel_goal = traj.observation[:obs_dim]\n print('new goal:', repr(relabel_goal.numpy()))\n\n last_traj_idx = len(all_trajs[ep_start_idx:idx + 1])\n for traj_idx, cur_trajectory in enumerate(all_trajs[ep_start_idx:idx +\n 1]):\n if cur_trajectory.step_type.numpy() != 2:\n new_obs = tf.concat(\n [cur_trajectory.observation[:obs_dim], relabel_goal], axis=0)\n\n next_obs = tf.concat([\n all_trajs[ep_start_idx + traj_idx + 1].observation[:obs_dim],\n relabel_goal\n ],\n axis=0)\n\n new_reward = tf.constant(reward_fn(obs=next_obs))\n # terminate episode\n if new_reward.numpy() > 0.0:\n new_traj = cur_trajectory._replace(\n observation=new_obs,\n next_step_type=tf.constant(2),\n reward=new_reward,\n discount=tf.constant(0., dtype=tf.float32))\n last_traj_idx = ep_start_idx + traj_idx + 1\n # _custom_print(new_traj)\n offline_data.add_batch(new_traj)\n break\n else:\n new_traj = cur_trajectory._replace(\n observation=new_obs,\n reward=new_reward,\n )\n # _custom_print(new_traj)\n offline_data.add_batch(new_traj)\n\n last_observation = tf.concat(\n [all_trajs[last_traj_idx].observation[:obs_dim], relabel_goal],\n axis=0)\n last_traj = cur_trajectory._replace( # pylint: disable=undefined-loop-variable\n step_type=tf.constant(2),\n observation=last_observation,\n next_step_type=tf.constant(0),\n reward=tf.constant(0.0),\n discount=tf.constant(1., dtype=tf.float32))\n # _custom_print(last_traj)\n offline_data.add_batch(last_traj)\n print('new size:', offline_data.num_frames())\n\n\nif __name__ == '__main__':\n max_episode_steps = 5000000\n # env = get_env(name='point_mass_full_goal', env_type='y', reward_type='sparse')\n # env = get_env(name='kitchen')\n env = get_env(name='playpen_reduced', task_list='rc_o', reward_type='sparse')\n\n base_dir = os.path.abspath('experiments/env_logs/playpen_reduced/symmetric/')\n env_log_dir = os.path.join(base_dir, 'rc_o/traj1/')\n # env = ResetFreeWrapper(env, reset_goal_frequency=500, full_reset_frequency=max_episode_steps)\n env = GoalTerminalResetWrapper(\n env,\n episodes_before_full_reset=max_episode_steps // 500,\n goal_reset_frequency=500)\n # env = Monitor(env, env_log_dir, video_callable=lambda x: x % 1 == 0, force=True)\n\n env = wrap_env(env)\n tf_env = tf_py_environment.TFPyEnvironment(env)\n tf_env.render = env.render\n time_step_spec = tf_env.time_step_spec()\n action_spec = tf_env.action_spec()\n policy = random_tf_policy.RandomTFPolicy(\n action_spec=action_spec, time_step_spec=time_step_spec)\n collect_data_spec = trajectory.Trajectory(\n step_type=time_step_spec.step_type,\n observation=time_step_spec.observation,\n action=action_spec,\n policy_info=policy.info_spec,\n next_step_type=time_step_spec.step_type,\n reward=time_step_spec.reward,\n discount=time_step_spec.discount)\n offline_data = tf_uniform_replay_buffer.TFUniformReplayBuffer(\n data_spec=collect_data_spec, batch_size=1, max_length=int(1e5))\n rb_checkpointer = common.Checkpointer(\n ckpt_dir=os.path.join(env_log_dir, 'replay_buffer'),\n max_to_keep=10_000,\n replay_buffer=offline_data)\n rb_checkpointer.initialize_or_restore()\n\n # replay buffer copy magic\n do_a_copy = False\n if do_a_copy:\n buffer_list = [\n os.path.join(base_dir, 'rc_o/combined/replay_buffer'),\n os.path.join(base_dir, 'rc_k/combined/replay_buffer'),\n os.path.join(base_dir, 'rc_p/combined/replay_buffer'),\n os.path.join(base_dir, 'rc_b/combined/replay_buffer'),\n ]\n\n for buffer_dir in buffer_list:\n loaded_buffer = tf_uniform_replay_buffer.TFUniformReplayBuffer(\n data_spec=collect_data_spec, batch_size=1, max_length=int(1e5))\n cur_checkpointer = common.Checkpointer(\n ckpt_dir=buffer_dir, max_to_keep=10_000, replay_buffer=loaded_buffer)\n print(loaded_buffer.num_frames())\n copy_replay_buffer(loaded_buffer, offline_data)\n\n rb_checkpointer.save(global_step=0)\n\n start_time = time.time()\n # env.do_custom_reset(pos=np.array([0, 8, 1.57]))\n time_step = tf_env.reset()\n # print_initial_state(time_step)\n # print(time_step.observation)\n\n step_size = 0.5\n command_to_action_map = {\n 'd': [step_size, 0],\n 'a': [-step_size, 0],\n 'w': [0, step_size],\n 's': [0, -step_size],\n 'x': [0, 0]\n }\n pick_drop_map = {'p': [1], 'l': [-1]}\n\n print(offline_data.num_frames())\n # data_multiplier(offline_data, tf_env.pyenv.envs[0].env.compute_reward)\n # print(offline_data.num_frames())\n # print(offline_data.gather_all())\n # exit()\n rb_checkpoint_idx = 0\n\n for i in range(1, 2000):\n tf_env.render(mode='human')\n print(time_step)\n action_step = policy.action(time_step)\n\n # get action from user\n command = input('action:')\n if len(command) > 1:\n action = np.concatenate(\n [command_to_action_map[command[0]], pick_drop_map[command[1]]])\n else:\n action = np.concatenate([command_to_action_map[command[0]], [1]])\n\n # add noise to action\n action[:2] += np.random.uniform(low=-0.1, high=0.1, size=2)\n action_step = action_step._replace(\n action=tf.constant([action], dtype=tf.float32))\n\n next_time_step = tf_env.step(action_step.action)\n print('reward:', next_time_step.reward)\n offline_data.add_batch(\n trajectory.from_transition(time_step, action_step, next_time_step))\n\n if next_time_step.is_last():\n # print(i, env.get_info())\n time_step = next_time_step\n print('last step:', time_step)\n next_time_step = tf_env.step(action_step.action) # dummy action for reset\n offline_data.add_batch(\n trajectory.from_transition(time_step, action_step, next_time_step))\n\n command = input('save offline data?')\n if command == 'y':\n print('saving data')\n rb_checkpointer.save(global_step=rb_checkpoint_idx)\n rb_checkpoint_idx += 1\n elif command == 'c':\n print('clearing data')\n offline_data.clear()\n else:\n print('not saving data')\n\n time_step = next_time_step\n\n print('time:', time.time() - start_time)\n\n\n# dummy stuff to store plotting code\nelse:\n import tensorflow as tf # tf # pylint: disable=g-import-not-at-top\n\n import matplotlib # pylint: disable=g-import-not-at-top, unused-import\n import matplotlib.pyplot as plt # pylint: disable=g-import-not-at-top\n import matplotlib.cm as cm # pylint: disable=g-import-not-at-top, unused-import\n\n import numpy as np # pylint: disable=g-import-not-at-top, reimported\n import seaborn as sns # pylint: disable=g-import-not-at-top, unused-import\n import re # pylint: disable=g-import-not-at-top, unused-import\n\n import pickle as pkl # pylint: disable=g-import-not-at-top, unused-import\n import os # pylint: disable=g-import-not-at-top, reimported\n\n max_index = int(1e7)\n\n def smooth(x, alpha):\n if isinstance(x, list):\n size = len(x)\n else:\n size = x.shape[0]\n for idx in range(1, size):\n x[idx] = (1 - alpha) * x[idx] + alpha * x[idx - 1]\n return x\n\n def make_graph_with_variance(vals, x_interval):\n data_x = []\n data_y = []\n global max_index\n\n for y_coords, eval_interval in zip(vals, x_interval):\n data_y.append(smooth(y_coords, 0.95))\n x_coords = [eval_interval * idx for idx in range(len(y_coords))]\n data_x.append(x_coords)\n\n plot_dict = {}\n cur_max_index = max_index\n # for cur_x, cur_y in zip(data_x, data_y):\n # cur_max_index = min(cur_max_index, cur_x[-1])\n # print(cur_max_index)\n\n for cur_x, cur_y in zip(data_x, data_y):\n for x, y in zip(cur_x, cur_y):\n if x <= cur_max_index:\n if x in plot_dict.keys():\n plot_dict[x].append(y)\n else:\n plot_dict[x] = [y]\n\n index, means, stds = [], [], []\n for key in sorted(plot_dict.keys()): # pylint: disable=g-builtin-op\n index.append(key)\n means.append(np.mean(plot_dict[key]))\n stds.append(np.std(plot_dict[key]))\n means = np.array(smooth(means, 0.9))\n stds = np.array(smooth(stds, 0.8))\n return index, means, stds\n\n def np_custom_load(fname):\n with tf.gfile.Open(fname, 'rb') as f:\n load_file = np.load(f).astype(np.float32)\n return load_file\n\n color_map = ['b', 'g', 'r', 'c', 'm', 'y', 'k']\n style_map = []\n for line_style in ['-', '--', '-.', ':']:\n style_map += [color + line_style for color in color_map]\n\n def plot_call(job_id,\n worker_ids,\n legend_label,\n plot_style,\n file_path,\n y_plot='return'):\n \"\"\"Outermost function for plotting graphs with variance.\"\"\"\n print(worker_ids)\n job_id = str(job_id)\n if y_plot == 'return':\n y_coords = [\n np_custom_load(file_path + # pylint: disable=g-complex-comprehension\n job_id + '/' + worker_id +\n '/eval/average_eval_return.npy')\n for worker_id in worker_ids\n ]\n elif y_plot == 'success':\n y_coords = [\n np_custom_load(file_path + # pylint: disable=g-complex-comprehension\n job_id + '/' + worker_id +\n '/eval/average_eval_success.npy')\n for worker_id in worker_ids\n ]\n eval_interval = [\n np_custom_load('/home/architsh/brain/reset_free/reset_free/' + job_id +\n '/' + worker_id + '/eval/eval_interval.npy')\n for worker_id in worker_ids\n ]\n index, means, stds = make_graph_with_variance(y_coords, eval_interval)\n plt.plot(index, means, plot_style, label=legend_label)\n cur_color = plot_style[0]\n plt.fill_between(\n index, means - stds, means + stds, color=cur_color, alpha=0.2)\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Library for rematerialization.\n\nIncubates a version of tf.recompute_grad that is XLA compatible.\n\"\"\"\nimport collections\nimport os\nimport threading\nfrom typing import Deque, List, NamedTuple, Optional, Sequence\n\nfrom absl import logging\nimport numpy as np\nimport tensorflow as tf\n\n\nclass RecomputeContext(\n NamedTuple('RecomputeContext', [\n ('is_recomputing', bool),\n ('seed', tf.Tensor),\n ('children', Deque['RecomputeContext']),\n ])):\n \"\"\"Context for recomputation.\n\n Attributes:\n is_recomputing: Whether we are in a recomputation phase.\n seed: Scalar integer tensor that should be used with stateless random ops\n for deterministic behavior and correct computation of the gradient.\n children: Nested `RecomputeContext` instances. Used internally by\n `recompute_grad` to track nested instances of `RecomputeContext`.\n \"\"\"\n\n def __enter__(self):\n return _context_stack.push(self)\n\n def __exit__(self, exc_type, exc_value, traceback):\n _context_stack.pop(self)\n\n\n# Simplified version of `_DefaultStack` in\n# https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/framework/ops.py.\nclass _ContextStack(threading.local):\n \"\"\"A thread-local stack for providing implicit recompute contexts.\"\"\"\n\n def __init__(self):\n super(_ContextStack, self).__init__()\n self._stack = []\n\n def top(self):\n return self._stack[-1] if self._stack else None\n\n def push(self, context):\n self._stack.append(context)\n return context\n\n def pop(self, context):\n if self._stack[-1] is not context:\n raise AssertionError('Nesting violated for RecomputeContext.')\n self._stack.pop()\n\n\n_context_stack = _ContextStack()\n\n\ndef get_recompute_context():\n \"\"\"Returns the current recomputing context if it exists.\"\"\"\n return _context_stack.top()\n\n\n# Adapted from\n# https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/control_flow_util.py.\ndef _get_containing_xla_context(graph):\n \"\"\"Returns the first ancestor `XLAControlFlowContext` in the `graph`.\"\"\"\n ctxt = graph._get_control_flow_context() # pylint: disable=protected-access\n while ctxt:\n if ctxt.IsXLAContext():\n return ctxt\n ctxt = ctxt.outer_context\n return None\n\n\ndef _in_xla_context(graph = None):\n \"\"\"Detects whether we are in an XLA context.\"\"\"\n if '--tf_xla_auto_jit=2' in os.environ.get('TF_XLA_FLAGS', ''):\n return True\n graph = tf.compat.v1.get_default_graph() if graph is None else graph\n while True:\n if _get_containing_xla_context(graph) is not None:\n return True\n try:\n graph = graph.outer_graph\n except AttributeError:\n return False\n\n\ndef _force_data_dependency(\n first_compute,\n then_compute):\n \"\"\"Force all of `then_compute` to depend on all of `first_compute`.\n\n Uses a dummy data dependency, which is useful when running on TPUs because\n XLA ignores control dependencies. Only supports float arguments.\n\n Args:\n first_compute: Sequence of `Tensor`s to be executed before `then_compute`.\n then_compute: Sequence of `Tensor`s to executed after `first_compute`.\n\n Returns:\n Sequence of `Tensor`s with same length of `then_compute`.\n\n Raises:\n ValueError: if ranks are unknown or types are not floating.\n \"\"\"\n\n def _first_element(x):\n if x.shape.ndims is None:\n raise ValueError('Rank of Tensor %s must be known' % x)\n ndims = x.shape.ndims\n begin = tf.zeros(ndims, dtype=tf.int32)\n size = tf.ones(ndims, dtype=tf.int32)\n return tf.reshape(tf.slice(x, begin, size), [])\n\n first_compute_sum = tf.add_n(\n [_first_element(x) for x in first_compute if x is not None])\n dtype = first_compute_sum.dtype\n if not dtype.is_floating:\n raise ValueError('_force_data_dependency only supports floating dtypes.')\n zero = np.finfo(dtype.as_numpy_dtype).tiny * first_compute_sum\n return [\n x + tf.cast(zero, x.dtype) if x is not None else None\n for x in then_compute\n ]\n\n\ndef _make_seed_if_none(seed):\n \"\"\"Uses the global generator to make a seed if necessary.\"\"\"\n if seed is not None:\n return seed\n generator = tf.random.experimental.get_global_generator()\n # The two seeds for stateless random ops don't have individual semantics and\n # are scrambled together, so providing one seed is fine. This makes it easier\n # for users to provide a local seed without worrying about integer overflow.\n # See `make_seeds` in\n # https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/stateful_random_ops.py.\n try:\n return generator.uniform_full_int([], tf.int32, name='recompute_grad_seed')\n except (RuntimeError, TypeError, ValueError, tf.errors.NotFoundError) as e:\n # For a number of reasons, the above operation can fail like using multiple\n # graphs or toggling between eager and graph modes. Reset the generator.\n logging.warn('Resetting the generator. %s: %s', type(e), e)\n tf.random.experimental.set_global_generator(None)\n generator = tf.random.experimental.get_global_generator()\n return generator.uniform_full_int([], tf.int32, name='recompute_grad_seed')\n\n\ndef recompute_grad(f, seed=None):\n \"\"\"An eager-compatible version of recompute_grad.\n\n For f(*args, **kwargs), this supports gradients with respect to args, or to\n gradients with respect to any variables residing in the kwarg 'variables'.\n Note that for keras layer and model objects, this is handled automatically.\n\n Warning: If `f` was originally a tf.keras Model or Layer object, `g` will not\n be able to access the member variables of that object, because `g` returns\n through the wrapper function `inner`. When recomputing gradients through\n objects that inherit from keras, we suggest keeping a reference to the\n underlying object around for the purpose of accessing these variables.\n\n Args:\n f: function `f(*x)` that returns a `Tensor` or sequence of `Tensor` outputs.\n seed: Optional seed for random ops. `seed` should an integer scalar\n `Tensor`. When compiling to XLA, `seed` must have dtype `tf.int32`. If\n `seed` is not provided one will be generated.\n\n Returns:\n A function `g` that wraps `f`, but which recomputes `f` on the backwards\n pass of a gradient call.\n \"\"\"\n\n @tf.custom_gradient\n def inner(*args, **kwargs):\n \"\"\"Inner function closure for calculating gradients.\"\"\"\n # Detect when we're nested and in the backwards pass, so we don't generate\n # an additional seed.\n parent_context = get_recompute_context()\n if parent_context is not None and parent_context.is_recomputing:\n # Use the cached context in the recomputation phase.\n with parent_context.children.popleft()._replace(\n is_recomputing=True) as context:\n result = f(*args, **kwargs)\n else:\n with RecomputeContext(\n is_recomputing=False,\n seed=_make_seed_if_none(seed),\n children=collections.deque()) as context:\n result = f(*args, **kwargs)\n # In the forward pass, build up a tree of recomputation contexts.\n if parent_context is not None and not parent_context.is_recomputing:\n parent_context.children.append(context)\n\n def grad(*dresult, **grad_kwargs):\n \"\"\"Gradient function calculation for inner function.\"\"\"\n variables = grad_kwargs.pop('variables', None)\n if grad_kwargs:\n raise ValueError('Found unexpected kwargs for `grad`: ',\n list(grad_kwargs.keys()))\n inputs, seed = list(args), context.seed\n if _in_xla_context():\n inputs = _force_data_dependency(\n tf.nest.flatten(dresult), inputs + [seed])\n seed = inputs.pop()\n with tf.GradientTape() as tape:\n tape.watch(inputs)\n if variables is not None:\n tape.watch(variables)\n with tf.control_dependencies(dresult):\n with context._replace(is_recomputing=True, seed=seed):\n result = f(*inputs, **kwargs)\n kw_vars = []\n if variables is not None:\n kw_vars = list(variables)\n grads = tape.gradient(\n result, list(inputs) + kw_vars, output_gradients=dresult)\n return grads[:len(inputs)], grads[len(inputs):]\n\n return result, grad\n\n return inner\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Routing Transformer for image problems.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom tensor2tensor.layers import common_hparams\nfrom tensor2tensor.layers import modalities\nfrom tensor2tensor.utils import registry\nfrom tensor2tensor.utils import t2t_model\nimport tensorflow.compat.v1 as tf\n\nfrom routing_transformer import utils\n\n_IMGS = {}\n\n\n@registry.register_model\nclass SparseImagetransformer(t2t_model.T2TModel):\n \"\"\"Sparse Image Transformer.\"\"\"\n\n @property\n def inputs_vocab_size(self):\n \"\"\"Size of vocabulary for 'inputs' feature.\"\"\"\n return self.problem_hparams.vocab_size[\"inputs\"]\n\n @property\n def targets_vocab_size(self):\n \"\"\"Size of vocabulary for 'targets' feature.\"\"\"\n return self.problem_hparams.vocab_size[\"targets\"]\n\n @property\n def frame_height(self):\n return self.hparams.frame_height\n\n @property\n def frame_width(self):\n return self.hparams.frame_width\n\n @property\n def num_channels(self):\n return self.hparams.problem.num_channels\n\n @property\n def batch_size(self):\n return self.hparams.batch_size\n\n @property\n def hidden_size(self):\n return self.hparams.hidden_size\n\n @property\n def num_decoder_layers(self):\n return self.hparams.num_decoder_layers\n\n @property\n def add_positional_emb(self):\n return self.hparams.add_positional_emb\n\n @property\n def is_inputs_class_label(self):\n \"\"\"True if 'inputs' feature represents a class label.\"\"\"\n return (self.problem_hparams.modality[\"inputs\"] ==\n modalities.ModalityType.CLASS_LABEL)\n\n @property\n def is_decode(self):\n return self.hparams.mode == tf.estimator.ModeKeys.PREDICT\n\n def get_shape_for_decoder(self):\n \"\"\"Returns the shape of the sequence to be fed into the decoder.\"\"\"\n if len(self.hparams.query_shape) == 2:\n return [self.frame_height, self.frame_width * self.num_channels]\n elif len(self.hparams.query_shape) == 1:\n return [self.frame_height * self.frame_width * self.num_channels]\n else:\n raise ValueError(\"Only local 1D and local 2D attention is supported.\")\n\n def process_partial_targets_decoding(self, targets):\n \"\"\"Processes partially generated targets in decoding mode.\"\"\"\n original_shape = self.get_shape_for_decoder()\n blocks_per_dim = [\n s // q for s, q in zip(original_shape, self.hparams.query_shape)\n ]\n targets_shape = utils.shape_list(targets)\n targets = tf.reshape(\n targets, [targets_shape[0], -1,\n np.prod(self.hparams.query_shape), 1])\n\n targets = utils.unflatten_blocks_nd(targets, blocks_per_dim)\n targets = utils.put_back_blocks_nd(targets, self.hparams.query_shape)\n targets = tf.reshape(\n targets, [-1, self.frame_height, self.frame_width, self.num_channels])\n return targets\n\n def prepare_decoder(self, targets):\n \"\"\"Prepares targets for transformer decoder.\"\"\"\n shape = utils.shape_list(targets)\n # image should be [batch, height, width, channels]\n assert len(shape) == 4, \"Image tensors should be 4-dimensional\"\n\n # Shift positions\n targets = tf.reshape(targets, [-1] + self.get_shape_for_decoder() + [1])\n targets = utils.right_shift_blockwise_nd(targets, self.hparams.query_shape)\n\n # Add channel embeddings\n targets = tf.reshape(\n targets, [-1, self.frame_height, self.frame_width, self.num_channels])\n targets = utils.get_channel_embeddings(\n io_depth=self.num_channels,\n targets=targets,\n hidden_size=self.hidden_size)\n\n # add positional embeddings if needed\n if self.add_positional_emb:\n targets = utils.add_positional_embedding_nd(\n targets,\n max_length=max(self.frame_height, self.frame_width,\n self.num_channels),\n name=\"pos_emb\")\n targets = tf.reshape(targets, [-1] + self.get_shape_for_decoder() +\n [self.hidden_size])\n return targets\n\n def multinomial_squeeze(self, logits, temperature=1.0):\n \"\"\"multinomial sampling from logits.\"\"\"\n logits_shape = utils.shape_list(logits)\n reshaped_logits = (tf.reshape(logits, [-1, logits_shape[-1]]) / temperature)\n choices = tf.multinomial(reshaped_logits, 1)\n choices = tf.reshape(choices, logits_shape[:-1])\n return tf.to_int32(choices)\n\n def produce_output(self, decoder_output):\n \"\"\"Maps decoder output to final logits.\"\"\"\n # map decoder output to output vocab size\n output = tf.layers.dense(\n decoder_output,\n self.targets_vocab_size,\n activation=None,\n name=\"final_dense\")\n\n if self.is_decode:\n return output\n\n # Reshape to a normal image\n output = tf.reshape(output, [\n -1, self.frame_height, self.frame_width, self.num_channels,\n self.targets_vocab_size\n ])\n return output\n\n def body(self, features, decode_step=None, cache=None, decoding_stats=None):\n targets = tf.to_int32(features[\"targets\"])\n if self.is_decode:\n targets = self.process_partial_targets_decoding(targets)\n decoder_input = self.prepare_decoder(targets)\n extra_losses = []\n\n if not self.hparams.unconditional: # condition on class label\n if not self.is_inputs_class_label:\n raise ValueError(\"SparseImagetransformer can only condition on \"\n \"'inputs' feature if it represents class label.\")\n inputs = features[\"inputs\"]\n\n # Embed class here rather than in bottom().\n if inputs.dtype not in [tf.int32, tf.int64]:\n raise ValueError(\"Do not embed 'inputs' before body(). \"\n \"Found dtype=%s.\" % inputs.dtype)\n inputs = utils.get_embeddings(\n targets=inputs,\n vocab_size=self.inputs_vocab_size,\n hidden_size=self.hidden_size,\n name=\"class_conditional_embedding\")\n\n # Add class embedding to each spatial location.\n batch_size = tf.shape(targets)[0]\n hidden_size = tf.shape(inputs)[-1]\n num_middle_dims = len(decoder_input.shape) - 2\n decoder_input += tf.reshape(inputs, [batch_size] + [1] * num_middle_dims +\n [hidden_size])\n\n decoder_output = utils.transformer_decoder_layers(\n inputs=decoder_input,\n num_layers=self.num_decoder_layers,\n hparams=self.hparams,\n decode_step=decode_step,\n losses=extra_losses,\n cache=cache,\n name=\"decoder\",\n decoding_stats=decoding_stats)\n logits = self.produce_output(decoder_output)\n\n # Return logits as-is in decoding mode\n if self.is_decode:\n return logits\n\n # Produce a summary of the output.\n results = self.multinomial_squeeze(logits, self.hparams.sampling_temp)\n results = tf.reshape(\n results, [-1, self.frame_height, self.frame_width, self.num_channels])\n if utils.is_xla_compiled():\n _IMGS[\"predictions\"] = results\n\n # Prepare loss.\n loss_dict = {}\n if extra_losses:\n loss_dict[\"extra_loss\"] = tf.add_n(extra_losses)\n return logits, loss_dict\n\n def top(self, body_outputs, features):\n return body_outputs\n\n def loss(self, logits, features):\n # Add cross entropy loss\n targets = features[\"targets\"]\n one_hot_targets = tf.one_hot(\n tf.cast(targets, dtype=tf.int32), self.targets_vocab_size)\n loss = tf.losses.softmax_cross_entropy(\n onehot_labels=one_hot_targets, logits=logits)\n return loss\n\n def sample(self, features, decode_step, cache, decoding_stats):\n \"\"\"Sample step for infer.\"\"\"\n with tf.variable_scope(\"sparse_imagetransformer/body\", reuse=tf.AUTO_REUSE):\n logits = self.body(features, decode_step, cache, decoding_stats)\n logits = tf.reshape(logits, [self.batch_size, self.targets_vocab_size])\n sample = self.multinomial_squeeze(logits, self.hparams.sampling_temp)\n sample = tf.reshape(sample, [self.batch_size])\n return sample, logits\n\n def infer(self, features, **kwargs):\n decode_length = (self.frame_height * self.frame_width * self.num_channels)\n cache = {}\n decoding_stats = {}\n targets_old = features.get(\"targets\", None)\n initial_output = tf.zeros((self.batch_size, decode_length), dtype=tf.int32)\n initial_logits = tf.zeros(\n (self.batch_size, decode_length, self.targets_vocab_size))\n # call body once to initialize cache with representations of input frames.\n features[\"targets\"] = initial_output\n with tf.variable_scope(\n \"sparse_imagetransformer/body\", reuse=tf.AUTO_REUSE, use_resource=True):\n self.body(\n features,\n decode_step=None,\n cache=cache,\n decoding_stats=decoding_stats)\n\n def infer_step(i, recent_output, recent_logits, cache, decoding_stats):\n \"\"\"Inference step.\"\"\"\n features_copy = features.copy()\n features_copy[\"targets\"] = recent_output\n cur_sample, cur_logit = self.sample(\n features_copy,\n decode_step=i,\n cache=cache,\n decoding_stats=decoding_stats)\n pos = i\n samples = recent_output + tf.scatter_nd(\n indices=[[b, pos] for b in range(self.batch_size)],\n updates=cur_sample,\n shape=utils.shape_list(recent_output))\n logits = recent_logits + tf.scatter_nd(\n indices=[[b, pos] for b in range(self.batch_size)],\n updates=cur_logit,\n shape=utils.shape_list(recent_logits))\n return i + 1, samples, logits, cache, decoding_stats\n\n def while_exit_cond(i, result, logits, cache, decoding_stats): # pylint: disable=unused-argument\n \"\"\"Exit the loop if it reaches decode_length.\"\"\"\n not_overflow = i < decode_length\n return not_overflow\n\n _, final_result, final_logits, _, decoding_stats = tf.while_loop(\n while_exit_cond,\n infer_step,\n [tf.constant(0), initial_output, initial_logits, cache, decoding_stats],\n back_prop=False,\n parallel_iterations=1)\n\n original_shape = self.get_shape_for_decoder()\n\n blocks_per_dim = [\n s // q for s, q in zip(original_shape, self.hparams.query_shape)\n ]\n final_result_shape = utils.shape_list(final_result)\n final_result = tf.reshape(\n final_result,\n [final_result_shape[0], -1,\n np.prod(self.hparams.query_shape), 1])\n final_logits_shape = utils.shape_list(final_logits)\n final_logits = tf.reshape(final_logits, [\n final_logits_shape[0], -1,\n np.prod(self.hparams.query_shape), final_logits_shape[-1]\n ])\n final_result = utils.unflatten_blocks_nd(final_result, blocks_per_dim)\n final_result = utils.put_back_blocks_nd(final_result,\n self.hparams.query_shape)\n final_logits = utils.unflatten_blocks_nd(final_logits, blocks_per_dim)\n final_logits = utils.put_back_blocks_nd(final_logits,\n self.hparams.query_shape)\n\n final_result = tf.reshape(\n final_result,\n [-1, self.frame_height, self.frame_width, self.num_channels])\n final_logits = tf.reshape(final_logits, [\n -1, self.frame_height, self.frame_width, self.num_channels,\n self.targets_vocab_size\n ])\n\n if utils.is_xla_compiled():\n _IMGS[\"decodes\"] = final_result\n\n for name, value in decoding_stats.items():\n tf.summary.scalar(\"decodes/%s\" % name, value / decode_length)\n\n # Reassign targets back to the previous value.\n if targets_old is not None:\n features[\"targets\"] = targets_old\n\n return {\n \"outputs\": final_result,\n \"scores\": None,\n \"logits\": final_logits,\n \"losses\": None,\n }\n\n\ndef _targets_bottom(x, model_hparams, vocab_size):\n del model_hparams, vocab_size # Unused\n if utils.is_xla_compiled():\n _IMGS[\"targets\"] = x\n else:\n tf.summary.image(\"targets\", tf.cast(x, dtype=tf.uint8))\n return x\n\n\ndef _inputs_bottom(x, model_hparams, vocab_size):\n del model_hparams, vocab_size # Unused\n return x\n\n\n@registry.register_hparams\ndef sparse_imagetransformer_base():\n \"\"\"Sparse image transformer base hparams with local 1D attention.\"\"\"\n hparams = common_hparams.basic_params1()\n\n # Basic HParams\n hparams.hidden_size = 256\n hparams.batch_size = 1 # Per TPU core\n hparams.dropout = 0.0\n hparams.clip_grad_norm = 0. # i.e. no gradient clipping\n hparams.optimizer = \"adafactor\"\n hparams.optimizer_adafactor_beta1 = 0.0\n hparams.optimizer_adafactor_beta2 = 0.999\n hparams.optimizer_adafactor_clipping_threshold = 1.0\n hparams.optimizer_adafactor_decay_type = \"pow\"\n hparams.optimizer_adafactor_memory_exponent = 0.8\n hparams.optimizer_adafactor_multiply_by_parameter_scale = True\n hparams.learning_rate_schedule = \"constant*rsqrt_normalized_decay\"\n hparams.learning_rate_warmup_steps = 10000\n hparams.learning_rate_constant = 0.01\n hparams.initializer_gain = 0.2\n hparams.initializer = \"uniform_unit_scaling\"\n hparams.weight_decay = 0.0\n hparams.label_smoothing = 0.0\n hparams.bottom = {\n # Bypass bottom().\n \"inputs\": _inputs_bottom,\n \"targets\": _targets_bottom,\n }\n hparams.tpu_enable_host_call = True # Enable summaries on TPU\n hparams.add_hparam(\"use_tpu\", True)\n hparams.add_hparam(\"add_positional_emb\", True)\n hparams.add_hparam(\"frame_height\", 32)\n hparams.add_hparam(\"frame_width\", 32)\n\n # Transformer HParams\n hparams.norm_type = \"layer\"\n hparams.layer_prepostprocess_dropout = 0.0\n hparams.add_hparam(\"num_decoder_layers\", 12)\n hparams.add_hparam(\"local_num_heads\", 8)\n hparams.add_hparam(\"attention_key_channels\", 0) # Uses hidden_size\n hparams.add_hparam(\"attention_value_channels\", 0) # Uses hidden_size\n hparams.add_hparam(\"attention_dropout\", 0.0)\n hparams.add_hparam(\"ffn_layer\", \"conv_hidden_relu\")\n hparams.add_hparam(\"filter_size\", 256) # Used in ffn_layer\n hparams.add_hparam(\"relu_dropout\", 0.0) # Used in ffn_layer\n\n # Local 1D HParams\n hparams.add_hparam(\"q_filter_width\", 1)\n hparams.add_hparam(\"kv_filter_width\", 1)\n hparams.add_hparam(\"query_shape\", (128,))\n hparams.add_hparam(\"memory_query_shape\", (128,))\n hparams.add_hparam(\"memory_flange\", (128,))\n\n # Sparsity HParams\n hparams.add_hparam(\"sparsity_cluster_size\", 0)\n hparams.add_hparam(\"sparsity_cluster_attention_window\", 0)\n hparams.add_hparam(\"sparsity_cluster_num_heads\", 0)\n hparams.add_hparam(\"sparsity_strided_num_heads\", 0)\n hparams.add_hparam(\"sparsity_cluster_strided_num_heads\", 0)\n hparams.add_hparam(\"ema\", True)\n hparams.add_hparam(\"share_qk\", True)\n hparams.add_hparam(\"sparsity_skip_first\", 0)\n hparams.add_hparam(\"hash_items\", False)\n\n # Clustering HParams\n hparams.add_hparam(\"beta\", 1e-4)\n hparams.add_hparam(\"decay\", 0.999)\n\n # Memory saving measures\n hparams.add_hparam(\"cache_padding_bias\", True)\n\n # relative attention\n hparams.max_relative_position = 0\n hparams.add_hparam(\"local_relative\", False)\n hparams.add_hparam(\"sparsity_cluster_relative\", False)\n hparams.add_hparam(\"sparsity_cluster_strided_relative\", False)\n hparams.add_hparam(\"sparsity_strided_relative\", False)\n\n # Conditioning\n hparams.add_hparam(\"unconditional\", True)\n hparams.add_hparam(\"token_bias_wt_trainable\", False)\n return hparams\n\n\n@registry.register_hparams\ndef sparse_imagetransformer_local2d():\n hparams = sparse_imagetransformer_base()\n\n # Local 2D HParams\n hparams.query_shape = (16, 16 * 3)\n hparams.memory_query_shape = (16, 16 * 3)\n hparams.memory_flange = (16, 16 * 3)\n\n return hparams\n\n\n@registry.register_hparams\ndef mnist_local1d():\n \"\"\"MNIST local 1D attention.\"\"\"\n hparams = sparse_imagetransformer_base()\n\n hparams.frame_height = 28\n hparams.frame_width = 28\n\n hparams.local_num_heads = 4\n hparams.num_decoder_layers = 12\n hparams.query_shape = (56,)\n hparams.memory_query_shape = (56,)\n hparams.memory_flange = (56,)\n hparams.hidden_size = 512\n hparams.filter_size = 2048\n hparams.layer_preprocess_sequence = \"none\"\n hparams.layer_postprocess_sequence = \"dan\"\n hparams.layer_prepostprocess_dropout = 0.3\n\n return hparams\n\n\n@registry.register_hparams\ndef mnist_full():\n \"\"\"MNIST full attention.\"\"\"\n hparams = mnist_local1d()\n\n hparams.query_shape = (784,)\n hparams.memory_query_shape = (784,)\n hparams.memory_flange(0,)\n\n return hparams\n\n\n@registry.register_hparams\ndef mnist_cluster_local():\n \"\"\"MNIST routing attention.\"\"\"\n hparams = mnist_local1d()\n\n hparams.local_num_heads = 2\n hparams.sparsity_cluster_num_heads = 2\n hparams.sparsity_cluster_size = 7\n hparams.sparsity_cluster_attention_window = 112\n\n return hparams\n\n\n@registry.register_hparams\ndef mnist_local_cluster_strided():\n \"\"\"MNIST routing attention plus strided attention.\"\"\"\n hparams = mnist_local1d()\n\n hparams.local_num_heads = 4\n hparams.sparsity_cluster_num_heads = 2\n hparams.sparsity_cluster_strided_num_heads = 2\n hparams.sparsity_cluster_size = 7\n hparams.sparsity_cluster_attention_window = 112\n\n return hparams\n\n\n@registry.register_hparams\ndef cifar10_local1d():\n \"\"\"CIFAR-10 local 1D attention.\"\"\"\n hparams = sparse_imagetransformer_base()\n\n hparams.local_num_heads = 8\n hparams.num_decoder_layers = 12\n hparams.query_shape = (256,)\n hparams.memory_query_shape = (256,)\n hparams.memory_flange = (256,)\n hparams.hidden_size = 1024\n hparams.filter_size = 2048\n hparams.layer_preprocess_sequence = \"none\"\n hparams.layer_postprocess_sequence = \"dan\"\n hparams.layer_prepostprocess_dropout = 0.3\n\n return hparams\n\n\n@registry.register_hparams\ndef cifar10_full():\n \"\"\"CIFAR-10 full attention.\"\"\"\n hparams = cifar10_local1d()\n\n hparams.query_shape = (3072,)\n hparams.memory_query_shape = (3072,)\n hparams.memory_flange = (0,)\n\n return hparams\n\n\n@registry.register_hparams\ndef cifar10_local_cluster():\n \"\"\"CIFAR-10 routing attention.\"\"\"\n hparams = cifar10_local1d()\n\n hparams.local_num_heads = 4\n hparams.sparsity_cluster_num_heads = 4\n hparams.sparsity_cluster_size = 6\n hparams.sparsity_cluster_attention_window = 512\n\n return hparams\n\n\n@registry.register_hparams\ndef cifar10_local_cluster_strided():\n \"\"\"CIFAR-10 routing attention plus strided.\"\"\"\n hparams = cifar10_local_cluster()\n\n hparams.local_num_heads = 4\n hparams.sparsity_cluster_num_heads = 2\n hparams.sparsity_cluster_strided_num_heads = 2\n\n return hparams\n\n\n@registry.register_hparams\ndef imagenet_local1d():\n \"\"\"Imagenet64 local 1D attention.\"\"\"\n hparams = sparse_imagetransformer_base()\n\n hparams.frame_height = 64\n hparams.frame_width = 64\n\n hparams.hidden_size = 1024\n hparams.local_num_heads = 16\n hparams.num_decoder_layers = 24\n hparams.query_shape = (256,)\n hparams.memory_query_shape = (256,)\n hparams.memory_flange = (256,)\n hparams.filter_size = 2048\n hparams.layer_preprocess_sequence = \"none\"\n hparams.layer_postprocess_sequence = \"dan\"\n hparams.layer_prepostprocess_dropout = 0.3\n\n return hparams\n\n\n@registry.register_hparams\ndef imagenet_full():\n \"\"\"Imagenet64 full attention.\"\"\"\n hparams = imagenet_local1d()\n\n hparams.query_shape = (64 * 64 * 3,)\n hparams.memory_query_shape = (64 * 64 * 3,)\n hparams.memory_flange(0,)\n\n return hparams\n\n\n@registry.register_hparams\ndef imagenet_local_cluster():\n \"\"\"Imagenet64 routing attention.\"\"\"\n hparams = imagenet_local1d()\n\n hparams.local_num_heads = 12\n hparams.sparsity_cluster_num_heads = 4\n hparams.sparsity_cluster_size = 8\n hparams.num_decoder_layers = 24\n hparams.sparsity_skip_first = 0\n hparams.sparsity_cluster_attention_window = 2048\n\n return hparams\n\n\n@registry.register_hparams\ndef imagenet_local_cluster_strided():\n \"\"\"Imagenet64 routing attention plus strided attention.\"\"\"\n hparams = imagenet_local_cluster()\n\n hparams.local_num_heads = 6\n hparams.sparsity_cluster_num_heads = 5\n hparams.sparsity_cluster_strided_num_heads = 5\n\n return hparams\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Lint as: python3\n\"\"\"Factory to build language models.\"\"\"\n\nimport logging\nfrom typing import Any, Dict, Optional, Text\n\nimport tensorflow as tf\n\nfrom vatt.configs import factory as configs_factory\nfrom vatt.configs import text as text_config\nfrom vatt.modeling.backbones.text import bert\nfrom vatt.modeling.backbones.text import linear\nfrom vatt.modeling.backbones.text import t5\n\n\nLANGUAGE_MODEL_HEADS = {\n \"linear\": linear.LinearLM,\n \"t5\": t5.T5Encoder,\n \"bert\": bert.BertEncoder,\n}\n\n\ndef get_shape(x):\n \"\"\"Deal with dynamic shape in tensorflow cleanly.\"\"\"\n static = x.shape.as_list()\n dynamic = tf.shape(x)\n return [dynamic[i] if s is None else s for i, s in enumerate(static)]\n\n\nclass LanguageModel(tf.keras.layers.Layer):\n \"\"\"Constructs a language model given the configs.\"\"\"\n\n def __init__(self,\n base_lm_head,\n params):\n \"\"\"Main language model.\n\n Args:\n base_lm_head: the language model, either linear or Transformer-based.\n params: Hyperparameters of the model.\n\n \"\"\"\n super(LanguageModel, self).__init__(name=\"text_module\")\n\n self._vocab_size = params.vocab_size\n self._d_embedding = params.d_embedding\n self._use_agg_token = params.use_agg_token\n self._trainable_embeddings = params.trainable_embeddings\n self._is_transformer = params.is_transformer\n self.embedding = tf.keras.layers.Embedding(\n self._vocab_size,\n self._d_embedding,\n trainable=self._trainable_embeddings,\n )\n\n # if specified, there would be a dense projection before feeding to the LM\n if params.d_pre_proj is not None:\n self.pre_proj = tf.keras.layers.Dense(\n params.d_pre_proj,\n use_bias=False,\n activation=params.activation,\n name=\"pre_proj\"\n )\n else:\n self.pre_proj = tf.identity\n\n self.base_lm = base_lm_head(**params.as_dict())\n\n # if specified, there would be a dense projection after the LM outputs\n if params.d_post_proj is not None:\n self.post_proj = tf.keras.layers.Dense(\n params.d_post_proj,\n use_bias=False,\n activation=params.activation,\n name=\"post_proj\"\n )\n else:\n self.post_proj = tf.identity\n\n def build(self, input_shape):\n if self._use_agg_token:\n self.agg_token_embd = self.add_weight(\n name=\"agg_embedding\",\n shape=(self._d_embedding,),\n initializer=tf.keras.initializers.get(\"glorot_normal\"),\n trainable=True,\n dtype=tf.float32,\n )\n\n def _append_special_token(self, word_embeddings, attention_mask):\n batch_size = get_shape(word_embeddings)[0]\n agg_embeddings = tf.tile(self.agg_token_embd[None, None, :],\n [batch_size, 1, 1])\n word_embeddings = tf.concat([agg_embeddings, word_embeddings],\n axis=1)\n attention_mask = tf.concat([tf.ones((batch_size, 1),\n dtype=attention_mask.dtype),\n attention_mask],\n axis=1)\n return word_embeddings, attention_mask\n\n def call(self,\n inputs_ids,\n training=True,\n attention_mask=None):\n \"\"\"Connects graph to sentence representation.\"\"\"\n\n # word_id to embeddings\n word_embeddings = self.embedding(inputs_ids)\n\n # generate padding mask\n if attention_mask is None:\n attention_mask = tf.where(inputs_ids == 0, 0, 1)\n\n # append special aggregation token if T5\n # the BERT implementation already supports AGG append\n if self._use_agg_token:\n word_embeddings, attention_mask = self._append_special_token(\n word_embeddings,\n attention_mask,\n )\n\n word_embeddings = self.pre_proj(word_embeddings)\n base_outputs = self.base_lm(\n inputs=None,\n inputs_embeddings=word_embeddings,\n attention_mask=attention_mask,\n training=training,\n )\n\n last_hidden_states = self.post_proj(base_outputs[\"hidden_states\"][-1])\n if self._use_agg_token or self._is_transformer:\n word_embeddings = last_hidden_states[:, 1:, :]\n sentence_embeddings = last_hidden_states[:, 0, :]\n else:\n word_embeddings = last_hidden_states\n sentence_embeddings = tf.reduce_max(last_hidden_states, axis=1)\n\n outputs = {\n \"word_embeddings\": word_embeddings,\n \"sentence_embeddings\": sentence_embeddings,\n }\n\n return outputs\n\n\ndef build_model(\n params = None,\n override_params = None,\n backbone = None,\n ):\n \"\"\"Build language model by name.\"\"\"\n\n if params is None:\n assert backbone is not None, (\n \"either params or backbone should be specified\")\n params = configs_factory.build_model_configs(backbone)\n\n if override_params is not None:\n params.override(override_params)\n\n model_name = params.name.lower()\n if model_name.startswith(\"linear\"):\n base_lm_head = LANGUAGE_MODEL_HEADS[\"linear\"]\n elif model_name.startswith(\"t5\"):\n base_lm_head = LANGUAGE_MODEL_HEADS[\"t5\"]\n elif model_name.startswith(\"bert\"):\n base_lm_head = LANGUAGE_MODEL_HEADS[\"bert\"]\n else:\n raise ValueError(\"Unknown model name {!r}\".format(params.name))\n\n model = LanguageModel(\n base_lm_head=base_lm_head,\n params=params,\n )\n\n logging.info(\"Text model %s created successfully.\", params.name)\n\n return model\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Lint as: python3\n\"\"\"Tests for convert_video_to_dataset.\"\"\"\n\nfrom absl.testing import absltest\nimport tensorflow as tf\n\nfrom uflow.data import generic_flow_dataset\nfrom uflow.misc import convert_video_to_dataset\n\n\nclass ConvertVideoToDatasetTest(absltest.TestCase):\n\n def test_video_parsing(self):\n \"\"\"Test that we can convert a video to a dataset and load it correctly.\"\"\"\n filepath = 'uflow/files/billiard_clip.mp4'\n output_dir = '/tmp/dataset'\n convert_video_to_dataset.convert_video(\n video_file_path=filepath,\n output_folder=output_dir)\n dataset = generic_flow_dataset.make_dataset(path=output_dir, mode='test')\n data_iterator = tf.compat.v1.data.make_one_shot_iterator(dataset)\n count = 0\n for element in data_iterator:\n image1, image2 = element\n count += 1\n self.assertEqual(image1.shape[0], image2.shape[0])\n self.assertEqual(image1.shape[1], image2.shape[1])\n self.assertEqual(image1.shape[2], 3)\n self.assertEqual(count, 299)\n\nif __name__ == '__main__':\n absltest.main()\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Tests for task_set.registry.\"\"\"\n\nfrom task_set import registry\n# pylint: disable=unused-import\nfrom task_set.optimizers import adam\nfrom task_set.tasks import mlp\n# pylint: enable=unused-import\nimport tensorflow.compat.v1 as tf\n\n\nclass RegistryTest(tf.test.TestCase):\n\n def test_optimizer_registry(self):\n optimizer_instance = registry.optimizers_registry.get_instance(\n \"adam_lr_-5.00\")\n loss = tf.get_variable(shape=[], dtype=tf.float32, name=\"var\")\n _ = optimizer_instance.minimize(loss)\n\n def test_task_registry(self):\n task_instance = registry.task_registry.get_instance(\"mlp_family_seed10\")\n self.assertEqual(task_instance.name, \"mlp_family_seed10\")\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Implementation of DualDICE.\"\"\"\nimport typing\nimport tensorflow as tf\nfrom tensorflow_addons import optimizers as tfa_optimizers\nimport tqdm\nfrom policy_eval.q_fitter import CriticNet\n\n\nclass DualDICE(object):\n \"\"\"Implementation of DualDICE.\"\"\"\n\n def __init__(self, state_dim, action_dim, weight_decay):\n self.nu = CriticNet(state_dim, action_dim)\n self.zeta = CriticNet(state_dim, action_dim)\n\n self.nu_optimizer = tfa_optimizers.AdamW(\n learning_rate=1e-4, beta_1=0.0, beta_2=0.99, weight_decay=weight_decay)\n self.zeta_optimizer = tfa_optimizers.AdamW(\n learning_rate=1e-3, beta_1=0.0, beta_2=0.99, weight_decay=weight_decay)\n\n @tf.function\n def update(self, initial_states, initial_actions,\n initial_weights, states, actions,\n next_states, next_actions, masks,\n weights, discount):\n \"\"\"Updates parameters.\n\n Args:\n initial_states: A batch of states.\n initial_actions: A batch of actions sampled from target policy.\n initial_weights: A batch of weights for the initial states.\n states: A batch of states.\n actions: A batch of actions sampled from behavior policy.\n next_states: A batch of next states.\n next_actions: A batch of next actions sampled from target policy.\n masks: A batch of masks indicating the end of the episodes.\n weights: A batch of weights.\n discount: An MDP discount factor.\n\n Returns:\n Critic loss.\n \"\"\"\n with tf.GradientTape(\n watch_accessed_variables=False, persistent=True) as tape:\n tape.watch(self.nu.trainable_variables)\n tape.watch(self.zeta.trainable_variables)\n\n nu = self.nu(states, actions)\n nu_next = self.nu(next_states, next_actions)\n nu_0 = self.nu(initial_states, initial_actions)\n\n zeta = self.zeta(states, actions)\n\n nu_loss = (\n tf.reduce_sum(weights * (\n (nu - discount * masks * nu_next) * zeta - tf.square(zeta) / 2)) /\n tf.reduce_sum(weights) -\n tf.reduce_sum(initial_weights *\n (1 - discount) * nu_0) / tf.reduce_sum(initial_weights))\n zeta_loss = -nu_loss\n\n nu_grads = tape.gradient(nu_loss, self.nu.trainable_variables)\n zeta_grads = tape.gradient(zeta_loss, self.zeta.trainable_variables)\n\n self.nu_optimizer.apply_gradients(\n zip(nu_grads, self.nu.trainable_variables))\n self.zeta_optimizer.apply_gradients(\n zip(zeta_grads, self.zeta.trainable_variables))\n\n del tape\n\n tf.summary.scalar(\n 'train/nu loss', nu_loss, step=self.nu_optimizer.iterations)\n tf.summary.scalar(\n 'train/zeta loss', zeta_loss, step=self.zeta_optimizer.iterations)\n\n return nu_loss\n\n @tf.function\n def estimate_returns(\n self,\n tf_dataset_iter,\n num_samples = 100):\n \"\"\"Estimated returns for a target policy.\n\n Args:\n tf_dataset_iter: Iterator over the dataset.\n num_samples: Number of samples used to estimate the returns.\n\n Returns:\n Estimated returns.\n \"\"\"\n pred_returns = 0.0\n pred_ratio = 0.0\n for _ in tqdm.tqdm(range(num_samples), desc='Estimating Returns'):\n states, actions, _, rewards, _, weights, _ = next(tf_dataset_iter)\n zeta = self.zeta(states, actions)\n pred_ratio += tf.reduce_sum(weights * zeta) / tf.reduce_sum(weights)\n pred_returns += tf.reduce_sum(\n weights * zeta * rewards) / tf.reduce_sum(weights)\n return pred_returns / num_samples, pred_ratio / num_samples\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Reference implementation for Infinite Nature's training loss.\n\nThese functions are NOT referenced by the demo code and are included\nto supplement the training details provided in the paper.\n\"\"\"\nimport ops\nimport tensorflow as tf\n\n\ndef compute_infinite_nature_loss(\n generated_rgbd, gt_rgbd, discriminator, mu_logvar):\n \"\"\"Computes loss between a generated RGBD sequence and the ground truth.\n\n Lambda terms are the default values used during the original submission.\n\n Args:\n generated_rgbd: [B, T, H, W, 4] A batch of T-length RGBD sequences\n produced by the generator. Ranges from (0, 1)\n gt_rgbd: [B, T, H, W, 4] The ground truth sequence from a video.\n Ranges from (0, 1)\n discriminator: a discriminator which accepts an [B, H, W, D] tensor\n and runs a discriminator on multiple scales and returns\n a list of (features, logit) for each scale.\n mu_logvar: ([B, 128], [B, 128]) A tuple of mu, log-variance features\n parameterizing the Gaussian used to sample the variational noise.\n\n Returns:\n A dictionary of losses. total_loss refers to the final\n loss used to optimize the generator and total_disc_loss refers to the\n loss used by the discriminator.\n \"\"\"\n _, _, height, width, _ = tf.shape(generated_rgbd).as_list()\n gen_flatten = tf.reshape(generated_rgbd, [-1, height, width, 4])\n gt_flatten = tf.reshape(gt_rgbd, [-1, height, width, 4])\n\n # discriminator returns:\n # [(scale_1_feats, scale_1_logits), (scale_2_feats, scale_2_logits), ...]\n disc_on_generated = discriminator(gen_flatten)\n generated_features = [f[0] for f in disc_on_generated]\n generated_logits = [f[1] for f in disc_on_generated]\n disc_on_real = discriminator(gt_flatten)\n real_features = [f[0] for f in disc_on_real]\n real_logits = [f[1] for f in disc_on_real]\n\n disc_loss, _, _ = compute_discriminator_loss(\n real_logits, tf.stop_gradients(generated_logits))\n fool_d_loss = compute_adversarial_loss(generated_logits)\n\n feature_matching_loss = compute_feature_matching(real_features,\n generated_features)\n kld_loss = compute_kld_loss(mu_logvar[0], mu_logvar[1])\n\n rgbd_loss = tf.reduce_mean(tf.abs(generated_rgbd - gt_rgbd))\n perceptual_loss = compute_perceptual_loss(generated_rgbd * 255.,\n gt_rgbd * 255.)\n\n loss_dict = {}\n loss_dict[\"disc_loss\"] = disc_loss\n loss_dict[\"adversarial_loss\"] = fool_d_loss\n loss_dict[\"feature_matching_loss\"] = feature_matching_loss\n loss_dict[\"kld_loss\"] = kld_loss\n loss_dict[\"perceptual_loss\"] = perceptual_loss\n loss_dict[\"reconstruction_loss\"] = rgbd_loss\n\n total_loss = (1e-2 * perceptual_loss +\n 10.0 * feature_matching_loss + 0.05 * kld_loss +\n 1.5 * fool_d_loss + 0.5 * rgbd_loss)\n total_disc_loss = 1.5 * disc_loss\n loss_dict[\"total_loss\"] = total_loss\n loss_dict[\"total_disc_loss\"] = total_disc_loss\n return loss_dict\n\n\ndef compute_kld_loss(mu, logvar):\n loss = -0.5 * tf.reduce_sum(1 + logvar - tf.square(mu) - tf.exp(logvar))\n return loss\n\n\ndef compute_discriminator_loss(real_logit, fake_logit):\n \"\"\"Computes the discriminator hinge loss given logits.\n\n Args:\n real_logit: A list of logits produced from the real image\n fake_logit: A list of logits produced from the fake image\n\n Returns:\n Scalars discriminator loss, adv_loss, patchwise accuracy of discriminator\n at detecting real and fake patches respectively.\n \"\"\"\n # Multi-scale disc returns a list.\n real_loss, fake_loss = 0, 0\n real_total, fake_total = 0, 0\n real_correct, fake_correct = 0, 0\n for real_l, fake_l in zip(real_logit, fake_logit):\n real_loss += tf.reduce_mean(tf.nn.relu(1 - real_l))\n fake_loss += tf.reduce_mean(tf.nn.relu(1 + fake_l))\n real_total += tf.cast(tf.reduce_prod(tf.shape(real_l)), tf.float32)\n fake_total += tf.cast(tf.reduce_prod(tf.shape(fake_l)), tf.float32)\n real_correct += tf.reduce_sum(tf.cast(real_l >= 0, tf.float32))\n fake_correct += tf.reduce_sum(tf.cast(fake_l < 0, tf.float32))\n\n # Avg of all outputs.\n real_loss = real_loss / float(len(real_logit))\n fake_loss = fake_loss / float(len(fake_logit))\n real_accuracy = real_correct / real_total\n fake_accuracy = fake_correct / fake_total\n\n disc_loss = real_loss + fake_loss\n\n return disc_loss, real_accuracy, fake_accuracy\n\n\ndef compute_adversarial_loss(fake_logit):\n \"\"\"Computes the adversarial hinge loss to apply to the generator.\n\n Args:\n fake_logit: list of tensors which correspond to discriminator logits\n on generated images\n\n Returns:\n A scalar of the loss.\n \"\"\"\n fake_loss = 0\n for fake_l in fake_logit:\n fake_loss += -tf.reduce_mean(fake_l)\n\n # average of all.\n fake_loss = fake_loss / float(len(fake_logit))\n\n return fake_loss\n\n\ndef compute_feature_matching(real_feats, fake_feats):\n \"\"\"Computes a feature matching loss between real and fake feature pyramids.\n\n Args:\n real_feats: A list of feature activations of a discriminator on real images\n fake_feats: A list of feature activations on fake images\n\n Returns:\n A scalar of the loss.\n \"\"\"\n losses = []\n # Loop for scale\n for real_feat, fake_feat in zip(real_feats, fake_feats):\n losses.append(tf.reduce_mean(tf.abs(real_feat - fake_feat)))\n\n return tf.reduce_mean(losses)\n\n\ndef compute_perceptual_loss(generated, real):\n \"\"\"Compute the perceptual loss between a generated and real sample.\n\n The input to this are RGB images ranging from [0, 255].\n\n build_vgg19's reference library can be found here:\n https://github.com/CQFIO/PhotographicImageSynthesis/blob/master/demo_1024p.py\n\n Args:\n generated: [B, H, W, 3] Generated image that we want to be perceptually\n close to real.\n real: [B, H, W, 3] Ground truth image that we want to target.\n\n Returns:\n A tf scalar corresponding to the perceptual loss.\n \"\"\"\n # Input is [0, 255.], not necessarily clipped though\n def build_vgg19(*args):\n raise NotImplementedError\n vgg_real_fake = build_vgg19(\n tf.concat([real, generated], axis=0),\n \"imagenet-vgg-verydeep-19.mat\")\n\n def compute_l1_loss(key):\n real, fake = tf.split(vgg_real_fake[key], 2, axis=0)\n return tf.reduce_mean(tf.abs(real - fake))\n\n p0 = tf.zeros([])\n p1 = compute_l1_loss(\"conv1_2\") / 2.6\n p2 = compute_l1_loss(\"conv2_2\") / 4.8\n p3 = compute_l1_loss(\"conv3_2\") / 3.7\n p4 = compute_l1_loss(\"conv4_2\") / 5.6\n p5 = compute_l1_loss(\"conv5_2\") * 10 / 1.5\n return p0 + p1 + p2 + p3 + p4 + p5\n\n\ndef multiscale_discriminator(rgbd_sequence):\n \"\"\"A reference implementation for the discriminator.\n\n This is not used by the demo during inference.\n\n Args:\n rgbd_sequence: [B, H, W, 4] A batch of RGBD images.\n\n Returns:\n A list of (features, logits) tuples corresponding to two scales.\n \"\"\"\n features, logit = patch_discriminator(\n rgbd_sequence, scope=\"spade_discriminator_0\")\n\n x_small = ops.half_size(rgbd_sequence)\n features_small, logit_small = patch_discriminator(\n x_small, scope=\"spade_discriminator_1\")\n\n # These are lists\n return [features, features_small], [logit, logit_small]\n\n\ndef patch_discriminator(rgbd_sequence, scope=\"spade_discriminator\"):\n \"\"\"Creates a patch discriminator to process RGBD values.\n\n Args:\n rgbd_sequence: [B, H, W, 4] A batch of RGBD images.\n scope: (str) variable scope\n\n Returns:\n (list of features, logits)\n \"\"\"\n num_channel = 64\n num_layers = 4\n features = []\n with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):\n x = ops.sn_conv(\n rgbd_sequence, num_channel, kernel_size=4, stride=2, sn=False)\n channel = num_channel\n for i in range(1, num_layers):\n stride = 1 if i == num_layers - 1 else 2\n channel = min(channel * 2, 512)\n x = ops.sn_conv(\n x, channel, kernel_size=4, stride=stride, sn=True,\n scope=\"conv_{}\".format(i))\n x = ops.instance_norm(x, scope=\"inst_norm_{}\".format(i))\n x = tf.nn.lrelu(x, 0.2)\n features.append(x)\n\n logit = ops.sn_conv(\n x, 1, kernel_size=4, stride=1,\n sn=False, scope=\"D_logit\")\n\n return features, logit\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"TFlite utils.\"\"\"\n# Lint as: python3\nimport os\n\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.lite.python import interpreter as interpreter_wrapper # pylint: disable=g-direct-tensorflow-import\nfrom tensorflow.lite.tools import flatbuffer_utils # pylint: disable=g-direct-tensorflow-import\nfrom tensorflow.python.tools import saved_model_utils # pylint: disable=g-direct-tensorflow-import\n\n\ndef export_tflite_from_saved_model(saved_model_dir):\n \"\"\"Convert SavedModel to TFlite graph.\"\"\"\n converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir)\n supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS]\n converter.target_spec.supported_ops = supported_ops\n converter.allow_custom_ops = True\n converter.optimizations = [tf.lite.Optimize.DEFAULT]\n tflite_model = converter.convert()\n export_path = os.path.join(saved_model_dir, \"model.tflite\")\n with tf.io.gfile.GFile(export_path, \"wb\") as f:\n f.write(tflite_model)\n\n\ndef tflite_graph_rewrite(tflite_model_path,\n saved_model_dir,\n custom_op_registerers=None):\n \"\"\"Rewrite TFLite graph to make inputs/outputs tensor name consistent.\n\n TF users do not have good control over outputs tensor names from\n get_concrete_function(), to maintain backward compatibility the tensor name\n in TFLite graph need to be meaningful and properly set. This function looks up\n the meaningful names from SavedModel signature meta data and rewrite it into\n TFlite graph.\n\n Arguments:\n tflite_model_path: The path to the exported TFLite graph, which will be\n overwrite after rewrite.\n saved_model_dir: Directory that stores SavedModelthat used for TFLite\n custom_op_registerers: list with custom op registers\n conversion.\n \"\"\"\n # Find map from signature inputs/outputs name to tensor name in SavedModel.\n meta_graph_def = saved_model_utils.get_meta_graph_def(saved_model_dir,\n \"serve\")\n signature_def = meta_graph_def.signature_def\n tensor_name_to_signature_name = {}\n for key, value in signature_def[\"serving_default\"].inputs.items():\n tensor_name_to_signature_name[value.name] = key\n for key, value in signature_def[\"serving_default\"].outputs.items():\n tensor_name_to_signature_name[value.name] = key\n\n # Find map from TFlite inputs/outputs index to tensor name in TFLite graph.\n with tf.io.gfile.GFile(tflite_model_path, \"rb\") as f:\n interpreter = interpreter_wrapper.InterpreterWithCustomOps(\n model_content=f.read(),\n custom_op_registerers=custom_op_registerers)\n tflite_input_index_to_tensor_name = {}\n tflite_output_index_to_tensor_name = {}\n for idx, input_detail in enumerate(interpreter.get_input_details()):\n tflite_input_index_to_tensor_name[idx] = input_detail[\"name\"]\n for idx, output_detail in enumerate(interpreter.get_output_details()):\n tflite_output_index_to_tensor_name[idx] = output_detail[\"name\"]\n\n # Rewrite TFLite graph inputs/outputs name.\n mutable_fb = flatbuffer_utils.read_model_with_mutable_tensors(\n tflite_model_path)\n subgraph = mutable_fb.subgraphs[0]\n for input_idx, input_tensor_name in tflite_input_index_to_tensor_name.items():\n subgraph.tensors[subgraph.inputs[\n input_idx]].name = tensor_name_to_signature_name[input_tensor_name]\n for output_idx, output_tensor_name in tflite_output_index_to_tensor_name.items(\n ):\n subgraph.tensors[subgraph.outputs[\n output_idx]].name = tensor_name_to_signature_name[output_tensor_name]\n flatbuffer_utils.write_model(mutable_fb, tflite_model_path)\n\n\ndef get_tensor_name_to_tflite_input_index(details):\n tensor_name_to_tflite_input_index = {}\n for i, detail in enumerate(details):\n tensor_name_to_tflite_input_index[detail[\"name\"]] = i\n return tensor_name_to_tflite_input_index\n\n\ndef run_stream_inference_classification_tflite(interpreter,\n inp_audio,\n input_states,\n stride,\n input_tensot_name=\"input_0\",\n output_tensor_name=\"output_0\"):\n \"\"\"Runs streaming inference classification with tflite (external state).\n\n It is useful for testing streaming classification\n Args:\n interpreter: tf lite interpreter in streaming mode\n inp_audio: input audio data\n input_states: input states\n stride: total stride in the model\n input_tensot_name: input tensor name\n output_tensor_name: output tensor name\n Returns:\n last output\n \"\"\"\n\n input_details = interpreter.get_input_details()\n output_details = interpreter.get_output_details()\n\n inp_tensor_name_to_tflite_inp_index = get_tensor_name_to_tflite_input_index(\n input_details)\n out_tensor_name_to_tflite_out_index = get_tensor_name_to_tflite_input_index(\n output_details)\n\n start = 0\n end = stride\n while end <= inp_audio.shape[1]:\n # get new audio chunk\n stream_update = inp_audio[:, start:end]\n\n # update indexes of streamed updates\n start = end\n end += stride\n\n # classification result of a current frame\n interpreter.set_tensor(\n input_details[inp_tensor_name_to_tflite_inp_index[input_tensot_name]]\n [\"index\"], stream_update.astype(np.float32))\n\n # set states\n for key in input_states.keys():\n interpreter.set_tensor(\n input_details[inp_tensor_name_to_tflite_inp_index[key]][\"index\"],\n input_states[key].astype(np.float32))\n\n interpreter.invoke()\n\n # classification output\n tflite_output = interpreter.get_tensor(output_details[\n out_tensor_name_to_tflite_out_index[output_tensor_name]][\"index\"])\n\n # update states\n for key in input_states.keys():\n input_states[key] = interpreter.get_tensor(\n output_details[out_tensor_name_to_tflite_out_index[key]][\"index\"])\n\n # return the last classification results\n return tflite_output\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# python3\n\"\"\"Implementation of DDPG.\"\"\"\n\nimport typing\n\nfrom dm_env import specs as dm_env_specs\nimport numpy as np\nimport tensorflow as tf\nfrom tf_agents.specs.tensor_spec import TensorSpec\n\nfrom representation_batch_rl.batch_rl import critic\nfrom representation_batch_rl.batch_rl.encoders import ConvStack\nfrom representation_batch_rl.batch_rl.encoders import ImageEncoder\nfrom representation_batch_rl.batch_rl.encoders import make_impala_cnn_network\nfrom representation_batch_rl.representation_batch_rl import tf_utils\n\n\nclass CSSC(object):\n \"\"\"Class performing CQL training.\"\"\"\n\n def __init__(self,\n observation_spec,\n action_spec,\n actor_lr = 1e-4,\n critic_lr = 3e-4,\n discount = 0.99,\n tau = 0.005,\n target_entropy = 0.0,\n reg = 0.0,\n num_cql_actions = 10,\n embedding_dim = 512,\n bc_pretraining_steps = 40_000,\n min_q_weight = 10.0,\n num_augmentations = 1,\n rep_learn_keywords = 'outer',\n batch_size = 256):\n \"\"\"Creates networks.\n\n Args:\n observation_spec: environment observation spec.\n action_spec: Action spec.\n actor_lr: Actor learning rate.\n critic_lr: Critic learning rate.\n discount: MDP discount.\n tau: Soft target update parameter.\n target_entropy: Target entropy.\n reg: Coefficient for out of distribution regularization.\n num_cql_actions: Number of actions to sample for CQL loss.\n embedding_dim: Size of embedding (now hardcoded)\n bc_pretraining_steps: Use BC loss instead of CQL loss for N steps.\n min_q_weight: CQL alpha.\n num_augmentations: Num of random crops\n rep_learn_keywords: Representation learning loss to add.\n batch_size: Batch size\n \"\"\"\n del embedding_dim\n self.num_augmentations = num_augmentations\n self.batch_size = batch_size\n self.rep_learn_keywords = rep_learn_keywords.split('__')\n\n actor_kwargs = {}\n critic_kwargs = {}\n\n if observation_spec.shape == (64, 64, 3):\n # IMPALA for Procgen\n def conv_stack():\n return make_impala_cnn_network(\n depths=[16, 32, 32], use_batch_norm=False, dropout_rate=0.)\n\n state_dim = 256\n else:\n # Reduced architecture for DMC\n def conv_stack():\n return ConvStack(observation_spec.shape)\n state_dim = 50\n\n conv_stack_bc = conv_stack()\n conv_stack_actor = conv_stack()\n conv_stack_critic = conv_stack()\n conv_target_stack_critic = conv_stack()\n\n if observation_spec.shape == (64, 64, 3):\n conv_stack_bc.output_size = state_dim\n conv_stack_actor.output_size = state_dim\n conv_stack_critic.output_size = state_dim\n conv_target_stack_critic.output_size = state_dim\n # Combine and stop_grad some of the above conv stacks\n actor_kwargs['encoder_bc'] = ImageEncoder(\n conv_stack_bc, feature_dim=state_dim, bprop_conv_stack=True)\n actor_kwargs['encoder'] = ImageEncoder(\n conv_stack_critic, feature_dim=state_dim, bprop_conv_stack=False)\n critic_kwargs['encoder'] = ImageEncoder(\n conv_stack_critic, feature_dim=state_dim, bprop_conv_stack=True)\n # Note: the target critic does not share any weights.\n critic_kwargs['encoder_target'] = ImageEncoder(\n conv_target_stack_critic, feature_dim=state_dim, bprop_conv_stack=True)\n\n if self.num_augmentations == 0:\n dummy_state = tf.constant(\n np.zeros(shape=[1] + list(observation_spec.shape)))\n else: # account for padding of +4 everywhere and then cropping out 68\n dummy_state = tf.constant(np.zeros(shape=[1, 68, 68, 3]))\n\n @tf.function\n def init_models():\n actor_kwargs['encoder_bc'](dummy_state)\n actor_kwargs['encoder'](dummy_state)\n critic_kwargs['encoder'](dummy_state)\n critic_kwargs['encoder_target'](dummy_state)\n\n init_models()\n\n hidden_dims = (256, 256)\n # self.actor = policies.CategoricalPolicy(state_dim, action_spec,\n # hidden_dims=hidden_dims, encoder=actor_kwargs['encoder'])\n action_dim = action_spec.maximum.item() + 1\n\n self.action_dim = action_dim\n\n self.log_alpha = tf.Variable(tf.math.log(1.0), trainable=True)\n self.log_cql_alpha = self.log_alpha\n self.alpha_optimizer = tf.keras.optimizers.Adam(learning_rate=actor_lr)\n\n self.critic = critic.Critic(\n state_dim,\n action_dim,\n hidden_dims=hidden_dims,\n encoder=critic_kwargs['encoder'],\n discrete_actions=True,\n linear='linear_Q' in self.rep_learn_keywords)\n self.critic_target = critic.Critic(\n state_dim,\n action_dim,\n hidden_dims=hidden_dims,\n encoder=critic_kwargs['encoder_target'],\n discrete_actions=True,\n linear='linear_Q' in self.rep_learn_keywords)\n\n @tf.function\n def init_models2():\n dummy_state = tf.zeros((1, 68, 68, 3), dtype=tf.float32)\n phi_s = self.critic.encoder(dummy_state)\n phi_a = tf.eye(15, dtype=tf.float32)\n if 'linear_Q' in self.rep_learn_keywords:\n _ = self.critic.critic1.state_encoder(phi_s)\n _ = self.critic.critic2.state_encoder(phi_s)\n _ = self.critic.critic1.action_encoder(phi_a)\n _ = self.critic.critic2.action_encoder(phi_a)\n _ = self.critic_target.critic1.state_encoder(phi_s)\n _ = self.critic_target.critic2.state_encoder(phi_s)\n _ = self.critic_target.critic1.action_encoder(phi_a)\n _ = self.critic_target.critic2.action_encoder(phi_a)\n\n init_models2()\n\n critic.soft_update(self.critic, self.critic_target, tau=1.0)\n self.critic_optimizer = tf.keras.optimizers.Adam(learning_rate=critic_lr)\n self.br_optimizer = tf.keras.optimizers.Adam(learning_rate=3e-4)\n self.tau = tau\n\n self.reg = reg\n self.target_entropy = target_entropy\n self.discount = discount\n\n self.num_cql_actions = num_cql_actions\n self.bc_pretraining_steps = bc_pretraining_steps\n self.min_q_weight = min_q_weight\n\n self.bc = None\n\n self.model_dict = {\n 'critic': self.critic,\n 'critic_target': self.critic_target,\n 'critic_optimizer': self.critic_optimizer,\n 'alpha_optimizer': self.alpha_optimizer\n }\n\n @tf.function\n def infonce_by_class(self,\n features,\n classes,\n target_features=None,\n n_batch=None):\n \"\"\"InfoNCE between features of a given class vs other clases.\n\n Args:\n\n features: n_batch x n_features\n classes: n_batch x n_features\n target_features: optional target features for dot product\n n_batch: int, optional dimension param\n\n Returns:\n scores: tf.tensor\n \"\"\"\n if n_batch is None:\n n_batch = self.batch_size\n # \\sum_ij A_i:A_:j\n # Picks elements of A which are the same class as A_i\n class_mapping = tf.einsum('ik,jk->ij', classes, classes)\n # outer_prod: n_batch x n_batch\n if target_features is None:\n outer_prod = tf.einsum('ik,jk->ij', features, features)\n else:\n outer_prod = tf.einsum('ik,jk->ij', features, target_features)\n\n scores = tf.nn.log_softmax(outer_prod, -1)\n\n # Add all instances with class=i to numerator by summing over axis 1\n return tf.reduce_mean(tf.reduce_sum(class_mapping * scores, -1))\n\n @property\n def alpha(self):\n return tf.constant(0.)\n # return tf.exp(self.log_alpha)\n\n @property\n def cql_alpha(self):\n return tf.exp(self.log_cql_alpha)\n\n def fit_critic(self, states, actions,\n next_states, next_actions, rewards,\n discounts):\n \"\"\"Updates critic parameters.\n\n Args:\n states: Batch of states.\n actions: Batch of actions.\n next_states: Batch of next states.\n next_actions: Batch of next actions from training policy.\n rewards: Batch of rewards.\n discounts: Batch of masks indicating the end of the episodes.\n\n Returns:\n Dictionary with information to track.\n \"\"\"\n action_indices = tf.stack(\n [tf.range(tf.shape(actions)[0], dtype=tf.int64), actions], axis=-1)\n next_action_indices = tf.stack(\n [tf.range(tf.shape(next_actions)[0], dtype=tf.int64), next_actions],\n axis=-1)\n\n if self.num_augmentations > 0:\n target_q = 0.\n for i in range(self.num_augmentations):\n next_q1_i, next_q2_i = self.critic_target(next_states[i], actions=None)\n target_q_i = tf.expand_dims(\n rewards, 1) + self.discount * tf.expand_dims(\n discounts, 1) * tf.minimum(next_q1_i, next_q2_i)\n target_q += target_q_i\n target_q /= self.num_augmentations\n else:\n next_q1, next_q2 = self.critic_target(next_states, actions=None)\n target_q = tf.expand_dims(rewards, 1) + self.discount * tf.expand_dims(\n discounts, 1) * tf.minimum(next_q1, next_q2)\n\n target_q = tf.gather_nd(target_q, indices=next_action_indices)\n\n with tf.GradientTape(watch_accessed_variables=False) as tape:\n tape.watch(self.critic.trainable_variables)\n\n if self.num_augmentations > 0:\n critic_loss = 0.\n q1 = 0.\n q2 = 0.\n for i in range(self.num_augmentations):\n q1_i, q2_i = self.critic(states[i], actions=None)\n critic_loss_i = (\n tf.losses.mean_squared_error(\n target_q, tf.gather_nd(q1_i, indices=action_indices)) +\n tf.losses.mean_squared_error(\n target_q, tf.gather_nd(q2_i, indices=action_indices)))\n q1 += q1_i\n q2 += q2_i\n critic_loss += critic_loss_i\n q1 /= self.num_augmentations\n q2 /= self.num_augmentations\n critic_loss /= self.num_augmentations\n else:\n q1, q2 = self.critic(states, actions=None)\n q = tf.minimum(q1, q2)\n critic_loss = (\n tf.losses.mean_squared_error(\n target_q, tf.gather_nd(q1, indices=action_indices)) +\n tf.losses.mean_squared_error(\n target_q, tf.gather_nd(q2, indices=action_indices)))\n\n cql_logsumexp = tf.reduce_logsumexp(q, 1)\n cql_loss = tf.reduce_mean(cql_logsumexp -\n tf.gather_nd(q, indices=action_indices))\n\n critic_loss += (self.reg * cql_loss)\n\n critic_grads = tape.gradient(critic_loss, self.critic.trainable_variables)\n\n self.critic_optimizer.apply_gradients(\n zip(critic_grads, self.critic.trainable_variables))\n\n critic.soft_update(self.critic, self.critic_target, tau=self.tau)\n\n return {\n 'q1': tf.reduce_mean(q1),\n 'q2': tf.reduce_mean(q2),\n 'critic_loss': critic_loss,\n 'cql_loss': cql_loss\n }\n\n @tf.function\n def fit_embedding(self, states, actions,\n next_states, next_actions, rewards,\n discounts, level_ids):\n \"\"\"Fit representation (pixel encoder).\n\n Args:\n states: tf.tensor\n actions: tf.tensor\n next_states: tf.tensor\n next_actions: tf.tensor\n rewards: tf.tensor\n discounts: tf.tensor\n level_ids: tf.tensor, contains level id labels\n\n Returns:\n embedding_dict: dict\n\n \"\"\"\n del states, next_actions, discounts, rewards, level_ids\n ssl_variables = self.critic.trainable_variables\n\n with tf.GradientTape(watch_accessed_variables=True) as tape:\n next_state_features = self.critic.encoder(next_states[0])\n rep_loss = -self.infonce_by_class(\n next_state_features,\n tf.cast(tf.one_hot(actions, depth=self.action_dim), tf.float32))\n embedding_loss = 0.01 * (rep_loss)\n\n br_grads = tape.gradient(embedding_loss, ssl_variables)\n self.br_optimizer.apply_gradients(zip(br_grads, ssl_variables))\n\n gn = tf.reduce_mean([tf.linalg.norm(v) for v in br_grads if v is not None])\n\n return {\n # 'rep_loss': rep_loss,\n # 'state_nce_loss': rep_loss,\n 'embedding_loss': embedding_loss,\n 'embedding_grad_norm': gn\n }\n\n @tf.function\n def update_step(self,\n replay_buffer_iter,\n train_target='both'):\n \"\"\"Performs a single training step for critic and embedding.\n\n Args:\n replay_buffer_iter: A tensorflow graph iteratable object.\n train_target: string specifying whether update RL and or representation\n\n Returns:\n Dictionary with losses to track.\n \"\"\"\n del train_target\n transition = next(replay_buffer_iter)\n numpy_dataset = isinstance(replay_buffer_iter, np.ndarray)\n # observation: n_batch x n_timesteps x 1 x H*W*3*n_frames x 1 ->\n # n_batch x H x W x 3*n_frames\n if not numpy_dataset:\n states = transition.observation[:, 0]\n next_states = transition.observation[:, 1]\n actions = transition.action[:, 0]\n rewards = transition.reward[:, 0]\n discounts = transition.discount[:, 0]\n level_ids = transition.policy_info[:, 0]\n\n if transition.observation.dtype == tf.uint8:\n states = tf.cast(states, tf.float32) / 255.\n next_states = tf.cast(next_states, tf.float32) / 255.\n else:\n states, actions, rewards, next_states, discounts = transition\n\n if self.num_augmentations > 0:\n states, next_states = tf_utils.image_aug(\n states,\n next_states,\n img_pad=4,\n num_augmentations=self.num_augmentations,\n obs_dim=64,\n channels=3,\n cropped_shape=[self.batch_size, 68, 68, 3])\n\n next_actions = self.act(next_states, data_aug=True)\n\n critic_dict = self.fit_critic(states, actions, next_states, next_actions,\n rewards, discounts)\n ssl_dict = self.fit_embedding(states, actions, next_states, next_actions,\n rewards, discounts, level_ids)\n\n return {**critic_dict, **ssl_dict}\n\n @tf.function\n def act(self, states, data_aug=False):\n \"\"\"Act with batch of states.\n\n Args:\n states: tf.tensor n_batch x 64 x 64 x 3\n data_aug: bool, whether to use stochastic data aug (else deterministic)\n\n Returns:\n action: tf.tensor\n \"\"\"\n if data_aug and self.num_augmentations > 0:\n states = states[0]\n if self.num_augmentations > 0:\n # use pad of 2 to bump 64 to 68 with 2 + 64 + 2 on each side\n img_pad = 2\n paddings = tf.constant(\n [[0, 0], [img_pad, img_pad], [img_pad, img_pad], [0, 0]],\n dtype=tf.int32)\n states = tf.cast(\n tf.pad(tf.cast(states * 255., tf.int32), paddings, 'SYMMETRIC'),\n tf.float32) / 255.\n\n q1, q2 = self.critic(states, actions=None)\n q = tf.minimum(q1, q2)\n actions = tf.argmax(q, -1)\n return actions\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Tests for pipeline.\"\"\"\n\nimport os\n\nfrom absl import logging\nfrom absl.testing import absltest\nfrom absl.testing import flagsaver\nimport apache_beam as beam\nimport tensorflow as tf\nfrom tensorflow.io import gfile\n\nfrom smu import dataset_pb2\nfrom smu import pipeline\n\nTESTDATA_PATH = os.path.join(\n os.path.dirname(os.path.abspath(__file__)), 'testdata')\n\n\nclass FunctionalTest(absltest.TestCase):\n\n def test_merge_duplicate_information_same_topology(self):\n main_conf = dataset_pb2.Conformer(conformer_id=123000)\n main_conf.initial_geometries.add()\n main_conf.initial_geometries[0].atom_positions.add(x=1, y=2, z=3)\n\n dup_conf = dataset_pb2.Conformer(conformer_id=123456, duplicated_by=123000)\n dup_conf.initial_geometries.add()\n dup_conf.initial_geometries[0].atom_positions.add(x=4, y=5, z=6)\n\n got = pipeline.merge_duplicate_information(123000, [dup_conf, main_conf])\n self.assertEqual(got.conformer_id, 123000)\n self.assertEqual(got.duplicated_by, 0)\n self.assertEqual(got.duplicate_of, [123456])\n self.assertLen(got.initial_geometries, 2)\n self.assertEqual(got.initial_geometries[0].atom_positions[0].x, 1)\n self.assertEqual(got.initial_geometries[1].atom_positions[0].x, 4)\n\n def test_merge_duplicate_information_diff_topology(self):\n main_conf = dataset_pb2.Conformer(conformer_id=123000)\n main_conf.initial_geometries.add()\n main_conf.initial_geometries[0].atom_positions.add(x=1, y=2, z=3)\n\n dup_conf = dataset_pb2.Conformer(conformer_id=456000, duplicated_by=123000)\n dup_conf.initial_geometries.add()\n dup_conf.initial_geometries[0].atom_positions.add(x=4, y=5, z=6)\n\n got = pipeline.merge_duplicate_information(123000, [dup_conf, main_conf])\n self.assertEqual(got.conformer_id, 123000)\n self.assertEqual(got.duplicated_by, 0)\n self.assertEqual(got.duplicate_of, [456000])\n # TODO(pfr, ianwatson): implement correct copying of initial geometry\n self.assertLen(got.initial_geometries, 1)\n self.assertEqual(got.initial_geometries[0].atom_positions[0].x, 1)\n\n def test_extract_bond_lengths(self):\n # This conformer does not obey valence rules, but it's fine for this test.\n conf = dataset_pb2.Conformer(conformer_id=123000)\n conf.properties.errors.status = 4\n bt = conf.bond_topologies.add()\n bt.atoms.extend([\n dataset_pb2.BondTopology.ATOM_ONEG, dataset_pb2.BondTopology.ATOM_NPOS,\n dataset_pb2.BondTopology.ATOM_C, dataset_pb2.BondTopology.ATOM_H\n ])\n bt.bonds.add(\n atom_a=0, atom_b=1, bond_type=dataset_pb2.BondTopology.BOND_SINGLE)\n bt.bonds.add(\n atom_a=0, atom_b=2, bond_type=dataset_pb2.BondTopology.BOND_DOUBLE)\n bt.bonds.add(\n atom_a=0, atom_b=3, bond_type=dataset_pb2.BondTopology.BOND_SINGLE)\n conf.optimized_geometry.atom_positions.add(x=0, y=0, z=0)\n conf.optimized_geometry.atom_positions.add(x=1, y=0, z=0)\n conf.optimized_geometry.atom_positions.add(x=0, y=2, z=0)\n conf.optimized_geometry.atom_positions.add(x=111, y=222, z=333)\n\n got = list(\n pipeline.extract_bond_lengths(\n conf, dist_sig_digits=2, unbonded_max=2.0))\n # Note that these are *not* rounded, but truncated to this many digits.\n self.assertEqual(\n got,\n [\n # 1 bohr -> 0.529177249 angstroms\n ('n', 'o', dataset_pb2.BondTopology.BOND_SINGLE, '0.52'),\n # 2 bohr -> 2 * 0.529177249 angstroms\n ('c', 'o', dataset_pb2.BondTopology.BOND_DOUBLE, '1.05'),\n # sqrt(1**2 + 2**2) bohr -> 2.23606 * 0.529177249 angstroms\n ('c', 'n', dataset_pb2.BondTopology.BOND_UNDEFINED, '1.18')\n ])\n\n def test_extract_bond_lengths_max_unbonded(self):\n # This conformer does not obery valence rules, but it's fine for this test.\n conf = dataset_pb2.Conformer(conformer_id=123000)\n conf.properties.errors.status = 4\n bt = conf.bond_topologies.add()\n bt.atoms.extend([\n dataset_pb2.BondTopology.ATOM_C, dataset_pb2.BondTopology.ATOM_N,\n dataset_pb2.BondTopology.ATOM_O\n ])\n bt.bonds.add(\n atom_a=0, atom_b=1, bond_type=dataset_pb2.BondTopology.BOND_SINGLE)\n bt.bonds.add(\n atom_a=0, atom_b=2, bond_type=dataset_pb2.BondTopology.BOND_SINGLE)\n conf.optimized_geometry.atom_positions.add(x=0, y=0, z=0)\n conf.optimized_geometry.atom_positions.add(x=1, y=0, z=0)\n conf.optimized_geometry.atom_positions.add(x=100, y=2, z=0)\n\n got = list(\n pipeline.extract_bond_lengths(\n conf, dist_sig_digits=2, unbonded_max=2.0))\n # Note that these are *not* rounded, but truncated to this many digits.\n self.assertEqual(\n got,\n [\n # 1 bohr -> 0.529177249 angstroms\n ('c', 'n', dataset_pb2.BondTopology.BOND_SINGLE, '0.52'),\n # It seems like this should be 52.91 but it looks like some\n # numerical noise in np.linalg.norm.\n ('c', 'o', dataset_pb2.BondTopology.BOND_SINGLE, '52.92')\n ])\n # Note that the N-O distance is not reported while the C-O is.\n\n def _create_dummy_conformer(self):\n conf = dataset_pb2.Conformer(conformer_id=123000)\n bt = conf.bond_topologies.add()\n bt.atoms.extend(\n [dataset_pb2.BondTopology.ATOM_C, dataset_pb2.BondTopology.ATOM_C])\n bt.bonds.add(\n atom_a=0, atom_b=1, bond_type=dataset_pb2.BondTopology.BOND_SINGLE)\n conf.optimized_geometry.atom_positions.add(x=0, y=0, z=0)\n conf.optimized_geometry.atom_positions.add(x=1, y=0, z=0)\n return conf\n\n def test_extract_bond_lengths_has_errors(self):\n conf = self._create_dummy_conformer()\n conf.properties.errors.status = 8\n got = list(\n pipeline.extract_bond_lengths(\n conf, dist_sig_digits=2, unbonded_max=2.0))\n self.assertEqual([], got)\n\n def test_extract_bond_lengths_is_dup(self):\n conf = self._create_dummy_conformer()\n conf.properties.errors.status = 0\n conf.duplicated_by = 456000\n got = list(\n pipeline.extract_bond_lengths(\n conf, dist_sig_digits=2, unbonded_max=2.0))\n self.assertEqual([], got)\n\n\nclass IntegrationTest(absltest.TestCase):\n\n def test_whole_pipeline(self):\n test_subdirectory = self.create_tempdir()\n output_stem = os.path.join(test_subdirectory, 'testout')\n input_stage1_dat_glob = os.path.join(TESTDATA_PATH,\n 'pipeline_input_stage1.dat')\n input_stage2_dat_glob = os.path.join(TESTDATA_PATH,\n 'pipeline_input_stage2.dat')\n input_equivalent_glob = os.path.join(TESTDATA_PATH,\n 'pipeline_equivalent.dat')\n input_bond_topology_csv = os.path.join(TESTDATA_PATH,\n 'pipeline_bond_topology.csv')\n with flagsaver.flagsaver(\n input_stage1_dat_glob=input_stage1_dat_glob,\n input_stage2_dat_glob=input_stage2_dat_glob,\n input_equivalent_glob=input_equivalent_glob,\n input_bond_topology_csv=input_bond_topology_csv,\n output_stem=output_stem,\n output_shards=1):\n # If you have custom beam options, add them here.\n beam_options = None\n with beam.Pipeline(beam_options) as root:\n pipeline.pipeline(root)\n\n metrics = root.result.metrics().query()\n counters_dict = {\n m.key.metric.name: m.committed for m in metrics['counters']\n }\n\n self.assertEqual(counters_dict['attempted_topology_matches'], 3)\n # Conformer 620517 will not match because bond lengths are not extracted\n # from conformers with serious errors like this.\n self.assertEqual(counters_dict['no_topology_matches'], 1)\n self.assertNotIn('topology_match_smiles_failure', counters_dict)\n\n logging.info('Files in output: %s',\n '\\n'.join(gfile.glob(os.path.join(test_subdirectory, '*'))))\n for stage in ['stage1', 'stage2']:\n self.assertTrue(\n gfile.exists(output_stem + '_' + stage +\n '_original_known_error-00000-of-00001.dat'))\n self.assertTrue(\n gfile.exists(output_stem + '_' + stage +\n '_original_unknown_error-00000-of-00001.dat'))\n self.assertTrue(\n gfile.exists(output_stem + '_' + stage +\n '_mismatched_original-00000-of-00001.dat'))\n self.assertTrue(\n gfile.exists(output_stem + '_' + stage +\n '_mismatched_regen-00000-of-00001.dat'))\n\n # Check the merge conflicts file\n with gfile.GFile(output_stem + '_conflicts-00000-of-00001.csv') as f:\n conflicts_lines = f.readlines()\n self.assertIn('conformer_id,', conflicts_lines[0])\n self.assertEqual(\n conflicts_lines[1], '618451001,1,1,1,1,'\n '-406.51179,9.999999,-406.522079,9.999999,True,True,'\n '-406.51179,0.052254,-406.522079,2.5e-05,True,True\\n')\n\n # Check a couple of the stats.\n with gfile.GFile(output_stem + '_stats-00000-of-00001.csv') as f:\n stats_lines = f.readlines()\n self.assertIn('errors.status,0,2\\n', stats_lines)\n self.assertIn('errors.warn_t1,0,4\\n', stats_lines)\n self.assertIn('fate,FATE_SUCCESS,2\\n', stats_lines)\n self.assertIn('fate,FATE_DUPLICATE_DIFFERENT_TOPOLOGY,1\\n', stats_lines)\n self.assertIn('num_initial_geometries,1,4\\n', stats_lines)\n self.assertIn('num_duplicates,1,1\\n', stats_lines)\n self.assertIn('zero_field,single_point_energy_pbe0d3_6_311gd,1\\n',\n stats_lines)\n\n # Check the smiles comparison output\n with gfile.GFile(output_stem + '_smiles_compare-00000-of-00001.csv') as f:\n smiles_lines = f.readlines()\n self.assertIn(\n '620517002,MISMATCH,NotAValidSmilesString,'\n '[H]C1=C2OC2=C(F)O1,FC1=C2OC2=CO1\\n', smiles_lines)\n # Make sure that a bond topology with a matching smiles doesn't show\n for line in smiles_lines:\n self.assertNotIn('618451001', line)\n\n # Check the bond topology summary\n with gfile.GFile(output_stem + '_bt_summary-00000-of-00001.csv') as f:\n bt_summary_lines = f.readlines()\n # Check part of the header line\n self.assertIn('bt_id', bt_summary_lines[0])\n self.assertIn('count_attempted_conformers', bt_summary_lines[0])\n # This is the bond topology that has no conformer\n self.assertIn('10,0,0,0,0,0,0,0,0,0,0,0,0,0\\n', bt_summary_lines)\n # This is a bond topology with 1 conformer\n self.assertIn('620517,1,0,0,0,1,0,1,0,0,0,0,0,0\\n', bt_summary_lines)\n # This is a bond topology with 2 conformers\n self.assertIn('618451,2,0,0,0,2,0,0,0,2,0,0,0,0\\n', bt_summary_lines)\n\n # Check the bond lengths file\n with gfile.GFile(output_stem + '_bond_lengths.csv') as f:\n bond_length_lines = f.readlines()\n self.assertEqual('atom_char_0,atom_char_1,bond_type,length_str,count\\n',\n bond_length_lines[0])\n self.assertIn('c,c,2,1.336,1\\n', bond_length_lines)\n self.assertIn('c,o,1,1.422,2\\n', bond_length_lines)\n\n # For the gzip files below, we check >100 because even an empty gzip file\n # has non-zero length. 100 is kind of arbitrary to be bigger than the\n # expected header of 20.\n\n # Check that the generated TFRecord files contain some expected outputs\n standard_dataset = tf.data.TFRecordDataset(\n output_stem + '_standard_tfrecord-00000-of-00001')\n standard_output = [\n dataset_pb2.Conformer.FromString(raw)\n for raw in standard_dataset.as_numpy_iterator()\n ]\n self.assertCountEqual([c.conformer_id for c in standard_output],\n [618451001, 618451123])\n # Check that fields are filtered the way we expect\n self.assertFalse(\n standard_output[0].properties.HasField('compute_cluster_info'))\n self.assertFalse(\n standard_output[0].properties.HasField('homo_pbe0_aug_pc_1'))\n self.assertTrue(\n standard_output[0].properties.HasField('rotational_constants'))\n\n complete_dataset = tf.data.TFRecordDataset(\n output_stem + '_complete_tfrecord-00000-of-00001')\n complete_output = [\n dataset_pb2.Conformer.FromString(raw)\n for raw in complete_dataset.as_numpy_iterator()\n ]\n self.assertCountEqual([c.conformer_id for c in complete_output],\n [618451001, 618451123, 620517002, 79593005])\n # Check that fields are filtered the way we expect\n # The DirectRunner randomizes the order of output so we need to make sure\n # that we get a full record.\n complete_entry = [\n c for c in complete_output if c.conformer_id == 618451001\n ][0]\n self.assertFalse(complete_entry.properties.HasField('compute_cluster_info'))\n self.assertTrue(complete_entry.properties.HasField('homo_pbe0_aug_pc_1'))\n self.assertTrue(complete_entry.properties.HasField('rotational_constants'))\n\n complete_entry_for_smiles = [\n c for c in complete_output if c.conformer_id == 620517002\n ][0]\n self.assertEqual(complete_entry_for_smiles.properties.smiles_openbabel,\n 'NotAValidSmilesString')\n\n\n\nif __name__ == '__main__':\n absltest.main()\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Lint as: python3\n# pylint: disable=g-complex-comprehension\n# pylint: disable=missing-docstring\n\nimport tensorflow as tf\nfrom tensorflow.keras import layers\n\nfrom muzero import network\n\nLARGE_NUM = 1e9\n\n\nclass MLPandLSTM(network.AbstractEncoderandLSTM):\n \"\"\"Conv+LSTM network for use with MuZero.\"\"\"\n\n def __init__(self,\n trivial_encoding,\n observation_space,\n *args,\n encoder_size=3,\n pretrain_temperature=1.,\n **kwargs):\n super().__init__(*args, **kwargs)\n self.trivial_encoding = trivial_encoding\n self.pretrain_temperature = 1.\n\n if encoder_size == 0:\n encoding_layers = [\n layers.Conv2D(\n filters=32,\n kernel_size=8,\n strides=(4, 4),\n padding='valid',\n activation='relu',\n batch_input_shape=(None, *observation_space)),\n layers.Conv2D(\n filters=64,\n kernel_size=4,\n strides=(2, 2),\n padding='valid',\n activation=None,\n use_bias=False,\n ),\n tf.keras.layers.LayerNormalization(),\n tf.keras.layers.ReLU(),\n layers.Conv2D(\n filters=128,\n kernel_size=4,\n strides=(2, 2),\n padding='valid',\n activation='relu',\n ),\n layers.Conv2D(\n filters=256,\n kernel_size=3,\n strides=(1, 1),\n padding='valid',\n activation=None,\n use_bias=False,\n ),\n tf.keras.layers.LayerNormalization(),\n tf.keras.layers.ReLU(),\n ]\n else:\n encoding_layers = [\n layers.Conv2D(\n filters=64,\n kernel_size=3,\n strides=(2, 2),\n padding='same',\n activation='relu',\n batch_input_shape=(None, *observation_space)), # add activation?\n ]\n if encoder_size > 0:\n encoding_layers.append(ResidualBlock(64),)\n if encoder_size > 1:\n encoding_layers.append(ResidualBlock(64),)\n encoding_layers.append(\n layers.Conv2D(\n filters=128,\n kernel_size=3,\n strides=(2, 2),\n activation='relu',\n padding='same'), # add activation?\n )\n if encoder_size > 0:\n encoding_layers.append(ResidualBlock(128),)\n if encoder_size > 1:\n encoding_layers.append(ResidualBlock(128),)\n if encoder_size > 2:\n encoding_layers.append(ResidualBlock(128),)\n encoding_layers.append(\n layers.AveragePooling2D(\n pool_size=(3, 3), strides=(2, 2), padding='same'),)\n if encoder_size > 0:\n encoding_layers.append(ResidualBlock(128),)\n if encoder_size > 1:\n encoding_layers.append(ResidualBlock(128),)\n if encoder_size > 2:\n encoding_layers.append(ResidualBlock(128),)\n encoding_layers.append(\n layers.AveragePooling2D(\n pool_size=(3, 3), strides=(2, 2), padding='same'))\n\n self._observation_encoder = tf.keras.Sequential(\n encoding_layers, name='observation_encoder')\n\n pretrain_hidden_layers = self._head_hidden_layers()\n pretrain_output_size = self.head_hidden_sizes[\n -1] if self.head_hidden_sizes else self.hidden_state_size\n self._pretrain_head = tf.keras.Sequential(\n pretrain_hidden_layers + [\n layers.Dense(pretrain_output_size, name='pretrain_output'),\n ],\n name='pretrain_head')\n self._pretrain_predictor = tf.keras.Sequential([\n tf.keras.layers.Dense(pretrain_output_size // 4, use_bias=False),\n tf.keras.layers.LayerNormalization(),\n tf.keras.layers.ReLU(),\n tf.keras.layers.Dense(pretrain_output_size),\n ],\n name='pretrain_predictor')\n\n def _encode_observation(self, observation, training=True):\n observation = observation * 2 - 1.\n if self.trivial_encoding:\n # use the trivial observation encoding from\n # https://gist.github.com/karpathy/a4166c7fe253700972fcbc77e4ea32c5.\n # Simply take the difference between the last two observations.\n return observation[:, :, :, -1] - observation[:, :, :, -2]\n return self._observation_encoder(observation, training=training)\n\n # The loss is according to SimCLR(https://arxiv.org/abs/2002.05709).\n def pretraining_loss(self, sample, training=True):\n obs1, obs2 = sample\n out1 = self._pretrain_head(\n self.initial_inference(obs1, training=training).hidden_state)\n out2 = self._pretrain_head(\n self.initial_inference(obs2, training=training).hidden_state)\n pred1 = self._pretrain_predictor(out1)\n pred2 = self._pretrain_predictor(out2)\n loss = self.add_contrastive_loss(\n pred1, out2) / 2. + self.add_contrastive_loss(pred2, out1) / 2.\n\n return loss, None\n\n def add_contrastive_loss(self,\n hidden1,\n hidden2,\n hidden_norm=True,\n weights=1.0):\n # Get (normalized) hidden1 and hidden2.\n if hidden_norm:\n hidden1 = tf.math.l2_normalize(hidden1, -1)\n hidden2 = tf.math.l2_normalize(hidden2, -1)\n batch_size = tf.shape(hidden1)[0]\n\n labels = tf.one_hot(tf.range(batch_size), batch_size * 2)\n masks = tf.one_hot(tf.range(batch_size), batch_size)\n\n logits_aa = tf.matmul(\n hidden1, hidden1, transpose_b=True) / self.pretrain_temperature\n logits_aa = logits_aa - masks * LARGE_NUM\n logits_bb = tf.matmul(\n hidden2, hidden2, transpose_b=True) / self.pretrain_temperature\n logits_bb = logits_bb - masks * LARGE_NUM\n logits_ab = tf.matmul(\n hidden1, hidden2, transpose_b=True) / self.pretrain_temperature\n logits_ba = tf.matmul(\n hidden2, hidden1, transpose_b=True) / self.pretrain_temperature\n logits_a = tf.concat([logits_ab, logits_aa], 1)\n logits_b = tf.concat([logits_ba, logits_bb], 1)\n\n loss_a = tf.nn.softmax_cross_entropy_with_logits(\n labels=labels, logits=logits_a)\n loss_b = tf.nn.softmax_cross_entropy_with_logits(\n labels=labels, logits=logits_b)\n loss = loss_a + loss_b\n\n return loss\n\n def get_pretraining_trainable_variables(self):\n return (self._observation_encoder.trainable_variables +\n self._to_hidden.trainable_variables +\n self._pretrain_head.trainable_variables +\n self._pretrain_predictor.trainable_variables)\n\n\nclass ResidualBlock(layers.Layer):\n \"\"\"Residualblock.\n\n Implementation adapted from:\n https://towardsdatascience.com/from-scratch-implementation-of-alphazero-for-connect4-f73d4554002a\n .\n\n \"\"\"\n\n def __init__(self, planes):\n super(ResidualBlock, self).__init__(name='')\n self.planes = planes\n\n self.conv2a = layers.Conv2D(\n filters=self.planes,\n kernel_size=3,\n strides=(1, 1),\n padding='same',\n use_bias=False)\n self.bn2a = layers.LayerNormalization()\n\n self.conv2b = layers.Conv2D(\n filters=self.planes,\n kernel_size=3,\n strides=(1, 1),\n padding='same',\n use_bias=False)\n self.bn2b = layers.LayerNormalization()\n self.relu = layers.ReLU()\n\n def __call__(self, input_tensor, training=True, **kwargs):\n\n x = self.conv2a(input_tensor, training=training)\n x = self.bn2a(x, training=training)\n x = self.relu(x)\n\n x = self.conv2b(x, training=training)\n x = self.bn2b(x, training=training)\n\n x += input_tensor\n return self.relu(x)\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Forward-backward algorithm for integrating out discrete states.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport tensorflow as tf\nfrom snlds import utils\n\nnamedtuple = collections.namedtuple\n\n\ndef forward_pass(log_a, log_b, logprob_s0):\n \"\"\"Computing the forward pass of Baum-Welch Algorithm.\n\n By employing log-exp-sum trick, values are computed in log space, including\n the output. Notation is adopted from https://arxiv.org/abs/1910.09588.\n `log_a` is the likelihood of discrete states, `log p(s[t] | s[t-1], x[t-1])`,\n `log_b` is the likelihood of observations, `log p(x[t], z[t] | s[t])`,\n and `logprob_s0` is the likelihood of initial discrete states, `log p(s[0])`.\n Forward pass calculates the filtering likelihood of `log p(s_t | x_1:t)`.\n\n Args:\n log_a: a float `Tensor` of size [batch, num_steps, num_categ, num_categ]\n stores time dependent transition matrices, `log p(s[t] | s[t-1], x[t-1])`.\n `A[i, j]` is the transition probability from `s[t-1]=j` to `s[t]=i`.\n log_b: a float `Tensor` of size [batch, num_steps, num_categ] stores time\n dependent emission matrices, 'log p(x[t](, z[t])| s[t])`.\n logprob_s0: a float `Tensor` of size [num_categ], initial discrete states\n probability, `log p(s[0])`.\n\n Returns:\n forward_pass: a float 3D `Tensor` of size [batch, num_steps, num_categ]\n stores the forward pass probability of `log p(s_t | x_1:t)`, which is\n normalized.\n normalizer: a float 2D `Tensor` of size [batch, num_steps] stores the\n normalizing probability, `log p(x_t | x_1:t-1)`.\n \"\"\"\n num_steps = log_a.get_shape().with_rank_at_least(3).dims[1].value\n\n tas = [tf.TensorArray(tf.float32, num_steps, name=n)\n for n in [\"forward_prob\", \"normalizer\"]]\n\n # The function will return normalized forward probability and\n # normalizing constant as a list, [forward_logprob, normalizer].\n init_updates = utils.normalize_logprob(\n logprob_s0[tf.newaxis, :] + log_b[:, 0, :], axis=-1)\n\n tas = utils.write_updates_to_tas(tas, 0, init_updates)\n\n prev_prob = init_updates[0]\n init_state = (1,\n prev_prob,\n tas)\n\n def _cond(t, *unused_args):\n return t < num_steps\n\n def _steps(t, prev_prob, fwd_tas):\n \"\"\"One step forward in iterations.\"\"\"\n bi_t = log_b[:, t, :] # log p(x[t+1] | s[t+1])\n aij_t = log_a[:, t, :, :] # log p(s[t+1] | s[t], x[t])\n\n current_updates = tf.math.reduce_logsumexp(\n bi_t[:, :, tf.newaxis] + aij_t + prev_prob[:, tf.newaxis, :],\n axis=-1)\n current_updates = utils.normalize_logprob(current_updates, axis=-1)\n\n prev_prob = current_updates[0]\n fwd_tas = utils.write_updates_to_tas(fwd_tas, t, current_updates)\n\n return (t+1, prev_prob, fwd_tas)\n\n _, _, tas_final = tf.while_loop(\n _cond,\n _steps,\n init_state\n )\n\n # transpose to [batch, step, state]\n forward_prob = tf.transpose(tas_final[0].stack(), [1, 0, 2])\n normalizer = tf.transpose(tf.squeeze(tas_final[1].stack(), axis=[-1]), [1, 0])\n return forward_prob, normalizer\n\n\ndef backward_pass(log_a, log_b, logprob_s0):\n \"\"\"Computing the backward pass of Baum-Welch Algorithm.\n\n Args:\n log_a: a float `Tensor` of size [batch, num_steps, num_categ, num_categ]\n stores time dependent transition matrices, `log p(s[t] | s[t-1], x[t-1])`.\n `A[:, t, i, j]` is the transition probability from `s[t-1]=j` to `s[t]=i`.\n Since `A[:, t, :, :]` is using the information from `t-1`, `A[:, 0, :, :]`\n is meaningless, i.e. set to zeros.\n log_b: a float `Tensor` of size [batch, num_steps, num_categ] stores time\n dependent emission matrices, `log p(x[t](, z[t])| s[t])`\n logprob_s0: a float `Tensor` of size [num_categ], initial discrete states\n probability, `log p(s[0])`.\n\n Returns:\n backward_pass: a float `Tensor` of size [batch_size, num_steps, num_categ]\n stores the backward-pass probability log p(s_t | x_t+1:T(, z_t+1:T)).\n normalizer: a float `Tensor` of size [batch, num_steps, num_categ] stores\n the normalizing probability, log p(x_t | x_t:T).\n \"\"\"\n batch_size = tf.shape(log_b)[0]\n num_steps = tf.shape(log_b)[1]\n num_categ = logprob_s0.shape[0]\n\n tas = [tf.TensorArray(tf.float32, num_steps, name=n)\n for n in [\"backward_prob\", \"normalizer\"]]\n\n init_updates = [tf.zeros([batch_size, num_categ]), tf.zeros([batch_size, 1])]\n\n tas = utils.write_updates_to_tas(tas, num_steps-1, init_updates)\n\n next_prob = init_updates[0]\n init_state = (num_steps-2,\n next_prob,\n tas)\n\n def _cond(t, *unused_args):\n return t > -1\n\n def _steps(t, next_prob, bwd_tas):\n \"\"\"One step backward.\"\"\"\n bi_tp1 = log_b[:, t+1, :] # log p(x[t+1] | s[t+1])\n aij_tp1 = log_a[:, t+1, :, :] # log p(s[t+1] | s[t], x[t])\n current_updates = tf.math.reduce_logsumexp(\n next_prob[:, :, tf.newaxis] + aij_tp1 + bi_tp1[:, :, tf.newaxis],\n axis=-2)\n\n current_updates = utils.normalize_logprob(current_updates, axis=-1)\n\n next_prob = current_updates[0]\n bwd_tas = utils.write_updates_to_tas(bwd_tas, t, current_updates)\n\n return (t-1, next_prob, bwd_tas)\n\n _, _, tas_final = tf.while_loop(\n _cond,\n _steps,\n init_state\n )\n\n backward_prob = tf.transpose(tas_final[0].stack(), [1, 0, 2])\n normalizer = tf.transpose(tf.squeeze(tas_final[1].stack(), axis=[-1]), [1, 0])\n\n return backward_prob, normalizer\n\n\ndef forward_backward(log_a, log_b, log_init):\n \"\"\"Forward backward algorithm.\"\"\"\n fwd, _ = forward_pass(log_a, log_b, log_init)\n bwd, _ = backward_pass(log_a, log_b, log_init)\n\n m_fwd = fwd[:, 0:-1, tf.newaxis, :]\n m_bwd = bwd[:, 1:, :, tf.newaxis]\n m_a = log_a[:, 1:, :, :]\n m_b = log_b[:, 1:, :, tf.newaxis]\n\n # posterior score\n posterior = fwd + bwd\n gamma_ij = m_fwd + m_a + m_bwd + m_b\n\n # normalize the probability matrices\n posterior, _ = utils.normalize_logprob(posterior, axis=-1)\n gamma_ij, _ = utils.normalize_logprob(gamma_ij, axis=[-2, -1])\n\n # padding the matrix to the same shape of inputs\n gamma_ij = tf.concat([tf.zeros([tf.shape(log_a)[0], 1,\n tf.shape(log_a)[2], tf.shape(log_a)[3]]),\n gamma_ij], axis=1, name=\"concat_f_b\")\n\n return fwd, bwd, posterior, gamma_ij\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Environments used in the DARC experiments.\"\"\"\nimport tempfile\nimport gin\nimport gym\nfrom gym import utils\nfrom gym.envs.mujoco import ant\nfrom gym.envs.mujoco import half_cheetah\nfrom gym.envs.mujoco import hopper\nfrom gym.envs.mujoco import humanoid\nfrom gym.envs.mujoco import mujoco_env\nfrom gym.envs.mujoco import walker2d\nimport gym.spaces\nimport numpy as np\nimport reacher_7dof\nfrom tf_agents.environments import suite_gym\nfrom tf_agents.environments import tf_py_environment\n\n\nXML = \"\"\"\n<mujoco model=\"cheetah\">\n <compiler angle=\"radian\" coordinate=\"local\" inertiafromgeom=\"true\" settotalmass=\"14\"/>\n <default>\n <joint armature=\".1\" damping=\".01\" limited=\"true\" solimplimit=\"0 .8 .03\" solreflimit=\".02 1\" stiffness=\"8\"/>\n <geom conaffinity=\"0\" condim=\"3\" contype=\"1\" friction=\".4 .1 .1\" rgba=\"0.8 0.6 .4 1\" solimp=\"0.0 0.8 0.01\" solref=\"0.02 1\"/>\n <motor ctrllimited=\"true\" ctrlrange=\"-1 1\"/>\n </default>\n <size nstack=\"300000\" nuser_geom=\"1\"/>\n <option gravity=\"0 0 -9.81\" timestep=\"0.01\"/>\n <asset>\n <texture builtin=\"gradient\" height=\"100\" rgb1=\"1 1 1\" rgb2=\"0 0 0\" type=\"skybox\" width=\"100\"/>\n <texture builtin=\"flat\" height=\"1278\" mark=\"cross\" markrgb=\"1 1 1\" name=\"texgeom\" random=\"0.01\" rgb1=\"0.8 0.6 0.4\" rgb2=\"0.8 0.6 0.4\" type=\"cube\" width=\"127\"/>\n <texture builtin=\"checker\" height=\"100\" name=\"texplane\" rgb1=\"0 0 0\" rgb2=\"0.8 0.8 0.8\" type=\"2d\" width=\"100\"/>\n <material name=\"MatPlane\" reflectance=\"0.5\" shininess=\"1\" specular=\"1\" texrepeat=\"60 60\" texture=\"texplane\"/>\n <material name=\"geom\" texture=\"texgeom\" texuniform=\"true\"/>\n </asset>\n <worldbody>\n <light cutoff=\"100\" diffuse=\"1 1 1\" dir=\"-0 0 -1.3\" directional=\"true\" exponent=\"1\" pos=\"0 0 1.3\" specular=\".1 .1 .1\"/>\n <geom conaffinity=\"1\" condim=\"3\" material=\"MatPlane\" name=\"floor\" pos=\"0 0 0\" rgba=\"0.8 0.9 0.8 1\" size=\"40 40 40\" type=\"plane\"/>\n <body name=\"torso\" pos=\"0 0 .7\">\n <camera name=\"track\" mode=\"trackcom\" pos=\"0 -3 0.3\" xyaxes=\"1 0 0 0 0 1\"/>\n <joint armature=\"0\" axis=\"1 0 0\" damping=\"0\" limited=\"false\" name=\"rootx\" pos=\"0 0 0\" stiffness=\"0\" type=\"slide\"/>\n <joint armature=\"0\" axis=\"0 0 1\" damping=\"0\" limited=\"false\" name=\"rootz\" pos=\"0 0 0\" stiffness=\"0\" type=\"slide\"/>\n <joint armature=\"0\" axis=\"0 1 0\" damping=\"0\" limited=\"false\" name=\"rooty\" pos=\"0 0 0\" stiffness=\"0\" type=\"hinge\"/>\n <geom fromto=\"-.5 0 0 .5 0 0\" name=\"torso\" size=\"0.046\" type=\"capsule\"/>\n <geom axisangle=\"0 1 0 .87\" name=\"head\" pos=\".6 0 .1\" size=\"0.046 .15\" type=\"capsule\"/>\n <!-- <site name='tip' pos='.15 0 .11'/>-->\n <body name=\"bthigh\" pos=\"-.5 0 0\">\n <joint axis=\"0 1 0\" damping=\"6\" name=\"bthigh\" pos=\"0 0 0\" range=\"-.52 1.05\" stiffness=\"240\" type=\"hinge\"/>\n <geom axisangle=\"0 1 0 -3.8\" name=\"bthigh\" pos=\".1 0 -.13\" size=\"0.046 .145\" type=\"capsule\"/>\n <body name=\"bshin\" pos=\".16 0 -.25\">\n <joint axis=\"0 1 0\" damping=\"4.5\" name=\"bshin\" pos=\"0 0 0\" range=\"-.785 .785\" stiffness=\"180\" type=\"hinge\"/>\n <geom axisangle=\"0 1 0 -2.03\" name=\"bshin\" pos=\"-.14 0 -.07\" rgba=\"0.9 0.6 0.6 1\" size=\"0.046 .15\" type=\"capsule\"/>\n <body name=\"bfoot\" pos=\"-.28 0 -.14\">\n <joint axis=\"0 1 0\" damping=\"3\" name=\"bfoot\" pos=\"0 0 0\" range=\"-.4 .785\" stiffness=\"120\" type=\"hinge\"/>\n <geom axisangle=\"0 1 0 -.27\" name=\"bfoot\" pos=\".03 0 -.097\" rgba=\"0.9 0.6 0.6 1\" size=\"0.046 .094\" type=\"capsule\"/>\n </body>\n </body>\n </body>\n <body name=\"fthigh\" pos=\".5 0 0\">\n <joint axis=\"0 1 0\" damping=\"4.5\" name=\"fthigh\" pos=\"0 0 0\" range=\"-1 .7\" stiffness=\"180\" type=\"hinge\"/>\n <geom axisangle=\"0 1 0 .52\" name=\"fthigh\" pos=\"-.07 0 -.12\" size=\"0.046 .133\" type=\"capsule\"/>\n <body name=\"fshin\" pos=\"-.14 0 -.24\">\n <joint axis=\"0 1 0\" damping=\"3\" name=\"fshin\" pos=\"0 0 0\" range=\"-1.2 .87\" stiffness=\"120\" type=\"hinge\"/>\n <geom axisangle=\"0 1 0 -.6\" name=\"fshin\" pos=\".065 0 -.09\" rgba=\"0.9 0.6 0.6 1\" size=\"0.046 .106\" type=\"capsule\"/>\n <body name=\"ffoot\" pos=\".13 0 -.18\">\n <joint axis=\"0 1 0\" damping=\"1.5\" name=\"ffoot\" pos=\"0 0 0\" range=\"-.5 .5\" stiffness=\"60\" type=\"hinge\"/>\n <geom axisangle=\"0 1 0 -.6\" name=\"ffoot\" pos=\".045 0 -.07\" rgba=\"0.9 0.6 0.6 1\" size=\"0.046 .07\" type=\"capsule\"/>\n </body>\n </body>\n </body>\n </body>\n\n <geom name=\"obstacle\" type=\"box\" pos=\"-3 0 %f\" size=\"1 10 10\" rgba=\"0.2 0.5 0.2 1\" conaffinity=\"1\"/>\n\n </worldbody>\n <actuator>\n <motor gear=\"120\" joint=\"bthigh\" name=\"bthigh\"/>\n <motor gear=\"90\" joint=\"bshin\" name=\"bshin\"/>\n <motor gear=\"60\" joint=\"bfoot\" name=\"bfoot\"/>\n <motor gear=\"120\" joint=\"fthigh\" name=\"fthigh\"/>\n <motor gear=\"60\" joint=\"fshin\" name=\"fshin\"/>\n <motor gear=\"30\" joint=\"ffoot\" name=\"ffoot\"/>\n </actuator>\n</mujoco>\n\"\"\"\n\n\nclass HalfCheetahDirectionEnv(half_cheetah.HalfCheetahEnv):\n \"\"\"Variant of half-cheetah that includes an obstacle.\"\"\"\n\n def __init__(self, use_obstacle):\n self._tempfile = tempfile.NamedTemporaryFile(mode=\"w\", suffix=\".xml\")\n if use_obstacle:\n obstacle_height = 1.0\n else:\n obstacle_height = -50\n self._tempfile.write(XML % (obstacle_height))\n self._tempfile.flush()\n mujoco_env.MujocoEnv.__init__(self, self._tempfile.name, 5)\n utils.EzPickle.__init__(self)\n self.observation_space = gym.spaces.Box(\n low=self.observation_space.low,\n high=self.observation_space.high,\n dtype=np.float32,\n )\n\n def step(self, action):\n xposbefore = self.sim.data.qpos[0]\n self.do_simulation(action, self.frame_skip)\n xposafter = self.sim.data.qpos[0]\n ob = self._get_obs()\n reward_ctrl = -0.1 * np.square(action).sum()\n reward_run = abs(xposafter - xposbefore) / self.dt\n reward = reward_ctrl + reward_run\n done = False\n return ob, reward, done, dict(\n reward_run=reward_run, reward_ctrl=reward_ctrl)\n\n def camera_setup(self):\n super(HalfCheetahDirectionEnv, self).camera_setup()\n self.camera._render_camera.distance = 5.0 # pylint: disable=protected-access\n\n\ndef get_half_cheetah_direction_env(mode):\n if mode == \"sim\":\n env = HalfCheetahDirectionEnv(use_obstacle=False)\n else:\n assert mode == \"real\"\n env = HalfCheetahDirectionEnv(use_obstacle=True)\n env = suite_gym.wrap_env(env, max_episode_steps=1000)\n return tf_py_environment.TFPyEnvironment(env)\n\n\nclass BrokenReacherEnv(reacher_7dof.Reacher7DofEnv):\n \"\"\"Variant of the 7DOF reaching environment with a broken joint.\n\n I implemented the BrokenReacherEnv before implementing the more general\n BrokenJoint wrapper. While in theory they should do the same thing, I haven't\n confirmed this yet, so I'm keeping BrokenReacherEnv separate for now.\n \"\"\"\n\n def __init__(self, broken_joint=2, state_includes_action=True):\n self._broken_joint = broken_joint\n self._state_includes_action = state_includes_action\n super(BrokenReacherEnv, self).__init__()\n if state_includes_action:\n obs_dim = len(self.observation_space.low)\n action_dim = len(self.action_space.low)\n self._observation_space = gym.spaces.Box(\n low=np.full(obs_dim + action_dim, -np.inf, dtype=np.float32),\n high=np.full(obs_dim + action_dim, np.inf, dtype=np.float32),\n )\n\n def reset(self):\n s = super(BrokenReacherEnv, self).reset()\n a = np.zeros(len(self.action_space.low))\n if self._state_includes_action:\n s = np.concatenate([s, a])\n return s\n\n def step(self, action):\n action = action.copy()\n if self._broken_joint is not None:\n action[self._broken_joint] = 0.0\n ns, r, done, info = super(BrokenReacherEnv, self).step(action)\n if self._state_includes_action:\n ns = np.concatenate([ns, action])\n return ns, r, done, info\n\n\nclass BrokenJoint(gym.Wrapper):\n \"\"\"Wrapper that disables one coordinate of the action, setting it to 0.\"\"\"\n\n def __init__(self, env, broken_joint):\n super(BrokenJoint, self).__init__(env)\n # Change dtype of observation to be float32\n self.observation_space = gym.spaces.Box(\n low=self.observation_space.low,\n high=self.observation_space.high,\n dtype=np.float32,\n )\n if broken_joint is not None:\n assert 0 <= broken_joint <= len(self.action_space.low) - 1\n self.broken_joint = broken_joint\n\n def step(self, action):\n action = action.copy()\n if self.broken_joint is not None:\n action[self.broken_joint] = 0\n return super(BrokenJoint, self).step(action)\n\n\n@gin.configurable\ndef get_broken_joint_env(mode, env_name, broken_joint=0):\n \"\"\"Creates an environment with a broken joint.\"\"\"\n if env_name == \"ant\":\n env = ant.AntEnv()\n elif env_name == \"half_cheetah\":\n env = half_cheetah.HalfCheetahEnv()\n elif env_name == \"reacher_7dof\":\n env = reacher_7dof.Reacher7DofEnv()\n else:\n raise NotImplementedError\n if mode == \"sim\":\n env = BrokenJoint(env, broken_joint=None)\n else:\n assert mode == \"real\"\n env = BrokenJoint(env, broken_joint=broken_joint)\n env = suite_gym.wrap_env(env, max_episode_steps=1000)\n return tf_py_environment.TFPyEnvironment(env)\n\n\nclass FallingEnv(gym.Wrapper):\n \"\"\"Wrapper that disables the termination condition.\"\"\"\n\n def __init__(self, env, ignore_termination=False):\n self._ignore_termination = ignore_termination\n super(FallingEnv, self).__init__(env)\n\n def step(self, a):\n ns, r, done, info = super(FallingEnv, self).step(a)\n r = 0.0\n if self._ignore_termination:\n done = False\n return ns, r, done, info\n\n\ndef get_falling_env(mode, env_name):\n \"\"\"Creates an environment with the termination condition disabled.\"\"\"\n if env_name == \"hopper\":\n env = hopper.HopperEnv()\n elif env_name == \"humanoid\":\n env = humanoid.HumanoidEnv()\n elif env_name == \"walker\":\n env = walker2d.Walker2dEnv()\n else:\n raise NotImplementedError\n if mode == \"sim\":\n env = FallingEnv(env, ignore_termination=True)\n else:\n assert mode == \"real\"\n env = FallingEnv(env, ignore_termination=False)\n\n env = suite_gym.wrap_env(env, max_episode_steps=300)\n return tf_py_environment.TFPyEnvironment(env)\n\n\n@gin.configurable\ndef get_broken_reacher_env(mode, broken_joint=0):\n if mode == \"sim\":\n env = BrokenReacherEnv(broken_joint=None)\n else:\n assert mode == \"real\"\n env = BrokenReacherEnv(broken_joint=broken_joint)\n env = suite_gym.wrap_env(env, max_episode_steps=100)\n return tf_py_environment.TFPyEnvironment(env)\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Generates training TFRecords from 2D keypoint CSV and 3D keypoint H5 files.\n\nThe CSV file is expected to have:\n\n1. The first row as header as follows:\n\nimage/object/subject,image/subaction,image/object/camera,image/frame_index,image/width,image/height,image/object/part/NOSE_TIP/center/x,image/object/part/NOSE_TIP/center/y,image/object/part/NOSE_TIP/score,image/object/part/LEFT_SHOULDER/center/x,image/object/part/LEFT_SHOULDER/center/y,image/object/part/LEFT_SHOULDER/score,image/object/part/RIGHT_SHOULDER/center/x,image/object/part/RIGHT_SHOULDER/center/y,image/object/part/RIGHT_SHOULDER/score,image/object/part/LEFT_ELBOW/center/x,image/object/part/LEFT_ELBOW/center/y,image/object/part/LEFT_ELBOW/score,image/object/part/RIGHT_ELBOW/center/x,image/object/part/RIGHT_ELBOW/center/y,image/object/part/RIGHT_ELBOW/score,image/object/part/LEFT_WRIST/center/x,image/object/part/LEFT_WRIST/center/y,image/object/part/LEFT_WRIST/score,image/object/part/RIGHT_WRIST/center/x,image/object/part/RIGHT_WRIST/center/y,image/object/part/RIGHT_WRIST/score,image/object/part/LEFT_HIP/center/x,image/object/part/LEFT_HIP/center/y,image/object/part/LEFT_HIP/score,image/object/part/RIGHT_HIP/center/x,image/object/part/RIGHT_HIP/center/y,image/object/part/RIGHT_HIP/score,image/object/part/LEFT_KNEE/center/x,image/object/part/LEFT_KNEE/center/y,image/object/part/LEFT_KNEE/score,image/object/part/RIGHT_KNEE/center/x,image/object/part/RIGHT_KNEE/center/y,image/object/part/RIGHT_KNEE/score,image/object/part/LEFT_ANKLE/center/x,image/object/part/LEFT_ANKLE/center/y,image/object/part/LEFT_ANKLE/score,image/object/part/RIGHT_ANKLE/center/x,image/object/part/RIGHT_ANKLE/center/y,image/object/part/RIGHT_ANKLE/score,image/object/subject,image/subaction,image/object/camera,image/frame_index,image/width,image/height,image/object/part/NOSE_TIP/center/x,image/object/part/NOSE_TIP/center/y,image/object/part/NOSE_TIP/score,image/object/part/LEFT_SHOULDER/center/x,image/object/part/LEFT_SHOULDER/center/y,image/object/part/LEFT_SHOULDER/score,image/object/part/RIGHT_SHOULDER/center/x,image/object/part/RIGHT_SHOULDER/center/y,image/object/part/RIGHT_SHOULDER/score,image/object/part/LEFT_ELBOW/center/x,image/object/part/LEFT_ELBOW/center/y,image/object/part/LEFT_ELBOW/score,image/object/part/RIGHT_ELBOW/center/x,image/object/part/RIGHT_ELBOW/center/y,image/object/part/RIGHT_ELBOW/score,image/object/part/LEFT_WRIST/center/x,image/object/part/LEFT_WRIST/center/y,image/object/part/LEFT_WRIST/score,image/object/part/RIGHT_WRIST/center/x,image/object/part/RIGHT_WRIST/center/y,image/object/part/RIGHT_WRIST/score,image/object/part/LEFT_HIP/center/x,image/object/part/LEFT_HIP/center/y,image/object/part/LEFT_HIP/score,image/object/part/RIGHT_HIP/center/x,image/object/part/RIGHT_HIP/center/y,image/object/part/RIGHT_HIP/score,image/object/part/LEFT_KNEE/center/x,image/object/part/LEFT_KNEE/center/y,image/object/part/LEFT_KNEE/score,image/object/part/RIGHT_KNEE/center/x,image/object/part/RIGHT_KNEE/center/y,image/object/part/RIGHT_KNEE/score,image/object/part/LEFT_ANKLE/center/x,image/object/part/LEFT_ANKLE/center/y,image/object/part/LEFT_ANKLE/score,image/object/part/RIGHT_ANKLE/center/x,image/object/part/RIGHT_ANKLE/center/y,image/object/part/RIGHT_ANKLE/score\n\n2. The following rows are CSV values according to the header, a pair of samples\n per row for the same 3D pose from two different camera views.\n\nBelow is a dummy sample CSV row:\n\nS1,Eating,60457274,001346,1000,1002,0.1234,0.4321,1.0,0.1234,0.4321,1.0,0.1234,0.4321,1.0,0.1234,0.4321,1.0,0.1234,0.4321,1.0,0.1234,0.4321,1.0,0.1234,0.4321,1.0,0.1234,0.4321,1.0,0.1234,0.4321,1.0,0.1234,0.4321,1.0,0.1234,0.4321,1.0,0.1234,0.4321,1.0,0.1234,0.4321,1.0,S1,Eating,58860488,001346,1000,1000,0.2468,0.2155,1.0,0.2468,0.2155,1.0,0.2468,0.2155,1.0,0.2468,0.2155,1.0,0.2468,0.2155,1.0,0.2468,0.2155,1.0,0.2468,0.2155,1.0,0.2468,0.2155,1.0,0.2468,0.2155,1.0,0.2468,0.2155,1.0,0.2468,0.2155,1.0,0.2468,0.2155,1.0,0.2468,0.2155,1.0\n\nNotes:\na. The \"image/frame_index\" values are expected to start at 0.\nb. The 2D keypoint coordinate values are required to be normalized by image\n sizes to within [0, 1].\nc. The 3D keypoint coordinate values are assumed to be unnormalized.\nd. In practice, we include all possible pairs in our training tables. For\n example, for one pose in the Human3.6M dataset (which has 4 views C{0..3}),\n we include all 12 pairs in the CSV, i.e., (C0, C1), (C0, C2), (C0, C3), (C1,\n C0), (C1, C2), (C1, C3), (C2, C0), (C2, C1), (C2, C3), (C3, C0), (C3, C1),\n and (C3, C2).\n\nThe H5 files contain 3D poses from Human3.6M and CSV files contain 2D poses.\nProduces TFRecords file for input into training pipelines. The instructions\nfor downloading the H5 files are located in the Github page:\nhttps://github.com/una-dinosauria/3d-pose-baseline.\n\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\n\nimport h5py\nimport numpy as np\nimport tensorflow.compat.v1 as tf\n\nfrom poem.core import keypoint_profiles\n\nflags = tf.app.flags\nFLAGS = flags.FLAGS\n\n# The relevant Human3.6M 3D keypoints and their indices from the H5 file are\n# (with their mapped names in the `3DSTD16` keypoint profile in the\n# parentheses):\n# [0] Hip (PELVIS)\n# [15] Head (HEAD)\n# [14] Neck/Nose (-)\n# [13] Thorax (NECK)\n# [17] LShoulder (LEFT_SHOULDER)\n# [25] RShoulder (RIGHT_SHOULDER)\n# [18] LElbow (LEFT_ELBOW)\n# [26] RElbow (RIGHT_ELBOW)\n# [19] LWrist (LEFT_WRIST)\n# [27] RWrist (RIGHT_WRIST)\n# [12] Spine (SPINE)\n# [6] LHip (LEFT_HIP)\n# [1] RHip (RIGHT_HIP)\n# [7] LKnee (LEFT_KNEE)\n# [2] RKnee (RIGHT_KNEE)\n# [8] LFoot (LEFT_ANKLE)\n# [3] RFoot (RIGHT_ANKLE)\n\n# Indices of Human3.6M keypoints to be read from the H5 file. The\n# keypoint ordering follows the H5 file and the `LEGACY_3DH36M17` keypoint\n# profile.\nKEYPOINT_INDICES_LEGACY_3DH36M17 = [\n 0, 15, 14, 13, 17, 25, 18, 26, 19, 27, 12, 6, 1, 7, 2, 8, 3\n]\n\n# Indices of Human3.6M keypoints to be read from the H5 file. The\n# keypoint ordering follows the H5 file and the `3DSTD16` keypoint profile.\nKEYPOINT_INDICES_3DSTD16 = [\n 15, 13, 17, 25, 18, 26, 19, 27, 12, 0, 6, 1, 7, 2, 8, 3\n]\n\nflags.DEFINE_enum('input_data_type', 'H36M_H5', ['H36M_H5'],\n 'Input type of Human3.6M dataset.')\n\nflags.DEFINE_enum('keypoint_profile_name_3d', 'LEGACY_3DH36M17',\n ['LEGACY_3DH36M17', '3DSTD16'],\n 'Name of the 3D keypoint profile to use.')\n\nflags.DEFINE_string(\n 'input_root_dir', '', 'Input root directory that contains the Human3.6M 3D '\n 'keypoint files.')\n\nflags.DEFINE_string('input_csv_file', '',\n 'Input CSV file containing 2D keypoints to parse.')\n\nflags.DEFINE_bool(\n 'input_paired_entries', True,\n 'Whether each row in the CSV file stores entry pairs. Use False to disable'\n 'reading rows as pairs.')\n\nflags.DEFINE_string(\n 'subjects_to_read', '', 'A string for either \"train\", \"val\", \"all\", or a'\n 'comma separated list of subjects in Human3.6M for which we want to read'\n 'the 3D keypoints. For example: S1,S5,S7.')\n\nflags.DEFINE_string('output_tfrecords', '',\n 'Output TFRecords from parsing the 2d and 3d keypoints.')\n\nflags.DEFINE_integer(\n 'output_num_shards', 100,\n 'Output number of shards for the TFRecords. Use < 1 to disable sharding.')\n\n\ndef load_h36m_3d_keypoints_h5_files(input_root_dir, subjects):\n \"\"\"Loads a dictionary of 3D keypoints given input directory to H5 files.\n\n Args:\n input_root_dir: A string for the root directory path containing H5 files\n with 3D poses keypoints from Human3.6M dataset.\n subjects: A list of strings for subjects to read from the directory.\n\n Returns:\n keypoint_dict: A dictionary for loaded 3D keypoints. Keys are (subject,\n action) and values are of shape [sequence_length, num_keypoints, 3].\n \"\"\"\n\n keypoint_dict = {}\n for subject in subjects:\n h5_path = os.path.join(input_root_dir, subject, 'MyPoses/3D_positions/*.h5')\n for fname in tf.io.gfile.glob(h5_path):\n # The H5 file is located in path with subject and action:\n # h36m/subject/MyPoses/3D_positions/action.h5.\n action = fname.split('/')[-1][:-3]\n with h5py.File(fname, 'r') as hf:\n keypoint_dict[(subject, action)] = (\n hf['3D_positions'].value.reshape(32, 3, -1).transpose(2, 0, 1))\n return keypoint_dict\n\n\ndef extend_example_with_2d_3d_keypoints(example, input_list, headers):\n \"\"\"Extends an existing tf.example with 2D and 3D keypoint information.\n\n Args:\n example: A tf.example to add keypoint information.\n input_list: A list of values with 2D keypoints, 3D keypoints and metadata\n (subject name, action, name, camera, timestamp and image size).\n headers: A list of string headers with 2D keypoint names, 3D keypoint names,\n and metadata to write to the tf.example.\n\n Returns:\n example: A tf.example with appended information from input_list.\n \"\"\"\n # Write subject name.\n example.features.feature[headers[0]].bytes_list.value.extend(\n [input_list[0].encode()])\n # Write action name.\n example.features.feature[headers[1]].bytes_list.value.extend(\n [input_list[1].encode()])\n # Write camera name.\n example.features.feature[headers[2]].int64_list.value.extend(\n [int(input_list[2])])\n # Write timestamp.\n example.features.feature[headers[3]].int64_list.value.extend(\n [int(input_list[3])])\n # Write image width and height.\n example.features.feature[headers[4]].int64_list.value.extend(\n [int(input_list[4])])\n example.features.feature[headers[5]].int64_list.value.extend(\n [int(input_list[5])])\n\n # Write the 2D and 3D keypoints as floats.\n for i in range(6, len(headers)):\n example.features.feature[headers[i]].float_list.value.extend(\n [float(input_list[i])])\n return example\n\n\ndef create_serialized_example_with_2d_3d_keypoints(input_list, headers,\n write_pairs):\n \"\"\"Creates serialized example with 2D and 3D keypoints to write to TFRecord.\n\n Args:\n input_list: A list of values with 2D keypoints, 3D keypoints and metadata\n (subject name, action, name, camera, timestamp and image size).\n headers: A list of string headers with 2D keypoint names, 3D keypoint names,\n and metadata to write to the tf.example.\n write_pairs: A boolean for whether we want to write paired entries to output\n TFRecord. If False, we write a single entry.\n\n Returns:\n serialized_example: A string for serialized tf.example to write to TFRecord.\n \"\"\"\n example = tf.train.Example()\n\n example = extend_example_with_2d_3d_keypoints(example,\n input_list[:len(headers)],\n headers)\n\n if write_pairs:\n example = extend_example_with_2d_3d_keypoints(example,\n input_list[len(headers):],\n headers)\n\n return example.SerializeToString()\n\n\ndef load_2d_keypoints_and_write_tfrecord_with_3d_keypoints(\n input_csv_file, keypoint_dict, output_tfrecord_file, read_csv_pairs,\n num_shards):\n \"\"\"Loads 2D keypoints from a CSV file and write TFRecord with 3D poses.\n\n The TFRecord written contains the 2D keypoints with corresponding 3D keypoints\n stored in keypoint_dict.\n\n Args:\n input_csv_file: A string of the CSV file name containing 2D keypoints to\n load with subjects, actions and timestamps to be matched to 3D keypoints\n from keypoint_dict.\n keypoint_dict: A dictionary for loaded 3D keypoints. Keys are (subject,\n action) and values are of shape [sequence_length, num_keypoints, 3].\n output_tfrecord_file: A string of output filename for the TFRecord\n containing 2D and 3D keypoints.\n read_csv_pairs: A boolean that is True when each row of the CSV file stores\n paired entried and is False when the row contains a single entry.\n num_shards: An integer for the number of shards in the output TFRecord file.\n \"\"\"\n\n # Read the first row of the file as the header.\n read_header = True\n\n if FLAGS.keypoint_profile_name_3d == 'LEGACY_3DH36M17':\n keypoint_indices_3d = KEYPOINT_INDICES_LEGACY_3DH36M17\n elif FLAGS.keypoint_profile_name_3d == '3DSTD16':\n keypoint_indices_3d = KEYPOINT_INDICES_3DSTD16\n else:\n raise ValueError('Unsupported 3D keypoint profile: %s.' %\n str(FLAGS.keypoint_profile_name_3d))\n\n keypoint_profile_3d = keypoint_profiles.create_keypoint_profile_or_die(\n FLAGS.keypoint_profile_name_3d)\n\n tfrecord_writers = []\n if num_shards > 1:\n for i in range(num_shards):\n output_tfrecord_file_sharded = (\n output_tfrecord_file + '-{:05d}-of-{:05d}'.format(i, num_shards))\n writer = tf.python_io.TFRecordWriter(output_tfrecord_file_sharded)\n tfrecord_writers.append(writer)\n else:\n writer = tf.python_io.TFRecordWriter(output_tfrecord_file)\n tfrecord_writers.append(writer)\n\n with tf.io.gfile.GFile(input_csv_file, 'r') as csv_rows:\n for shard_counter, row in enumerate(csv_rows):\n writer = tfrecord_writers[shard_counter % num_shards]\n row = row.split(',')\n\n feature_size = len(row)\n if read_csv_pairs:\n feature_size = len(row) // 2\n if len(row) != feature_size * 2 or len(row) % 2 != 0:\n raise ValueError('CSV row has length {} but it should have an even'\n 'number of elements.'.format(len(row)))\n if read_header:\n read_header = False\n # Keep the first half of the row as header if the csv file contains\n # pairs. Otherwise, keep the full row.\n headers = row[:feature_size]\n # Add 3D pose headers using the keypoint names to the header list.\n prefix = 'image/object/part_3d/'\n suffix = '/center/'\n for name in keypoint_profile_3d.keypoint_names:\n headers.append(prefix + name + suffix + 'x')\n headers.append(prefix + name + suffix + 'y')\n headers.append(prefix + name + suffix + 'z')\n continue\n\n anchor_subject = row[0]\n anchor_action = row[1]\n anchor_frame_index = int(row[3])\n # Replace names to be consistent with H5 file names.\n anchor_action = anchor_action.replace('TakingPhoto', 'Photo').replace(\n 'WalkingDog', 'WalkDog')\n\n # Obtain matching 3D keypoints from keypoint_dict.\n anchor_keypoint_3d = keypoint_dict[(\n anchor_subject, anchor_action)][anchor_frame_index,\n keypoint_indices_3d, :].reshape([-1])\n\n # If we need to read csv pairs, the second element in the pair in the row\n # is the positive match.\n if read_csv_pairs:\n positive_subject = row[feature_size]\n positive_action = row[feature_size + 1]\n positive_frame_index = int(row[feature_size + 3])\n positive_action = positive_action.replace('TakingPhoto',\n 'Photo').replace(\n 'WalkingDog', 'WalkDog')\n positive_keypoint_3d = keypoint_dict[(\n positive_subject,\n positive_action)][positive_frame_index,\n keypoint_indices_3d, :].reshape([-1])\n\n # Concatenate 3D keypoints into current row with 2D keypoints.\n row_with_3d_keypoints = np.concatenate(\n (row[:feature_size], anchor_keypoint_3d, row[feature_size:],\n positive_keypoint_3d))\n else:\n row_with_3d_keypoints = np.concatenate((row, anchor_keypoint_3d))\n\n serialized_example = create_serialized_example_with_2d_3d_keypoints(\n row_with_3d_keypoints, headers, write_pairs=read_csv_pairs)\n writer.write(serialized_example)\n\n\ndef main(_):\n\n if FLAGS.subjects_to_read.lower() == 'all':\n subjects = ['S1', 'S5', 'S6', 'S7', 'S8', 'S9', 'S11']\n elif FLAGS.subjects_to_read.lower() == 'train':\n subjects = ['S1', 'S5', 'S6', 'S7', 'S8']\n elif FLAGS.subjects_to_read.lower() == 'val':\n subjects = ['S9', 'S11']\n elif not FLAGS.subjects_to_read:\n raise ValueError('Must add flag specifying subjects to read from H5 files.')\n else:\n subjects = FLAGS.subjects_to_read.split()\n\n if FLAGS.input_data_type == 'H36M_H5':\n tf.logging.info('Loading 3D keypoints from H5 files.')\n keypoint_dict = load_h36m_3d_keypoints_h5_files(FLAGS.input_root_dir,\n subjects)\n else:\n raise NotImplementedError\n\n tf.logging.info('3D keypoints loaded.')\n\n load_2d_keypoints_and_write_tfrecord_with_3d_keypoints(\n FLAGS.input_csv_file,\n keypoint_dict,\n FLAGS.output_tfrecords,\n read_csv_pairs=FLAGS.input_paired_entries,\n num_shards=FLAGS.output_num_shards)\n\n\nif __name__ == '__main__':\n tf.app.run(main)\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Lint as: python3\nr\"\"\"Script for training a captioning model.\"\"\"\n# pylint: disable=unused-variable\n# pylint: disable=undefined-variable\n# pylint: disable=wildcard-import\n# pylint: disable=g-import-not-at-top\nfrom __future__ import absolute_import\nfrom __future__ import division\n\nimport pickle\nimport time\n\nfrom absl import app\nfrom absl import flags\n\nimport numpy as np\nimport tensorflow.compat.v2 as tf\n\nfrom hal.labeler.labeler_utils import *\nfrom hal.learner.language_utils import pad_to_max_length\nimport hal.utils.word_vectorization as wv\n\nif 'gfile' not in sys.modules:\n import tf.io.gfile as gfile\n\nFLAGS = flags.FLAGS\nflags.DEFINE_string('save_dir', None, 'directory for saving models')\n\ntransition_path = None\ntransition_state_path = None\ntransition_label_path = None\nvocab_path = None\n\n\ndef main(_):\n tf.enable_v2_behavior()\n ##############################################################################\n ######################### Data loading and processing ########################\n ##############################################################################\n print('Loading data')\n # with gfile.GFile(transition_path, 'r') as f:\n # transitions = np.load(f)\n\n with gfile.GFile(transition_state_path, 'r') as f:\n states = np.load(f)\n states = np.float32(states)\n\n with gfile.GFile(transition_label_path, 'r') as f:\n captions = pickle.load(f)\n\n with gfile.GFile(answer_path, 'r') as f:\n answers = pickle.load(f)\n\n with gfile.GFile(vocab_path, 'r') as f:\n vocab_list = f.readlines()\n\n vocab_list = [w[:-1].decode('utf-8') for w in vocab_list]\n vocab_list = ['eos', 'sos', 'nothing'] + vocab_list\n vocab_list[-1] = 'to'\n\n v2i, i2v = wv.create_look_up_table(vocab_list)\n encode_fn = wv.encode_text_with_lookup_table(v2i)\n decode_fn = wv.decode_with_lookup_table(i2v)\n\n caption_decoding_map = {v: k for k, v in captions[0].items()}\n decompressed_captions = []\n for caption in captions[1:]:\n new_caption = []\n for c in caption:\n new_caption.append(caption_decoding_map[c])\n decompressed_captions.append(new_caption)\n captions = decompressed_captions\n\n encoded_captions = []\n new_answers = []\n for i, all_cp in enumerate(captions):\n for cp in all_cp:\n encoded_captions.append(np.array(encode_fn(cp)))\n for a in answers[i]:\n new_answers.append(float(a))\n all_caption_n = len(encoded_captions)\n encoded_captions = np.array(encoded_captions)\n encoded_captions = pad_to_max_length(encoded_captions)\n answers = np.float32(new_answers)\n\n obs_idx, caption_idx = [], []\n curr_caption_idx = 0\n for i, _ in enumerate(states):\n for cp in captions[i]:\n obs_idx.append(i)\n caption_idx.append(curr_caption_idx)\n curr_caption_idx += 1\n assert curr_caption_idx == all_caption_n\n\n obs_idx = np.array(obs_idx)\n caption_idx = np.array(caption_idx)\n all_idx = np.arange(len(caption_idx))\n train_idx = all_idx[:int(len(all_idx) * 0.7)]\n test_idx = all_idx[int(len(all_idx) * 0.7):]\n print('Number of training examples: {}'.format(len(train_idx)))\n print('Number of test examples: {}\\n'.format(len(test_idx)))\n\n ##############################################################################\n ############################# Training Setup #################################\n ##############################################################################\n embedding_dim = 32\n units = 64\n vocab_size = len(vocab_list)\n batch_size = 128\n max_sequence_length = 21\n\n encoder_config = {'name': 'state', 'embedding_dim': 64}\n decoder_config = {\n 'name': 'state',\n 'word_embedding_dim': 64,\n 'hidden_units': 512,\n 'vocab_size': len(vocab_list),\n }\n\n encoder = get_answering_encoder(encoder_config)\n decoder = get_answering_decoder(decoder_config)\n projection_layer = tf.keras.layers.Dense(\n 1, activation='sigmoid', name='answering_projection')\n\n optimizer = tf.keras.optimizers.Adam(1e-4)\n bce = tf.keras.losses.BinaryCrossentropy()\n\n @tf.function\n def compute_loss(obs, instruction, target):\n instruction = tf.expand_dims(instruction, axis=-1)\n hidden = decoder.reset_state(batch_size=target.shape[0])\n features = encoder(obs)\n for i in tf.range(max_sequence_length):\n _, hidden, _ = decoder(instruction[:, i], features, hidden)\n projection = tf.squeeze(projection_layer(hidden), axis=1)\n loss = bce(target, projection)\n return loss, projection\n\n @tf.function\n def train_step(obs, instruction, target):\n with tf.GradientTape() as tape:\n loss, _ = compute_loss(obs, instruction, target)\n trainable_variables = encoder.trainable_variables + decoder.trainable_variables + projection_layer.trainable_variables\n gradients = tape.gradient(loss, trainable_variables)\n optimizer.apply_gradients(zip(gradients, trainable_variables))\n return loss\n\n ##############################################################################\n ############################# Training Loop ##################################\n ##############################################################################\n print('Start training...\\n')\n start_epoch = 0\n if FLAGS.save_dir:\n checkpoint_path = FLAGS.save_dir\n ckpt = tf.train.Checkpoint(\n encoder=encoder,\n decoder=decoder,\n projection_layer=projection_layer,\n optimizer=optimizer)\n ckpt_manager = tf.train.CheckpointManager(\n ckpt, checkpoint_path, max_to_keep=5)\n if ckpt_manager.latest_checkpoint:\n start_epoch = int(ckpt_manager.latest_checkpoint.split('-')[-1])\n\n epochs = 400\n step_per_epoch = int(all_caption_n / batch_size)\n\n previous_best, previous_best_accuracy = 100., 0.0\n\n for epoch in range(start_epoch, epochs):\n start = time.time()\n total_loss = 0\n for batch in range(step_per_epoch):\n batch_idx = np.random.choice(train_idx, size=batch_size)\n input_tensor = tf.convert_to_tensor(states[obs_idx[batch_idx], :])\n instruction = tf.convert_to_tensor(\n encoded_captions[caption_idx[batch_idx]])\n target = tf.convert_to_tensor(answers[caption_idx[batch_idx]])\n batch_loss = train_step(input_tensor, instruction, target)\n total_loss += batch_loss\n\n if batch % 1000 == 0:\n print('Epoch {} Batch {} Loss {:.4f}'.format(epoch, batch,\n batch_loss.numpy()))\n\n if epoch % 5 == 0 and FLAGS.save_dir:\n test_total_loss = 0\n accuracy = 0\n for batch in range(10):\n batch_idx = np.arange(batch_size) + batch * batch_size\n idx = test_idx[batch_idx]\n input_tensor = tf.convert_to_tensor(states[obs_idx[idx], :])\n instruction = tf.convert_to_tensor(encoded_captions[caption_idx[idx]])\n target = tf.convert_to_tensor(answers[caption_idx[idx]])\n t_loss, prediction = compute_loss(input_tensor, instruction, target)\n test_total_loss += t_loss\n accuracy += np.mean(np.float32(np.float32(prediction > 0.5) == target))\n test_total_loss /= 10.\n accuracy /= 10.\n if accuracy > previous_best_accuracy:\n previous_best_accuracy, previous_best = accuracy, test_total_loss\n ckpt_manager.save(checkpoint_number=epoch)\n\n print('\\nEpoch {} | Loss {:.6f} | Val loss {:.6f} | Accuracy {:.3f}'.format(\n epoch + 1, total_loss / step_per_epoch, previous_best,\n previous_best_accuracy))\n print('Time taken for 1 epoch {:.6f} sec\\n'.format(time.time() - start))\n\n if epoch % 10 == 0:\n test_total_loss = 0\n accuracy = 0\n for batch in range(len(test_idx) // batch_size):\n batch_idx = np.arange(batch_size) + batch * batch_size\n idx = test_idx[batch_idx]\n input_tensor = tf.convert_to_tensor(states[obs_idx[idx], :])\n instruction = tf.convert_to_tensor(encoded_captions[caption_idx[idx]])\n target = tf.convert_to_tensor(answers[caption_idx[idx]])\n t_loss, prediction = compute_loss(input_tensor, instruction, target)\n test_total_loss += t_loss\n accuracy += np.mean(np.float32(np.float32(prediction > 0.5) == target))\n test_total_loss /= (len(test_idx) // batch_size)\n accuracy /= (len(test_idx) // batch_size)\n if accuracy > previous_best_accuracy and FLAGS.save_dir:\n previous_best_accuracy, previous_best = accuracy, test_total_loss\n ckpt_manager.save(checkpoint_number=epoch)\n print('\\n====================================================')\n print('Test Loss {:.6f} | Test Accuracy {:.3f}'.format(\n test_total_loss, accuracy))\n print('====================================================\\n')\n\n\nif __name__ == '__main__':\n app.run(main)\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Functions the behaviour of a inner training loop.\"\"\"\nimport dataclasses as dc\nimport functools as ft\nfrom typing import Any, Callable, List, Optional, Text, Tuple, Union\n\nimport jax.numpy as jp\nimport numpy as np\nimport tensorflow.compat.v1 as tf\nimport typing_extensions\n\nfrom blur import blur_env\nfrom blur import genome_util\nfrom blur import synapse_util\n\n\n@dc.dataclass\nclass OjasSpec:\n use_ojas_rule: bool = False\n use_multiplier: bool = False\n extra_multiplier: float = 1.0\n # Replaces standard rule of sort W_ijA_j^2, with W_{ij}\\sum W^2_kj\n use_synapse_weights: bool = False\n\nProtocol = typing_extensions.Protocol\nTensor = Union[tf.Tensor, np.ndarray, jp.array]\nActivationFn = Callable[[Tensor], Tensor]\n\n# Incorporates synaptic update for fully connected layers\n# Here \"s\" represents species (With distinct genome),\n# \"r\", replicas (different synapse patterns, sharing the same genome)\n# \"b\" batch (same synapse pattern, different neuronal activation)\n# \"i\" and \"j\" fully connected input and \"output\"\n# \"k\", \"o\", \"l\", -neuronal state\n# Terms are\n# 1. the pre-synaptic input\n# 2. Genome-based transformation of pre-synaptic states\n# 3. Synapse state\nFC_UPDATE_PATTERN = 'srbik,skl,srijl->srbjl'\n\n# 1. Pre-synaptic state\n# 2. Genome-based transformation of pre-synaptic state\n# 3. Genome-based transformation of post-synaptic state\n# 4. Post-synaptic state.\nFC_SYNAPSE_UPDATE = 'srbik,sko,sol,srbjl->srijo'\n\n# 1. Synapses\n# 2. Negated squared post-synaptic activations\nFC_OJAS_SYNAPSE_UPDATE = 'srijo,srbjo->srijo'\n\n\n@dc.dataclass\nclass NetworkState:\n layers: List[Tensor] = dc.field(default_factory=list)\n synapses: List[Tensor] = dc.field(default_factory=list)\n ground_truth: Optional[Tensor] = None\n updatable: List[bool] = dc.field(default_factory=list)\n\n\nclass SynapseUpdateFn(Protocol):\n \"\"\"Type declaring function signature for synapse update function.\"\"\"\n\n def __call__(self, inp, out, synapse,\n *,\n synaptic_genome,\n update_type,\n global_spec, env): Ellipsis\n\n\nclass StateUpdateFn(Protocol):\n \"\"\"Type declaring state update function called at the start of every step.\"\"\"\n\n def __call__(self,\n state,\n genome,\n network_spec,\n env): Ellipsis\n\n\nclass NeuronUpdateFn(Protocol):\n \"\"\"Type declaring function signature for neuron update function.\"\"\"\n\n def __call__(self, inp, out, synapse,\n inp_act,\n out_act,\n *,\n neuron_genome,\n update_type,\n global_spec, env):\n \"\"\"Computes a new value for neurons, given inp, out and synapse.\"\"\"\n\n\nclass FeedbackFn(Protocol):\n \"\"\"Type declaring function signature for feedback_fn.\"\"\"\n\n def __call__(self,\n final_layer,\n ground_truth,\n env = blur_env.tf_env):\n \"\"\"Computes a feedback function from the last layer and the ground truth.\"\"\"\n\n\ndef concat_groundtruth_in(final_layer, ground_truth,\n env = blur_env.tf_env):\n return env.concat(\n [final_layer[Ellipsis, 0:1], ground_truth[Ellipsis, None],\n env.zeros_like(final_layer[Ellipsis, 2:])], axis=-1)\n\n\n@dc.dataclass\nclass SynapseNormalizationSpec:\n normalize_synapses: bool = False\n rescale: bool = False\n normalize_in_activations: bool = False\n\n\nSynapseTransformFn = Callable[[Tensor], Tensor]\n\n\n@dc.dataclass\nclass NetworkSpec:\n \"\"\"Global specification of the network properties.\"\"\"\n synapse_activation_fn: Optional[ActivationFn] = None\n forward_activation_fn: Optional[ActivationFn] = None\n backward_activation_fn: Optional[ActivationFn] = None\n last_layer_activation_fn: Optional[ActivationFn] = None\n zero_out_neurons: bool = True\n per_layer_genome: bool = False\n ojas_spec: Optional[OjasSpec] = None\n synapse_normalization_spec: Optional[SynapseNormalizationSpec] = None\n forward_synapse_update: bool = False\n supervised_every: Optional[int] = None\n synapse_transform_fn: Optional[SynapseTransformFn] = None\n fixed_batches: bool = False\n # Synapse saturation mechanism and parameters\n synapse_saturation_eps: Optional[float] = None\n synapse_saturation_type: Optional[str] = None\n\n neuron_update_fn: Optional[NeuronUpdateFn] = None\n synapse_update_fn: Optional[SynapseUpdateFn] = None\n get_genome_fn: Optional[Callable[[Any, int], Any]] = None\n state_update_fn: Optional[StateUpdateFn] = None\n feedback_fn: Optional[FeedbackFn] = None\n\n # Can be either `multiplicative_second_state`, 'multiplicative' or `additive`.\n # - `multiplicative_second_state` means the first state is passed through with\n # no changes, while the second state receives multipicative update.\n # - `multiplicative` means all the states are updated multiplicatively.\n # - `additive` means all the states are updated additively.\n backward_update: str = 'additive'\n # Whether to apply the same synapse matrix for the forward and backward pass.\n symmetric_in_out_synapses: bool = False\n symmetric_states_synapses: bool = False\n\n use_forward_activations_for_synapse_update: bool = False\n\n def __post_init__(self):\n if self.neuron_update_fn is None:\n self.neuron_update_fn = dense_neuron_update\n if self.synapse_update_fn is None:\n self.synapse_update_fn = ft.partial(\n dense_synapse_update,\n saturation_eps=self.synapse_saturation_eps,\n saturation_type=self.synapse_saturation_type)\n if self.get_genome_fn is None:\n self.get_genome_fn = ft.partial(genome_util.get_genome,\n per_layer_genome=self.per_layer_genome)\n if self.state_update_fn is None:\n self.state_update_fn = default_state_update\n if self.feedback_fn is None:\n self.feedback_fn = concat_groundtruth_in\n\n\ndef default_network_spec(env):\n return NetworkSpec(forward_activation_fn=env.relu_tanh,\n backward_activation_fn=env.relu_tanh,\n last_layer_activation_fn=env.tanh)\n\n\ndef backprop_network_spec(env):\n del env # Unused.\n return NetworkSpec(\n backward_update='multiplicative_second_state',\n symmetric_in_out_synapses=True,\n symmetric_states_synapses=True)\n\n\ndef network_step(state,\n genome,\n input_fn,\n backward_pass_neurons=True,\n backward_pass_synapses=True,\n *,\n network_spec = None,\n debug_hidden_states = None,\n step = None,\n env = blur_env.tf_env):\n \"\"\"Given the current state of the network produces new state.\"\"\"\n if network_spec is None:\n network_spec = default_network_spec(env)\n if network_spec.synapse_transform_fn is None:\n network_spec.synapse_transform_fn = default_synapse_transform_fn(\n genome, network_spec, env)\n if debug_hidden_states is None:\n debug_hidden_states = []\n with env.name_scope('step'):\n input_batch, gt_batch = input_fn()\n new_layers = list(state.layers)\n\n if network_spec.zero_out_neurons:\n for i, layer in enumerate(new_layers):\n new_layers[i] = env.zeros_like(layer)\n\n state = dc.replace(state, layers=new_layers)\n debug_hidden_states.append(state)\n # Concatenate input signal to the last axis\n state.layers[0] = env.concat(\n [input_batch[Ellipsis, None],\n env.zeros_like(state.layers[0][Ellipsis, 1:])],\n axis=-1)\n debug_hidden_states.append(state)\n state = network_spec.state_update_fn(\n state, genome, network_spec=network_spec, env=env)\n debug_hidden_states.append(state)\n with env.name_scope('forward'):\n state = update_network_neurons(\n state, genome.neuron, backward=False,\n network_spec=network_spec, env=env)\n debug_hidden_states.append(state)\n\n if network_spec.forward_synapse_update:\n with env.name_scope('synapse_update'):\n assert genome.forward_synapse is not None\n state = update_network_synapses(\n state, genome.forward_synapse, backward=False,\n network_spec=network_spec, env=env)\n debug_hidden_states.append(state)\n\n forward_state = None\n if network_spec.use_forward_activations_for_synapse_update:\n forward_state = state\n\n state.ground_truth = gt_batch\n\n backward_pass = (step is None or\n network_spec.supervised_every is None or\n step % network_spec.supervised_every == 0)\n with env.name_scope('backward'):\n if backward_pass_neurons and backward_pass:\n state.layers[-1] = network_spec.feedback_fn(\n final_layer=state.layers[-1], ground_truth=gt_batch, env=env)\n debug_hidden_states.append(state)\n state = update_network_neurons(state, genome.neuron,\n backward=True,\n network_spec=network_spec, env=env)\n debug_hidden_states.append(state)\n if backward_pass_synapses and backward_pass:\n with env.name_scope('synapse_update'):\n state = update_network_synapses(\n state, genome.synapse, backward=True,\n network_spec=network_spec, env=env,\n forward_state=forward_state)\n debug_hidden_states.append(state)\n return state\n\n\ndef update_network_neurons(\n state,\n neuron_genome,\n network_spec,\n backward=False,\n *, env):\n \"\"\"Updates neuronal states.\n\n The updates are applied sequentially.\n if backward is False, the updates are applied in increasing order (e.g.\n layer[1] is updated from layer[0] etc) if backward is True updates are\n applied in reversed order.\n\n E.g. for forward pass: we apply updates like so\n for i in num_layers:\n Δl_i, Δl_{i+1} = synaptic_update(l_i, l_i+1).\n l_{i+1} += Δl_{i+1}\n\n where the next update is computed after previous have been applied.\n E.g. for backward mdoe: we compute updates like so\n for i in reverse(num_layers-1):\n Δl_i, Δl_{i+1} = synaptic_update(l_i, l_i+1).\n l_{i} += Δl_{i}\n\n Importantly: for efficiency we don't (at the moment) apply\n l_{i} on forward pass and l_{i+1} on backward pass.\n\n Args:\n state: NetworkState,\n neuron_genome: genome_util.NeuronGenome,\n network_spec: network spec\n backward: the direction of the pass.\n env: blur_env.Env environment.\n Returns:\n new NetworkState\n \"\"\"\n network_spec = network_spec or NetworkSpec()\n enumerated_synapses = list(enumerate(state.synapses))\n if backward:\n base_act_fn = network_spec.backward_activation_fn\n update = synapse_util.UpdateType.BACKWARD\n enumerated_synapses = reversed(enumerated_synapses)\n else:\n base_act_fn = network_spec.forward_activation_fn\n update = synapse_util.UpdateType.FORWARD\n\n neuron_activations = [base_act_fn] * (len(state.layers) - 1) + [\n network_spec.last_layer_activation_fn]\n layers = list(state.layers)\n synapses = list(state.synapses)\n for i, synapse in enumerated_synapses:\n with env.name_scope(f'{update.name.lower()}_{i}_{i+1}'):\n new_layer = network_spec.neuron_update_fn(\n layers[i], layers[i+1], synapse,\n neuron_genome=network_spec.get_genome_fn(neuron_genome, i),\n inp_act=neuron_activations[i],\n out_act=neuron_activations[i+1],\n update_type=update,\n global_spec=network_spec,\n env=env)\n\n if state.updatable[i]:\n layers[i] = new_layer[0]\n if state.updatable[i+1]:\n layers[i+1] = new_layer[1]\n\n return NetworkState(\n layers=layers, synapses=synapses,\n ground_truth=state.ground_truth,\n updatable=state.updatable)\n\n\ndef update_network_synapses(state,\n synaptic_genome,\n network_spec = None,\n backward=False,\n forward_state=None, *, env):\n \"\"\"Updates synapses.\"\"\"\n network_spec = network_spec or NetworkSpec()\n layers = list(state.layers)\n synapses = list(state.synapses)\n update_type = (synapse_util.UpdateType.BACKWARD if backward else\n synapse_util.UpdateType.FORWARD)\n enumerated_synapses = list(enumerate(state.synapses))\n if backward:\n enumerated_synapses = reversed(enumerated_synapses)\n\n if not network_spec.use_forward_activations_for_synapse_update:\n assert forward_state is None\n forward_state = state\n else:\n assert forward_state\n\n for i, synapse in enumerated_synapses:\n pre = env.identity(forward_state.layers[i], name='hebbian_pre')\n post = env.identity(layers[1+i], name='hebbian_post')\n synapses[i] = network_spec.synapse_update_fn(\n pre, post, synapse,\n synaptic_genome=network_spec.get_genome_fn(synaptic_genome, i),\n update_type=update_type, global_spec=network_spec, env=env)\n\n return NetworkState(\n layers=layers, synapses=synapses,\n ground_truth=state.ground_truth,\n updatable=state.updatable)\n\n\ndef default_synapse_transform_fn(\n genome,\n network_spec,\n env):\n \"\"\"Creates additional parameters for the neuron update.\"\"\"\n normalization_spec = network_spec.synapse_normalization_spec\n if (normalization_spec is None or\n not normalization_spec.normalize_in_activations):\n return None\n rescale_to = genome.synapse.rescale_to if normalization_spec.rescale else None\n return ft.partial(\n synapse_util.normalize_synapses, rescale_to=rescale_to, env=env)\n\n\ndef get_ojas_update(pre, post, synapse,\n genome,\n ojas_spec,\n env):\n \"\"\"Additional update term designed to match a version of the Oja's rule.\n\n Currently implemented expression is a version of:\n Δw_{ij} ~ - w_{ij} y_j^2\n\n where y are post-synaptic activations (additional state transform is not\n shown).\n\n For reference see, for example:\n \"A meta-learning approach to (re)discover plasticity rules that carve a\n desired function into a neural network\"\n https://www.biorxiv.org/content/10.1101/2020.10.24.353409v1.full.pdf\n\n Args:\n pre: [population] x batch_size x in_channels x num_states\n post: [population] x batch_size x out_channels x num_states\n synapse: [population] x in_channels x out_channels x num_states\n genome: Synaptic genome\n ojas_spec: Specification of the Oja's term\n env: Environment\n Returns:\n Update. [in_channels + 1 + out_channels, in_channels + 1 + out_channels, k]\n \"\"\"\n if ojas_spec.use_synapse_weights:\n act_squared = -synapse ** 2 * ojas_spec.extra_multiplier\n else:\n activations = env.concat([env.concat_row(pre, 0), post], axis=-2)\n act_squared = env.einsum(\n 'srbjl,sol->srbjo', activations, genome.transform.post)\n act_squared = -act_squared * act_squared * ojas_spec.extra_multiplier\n\n if ojas_spec.use_multiplier:\n act_squared *= env.abs(genome.transform.ojas_multiplier)\n # Negative `update` can turn this term into an amplifying force.\n # We solve this by properly adjusting the sign.\n act_squared *= env.sign(genome.update)\n return env.einsum(FC_OJAS_SYNAPSE_UPDATE, synapse, act_squared)\n\n\ndef get_synaptic_update(pre,\n post,\n synapse,\n input_transform_gn,\n *,\n update_type=synapse_util.UpdateType.BOTH,\n synapse_transform_fn=None,\n env):\n \"\"\"Performs synaptic update.\n\n [Δpre, Δpost] = synapse * input_transform @ [pre, post]\n\n This transformation allows both asymmetric updates with information only\n flows\n from pre to post, however it also allows reverse flow if input_transform\n is non-zero its upper left quadrant (similar to e.g. akin electrical\n synapse).\n\n This function can perform updates on a bunch of replicas sharing the\n same genome. As well as on population of species each containing bunch\n of agents with different genomes.\n\n The population dimensions (species/replica) are present in all tensors\n or not present at all.\n\n Args:\n pre: [#species x #replicas] x batch_size x input_shape x\n num_neuron_states,\n post: [#species x #replicas] x batch_size x output_shape x\n num_neuron_states\n synapse: [#species x #replicas] x (input_shape + output_shape + 1)^ 2 x\n num_neuron_states. the synapse weight connecting input_shape with\n output_shape\n input_transform_gn: [#species] x (2 num_neuron_states ) ^2: describes\n genome's input transformation.\n update_type: which update to compute (update to the input, update to the\n output or both).\n synapse_transform_fn: function used to transform synapses while\n calculating activations\n env: compute environment\n\n Returns:\n update signals\n \"\"\"\n k = pre.shape[-1]\n # Verifies that we use the same embedding size.\n if pre.shape[-1] != post.shape[-1]:\n raise ValueError(f'pre: {pre.shape}[-1] != post: {post.shape}[-1]')\n\n # Note: we cheat here:\n # Update for \"post\" here only uses \"pre\" (ignoring current value of \"post\")\n # And vice versa for \"pre\".\n # That is we ignore the following elements of input_transform_gn\n # and synapse matrices\n # [ x U ]\n # [ V x ] (U and V are the only submatrices that are being used)\n # Add support for immediate feedback if and when desired.\n output_update = None\n if update_type in (synapse_util.UpdateType.FORWARD,\n synapse_util.UpdateType.BOTH):\n output_update = single_synaptic_update(\n synapse,\n input_layer=pre,\n in_channels=pre.shape[-2],\n update_type=synapse_util.UpdateType.FORWARD,\n transform_gn=input_transform_gn[Ellipsis, :k, k:],\n synapse_transform_fn=synapse_transform_fn,\n env=env)\n output_update = env.identity(output_update, 'output_update')\n input_update = None\n if update_type in (synapse_util.UpdateType.BACKWARD,\n synapse_util.UpdateType.BOTH):\n # Transforming \"post\"\n # Generating update for the \"input\" part of the synapse.\n input_update = single_synaptic_update(\n synapse,\n input_layer=post,\n in_channels=pre.shape[-2],\n update_type=synapse_util.UpdateType.BACKWARD,\n transform_gn=input_transform_gn[Ellipsis, k:, :k],\n synapse_transform_fn=synapse_transform_fn,\n env=env)\n input_update = env.identity(input_update, 'input_update')\n return input_update, output_update\n\n\ndef single_synaptic_update(\n synapse,\n input_layer,\n in_channels,\n update_type,\n transform_gn,\n synapse_transform_fn=None,\n *,\n env):\n \"\"\"Computes one-way (Forward or Backward) synaptic update.\"\"\"\n include_bias = False\n if update_type == synapse_util.UpdateType.FORWARD:\n # Input channels are +1 to include \"1\" channel to simulate bias.\n input_layer = env.concat_row(input_layer)\n include_bias = True\n subsynapse = synapse_util.synapse_submatrix(\n synapse,\n in_channels=in_channels,\n update_type=update_type,\n include_bias=include_bias)\n if synapse_transform_fn is not None:\n subsynapse = synapse_transform_fn(subsynapse)\n update = env.einsum(\n FC_UPDATE_PATTERN, input_layer, transform_gn, subsynapse)\n return update\n\n\ndef compute_neuron_state(old_neuron_state, synaptic_update,\n g,\n activation_fn, update_type, *,\n env):\n \"\"\"Computes new neuron state from the synaptic update.\"\"\"\n if activation_fn is None:\n activation_fn = lambda x: x\n # TODO(sandler): Add inverse activation of old_state if needed.\n if synaptic_update is None:\n return old_neuron_state\n if update_type == 'multiplicative_second_state':\n # TODO(mxv): possibly rename this update_type, since technically it should\n # be called skip_first_state or something like this.\n second_state_update = old_neuron_state[Ellipsis, 1:] * synaptic_update[Ellipsis, 1:]\n new_neuron_state = env.concat(\n [old_neuron_state[Ellipsis, 0:1], second_state_update], axis=-1\n ) * env.right_pad_shape(g.keep, to=old_neuron_state)\n elif update_type == 'multiplicative':\n new_neuron_state = (\n old_neuron_state * synaptic_update *\n env.right_pad_shape(g.keep, to=old_neuron_state))\n elif update_type == 'additive':\n new_neuron_state = (\n old_neuron_state * env.right_pad_shape(g.keep, to=old_neuron_state) +\n synaptic_update * env.right_pad_shape(g.update, to=synaptic_update))\n elif update_type == 'none':\n new_neuron_state = synaptic_update\n return activation_fn(new_neuron_state)\n\n\ndef dense_neuron_update(\n inp, out, synapse,\n *,\n inp_act, out_act,\n neuron_genome,\n update_type = synapse_util.UpdateType.FORWARD,\n global_spec, # pylint: disable=unused-argument\n env):\n \"\"\"Default neuron update function.\"\"\"\n input_update, output_update = get_synaptic_update(\n inp, out, synapse,\n input_transform_gn=neuron_genome.transform,\n update_type=update_type,\n synapse_transform_fn=global_spec.synapse_transform_fn,\n env=env)\n\n inp = compute_neuron_state(\n inp, input_update, neuron_genome, activation_fn=inp_act,\n update_type=global_spec.backward_update, env=env)\n out = compute_neuron_state(\n out, output_update, neuron_genome, activation_fn=out_act,\n update_type='additive', env=env)\n return inp, out\n\n\ndef get_hebbian_update(pre, post, transform,\n global_spec,\n env):\n \"\"\"Performs hebbian update of the synapse weight matrix.\n\n Δ w = [pre, [1], post] @ transform.pre * transform.post @ [pre, [0],\n post]\n\n Args:\n pre: [population] x batch_size x in_channels x num_states\n post: [population] x batch_size x out_channels x num_states\n transform: genome_util.HebbianTransform\n global_spec: Specification of the network.\n env: Environment\n\n Returns:\n Update. [in_channels+1 + in_channels, out_channels + 1 + out_channels, k]\n \"\"\"\n inp = env.concat([env.concat_row(pre, 1), post], axis=-2)\n out = env.concat([env.concat_row(pre, 1), post], axis=-2)\n # inp: [b x (in+out) x k],\n # transforms: [k x k]\n hebbian_update = env.einsum(FC_SYNAPSE_UPDATE, inp, transform.pre,\n transform.post, out)\n if global_spec.symmetric_in_out_synapses:\n hebbian_update = synapse_util.sync_in_and_out_synapse(\n hebbian_update, pre.shape[-2], env)\n if global_spec.symmetric_states_synapses:\n hebbian_update = synapse_util.sync_states_synapse(hebbian_update, env)\n return hebbian_update\n\n\ndef compute_synapse_state(old_synapse,\n hebbian_update,\n g,\n activation_fn=None,\n saturation_type = None,\n saturation_eps = None,\n *,\n env):\n \"\"\"Computes new synapse state given Hebbian update.\"\"\"\n if activation_fn is None:\n activation_fn = lambda x: x\n if saturation_type == 'exp_update':\n assert saturation_eps is not None\n # This is necessary to avoid type issues during eval\n delta_keep = np.float32(-1.0)\n delta_keep += g.keep\n dw = (old_synapse * env.right_pad_shape(delta_keep, to=old_synapse) +\n hebbian_update * env.right_pad_shape(g.update, to=hebbian_update))\n dw *= env.exp(\n -env.abs(old_synapse) * (saturation_eps + env.abs(g.saturation)))\n return activation_fn(old_synapse + dw)\n elif (saturation_type in ['disabled', 'normalization'] or\n saturation_type is None):\n return activation_fn(\n old_synapse * env.right_pad_shape(g.keep, to=old_synapse) +\n hebbian_update * env.right_pad_shape(g.update, to=hebbian_update))\n else:\n raise AssertionError\n\n\n# Note there might be multiple implementatios of \"dense\", we should rename\n# this to as we have a better name.\ndef dense_synapse_update(\n inp, out, synapse,\n saturation_type = None,\n saturation_eps = None,\n *,\n synaptic_genome,\n update_type = synapse_util.UpdateType.FORWARD,\n global_spec,\n env):\n \"\"\"Default synapse update function.\"\"\"\n del update_type\n hebbian_update = get_hebbian_update(inp, out,\n synaptic_genome.transform,\n global_spec, env=env)\n if global_spec.ojas_spec:\n hebbian_update += get_ojas_update(inp, out, synapse,\n synaptic_genome,\n ojas_spec=global_spec.ojas_spec, env=env)\n hebbian_update = env.identity(hebbian_update, name='hebbian_update')\n return compute_synapse_state(\n synapse,\n hebbian_update,\n synaptic_genome,\n saturation_eps=saturation_eps,\n saturation_type=saturation_type,\n activation_fn=global_spec.synapse_activation_fn, env=env)\n\n\ndef default_state_update(state,\n genome,\n network_spec,\n env):\n \"\"\"Transforms system state (currently can normalize synapses).\"\"\"\n synapse_norm_spec = network_spec.synapse_normalization_spec\n if synapse_norm_spec is None:\n return state\n rescale_to = genome.synapse.rescale_to if synapse_norm_spec.rescale else None\n normalize = ft.partial(\n synapse_util.normalize_synapses, rescale_to=rescale_to, env=env)\n if synapse_norm_spec.normalize_synapses:\n for i in range(len(state.synapses)):\n synapse = state.synapses[i]\n in_channels = state.layers[i].shape[-2]\n forward = synapse[Ellipsis, :(in_channels + 1), (in_channels + 1):, :]\n # We include an extra dimension for axis=-2 here because it does not\n # influence normalization, but the tensors would have proper shapes:\n backward = synapse[Ellipsis, (in_channels + 1):, :(in_channels + 1), :]\n state.synapses[i] = synapse_util.combine_in_out_synapses(\n normalize(forward), normalize(backward), env)\n\n return state\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Matrix connection utilities.\"\"\"\nimport abc\nimport numpy as np\nimport six\n\n\nclass Connector(six.with_metaclass(abc.ABCMeta)):\n \"\"\"Defines API for a weight connector.\"\"\"\n\n def __init__(self, sparsity, round_to=1):\n \"\"\"Initialization for weight connector.\n\n This method can be overridden to save input keyword arguments\n for the specific conenctor.\n\n Args:\n sparsity: Desired sparsity for the weight matrix.\n round_to: The number of nonzeros to round up to.\n \"\"\"\n if sparsity < 0.0 or sparsity >= 1.0:\n raise ValueError(\"Sparsity should be >= 0 and < 1.0.\")\n self.sparsity = sparsity\n self.round_to = round_to\n\n @abc.abstractmethod\n def __call__(self, dense_matrix):\n pass\n\n\nclass Uniform(Connector):\n \"\"\"Uniformly samples which weights should be nonzero.\"\"\"\n\n def __call__(self, dense_weights):\n \"\"\"Masks weights selected uniformly from `dense_weights`.\n\n Args:\n dense_weights: Numpy array of the dense weight matrix.\n\n Returns:\n A numpy array with a proportion of the weights set to\n zero.\n \"\"\"\n if self.sparsity == 0.0:\n return dense_weights\n\n # Select (without replacement) the weights that\n # should be set to zero.\n num_dormant = int(round(self.sparsity * dense_weights.size))\n\n if self.round_to > 1:\n nnz = dense_weights.size - num_dormant\n nnz = (nnz + self.round_to - 1) // self.round_to * self.round_to\n num_dormant = dense_weights.size - nnz\n\n dormant_mask = np.random.choice(\n dense_weights.size, num_dormant, replace=False)\n\n weights_shape = dense_weights.shape\n dense_weights = np.reshape(dense_weights, [-1])\n dense_weights[dormant_mask] = 0.0\n sparse_weights = np.reshape(dense_weights, weights_shape)\n return sparse_weights\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Builds the CIFAR-10 network with additional variables to support compression.\n\nSummary of available functions:\n\n # Compute input images and labels for training. If you would like to run\n # evaluations, use inputs() instead.\n inputs, labels = distorted_inputs()\n\n # Compute inference on the model inputs to make a prediction.\n predictions = inference(inputs)\n\n # Compute the total loss of the prediction with respect to the labels.\n loss = loss(predictions, labels)\n\n # Create a graph to run one step of training with respect to the loss.\n train_op = train(loss, global_step)\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport re\nimport sys\nimport tarfile\n\nfrom six.moves import urllib\nimport tensorflow.compat.v1 as tf\n\nfrom graph_compression.compression_lib import compression_op as compression\nfrom graph_compression.compression_lib import compression_op_utils as comp_op_utils\nfrom graph_compression.compression_lib import compression_wrapper\nfrom graph_compression.compression_lib.examples.cifar10 import cifar10_input\n\n# Global constants describing the CIFAR-10 data set.\nIMAGE_SIZE = cifar10_input.IMAGE_SIZE\nNUM_CLASSES = cifar10_input.NUM_CLASSES\nNUM_EXAMPLES_PER_EPOCH_FOR_TRAIN = cifar10_input.NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN\nNUM_EXAMPLES_PER_EPOCH_FOR_EVAL = cifar10_input.NUM_EXAMPLES_PER_EPOCH_FOR_EVAL\nBATCH_SIZE = 128\nDATA_DIR = '/tmp/cifar10_data'\n\n# Constants describing the training process.\nMOVING_AVERAGE_DECAY = 0.9999 # The decay to use for the moving average.\nNUM_EPOCHS_PER_DECAY = 350.0 # Epochs after which learning rate decays.\nLEARNING_RATE_DECAY_FACTOR = 0.1 # Learning rate decay factor.\nINITIAL_LEARNING_RATE = 0.1 # Initial learning rate.\n\n# If a model is trained with multiple GPUs, prefix all Op names with tower_name\n# to differentiate the operations. Note that this prefix is removed from the\n# names of the summaries when visualizing a model.\nTOWER_NAME = 'tower'\n\nDATA_URL = 'http://www.cs.toronto.edu/~kriz/cifar-10-binary.tar.gz'\n\n\ndef _activation_summary(x):\n \"\"\"Helper to create summaries for activations.\n\n Creates a summary that provides a histogram of activations.\n Creates a summary that measures the sparsity of activations.\n\n Args:\n x: Tensor\n\n Returns:\n nothing\n \"\"\"\n # Remove 'tower_[0-9]/' from the name in case this is a multi-GPU training\n # session. This helps the clarity of presentation on tensorboard.\n tensor_name = re.sub('%s_[0-9]*/' % TOWER_NAME, '', x.op.name)\n tf.summary.histogram(tensor_name + '/activations', x)\n tf.summary.scalar(tensor_name + '/sparsity', tf.nn.zero_fraction(x))\n\n\ndef _variable_on_cpu(name, shape, initializer):\n \"\"\"Helper to create a Variable stored on CPU memory.\n\n Args:\n name: name of the variable\n shape: list of ints\n initializer: initializer for Variable\n\n Returns:\n Variable Tensor\n \"\"\"\n with tf.device('/cpu:0'):\n dtype = tf.float32\n var = tf.get_variable(name, shape, initializer=initializer, dtype=dtype)\n return var\n\n\ndef _variable_with_weight_decay(name, shape, stddev, wd):\n \"\"\"Helper to create an initialized Variable with weight decay.\n\n Note that the Variable is initialized with a truncated normal distribution.\n A weight decay is added only if one is specified.\n\n Args:\n name: name of the variable\n shape: list of ints\n stddev: standard deviation of a truncated Gaussian\n wd: add L2Loss weight decay multiplied by this float. If None, weight decay\n is not added for this Variable.\n\n Returns:\n Variable Tensor\n \"\"\"\n dtype = tf.float32\n var = _variable_on_cpu(\n name, shape, tf.truncated_normal_initializer(stddev=stddev, dtype=dtype))\n if wd is not None:\n weight_decay = tf.multiply(tf.nn.l2_loss(var), wd, name='weight_loss')\n tf.add_to_collection('losses', weight_decay)\n return var\n\n\ndef distorted_inputs():\n \"\"\"Construct distorted input for CIFAR training using the Reader ops.\n\n Returns:\n images: Images. 4D tensor of [batch_size, IMAGE_SIZE, IMAGE_SIZE, 3] size.\n labels: Labels. 1D tensor of [batch_size] size.\n\n Raises:\n ValueError: If no data_dir\n \"\"\"\n if not DATA_DIR:\n raise ValueError('Please supply a data_dir')\n data_dir = os.path.join(DATA_DIR, 'cifar-10-batches-bin')\n images, labels = cifar10_input.distorted_inputs(\n data_dir=data_dir, batch_size=BATCH_SIZE)\n return images, labels\n\n\ndef create_compressor(hparams='', global_step=None):\n \"\"\"Creates an ApplyCompression object to use during the inference step.\"\"\"\n # Parse compression hyperparameters\n compression_hparams = compression.CompressionOp.get_default_hparams().parse(\n hparams)\n\n # Create a compression object using the compression hyperparameters\n compression_obj = compression_wrapper.get_apply_compression(\n compression_hparams, global_step=global_step)\n return compression_obj\n\n\ndef inputs(eval_data):\n \"\"\"Construct input for CIFAR evaluation using the Reader ops.\n\n Args:\n eval_data: bool, indicating if one should use the train or eval data set.\n\n Returns:\n images: Images. 4D tensor of [batch_size, IMAGE_SIZE, IMAGE_SIZE, 3] size.\n labels: Labels. 1D tensor of [batch_size] size.\n\n Raises:\n ValueError: If no data_dir\n \"\"\"\n if not DATA_DIR:\n raise ValueError('Please supply a data_dir')\n data_dir = os.path.join(DATA_DIR, 'cifar-10-batches-bin')\n images, labels = cifar10_input.inputs(\n eval_data=eval_data, data_dir=data_dir, batch_size=BATCH_SIZE)\n return images, labels\n\n\ndef inference(images, compression_obj):\n \"\"\"Build the CIFAR-10 model.\n\n Args:\n images: Images returned from distorted_inputs() or inputs().\n compression_obj: The compression object to use for compressing matrices in\n the main graph.\n\n Returns:\n Logits.\n \"\"\"\n # We instantiate all variables using tf.compat.v1.get_variable() instead of\n # tf.Variable() in order to share variables across multiple GPU training runs.\n # If we only ran this model on a single GPU, we could simplify this function\n # by replacing all instances of tf.compat.v1.get_variable() with\n # tf.Variable().\n #\n # While instantiating conv and local layers, we add mask and threshold\n # variables to the layer by calling the pruning.apply_mask() function.\n # Note that the masks are applied only to the weight tensors\n # conv1\n with tf.variable_scope('conv1') as scope:\n kernel = _variable_with_weight_decay(\n 'weights', shape=[5, 5, 3, 64], stddev=5e-2, wd=0.0)\n\n conv = tf.nn.conv2d(images, kernel, [1, 1, 1, 1], padding='SAME')\n biases = _variable_on_cpu('biases', [64], tf.constant_initializer(0.0))\n pre_activation = tf.nn.bias_add(conv, biases)\n conv1 = tf.nn.relu(pre_activation, name=scope.name)\n _activation_summary(conv1)\n\n # pool1\n pool1 = tf.nn.max_pool(\n conv1,\n ksize=[1, 3, 3, 1],\n strides=[1, 2, 2, 1],\n padding='SAME',\n name='pool1')\n # norm1\n norm1 = tf.nn.lrn(\n pool1, 4, bias=1.0, alpha=0.001 / 9.0, beta=0.75, name='norm1')\n\n # conv2\n with tf.variable_scope('conv2') as scope:\n kernel = _variable_with_weight_decay(\n 'weights', shape=[5, 5, 64, 64], stddev=5e-2, wd=0.0)\n\n conv = tf.nn.conv2d(norm1, kernel, [1, 1, 1, 1], padding='SAME')\n biases = _variable_on_cpu('biases', [64], tf.constant_initializer(0.1))\n pre_activation = tf.nn.bias_add(conv, biases)\n conv2 = tf.nn.relu(pre_activation, name=scope.name)\n _activation_summary(conv2)\n\n # norm2\n norm2 = tf.nn.lrn(\n conv2, 4, bias=1.0, alpha=0.001 / 9.0, beta=0.75, name='norm2')\n # pool2\n pool2 = tf.nn.max_pool(\n norm2,\n ksize=[1, 3, 3, 1],\n strides=[1, 2, 2, 1],\n padding='SAME',\n name='pool2')\n\n # local3\n with tf.variable_scope('local3') as scope:\n # Move everything into depth so we can perform a single matrix multiply.\n reshape = tf.reshape(pool2, [BATCH_SIZE, -1])\n dim = reshape.get_shape()[1].value\n weights = _variable_with_weight_decay(\n 'weights', shape=[dim, 384], stddev=0.04, wd=0.004)\n biases = _variable_on_cpu('biases', [384], tf.constant_initializer(0.1))\n\n local3 = tf.nn.relu(\n tf.matmul(reshape, compression_obj.apply_compression(weights, scope)) +\n biases,\n name=scope.name)\n _activation_summary(local3)\n\n # local4\n with tf.variable_scope('local4') as scope:\n weights = _variable_with_weight_decay(\n 'weights', shape=[384, 192], stddev=0.04, wd=0.004)\n biases = _variable_on_cpu('biases', [192], tf.constant_initializer(0.1))\n\n local4 = tf.nn.relu(\n tf.matmul(local3, compression_obj.apply_compression(weights, scope)) +\n biases,\n name=scope.name)\n _activation_summary(local4)\n\n # linear layer(WX + b),\n # We don't apply softmax here because\n # tf.nn.sparse_softmax_cross_entropy_with_logits accepts the unscaled logits\n # and performs the softmax internally for efficiency.\n with tf.variable_scope('softmax_linear') as scope:\n weights = _variable_with_weight_decay(\n 'weights', [192, NUM_CLASSES], stddev=1 / 192.0, wd=0.0)\n biases = _variable_on_cpu('biases', [NUM_CLASSES],\n tf.constant_initializer(0.0))\n\n softmax_linear = tf.add(tf.matmul(local4, weights), biases, name=scope.name)\n _activation_summary(softmax_linear)\n\n return softmax_linear\n\n\ndef loss(logits, labels):\n \"\"\"Add L2Loss to all the trainable variables.\n\n Add summary for \"Loss\" and \"Loss/avg\".\n Args:\n logits: Logits from inference().\n labels: Labels from distorted_inputs or inputs(). 1-D tensor of shape\n [batch_size]\n\n Returns:\n Loss tensor of type float.\n \"\"\"\n # Calculate the average cross entropy loss across the batch.\n labels = tf.cast(labels, tf.int64)\n cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(\n labels=labels, logits=logits, name='cross_entropy_per_example')\n cross_entropy_mean = tf.reduce_mean(cross_entropy, name='cross_entropy')\n tf.add_to_collection('losses', cross_entropy_mean)\n\n # The total loss is defined as the cross entropy loss plus all of the weight\n # decay terms (L2 loss).\n return tf.add_n(tf.get_collection('losses'), name='total_loss')\n\n\ndef _add_loss_summaries(total_loss):\n \"\"\"Add summaries for losses in CIFAR-10 model.\n\n Generates moving average for all losses and associated summaries for\n visualizing the performance of the network.\n\n Args:\n total_loss: Total loss from loss().\n\n Returns:\n loss_averages_op: op for generating moving averages of losses.\n \"\"\"\n # Compute the moving average of all individual losses and the total loss.\n loss_averages = tf.train.ExponentialMovingAverage(0.9, name='avg')\n losses = tf.get_collection('losses')\n loss_averages_op = loss_averages.apply(losses + [total_loss])\n\n # Attach a scalar summary to all individual losses and the total loss; do the\n # same for the averaged version of the losses.\n for l in losses + [total_loss]:\n # Name each loss as '(raw)' and name the moving average version of the loss\n # as the original loss name.\n tf.summary.scalar(l.op.name + ' (raw)', l)\n tf.summary.scalar(l.op.name, loss_averages.average(l))\n\n return loss_averages_op\n\n\ndef train(total_loss, global_step, compression_obj):\n \"\"\"Train CIFAR-10 model.\n\n Create an optimizer and apply to all trainable variables. Add moving\n average for all trainable variables.\n\n Args:\n total_loss: Total loss from loss().\n global_step: Integer Variable counting the number of training steps\n processed.\n compression_obj: The compression object to use for compressing matrices in\n the main graph.\n\n Returns:\n train_op: op for training.\n \"\"\"\n # Variables that affect learning rate.\n num_batches_per_epoch = NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN / BATCH_SIZE\n decay_steps = int(num_batches_per_epoch * NUM_EPOCHS_PER_DECAY)\n\n # Decay the learning rate exponentially based on the number of steps.\n lr = tf.train.exponential_decay(\n INITIAL_LEARNING_RATE,\n global_step,\n decay_steps,\n LEARNING_RATE_DECAY_FACTOR,\n staircase=True)\n tf.summary.scalar('learning_rate', lr)\n\n # Generate moving averages of all losses and associated summaries.\n loss_averages_op = _add_loss_summaries(total_loss)\n\n # Compute gradients.\n with tf.control_dependencies([loss_averages_op]):\n opt = tf.train.GradientDescentOptimizer(lr)\n grads = opt.compute_gradients(total_loss)\n\n # Apply gradients.\n apply_gradient_op = opt.apply_gradients(grads, global_step=global_step)\n\n # Add histograms for trainable variables.\n for var in tf.trainable_variables():\n tf.summary.histogram(var.op.name, var)\n\n # Add histograms for gradients.\n for grad, var in grads:\n if grad is not None:\n tf.summary.histogram(var.op.name + '/gradients', grad)\n\n # Track the moving averages of all trainable variables.\n variable_averages = tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY,\n global_step)\n variables_averages_op = variable_averages.apply(tf.trainable_variables())\n\n all_update_op = [apply_gradient_op, variables_averages_op]\n # If using tensorflow operations for the update step, append compression\n # updates to the list of all updates.\n if compression_obj.get_operator_hparam(\n 'update_option') == comp_op_utils.UpdateOptions.TF_UPDATE:\n all_update_op.append(compression_obj.all_update_op())\n else:\n # TODO(loganesian): Once update_option=PYTHON_UPDATE is fully supported,\n # add the python update operation here.\n pass\n\n with tf.control_dependencies(all_update_op):\n train_op = tf.no_op(name='train')\n\n return train_op\n\n\ndef maybe_download_and_extract():\n \"\"\"Download and extract the tarball from Alex's website.\"\"\"\n dest_directory = DATA_DIR\n if not os.path.exists(dest_directory):\n os.makedirs(dest_directory)\n filename = DATA_URL.split('/')[-1]\n filepath = os.path.join(dest_directory, filename)\n if not os.path.exists(filepath):\n\n def _progress(count, block_size, total_size):\n sys.stdout.write(\n '\\r>> Downloading %s %.1f%%' %\n (filename, float(count * block_size) / float(total_size) * 100.0))\n sys.stdout.flush()\n\n filepath, _ = urllib.request.urlretrieve(DATA_URL, filepath, _progress)\n print()\n statinfo = os.stat(filepath)\n print('Successfully downloaded', filename, statinfo.st_size, 'bytes.')\n\n tarfile.open(filepath, 'r:gz').extractall(dest_directory)\n", "# coding=utf-8\n\"\"\"The proposed model training code.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\n\nfrom absl import flags\nimport numpy as np\nimport tensorflow.compat.v1 as tf\nfrom tqdm import tqdm\n\nfrom ieg import utils\nfrom ieg.dataset_utils.utils import autoaug_batch_process_map_fn\nfrom ieg.models import networks\nfrom ieg.models.basemodel import BaseModel\nfrom ieg.models.custom_ops import logit_norm\nfrom ieg.models.custom_ops import MixMode\n\nFLAGS = flags.FLAGS\nlogging = tf.logging\n\n\nclass IEG(BaseModel):\n \"\"\"Model training class.\"\"\"\n\n def __init__(self, sess, strategy, dataset):\n super(IEG, self).__init__(sess, strategy, dataset)\n logging.info('Init IEG model')\n\n self.augment = MixMode()\n self.beta = 0.5\n self.nu = 2\n\n def set_input(self):\n if len(self.dataset.train_dataflow.output_shapes[0]) == 3:\n # Use for cifar\n train_ds = self.dataset.train_dataflow.shuffle(\n buffer_size=self.batch_size * 10).repeat().batch(\n self.batch_size, drop_remainder=True).map(\n # strong augment each batch data and expand to 5D [Bx2xHxWx3]\n autoaug_batch_process_map_fn,\n num_parallel_calls=tf.data.experimental.AUTOTUNE).prefetch(\n buffer_size=tf.data.experimental.AUTOTUNE)\n else:\n train_ds = self.dataset.train_dataflow.shuffle(\n buffer_size=self.batch_size * 10).repeat().batch(\n self.batch_size, drop_remainder=True).prefetch(\n buffer_size=tf.data.experimental.AUTOTUNE)\n # no shuffle for probe, so a batch is class balanced.\n probe_ds = self.dataset.probe_dataflow.repeat().batch(\n self.batch_size,\n drop_remainder=True).prefetch(buffer_size=tf.data.experimental.AUTOTUNE)\n\n val_ds = self.dataset.val_dataflow.batch(\n FLAGS.val_batch_size, drop_remainder=False).prefetch(\n buffer_size=tf.data.experimental.AUTOTUNE)\n\n self.train_input_iterator = (\n self.strategy.experimental_distribute_dataset(\n train_ds).make_initializable_iterator())\n self.probe_input_iterator = (\n self.strategy.experimental_distribute_dataset(\n probe_ds).make_initializable_iterator())\n\n self.eval_input_iterator = (\n self.strategy.experimental_distribute_dataset(\n val_ds).make_initializable_iterator())\n\n def meta_momentum_update(self, grad, var_name, optimizer):\n # Finds corresponding momentum of a var name\n accumulation = utils.get_var(optimizer.variables(), var_name.split(':')[0])\n if len(accumulation) != 1:\n raise ValueError('length of accumulation {}'.format(len(accumulation)))\n new_grad = tf.math.add(\n tf.stop_gradient(accumulation[0]) * FLAGS.meta_momentum, grad)\n return new_grad\n\n def guess_label(self, logit, temp=0.5):\n logit = tf.reshape(logit, [-1, self.dataset.num_classes])\n logit = tf.split(logit, self.nu, axis=0)\n logit = [logit_norm(x) for x in logit]\n logit = tf.concat(logit, 0)\n ## Done with logit norm\n p_model_y = tf.reshape(\n tf.nn.softmax(logit), [self.nu, -1, self.dataset.num_classes])\n p_model_y = tf.reduce_mean(p_model_y, axis=0)\n\n p_target = tf.pow(p_model_y, 1.0 / temp)\n p_target /= tf.reduce_sum(p_target, axis=1, keepdims=True)\n\n return p_target\n\n def crossentropy_minimize(self,\n u_logits,\n u_images,\n l_images,\n l_labels,\n u_labels=None):\n \"\"\"Cross-entropy optimization step implementation for TPU.\"\"\"\n batch_size = self.batch_size // self.strategy.num_replicas_in_sync\n guessed_label = self.guess_label(u_logits)\n self.guessed_label = guessed_label\n\n guessed_label = tf.reshape(\n tf.stop_gradient(guessed_label), shape=(-1, self.dataset.num_classes))\n\n l_labels = tf.reshape(\n tf.one_hot(l_labels, self.dataset.num_classes),\n shape=(-1, self.dataset.num_classes))\n augment_images, augment_labels = self.augment(\n [l_images, u_images], [l_labels] + [guessed_label] * self.nu,\n [self.beta, self.beta])\n logit = self.net(augment_images, name='model', training=True)\n\n zbs = batch_size * 2\n halfzbs = batch_size\n\n split_pos = [tf.shape(l_images)[0], halfzbs, halfzbs]\n\n logit = [logit_norm(lgt) for lgt in tf.split(logit, split_pos, axis=0)]\n u_logit = tf.concat(logit[1:], axis=0)\n\n split_pos = [tf.shape(l_images)[0], zbs]\n l_augment_labels, u_augment_labels = tf.split(\n augment_labels, split_pos, axis=0)\n\n u_loss = tf.losses.softmax_cross_entropy(u_augment_labels, u_logit)\n l_loss = tf.losses.softmax_cross_entropy(l_augment_labels, logit[0])\n\n loss = tf.math.add(\n l_loss, u_loss * FLAGS.ce_factor, name='crossentropy_minimization_loss')\n\n return loss\n\n def consistency_loss(self, logit, aug_logit):\n\n def kl_divergence(q_logits, p_logits):\n q = tf.nn.softmax(q_logits)\n per_example_kl_loss = q * (\n tf.nn.log_softmax(q_logits) - tf.nn.log_softmax(p_logits))\n return tf.reduce_mean(per_example_kl_loss) * self.dataset.num_classes\n\n return tf.math.multiply(\n kl_divergence(tf.stop_gradient(logit), aug_logit),\n FLAGS.consistency_factor,\n name='consistency_loss')\n\n def unsupervised_loss(self):\n \"\"\"Creates unsupervised losses.\n\n Here we create two cross-entropy losses and a KL-loss defined in the paper.\n\n Returns:\n A list of losses.\n \"\"\"\n\n if FLAGS.ce_factor == 0 and FLAGS.consistency_factor == 0:\n return [tf.constant(0, tf.float32), tf.constant(0, tf.float32)]\n logits = self.logits\n images = self.images\n aug_images = self.aug_images\n probe_images, probe_labels = self.probe_images, self.probe_labels\n im_shape = (-1, int(probe_images.shape[1]), int(probe_images.shape[2]),\n int(probe_images.shape[3]))\n\n aug_logits = self.net(aug_images, name='model', training=True)\n\n n_probe_to_mix = tf.shape(aug_images)[0]\n probe = tf.tile(tf.constant([[10.]]), [1, tf.shape(probe_images)[0]])\n idx = tf.squeeze(tf.random.categorical(probe, n_probe_to_mix))\n\n l_images = tf.reshape(tf.gather(probe_images, idx), im_shape)\n l_labels = tf.reshape(tf.gather(probe_labels, idx), (-1,))\n\n u_logits = tf.concat([logits, aug_logits], axis=0)\n u_images = tf.concat([images, aug_images], axis=0)\n\n losses = []\n if FLAGS.ce_factor > 0:\n logging.info('Use crossentropy minimization loss {}'.format(\n FLAGS.ce_factor))\n ce_min_loss = self.crossentropy_minimize(u_logits, u_images, l_images,\n l_labels)\n losses.append(ce_min_loss)\n else:\n losses.append(tf.constant(0, tf.float32))\n\n if FLAGS.consistency_factor > 0:\n logging.info('Use consistency loss {}'.format(FLAGS.consistency_factor))\n consis_loss = self.consistency_loss(logits, aug_logits)\n losses.append(consis_loss)\n\n else:\n losses.append(tf.constant(0, tf.float32))\n\n return losses\n\n def meta_optimize(self):\n \"\"\"Meta optimization step.\"\"\"\n\n probe_images, probe_labels = self.probe_images, self.probe_labels\n labels = self.labels\n net = self.net\n logits = self.logits\n gate_gradients = 1\n\n batch_size = int(self.batch_size / self.strategy.num_replicas_in_sync)\n init_eps_val = float(1) / batch_size\n\n meta_net = networks.MetaImage(self.net, name='meta_model')\n\n if FLAGS.meta_momentum and not self.optimizer.variables():\n # Initializing momentum state of optimizer for meta momentum update.\n # It is a hacky implementation\n logging.info('Pre-initialize optimizer momentum states.')\n idle_net_cost = tf.losses.sparse_softmax_cross_entropy(\n self.labels, logits)\n tmp_var_grads = self.optimizer.compute_gradients(\n tf.reduce_mean(idle_net_cost), net.trainable_variables)\n self.optimizer.apply_gradients(tmp_var_grads)\n\n with tf.name_scope('coefficient'):\n # Data weight coefficient\n target = tf.constant(\n [init_eps_val] * batch_size,\n shape=(batch_size,),\n dtype=np.float32,\n name='weight')\n # Data re-labeling coefficient\n eps = tf.constant(\n [FLAGS.grad_eps_init] * batch_size,\n shape=(batch_size,),\n dtype=tf.float32,\n name='eps')\n\n onehot_labels = tf.one_hot(labels, self.dataset.num_classes)\n onehot_labels = tf.cast(onehot_labels, tf.float32)\n eps_k = tf.reshape(eps, [batch_size, 1])\n\n mixed_labels = eps_k * onehot_labels + (1 - eps_k) * self.guessed_label\n # raw softmax loss\n log_softmax = tf.nn.log_softmax(logits)\n net_cost = -tf.reduce_sum(mixed_labels * log_softmax, 1)\n\n lookahead_loss = tf.reduce_sum(tf.multiply(target, net_cost))\n lookahead_loss = lookahead_loss + net.regularization_loss\n\n with tf.control_dependencies([lookahead_loss]):\n train_vars = net.trainable_variables\n var_grads = tf.gradients(\n lookahead_loss, train_vars, gate_gradients=gate_gradients)\n\n static_vars = []\n for i in range(len(train_vars)):\n if FLAGS.meta_momentum > 0:\n actual_grad = self.meta_momentum_update(var_grads[i],\n train_vars[i].name,\n self.optimizer)\n static_vars.append(\n tf.math.subtract(train_vars[i],\n FLAGS.meta_stepsize * actual_grad))\n else:\n static_vars.append(\n tf.math.subtract(train_vars[i],\n FLAGS.meta_stepsize * var_grads[i]))\n # new style\n meta_net.add_variable_alias(\n static_vars[-1], var_name=train_vars[i].name)\n\n for uv in net.updates_variables:\n meta_net.add_variable_alias(\n uv, var_name=uv.name, var_type='updates_variables')\n meta_net.verbose()\n\n with tf.control_dependencies(static_vars):\n g_logits = meta_net(\n probe_images, name='meta_model', reuse=True, training=True)\n\n desired_y = tf.one_hot(probe_labels, self.dataset.num_classes)\n meta_loss = tf.nn.softmax_cross_entropy_with_logits_v2(\n desired_y, g_logits)\n meta_loss = tf.reduce_mean(meta_loss, name='meta_loss')\n meta_loss = meta_loss + meta_net.get_regularization_loss(net.wd)\n meta_acc, meta_acc_op = tf.metrics.accuracy(probe_labels,\n tf.argmax(g_logits, axis=1))\n\n with tf.control_dependencies([meta_loss] + [meta_acc_op]):\n meta_train_vars = meta_net.trainable_variables\n grad_meta_vars = tf.gradients(\n meta_loss, meta_train_vars, gate_gradients=gate_gradients)\n grad_target, grad_eps = tf.gradients(\n static_vars, [target, eps],\n grad_ys=grad_meta_vars,\n gate_gradients=gate_gradients)\n # updates weight\n raw_weight = target - grad_target\n raw_weight = raw_weight - init_eps_val\n unorm_weight = tf.clip_by_value(\n raw_weight, clip_value_min=0, clip_value_max=float('inf'))\n norm_c = tf.reduce_sum(unorm_weight)\n weight = tf.divide(unorm_weight, norm_c + 0.00001)\n\n # gets new lambda by the sign of gradient\n new_eps = tf.where(grad_eps < 0, x=tf.ones_like(eps), y=tf.zeros_like(eps))\n\n return tf.stop_gradient(weight), tf.stop_gradient(\n new_eps), meta_loss, meta_acc\n\n def train_step(self):\n\n def step_fn(inputs):\n \"\"\"Step functon.\n\n Args:\n inputs: inputs from data iterator\n\n Returns:\n a set of variables want to observe in Tensorboard\n \"\"\"\n net = self.net\n (all_images, labels), (self.probe_images, self.probe_labels) = inputs\n assert len(all_images.shape) == 5\n images, self.aug_images = all_images[:, 0], all_images[:, 1]\n\n self.images, self.labels = images, labels\n batch_size = int(self.batch_size / self.strategy.num_replicas_in_sync)\n\n logits = net(images, name='model', reuse=tf.AUTO_REUSE, training=True)\n self.logits = logits\n\n # other losses\n # initialized first to use self.guessed_label for meta step\n xe_loss, cs_loss = self.unsupervised_loss()\n\n # meta optimization\n weight, eps, meta_loss, meta_acc = self.meta_optimize()\n\n ## losses w.r.t new weight and loss\n onehot_labels = tf.one_hot(labels, self.dataset.num_classes)\n onehot_labels = tf.cast(onehot_labels, tf.float32)\n eps_k = tf.reshape(eps, [batch_size, 1])\n\n mixed_labels = tf.math.add(\n eps_k * onehot_labels, (1 - eps_k) * self.guessed_label,\n name='mixed_labels')\n net_cost = tf.losses.softmax_cross_entropy(\n mixed_labels, logits, reduction=tf.losses.Reduction.NONE)\n # loss with initial weight\n net_loss1 = tf.reduce_mean(net_cost)\n\n # loss with initial eps\n init_eps = tf.constant(\n [FLAGS.grad_eps_init] * batch_size, dtype=tf.float32)\n init_eps = tf.reshape(init_eps, (-1, 1))\n init_mixed_labels = tf.math.add(\n init_eps * onehot_labels, (1 - init_eps) * self.guessed_label,\n name='init_mixed_labels')\n\n net_cost2 = tf.losses.softmax_cross_entropy(\n init_mixed_labels, logits, reduction=tf.losses.Reduction.NONE)\n net_loss2 = tf.reduce_sum(tf.math.multiply(net_cost2, weight))\n\n net_loss = (net_loss1 + net_loss2) / 2\n\n net_loss = net_loss + tf.add_n([xe_loss, cs_loss])\n net_loss += net.regularization_loss\n net_loss /= self.strategy.num_replicas_in_sync\n\n # rescale by gpus\n with tf.control_dependencies(net.updates):\n net_grads = tf.gradients(net_loss, net.trainable_variables)\n minimizer_op = self.optimizer.apply_gradients(\n zip(net_grads, net.trainable_variables),\n global_step=self.global_step)\n\n with tf.control_dependencies([minimizer_op]):\n train_op = self.ema.apply(net.trainable_variables)\n\n acc_op, acc_update_op = self.acc_func(labels, tf.argmax(logits, axis=1))\n\n with tf.control_dependencies([train_op, acc_update_op]):\n return (tf.identity(net_loss), tf.identity(xe_loss),\n tf.identity(cs_loss), tf.identity(meta_loss),\n tf.identity(meta_acc), tf.identity(acc_op), tf.identity(weight),\n tf.identity(labels))\n\n # end of parallel\n (pr_net_loss, pr_xe_loss, pr_cs_loss, pr_metaloss, pr_metaacc, pr_acc,\n pr_weight, pr_labels) = self.strategy.run(\n step_fn,\n args=((next(self.train_input_iterator),\n next(self.probe_input_iterator)),))\n # collect device variables\n weights = self.strategy.unwrap(pr_weight)\n weights = tf.concat(weights, axis=0)\n labels = self.strategy.unwrap(pr_labels)\n labels = tf.concat(labels, axis=0)\n\n mean_acc = self.strategy.reduce(tf.distribute.ReduceOp.MEAN, pr_acc)\n mean_metaacc = self.strategy.reduce(tf.distribute.ReduceOp.MEAN, pr_metaacc)\n net_loss = self.strategy.reduce(tf.distribute.ReduceOp.MEAN, pr_net_loss)\n xe_loss = self.strategy.reduce(tf.distribute.ReduceOp.MEAN, pr_xe_loss)\n cs_loss = self.strategy.reduce(tf.distribute.ReduceOp.MEAN, pr_cs_loss)\n meta_loss = self.strategy.reduce(tf.distribute.ReduceOp.MEAN, pr_metaloss)\n\n # The following add variables for tensorboard visualization\n merges = []\n merges.append(tf.summary.scalar('acc/train', mean_acc))\n merges.append(tf.summary.scalar('loss/xemin', xe_loss))\n merges.append(tf.summary.scalar('loss/consistency', cs_loss))\n merges.append(tf.summary.scalar('loss/net', net_loss))\n merges.append(tf.summary.scalar('loss/meta', meta_loss))\n merges.append(tf.summary.scalar('acc/meta', mean_metaacc))\n if hasattr(self, 'eval_acc_on_train'):\n merges.append(\n tf.summary.scalar('acc/eval_on_train', self.eval_acc_on_train[0]))\n merges.append(\n tf.summary.scalar('acc/eval_on_train_top5',\n self.eval_acc_on_train[1]))\n merges.append(\n tf.summary.scalar('acc/num_eval', self.eval_acc_on_train[2]))\n\n zw_inds = tf.squeeze(\n tf.where(tf.less_equal(weights, 0), name='zero_weight_index'))\n merges.append(\n tf.summary.scalar(\n 'weights/zeroratio',\n tf.math.divide(\n tf.cast(tf.size(zw_inds), tf.float32),\n tf.cast(tf.size(weights), tf.float32))))\n\n self.epoch_var = tf.cast(self.global_step / self.iter_epoch, tf.float32)\n merges.append(tf.summary.scalar('epoch', self.epoch_var))\n merges.append(tf.summary.scalar('learningrate', self.learning_rate))\n summary = tf.summary.merge(merges)\n\n return [\n net_loss, meta_loss, xe_loss, cs_loss, mean_acc, mean_metaacc, summary,\n weights\n ]\n\n def train(self):\n self.set_input()\n self.build_graph()\n\n with self.strategy.scope():\n self.initialize_variables()\n\n self.sess.run([\n self.train_input_iterator.initializer,\n self.probe_input_iterator.initializer\n ])\n self.sess.run([self.eval_input_iterator.initializer])\n\n logging.info('Finish variable initialization')\n iter_epoch = self.iter_epoch\n\n self.saver = tf.train.Saver(max_to_keep=4)\n self.load_model()\n FLAGS.restore_step = self.global_step.eval()\n\n pbar = tqdm(total=(FLAGS.max_iteration - FLAGS.restore_step))\n for iteration in range(FLAGS.restore_step + 1, FLAGS.max_iteration + 1):\n self.update_learning_rate(iteration)\n (lr, net_loss, meta_loss, xe_loss, cs_loss, acc, meta_acc,\n merged_summary, weights) = (\n self.sess.run([self.learning_rate] + self.train_op))\n pbar.update(1)\n message = ('Epoch {}[{}/{}] lr{:.3f} meta_loss:{:.2f} loss:{:.2f} '\n 'mc_loss:{:.2f} uc_loss:{:.2f} weight{:.2f}({:.2f}) '\n 'acc:{:.2f} mata_acc{:.2f}').format(iteration // iter_epoch,\n iteration % iter_epoch,\n iter_epoch, lr,\n float(meta_loss),\n float(net_loss),\n float(xe_loss),\n float(cs_loss),\n float(np.mean(weights)),\n float(np.std(weights)),\n float(acc),\n float(meta_acc))\n pbar.set_description(message)\n if iteration % 100 == 0 or iteration == 1:\n self.summary_writer.add_summary(merged_summary, iteration)\n\n # checkpoint\n if self.time_for_evaluation(iteration, lr):\n logging.info(message)\n self.evaluate(iteration, lr)\n self.save_model(iteration)\n self.summary_writer.flush()\n # end of iterations\n pbar.close()\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nr\"\"\"Implementation of Splitter, a method for learning node representations that capture multiple contexts.\n\n===============================\n\nThis is part of the implementation accompanying the WWW 2019 paper, [_Is a\nSingle Embedding Enough? Learning Node Representations that Capture Multiple\nSocial Contexts_](https://ai.google/research/pubs/pub46238).\n\nCiting\n------\nIf you find _Splitter_ or the associated resources useful in your research,\nwe ask that you cite the following paper:\n> Epasto, A., Perozzi, B., (2019).\n> Is a Single Embedding Enough? Learning Node Representations that Capture\nMultiple Social Contexts.\n> In _The Web Conference_.\n\nExample execution\n------\npython3 -m graph_embedding.persona.splitter\n --input_graph=${graph} \\\n --output_embedding=${embedding_output}\n\nWhere ${graph} is the path to a text file containing the graph and\n${embedding_output} is the path to the output embedding.\n\nThe graph input format is a text file containing one edge per row represented\nas its pair of node ids. The graph is supposed to be undirected.\nFor instance the file:\n1 2\n2 3\nrepresents the triangle 1, 2, 3.\n\nThe output embedding format is a text file containing for each row one\n(overlapping) cluster represented as the space-separted list of node ids in the\ncluster.\n\nFor the persona decomposition, a number of different local clustering\nalgorithms can be used. Supported out of the box are\"\n\nconnected_components: the standard connected component algorithm.\nlabel_prop: a label propagation based algorithm\n (nx.label_prop.label_propagation_communities).\nmodularity: an algorithm optimizing modularity\n (nx.modularity.greedy_modularity_communities).\n\"\"\"\n#pylint: skip-file\nfrom __future__ import print_function\n\nimport os.path\nimport random\n\nfrom . import persona\nfrom absl import app\nfrom absl import flags\nfrom gensim.models import Word2Vec\nimport networkx as nx\nimport numpy\nfrom six.moves import xrange\nfrom .third_party import persona2vec\n\nflags.DEFINE_string('output_persona_embedding', None, 'model.')\n\nflags.DEFINE_string('output_embedding_prior', None, 'model.')\n\nflags.DEFINE_integer('embedding_dim', 128, 'embedding_dim.')\n\nflags.DEFINE_integer('walk_length', 10, 'walk_length.')\n\nflags.DEFINE_integer('num_walks_node', 40, 'num_walks_node.')\n\nflags.DEFINE_integer('iterations', 10, 'iterations.')\n\nflags.DEFINE_float('constraint_learning_rate_scaling_factor', 0.1,\n 'learning rate constraint.')\n\nflags.DEFINE_integer('seed', 1, 'seed.')\n\nflags.DEFINE_integer('window_size', 5, 'window size over random walk.')\n\nFLAGS = flags.FLAGS\n\n\ndef Splitter(graph,\n embedding_dim=128,\n walk_length=40,\n num_walks_node=10,\n constraint_learning_rate_scaling_factor=0.1,\n iterations=10,\n seed=None,\n window_size=5,\n local_clustering_fn=persona._CLUSTERING_FN['label_prop']):\n \"\"\"This function runs the Splitter algorithm.\n\n Given a graph, it decomposes the nodes into personas. It then embeds the\n original graph, and the persona graph to learn a representation that has\n multiple senses.\n\n Args:\n graph: Undirected graph represented as a dictionary of lists that maps each\n node id its list of neighbor ids;\n embedding_dim: The dimensionality of the embedding to use.\n walk_length: The length of the random walks to generate from each node.\n num_walks_node: The number of walks to start at each node.\n constraint_learning_rate_scaling_factor: Strength of the constraint that\n personas predict their original node.\n iterations: Number of iterations to run for.\n seed: Initial seed to use.\n window_size: Size of the window around the source node in the random walk.\n local_clustering_fn: A non-overlapping clustering algorithm function that\n takes in input a nx.Graph and outputs the a clustering. The output format\n is a list containing each partition as element. Each partition is in turn\n represented as a list of node ids. The default function is the networkx\n label_propagation_communities clustering algorithm.\n\n Returns:\n A pair of (graph, mapping) where \"graph\" is an nx.Graph instance of the\n persona graph (which contains different nodes from the original graph) and\n \"mapping\" is a dict of the new node ids to the node ids in the original\n graph.The persona graph as nx.Graph, and the mapping of persona nodes to\n original node ids.\n \"\"\"\n to_return = {}\n\n print('Running persona decomposition...')\n # perform persona decomposition\n persona_graph, persona_id_mapping = persona.CreatePersonaGraph(\n graph, local_clustering_fn, persona_start_id=graph.number_of_nodes() + 1)\n\n # make sure ids don't collide between persona graph & input\n persona_id_set = set()\n graph_id_set = set()\n\n for x in graph:\n for y in graph[x]:\n graph_id_set.add(str(y))\n\n for x in persona_graph:\n for y in persona_graph[x]:\n persona_id_set.add(str(y))\n\n assert len(graph_id_set & persona_id_set\n ) == 0, 'intersection between graph ids and persona ids is non-zero'\n\n to_return['persona_graph'] = persona_graph\n to_return['persona_id_mapping'] = persona_id_mapping\n\n # generate random walks\n print('Generating persona random walks...')\n sentences_persona = list(\n GenerateRandomWalks(\n persona_graph, walks_per_node=num_walks_node,\n walk_length=walk_length))\n random.shuffle(sentences_persona)\n\n print('Generating regular random walks...')\n sentences_regular = list(\n GenerateRandomWalks(\n graph, walks_per_node=num_walks_node, walk_length=walk_length))\n random.shuffle(sentences_regular)\n\n # initial embedding for prior\n regular_model = RunDeepWalk(\n sentences_regular, embedding_dim, window_size, iterations, seed=seed)\n\n # persona embedding\n persona_model = RunPersona2Vec(\n persona_id_mapping,\n sentences_persona,\n embedding_dim,\n window_size,\n iterations,\n constraint_learning_rate_scaling_factor,\n prior_model=regular_model,\n seed=seed)\n\n to_return['regular_model'] = regular_model\n to_return['persona_model'] = persona_model\n\n return to_return\n\n\ndef SampleNextNode(graph, node):\n d = graph[node]\n v_list = list(d.keys())\n num = len(v_list)\n if num > 0:\n random_value = numpy.random.choice(num)\n return v_list[random_value]\n else:\n return node\n\n\ndef GenerateRandomWalks(graph, walks_per_node, walk_length):\n for node in graph:\n for _ in xrange(walks_per_node):\n walk = [node]\n for _ in xrange(walk_length):\n walk.append(SampleNextNode(graph, walk[-1]))\n yield walk\n\n\ndef RunPersona2Vec(persona_id_mapping,\n sentences,\n embedding_dim,\n window_size,\n iterations,\n constraint_learning_rate_scaling_factor,\n seed=0,\n prior_model=None):\n \"\"\"Runs Persona2Vec implementation.\"\"\"\n persona_map = {}\n for p, node in persona_id_mapping.items():\n if node not in persona_map:\n persona_map[node] = []\n persona_map[node].append(p)\n\n node_init_cnt = 0\n persona_init_cnt = 0\n\n initialization_map = {}\n if prior_model:\n for node in persona_map:\n initialization_map[node] = prior_model[node]\n node_init_cnt += 1\n for p in persona_map[node]:\n initialization_map[p] = prior_model[node]\n persona_init_cnt += 1\n\n print('Initialized %d nodes' % node_init_cnt)\n print('Initialized %d personas' % persona_init_cnt)\n\n model = persona2vec.Persona2Vec(\n initial_weight_map=initialization_map,\n extra_constraint_map=persona_map,\n constraint_learning_rate_scaling_factor=constraint_learning_rate_scaling_factor,\n sentences=sentences,\n min_count=0,\n sg=1,\n hs=1,\n negative=0,\n size=embedding_dim,\n seed=seed,\n sample=0,\n workers=12,\n window=window_size,\n iter=iterations)\n\n return model\n\n\ndef RunDeepWalk(sentences, embedding_dim, window_size, iterations, seed=0):\n \"\"\"Runs standard DeepWalk model.\"\"\"\n model = Word2Vec(\n sentences=sentences,\n min_count=0,\n sg=1,\n hs=1,\n negative=0,\n size=embedding_dim,\n seed=seed,\n sample=0,\n workers=12,\n window=window_size,\n iter=iterations)\n\n return model\n\n\ndef main(argv=()):\n del argv # Unused.\n\n # confirm output paths exist\n assert os.path.exists(os.path.dirname(FLAGS.output_persona_embedding))\n if FLAGS.output_embedding_prior:\n assert os.path.exists(os.path.dirname(FLAGS.output_embedding_prior))\n if FLAGS.output_persona_graph:\n assert os.path.exists(os.path.dirname(FLAGS.output_persona_graph))\n if FLAGS.output_persona_graph_mapping:\n assert os.path.exists(os.path.dirname(FLAGS.output_persona_graph_mapping))\n\n print('Loading graph...')\n graph = nx.read_edgelist(FLAGS.input_graph, create_using=nx.Graph)\n\n # read persona args\n local_clustering_fn = persona._CLUSTERING_FN[\n FLAGS.local_clustering_method]\n\n print('Running splitter...')\n splitter = Splitter(\n graph,\n embedding_dim=FLAGS.embedding_dim,\n walk_length=FLAGS.walk_length,\n num_walks_node=FLAGS.num_walks_node,\n constraint_learning_rate_scaling_factor=FLAGS\n .constraint_learning_rate_scaling_factor,\n iterations=FLAGS.iterations,\n seed=FLAGS.seed,\n local_clustering_fn=local_clustering_fn)\n\n # output embeddings\n splitter['persona_model'].save_word2vec_format(\n open(FLAGS.output_persona_embedding, 'wb'))\n\n # optional output\n if FLAGS.output_embedding_prior is not None:\n splitter['regular_model'].save_word2vec_format(\n open(FLAGS.output_embedding_prior, 'wb'))\n\n if FLAGS.output_persona_graph is not None:\n nx.write_edgelist(splitter['persona_graph'], FLAGS.output_persona_graph)\n\n if FLAGS.output_persona_graph_mapping is not None:\n with open(FLAGS.output_persona_graph_mapping, 'w') as outfile:\n for persona_node, original_node in splitter['persona_id_mapping'].items():\n outfile.write('{} {}\\n'.format(persona_node, original_node))\n\n return 0\n\n\nif __name__ == '__main__':\n flags.mark_flag_as_required('input_graph')\n flags.mark_flag_as_required('output_persona_embedding')\n flags.mark_flag_as_required('output_persona_graph_mapping')\n app.run(main)\n", "# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Used to unify various data providers under a single namespace.\"\"\"\n\nimport logging\nimport gin\nimport gin.tf\nimport tensorflow as tf\n\n\nfrom tf3d.datasets import rio # pylint: disable=g-bad-import-order\nfrom tf3d.datasets import scannet_scene # pylint: disable=g-bad-import-order\nfrom tf3d.datasets import waymo_object_per_frame # pylint: disable=g-bad-import-order\n\n\n_DATASET_MAP = {\n 'rio': rio,\n 'scannet_scene': scannet_scene,\n 'waymo_object_per_frame': waymo_object_per_frame,\n}\n\n\ndef get_file_pattern(dataset_name,\n split_name,\n dataset_format=None,\n dataset_dir=None):\n \"\"\"Returns the file pattern given the dataset name and split.\n\n Args:\n dataset_name: Dataset name.\n split_name: A train/test split name.\n dataset_format: A str of the dataset format.\n dataset_dir: The base directory of the dataset sources.\n\n Returns:\n A string containing the file pattern.\n \"\"\"\n if dataset_dir is not None:\n return _DATASET_MAP[dataset_name].get_file_pattern(\n split_name=split_name,\n dataset_dir=dataset_dir,\n dataset_format=dataset_format)\n else:\n return _DATASET_MAP[dataset_name].get_file_pattern(split_name=split_name)\n\n\ndef get_decode_fn(dataset_name,\n include_saved_predictions=False):\n decoder_params = {}\n if include_saved_predictions:\n decoder_params['include_saved_predictions'] = include_saved_predictions\n return _DATASET_MAP[dataset_name].get_decode_fn(**decoder_params)\n\n\ndef get_items_to_descriptions(dataset_name):\n return _DATASET_MAP[dataset_name].ITEMS_TO_DESCRIPTIONS\n\n\ndef get_num_samples(dataset_name, split_name):\n return _DATASET_MAP[dataset_name].SPLITS_TO_SIZES[split_name]\n\n\ndef _get_params(dataset_name):\n params = {}\n if _DATASET_MAP[dataset_name].IGNORE_LABEL is not None:\n params['ignore_label'] = _DATASET_MAP[dataset_name].IGNORE_LABEL\n if _DATASET_MAP[dataset_name].NUM_CLASSES is not None:\n params['num_classes'] = _DATASET_MAP[dataset_name].NUM_CLASSES\n return params\n\n\n\n\ndef _read_data(file_read_func, file_pattern, shuffle, num_readers,\n filenames_shuffle_buffer_size, num_epochs, read_block_length,\n shuffle_buffer_size):\n \"\"\"Gets a dataset tuple.\n\n Args:\n file_read_func: Function to use in tf.contrib.data.parallel_interleave, to\n read every individual file into a tf.data.Dataset.\n file_pattern: A string containing a file pattern that corresponds to a set\n of files containing the data.\n shuffle: Whether data should be processed in the order they are read in, or\n shuffled randomly.\n num_readers: Number of file shards to read in parallel.\n filenames_shuffle_buffer_size: Buffer size to be used when shuffling file\n names.\n num_epochs: The number of times a data source is read. If set to zero, the\n data source will be reused indefinitely.\n read_block_length: Number of records to read from each reader at once.\n shuffle_buffer_size: Buffer size to be used when shuffling.\n\n Returns:\n A tf.data.Dataset.\n \"\"\"\n # Shard, shuffle, and read files.\n dataset = tf.data.Dataset.list_files(\n file_pattern=file_pattern, shuffle=shuffle)\n if shuffle:\n dataset = dataset.shuffle(filenames_shuffle_buffer_size)\n elif num_readers > 1:\n logging.warning('`shuffle` is false, but the input data stream is '\n 'still slightly shuffled since `num_readers` > 1.')\n dataset = dataset.repeat(num_epochs or None)\n\n records_dataset = dataset.interleave(\n map_func=file_read_func,\n cycle_length=num_readers,\n block_length=read_block_length,\n num_parallel_calls=tf.data.experimental.AUTOTUNE,\n deterministic=shuffle)\n\n if shuffle:\n records_dataset = records_dataset.shuffle(shuffle_buffer_size)\n return records_dataset\n\n\n\n\ndef tfrecord_read_fn(filename):\n return tf.data.TFRecordDataset(filename).prefetch(1)\n\n\n@gin.configurable(\n 'get_tf_data_decoder', denylist=['batch_size', 'is_training'])\ndef get_tf_data_decoder(dataset_format,\n decode_fn,\n file_pattern,\n batch_size,\n is_training,\n preprocess_fn=None,\n feature_keys=None,\n label_keys=None,\n num_readers=64,\n filenames_shuffle_buffer_size=100,\n num_epochs=0,\n read_block_length=32,\n shuffle_buffer_size=256,\n num_parallel_batches=8,\n num_prefetch_batches=2,\n ):\n \"\"\"Reads a tf.data.Dataset given a decoder and outputs tensor dictionaries.\n\n Args:\n dataset_format: Currently 'tfexample' and 'recordio' are supported.\n decode_fn: Decoder function.\n file_pattern: A string containing the file pattern that represents the\n sstable.\n batch_size: Batch size.\n is_training: Whether reading data in training mode or not. If in training,\n data will be shuffled and if not it won't be shuffled. Also in training\n preprocessing can act different than in eval time.\n preprocess_fn: A function that preprocesses data.\n feature_keys: Either None or a list[str] with keys in features.\n label_keys: Either None or a list[str] with keys in labels.\n num_readers: Number of file shards to read in parallel.\n filenames_shuffle_buffer_size: Buffer size to be used when shuffling file\n names.\n num_epochs: The number of times a data source is read. If set to zero, the\n data source will be reused indefinitely.\n read_block_length: Number of records to read from each reader at once.\n shuffle_buffer_size: Buffer size to be used when shuffling.\n num_parallel_batches: Number of batches to produce in parallel. If this is\n run on a 2x2 TPU set this to 8.\n num_prefetch_batches: Number of batches to prefetch. Prefetch decouples\n input pipeline and model so they can be pipelined resulting in higher\n throughput. Set this to a small constant and increment linearly until the\n improvements become marginal or you exceed your cpu memory budget. Setting\n this to -1, automatically tunes this value for you.\n\n Returns:\n Return a tf.data.dataset where each element is a dictionary with features\n and labels; if not executing eagerly i.e. under tf1 environment, returns a\n dictionary with features and labels instead.\n \"\"\"\n\n def _process_fn(key, value):\n \"\"\"Sets up tf graph that decodes and preprocesses input.\"\"\"\n tensors_dict = decode_fn(value)\n if preprocess_fn is None:\n return tensors_dict\n else:\n output_keys = feature_keys + label_keys\n return preprocess_fn(\n inputs=tensors_dict, output_keys=output_keys, is_training=is_training)\n\n if dataset_format == 'tfrecord':\n read_fn = tfrecord_read_fn\n else:\n raise ValueError('Unknown dataset type')\n\n # Read data\n dataset = _read_data(\n file_read_func=read_fn,\n file_pattern=file_pattern,\n num_readers=num_readers,\n shuffle=is_training,\n filenames_shuffle_buffer_size=filenames_shuffle_buffer_size,\n num_epochs=num_epochs,\n read_block_length=read_block_length,\n shuffle_buffer_size=shuffle_buffer_size)\n\n if dataset_format == 'tfrecord':\n # insert dummy key to form (key, value pair)\n dataset = dataset.map(lambda x: (None, x))\n\n # Preprocess data\n dataset_dict = tf.data.Dataset.batch(\n dataset.map(\n _process_fn, num_parallel_calls=num_parallel_batches),\n batch_size=batch_size,\n drop_remainder=True)\n dataset_dict = dataset_dict.prefetch(num_prefetch_batches)\n\n return dataset_dict\n\n\n\n\n@gin.configurable(denylist=['batch_size', 'is_training'])\ndef get_tf_data_dataset(dataset_name,\n split_name,\n batch_size,\n is_training,\n preprocess_fn=None,\n feature_keys=None,\n label_keys=None,\n num_readers=64,\n filenames_shuffle_buffer_size=100,\n num_epochs=0,\n read_block_length=32,\n shuffle_buffer_size=256,\n num_parallel_batches=8,\n num_prefetch_batches=2,\n dataset_dir=None,\n dataset_format=None):\n \"\"\"Reads a tf.data.Dataset given a dataset name and split and outputs tensors.\n\n Args:\n dataset_name: Dataset name.\n split_name: A train/test split name.\n batch_size: Batch size.\n is_training: Whether reading data in training mode or not. If in training,\n data will be shuffled and if not it won't be shuffled. Also in training\n preprocessing can act different than in eval time.\n preprocess_fn: A function that preprocesses data.\n feature_keys: Either None or a list[str] with keys in features.\n label_keys: Either None or a list[str] with keys in labels.\n num_readers: Number of file shards to read in parallel.\n filenames_shuffle_buffer_size: Buffer size to be used when shuffling file\n names.\n num_epochs: The number of times a data source is read. If set to zero, the\n data source will be reused indefinitely.\n read_block_length: Number of records to read from each reader at once.\n shuffle_buffer_size: Buffer size to be used when shuffling.\n num_parallel_batches: Number of batches to produce in parallel. If this is\n run on a 2x2 TPU set this to 8.\n num_prefetch_batches: Number of batches to prefetch. Prefetch decouples\n input pipeline and model so they can be pipelined resulting in higher\n throughput. Set this to a small constant and increment linearly until the\n improvements become marginal or you exceed your cpu memory budget. Setting\n this to -1, automatically tunes this value for you.\n dataset_dir: The base directory of the dataset sources.\n dataset_format: If not None, a str of dataset format, can be 'tfrecord',\n 'sstable' or 'recordio'.\n\n Returns:\n Return a tf.data.dataset where each element is a dictionary with features\n and labels; if not executing eagerly i.e. under tf1 environment, returns a\n dictionary with features and labels instead.\n \"\"\"\n if dataset_format is None:\n dataset_format = _DATASET_MAP[dataset_name].DATASET_FORMAT\n file_pattern = get_file_pattern(\n dataset_name=dataset_name,\n split_name=split_name,\n dataset_dir=dataset_dir,\n dataset_format=dataset_format)\n\n decode_fn = get_decode_fn(dataset_name=dataset_name)\n if feature_keys is None:\n feature_keys = list(_DATASET_MAP[dataset_name].get_feature_keys())\n if label_keys is None:\n label_keys = list(_DATASET_MAP[dataset_name].get_label_keys())\n return get_tf_data_decoder(\n dataset_format=dataset_format,\n decode_fn=decode_fn,\n file_pattern=file_pattern,\n batch_size=batch_size,\n is_training=is_training,\n preprocess_fn=preprocess_fn,\n feature_keys=feature_keys,\n label_keys=label_keys,\n num_readers=num_readers,\n filenames_shuffle_buffer_size=filenames_shuffle_buffer_size,\n num_epochs=num_epochs,\n read_block_length=read_block_length,\n shuffle_buffer_size=shuffle_buffer_size,\n num_parallel_batches=num_parallel_batches,\n num_prefetch_batches=num_prefetch_batches)\n\n\n" ]
[ [ "tensorflow.make_tensor_proto", "tensorflow.io.gfile.GFile", "tensorflow.constant_initializer", "tensorflow.keras.callbacks.TerminateOnNaN", "tensorflow.ones", "tensorflow.logical_not", "tensorflow.reshape", "tensorflow.keras.layers.Dense", "tensorflow.py_function", "tensorflow.keras.callbacks.ModelCheckpoint", "tensorflow.executing_eagerly", "tensorflow.nn.embedding_lookup", "tensorflow.greater", "tensorflow.keras.layers.BatchNormalization", "tensorflow.cast", "tensorflow.keras.callbacks.experimental.BackupAndRestore", "tensorflow.distribute.experimental.MultiWorkerMirroredStrategy", "tensorflow.shape", "tensorflow.concat", "tensorflow.GradientTape", "tensorflow.train.load_checkpoint", "tensorflow.add_n", "tensorflow.keras.layers.Conv2D", "tensorflow.math.is_nan", "tensorflow.pad", "tensorflow.keras.optimizers.Adam", "tensorflow.nn.dropout", "numpy.array", "tensorflow.distribute.MirroredStrategy", "tensorflow.zeros", "tensorflow.nn.relu", "tensorflow.expand_dims", "tensorflow.where", "tensorflow.summary.scalar", "numpy.stack", "tensorflow.name_scope", "tensorflow.reduce_sum", "tensorflow.clip_by_global_norm", "tensorflow.nn.sparse_softmax_cross_entropy_with_logits", "tensorflow.keras.metrics.Mean", "tensorflow.not_equal", "numpy.rank", "tensorflow.greater_equal", "tensorflow.equal", "tensorflow.reduce_any", "tensorflow.keras.backend.batch_set_value", "tensorflow.keras.initializers.RandomNormal", "tensorflow.reduce_max", "tensorflow.gather", "tensorflow.maximum" ], [ "numpy.array", "numpy.logspace", "numpy.exp", "numpy.log" ], [ "tensorflow.data.TFRecordDataset", "tensorflow.io.gfile.glob", "tensorflow.io.FixedLenFeature", "tensorflow.reshape", "tensorflow.cast", "tensorflow.constant", "tensorflow.image.per_image_standardization", "tensorflow.parse_single_example", "tensorflow.io.decode_png" ], [ "numpy.abs" ], [ "tensorflow.nn.softmax_cross_entropy_with_logits", "numpy.tile", "numpy.mean", "tensorflow.nn.softmax", "tensorflow.one_hot", "tensorflow.global_variables_initializer", "tensorflow.cast", "tensorflow.set_random_seed", "numpy.concatenate", "numpy.log", "tensorflow.argmax", "tensorflow.train.Saver", "numpy.array", "tensorflow.train.AdamOptimizer", "numpy.reshape", "tensorflow.Session", "tensorflow.placeholder", "numpy.clip", "tensorflow.nn.sparse_softmax_cross_entropy_with_logits", "numpy.sum", "tensorflow.train.MomentumOptimizer", "tensorflow.variables_initializer", "numpy.repeat", "tensorflow.reduce_mean" ], [ "numpy.concatenate", "tensorflow.concat", "numpy.set_printoptions", "tensorflow.gfile.Open", "matplotlib.pyplot.plot", "numpy.load", "numpy.mean", "tensorflow.constant", "numpy.std", "numpy.random.uniform", "matplotlib.pyplot.fill_between" ], [ "tensorflow.zeros", "tensorflow.random.experimental.get_global_generator", "tensorflow.GradientTape", "tensorflow.compat.v1.get_default_graph", "tensorflow.random.experimental.set_global_generator", "tensorflow.ones", "tensorflow.nest.flatten", "numpy.finfo", "tensorflow.control_dependencies", "tensorflow.slice", "tensorflow.cast" ], [ "tensorflow.compat.v1.reshape", "tensorflow.compat.v1.cast", "tensorflow.compat.v1.zeros", "tensorflow.compat.v1.losses.softmax_cross_entropy", "tensorflow.compat.v1.add_n", "tensorflow.compat.v1.variable_scope", "tensorflow.compat.v1.shape", "tensorflow.compat.v1.multinomial", "numpy.prod", "tensorflow.compat.v1.summary.scalar", "tensorflow.compat.v1.layers.dense", "tensorflow.compat.v1.to_int32", "tensorflow.compat.v1.constant" ], [ "tensorflow.shape", "tensorflow.concat", "tensorflow.keras.initializers.get", "tensorflow.where", "tensorflow.ones", "tensorflow.keras.layers.Dense", "tensorflow.keras.layers.Embedding", "tensorflow.reduce_max", "tensorflow.tile" ], [ "tensorflow.compat.v1.data.make_one_shot_iterator" ], [ "tensorflow.compat.v1.get_variable", "tensorflow.compat.v1.test.main" ], [ "tensorflow.reduce_sum", "tensorflow.square", "tensorflow.GradientTape", "tensorflow.summary.scalar" ], [ "tensorflow.exp", "tensorflow.abs", "tensorflow.zeros", "tensorflow.shape", "tensorflow.concat", "tensorflow.nn.relu", "tensorflow.nn.lrelu", "tensorflow.reshape", "tensorflow.variable_scope", "tensorflow.stop_gradients", "tensorflow.split", "tensorflow.reduce_mean", "tensorflow.square", "tensorflow.cast" ], [ "tensorflow.io.gfile.GFile", "tensorflow.lite.TFLiteConverter.from_saved_model", "tensorflow.lite.tools.flatbuffer_utils.read_model_with_mutable_tensors", "tensorflow.lite.tools.flatbuffer_utils.write_model", "tensorflow.python.tools.saved_model_utils.get_meta_graph_def" ], [ "tensorflow.exp", "tensorflow.linalg.norm", "tensorflow.one_hot", "tensorflow.cast", "tensorflow.einsum", "tensorflow.shape", "tensorflow.GradientTape", "tensorflow.argmax", "tensorflow.math.log", "tensorflow.constant", "tensorflow.reduce_logsumexp", "tensorflow.keras.optimizers.Adam", "tensorflow.nn.log_softmax", "tensorflow.zeros", "tensorflow.minimum", "tensorflow.eye", "numpy.zeros", "tensorflow.gather_nd", "tensorflow.expand_dims", "tensorflow.reduce_sum", "tensorflow.reduce_mean" ], [ "tensorflow.io.gfile.exists", "tensorflow.io.gfile.GFile", "tensorflow.data.TFRecordDataset" ], [ "tensorflow.nn.softmax_cross_entropy_with_logits", "tensorflow.shape", "tensorflow.concat", "tensorflow.range", "tensorflow.keras.layers.AveragePooling2D", "tensorflow.matmul", "tensorflow.keras.layers.LayerNormalization", "tensorflow.keras.Sequential", "tensorflow.keras.layers.Conv2D", "tensorflow.keras.layers.Dense", "tensorflow.math.l2_normalize", "tensorflow.keras.layers.ReLU" ], [ "tensorflow.TensorArray", "tensorflow.math.reduce_logsumexp", "tensorflow.shape", "tensorflow.zeros", "tensorflow.while_loop" ], [ "numpy.concatenate", "numpy.full", "numpy.square" ], [ "numpy.concatenate", "tensorflow.compat.v1.logging.info", "tensorflow.compat.v1.train.Example", "tensorflow.compat.v1.io.gfile.GFile", "tensorflow.compat.v1.io.gfile.glob", "tensorflow.compat.v1.python_io.TFRecordWriter", "tensorflow.compat.v1.app.run" ], [ "numpy.array", "tensorflow.compat.v2.train.Checkpoint", "tensorflow.compat.v2.train.CheckpointManager", "tensorflow.compat.v2.keras.losses.BinaryCrossentropy", "tensorflow.compat.v2.range", "numpy.random.choice", "tensorflow.compat.v2.keras.layers.Dense", "numpy.load", "tensorflow.compat.v2.expand_dims", "tensorflow.compat.v2.keras.optimizers.Adam", "numpy.float32", "tensorflow.compat.v2.enable_v2_behavior", "numpy.arange", "tensorflow.compat.v2.GradientTape", "tensorflow.compat.v2.convert_to_tensor" ], [ "numpy.float32" ], [ "numpy.random.choice", "numpy.reshape" ], [ "tensorflow.compat.v1.summary.histogram", "tensorflow.compat.v1.nn.bias_add", "tensorflow.compat.v1.nn.relu", "tensorflow.compat.v1.matmul", "tensorflow.compat.v1.trainable_variables", "tensorflow.compat.v1.device", "tensorflow.compat.v1.add_to_collection", "tensorflow.compat.v1.constant_initializer", "tensorflow.compat.v1.nn.l2_loss", "tensorflow.compat.v1.nn.lrn", "tensorflow.compat.v1.reshape", "tensorflow.compat.v1.nn.conv2d", "tensorflow.compat.v1.nn.sparse_softmax_cross_entropy_with_logits", "tensorflow.compat.v1.nn.max_pool", "tensorflow.compat.v1.no_op", "tensorflow.compat.v1.reduce_mean", "tensorflow.compat.v1.cast", "tensorflow.compat.v1.variable_scope", "tensorflow.compat.v1.control_dependencies", "tensorflow.compat.v1.summary.scalar", "tensorflow.compat.v1.get_collection", "tensorflow.compat.v1.train.ExponentialMovingAverage", "tensorflow.compat.v1.get_variable", "tensorflow.compat.v1.train.GradientDescentOptimizer", "tensorflow.compat.v1.train.exponential_decay", "tensorflow.compat.v1.truncated_normal_initializer", "tensorflow.compat.v1.nn.zero_fraction" ], [ "tensorflow.compat.v1.math.add", "tensorflow.compat.v1.ones_like", "tensorflow.compat.v1.shape", "tensorflow.compat.v1.identity", "numpy.mean", "tensorflow.compat.v1.argmax", "tensorflow.compat.v1.reduce_sum", "tensorflow.compat.v1.constant", "tensorflow.compat.v1.reshape", "tensorflow.compat.v1.random.categorical", "tensorflow.compat.v1.name_scope", "tensorflow.compat.v1.gradients", "tensorflow.compat.v1.less_equal", "tensorflow.compat.v1.summary.merge", "tensorflow.compat.v1.split", "tensorflow.compat.v1.zeros_like", "tensorflow.compat.v1.losses.sparse_softmax_cross_entropy", "tensorflow.compat.v1.multiply", "tensorflow.compat.v1.reduce_mean", "tensorflow.compat.v1.cast", "tensorflow.compat.v1.pow", "tensorflow.compat.v1.math.subtract", "tensorflow.compat.v1.train.Saver", "tensorflow.compat.v1.stop_gradient", "tensorflow.compat.v1.control_dependencies", "numpy.std", "tensorflow.compat.v1.gather", "tensorflow.compat.v1.summary.scalar", "tensorflow.compat.v1.nn.log_softmax", "tensorflow.compat.v1.nn.softmax_cross_entropy_with_logits_v2", "tensorflow.compat.v1.one_hot", "tensorflow.compat.v1.losses.softmax_cross_entropy", "tensorflow.compat.v1.size", "tensorflow.compat.v1.concat", "tensorflow.compat.v1.nn.softmax", "tensorflow.compat.v1.add_n", "tensorflow.compat.v1.divide", "tensorflow.compat.v1.math.multiply" ], [ "numpy.random.choice" ], [ "tensorflow.data.Dataset.list_files", "tensorflow.data.TFRecordDataset" ] ]
janjagusch/kartothek
[ "90ee486b73b0de84b7e69f97f8246446ba6001e2" ]
[ "kartothek/io/dask/_shuffle.py" ]
[ "from functools import partial\nfrom typing import List, Optional, Sequence, cast\n\nimport dask.array as da\nimport dask.dataframe as dd\nimport numpy as np\nimport pandas as pd\n\nfrom kartothek.core.typing import StoreFactory\nfrom kartothek.io.dask.compression import pack_payload, unpack_payload_pandas\nfrom kartothek.io_components.metapartition import MetaPartition\nfrom kartothek.io_components.write import write_partition\nfrom kartothek.serialization import DataFrameSerializer\n\n_KTK_HASH_BUCKET = \"__KTK_HASH_BUCKET\"\n\n\ndef _hash_bucket(df: pd.DataFrame, subset: Optional[Sequence[str]], num_buckets: int):\n \"\"\"\n Categorize each row of `df` based on the data in the columns `subset`\n into `num_buckets` values. This is based on `pandas.util.hash_pandas_object`\n \"\"\"\n\n if not subset:\n subset = df.columns\n hash_arr = pd.util.hash_pandas_object(df[subset], index=False)\n buckets = hash_arr % num_buckets\n\n available_bit_widths = np.array([8, 16, 32, 64])\n mask = available_bit_widths > np.log2(num_buckets)\n bit_width = min(available_bit_widths[mask])\n return df.assign(**{_KTK_HASH_BUCKET: buckets.astype(f\"uint{bit_width}\")})\n\n\ndef shuffle_store_dask_partitions(\n ddf: dd.DataFrame,\n table: str,\n secondary_indices: List[str],\n metadata_version: int,\n partition_on: List[str],\n store_factory: StoreFactory,\n df_serializer: Optional[DataFrameSerializer],\n dataset_uuid: str,\n num_buckets: int,\n sort_partitions_by: List[str],\n bucket_by: Sequence[str],\n) -> da.Array:\n \"\"\"\n Perform a dataset update with dask reshuffling to control partitioning.\n\n The shuffle operation will perform the following steps\n\n 1. Pack payload data\n\n Payload data is serialized and compressed into a single byte value using\n ``distributed.protocol.serialize_bytes``, see also ``pack_payload``.\n\n 2. Apply bucketing\n\n Hash the column subset ``bucket_by`` and distribute the hashes in\n ``num_buckets`` bins/buckets. Internally every bucket is identified by an\n integer and we will create one physical file for every bucket ID. The\n bucket ID is not exposed to the user and is dropped after the shuffle,\n before the store. This is done since we do not want to guarantee at the\n moment, that the hash function remains stable.\n\n 3. Perform shuffle (dask.DataFrame.groupby.apply)\n\n The groupby key will be the combination of ``partition_on`` fields and the\n hash bucket ID. This will create a physical file for every unique tuple\n in ``partition_on + bucket_ID``. The function which is applied to the\n dataframe will perform all necessary subtask for storage of the dataset\n (partition_on, index calc, etc.).\n\n 4. Unpack data (within the apply-function)\n\n After the shuffle, the first step is to unpack the payload data since\n the follow up tasks will require the full dataframe.\n\n 5. Pre storage processing and parquet serialization\n\n We apply important pre storage processing like sorting data, applying\n final partitioning (at this time there should be only one group in the\n payload data but using the ``MetaPartition.partition_on`` guarantees the\n appropriate data structures kartothek expects are created.).\n After the preprocessing is done, the data is serialized and stored as\n parquet. The applied function will return an (empty) MetaPartition with\n indices and metadata which will then be used to commit the dataset.\n\n Returns\n -------\n\n A dask.Array holding relevant MetaPartition objects as values\n\n \"\"\"\n if ddf.npartitions == 0:\n return ddf\n\n group_cols = partition_on.copy()\n\n if num_buckets is None:\n raise ValueError(\"``num_buckets`` must not be None when shuffling data.\")\n\n meta = ddf._meta\n meta[_KTK_HASH_BUCKET] = np.uint64(0)\n ddf = ddf.map_partitions(_hash_bucket, bucket_by, num_buckets, meta=meta)\n group_cols.append(_KTK_HASH_BUCKET)\n\n unpacked_meta = ddf._meta\n\n ddf = pack_payload(ddf, group_key=group_cols)\n ddf_grouped = ddf.groupby(by=group_cols)\n\n unpack = partial(\n _unpack_store_partition,\n secondary_indices=secondary_indices,\n sort_partitions_by=sort_partitions_by,\n table=table,\n dataset_uuid=dataset_uuid,\n partition_on=partition_on,\n store_factory=store_factory,\n df_serializer=df_serializer,\n metadata_version=metadata_version,\n unpacked_meta=unpacked_meta,\n )\n return cast(\n da.Array, # Output type depends on meta but mypy cannot infer this easily.\n ddf_grouped.apply(unpack, meta=(\"MetaPartition\", \"object\")),\n )\n\n\ndef _unpack_store_partition(\n df: pd.DataFrame,\n secondary_indices: List[str],\n sort_partitions_by: List[str],\n table: str,\n dataset_uuid: str,\n partition_on: List[str],\n store_factory: StoreFactory,\n df_serializer: DataFrameSerializer,\n metadata_version: int,\n unpacked_meta: pd.DataFrame,\n) -> MetaPartition:\n \"\"\"Unpack payload data and store partition\"\"\"\n df = unpack_payload_pandas(df, unpacked_meta)\n if _KTK_HASH_BUCKET in df:\n df = df.drop(_KTK_HASH_BUCKET, axis=1)\n return write_partition(\n partition_df=df,\n secondary_indices=secondary_indices,\n sort_partitions_by=sort_partitions_by,\n dataset_table_name=table,\n dataset_uuid=dataset_uuid,\n partition_on=partition_on,\n store_factory=store_factory,\n df_serializer=df_serializer,\n metadata_version=metadata_version,\n )\n" ]
[ [ "numpy.uint64", "pandas.util.hash_pandas_object", "numpy.array", "numpy.log2" ] ]
I-Bouros/seqgibbs
[ "139e6e5b160586a70dad9c5f7bbfe1c7e56e5cc9" ]
[ "seqgibbs/tests/test_samplers.py" ]
[ "#\n# This file is part of SEQGIBBS\n# (https://github.com/I-Bouros/seqgibbs.git) which is released\n# under the MIT license. See accompanying LICENSE for copyright\n# notice and full license details.\n#\n\nimport unittest\n\nimport scipy.stats\nimport numpy as np\nimport numpy.testing as npt\n\nimport seqgibbs as gibbs\n\n\ndef fun(x):\n \"\"\"\n Function returning the parameters of the normal sampler.\n mean = product of elements of x\n variance = exp(|x|)/(1+exp(|x|)).\n \"\"\"\n return np.prod(x), np.exp(np.sum(x))/(np.exp(np.sum(x))+1)\n\n\ndef another_fun(x):\n \"\"\"\n Function returning the parameters of the normal sampler.\n mean = sum of elements of x\n variance = exp(|x|)/(1+exp(|x|)).\n \"\"\"\n return np.sum(x), np.exp(np.sum(x))/(np.exp(np.sum(x))+1)\n\n\nclass TestSysGibbsAlgoClass(unittest.TestCase):\n \"\"\"\n Test the 'SysGibbsAlgo' class.\n \"\"\"\n def test__init__(self):\n sampler = gibbs.SysGibbsAlgo(num_dim=2)\n\n self.assertEqual(sampler.num_dim, 2)\n self.assertEqual(len(sampler.one_d_samplers), 0)\n self.assertEqual(len(sampler.chain_states), 1)\n npt.assert_array_equal(sampler.initial_state, np.zeros(2))\n npt.assert_array_equal(sampler.current_state, np.zeros(2))\n\n with self.assertRaises(TypeError):\n gibbs.SysGibbsAlgo('0', np.ones(2))\n\n with self.assertRaises(ValueError):\n gibbs.SysGibbsAlgo(0, np.ones(2))\n\n with self.assertRaises(ValueError):\n gibbs.SysGibbsAlgo(3, np.ones(2))\n\n with self.assertRaises(ValueError):\n gibbs.SysGibbsAlgo(2, [[1], [2]])\n\n def test_change_initial_state(self):\n sampler = gibbs.SysGibbsAlgo(num_dim=2)\n sampler.change_initial_state(new_state=np.array([2, 0]))\n\n npt.assert_array_equal(sampler.initial_state, np.array([2, 0]))\n\n with self.assertRaises(ValueError):\n sampler.change_initial_state(new_state=np.array([[1], [2]]))\n\n with self.assertRaises(ValueError):\n sampler.change_initial_state(new_state=np.array([1, 2, 0]))\n\n def test_add_1_d_sampler(self):\n sampler = gibbs.SysGibbsAlgo(num_dim=2, initial_state=np.array([2, 3]))\n new_1_d_sampler = gibbs.OneDimSampler(scipy.stats.norm.rvs, fun)\n\n sampler.add_1_d_sampler(new_1_d_sampler)\n self.assertEqual(len(sampler.one_d_samplers), 1)\n\n with self.assertRaises(TypeError):\n sampler.add_1_d_sampler(0)\n\n def test_run(self):\n sampler = gibbs.SysGibbsAlgo(\n num_dim=2, initial_state=np.array([2, 3]))\n\n # Feed in the two partial conditional samplers\n first_1_d_sampler = gibbs.OneDimSampler(scipy.stats.norm.rvs, fun)\n second_1_d_sampler = gibbs.OneDimSampler(\n scipy.stats.norm.rvs, another_fun)\n\n sampler.add_1_d_sampler(first_1_d_sampler)\n sampler.add_1_d_sampler(second_1_d_sampler)\n\n # Run 3 complete scan cycles of the algorithm\n sampler.run(num_cycles=3)\n last_state = sampler.chain_states[-1]\n\n self.assertEqual(len(sampler.chain_states), 4)\n self.assertEqual(len(last_state), len(sampler.initial_state))\n npt.assert_array_equal(last_state, sampler.current_state)\n\n # Run 3 more complete scan cycles of the algorithm\n sampler.run(num_cycles=3, mode='continue')\n self.assertEqual(len(sampler.chain_states), 7)\n\n # Rerun for 3 complete scan cycles of the algorithm\n sampler.run(num_cycles=3, mode='restart')\n self.assertEqual(len(sampler.chain_states), 4)\n\n with self.assertRaises(ValueError):\n sampler.run(num_cycles=3, mode='0')\n\n with self.assertRaises(TypeError):\n sampler.run(num_cycles=3.5)\n\n with self.assertRaises(ValueError):\n sampler.run(num_cycles=0, mode='restart')\n\n\nclass TestRandGibbsAlgoClass(unittest.TestCase):\n \"\"\"\n Test the 'RandGibbsAlgo' class.\n \"\"\"\n def test__init__(self):\n sampler = gibbs.RandGibbsAlgo(num_dim=2)\n\n self.assertEqual(sampler.num_dim, 2)\n self.assertEqual(len(sampler.one_d_samplers), 0)\n self.assertEqual(len(sampler.chain_states), 1)\n npt.assert_array_equal(sampler.initial_state, np.zeros(2))\n npt.assert_array_equal(sampler.current_state, np.zeros(2))\n\n with self.assertRaises(ValueError):\n gibbs.RandGibbsAlgo(3, dimen_prob=np.ones(2))\n\n with self.assertRaises(ValueError):\n gibbs.RandGibbsAlgo(2, dimen_prob=[[1], [2]])\n\n def test_change_dimen_prob(self):\n sampler = gibbs.RandGibbsAlgo(num_dim=3)\n sampler.change_dimen_prob(new_probs=np.array([2, 0, 1]))\n\n npt.assert_array_equal(\n sampler.dimen_prob,\n np.array([2, 0, 1])/np.sum(np.array([2, 0, 1])))\n\n with self.assertRaises(ValueError):\n sampler.change_dimen_prob(new_probs=np.array([[2], [0], [1]]))\n\n with self.assertRaises(ValueError):\n sampler.change_dimen_prob(new_probs=np.array([2, 1]))\n\n def test_run(self):\n sampler = gibbs.RandGibbsAlgo(\n num_dim=2,\n initial_state=np.array([2, 3]),\n dimen_prob=np.array([2, 5]))\n\n # Feed in the two partial conditional samplers\n first_1_d_sampler = gibbs.OneDimSampler(scipy.stats.norm.rvs, fun)\n second_1_d_sampler = gibbs.OneDimSampler(\n scipy.stats.norm.rvs, another_fun)\n\n sampler.add_1_d_sampler(first_1_d_sampler)\n sampler.add_1_d_sampler(second_1_d_sampler)\n\n # Run 3 complete scan cycles of the algorithm\n sampler.run(num_cycles=3)\n last_state = sampler.chain_states[-1]\n\n self.assertEqual(len(sampler.chain_states), 4)\n self.assertEqual(len(last_state), len(sampler.initial_state))\n npt.assert_array_equal(last_state, sampler.current_state)\n\n # Run 3 more complete scan cycles of the algorithm\n sampler.run(num_cycles=3, mode='continue')\n self.assertEqual(len(sampler.chain_states), 7)\n\n # Rerun for 3 complete scan cycles of the algorithm\n sampler.run(num_cycles=3, mode='restart')\n self.assertEqual(len(sampler.chain_states), 4)\n" ]
[ [ "numpy.array", "numpy.zeros", "numpy.sum", "numpy.testing.assert_array_equal", "numpy.ones", "numpy.prod" ] ]
WeihanSun/python_sample
[ "e69e218558733733960a4633c8e7c92d7c3530c0" ]
[ "opencv/src/face_motion1.py" ]
[ "#!/usr/bin/env python\n\nimport os\nimport cv2\nimport numpy as np\nfrom enum import Enum\nimport math\n\nclass Calc (Enum):\n OPENCV = 1\n GSL_MULTI_ROOT = 2\n GSL_MULTI_FIT = 3\n\nimage_file_name = \"Man2_10deg.png\"\n\nuse_calc = Calc.GSL_MULTI_FIT\n#use_calc = Calc.GSL_MULTI_ROOT\n#use_calc = Calc.OPENCV\n\ndef get_project_xy(A, R, X, Y, Z):\n P = np.array([X, Y, Z, 1])\n pp = A.dot(R.dot(P))\n return [pp[0]/pp[2], pp[1]/pp[2]]\n\ndef get_project_uv(A, R, X, Y, Z):\n fx, fy, cx, cy = A[0][0], A[1][1], A[0][2], A[1][2]\n r11, r12, r13, t1 = R[0][0], R[0][1], R[0][2], R[0][3]\n r21, r22, r23, t2 = R[1][0], R[1][1], R[1][2], R[1][3]\n r31, r32, r33, t3 = R[2][0], R[2][1], R[2][2], R[2][3]\n s = r31 * X + r32 * Y + r33 * Z + t3\n# print(\"%f * %f + %f * %f + %f * %f + %f = %f\\n\" % (r31, X, r32, Y, r33, Z, t3, s))\n u = ((fx*r11 + cx*r31)*X + (fx*r12 + cx*r32)*Y + (fx*r13 + cx*r33)*Z + fx*t1 + cx*t3)/s\n v = ((fy*r21 + cy*r31)*X + (fy*r22 + cy*r32)*Y +(fy*r23 + cy*r33)*Z + fy*t2 + cy*t3)/s\n# print(\"%f/%f\" % ((fx*r11 + cx*r31)*X + (fx*r12 + cx*r32)*Y + (fx*r13 + cx*r33)*Z + fx*t1 + cx*t3, s))\n# print(\"%f/%f\" % ((fy*r21 + cy*r31)*X + (fy*r22 + cy*r32)*Y +(fy*r23 + cy*r33)*Z + fy*t2 + cy*t3, s))\n return u, v\n\n\ndef get_rot_tran_matrix2(M):\n a = []\n for i in range(0, 12):\n a.append(float(M[i]))\n R = np.array([[a[0], a[1], a[2], a[9]], [a[3], a[4], a[5], a[10]], [a[6], a[7], a[8], a[11]]])\n return R\n\ndef print_rotation_angle(RT):\n R = RT[:, 0:3]\n# print('R:', R)\n V = R.dot(np.array([0, 0, 1]))\n print('\\033[92mV:', V)\n print('phi = %f degree' % math.degrees(math.atan(V[0] / V[2])))\n print('theta = %f degree' % (math.sqrt(V[0]**2 + V[2]**2)))\n\n print('\\033[0m')\n\n\ndef verification_rot_tran_matrix(A, R, u, v, X, Y, Z):\n P = np.array([X, Y, Z, 1], dtype=\"double\")\n pp = A.dot(R.dot(P))\n diff = np.fabs(u - pp[0]/pp[2]) + np.fabs(v - pp[1]/pp[2])\n print(u, v, '<->', pp[0]/pp[2], pp[1]/pp[2])\n return diff\n\ndef verification_rot_tran_matrix_2(A, R, u, v, X, Y, Z):\n ud, vd = get_project_uv(A, R, X, Y, Z)\n print(u, v, '<->', ud, vd)\n\ndef get_rot_tran_matrix(img_pnts, mod_pnts, cam_matrix): # s = 1\n (u1, v1) = img_pnts[0] # nose tip\n (u2, v2) = img_pnts[1] # left eye\n (u3, v3) = img_pnts[2] # right eye\n (u4, v4) = img_pnts[3] # left mouth\n (u5, v5) = img_pnts[4] # right mouth\n (X1, Y1, Z1) = model_points[0]\n (X2, Y2, Z2) = model_points[1]\n (X3, Y3, Z3) = model_points[2]\n (X4, Y4, Z4) = model_points[3]\n (X5, Y5, Z5) = model_points[4]\n fx = cam_matrix[0][0]\n fy = cam_matrix[1][1]\n cx = cam_matrix[0][2]\n cy = cam_matrix[1][2]\n r31, r32, r33, t3 = 0, 0, 0, 1\n D = np.array([[X1, Y1, Z1, 1], [X2, Y2, Z2, 1], [X3, Y3, Z3, 1], [X4, Y4, Z4, 1]])\n D1 = np.array([[(v1 - cy) / fy, Y1, Z1, 1], [(v2 - cy) / fy, Y2, Z2, 1], [(v3 - cy) / fy, Y3, Z3, 1],\n [(v4 - cy) / fy, Y4, Z4, 1]])\n D2 = np.array([[X1, (v1 - cy) / fy, Z1, 1], [X2, (v2 - cy) / fy, Z2, 1], [X3, (v3 - cy) / fy, Z3, 1],\n [X4, (v4 - cy) / fy, Z4, 1]])\n D3 = np.array([[X1, Y1, (v1 - cy) / fy, 1], [X2, Y2, (v2 - cy) / fy, 1], [X3, Y3, (v3 - cy) / fy, 1],\n [X4, Y4, (v4 - cy) / fy, 1]])\n D4 = np.array([[X1, Y1, Z1, (v1 - cy) / fy], [X2, Y2, Z2, (v2 - cy) / fy], [X3, Y3, Z3, (v3 - cy) / fy],\n [X4, Y4, Z4, (v4 - cy) / fy]])\n r21 = np.linalg.det(D1) / np.linalg.det(D)\n r22 = np.linalg.det(D2) / np.linalg.det(D)\n r23 = np.linalg.det(D3) / np.linalg.det(D)\n t2 = np.linalg.det(D4) / np.linalg.det(D)\n D1 = np.array([[(u1 - cx) / fx, Y1, Z1, 1], [(u2 - cx) / fx, Y2, Z2, 1], [(u3 - cx) / fx, Y3, Z3, 1],\n [(u4 - cx) / fx, Y4, Z4, 1]])\n D2 = np.array([[X1, (u1 - cx) / fx, Z1, 1], [X2, (u2 - cx) / fx, Z2, 1], [X3, (u3 - cx) / fx, Z3, 1],\n [X4, (u4 - cx) / fx, Z4, 1]])\n D3 = np.array([[X1, Y1, (u1 - cx) / fx, 1], [X2, Y2, (u2 - cx) / fx, 1], [X3, Y3, (u3 - cx) / fx, 1],\n [X4, Y4, (u4 - cx) / fx, 1]])\n D4 = np.array([[X1, Y1, Z1, (u1 - cx) / fx], [X2, Y2, Z2, (v2 - cy) / fy], [X3, Y3, Z3, (u3 - cx) / fx],\n [X4, Y4, Z4, (u4 - cx) / fx]])\n r11 = np.linalg.det(D1) / np.linalg.det(D)\n r12 = np.linalg.det(D2) / np.linalg.det(D)\n r13 = np.linalg.det(D3) / np.linalg.det(D)\n t1 = np.linalg.det(D4) / np.linalg.det(D)\n R = np.array([[r11, r12, r13, t1], [r21, r22, r23, t2], [r31, r32, r33, t3]])\n return R\n\n\nif __name__ == '__main__':\n # 3D model points.\n model_points = np.array([\n (0.0, 0.0, 0.0), # Nose tip\n (-50.0, -40.0, 20.0), # Left eye left corner\n (50.0, -40.0, 20.0), # Right eye right corner\n (-27.5, 30.0, 10.0), # Left Mouth corner\n (27.5, 30.0, 10.0) # Right mouth corner\n ])\n index = 4\n points_file = \"points.txt\"\n image_file = []\n key_points = []\n matrix = []\n if not os.path.exists(points_file):\n print('do not have file %s' % points_file)\n exit(0)\n points_f = open(points_file, 'r')\n\n for line in points_f:\n a = line.split('|')\n b = a[0].split(',')\n image_file.append(b[0])\n key_points.append(b[1:11])\n matrix.append(a[1].split(','))\n\n points_f.close()\n\n image_points = np.array([\n (int(key_points[index][0]), int(key_points[index][5])), # Nose tip\n (int(key_points[index][1]), int(key_points[index][6])), # Left eye left corner\n (int(key_points[index][2]), int(key_points[index][7])), # Right eye right corner\n (int(key_points[index][3]), int(key_points[index][8])), # Left Mouth corner\n (int(key_points[index][4]), int(key_points[index][9])) # Right mouth corner\n ], dtype=\"double\")\n\n # Read Image\n im = cv2.imread(image_file[index])\n size = im.shape\n\n # Camera internals\n focal_length = size[1]\n center = (size[1] / 2, size[0] / 2)\n camera_matrix = np.array(\n [[focal_length, 0, center[0]],\n [0, focal_length, center[1]],\n [0, 0, 1]], dtype=\"double\")\n\n R = get_rot_tran_matrix2(matrix[index]) # read gsl result\n\n print(\"\\033[94m----check----\")\n for i in range(0, 5):\n verification_rot_tran_matrix_2(camera_matrix, R, image_points[i][0], image_points[i][1],\n model_points[i][0], model_points[i][1], model_points[i][2])\n print(\"----end-----\\033[0m\")\n\n print_rotation_angle(R)\n print(\"rotation_matrix:\\n {0}\".format(R))\n\n # draw axes\n axis_length = 100.0\n\n if False:\n Z_pnt = get_project_uv(camera_matrix, R, 0, 0, axis_length)\n Y_pnt = get_project_uv(camera_matrix, R, 0, axis_length, 0)\n X_pnt = get_project_uv(camera_matrix, R, axis_length, 0, 0)\n Org_pnt = get_project_uv(camera_matrix, R, 0, 0, 0)\n else:\n Z_pnt = get_project_xy(camera_matrix, R, 0, 0, axis_length)\n Y_pnt = get_project_xy(camera_matrix, R, 0, axis_length, 0)\n X_pnt = get_project_xy(camera_matrix, R, axis_length, 0, 0)\n Org_pnt = get_project_xy(camera_matrix, R, 0, 0, 0)\n\n\n #print('Rt:\\033[93m', R, '\\033[0m')\n# print('X:\\033[93m', R[:, 0:3].dot(np.array([axis_length, 0, 0])), '\\033[0m')\n# print('Y:\\033[93m', R[:, 0:3].dot(np.array([0, axis_length, 0])), '\\033[0m')\n# print('Z:\\033[93m', R[:, 0:3].dot(np.array([0, 0, axis_length])), '\\033[0m')\n\n for p in image_points:\n cv2.circle(im, (int(p[0]), int(p[1])), 3, (0, 0, 255), -1)\n\n p1 = (int(Org_pnt[0]), int(Org_pnt[1]))\n p2 = (int(Z_pnt[0]), int(Z_pnt[1]))\n cv2.line(im, p1, p2, (255, 0, 0), 2) #blue:Z\n p1 = (int(Org_pnt[0]), int(Org_pnt[1]))\n p2 = (int(Y_pnt[0]), int(Y_pnt[1]))\n cv2.line(im, p1, p2, (0, 255, 0), 2) #green:Y\n p1 = (int(Org_pnt[0]), int(Org_pnt[1]))\n p2 = (int(X_pnt[0]), int(X_pnt[1]))\n cv2.line(im, p1, p2, (0, 255, 255), 2) #yellow: X\n # Display image\n cv2.imshow(\"Output\", im)\n cv2.waitKey(0)\n" ]
[ [ "numpy.array", "numpy.fabs", "numpy.linalg.det" ] ]
SLINGhub/MSOrganiser
[ "918acda503093963a87a272f73bf6b07e8363e19" ]
[ "MSOrganiser.py" ]
[ "# coding: utf-8\nimport sys\nimport MSDuplicateCheck\nimport MSParser\nfrom MSAnalysis import MS_Analysis\nfrom MSDataOutput import MSDataOutput_Excel\nfrom MSDataOutput import MSDataOutput_csv\nfrom MSDataReport import MSDataReport_PDF\n\nfrom logging.handlers import TimedRotatingFileHandler\n\nimport os\nimport sys\nimport logging\nimport pandas as pd\n\nfrom datetime import datetime\nimport time\n\ndef start_logger(log_directory_path):\n \"\"\"To set up the log file folder and default configuration give a log directory path\n\n Args:\n log_directory_path (str): The directory path to create a folder containing the log files.\n \n Returns:\n logger (object): A logger object used for the MSOrganiser software.\n\n \"\"\"\n\n logdirectory = os.path.join(log_directory_path,\"logfiles\")\n\n try:\n os.makedirs(logdirectory, exist_ok=True)\n except Exception as e:\n print(\"Unable to create log directory in \" + logdirectory + \" due to this error message\",flush=True)\n print(e,flush=True)\n sys.exit(-1)\n\n logger = logging.getLogger(\"MSOrganiser\")\n logger.setLevel(logging.INFO)\n\n # create file handler (fh)\n logfilename = os.path.join(logdirectory , 'Test_Log')\n fh = TimedRotatingFileHandler(logfilename,\n when='midnight',\n interval=1,\n backupCount=2)\n \n # create a logging format\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n fh.setFormatter(formatter)\n \n # add the handlers to the logger\n logger.addHandler(fh)\n return logger\n\ndef get_Parameters_df(stored_args, MS_FilePath = None,\n MS_FilePaths = [], using_multiple_input_files = False):\n \"\"\"To set up a pandas dataframe storing the input parameters, This data frame will be converted to a PDF page\n\n Args:\n stored_args (dict): A dictionary storing the input parameters. The dictionary is created in MSParser\n MS_FilePath (str): The file path to the MRM transition name file.\n MS_FilePaths (list): A list of file path to the MRM transition name file.\n using_multiple_input_files (bool): if True, the Input_File parameter will be constructed from multiple input files, denoted in MS_FilePaths (in development)\n \n Returns:\n Parameters_df (pandas DataFrame): A dataframe storing the input parameters\n\n \"\"\"\n\n Parameter_list = []\n\n #Get specific keys into the parameters list\n if using_multiple_input_files:\n i = 1\n for input_file in [os.path.basename(file) for file in MS_FilePaths]:\n Parameter_list.append((\"Input_File \" + str(i),input_file))\n i +=1\n else:\n if MS_FilePath is not None:\n Parameter_list.append((\"Input_File\",str(os.path.basename(MS_FilePath))))\n\n Parameter_list.append((\"Input_File_Type\",stored_args['MS_FileType']))\n\n if stored_args['Annot_File']:\n Parameter_list.append((\"Annot_File\",os.path.basename(stored_args['Annot_File'])))\n\n if stored_args['Output_Options']:\n for things in stored_args['Output_Options']:\n Parameter_list.append((\"Output_Options\",things))\n\n if stored_args['Output_Format']:\n Parameter_list.append((\"Output_Format\",stored_args['Output_Format']))\n\n if stored_args['Concatenate']:\n Parameter_list.append((\"Concatenate\",stored_args['Concatenate']))\n\n if stored_args['Allow_Multiple_ISTD'] is not None:\n Parameter_list.append((\"Allow_Multiple_ISTD\",stored_args['Allow_Multiple_ISTD']))\n\n if stored_args['Transpose_Results'] is not None:\n Parameter_list.append((\"Transpose_Results\",stored_args['Transpose_Results']))\n\n if stored_args['Long_Table'] is not None:\n Parameter_list.append((\"Long_Table\",stored_args['Long_Table']))\n\n if stored_args['Long_Table_Annot'] is not None:\n Parameter_list.append((\"Long_Table_Annot\",stored_args['Long_Table_Annot']))\n\n Parameters_df = pd.DataFrame(Parameter_list,columns=['Parameters', 'Value'])\n return Parameters_df\n\ndef output_concatenated_wide_data(stored_args, \n concatenate_df_list, concatenate_df_sheet_name,\n logger=None):\n\n #Output concatenated wide data after going through all the files\n if stored_args['Transpose_Results']:\n result_name = \"TransposeResults\"\n else:\n result_name = \"Results\"\n\n logger.info(\"Outputting concatenated file.\")\n print(\"Creating concatenated file.\",flush=True)\n\n #Set up the file writing configuration for Excel, or csv ...\n if stored_args['Output_Format'] == \"Excel\" :\n DfConcatenateOutput = MSDataOutput_Excel(stored_args['Output_Directory'], \"Concatenated\", \n result_name ,logger=logger, ingui=True)\n elif stored_args['Output_Format'] == \"csv\" :\n DfConcatenateOutput = MSDataOutput_csv(stored_args['Output_Directory'], \"Concatenated\",\n result_name ,logger=logger, ingui=True)\n\n DfConcatenateOutput.start_writer()\n for i in range(len(concatenate_df_list)):\n if concatenate_df_sheet_name[i] != \"Long_Table\":\n #Decide the appropriate table to perfrom the transpose if set to True.\n if concatenate_df_sheet_name[i] in [\"Transition_Name_Annot\",\"Sample_Annot\"]:\n #For these two data frame, no transpose is required.\n DfConcatenateOutput.df_to_file(concatenate_df_sheet_name[i],concatenate_df_list[i],\n transpose = False,\n allow_multiple_istd = False)\n elif concatenate_df_sheet_name[i] in [\"Area\", \"RT\", \"FWHM\", \"S/N\", \"Symmetry\",\n \"Precursor Ion\", \"Product Ion\"]:\n DfConcatenateOutput.df_to_file(concatenate_df_sheet_name[i],concatenate_df_list[i],\n transpose=stored_args['Transpose_Results'],\n allow_multiple_istd = False)\n else:\n DfConcatenateOutput.df_to_file(concatenate_df_sheet_name[i],concatenate_df_list[i],\n transpose=stored_args['Transpose_Results'],\n allow_multiple_istd=stored_args['Allow_Multiple_ISTD'])\n if stored_args['Output_Format'] == \"Excel\" :\n DfConcatenateOutput.end_writer()\n\ndef output_concatenated_long_table(stored_args, \n concatenate_df_list, concatenate_df_sheet_name,\n logger=None):\n\n #Output concatenated long table\n if stored_args['Long_Table']:\n #Set up the file writing configuration for Excel, or csv ...\n if stored_args['Output_Format'] == \"Excel\" :\n if stored_args['Long_Table_Annot']:\n result_name = \"Long_Table_with_Annot\"\n else:\n result_name = \"Long_Table\"\n DfConcatenateLongOutput = MSDataOutput_Excel(stored_args['Output_Directory'], \"Concatenated\", \n result_name = result_name ,logger=logger, ingui=True)\n elif stored_args['Output_Format'] == \"csv\" :\n DfConcatenateLongOutput = MSDataOutput_csv(stored_args['Output_Directory'], \"Concatenated\", \n result_name = \"\" ,logger=logger, ingui=True)\n DfConcatenateLongOutput.start_writer()\n Long_Table_index = concatenate_df_sheet_name.index(\"Long_Table\")\n if stored_args['Output_Format'] == \"csv\" and stored_args['Long_Table_Annot']:\n concatenate_df_sheet_name[Long_Table_index] = \"Long_Table_with_Annot\"\n DfConcatenateLongOutput.df_to_file(concatenate_df_sheet_name[Long_Table_index],concatenate_df_list[Long_Table_index])\n if stored_args['Output_Format'] == \"Excel\" :\n DfConcatenateLongOutput.end_writer()\n\ndef no_concatenate_workflow(stored_args, logger=None, testing = False):\n\n # Use during unit testing\n file_data_list = []\n file_name = []\n\n no_need_full_data_output_options = []\n need_full_data_output_options = []\n\n for output_option in stored_args['Output_Options']:\n #if output_option in [\"Area\",\"RT\",\"FWHM\",\"S/N\",\"Symmetry\",\n # \"Precursor Ion\",\"Product Ion\"]:\n # no_need_full_data_output_options.append(output_option)\n if output_option not in ['normConc by ISTD', 'normArea by ISTD']:\n no_need_full_data_output_options.append(output_option)\n else:\n if output_option == 'normConc by ISTD' and 'normArea by ISTD' not in need_full_data_output_options:\n need_full_data_output_options.append(\"normArea by ISTD\")\n need_full_data_output_options.append(output_option)\n if any(['normArea by ISTD' in stored_args['Output_Options'],\n 'normConc by ISTD' in stored_args['Output_Options']\n ]) and 'Area' not in no_need_full_data_output_options:\n no_need_full_data_output_options.append(\"Area\")\n\n # We do this for every mass hunter file output\n # MS_Files is no longer a long string of paths separated by ;, \n # we split them into a list\n for MS_FilePath in stored_args['MS_Files']:\n\n if not testing:\n print(\"Working on \" + MS_FilePath,flush=True)\n if logger:\n logger.info(\"Working on \" + MS_FilePath)\n\n MyData = MS_Analysis(MS_FilePath = MS_FilePath, \n MS_FileType = stored_args['MS_FileType'], \n Annotation_FilePath = stored_args['Annot_File'],\n logger = logger, \n ingui = True, \n longtable = stored_args['Long_Table'], \n longtable_annot = stored_args['Long_Table_Annot'])\n\n #Initiate the pdf report file\n PDFReport = MSDataReport_PDF(output_directory = stored_args['Output_Directory'], \n input_file_path = MS_FilePath, \n logger = logger, \n ingui = True,\n testing = testing)\n\n #Generate the parameters report\n Parameters_df = get_Parameters_df(stored_args = stored_args,\n MS_FilePath = MS_FilePath)\n PDFReport.create_parameters_report(Parameters_df)\n\n if stored_args['Transpose_Results']:\n result_name = \"TransposeResults\"\n else:\n result_name = \"Results\"\n\n if not testing:\n #Set up the file writing configuration for Excel, or csv ...\n if stored_args['Output_Format'] == \"Excel\":\n DfOutput = MSDataOutput_Excel(stored_args['Output_Directory'], MS_FilePath, \n result_name = result_name ,\n logger = logger, ingui = True)\n elif stored_args['Output_Format'] == \"csv\":\n DfOutput = MSDataOutput_csv(stored_args['Output_Directory'], MS_FilePath, \n result_name = result_name ,\n logger = logger, ingui = True)\n if not testing:\n DfOutput.start_writer()\n\n #Use during unit testing\n file_data = []\n sheet_name = []\n\n if len(no_need_full_data_output_options) > 0:\n for output_option in no_need_full_data_output_options:\n #We extract the data directly from the file and output accordingly\n Output_df = MyData.get_from_Input_Data(output_option,\n allow_multiple_istd=False)\n\n #If not doing unit testing,\n #Output the Output_df results\n if not testing:\n DfOutput.df_to_file(output_option,Output_df,\n transpose=stored_args['Transpose_Results'],\n allow_multiple_istd=False)\n\n #If doing unit testing, output the Output_df\n #in the file_data list\n if testing:\n file_data.append(Output_df)\n sheet_name.append(output_option)\n\n if len(need_full_data_output_options) > 0:\n for output_option in need_full_data_output_options:\n if output_option == 'normArea by ISTD':\n # Perform normalisation using ISTD\n [norm_Area_df,ISTD_Area,ISTD_map_df,ISTD_Report] = MyData.get_Normalised_Area(output_option,stored_args['Annot_File'],\n allow_multiple_istd = stored_args['Allow_Multiple_ISTD'])\n\n # Output the normalised area results\n\n # If testing check box is checked and not doing unit testing, \n # output the ISTD_Area results\n if stored_args['Testing'] and not testing:\n DfOutput.df_to_file(\"ISTD_Area\",ISTD_Area,\n transpose=stored_args['Transpose_Results'],\n allow_multiple_istd=stored_args['Allow_Multiple_ISTD']\n )\n\n # If testing check box is checked and doing unit testing, \n # output the ISTD_Area in the file_data list\n if stored_args['Testing'] and testing:\n file_data.append(ISTD_Area)\n sheet_name.append(\"ISTD_Area\")\n\n # If not doing unit testing,\n # output the normalised area and transition annotation results\n if not testing:\n DfOutput.df_to_file(\"Transition_Name_Annot\",ISTD_map_df)\n DfOutput.df_to_file(\"normArea_by_ISTD\",norm_Area_df,\n transpose=stored_args['Transpose_Results'],\n allow_multiple_istd=stored_args['Allow_Multiple_ISTD'])\n\n # If doing unit testing, output the normalised area and \n # transition annotation results in the file_data list\n if testing:\n file_data.extend([ISTD_map_df,norm_Area_df])\n sheet_name.extend([\"Transition_Name_Annot\", \"normArea_by_ISTD\"])\n \n # Generate the ISTD normalisation report\n PDFReport.create_ISTD_report(ISTD_Report)\n\n elif output_option == 'normConc by ISTD':\n # Perform concentration need_full_data\n [norm_Conc_df,ISTD_Conc_df,ISTD_Samp_Ratio_df,Sample_Annot_df] = MyData.get_Analyte_Concentration(output_option,stored_args['Annot_File'],\n allow_multiple_istd=stored_args['Allow_Multiple_ISTD'])\n\n # Remove the column \"Merge_Status\" as it is not relevant\n # Reorder the column such that \"Concentration_Unit\" is at the last column\n Sample_Annot_df = Sample_Annot_df[[\"Data_File_Name\", \"Sample_Name\",\n \"Sample_Amount\", \"Sample_Amount_Unit\",\n \"ISTD_Mixture_Volume_[uL]\", \"ISTD_to_Sample_Amount_Ratio\",\n \"Concentration_Unit\"]]\n\n # Output the concentration results\n\n # If testing check box is checked and not doing unit testing, \n # output the ISTD_Conc and ISTD_to_Samp_Amt_Ratio results\n if stored_args['Testing'] and not testing:\n DfOutput.df_to_file(\"ISTD_Conc\",ISTD_Conc_df,\n transpose=stored_args['Transpose_Results'],\n allow_multiple_istd=stored_args['Allow_Multiple_ISTD'])\n DfOutput.df_to_file(\"ISTD_to_Samp_Amt_Ratio\",ISTD_Samp_Ratio_df,\n transpose=stored_args['Transpose_Results'],\n allow_multiple_istd=stored_args['Allow_Multiple_ISTD'])\n\n # If testing check box is checked and doing unit testing, \n # output the ISTD_Conc and ISTD_to_Samp_Amt_Ratio in the file_data list\n if stored_args['Testing'] and testing:\n file_data.extend([ISTD_Conc_df,ISTD_Samp_Ratio_df])\n sheet_name.extend([\"ISTD_Conc\", \"ISTD_to_Samp_Amt_Ratio\"])\n\n # If not doing unit testing,\n # Output the concentration data and sample annotation results\n if not testing:\n DfOutput.df_to_file(\"Sample_Annot\",Sample_Annot_df)\n DfOutput.df_to_file(\"normConc_by_ISTD\",norm_Conc_df,\n transpose=stored_args['Transpose_Results'],\n allow_multiple_istd=stored_args['Allow_Multiple_ISTD'])\n\n # If doing unit testing, output the Sample_Annot_df and\n # norm_Conc_df results in the file_data list\n if testing:\n file_data.extend([Sample_Annot_df, norm_Conc_df])\n sheet_name.extend([\"Sample_Annot\", \"normConc_by_ISTD\"])\n\n #End the writing configuration for Excel, ...\n if stored_args['Output_Format'] == \"Excel\" and not testing:\n DfOutput.end_writer()\n\n #Output the report to a pdf file\n if not testing:\n PDFReport.output_to_PDF()\n\n #Output the LongTable Data Table in another csv or excel sheet\n if stored_args['Long_Table']:\n Long_Table_df = MyData.get_Long_Table(allow_multiple_istd=stored_args['Allow_Multiple_ISTD'],\n concatenation_type = None)\n\n result_name = \"Long_Table\" \n if stored_args['Long_Table_Annot']:\n result_name = \"Long_Table_with_Annot\"\n\n #If doing unit testing, output the Long_Table_df\n #in the file_data list\n if testing:\n file_data.append(Long_Table_df)\n sheet_name.append(\"Long_Table\")\n\n if not testing:\n #Set up the file writing configuration for Excel, or csv ...\n if stored_args['Output_Format'] == \"Excel\":\n DfLongOutput = MSDataOutput_Excel(stored_args['Output_Directory'], MS_FilePath, \n result_name = result_name ,logger=logger, ingui=True)\n elif stored_args['Output_Format'] == \"csv\":\n DfLongOutput = MSDataOutput_csv(stored_args['Output_Directory'], MS_FilePath, \n result_name = \"\" ,logger=logger, ingui=True)\n DfLongOutput.start_writer()\n DfLongOutput.df_to_file(\"Long_Table\",Long_Table_df)\n\n if stored_args['Output_Format'] == \"Excel\" :\n DfLongOutput.end_writer()\n\n #Use during unit testing\n if testing:\n file_name.append(MS_FilePath)\n file_data_list.append([file_data,sheet_name])\n\n #Use during unit testing\n if testing:\n return([file_data_list, file_name])\n\ndef concatenate_along_rows_workflow(stored_args, logger=None, testing = False):\n\n #Initiate the pdf report file\n PDFReport = MSDataReport_PDF(output_directory = stored_args['Output_Directory'], \n input_file_path = \"ConcatenatedRow\", \n logger = logger, \n ingui = True,\n testing = testing)\n\n #Generate the parameters report\n Parameters_df = get_Parameters_df(stored_args = stored_args,\n MS_FilePaths = stored_args['MS_Files'],\n using_multiple_input_files = True\n )\n\n PDFReport.create_parameters_report(Parameters_df)\n\n no_need_full_data_output_options = []\n need_full_data_output_options = []\n\n for output_option in stored_args['Output_Options']:\n #if output_option in [\"Area\",\"RT\",\"FWHM\",\"S/N\",\"Symmetry\",\n # \"Precursor Ion\",\"Product Ion\"]:\n # no_need_full_data_output_options.append(output_option)\n if output_option not in ['normConc by ISTD', 'normArea by ISTD']:\n no_need_full_data_output_options.append(output_option)\n else:\n if output_option == 'normConc by ISTD' and 'normArea by ISTD' not in need_full_data_output_options:\n need_full_data_output_options.append(\"normArea by ISTD\")\n need_full_data_output_options.append(output_option)\n if any(['normArea by ISTD' in stored_args['Output_Options'],\n 'normConc by ISTD' in stored_args['Output_Options']\n ]) and 'Area' not in no_need_full_data_output_options:\n no_need_full_data_output_options.append(\"Area\")\n\n concatenate_df_list = []\n concatenate_df_sheet_name = []\n\n #We first need to concatenate Output Options that do not require full data like\n #Area, RT, etc\n if(len(no_need_full_data_output_options) > 0):\n\n #We do this for every mass hunter file output\n #MS_Files is no longer a long string of paths separated by ;, we split them into a list\n for MS_FilePath in stored_args['MS_Files']:\n\n MyNoCalcData = MS_Analysis(MS_FilePath = MS_FilePath, \n MS_FileType = stored_args['MS_FileType'], \n Annotation_FilePath = stored_args['Annot_File'],\n logger = logger, \n ingui = True, \n longtable = stored_args['Long_Table'], \n longtable_annot = stored_args['Long_Table_Annot'])\n\n #Initialise a list of df and sheet name\n one_file_df_list = []\n one_file_df_sheet_name = []\n\n for output_option in no_need_full_data_output_options:\n #We extract the data directly from the file and put them in the list accordingly\n Output_df = MyNoCalcData.get_from_Input_Data(output_option,\n allow_multiple_istd= False)\n one_file_df_list.extend([Output_df])\n one_file_df_sheet_name.extend([output_option])\n\n #Output the LongTable Data Table in another csv or excel sheet\n if stored_args['Long_Table']:\n Long_Table_df = MyNoCalcData.get_Long_Table(allow_multiple_istd=stored_args['Allow_Multiple_ISTD'],\n concatenation_type = None)\n one_file_df_list.extend([Long_Table_df])\n one_file_df_sheet_name.extend([\"Long_Table\"])\n\n #After creating the one_file_df_list and one_file_df_sheet_name\n #Start to concatenate when we reach the second file\n if len(concatenate_df_list) == 0:\n concatenate_df_list = one_file_df_list\n concatenate_df_sheet_name = one_file_df_sheet_name\n else:\n #When we have the second file onwards\n for i in range(len(one_file_df_list)):\n #Concatenate Row Wise all df except those indicated\n if not one_file_df_sheet_name[i] in [\"Transition_Name_Annot\"]:\n concatenate_df_list[i] = pd.concat([concatenate_df_list[i], one_file_df_list[i]], \n ignore_index=True, \n sort=False, \n axis = 0)\n\n # We check if the concatenated data is valid without\n # any duplicated columns and sample names, if there are, we should not proceed to calculation\n # and inform the user of this issue.\n for output_option in no_need_full_data_output_options:\n # Get the data frame that correspond to the column_name like\n # \"Area\",\"RT\",\"FWHM\",\"S/N\" etc\n output_option_index = concatenate_df_sheet_name.index(output_option)\n concatenated_data = concatenate_df_list[output_option_index]\n MSDuplicateCheck.check_duplicated_columns_in_wide_data(concatenated_data, \n \"row concatenated \" + output_option,\n logger = logger, ingui = True,\n allow_multiple_istd = False)\n MSDuplicateCheck.check_duplicated_sample_names_in_wide_data(concatenated_data, \n \"row concatenated \" + output_option,\n logger = None, ingui = True,\n allow_multiple_istd = False)\n\n #We now create data frame of output options that require the full data like\n #normArea by ISTD, normConc by ISTD, etc\n\n if(len(need_full_data_output_options) > 0):\n\n MyCalcData = MS_Analysis(MS_FilePaths = stored_args['MS_Files'], \n MS_FileType = stored_args['MS_FileType'], \n Annotation_FilePath = stored_args['Annot_File'],\n logger = logger, \n ingui = True, \n longtable = stored_args['Long_Table'], \n longtable_annot = stored_args['Long_Table_Annot'])\n\n\n #print(\"Working on Output options that needs to be calculated\",flush=True)\n for output_option in need_full_data_output_options:\n if output_option == 'normArea by ISTD':\n\n #Perform normalisation using ISTD\n [norm_Area_df,ISTD_Area,ISTD_map_df,ISTD_Report] = MyCalcData.get_Normalised_Area(output_option,stored_args['Annot_File'],\n allow_multiple_istd = stored_args['Allow_Multiple_ISTD'],\n using_multiple_input_files = True,\n concatenation_type = \"rows\")\n\n #If testing, output the ISTD_Area results in the concatenate_df list\n if stored_args['Testing']:\n concatenate_df_list.extend([ISTD_Area])\n concatenate_df_sheet_name.extend([\"ISTD_Area\"])\n\n #Put the normalised area and transition annotation results in the concatenate_df list\n concatenate_df_list.extend([ISTD_map_df,norm_Area_df])\n concatenate_df_sheet_name.extend([\"Transition_Name_Annot\",\"normArea_by_ISTD\"])\n\n #Generate the ISTD normalisation report\n PDFReport.create_ISTD_report(ISTD_Report)\n\n elif output_option == 'normConc by ISTD':\n #Perform concentration calculation using ISTD\n [norm_Conc_df,ISTD_Conc_df,ISTD_Samp_Ratio_df,Sample_Annot_df] = MyCalcData.get_Analyte_Concentration(output_option,stored_args['Annot_File'],\n allow_multiple_istd=stored_args['Allow_Multiple_ISTD'],\n using_multiple_input_files = True,\n concatenation_type = \"rows\")\n\n #Remove the column \"Merge_Status\" as it is not relevant\n #Reorder the column such that \"Concentration_Unit\" is at the last column\n Sample_Annot_df = Sample_Annot_df[[\"Data_File_Name\", \"Sample_Name\",\n \"Sample_Amount\", \"Sample_Amount_Unit\",\n \"ISTD_Mixture_Volume_[uL]\", \"ISTD_to_Sample_Amount_Ratio\",\n \"Concentration_Unit\"]]\n \n #If testing, output the ISTD_Conc and ISTD_to_Samp_Amt_Ratio results in the list\n if stored_args['Testing']:\n concatenate_df_list.extend([ISTD_Conc_df,ISTD_Samp_Ratio_df])\n concatenate_df_sheet_name.extend([\"ISTD_Conc\",\"ISTD_to_Samp_Amt_Ratio\"])\n\n #Output the concentration data and sample annotation results in the list\n concatenate_df_list.extend([Sample_Annot_df,norm_Conc_df])\n concatenate_df_sheet_name.extend([\"Sample_Annot\",\"normConc_by_ISTD\"])\n\n #Merge the Long_Table created from calculation_columns to the Long_Table created from no_need_full_data_columns\n if stored_args['Long_Table']:\n for index, output_option in enumerate(need_full_data_output_options):\n if output_option == 'normArea by ISTD':\n need_full_data_output_options[index] = 'normArea'\n if output_option == 'normConc by ISTD':\n need_full_data_output_options[index] = 'normConc'\n Long_Table_df = MyCalcData.get_Long_Table(allow_multiple_istd=stored_args['Allow_Multiple_ISTD'],\n concatenation_type = \"rows\")\n if \"Long_Table\" in concatenate_df_sheet_name:\n Long_Table_index = concatenate_df_sheet_name.index(\"Long_Table\")\n common_columns = list(set(concatenate_df_list[Long_Table_index].columns).intersection(Long_Table_df.columns))\n front_columns = [x for x in Long_Table_df.columns if x not in need_full_data_output_options]\n concatenate_df_list[Long_Table_index] = pd.merge(concatenate_df_list[Long_Table_index], \n Long_Table_df,\n how='inner',\n on = common_columns)\n col_order = front_columns + no_need_full_data_output_options + need_full_data_output_options\n concatenate_df_list[Long_Table_index] = concatenate_df_list[Long_Table_index][col_order]\n else:\n concatenate_df_list.extend([Long_Table_df])\n concatenate_df_sheet_name.extend([\"Long_Table\"])\n\n return([PDFReport, concatenate_df_list, concatenate_df_sheet_name])\n\ndef concatenate_along_columns_workflow(stored_args, logger=None, testing = False):\n\n #Initiate the pdf report file\n PDFReport = MSDataReport_PDF(output_directory = stored_args['Output_Directory'], \n input_file_path = \"ConcatenatedColumn\", \n logger = logger, \n ingui = True,\n testing = testing)\n\n #Generate the parameters report\n Parameters_df = get_Parameters_df(stored_args = stored_args,\n MS_FilePaths = stored_args['MS_Files'],\n using_multiple_input_files = True\n )\n PDFReport.create_parameters_report(Parameters_df)\n\n no_need_full_data_output_options = []\n need_full_data_output_options = []\n\n for output_option in stored_args['Output_Options']:\n #if output_option in [\"Area\",\"RT\",\"FWHM\",\"S/N\",\"Symmetry\",\n # \"Precursor Ion\",\"Product Ion\"]:\n # no_need_full_data_output_options.append(output_option)\n if output_option not in ['normConc by ISTD', 'normArea by ISTD']:\n no_need_full_data_output_options.append(output_option)\n else:\n if output_option == 'normConc by ISTD' and 'normArea by ISTD' not in need_full_data_output_options:\n need_full_data_output_options.append(\"normArea by ISTD\")\n need_full_data_output_options.append(output_option)\n if any(['normArea by ISTD' in stored_args['Output_Options'],\n 'normConc by ISTD' in stored_args['Output_Options']\n ]) and 'Area' not in no_need_full_data_output_options:\n no_need_full_data_output_options.append(\"Area\")\n \n concatenate_df_list = []\n concatenate_df_sheet_name = []\n\n #We first need to concatenate Output Options that do not require full data like\n #Area, RT, etc\n if(len(no_need_full_data_output_options) > 0):\n #print(\"Working on Output options that do not need to be calculated\",flush=True)\n\n #We do this for every mass hunter file output\n #MS_Files is no longer a long string of paths separated by ;, we split them into a list\n for MS_FilePath in stored_args['MS_Files']:\n\n MyNoCalcData = MS_Analysis(MS_FilePath = MS_FilePath, \n MS_FileType = stored_args['MS_FileType'], \n Annotation_FilePath = stored_args['Annot_File'],\n logger = logger, \n ingui = True, \n longtable = stored_args['Long_Table'], \n longtable_annot = stored_args['Long_Table_Annot'])\n\n #Initialise a list of df and sheet name\n one_file_df_list = []\n one_file_df_sheet_name = []\n\n for output_option in no_need_full_data_output_options:\n #We extract the data directly from the file and put them in the list accordingly\n Output_df = MyNoCalcData.get_from_Input_Data(output_option,\n allow_multiple_istd = False)\n one_file_df_list.extend([Output_df])\n one_file_df_sheet_name.extend([output_option])\n\n #Output the LongTable Data Table in another csv or excel sheet\n if stored_args['Long_Table']:\n Long_Table_df = MyNoCalcData.get_Long_Table(allow_multiple_istd=stored_args['Allow_Multiple_ISTD'],\n concatenation_type = None)\n one_file_df_list.extend([Long_Table_df])\n one_file_df_sheet_name.extend([\"Long_Table\"])\n\n #After creating the one_file_df_list and one_file_df_sheet_name\n #Start to concatenate when we reach the second file\n if len(concatenate_df_list) == 0:\n concatenate_df_list = one_file_df_list\n concatenate_df_sheet_name = one_file_df_sheet_name\n else:\n #When we have the second file onwards\n for i in range(len(one_file_df_list)):\n #Concantenate Row Wise\n if one_file_df_sheet_name[i] in [\"Long_Table\"]:\n concatenate_df_list[i] = pd.concat([concatenate_df_list[i], one_file_df_list[i]], \n ignore_index=True,\n sort=False, \n axis = 0)\n else:\n #Concantenate Column Wise\n #Remove the Sample_Name column\n appending_df = one_file_df_list[i].loc[:, one_file_df_list[i].columns != 'Sample_Name']\n concatenate_df_list[i] = pd.concat([concatenate_df_list[i], appending_df], \n ignore_index=False, \n sort=False, \n axis = 1)\n\n # We check if the concatenated data is valid without\n # any duplicated columns and sample names, if there are, we should not proceed to calculation\n # and inform the user of this issue.\n for output_option in no_need_full_data_output_options:\n # Get the data frame that correspond to the column_name like\n # \"Area\",\"RT\",\"FWHM\",\"S/N\" etc\n output_option_index = concatenate_df_sheet_name.index(output_option)\n concatenated_data = concatenate_df_list[output_option_index]\n MSDuplicateCheck.check_duplicated_columns_in_wide_data(concatenated_data, \n \"column concatenated \" + output_option,\n logger = logger, ingui = True,\n allow_multiple_istd = False)\n MSDuplicateCheck.check_duplicated_sample_names_in_wide_data(concatenated_data, \n \"column concatenated \" + output_option,\n logger = None, ingui = True,\n allow_multiple_istd = False)\n #We now create data frame of output options that require the full data like\n #normArea by ISTD, normConc by ISTD, etc\n\n if(len(need_full_data_output_options) > 0):\n\n MyCalcData = MS_Analysis(MS_FilePaths = stored_args['MS_Files'], \n MS_FileType = stored_args['MS_FileType'], \n Annotation_FilePath = stored_args['Annot_File'],\n logger = logger, \n ingui = True, \n longtable = stored_args['Long_Table'], \n longtable_annot = stored_args['Long_Table_Annot'])\n\n\n #print(\"Working on Output options that needs to be calculated\",flush=True)\n for output_option in need_full_data_output_options:\n if output_option == 'normArea by ISTD':\n\n #Perform normalisation using ISTD\n [norm_Area_df,ISTD_Area,ISTD_map_df,ISTD_Report] = MyCalcData.get_Normalised_Area(output_option,stored_args['Annot_File'],\n allow_multiple_istd = stored_args['Allow_Multiple_ISTD'],\n using_multiple_input_files = True,\n concatenation_type = \"columns\")\n\n #If testing, output the ISTD_Area results in the concatenate_df list\n if stored_args['Testing']:\n concatenate_df_list.extend([ISTD_Area])\n concatenate_df_sheet_name.extend([\"ISTD_Area\"])\n\n #Put the normalised area and transition annotation results in the concatenate_df list\n concatenate_df_list.extend([ISTD_map_df,norm_Area_df])\n concatenate_df_sheet_name.extend([\"Transition_Name_Annot\",\"normArea_by_ISTD\"])\n\n #Generate the ISTD normalisation report\n PDFReport.create_ISTD_report(ISTD_Report)\n\n elif output_option == 'normConc by ISTD':\n #Perform concentration calculation using ISTD\n [norm_Conc_df,ISTD_Conc_df,ISTD_Samp_Ratio_df,Sample_Annot_df] = MyCalcData.get_Analyte_Concentration(output_option,stored_args['Annot_File'],\n allow_multiple_istd=stored_args['Allow_Multiple_ISTD'],\n using_multiple_input_files = True,\n concatenation_type = \"columns\")\n\n #Remove the column \"Merge_Status\" as it is not relevant\n #Reorder the column such that \"Concentration_Unit\" is at the last column\n Sample_Annot_df = Sample_Annot_df[[\"Data_File_Name\", \"Sample_Name\",\n \"Sample_Amount\", \"Sample_Amount_Unit\",\n \"ISTD_Mixture_Volume_[uL]\", \"ISTD_to_Sample_Amount_Ratio\",\n \"Concentration_Unit\"]]\n \n #If testing, output the ISTD_Conc and ISTD_to_Samp_Amt_Ratio results in the list\n if stored_args['Testing']:\n concatenate_df_list.extend([ISTD_Conc_df,ISTD_Samp_Ratio_df])\n concatenate_df_sheet_name.extend([\"ISTD_Conc\",\"ISTD_to_Samp_Amt_Ratio\"])\n\n #Output the concentration data and sample annotation results in the list\n concatenate_df_list.extend([Sample_Annot_df,norm_Conc_df])\n concatenate_df_sheet_name.extend([\"Sample_Annot\",\"normConc_by_ISTD\"])\n\n #Merge the Long_Table created from calculation_columns to the Long_Table created from no_need_full_data_output_options\n if stored_args['Long_Table']:\n for index, output_option in enumerate(need_full_data_output_options):\n if output_option == 'normArea by ISTD':\n need_full_data_output_options[index] = 'normArea'\n if output_option == 'normConc by ISTD':\n need_full_data_output_options[index] = 'normConc'\n Long_Table_df = MyCalcData.get_Long_Table(allow_multiple_istd=stored_args['Allow_Multiple_ISTD'],\n concatenation_type = \"columns\")\n if \"Long_Table\" in concatenate_df_sheet_name:\n Long_Table_index = concatenate_df_sheet_name.index(\"Long_Table\")\n common_columns = list(set(concatenate_df_list[Long_Table_index].columns).intersection(Long_Table_df.columns))\n front_columns = [x for x in Long_Table_df.columns if x not in need_full_data_output_options]\n concatenate_df_list[Long_Table_index] = pd.merge(Long_Table_df,\n concatenate_df_list[Long_Table_index], \n how = 'inner',\n on = common_columns )\n col_order = front_columns + no_need_full_data_output_options + need_full_data_output_options\n concatenate_df_list[Long_Table_index] = concatenate_df_list[Long_Table_index][col_order]\n else:\n concatenate_df_list.extend([Long_Table_df])\n concatenate_df_sheet_name.extend([\"Long_Table\"])\n\n return([PDFReport, concatenate_df_list, concatenate_df_sheet_name])\n\nif __name__ == '__main__':\n\n #Read the parser\n stored_args = MSParser.parse_MSOrganiser_args()\n\n #Start log on a job\n #Logfile will be the same directory as the exe file\n logger = start_logger(os.path.abspath(os.path.dirname(sys.argv[0])))\n logger.info(\"Starting the job.\")\n print(\"Starting the job.\",flush=True)\n\n #In Gooey 1.0.8, there is no need to split stored_args['MS_Files'] by \";\"\n #As stored_args['MS_Files'] is a list\n #Find the number of input files\n input_files_amount = len(stored_args['MS_Files'])\n\n if stored_args['Concatenate']==\"No Concatenate\":\n no_concatenate_workflow(stored_args,logger)\n elif stored_args['Concatenate']==\"Concatenate along Sample Name (rows)\":\n [PDFReport, concatenate_df_list, concatenate_df_sheet_name] = concatenate_along_rows_workflow(stored_args,logger)\n elif stored_args['Concatenate']==\"Concatenate along Transition Name (columns)\":\n [PDFReport, concatenate_df_list, concatenate_df_sheet_name] = concatenate_along_columns_workflow(stored_args, logger)\n\n if stored_args['Concatenate']!=\"No Concatenate\":\n #Output the report to a pdf file\n PDFReport.output_to_PDF()\n #Output concatenated wide data after going through all the files\n output_concatenated_wide_data(stored_args, \n concatenate_df_list = concatenate_df_list, \n concatenate_df_sheet_name = concatenate_df_sheet_name,\n logger = logger)\n\n #Output concatenated long table\n output_concatenated_long_table(stored_args, \n concatenate_df_list = concatenate_df_list, \n concatenate_df_sheet_name = concatenate_df_sheet_name,\n logger = logger)\n\n #End log on a job\n logger.info(\"Job is finished.\")\n print(\"Job is finished\",flush=True)" ]
[ [ "pandas.DataFrame", "pandas.merge", "pandas.concat" ] ]
astrofyz/PH482_582
[ "bb36cfe78d91204f5907a2a79a49ea6af7d3ff0e" ]
[ "students_final_projects/group-f/gizmo_analysis/gizmo_file.py" ]
[ "#!/usr/bin/env python3\n\n'''\nEdit gizmo snapshot files: compress, delete, transfer across machines.\n\n@author: Andrew Wetzel <arwetzel@gmail.com>\n'''\n\n# system ----\nfrom __future__ import absolute_import, division, print_function # python 2 compatability\nimport os\nimport sys\nimport glob\nimport numpy as np\n# local ----\nimport utilities as ut\nfrom gizmo_analysis import gizmo_io\n\n# default subset of snapshots (65 snapshots)\nsnapshot_indices_keep = [\n 0, # z = 99\n 20, 26, 33, 41, 52, # z = 10 - 6\n 55, 57, 60, 64, 67, # z = 5.8 - 5.0\n 71, 75, 79, 83, 88, # z = 4.8 - 4.0\n 91, 93, 96, 99, 102, 105, 109, 112, 116, 120, # z = 3.9 - 3.0\n 124, 128, 133, 137, 142, 148, 153, 159, 165, 172, # z = 2.9 - 2.0\n 179, 187, 195, 204, 214, 225, 236, 248, 262, 277, # z = 1.9 - 1.0\n 294, 312, 332, 356, 382, 412, 446, 486, 534, # z = 0.9 - 0.1\n 539, 544, 550, 555, 561, 567, 573, 579, 585, # z = 0.09 - 0.01\n 600\n]\n\n\n#===================================================================================================\n# compress files\n#===================================================================================================\nclass CompressClass(ut.io.SayClass):\n\n def compress_snapshots(\n self, directory='output', directory_out='', snapshot_index_limits=[0, 600],\n thread_number=1):\n '''\n Compress all snapshots in input directory.\n\n Parameters\n ----------\n directory : str : directory of snapshots\n directory_out : str : directory to write compressed snapshots\n snapshot_index_limits : list : min and max snapshot indices to compress\n syncronize : bool : whether to synchronize parallel tasks,\n wait for each thread bundle to complete before starting new bundle\n '''\n snapshot_indices = np.arange(snapshot_index_limits[0], snapshot_index_limits[1] + 1)\n\n args_list = [(directory, directory_out, snapshot_index)\n for snapshot_index in snapshot_indices]\n\n ut.io.run_in_parallel(self.compress_snapshot, args_list, thread_number=thread_number)\n\n def compress_snapshot(\n self, directory='output', directory_out='', snapshot_index=600,\n analysis_directory='~/analysis', python_executable='python3'):\n '''\n Compress single snapshot (which may be multiple files) in input directory.\n\n Parameters\n ----------\n directory : str : directory of snapshot\n directory_out : str : directory to write compressed snapshot\n snapshot_index : int : index of snapshot\n analysis_directory : str : directory of analysis code\n '''\n executable = '{} {}/manipulate_hdf5/compactify_hdf5.py -L 0'.format(\n python_executable, analysis_directory)\n snapshot_name_base = 'snap*_{:03d}*'\n\n if directory[-1] != '/':\n directory += '/'\n if directory_out and directory_out[-1] != '/':\n directory_out += '/'\n\n path_file_names = glob.glob(directory + snapshot_name_base.format(snapshot_index))\n\n if len(path_file_names):\n if 'snapdir' in path_file_names[0]:\n path_file_names = glob.glob(path_file_names[0] + '/*')\n\n path_file_names.sort()\n\n for path_file_name in path_file_names:\n if directory_out:\n path_file_name_out = path_file_name.replace(directory, directory_out)\n else:\n path_file_name_out = path_file_name\n\n executable_i = '{} -o {} {}'.format(executable, path_file_name_out, path_file_name)\n self.say('executing: {}'.format(executable_i))\n os.system(executable_i)\n\n def test_compression(\n self, snapshot_indices='all', simulation_directory='.', snapshot_directory='output',\n compression_level=0):\n '''\n Read headers from all snapshot files in simulation_directory to check whether files have\n been compressed.\n '''\n header_compression_name = 'compression.level'\n\n simulation_directory = ut.io.get_path(simulation_directory)\n snapshot_directory = ut.io.get_path(snapshot_directory)\n\n Read = gizmo_io.ReadClass()\n\n compression_wrong_snapshots = []\n compression_none_snapshots = []\n\n if snapshot_indices is None or snapshot_indices == 'all':\n _path_file_names, snapshot_indices = Read.get_snapshot_file_names_indices(\n simulation_directory + snapshot_directory)\n elif np.isscalar(snapshot_indices):\n snapshot_indices = [snapshot_indices]\n\n for snapshot_index in snapshot_indices:\n header = Read.read_header('index', snapshot_index, simulation_directory, verbose=False)\n if header_compression_name in header:\n if (compression_level is not None and\n header[header_compression_name] != compression_level):\n compression_wrong_snapshots.append(snapshot_index)\n else:\n compression_none_snapshots.append(snapshot_index)\n\n self.say('* tested {} snapshots: {} - {}'.format(\n len(snapshot_indices), min(snapshot_indices), max(snapshot_indices)))\n self.say('* {} are uncompressed'.format(len(compression_none_snapshots)))\n if len(compression_none_snapshots):\n self.say('{}'.format(compression_none_snapshots))\n self.say('* {} have wrong compression (level != {})'.format(\n len(compression_wrong_snapshots), compression_level))\n if len(compression_wrong_snapshots):\n self.say('{}'.format(compression_wrong_snapshots))\n\n\nCompress = CompressClass()\n\n\n#===================================================================================================\n# transfer files via globus\n#===================================================================================================\nclass GlobusClass(ut.io.SayClass):\n\n def submit_transfer(\n self, simulation_path_directory='.', snapshot_directory='output',\n batch_file_name='globus_batch.txt', machine_name='peloton'):\n '''\n Submit globus transfer of simulation files.\n Must initiate from Stampede.\n\n Parameters\n ----------\n simulation_path_directory : str : '.' or full path + directory of simulation\n snapshot_directory : str : directory of snapshot files within simulation_directory\n batch_file_name : str : name of file to write\n machine_name : str : name of machine transfering files to\n '''\n # set directory from which to transfer\n simulation_path_directory = ut.io.get_path(simulation_path_directory)\n if simulation_path_directory == './':\n simulation_path_directory = os.getcwd()\n if simulation_path_directory[-1] != '/':\n simulation_path_directory += '/'\n\n command = 'globus transfer $(globus bookmark show stampede){}'.format(\n simulation_path_directory[1:]) # preceeding '/' already in globus bookmark\n\n path_directories = simulation_path_directory.split('/')\n simulation_directory = path_directories[-2]\n\n # parse machine + directory to transfer to\n if machine_name == 'peloton':\n if 'elvis' in simulation_directory:\n directory_to = 'm12_elvis'\n else:\n directory_to = simulation_directory.split('_')[0]\n directory_to += '/' + simulation_directory + '/'\n\n command += ' $(globus bookmark show peloton-scratch){}'.format(directory_to)\n\n # set globus parameters\n command += ' --sync-level=checksum --preserve-mtime --verify-checksum'\n command += ' --label \"{}\" --batch < {}'.format(simulation_directory, batch_file_name)\n\n # write globus batch file\n self.write_batch_file(simulation_path_directory, snapshot_directory, batch_file_name)\n\n self.say('* executing:\\n{}\\n'.format(command))\n os.system(command)\n\n def write_batch_file(\n self, simulation_directory='.', snapshot_directory='output', file_name='globus_batch.txt'):\n '''\n Write batch file that sets files to transfer via globus.\n\n Parameters\n ----------\n simulation_directory : str : directory of simulation\n snapshot_directory : str : directory of snapshot files within simulation_directory\n file_name : str : name of batch file to write\n '''\n simulation_directory = ut.io.get_path(simulation_directory)\n snapshot_directory = ut.io.get_path(snapshot_directory)\n\n transfer_string = ''\n\n # general files\n transfer_items = [\n 'gizmo/',\n 'gizmo_config.sh',\n 'gizmo_parameters.txt',\n 'gizmo_parameters.txt-usedvalues',\n 'gizmo.out.txt',\n 'snapshot_times.txt',\n 'notes.txt',\n\n 'track/',\n 'halo/rockstar_dm/catalog_hdf5/',\n ]\n for transfer_item in transfer_items:\n if os.path.exists(simulation_directory + transfer_item):\n command = '{} {}'\n if transfer_item[-1] == '/':\n transfer_item = transfer_item[:-1]\n command += ' --recursive'\n command = command.format(transfer_item, transfer_item) + '\\n'\n transfer_string += command\n\n # initial condition files\n transfer_items = glob.glob(simulation_directory + 'initial_condition*/*')\n for transfer_item in transfer_items:\n if '.ics' not in transfer_item:\n transfer_item = transfer_item.replace(simulation_directory, '')\n command = '{} {}\\n'.format(transfer_item, transfer_item)\n transfer_string += command\n\n # snapshot files\n for snapshot_index in snapshot_indices_keep:\n snapshot_name = '{}snapdir_{:03d}'.format(snapshot_directory, snapshot_index)\n if os.path.exists(simulation_directory + snapshot_name):\n snapshot_string = '{} {} --recursive\\n'.format(snapshot_name, snapshot_name)\n transfer_string += snapshot_string\n\n snapshot_name = '{}snapshot_{:03d}.hdf5'.format(snapshot_directory, snapshot_index)\n if os.path.exists(simulation_directory + snapshot_name):\n snapshot_string = '{} {}\\n'.format(snapshot_name, snapshot_name)\n transfer_string += snapshot_string\n\n with open(file_name, 'w') as file_out:\n file_out.write(transfer_string)\n\n\nGlobus = GlobusClass()\n\n\n#===================================================================================================\n# transfer files via rsync\n#===================================================================================================\ndef rsync_snapshots(\n machine_name, simulation_directory_from='', simulation_directory_to='.',\n snapshot_indices=snapshot_indices_keep):\n '''\n Use rsync to copy snapshot file[s].\n\n Parameters\n ----------\n machine_name : str : 'pfe', 'stampede', 'bw', 'peloton'\n directory_from : str : directory to copy from\n directory_to : str : local directory to put snapshots\n snapshot_indices : int or list : index[s] of snapshots to transfer\n '''\n snapshot_name_base = 'snap*_{:03d}*'\n\n directory_from = ut.io.get_path(simulation_directory_from) + 'output/'\n directory_to = ut.io.get_path(simulation_directory_to) + 'output/.'\n\n if np.isscalar(snapshot_indices):\n snapshot_indices = [snapshot_indices]\n\n snapshot_path_names = ''\n for snapshot_index in snapshot_indices:\n snapshot_path_names += (\n directory_from + snapshot_name_base.format(snapshot_index) + ' ')\n\n command = 'rsync -ahvP --size-only '\n command += '{}:\"{}\" {}'.format(machine_name, snapshot_path_names, directory_to)\n print('\\n* executing:\\n{}\\n'.format(command))\n os.system(command)\n\n\ndef rsync_simulation_files(\n machine_name, directory_from='/oldscratch/projects/xsede/GalaxiesOnFIRE', directory_to='.'):\n '''\n Use rsync to copy simulation files.\n\n Parameters\n ----------\n machine_name : str : 'pfe', 'stampede', 'bw', 'peloton'\n directory_from : str : directory to copy from\n directory_to : str : directory to put files\n '''\n excludes = [\n 'output/',\n 'restartfiles/',\n\n 'ewald_spc_table_64_dbl.dat',\n 'spcool_tables/',\n 'TREECOOL',\n\n 'energy.txt',\n 'balance.txt',\n 'GasReturn.txt',\n 'HIIheating.txt',\n 'MomWinds.txt',\n 'SNeIIheating.txt',\n\n '*.ics',\n\n 'snapshot_scale-factors.txt',\n 'submit_gizmo*.py',\n\n '*.bin',\n '*.particles',\n\n '*.bak',\n '*.err',\n '*.pyc',\n '*.o',\n '*.pro',\n '*.perl',\n '.ipynb_checkpoints',\n '.slurm',\n '.DS_Store',\n '*~',\n '._*',\n '#*#',\n ]\n\n directory_from = machine_name + ':' + ut.io.get_path(directory_from)\n directory_to = ut.io.get_path(directory_to)\n\n command = 'rsync -ahvP --size-only '\n\n arguments = ''\n for exclude in excludes:\n arguments += '--exclude=\"{}\" '.format(exclude)\n\n command += arguments + directory_from + ' ' + directory_to + '.'\n print('\\n* executing:\\n{}\\n'.format(command))\n os.system(command)\n\n\n#===================================================================================================\n# delete files\n#===================================================================================================\ndef delete_snapshots(\n snapshot_directory='output', snapshot_index_limits=[1, 599], delete_halos=False):\n '''\n Delete all snapshots in given directory within snapshot_index_limits,\n except for those in snapshot_indices_keep list.\n\n Parameters\n ----------\n snapshot_directory : str : directory of snapshots\n snapshot_index_limits : list : min and max snapshot indices to delete\n delete_halos : bool : whether to delete halo catalog files at same snapshot times\n '''\n snapshot_name_base = 'snap*_{:03d}*'\n if not snapshot_directory:\n snapshot_directory = 'output/'\n\n halo_name_base = 'halos_{:03d}*'\n halo_directory = 'halo/rockstar_dm/catalog/'\n\n if snapshot_directory[-1] != '/':\n snapshot_directory += '/'\n\n if snapshot_index_limits is None or not len(snapshot_index_limits):\n snapshot_index_limits = [1, 599]\n snapshot_indices = np.arange(snapshot_index_limits[0], snapshot_index_limits[1] + 1)\n\n print()\n for snapshot_index in snapshot_indices:\n if snapshot_index not in snapshot_indices_keep:\n snapshot_name = snapshot_directory + snapshot_name_base.format(snapshot_index)\n print('* deleting: {}'.format(snapshot_name))\n os.system('rm -rf {}'.format(snapshot_name))\n\n if delete_halos:\n halo_name = halo_directory + halo_name_base.format(snapshot_index)\n print('* deleting: {}'.format(halo_name))\n os.system('rm -rf {}'.format(halo_name))\n print()\n\n\n#===================================================================================================\n# running from command line\n#===================================================================================================\nif __name__ == '__main__':\n if len(sys.argv) <= 1:\n raise OSError('specify function to run: compress, globus, rsync, delete')\n\n function_kind = str(sys.argv[1])\n\n assert ('compress' in function_kind or 'rsync' in function_kind or 'globus' in function_kind or\n 'delete' in function_kind)\n\n if 'compress' in function_kind:\n directory = 'output'\n if len(sys.argv) > 2:\n directory = str(sys.argv[2])\n\n snapshot_index_max = 600\n if len(sys.argv) > 3:\n snapshot_index_max = int(sys.argv[3])\n snapshot_index_limits = [0, snapshot_index_max]\n\n Compress.compress_snapshots(directory, snapshot_index_limits=snapshot_index_limits)\n\n elif 'globus' in function_kind:\n directory = '.'\n if len(sys.argv) > 2:\n directory = str(sys.argv[2])\n Globus.submit_transfer(directory)\n\n elif 'rsync' in function_kind:\n if len(sys.argv) < 5:\n raise OSError(\n 'imports: machine_name simulation_directory_from simulation_directory_to')\n\n machine_name = str(sys.argv[2])\n simulation_directory_from = str(sys.argv[3])\n simulation_directory_to = str(sys.argv[4])\n\n rsync_simulation_files(machine_name, simulation_directory_from, simulation_directory_to)\n rsync_snapshots(machine_name, simulation_directory_from, simulation_directory_to)\n\n elif 'delete' in function_kind:\n directory = 'output'\n if len(sys.argv) > 3:\n directory = str(sys.argv[3])\n\n snapshot_index_limits = None\n if len(sys.argv) > 4:\n snapshot_index_limits = [int(sys.argv[4]), int(sys.argv[5])]\n\n delete_snapshots(directory, snapshot_index_limits)\n" ]
[ [ "numpy.arange", "numpy.isscalar" ] ]
yuchen071/Normal-map-generator
[ "40f92a38a75a35dcf4b8309517bf83b6a52b4fbb" ]
[ "train_norm.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jun 7 14:34:39 2021\n\n@author: Eric\n\"\"\"\n#%%\nfrom model import Unet\nfrom utils import random_fliplr, random_crop\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torchvision import transforms\nfrom torch.utils.data import DataLoader\nfrom torch.utils.data import Dataset\nfrom torch.utils.data import random_split\nfrom torchvision.utils import save_image\n# from torchinfo import summary\n\nimport os\nimport glob\nimport numpy as np\nfrom tqdm import tqdm\nfrom time import sleep\nfrom PIL import Image\nimport matplotlib.pyplot as plt\n\nimport json\nfrom torch.utils.tensorboard import SummaryWriter\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n#%%\nDIR_TRAIN = \"dataset/train\"\nDIR_VALID = \"valid\"\nDIR_TEST = \"test\"\nCHK_OUT = \"checkpoints/norm\"\nTEST_CROP = 512 # px\n\nPARAMS = {\n \"Type\": \"Normal net\",\n\n # \"pretrain\": \"norm_net_epoch_200.pth\",\n \"pretrain\": None,\n\n \"train\": {\n \"epochs\": 100,\n \"batch\": 4,\n \"lr\": 5e-4,\n \"split\": 0.9,\n \"nWorkers\": 2,\n },\n \n \"valid\": {\n \"num\": 2, # should be smaller than batch size\n \"log_interv\": 10,\n },\n\n \"image\": {\n \"img_resize\": 512,\n \"img_crop\": 512,\n \"rand_flip\": True,\n \"rand_crop\": None\n },\n\n \"writer\": False, # Tensorboard on/off\n}\n\nif not os.path.exists(DIR_VALID):\n os.makedirs(DIR_VALID)\nif not os.path.exists(CHK_OUT):\n os.makedirs(CHK_OUT)\nif PARAMS[\"train\"][\"batch\"] <= PARAMS[\"valid\"][\"num\"]:\n PARAMS[\"valid\"][\"num\"] = PARAMS[\"train\"][\"batch\"]\n\ndef pretty_json(hp):\n json_hp = json.dumps(hp, indent=2)\n return \"\".join(\"\\t\" + line for line in json_hp.splitlines(True))\n\n#%%\ntransform = transforms.Compose([\n transforms.Resize(PARAMS[\"image\"][\"img_resize\"]),\n transforms.CenterCrop(PARAMS[\"image\"][\"img_crop\"]),\n transforms.ToTensor(),\n transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)) # (input - mean) / std\n # outputs range from -1 to 1\n])\n\ntest_transform = transforms.Compose([\n transforms.Resize(TEST_CROP),\n transforms.CenterCrop(TEST_CROP),\n transforms.ToTensor(),\n transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)) # (input - mean) / std\n # outputs range from -1 to 1\n])\n\nclass TrainDataset(Dataset):\n def __init__(self, img_dir, target_dir, name_list):\n self.img_dir = img_dir\n self.target_dir = target_dir\n self.names = name_list\n\n def __len__(self):\n return len(self.names)\n\n def __str__(self):\n return self.names\n\n def __getitem__(self, i):\n img_filename = os.path.join(self.img_dir, self.names[i]) + \".jpg\"\n target_filename = os.path.join(self.target_dir, self.names[i]) + \".jpg\"\n\n img = Image.open(img_filename).convert('RGB')\n target = Image.open(target_filename).convert('RGB')\n img = transform(img)\n target = transform(target)\n\n return (img, target, self.names[i])\n\nclass TestDataset(Dataset):\n def __init__(self, img_dir):\n self.file_list = glob.glob(img_dir+\"/*.jpg\")\n self.names = [os.path.splitext(os.path.basename(fp))[0] for fp in self.file_list]\n\n def __len__(self):\n return len(self.names)\n\n def __getitem__(self, i):\n img = Image.open(self.file_list[i]).convert('RGB')\n img = test_transform(img)\n\n return img, self.names[i]\n\n#%%\ndef train(img_folder, label_folder, name_list, valid_folder, pretrained=None):\n\n data_train = TrainDataset(img_folder, label_folder, name_list)\n num_train = int(len(data_train) * PARAMS[\"train\"][\"split\"])\n data_train, data_valid = random_split(data_train, [num_train, len(data_train) - num_train])\n\n print(\"Train data: %d, Validation data: %d, Train batches: %.2f\\n\" % \\\n (len(data_train), len(data_valid), len(data_train)/PARAMS[\"train\"][\"batch\"]))\n\n trainloader = DataLoader(data_train, batch_size=PARAMS[\"train\"][\"batch\"],\n num_workers=PARAMS[\"train\"][\"nWorkers\"], shuffle=True, drop_last=True)\n validloader = DataLoader(data_valid, batch_size=PARAMS[\"train\"][\"batch\"], shuffle=False, num_workers=2)\n\n net = Unet()\n net.weight_init(mean=0.0, std=0.02)\n net.to(device)\n # summary(net, (1, 3, 512, 512))\n\n criterion = nn.MSELoss().to(device)\n optimizer = optim.Adam(net.parameters(), lr=PARAMS[\"train\"][\"lr\"], betas=(0.5, 0.999))\n\n # train\n train_loss_hist = []\n valid_loss_hist = []\n\n if pretrained:\n checkpoint = torch.load(os.path.join(CHK_OUT, pretrained))\n net.load_state_dict(checkpoint[\"model\"])\n optimizer.load_state_dict(checkpoint[\"optim\"])\n train_loss_hist = checkpoint[\"train_loss_hist\"]\n valid_loss_hist = checkpoint[\"valid_loss_hist\"]\n start_epoch = checkpoint[\"epoch\"]\n else:\n start_epoch = 0\n\n # fixed valid output\n v_num = PARAMS[\"valid\"][\"num\"]\n if len(data_valid) <= v_num:\n v_num = len(data_valid) # on the off-chance valid dataset only has 1 image\n\n valid_img_data = next(iter(validloader))\n valid_img_data = [data[:v_num] for data in valid_img_data]\n if PARAMS[\"image\"][\"rand_crop\"]:\n valid_img_data[0], valid_img_data[1] = random_crop(valid_img_data[0], valid_img_data[1], PARAMS[\"image\"][\"rand_crop\"])\n\n # tensorboard\n if PARAMS[\"writer\"]:\n writer = SummaryWriter()\n writer.add_text(\"Parameters\", pretty_json(PARAMS), 0)\n writer.add_text(\"Validation images\", str(valid_img_data[2]), 0)\n\n sleep(0.3)\n for epoch in range(start_epoch, PARAMS[\"train\"][\"epochs\"]):\n # train\n pbar = tqdm(trainloader, ascii=True, bar_format='{l_bar}{bar:10}{r_bar}')\n p_desc = \"Train %2d/%d\" % (epoch + 1, PARAMS[\"train\"][\"epochs\"])\n pbar.set_description(p_desc)\n\n net.train()\n tmp_loss = []\n for batch_id, (img_in, target, _) in enumerate(pbar):\n\n if PARAMS[\"image\"][\"rand_flip\"]:\n img_in, target = random_fliplr(img_in, target)\n\n if PARAMS[\"image\"][\"rand_crop\"]:\n img_in, target = random_crop(img_in, target, PARAMS[\"image\"][\"rand_crop\"])\n\n img_in = img_in.to(device)\n target = target.to(device)\n\n optimizer.zero_grad()\n img_out = net(img_in)\n loss = criterion(img_out, target)\n loss.backward()\n optimizer.step()\n\n tmp_loss.append(loss.item())\n\n p_post = f\"T_Loss: {loss.item(): .4f}\"\n pbar.set_postfix_str(p_post)\n pbar.update(0)\n\n train_loss_hist.append(np.mean(tmp_loss))\n\n if PARAMS[\"writer\"]:\n writer.add_scalar(\"Loss/Train\", train_loss_hist[-1], epoch)\n\n # validation\n pbar = tqdm(validloader, ascii=True, bar_format='{l_bar}{bar:10}{r_bar}')\n p_desc = \"Valid %2d/%d\" % (epoch + 1, PARAMS[\"train\"][\"epochs\"])\n pbar.set_description(p_desc)\n\n net.eval()\n tmp_loss = []\n with torch.no_grad():\n for batch_id, (img_in, target, _) in enumerate(pbar):\n\n if PARAMS[\"image\"][\"rand_flip\"]:\n img_in, target = random_fliplr(img_in, target)\n\n if PARAMS[\"image\"][\"rand_crop\"]:\n img_in, target = random_crop(img_in, target, PARAMS[\"image\"][\"rand_crop\"])\n\n img_in = img_in.to(device)\n target = target.to(device)\n\n img_out = net(img_in)\n loss = criterion(img_out, target)\n\n tmp_loss.append(loss.item())\n\n p_post = f\"V_Loss: {loss.item(): .4f}\"\n pbar.set_postfix_str(p_post)\n pbar.update(0)\n\n valid_loss_hist.append(np.mean(tmp_loss))\n\n if PARAMS[\"writer\"]:\n writer.add_scalar(\"Loss/Valid\", valid_loss_hist[-1], epoch)\n\n if (epoch+1) % PARAMS[\"valid\"][\"log_interv\"] == 0 or epoch == 0:\n with torch.no_grad():\n img_in = valid_img_data[0].to(device)\n target = valid_img_data[1].to(device)\n img_out = net(img_in)\n\n imgs = torch.cat([img_in, target, img_out])\n save_image(imgs, os.path.join(valid_folder, f\"epoch_{epoch+1}.png\"),\n value_range=(-1,1), normalize=True, nrow=v_num)\n\n # save pth\n torch.save({\n \"epoch\": epoch+1,\n \"model\": net.state_dict(),\n \"optim\": optimizer.state_dict(),\n \"train_loss_hist\": train_loss_hist,\n \"valid_loss_hist\": valid_loss_hist\n }, os.path.join(CHK_OUT, f\"norm_net_epoch_{epoch+1:03}.pth\"))\n\n plotLoss(train_loss_hist, valid_loss_hist, \"Loss history\")\n\n # tensorboard\n if PARAMS[\"writer\"]:\n writer.flush()\n writer.close()\n\n return net\n\n#%% test\ndef test(net, in_folder, out_folder):\n data_test = TestDataset(in_folder)\n batch_size = len(data_test)\n # print(batch_size)\n testloader = DataLoader(data_test, batch_size=batch_size, shuffle=False)\n\n print(\"\\nOutput test files...\")\n\n net.eval()\n with torch.no_grad():\n for idx, data in enumerate(testloader):\n img_in = data[0].to(device)\n img_out = net(img_in)\n # print(img_name)\n out_filename = os.path.join(out_folder, \"output.png\")\n save_image(torch.cat([img_in, img_out]), out_filename, value_range=(-1,1), normalize=True, nrow=batch_size)\n\n print(\"Done!\")\n\n#%%\ndef plotLoss(t_hist, v_hist, title):\n plt.figure()\n plt.plot(t_hist, label=\"Train\")\n plt.plot(v_hist, label=\"Valid\")\n plt.title(title)\n plt.legend()\n plt.xlabel(\"Epochs\")\n plt.show()\n\n#%%\ndef main():\n # ==== train normal ====\n print(\"Normal map\")\n color_folder = os.path.join(DIR_TRAIN, \"color\")\n norm_folder = os.path.join(DIR_TRAIN, \"normal\")\n name_txt = os.path.join(DIR_TRAIN, \"name_list.txt\")\n\n with open(name_txt, \"r\") as f:\n name_list = [line.rstrip('\\n') for line in f.readlines()]\n\n test_in_folder = os.path.join(DIR_TEST, \"input\")\n test_norm_folder = os.path.join(DIR_TEST, \"output_norm\")\n valid_folder = os.path.join(DIR_VALID, \"norm\")\n if not os.path.exists(test_norm_folder):\n os.makedirs(test_norm_folder)\n if not os.path.exists(valid_folder):\n os.makedirs(valid_folder)\n\n norm_net = train(color_folder, norm_folder, name_list, valid_folder, pretrained=PARAMS[\"pretrain\"])\n test(norm_net, test_in_folder, test_norm_folder)\n if str(device) == 'cuda':\n torch.cuda.empty_cache()\n\nif __name__ == \"__main__\":\n main()\n\n" ]
[ [ "torch.cat", "torch.nn.MSELoss", "matplotlib.pyplot.xlabel", "torch.no_grad", "matplotlib.pyplot.plot", "matplotlib.pyplot.legend", "matplotlib.pyplot.title", "numpy.mean", "matplotlib.pyplot.figure", "torch.cuda.empty_cache", "torch.cuda.is_available", "torch.utils.data.DataLoader", "matplotlib.pyplot.show", "torch.utils.tensorboard.SummaryWriter" ] ]
lc0/nn
[ "0de7e343a11685de37a03ae4ee2510d18fc07369" ]
[ "labml_nn/transformers/feedback/experiment.py" ]
[ "\"\"\"\n---\ntitle: Train Feedback Transformer\nsummary: This is training code with notes for a feedback transformer.\n---\n\n# Train Feedback Transformer\n\nThis trains a [feedback transformer](index.html) model for auto-regression.\nYou can pick the original feedback transformer or the new version\nwhere the keys and values are precalculated.\n\nHere's a Colab notebook for training a feedback transformer on Tiny Shakespeare dataset.\n\n[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/lab-ml/nn/blob/master/labml_nn/transformers/feedback/experiment.ipynb)\n[![View Run](https://img.shields.io/badge/labml-experiment-brightgreen)](https://web.lab-ml.com/run?uuid=d8eb9416530a11eb8fb50242ac1c0002)\n\"\"\"\n\nimport torch\nfrom torch import nn\n\nfrom labml import experiment\nfrom labml.configs import option\nfrom labml.utils.pytorch import get_modules\nfrom labml_helpers.module import Module\n\nfrom labml_nn.experiments.nlp_autoregression import NLPAutoRegressionConfigs\nfrom labml_nn.transformers import Encoder, Generator, TransformerConfigs\nfrom labml_nn.transformers.utils import subsequent_mask\n\n\nclass AutoregressiveModel(Module):\n \"\"\"\n ## Auto regressive model\n \"\"\"\n\n def __init__(self, n_vocab: int, d_model: int, transformer: Module):\n super().__init__()\n # Token embedding module\n self.src_embed = nn.Embedding(n_vocab, d_model)\n self.transformer = transformer\n self.generator = nn.Linear(d_model, n_vocab)\n\n def __call__(self, x: torch.Tensor):\n # Embed the tokens\n x = self.src_embed(x)\n # Run it through the the transformer\n res = self.transformer(x)\n # Generate logits of the next token\n return self.generator(res), None\n\n\nclass Configs(NLPAutoRegressionConfigs):\n \"\"\"\n ## Configurations\n\n The default configs can and will be over-ridden when we start the experiment\n \"\"\"\n\n model: AutoregressiveModel\n\n d_model: int = 512\n heads: int = 8\n dropout: float = 0.0\n d_ff: int = 2048\n n_layers: int = 6\n\n\n@option(Configs.model)\ndef feedback_transformer(c: Configs):\n \"\"\"\n Create [original feedback transformer](index.html).\n \"\"\"\n from labml_nn.transformers.feedback import FeedbackTransformer, FeedbackTransformerLayer, \\\n FeedbackAttention, FeedForward\n\n return AutoregressiveModel(\n c.n_tokens, c.d_model,\n FeedbackTransformer(\n FeedbackTransformerLayer(d_model=c.d_model,\n attn=FeedbackAttention(c.heads, c.d_model, c.dropout),\n feed_forward=FeedForward(c.d_model, c.d_ff, c.dropout),\n dropout_prob=c.dropout),\n c.n_layers)).to(c.device)\n\n\n@option(Configs.model)\ndef feedback_transformer_kv(c: Configs):\n \"\"\"\n Create [updated feedback transformer](index.html#kv_shared), with precalculated keys and values.\n \"\"\"\n from labml_nn.transformers.feedback import FeedbackTransformerKV, FeedbackTransformerLayer, \\\n FeedbackAttention, FeedForward\n\n return AutoregressiveModel(\n c.n_tokens, c.d_model,\n FeedbackTransformerKV(\n FeedbackTransformerLayer(d_model=c.d_model,\n attn=FeedbackAttention(c.heads, c.d_model, c.dropout,\n is_kv_precomputed=True),\n feed_forward=FeedForward(c.d_model, c.d_ff, c.dropout),\n dropout_prob=c.dropout),\n c.n_layers, c.d_model, c.heads)).to(c.device)\n\n\ndef main():\n # Create experiment\n experiment.create(name=\"feedback_transformer\")\n # Create configs\n conf = Configs()\n # Load configurations\n experiment.configs(conf,\n # A dictionary of configurations to override\n {'tokenizer': 'character',\n 'text': 'tiny_shakespeare',\n 'optimizer.learning_rate': 1.0,\n 'optimizer.optimizer': 'Noam',\n 'prompt': 'It is',\n 'prompt_separator': '',\n\n # Use `feedback_transformer` for original feedback transformer\n 'model': 'feedback_transformer_kv',\n\n 'train_loader': 'shuffled_train_loader',\n 'valid_loader': 'shuffled_valid_loader',\n\n 'seq_len': 128,\n 'epochs': 128,\n 'batch_size': 64,\n 'inner_iterations': 25})\n\n # Set models for saving and loading\n experiment.add_pytorch_models(get_modules(conf))\n\n # Start the experiment\n with experiment.start():\n # Run the training loop\n conf.run()\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "torch.nn.Linear", "torch.nn.Embedding" ] ]
VincentWang25/Kaggle_TGBR
[ "9a93d8cf75ae0a9716a72cb6da49645eac63a641" ]
[ "src/util.py" ]
[ "import sys\nimport cv2\nimport os\nfrom ast import literal_eval\nfrom pathlib import Path\nimport shutil\nimport logging\nimport random\nimport pickle\nimport yaml\nimport subprocess\nfrom PIL import Image\nfrom glob import glob\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom matplotlib import animation, rc\nplt.rcParams['figure.figsize'] = 30, 30\nnp.set_printoptions(precision=3, suppress=True)\nrc('animation', html='jshtml')\n\nimport torch\n\nfrom augmentations import get_albu_transforms\n\n\nIMAGE_DIR = '~/Kaggle/data/tensorflow-great-barrier-reef/train_images'\n\ndef load_image(video_id, video_frame, image_dir):\n img_path = f'{image_dir}/video_{video_id}/{video_frame}.jpg'\n assert os.path.exists(img_path), f'{img_path} does not exist.'\n img = cv2.imread(img_path)\n return img\n\ndef decode_annotations(annotaitons_str):\n \"\"\"decode annotations in string to list of dict\"\"\"\n return literal_eval(annotaitons_str)\n\n\ndef load_image_with_annotations(video_id, video_frame, image_dir, annotaitons_str):\n img = load_image(video_id, video_frame, image_dir)\n annotations = decode_annotations(annotaitons_str)\n if len(annotations) > 0:\n for ann in annotations:\n cv2.rectangle(img, (ann['x'], ann['y']),\n (ann['x'] + ann['width'], ann['y'] + ann['height']),\n (255, 0, 0), thickness=2,)\n return img\n\ndef draw_predictions(img, pred_bboxes):\n img = img.copy()\n if len(pred_bboxes) > 0:\n for bbox in pred_bboxes:\n conf = bbox[0]\n x, y, w, h = bbox[1:].round().astype(int)\n cv2.rectangle(img, (x, y),(x+w, y+h),(0, 255, 255), thickness=2,)\n cv2.putText(img, f\"{conf:.2}\",(x, max(0, y-5)),\n cv2.FONT_HERSHEY_SIMPLEX,0.5,(0, 0, 255),\n thickness=1,\n )\n return img\n\ndef plot_img(df, idx, image_dir, pred_bboxes=None):\n row = df.iloc[idx]\n video_id = row.video_id\n video_frame = row.video_frame\n annotations_str = row.annotations\n img = load_image_with_annotations(video_id, video_frame, image_dir, annotations_str)\n \n if pred_bboxes and len(pred_bboxes) > 0:\n pred_bboxes = pred_bboxes[pred_bboxes[:,0].argsort()[::-1]] # sort by conf\n img = draw_predictions(img, pred_bboxes)\n plt.imshow(img[:, :, ::-1]) \n \ndef calc_iou(bboxes1, bboxes2, bbox_mode='xywh'):\n assert len(bboxes1.shape) == 2 and bboxes1.shape[1] == 4\n assert len(bboxes2.shape) == 2 and bboxes2.shape[1] == 4\n \n bboxes1 = bboxes1.copy()\n bboxes2 = bboxes2.copy()\n \n if bbox_mode == 'xywh':\n bboxes1[:, 2:] += bboxes1[:, :2]\n bboxes2[:, 2:] += bboxes2[:, :2]\n\n x11, y11, x12, y12 = np.split(bboxes1, 4, axis=1)\n x21, y21, x22, y22 = np.split(bboxes2, 4, axis=1)\n xA = np.maximum(x11, np.transpose(x21))\n yA = np.maximum(y11, np.transpose(y21))\n xB = np.minimum(x12, np.transpose(x22))\n yB = np.minimum(y12, np.transpose(y22))\n interArea = np.maximum((xB - xA + 1e-9), 0) * np.maximum((yB - yA + 1e-9), 0)\n boxAArea = (x12 - x11 + 1e-9) * (y12 - y11 + 1e-9)\n boxBArea = (x22 - x21 + 1e-9) * (y22 - y21 + 1e-9)\n iou = interArea / (boxAArea + np.transpose(boxBArea) - interArea)\n return iou\n\ndef f_beta(tp, fp, fn, beta=2):\n if tp == 0:\n return 0\n return (1+beta**2)*tp / ((1+beta**2)*tp + beta**2*fn+fp)\n\ndef calc_is_correct_at_iou_th(gt_bboxes, pred_bboxes, iou_th, verbose=False):\n gt_bboxes = gt_bboxes.copy()\n pred_bboxes = pred_bboxes.copy()\n \n tp = 0\n fp = 0\n for k, pred_bbox in enumerate(pred_bboxes): # fixed in ver.7\n if len(gt_bboxes) == 0:\n fp += len(pred_bboxes) - k # fix in ver.7\n break\n ious = calc_iou(gt_bboxes, pred_bbox[None, 1:])\n max_iou = ious.max()\n if max_iou >= iou_th:\n tp += 1\n gt_bboxes = np.delete(gt_bboxes, ious.argmax(), axis=0)\n else:\n fp += 1\n\n fn = len(gt_bboxes)\n return tp, fp, fn\n\ndef calc_is_correct(gt_bboxes, pred_bboxes, iou_th=0.5):\n \"\"\"\n gt_bboxes: (N, 4) np.array in xywh format\n pred_bboxes: (N, 5) np.array in conf+xywh format\n \"\"\"\n if len(gt_bboxes) == 0 and len(pred_bboxes) == 0:\n tps, fps, fns = 0, 0, 0\n return tps, fps, fns\n\n elif len(gt_bboxes) == 0:\n tps, fps, fns = 0, len(pred_bboxes), 0\n return tps, fps, fns\n\n elif len(pred_bboxes) == 0:\n tps, fps, fns = 0, 0, len(gt_bboxes)\n return tps, fps, fns\n\n pred_bboxes = pred_bboxes[pred_bboxes[:,0].argsort()[::-1]] # sort by conf\n\n tps, fps, fns = 0, 0, 0\n tp, fp, fn = calc_is_correct_at_iou_th(gt_bboxes, pred_bboxes, iou_th)\n tps += tp\n fps += fp\n fns += fn\n return tps, fps, fns\n\ndef calc_f2_score(gt_bboxes_list, pred_bboxes_list, verbose=False):\n \"\"\"\n gt_bboxes_list: list of (N, 4) np.array in xywh format\n pred_bboxes_list: list of (N, 5) np.array in conf+xywh format\n \"\"\"\n #f2s = []\n f2_dict = {'f2':0, \"P\":0, \"R\": 0}\n all_tps = [list([0] * 11) for _ in range(len(gt_bboxes_list))]\n all_fps = [list([0] * 11) for _ in range(len(gt_bboxes_list))]\n all_fns = [list([0] * 11) for _ in range(len(gt_bboxes_list))]\n for k, iou_th in enumerate(np.arange(0.3, 0.85, 0.05)):\n tps, fps, fns = 0, 0, 0\n for i, (gt_bboxes, pred_bboxes) in enumerate(zip(gt_bboxes_list, pred_bboxes_list)):\n tp, fp, fn = calc_is_correct(gt_bboxes, pred_bboxes, iou_th)\n tps += tp\n fps += fp\n fns += fn\n all_tps[i][k] = tp\n all_fps[i][k] = fp\n all_fns[i][k] = fn\n if verbose:\n num_gt = len(gt_bboxes)\n num_pred = len(pred_bboxes)\n print(f'num_gt:{num_gt:<3} num_pred:{num_pred:<3} tp:{tp:<3} fp:{fp:<3} fn:{fn:<3}')\n f2 = f_beta(tps, fps, fns, beta=2) \n precision = f_beta(tps, fps, fns, beta=0)\n recall = f_beta(tps, fps, fns, beta=100)\n f2_dict[\"f2_\" + str(round(iou_th,3))] = f2\n f2_dict[\"P_\" + str(round(iou_th,3))] = precision\n f2_dict[\"R_\" + str(round(iou_th,3))] = recall\n f2_dict['f2'] += f2 / 11\n f2_dict['P'] += precision / 11\n f2_dict['R'] += recall / 11\n f2_dict[\"tps\"] = all_tps\n f2_dict[\"fps\"] = all_fps\n f2_dict[\"fns\"] = all_fns\n return f2_dict\n\ndef print_f2_dict(d):\n print(\"Overall f2: {:.3f}, precision {:.3f}, recall {:.3f}\".format(d['f2'], d['precision'], d['recall']))\n for k, iou_th in enumerate(np.arange(0.3, 0.85, 0.05)):\n print(f\"IOU {iou_th:.2f}:\", end=\" \")\n print(\"f2: {:.3f}, precision {:.3f}, recall {:.3f}\".format(d[\"f2_\" + str(round(iou_th,3))], \n d[\"precision_\" + str(round(iou_th,3))], \n d[\"recall_\" + str(round(iou_th,3))]))\n \n \n\ndef get_path(row, params, infer=False):\n row['old_image_path'] = params['root_dir'] / f'train_images/video_{row.video_id}/{row.video_frame}.jpg'\n if infer:\n row['image_path'] = row[\"old_image_path\"]\n else:\n row['image_path'] = params['image_dir'] / f'video_{row.video_id}_{row.video_frame}.jpg'\n row['label_path'] = params['label_dir'] / f'video_{row.video_id}_{row.video_frame}.txt'\n return row\n\ndef make_copy(path, params):\n # TODO: fix split issue\n data = str(path).split('/')\n filename = data[-1]\n video_id = data[-2]\n new_path = params[\"image_dir\"] / f'{video_id}_{filename}'\n shutil.copy(path, new_path)\n return\n\n# https://www.kaggle.com/awsaf49/great-barrier-reef-yolov5-train\ndef voc2yolo(image_height, image_width, bboxes):\n \"\"\"\n voc => [x1, y1, x2, y1]\n yolo => [xmid, ymid, w, h] (normalized)\n \"\"\"\n \n bboxes = bboxes.copy().astype(float) # otherwise all value will be 0 as voc_pascal dtype is np.int\n \n bboxes[..., [0, 2]] = bboxes[..., [0, 2]]/ image_width\n bboxes[..., [1, 3]] = bboxes[..., [1, 3]]/ image_height\n \n w = bboxes[..., 2] - bboxes[..., 0]\n h = bboxes[..., 3] - bboxes[..., 1]\n \n bboxes[..., 0] = bboxes[..., 0] + w/2\n bboxes[..., 1] = bboxes[..., 1] + h/2\n bboxes[..., 2] = w\n bboxes[..., 3] = h\n \n return bboxes\n\ndef yolo2voc(image_height, image_width, bboxes):\n \"\"\"\n yolo => [xmid, ymid, w, h] (normalized)\n voc => [x1, y1, x2, y1]\n \n \"\"\" \n bboxes = bboxes.copy().astype(float) # otherwise all value will be 0 as voc_pascal dtype is np.int\n \n bboxes[..., [0, 2]] = bboxes[..., [0, 2]]* image_width\n bboxes[..., [1, 3]] = bboxes[..., [1, 3]]* image_height\n \n bboxes[..., [0, 1]] = bboxes[..., [0, 1]] - bboxes[..., [2, 3]]/2\n bboxes[..., [2, 3]] = bboxes[..., [0, 1]] + bboxes[..., [2, 3]]\n \n return bboxes\n\ndef coco2yolo(image_height, image_width, bboxes):\n \"\"\"\n coco => [xmin, ymin, w, h]\n yolo => [xmid, ymid, w, h] (normalized)\n \"\"\"\n \n bboxes = bboxes.copy().astype(float) # otherwise all value will be 0 as voc_pascal dtype is np.int\n \n # normolizinig\n bboxes[..., [0, 2]]= bboxes[..., [0, 2]]/ image_width\n bboxes[..., [1, 3]]= bboxes[..., [1, 3]]/ image_height\n \n # converstion (xmin, ymin) => (xmid, ymid)\n bboxes[..., [0, 1]] = bboxes[..., [0, 1]] + bboxes[..., [2, 3]]/2\n \n return bboxes\n\ndef yolo2coco(image_height, image_width, bboxes):\n \"\"\"\n yolo => [xmid, ymid, w, h] (normalized)\n coco => [xmin, ymin, w, h]\n \n \"\"\" \n bboxes = bboxes.copy().astype(float) # otherwise all value will be 0 as voc_pascal dtype is np.int\n \n # denormalizing\n bboxes[..., [0, 2]]= bboxes[..., [0, 2]]* image_width\n bboxes[..., [1, 3]]= bboxes[..., [1, 3]]* image_height\n \n # converstion (xmid, ymid) => (xmin, ymin) \n bboxes[..., [0, 1]] = bboxes[..., [0, 1]] - bboxes[..., [2, 3]]/2\n \n return bboxes\n\ndef voc2coco(bboxes, image_height=720, image_width=1280):\n bboxes = voc2yolo(image_height, image_width, bboxes)\n bboxes = yolo2coco(image_height, image_width, bboxes)\n return bboxes\n\n\ndef load_image(image_path):\n return cv2.cvtColor(cv2.imread(image_path), cv2.COLOR_BGR2RGB)\n\ndef plot_one_box(x, img, color=None, label=None, line_thickness=None):\n # Plots one bounding box on image img\n tl = line_thickness or round(0.002 * (img.shape[0] + img.shape[1]) / 2) + 1 # line/font thickness\n color = color or [random.randint(0, 255) for _ in range(3)]\n c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3]))\n cv2.rectangle(img, c1, c2, color, thickness=tl, lineType=cv2.LINE_AA)\n if label:\n tf = max(tl - 1, 1) # font thickness\n t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]\n c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3\n cv2.rectangle(img, c1, c2, color, -1, cv2.LINE_AA) # filled\n cv2.putText(img, label, (c1[0], c1[1] - 2), 0, tl / 3, [225, 255, 255], thickness=tf, lineType=cv2.LINE_AA)\n \n \ndef draw_bboxes(img, bboxes, classes, colors = None, show_classes = None, bbox_format = 'yolo', class_name = False, line_thickness = 1): \n \n image = img.copy()\n show_classes = classes if show_classes is None else show_classes\n colors = (0, 255 ,0) if colors is None else colors\n \n if bbox_format == 'yolo':\n \n for idx in range(len(bboxes)): \n \n bbox = bboxes[idx]\n cls = classes[idx]\n color = colors[idx]\n if cls in show_classes:\n \n x1 = round(float(bbox[0])*image.shape[1])\n y1 = round(float(bbox[1])*image.shape[0])\n w = round(float(bbox[2])*image.shape[1]/2) #w/2 \n h = round(float(bbox[3])*image.shape[0]/2)\n\n voc_bbox = (x1-w, y1-h, x1+w, y1+h)\n plot_one_box(voc_bbox, \n image,\n color = color,\n label = cls if class_name else str(get_label(cls)),\n line_thickness = line_thickness)\n \n elif bbox_format == 'coco':\n \n for idx in range(len(bboxes)): \n \n bbox = bboxes[idx]\n cls = classes[idx]\n color = colors[idx]\n \n if cls in show_classes: \n x1 = int(round(bbox[0]))\n y1 = int(round(bbox[1]))\n w = int(round(bbox[2]))\n h = int(round(bbox[3]))\n\n voc_bbox = (x1, y1, x1+w, y1+h)\n plot_one_box(voc_bbox, \n image,\n color = color,\n label = cls,\n line_thickness = line_thickness)\n\n elif bbox_format == 'voc_pascal':\n \n for idx in range(len(bboxes)): \n \n bbox = bboxes[idx]\n cls = classes[idx]\n cls_id = class_ids[idx]\n color = colors[cls_id] if type(colors) is list else colors\n \n if cls in show_classes: \n x1 = int(round(bbox[0]))\n y1 = int(round(bbox[1]))\n x2 = int(round(bbox[2]))\n y2 = int(round(bbox[3]))\n voc_bbox = (x1, y1, x2, y2)\n plot_one_box(voc_bbox, \n image,\n color = color,\n label = cls if class_name else str(cls_id),\n line_thickness = line_thickness)\n else:\n raise ValueError('wrong bbox format')\n\n return image\n\ndef get_bbox(annots):\n bboxes = [list(annot.values()) for annot in annots]\n return bboxes\n\ndef get_imgsize(row):\n row['width'], row['height'] = imagesize.get(row['image_path'])\n return row\n\n\n# https://www.kaggle.com/diegoalejogm/great-barrier-reefs-eda-with-animations\ndef create_animation(ims):\n fig = plt.figure(figsize=(16, 12))\n plt.axis('off')\n im = plt.imshow(ims[0])\n\n def animate_func(i):\n im.set_array(ims[i])\n return [im]\n\n return animation.FuncAnimation(fig, animate_func, frames = len(ims), interval = 1000//12)\n\n# https://github.com/rbgirshick/fast-rcnn/blob/master/lib/utils/nms.py\ndef nms(dets, thresh):\n x1 = dets[:, 0]\n y1 = dets[:, 1]\n x2 = dets[:, 2]\n y2 = dets[:, 3]\n scores = dets[:, 4]\n\n areas = (x2 - x1 + 1) * (y2 - y1 + 1)\n order = scores.argsort()[::-1]\n\n keep = []\n while order.size > 0:\n i = order[0]\n keep.append(i)\n xx1 = np.maximum(x1[i], x1[order[1:]])\n yy1 = np.maximum(y1[i], y1[order[1:]])\n xx2 = np.minimum(x2[i], x2[order[1:]])\n yy2 = np.minimum(y2[i], y2[order[1:]])\n\n w = np.maximum(0.0, xx2 - xx1 + 1)\n h = np.maximum(0.0, yy2 - yy1 + 1)\n inter = w * h\n ovr = inter / (areas[i] + areas[order[1:]] - inter)\n\n inds = np.where(ovr <= thresh)[0]\n order = order[inds + 1]\n\n return keep\n\n# https://github.com/DocF/Soft-NMS/blob/master/soft_nms.py\n\ndef py_cpu_softnms(dets, sc, Nt=0.3, sigma=0.5, thresh=0.001, method=2):\n \"\"\"\n py_cpu_softnms\n :param dets: boexs 坐标矩阵 format [y1, x1, y2, x2]\n :param sc: 每个 boxes 对应的分数\n :param Nt: iou 交叠门限\n :param sigma: 使用 gaussian 函数的方差\n :param thresh: 最后的分数门限\n :param method: 使用的方法\n :return: 留下的 boxes 的 index\n \"\"\"\n\n # indexes concatenate boxes with the last column\n N = dets.shape[0]\n indexes = np.array([np.arange(N)])\n dets = np.concatenate((dets, indexes.T), axis=1)\n\n # the order of boxes coordinate is [y1,x1,y2,x2]\n y1 = dets[:, 0]\n x1 = dets[:, 1]\n y2 = dets[:, 2]\n x2 = dets[:, 3]\n scores = sc\n areas = (x2 - x1 + 1) * (y2 - y1 + 1)\n\n for i in range(N):\n # intermediate parameters for later parameters exchange\n tBD = dets[i, :].copy()\n tscore = scores[i].copy()\n tarea = areas[i].copy()\n pos = i + 1\n\n #\n if i != N-1:\n maxscore = np.max(scores[pos:], axis=0)\n maxpos = np.argmax(scores[pos:], axis=0)\n else:\n maxscore = scores[-1]\n maxpos = 0\n if tscore < maxscore:\n dets[i, :] = dets[maxpos + i + 1, :]\n dets[maxpos + i + 1, :] = tBD\n tBD = dets[i, :]\n\n scores[i] = scores[maxpos + i + 1]\n scores[maxpos + i + 1] = tscore\n tscore = scores[i]\n\n areas[i] = areas[maxpos + i + 1]\n areas[maxpos + i + 1] = tarea\n tarea = areas[i]\n\n # IoU calculate\n xx1 = np.maximum(dets[i, 1], dets[pos:, 1])\n yy1 = np.maximum(dets[i, 0], dets[pos:, 0])\n xx2 = np.minimum(dets[i, 3], dets[pos:, 3])\n yy2 = np.minimum(dets[i, 2], dets[pos:, 2])\n\n w = np.maximum(0.0, xx2 - xx1 + 1)\n h = np.maximum(0.0, yy2 - yy1 + 1)\n inter = w * h\n ovr = inter / (areas[i] + areas[pos:] - inter)\n\n # Three methods: 1.linear 2.gaussian 3.original NMS\n if method == 1: # linear\n weight = np.ones(ovr.shape)\n weight[ovr > Nt] = weight[ovr > Nt] - ovr[ovr > Nt]\n elif method == 2: # gaussian\n weight = np.exp(-(ovr * ovr) / sigma)\n else: # original NMS\n weight = np.ones(ovr.shape)\n weight[ovr > Nt] = 0\n\n scores[pos:] = weight * scores[pos:]\n\n # select the boxes and keep the corresponding indexes\n inds = dets[:, 4][scores > thresh]\n keep = inds.astype(int)\n\n return keep\n\n\ndef seed_torch(seed=42):\n random.seed(seed)\n os.environ['PYTHONHASHSEED'] = str(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n torch.backends.cudnn.deterministic = True\n \n \ndef create_logger(filename, filemode='a'):\n # better logging file - output the in terminal as well\n file_handler = logging.FileHandler(filename=filename, mode=filemode)\n stdout_handler = logging.StreamHandler(sys.stdout)\n handlers = [file_handler, stdout_handler]\n formatter = \"%(asctime)s %(levelname)s: %(message)s\"\n datefmt = \"%m/%d/%Y %I:%M:%S %p\"\n logging.basicConfig(format=formatter, datefmt=datefmt, \n level=logging.DEBUG, handlers=handlers)\n return\n\ndef save_pickle(obj, folder_path):\n pickle.dump(obj, open(folder_path, 'wb'), pickle.HIGHEST_PROTOCOL)\n\ndef load_pickle(folder_path):\n return pickle.load(open(folder_path, 'rb'))\n\ndef save_yaml(obj, folder_path):\n obj2 = obj.copy()\n for key, value in obj2.items():\n if isinstance(value, Path):\n obj2[key] = str(value.resolve())\n else:\n obj2[key] = value\n with open(folder_path, 'w') as file:\n yaml.dump(obj2, file) \n \ndef load_yaml(folder_path):\n with open(folder_path) as file:\n data = yaml.load(file, Loader=yaml.FullLoader)\n return data\n\ndef load_model(params):\n try:\n model = torch.hub.load(params['repo'],\n 'custom',\n path=params['ckpt_path'],\n source='local',\n force_reload=True) # local repo\n except:\n print(\"torch.hub.load failed, try torch.load\")\n model = torch.load(params['ckpt_path'])\n model.conf = params['conf'] # NMS confidence threshold\n model.iou = params['iou'] # NMS IoU threshold\n model.classes = None # (optional list) filter by class, i.e. = [0, 15, 16] for persons, cats and dogs\n model.multi_label = False # NMS multiple labels per box\n model.max_det = 50 # maximum number of detections per image\n return model\n\n\ndef predict(model, img, size=768, augment=False, use_sahi=False):\n if use_sahi:\n from sahi.predict import get_sliced_prediction\n results = get_sliced_prediction(\n img,\n model,\n slice_height = 512,\n slice_width = 512,\n overlap_height_ratio = 0.2,\n overlap_width_ratio = 0.2\n ) \n preds = results.object_prediction_list\n bboxes = np.array([pred.bbox.to_voc_bbox() for pred in preds]) \n else: \n results = model(img, size=size, augment=augment) # custom inference size\n preds = results.pandas().xyxy[0]\n bboxes = preds[['xmin','ymin','xmax','ymax']].values\n if len(bboxes):\n height, width = img.shape[:2]\n bboxes = voc2coco(bboxes,height,width).astype(int)\n if use_sahi:\n confs = np.array([pred.score.value for pred in preds])\n else:\n confs = preds.confidence.values\n return bboxes, confs\n else:\n return np.array([]),[]\n \ndef format_prediction(bboxes, confs):\n annot = ''\n if len(bboxes)>0:\n for idx in range(len(bboxes)):\n xmin, ymin, w, h = bboxes[idx]\n conf = confs[idx]\n annot += f'{conf} {xmin} {ymin} {w} {h}'\n annot +=' '\n annot = annot.strip(' ')\n return annot\n\ndef show_img(img, bboxes, confs, colors, bbox_format='yolo'):\n labels = [str(round(conf,2)) for conf in confs]\n img = draw_bboxes(img = img,\n bboxes = bboxes, \n classes = labels,\n class_name = True, \n colors = colors, \n bbox_format = bbox_format,\n line_thickness = 2)\n\n return Image.fromarray(img)\n\n\ndef write_hyp(params): \n with open(params[\"hyp_file\"], mode=\"w\") as f:\n for key, val in params[\"hyp_param\"].items():\n f.write(f\"{key}: {val}\\n\")\n \ndef class2dict(f):\n return dict((name, getattr(f, name)) for name in dir(f) if not name.startswith('__'))\n\n\ndef upload(params):\n data_version = \"-\".join(params[\"exp_name\"].split(\"_\"))\n if os.path.exists(params[\"output_dir\"] / \"wandb\"):\n shutil.move(str(params[\"output_dir\"] / \"wandb\"), \n str(params[\"output_dir\"].parent / f\"{params['exp_name']}_wandb/\")\n ) \n with open(params[\"output_dir\"] / \"dataset-metadata.json\", \"w\") as f:\n f.write(\"{\\n\")\n f.write(f\"\"\" \"title\": \"{data_version}\",\\n\"\"\")\n f.write(f\"\"\" \"id\": \"vincentwang25/{data_version}\",\\n\"\"\")\n f.write(\"\"\" \"licenses\": [\\n\"\"\")\n f.write(\"\"\" {\\n\"\"\")\n f.write(\"\"\" \"name\": \"CC0-1.0\"\\n\"\"\")\n f.write(\"\"\" }\\n\"\"\")\n f.write(\"\"\" ]\\n\"\"\")\n f.write(\"\"\"}\"\"\") \n subprocess.call([\"kaggle\", \"datasets\", \"create\", \"-p\", str(params[\"output_dir\"]), \"-r\", \"zip\"])\n \ndef coco(df):\n annotion_id = 0\n images = []\n annotations = []\n\n categories = [{'id': 0, 'name': 'cots'}]\n\n for i, row in df.iterrows():\n\n images.append({\n \"id\": i,\n \"file_name\": f\"video_{row['video_id']}_{row['video_frame']}.jpg\",\n \"height\": 720,\n \"width\": 1280,\n })\n for bbox in row['annotations']:\n annotations.append({\n \"id\": annotion_id,\n \"image_id\": i,\n \"category_id\": 0,\n \"bbox\": list(bbox.values()),\n \"area\": bbox['width'] * bbox['height'],\n \"segmentation\": [],\n \"iscrowd\": 0\n })\n annotion_id += 1\n\n json_file = {'categories':categories, 'images':images, 'annotations':annotations}\n return json_file\n\n\ndef mmcfg_from_param(params):\n from mmcv import Config\n # model\n cfg = Config.fromfile(params['hyp_param']['base_file'])\n cfg.work_dir = str(params['output_dir'])\n cfg.seed = 2022\n cfg.gpu_ids = range(2)\n cfg.load_from = params['hyp_param']['load_from'] \n if params['hyp_param']['model_type'] == 'faster_rcnn':\n cfg.model.roi_head.bbox_head.num_classes = 1\n \n cfg.model.roi_head.bbox_head.loss_bbox.type = params['hyp_param']['loss_fnc']\n cfg.model.rpn_head.loss_bbox.type = params['hyp_param']['loss_fnc']\n if params['hyp_param']['loss_fnc'] == \"GIoULoss\":\n cfg.model.roi_head.bbox_head.reg_decoded_bbox = True\n cfg.model.rpn_head.reg_decoded_bbox = True\n \n \n cfg.model.train_cfg.rpn_proposal.nms.type = params['hyp_param']['nms']\n cfg.model.test_cfg.rpn.nms.type = params['hyp_param']['nms']\n cfg.model.test_cfg.rcnn.nms.type = params['hyp_param']['nms']\n \n cfg.model.train_cfg.rcnn.sampler.type = params['hyp_param']['sampler'] \n \n elif params['hyp_param']['model_type'] == 'swin': \n pass # already changed\n elif params['hyp_param']['model_type'] == 'vfnet':\n cfg.model.bbox_head.num_classes = 1\n\n if params['hyp_param'].get(\"optimizer\", cfg.optimizer.type) == \"AdamW\":\n cfg.optimizer = dict(\n type=\"AdamW\",\n lr=params['hyp_param'].get(\"lr\", cfg.optimizer.lr),\n weight_decay=params['hyp_param'].get(\n \"weight_decay\", cfg.optimizer.weight_decay\n ),\n )\n else:\n cfg.optimizer.lr = params['hyp_param'].get(\"lr\", cfg.optimizer.lr)\n cfg.optimizer.weight_decay = params['hyp_param'].get(\n \"weight_decay\", cfg.optimizer.weight_decay)\n cfg.lr_config = dict(\n policy='CosineAnnealing', \n by_epoch=False,\n warmup='linear', \n warmup_iters= 1000, \n warmup_ratio= 1/10,\n min_lr=1e-07) \n \n # data\n cfg = add_data_pipeline(cfg, params) \n \n cfg.runner.max_epochs = params['epochs']\n cfg.evaluation.start = 1\n cfg.evaluation.interval = 1\n cfg.evaluation.save_best='auto'\n cfg.evaluation.metric ='bbox'\n \n cfg.checkpoint_config.interval = -1\n cfg.log_config.interval = 500\n cfg.log_config.with_step = True\n cfg.log_config.by_epoch = True\n \n cfg.log_config.hooks =[dict(type='TextLoggerHook'),\n dict(type='TensorboardLoggerHook')] \n cfg.workflow = [('train',1)]\n \n logging.info(str(cfg))\n return cfg\n\n\ndef add_data_pipeline(cfg, params):\n cfg.dataset_type = 'COCODataset'\n cfg.classes = ('cots',)\n cfg.data_root = str(params['data_path'].resolve())\n params['aug_param']['img_scale'] = (params['img_size'], params['img_size'])\n cfg.img_scale = params['aug_param']['img_scale']\n cfg.dataset_type = 'CocoDataset'\n cfg.filter_empty_gt = False\n cfg.data.filter_empty_gt = False\n\n cfg.data.train.type = cfg.dataset_type\n cfg.data.train.classes = cfg.classes\n cfg.data.train.ann_file = str(params[\"cfg_dir\"] / 'annotations_train.json')\n cfg.data.train.img_prefix = cfg.data_root + '/images/'\n cfg.data.train.filter_empty_gt = False\n\n cfg.data.test.type = cfg.dataset_type\n cfg.data.test.classes = cfg.classes\n cfg.data.test.ann_file = str(params[\"cfg_dir\"] / 'annotations_valid.json')\n cfg.data.test.img_prefix = cfg.data_root + '/images/'\n cfg.data.test.filter_empty_gt = False\n\n cfg.data.val.type = cfg.dataset_type\n cfg.data.val.classes = cfg.classes\n cfg.data.val.ann_file = str(params[\"cfg_dir\"] / 'annotations_valid.json')\n cfg.data.val.img_prefix = cfg.data_root + '/images/' \n cfg.data.val.filter_empty_gt = False\n \n cfg.data.samples_per_gpu = params['batch'] // len(cfg.gpu_ids)\n cfg.data.workers_per_gpu = params['workers'] // len(cfg.gpu_ids) \n \n # train pipeline \n albu_train_transforms = get_albu_transforms(params['aug_param'], is_train=True)\n \n if params['aug_param']['use_mixup'] or params['aug_param']['use_mosaic']:\n train_pipeline = []\n else:\n train_pipeline = [\n dict(type='LoadImageFromFile'),\n dict(type='LoadAnnotations', with_bbox=True)]\n if params['aug_param']['use_mosaic']:\n train_pipeline.append(dict(type='Mosaic', img_scale=cfg.img_scale, pad_val=114.0))\n else:\n train_pipeline.append(dict(type='Resize', img_scale=cfg.img_scale, keep_ratio=False))\n \n train_pipeline = train_pipeline +[\n dict(type='Pad', size_divisor=32),\n dict(\n type='Albu',\n transforms=albu_train_transforms,\n bbox_params=dict(\n type='BboxParams',\n format='pascal_voc',\n label_fields=['gt_labels'],\n min_visibility=0.0,\n filter_lost_elements=True),\n keymap={\n 'img': 'image',\n 'gt_bboxes': 'bboxes'\n },\n update_pad_shape=False,\n skip_img_without_anno=False\n )]\n \n if params['aug_param']['use_mixup']:\n train_pipeline.append(dict(type='MixUp', img_scale=cfg.img_scale, ratio_range=(0.8, 1.6), pad_val=114.0))\n \n train_pipeline = train_pipeline +\\\n [\n dict(type='Normalize', **cfg.img_norm_cfg),\n dict(type='DefaultFormatBundle'),\n dict(type='Collect', \n keys=['img', 'gt_bboxes', 'gt_labels'],\n meta_keys=('filename', 'ori_filename', 'ori_shape', 'img_shape', 'pad_shape', \n 'scale_factor', 'img_norm_cfg')),\n ]\n \n val_pipeline = [\n dict(type='LoadImageFromFile'),\n dict(\n type='MultiScaleFlipAug',\n img_scale=cfg.img_scale,\n flip=False,\n transforms=[\n dict(type='Resize', keep_ratio=True),\n dict(type='RandomFlip'),\n dict(type='Normalize', **cfg.img_norm_cfg),\n dict(type='Pad', size_divisor=32),\n dict(type='ImageToTensor', keys=['img']),\n dict(type='Collect', keys=['img'])\n ])\n ]\n \n test_pipeline = [\n dict(type='LoadImageFromFile'),\n dict(\n type='MultiScaleFlipAug',\n img_scale=[cfg.img_scale],\n flip=[False],\n transforms=[\n dict(type='Resize', keep_ratio=False),\n dict(type='Pad', size_divisor=32),\n dict(type='RandomFlip', direction='horizontal'),\n dict(type='Normalize', **cfg.img_norm_cfg),\n dict(type='ImageToTensor', keys=['img']),\n dict(type='Collect', keys=['img']),\n ])\n ] \n \n cfg.train_pipeline = train_pipeline\n cfg.val_pipeline = val_pipeline\n cfg.test_pipeline = test_pipeline\n \n \n if params['aug_param']['use_mixup'] or params['aug_param']['use_mosaic']:\n cfg.train_dataset = dict(\n type='MultiImageMixDataset',\n dataset=dict(\n type=cfg.dataset_type,\n classes=cfg.classes,\n ann_file=str(params[\"cfg_dir\"] / 'annotations_train.json'),\n img_prefix=cfg.data_root + '/images/',\n pipeline=[\n dict(type='LoadImageFromFile'),\n dict(type='LoadAnnotations', with_bbox=True)\n ],\n filter_empty_gt=False,\n ),\n pipeline=cfg.train_pipeline\n )\n cfg.data.train = cfg.train_dataset\n else:\n cfg.data.train.pipeline = cfg.train_pipeline\n \n cfg.data.val.pipeline = cfg.val_pipeline\n cfg.data.test.pipeline = cfg.test_pipeline \n \n return cfg \n\n\ndef find_ckp(output_dir):\n return glob(output_dir / \"best*.pth\")[0]" ]
[ [ "torch.cuda.manual_seed", "numpy.minimum", "numpy.set_printoptions", "numpy.exp", "numpy.where", "torch.load", "matplotlib.pyplot.imshow", "torch.hub.load", "numpy.concatenate", "numpy.max", "torch.manual_seed", "numpy.transpose", "numpy.arange", "numpy.argmax", "matplotlib.pyplot.axis", "numpy.array", "torch.cuda.manual_seed_all", "matplotlib.pyplot.figure", "matplotlib.rc", "numpy.random.seed", "numpy.ones", "numpy.split", "numpy.maximum" ] ]
statKim/TIL
[ "3297d09023d97653773b35160794d3324b95c111" ]
[ "Python/tensorflow/DeepLearningZeroToAll/ver.py/Lab02-1-linear_regression.py" ]
[ "# Lab 2 Linear Regression\nimport tensorflow as tf\n\ntf.set_random_seed(777) # seed 설정\n\n# training data\nx_train = [1, 2, 3]\ny_train = [1, 2, 3]\n\n# regerssion 결과는 W = 1, b = 0 이라는 것을 알 수 있음\n# but tensorflow로 training 시켜서 해보기!!\n# W와 b는 어떻게 달라질까?\n\n# tf.Variable() : tensorflow가 사용하는 변수(trainable variable)\n# tf.random_normal([1]) : normal dist에서 1개의 난수 생성\nW = tf.Variable(tf.random_normal([1]), name='weight')\nb = tf.Variable(tf.random_normal([1]), name='bias')\n\n# Linear regression model\nhypothesis = x_train * W + b\n\n# cost/loss function (MSE)\n# tf.square() : 제곱해주는 tf 함수\n# tf.reduce_mean() : mean 구해주는 tf 함수\n# hypothesis(y_hat), y_train(true value)\ncost = tf.reduce_mean(tf.square(hypothesis - y_train))\n\n# GradientDescent\n# Minimize\n# learning rate=0.01로 training 시킴 => gradient descent로 인해 조금씩 true에 가까워짐\noptimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)\ntrain = optimizer.minimize(cost)\n\n# session 객체 생성(tf graph 객체 생성)\nsess = tf.Session()\n# 모든 tf variavle 초기화\nsess.run(tf.global_variables_initializer())\n\n# Fit\n# 2001번 최적화 시킴!!!\nfor step in range(2001):\n sess.run(train)\n if step % 20 == 0: # 다 뽑으면 너무 많으니까 몇개만 뽑기 위해서\n # step(몇 번째인지?), cost(mse), W(weight), b(bias)\n print(step, sess.run(cost), sess.run(W), sess.run(b))\n\n# Learns best fit W:[ 1.], b:[ 0.]\n\n'''\n0 2.82329 [ 2.12867713] [-0.85235667]\n20 0.190351 [ 1.53392804] [-1.05059612]\n40 0.151357 [ 1.45725465] [-1.02391243]\n...\n1920 1.77484e-05 [ 1.00489295] [-0.01112291]\n1940 1.61197e-05 [ 1.00466311] [-0.01060018]\n1960 1.46397e-05 [ 1.004444] [-0.01010205]\n1980 1.32962e-05 [ 1.00423515] [-0.00962736]\n2000 1.20761e-05 [ 1.00403607] [-0.00917497]\n'''" ]
[ [ "tensorflow.set_random_seed", "tensorflow.Session", "tensorflow.global_variables_initializer", "tensorflow.square", "tensorflow.random_normal", "tensorflow.train.GradientDescentOptimizer" ] ]
wileyw/VideoGAN
[ "d5c40ce4180b63d9dc6017a8caf19cfd63166a96" ]
[ "process.py" ]
[ "import os\nimport scipy.misc\nimport torch\nimport numpy as np\nimport torch.optim as optim\n\nimport config\nimport data_loader\nimport d_net\nimport loss_funs\nimport g_net\n\ndtype = config.dtype\n\n\ndef save_samples(generated_images, iteration, prefix):\n\n generated_images = generated_images.data.cpu().numpy()\n\n num_images, channels, cell_h, cell_w = generated_images.shape\n ncols = int(np.sqrt(num_images))\n nrows = int(np.math.floor(num_images / float(ncols)))\n result = np.zeros(\n (cell_h * nrows, cell_w * ncols, channels), dtype=generated_images.dtype\n )\n for i in range(0, nrows):\n for j in range(0, ncols):\n result[\n i * cell_h : (i + 1) * cell_h, j * cell_w : (j + 1) * cell_w, :\n ] = generated_images[i * ncols + j].transpose(1, 2, 0)\n grid = result\n\n if not os.path.exists(\"output\"):\n os.makedirs(\"output\")\n scipy.misc.imsave(\"output/{}_{:05d}.jpg\".format(prefix, iteration), grid)\n\n\ndef main():\n loss_fp = open(\"losses.csv\", \"w\")\n\n video_d_net = d_net.DiscriminatorModel(\n kernel_sizes_list=d_net.SCALE_KERNEL_SIZES_D,\n conv_layer_fms_list=d_net.SCALE_CONV_FMS_D,\n scale_fc_layer_sizes_list=d_net.SCALE_FC_LAYER_SIZES_D,\n )\n video_d_net.type(dtype)\n\n video_g_net = g_net.VideoGANGenerator()\n video_g_net.type(dtype)\n\n video_d_optimizer = optim.SGD(video_d_net.parameters(), lr=0.0001)\n video_g_optimizer = optim.SGD(video_g_net.parameters(), lr=0.0001)\n\n # Load Pacman dataset\n max_size = len(os.listdir(\"train\"))\n pacman_dataloader = data_loader.DataLoader(\"train\", max_size, 16, 32, 32, 4)\n\n count = 0\n for i in range(1, 5000):\n clips_x, clips_y = pacman_dataloader.get_train_batch()\n clips_x = torch.tensor(np.rollaxis(clips_x, 3, 1)).type(dtype)\n clips_y = torch.tensor(np.rollaxis(clips_y, 3, 1)).type(dtype)\n\n video_d_optimizer.zero_grad()\n video_g_optimizer.zero_grad()\n\n # batch_size x noise_size x 1 x 1\n batch_size = 16\n\n # WGAN loss\n # https://github.com/keras-team/keras-contrib/blob/master/examples/improved_wgan.py\n\n video_images = video_g_net(clips_x)\n # TESTING: Vanilla Video Gan\n video_d_loss_real = (video_d_net(clips_y) - 1).pow(2).mean()\n video_d_loss_fake = (video_d_net(video_images)).pow(2).mean()\n\n # Fake batch\n labels = torch.zeros(batch_size, 4).t().unsqueeze(2).type(dtype)\n video_d_loss_fake = loss_funs.adv_loss(\n video_d_net(video_images), labels\n ) # TODO: Validate if it's right.\n video_d_optimizer.zero_grad()\n video_d_loss_fake.backward()\n video_d_optimizer.step()\n\n # Real batch\n labels = torch.ones(batch_size, 4).t().unsqueeze(2).type(dtype)\n video_d_loss_real = loss_funs.adv_loss(\n video_d_net(clips_y), labels\n ) # TODO: Validate if it's right.\n video_d_optimizer.zero_grad()\n video_d_loss_real.backward()\n video_d_optimizer.step()\n\n # batch_size x noise_size x 1 x 1\n batch_size = 16\n\n # print('G_Time:', end - start)\n\n # TESTING: Vanilla Video Gan\n video_images = video_g_net(clips_x)\n d_preds = video_d_net(video_images).type(\n dtype\n ) # TODO: Make sure this is working.\n gt_frames = clips_y.type(dtype) # TODO: make clips_y at different scales.\n gen_frames = video_images.type(\n dtype\n ) # TODO: make the generated frames multi scale.\n video_g_loss = loss_funs.combined_loss(gen_frames, gt_frames, d_preds)\n video_g_loss.backward()\n video_g_optimizer.step()\n\n if count % 20 == 0:\n save_samples(clips_y, count, \"video_real\")\n save_samples(video_images, count, \"video_fake\")\n\n out_str = \"{}, {}, {}, {}\".format(\n count, video_d_loss_real, video_d_loss_fake, video_g_loss\n )\n\n print(out_str)\n loss_fp.write(out_str)\n loss_fp.write(\"\\n\")\n loss_fp.flush()\n torch.save(video_g_net.state_dict(), \"generator_net.pth.tmp\")\n count += 1\n\n loss_fp.close()\n\n # Final Generator save.\n torch.save(video_g_net.state_dict(), \"generator_net.pth\")\n\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "torch.zeros", "numpy.zeros", "numpy.rollaxis", "torch.ones", "numpy.sqrt" ] ]
speedcell4/OpenSelfSup
[ "f80fad08c795143e0e9cf2dc9466df3c6eec67d7", "f80fad08c795143e0e9cf2dc9466df3c6eec67d7" ]
[ "tools/extract.py", "openselfsup/utils/collect.py" ]
[ "import argparse\nimport importlib\nimport mmcv\nimport numpy as np\nimport os\nimport os.path as osp\nimport time\nimport torch\nfrom mmcv.parallel import MMDataParallel, MMDistributedDataParallel\nfrom mmcv.runner import get_dist_info, init_dist, load_checkpoint\n\nfrom openselfsup.datasets import build_dataloader, build_dataset\nfrom openselfsup.models import build_model\nfrom openselfsup.models.utils import MultiPooling\nfrom openselfsup.utils import dist_forward_collect, nondist_forward_collect\nfrom openselfsup.utils import get_root_logger\n\n\nclass ExtractProcess(object):\n\n def __init__(self,\n pool_type='specified',\n backbone='resnet50',\n layer_indices=(0, 1, 2, 3, 4)):\n self.multi_pooling = MultiPooling(\n pool_type, in_indices=layer_indices, backbone=backbone)\n\n def _forward_func(self, model, **x):\n backbone_feats = model(mode='extract', **x)\n pooling_feats = self.multi_pooling(backbone_feats)\n flat_feats = [xx.view(xx.size(0), -1) for xx in pooling_feats]\n feat_dict = {'feat{}'.format(i + 1): feat.cpu() \\\n for i, feat in enumerate(flat_feats)}\n return feat_dict\n\n def extract(self, model, data_loader, distributed=False):\n model.eval()\n func = lambda **x: self._forward_func(model, **x)\n if distributed:\n rank, world_size = get_dist_info()\n results = dist_forward_collect(func, data_loader, rank,\n len(data_loader.dataset))\n else:\n results = nondist_forward_collect(func, data_loader,\n len(data_loader.dataset))\n return results\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(\n description='OpenSelfSup extract features of a model')\n parser.add_argument('config', help='test config file path')\n parser.add_argument('--checkpoint', default=None, help='checkpoint file')\n parser.add_argument(\n '--pretrained', default='random',\n help='pretrained model file, exclusive to --checkpoint')\n parser.add_argument(\n '--dataset-config',\n default='benchmarks/extract_info/voc07.py',\n help='extract dataset config file path')\n parser.add_argument(\n '--layer-ind',\n type=str,\n help='layer indices, separated by comma, e.g., \"0,1,2,3,4\"')\n parser.add_argument(\n '--work_dir',\n type=str,\n default=None,\n help='the dir to save logs and models')\n parser.add_argument(\n '--launcher',\n choices=['none', 'pytorch', 'slurm', 'mpi'],\n default='none',\n help='job launcher')\n parser.add_argument('--local_rank', type=int, default=0)\n parser.add_argument('--port', type=int, default=29500,\n help='port only works when launcher==\"slurm\"')\n args = parser.parse_args()\n if 'LOCAL_RANK' not in os.environ:\n os.environ['LOCAL_RANK'] = str(args.local_rank)\n return args\n\n\ndef main():\n args = parse_args()\n cfg = mmcv.Config.fromfile(args.config)\n # set cudnn_benchmark\n if cfg.get('cudnn_benchmark', False):\n torch.backends.cudnn.benchmark = True\n # update configs according to CLI args\n if args.work_dir is not None:\n cfg.work_dir = args.work_dir\n layer_ind = [int(idx) for idx in args.layer_ind.split(',')]\n cfg.model.backbone.out_indices = layer_ind\n\n # checkpoint and pretrained are exclusive\n assert args.pretrained == \"random\" or args.checkpoint is None, \\\n \"Checkpoint and pretrained are exclusive.\"\n\n # check memcached package exists\n if importlib.util.find_spec('mc') is None:\n for field in ['train', 'val', 'test']:\n if hasattr(cfg.data, field):\n getattr(cfg.data, field).data_source.memcached = False\n\n # init distributed env first, since logger depends on the dist info.\n if args.launcher == 'none':\n distributed = False\n else:\n distributed = True\n if args.launcher == 'slurm':\n cfg.dist_params['port'] = args.port\n init_dist(args.launcher, **cfg.dist_params)\n\n # create work_dir\n mmcv.mkdir_or_exist(osp.abspath(cfg.work_dir))\n # logger\n timestamp = time.strftime('%Y%m%d_%H%M%S', time.localtime())\n log_file = osp.join(cfg.work_dir, 'extract_{}.log'.format(timestamp))\n logger = get_root_logger(log_file=log_file, log_level=cfg.log_level)\n\n # build the dataloader\n dataset_cfg = mmcv.Config.fromfile(args.dataset_config)\n dataset = build_dataset(dataset_cfg.data.extract)\n data_loader = build_dataloader(\n dataset,\n imgs_per_gpu=dataset_cfg.data.imgs_per_gpu,\n workers_per_gpu=dataset_cfg.data.workers_per_gpu,\n dist=distributed,\n shuffle=False)\n\n # specify pretrained model\n if args.pretrained != 'random':\n assert isinstance(args.pretrained, str)\n cfg.model.pretrained = args.pretrained\n\n # build the model and load checkpoint\n model = build_model(cfg.model)\n if args.checkpoint is not None:\n logger.info(\"Use checkpoint: {} to extract features\".format(\n args.checkpoint))\n load_checkpoint(model, args.checkpoint, map_location='cpu')\n elif args.pretrained != \"random\":\n logger.info('Use pretrained model: {} to extract features'.format(\n args.pretrained))\n else:\n logger.info('No checkpoint or pretrained is give, use random init.')\n\n if not distributed:\n model = MMDataParallel(model, device_ids=[0])\n else:\n model = MMDistributedDataParallel(\n model.cuda(),\n device_ids=[torch.cuda.current_device()],\n broadcast_buffers=False)\n\n # build extraction processor\n extractor = ExtractProcess(\n pool_type='specified', backbone='resnet50', layer_indices=layer_ind)\n\n # run\n outputs = extractor.extract(model, data_loader, distributed=distributed)\n rank, _ = get_dist_info()\n mmcv.mkdir_or_exist(\"{}/features/\".format(args.work_dir))\n if rank == 0:\n for key, val in outputs.items():\n split_num = len(dataset_cfg.split_name)\n split_at = dataset_cfg.split_at\n for ss in range(split_num):\n output_file = \"{}/features/{}_{}.npy\".format(\n args.work_dir, dataset_cfg.split_name[ss], key)\n if ss == 0:\n np.save(output_file, val[:split_at[0]])\n elif ss == split_num - 1:\n np.save(output_file, val[split_at[-1]:])\n else:\n np.save(output_file, val[split_at[ss - 1]:split_at[ss]])\n\n\nif __name__ == '__main__':\n main()\n", "import mmcv\nimport numpy as np\nimport torch\n\nfrom .gather import gather_tensors_batch\n\n\ndef nondist_forward_collect(func, data_loader, length):\n '''Forward and collect network outputs.\n\n This function performs forward propagation and collects outputs.\n It can be used to collect results, features, losses, etc.\n\n Args:\n func (function): The function to process data. The output must be\n a dictionary of CPU tensors.\n length (int): Expected length of output arrays.\n\n Returns:\n results_all (dict(np.ndarray)): The concatenated outputs.\n '''\n results = []\n prog_bar = mmcv.ProgressBar(len(data_loader))\n for i, data in enumerate(data_loader):\n with torch.no_grad():\n result = func(**data)\n results.append(result)\n prog_bar.update()\n\n results_all = {}\n for k in results[0].keys():\n results_all[k] = np.concatenate(\n [batch[k].numpy() for batch in results], axis=0)\n assert results_all[k].shape[0] == length\n return results_all\n\n\ndef dist_forward_collect(func, data_loader, rank, length, ret_rank=-1):\n '''Forward and collect network outputs in a distributed manner.\n\n This function performs forward propagation and collects outputs.\n It can be used to collect results, features, losses, etc.\n\n Args:\n func (function): The function to process data. The output must be\n a dictionary of CPU tensors.\n rank (int): This process id.\n length (int): Expected length of output arrays.\n ret_rank (int): The process that returns.\n Other processes will return None.\n\n Returns:\n results_all (dict(np.ndarray)): The concatenated outputs.\n '''\n results = []\n if rank == 0:\n prog_bar = mmcv.ProgressBar(len(data_loader))\n for idx, data in enumerate(data_loader):\n with torch.no_grad():\n result = func(**data) # dict{key: tensor}\n results.append(result)\n\n if rank == 0:\n prog_bar.update()\n\n results_all = {}\n for k in results[0].keys():\n results_cat = np.concatenate([batch[k].numpy() for batch in results],\n axis=0)\n if ret_rank == -1:\n results_gathered = gather_tensors_batch(results_cat, part_size=20)\n results_strip = np.concatenate(results_gathered, axis=0)[:length]\n else:\n results_gathered = gather_tensors_batch(\n results_cat, part_size=20, ret_rank=ret_rank)\n if rank == ret_rank:\n results_strip = np.concatenate(\n results_gathered, axis=0)[:length]\n else:\n results_strip = None\n results_all[k] = results_strip\n return results_all\n" ]
[ [ "numpy.save", "torch.cuda.current_device" ], [ "numpy.concatenate", "torch.no_grad" ] ]
UASLab/OpenFlightAnalysis
[ "b5ecb3ea7ff82f5fb21efa7e9cbee60bf68aea37" ]
[ "Core/OpenData.py" ]
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Dec 28 15:05:36 2018\n\n@author: louismueller\n\"\"\"\n\n# import\nimport numpy as np\n\n#%% \ndef PlotOverview(oData):\n import matplotlib.pyplot as plt\n from mpl_toolkits.mplot3d import Axes3D\n\n # Overview Plots\n # Find interesting stuff: takeoff, landing, excitations etc.\n time_s = oData['time_s']\n \n # Airspeed\n vIas_mps = oData['vIas_mps']\n vGps_mps = np.linalg.norm(oData['vGps_L_mps'], 2, axis=0)\n vB_mps = np.linalg.norm(oData['vB_L_mps'], 2, axis=0)\n fig0, ax0 = plt.subplots()\n ax0.plot(time_s, oData['refV_mps'], label='ref')\n ax0.plot(time_s, vIas_mps, label='airspeed')\n ax0.plot(time_s, vGps_mps, '.', label='Gps')\n ax0.plot(time_s, vB_mps, label='Ekf')\n ax0.grid()\n ax0.set_xlabel('Time (s)')\n ax0.set_ylabel('Airspeed (m/s)')\n ax0.set_title('Air Data Airspeed')\n ax0.legend()\n \n # Altitude\n altBaro_m = oData['altBaro_m']\n altGps_m = oData['rGps_D_ddm'][2]\n altB_m = oData['rB_D_ddm'][2]\n fig1, ax1 = plt.subplots()\n ax1.plot(time_s, oData['refH_m'], label='ref')\n ax1.plot(time_s, altBaro_m, label='Baro')\n ax1.plot(time_s, altGps_m, '.', label='GPS')\n ax1.plot(time_s, altB_m - altB_m, label='Ekf')\n ax1.grid()\n ax1.set_xlabel('Time (s)')\n ax1.set_ylabel('Altitude (m)')\n ax1.set_title('Altitude')\n ax1.legend()\n \n # X and Y Position\n latGps_deg = oData['rGps_D_ddm'][0]\n lonGps_deg = oData['rGps_D_ddm'][1]\n latB_deg = oData['rB_D_ddm'][0]\n lonB_deg = oData['rB_D_ddm'][1]\n fig2, ax2 = plt.subplots()\n ax2.plot(lonGps_deg, latGps_deg, '.', label='GPS')\n ax2.plot(lonB_deg, latB_deg, label='Ekf')\n ax2.grid()\n ax2.axis('equal')\n ax2.set_xlabel('Longitude (deg)')\n ax2.set_ylabel('Latitude (deg)')\n ax2.set_title('Latitude and Longitude')\n ax2.legend()\n \n # Voltage\n pwrFmu_V = oData['pwrFmu_V']\n fig3, ax3 = plt.subplots()\n ax3.plot(time_s, pwrFmu_V)\n ax3.set_xlabel('Time (s)')\n ax3.set_ylabel('Avionics Voltage (V)')\n ax3.set_title('Power')\n ax3.grid()\n \n # 3D Position\n fig4 = plt.figure()\n ax4 = fig4.gca(projection='3d', proj_type = 'ortho')\n ax4.plot(lonGps_deg, latGps_deg, altGps_m, '.', label='GPS')\n ax4.plot(lonB_deg, latB_deg, altB_m, label='Ekf')\n ax4.axis('equal')\n ax4.grid()\n ax4.set_xlabel('Longitude (deg)')\n ax4.set_ylabel('Latitude (deg)')\n ax4.set_title('Flight Path')\n ax4.legend()\n \n plt.show()\n \n return 1\n\n#%% Find Excitation Times based on 'exciteEngage'\ndef FindExcite(oData):\n # returns list of tuples: \n #(testID, [timeMin_us, timeMax_us])\n \n # Create array that is the testID value when exciteEngage is True and -1 everywhere else\n iTestExcite = np.where(oData['exciteEngage'], oData['testID'], -1 * np.ones_like(oData['testID']))\n \n # Find where the index changes\n iRange = np.where(iTestExcite[:-1] != iTestExcite[1:])[0]\n \n iStartList = iRange[0::2]\n iEndList = iRange[1::2]\n \n excList = []\n for iExc in range(0,len(iStartList)):\n iStart = iStartList[iExc]\n iEnd = iEndList[iExc]\n timeRange_us = [int(oData['time_us'][iStart]), int(oData['time_us'][iEnd])]\n \n testID = oData['testID'][iStart]\n \n exc = (testID, timeRange_us)\n excList.append(exc)\n \n return excList\n\n#%% \ndef TestPointOut(excList, testPointList):\n\n testList = []\n for iExc, exc in enumerate(excList):\n iTestID = exc[0]\n testPoint = testPointList[iTestID]\n testPoint['time_us'] = excList[iExc][1]\n testList.append(testPoint)\n\n return testList\n\n#%% Segment oData by condition\nimport copy\n\ndef SliceDict(oData, iCond):\n \n oDataSeg = {}\n \n lenCond = len(iCond)\n for k, v in oData.items():\n if isinstance(v, dict):\n oDataSeg[k] = {}\n oDataSeg[k] = SliceDict(v, iCond)\n else: \n if v.shape[-1] >= lenCond:\n oDataSeg[k] = np.copy(v[...,iCond])\n else:\n oDataSeg[k] = np.copy(v)\n \n return oDataSeg\n \n# \ndef Segment(oData, cond):\n # cond = (condName, [min, max])\n # if cond is a list, will return a list of oData segments\n # Example: cond = ('time_s', [60, 61])\n \n # Recursive call if cond is a list of conditions\n if type(cond) is list:\n oDataSeg = []\n for c in cond:\n seg = Segment(oData, c)\n oDataSeg.append(seg)\n return oDataSeg\n \n # Slice into Segments\n condName = cond[0]\n condRange = cond[1]\n if len(cond) > 2:\n condDesc = cond[2]\n else:\n condDesc = ''\n \n # Bool that matches the condition\n iCond = (oData[condName] >= condRange[0]) & (oData[condName] <= condRange[1])\n \n # Slice, with full copy, into segmented oData. SliceDict will handle recursive calls\n oDataSeg = copy.deepcopy(SliceDict(oData, iCond))\n oDataSeg['Desc'] = condDesc\n \n return oDataSeg\n\n#\ndef Decimate(oData, skip):\n # Recursive call if cond is a list of conditions\n if type(skip) is list:\n oDataSeg = []\n for s in skip:\n seg = Segment(oData, s)\n oDataSeg.append(seg)\n return oDataSeg\n \n # Bool that matches the condition\n iCond = range(0, len(oData['time_s']), skip)\n \n # Slice, with full copy, into segmented oData. SliceDict will handle recursive calls\n oDataSeg = copy.deepcopy(SliceDict(oData, iCond))\n# oDataSeg['Desc'] = condDesc\n \n return oDataSeg\n " ]
[ [ "numpy.linalg.norm", "numpy.ones_like", "numpy.copy", "matplotlib.pyplot.subplots", "matplotlib.pyplot.figure", "numpy.where", "matplotlib.pyplot.show" ] ]
Vaibhavs10/IMS-Toucan
[ "931e4ce63a4cc675cb15b72474a3c3619632a07b", "931e4ce63a4cc675cb15b72474a3c3619632a07b" ]
[ "InferenceInterfaces/Nancy_Tacotron2.py", "TrainingInterfaces/Text_to_Spectrogram/Tacotron2/tacotron2_train_loop.py" ]
[ "import os\n\nimport librosa.display as lbd\nimport matplotlib.pyplot as plt\nimport sounddevice\nimport soundfile\nimport torch\n\nfrom InferenceInterfaces.InferenceArchitectures.InferenceHiFiGAN import HiFiGANGenerator\nfrom InferenceInterfaces.InferenceArchitectures.InferenceTacotron2 import Tacotron2\nfrom Preprocessing.TextFrontend import TextFrontend\n\n\nclass Nancy_Tacotron2(torch.nn.Module):\n\n def __init__(self, device=\"cpu\", speaker_embedding=None):\n super().__init__()\n self.speaker_embedding = None\n self.device = device\n self.text2phone = TextFrontend(language=\"en\", use_word_boundaries=False,\n use_explicit_eos=False, inference=True)\n self.phone2mel = Tacotron2(path_to_weights=os.path.join(\"Models\", \"Tacotron2_Nancy\", \"best.pt\"),\n idim=166, odim=80, spk_embed_dim=None, reduction_factor=1).to(torch.device(device))\n self.mel2wav = HiFiGANGenerator(path_to_weights=os.path.join(\"Models\", \"HiFiGAN_combined\", \"best.pt\")).to(torch.device(device))\n self.phone2mel.eval()\n self.mel2wav.eval()\n self.to(torch.device(device))\n\n def forward(self, text, view=False):\n with torch.no_grad():\n phones = self.text2phone.string_to_tensor(text).squeeze(0).long().to(torch.device(self.device))\n mel = self.phone2mel(phones, speaker_embedding=self.speaker_embedding).transpose(0, 1)\n wave = self.mel2wav(mel)\n if view:\n fig, ax = plt.subplots(nrows=2, ncols=1)\n ax[0].plot(wave.cpu().numpy())\n lbd.specshow(mel.cpu().numpy(), ax=ax[1], sr=16000, cmap='GnBu', y_axis='mel', x_axis='time', hop_length=256)\n ax[0].set_title(self.text2phone.get_phone_string(text))\n ax[0].yaxis.set_visible(False)\n ax[1].yaxis.set_visible(False)\n plt.subplots_adjust(left=0.05, bottom=0.1, right=0.95, top=.9, wspace=0.0, hspace=0.0)\n plt.show()\n\n return wave\n\n def read_to_file(self, text_list, file_location, silent=False):\n \"\"\"\n :param silent: Whether to be verbose about the process\n :param text_list: A list of strings to be read\n :param file_location: The path and name of the file it should be saved to\n \"\"\"\n wav = None\n silence = torch.zeros([24000])\n for text in text_list:\n if text.strip() != \"\":\n if not silent:\n print(\"Now synthesizing: {}\".format(text))\n if wav is None:\n wav = self(text).cpu()\n wav = torch.cat((wav, silence), 0)\n else:\n wav = torch.cat((wav, self(text).cpu()), 0)\n wav = torch.cat((wav, silence), 0)\n soundfile.write(file=file_location, data=wav.cpu().numpy(), samplerate=48000)\n\n def read_aloud(self, text, view=False, blocking=False):\n if text.strip() == \"\":\n return\n wav = self(text, view).cpu()\n wav = torch.cat((wav, torch.zeros([24000])), 0)\n if not blocking:\n sounddevice.play(wav.numpy(), samplerate=48000)\n else:\n sounddevice.play(torch.cat((wav, torch.zeros([12000])), 0).numpy(), samplerate=48000)\n sounddevice.wait()\n\n def plot_attention(self, sentence):\n sentence_tensor = self.text2phone.string_to_tensor(sentence).squeeze(0).long().to(torch.device(self.device))\n att = self.phone2mel(text=sentence_tensor, speaker_embedding=self.speaker_embedding, return_atts=True)\n fig, axes = plt.subplots(nrows=1, ncols=1)\n axes.imshow(att.detach().numpy(), interpolation='nearest', aspect='auto', origin=\"lower\")\n axes.set_title(\"{}\".format(sentence))\n axes.xaxis.set_visible(False)\n axes.yaxis.set_visible(False)\n plt.tight_layout()\n plt.show()\n", "import os\nimport time\n\nimport matplotlib.pyplot as plt\nimport torch\nimport torch.multiprocessing\nimport torch.nn.functional as F\nfrom speechbrain.pretrained import EncoderClassifier\nfrom torch.cuda.amp import GradScaler\nfrom torch.cuda.amp import autocast\nfrom torch.nn.utils.rnn import pad_sequence\nfrom torch.utils.data.dataloader import DataLoader\nfrom tqdm import tqdm\n\nfrom Preprocessing.TextFrontend import TextFrontend\nfrom TrainingInterfaces.Text_to_Spectrogram.Tacotron2.AlignmentLoss import binarize_attention_parallel\nfrom Utility.utils import delete_old_checkpoints\nfrom Utility.utils import get_most_recent_checkpoint\n\n\ndef plot_attention(model, lang, device, speaker_embedding, att_dir, step):\n tf = TextFrontend(language=lang, use_word_boundaries=False, use_explicit_eos=False)\n sentence = \"\"\n if lang == \"en\":\n sentence = \"This is a complex sentence, it even has a pause!\"\n elif lang == \"de\":\n sentence = \"Dies ist ein komplexer Satz, er hat sogar eine Pause!\"\n text = tf.string_to_tensor(sentence).long().squeeze(0).to(device)\n phones = tf.get_phone_string(sentence)\n model.eval()\n att = model.inference(text=text, speaker_embeddings=speaker_embedding)[2].to(\"cpu\")\n model.train()\n del tf\n bin_att = binarize_attention_parallel(att.unsqueeze(0).unsqueeze(1),\n in_lens=torch.LongTensor([len(text)]),\n out_lens=torch.LongTensor([len(att)])).squeeze(0).squeeze(0).detach().numpy()\n fig, ax = plt.subplots(nrows=2, ncols=1, figsize=(8, 9))\n ax[0].imshow(att.detach().numpy(), interpolation='nearest', aspect='auto', origin=\"lower\")\n ax[1].imshow(bin_att, interpolation='nearest', aspect='auto', origin=\"lower\")\n ax[1].set_xlabel(\"Inputs\")\n ax[0].xaxis.set_visible(False)\n ax[0].set_ylabel(\"Outputs\")\n ax[1].set_ylabel(\"Outputs\")\n ax[1].set_xticks(range(len(att[0])))\n del att\n ax[1].set_xticklabels(labels=[phone for phone in phones])\n ax[0].set_title(\"Soft-Attention\")\n ax[1].set_title(\"Hard-Attention\")\n fig.tight_layout()\n if not os.path.exists(os.path.join(att_dir, \"attention_plots\")):\n os.makedirs(os.path.join(att_dir, \"attention_plots\"))\n fig.savefig(os.path.join(os.path.join(att_dir, \"attention_plots\"), str(step) + \".png\"))\n fig.clf()\n plt.close()\n\n\ndef collate_and_pad(batch):\n if len(batch[0]) == 4:\n # every entry in batch: [text, text_length, spec, spec_length]\n return (pad_sequence([datapoint[0].squeeze(0) for datapoint in batch], batch_first=True),\n torch.stack([datapoint[1] for datapoint in batch]).squeeze(1),\n pad_sequence([datapoint[2] for datapoint in batch], batch_first=True),\n torch.stack([datapoint[3] for datapoint in batch]).squeeze(1))\n elif len(batch[0]) == 5:\n # every entry in batch: [text, text_length, spec, spec_length, speaker_embedding]\n return (pad_sequence([datapoint[0].squeeze(0) for datapoint in batch], batch_first=True),\n torch.stack([datapoint[1] for datapoint in batch]).squeeze(1),\n pad_sequence([datapoint[2] for datapoint in batch], batch_first=True),\n torch.stack([datapoint[3] for datapoint in batch]).squeeze(1),\n torch.stack([datapoint[4] for datapoint in batch]))\n\n\ndef train_loop(net,\n train_dataset,\n device,\n save_directory,\n batch_size,\n steps,\n epochs_per_save,\n lang,\n lr,\n use_speaker_embedding=False,\n path_to_checkpoint=None,\n fine_tune=False,\n collapse_margin=5.0, # be wary of loss scheduling\n resume=False,\n use_cycle_consistency_for_speakerembedding=False):\n \"\"\"\n Args:\n resume: whether to resume from the most recent checkpoint\n collapse_margin: margin in which the loss may increase in one epoch without triggering the soft-reset\n steps: How many steps to train\n lr: The initial learning rate for the optimiser\n path_to_checkpoint: reloads a checkpoint to continue training from there\n fine_tune: whether to load everything from a checkpoint, or only the model parameters\n lang: language of the synthesis\n use_speaker_embedding: whether to expect speaker embeddings\n net: Model to train\n train_dataset: Pytorch Dataset Object for train data\n device: Device to put the loaded tensors on\n save_directory: Where to save the checkpoints\n batch_size: How many elements should be loaded at once\n epochs_per_save: how many epochs to train in between checkpoints\n \"\"\"\n net = net.to(device)\n scaler = GradScaler()\n\n previous_error = 999999 # tacotron can collapse sometimes and requires soft-resets. This is to detect collapses.\n train_loader = DataLoader(batch_size=batch_size,\n dataset=train_dataset,\n drop_last=True,\n num_workers=10,\n pin_memory=True,\n shuffle=True,\n prefetch_factor=10,\n collate_fn=collate_and_pad,\n persistent_workers=True)\n if use_speaker_embedding:\n reference_speaker_embedding_for_att_plot = torch.Tensor(train_dataset[0][4]).to(device)\n if use_cycle_consistency_for_speakerembedding:\n speaker_embedding_func = EncoderClassifier.from_hparams(source=\"speechbrain/spkrec-ecapa-voxceleb\",\n run_opts={\"device\": str(device)},\n savedir=\"Models/speechbrain_speaker_embedding_ecapa\")\n else:\n reference_speaker_embedding_for_att_plot = None\n step_counter = 0\n epoch = 0\n net.train()\n optimizer = torch.optim.Adam(net.parameters(), lr=lr)\n if resume:\n path_to_checkpoint = get_most_recent_checkpoint(checkpoint_dir=save_directory)\n if path_to_checkpoint is not None:\n # careful when restarting, plotting data will be overwritten!\n check_dict = torch.load(os.path.join(path_to_checkpoint), map_location=device)\n net.load_state_dict(check_dict[\"model\"])\n if not fine_tune:\n optimizer.load_state_dict(check_dict[\"optimizer\"])\n scaler.load_state_dict(check_dict[\"scaler\"])\n step_counter = check_dict[\"step_counter\"]\n start_time = time.time()\n while True:\n epoch += 1\n optimizer.zero_grad()\n train_losses_this_epoch = list()\n for batch in tqdm(train_loader):\n with autocast():\n if not use_speaker_embedding:\n train_loss = net(text=batch[0].to(device),\n text_lengths=batch[1].to(device),\n speech=batch[2].to(device),\n speech_lengths=batch[3].to(device),\n step=step_counter)\n else:\n if not use_cycle_consistency_for_speakerembedding:\n train_loss = net(text=batch[0].to(device),\n text_lengths=batch[1].to(device),\n speech=batch[2].to(device),\n speech_lengths=batch[3].to(device),\n step=step_counter,\n speaker_embeddings=batch[4].to(device))\n else:\n train_loss, predicted_mels = net(text=batch[0].to(device),\n text_lengths=batch[1].to(device),\n speech=batch[2].to(device),\n speech_lengths=batch[3].to(device),\n step=step_counter,\n speaker_embeddings=batch[4].to(device),\n return_mels=True)\n pred_spemb = speaker_embedding_func.modules.embedding_model(predicted_mels,\n torch.tensor([x / len(predicted_mels[0]) for x in batch[3]]))\n gold_spemb = speaker_embedding_func.modules.embedding_model(batch[2].to(device),\n torch.tensor([x / len(batch[2][0]) for x in batch[3]]))\n # we have to recalculate the speaker embedding from our own mel because we project into a slightly different mel space\n cosine_cycle_distance = torch.tensor(1.0) - F.cosine_similarity(pred_spemb.squeeze(), gold_spemb.squeeze(), dim=1).mean()\n pairwise_cycle_distance = F.pairwise_distance(pred_spemb.squeeze(), gold_spemb.squeeze()).mean()\n cycle_distance = cosine_cycle_distance + pairwise_cycle_distance\n del pred_spemb\n del predicted_mels\n del gold_spemb\n train_loss = train_loss + cycle_distance * 5\n train_losses_this_epoch.append(train_loss.item())\n optimizer.zero_grad()\n scaler.scale(train_loss).backward()\n del train_loss\n step_counter += 1\n scaler.unscale_(optimizer)\n torch.nn.utils.clip_grad_norm_(net.parameters(), 1.0, error_if_nonfinite=False)\n scaler.step(optimizer)\n scaler.update()\n with torch.no_grad():\n net.eval()\n loss_this_epoch = sum(train_losses_this_epoch) / len(train_losses_this_epoch)\n if previous_error + collapse_margin < loss_this_epoch:\n print(\"Model Collapse detected! \\nPrevious Loss: {}\\nNew Loss: {}\".format(previous_error, loss_this_epoch))\n print(\"Trying to reset to a stable state ...\")\n path_to_checkpoint = get_most_recent_checkpoint(checkpoint_dir=save_directory)\n check_dict = torch.load(path_to_checkpoint, map_location=device)\n net.load_state_dict(check_dict[\"model\"])\n if not fine_tune:\n optimizer.load_state_dict(check_dict[\"optimizer\"])\n step_counter = check_dict[\"step_counter\"]\n scaler.load_state_dict(check_dict[\"scaler\"])\n else:\n previous_error = loss_this_epoch\n if epoch % epochs_per_save == 0:\n torch.save({\n \"model\" : net.state_dict(),\n \"optimizer\" : optimizer.state_dict(),\n \"scaler\" : scaler.state_dict(),\n \"step_counter\": step_counter,\n }, os.path.join(save_directory, \"checkpoint_{}.pt\".format(step_counter)))\n delete_old_checkpoints(save_directory, keep=5)\n plot_attention(model=net,\n lang=lang,\n device=device,\n speaker_embedding=reference_speaker_embedding_for_att_plot,\n att_dir=save_directory,\n step=step_counter)\n if step_counter > steps:\n # DONE\n return\n print(\"Epoch: {}\".format(epoch))\n print(\"Train Loss: {}\".format(loss_this_epoch))\n print(\"Time elapsed: {} Minutes\".format(round((time.time() - start_time) / 60)))\n print(\"Steps: {}\".format(step_counter))\n torch.cuda.empty_cache()\n net.train()\n" ]
[ [ "torch.zeros", "torch.device", "torch.cat", "torch.no_grad", "matplotlib.pyplot.subplots", "matplotlib.pyplot.tight_layout", "matplotlib.pyplot.show", "matplotlib.pyplot.subplots_adjust" ], [ "torch.utils.data.dataloader.DataLoader", "torch.stack", "torch.cuda.amp.autocast", "torch.nn.utils.rnn.pad_sequence", "torch.no_grad", "matplotlib.pyplot.close", "matplotlib.pyplot.subplots", "torch.cuda.empty_cache", "torch.tensor", "torch.load", "torch.cuda.amp.GradScaler", "torch.Tensor" ] ]
oyj0594/apex
[ "b66ffc1d952d0b20d6706ada783ae5b23e4ee734", "b66ffc1d952d0b20d6706ada783ae5b23e4ee734" ]
[ "apex/pyprof/examples/jit/jit_script_method.py", "apex/pyprof/examples/imagenet/imagenet.py" ]
[ "#!/usr/bin/env python3\n\nimport torch\nimport torch.cuda.profiler as profiler\nfrom apex import pyprof\n\nclass Foo(torch.jit.ScriptModule):\n def __init__(self, size):\n super(Foo, self).__init__()\n self.n = torch.nn.Parameter(torch.ones(size))\n self.m = torch.nn.Parameter(torch.ones(size))\n\n @torch.jit.script_method\n def forward(self, input):\n return self.n*input + self.m\n\n#Initialize pyprof after the JIT step\npyprof.nvtx.init()\n\n#Hook up the forward function to pyprof\npyprof.nvtx.wrap(Foo, 'forward')\n\nfoo = Foo(4)\nfoo.cuda()\nx = torch.ones(4).cuda()\n\nwith torch.autograd.profiler.emit_nvtx():\n\tprofiler.start()\n\tz = foo(x)\n\tprofiler.stop()\n\tprint(z)\n", "#!/usr/bin/env python3\n\n\"\"\"\nExample to run pyprof with imagenet models.\n\"\"\"\n\nimport sys\nimport torch\nimport torch.nn as nn\nimport torchvision.models as models\nimport torch.cuda.profiler as profiler\nimport argparse\n\nfrom apex import pyprof\nfrom apex.optimizers import FusedAdam\n\ndef parseArgs():\n\tparser = argparse.ArgumentParser(prog=sys.argv[0], description=\"Run popular imagenet models.\")\n\n\tparser.add_argument(\"-m\",\n\t\ttype=str,\n\t\tdefault=\"resnet50\",\n\t\tchoices=[\"alexnet\", \"densenet121\", \"densenet161\", \"densenet169\", \"densenet201\", \"googlenet\", \"mnasnet0_5\", \"mnasnet0_75\", \"mnasnet1_0\", \"mnasnet1_3\", \"mobilenet_v2\", \"resnet18\", \"resnet34\", \"resnet50\", \"resnet101\", \"resnet152\", \"resnext50_32x4d\", \"resnext101_32x8d\", \"wide_resnet50_2\", \"wide_resnet101_2\", \"shufflenet_v2_x0_5\", \"shufflenet_v2_x1_0\", \"shufflenet_v2_x1_5\", \"shufflenet_v2_x2_0\", \"squeezenet1_0\", \"squeezenet1_1\", \"vgg11\", \"vgg11_bn\", \"vgg13\", \"vgg13_bn\", \"vgg16\", \"vgg16_bn\", \"vgg19\", \"vgg19_bn\", \"inception_v3\"],\n\t\thelp=\"Model.\")\n\n\tparser.add_argument(\"-b\",\n\t\ttype=int,\n\t\tdefault=32,\n\t\thelp=\"Batch size.\")\n\n\tparser.add_argument(\"-o\",\n\t\ttype=str,\n\t\tdefault=\"adam\",\n\t\tchoices=[\"adam\", \"sgd\"],\n\t\thelp=\"Optimizer.\")\n\n\targs = parser.parse_args()\n\treturn args\n\nd = {\n\t\"alexnet\":\t\t\t\t{'H': 224, 'W': 224, 'opts': {}},\n\n\t\"densenet121\":\t\t\t{'H': 224, 'W': 224, 'opts': {}},\n\t\"densenet161\":\t\t\t{'H': 224, 'W': 224, 'opts': {}},\n\t\"densenet169\":\t\t\t{'H': 224, 'W': 224, 'opts': {}},\n\t\"densenet201\":\t\t\t{'H': 224, 'W': 224, 'opts': {}},\n\n\t\"googlenet\":\t\t\t{'H': 224, 'W': 224, 'opts': {'aux_logits': False}},\n\n\t\"mnasnet0_5\":\t\t\t{'H': 224, 'W': 224, 'opts': {}},\n\t\"mnasnet0_75\":\t\t\t{'H': 224, 'W': 224, 'opts': {}},\n\t\"mnasnet1_0\":\t\t\t{'H': 224, 'W': 224, 'opts': {}},\n\t\"mnasnet1_3\":\t\t\t{'H': 224, 'W': 224, 'opts': {}},\n\n\t\"mobilenet_v2\":\t\t\t{'H': 224, 'W': 224, 'opts': {}},\n\n\t\"resnet18\":\t\t\t\t{'H': 224, 'W': 224, 'opts': {}},\n\t\"resnet34\":\t\t\t\t{'H': 224, 'W': 224, 'opts': {}},\n\t\"resnet50\":\t\t\t\t{'H': 224, 'W': 224, 'opts': {}},\n\t\"resnet101\":\t\t\t{'H': 224, 'W': 224, 'opts': {}},\n\t\"resnet152\":\t\t\t{'H': 224, 'W': 224, 'opts': {}},\n\n\t\"resnext50_32x4d\":\t\t{'H': 224, 'W': 224, 'opts': {}},\n\t\"resnext101_32x8d\":\t\t{'H': 224, 'W': 224, 'opts': {}},\n\n\t\"wide_resnet50_2\":\t\t{'H': 224, 'W': 224, 'opts': {}},\n\t\"wide_resnet101_2\":\t\t{'H': 224, 'W': 224, 'opts': {}},\n\n\t\"shufflenet_v2_x0_5\": \t{'H': 224, 'W': 224, 'opts': {}},\n\t\"shufflenet_v2_x1_0\": \t{'H': 224, 'W': 224, 'opts': {}},\n\t\"shufflenet_v2_x1_5\": \t{'H': 224, 'W': 224, 'opts': {}},\n\t\"shufflenet_v2_x2_0\":\t{'H': 224, 'W': 224, 'opts': {}},\n\n\t\"squeezenet1_0\":\t\t{'H': 224, 'W': 224, 'opts': {}},\n\t\"squeezenet1_1\":\t\t{'H': 224, 'W': 224, 'opts': {}},\n\n\t\"vgg11\":\t\t\t\t{'H': 224, 'W': 224, 'opts': {}},\n\t\"vgg11_bn\":\t\t\t\t{'H': 224, 'W': 224, 'opts': {}},\n\t\"vgg13\":\t\t\t\t{'H': 224, 'W': 224, 'opts': {}},\n\t\"vgg13_bn\":\t\t\t\t{'H': 224, 'W': 224, 'opts': {}},\n\t\"vgg16\":\t\t\t\t{'H': 224, 'W': 224, 'opts': {}},\n\t\"vgg16_bn\":\t\t\t\t{'H': 224, 'W': 224, 'opts': {}},\n\t\"vgg19\":\t\t\t\t{'H': 224, 'W': 224, 'opts': {}},\n\t\"vgg19_bn\":\t\t\t\t{'H': 224, 'W': 224, 'opts': {}},\n\n\t\"inception_v3\":\t\t\t{'H': 299, 'W': 299, 'opts': {'aux_logits': False}},\n\t}\n\ndef main():\n\targs = parseArgs()\n\n\tpyprof.nvtx.init()\n#\tpyprof.nvtx.wrap(fused_adam_cuda, 'adam')\n\n\tN = args.b\n\tC = 3\n\tH = d[args.m]['H']\n\tW = d[args.m]['W']\n\topts = d[args.m]['opts']\n\tclasses = 1000\n\n\tnet = getattr(models, args.m)\n\tnet = net(**opts).cuda().half()\n\tnet.train()\n\n\tx = torch.rand(N, C, H, W).cuda().half()\n\ttarget = torch.empty(N, dtype=torch.long).random_(classes).cuda()\n\n\tcriterion = nn.CrossEntropyLoss().cuda()\n\tif (args.o == \"sgd\"):\n\t\toptimizer = torch.optim.SGD(net.parameters(), lr = 0.01, momentum=0.9)\n\telif (args.o == \"adam\"):\n\t\toptimizer = FusedAdam(net.parameters())\n\telse:\n\t\tassert False\n\n\t#Warm up without profiler\n\tfor i in range(2):\n\t\toutput = net(x)\n\t\tloss = criterion(output, target)\n\t\toptimizer.zero_grad()\n\t\tloss.backward()\n\t\toptimizer.step()\n\n\twith torch.autograd.profiler.emit_nvtx():\n\t\tprofiler.start()\n\t\toutput = net(x)\n\t\tloss = criterion(output, target)\n\t\toptimizer.zero_grad()\n\t\tloss.backward()\n\t\toptimizer.step()\n\t\tprofiler.stop()\n\nif __name__ == \"__main__\":\n\tmain()\n" ]
[ [ "torch.cuda.profiler.start", "torch.autograd.profiler.emit_nvtx", "torch.cuda.profiler.stop", "torch.ones" ], [ "torch.rand", "torch.autograd.profiler.emit_nvtx", "torch.cuda.profiler.stop", "torch.cuda.profiler.start", "torch.empty", "torch.nn.CrossEntropyLoss" ] ]
enohoxha/AxonPy
[ "2c89200cdc1818cdaa4dc9b0fbec68036cb11a4b" ]
[ "playgrounds/keras_models/features/girl_boy/girl_boy_feature.py" ]
[ "import cv2\nimport numpy as np\n\nimport definitions\nfrom playgrounds.core.features import Feature\nfrom playgrounds.keras_models.features.girl_boy.workers.custom_workers import CustomWorker1\nfrom playgrounds.opencv import face_detection\nfrom playgrounds.utilities import opencv_utilities\n\n\nclass GenderClassifier(Feature):\n\n def __init__(self):\n super().__init__()\n self.workers = {\n \"custom1\": CustomWorker1()\n }\n\n def runFeature(self, worker, inputData, inType =\"image\"):\n self.worker = self.workers.get(worker)\n func = self.inputTypes.get(inType)\n func(worker, inputData)\n\n\n def trainFeature(self, worker):\n self.worker = self.workers.get(worker)\n self.worker.train()\n\n\n def runOnVideo(self, worker, inputData):\n self.worker = self.workers.get(worker)\n self.worker.buildModel()\n cap = cv2.VideoCapture(inputData)\n fourcc = cv2.VideoWriter_fourcc(*'mp4v')\n path = definitions.ROOT_DIR + \"/outputs/tiny_yolo/\" + opencv_utilities.getFileNameFromPath(inputData)\n out = cv2.VideoWriter(path, fourcc, 20.0, (854, 356))\n while cap.isOpened():\n ret, frame = cap.read()\n self.getGender(frame)\n # out.write(frame)\n cv2.imshow(\"V\", frame)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n cap.release()\n cv2.destroyAllWindows()\n\n def getGender(self, img):\n faces = opencv_utilities.getFaceFromImage(img)\n for (x, y, width, height) in faces:\n if x > 40 and y > 40:\n x = x-40\n y = y-40\n width += 40\n height += 40\n crop_img = img[y:y + height, x:x + width]\n crop_img = cv2.resize(crop_img, (64, 64))\n crop_img = crop_img / 255\n crop_img = np.expand_dims(crop_img, axis=0)\n\n text = self.worker.predict(crop_img)\n if text > 0.6:\n text = \"Man\"\n elif text < 0.6:\n text = \"Woman\"\n cv2.rectangle(img, (x, y), (x + width, y + height), (0, 255, 0), 1)\n font = cv2.FONT_HERSHEY_SIMPLEX\n cv2.putText(img, text, (x, y), font, 0.8, (255, 255, 255), 1, cv2.LINE_AA)\n" ]
[ [ "numpy.expand_dims" ] ]
RPGroup-PBoC/sortseq_belliveau
[ "ca3b0b8092bbe6deaf1b82b2dab67b4bcca679f2" ]
[ "code/figures/figS8_purT_massspec_scatter_nohypoxanthine.py" ]
[ "import os\nimport glob\nimport pickle\nimport re\n\n# Our numerical workhorses\nimport numpy as np\nimport pandas as pd\n\n# Import the project utils\nimport sys\nsys.path.insert(0, '../')\nimport NB_sortseq_utils as utils\n\n# Import matplotlib stuff for plotting\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\n\n# Seaborn, useful for graphics\nimport seaborn as sns\n\nsns.set_palette(\"deep\", color_codes=True)\n\nutils.set_plotting_style_MS()\n\n#===============================================================================\n# Set output directory\n#===============================================================================\noutput = 'output_figs/'\n\n#===============================================================================\n# Read the data\n#===============================================================================\n\ndatadir = '../mass_spec/*/'\nfiles = glob.glob(datadir+'*2016*_purT_*.csv')\n\ndf = pd.DataFrame()\n\nfor f in enumerate(files):\n print(f[1])\n df_temp = pd.DataFrame()\n df_temp = pd.read_csv(f[1])\n\n # append data to df\n df = df.append(df_temp)\n\n\n#===============================================================================\n# determine 95% probability density bounds using all data\n#===============================================================================\n\n# calculate the average and standard deviation of each protein detected\nby_row_index = df.groupby(df.gene)\ndf_means = by_row_index['maxquant_ratio_medianshift'].mean()\ndf_std = by_row_index['maxquant_ratio_medianshift'].std()\n\n# convert the groupby arrays back into dataframes\ndf_means_new = pd.DataFrame(df_means).reset_index()\ndf_means_new.columns = ['gene', 'maxquant_ratio_normalized_avg']\ndf_std_new = pd.DataFrame(df_std).reset_index()\ndf_means_new['maxquant_ratio_normalized_std'] = df_std_new['maxquant_ratio_medianshift']\n\n# determine 95% bounds on data\nY = df_means_new['maxquant_ratio_normalized_avg'].dropna().values\nx_2_5 = np.log(np.percentile(Y,2.5))\nx_97_5 = np.log(np.percentile(Y,97.5))\n\n\n#===============================================================================\n# remove proteins which were not identified in each replicate.\n# for identification of TFs we will consider those proteins which were\n# found in each of the three replicates.\n#===============================================================================\n\n# group by gene names and remove those which do not have a ratio in\n# each replicate\n# by_row_index = df.groupby(df.gene)\n\n# # discard enrichment ratios not based on three measurements\n# for i in by_row_index['maxquant_ratio_medianshift']:\n# if len(i[1].dropna()) < 3:\n# df = df[df.gene != i[0]]\n\n#===============================================================================\n# plot the enrichment ratios as scatter points\n#===============================================================================\n\n\n#-------------------------------------------------------------------------------\n# consider only the proteins with predicted DNA binding motif for plotting.\n# follow same procedure and find mean and standard deviation\n#-------------------------------------------------------------------------------\n# make DataFrame with only proteins with known or predicted DNA binding domain\ndf_TF = df[df['TF_check'] == 1]\n# group data by protein and calculate average log ratio and std. deviation\nby_row_index = df_TF.groupby(df_TF.gene)\ndf_means_TF_log = by_row_index['maxquant_logratio_medianshift'].mean()\ndf_std_TF_log = by_row_index['maxquant_logratio_medianshift'].std()\n\n# Make DataFrame of mean values\ndf_means_new_TF = pd.DataFrame(df_means_TF_log).reset_index()\ndf_means_new_TF.columns = ['gene', 'maxquant_ratio_normalized_avg_log']\n\n# Make DataFrame of std. deviation values\ndf_std_new_TF = pd.DataFrame(df_std_TF_log).reset_index()\ndf_std_new_TF.columns = ['gene', 'maxquant_ratio_normalized_std_log']\n\n# Merge average and std. deviation values into summary DataFrame\ndf_summary_TF = pd.merge(df_means_new_TF,df_std_new_TF,on='gene')\n\n#-------------------------------------------------------------------------------\n# calculate average enrichment ratio (not log) as well as lower and upper bounds\n# based on log std. deviation.\n#-------------------------------------------------------------------------------\n\ndf_summary_TF['maxquant_ratio_normalized_avg'] = \\\n np.exp(df_summary_TF['maxquant_ratio_normalized_avg_log'])\n\n# determine error bar - lower bound\ndf_summary_TF['bottom'] = np.exp(df_summary_TF['maxquant_ratio_normalized_avg_log'] -\n df_summary_TF['maxquant_ratio_normalized_std_log']/np.sqrt(3))\n# determine error bar - upper bound\ndf_summary_TF['top'] = np.exp(df_summary_TF['maxquant_ratio_normalized_avg_log'] +\n df_summary_TF['maxquant_ratio_normalized_std_log']/np.sqrt(3))\n\n#-------------------------------------------------------------------------------\n# plot mean enrichment ratio and standard deviation for each protein\n#-------------------------------------------------------------------------------\n\nfig = plt.figure(figsize=utils.cm2inch(3, 5))\nax1 = fig.add_subplot(111)\n\nax1.fill_between([0.95,1.05],np.exp(x_2_5),np.exp(x_97_5), color = 'k',alpha = 0.25)\n\nyvals_TF = df_summary_TF\nvals = np.random.uniform(0.99,1.01,size=len(yvals_TF))\n\nyvals_err = [df_summary_TF['maxquant_ratio_normalized_avg'] - df_summary_TF['bottom'],\n df_summary_TF['top'] - df_summary_TF['maxquant_ratio_normalized_avg']]\n\nax1.errorbar(vals, yvals_TF['maxquant_ratio_normalized_avg'],\n yerr = yvals_err,\n linestyle='none',fmt='o', alpha = 0.6, markersize=4)\nax1.set_xlim(0.95,1.05)\nax1.set_xticklabels(['purT'])\nax1.set_ylabel('enrichment ratio', fontsize=8)\nax1.xaxis.grid(False)\n\nax1.set_yscale('log')\nax1.tick_params(which='minor', length=1.5, color='#ffffff', direction = 'in')\nax1.set_ylim(1E-3,1E3)\nplt.tight_layout()\n\nplt.savefig(output+'figS8_purT_massspec_scatter_nohypoxanthine.pdf', format='pdf')\nprint('# with predected DNA-binding motif',len(yvals_TF))\n" ]
[ [ "pandas.merge", "pandas.DataFrame", "matplotlib.pyplot.savefig", "numpy.percentile", "numpy.exp", "matplotlib.pyplot.tight_layout", "numpy.sqrt", "pandas.read_csv" ] ]
jo-ny/CarND-Advanced-Lane-Lines
[ "9362e11cdd239fbf7422fa057a44734d9c0938d3" ]
[ "lane/Lane.py" ]
[ "# -*- coding: utf-8 -*-\nimport cv2\nimport numpy as np\nimport matplotlib.image as mpimg\nimport matplotlib.pyplot as plt\n\n\n# Define a class to receive the characteristics of each line detection\nclass Lane():\n def __init__(self):\n # 当前的图像\n self.current_warped_binary = None\n # 当前图片的尺寸\n self.current_warped_binary_shape = []\n\n # 检测到的车道线像素的横坐标 x values for detected line pixels\n self.allx = None\n\n # 检测到的车道线像素的纵坐标 y values for detected line pixels\n self.ally = None\n\n # 以纵坐标为自变量,取值空间\n self.ploty = None\n\n # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n # 是否检测到车道线 was the line detected in the last iteration?\n self.detected = False\n\n # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n # 保存的数据量\n self.n = 5\n\n # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n # 最近n个帧的拟合曲线 x values of the last n fits of the line\n self.recent_fitted_xs = []\n\n # 最近n个帧的平均拟合曲线 average x values of the fitted line over the last n iterations\n self.average_fitted_x = []\n\n # 当前帧的拟合曲线\n self.current_fitted_x = []\n\n # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n # 最近n个帧的拟合函数\n self.recent_fits = []\n\n # 最近n个帧的拟合函数 polynomial coefficients averaged over the last n iterations\n self.average_fit = []\n\n # 当前帧的拟合函数 polynomial coefficients for the most recent fit\n self.current_fit = [np.array([False])]\n\n # 拟合函数的误差 difference in fit coefficients between last and new fits\n self.diffs = np.array([0, 0, 0], dtype='float')\n\n # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n # 半径 radius of curvature of the line in some units\n self.radius_of_curvature = []\n\n # 车辆在车道线之间距离 distance in meters of vehicle center from the line\n self.line_base_pos = None\n\n # 对全新的帧进行车道线像素检测\n def find_lane_pixels(self, binary_warped, location):\n self.current_warped_binary = binary_warped\n self.current_warped_binary_shape = binary_warped.shape\n self.ploty = np.linspace(0, binary_warped.shape[0] - 1, binary_warped.shape[0])\n\n # Take a histogram of the bottom half of the image\n histogram = np.sum(binary_warped[binary_warped.shape[0] // 2:, :], axis=0)\n # Create an output image to draw on and visualize the result\n # out_img = np.dstack((binary_warped, binary_warped, binary_warped))\n # Find the peak of the left and right halves of the histogram\n # These will be the starting point for the left and right lines\n midpoint = np.int(histogram.shape[0] // 2)\n\n if location == \"left\":\n base = np.argmax(histogram[:midpoint])\n elif location == \"right\":\n base = np.argmax(histogram[midpoint:]) + midpoint\n\n # HYPERPARAMETERS\n # Choose the number of sliding windows\n nwindows = 9\n # Set the width of the windows +/- margin\n margin = 80\n # Set minimum number of pixels found to recenter window\n minpix = 50\n\n # Set height of windows - based on nwindows above and image shape\n window_height = np.int(binary_warped.shape[0] // nwindows)\n # Identify the x and y positions of all nonzero pixels in the image\n nonzero = binary_warped.nonzero() # 扁平化后非零值点的列表\n nonzeroy = np.array(nonzero[0])\n nonzerox = np.array(nonzero[1])\n # Current positions to be updated later for each window in nwindows\n\n current = base\n\n # Create empty lists to receive left and right lane pixel indices\n lane_inds = []\n # right_lane_inds = []\n\n # Step through the windows one by one\n for window in range(nwindows):\n # Identify window boundaries in x and y (and right and left)\n win_y_low = binary_warped.shape[0] - (window + 1) * window_height\n win_y_high = binary_warped.shape[0] - window * window_height\n win_x_low = current - margin\n win_x_high = current + margin\n\n # # Draw the windows on the visualization image\n # cv2.rectangle(out_img, (win_xleft_low, win_y_low),\n # (win_xleft_high, win_y_high), (0, 255, 0), 2)\n # cv2.rectangle(out_img, (win_xright_low, win_y_low),\n # (win_xright_high, win_y_high), (0, 255, 0), 2)\n\n # 形成对每个像素的bool值\n # Identify the nonzero pixels in x and y within the window #\n good_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) &\n (nonzerox >= win_x_low) & (nonzerox < win_x_high)).nonzero()[0]\n\n # Append these indices to the lists\n lane_inds.append(good_inds)\n\n # If you found > minpix pixels, recenter next window on their mean position\n if len(good_inds) > minpix:\n current = np.int(np.mean(nonzerox[good_inds]))\n\n # Concatenate the arrays of indices (previously was a list of lists of pixels)\n try:\n lane_inds = np.concatenate(lane_inds)\n except ValueError:\n # Avoids an error if the above is not implemented fully\n pass\n\n # Extract left and right line pixel positions\n x = nonzerox[lane_inds]\n y = nonzeroy[lane_inds]\n\n self.allx = x\n self.ally = y\n\n return x, y\n\n # 在之前的plot基础上找车道线\n def search_pixel_around_poly(self, binary_warped):\n\n self.current_warped_binary = binary_warped\n self.current_warped_binary_shape = binary_warped.shape\n self.ploty = np.linspace(0, binary_warped.shape[0] - 1, binary_warped.shape[0])\n\n # HYPERPARAMETER\n # Choose the width of the margin around the previous polynomial to search\n # The quiz grader expects 100 here, but feel free to tune on your own!\n margin = 80\n\n # Grab activated pixels\n nonzero = binary_warped.nonzero()\n nonzeroy = np.array(nonzero[0])\n nonzerox = np.array(nonzero[1])\n\n fit = self.recent_fits[-1]\n\n ### TO-DO: Set the area of search based on activated x-values ###\n ### within the +/- margin of our polynomial function ###\n ### Hint: consider the window areas for the similarly named variables ###\n ### in the previous quiz, but change the windows to our new search area ###\n lane_inds = ((nonzerox > (fit[0] * (nonzeroy ** 2) + fit[1] * nonzeroy + fit[2] - margin)) & (\n nonzerox < (fit[0] * (nonzeroy ** 2) + fit[1] * nonzeroy + fit[2] + margin)))\n\n # Again, extract left and right line pixel positions\n x = nonzerox[lane_inds]\n y = nonzeroy[lane_inds]\n\n self.allx = x\n self.ally = y\n\n return x, y\n\n def fit_polynomial(self):\n ploty = self.ploty\n\n # Fit a second order polynomial to each using `np.polyfit`\n fit = np.polyfit(self.ally, self.allx, 2)\n\n # 存储当前结果\n self.current_fit = fit\n\n # 计算误差\n if len(self.recent_fits) == 0:\n self.diffs = [0,0,0]\n else:\n new = np.array(self.current_fit)\n old = np.array(self.recent_fits[-1])\n self.diffs = new - old\n\n # 存储为历史结果\n if len(self.recent_fits) < self.n:\n self.recent_fits.append(self.current_fit)\n elif len(self.recent_fits) == self.n:\n self.recent_fits.pop(0)\n self.recent_fits.append(self.current_fit)\n else:\n self.recent_fits.append(self.current_fit)\n self.recent_fits = self.recent_fits[-self.n:] # 后面n个\n\n # 计算当前平均\n self.average_fit = np.array(self.recent_fits).mean(axis=0)\n\n\n try:\n x_fitted = self.average_fit[0] * ploty ** 2 + self.average_fit[1] * ploty + self.average_fit[2]\n except TypeError:\n # Avoids an error if `left` and `right_fit` are still none or incorrect\n print('The function failed to fit a line!')\n x_fitted = 1 * ploty ** 2 + 1 * ploty\n self.detected = False\n else:\n self.detected = True\n\n self.current_fitted_x = x_fitted\n\n # 存储为历史结果\n if len(self.recent_fitted_xs) < self.n:\n self.recent_fitted_xs.append(self.current_fitted_x)\n elif len(self.recent_fitted_xs) == self.n:\n self.recent_fitted_xs.pop(0)\n self.recent_fitted_xs.append(self.current_fitted_x)\n else:\n self.recent_fitted_xs.append(self.current_fitted_x)\n self.recent_fitted_xs = self.recent_fitted_xs[-self.n:] # 后面n个\n\n self.average_fitted_x = np.array(self.recent_fitted_xs).mean(axis=0)\n\n return self.average_fitted_x\n\n def fit(self, binary_warped,location,sequence=True):\n if sequence:\n if not self.detected:\n # 没有检测到,重新开始检测\n self.find_lane_pixels(binary_warped,location)\n else:\n # 从上一次周围开始检测\n self.search_pixel_around_poly(binary_warped)\n # TODO 如果两次检测的误差较大怎么办?\n # TODO 是否存在\n\n self.fit_polynomial()\n # if np.abs(self.diffs).sum() > 20:\n # self.current_fit = np.array(self.recent_fits[:-1]).mean(axis=0)\n # self.recent_fits[-1] = self.current_fit\n # self.average_fit = np.array(self.recent_fits).mean(axis=0)\n #\n # self.current_fitted_x = np.array(self.recent_fitted_xs[:-1]).mean(axis=0)\n # self.recent_fitted_xs[-1] = self.current_fitted_x\n # self.average_fitted_x = np.array(self.recent_fitted_xs).mean(axis=0)\n else:\n self.find_lane_pixels(binary_warped, location)\n self.fit_polynomial()\n\n def measure_curvature_real(self,ploty, x, y):\n '''\n Calculates the curvature of polynomial functions in meters.\n '''\n # Define conversions in x and y from pixels space to meters\n ym_per_pix = 30 / 720 # meters per pixel in y dimension\n xm_per_pix = 3.7 / 700 # meters per pixel in x dimension\n\n fit_cr = np.polyfit(y * ym_per_pix, x * xm_per_pix, 2)\n\n # Define y-value where we want radius of curvature\n # We'll choose the maximum y-value, corresponding to the bottom of the image\n y_eval = np.max(ploty)\n\n # Calculation of R_curve (radius of curvature)\n curverad = ((1 + (2 * fit_cr[0] * y_eval * ym_per_pix + fit_cr[1]) ** 2) ** 1.5) / np.absolute(2 * fit_cr[0])\n\n self.radius_of_curvature = curverad\n\n return curverad\n\n\nif __name__ == \"__main__\":\n from lane.perspective import perspective,src,dst\n from lane.gaussian_blur import gaussian_blur\n from lane.combined_threshold import combined_threshold\n from lane.measure_vehicle_pos import measure_vehicle_pos\n from lane.draw_lane import draw_lane\n\n image = mpimg.imread('../output_images/undistorted/straight_lines1-undistorted.jpg')\n\n image = gaussian_blur(image, 3)\n combined = combined_threshold(image, ksize=3,\n th=[[20, 100], [25, 254], [100, 250], [0.6, 1.2], [180, 254], [250, 0]])\n combined = gaussian_blur(combined, 3)\n perspectived_img = perspective(combined,src,dst)\n \n # plt.imshow(perspectived_img,cmap=\"gray\")\n # plt.show()\n\n left_lane = Lane()\n left_lane.fit(perspectived_img,\"left\")\n\n right_lane = Lane()\n right_lane.fit(perspectived_img, \"right\")\n\n\n result = left_lane.visual(perspectived_img,\"left\")\n plt.imshow(result)\n result = right_lane.visual(perspectived_img, \"right\")\n plt.imshow(result)\n plt.show()\n # # 计算曲率\n # left_r = left_lane.measure_curvature_real(left_lane.ploty, left_lane.average_fitted_x, left_lane.ploty)\n # right_r = left_lane.measure_curvature_real(right_lane.ploty, right_lane.average_fitted_x, right_lane.ploty)\n #\n # # 计算偏移值\n # v = measure_vehicle_pos(left_lane.average_fitted_x, right_lane.average_fitted_x,left_lane.current_warped_binary_shape[1])\n #\n # # 绘制车道线\n # img = draw_lane(image, combined, dst, src,left_lane.current_fitted_x, right_lane.current_fitted_x, right_lane.ploty)\n\n\n # plt.imshow(img)\n\n\n # # 打印文字\n # plt.text(0,60,\"Radius of Curvature = %d(m)\"%int(r),fontdict={'size': 20, 'color': 'w'})\n # plt.text(0,120, \"Vehicle is %.2f(m) left of center\" % v, fontdict={'size': 20, 'color': 'w'})\n # plt.show()\n\n\n\n\n\n\n\n\n" ]
[ [ "numpy.max", "numpy.concatenate", "numpy.array", "numpy.int", "numpy.sum", "matplotlib.image.imread", "numpy.mean", "numpy.argmax", "numpy.polyfit", "numpy.absolute", "matplotlib.pyplot.show", "numpy.linspace", "matplotlib.pyplot.imshow" ] ]
arepstein/pymatgen
[ "084adf5262ff5151bf07fb93cbd4524101bfaf62" ]
[ "pymatgen/io/vasp/outputs.py" ]
[ "# coding: utf-8\n# Copyright (c) Pymatgen Development Team.\n# Distributed under the terms of the MIT License.\n\n\"\"\"\nClasses for reading/manipulating/writing VASP ouput files.\n\"\"\"\n\nimport json\nimport glob\nimport itertools\nimport logging\nimport math\nimport os\nimport re\nimport warnings\nfrom pathlib import Path\nimport xml.etree.cElementTree as ET\nfrom collections import defaultdict\nfrom io import StringIO\nimport collections\n\nimport numpy as np\nfrom monty.io import zopen, reverse_readfile\nfrom monty.json import MSONable\nfrom monty.json import jsanitize\nfrom monty.re import regrep\nfrom monty.os.path import zpath\nfrom monty.dev import deprecated\n\nfrom pymatgen.core.composition import Composition\nfrom pymatgen.core.lattice import Lattice\nfrom pymatgen.core.periodic_table import Element\nfrom pymatgen.core.structure import Structure\nfrom pymatgen.core.units import unitized\nfrom pymatgen.electronic_structure.bandstructure import BandStructure, \\\n BandStructureSymmLine, get_reconstructed_band_structure\nfrom pymatgen.electronic_structure.core import Spin, Orbital, OrbitalType, Magmom\nfrom pymatgen.electronic_structure.dos import CompleteDos, Dos\nfrom pymatgen.entries.computed_entries import \\\n ComputedEntry, ComputedStructureEntry\nfrom pymatgen.io.vasp.inputs import Incar, Kpoints, Poscar, Potcar\nfrom pymatgen.util.io_utils import clean_lines, micro_pyawk\nfrom pymatgen.util.num import make_symmetric_matrix_from_upper_tri\n\n\n__author__ = \"Shyue Ping Ong, Geoffroy Hautier, Rickard Armiento, \" + \\\n \"Vincent L Chevrier, Ioannis Petousis, Stephen Dacek, Mark Turiansky\"\n__credits__ = \"Anubhav Jain\"\n__copyright__ = \"Copyright 2011, The Materials Project\"\n__version__ = \"1.2\"\n__maintainer__ = \"Shyue Ping Ong\"\n__email__ = \"shyuep@gmail.com\"\n__status__ = \"Production\"\n__date__ = \"Nov 30, 2012\"\n\nlogger = logging.getLogger(__name__)\n\n\ndef _parse_parameters(val_type, val):\n \"\"\"\n Helper function to convert a Vasprun parameter into the proper type.\n Boolean, int and float types are converted.\n\n Args:\n val_type: Value type parsed from vasprun.xml.\n val: Actual string value parsed for vasprun.xml.\n \"\"\"\n if val_type == \"logical\":\n return val == \"T\"\n elif val_type == \"int\":\n return int(val)\n elif val_type == \"string\":\n return val.strip()\n else:\n return float(val)\n\n\ndef _parse_v_parameters(val_type, val, filename, param_name):\n r\"\"\"\n Helper function to convert a Vasprun array-type parameter into the proper\n type. Boolean, int and float types are converted.\n\n Args:\n val_type: Value type parsed from vasprun.xml.\n val: Actual string value parsed for vasprun.xml.\n filename: Fullpath of vasprun.xml. Used for robust error handling.\n E.g., if vasprun.xml contains *** for some Incar parameters,\n the code will try to read from an INCAR file present in the same\n directory.\n param_name: Name of parameter.\n\n Returns:\n Parsed value.\n \"\"\"\n if val_type == \"logical\":\n val = [i == \"T\" for i in val.split()]\n elif val_type == \"int\":\n try:\n val = [int(i) for i in val.split()]\n except ValueError:\n # Fix for stupid error in vasprun sometimes which displays\n # LDAUL/J as 2****\n val = _parse_from_incar(filename, param_name)\n if val is None:\n raise IOError(\"Error in parsing vasprun.xml\")\n elif val_type == \"string\":\n val = val.split()\n else:\n try:\n val = [float(i) for i in val.split()]\n except ValueError:\n # Fix for stupid error in vasprun sometimes which displays\n # MAGMOM as 2****\n val = _parse_from_incar(filename, param_name)\n if val is None:\n raise IOError(\"Error in parsing vasprun.xml\")\n return val\n\n\ndef _parse_varray(elem):\n if elem.get(\"type\", None) == 'logical':\n m = [[True if i == 'T' else False for i in v.text.split()] for v in elem]\n else:\n m = [[_vasprun_float(i) for i in v.text.split()] for v in elem]\n return m\n\n\ndef _parse_from_incar(filename, key):\n \"\"\"\n Helper function to parse a parameter from the INCAR.\n \"\"\"\n dirname = os.path.dirname(filename)\n for f in os.listdir(dirname):\n if re.search(r\"INCAR\", f):\n warnings.warn(\"INCAR found. Using \" + key + \" from INCAR.\")\n incar = Incar.from_file(os.path.join(dirname, f))\n if key in incar:\n return incar[key]\n else:\n return None\n return None\n\n\ndef _vasprun_float(f):\n \"\"\"\n Large numbers are often represented as ********* in the vasprun.\n This function parses these values as np.nan\n \"\"\"\n try:\n return float(f)\n except ValueError as e:\n f = f.strip()\n if f == '*' * len(f):\n warnings.warn('Float overflow (*******) encountered in vasprun')\n return np.nan\n raise e\n\n\nclass Vasprun(MSONable):\n \"\"\"\n Vastly improved cElementTree-based parser for vasprun.xml files. Uses\n iterparse to support incremental parsing of large files.\n Speedup over Dom is at least 2x for smallish files (~1Mb) to orders of\n magnitude for larger files (~10Mb).\n\n **Vasp results**\n\n .. attribute:: ionic_steps\n\n All ionic steps in the run as a list of\n {\"structure\": structure at end of run,\n \"electronic_steps\": {All electronic step data in vasprun file},\n \"stresses\": stress matrix}\n\n .. attribute:: tdos\n\n Total dos calculated at the end of run.\n\n .. attribute:: idos\n\n Integrated dos calculated at the end of run.\n\n .. attribute:: pdos\n\n List of list of PDos objects. Access as pdos[atomindex][orbitalindex]\n\n .. attribute:: efermi\n\n Fermi energy\n\n .. attribute:: eigenvalues\n\n Available only if parse_eigen=True. Final eigenvalues as a dict of\n {(spin, kpoint index):[[eigenvalue, occu]]}.\n This representation is based on actual ordering in VASP and is meant as\n an intermediate representation to be converted into proper objects. The\n kpoint index is 0-based (unlike the 1-based indexing in VASP).\n\n .. attribute:: projected_eigenvalues\n\n Final projected eigenvalues as a dict of {spin: nd-array}. To access\n a particular value, you need to do\n Vasprun.projected_eigenvalues[spin][kpoint index][band index][atom index][orbital_index]\n This representation is based on actual ordering in VASP and is meant as\n an intermediate representation to be converted into proper objects. The\n kpoint, band and atom indices are 0-based (unlike the 1-based indexing\n in VASP).\n\n\n .. attribute:: other_dielectric\n\n Dictionary, with the tag comment as key, containing other variants of\n the real and imaginary part of the dielectric constant (e.g., computed\n by RPA) in function of the energy (frequency). Optical properties (e.g.\n absorption coefficient) can be obtained through this.\n The data is given as a tuple of 3 values containing each of them\n the energy, the real part tensor, and the imaginary part tensor\n ([energies],[[real_partxx,real_partyy,real_partzz,real_partxy,\n real_partyz,real_partxz]],[[imag_partxx,imag_partyy,imag_partzz,\n imag_partxy, imag_partyz, imag_partxz]])\n\n .. attribute:: nionic_steps\n\n The total number of ionic steps. This number is always equal\n to the total number of steps in the actual run even if\n ionic_step_skip is used.\n\n .. attribute:: force_constants\n\n Force constants computed in phonon DFPT run(IBRION = 8).\n The data is a 4D numpy array of shape (natoms, natoms, 3, 3).\n\n .. attribute:: normalmode_eigenvals\n\n Normal mode frequencies.\n 1D numpy array of size 3*natoms.\n\n .. attribute:: normalmode_eigenvecs\n\n Normal mode eigen vectors.\n 3D numpy array of shape (3*natoms, natoms, 3).\n\n **Vasp inputs**\n\n .. attribute:: incar\n\n Incar object for parameters specified in INCAR file.\n\n .. attribute:: parameters\n\n Incar object with parameters that vasp actually used, including all\n defaults.\n\n .. attribute:: kpoints\n\n Kpoints object for KPOINTS specified in run.\n\n .. attribute:: actual_kpoints\n\n List of actual kpoints, e.g.,\n [[0.25, 0.125, 0.08333333], [-0.25, 0.125, 0.08333333],\n [0.25, 0.375, 0.08333333], ....]\n\n .. attribute:: actual_kpoints_weights\n\n List of kpoint weights, E.g.,\n [0.04166667, 0.04166667, 0.04166667, 0.04166667, 0.04166667, ....]\n\n .. attribute:: atomic_symbols\n\n List of atomic symbols, e.g., [\"Li\", \"Fe\", \"Fe\", \"P\", \"P\", \"P\"]\n\n .. attribute:: potcar_symbols\n\n List of POTCAR symbols. e.g.,\n [\"PAW_PBE Li 17Jan2003\", \"PAW_PBE Fe 06Sep2000\", ..]\n\n Author: Shyue Ping Ong\n \"\"\"\n\n def __init__(self, filename, ionic_step_skip=None,\n ionic_step_offset=0, parse_dos=True,\n parse_eigen=True, parse_projected_eigen=False,\n parse_potcar_file=True, occu_tol=1e-8,\n exception_on_bad_xml=True):\n \"\"\"\n Args:\n filename (str): Filename to parse\n ionic_step_skip (int): If ionic_step_skip is a number > 1,\n only every ionic_step_skip ionic steps will be read for\n structure and energies. This is very useful if you are parsing\n very large vasprun.xml files and you are not interested in every\n single ionic step. Note that the final energies may not be the\n actual final energy in the vasprun.\n ionic_step_offset (int): Used together with ionic_step_skip. If set,\n the first ionic step read will be offset by the amount of\n ionic_step_offset. For example, if you want to start reading\n every 10th structure but only from the 3rd structure onwards,\n set ionic_step_skip to 10 and ionic_step_offset to 3. Main use\n case is when doing statistical structure analysis with\n extremely long time scale multiple VASP calculations of\n varying numbers of steps.\n parse_dos (bool): Whether to parse the dos. Defaults to True. Set\n to False to shave off significant time from the parsing if you\n are not interested in getting those data.\n parse_eigen (bool): Whether to parse the eigenvalues. Defaults to\n True. Set to False to shave off significant time from the\n parsing if you are not interested in getting those data.\n parse_projected_eigen (bool): Whether to parse the projected\n eigenvalues. Defaults to False. Set to True to obtain projected\n eigenvalues. **Note that this can take an extreme amount of time\n and memory.** So use this wisely.\n parse_potcar_file (bool/str): Whether to parse the potcar file to read\n the potcar hashes for the potcar_spec attribute. Defaults to True,\n where no hashes will be determined and the potcar_spec dictionaries\n will read {\"symbol\": ElSymbol, \"hash\": None}. By Default, looks in\n the same directory as the vasprun.xml, with same extensions as\n Vasprun.xml. If a string is provided, looks at that filepath.\n occu_tol (float): Sets the minimum tol for the determination of the\n vbm and cbm. Usually the default of 1e-8 works well enough,\n but there may be pathological cases.\n exception_on_bad_xml (bool): Whether to throw a ParseException if a\n malformed XML is detected. Default to True, which ensures only\n proper vasprun.xml are parsed. You can set to False if you want\n partial results (e.g., if you are monitoring a calculation during a\n run), but use the results with care. A warning is issued.\n \"\"\"\n self.filename = filename\n self.ionic_step_skip = ionic_step_skip\n self.ionic_step_offset = ionic_step_offset\n self.occu_tol = occu_tol\n self.exception_on_bad_xml = exception_on_bad_xml\n\n with zopen(filename, \"rt\") as f:\n if ionic_step_skip or ionic_step_offset:\n # remove parts of the xml file and parse the string\n run = f.read()\n steps = run.split(\"<calculation>\")\n # The text before the first <calculation> is the preamble!\n preamble = steps.pop(0)\n self.nionic_steps = len(steps)\n new_steps = steps[ionic_step_offset::int(ionic_step_skip)]\n # add the tailing informat in the last step from the run\n to_parse = \"<calculation>\".join(new_steps)\n if steps[-1] != new_steps[-1]:\n to_parse = \"{}<calculation>{}{}\".format(\n preamble, to_parse,\n steps[-1].split(\"</calculation>\")[-1])\n else:\n to_parse = \"{}<calculation>{}\".format(preamble, to_parse)\n self._parse(StringIO(to_parse), parse_dos=parse_dos,\n parse_eigen=parse_eigen,\n parse_projected_eigen=parse_projected_eigen)\n else:\n self._parse(f, parse_dos=parse_dos, parse_eigen=parse_eigen,\n parse_projected_eigen=parse_projected_eigen)\n self.nionic_steps = len(self.ionic_steps)\n\n if parse_potcar_file:\n self.update_potcar_spec(parse_potcar_file)\n self.update_charge_from_potcar(parse_potcar_file)\n\n if self.incar.get(\"ALGO\", \"\") != \"BSE\" and (not self.converged):\n msg = \"%s is an unconverged VASP run.\\n\" % filename\n msg += \"Electronic convergence reached: %s.\\n\" % \\\n self.converged_electronic\n msg += \"Ionic convergence reached: %s.\" % self.converged_ionic\n warnings.warn(msg, UnconvergedVASPWarning)\n\n def _parse(self, stream, parse_dos, parse_eigen, parse_projected_eigen):\n self.efermi = None\n self.eigenvalues = None\n self.projected_eigenvalues = None\n self.dielectric_data = {}\n self.other_dielectric = {}\n ionic_steps = []\n parsed_header = False\n try:\n for event, elem in ET.iterparse(stream):\n tag = elem.tag\n if not parsed_header:\n if tag == \"generator\":\n self.generator = self._parse_params(elem)\n elif tag == \"incar\":\n self.incar = self._parse_params(elem)\n elif tag == \"kpoints\":\n if not hasattr(self, 'kpoints'):\n self.kpoints, self.actual_kpoints, self.actual_kpoints_weights = self._parse_kpoints(elem)\n elif tag == \"parameters\":\n self.parameters = self._parse_params(elem)\n elif tag == \"structure\" and elem.attrib.get(\"name\") == \"initialpos\":\n self.initial_structure = self._parse_structure(elem)\n elif tag == \"atominfo\":\n self.atomic_symbols, self.potcar_symbols = self._parse_atominfo(elem)\n self.potcar_spec = [{\"titel\": p,\n \"hash\": None} for\n p in self.potcar_symbols]\n if tag == \"calculation\":\n parsed_header = True\n if not self.parameters.get(\"LCHIMAG\", False):\n ionic_steps.append(self._parse_calculation(elem))\n else:\n ionic_steps.extend(self._parse_chemical_shielding_calculation(elem))\n elif parse_dos and tag == \"dos\":\n try:\n self.tdos, self.idos, self.pdos = self._parse_dos(elem)\n self.efermi = self.tdos.efermi\n self.dos_has_errors = False\n except Exception:\n self.dos_has_errors = True\n elif parse_eigen and tag == \"eigenvalues\":\n self.eigenvalues = self._parse_eigen(elem)\n elif parse_projected_eigen and tag == \"projected\":\n self.projected_eigenvalues = self._parse_projected_eigen(\n elem)\n elif tag == \"dielectricfunction\":\n if (\"comment\" not in elem.attrib or\n elem.attrib[\"comment\"] ==\n \"INVERSE MACROSCOPIC DIELECTRIC TENSOR (including \"\n \"local field effects in RPA (Hartree))\"):\n if 'density' not in self.dielectric_data:\n self.dielectric_data['density'] = self._parse_diel(\n elem)\n elif 'velocity' not in self.dielectric_data:\n # \"velocity-velocity\" is also named\n # \"current-current\" in OUTCAR\n self.dielectric_data['velocity'] = self._parse_diel(\n elem)\n else:\n raise NotImplementedError(\n 'This vasprun.xml has >2 unlabelled dielectric '\n 'functions')\n else:\n comment = elem.attrib[\"comment\"]\n # VASP 6+ has labels for the density and current\n # derived dielectric constants\n if comment == \"density-density\":\n self.dielectric_data[\"density\"] = self._parse_diel(\n elem)\n elif comment == \"current-current\":\n self.dielectric_data[\"velocity\"] = self._parse_diel(\n elem)\n else:\n self.other_dielectric[comment] = self._parse_diel(\n elem)\n\n elif tag == \"varray\" and elem.attrib.get(\"name\") == 'opticaltransitions':\n self.optical_transition = np.array(_parse_varray(elem))\n elif tag == \"structure\" and elem.attrib.get(\"name\") == \\\n \"finalpos\":\n self.final_structure = self._parse_structure(elem)\n elif tag == \"dynmat\":\n hessian, eigenvalues, eigenvectors = self._parse_dynmat(elem)\n natoms = len(self.atomic_symbols)\n hessian = np.array(hessian)\n self.force_constants = np.zeros((natoms, natoms, 3, 3), dtype='double')\n for i in range(natoms):\n for j in range(natoms):\n self.force_constants[i, j] = hessian[i * 3:(i + 1) * 3, j * 3:(j + 1) * 3]\n phonon_eigenvectors = []\n for ev in eigenvectors:\n phonon_eigenvectors.append(np.array(ev).reshape(natoms, 3))\n self.normalmode_eigenvals = np.array(eigenvalues)\n self.normalmode_eigenvecs = np.array(phonon_eigenvectors)\n except ET.ParseError as ex:\n if self.exception_on_bad_xml:\n raise ex\n else:\n warnings.warn(\n \"XML is malformed. Parsing has stopped but partial data\"\n \"is available.\", UserWarning)\n self.ionic_steps = ionic_steps\n self.vasp_version = self.generator[\"version\"]\n\n @property\n def structures(self):\n \"\"\"\n Returns:\n List of Structure objects for the structure at each ionic step.\n \"\"\"\n return [step[\"structure\"] for step in self.ionic_steps]\n\n @property\n def epsilon_static(self):\n \"\"\"\n Property only available for DFPT calculations.\n\n Returns:\n The static part of the dielectric constant. Present when it's a DFPT run\n (LEPSILON=TRUE)\n \"\"\"\n return self.ionic_steps[-1].get(\"epsilon\", [])\n\n @property\n def epsilon_static_wolfe(self):\n \"\"\"\n Property only available for DFPT calculations.\n\n Returns:\n The static part of the dielectric constant without any local field\n effects. Present when it's a DFPT run (LEPSILON=TRUE)\n \"\"\"\n return self.ionic_steps[-1].get(\"epsilon_rpa\", [])\n\n @property\n def epsilon_ionic(self):\n \"\"\"\n Property only available for DFPT calculations and when IBRION=5, 6, 7 or 8.\n\n Returns:\n The ionic part of the static dielectric constant. Present when it's a\n DFPT run (LEPSILON=TRUE) and IBRION=5, 6, 7 or 8\n\n \"\"\"\n return self.ionic_steps[-1].get(\"epsilon_ion\", [])\n\n @property\n def dielectric(self):\n \"\"\"\n Returns:\n The real and imaginary part of the dielectric constant (e.g., computed\n by RPA) in function of the energy (frequency). Optical properties (e.g.\n absorption coefficient) can be obtained through this.\n The data is given as a tuple of 3 values containing each of them\n the energy, the real part tensor, and the imaginary part tensor\n ([energies],[[real_partxx,real_partyy,real_partzz,real_partxy,\n real_partyz,real_partxz]],[[imag_partxx,imag_partyy,imag_partzz,\n imag_partxy, imag_partyz, imag_partxz]])\n \"\"\"\n return self.dielectric_data['density']\n\n @property\n def optical_absorption_coeff(self):\n \"\"\"\n Calculate the optical absorption coefficient\n from the dielectric constants. Note that this method is only\n implemented for optical properties calculated with GGA and BSE.\n Returns:\n optical absorption coefficient in list\n \"\"\"\n if self.dielectric_data[\"density\"]:\n real_avg = [sum(self.dielectric_data[\"density\"][1][i][0:3]) / 3\n for i in range(len(self.dielectric_data[\"density\"][0]))]\n imag_avg = [sum(self.dielectric_data[\"density\"][2][i][0:3]) / 3\n for i in range(len(self.dielectric_data[\"density\"][0]))]\n\n def f(freq, real, imag):\n \"\"\"\n The optical absorption coefficient calculated in terms of\n \u0004\u0001equation\n \"\"\"\n hbar = 6.582119514e-16 # eV/K\n coeff = np.sqrt(np.sqrt(real ** 2 + imag ** 2) - real) * np.sqrt(2) / hbar * freq\n return coeff\n\n absorption_coeff = [f(freq, real, imag) for freq, real, imag in\n zip(self.dielectric_data[\"density\"][0], real_avg, imag_avg)]\n return absorption_coeff\n\n @property\n def converged_electronic(self):\n \"\"\"\n Returns:\n True if electronic step convergence has been reached in the final\n ionic step\n \"\"\"\n final_esteps = self.ionic_steps[-1][\"electronic_steps\"]\n if 'LEPSILON' in self.incar and self.incar['LEPSILON']:\n i = 1\n to_check = set(['e_wo_entrp', 'e_fr_energy', 'e_0_energy'])\n while set(final_esteps[i].keys()) == to_check:\n i += 1\n return i + 1 != self.parameters[\"NELM\"]\n return len(final_esteps) < self.parameters[\"NELM\"]\n\n @property\n def converged_ionic(self):\n \"\"\"\n Returns:\n True if ionic step convergence has been reached, i.e. that vasp\n exited before reaching the max ionic steps for a relaxation run\n \"\"\"\n nsw = self.parameters.get(\"NSW\", 0)\n return nsw <= 1 or len(self.ionic_steps) < nsw\n\n @property\n def converged(self):\n \"\"\"\n Returns:\n True if a relaxation run is converged both ionically and\n electronically.\n \"\"\"\n return self.converged_electronic and self.converged_ionic\n\n @property # type: ignore\n @unitized(\"eV\")\n def final_energy(self):\n \"\"\"\n Final energy from the vasp run.\n \"\"\"\n try:\n final_istep = self.ionic_steps[-1]\n if final_istep[\"e_wo_entrp\"] != final_istep['electronic_steps'][-1][\"e_0_energy\"]:\n warnings.warn(\"Final e_wo_entrp differs from the final \"\n \"electronic step. VASP may have included some \"\n \"corrections, e.g., vdw. Vasprun will return \"\n \"the final e_wo_entrp, i.e., including \"\n \"corrections in such instances.\")\n return final_istep[\"e_wo_entrp\"]\n return final_istep['electronic_steps'][-1][\"e_0_energy\"]\n except (IndexError, KeyError):\n warnings.warn(\"Calculation does not have a total energy. \"\n \"Possibly a GW or similar kind of run. A value of \"\n \"infinity is returned.\")\n return float('inf')\n\n @property\n def complete_dos(self):\n \"\"\"\n A complete dos object which incorporates the total dos and all\n projected dos.\n \"\"\"\n final_struct = self.final_structure\n pdoss = {final_struct[i]: pdos for i, pdos in enumerate(self.pdos)}\n return CompleteDos(self.final_structure, self.tdos, pdoss)\n\n @property\n def hubbards(self):\n \"\"\"\n Hubbard U values used if a vasprun is a GGA+U run. {} otherwise.\n \"\"\"\n symbols = [s.split()[1] for s in self.potcar_symbols]\n symbols = [re.split(r\"_\", s)[0] for s in symbols]\n if not self.incar.get(\"LDAU\", False):\n return {}\n us = self.incar.get(\"LDAUU\", self.parameters.get(\"LDAUU\"))\n js = self.incar.get(\"LDAUJ\", self.parameters.get(\"LDAUJ\"))\n if len(js) != len(us):\n js = [0] * len(us)\n if len(us) == len(symbols):\n return {symbols[i]: us[i] - js[i] for i in range(len(symbols))}\n elif sum(us) == 0 and sum(js) == 0:\n return {}\n else:\n raise VaspParserError(\"Length of U value parameters and atomic \"\n \"symbols are mismatched\")\n\n @property\n def run_type(self):\n \"\"\"\n Returns the run type. Currently supports LDA, GGA, vdW-DF and HF calcs.\n\n TODO: Fix for other functional types like PW91, other vdW types, etc.\n \"\"\"\n GGA_TYPES = {\"RE\": \"revPBE\", \"PE\": \"PBE\", \"PS\": \"PBESol\", \"RP\": \"RevPBE+PADE\", \"AM\": \"AM05\", \"OR\": \"optPBE\",\n \"BO\": \"optB88\", \"MK\": \"optB86b\", \"--\": \"GGA\"}\n\n METAGGA_TYPES = {\"TPSS\": \"TPSS\", \"RTPSS\": \"revTPSS\", \"M06L\": \"M06-L\", \"MBJ\": \"modified Becke-Johnson\",\n \"SCAN\": \"SCAN\", \"MS0\": \"MadeSimple0\", \"MS1\": \"MadeSimple1\", \"MS2\": \"MadeSimple2\"}\n\n if self.parameters.get(\"AEXX\", 1.00) == 1.00:\n rt = \"HF\"\n elif self.parameters.get(\"HFSCREEN\", 0.30) == 0.30:\n rt = \"HSE03\"\n elif self.parameters.get(\"HFSCREEN\", 0.20) == 0.20:\n rt = \"HSE06\"\n elif self.parameters.get(\"AEXX\", 0.20) == 0.20:\n rt = \"B3LYP\"\n elif self.parameters.get(\"LHFCALC\", True):\n rt = \"PBEO or other Hybrid Functional\"\n elif self.parameters.get(\"LUSE_VDW\", False):\n if self.incar.get(\"METAGGA\", \"\").strip().upper() in METAGGA_TYPES:\n rt = METAGGA_TYPES[self.incar.get(\"METAGGA\", \"\").strip().upper()] + \"+rVV10\"\n else:\n rt = GGA_TYPES[self.parameters.get(\"GGA\", \"\").strip().upper()] + \"+rVV10\"\n elif self.incar.get(\"METAGGA\", \"\").strip().upper() in METAGGA_TYPES:\n rt = METAGGA_TYPES[self.incar.get(\"METAGGA\", \"\").strip().upper()]\n if self.is_hubbard or self.parameters.get(\"LDAU\", True):\n rt += \"+U\"\n elif self.potcar_symbols[0].split()[0] == 'PAW':\n rt = \"LDA\"\n elif self.parameters.get(\"GGA\", \"\").strip().upper() in GGA_TYPES:\n rt = GGA_TYPES[self.parameters.get(\"GGA\", \"\").strip().upper()]\n if self.is_hubbard or self.parameters.get(\"LDAU\", True):\n rt += \"+U\"\n return rt\n\n @property\n def is_hubbard(self):\n \"\"\"\n True if run is a DFT+U run.\n \"\"\"\n if len(self.hubbards) == 0:\n return False\n return sum(self.hubbards.values()) > 1e-8\n\n @property\n def is_spin(self):\n \"\"\"\n True if run is spin-polarized.\n \"\"\"\n return self.parameters.get(\"ISPIN\", 1) == 2\n\n def get_computed_entry(self, inc_structure=True, parameters=None,\n data=None):\n \"\"\"\n Returns a ComputedStructureEntry from the vasprun.\n\n Args:\n inc_structure (bool): Set to True if you want\n ComputedStructureEntries to be returned instead of\n ComputedEntries.\n parameters (list): Input parameters to include. It has to be one of\n the properties supported by the Vasprun object. If\n parameters is None, a default set of parameters that are\n necessary for typical post-processing will be set.\n data (list): Output data to include. Has to be one of the properties\n supported by the Vasprun object.\n\n Returns:\n ComputedStructureEntry/ComputedEntry\n \"\"\"\n param_names = {\"is_hubbard\", \"hubbards\", \"potcar_symbols\",\n \"potcar_spec\", \"run_type\"}\n if parameters:\n param_names.update(parameters)\n params = {p: getattr(self, p) for p in param_names}\n data = {p: getattr(self, p) for p in data} if data is not None else {}\n\n if inc_structure:\n return ComputedStructureEntry(self.final_structure,\n self.final_energy, parameters=params,\n data=data)\n else:\n return ComputedEntry(self.final_structure.composition,\n self.final_energy, parameters=params,\n data=data)\n\n def get_band_structure(self, kpoints_filename=None, efermi=None,\n line_mode=False, force_hybrid_mode=False):\n \"\"\"\n Returns the band structure as a BandStructure object\n\n Args:\n kpoints_filename (str): Full path of the KPOINTS file from which\n the band structure is generated.\n If none is provided, the code will try to intelligently\n determine the appropriate KPOINTS file by substituting the\n filename of the vasprun.xml with KPOINTS.\n The latter is the default behavior.\n efermi (float): If you want to specify manually the fermi energy\n this is where you should do it. By default, the None value\n means the code will get it from the vasprun.\n line_mode (bool): Force the band structure to be considered as\n a run along symmetry lines.\n force_hybrid_mode (bool): Makes it possible to read in self-consistent band structure calculations for\n every type of functional\n\n Returns:\n a BandStructure object (or more specifically a\n BandStructureSymmLine object if the run is detected to be a run\n along symmetry lines)\n\n Two types of runs along symmetry lines are accepted: non-sc with\n Line-Mode in the KPOINT file or hybrid, self-consistent with a\n uniform grid+a few kpoints along symmetry lines (explicit KPOINTS\n file) (it's not possible to run a non-sc band structure with hybrid\n functionals). The explicit KPOINTS file needs to have data on the\n kpoint label as commentary.\n \"\"\"\n\n if not kpoints_filename:\n kpoints_filename = zpath(\n os.path.join(os.path.dirname(self.filename), 'KPOINTS'))\n if not os.path.exists(kpoints_filename) and line_mode is True:\n raise VaspParserError('KPOINTS needed to obtain band structure '\n 'along symmetry lines.')\n\n if efermi is None:\n efermi = self.efermi\n\n kpoint_file = None\n if os.path.exists(kpoints_filename):\n kpoint_file = Kpoints.from_file(kpoints_filename)\n lattice_new = Lattice(self.final_structure.lattice.reciprocal_lattice.matrix)\n\n kpoints = [np.array(self.actual_kpoints[i])\n for i in range(len(self.actual_kpoints))]\n\n p_eigenvals = defaultdict(list)\n eigenvals = defaultdict(list)\n\n nkpts = len(kpoints)\n\n for spin, v in self.eigenvalues.items():\n v = np.swapaxes(v, 0, 1)\n eigenvals[spin] = v[:, :, 0]\n\n if self.projected_eigenvalues:\n peigen = self.projected_eigenvalues[spin]\n # Original axes for self.projected_eigenvalues are kpoints,\n # band, ion, orb.\n # For BS input, we need band, kpoints, orb, ion.\n peigen = np.swapaxes(peigen, 0, 1) # Swap kpoint and band axes\n peigen = np.swapaxes(peigen, 2, 3) # Swap ion and orb axes\n\n p_eigenvals[spin] = peigen\n # for b in range(min_eigenvalues):\n # p_eigenvals[spin].append(\n # [{Orbital(orb): v for orb, v in enumerate(peigen[b, k])}\n # for k in range(nkpts)])\n\n # check if we have an hybrid band structure computation\n # for this we look at the presence of the LHFCALC tag\n hybrid_band = False\n if self.parameters.get('LHFCALC', False) or \\\n 0. in self.actual_kpoints_weights:\n hybrid_band = True\n\n if kpoint_file is not None:\n if kpoint_file.style == Kpoints.supported_modes.Line_mode:\n line_mode = True\n\n if line_mode:\n labels_dict = {}\n if hybrid_band or force_hybrid_mode:\n start_bs_index = 0\n for i in range(len(self.actual_kpoints)):\n if self.actual_kpoints_weights[i] == 0.0:\n start_bs_index = i\n break\n for i in range(start_bs_index, len(kpoint_file.kpts)):\n if kpoint_file.labels[i] is not None:\n labels_dict[kpoint_file.labels[i]] = \\\n kpoint_file.kpts[i]\n # remake the data only considering line band structure k-points\n # (weight = 0.0 kpoints)\n nbands = len(eigenvals[Spin.up])\n kpoints = kpoints[start_bs_index:nkpts]\n up_eigen = [eigenvals[Spin.up][i][start_bs_index:nkpts]\n for i in range(nbands)]\n if self.projected_eigenvalues:\n p_eigenvals[Spin.up] = [p_eigenvals[Spin.up][i][\n start_bs_index:nkpts]\n for i in range(nbands)]\n if self.is_spin:\n down_eigen = [eigenvals[Spin.down][i][start_bs_index:nkpts]\n for i in range(nbands)]\n eigenvals = {Spin.up: up_eigen, Spin.down: down_eigen}\n if self.projected_eigenvalues:\n p_eigenvals[Spin.down] = [p_eigenvals[Spin.down][i][\n start_bs_index:nkpts]\n for i in range(nbands)]\n else:\n eigenvals = {Spin.up: up_eigen}\n else:\n if '' in kpoint_file.labels:\n raise Exception(\"A band structure along symmetry lines \"\n \"requires a label for each kpoint. \"\n \"Check your KPOINTS file\")\n labels_dict = dict(zip(kpoint_file.labels, kpoint_file.kpts))\n labels_dict.pop(None, None)\n return BandStructureSymmLine(kpoints, eigenvals, lattice_new,\n efermi, labels_dict,\n structure=self.final_structure,\n projections=p_eigenvals)\n else:\n return BandStructure(kpoints, eigenvals, lattice_new, efermi,\n structure=self.final_structure,\n projections=p_eigenvals)\n\n @property\n def eigenvalue_band_properties(self):\n \"\"\"\n Band properties from the eigenvalues as a tuple,\n (band gap, cbm, vbm, is_band_gap_direct).\n \"\"\"\n vbm = -float(\"inf\")\n vbm_kpoint = None\n cbm = float(\"inf\")\n cbm_kpoint = None\n for spin, d in self.eigenvalues.items():\n for k, val in enumerate(d):\n for (eigenval, occu) in val:\n if occu > self.occu_tol and eigenval > vbm:\n vbm = eigenval\n vbm_kpoint = k\n elif occu <= self.occu_tol and eigenval < cbm:\n cbm = eigenval\n cbm_kpoint = k\n return max(cbm - vbm, 0), cbm, vbm, vbm_kpoint == cbm_kpoint\n\n def get_potcars(self, path):\n \"\"\"\n :param path: Path to search for POTCARs\n :return: Potcar from path.\n \"\"\"\n def get_potcar_in_path(p):\n for fn in os.listdir(os.path.abspath(p)):\n if fn.startswith('POTCAR'):\n pc = Potcar.from_file(os.path.join(p, fn))\n if {d.header for d in pc} == \\\n {sym for sym in self.potcar_symbols}:\n return pc\n warnings.warn(\"No POTCAR file with matching TITEL fields\"\n \" was found in {}\".format(os.path.abspath(p)))\n\n if isinstance(path, (str, Path)):\n path = str(path)\n if \"POTCAR\" in path:\n potcar = Potcar.from_file(path)\n if {d.TITEL for d in potcar} != \\\n {sym for sym in self.potcar_symbols}:\n raise ValueError(\"Potcar TITELs do not match Vasprun\")\n else:\n potcar = get_potcar_in_path(path)\n elif isinstance(path, bool) and path:\n potcar = get_potcar_in_path(os.path.split(self.filename)[0])\n else:\n potcar = None\n\n return potcar\n\n def update_potcar_spec(self, path):\n \"\"\"\n :param path: Path to search for POTCARs\n :return: Potcar spec from path.\n \"\"\"\n potcar = self.get_potcars(path)\n if potcar:\n self.potcar_spec = [{\"titel\": sym, \"hash\": ps.get_potcar_hash()}\n for sym in self.potcar_symbols\n for ps in potcar if\n ps.symbol == sym.split()[1]]\n\n def update_charge_from_potcar(self, path):\n \"\"\"\n Sets the charge of a structure based on the POTCARs found.\n\n :param path: Path to search for POTCARs\n \"\"\"\n potcar = self.get_potcars(path)\n\n if potcar and self.incar.get(\"ALGO\", \"\") not in [\"GW0\", \"G0W0\", \"GW\", \"BSE\"]:\n nelect = self.parameters[\"NELECT\"]\n if len(potcar) == len(self.initial_structure.composition.element_composition):\n potcar_nelect = sum([\n self.initial_structure.composition.element_composition[ps.element] * ps.ZVAL\n for ps in potcar])\n else:\n nums = [len(list(g)) for _, g in\n itertools.groupby(self.atomic_symbols)]\n potcar_nelect = sum(ps.ZVAL * num for ps, num in\n zip(potcar, nums))\n charge = nelect - potcar_nelect\n\n if charge:\n for s in self.structures:\n s._charge = charge\n\n def as_dict(self):\n \"\"\"\n Json-serializable dict representation.\n \"\"\"\n d = {\"vasp_version\": self.vasp_version,\n \"has_vasp_completed\": self.converged,\n \"nsites\": len(self.final_structure)}\n comp = self.final_structure.composition\n d[\"unit_cell_formula\"] = comp.as_dict()\n d[\"reduced_cell_formula\"] = Composition(comp.reduced_formula).as_dict()\n d[\"pretty_formula\"] = comp.reduced_formula\n symbols = [s.split()[1] for s in self.potcar_symbols]\n symbols = [re.split(r\"_\", s)[0] for s in symbols]\n d[\"is_hubbard\"] = self.is_hubbard\n d[\"hubbards\"] = self.hubbards\n\n unique_symbols = sorted(list(set(self.atomic_symbols)))\n d[\"elements\"] = unique_symbols\n d[\"nelements\"] = len(unique_symbols)\n\n d[\"run_type\"] = self.run_type\n\n vin = {\"incar\": {k: v for k, v in self.incar.items()},\n \"crystal\": self.initial_structure.as_dict(),\n \"kpoints\": self.kpoints.as_dict()}\n actual_kpts = [{\"abc\": list(self.actual_kpoints[i]),\n \"weight\": self.actual_kpoints_weights[i]}\n for i in range(len(self.actual_kpoints))]\n vin[\"kpoints\"][\"actual_points\"] = actual_kpts\n vin[\"nkpoints\"] = len(actual_kpts)\n vin[\"potcar\"] = [s.split(\" \")[1] for s in self.potcar_symbols]\n vin[\"potcar_spec\"] = self.potcar_spec\n vin[\"potcar_type\"] = [s.split(\" \")[0] for s in self.potcar_symbols]\n vin[\"parameters\"] = {k: v for k, v in self.parameters.items()}\n vin[\"lattice_rec\"] = self.final_structure.lattice.reciprocal_lattice.as_dict()\n d[\"input\"] = vin\n\n nsites = len(self.final_structure)\n\n try:\n vout = {\"ionic_steps\": self.ionic_steps,\n \"final_energy\": self.final_energy,\n \"final_energy_per_atom\": self.final_energy / nsites,\n \"crystal\": self.final_structure.as_dict(),\n \"efermi\": self.efermi}\n except (ArithmeticError, TypeError):\n vout = {\"ionic_steps\": self.ionic_steps,\n \"final_energy\": self.final_energy,\n \"final_energy_per_atom\": None,\n \"crystal\": self.final_structure.as_dict(),\n \"efermi\": self.efermi}\n\n if self.eigenvalues:\n eigen = {str(spin): v.tolist()\n for spin, v in self.eigenvalues.items()}\n vout[\"eigenvalues\"] = eigen\n (gap, cbm, vbm, is_direct) = self.eigenvalue_band_properties\n vout.update(dict(bandgap=gap, cbm=cbm, vbm=vbm,\n is_gap_direct=is_direct))\n\n if self.projected_eigenvalues:\n vout['projected_eigenvalues'] = {\n str(spin): v.tolist()\n for spin, v in self.projected_eigenvalues.items()}\n\n vout['epsilon_static'] = self.epsilon_static\n vout['epsilon_static_wolfe'] = self.epsilon_static_wolfe\n vout['epsilon_ionic'] = self.epsilon_ionic\n d['output'] = vout\n return jsanitize(d, strict=True)\n\n def _parse_params(self, elem):\n params = {}\n for c in elem:\n name = c.attrib.get(\"name\")\n if c.tag not in (\"i\", \"v\"):\n p = self._parse_params(c)\n if name == \"response functions\":\n # Delete duplicate fields from \"response functions\",\n # which overrides the values in the root params.\n p = {k: v for k, v in p.items() if k not in params}\n params.update(p)\n else:\n ptype = c.attrib.get(\"type\")\n val = c.text.strip() if c.text else \"\"\n if c.tag == \"i\":\n params[name] = _parse_parameters(ptype, val)\n else:\n params[name] = _parse_v_parameters(ptype, val,\n self.filename, name)\n elem.clear()\n return Incar(params)\n\n def _parse_atominfo(self, elem):\n for a in elem.findall(\"array\"):\n if a.attrib[\"name\"] == \"atoms\":\n atomic_symbols = [rc.find(\"c\").text.strip()\n for rc in a.find(\"set\")]\n elif a.attrib[\"name\"] == \"atomtypes\":\n potcar_symbols = [rc.findall(\"c\")[4].text.strip()\n for rc in a.find(\"set\")]\n\n # ensure atomic symbols are valid elements\n def parse_atomic_symbol(symbol):\n try:\n return str(Element(symbol))\n # vasprun.xml uses X instead of Xe for xenon\n except ValueError as e:\n if symbol == \"X\":\n return \"Xe\"\n elif symbol == \"r\":\n return \"Zr\"\n raise e\n\n elem.clear()\n return [parse_atomic_symbol(sym) for\n sym in atomic_symbols], potcar_symbols\n\n def _parse_kpoints(self, elem):\n e = elem\n if elem.find(\"generation\"):\n e = elem.find(\"generation\")\n k = Kpoints(\"Kpoints from vasprun.xml\")\n k.style = Kpoints.supported_modes.from_string(\n e.attrib[\"param\"] if \"param\" in e.attrib else \"Reciprocal\")\n for v in e.findall(\"v\"):\n name = v.attrib.get(\"name\")\n toks = v.text.split()\n if name == \"divisions\":\n k.kpts = [[int(i) for i in toks]]\n elif name == \"usershift\":\n k.kpts_shift = [float(i) for i in toks]\n elif name in {\"genvec1\", \"genvec2\", \"genvec3\", \"shift\"}:\n setattr(k, name, [float(i) for i in toks])\n for va in elem.findall(\"varray\"):\n name = va.attrib[\"name\"]\n if name == \"kpointlist\":\n actual_kpoints = _parse_varray(va)\n elif name == \"weights\":\n weights = [i[0] for i in _parse_varray(va)]\n elem.clear()\n if k.style == Kpoints.supported_modes.Reciprocal:\n k = Kpoints(comment=\"Kpoints from vasprun.xml\",\n style=Kpoints.supported_modes.Reciprocal,\n num_kpts=len(k.kpts),\n kpts=actual_kpoints, kpts_weights=weights)\n return k, actual_kpoints, weights\n\n def _parse_structure(self, elem):\n latt = _parse_varray(elem.find(\"crystal\").find(\"varray\"))\n pos = _parse_varray(elem.find(\"varray\"))\n struct = Structure(latt, self.atomic_symbols, pos)\n sdyn = elem.find(\"varray/[@name='selective']\")\n if sdyn:\n struct.add_site_property('selective_dynamics',\n _parse_varray(sdyn))\n return struct\n\n def _parse_diel(self, elem):\n imag = [[_vasprun_float(l) for l in r.text.split()]\n for r in elem.find(\"imag\").find(\"array\").find(\"set\").findall(\"r\")]\n real = [[_vasprun_float(l) for l in r.text.split()]\n for r in elem.find(\"real\").find(\"array\").find(\"set\").findall(\"r\")]\n elem.clear()\n return [e[0] for e in imag], \\\n [e[1:] for e in real], [e[1:] for e in imag]\n\n def _parse_optical_transition(self, elem):\n for va in elem.findall(\"varray\"):\n if va.attrib.get(\"name\") == \"opticaltransitions\":\n # opticaltransitions array contains oscillator strength and probability of transition\n oscillator_strength = np.array(_parse_varray(va))[0:, ]\n probability_transition = np.array(_parse_varray(va))[0:, 1]\n return oscillator_strength, probability_transition\n\n def _parse_chemical_shielding_calculation(self, elem):\n calculation = []\n istep = {}\n try:\n s = self._parse_structure(elem.find(\"structure\"))\n except AttributeError: # not all calculations have a structure\n s = None\n pass\n for va in elem.findall(\"varray\"):\n istep[va.attrib[\"name\"]] = _parse_varray(va)\n istep[\"structure\"] = s\n istep[\"electronic_steps\"] = []\n calculation.append(istep)\n for scstep in elem.findall(\"scstep\"):\n try:\n d = {i.attrib[\"name\"]: _vasprun_float(i.text)\n for i in scstep.find(\"energy\").findall(\"i\")}\n cur_ene = d['e_fr_energy']\n min_steps = 1 if len(calculation) >= 1 else self.parameters.get(\"NELMIN\", 5)\n if len(calculation[-1][\"electronic_steps\"]) <= min_steps:\n calculation[-1][\"electronic_steps\"].append(d)\n else:\n last_ene = calculation[-1][\"electronic_steps\"][-1][\"e_fr_energy\"]\n if abs(cur_ene - last_ene) < 1.0:\n calculation[-1][\"electronic_steps\"].append(d)\n else:\n calculation.append({\"electronic_steps\": [d]})\n except AttributeError: # not all calculations have an energy\n pass\n calculation[-1].update(calculation[-1][\"electronic_steps\"][-1])\n return calculation\n\n def _parse_calculation(self, elem):\n try:\n istep = {i.attrib[\"name\"]: float(i.text)\n for i in elem.find(\"energy\").findall(\"i\")}\n except AttributeError: # not all calculations have an energy\n istep = {}\n pass\n esteps = []\n for scstep in elem.findall(\"scstep\"):\n try:\n d = {i.attrib[\"name\"]: _vasprun_float(i.text)\n for i in scstep.find(\"energy\").findall(\"i\")}\n esteps.append(d)\n except AttributeError: # not all calculations have an energy\n pass\n try:\n s = self._parse_structure(elem.find(\"structure\"))\n except AttributeError: # not all calculations have a structure\n s = None\n pass\n for va in elem.findall(\"varray\"):\n istep[va.attrib[\"name\"]] = _parse_varray(va)\n istep[\"electronic_steps\"] = esteps\n istep[\"structure\"] = s\n elem.clear()\n return istep\n\n def _parse_dos(self, elem):\n efermi = float(elem.find(\"i\").text)\n energies = None\n tdensities = {}\n idensities = {}\n\n for s in elem.find(\"total\").find(\"array\").find(\"set\").findall(\"set\"):\n data = np.array(_parse_varray(s))\n energies = data[:, 0]\n spin = Spin.up if s.attrib[\"comment\"] == \"spin 1\" else Spin.down\n tdensities[spin] = data[:, 1]\n idensities[spin] = data[:, 2]\n\n pdoss = []\n partial = elem.find(\"partial\")\n if partial is not None:\n orbs = [ss.text for ss in partial.find(\"array\").findall(\"field\")]\n orbs.pop(0)\n lm = any([\"x\" in s for s in orbs])\n for s in partial.find(\"array\").find(\"set\").findall(\"set\"):\n pdos = defaultdict(dict)\n\n for ss in s.findall(\"set\"):\n spin = Spin.up if ss.attrib[\"comment\"] == \"spin 1\" else \\\n Spin.down\n data = np.array(_parse_varray(ss))\n nrow, ncol = data.shape\n for j in range(1, ncol):\n if lm:\n orb = Orbital(j - 1)\n else:\n orb = OrbitalType(j - 1)\n pdos[orb][spin] = data[:, j]\n pdoss.append(pdos)\n elem.clear()\n return Dos(efermi, energies, tdensities), Dos(efermi, energies, idensities), pdoss\n\n def _parse_eigen(self, elem):\n eigenvalues = defaultdict(list)\n for s in elem.find(\"array\").find(\"set\").findall(\"set\"):\n spin = Spin.up if s.attrib[\"comment\"] == \"spin 1\" else Spin.down\n for ss in s.findall(\"set\"):\n eigenvalues[spin].append(_parse_varray(ss))\n eigenvalues = {spin: np.array(v) for spin, v in eigenvalues.items()}\n elem.clear()\n return eigenvalues\n\n def _parse_projected_eigen(self, elem):\n root = elem.find(\"array\").find(\"set\")\n proj_eigen = defaultdict(list)\n for s in root.findall(\"set\"):\n spin = int(re.match(r\"spin(\\d+)\", s.attrib[\"comment\"]).group(1))\n\n # Force spin to be +1 or -1\n spin = Spin.up if spin == 1 else Spin.down\n for kpt, ss in enumerate(s.findall(\"set\")):\n dk = []\n for band, sss in enumerate(ss.findall(\"set\")):\n db = _parse_varray(sss)\n dk.append(db)\n proj_eigen[spin].append(dk)\n proj_eigen = {spin: np.array(v) for spin, v in proj_eigen.items()}\n elem.clear()\n return proj_eigen\n\n def _parse_dynmat(self, elem):\n hessian = []\n eigenvalues = []\n eigenvectors = []\n for v in elem.findall(\"v\"):\n if v.attrib[\"name\"] == \"eigenvalues\":\n eigenvalues = [float(i) for i in v.text.split()]\n for va in elem.findall(\"varray\"):\n if va.attrib[\"name\"] == \"hessian\":\n for v in va.findall(\"v\"):\n hessian.append([float(i) for i in v.text.split()])\n elif va.attrib[\"name\"] == \"eigenvectors\":\n for v in va.findall(\"v\"):\n eigenvectors.append([float(i) for i in v.text.split()])\n return hessian, eigenvalues, eigenvectors\n\n\nclass BSVasprun(Vasprun):\n \"\"\"\n A highly optimized version of Vasprun that parses only eigenvalues for\n bandstructures. All other properties like structures, parameters,\n etc. are ignored.\n \"\"\"\n\n def __init__(self, filename, parse_projected_eigen=False,\n parse_potcar_file=False, occu_tol=1e-8):\n \"\"\"\n Args:\n filename (str): Filename to parse\n parse_projected_eigen (bool): Whether to parse the projected\n eigenvalues. Defaults to False. Set to True to obtain projected\n eigenvalues. **Note that this can take an extreme amount of time\n and memory.** So use this wisely.\n parse_potcar_file (bool/str): Whether to parse the potcar file to read\n the potcar hashes for the potcar_spec attribute. Defaults to True,\n where no hashes will be determined and the potcar_spec dictionaries\n will read {\"symbol\": ElSymbol, \"hash\": None}. By Default, looks in\n the same directory as the vasprun.xml, with same extensions as\n Vasprun.xml. If a string is provided, looks at that filepath.\n occu_tol (float): Sets the minimum tol for the determination of the\n vbm and cbm. Usually the default of 1e-8 works well enough,\n but there may be pathological cases.\n \"\"\"\n self.filename = filename\n self.occu_tol = occu_tol\n\n with zopen(filename, \"rt\") as f:\n self.efermi = None\n parsed_header = False\n self.eigenvalues = None\n self.projected_eigenvalues = None\n for event, elem in ET.iterparse(f):\n tag = elem.tag\n if not parsed_header:\n if tag == \"generator\":\n self.generator = self._parse_params(elem)\n elif tag == \"incar\":\n self.incar = self._parse_params(elem)\n elif tag == \"kpoints\":\n self.kpoints, self.actual_kpoints, self.actual_kpoints_weights = self._parse_kpoints(elem)\n elif tag == \"parameters\":\n self.parameters = self._parse_params(elem)\n elif tag == \"atominfo\":\n self.atomic_symbols, self.potcar_symbols = self._parse_atominfo(elem)\n self.potcar_spec = [{\"titel\": p, \"hash\": None} for p in self.potcar_symbols]\n parsed_header = True\n elif tag == \"i\" and elem.attrib.get(\"name\") == \"efermi\":\n self.efermi = float(elem.text)\n elif tag == \"eigenvalues\":\n self.eigenvalues = self._parse_eigen(elem)\n elif parse_projected_eigen and tag == \"projected\":\n self.projected_eigenvalues = self._parse_projected_eigen(\n elem)\n elif tag == \"structure\" and elem.attrib.get(\"name\") == \\\n \"finalpos\":\n self.final_structure = self._parse_structure(elem)\n self.vasp_version = self.generator[\"version\"]\n if parse_potcar_file:\n self.update_potcar_spec(parse_potcar_file)\n\n def as_dict(self):\n \"\"\"\n Json-serializable dict representation.\n \"\"\"\n d = {\"vasp_version\": self.vasp_version,\n \"has_vasp_completed\": True,\n \"nsites\": len(self.final_structure)}\n comp = self.final_structure.composition\n d[\"unit_cell_formula\"] = comp.as_dict()\n d[\"reduced_cell_formula\"] = Composition(comp.reduced_formula).as_dict()\n d[\"pretty_formula\"] = comp.reduced_formula\n symbols = [s.split()[1] for s in self.potcar_symbols]\n symbols = [re.split(r\"_\", s)[0] for s in symbols]\n d[\"is_hubbard\"] = self.is_hubbard\n d[\"hubbards\"] = self.hubbards\n\n unique_symbols = sorted(list(set(self.atomic_symbols)))\n d[\"elements\"] = unique_symbols\n d[\"nelements\"] = len(unique_symbols)\n\n d[\"run_type\"] = self.run_type\n\n vin = {\"incar\": {k: v for k, v in self.incar.items()},\n \"crystal\": self.final_structure.as_dict(),\n \"kpoints\": self.kpoints.as_dict()}\n actual_kpts = [{\"abc\": list(self.actual_kpoints[i]),\n \"weight\": self.actual_kpoints_weights[i]}\n for i in range(len(self.actual_kpoints))]\n vin[\"kpoints\"][\"actual_points\"] = actual_kpts\n vin[\"potcar\"] = [s.split(\" \")[1] for s in self.potcar_symbols]\n vin[\"potcar_spec\"] = self.potcar_spec\n vin[\"potcar_type\"] = [s.split(\" \")[0] for s in self.potcar_symbols]\n vin[\"parameters\"] = {k: v for k, v in self.parameters.items()}\n vin[\"lattice_rec\"] = self.final_structure.lattice.reciprocal_lattice.as_dict()\n d[\"input\"] = vin\n\n vout = {\"crystal\": self.final_structure.as_dict(),\n \"efermi\": self.efermi}\n\n if self.eigenvalues:\n eigen = defaultdict(dict)\n for spin, values in self.eigenvalues.items():\n for i, v in enumerate(values):\n eigen[i][str(spin)] = v\n vout[\"eigenvalues\"] = eigen\n (gap, cbm, vbm, is_direct) = self.eigenvalue_band_properties\n vout.update(dict(bandgap=gap, cbm=cbm, vbm=vbm,\n is_gap_direct=is_direct))\n\n if self.projected_eigenvalues:\n peigen = []\n for i in range(len(eigen)):\n peigen.append({})\n for spin, v in self.projected_eigenvalues.items():\n for kpoint_index, vv in enumerate(v):\n if str(spin) not in peigen[kpoint_index]:\n peigen[kpoint_index][str(spin)] = vv\n vout['projected_eigenvalues'] = peigen\n\n d['output'] = vout\n return jsanitize(d, strict=True)\n\n\nclass Outcar:\n \"\"\"\n Parser for data in OUTCAR that is not available in Vasprun.xml\n\n Note, this class works a bit differently than most of the other\n VaspObjects, since the OUTCAR can be very different depending on which\n \"type of run\" performed.\n\n Creating the OUTCAR class with a filename reads \"regular parameters\" that\n are always present.\n\n .. attribute:: magnetization\n\n Magnetization on each ion as a tuple of dict, e.g.,\n ({\"d\": 0.0, \"p\": 0.003, \"s\": 0.002, \"tot\": 0.005}, ... )\n Note that this data is not always present. LORBIT must be set to some\n other value than the default.\n\n .. attribute:: chemical_shielding\n\n chemical shielding on each ion as a dictionary with core and valence contributions\n\n .. attribute:: unsym_cs_tensor\n\n Unsymmetrized chemical shielding tensor matrixes on each ion as a list.\n e.g.,\n [[[sigma11, sigma12, sigma13],\n [sigma21, sigma22, sigma23],\n [sigma31, sigma32, sigma33]],\n ...\n [[sigma11, sigma12, sigma13],\n [sigma21, sigma22, sigma23],\n [sigma31, sigma32, sigma33]]]\n\n .. attribute:: cs_g0_contribution\n\n G=0 contribution to chemical shielding. 2D rank 3 matrix\n\n .. attribute:: cs_core_contribution\n\n Core contribution to chemical shielding. dict. e.g.,\n {'Mg': -412.8, 'C': -200.5, 'O': -271.1}\n\n .. attribute:: efg\n\n Electric Field Gradient (EFG) tensor on each ion as a tuple of dict, e.g.,\n ({\"cq\": 0.1, \"eta\", 0.2, \"nuclear_quadrupole_moment\": 0.3},\n {\"cq\": 0.7, \"eta\", 0.8, \"nuclear_quadrupole_moment\": 0.9},\n ...)\n\n .. attribute:: charge\n\n Charge on each ion as a tuple of dict, e.g.,\n ({\"p\": 0.154, \"s\": 0.078, \"d\": 0.0, \"tot\": 0.232}, ...)\n Note that this data is not always present. LORBIT must be set to some\n other value than the default.\n\n .. attribute:: is_stopped\n\n True if OUTCAR is from a stopped run (using STOPCAR, see Vasp Manual).\n\n .. attribute:: run_stats\n\n Various useful run stats as a dict including \"System time (sec)\",\n \"Total CPU time used (sec)\", \"Elapsed time (sec)\",\n \"Maximum memory used (kb)\", \"Average memory used (kb)\",\n \"User time (sec)\".\n\n .. attribute:: elastic_tensor\n Total elastic moduli (Kbar) is given in a 6x6 array matrix.\n\n .. attribute:: drift\n Total drift for each step in eV/Atom\n\n .. attribute:: ngf\n Dimensions for the Augementation grid\n\n .. attribute: sampling_radii\n Size of the sampling radii in VASP for the test charges for\n the electrostatic potential at each atom. Total array size is the number\n of elements present in the calculation\n\n .. attribute: electrostatic_potential\n Average electrostatic potential at each atomic position in order\n of the atoms in POSCAR.\n\n ..attribute: final_energy_contribs\n Individual contributions to the total final energy as a dictionary.\n Include contirbutions from keys, e.g.:\n {'DENC': -505778.5184347, 'EATOM': 15561.06492564, 'EBANDS': -804.53201231,\n 'EENTRO': -0.08932659, 'EXHF': 0.0, 'Ediel_sol': 0.0,\n 'PAW double counting': 664.6726974100002, 'PSCENC': 742.48691646,\n 'TEWEN': 489742.86847338, 'XCENC': -169.64189814}\n\n One can then call a specific reader depending on the type of run being\n performed. These are currently: read_igpar(), read_lepsilon() and\n read_lcalcpol(), read_core_state_eign(), read_avg_core_pot().\n\n See the documentation of those methods for more documentation.\n\n Authors: Rickard Armiento, Shyue Ping Ong\n \"\"\"\n\n def __init__(self, filename):\n \"\"\"\n Args:\n filename (str): OUTCAR filename to parse.\n \"\"\"\n self.filename = filename\n self.is_stopped = False\n\n # data from end of OUTCAR\n charge = []\n mag_x = []\n mag_y = []\n mag_z = []\n header = []\n run_stats = {}\n total_mag = None\n nelect = None\n efermi = None\n total_energy = None\n\n time_patt = re.compile(r\"\\((sec|kb)\\)\")\n efermi_patt = re.compile(r\"E-fermi\\s*:\\s*(\\S+)\")\n nelect_patt = re.compile(r\"number of electron\\s+(\\S+)\\s+magnetization\")\n mag_patt = re.compile(r\"number of electron\\s+\\S+\\s+magnetization\\s+(\"\n r\"\\S+)\")\n toten_pattern = re.compile(r\"free energy TOTEN\\s+=\\s+([\\d\\-\\.]+)\")\n\n all_lines = []\n for line in reverse_readfile(self.filename):\n clean = line.strip()\n all_lines.append(clean)\n if clean.find(\"soft stop encountered! aborting job\") != -1:\n self.is_stopped = True\n else:\n if time_patt.search(line):\n tok = line.strip().split(\":\")\n run_stats[tok[0].strip()] = float(tok[1].strip())\n continue\n m = efermi_patt.search(clean)\n if m:\n try:\n # try-catch because VASP sometimes prints\n # 'E-fermi: ******** XC(G=0): -6.1327\n # alpha+bet : -1.8238'\n efermi = float(m.group(1))\n continue\n except ValueError:\n efermi = None\n continue\n m = nelect_patt.search(clean)\n if m:\n nelect = float(m.group(1))\n m = mag_patt.search(clean)\n if m:\n total_mag = float(m.group(1))\n if total_energy is None:\n m = toten_pattern.search(clean)\n if m:\n total_energy = float(m.group(1))\n if all([nelect, total_mag is not None, efermi is not None,\n run_stats]):\n break\n\n # For single atom systems, VASP doesn't print a total line, so\n # reverse parsing is very difficult\n read_charge = False\n read_mag_x = False\n read_mag_y = False # for SOC calculations only\n read_mag_z = False\n all_lines.reverse()\n for clean in all_lines:\n if read_charge or read_mag_x or read_mag_y or read_mag_z:\n if clean.startswith(\"# of ion\"):\n header = re.split(r\"\\s{2,}\", clean.strip())\n header.pop(0)\n else:\n m = re.match(r\"\\s*(\\d+)\\s+(([\\d\\.\\-]+)\\s+)+\", clean)\n if m:\n toks = [float(i)\n for i in re.findall(r\"[\\d\\.\\-]+\", clean)]\n toks.pop(0)\n if read_charge:\n charge.append(dict(zip(header, toks)))\n elif read_mag_x:\n mag_x.append(dict(zip(header, toks)))\n elif read_mag_y:\n mag_y.append(dict(zip(header, toks)))\n elif read_mag_z:\n mag_z.append(dict(zip(header, toks)))\n elif clean.startswith('tot'):\n read_charge = False\n read_mag_x = False\n read_mag_y = False\n read_mag_z = False\n if clean == \"total charge\":\n charge = []\n read_charge = True\n read_mag_x, read_mag_y, read_mag_z = False, False, False\n elif clean == \"magnetization (x)\":\n mag_x = []\n read_mag_x = True\n read_charge, read_mag_y, read_mag_z = False, False, False\n elif clean == \"magnetization (y)\":\n mag_y = []\n read_mag_y = True\n read_charge, read_mag_x, read_mag_z = False, False, False\n elif clean == \"magnetization (z)\":\n mag_z = []\n read_mag_z = True\n read_charge, read_mag_x, read_mag_y = False, False, False\n elif re.search(\"electrostatic\", clean):\n read_charge, read_mag_x, read_mag_y, read_mag_z = False, False, False, False\n\n # merge x, y and z components of magmoms if present (SOC calculation)\n if mag_y and mag_z:\n # TODO: detect spin axis\n mag = []\n for idx in range(len(mag_x)):\n mag.append({\n key: Magmom([mag_x[idx][key], mag_y[idx][key], mag_z[idx][key]])\n for key in mag_x[0].keys()\n })\n else:\n mag = mag_x\n\n # data from beginning of OUTCAR\n run_stats['cores'] = 0\n with zopen(filename, \"rt\") as f:\n for line in f:\n if \"running\" in line:\n run_stats['cores'] = line.split()[2]\n break\n\n self.run_stats = run_stats\n self.magnetization = tuple(mag)\n self.charge = tuple(charge)\n self.efermi = efermi\n self.nelect = nelect\n self.total_mag = total_mag\n self.final_energy = total_energy\n self.data = {}\n\n # Read \"total number of plane waves\", NPLWV:\n self.read_pattern(\n {\"nplwv\": r\"total plane-waves NPLWV =\\s+(\\*{6}|\\d+)\"},\n terminate_on_match=True\n )\n try:\n self.data[\"nplwv\"] = [[int(self.data[\"nplwv\"][0][0])]]\n except ValueError:\n self.data[\"nplwv\"] = [[None]]\n\n nplwvs_at_kpoints = [\n n for [n] in self.read_table_pattern(\n r\"\\n{3}-{104}\\n{3}\",\n r\".+plane waves:\\s+(\\*{6,}|\\d+)\",\n r\"maximum and minimum number of plane-waves\"\n )\n ]\n self.data[\"nplwvs_at_kpoints\"] = [None for n in nplwvs_at_kpoints]\n for (n, nplwv) in enumerate(nplwvs_at_kpoints):\n try:\n self.data[\"nplwvs_at_kpoints\"][n] = int(nplwv)\n except ValueError:\n pass\n\n # Read the drift:\n self.read_pattern({\n \"drift\": r\"total drift:\\s+([\\.\\-\\d]+)\\s+([\\.\\-\\d]+)\\s+([\\.\\-\\d]+)\"},\n terminate_on_match=False,\n postprocess=float)\n self.drift = self.data.get('drift', [])\n\n # Check if calculation is spin polarized\n self.spin = False\n self.read_pattern({'spin': 'ISPIN = 2'})\n if self.data.get('spin', []):\n self.spin = True\n\n # Check if calculation is noncollinear\n self.noncollinear = False\n self.read_pattern({'noncollinear': 'LNONCOLLINEAR = T'})\n if self.data.get('noncollinear', []):\n self.noncollinear = False\n\n # Check if the calculation type is DFPT\n self.dfpt = False\n self.read_pattern({'ibrion': r\"IBRION =\\s+([\\-\\d]+)\"},\n terminate_on_match=True,\n postprocess=int)\n if self.data.get(\"ibrion\", [[0]])[0][0] > 6:\n self.dfpt = True\n self.read_internal_strain_tensor()\n\n # Check to see if LEPSILON is true and read piezo data if so\n self.lepsilon = False\n self.read_pattern({'epsilon': 'LEPSILON= T'})\n if self.data.get('epsilon', []):\n self.lepsilon = True\n self.read_lepsilon()\n # only read ionic contribution if DFPT is turned on\n if self.dfpt:\n self.read_lepsilon_ionic()\n\n # Check to see if LCALCPOL is true and read polarization data if so\n self.lcalcpol = False\n self.read_pattern({'calcpol': 'LCALCPOL = T'})\n if self.data.get('calcpol', []):\n self.lcalcpol = True\n self.read_lcalcpol()\n self.read_pseudo_zval()\n\n # Read electrostatic potential\n self.read_pattern({\n 'electrostatic': r\"average \\(electrostatic\\) potential at core\"})\n if self.data.get('electrostatic', []):\n self.read_electrostatic_potential()\n\n self.nmr_cs = False\n self.read_pattern({\"nmr_cs\": r\"LCHIMAG = (T)\"})\n if self.data.get(\"nmr_cs\", None):\n self.nmr_cs = True\n self.read_chemical_shielding()\n self.read_cs_g0_contribution()\n self.read_cs_core_contribution()\n self.read_cs_raw_symmetrized_tensors()\n\n self.nmr_efg = False\n self.read_pattern({\"nmr_efg\": r\"NMR quadrupolar parameters\"})\n if self.data.get(\"nmr_efg\", None):\n self.nmr_efg = True\n self.read_nmr_efg()\n self.read_nmr_efg_tensor()\n\n self.has_onsite_density_matrices = False\n self.read_pattern({\"has_onsite_density_matrices\": r\"onsite density matrix\"},\n terminate_on_match=True)\n if \"has_onsite_density_matrices\" in self.data:\n self.has_onsite_density_matrices = True\n self.read_onsite_density_matrices()\n\n # Store the individual contributions to the final total energy\n final_energy_contribs = {}\n for k in [\"PSCENC\", \"TEWEN\", \"DENC\", \"EXHF\", \"XCENC\", \"PAW double counting\",\n \"EENTRO\", \"EBANDS\", \"EATOM\", \"Ediel_sol\"]:\n if k == \"PAW double counting\":\n self.read_pattern({k: r\"%s\\s+=\\s+([\\.\\-\\d]+)\\s+([\\.\\-\\d]+)\" % (k)})\n else:\n self.read_pattern({k: r\"%s\\s+=\\s+([\\d\\-\\.]+)\" % (k)})\n if not self.data[k]:\n continue\n final_energy_contribs[k] = sum([float(f) for f in self.data[k][-1]])\n self.final_energy_contribs = final_energy_contribs\n\n def read_pattern(self, patterns, reverse=False, terminate_on_match=False,\n postprocess=str):\n r\"\"\"\n General pattern reading. Uses monty's regrep method. Takes the same\n arguments.\n\n Args:\n patterns (dict): A dict of patterns, e.g.,\n {\"energy\": r\"energy\\\\(sigma->0\\\\)\\\\s+=\\\\s+([\\\\d\\\\-.]+)\"}.\n reverse (bool): Read files in reverse. Defaults to false. Useful for\n large files, esp OUTCARs, especially when used with\n terminate_on_match.\n terminate_on_match (bool): Whether to terminate when there is at\n least one match in each key in pattern.\n postprocess (callable): A post processing function to convert all\n matches. Defaults to str, i.e., no change.\n\n Renders accessible:\n Any attribute in patterns. For example,\n {\"energy\": r\"energy\\\\(sigma->0\\\\)\\\\s+=\\\\s+([\\\\d\\\\-.]+)\"} will set the\n value of self.data[\"energy\"] = [[-1234], [-3453], ...], to the\n results from regex and postprocess. Note that the returned values\n are lists of lists, because you can grep multiple items on one line.\n \"\"\"\n matches = regrep(self.filename, patterns, reverse=reverse,\n terminate_on_match=terminate_on_match,\n postprocess=postprocess)\n for k in patterns.keys():\n self.data[k] = [i[0] for i in matches.get(k, [])]\n\n def read_table_pattern(self, header_pattern, row_pattern, footer_pattern,\n postprocess=str, attribute_name=None,\n last_one_only=True):\n r\"\"\"\n Parse table-like data. A table composes of three parts: header,\n main body, footer. All the data matches \"row pattern\" in the main body\n will be returned.\n\n Args:\n header_pattern (str): The regular expression pattern matches the\n table header. This pattern should match all the text\n immediately before the main body of the table. For multiple\n sections table match the text until the section of\n interest. MULTILINE and DOTALL options are enforced, as a\n result, the \".\" meta-character will also match \"\\n\" in this\n section.\n row_pattern (str): The regular expression matches a single line in\n the table. Capture interested field using regular expression\n groups.\n footer_pattern (str): The regular expression matches the end of the\n table. E.g. a long dash line.\n postprocess (callable): A post processing function to convert all\n matches. Defaults to str, i.e., no change.\n attribute_name (str): Name of this table. If present the parsed data\n will be attached to \"data. e.g. self.data[\"efg\"] = [...]\n last_one_only (bool): All the tables will be parsed, if this option\n is set to True, only the last table will be returned. The\n enclosing list will be removed. i.e. Only a single table will\n be returned. Default to be True.\n\n Returns:\n List of tables. 1) A table is a list of rows. 2) A row if either a list of\n attribute values in case the the capturing group is defined without name in\n row_pattern, or a dict in case that named capturing groups are defined by\n row_pattern.\n \"\"\"\n with zopen(self.filename, 'rt') as f:\n text = f.read()\n table_pattern_text = header_pattern + r\"\\s*^(?P<table_body>(?:\\s+\" + row_pattern + r\")+)\\s+\" + footer_pattern\n table_pattern = re.compile(table_pattern_text, re.MULTILINE | re.DOTALL)\n rp = re.compile(row_pattern)\n tables = []\n for mt in table_pattern.finditer(text):\n table_body_text = mt.group(\"table_body\")\n table_contents = []\n for line in table_body_text.split(\"\\n\"):\n ml = rp.search(line)\n # skip empty lines\n if not ml:\n continue\n d = ml.groupdict()\n if len(d) > 0:\n processed_line = {k: postprocess(v) for k, v in d.items()}\n else:\n processed_line = [postprocess(v) for v in ml.groups()]\n table_contents.append(processed_line)\n tables.append(table_contents)\n if last_one_only:\n retained_data = tables[-1]\n else:\n retained_data = tables\n if attribute_name is not None:\n self.data[attribute_name] = retained_data\n return retained_data\n\n def read_electrostatic_potential(self):\n \"\"\"\n Parses the eletrostatic potential for the last ionic step\n \"\"\"\n pattern = {\"ngf\": r\"\\s+dimension x,y,z NGXF=\\s+([\\.\\-\\d]+)\\sNGYF=\\s+([\\.\\-\\d]+)\\sNGZF=\\s+([\\.\\-\\d]+)\"}\n self.read_pattern(pattern, postprocess=int)\n self.ngf = self.data.get(\"ngf\", [[]])[0]\n\n pattern = {\"radii\": r\"the test charge radii are((?:\\s+[\\.\\-\\d]+)+)\"}\n self.read_pattern(pattern, reverse=True, terminate_on_match=True, postprocess=str)\n self.sampling_radii = [float(f) for f in self.data[\"radii\"][0][0].split()]\n\n header_pattern = r\"\\(the norm of the test charge is\\s+[\\.\\-\\d]+\\)\"\n table_pattern = r\"((?:\\s+\\d+\\s*[\\.\\-\\d]+)+)\"\n footer_pattern = r\"\\s+E-fermi :\"\n\n pots = self.read_table_pattern(header_pattern, table_pattern, footer_pattern)\n pots = \"\".join(itertools.chain.from_iterable(pots))\n\n pots = re.findall(r\"\\s+\\d+\\s*([\\.\\-\\d]+)+\", pots)\n\n self.electrostatic_potential = [float(f) for f in pots]\n\n def read_freq_dielectric(self):\n \"\"\"\n Parses the frequency dependent dielectric function (obtained with\n LOPTICS). Frequencies (in eV) are in self.frequencies, and dielectric\n tensor function is given as self.dielectric_tensor_function.\n \"\"\"\n\n plasma_pattern = r\"plasma frequency squared.*\"\n dielectric_pattern = r\"frequency dependent\\s+IMAGINARY \" \\\n r\"DIELECTRIC FUNCTION \\(independent particle, \" \\\n r\"no local field effects\\)(\\sdensity-density)*$\"\n row_pattern = r\"\\s+\".join([r\"([\\.\\-\\d]+)\"] * 3)\n plasma_frequencies = collections.defaultdict(list)\n read_plasma = False\n read_dielectric = False\n energies = []\n data = {\"REAL\": [], \"IMAGINARY\": []}\n count = 0\n component = \"IMAGINARY\"\n with zopen(self.filename, \"rt\") as f:\n for l in f:\n l = l.strip()\n if re.match(plasma_pattern, l):\n read_plasma = \"intraband\" if \"intraband\" in l else \"interband\"\n elif re.match(dielectric_pattern, l):\n read_plasma = False\n read_dielectric = True\n row_pattern = r\"\\s+\".join([r\"([\\.\\-\\d]+)\"] * 7)\n\n if read_plasma and re.match(row_pattern, l):\n plasma_frequencies[read_plasma].append(\n [float(t) for t in l.strip().split()])\n elif read_dielectric:\n if re.match(row_pattern, l.strip()):\n toks = l.strip().split()\n if component == \"IMAGINARY\":\n energies.append(float(toks[0]))\n xx, yy, zz, xy, yz, xz = [float(t) for t in toks[1:]]\n matrix = [[xx, xy, xz], [xy, yy, yz], [xz, yz, zz]]\n data[component].append(matrix)\n elif re.match(r\"\\s*-+\\s*\", l):\n count += 1\n if count == 2:\n component = \"REAL\"\n elif count == 3:\n break\n\n self.plasma_frequencies = {k: np.array(v[:3])\n for k, v in plasma_frequencies.items()}\n self.dielectric_energies = np.array(energies)\n self.dielectric_tensor_function = np.array(data[\"REAL\"]) + 1j * np.array(data[\"IMAGINARY\"])\n\n @property # type: ignore\n @deprecated(message=\"frequencies has been renamed to dielectric_energies.\")\n def frequencies(self):\n \"\"\"\n Renamed to dielectric energies.\n \"\"\"\n return self.dielectric_energies\n\n def read_chemical_shielding(self):\n \"\"\"\n Parse the NMR chemical shieldings data. Only the second part \"absolute, valence and core\"\n will be parsed. And only the three right most field (ISO_SHIELDING, SPAN, SKEW) will be retrieved.\n\n Returns:\n List of chemical shieldings in the order of atoms from the OUTCAR. Maryland notation is adopted.\n \"\"\"\n header_pattern = r\"\\s+CSA tensor \\(J\\. Mason, Solid State Nucl\\. Magn\\. Reson\\. 2, \" \\\n r\"285 \\(1993\\)\\)\\s+\" \\\n r\"\\s+-{50,}\\s+\" \\\n r\"\\s+EXCLUDING G=0 CONTRIBUTION\\s+INCLUDING G=0 CONTRIBUTION\\s+\" \\\n r\"\\s+-{20,}\\s+-{20,}\\s+\" \\\n r\"\\s+ATOM\\s+ISO_SHIFT\\s+SPAN\\s+SKEW\\s+ISO_SHIFT\\s+SPAN\\s+SKEW\\s+\" \\\n r\"-{50,}\\s*$\"\n first_part_pattern = r\"\\s+\\(absolute, valence only\\)\\s+$\"\n swallon_valence_body_pattern = r\".+?\\(absolute, valence and core\\)\\s+$\"\n row_pattern = r\"\\d+(?:\\s+[-]?\\d+\\.\\d+){3}\\s+\" + r'\\s+'.join(\n [r\"([-]?\\d+\\.\\d+)\"] * 3)\n footer_pattern = r\"-{50,}\\s*$\"\n h1 = header_pattern + first_part_pattern\n cs_valence_only = self.read_table_pattern(\n h1, row_pattern, footer_pattern, postprocess=float,\n last_one_only=True)\n h2 = header_pattern + swallon_valence_body_pattern\n cs_valence_and_core = self.read_table_pattern(\n h2, row_pattern, footer_pattern, postprocess=float,\n last_one_only=True)\n all_cs = {}\n for name, cs_table in [[\"valence_only\", cs_valence_only],\n [\"valence_and_core\", cs_valence_and_core]]:\n all_cs[name] = cs_table\n self.data[\"chemical_shielding\"] = all_cs\n\n def read_cs_g0_contribution(self):\n \"\"\"\n Parse the G0 contribution of NMR chemical shielding.\n\n Returns:\n G0 contribution matrix as list of list.\n \"\"\"\n header_pattern = r'^\\s+G\\=0 CONTRIBUTION TO CHEMICAL SHIFT \\(field along BDIR\\)\\s+$\\n' \\\n r'^\\s+-{50,}$\\n' \\\n r'^\\s+BDIR\\s+X\\s+Y\\s+Z\\s*$\\n' \\\n r'^\\s+-{50,}\\s*$\\n'\n row_pattern = r'(?:\\d+)\\s+' + r'\\s+'.join([r'([-]?\\d+\\.\\d+)'] * 3)\n footer_pattern = r'\\s+-{50,}\\s*$'\n self.read_table_pattern(header_pattern, row_pattern, footer_pattern, postprocess=float,\n last_one_only=True, attribute_name=\"cs_g0_contribution\")\n\n def read_cs_core_contribution(self):\n \"\"\"\n Parse the core contribution of NMR chemical shielding.\n\n Returns:\n G0 contribution matrix as list of list.\n \"\"\"\n header_pattern = r'^\\s+Core NMR properties\\s*$\\n' \\\n r'\\n' \\\n r'^\\s+typ\\s+El\\s+Core shift \\(ppm\\)\\s*$\\n' \\\n r'^\\s+-{20,}$\\n'\n row_pattern = r'\\d+\\s+(?P<element>[A-Z][a-z]?\\w?)\\s+(?P<shift>[-]?\\d+\\.\\d+)'\n footer_pattern = r'\\s+-{20,}\\s*$'\n self.read_table_pattern(header_pattern, row_pattern, footer_pattern, postprocess=str,\n last_one_only=True, attribute_name=\"cs_core_contribution\")\n core_contrib = {d['element']: float(d['shift'])\n for d in self.data[\"cs_core_contribution\"]}\n self.data[\"cs_core_contribution\"] = core_contrib\n\n def read_cs_raw_symmetrized_tensors(self):\n \"\"\"\n Parse the matrix form of NMR tensor before corrected to table.\n\n Returns:\n nsymmetrized tensors list in the order of atoms.\n \"\"\"\n header_pattern = r\"\\s+-{50,}\\s+\" \\\n r\"\\s+Absolute Chemical Shift tensors\\s+\" \\\n r\"\\s+-{50,}$\"\n first_part_pattern = r\"\\s+UNSYMMETRIZED TENSORS\\s+$\"\n row_pattern = r\"\\s+\".join([r\"([-]?\\d+\\.\\d+)\"] * 3)\n unsym_footer_pattern = r\"^\\s+SYMMETRIZED TENSORS\\s+$\"\n\n with zopen(self.filename, 'rt') as f:\n text = f.read()\n unsym_table_pattern_text = header_pattern + first_part_pattern + r\"(?P<table_body>.+)\" + unsym_footer_pattern\n table_pattern = re.compile(unsym_table_pattern_text, re.MULTILINE | re.DOTALL)\n rp = re.compile(row_pattern)\n m = table_pattern.search(text)\n if m:\n table_text = m.group(\"table_body\")\n micro_header_pattern = r\"ion\\s+\\d+\"\n micro_table_pattern_text = micro_header_pattern + r\"\\s*^(?P<table_body>(?:\\s*\" + row_pattern + r\")+)\\s+\"\n micro_table_pattern = re.compile(micro_table_pattern_text,\n re.MULTILINE | re.DOTALL)\n unsym_tensors = []\n for mt in micro_table_pattern.finditer(table_text):\n table_body_text = mt.group(\"table_body\")\n tensor_matrix = []\n for line in table_body_text.rstrip().split(\"\\n\"):\n ml = rp.search(line)\n processed_line = [float(v) for v in ml.groups()]\n tensor_matrix.append(processed_line)\n unsym_tensors.append(tensor_matrix)\n self.data[\"unsym_cs_tensor\"] = unsym_tensors\n else:\n raise ValueError(\"NMR UNSYMMETRIZED TENSORS is not found\")\n\n def read_nmr_efg_tensor(self):\n \"\"\"\n Parses the NMR Electric Field Gradient Raw Tensors\n\n Returns:\n A list of Electric Field Gradient Tensors in the order of Atoms from OUTCAR\n \"\"\"\n\n header_pattern = r'Electric field gradients \\(V/A\\^2\\)\\n' \\\n r'-*\\n' \\\n r' ion\\s+V_xx\\s+V_yy\\s+V_zz\\s+V_xy\\s+V_xz\\s+V_yz\\n' \\\n r'-*\\n'\n\n row_pattern = r'\\d+\\s+([-\\d\\.]+)\\s+([-\\d\\.]+)\\s+([-\\d\\.]+)\\s+([-\\d\\.]+)\\s+([-\\d\\.]+)\\s+([-\\d\\.]+)'\n footer_pattern = r'-*\\n'\n\n data = self.read_table_pattern(header_pattern, row_pattern, footer_pattern, postprocess=float)\n tensors = [make_symmetric_matrix_from_upper_tri(d) for d in data]\n self.data[\"unsym_efg_tensor\"] = tensors\n return tensors\n\n def read_nmr_efg(self):\n \"\"\"\n Parse the NMR Electric Field Gradient interpretted values.\n\n Returns:\n Electric Field Gradient tensors as a list of dict in the order of atoms from OUTCAR.\n Each dict key/value pair corresponds to a component of the tensors.\n \"\"\"\n header_pattern = r'^\\s+NMR quadrupolar parameters\\s+$\\n' \\\n r'^\\s+Cq : quadrupolar parameter\\s+Cq=e[*]Q[*]V_zz/h$\\n' \\\n r'^\\s+eta: asymmetry parameters\\s+\\(V_yy - V_xx\\)/ V_zz$\\n' \\\n r'^\\s+Q : nuclear electric quadrupole moment in mb \\(millibarn\\)$\\n' \\\n r'^-{50,}$\\n' \\\n r'^\\s+ion\\s+Cq\\(MHz\\)\\s+eta\\s+Q \\(mb\\)\\s+$\\n' \\\n r'^-{50,}\\s*$\\n'\n row_pattern = r'\\d+\\s+(?P<cq>[-]?\\d+\\.\\d+)\\s+(?P<eta>[-]?\\d+\\.\\d+)\\s+' \\\n r'(?P<nuclear_quadrupole_moment>[-]?\\d+\\.\\d+)'\n footer_pattern = r'-{50,}\\s*$'\n self.read_table_pattern(header_pattern, row_pattern, footer_pattern, postprocess=float,\n last_one_only=True, attribute_name=\"efg\")\n\n def read_elastic_tensor(self):\n \"\"\"\n Parse the elastic tensor data.\n\n Returns:\n 6x6 array corresponding to the elastic tensor from the OUTCAR.\n \"\"\"\n header_pattern = r\"TOTAL ELASTIC MODULI \\(kBar\\)\\s+\" \\\n r\"Direction\\s+([X-Z][X-Z]\\s+)+\" \\\n r\"\\-+\"\n row_pattern = r\"[X-Z][X-Z]\\s+\" + r\"\\s+\".join([r\"(\\-*[\\.\\d]+)\"] * 6)\n footer_pattern = r\"\\-+\"\n et_table = self.read_table_pattern(header_pattern, row_pattern,\n footer_pattern, postprocess=float)\n self.data[\"elastic_tensor\"] = et_table\n\n def read_piezo_tensor(self):\n \"\"\"\n Parse the piezo tensor data\n \"\"\"\n header_pattern = r\"PIEZOELECTRIC TENSOR for field in x, y, \" \\\n r\"z\\s+\\(C/m\\^2\\)\\s+([X-Z][X-Z]\\s+)+\\-+\"\n row_pattern = r\"[x-z]\\s+\" + r\"\\s+\".join([r\"(\\-*[\\.\\d]+)\"] * 6)\n footer_pattern = r\"BORN EFFECTIVE\"\n pt_table = self.read_table_pattern(header_pattern, row_pattern,\n footer_pattern, postprocess=float)\n self.data[\"piezo_tensor\"] = pt_table\n\n def read_onsite_density_matrices(self):\n \"\"\"\n Parse the onsite density matrices, returns list with index corresponding\n to atom index in Structure.\n \"\"\"\n\n # matrix size will vary depending on if d or f orbitals are present\n # therefore regex assumes f, but filter out None values if d\n\n header_pattern = r\"spin component 1\\n\"\n row_pattern = r'[^\\S\\r\\n]*(?:([\\d.-]+))' + r'(?:[^\\S\\r\\n]*(-?[\\d.]+)[^\\S\\r\\n]*)?' * 6 + r'.*?'\n footer_pattern = r\"\\nspin component 2\"\n spin1_component = self.read_table_pattern(header_pattern, row_pattern,\n footer_pattern, postprocess=lambda x: float(x) if x else None,\n last_one_only=False)\n\n # filter out None values\n spin1_component = [[[e for e in row if e is not None] for row in matrix] for matrix in spin1_component]\n\n # and repeat for Spin.down\n\n header_pattern = r\"spin component 2\\n\"\n row_pattern = r'[^\\S\\r\\n]*(?:([\\d.-]+))' + r'(?:[^\\S\\r\\n]*(-?[\\d.]+)[^\\S\\r\\n]*)?' * 6 + r'.*?'\n footer_pattern = r\"\\n occupancies and eigenvectors\"\n spin2_component = self.read_table_pattern(header_pattern, row_pattern,\n footer_pattern, postprocess=lambda x: float(x) if x else None,\n last_one_only=False)\n\n spin2_component = [[[e for e in row if e is not None] for row in matrix] for matrix in spin2_component]\n\n self.data[\"onsite_density_matrices\"] = [\n {\n Spin.up: spin1_component[idx],\n Spin.down: spin2_component[idx]\n }\n for idx in range(len(spin1_component))\n ]\n\n def read_corrections(self, reverse=True, terminate_on_match=True):\n \"\"\"\n Reads the dipol qudropol corrections into the\n Outcar.data[\"dipol_quadrupol_correction\"].\n\n :param reverse: Whether to start from end of OUTCAR.\n :param terminate_on_match: Whether to terminate once match is found.\n \"\"\"\n patterns = {\n \"dipol_quadrupol_correction\": r\"dipol\\+quadrupol energy \"\n r\"correction\\s+([\\d\\-\\.]+)\"\n }\n self.read_pattern(patterns, reverse=reverse,\n terminate_on_match=terminate_on_match,\n postprocess=float)\n self.data[\"dipol_quadrupol_correction\"] = self.data[\"dipol_quadrupol_correction\"][0][0]\n\n def read_neb(self, reverse=True, terminate_on_match=True):\n \"\"\"\n Reads NEB data. This only works with OUTCARs from both normal\n VASP NEB calculations or from the CI NEB method implemented by\n Henkelman et al.\n\n Args:\n reverse (bool): Read files in reverse. Defaults to false. Useful for\n large files, esp OUTCARs, especially when used with\n terminate_on_match. Defaults to True here since we usually\n want only the final value.\n terminate_on_match (bool): Whether to terminate when there is at\n least one match in each key in pattern. Defaults to True here\n since we usually want only the final value.\n\n Renders accessible:\n tangent_force - Final tangent force.\n energy - Final energy.\n These can be accessed under Outcar.data[key]\n \"\"\"\n patterns = {\n \"energy\": r\"energy\\(sigma->0\\)\\s+=\\s+([\\d\\-\\.]+)\",\n \"tangent_force\": r\"(NEB: projections on to tangent \\(spring, REAL\\)\\s+\\S+|tangential force \\(eV/A\\))\\s+\"\n r\"([\\d\\-\\.]+)\"\n }\n self.read_pattern(patterns, reverse=reverse,\n terminate_on_match=terminate_on_match,\n postprocess=str)\n self.data[\"energy\"] = float(self.data[\"energy\"][0][0])\n if self.data.get(\"tangent_force\"):\n self.data[\"tangent_force\"] = float(\n self.data[\"tangent_force\"][0][1])\n\n def read_igpar(self):\n \"\"\"\n Renders accessible:\n er_ev = e<r>_ev (dictionary with Spin.up/Spin.down as keys)\n er_bp = e<r>_bp (dictionary with Spin.up/Spin.down as keys)\n er_ev_tot = spin up + spin down summed\n er_bp_tot = spin up + spin down summed\n p_elc = spin up + spin down summed\n p_ion = spin up + spin down summed\n\n (See VASP section \"LBERRY, IGPAR, NPPSTR, DIPOL tags\" for info on\n what these are).\n \"\"\"\n\n # variables to be filled\n self.er_ev = {} # will be dict (Spin.up/down) of array(3*float)\n self.er_bp = {} # will be dics (Spin.up/down) of array(3*float)\n self.er_ev_tot = None # will be array(3*float)\n self.er_bp_tot = None # will be array(3*float)\n self.p_elec = None\n self.p_ion = None\n try:\n search = []\n\n # Nonspin cases\n def er_ev(results, match):\n results.er_ev[Spin.up] = np.array(map(float,\n match.groups()[1:4])) / 2\n results.er_ev[Spin.down] = results.er_ev[Spin.up]\n results.context = 2\n\n search.append([r\"^ *e<r>_ev=\\( *([-0-9.Ee+]*) *([-0-9.Ee+]*) \"\n r\"*([-0-9.Ee+]*) *\\)\",\n None, er_ev])\n\n def er_bp(results, match):\n results.er_bp[Spin.up] = np.array([float(match.group(i))\n for i in range(1, 4)]) / 2\n results.er_bp[Spin.down] = results.er_bp[Spin.up]\n\n search.append([r\"^ *e<r>_bp=\\( *([-0-9.Ee+]*) *([-0-9.Ee+]*) \"\n r\"*([-0-9.Ee+]*) *\\)\",\n lambda results, line: results.context == 2, er_bp])\n\n # Spin cases\n def er_ev_up(results, match):\n results.er_ev[Spin.up] = np.array([float(match.group(i))\n for i in range(1, 4)])\n results.context = Spin.up\n\n search.append([r\"^.*Spin component 1 *e<r>_ev=\\( *([-0-9.Ee+]*) \"\n r\"*([-0-9.Ee+]*) *([-0-9.Ee+]*) *\\)\",\n None, er_ev_up])\n\n def er_bp_up(results, match):\n results.er_bp[Spin.up] = np.array([float(match.group(1)),\n float(match.group(2)),\n float(match.group(3))])\n\n search.append([r\"^ *e<r>_bp=\\( *([-0-9.Ee+]*) *([-0-9.Ee+]*) \"\n r\"*([-0-9.Ee+]*) *\\)\",\n lambda results, line: results.context == Spin.up, er_bp_up])\n\n def er_ev_dn(results, match):\n results.er_ev[Spin.down] = np.array([float(match.group(1)),\n float(match.group(2)),\n float(match.group(3))])\n results.context = Spin.down\n\n search.append([r\"^.*Spin component 2 *e<r>_ev=\\( *([-0-9.Ee+]*) \"\n r\"*([-0-9.Ee+]*) *([-0-9.Ee+]*) *\\)\",\n None, er_ev_dn])\n\n def er_bp_dn(results, match):\n results.er_bp[Spin.down] = np.array([float(match.group(i))\n for i in range(1, 4)])\n\n search.append([r\"^ *e<r>_bp=\\( *([-0-9.Ee+]*) *([-0-9.Ee+]*) \"\n r\"*([-0-9.Ee+]*) *\\)\",\n lambda results, line: results.context == Spin.down, er_bp_dn])\n\n # Always present spin/non-spin\n def p_elc(results, match):\n results.p_elc = np.array([float(match.group(i)) for i in range(1, 4)])\n\n search.append([r\"^.*Total electronic dipole moment: \"\n r\"*p\\[elc\\]=\\( *([-0-9.Ee+]*) *([-0-9.Ee+]*) \"\n r\"*([-0-9.Ee+]*) *\\)\", None, p_elc])\n\n def p_ion(results, match):\n results.p_ion = np.array([float(match.group(i)) for i in range(1, 4)])\n\n search.append([r\"^.*ionic dipole moment: \"\n r\"*p\\[ion\\]=\\( *([-0-9.Ee+]*) *([-0-9.Ee+]*) \"\n r\"*([-0-9.Ee+]*) *\\)\", None, p_ion])\n\n self.context = None\n self.er_ev = {Spin.up: None, Spin.down: None}\n self.er_bp = {Spin.up: None, Spin.down: None}\n\n micro_pyawk(self.filename, search, self)\n\n if self.er_ev[Spin.up] is not None and \\\n self.er_ev[Spin.down] is not None:\n self.er_ev_tot = self.er_ev[Spin.up] + self.er_ev[Spin.down]\n\n if self.er_bp[Spin.up] is not None and \\\n self.er_bp[Spin.down] is not None:\n self.er_bp_tot = self.er_bp[Spin.up] + self.er_bp[Spin.down]\n\n except Exception:\n self.er_ev_tot = None\n self.er_bp_tot = None\n raise Exception(\"IGPAR OUTCAR could not be parsed.\")\n\n def read_internal_strain_tensor(self):\n \"\"\"\n Reads the internal strain tensor and populates self.internal_strain_tensor with an array of voigt notation\n tensors for each site.\n \"\"\"\n search = []\n\n def internal_strain_start(results, match):\n results.internal_strain_ion = int(match.group(1)) - 1\n results.internal_strain_tensor.append(np.zeros((3, 6)))\n\n search.append([r\"INTERNAL STRAIN TENSOR FOR ION\\s+(\\d+)\\s+for displacements in x,y,z \\(eV/Angst\\):\",\n None, internal_strain_start])\n\n def internal_strain_data(results, match):\n if match.group(1).lower() == \"x\":\n index = 0\n elif match.group(1).lower() == \"y\":\n index = 1\n elif match.group(1).lower() == \"z\":\n index = 2\n else:\n raise Exception(\n \"Couldn't parse row index from symbol for internal strain tensor: {}\".format(match.group(1)))\n results.internal_strain_tensor[results.internal_strain_ion][index] = np.array([float(match.group(i))\n for i in range(2, 8)])\n if index == 2:\n results.internal_strain_ion = None\n\n search.append([r\"^\\s+([x,y,z])\\s+\" + r\"([-]?\\d+\\.\\d+)\\s+\" * 6,\n lambda results, line: results.internal_strain_ion is not None,\n internal_strain_data])\n\n self.internal_strain_ion = None\n self.internal_strain_tensor = []\n micro_pyawk(self.filename, search, self)\n\n def read_lepsilon(self):\n \"\"\"\n Reads an LEPSILON run.\n\n # TODO: Document the actual variables.\n \"\"\"\n try:\n search = []\n\n def dielectric_section_start(results, match):\n results.dielectric_index = -1\n\n search.append([r\"MACROSCOPIC STATIC DIELECTRIC TENSOR \\(\", None,\n dielectric_section_start])\n\n def dielectric_section_start2(results, match):\n results.dielectric_index = 0\n\n search.append(\n [r\"-------------------------------------\",\n lambda results, line: results.dielectric_index == -1,\n dielectric_section_start2])\n\n def dielectric_data(results, match):\n results.dielectric_tensor[results.dielectric_index, :] = \\\n np.array([float(match.group(i)) for i in range(1, 4)])\n results.dielectric_index += 1\n\n search.append(\n [r\"^ *([-0-9.Ee+]+) +([-0-9.Ee+]+) +([-0-9.Ee+]+) *$\",\n lambda results, line: results.dielectric_index >= 0\n if results.dielectric_index is not None\n else None,\n dielectric_data])\n\n def dielectric_section_stop(results, match):\n results.dielectric_index = None\n\n search.append(\n [r\"-------------------------------------\",\n lambda results, line: results.dielectric_index >= 1\n if results.dielectric_index is not None\n else None,\n dielectric_section_stop])\n\n self.dielectric_index = None\n self.dielectric_tensor = np.zeros((3, 3))\n\n def piezo_section_start(results, match):\n results.piezo_index = 0\n\n search.append([r\"PIEZOELECTRIC TENSOR for field in x, y, z \"\n r\"\\(C/m\\^2\\)\",\n None, piezo_section_start])\n\n def piezo_data(results, match):\n results.piezo_tensor[results.piezo_index, :] = \\\n np.array([float(match.group(i)) for i in range(1, 7)])\n results.piezo_index += 1\n\n search.append(\n [r\"^ *[xyz] +([-0-9.Ee+]+) +([-0-9.Ee+]+)\" +\n r\" +([-0-9.Ee+]+) *([-0-9.Ee+]+) +([-0-9.Ee+]+)\" +\n r\" +([-0-9.Ee+]+)*$\",\n lambda results, line: results.piezo_index >= 0\n if results.piezo_index is not None\n else None,\n piezo_data])\n\n def piezo_section_stop(results, match):\n results.piezo_index = None\n\n search.append(\n [r\"-------------------------------------\",\n lambda results, line: results.piezo_index >= 1\n if results.piezo_index is not None\n else None,\n piezo_section_stop])\n\n self.piezo_index = None\n self.piezo_tensor = np.zeros((3, 6))\n\n def born_section_start(results, match):\n results.born_ion = -1\n\n search.append([r\"BORN EFFECTIVE CHARGES \",\n None, born_section_start])\n\n def born_ion(results, match):\n results.born_ion = int(match.group(1)) - 1\n results.born.append(np.zeros((3, 3)))\n\n search.append([r\"ion +([0-9]+)\", lambda results, line: results.born_ion is not None, born_ion])\n\n def born_data(results, match):\n results.born[results.born_ion][int(match.group(1)) - 1, :] = \\\n np.array([float(match.group(i)) for i in range(2, 5)])\n\n search.append(\n [r\"^ *([1-3]+) +([-0-9.Ee+]+) +([-0-9.Ee+]+) +([-0-9.Ee+]+)$\",\n lambda results, line: results.born_ion >= 0\n if results.born_ion is not None\n else results.born_ion,\n born_data])\n\n def born_section_stop(results, match):\n results.born_ion = None\n\n search.append(\n [r\"-------------------------------------\",\n lambda results, line: results.born_ion >= 1\n if results.born_ion is not None\n else results.born_ion,\n born_section_stop])\n\n self.born_ion = None\n self.born = []\n\n micro_pyawk(self.filename, search, self)\n\n self.born = np.array(self.born)\n\n self.dielectric_tensor = self.dielectric_tensor.tolist()\n self.piezo_tensor = self.piezo_tensor.tolist()\n\n except Exception:\n raise Exception(\"LEPSILON OUTCAR could not be parsed.\")\n\n def read_lepsilon_ionic(self):\n \"\"\"\n Reads an LEPSILON run, the ionic component.\n\n # TODO: Document the actual variables.\n \"\"\"\n try:\n search = []\n\n def dielectric_section_start(results, match):\n results.dielectric_ionic_index = -1\n\n search.append([r\"MACROSCOPIC STATIC DIELECTRIC TENSOR IONIC\", None,\n dielectric_section_start])\n\n def dielectric_section_start2(results, match):\n results.dielectric_ionic_index = 0\n\n search.append(\n [r\"-------------------------------------\",\n lambda results, line: results.dielectric_ionic_index == -1\n if results.dielectric_ionic_index is not None\n else results.dielectric_ionic_index,\n dielectric_section_start2])\n\n def dielectric_data(results, match):\n results.dielectric_ionic_tensor[results.dielectric_ionic_index, :] = \\\n np.array([float(match.group(i)) for i in range(1, 4)])\n results.dielectric_ionic_index += 1\n\n search.append(\n [r\"^ *([-0-9.Ee+]+) +([-0-9.Ee+]+) +([-0-9.Ee+]+) *$\",\n lambda results, line: results.dielectric_ionic_index >= 0\n if results.dielectric_ionic_index is not None\n else results.dielectric_ionic_index,\n dielectric_data])\n\n def dielectric_section_stop(results, match):\n results.dielectric_ionic_index = None\n\n search.append(\n [r\"-------------------------------------\",\n lambda results, line: results.dielectric_ionic_index >= 1\n if results.dielectric_ionic_index is not None\n else results.dielectric_ionic_index,\n dielectric_section_stop])\n\n self.dielectric_ionic_index = None\n self.dielectric_ionic_tensor = np.zeros((3, 3))\n\n def piezo_section_start(results, match):\n results.piezo_ionic_index = 0\n\n search.append([r\"PIEZOELECTRIC TENSOR IONIC CONTR for field in \"\n r\"x, y, z \",\n None, piezo_section_start])\n\n def piezo_data(results, match):\n results.piezo_ionic_tensor[results.piezo_ionic_index, :] = \\\n np.array([float(match.group(i)) for i in range(1, 7)])\n results.piezo_ionic_index += 1\n\n search.append(\n [r\"^ *[xyz] +([-0-9.Ee+]+) +([-0-9.Ee+]+)\" +\n r\" +([-0-9.Ee+]+) *([-0-9.Ee+]+) +([-0-9.Ee+]+)\" +\n r\" +([-0-9.Ee+]+)*$\",\n lambda results, line: results.piezo_ionic_index >= 0\n if results.piezo_ionic_index is not None\n else results.piezo_ionic_index,\n piezo_data])\n\n def piezo_section_stop(results, match):\n results.piezo_ionic_index = None\n\n search.append(\n [\"-------------------------------------\",\n lambda results, line: results.piezo_ionic_index >= 1\n if results.piezo_ionic_index is not None\n else results.piezo_ionic_index,\n piezo_section_stop])\n\n self.piezo_ionic_index = None\n self.piezo_ionic_tensor = np.zeros((3, 6))\n\n micro_pyawk(self.filename, search, self)\n\n self.dielectric_ionic_tensor = self.dielectric_ionic_tensor.tolist()\n self.piezo_ionic_tensor = self.piezo_ionic_tensor.tolist()\n\n except Exception:\n raise Exception(\n \"ionic part of LEPSILON OUTCAR could not be parsed.\")\n\n def read_lcalcpol(self):\n \"\"\"\n Reads the lcalpol.\n\n # TODO: Document the actual variables.\n \"\"\"\n self.p_elec = None\n self.p_sp1 = None\n self.p_sp2 = None\n self.p_ion = None\n try:\n search = []\n\n # Always present spin/non-spin\n def p_elec(results, match):\n results.p_elec = np.array([float(match.group(1)),\n float(match.group(2)),\n float(match.group(3))])\n\n search.append([r\"^.*Total electronic dipole moment: \"\n r\"*p\\[elc\\]=\\( *([-0-9.Ee+]*) *([-0-9.Ee+]*) \"\n r\"*([-0-9.Ee+]*) *\\)\",\n None, p_elec])\n\n # If spin-polarized (and not noncollinear)\n # save spin-polarized electronic values\n if self.spin and not self.noncollinear:\n def p_sp1(results, match):\n results.p_sp1 = np.array([float(match.group(1)),\n float(match.group(2)),\n float(match.group(3))])\n\n search.append([r\"^.*p\\[sp1\\]=\\( *([-0-9.Ee+]*) *([-0-9.Ee+]*) \"\n r\"*([-0-9.Ee+]*) *\\)\",\n None, p_sp1])\n\n def p_sp2(results, match):\n results.p_sp2 = np.array([float(match.group(1)),\n float(match.group(2)),\n float(match.group(3))])\n\n search.append([r\"^.*p\\[sp2\\]=\\( *([-0-9.Ee+]*) *([-0-9.Ee+]*) \"\n r\"*([-0-9.Ee+]*) *\\)\",\n None, p_sp2])\n\n def p_ion(results, match):\n results.p_ion = np.array([float(match.group(1)),\n float(match.group(2)),\n float(match.group(3))])\n\n search.append([r\"^.*Ionic dipole moment: *p\\[ion\\]=\"\n r\"\\( *([-0-9.Ee+]*)\"\n r\" *([-0-9.Ee+]*) *([-0-9.Ee+]*) *\\)\",\n None, p_ion])\n\n micro_pyawk(self.filename, search, self)\n\n except Exception:\n raise Exception(\"LCALCPOL OUTCAR could not be parsed.\")\n\n def read_pseudo_zval(self):\n \"\"\"\n Create pseudopotential ZVAL dictionary.\n \"\"\"\n try:\n def atom_symbols(results, match):\n element_symbol = match.group(1)\n if not hasattr(results, 'atom_symbols'):\n results.atom_symbols = []\n results.atom_symbols.append(element_symbol.strip())\n\n def zvals(results, match):\n zvals = match.group(1)\n results.zvals = map(float, re.findall(r'-?\\d+\\.\\d*', zvals))\n\n search = []\n search.append([r'(?<=VRHFIN =)(.*)(?=:)', None, atom_symbols])\n search.append([r'^\\s+ZVAL.*=(.*)', None, zvals])\n\n micro_pyawk(self.filename, search, self)\n\n zval_dict = {}\n for x, y in zip(self.atom_symbols, self.zvals):\n zval_dict.update({x: y})\n self.zval_dict = zval_dict\n\n # Clean-up\n del (self.atom_symbols)\n del (self.zvals)\n except Exception:\n raise Exception(\"ZVAL dict could not be parsed.\")\n\n def read_core_state_eigen(self):\n \"\"\"\n Read the core state eigenenergies at each ionic step.\n\n Returns:\n A list of dict over the atom such as [{\"AO\":[core state eig]}].\n The core state eigenenergie list for each AO is over all ionic\n step.\n\n Example:\n The core state eigenenergie of the 2s AO of the 6th atom of the\n structure at the last ionic step is [5][\"2s\"][-1]\n \"\"\"\n\n with zopen(self.filename, \"rt\") as foutcar:\n line = foutcar.readline()\n while line != \"\":\n line = foutcar.readline()\n if \"NIONS =\" in line:\n natom = int(line.split(\"NIONS =\")[1])\n cl = [defaultdict(list) for i in range(natom)]\n if \"the core state eigen\" in line:\n iat = -1\n while line != \"\":\n line = foutcar.readline()\n # don't know number of lines to parse without knowing\n # specific species, so stop parsing when we reach\n # \"E-fermi\" instead\n if \"E-fermi\" in line:\n break\n data = line.split()\n # data will contain odd number of elements if it is\n # the start of a new entry, or even number of elements\n # if it continues the previous entry\n if len(data) % 2 == 1:\n iat += 1 # started parsing a new ion\n data = data[1:] # remove element with ion number\n for i in range(0, len(data), 2):\n cl[iat][data[i]].append(float(data[i + 1]))\n return cl\n\n def read_avg_core_poten(self):\n \"\"\"\n Read the core potential at each ionic step.\n\n Returns:\n A list for each ionic step containing a list of the average core\n potentials for each atom: [[avg core pot]].\n\n Example:\n The average core potential of the 2nd atom of the structure at the\n last ionic step is: [-1][1]\n \"\"\"\n\n def pairwise(iterable):\n \"\"\"s -> (s0,s1), (s1,s2), (s2, s3), ...\"\"\"\n a = iter(iterable)\n return zip(a, a)\n\n with zopen(self.filename, \"rt\") as foutcar:\n line = foutcar.readline()\n aps = []\n while line != \"\":\n line = foutcar.readline()\n if \"the norm of the test charge is\" in line:\n ap = []\n while line != \"\":\n line = foutcar.readline()\n # don't know number of lines to parse without knowing\n # specific species, so stop parsing when we reach\n # \"E-fermi\" instead\n if \"E-fermi\" in line:\n aps.append(ap)\n break\n data = line.split()\n # the average core potentials of up to 5 elements are\n # given per line\n for i, pot in pairwise(data):\n ap.append(float(pot))\n return aps\n\n def as_dict(self):\n \"\"\"\n :return: MSONAble dict.\n \"\"\"\n d = {\"@module\": self.__class__.__module__,\n \"@class\": self.__class__.__name__, \"efermi\": self.efermi,\n \"run_stats\": self.run_stats, \"magnetization\": self.magnetization,\n \"charge\": self.charge, \"total_magnetization\": self.total_mag,\n \"nelect\": self.nelect, \"is_stopped\": self.is_stopped,\n \"drift\": self.drift, \"ngf\": self.ngf,\n \"sampling_radii\": self.sampling_radii,\n \"electrostatic_potential\": self.electrostatic_potential}\n\n if self.lepsilon:\n d.update({\"piezo_tensor\": self.piezo_tensor,\n \"dielectric_tensor\": self.dielectric_tensor,\n \"born\": self.born})\n\n if self.dfpt:\n d.update({\"internal_strain_tensor\": self.internal_strain_tensor})\n\n if self.dfpt and self.lepsilon:\n d.update({\"piezo_ionic_tensor\": self.piezo_ionic_tensor,\n \"dielectric_ionic_tensor\": self.dielectric_ionic_tensor})\n\n if self.lcalcpol:\n d.update({'p_elec': self.p_elec,\n 'p_ion': self.p_ion})\n if self.spin and not self.noncollinear:\n d.update({'p_sp1': self.p_sp1,\n 'p_sp2': self.p_sp2})\n d.update({'zval_dict': self.zval_dict})\n\n if self.nmr_cs:\n d.update({\"nmr_cs\": {\"valence and core\": self.data[\"chemical_shielding\"][\"valence_and_core\"],\n \"valence_only\": self.data[\"chemical_shielding\"][\"valence_only\"],\n \"g0\": self.data[\"cs_g0_contribution\"],\n \"core\": self.data[\"cs_core_contribution\"],\n \"raw\": self.data[\"unsym_cs_tensor\"]}})\n\n if self.nmr_efg:\n d.update({\"nmr_efg\": {\"raw\": self.data[\"unsym_efg_tensor\"],\n \"parameters\": self.data[\"efg\"]}})\n\n if self.has_onsite_density_matrices:\n # cast Spin to str for consistency with electronic_structure\n # TODO: improve handling of Enum (de)serialization in monty\n onsite_density_matrices = [{str(k): v for k, v in d.items()}\n for d in self.data[\"onsite_density_matrices\"]]\n d.update({\"onsite_density_matrices\": onsite_density_matrices})\n\n return d\n\n def read_fermi_contact_shift(self):\n \"\"\"\n output example:\n Fermi contact (isotropic) hyperfine coupling parameter (MHz)\n -------------------------------------------------------------\n ion A_pw A_1PS A_1AE A_1c A_tot\n -------------------------------------------------------------\n 1 -0.002 -0.002 -0.051 0.000 -0.052\n 2 -0.002 -0.002 -0.051 0.000 -0.052\n 3 0.056 0.056 0.321 -0.048 0.321\n -------------------------------------------------------------\n , which corresponds to\n [[-0.002, -0.002, -0.051, 0.0, -0.052],\n [-0.002, -0.002, -0.051, 0.0, -0.052],\n [0.056, 0.056, 0.321, -0.048, 0.321]] from 'fch' data\n \"\"\"\n\n # Fermi contact (isotropic) hyperfine coupling parameter (MHz)\n header_pattern1 = r\"\\s*Fermi contact \\(isotropic\\) hyperfine coupling parameter \\(MHz\\)\\s+\" \\\n r\"\\s*\\-+\" \\\n r\"\\s*ion\\s+A_pw\\s+A_1PS\\s+A_1AE\\s+A_1c\\s+A_tot\\s+\" \\\n r\"\\s*\\-+\"\n row_pattern1 = r'(?:\\d+)\\s+' + r'\\s+'.join([r'([-]?\\d+\\.\\d+)'] * 5)\n footer_pattern = r\"\\-+\"\n fch_table = self.read_table_pattern(header_pattern1, row_pattern1,\n footer_pattern, postprocess=float,\n last_one_only=True)\n\n # Dipolar hyperfine coupling parameters (MHz)\n header_pattern2 = r\"\\s*Dipolar hyperfine coupling parameters \\(MHz\\)\\s+\" \\\n r\"\\s*\\-+\" \\\n r\"\\s*ion\\s+A_xx\\s+A_yy\\s+A_zz\\s+A_xy\\s+A_xz\\s+A_yz\\s+\" \\\n r\"\\s*\\-+\"\n row_pattern2 = r'(?:\\d+)\\s+' + r'\\s+'.join([r'([-]?\\d+\\.\\d+)'] * 6)\n dh_table = self.read_table_pattern(header_pattern2, row_pattern2,\n footer_pattern, postprocess=float,\n last_one_only=True)\n\n # Total hyperfine coupling parameters after diagonalization (MHz)\n header_pattern3 = r\"\\s*Total hyperfine coupling parameters after diagonalization \\(MHz\\)\\s+\" \\\n r\"\\s*\\(convention: \\|A_zz\\| > \\|A_xx\\| > \\|A_yy\\|\\)\\s+\" \\\n r\"\\s*\\-+\" \\\n r\"\\s*ion\\s+A_xx\\s+A_yy\\s+A_zz\\s+asymmetry \\(A_yy - A_xx\\)/ A_zz\\s+\" \\\n r\"\\s*\\-+\"\n row_pattern3 = r'(?:\\d+)\\s+' + r'\\s+'.join([r'([-]?\\d+\\.\\d+)'] * 4)\n th_table = self.read_table_pattern(header_pattern3, row_pattern3,\n footer_pattern, postprocess=float,\n last_one_only=True)\n\n fc_shift_table = {'fch': fch_table, 'dh': dh_table, 'th': th_table}\n\n self.data[\"fermi_contact_shift\"] = fc_shift_table\n\n\nclass VolumetricData(MSONable):\n \"\"\"\n Simple volumetric object for reading LOCPOT and CHGCAR type files.\n\n .. attribute:: structure\n\n Structure associated with the Volumetric Data object\n\n ..attribute:: is_spin_polarized\n\n True if run is spin polarized\n\n ..attribute:: dim\n\n Tuple of dimensions of volumetric grid in each direction (nx, ny, nz).\n\n ..attribute:: data\n\n Actual data as a dict of {string: np.array}. The string are \"total\"\n and \"diff\", in accordance to the output format of vasp LOCPOT and\n CHGCAR files where the total spin density is written first, followed\n by the difference spin density.\n\n .. attribute:: ngridpts\n\n Total number of grid points in volumetric data.\n \"\"\"\n\n def __init__(self, structure, data, distance_matrix=None, data_aug=None):\n \"\"\"\n Typically, this constructor is not used directly and the static\n from_file constructor is used. This constructor is designed to allow\n summation and other operations between VolumetricData objects.\n\n Args:\n structure: Structure associated with the volumetric data\n data: Actual volumetric data.\n data_aug: Any extra information associated with volumetric data\n (typically augmentation charges)\n distance_matrix: A pre-computed distance matrix if available.\n Useful so pass distance_matrices between sums,\n shortcircuiting an otherwise expensive operation.\n \"\"\"\n self.structure = structure\n self.is_spin_polarized = len(data) >= 2\n self.is_soc = len(data) >= 4\n self.dim = data[\"total\"].shape\n self.data = data\n self.data_aug = data_aug if data_aug else {}\n self.ngridpts = self.dim[0] * self.dim[1] * self.dim[2]\n # lazy init the spin data since this is not always needed.\n self._spin_data = {}\n self._distance_matrix = {} if not distance_matrix else distance_matrix\n\n @property\n def spin_data(self):\n \"\"\"\n The data decomposed into actual spin data as {spin: data}.\n Essentially, this provides the actual Spin.up and Spin.down data\n instead of the total and diff. Note that by definition, a\n non-spin-polarized run would have Spin.up data == Spin.down data.\n \"\"\"\n if not self._spin_data:\n spin_data = dict()\n spin_data[Spin.up] = 0.5 * (self.data[\"total\"] +\n self.data.get(\"diff\", 0))\n spin_data[Spin.down] = 0.5 * (self.data[\"total\"] -\n self.data.get(\"diff\", 0))\n self._spin_data = spin_data\n return self._spin_data\n\n def get_axis_grid(self, ind):\n \"\"\"\n Returns the grid for a particular axis.\n\n Args:\n ind (int): Axis index.\n \"\"\"\n ng = self.dim\n num_pts = ng[ind]\n lengths = self.structure.lattice.abc\n return [i / num_pts * lengths[ind] for i in range(num_pts)]\n\n def __add__(self, other):\n return self.linear_add(other, 1.0)\n\n def __sub__(self, other):\n return self.linear_add(other, -1.0)\n\n def copy(self):\n \"\"\"\n :return: Copy of Volumetric object\n \"\"\"\n return VolumetricData(\n self.structure,\n {k: v.copy() for k, v in self.data.items()},\n distance_matrix=self._distance_matrix,\n data_aug=self.data_aug\n )\n\n def linear_add(self, other, scale_factor=1.0):\n \"\"\"\n Method to do a linear sum of volumetric objects. Used by + and -\n operators as well. Returns a VolumetricData object containing the\n linear sum.\n\n Args:\n other (VolumetricData): Another VolumetricData object\n scale_factor (float): Factor to scale the other data by.\n\n Returns:\n VolumetricData corresponding to self + scale_factor * other.\n \"\"\"\n if self.structure != other.structure:\n warnings.warn(\"Structures are different. Make sure you know what \"\n \"you are doing...\")\n if self.data.keys() != other.data.keys():\n raise ValueError(\"Data have different keys! Maybe one is spin-\"\n \"polarized and the other is not?\")\n\n # To add checks\n data = {}\n for k in self.data.keys():\n data[k] = self.data[k] + scale_factor * other.data[k]\n return VolumetricData(self.structure, data, self._distance_matrix)\n\n @staticmethod\n def parse_file(filename):\n \"\"\"\n Convenience method to parse a generic volumetric data file in the vasp\n like format. Used by subclasses for parsing file.\n\n Args:\n filename (str): Path of file to parse\n\n Returns:\n (poscar, data)\n \"\"\"\n poscar_read = False\n poscar_string = []\n dataset = []\n all_dataset = []\n # for holding any strings in input that are not Poscar\n # or VolumetricData (typically augmentation charges)\n all_dataset_aug = {}\n dim = None\n dimline = None\n read_dataset = False\n ngrid_pts = 0\n data_count = 0\n poscar = None\n with zopen(filename, \"rt\") as f:\n for line in f:\n original_line = line\n line = line.strip()\n if read_dataset:\n toks = line.split()\n for tok in toks:\n if data_count < ngrid_pts:\n # This complicated procedure is necessary because\n # vasp outputs x as the fastest index, followed by y\n # then z.\n x = data_count % dim[0]\n y = int(math.floor(data_count / dim[0])) % dim[1]\n z = int(math.floor(data_count / dim[0] / dim[1]))\n dataset[x, y, z] = float(tok)\n data_count += 1\n if data_count >= ngrid_pts:\n read_dataset = False\n data_count = 0\n all_dataset.append(dataset)\n elif not poscar_read:\n if line != \"\" or len(poscar_string) == 0:\n poscar_string.append(line)\n elif line == \"\":\n poscar = Poscar.from_string(\"\\n\".join(poscar_string))\n poscar_read = True\n elif not dim:\n dim = [int(i) for i in line.split()]\n ngrid_pts = dim[0] * dim[1] * dim[2]\n dimline = line\n read_dataset = True\n dataset = np.zeros(dim)\n elif line == dimline:\n # when line == dimline, expect volumetric data to follow\n # so set read_dataset to True\n read_dataset = True\n dataset = np.zeros(dim)\n else:\n # store any extra lines that were not part of the\n # volumetric data so we know which set of data the extra\n # lines are associated with\n key = len(all_dataset) - 1\n if key not in all_dataset_aug:\n all_dataset_aug[key] = []\n all_dataset_aug[key].append(original_line)\n if len(all_dataset) == 4:\n\n data = {\"total\": all_dataset[0], \"diff_x\": all_dataset[1],\n \"diff_y\": all_dataset[2], \"diff_z\": all_dataset[3]}\n data_aug = {\"total\": all_dataset_aug.get(0, None),\n \"diff_x\": all_dataset_aug.get(1, None),\n \"diff_y\": all_dataset_aug.get(2, None),\n \"diff_z\": all_dataset_aug.get(3, None)}\n\n # construct a \"diff\" dict for scalar-like magnetization density,\n # referenced to an arbitrary direction (using same method as\n # pymatgen.electronic_structure.core.Magmom, see\n # Magmom documentation for justification for this)\n # TODO: re-examine this, and also similar behavior in\n # Magmom - @mkhorton\n # TODO: does CHGCAR change with different SAXIS?\n diff_xyz = np.array([data[\"diff_x\"], data[\"diff_y\"],\n data[\"diff_z\"]])\n diff_xyz = diff_xyz.reshape((3, dim[0] * dim[1] * dim[2]))\n ref_direction = np.array([1.01, 1.02, 1.03])\n ref_sign = np.sign(np.dot(ref_direction, diff_xyz))\n diff = np.multiply(np.linalg.norm(diff_xyz, axis=0), ref_sign)\n data[\"diff\"] = diff.reshape((dim[0], dim[1], dim[2]))\n\n elif len(all_dataset) == 2:\n data = {\"total\": all_dataset[0], \"diff\": all_dataset[1]}\n data_aug = {\"total\": all_dataset_aug.get(0, None),\n \"diff\": all_dataset_aug.get(1, None)}\n else:\n data = {\"total\": all_dataset[0]}\n data_aug = {\"total\": all_dataset_aug.get(0, None)}\n return poscar, data, data_aug\n\n def write_file(self, file_name, vasp4_compatible=False):\n \"\"\"\n Write the VolumetricData object to a vasp compatible file.\n\n Args:\n file_name (str): Path to a file\n vasp4_compatible (bool): True if the format is vasp4 compatible\n \"\"\"\n\n def _print_fortran_float(f):\n \"\"\"\n Fortran codes print floats with a leading zero in scientific\n notation. When writing CHGCAR files, we adopt this convention\n to ensure written CHGCAR files are byte-to-byte identical to\n their input files as far as possible.\n :param f: float\n :return: str\n \"\"\"\n s = \"{:.10E}\".format(f)\n if f >= 0:\n return \"0.\" + s[0] + s[2:12] + 'E' + \"{:+03}\".format(int(s[13:]) + 1)\n else:\n return \"-.\" + s[1] + s[3:13] + 'E' + \"{:+03}\".format(int(s[14:]) + 1)\n\n with zopen(file_name, \"wt\") as f:\n p = Poscar(self.structure)\n\n # use original name if it's been set (e.g. from Chgcar)\n comment = getattr(self, 'name', p.comment)\n\n lines = comment + \"\\n\"\n lines += \" 1.00000000000000\\n\"\n latt = self.structure.lattice.matrix\n lines += \" %12.6f%12.6f%12.6f\\n\" % tuple(latt[0, :])\n lines += \" %12.6f%12.6f%12.6f\\n\" % tuple(latt[1, :])\n lines += \" %12.6f%12.6f%12.6f\\n\" % tuple(latt[2, :])\n if not vasp4_compatible:\n lines += \"\".join([\"%5s\" % s for s in p.site_symbols]) + \"\\n\"\n lines += \"\".join([\"%6d\" % x for x in p.natoms]) + \"\\n\"\n lines += \"Direct\\n\"\n for site in self.structure:\n lines += \"%10.6f%10.6f%10.6f\\n\" % tuple(site.frac_coords)\n lines += \" \\n\"\n f.write(lines)\n a = self.dim\n\n def write_spin(data_type):\n lines = []\n count = 0\n f.write(\" {} {} {}\\n\".format(a[0], a[1], a[2]))\n for (k, j, i) in itertools.product(list(range(a[2])),\n list(range(a[1])),\n list(range(a[0]))):\n lines.append(_print_fortran_float(self.data[data_type][i, j, k]))\n count += 1\n if count % 5 == 0:\n f.write(\" \" + \"\".join(lines) + \"\\n\")\n lines = []\n else:\n lines.append(\" \")\n if count % 5 != 0:\n f.write(\" \" + \"\".join(lines) + \" \\n\")\n f.write(\"\".join(self.data_aug.get(data_type, [])))\n\n write_spin(\"total\")\n if self.is_spin_polarized and self.is_soc:\n write_spin(\"diff_x\")\n write_spin(\"diff_y\")\n write_spin(\"diff_z\")\n elif self.is_spin_polarized:\n write_spin(\"diff\")\n\n def get_integrated_diff(self, ind, radius, nbins=1):\n \"\"\"\n Get integrated difference of atom index ind up to radius. This can be\n an extremely computationally intensive process, depending on how many\n grid points are in the VolumetricData.\n\n Args:\n ind (int): Index of atom.\n radius (float): Radius of integration.\n nbins (int): Number of bins. Defaults to 1. This allows one to\n obtain the charge integration up to a list of the cumulative\n charge integration values for radii for [radius/nbins,\n 2 * radius/nbins, ....].\n\n Returns:\n Differential integrated charge as a np array of [[radius, value],\n ...]. Format is for ease of plotting. E.g., plt.plot(data[:,0],\n data[:,1])\n \"\"\"\n # For non-spin-polarized runs, this is zero by definition.\n if not self.is_spin_polarized:\n radii = [radius / nbins * (i + 1) for i in range(nbins)]\n data = np.zeros((nbins, 2))\n data[:, 0] = radii\n return data\n\n struct = self.structure\n a = self.dim\n if ind not in self._distance_matrix or \\\n self._distance_matrix[ind][\"max_radius\"] < radius:\n coords = []\n for (x, y, z) in itertools.product(*[list(range(i)) for i in a]):\n coords.append([x / a[0], y / a[1], z / a[2]])\n sites_dist = struct.lattice.get_points_in_sphere(\n coords, struct[ind].coords, radius)\n self._distance_matrix[ind] = {\"max_radius\": radius,\n \"data\": np.array(sites_dist)}\n\n data = self._distance_matrix[ind][\"data\"]\n\n # Use boolean indexing to find all charges within the desired distance.\n inds = data[:, 1] <= radius\n dists = data[inds, 1]\n data_inds = np.rint(np.mod(list(data[inds, 0]), 1) *\n np.tile(a, (len(dists), 1))).astype(int)\n vals = [self.data[\"diff\"][x, y, z] for x, y, z in data_inds]\n\n hist, edges = np.histogram(dists, bins=nbins,\n range=[0, radius],\n weights=vals)\n data = np.zeros((nbins, 2))\n data[:, 0] = edges[1:]\n data[:, 1] = [sum(hist[0:i + 1]) / self.ngridpts\n for i in range(nbins)]\n return data\n\n def get_average_along_axis(self, ind):\n \"\"\"\n Get the averaged total of the volumetric data a certain axis direction.\n For example, useful for visualizing Hartree Potentials from a LOCPOT\n file.\n\n Args:\n ind (int): Index of axis.\n\n Returns:\n Average total along axis\n \"\"\"\n m = self.data[\"total\"]\n ng = self.dim\n if ind == 0:\n total = np.sum(np.sum(m, axis=1), 1)\n elif ind == 1:\n total = np.sum(np.sum(m, axis=0), 1)\n else:\n total = np.sum(np.sum(m, axis=0), 0)\n return total / ng[(ind + 1) % 3] / ng[(ind + 2) % 3]\n\n def to_hdf5(self, filename):\n \"\"\"\n Writes the VolumetricData to a HDF5 format, which is a highly optimized\n format for reading storing large data. The mapping of the VolumetricData\n to this file format is as follows:\n\n VolumetricData.data -> f[\"vdata\"]\n VolumetricData.structure ->\n f[\"Z\"]: Sequence of atomic numbers\n f[\"fcoords\"]: Fractional coords\n f[\"lattice\"]: Lattice in the pymatgen.core.lattice.Lattice matrix\n format\n f.attrs[\"structure_json\"]: String of json representation\n\n Args:\n filename (str): Filename to output to.\n \"\"\"\n import h5py\n with h5py.File(filename, \"w\") as f:\n ds = f.create_dataset(\"lattice\", (3, 3), dtype='float')\n ds[...] = self.structure.lattice.matrix\n ds = f.create_dataset(\"Z\", (len(self.structure.species),),\n dtype=\"i\")\n ds[...] = np.array([sp.Z for sp in self.structure.species])\n ds = f.create_dataset(\"fcoords\", self.structure.frac_coords.shape,\n dtype='float')\n ds[...] = self.structure.frac_coords\n dt = h5py.special_dtype(vlen=str)\n ds = f.create_dataset(\"species\", (len(self.structure.species),),\n dtype=dt)\n ds[...] = [str(sp) for sp in self.structure.species]\n grp = f.create_group(\"vdata\")\n for k, v in self.data.items():\n ds = grp.create_dataset(k, self.data[k].shape, dtype='float')\n ds[...] = self.data[k]\n f.attrs[\"name\"] = self.name\n f.attrs[\"structure_json\"] = json.dumps(self.structure.as_dict())\n\n @classmethod\n def from_hdf5(cls, filename, **kwargs):\n \"\"\"\n Reads VolumetricData from HDF5 file.\n\n :param filename: Filename\n :return: VolumetricData\n \"\"\"\n import h5py\n with h5py.File(filename, \"r\") as f:\n data = {k: np.array(v) for k, v in f[\"vdata\"].items()}\n data_aug = None\n if 'vdata_aug' in f:\n data_aug = {k: np.array(v) for k, v in f[\"vdata_aug\"].items()}\n structure = Structure.from_dict(json.loads(f.attrs[\"structure_json\"]))\n return cls(structure, data=data, data_aug=data_aug, **kwargs)\n\n\nclass Locpot(VolumetricData):\n \"\"\"\n Simple object for reading a LOCPOT file.\n \"\"\"\n\n def __init__(self, poscar, data):\n \"\"\"\n Args:\n poscar (Poscar): Poscar object containing structure.\n data: Actual data.\n \"\"\"\n super().__init__(poscar.structure, data)\n self.name = poscar.comment\n\n @classmethod\n def from_file(cls, filename, **kwargs):\n \"\"\"\n Reads a LOCPOT file.\n\n :param filename: Filename\n :return: Locpot\n \"\"\"\n (poscar, data, data_aug) = VolumetricData.parse_file(filename)\n return cls(poscar, data, **kwargs)\n\n\nclass Chgcar(VolumetricData):\n \"\"\"\n Simple object for reading a CHGCAR file.\n \"\"\"\n\n def __init__(self, poscar, data, data_aug=None):\n \"\"\"\n Args:\n poscar (Poscar): Poscar object containing structure.\n data: Actual data.\n data_aug: Augmentation charge data\n \"\"\"\n # allow for poscar or structure files to be passed\n if isinstance(poscar, Poscar):\n tmp_struct = poscar.structure\n self.poscar = poscar\n self.name = poscar.comment\n elif isinstance(poscar, Structure):\n tmp_struct = poscar\n self.poscar = Poscar(poscar)\n self.name = None\n\n super().__init__(tmp_struct, data, data_aug=data_aug)\n self._distance_matrix = {}\n\n @staticmethod\n def from_file(filename):\n \"\"\"\n Reads a CHGCAR file.\n\n :param filename: Filename\n :return: Chgcar\n \"\"\"\n (poscar, data, data_aug) = VolumetricData.parse_file(filename)\n return Chgcar(poscar, data, data_aug=data_aug)\n\n @property\n def net_magnetization(self):\n \"\"\"\n :return: Net magnetization from Chgcar\n \"\"\"\n if self.is_spin_polarized:\n return np.sum(self.data['diff'])\n else:\n return None\n\n\nclass Elfcar(VolumetricData):\n \"\"\"\n Read an ELFCAR file which contains the Electron Localization Function (ELF)\n as calculated by VASP.\n\n For ELF, \"total\" key refers to Spin.up, and \"diff\" refers to Spin.down.\n\n This also contains information on the kinetic energy density.\n \"\"\"\n\n def __init__(self, poscar, data):\n \"\"\"\n Args:\n poscar (Poscar): Poscar object containing structure.\n data: Actual data.\n \"\"\"\n super().__init__(poscar.structure, data)\n # TODO: modify VolumetricData so that the correct keys can be used.\n # for ELF, instead of \"total\" and \"diff\" keys we have\n # \"Spin.up\" and \"Spin.down\" keys\n # I believe this is correct, but there's not much documentation -mkhorton\n self.data = data\n\n @classmethod\n def from_file(cls, filename):\n \"\"\"\n Reads a ELFCAR file.\n\n :param filename: Filename\n :return: Elfcar\n \"\"\"\n (poscar, data, data_aug) = VolumetricData.parse_file(filename)\n return cls(poscar, data)\n\n def get_alpha(self):\n \"\"\"\n Get the parameter alpha where ELF = 1/(1+alpha^2).\n \"\"\"\n alpha_data = {}\n for k, v in self.data.items():\n alpha = 1 / v\n alpha = alpha - 1\n alpha = np.sqrt(alpha)\n alpha_data[k] = alpha\n return VolumetricData(self.structure, alpha_data)\n\n\nclass Procar:\n \"\"\"\n Object for reading a PROCAR file.\n\n\n .. attribute:: data\n\n The PROCAR data of the form below. It should VASP uses 1-based indexing,\n but all indices are converted to 0-based here.::\n\n {\n spin: nd.array accessed with (k-point index, band index,\n ion index, orbital index)\n }\n\n .. attribute:: weights\n\n The weights associated with each k-point as an nd.array of lenght\n nkpoints.\n\n ..attribute:: phase_factors\n\n Phase factors, where present (e.g. LORBIT = 12). A dict of the form:\n {\n spin: complex nd.array accessed with (k-point index, band index,\n ion index, orbital index)\n }\n\n ..attribute:: nbands\n\n Number of bands\n\n ..attribute:: nkpoints\n\n Number of k-points\n\n ..attribute:: nions\n\n Number of ions\n \"\"\"\n\n def __init__(self, filename):\n \"\"\"\n Args:\n filename: Name of file containing PROCAR.\n \"\"\"\n headers = None\n\n with zopen(filename, \"rt\") as f:\n preambleexpr = re.compile(\n r\"# of k-points:\\s*(\\d+)\\s+# of bands:\\s*(\\d+)\\s+# of \"\n r\"ions:\\s*(\\d+)\")\n kpointexpr = re.compile(r\"^k-point\\s+(\\d+).*weight = ([0-9\\.]+)\")\n bandexpr = re.compile(r\"^band\\s+(\\d+)\")\n ionexpr = re.compile(r\"^ion.*\")\n expr = re.compile(r\"^([0-9]+)\\s+\")\n current_kpoint = 0\n current_band = 0\n done = False\n spin = Spin.down\n weights = None\n\n for l in f:\n l = l.strip()\n if bandexpr.match(l):\n m = bandexpr.match(l)\n current_band = int(m.group(1)) - 1\n done = False\n elif kpointexpr.match(l):\n m = kpointexpr.match(l)\n current_kpoint = int(m.group(1)) - 1\n weights[current_kpoint] = float(m.group(2))\n if current_kpoint == 0:\n spin = Spin.up if spin == Spin.down else Spin.down\n done = False\n elif headers is None and ionexpr.match(l):\n headers = l.split()\n headers.pop(0)\n headers.pop(-1)\n\n def f():\n return np.zeros((nkpoints, nbands, nions, len(headers)))\n\n data = defaultdict(f)\n\n def f2():\n return np.full((nkpoints, nbands, nions, len(headers)),\n np.NaN, dtype=np.complex128)\n\n phase_factors = defaultdict(f2)\n elif expr.match(l):\n toks = l.split()\n index = int(toks.pop(0)) - 1\n num_data = np.array([float(t) for t in toks[:len(headers)]])\n if not done:\n data[spin][current_kpoint, current_band, index, :] = num_data\n else:\n if len(toks) > len(headers):\n # new format of PROCAR (vasp 5.4.4)\n num_data = np.array([float(t)\n for t in toks[:2 * len(headers)]])\n for orb in range(len(headers)):\n phase_factors[spin][current_kpoint, current_band,\n index, orb] = complex(num_data[2 * orb], num_data[2 * orb + 1])\n else:\n # old format of PROCAR (vasp 5.4.1 and before)\n if np.isnan(phase_factors[spin][current_kpoint, current_band, index, 0]):\n phase_factors[spin][current_kpoint, current_band, index, :] = num_data\n else:\n phase_factors[spin][current_kpoint, current_band, index, :] += 1j * num_data\n elif l.startswith(\"tot\"):\n done = True\n elif preambleexpr.match(l):\n m = preambleexpr.match(l)\n nkpoints = int(m.group(1))\n nbands = int(m.group(2))\n nions = int(m.group(3))\n weights = np.zeros(nkpoints)\n\n self.nkpoints = nkpoints\n self.nbands = nbands\n self.nions = nions\n self.weights = weights\n self.orbitals = headers\n self.data = data\n self.phase_factors = phase_factors\n\n def get_projection_on_elements(self, structure):\n \"\"\"\n Method returning a dictionary of projections on elements.\n\n Args:\n structure (Structure): Input structure.\n\n Returns:\n a dictionary in the {Spin.up:[k index][b index][{Element:values}]]\n \"\"\"\n dico = {}\n for spin in self.data.keys():\n dico[spin] = [[defaultdict(float)\n for i in range(self.nkpoints)]\n for j in range(self.nbands)]\n\n for iat in range(self.nions):\n name = structure.species[iat].symbol\n for spin, d in self.data.items():\n for k, b in itertools.product(range(self.nkpoints),\n range(self.nbands)):\n dico[spin][b][k][name] = np.sum(d[k, b, iat, :])\n\n return dico\n\n def get_occupation(self, atom_index, orbital):\n \"\"\"\n Returns the occupation for a particular orbital of a particular atom.\n\n Args:\n atom_num (int): Index of atom in the PROCAR. It should be noted\n that VASP uses 1-based indexing for atoms, but this is\n converted to 0-based indexing in this parser to be\n consistent with representation of structures in pymatgen.\n orbital (str): An orbital. If it is a single character, e.g., s,\n p, d or f, the sum of all s-type, p-type, d-type or f-type\n orbitals occupations are returned respectively. If it is a\n specific orbital, e.g., px, dxy, etc., only the occupation\n of that orbital is returned.\n\n Returns:\n Sum occupation of orbital of atom.\n \"\"\"\n\n orbital_index = self.orbitals.index(orbital)\n return {spin: np.sum(d[:, :, atom_index, orbital_index] * self.weights[:, None])\n for spin, d in self.data.items()}\n\n\nclass Oszicar:\n \"\"\"\n A basic parser for an OSZICAR output from VASP. In general, while the\n OSZICAR is useful for a quick look at the output from a VASP run, we\n recommend that you use the Vasprun parser instead, which gives far richer\n information about a run.\n\n .. attribute:: electronic_steps\n\n All electronic steps as a list of list of dict. e.g.,\n [[{\"rms\": 160.0, \"E\": 4507.24605593, \"dE\": 4507.2, \"N\": 1,\n \"deps\": -17777.0, \"ncg\": 16576}, ...], [....]\n where electronic_steps[index] refers the list of electronic steps\n in one ionic_step, electronic_steps[index][subindex] refers to a\n particular electronic step at subindex in ionic step at index. The\n dict of properties depends on the type of VASP run, but in general,\n \"E\", \"dE\" and \"rms\" should be present in almost all runs.\n\n .. attribute:: ionic_steps:\n\n All ionic_steps as a list of dict, e.g.,\n [{\"dE\": -526.36, \"E0\": -526.36024, \"mag\": 0.0, \"F\": -526.36024},\n ...]\n This is the typical output from VASP at the end of each ionic step.\n \"\"\"\n\n def __init__(self, filename):\n \"\"\"\n Args:\n filename (str): Filename of file to parse\n \"\"\"\n electronic_steps = []\n ionic_steps = []\n ionic_pattern = re.compile(r\"(\\d+)\\s+F=\\s*([\\d\\-\\.E\\+]+)\\s+\"\n r\"E0=\\s*([\\d\\-\\.E\\+]+)\\s+\"\n r\"d\\s*E\\s*=\\s*([\\d\\-\\.E\\+]+)$\")\n ionic_mag_pattern = re.compile(r\"(\\d+)\\s+F=\\s*([\\d\\-\\.E\\+]+)\\s+\"\n r\"E0=\\s*([\\d\\-\\.E\\+]+)\\s+\"\n r\"d\\s*E\\s*=\\s*([\\d\\-\\.E\\+]+)\\s+\"\n r\"mag=\\s*([\\d\\-\\.E\\+]+)\")\n ionic_MD_pattern = re.compile(r\"(\\d+)\\s+T=\\s*([\\d\\-\\.E\\+]+)\\s+\"\n r\"E=\\s*([\\d\\-\\.E\\+]+)\\s+\"\n r\"F=\\s*([\\d\\-\\.E\\+]+)\\s+\"\n r\"E0=\\s*([\\d\\-\\.E\\+]+)\\s+\"\n r\"EK=\\s*([\\d\\-\\.E\\+]+)\\s+\"\n r\"SP=\\s*([\\d\\-\\.E\\+]+)\\s+\"\n r\"SK=\\s*([\\d\\-\\.E\\+]+)\")\n electronic_pattern = re.compile(r\"\\s*\\w+\\s*:(.*)\")\n\n def smart_convert(header, num):\n try:\n if header == \"N\" or header == \"ncg\":\n v = int(num)\n return v\n v = float(num)\n return v\n except ValueError:\n return \"--\"\n\n header = []\n with zopen(filename, \"rt\") as fid:\n for line in fid:\n line = line.strip()\n m = electronic_pattern.match(line)\n if m:\n toks = m.group(1).split()\n data = {header[i]: smart_convert(header[i], toks[i])\n for i in range(len(toks))}\n if toks[0] == \"1\":\n electronic_steps.append([data])\n else:\n electronic_steps[-1].append(data)\n elif ionic_pattern.match(line.strip()):\n m = ionic_pattern.match(line.strip())\n ionic_steps.append({\"F\": float(m.group(2)),\n \"E0\": float(m.group(3)),\n \"dE\": float(m.group(4))})\n elif ionic_mag_pattern.match(line.strip()):\n m = ionic_mag_pattern.match(line.strip())\n ionic_steps.append({\"F\": float(m.group(2)),\n \"E0\": float(m.group(3)),\n \"dE\": float(m.group(4)),\n \"mag\": float(m.group(5))})\n elif ionic_MD_pattern.match(line.strip()):\n m = ionic_MD_pattern.match(line.strip())\n ionic_steps.append({\"T\": float(m.group(2)),\n \"E\": float(m.group(3)),\n \"F\": float(m.group(4)),\n \"E0\": float(m.group(5)),\n \"EK\": float(m.group(6)),\n \"SP\": float(m.group(7)),\n \"SK\": float(m.group(8))})\n elif re.match(r\"^\\s*N\\s+E\\s*\", line):\n header = line.strip().replace(\"d eps\", \"deps\").split()\n self.electronic_steps = electronic_steps\n self.ionic_steps = ionic_steps\n\n @property\n def all_energies(self):\n \"\"\"\n Compilation of all energies from all electronic steps and ionic steps\n as a tuple of list of energies, e.g.,\n ((4507.24605593, 143.824705755, -512.073149912, ...), ...)\n \"\"\"\n all_energies = []\n for i in range(len(self.electronic_steps)):\n energies = [step[\"E\"] for step in self.electronic_steps[i]]\n energies.append(self.ionic_steps[i][\"F\"])\n all_energies.append(tuple(energies))\n return tuple(all_energies)\n\n @property # type: ignore\n @unitized(\"eV\")\n def final_energy(self):\n \"\"\"\n Final energy from run.\n \"\"\"\n return self.ionic_steps[-1][\"E0\"]\n\n def as_dict(self):\n \"\"\"\n :return: MSONable dict\n \"\"\"\n return {\"electronic_steps\": self.electronic_steps,\n \"ionic_steps\": self.ionic_steps}\n\n\nclass VaspParserError(Exception):\n \"\"\"\n Exception class for VASP parsing.\n \"\"\"\n pass\n\n\ndef get_band_structure_from_vasp_multiple_branches(dir_name, efermi=None,\n projections=False):\n \"\"\"\n This method is used to get band structure info from a VASP directory. It\n takes into account that the run can be divided in several branches named\n \"branch_x\". If the run has not been divided in branches the method will\n turn to parsing vasprun.xml directly.\n\n The method returns None is there\"s a parsing error\n\n Args:\n dir_name: Directory containing all bandstructure runs.\n efermi: Efermi for bandstructure.\n projections: True if you want to get the data on site projections if\n any. Note that this is sometimes very large\n\n Returns:\n A BandStructure Object\n \"\"\"\n # TODO: Add better error handling!!!\n if os.path.exists(os.path.join(dir_name, \"branch_0\")):\n # get all branch dir names\n branch_dir_names = [os.path.abspath(d)\n for d in glob.glob(\"{i}/branch_*\"\n .format(i=dir_name))\n if os.path.isdir(d)]\n\n # sort by the directory name (e.g, branch_10)\n sorted_branch_dir_names = sorted(branch_dir_names, key=lambda x: int(x.split(\"_\")[-1]))\n\n # populate branches with Bandstructure instances\n branches = []\n for dir_name in sorted_branch_dir_names:\n xml_file = os.path.join(dir_name, \"vasprun.xml\")\n if os.path.exists(xml_file):\n run = Vasprun(xml_file, parse_projected_eigen=projections)\n branches.append(run.get_band_structure(efermi=efermi))\n else:\n # It might be better to throw an exception\n warnings.warn(\"Skipping {}. Unable to find {}\".format(dir_name, xml_file))\n\n return get_reconstructed_band_structure(branches, efermi)\n else:\n xml_file = os.path.join(dir_name, \"vasprun.xml\")\n # Better handling of Errors\n if os.path.exists(xml_file):\n return Vasprun(xml_file, parse_projected_eigen=projections) \\\n .get_band_structure(kpoints_filename=None, efermi=efermi)\n else:\n return None\n\n\nclass Xdatcar:\n \"\"\"\n Class representing an XDATCAR file. Only tested with VASP 5.x files.\n\n .. attribute:: structures\n\n List of structures parsed from XDATCAR.\n .. attribute:: comment\n\n Optional comment string.\n Authors: Ram Balachandran\n \"\"\"\n\n def __init__(self, filename, ionicstep_start=1,\n ionicstep_end=None, comment=None):\n \"\"\"\n Init a Xdatcar.\n\n Args:\n filename (str): Filename of input XDATCAR file.\n ionicstep_start (int): Starting number of ionic step.\n ionicstep_end (int): Ending number of ionic step.\n \"\"\"\n preamble = None\n coords_str = []\n structures = []\n preamble_done = False\n if (ionicstep_start < 1):\n raise Exception('Start ionic step cannot be less than 1')\n if (ionicstep_end is not None and\n ionicstep_start < 1):\n raise Exception('End ionic step cannot be less than 1')\n\n ionicstep_cnt = 1\n with zopen(filename, \"rt\") as f:\n for l in f:\n l = l.strip()\n if preamble is None:\n preamble = [l]\n elif not preamble_done:\n if l == \"\" or \"Direct configuration=\" in l:\n preamble_done = True\n tmp_preamble = [preamble[0]]\n for i in range(1, len(preamble)):\n if preamble[0] != preamble[i]:\n tmp_preamble.append(preamble[i])\n else:\n break\n preamble = tmp_preamble\n else:\n preamble.append(l)\n elif l == \"\" or \"Direct configuration=\" in l:\n p = Poscar.from_string(\"\\n\".join(preamble +\n [\"Direct\"] + coords_str))\n if ionicstep_end is None:\n if (ionicstep_cnt >= ionicstep_start):\n structures.append(p.structure)\n else:\n if ionicstep_start <= ionicstep_cnt < ionicstep_end:\n structures.append(p.structure)\n if ionicstep_cnt >= ionicstep_end:\n break\n ionicstep_cnt += 1\n coords_str = []\n else:\n coords_str.append(l)\n p = Poscar.from_string(\"\\n\".join(preamble +\n [\"Direct\"] + coords_str))\n if ionicstep_end is None:\n if ionicstep_cnt >= ionicstep_start:\n structures.append(p.structure)\n else:\n if ionicstep_start <= ionicstep_cnt < ionicstep_end:\n structures.append(p.structure)\n self.structures = structures\n self.comment = comment or self.structures[0].formula\n\n @property\n def site_symbols(self):\n \"\"\"\n Sequence of symbols associated with the Xdatcar. Similar to 6th line in\n vasp 5+ Xdatcar.\n \"\"\"\n syms = [site.specie.symbol for site in self.structures[0]]\n return [a[0] for a in itertools.groupby(syms)]\n\n @property\n def natoms(self):\n \"\"\"\n Sequence of number of sites of each type associated with the Poscar.\n Similar to 7th line in vasp 5+ Xdatcar.\n \"\"\"\n syms = [site.specie.symbol for site in self.structures[0]]\n return [len(tuple(a[1])) for a in itertools.groupby(syms)]\n\n def concatenate(self, filename, ionicstep_start=1,\n ionicstep_end=None):\n \"\"\"\n Concatenate structures in file to Xdatcar.\n\n Args:\n filename (str): Filename of XDATCAR file to be concatenated.\n ionicstep_start (int): Starting number of ionic step.\n ionicstep_end (int): Ending number of ionic step.\n TODO(rambalachandran):\n Requires a check to ensure if the new concatenating file has the\n same lattice structure and atoms as the Xdatcar class.\n \"\"\"\n preamble = None\n coords_str = []\n structures = self.structures\n preamble_done = False\n if ionicstep_start < 1:\n raise Exception('Start ionic step cannot be less than 1')\n if (ionicstep_end is not None and\n ionicstep_start < 1):\n raise Exception('End ionic step cannot be less than 1')\n ionicstep_cnt = 1\n with zopen(filename, \"rt\") as f:\n for l in f:\n l = l.strip()\n if preamble is None:\n preamble = [l]\n elif not preamble_done:\n if l == \"\" or \"Direct configuration=\" in l:\n preamble_done = True\n tmp_preamble = [preamble[0]]\n for i in range(1, len(preamble)):\n if preamble[0] != preamble[i]:\n tmp_preamble.append(preamble[i])\n else:\n break\n preamble = tmp_preamble\n else:\n preamble.append(l)\n elif l == \"\" or \"Direct configuration=\" in l:\n p = Poscar.from_string(\"\\n\".join(preamble +\n [\"Direct\"] + coords_str))\n if ionicstep_end is None:\n if (ionicstep_cnt >= ionicstep_start):\n structures.append(p.structure)\n else:\n if ionicstep_start <= ionicstep_cnt < ionicstep_end:\n structures.append(p.structure)\n ionicstep_cnt += 1\n coords_str = []\n else:\n coords_str.append(l)\n p = Poscar.from_string(\"\\n\".join(preamble +\n [\"Direct\"] + coords_str))\n if ionicstep_end is None:\n if ionicstep_cnt >= ionicstep_start:\n structures.append(p.structure)\n else:\n if ionicstep_start <= ionicstep_cnt < ionicstep_end:\n structures.append(p.structure)\n self.structures = structures\n\n def get_string(self, ionicstep_start=1,\n ionicstep_end=None,\n significant_figures=8):\n \"\"\"\n Write Xdatcar class to a string.\n\n Args:\n ionicstep_start (int): Starting number of ionic step.\n ionicstep_end (int): Ending number of ionic step.\n significant_figures (int): Number of significant figures.\n \"\"\"\n if ionicstep_start < 1:\n raise Exception('Start ionic step cannot be less than 1')\n if ionicstep_end is not None and ionicstep_end < 1:\n raise Exception('End ionic step cannot be less than 1')\n latt = self.structures[0].lattice\n if np.linalg.det(latt.matrix) < 0:\n latt = Lattice(-latt.matrix)\n lines = [self.comment, \"1.0\", str(latt)]\n lines.append(\" \".join(self.site_symbols))\n lines.append(\" \".join([str(x) for x in self.natoms]))\n format_str = \"{{:.{0}f}}\".format(significant_figures)\n ionicstep_cnt = 1\n output_cnt = 1\n for cnt, structure in enumerate(self.structures):\n ionicstep_cnt = cnt + 1\n if ionicstep_end is None:\n if (ionicstep_cnt >= ionicstep_start):\n lines.append(\"Direct configuration=\" +\n ' ' * (7 - len(str(output_cnt))) + str(output_cnt))\n for (i, site) in enumerate(structure):\n coords = site.frac_coords\n line = \" \".join([format_str.format(c) for c in coords])\n lines.append(line)\n output_cnt += 1\n else:\n if ionicstep_start <= ionicstep_cnt < ionicstep_end:\n lines.append(\"Direct configuration=\" +\n ' ' * (7 - len(str(output_cnt))) + str(output_cnt))\n for (i, site) in enumerate(structure):\n coords = site.frac_coords\n line = \" \".join([format_str.format(c) for c in coords])\n lines.append(line)\n output_cnt += 1\n return \"\\n\".join(lines) + \"\\n\"\n\n def write_file(self, filename, **kwargs):\n \"\"\"\n Write Xdatcar class into a file.\n\n Args:\n filename (str): Filename of output XDATCAR file.\n The supported kwargs are the same as those for the\n Xdatcar.get_string method and are passed through directly.\n \"\"\"\n with zopen(filename, \"wt\") as f:\n f.write(self.get_string(**kwargs))\n\n def __str__(self):\n return self.get_string()\n\n\nclass Dynmat:\n \"\"\"\n Object for reading a DYNMAT file.\n\n .. attribute:: data\n\n A nested dict containing the DYNMAT data of the form::\n [atom <int>][disp <int>]['dispvec'] =\n displacement vector (part of first line in dynmat block, e.g. \"0.01 0 0\")\n [atom <int>][disp <int>]['dynmat'] =\n <list> list of dynmat lines for this atom and this displacement\n\n Authors: Patrick Huck\n \"\"\"\n\n def __init__(self, filename):\n \"\"\"\n Args:\n filename: Name of file containing DYNMAT\n \"\"\"\n with zopen(filename, \"rt\") as f:\n lines = list(clean_lines(f.readlines()))\n self._nspecs, self._natoms, self._ndisps = map(int, lines[\n 0].split())\n self._masses = map(float, lines[1].split())\n self.data = defaultdict(dict)\n atom, disp = None, None\n for i, l in enumerate(lines[2:]):\n v = list(map(float, l.split()))\n if not i % (self._natoms + 1):\n atom, disp = map(int, v[:2])\n if atom not in self.data:\n self.data[atom] = {}\n if disp not in self.data[atom]:\n self.data[atom][disp] = {}\n self.data[atom][disp]['dispvec'] = v[2:]\n else:\n if 'dynmat' not in self.data[atom][disp]:\n self.data[atom][disp]['dynmat'] = []\n self.data[atom][disp]['dynmat'].append(v)\n\n def get_phonon_frequencies(self):\n \"\"\"calculate phonon frequencies\"\"\"\n # TODO: the following is most likely not correct or suboptimal\n # hence for demonstration purposes only\n frequencies = []\n for k, v0 in self.data.iteritems():\n for v1 in v0.itervalues():\n vec = map(abs, v1['dynmat'][k - 1])\n frequency = math.sqrt(sum(vec)) * 2. * math.pi * 15.633302 # THz\n frequencies.append(frequency)\n return frequencies\n\n @property\n def nspecs(self):\n \"\"\"returns the number of species\"\"\"\n return self._nspecs\n\n @property\n def natoms(self):\n \"\"\"returns the number of atoms\"\"\"\n return self._natoms\n\n @property\n def ndisps(self):\n \"\"\"returns the number of displacements\"\"\"\n return self._ndisps\n\n @property\n def masses(self):\n \"\"\"returns the list of atomic masses\"\"\"\n return list(self._masses)\n\n\ndef get_adjusted_fermi_level(efermi, cbm, band_structure):\n \"\"\"\n When running a band structure computations the fermi level needs to be\n take from the static run that gave the charge density used for the non-self\n consistent band structure run. Sometimes this fermi level is however a\n little too low because of the mismatch between the uniform grid used in\n the static run and the band structure k-points (e.g., the VBM is on Gamma\n and the Gamma point is not in the uniform mesh). Here we use a procedure\n consisting in looking for energy levels higher than the static fermi level\n (but lower than the LUMO) if any of these levels make the band structure\n appears insulating and not metallic anymore, we keep this adjusted fermi\n level. This procedure has shown to detect correctly most insulators.\n\n Args:\n efermi (float): Fermi energy of the static run\n cbm (float): Conduction band minimum of the static run\n run_bandstructure: a band_structure object\n\n Returns:\n a new adjusted fermi level\n \"\"\"\n # make a working copy of band_structure\n bs_working = BandStructureSymmLine.from_dict(band_structure.as_dict())\n if bs_working.is_metal():\n e = efermi\n while e < cbm:\n e += 0.01\n bs_working._efermi = e\n if not bs_working.is_metal():\n return e\n return efermi\n\n\nclass Wavecar:\n \"\"\"\n This is a class that contains the (pseudo-) wavefunctions from VASP.\n\n Coefficients are read from the given WAVECAR file and the corresponding\n G-vectors are generated using the algorithm developed in WaveTrans (see\n acknowledgments below). To understand how the wavefunctions are evaluated,\n please see the evaluate_wavefunc docstring.\n\n It should be noted that the pseudopotential augmentation is not included in\n the WAVECAR file. As a result, some caution should be exercised when\n deriving value from this information.\n\n The usefulness of this class is to allow the user to do projections or band\n unfolding style manipulations of the wavefunction. An example of this can\n be seen in the work of Shen et al. 2017\n (https://doi.org/10.1103/PhysRevMaterials.1.065001).\n\n .. attribute:: filename\n\n String of the input file (usually WAVECAR)\n\n .. attribute:: nk\n\n Number of k-points from the WAVECAR\n\n .. attribute:: nb\n\n Number of bands per k-point\n\n .. attribute:: encut\n\n Energy cutoff (used to define G_{cut})\n\n .. attribute:: efermi\n\n Fermi energy\n\n .. attribute:: a\n\n Primitive lattice vectors of the cell (e.g. a_1 = self.a[0, :])\n\n .. attribute:: b\n\n Reciprocal lattice vectors of the cell (e.g. b_1 = self.b[0, :])\n\n .. attribute:: vol\n\n The volume of the unit cell in real space\n\n .. attribute:: kpoints\n\n The list of k-points read from the WAVECAR file\n\n .. attribute:: band_energy\n\n The list of band eigenenergies (and corresponding occupancies) for\n each kpoint, where the first index corresponds to the index of the\n k-point (e.g. self.band_energy[kp])\n\n .. attribute:: Gpoints\n\n The list of generated G-points for each k-point (a double list), which\n are used with the coefficients for each k-point and band to recreate\n the wavefunction (e.g. self.Gpoints[kp] is the list of G-points for\n k-point kp). The G-points depend on the k-point and reciprocal lattice\n and therefore are identical for each band at the same k-point. Each\n G-point is represented by integer multipliers (e.g. assuming\n Gpoints[kp][n] == [n_1, n_2, n_3], then\n G_n = n_1*b_1 + n_2*b_2 + n_3*b_3)\n\n .. attribute:: coeffs\n\n The list of coefficients for each k-point and band for reconstructing\n the wavefunction. For non-spin-polarized, the first index corresponds\n to the kpoint and the second corresponds to the band (e.g.\n self.coeffs[kp][b] corresponds to k-point kp and band b). For\n spin-polarized calculations, the first index is for the spin.\n\n Acknowledgments:\n This code is based upon the Fortran program, WaveTrans, written by\n R. M. Feenstra and M. Widom from the Dept. of Physics at Carnegie\n Mellon University. To see the original work, please visit:\n https://www.andrew.cmu.edu/user/feenstra/wavetrans/\n\n Author: Mark Turiansky\n \"\"\"\n\n def __init__(self, filename='WAVECAR', verbose=False, precision='normal'):\n \"\"\"\n Information is extracted from the given WAVECAR\n\n Args:\n filename (str): input file (default: WAVECAR)\n verbose (bool): determines whether processing information is shown\n precision (str): determines how fine the fft mesh is (normal or\n accurate), only the first letter matters\n \"\"\"\n self.filename = filename\n\n # c = 0.26246582250210965422\n # 2m/hbar^2 in agreement with VASP\n self._C = 0.262465831\n with open(self.filename, 'rb') as f:\n # read the header information\n recl, spin, rtag = np.fromfile(f, dtype=np.float64, count=3) \\\n .astype(np.int)\n if verbose:\n print('recl={}, spin={}, rtag={}'.format(recl, spin, rtag))\n recl8 = int(recl / 8)\n self.spin = spin\n\n # check that ISPIN wasn't set to 2\n # if spin == 2:\n # raise ValueError('spin polarization not currently supported')\n\n # check to make sure we have precision correct\n if rtag != 45200 and rtag != 45210:\n raise ValueError('invalid rtag of {}'.format(rtag))\n\n # padding\n np.fromfile(f, dtype=np.float64, count=(recl8 - 3))\n\n # extract kpoint, bands, energy, and lattice information\n self.nk, self.nb, self.encut = np.fromfile(f, dtype=np.float64,\n count=3).astype(np.int)\n self.a = np.fromfile(f, dtype=np.float64, count=9).reshape((3, 3))\n self.efermi = np.fromfile(f, dtype=np.float64, count=1)[0]\n if verbose:\n print('kpoints = {}, bands = {}, energy cutoff = {}, fermi '\n 'energy= {:.04f}\\n'.format(self.nk, self.nb, self.encut,\n self.efermi))\n print('primitive lattice vectors = \\n{}'.format(self.a))\n\n self.vol = np.dot(self.a[0, :],\n np.cross(self.a[1, :], self.a[2, :]))\n if verbose:\n print('volume = {}\\n'.format(self.vol))\n\n # calculate reciprocal lattice\n b = np.array([np.cross(self.a[1, :], self.a[2, :]),\n np.cross(self.a[2, :], self.a[0, :]),\n np.cross(self.a[0, :], self.a[1, :])])\n b = 2 * np.pi * b / self.vol\n self.b = b\n if verbose:\n print('reciprocal lattice vectors = \\n{}'.format(b))\n print('reciprocal lattice vector magnitudes = \\n{}\\n'\n .format(np.linalg.norm(b, axis=1)))\n\n # calculate maximum number of b vectors in each direction\n self._generate_nbmax()\n if verbose:\n print('max number of G values = {}\\n\\n'.format(self._nbmax))\n self.ng = self._nbmax * 3 if precision.lower()[0] == 'n' else \\\n self._nbmax * 4\n\n # padding\n np.fromfile(f, dtype=np.float64, count=recl8 - 13)\n\n # reading records\n # np.set_printoptions(precision=7, suppress=True)\n self.Gpoints = [None for _ in range(self.nk)]\n self.kpoints = []\n if spin == 2:\n self.coeffs = [[[None for i in range(self.nb)]\n for j in range(self.nk)] for _ in range(spin)]\n self.band_energy = [[] for _ in range(spin)]\n else:\n self.coeffs = [[None for i in range(self.nb)]\n for j in range(self.nk)]\n self.band_energy = []\n for ispin in range(spin):\n if verbose:\n print('reading spin {}'.format(ispin))\n for ink in range(self.nk):\n # information for this kpoint\n nplane = int(np.fromfile(f, dtype=np.float64, count=1)[0])\n kpoint = np.fromfile(f, dtype=np.float64, count=3)\n\n if ispin == 0:\n self.kpoints.append(kpoint)\n else:\n assert np.allclose(self.kpoints[ink], kpoint)\n\n if verbose:\n print('kpoint {: 4} with {: 5} plane waves at {}'\n .format(ink, nplane, kpoint))\n\n # energy and occupation information\n enocc = np.fromfile(f, dtype=np.float64,\n count=3 * self.nb).reshape((self.nb, 3))\n if spin == 2:\n self.band_energy[ispin].append(enocc)\n else:\n self.band_energy.append(enocc)\n\n if verbose:\n print(enocc[:, [0, 2]])\n\n # padding\n np.fromfile(f, dtype=np.float64, count=(recl8 - 4 - 3 * self.nb))\n\n # generate G integers\n self.Gpoints[ink] = self._generate_G_points(kpoint)\n if len(self.Gpoints[ink]) != nplane:\n raise ValueError('failed to generate the correct '\n 'number of G points')\n\n # extract coefficients\n for inb in range(self.nb):\n if rtag == 45200:\n data = np.fromfile(f, dtype=np.complex64, count=nplane)\n np.fromfile(f, dtype=np.float64, count=recl8 - nplane)\n elif rtag == 45210:\n # this should handle double precision coefficients\n # but I don't have a WAVECAR to test it with\n data = np.fromfile(f, dtype=np.complex128, count=nplane)\n np.fromfile(f, dtype=np.float64, count=recl8 - 2 * nplane)\n\n if spin == 2:\n self.coeffs[ispin][ink][inb] = data\n else:\n self.coeffs[ink][inb] = data\n\n def _generate_nbmax(self):\n \"\"\"\n Helper function that determines maximum number of b vectors for\n each direction.\n\n This algorithm is adapted from WaveTrans (see Class docstring). There\n should be no reason for this function to be called outside of\n initialization.\n \"\"\"\n bmag = np.linalg.norm(self.b, axis=1)\n b = self.b\n\n # calculate maximum integers in each direction for G\n phi12 = np.arccos(np.dot(b[0, :], b[1, :]) / (bmag[0] * bmag[1]))\n sphi123 = np.dot(b[2, :], np.cross(b[0, :], b[1, :])) / (bmag[2] * np.linalg.norm(np.cross(b[0, :], b[1, :])))\n nbmaxA = np.sqrt(self.encut * self._C) / bmag\n nbmaxA[0] /= np.abs(np.sin(phi12))\n nbmaxA[1] /= np.abs(np.sin(phi12))\n nbmaxA[2] /= np.abs(sphi123)\n nbmaxA += 1\n\n phi13 = np.arccos(np.dot(b[0, :], b[2, :]) / (bmag[0] * bmag[2]))\n sphi123 = np.dot(b[1, :], np.cross(b[0, :], b[2, :])) / (bmag[1] * np.linalg.norm(np.cross(b[0, :], b[2, :])))\n nbmaxB = np.sqrt(self.encut * self._C) / bmag\n nbmaxB[0] /= np.abs(np.sin(phi13))\n nbmaxB[1] /= np.abs(sphi123)\n nbmaxB[2] /= np.abs(np.sin(phi13))\n nbmaxB += 1\n\n phi23 = np.arccos(np.dot(b[1, :], b[2, :]) / (bmag[1] * bmag[2]))\n sphi123 = np.dot(b[0, :], np.cross(b[1, :], b[2, :])) / (bmag[0] * np.linalg.norm(np.cross(b[1, :], b[2, :])))\n nbmaxC = np.sqrt(self.encut * self._C) / bmag\n nbmaxC[0] /= np.abs(sphi123)\n nbmaxC[1] /= np.abs(np.sin(phi23))\n nbmaxC[2] /= np.abs(np.sin(phi23))\n nbmaxC += 1\n\n self._nbmax = np.max([nbmaxA, nbmaxB, nbmaxC], axis=0).astype(np.int)\n\n def _generate_G_points(self, kpoint):\n \"\"\"\n Helper function to generate G-points based on nbmax.\n\n This function iterates over possible G-point values and determines\n if the energy is less than G_{cut}. Valid values are appended to\n the output array. This function should not be called outside of\n initialization.\n\n Args:\n kpoint (np.array): the array containing the current k-point value\n\n Returns:\n a list containing valid G-points\n \"\"\"\n gpoints = []\n for i in range(2 * self._nbmax[2] + 1):\n i3 = i - 2 * self._nbmax[2] - 1 if i > self._nbmax[2] else i\n for j in range(2 * self._nbmax[1] + 1):\n j2 = j - 2 * self._nbmax[1] - 1 if j > self._nbmax[1] else j\n for k in range(2 * self._nbmax[0] + 1):\n k1 = k - 2 * self._nbmax[0] - 1 if k > self._nbmax[0] else k\n G = np.array([k1, j2, i3])\n v = kpoint + G\n g = np.linalg.norm(np.dot(v, self.b))\n E = g ** 2 / self._C\n if E < self.encut:\n gpoints.append(G)\n return np.array(gpoints, dtype=np.float64)\n\n def evaluate_wavefunc(self, kpoint, band, r, spin=0):\n r\"\"\"\n Evaluates the wavefunction for a given position, r.\n\n The wavefunction is given by the k-point and band. It is evaluated\n at the given position by summing over the components. Formally,\n\n \\psi_n^k (r) = \\sum_{i=1}^N c_i^{n,k} \\exp (i (k + G_i^{n,k}) \\cdot r)\n\n where \\psi_n^k is the wavefunction for the nth band at k-point k, N is\n the number of plane waves, c_i^{n,k} is the ith coefficient that\n corresponds to the nth band and k-point k, and G_i^{n,k} is the ith\n G-point corresponding to k-point k.\n\n NOTE: This function is very slow; a discrete fourier transform is the\n preferred method of evaluation (see Wavecar.fft_mesh).\n\n Args:\n kpoint (int): the index of the kpoint where the wavefunction\n will be evaluated\n band (int): the index of the band where the wavefunction will be\n evaluated\n r (np.array): the position where the wavefunction will be evaluated\n spin (int): spin index for the desired wavefunction (only for\n ISPIN = 2, default = 0)\n Returns:\n a complex value corresponding to the evaluation of the wavefunction\n \"\"\"\n v = self.Gpoints[kpoint] + self.kpoints[kpoint]\n u = np.dot(np.dot(v, self.b), r)\n c = self.coeffs[spin][kpoint][band] if self.spin == 2 else \\\n self.coeffs[kpoint][band]\n return np.sum(np.dot(c, np.exp(1j * u, dtype=np.complex64))) / np.sqrt(self.vol)\n\n def fft_mesh(self, kpoint, band, spin=0, shift=True):\n \"\"\"\n Places the coefficients of a wavefunction onto an fft mesh.\n\n Once the mesh has been obtained, a discrete fourier transform can be\n used to obtain real-space evaluation of the wavefunction. The output\n of this function can be passed directly to numpy's fft function. For\n example:\n\n mesh = Wavecar('WAVECAR').fft_mesh(kpoint, band)\n evals = np.fft.ifftn(mesh)\n\n Args:\n kpoint (int): the index of the kpoint where the wavefunction\n will be evaluated\n band (int): the index of the band where the wavefunction will be\n evaluated\n spin (int): the spin of the wavefunction for the desired\n wavefunction (only for ISPIN = 2, default = 0)\n shift (bool): determines if the zero frequency coefficient is\n placed at index (0, 0, 0) or centered\n Returns:\n a numpy ndarray representing the 3D mesh of coefficients\n \"\"\"\n mesh = np.zeros(tuple(self.ng), dtype=np.complex)\n tcoeffs = self.coeffs[spin][kpoint][band] if self.spin == 2 else \\\n self.coeffs[kpoint][band]\n for gp, coeff in zip(self.Gpoints[kpoint], tcoeffs):\n t = tuple(gp.astype(np.int) + (self.ng / 2).astype(np.int))\n mesh[t] = coeff\n if shift:\n return np.fft.ifftshift(mesh)\n else:\n return mesh\n\n def get_parchg(self, poscar, kpoint, band, spin=None, phase=False,\n scale=2):\n \"\"\"\n Generates a Chgcar object, which is the charge density of the specified\n wavefunction.\n\n This function generates a Chgcar object with the charge density of the\n wavefunction specified by band and kpoint (and spin, if the WAVECAR\n corresponds to a spin-polarized calculation). The phase tag is a\n feature that is not present in VASP. For a real wavefunction, the phase\n tag being turned on means that the charge density is multiplied by the\n sign of the wavefunction at that point in space. A warning is generated\n if the phase tag is on and the chosen kpoint is not Gamma.\n\n Note: Augmentation from the PAWs is NOT included in this function. The\n maximal charge density will differ from the PARCHG from VASP, but the\n qualitative shape of the charge density will match.\n\n Args:\n poscar (pymatgen.io.vasp.inputs.Poscar): Poscar object that has the\n structure associated with the WAVECAR file\n kpoint (int): the index of the kpoint for the wavefunction\n band (int): the index of the band for the wavefunction\n spin (int): optional argument to specify the spin. If the\n Wavecar has ISPIN = 2, spin is None generates a\n Chgcar with total spin and magnetization, and\n spin == {0, 1} specifies just the spin up or\n down component.\n phase (bool): flag to determine if the charge density is\n multiplied by the sign of the wavefunction.\n Only valid for real wavefunctions.\n scale (int): scaling for the FFT grid. The default value of 2 is\n at least as fine as the VASP default.\n Returns:\n a pymatgen.io.vasp.outputs.Chgcar object\n \"\"\"\n\n if phase and not np.all(self.kpoints[kpoint] == 0.):\n warnings.warn('phase == True should only be used for the Gamma '\n 'kpoint! I hope you know what you\\'re doing!')\n\n # scaling of ng for the fft grid, need to restore value at the end\n temp_ng = self.ng\n self.ng = self.ng * scale\n N = np.prod(self.ng)\n\n data = {}\n if self.spin == 2:\n if spin is not None:\n wfr = np.fft.ifftn(self.fft_mesh(kpoint, band, spin=spin)) * N\n den = np.abs(np.conj(wfr) * wfr)\n if phase:\n den = np.sign(np.real(wfr)) * den\n data['total'] = den\n else:\n wfr = np.fft.ifftn(self.fft_mesh(kpoint, band, spin=0)) * N\n denup = np.abs(np.conj(wfr) * wfr)\n wfr = np.fft.ifftn(self.fft_mesh(kpoint, band, spin=1)) * N\n dendn = np.abs(np.conj(wfr) * wfr)\n data['total'] = denup + dendn\n data['diff'] = denup - dendn\n else:\n wfr = np.fft.ifftn(self.fft_mesh(kpoint, band)) * N\n den = np.abs(np.conj(wfr) * wfr)\n if phase:\n den = np.sign(np.real(wfr)) * den\n data['total'] = den\n\n self.ng = temp_ng\n return Chgcar(poscar, data)\n\n\nclass Eigenval:\n \"\"\"\n Object for reading EIGENVAL file.\n\n .. attribute:: filename\n\n string containing input filename\n\n .. attribute:: occu_tol\n\n tolerance for determining occupation in band properties\n\n .. attribute:: ispin\n\n spin polarization tag (int)\n\n .. attribute:: nelect\n\n number of electrons\n\n .. attribute:: nkpt\n\n number of kpoints\n\n .. attribute:: nbands\n\n number of bands\n\n .. attribute:: kpoints\n\n list of kpoints\n\n .. attribute:: kpoints_weights\n\n weights of each kpoint in the BZ, should sum to 1.\n\n .. attribute:: eigenvalues\n\n Eigenvalues as a dict of {(spin): np.ndarray(shape=(nkpt, nbands, 2))}.\n This representation is based on actual ordering in VASP and is meant as\n an intermediate representation to be converted into proper objects. The\n kpoint index is 0-based (unlike the 1-based indexing in VASP).\n \"\"\"\n\n def __init__(self, filename, occu_tol=1e-8):\n \"\"\"\n Reads input from filename to construct Eigenval object\n\n Args:\n filename (str): filename of EIGENVAL to read in\n occu_tol (float): tolerance for determining band gap\n\n Returns:\n a pymatgen.io.vasp.outputs.Eigenval object\n \"\"\"\n\n self.filename = filename\n self.occu_tol = occu_tol\n\n with zopen(filename, 'r') as f:\n self.ispin = int(f.readline().split()[-1])\n\n # useless header information\n for _ in range(4):\n f.readline()\n\n self.nelect, self.nkpt, self.nbands = \\\n list(map(int, f.readline().split()))\n\n self.kpoints = []\n self.kpoints_weights = []\n if self.ispin == 2:\n self.eigenvalues = \\\n {Spin.up: np.zeros((self.nkpt, self.nbands, 2)),\n Spin.down: np.zeros((self.nkpt, self.nbands, 2))}\n else:\n self.eigenvalues = \\\n {Spin.up: np.zeros((self.nkpt, self.nbands, 2))}\n\n ikpt = -1\n for line in f:\n if re.search(r'(\\s+[\\-+0-9eE.]+){4}', str(line)):\n ikpt += 1\n kpt = list(map(float, line.split()))\n self.kpoints.append(kpt[:-1])\n self.kpoints_weights.append(kpt[-1])\n for i in range(self.nbands):\n sl = list(map(float, f.readline().split()))\n if len(sl) == 3:\n self.eigenvalues[Spin.up][ikpt, i, 0] = sl[1]\n self.eigenvalues[Spin.up][ikpt, i, 1] = sl[2]\n elif len(sl) == 5:\n self.eigenvalues[Spin.up][ikpt, i, 0] = sl[1]\n self.eigenvalues[Spin.up][ikpt, i, 1] = sl[3]\n self.eigenvalues[Spin.down][ikpt, i, 0] = sl[2]\n self.eigenvalues[Spin.down][ikpt, i, 1] = sl[4]\n\n @property\n def eigenvalue_band_properties(self):\n \"\"\"\n Band properties from the eigenvalues as a tuple,\n (band gap, cbm, vbm, is_band_gap_direct).\n \"\"\"\n\n vbm = -float(\"inf\")\n vbm_kpoint = None\n cbm = float(\"inf\")\n cbm_kpoint = None\n for spin, d in self.eigenvalues.items():\n for k, val in enumerate(d):\n for (eigenval, occu) in val:\n if occu > self.occu_tol and eigenval > vbm:\n vbm = eigenval\n vbm_kpoint = k\n elif occu <= self.occu_tol and eigenval < cbm:\n cbm = eigenval\n cbm_kpoint = k\n return max(cbm - vbm, 0), cbm, vbm, vbm_kpoint == cbm_kpoint\n\n\nclass Wavederf:\n \"\"\"\n Object for reading a WAVEDERF file.\n\n Note: This file is only produced when LOPTICS is true AND vasp has been\n recompiled after uncommenting the line that calls\n WRT_CDER_BETWEEN_STATES_FORMATTED in linear_optics.F\n\n .. attribute:: data\n\n A numpy array containing the WAVEDERF data of the form below. It should\n be noted that VASP uses 1-based indexing for bands, but this is\n converted to 0-based numpy array indexing.\n\n For each kpoint (in the same order as in IBZKPT), and for each pair of\n bands:\n\n [ #kpoint index\n [ #band 1 index\n [ #band 2 index\n [cdum_x_real, cdum_x_imag, cdum_y_real, cdum_y_imag, cdum_z_real, cdum_z_imag]\n ]\n ]\n ]\n\n This structure follows the file format. Numpy array methods can be used\n to fetch data in a more useful way (e.g., get matrix elements between\n wo specific bands at each kpoint, fetch x/y/z components,\n real/imaginary parts, abs/phase, etc. )\n\n Author: Miguel Dias Costa\n \"\"\"\n\n def __init__(self, filename):\n \"\"\"\n Args:\n filename: Name of file containing WAVEDERF.\n \"\"\"\n with zopen(filename, \"rt\") as f:\n header = f.readline().split()\n nb_kpoints = int(header[1])\n nb_bands = int(header[2])\n data = np.zeros((nb_kpoints, nb_bands, nb_bands, 6))\n for ik in range(nb_kpoints):\n for ib1 in range(nb_bands):\n for ib2 in range(nb_bands):\n # each line in the file includes besides the band\n # indexes, which are redundant, each band's energy\n # and occupation, which are already available elsewhere,\n # so we store only the 6 matrix elements after this 6\n # redundant values\n data[ik][ib1][ib2] = [float(element)\n for element in f.readline().split()[6:]]\n\n self.data = data\n self._nb_kpoints = nb_kpoints\n self._nb_bands = nb_bands\n\n @property\n def nb_bands(self):\n \"\"\"\n returns the number of bands in the band structure\n \"\"\"\n return self._nb_bands\n\n @property\n def nb_kpoints(self):\n \"\"\"\n Returns the number of k-points in the band structure calculation\n \"\"\"\n return self._nb_kpoints\n\n def get_elements_between_bands(self, band_i, band_j):\n \"\"\"\n Method returning a numpy array with elements\n\n [cdum_x_real, cdum_x_imag, cdum_y_real, cdum_y_imag, cdum_z_real, cdum_z_imag]\n\n between bands band_i and band_j (vasp 1-based indexing) for all kpoints.\n\n Args:\n band_i (Integer): Index of band i\n band_j (Integer): Index of band j\n\n Returns:\n a numpy list of elements for each kpoint\n \"\"\"\n if band_i < 1 or band_i > self.nb_bands or band_j < 1 or band_j > self.nb_bands:\n raise ValueError(\"Band index out of bounds\")\n\n return self.data[:, band_i - 1, band_j - 1, :]\n\n\nclass Waveder:\n \"\"\"\n Class for reading a WAVEDER file.\n The LOPTICS tag produces a WAVEDER file.\n The WAVEDER contains the derivative of the orbitals with respect to k.\n Author: Kamal Choudhary, NIST\n \"\"\"\n\n def __init__(self, filename, gamma_only=False):\n \"\"\"\n Args:\n filename: Name of file containing WAVEDER.\n \"\"\"\n with open(filename, 'rb') as fp:\n def readData(dtype):\n \"\"\" Read records from Fortran binary file and convert to\n np.array of given dtype. \"\"\"\n data = b''\n while 1:\n prefix = np.fromfile(fp, dtype=np.int32, count=1)[0]\n data += fp.read(abs(prefix))\n suffix = np.fromfile(fp, dtype=np.int32, count=1)[0]\n if abs(prefix) - abs(suffix):\n raise RuntimeError(\"Read wrong amount of bytes.\\n\"\n \"Expected: %d, read: %d, suffix: %d.\" % (prefix, len(data), suffix))\n if prefix > 0:\n break\n return np.frombuffer(data, dtype=dtype)\n\n nbands, nelect, nk, ispin = readData(np.int32)\n _ = readData(np.float) # nodes_in_dielectric_function\n _ = readData(np.float) # wplasmon\n if gamma_only:\n cder = readData(np.float)\n else:\n cder = readData(np.complex64)\n\n cder_data = cder.reshape((3, ispin, nk, nelect, nbands)).T\n\n self._cder_data = cder_data\n self._nkpoints = nk\n self._ispin = ispin\n self._nelect = nelect\n self._nbands = nbands\n\n @property\n def cder_data(self):\n \"\"\"\n Returns the orbital derivative between states\n \"\"\"\n return self._cder_data\n\n @property\n def nbands(self):\n \"\"\"\n Returns the number of bands in the calculation\n \"\"\"\n return self._nbands\n\n @property\n def nkpoints(self):\n \"\"\"\n Returns the number of k-points in the calculation\n \"\"\"\n return self._nkpoints\n\n @property\n def nelect(self):\n \"\"\"\n Returns the number of electrons in the calculation\n \"\"\"\n return self._nelect\n\n def get_orbital_derivative_between_states(self, band_i, band_j, kpoint, spin, cart_dir):\n \"\"\"\n Method returning a value\n between bands band_i and band_j for k-point index, spin-channel and cartesian direction.\n Args:\n band_i (Integer): Index of band i\n band_j (Integer): Index of band j\n kpoint (Integer): Index of k-point\n spin (Integer): Index of spin-channel (0 or 1)\n cart_dir (Integer): Index of cartesian direction (0,1,2)\n\n Returns:\n a float value\n \"\"\"\n if band_i < 0 or band_i > self.nbands - 1 or band_j < 0 or band_j > self.nelect - 1:\n raise ValueError(\"Band index out of bounds\")\n if kpoint > self.nkpoints:\n raise ValueError(\"K-point index out of bounds\")\n if cart_dir > 2 or cart_dir < 0:\n raise ValueError(\"cart_dir index out of bounds\")\n\n return self._cder_data[band_i, band_j, kpoint, spin, cart_dir]\n\n\nclass UnconvergedVASPWarning(Warning):\n \"\"\"\n Warning for unconverged vasp run.\n \"\"\"\n pass\n" ]
[ [ "numpy.dot", "numpy.exp", "numpy.frombuffer", "numpy.max", "numpy.histogram", "numpy.sin", "numpy.linalg.norm", "numpy.prod", "numpy.swapaxes", "numpy.conj", "numpy.sqrt", "numpy.cross", "numpy.array", "numpy.zeros", "numpy.fft.ifftshift", "numpy.linalg.det", "numpy.real", "numpy.allclose", "numpy.fromfile", "numpy.isnan", "numpy.sum", "numpy.abs", "numpy.all" ] ]
lmluzern/MultiOpenCrowd
[ "520d141769bf99d0e3a363d20e2d0e55b34a3224" ]
[ "src/feature_based/multiclass_opencrowd/nn_em.py" ]
[ "import pandas as pd\nimport csv\nimport numpy as np\nfrom tensorflow.keras import Sequential, Model\nfrom tensorflow.keras.layers import Dense, Concatenate, Input, Conv1D, MaxPooling1D, Flatten, Dropout, GlobalAveragePooling1D\nfrom tensorflow.keras.callbacks import EarlyStopping\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import train_test_split\nfrom numpy import linalg as LA\n\nclass nn_em:\n def __init__(self):\n print(\"model initialized\")\n\n def my_init(self, shape):\n value = np.random.random(shape)\n return K.variable(value)\n\n def init_probabilities(self,n):\n # initialize probability z_i (item's quality) randomly\n p_z_i = np.random.randint(2, size=(n, 1)).astype(float)\n return p_z_i, 1 - p_z_i\n\n\n def define_nn(self,n_neurons, hidden,m,nb_hidden_layer,learning_rate):\n classifier = Sequential()\n if hidden == True:\n # First Hidden Layer\n layer0 = Dense(n_neurons, activation='sigmoid', kernel_initializer=initializers.random_normal(stddev=0.03, seed=98765), input_dim=m)\n classifier.add(layer0)\n nb = 1\n while (nb < nb_hidden_layer):\n layer_nb = Dense(n_neurons, activation='sigmoid', kernel_initializer=initializers.random_normal(stddev=0.03, seed=98765))\n classifier.add(layer_nb)\n nb += 1\n # Output Layer\n layer1 = Dense(1, activation='sigmoid', kernel_initializer=initializers.random_normal(stddev=0.03, seed=98765), \\\n kernel_regularizer=regularizers.l2(0.5))\n classifier.add(layer1)\n # Compiling the neural network\n sgd = optimizers.SGD(lr=learning_rate, clipvalue=0.5)\n classifier.compile(optimizer=sgd, loss='binary_crossentropy', metrics=['accuracy'])\n return classifier\n\n def define_multiclass_nn(self,n_neurons,m,class_num):\n classifier = Sequential()\n # Hidden Layer\n layer0 = Dense(n_neurons, input_dim=m, activation='relu')\n classifier.add(layer0)\n # Output Layer\n layer1 = Dense(class_num,activation='softmax')\n classifier.add(layer1)\n # Compiling the neural network\n classifier.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics =['accuracy'])\n return classifier\n\n def lr_pzi(self,classifier, X_train, X_test, y_train, y_test, steps):\n classifier.fit(X_train, y_train, epochs=steps, verbose=0)\n theta_i = classifier.predict(X_test)\n loss_and_metrics = classifier.evaluate(X_test, y_test)\n print(theta_i[1:10])\n eval_model = accuracy_score(y_test, np.where(theta_i > 0.5, 1, 0))\n print(\"eval model\",eval_model)\n weights = classifier.get_weights()\n return theta_i, eval_model,loss_and_metrics, weights[0]\n\n def nn_pzi(self,classifier, social_features, y, steps, true_labels):\n classifier.fit(social_features, y, epochs=steps, verbose=0)\n theta_i = classifier.predict(social_features)\n eval_model = accuracy_score(true_labels, np.where(theta_i > theta_i.mean(), 1, 0))\n weights = classifier.get_weights()\n return theta_i, eval_model, weights[0]\n\n def nn_pzi_test_val(self, classifier, social_features, prob_e_step, steps):\n classifier.fit(social_features, prob_e_step, epochs=steps, verbose=0)\n theta_i = classifier.predict(social_features)\n weights = classifier.get_weights()\n return theta_i, weights[0],classifier\n\n def train_m_step_early_stopp(self, classifier, social_features, prob_e_step,\n steps, total_epochs, y_test, y_val, X_val, start_val):\n monitor = EarlyStopping(monitor='val_loss', min_delta=1e-3, patience=10, \n verbose=0, mode='auto', restore_best_weights=True)\n\n classifier.fit(social_features, prob_e_step, validation_data=(X_val,y_val),\n callbacks=[monitor],verbose=0,epochs=total_epochs, batch_size=4)\n theta_i = classifier.predict(social_features)\n weights = classifier.get_weights()[0]\n\n return theta_i,classifier, weights\n\n def train_m_step(self, classifier, social_features, prob_e_step,\n steps, total_epochs, y_test, y_val,start_val):\n theta_i = prob_e_step.copy()\n weights = np.array([])\n iter = 0\n old_theta_i = np.zeros((social_features.shape[0], 1))\n epsilon = 1e-3\n y_test = np.argmax(y_test,axis=1)\n y_val = np.argmax(y_val,axis=1)\n\n while (LA.norm(theta_i - old_theta_i) > epsilon) and (iter < total_epochs):\n # if (iter % 5 == 0) and (iter>0):\n # min_norm = LA.norm(theta_i - old_theta_i)\n old_theta_i = theta_i.copy()\n theta_i, weights, classifier = self.nn_pzi_test_val(classifier, social_features, prob_e_step, steps)\n end_val = start_val + y_val.shape[0]\n # theta_i_test = theta_i[strat_val:(end_val)]\n # theta_i_val = theta_i[(end_val):]\n theta_i_val = theta_i[start_val:end_val]\n theta_i_test = theta_i[end_val:]\n\n theta_i_test = np.argmax(theta_i_test,axis=1)\n theta_i_val = np.argmax(theta_i_val,axis=1)\n\n eval_model_test = accuracy_score(y_test, theta_i_test)\n eval_model_val = accuracy_score(y_val, theta_i_val)\n if iter%10==0:\n print (\"epoch\", iter,\" convergence influencer:\", LA.norm(theta_i - old_theta_i),\"val\", eval_model_val,\\\n \"test\", eval_model_test)\n iter +=1\n print (\"epoch\", iter, \" convergence influencer:\", LA.norm(theta_i - old_theta_i), \"val\", eval_model_val, \\\n \"test\", eval_model_test)\n return theta_i,classifier, weights\n\n def train(self,classifier,social_features,true_labels, p_z_i_1, total_epochs, steps, size_train):\n y = np.concatenate((true_labels[0:size_train], p_z_i_1[size_train:]))\n for i in range(total_epochs):\n #print(\"epoch\", i)\n theta_i, eval_model, weights = self.nn_pzi(classifier, social_features, y, steps,true_labels)\n y = np.concatenate((true_labels[0:size_train], theta_i[size_train:]))\n result = pd.DataFrame(data=np.concatenate([np.where(theta_i > theta_i.mean(), 1, 0), true_labels], axis=1),\n columns=['classification', 'truth'])\n #print(\"evaluation\", eval_model)\n return result, eval_model,weights, classifier.metrics_names, theta_i,classifier\n\n\n def logistic_regression(self,input_file,output_file,true_labels,weights_file,total_epochs,learning_rate):\n simple_example = pd.read_csv(input_file, sep=\",\")\n social_features = simple_example[['follower_nbr', 'followee_nbr', 'tweets_nbr', 'avg_length_tweets']].values\n #social_features = simple_example.values\n labels = pd.read_csv(true_labels, sep=\",\")\n true_labels = labels[['label']].values\n X_train, X_test, y_train, y_test = train_test_split(social_features, true_labels, test_size = 0.2, random_state=45)\n n = social_features.shape[0]\n print(\"n=\",n)\n print (\"true_labels\", true_labels.shape[0])\n m = social_features.shape[1]\n # initi pzi\n p_z_i_0, p_z_i_1 = self.init_probabilities(n)\n\n n_neurons = 3\n steps = 1\n hidden = False\n size_train = int(0.6 * n)\n classifier = self.define_nn(n_neurons, hidden, m,learning_rate)\n for i in range(total_epochs):\n theta_i, eval_model,loss_and_metrics, weights = self.lr_pzi(classifier, X_train, X_test, y_train, y_test, steps)\n result = pd.DataFrame(data=np.concatenate([np.where(theta_i > 0.5, 1, 0), y_test], axis=1), columns=['classification', 'truth'])\n np.savetxt(weights_file,weights,delimiter=',')\n result.to_csv(output_file)\n metrics = pd.DataFrame(np.array(eval_model).reshape(1, 1), columns=[['accuracy']])\n with open(output_file, 'a') as f:\n metrics.to_csv(f, header=True)\n\n def nn(self, input_file,output_file,weights_file,total_epochs,learning_rate):\n simple_example = pd.read_csv(input_file, sep=\",\")\n social_features = simple_example[['follower_nbr', 'followee_nbr', 'tweets_nbr', 'avg_length_tweets']].values\n true_labels = simple_example[['label']].values\n n = social_features.shape[0]\n m = social_features.shape[1]\n # initi pzi\n p_z_i_0, p_z_i_1 = self.init_probabilities(n)\n\n n_neurons = 3\n steps = 1\n hidden = True\n size_train = int(0.8 * n)\n classifier = self.define_nn(n_neurons, hidden, m,learning_rate)\n result, eval_model, weights, metrics_names, theta_i = self.train(classifier,social_features, true_labels, p_z_i_1, total_epochs,\n steps, size_train)\n np.savetxt(weights_file,weights,delimiter=',')\n result.to_csv(output_file)\n metrics = pd.DataFrame(np.array(eval_model).reshape(1, 1), columns=[['accuracy']])\n with open(output_file, 'a') as f:\n metrics.to_csv(f, header=True)\n\n def create_multiple_input_model(self,mlp_neurons,input_dim_a,input_dim_b,class_num):\n inputA = Input(shape=input_dim_a)\n inputB = Input(shape=input_dim_b)\n\n a = Dense(mlp_neurons, activation=\"relu\")(inputA)\n a = Dense(class_num, activation=\"softmax\")(a)\n a = Model(inputs=inputA, outputs=a)\n\n b = Conv1D(64, 3, activation=\"relu\")(inputB)\n b = Conv1D(64, 3, activation=\"relu\")(b)\n b = Dropout(0.5)(b)\n b = MaxPooling1D()(b)\n b = Flatten()(b)\n b = Dense(100, activation='relu')(b)\n b = Model(inputs=inputB, outputs=b)\n\n combined = Concatenate()([a.output, b.output])\n\n c = Dense(mlp_neurons, activation=\"relu\")(combined)\n c = Dense(class_num, activation=\"softmax\")(c)\n model = Model(inputs=[a.input, b.input], outputs=c)\n model.compile(loss = 'categorical_crossentropy', optimizer='adam',metrics = ['accuracy'])\n\n return model\n\n def create_multiple_input_model_mlp(self,mlp_neurons,input_dim_a,input_dim_b,class_num):\n inputA = Input(shape=input_dim_a)\n inputB = Input(shape=input_dim_b)\n\n a = Dense(mlp_neurons, activation=\"relu\")(inputA)\n a = Dense(class_num, activation=\"relu\")(a)\n a = Model(inputs=inputA, outputs=a)\n\n b = Dense(int((input_dim_b[0] + class_num)/2), activation=\"relu\")(inputB)\n b = Dense(class_num, activation=\"relu\")(b)\n b = Model(inputs=inputB, outputs=b)\n\n combined = Concatenate()([a.output, b.output])\n\n c = Dense(int((class_num*3)/2), activation=\"relu\")(combined)\n c = Dense(class_num, activation=\"softmax\")(c)\n model = Model(inputs=[a.input, b.input], outputs=c)\n model.compile(loss = 'categorical_crossentropy', optimizer='adam',metrics = ['accuracy'])\n\n return model" ]
[ [ "tensorflow.keras.layers.Conv1D", "tensorflow.keras.layers.Dense", "tensorflow.keras.Sequential", "numpy.where", "tensorflow.keras.Model", "numpy.random.random", "pandas.read_csv", "numpy.concatenate", "numpy.linalg.norm", "tensorflow.keras.layers.MaxPooling1D", "sklearn.metrics.accuracy_score", "numpy.argmax", "numpy.random.randint", "tensorflow.keras.layers.Concatenate", "numpy.array", "numpy.savetxt", "numpy.zeros", "tensorflow.keras.layers.Dropout", "sklearn.model_selection.train_test_split", "tensorflow.keras.layers.Input", "tensorflow.keras.layers.Flatten", "tensorflow.keras.callbacks.EarlyStopping" ] ]
mickyLing/tensorflow
[ "bba3f6a4e733dfd5865dfb14943624c13a7ba9fd" ]
[ "tensorflow/python/keras/optimizer_v2/adam_test.py" ]
[ "# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for Adam.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.keras import optimizers\nfrom tensorflow.python.keras.optimizer_v2 import adam\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import resource_variable_ops\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.platform import test\n\n\ndef adam_update_numpy(param,\n g_t,\n t,\n m,\n v,\n lr=0.001,\n beta1=0.9,\n beta2=0.999,\n epsilon=1e-7):\n lr_t = lr * np.sqrt(1 - beta2**(t + 1)) / (1 - beta1**(t + 1))\n\n m_t = beta1 * m + (1 - beta1) * g_t\n v_t = beta2 * v + (1 - beta2) * g_t * g_t\n\n param_t = param - lr_t * m_t / (np.sqrt(v_t) + epsilon)\n return param_t, m_t, v_t\n\n\ndef adam_update_numpy_amsgrad(param,\n g_t,\n t,\n m,\n v,\n vhat,\n lr=0.001,\n beta1=0.9,\n beta2=0.999,\n epsilon=1e-7):\n lr_t = lr * np.sqrt(1 - beta2**(t + 1)) / (1 - beta1**(t + 1))\n\n m_t = beta1 * m + (1 - beta1) * g_t\n v_t = beta2 * v + (1 - beta2) * g_t * g_t\n vhat_t = np.maximum(vhat, v_t)\n\n param_t = param - lr_t * m_t / (np.sqrt(vhat_t) + epsilon)\n return param_t, m_t, v_t, vhat_t\n\n\ndef adam_sparse_update_numpy_amsgrad(param,\n indices,\n g_t,\n t,\n m,\n v,\n vhat,\n lr=0.001,\n beta1=0.9,\n beta2=0.999,\n epsilon=1e-7):\n m_t, v_t, vhat_t, param_t = (np.copy(m), np.copy(v), np.copy(vhat),\n np.copy(param))\n lr_t = lr * np.sqrt(1 - beta2**(t + 1)) / (1 - beta1**(t + 1))\n m_t_slice = beta1 * m[indices] + (1 - beta1) * g_t\n v_t_slice = beta2 * v[indices] + (1 - beta2) * g_t * g_t\n m_t[indices] = m_t_slice\n v_t[indices] = v_t_slice\n v_hat_t = np.maximum(vhat_t, v_t)\n v_hat_t_slice = v_hat_t[indices]\n param_t_slice = param[indices] - (\n lr_t * (m_t_slice / (np.sqrt(v_hat_t_slice) + epsilon)))\n param_t[indices] = param_t_slice\n return param_t, m_t, v_t, vhat_t\n\n\ndef get_beta_accumulators(opt, dtype):\n local_step = math_ops.cast(opt.iterations + 1, dtype)\n beta_1_t = math_ops.cast(opt._get_hyper(\"beta_1\"), dtype)\n beta_1_power = math_ops.pow(beta_1_t, local_step)\n beta_2_t = math_ops.cast(opt._get_hyper(\"beta_2\"), dtype)\n beta_2_power = math_ops.pow(beta_2_t, local_step)\n return (beta_1_power, beta_2_power)\n\n\nclass AdamOptimizerTest(test.TestCase):\n\n @test_util.run_deprecated_v1\n def testSparse(self):\n for dtype in [dtypes.half, dtypes.float32, dtypes.float64]:\n with self.cached_session():\n # Initialize variables for numpy implementation.\n m0, v0, m1, v1 = 0.0, 0.0, 0.0, 0.0\n var0_np = np.array([1.0, 1.0, 2.0], dtype=dtype.as_numpy_dtype)\n grads0_np = np.array([0.1, 0.0, 0.1], dtype=dtype.as_numpy_dtype)\n var1_np = np.array([3.0, 3.0, 4.0], dtype=dtype.as_numpy_dtype)\n grads1_np = np.array([0.01, 0.0, 0.01], dtype=dtype.as_numpy_dtype)\n\n var0 = resource_variable_ops.ResourceVariable(var0_np)\n var1 = resource_variable_ops.ResourceVariable(var1_np)\n grads0_np_indices = np.array([0, 2], dtype=np.int32)\n grads0 = ops.IndexedSlices(\n constant_op.constant(grads0_np[grads0_np_indices]),\n constant_op.constant(grads0_np_indices), constant_op.constant([3]))\n grads1_np_indices = np.array([0, 2], dtype=np.int32)\n grads1 = ops.IndexedSlices(\n constant_op.constant(grads1_np[grads1_np_indices]),\n constant_op.constant(grads1_np_indices), constant_op.constant([3]))\n opt = adam.Adam()\n update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))\n variables.global_variables_initializer().run()\n\n # Fetch params to validate initial values\n self.assertAllClose([1.0, 1.0, 2.0], self.evaluate(var0))\n self.assertAllClose([3.0, 3.0, 4.0], self.evaluate(var1))\n\n beta_1_power, beta_2_power = get_beta_accumulators(opt, dtype)\n # Run 3 steps of Adam\n for t in range(3):\n self.assertAllCloseAccordingToType(0.9**(t + 1),\n self.evaluate(beta_1_power))\n self.assertAllCloseAccordingToType(0.999**(t + 1),\n self.evaluate(beta_2_power))\n update.run()\n\n var0_np, m0, v0 = adam_update_numpy(var0_np, grads0_np, t, m0, v0)\n var1_np, m1, v1 = adam_update_numpy(var1_np, grads1_np, t, m1, v1)\n\n # Validate updated params\n self.assertAllCloseAccordingToType(var0_np, self.evaluate(var0))\n self.assertAllCloseAccordingToType(var1_np, self.evaluate(var1))\n\n @test_util.run_deprecated_v1\n def testSparseDevicePlacement(self):\n for index_dtype in [dtypes.int32, dtypes.int64]:\n with self.cached_session(force_gpu=test.is_gpu_available()):\n # If a GPU is available, tests that all optimizer ops can be placed on\n # it (i.e. they have GPU kernels).\n var = variables.Variable([[1.0], [2.0]])\n indices = constant_op.constant([0, 1], dtype=index_dtype)\n g_sum = lambda: math_ops.reduce_sum(array_ops.gather(var, indices)) # pylint: disable=cell-var-from-loop\n optimizer = adam.Adam(3.0)\n minimize_op = optimizer.minimize(g_sum, var_list=[var])\n variables.global_variables_initializer().run()\n minimize_op.run()\n\n @test_util.run_deprecated_v1\n def testSparseRepeatedIndices(self):\n for dtype in [dtypes.half, dtypes.float32, dtypes.float64]:\n with self.cached_session():\n repeated_index_update_var = variables.Variable(\n [[1.0], [2.0]], dtype=dtype)\n aggregated_update_var = variables.Variable(\n [[1.0], [2.0]], dtype=dtype)\n grad_repeated_index = ops.IndexedSlices(\n constant_op.constant(\n [0.1, 0.1], shape=[2, 1], dtype=dtype),\n constant_op.constant([1, 1]),\n constant_op.constant([2, 1]))\n grad_aggregated = ops.IndexedSlices(\n constant_op.constant(\n [0.2], shape=[1, 1], dtype=dtype),\n constant_op.constant([1]),\n constant_op.constant([2, 1]))\n repeated_update = adam.Adam().apply_gradients(\n [(grad_repeated_index, repeated_index_update_var)])\n aggregated_update = adam.Adam().apply_gradients(\n [(grad_aggregated, aggregated_update_var)])\n variables.global_variables_initializer().run()\n self.assertAllClose(aggregated_update_var.eval(),\n self.evaluate(repeated_index_update_var))\n for _ in range(3):\n repeated_update.run()\n aggregated_update.run()\n self.assertAllClose(aggregated_update_var.eval(),\n self.evaluate(repeated_index_update_var))\n\n def doTestBasic(self, use_callable_params=False):\n for i, dtype in enumerate([dtypes.half, dtypes.float32, dtypes.float64]):\n with self.session(graph=ops.Graph()):\n # Initialize variables for numpy implementation.\n m0, v0, m1, v1 = 0.0, 0.0, 0.0, 0.0\n var0_np = np.array([1.0, 2.0], dtype=dtype.as_numpy_dtype)\n grads0_np = np.array([0.1, 0.1], dtype=dtype.as_numpy_dtype)\n var1_np = np.array([3.0, 4.0], dtype=dtype.as_numpy_dtype)\n grads1_np = np.array([0.01, 0.01], dtype=dtype.as_numpy_dtype)\n\n var0 = resource_variable_ops.ResourceVariable(\n var0_np, name=\"var0_%d\" % i)\n var1 = resource_variable_ops.ResourceVariable(\n var1_np, name=\"var1_%d\" % i)\n grads0 = constant_op.constant(grads0_np)\n grads1 = constant_op.constant(grads1_np)\n\n learning_rate = lambda: 0.001\n beta1 = lambda: 0.9\n beta2 = lambda: 0.999\n epsilon = lambda: 1e-8\n if not use_callable_params:\n learning_rate = learning_rate()\n beta1 = beta1()\n beta2 = beta2()\n epsilon = epsilon()\n\n opt = adam.Adam(learning_rate=learning_rate)\n if not context.executing_eagerly():\n update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))\n\n self.evaluate(variables.global_variables_initializer())\n # Run 3 steps of Adam\n for t in range(3):\n beta_1_power, beta_2_power = get_beta_accumulators(opt, dtype)\n self.assertAllCloseAccordingToType(0.9**(t + 1),\n self.evaluate(beta_1_power))\n self.assertAllCloseAccordingToType(0.999**(t + 1),\n self.evaluate(beta_2_power))\n if not context.executing_eagerly():\n self.evaluate(update)\n else:\n opt.apply_gradients(zip([grads0, grads1], [var0, var1]))\n\n var0_np, m0, v0 = adam_update_numpy(var0_np, grads0_np, t, m0, v0)\n var1_np, m1, v1 = adam_update_numpy(var1_np, grads1_np, t, m1, v1)\n\n # Validate updated params\n self.assertAllCloseAccordingToType(var0_np, self.evaluate(var0))\n self.assertAllCloseAccordingToType(var1_np, self.evaluate(var1))\n\n @test_util.run_in_graph_and_eager_modes(reset_test=True)\n def testResourceBasic(self):\n self.doTestBasic()\n\n def testBasicCallableParams(self):\n with context.eager_mode():\n self.doTestBasic(use_callable_params=True)\n\n @test_util.run_in_graph_and_eager_modes(reset_test=True)\n def testBasicWithAmsgrad(self):\n for i, dtype in enumerate([dtypes.half, dtypes.float32, dtypes.float64]):\n with self.session(graph=ops.Graph()):\n # Initialize variables for numpy implementation.\n m0, v0, v0hat, m1, v1, v1hat = 0.0, 0.0, 0.0, 0.0, 0.0, 0.0\n var0_np = np.array([1.0, 2.0], dtype=dtype.as_numpy_dtype)\n grads0_np = np.array([0.1, 0.1], dtype=dtype.as_numpy_dtype)\n var1_np = np.array([3.0, 4.0], dtype=dtype.as_numpy_dtype)\n grads1_np = np.array([0.01, 0.01], dtype=dtype.as_numpy_dtype)\n\n var0 = resource_variable_ops.ResourceVariable(\n var0_np, name=\"var0_%d\" % i)\n var1 = resource_variable_ops.ResourceVariable(\n var1_np, name=\"var1_%d\" % i)\n grads0 = constant_op.constant(grads0_np)\n grads1 = constant_op.constant(grads1_np)\n\n opt = adam.Adam(amsgrad=True)\n if not context.executing_eagerly():\n update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))\n\n self.evaluate(variables.global_variables_initializer())\n # Run 3 steps of Adam\n for t in range(3):\n beta_1_power, beta_2_power = get_beta_accumulators(opt, dtype)\n self.assertAllCloseAccordingToType(0.9**(t + 1),\n self.evaluate(beta_1_power))\n self.assertAllCloseAccordingToType(0.999**(t + 1),\n self.evaluate(beta_2_power))\n if not context.executing_eagerly():\n self.evaluate(update)\n else:\n opt.apply_gradients(zip([grads0, grads1], [var0, var1]))\n\n var0_np, m0, v0, v0hat = adam_update_numpy_amsgrad(\n var0_np, grads0_np, t, m0, v0, v0hat)\n var1_np, m1, v1, v1hat = adam_update_numpy_amsgrad(\n var1_np, grads1_np, t, m1, v1, v1hat)\n\n # Validate updated params\n self.assertAllCloseAccordingToType(var0_np, self.evaluate(var0))\n self.assertAllCloseAccordingToType(var1_np, self.evaluate(var1))\n\n @test_util.run_in_graph_and_eager_modes\n def testSparseWithAmsgrad(self):\n # dtypes.half does not work on gpu + eager.\n for dtype in [dtypes.float32, dtypes.float64]:\n with self.cached_session():\n m0 = np.array([[0.0], [0.0]])\n v0 = np.array([[0.0], [0.0]])\n v0hat = np.array([[0.0], [0.0]])\n indices_np = np.array([1])\n indices = constant_op.constant(indices_np, dtype=dtypes.int32)\n var0_np = np.array([[1.0], [2.0]], dtype=dtype.as_numpy_dtype)\n repeated_index_update_var = variables.Variable(var0_np, dtype=dtype)\n aggregated_update_var = variables.Variable(var0_np, dtype=dtype)\n grads0_np = np.array([[0.2]], dtype=dtype.as_numpy_dtype)\n grad_repeated_index = ops.IndexedSlices(\n constant_op.constant([0.1, 0.1], shape=[2, 1], dtype=dtype),\n constant_op.constant([1, 1]), constant_op.constant([2, 1]))\n grad_aggregated = ops.IndexedSlices(grads0_np, indices,\n constant_op.constant([2, 1]))\n opt_repeated = adam.Adam(amsgrad=True)\n opt_aggregated = adam.Adam(amsgrad=True)\n if not context.executing_eagerly():\n repeated_update = opt_repeated.apply_gradients(\n [(grad_repeated_index, repeated_index_update_var)])\n aggregated_update = opt_aggregated.apply_gradients(\n [(grad_aggregated, aggregated_update_var)])\n self.evaluate(variables.global_variables_initializer())\n self.assertAllClose(\n self.evaluate(aggregated_update_var),\n self.evaluate(repeated_index_update_var))\n for t in range(3):\n if not context.executing_eagerly():\n self.evaluate(repeated_update)\n self.evaluate(aggregated_update)\n else:\n opt_repeated.apply_gradients(\n [(grad_repeated_index, repeated_index_update_var)])\n opt_aggregated.apply_gradients(\n [(grad_aggregated, aggregated_update_var)])\n\n var0_np, m0, v0, v0hat = adam_sparse_update_numpy_amsgrad(\n var0_np, indices_np, grads0_np, t, m0, v0, v0hat)\n\n # Validate updated params\n self.assertAllCloseAccordingToType(\n var0_np, self.evaluate(aggregated_update_var))\n self.assertAllCloseAccordingToType(\n self.evaluate(aggregated_update_var),\n self.evaluate(repeated_index_update_var))\n\n @test_util.run_deprecated_v1\n def testBasicWithLearningRateDecay(self):\n for i, dtype in enumerate([dtypes.half, dtypes.float32, dtypes.float64]):\n with self.session(graph=ops.Graph()):\n # Initialize variables for numpy implementation.\n m0, v0, m1, v1 = 0.0, 0.0, 0.0, 0.0\n var0_np = np.array([1.0, 2.0], dtype=dtype.as_numpy_dtype)\n grads0_np = np.array([0.1, 0.1], dtype=dtype.as_numpy_dtype)\n var1_np = np.array([3.0, 4.0], dtype=dtype.as_numpy_dtype)\n grads1_np = np.array([0.01, 0.01], dtype=dtype.as_numpy_dtype)\n\n var0 = resource_variable_ops.ResourceVariable(\n var0_np, name=\"var0_%d\" % i)\n var1 = resource_variable_ops.ResourceVariable(\n var1_np, name=\"var1_%d\" % i)\n grads0 = constant_op.constant(grads0_np)\n grads1 = constant_op.constant(grads1_np)\n\n learning_rate = 0.001\n beta_1 = 0.9\n beta_2 = 0.999\n epsilon = 1e-7\n decay = 0.5\n\n opt = adam.Adam(\n learning_rate=learning_rate,\n beta_1=beta_1,\n beta_2=beta_2,\n epsilon=epsilon,\n decay=decay)\n update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))\n\n self.evaluate(variables.global_variables_initializer())\n # Run 3 steps of Adam\n for t in range(3):\n self.evaluate(update)\n lr_np = learning_rate / (1 + decay * t)\n\n var0_np, m0, v0 = adam_update_numpy(\n var0_np, grads0_np, t, m0, v0, lr=lr_np)\n var1_np, m1, v1 = adam_update_numpy(\n var1_np, grads1_np, t, m1, v1, lr=lr_np)\n\n # Validate updated params\n self.assertAllCloseAccordingToType(var0_np, self.evaluate(var0))\n self.assertAllCloseAccordingToType(var1_np, self.evaluate(var1))\n\n @test_util.run_deprecated_v1\n def testTensorLearningRate(self):\n for dtype in [dtypes.half, dtypes.float32, dtypes.float64]:\n with self.cached_session():\n # Initialize variables for numpy implementation.\n m0, v0, m1, v1 = 0.0, 0.0, 0.0, 0.0\n var0_np = np.array([1.0, 2.0], dtype=dtype.as_numpy_dtype)\n grads0_np = np.array([0.1, 0.1], dtype=dtype.as_numpy_dtype)\n var1_np = np.array([3.0, 4.0], dtype=dtype.as_numpy_dtype)\n grads1_np = np.array([0.01, 0.01], dtype=dtype.as_numpy_dtype)\n\n var0 = variables.Variable(var0_np)\n var1 = variables.Variable(var1_np)\n grads0 = constant_op.constant(grads0_np)\n grads1 = constant_op.constant(grads1_np)\n opt = adam.Adam(constant_op.constant(0.001))\n update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))\n variables.global_variables_initializer().run()\n\n # Fetch params to validate initial values\n self.assertAllClose([1.0, 2.0], self.evaluate(var0))\n self.assertAllClose([3.0, 4.0], self.evaluate(var1))\n\n beta_1_power, beta_2_power = get_beta_accumulators(opt, dtype)\n # Run 3 steps of Adam\n for t in range(3):\n self.assertAllCloseAccordingToType(0.9**(t + 1),\n self.evaluate(beta_1_power))\n self.assertAllCloseAccordingToType(0.999**(t + 1),\n self.evaluate(beta_2_power))\n update.run()\n\n var0_np, m0, v0 = adam_update_numpy(var0_np, grads0_np, t, m0, v0)\n var1_np, m1, v1 = adam_update_numpy(var1_np, grads1_np, t, m1, v1)\n\n # Validate updated params\n self.assertAllCloseAccordingToType(var0_np, self.evaluate(var0))\n self.assertAllCloseAccordingToType(var1_np, self.evaluate(var1))\n\n @test_util.run_deprecated_v1\n def testSharing(self):\n for dtype in [dtypes.half, dtypes.float32, dtypes.float64]:\n with self.cached_session():\n # Initialize variables for numpy implementation.\n m0, v0, m1, v1 = 0.0, 0.0, 0.0, 0.0\n var0_np = np.array([1.0, 2.0], dtype=dtype.as_numpy_dtype)\n grads0_np = np.array([0.1, 0.1], dtype=dtype.as_numpy_dtype)\n var1_np = np.array([3.0, 4.0], dtype=dtype.as_numpy_dtype)\n grads1_np = np.array([0.01, 0.01], dtype=dtype.as_numpy_dtype)\n\n var0 = variables.Variable(var0_np)\n var1 = variables.Variable(var1_np)\n grads0 = constant_op.constant(grads0_np)\n grads1 = constant_op.constant(grads1_np)\n opt = adam.Adam()\n update1 = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))\n update2 = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))\n variables.global_variables_initializer().run()\n\n beta_1_power, beta_2_power = get_beta_accumulators(opt, dtype)\n\n # Fetch params to validate initial values\n self.assertAllClose([1.0, 2.0], self.evaluate(var0))\n self.assertAllClose([3.0, 4.0], self.evaluate(var1))\n\n # Run 3 steps of intertwined Adam1 and Adam2.\n for t in range(3):\n self.assertAllCloseAccordingToType(0.9**(t + 1),\n self.evaluate(beta_1_power))\n self.assertAllCloseAccordingToType(0.999**(t + 1),\n self.evaluate(beta_2_power))\n if t % 2 == 0:\n update1.run()\n else:\n update2.run()\n\n var0_np, m0, v0 = adam_update_numpy(var0_np, grads0_np, t, m0, v0)\n var1_np, m1, v1 = adam_update_numpy(var1_np, grads1_np, t, m1, v1)\n\n # Validate updated params\n self.assertAllCloseAccordingToType(var0_np, self.evaluate(var0))\n self.assertAllCloseAccordingToType(var1_np, self.evaluate(var1))\n\n def testSlotsUniqueEager(self):\n with context.eager_mode():\n v1 = resource_variable_ops.ResourceVariable(1.)\n v2 = resource_variable_ops.ResourceVariable(1.)\n opt = adam.Adam(1.)\n opt.minimize(lambda: v1 + v2, var_list=[v1, v2])\n # There should be iteration, and two unique slot variables for v1 and v2.\n self.assertEqual(5, len(set(opt.variables())))\n self.assertEqual(\n self.evaluate(opt.variables()[0]), self.evaluate(opt.iterations))\n\n def testSetWeightsFromV1AdamWithoutMinimize(self):\n keras_v1_adam = optimizers.Adam()\n keras_v2_adam = adam.Adam()\n keras_v2_adam.set_weights(keras_v1_adam.get_weights())\n keras_v1_iteration = keras_v1_adam.iterations\n keras_v2_iteration = keras_v2_adam.iterations\n self.evaluate(variables.global_variables_initializer())\n self.assertEqual(\n self.evaluate(keras_v1_iteration), self.evaluate(keras_v2_iteration))\n\n def testConstructAdamWithLR(self):\n opt = adam.Adam(lr=1.0)\n opt_2 = adam.Adam(learning_rate=0.1, lr=1.0)\n opt_3 = adam.Adam(learning_rate=0.1)\n self.assertIsInstance(opt.lr, variables.Variable)\n self.assertIsInstance(opt_2.lr, variables.Variable)\n self.assertIsInstance(opt_3.lr, variables.Variable)\n\n self.evaluate(variables.global_variables_initializer())\n self.assertAllClose(self.evaluate(opt.lr), (1.0))\n self.assertAllClose(self.evaluate(opt_2.lr), (1.0))\n self.assertAllClose(self.evaluate(opt_3.lr), (0.1))\n\n def testConstructAdamWithEpsilonValues(self):\n opt = adam.Adam(epsilon=None)\n config = opt.get_config()\n self.assertEqual(config[\"epsilon\"], 1e-7)\n\n opt = adam.Adam(epsilon=1e-8)\n config = opt.get_config()\n self.assertEqual(config[\"epsilon\"], 1e-8)\n\n\nif __name__ == \"__main__\":\n test.main()\n" ]
[ [ "tensorflow.python.ops.variables.Variable", "numpy.copy", "tensorflow.python.keras.optimizer_v2.adam.Adam", "tensorflow.python.keras.optimizers.Adam", "tensorflow.python.eager.context.executing_eagerly", "tensorflow.python.platform.test.main", "tensorflow.python.eager.context.eager_mode", "tensorflow.python.ops.math_ops.cast", "numpy.sqrt", "tensorflow.python.framework.test_util.run_in_graph_and_eager_modes", "tensorflow.python.ops.variables.global_variables_initializer", "numpy.array", "tensorflow.python.framework.ops.Graph", "tensorflow.python.ops.array_ops.gather", "tensorflow.python.platform.test.is_gpu_available", "tensorflow.python.ops.resource_variable_ops.ResourceVariable", "tensorflow.python.framework.constant_op.constant", "tensorflow.python.ops.math_ops.pow", "numpy.maximum" ] ]
Banyc/TensorFlow_practice
[ "f9b0d27cbc440d6c67dd29b94828a08f192f76e1", "f9b0d27cbc440d6c67dd29b94828a08f192f76e1" ]
[ "mnist/LeNet-5/mnist_inference.py", "mnist/test/filed/read_model_sess_reorganized.py" ]
[ "# -*- coding: utf-8 -*-\nimport tensorflow as tf\n\nINPUT_NODE = 784\nOUTPUT_NODE = 10\n\n# 28 (edge) * 28\nIMAGE_SIZE = 28\n# 黑白\nNUM_CHANNELS = 1\nNUM_LABELS = 10\n\nCONV1_DEEP = 32\n# 过滤器尺寸\nCONV1_SIZE = 5\nCONV2_DEEP = 64\nCONV2_SIZE = 5\n# num of Fully connected nodes\nFC_SIZE = 512\n\n\n# def get_weight_variable(shape, regularizer):\n# weights = tf.get_variable(\n# \"weight\", shape,\n# initializer=tf.truncated_normal_initializer(stddev=0.1))\n\n# if regularizer != None:\n# tf.add_to_collection(\"losses\", regularizer(weights)) # 这个是自定义集合,不受自动管理\n# return weights\n\n\n# def inference(input_tensor, regularizer):\n# with tf.variable_scope(\"layer1\"):\n# weights = get_weight_variable(\n# [INPUT_NODE, LAYER1_NODE], regularizer) # 注意当这行被多次运行时,记得修改 reuse=True\n# biases = tf.get_variable(\n# \"biases\", [LAYER1_NODE],\n# initializer=tf.constant_initializer(0.0))\n# layer1 = tf.nn.relu(tf.matmul(input_tensor, weights) + biases)\n\n# with tf.variable_scope(\"layer2\"):\n# weights = get_weight_variable(\n# [LAYER1_NODE, OUTPUT_NODE], regularizer) # 注意当这行被多次运行时,记得修改 reuse=True\n# biases = tf.get_variable(\n# \"biases\", [OUTPUT_NODE],\n# initializer=tf.constant_initializer(0.0))\n# layer2 = tf.matmul(layer1, weights) + biases\n\n# return layer2\n\n\ndef inference(input_tensor, train, regularizer):\n with tf.variable_scope('layer1-conv1'):\n conv1_weights = tf.get_variable( # 与 tf.Variable() 类似\n \"weight\", [CONV1_SIZE, CONV1_SIZE, NUM_CHANNELS, CONV1_DEEP], # x, y, prev-depth, depth\n initializer=tf.truncated_normal_initializer(stddev=0.1)\n )\n conv1_biases = tf.get_variable(\n \"bias\", [CONV1_DEEP], initializer=tf.constant_initializer(0.0)\n )\n\n # 过滤器:边长5,深度32,移动步长1,填充全0 \n conv1 = tf.nn.conv2d(\n input_tensor, conv1_weights, strides=[1, 1, 1, 1], padding='SAME'\n )\n relu1 = tf.nn.relu(tf.nn.bias_add(conv1, conv1_biases))\n\n # https://www.jianshu.com/p/cff8678de15a\n # 最大池化层:\n with tf.name_scope('layer2-pool1'):\n # 过滤器:边长2,移动步长2,全0填充\n pool1 = tf.nn.max_pool(\n relu1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME'\n )\n\n with tf.variable_scope('layer3-conv2'):\n conv2_weights = tf.get_variable(\n \"weight\", [CONV2_SIZE, CONV2_SIZE, CONV1_DEEP, CONV2_DEEP],\n initializer=tf.truncated_normal_initializer(stddev=0.1)\n )\n conv2_biases = tf.get_variable(\n \"bias\", [CONV2_DEEP], initializer=tf.constant_initializer(0.0)\n )\n\n conv2 = tf.nn.conv2d(\n pool1, conv2_weights, strides=[1, 1, 1, 1], padding='SAME'\n )\n relu2 = tf.nn.relu(tf.nn.bias_add(conv2, conv2_biases))\n\n with tf.name_scope('layer4-pool2'):\n pool2 = tf.nn.max_pool(\n relu2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME'\n )\n\n # as_list 拉成向量\n pool_shape = pool2.get_shape().as_list()\n\n # pool_shape[0] 为一个batch中数据的个数; 7*7*64\n nodes = pool_shape[1] * pool_shape[2] * pool_shape[3]\n\n # reshaped = tf.reshape(pool2, [pool_shape[0], nodes])\n reshaped = tf.reshape(pool2, [-1, nodes])\n\n with tf.variable_scope('layer5-fc1'):\n fc1_weights = tf.get_variable(\n \"weight\", [nodes, FC_SIZE],\n initializer=tf.truncated_normal_initializer(stddev=0.1)\n )\n if regularizer != None:\n tf.add_to_collection('losses', regularizer(fc1_weights))\n fc1_biases = tf.get_variable(\n \"bias\", [FC_SIZE], \n initializer=tf.constant_initializer(0.1)\n )\n\n fc1 = tf.nn.relu(tf.matmul(reshaped, fc1_weights) + fc1_biases)\n if train: \n fc1 = tf.nn.dropout(fc1, 0.5)\n\n with tf.variable_scope('layer6-fc2'):\n fc2_weights = tf.get_variable(\n \"weight\", [FC_SIZE, NUM_LABELS], \n initializer=tf.truncated_normal_initializer(stddev=0.1)\n )\n if regularizer != None:\n tf.add_to_collection('losses', regularizer(fc2_weights))\n fc2_biases = tf.get_variable(\n \"bias\", [NUM_LABELS],\n initializer=tf.constant_initializer(0.1)\n )\n logit = tf.matmul(fc1, fc2_weights) + fc2_biases\n\n return logit\n", "import tensorflow as tf\nfrom PIL import Image\nimport numpy as np\n\nMODEL_PATH = \"./saved_variables/mnist5.2.1.ckpt\"\nPIC_PATH = \"./pictures/4.png\"\n\nINPUT_NODE = 784 # 输入节点\nOUTPUT_NODE = 10 # 输出节点\n\nLAYER1_NODE = 500 # 隐藏层神经元数\n\n\ndef inference(input_tensor, weights1, biases1, weights2, biases2):\n layer1 = tf.nn.relu(tf.matmul(input_tensor, weights1) + biases1)\n layer2 = tf.matmul(layer1, weights2) + biases2\n return layer2\n \n\ndef Read_vars(sess, path):\n weights1 = tf.Variable(\n tf.truncated_normal([INPUT_NODE, LAYER1_NODE], stddev=0.1))\n biases1 = tf.Variable(tf.constant(0.1, shape=[LAYER1_NODE]))\n weights2 = tf.Variable(\n tf.truncated_normal([LAYER1_NODE, OUTPUT_NODE], stddev=0.1))\n biases2 = tf.Variable(tf.constant(0.1, shape=[OUTPUT_NODE]))\n\n saver = tf.train.Saver()\n\n saver.restore(sess, path)\n \n return (weights1, biases1, weights2, biases2)\n\n\ndef Print_var(sess, var1):\n # with tf.Session() as sess:\n # sess.run(tf.global_variables_initializer())\n print(var1.eval(session=sess))\n print()\n\n\ndef Import_pic(path):\n image1 = Image.open(path)\n # 读取顺序 是 逐行读取\n image1_pixels = []\n for j in range(28):\n for i in range(28):\n pixel = image1.getpixel((i, j))\n pixel = 1.0 - pixel # 背景色与前景色调换\n image1_pixels.append(pixel)\n return image1_pixels\n\n\ndef Guess(sess, image1_pixels, weights1, biases1, weights2, biases2):\n x_ = tf.placeholder(tf.float32, [None, INPUT_NODE], name=\"x_-input\")\n y = inference(x_, weights1, biases1, weights2, biases2)\n\n\n # https://blog.csdn.net/wuguangbin1230/article/details/71170903\n image_feed = np.reshape(image1_pixels, (1, -1)) # 转化为 横向量\n result_y = sess.run(y, feed_dict={x_: image_feed})\n print(result_y)\n prediction = sess.run(tf.argmax(result_y, 1))\n print(prediction)\n\n\ndef main(argv=None):\n tf.reset_default_graph()\n sess = tf.Session()\n\n weights1, biases1, weights2, biases2 = Read_vars(sess, MODEL_PATH)\n # Print_var(sess, weights1)\n image1_pixels = Import_pic(PIC_PATH)\n Guess(sess, image1_pixels, weights1, biases1, weights2, biases2)\n return 0 \n\n\nif __name__ == \"__main__\":\n main()\n\n \n\n" ]
[ [ "tensorflow.constant_initializer", "tensorflow.nn.conv2d", "tensorflow.matmul", "tensorflow.reshape", "tensorflow.variable_scope", "tensorflow.name_scope", "tensorflow.truncated_normal_initializer", "tensorflow.nn.bias_add", "tensorflow.nn.max_pool", "tensorflow.nn.dropout" ], [ "numpy.reshape", "tensorflow.argmax", "tensorflow.reset_default_graph", "tensorflow.Session", "tensorflow.train.Saver", "tensorflow.matmul", "tensorflow.truncated_normal", "tensorflow.constant", "tensorflow.placeholder" ] ]
smilelight/lightNLP
[ "772c5f6a1be9943c2ed4d1d713dd456089b48268" ]
[ "lightnlp/tg/lm/module.py" ]
[ "import torch\nfrom tqdm import tqdm\nimport torch.nn.functional as F\nfrom torch.utils.tensorboard import SummaryWriter\n\nimport flask\nfrom flask import Flask, request\n\nfrom ...utils.deploy import get_free_tcp_port\nfrom ...utils.learning import adjust_learning_rate\nfrom ...utils.log import logger\nfrom ...base.module import Module\n\nfrom .config import DEVICE, DEFAULT_CONFIG\nfrom .model import LMConfig, RNNLM\nfrom .tool import lm_tool, light_tokenize, TEXT\n\n\nclass LM(Module):\n def __init__(self):\n self._model = None\n self._word_vocab = None\n\n def train(self, train_path, save_path=DEFAULT_CONFIG['save_path'], dev_path=None, vectors_path=None, log_dir=None,\n **kwargs):\n writer = SummaryWriter(log_dir=log_dir)\n train_dataset = lm_tool.get_dataset(train_path)\n if dev_path:\n dev_dataset = lm_tool.get_dataset(dev_path)\n word_vocab = lm_tool.get_vocab(train_dataset, dev_dataset)\n else:\n word_vocab = lm_tool.get_vocab(train_dataset)\n self._word_vocab = word_vocab\n config = LMConfig(word_vocab, save_path=save_path, vector_path=vectors_path, **kwargs)\n train_iter = lm_tool.get_iterator(train_dataset, batch_size=config.batch_size,\n bptt_len=config.bptt_len)\n rnnlm = RNNLM(config)\n self._model = rnnlm\n optim = torch.optim.Adam(rnnlm.parameters(), lr=config.lr)\n for epoch in range(config.epoch):\n rnnlm.train()\n acc_loss = 0\n for item in tqdm(train_iter):\n optim.zero_grad()\n logits = rnnlm(item.text)\n item_loss = F.cross_entropy(logits, item.target.view(-1))\n acc_loss += item_loss.item()\n item_loss.backward()\n optim.step()\n logger.info('epoch: {}, acc_loss: {}'.format(epoch, acc_loss))\n writer.add_scalar('lm_train/acc_loss', acc_loss, epoch)\n if dev_path:\n dev_score = self._validate(dev_dataset)\n logger.info('dev score:{}'.format(dev_score))\n writer.add_scalar('lm_train/dev_score', dev_score, epoch)\n writer.flush()\n adjust_learning_rate(optim, config.lr / (1 + (epoch + 1) * config.lr_decay))\n writer.close()\n config.save()\n rnnlm.save()\n\n def load(self, save_path=DEFAULT_CONFIG['save_path']):\n config = LMConfig.load(save_path)\n rnnlm = RNNLM(config)\n rnnlm .load()\n self._model = rnnlm\n self._word_vocab = config.word_vocab\n\n def test(self, test_path):\n test_dataset = lm_tool.get_dataset(test_path)\n if not hasattr(TEXT, 'vocab'):\n TEXT.vocab = self._word_vocab\n test_score = self._validate(test_dataset)\n logger.info('test score:{}'.format(test_score))\n\n def _validate(self, dev_dataset):\n self._model.eval()\n dev_score_list = []\n dev_iter = lm_tool.get_iterator(dev_dataset, batch_size=DEFAULT_CONFIG['batch_size'],\n bptt_len=DEFAULT_CONFIG['bptt_len'])\n for dev_item in tqdm(dev_iter):\n item_score = lm_tool.get_score(self._model, dev_item.text, dev_item.target)\n dev_score_list.append(item_score)\n # print(dev_score_list)\n return sum(dev_score_list) / len(dev_score_list)\n\n def _predict_next_word_max(self, sentence_list: list):\n test_item = torch.tensor([[self._word_vocab.stoi[x]] for x in sentence_list], device=DEVICE)\n pred_prob, pred_index = torch.max(torch.softmax(self._model(test_item)[-1], dim=0).cpu().data, dim=0)\n pred_word = TEXT.vocab.itos[pred_index]\n pred_prob = pred_prob.item()\n return pred_word, pred_prob\n\n def _predict_next_word_sample(self, sentence_list: list):\n # 进行分布式采样,以获得随机结果\n test_item = torch.tensor([[self._word_vocab.stoi[x]] for x in sentence_list], device=DEVICE)\n pred_index = torch.multinomial(torch.softmax(self._model(test_item)[-1], dim=0).cpu().data, 1)\n pred_word = self._word_vocab.itos[pred_index]\n return pred_word\n\n def _predict_next_word_topk(self, sentence_list: list, topK=5):\n # 获取topK个next个词的可能取值和对应概率\n test_item = torch.tensor([[self._word_vocab.stoi[x]] for x in sentence_list], device=DEVICE)\n predict_softmax = torch.softmax(self._model(test_item)[-1], dim=0).cpu().data\n topK_prob, topK_index = torch.topk(predict_softmax, topK)\n topK_prob = topK_prob.tolist()\n topK_vocab = [self._word_vocab.itos[x] for x in topK_index]\n return list(zip(topK_vocab, topK_prob))\n\n def _predict_next_word_prob(self, sentence_list: list, next_word: str):\n test_item = torch.tensor([[self._word_vocab.stoi[x]] for x in sentence_list], device=DEVICE)\n predict_prob = torch.softmax(self._model(test_item)[-1], dim=0).cpu().data\n next_word_index = self._word_vocab.stoi[next_word]\n return predict_prob[next_word_index]\n\n def next_word(self, sentence: str, next_word: str):\n self._model.eval()\n temp_str = [x for x in light_tokenize(sentence)]\n predict_prob = self._predict_next_word_prob(temp_str, next_word)\n return predict_prob.item()\n\n def _next_word_score(self, sentence: str, next_word: str):\n self._model.eval()\n temp_str = [x for x in light_tokenize(sentence)]\n predict_prob = self._predict_next_word_prob(temp_str, next_word)\n return torch.log10(predict_prob).item()\n\n def next_word_topk(self, sentence: str, topK=5):\n self._model.eval()\n return self._predict_next_word_topk(sentence, topK)\n\n def sentence_score(self, sentence: str):\n self._model.eval()\n total_score = 0\n assert len(sentence) > 1\n for i in range(1, len(sentence)):\n temp_score = self._next_word_score(sentence[:i], sentence[i])\n total_score += temp_score\n return total_score\n\n def _predict_sentence(self, sentence: str, gen_len=30):\n results = []\n temp_str = [x for x in light_tokenize(sentence)]\n for i in range(gen_len):\n temp_result = self._predict_next_word_sample(temp_str)\n results.append(temp_result)\n temp_str.append(temp_result)\n return results\n\n def generate_sentence(self, sentence: str, gen_len=30):\n self._model.eval()\n results = self._predict_sentence(sentence, gen_len)\n predict_sen = ''.join([x for x in results])\n return sentence + predict_sen\n\n def deploy(self, route_path=\"/lm\", host=\"localhost\", port=None, debug=False):\n app = Flask(__name__)\n\n @app.route(route_path + \"/next_word\", methods=['POST', 'GET'])\n def next_word():\n sentence = request.args.get('sentence', '')\n word = request.args.get('word', '')\n result = self.next_word(sentence, word)\n return flask.jsonify({\n 'state': 'OK',\n 'result': {\n 'prob': result\n }\n })\n\n @app.route(route_path + \"/generate_sentence\", methods=['POST', 'GET'])\n def generate_sentence():\n sentence = request.args.get('sentence', '')\n gen_len = int(request.args.get('gen_len', 30))\n result = self.generate_sentence(sentence, gen_len)\n return flask.jsonify({\n 'state': 'OK',\n 'result': {\n 'sentence': result\n }\n })\n\n @app.route(route_path + \"/next_word_topk\", methods=['POST', 'GET'])\n def next_word_topk():\n sentence = request.args.get('sentence', '')\n topk = int(request.args.get('topk', 5))\n result = self.next_word_topk(sentence, topK=topk)\n return flask.jsonify({\n 'state': 'OK',\n 'result': {\n 'words': result\n }\n })\n\n @app.route(route_path + \"/sentence_score\", methods=['POST', 'GET'])\n def sentence_score():\n sentence = request.args.get('sentence', '')\n result = self.sentence_score(sentence)\n return flask.jsonify({\n 'state': 'OK',\n 'result': {\n 'score': result\n }\n })\n\n if not port:\n port = get_free_tcp_port()\n app.run(host=host, port=port, debug=debug)\n" ]
[ [ "torch.log10", "torch.tensor", "torch.utils.tensorboard.SummaryWriter", "torch.topk" ] ]
liuximarcus/GewitterGefahr
[ "d819874d616f98a25187bfd3091073a2e6d5279e" ]
[ "gewittergefahr/plotting/feature_map_plotting.py" ]
[ "\"\"\"Plotting methods for CNN feature maps.\"\"\"\n\nimport numpy\nimport matplotlib\nmatplotlib.use('agg')\nimport matplotlib.pyplot as pyplot\nfrom gewittergefahr.gg_utils import error_checking\nfrom gewittergefahr.plotting import plotting_utils\n\nDEFAULT_FIG_WIDTH_INCHES = 15\nDEFAULT_FIG_HEIGHT_INCHES = 15\nDEFAULT_FONT_SIZE = 20\n\n\ndef plot_2d_feature_map(\n feature_matrix, axes_object, colour_map_object,\n font_size=DEFAULT_FONT_SIZE, colour_norm_object=None,\n min_colour_value=None, max_colour_value=None, annotation_string=None):\n \"\"\"Plots 2-D feature map.\n\n M = number of rows in grid\n N = number of columns in grid\n\n :param feature_matrix: M-by-N numpy array of feature values (either before\n or after activation function -- this method doesn't care).\n :param axes_object: Instance of `matplotlib.axes._subplots.AxesSubplot`.\n :param font_size: Font size for annotation.\n :param colour_map_object: Instance of `matplotlib.pyplot.cm`.\n :param colour_norm_object: Instance of `matplotlib.colors.BoundaryNorm`.\n :param min_colour_value: [used only if `colour_norm_object is None`]\n Minimum value in colour scheme.\n :param max_colour_value: [used only if `colour_norm_object is None`]\n Max value in colour scheme.\n :param annotation_string: Annotation (printed in the bottom-center of the\n map). For no annotation, leave this alone.\n \"\"\"\n\n error_checking.assert_is_numpy_array_without_nan(feature_matrix)\n error_checking.assert_is_numpy_array(feature_matrix, num_dimensions=2)\n\n if colour_norm_object is None:\n error_checking.assert_is_greater(max_colour_value, min_colour_value)\n colour_norm_object = None\n else:\n if hasattr(colour_norm_object, 'boundaries'):\n min_colour_value = colour_norm_object.boundaries[0]\n max_colour_value = colour_norm_object.boundaries[-1]\n else:\n min_colour_value = colour_norm_object.vmin\n max_colour_value = colour_norm_object.vmax\n\n axes_object.pcolormesh(\n feature_matrix, cmap=colour_map_object, norm=colour_norm_object,\n vmin=min_colour_value, vmax=max_colour_value, shading='flat',\n edgecolors='None')\n\n if annotation_string is not None:\n error_checking.assert_is_string(annotation_string)\n\n axes_object.text(\n 0.5, 0.01, annotation_string, fontsize=font_size, fontweight='bold',\n color='black', horizontalalignment='center',\n verticalalignment='bottom', transform=axes_object.transAxes)\n\n axes_object.set_xticks([])\n axes_object.set_yticks([])\n\n\ndef plot_many_2d_feature_maps(\n feature_matrix, annotation_string_by_panel, num_panel_rows,\n colour_map_object, colour_norm_object=None, min_colour_value=None,\n max_colour_value=None, figure_width_inches=DEFAULT_FIG_WIDTH_INCHES,\n figure_height_inches=DEFAULT_FIG_HEIGHT_INCHES,\n font_size=DEFAULT_FONT_SIZE):\n \"\"\"Plots many 2-D feature maps in the same figure (one per panel).\n\n M = number of rows in spatial grid\n N = number of columns in spatial grid\n P = number of panels\n\n :param feature_matrix: M-by-N-by-P numpy array of feature values (either\n before or after activation function -- this method doesn't care).\n :param annotation_string_by_panel: length-P list of annotations.\n annotation_string_by_panel[k] will be printed in the bottom-center of\n the [k]th panel.\n :param num_panel_rows: Number of panel rows.\n :param colour_map_object: See doc for `plot_2d_feature_map`.\n :param colour_norm_object: Same.\n :param min_colour_value: Same.\n :param max_colour_value: Same.\n :param figure_width_inches: Figure width.\n :param figure_height_inches: Figure height.\n :param font_size: Font size for panel labels.\n :return: figure_object: See doc for `plotting_utils.create_paneled_figure`.\n :return: axes_object_matrix: Same.\n \"\"\"\n\n pyplot.rc('axes', linewidth=3)\n error_checking.assert_is_numpy_array(feature_matrix, num_dimensions=3)\n\n num_panels = feature_matrix.shape[-1]\n error_checking.assert_is_numpy_array(\n numpy.array(annotation_string_by_panel),\n exact_dimensions=numpy.array([num_panels])\n )\n\n error_checking.assert_is_integer(num_panel_rows)\n error_checking.assert_is_geq(num_panel_rows, 1)\n error_checking.assert_is_leq(num_panel_rows, num_panels)\n\n num_panel_columns = int(numpy.ceil(\n float(num_panels) / num_panel_rows\n ))\n\n figure_object, axes_object_matrix = plotting_utils.create_paneled_figure(\n num_rows=num_panel_rows, num_columns=num_panel_columns,\n figure_width_inches=figure_width_inches,\n figure_height_inches=figure_height_inches,\n horizontal_spacing=0., vertical_spacing=0.,\n shared_x_axis=False, shared_y_axis=False, keep_aspect_ratio=False)\n\n for i in range(num_panel_rows):\n for j in range(num_panel_columns):\n this_linear_index = i * num_panel_columns + j\n\n if this_linear_index >= num_panels:\n axes_object_matrix[i, j].axis('off')\n continue\n\n plot_2d_feature_map(\n feature_matrix=feature_matrix[..., this_linear_index],\n axes_object=axes_object_matrix[i, j], font_size=font_size,\n colour_map_object=colour_map_object,\n colour_norm_object=colour_norm_object,\n min_colour_value=min_colour_value,\n max_colour_value=max_colour_value,\n annotation_string=annotation_string_by_panel[this_linear_index]\n )\n\n return figure_object, axes_object_matrix\n\n\ndef plot_many_1d_feature_maps(\n feature_matrix, colour_map_object, colour_norm_object=None,\n min_colour_value=None, max_colour_value=None,\n figure_width_inches=DEFAULT_FIG_WIDTH_INCHES,\n figure_height_inches=DEFAULT_FIG_HEIGHT_INCHES):\n \"\"\"Plots many 1-D feature maps in the same figure (one per column).\n\n N = number of points in spatial grid\n C = number of channels\n\n :param feature_matrix: N-by-C numpy array of feature values.\n :param colour_map_object: See doc for `plot_many_2d_feature_maps`.\n :param colour_norm_object: Same.\n :param min_colour_value: Same.\n :param max_colour_value: Same.\n :param figure_width_inches: Same.\n :param figure_height_inches: Same.\n :return: figure_object: See doc for `plotting_utils.create_paneled_figure`.\n :return: axes_object_matrix: Same.\n \"\"\"\n\n pyplot.rc('axes', linewidth=1)\n error_checking.assert_is_numpy_array(feature_matrix, num_dimensions=2)\n\n num_channels = feature_matrix.shape[1]\n num_spatial_points = feature_matrix.shape[0]\n\n figure_object, axes_object_matrix = plotting_utils.create_paneled_figure(\n num_rows=1, num_columns=num_channels,\n figure_width_inches=figure_width_inches,\n figure_height_inches=figure_height_inches,\n horizontal_spacing=0., vertical_spacing=0.,\n shared_x_axis=False, shared_y_axis=False, keep_aspect_ratio=False)\n\n for k in range(num_channels):\n this_matrix = numpy.reshape(\n feature_matrix[..., k], (num_spatial_points, 1)\n )\n\n plot_2d_feature_map(\n feature_matrix=this_matrix, axes_object=axes_object_matrix[0, k],\n font_size=30, colour_map_object=colour_map_object,\n colour_norm_object=colour_norm_object,\n min_colour_value=min_colour_value,\n max_colour_value=max_colour_value,\n annotation_string=''\n )\n\n return figure_object, axes_object_matrix\n" ]
[ [ "matplotlib.use", "numpy.array", "numpy.reshape", "matplotlib.pyplot.rc" ] ]
bstadlbauer/panel
[ "c4c8255dfb1bb28b239067548bdd425f5d07bb5c" ]
[ "panel/tests/util.py" ]
[ "from __future__ import absolute_import, division, unicode_literals\n\nimport sys\n\nimport numpy as np\nimport pytest\n\ntry:\n import holoviews as hv\nexcept Exception:\n hv = None\nhv_available = pytest.mark.skipif(hv is None, reason=\"requires holoviews\")\n\ntry:\n import matplotlib as mpl\n mpl.use('Agg')\nexcept Exception:\n mpl = None\nmpl_available = pytest.mark.skipif(mpl is None, reason=\"requires matplotlib\")\n\ntry:\n import pandas as pd\nexcept Exception:\n pd = None\npd_available = pytest.mark.skipif(pd is None, reason=\"requires pandas\")\n\ntry:\n import streamz\nexcept Exception:\n streamz = None\nstreamz_available = pytest.mark.skipif(streamz is None, reason=\"requires streamz\")\n\ntry:\n import jupyter_bokeh\nexcept Exception:\n jupyter_bokeh = None\njb_available = pytest.mark.skipif(jupyter_bokeh is None, reason=\"requires jupyter_bokeh\")\n\npy3_only = pytest.mark.skipif(sys.version_info.major < 3, reason=\"requires Python 3\")\n\n\ndef mpl_figure():\n import matplotlib.pyplot as plt\n fig = plt.figure()\n ax = fig.add_subplot(111)\n ax.plot(np.random.rand(10, 2))\n plt.close(fig)\n return fig\n\n\ndef check_layoutable_properties(layoutable, model):\n layoutable.background = '#ffffff'\n assert model.background == '#ffffff'\n\n layoutable.css_classes = ['custom_class']\n assert model.css_classes == ['custom_class']\n\n layoutable.width = 500\n assert model.width == 500\n\n layoutable.height = 450\n assert model.height == 450\n\n layoutable.min_height = 300\n assert model.min_height == 300\n\n layoutable.min_width = 250\n assert model.min_width == 250\n\n layoutable.max_height = 600\n assert model.max_height == 600\n\n layoutable.max_width = 550\n assert model.max_width == 550\n\n layoutable.margin = 10\n assert model.margin == (10, 10, 10, 10)\n\n layoutable.sizing_mode = 'stretch_width'\n assert model.sizing_mode == 'stretch_width'\n\n layoutable.width_policy = 'max'\n assert model.width_policy == 'max'\n\n layoutable.height_policy = 'min'\n assert model.height_policy == 'min'\n" ]
[ [ "matplotlib.use", "numpy.random.rand", "matplotlib.pyplot.close", "matplotlib.pyplot.figure" ] ]
lgvaz/dqn
[ "b9961a9930b858d42ea69a3e27cad1bbb1ec04c6" ]
[ "rlbox/models/value_graphs.py" ]
[ "import tensorflow as tf\n\n\ndef dense_value_graph(inputs, activation_fn=tf.nn.tanh, scope='value_graph', reuse=None):\n with tf.variable_scope(scope, reuse=reuse):\n net = inputs\n net = tf.contrib.layers.flatten(net)\n net = tf.layers.dense(net, 64, activation=activation_fn)\n net = tf.layers.dense(net, 64, activation=activation_fn)\n state_value = tf.layers.dense(net, 1)\n\n return tf.squeeze(state_value)\n" ]
[ [ "tensorflow.variable_scope", "tensorflow.contrib.layers.flatten", "tensorflow.squeeze", "tensorflow.layers.dense" ] ]
alvarodemig/AlgorithmsPerformanceComparison
[ "22af010be047422c5c561e68e5a8cece5580c3f0" ]
[ "AlgPerformComparison.py" ]
[ "import pandas as pd\nimport os\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import roc_curve, auc\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import precision_recall_curve\nfrom sklearn.metrics import average_precision_score\nimport time\n\n#Criteo's CTR Prediction Challenge\n\n#Creating a list of the numerical and categorical variables\nintnames = []\ncatnames = []\nfor i in range(13):\n intnames += ['i'+ str(i+1)]\nfor i in range(26):\n catnames += ['c'+ str(i+1)]\ncolnames = ['clicked'] + intnames + catnames\n\n#Load Data (500,000 rows) and name columns\nds = pd.read_csv(\"train.txt\", nrows=500000, sep='\\t', header=None, names = colnames)\n\n#Basic info of dataset\nds.info()\nds['clicked'].mean()\n\n#Number of categories per each category variable\ncategoriesPerVariable = {}\nfor var in catnames:\n varList = ds[var].tolist()\n varUnique = set(varList)\n print(var, len(varUnique))\n categoriesPerVariable[var] = len(varUnique)\n\ncatnamesFinal = []\n#Delete variables with more than 100 categories\nfor var in categoriesPerVariable:\n if categoriesPerVariable[var] > 100:\n ds = ds.drop(var, 1)\n print(var, 'DELETED')\n else: catnamesFinal += [var]\n\nds.info()\n\n#Create dummy variables:\nfor var in catnamesFinal:\n ds = pd.concat([ds, pd.get_dummies(ds[var], prefix = var, prefix_sep = '_')], axis=1)\n ds = ds.drop(var, axis=1)\n print('Created dummy variables for: ', var)\n \nds.shape\n\n#Creating train and test datasets\ny = ds.clicked\nx_cols = set(ds.columns)\nx_cols.remove('clicked')\nX = ds[list(x_cols)]\n\n#Train, test and Validation Sets (60%, 20%, 20%)\nX_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.6)\nX_test, X_val, y_test, y_val = train_test_split(X_test, y_test, train_size=0.5)\n\n#More Preprocessing\n# - Fill NaN values in X_train, X_test, X_val with the mean of X_train\nX_train[intnames] = X_train[intnames].fillna(X_train[intnames].mean())\nX_test[intnames] = X_test[intnames].fillna(X_train[intnames].mean())\nX_val[intnames] = X_val[intnames].fillna(X_train[intnames].mean())\n\n#Dataset with PCA\n#Choosing the number of components\nfrom sklearn.decomposition import PCA\nfor e in range(10):\n pca1 = PCA(n_components=e)\n pca1.fit(X_train)\n exp_var = 0\n for i in pca1.explained_variance_ratio_:\n exp_var += i\n print(e, round(exp_var,3))\n\npca = PCA(n_components=5)\npca.fit(X_train)\nX_train_PCA = pd.DataFrame(pca.transform(X_train))\nX_test_PCA = pd.DataFrame(pca.transform(X_test))\nX_val_PCA = pd.DataFrame(pca.transform(X_val))\n\n'''\n###########################################\n# FUNCTIONS\n###########################################\n''' \n\ndef ROCcurve(y_pred, y_test):\n# Compute ROC curve and ROC area for each class\n n_classes = y_pred.shape[1]\n fpr = dict()\n tpr = dict()\n roc_auc = dict()\n \n y_test1 = []\n for index, row in y_test.iteritems():\n if row == 0: y_test1 += [[1,0]]\n else: y_test1 += [[0,1]]\n y_test1 = np.array(y_test1)\n \n for i in range(n_classes):\n fpr[i], tpr[i], _ = roc_curve(y_test1[:,i], y_pred[:,i])\n roc_auc[i] = auc(fpr[i], tpr[i])\n \n # Compute micro-average ROC curve and ROC area\n fpr[\"micro\"], tpr[\"micro\"], _ = roc_curve(y_test1.ravel(), y_pred.ravel())\n roc_auc[\"micro\"] = auc(fpr[\"micro\"], tpr[\"micro\"])\n return fpr, tpr, roc_auc\n\n#Precision Recall Curve\ndef precision_recall(y_test, y_pred):\n ydp = []\n for i in range(len(y_pred)): ydp+= [y_pred[i][1]]\n precision, recall, _ = precision_recall_curve(y_test, ydp)\n return precision, recall\n\ndef ypd(y_pred):\n ydp = []\n for i in range(len(y_pred)): ydp+= [y_pred[i][1]]\n return ydp \n\n#Return all the Algorithm Curves Info\ndef algorithmCurvesInfo(alg_name, y_pred, y_test):\n algDict = {}\n algDict['alg_name'] = alg_name\n algDict['fpr'], algDict['tpr'], \\\n algDict['roc_auc'] = ROCcurve(y_pred, y_test)\n algDict['precision'], algDict['recall'], = precision_recall(y_test, y_pred)\n algDict['average_precision'] = average_precision_score(y_test, ypd(y_pred))\n return algDict\n\n#PLOT ROC CURVE\ndef plotROC(alg_fpr_tpr_rocDict, color_paletteList, tuple_size, path_name):\n colors = []\n for p in color_paletteList:\n for c in plt.get_cmap(p).colors:\n colors += [c]\n #Dict with key --> name of algorithm (dict)\n #Each algorithm dict:\n # - fpr\n # - tpr\n # - roc_auc\n # - alg_name: algorithm name to be shown\n plt.figure(figsize=tuple_size)\n col = 0\n for al in alg_fpr_tpr_rocDict:\n fpr = alg_fpr_tpr_rocDict[al]['fpr']\n tpr = alg_fpr_tpr_rocDict[al]['tpr']\n roc_auc = alg_fpr_tpr_rocDict[al]['roc_auc']\n alg_name = alg_fpr_tpr_rocDict[al]['alg_name']\n plt.plot(fpr[1], tpr[1], color= colors[col], alpha = 0.7, \n label= alg_name + ' (area = %0.3f)' % roc_auc[1])\n col += 1\n \n plt.plot([0, 1], [0, 1], color='black', linestyle='--')\n plt.xlim([0.0, 1.0])\n plt.ylim([0.0, 1.0]) \n plt.xlabel('False Positive Rate')\n plt.ylabel('True Positive Rate')\n plt.title('ROC curves per each algorithm')\n plt.legend(loc=\"lower right\")\n plt.savefig(path_name + '_ROC-AUC.png')\n plt.show()\n\n#Plot the Precision-Recall Curve\ndef plotPrecisionRecall(alg_pre_recDict, color_paletteList, tuple_size, path_name):\n colors = []\n for p in color_paletteList:\n for c in plt.get_cmap(p).colors:\n colors += [c]\n col = 0\n plt.figure(figsize=tuple_size)\n for al in alg_pre_recDict:\n recall = alg_pre_recDict[al]['recall']\n precision = alg_pre_recDict[al]['precision']\n average_precision = alg_pre_recDict[al]['average_precision']\n alg_name = alg_pre_recDict[al]['alg_name']\n '''\n plt.step(recall, precision, color=colors[col], alpha=0.8, where='post', \\\n label= alg_name + ' (area = %0.3f)'.format(average_precision))\n '''\n plt.plot(recall, precision, color=colors[col], alpha=0.8, \\\n label= alg_name + ' (area = %0.3f)' % average_precision)\n col += 1\n\n plt.xlabel('Recall')\n plt.ylabel('Precision')\n plt.ylim([0.0, 1.0])\n plt.xlim([0.0, 1.0])\n plt.legend(loc=\"upper right\")\n plt.title('Precision-Recall curve for CLICKED')\n plt.savefig(path_name + '_PrecisionRecall.png')\n plt.show()\n\n#Algorithm Process Automation\ndef algorithmAutomat(algorithm, X_train, y_train, X_test, name):\n algDict = {}\n train_s = time.time()\n algorithm.fit(X_train, y_train)\n train_e = time.time()\n pred_s = time.time()\n y_pred = algorithm.predict_proba(X_test)\n pred_e = time.time()\n algDict = algorithmCurvesInfo(name, y_pred, y_test)\n algDict['train_time'] = round(train_e - train_s,2)\n algDict['predict_time'] = round(pred_e - pred_s,2)\n algDict['model'] = algorithm\n print(name + ' Prediction calculated')\n print('Elapsed time: ' + str(round(pred_e-train_s,2)) + ' seconds')\n return algDict\n\n#Algorithm Validation Prediction and Curves\ndef algorithmValidation(model, X_validation, y_validation, name):\n algDict = {}\n start = time.time()\n y_pred = model.predict_proba(X_validation)\n end = time.time()\n algDict = algorithmCurvesInfo(name, y_pred, y_validation)\n algDict['prediction_time'] = end - start\n print(name + ' Prediction calculated')\n return algDict\n\n\n'''\n###########################################\n# ALGORITHMS\n###########################################\n''' \n#Path where I will save the ROC and Precision-Recall curves\npath = os.getcwd() + '/graphs/'\n\n#Dictionaries to save algorithms' results for dataset with and without PCA\nalgs = {}\nalgsPCA = {}\n\n######################################\n# Logistic Regression\n######################################\nfrom sklearn.linear_model import LogisticRegression\n\n#Parameter tuning options\nregularizers = ['l1', 'l2']\nC = [0.001,0.01,0.1,1,10,100,1000]\n\nalgs['lr'] = {}\nfor r in regularizers:\n for c in C:\n #Algorithm name based on tuning options\n name = 'LogReg_' + str(r) + '_' + str(c)\n logreg = LogisticRegression(penalty = r, C = c ,random_state = 0)\n algs['lr'][name] = algorithmAutomat(logreg, X_train, y_train, X_test, name)\n\nalgsPCA['lr'] = {}\nfor r in regularizers:\n for c in C:\n name = 'LogRegPCA_' + str(r) + '_' + str(c)\n logreg = LogisticRegression(penalty = r, C = c ,random_state = 0)\n algsPCA['lr'][name] = algorithmAutomat(logreg, X_train_PCA, y_train, X_test_PCA, name)\n\n#Plots\nplotROC(algs['lr'], ['Set1', 'Set2', 'Set3'], (10,8), path + 'LR')\nplotROC(algsPCA['lr'], ['Set1', 'Set2', 'Set3'], (10,8), path + 'LRpca')\nplotPrecisionRecall(algs['lr'], ['Set1', 'Set2', 'Set3'], (10,8), path + 'LR')\nplotPrecisionRecall(algsPCA['lr'], ['Set1', 'Set2', 'Set3'], (10,8), path + 'LRpca')\n\n######################################\n# Random Forest\n######################################\nfrom sklearn.ensemble import RandomForestClassifier\n\nn_estim = [2, 10, 50, 100, 1000]\nmax_d = [None, 2, 5, 10, 50]\n\nalgsPCA['rf'] = {}\nfor n in n_estim:\n for m in max_d:\n name = 'RandForPCA_est' + str(n) + '_depth' + str(m)\n rf = RandomForestClassifier(n_estimators = n, max_depth=m, random_state=0)\n algsPCA['lr'][name] = algorithmAutomat(rf, X_train_PCA, y_train, X_test_PCA, name)\n\nalgs['rf'] = {}\nfor n in n_estim:\n for m in max_d:\n name = 'RandFor_est' + str(n) + '_depth' + str(m) \n rf = RandomForestClassifier(n_estimators = n, max_depth=m, random_state=0)\n algs['rf'][name] = algorithmAutomat(rf, X_train, y_train, X_test, name)\n\nplotROC(algs['rf'], ['Set1', 'Set2', 'Set3'], (10,8), path + 'RF')\nplotROC(algsPCA['rf'], ['Set1', 'Set2', 'Set3'], (10,8), path + 'RFpca')\nplotPrecisionRecall(algs['rf'], ['Set1', 'Set2', 'Set3'], (10,8), path + 'RF')\nplotPrecisionRecall(algsPCA['rf'], ['Set1', 'Set2', 'Set3'], (10,8), path + 'RFpca')\n\n######################################\n# K-nearest neighbors\n######################################\nfrom sklearn.neighbors import KNeighborsClassifier\n\nalgsPCA['knn'] = {}\n\nfor k in [5, 10, 20, 50, 100, 200]:\n name = 'KNN_PCA_' + str(k)\n knn = KNeighborsClassifier(n_neighbors=k)\n algsPCA['knn'][name] = algorithmAutomat(knn, X_train_PCA, y_train, X_test_PCA, name)\n \nalgs['knn'] = {}\n\nfor k in [5, 10, 20, 50, 100, 200]:\n name = 'KNN_' + str(k)\n knn = KNeighborsClassifier(n_neighbors=k)\n algs['knn'][name] = algorithmAutomat(knn, X_train, y_train, X_test, name)\n\nplotROC(algs['knn'], ['Set1', 'Set2', 'Set3'], (10,8), path + 'KNN')\nplotROC(algs['knn']['knn'], ['Set1', 'Set2', 'Set3'], (10,8), path + 'KNNpca')\nplotPrecisionRecall(algs['knn'], ['Set1', 'Set2', 'Set3'], (10,8), path + 'KNN')\nplotPrecisionRecall(algs['knn']['knn'], ['Set1', 'Set2', 'Set3'], (10,8), path + 'KNNpca')\n\n######################################\n# Naive Bayes\n######################################\nfrom sklearn.naive_bayes import GaussianNB\n\nalgsPCA['nbayes'] = {}\nalgs['nbayes'] = {}\n\ngnb = GaussianNB()\nname = 'NaiveBayes_PCA'\nalgsPCA['nbayes'][name] = algorithmAutomat(gnb, X_train_PCA, y_train, X_test_PCA, name)\n\nalgs['nbayes'] = {}\ngnb = GaussianNB()\nname = 'NaiveBayes'\nalgs['nbayes'][name] = algorithmAutomat(gnb, X_train, y_train, X_test, name)\n\nplotROC(algs['nbayes'], ['Set1', 'Set2', 'Set3'], (10,8), path + 'NB')\nplotPrecisionRecall(algs['nbayes'], ['Set1', 'Set2', 'Set3'], (10,8), path + 'NB')\nplotROC(algsPCA['nbayes'], ['Set1', 'Set2', 'Set3'], (10,8), path + 'NB')\nplotPrecisionRecall(algsPCA['nbayes'], ['Set1', 'Set2', 'Set3'], (10,8), path + 'NBpca')\n\n######################################\n# AdaBoost\n######################################\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom sklearn.tree import DecisionTreeClassifier\n\nn_estim = [2, 10, 50]\nmax_d = [2, 10, 50, None]\n\nalgsPCA['adab'] = {}\nfor n in n_estim:\n for m in max_d:\n name = 'AdaBoost_PCA_est' + str(n) + '_depth' + str(m)\n bdt = AdaBoostClassifier(DecisionTreeClassifier(max_depth=m),\n algorithm=\"SAMME\", n_estimators=n)\n algsPCA['adab'][name] = algorithmAutomat(bdt, X_train_PCA, y_train, X_test_PCA, name)\n \nalgs['adab'] = {}\nfor n in n_estim:\n for m in max_d:\n name = 'AdaBoost_est' + str(n) + '_depth' + str(m)\n bdt = AdaBoostClassifier(DecisionTreeClassifier(max_depth=m),\n algorithm=\"SAMME\", n_estimators=n)\n algs['adab'][name] = algorithmAutomat(bdt, X_train, y_train, X_test, name) \n\nplotROC(algs['adab'], ['Set1', 'Set2', 'Set3'], (10,8), path + 'AB')\nplotROC(algsPCA['adab'], ['Set1', 'Set2', 'Set3'], (10,8), path + 'ABpca')\nplotPrecisionRecall(algs['adab'], ['Set1', 'Set2', 'Set3'], (10,8), path + 'AB')\nplotPrecisionRecall(algsPCA['adab'], ['Set1', 'Set2', 'Set3'], (10,8), path + 'ABpca')\n\n######################################\n# Linear Discriminant Analysis\n######################################\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA\n\nalgsPCA['lda'] = {}\nlda = LDA()\nname = 'LDA_PCA'\nalgsPCA['lda'] [name] = algorithmAutomat(lda, X_train_PCA, y_train, X_test_PCA, name)\n\nalgs['lda'] = {}\nlda = LDA()\nname = 'LDA'\nalgs['lda'][name] = algorithmAutomat(lda, X_train, y_train, X_test, name)\n\nplotROC(algs['lda'], ['Set1', 'Set2', 'Set3'], (10,8), path + 'LDA')\nplotPrecisionRecall(algs['lda'], ['Set1', 'Set2', 'Set3'], (10,8), path + 'LDA')\nplotROC(algsPCA['lda'], ['Set1', 'Set2', 'Set3'], (10,8), path + 'LDA')\nplotPrecisionRecall(algsPCA['lda'], ['Set1', 'Set2', 'Set3'], (10,8), path + 'LDApca')\n\n######################################\n# Gradient Boosting\n######################################\nfrom sklearn.ensemble import GradientBoostingClassifier\n\nlearning_rate = [0.1, 1]\nmax_depth = [3,5]\nloss = ['deviance', 'exponential']\n\nalgsPCA['gradbo'] = {}\nfor l in learning_rate:\n for m in max_depth:\n for lo in loss:\n name = 'GradBoost_PCA_lr' + str(l) + '_depth' + str(m) + '_loss-' + lo\n gbc = GradientBoostingClassifier(learning_rate = l, max_depth = m, loss = lo)\n algsPCA['gradbo'][name] = algorithmAutomat(gbc, X_train_PCA, y_train, X_test_PCA, name)\n\nalgs['gradbo'] = {}\nfor l in learning_rate:\n for m in max_depth:\n for lo in loss:\n name = 'GradBoost_lr' + str(l) + '_depth' + str(m) + '_loss-' + lo\n gbc = GradientBoostingClassifier(learning_rate = l, max_depth = m, loss = lo)\n algs['gradbo'][name] = algorithmAutomat(gbc, X_train, y_train, X_test, name) \n\nplotROC(algs['gradbo'], ['Set1', 'Set2', 'Set3'], (10,8), path + 'GB')\nplotROC(algsPCA['gradbo'], ['Set1', 'Set2', 'Set3'], (10,8), path + 'GBpca')\nplotPrecisionRecall(algs['gradbo'], ['Set1', 'Set2', 'Set3'], (10,8), path + 'GB')\nplotPrecisionRecall(algsPCA['gradbo'], ['Set1', 'Set2', 'Set3'], (10,8), path + 'GBpca')\n\n\n######################################\n# NEURAL NETWORKS: MLP\n######################################\n#File mlp_train.py included in this repository\n#This file contains the needed functions\nimport mlp_train as mlp\n\nfrom keras.utils import to_categorical\n#Creating dummy variables for the response variable (needed in Neural Nets)\ny_train_cat = to_categorical(y_train)\ny_test_cat = to_categorical(y_test)\nalgs['mlp'] = {}\n#Load model trained in MLP.py\n\n#Parameters:\nbaseName = 'MLP_'\nbatch_size = 200\nepochs = 20\noptimizer = ['adam', 'rmsprop']\ndenseLayers = [2, 3]\nlayerNeurons = [200, 500]\ndropout = [True, False]\ndropoutRate = 0.3\nn_classes = 2\n\nfor o in optimizer:\n for d in denseLayers:\n for do in dropout:\n for ln in layerNeurons:\n name, y_pred_mlp, train_time = mlp.NeuralNetProcess(baseName, o, batch_size, epochs, d, ln,\n do, dropoutRate, X_train, X_test, y_train_cat, y_test_cat, n_classes)\n algs['mlp'][name] = algorithmCurvesInfo(name, y_pred_mlp, y_test)\n algs['mlp'][name]['train_time'] = train_time\n algs['mlp'][name]['predict_time'] = None\n \nplotROC(algs['mlp'], ['Set1', 'Set2', 'Set3', 'Set1'], (10,8), path + 'MLP')\nplotPrecisionRecall(algs['mlp'], ['Set1', 'Set2', 'Set3', 'Set1'], (10,8), path + 'MLP')\n\n\n'''\n###########################################\n# TEST EXPORTING SUMMARIES\n###########################################\n''' \n#Exporting summary info to csv file\nheaders = ['HAS_PCA', 'ALGORITHM', 'ALG_NAME', 'TRAIN_TIME', 'PREDICT_TIME', 'AVERAGE_PRECISION', 'ROC_AUC']\nrows = []\nfor a in algsPCA:\n print('---------------',a)\n for k in algsPCA[a]:\n row = []\n row += ['PCA']\n row += [a]\n row += [k]\n row += [str(algsPCA[a][k]['train_time'])]\n row += [str(algsPCA[a][k]['predict_time'])]\n row += [str(algsPCA[a][k]['average_precision'])]\n row += [str(algsPCA[a][k]['roc_auc'][1])]\n rows += [row]\n\nfor a in algs:\n print('---------------',a)\n for k in algs[a]:\n row = []\n row += ['REG']\n row += [a]\n row += [k]\n row += [str(algs[a][k]['train_time'])]\n row += [str(algs[a][k]['predict_time'])]\n row += [str(algs[a][k]['average_precision'])]\n row += [str(algs[a][k]['roc_auc'][1])]\n rows += [row] \n\ncsvfile = ', '.join(headers)\nfor r in rows:\n csvfile += '\\n' + ', '.join(r)\n\nf = open(os.getcwd() + \"\\\\algorithmsDataset.csv\",'w')\nf.write(csvfile)\nf.close()\n\n'''\n###########################################\n# VALIDATION MODELS\n###########################################\n''' \n\n#Select best tuned model for each algorithm and store the list\n#Established a limit_train_time and limit_predict_time.\nbestAlgs = {}\nlimitTrainTime = 400\nlimitPredictTime = 200\nbestAlgs['PCA'] = {}\nfor a in algsPCA:\n balg = ''\n roc = 0\n for k in algsPCA[a]:\n if algsPCA[a][k]['roc_auc'][1] > roc and algsPCA[a][k]['train_time'] < limitTrainTime and algsPCA[a][k]['predict_time'] < limitPredictTime:\n roc = algsPCA[a][k]['roc_auc'][1]\n balg = k\n bestAlgs['PCA'][balg] = roc\n\nbestAlgs['REG'] = {}\nfor a in algs:\n balg = ''\n roc = 0\n for k in algs[a]:\n if algs[a][k]['roc_auc'][1] > roc and algs[a][k]['train_time'] < limitTime and algs[a][k]['predict_time'] < limitPredictTime:\n roc = algs[a][k]['roc_auc'][1]\n balg = k\n bestAlgs['REG'][balg] = roc\n\n\n'''\n###########################################\n# VALIDATION PREDICTIONS\n###########################################\n''' \n#Predict results using the validation set for each selected model\n\nVALalgs = {}\nVALalgs['PCA'] = {}\nfor k in bestAlgs['PCA']: print(k)\n\nname = 'LogRegPCA_l1_100'\nVALalgs['PCA'][name] = algorithmValidation(algsPCA['lr'][name]['model'], X_val_PCA, y_val, name)\n\nname = 'RandForPCA_est100_depth10'\nVALalgs['PCA'][name] = algorithmValidation(algsPCA['rf'][name]['model'], X_val_PCA, y_val, name)\n\nname = 'KNN_PCA_100'\nVALalgs['PCA'][name] = algorithmValidation(algsPCA['knn'][name]['model'], X_val_PCA, y_val, name)\n\nname = 'NaiveBayes_PCA'\nVALalgs['PCA'][name] = algorithmValidation(algsPCA['nbayes'][name]['model'], X_val_PCA, y_val, name)\n\nname = 'AdaBoost_PCA_est50_depth10'\nVALalgs['PCA'][name] = algorithmValidation(algsPCA['adab'][name]['model'], X_val_PCA, y_val,name)\n\nname = 'GradBoost_PCA_lr0.1_depth5_loss-deviance'\nVALalgs['PCA'][name] = algorithmValidation(algsPCA['gradbo'][name]['model'], X_val_PCA, y_val, name)\n\nname = 'LDA_PCA'\nVALalgs['PCA'][name] = algorithmValidation(algsPCA['lda'][name]['model'], X_val_PCA, y_val, name)\n\nVALalgs['REG'] = {}\nfor k in bestAlgs['REG']: print(k)\n\nname = 'LogReg_l1_0.1'\nVALalgs['REG'][name] = algorithmValidation(algs['lr'][name]['model'], X_val, y_val, name)\n\nname = 'RandFor_est100_depth50'\nVALalgs['REG'][name] = algorithmValidation(algs['rf'][name]['model'], X_val, y_val, name)\n\nname = 'KNN_100'\nVALalgs['REG'][name] = algorithmValidation(algs['knn'][name]['model'], X_val, y_val, name)\n\nname = 'NaiveBayes'\nVALalgs['REG'][name] = algorithmValidation(algs['nbayes'][name]['model'], X_val, y_val, name)\n\nname = 'AdaBoost_est50_depth10'\nVALalgs['REG'][name] = algorithmValidation(algs['adab'][name]['model'], X_val, y_val, name)\n\nname = 'GradBoost_lr0.1_depth5_loss-deviance'\nVALalgs['REG'][name] = algorithmValidation(algs['gradbo'][name]['model'], X_val, y_val, name)\n\nname = 'LDA'\nVALalgs['REG'][name] = algorithmValidation(algs['lda'][name]['model'], X_val, y_val, name)\n\nname = 'MLP_rmsprop_b200_e20_DL2_200_drop-False_0.3'\nbestModelPath = os.getcwd() + '/NNbestModel/'\nbestModelPathLoss = bestModelPath + 'model_loss_' + name + '.hdf5'\ny_pred_mlp, prediction_time = mlp.NeuralNetPredict(bestModelPathLoss, X_val)\nVALalgs['REG'][name] = algorithmCurvesInfo(name, y_pred_mlp, y_val)\nVALalgs['REG'][name]['prediction_time'] = prediction_time\n\n#Plot & Save\nplotROC(VALalgs['PCA'], ['Set1', 'Set2', 'Set3'], (10,8), path + 'Val_PCA')\nplotROC(VALalgs['REG'], ['Set1', 'Set2', 'Set3'], (10,8), path + 'Val_REG')\nplotPrecisionRecall(VALalgs['PCA'], ['Set1', 'Set2', 'Set3'], (10,8), path + 'Val_PCA')\nplotPrecisionRecall(VALalgs['REG'], ['Set1', 'Set2', 'Set3'], (10,8), path + 'Val_REG')\n\n'''\n###########################################\n# VALIDATION EXPORTING SUMMARIES\n###########################################\n''' \n\n#Exporting validation set data to csv\nheaders = ['HAS_PCA', 'ALGORITHM', 'ALG_NAME', 'TRAIN_TIME', 'PREDICT_TIME', 'AVERAGE_PRECISION', 'ROC_AUC']\nval_rows = []\nfor a in algsPCA:\n for k in algsPCA[a]:\n if k in VALalgs['PCA']:\n print('---------------',a)\n row = []\n row += ['PCA']\n row += [a]\n row += [k]\n row += [str(algsPCA[a][k]['train_time'])]\n row += [str(VALalgs['PCA'][k]['prediction_time'])]\n row += [str(VALalgs['PCA'][k]['average_precision'])]\n row += [str(VALalgs['PCA'][k]['roc_auc'][1])]\n val_rows += [row]\n\nfor a in algs:\n for k in algs[a]:\n if k in VALalgs['REG']:\n print('---------------',a)\n row = []\n row += ['REG']\n row += [a]\n row += [k]\n row += [str(algs[a][k]['train_time'])]\n row += [str(VALalgs['REG'][k]['prediction_time'])]\n row += [str(VALalgs['REG'][k]['average_precision'])]\n row += [str(VALalgs['REG'][k]['roc_auc'][1])]\n val_rows += [row] \n\ncsvfile = ', '.join(headers)\nfor r in val_rows:\n csvfile += '\\n' + ', '.join(r)\n\nf = open(os.getcwd() + \"\\\\algorithmsValidationDataset.csv\",'w')\nf.write(csvfile)\nf.close()\n" ]
[ [ "matplotlib.pyplot.xlim", "pandas.read_csv", "sklearn.metrics.precision_recall_curve", "matplotlib.pyplot.savefig", "matplotlib.pyplot.get_cmap", "sklearn.decomposition.PCA", "sklearn.discriminant_analysis.LinearDiscriminantAnalysis", "numpy.array", "sklearn.ensemble.RandomForestClassifier", "sklearn.neighbors.KNeighborsClassifier", "matplotlib.pyplot.title", "sklearn.naive_bayes.GaussianNB", "matplotlib.pyplot.figure", "sklearn.tree.DecisionTreeClassifier", "sklearn.model_selection.train_test_split", "matplotlib.pyplot.show", "pandas.get_dummies", "sklearn.ensemble.GradientBoostingClassifier", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.ylim", "matplotlib.pyplot.plot", "matplotlib.pyplot.legend", "sklearn.linear_model.LogisticRegression", "matplotlib.pyplot.ylabel", "sklearn.metrics.auc", "sklearn.metrics.roc_curve" ] ]
yifan-you-37/rl_swiss
[ "8b0ee7caa5c1fa93860916004cf4fd970667764f", "8b0ee7caa5c1fa93860916004cf4fd970667764f", "8b0ee7caa5c1fa93860916004cf4fd970667764f", "8b0ee7caa5c1fa93860916004cf4fd970667764f", "8b0ee7caa5c1fa93860916004cf4fd970667764f", "8b0ee7caa5c1fa93860916004cf4fd970667764f" ]
[ "rlkit/scripted_experts/linear_few_shot_reach_env_expert.py", "gen_models/convgru.py", "rlkit/data_management/pusher_mil_pytorch_data_loader.py", "data_gen/gen_walls.py", "rlkit/envs/pickup_task_point_mass_env.py", "plotting_scripts/plot_adv_irl_hyper_range.py" ]
[ "import time\nimport random\nimport numpy as np\nimport gym\nfrom rlkit.scripted_experts.scripted_policy import ScriptedPolicy\n\nACT_MAG = 0.275\nACT_NOISE_SCALE = 0.1\nACT_SLOW_NOISE_SCALE = 0.05\nSLOW_DOWN_RADIUS = 0.01\n\ndef get_linear_pos_act(cur_pos, reach_pos):\n cur_pos = cur_pos.copy()\n reach_pos = reach_pos.copy()\n move_dir = reach_pos - cur_pos\n dist = np.linalg.norm(move_dir, axis=-1)\n\n # if dist > ACT_MAG:\n # if dist < ACT_MAG:\n # move_dir = move_dir\n # else:\n move_dir *= (ACT_MAG / dist)\n return move_dir\n\n\nclass ScriptedLinearFewShotReachPolicy(ScriptedPolicy):\n def __init__(self):\n super().__init__()\n \n\n def reset(self, env):\n # # first make the gripper go slightly above the object\n self.correct_obj_idx = env.correct_obj_idx\n if self.correct_obj_idx == 0:\n self.correct_obj_abs_pos = env.sim.data.get_site_xpos('object0')\n else:\n self.correct_obj_abs_pos = env.sim.data.get_site_xpos('object1')\n \n self.init_grip_pos = env.sim.data.get_site_xpos('robot0:grip')\n\n\n X_Y_FRAC = np.random.uniform(0.7, 0.8)\n Z_FRAC = np.random.uniform(0.2, 0.3)\n self.waypoint = np.zeros(3)\n self.waypoint[:2] = (self.correct_obj_abs_pos[:2] - self.init_grip_pos[:2]) * X_Y_FRAC\n self.waypoint[2] = (self.correct_obj_abs_pos[2] - self.init_grip_pos[2]) * Z_FRAC\n self.waypoint += self.init_grip_pos\n\n self.waypoint += np.random.uniform(-0.01, 0.01, 3)\n\n # first go to a way-point\n def cond_0(obs):\n grip_pos = env.sim.data.get_site_xpos('robot0:grip')\n return 0.01 > np.linalg.norm(grip_pos - self.waypoint, axis=-1)\n self.milestone_0_cond = cond_0\n\n # now actually go to the object\n def cond_1(obs):\n grip_pos = env.sim.data.get_site_xpos('robot0:grip')\n goal = env.goal\n return 0.01 > np.linalg.norm(grip_pos - goal)\n self.milestone_1_cond = cond_1\n\n # reset the milestones\n self.milestone_0_complete = False\n self.milestone_1_complete = False\n self.first_time_all_complete = -1\n\n\n def get_action(self, obs, env, timestep):\n # first find out what stage we are in and update milestone info\n cur_stage = -1\n if not self.milestone_0_complete:\n # check if milestone 0 was completed by the last step action\n if self.milestone_0_cond(obs):\n self.milestone_0_complete = True\n cur_stage = 1\n else:\n cur_stage = 0\n else:\n if not self.milestone_1_complete:\n # check if milestone 1 was completed by the last step action\n if self.milestone_1_cond(obs):\n self.milestone_1_complete = True\n self.first_time_all_complete = timestep\n print('solved')\n cur_stage = 1\n\n # now perform the action corresponding to the current stage\n if cur_stage == 0:\n grip_pos = env.sim.data.get_site_xpos('robot0:grip')\n\n action = [0, 0, 0, 0]\n pos_act = get_linear_pos_act(grip_pos, self.waypoint)\n pos_act += np.random.uniform(0.0, ACT_NOISE_SCALE, 3)\n for i in range(len(pos_act)):\n action[i] = pos_act[i]\n action[len(action)-1] = np.random.uniform(-0.005, -0.015) # close\n else:\n action = [0, 0, 0, 0]\n # print(np.linalg.norm(correct_obj_rel_target, axis=-1))\n grip_pos = env.sim.data.get_site_xpos('robot0:grip')\n target_rel_pos = env.goal - grip_pos\n if np.linalg.norm(target_rel_pos, axis=-1) < SLOW_DOWN_RADIUS:\n # pos_act = ACT_MAG*target_rel_pos*10\n pos_act = 0.25*get_linear_pos_act(np.zeros(3), target_rel_pos)\n pos_act += np.random.uniform(0.0, ACT_SLOW_NOISE_SCALE, 3)\n # print(pos_act)\n else:\n pos_act = get_linear_pos_act(np.zeros(3), target_rel_pos)\n pos_act += np.random.uniform(0.0, ACT_NOISE_SCALE, 3)\n # pos_act = get_linear_pos_act(np.zeros(3), correct_obj_rel_target)\n for i in range(len(pos_act)):\n action[i] = pos_act[i]\n action[len(action)-1] = np.random.uniform(-0.005, -0.015) # close\n \n action = np.clip(action, -1.0, 1.0)\n return action, {}\n", "'''\nStolen from https://github.com/jacobkimmel/pytorch_convgru/blob/master/convgru.py\n'''\nimport torch\nimport torch.nn as nn\nimport numpy as np\nimport torch.nn.functional as F\nfrom torch.nn import init\n\n\nclass ConvGRUCell(nn.Module):\n \"\"\"\n Generate a convolutional GRU cell\n \"\"\"\n\n def __init__(self, input_size, hidden_size, kernel_size):\n super().__init__()\n padding = kernel_size // 2\n self.input_size = input_size\n self.hidden_size = hidden_size\n self.reset_gate = nn.Conv2d(input_size + hidden_size, hidden_size, kernel_size, padding=padding)\n self.update_gate = nn.Conv2d(input_size + hidden_size, hidden_size, kernel_size, padding=padding)\n self.out_gate = nn.Conv2d(input_size + hidden_size, hidden_size, kernel_size, padding=padding)\n\n init.orthogonal(self.reset_gate.weight)\n init.orthogonal(self.update_gate.weight)\n init.orthogonal(self.out_gate.weight)\n init.constant(self.reset_gate.bias, 0.)\n init.constant(self.update_gate.bias, 0.)\n init.constant(self.out_gate.bias, 0.)\n\n\n def forward(self, input_, prev_state):\n\n # get batch and spatial sizes\n batch_size = input_.data.size()[0]\n spatial_size = input_.data.size()[2:]\n\n # generate empty prev_state, if None is provided\n if prev_state is None:\n state_size = [batch_size, self.hidden_size] + list(spatial_size)\n if torch.cuda.is_available():\n prev_state = Variable(torch.zeros(state_size)).cuda()\n else:\n prev_state = Variable(torch.zeros(state_size))\n\n # data size is [batch, channel, height, width]\n stacked_inputs = torch.cat([input_, prev_state], dim=1)\n update = F.sigmoid(self.update_gate(stacked_inputs))\n reset = F.sigmoid(self.reset_gate(stacked_inputs))\n out_inputs = F.tanh(self.out_gate(torch.cat([input_, prev_state * reset], dim=1)))\n new_state = prev_state * (1 - update) + out_inputs * update\n\n return new_state\n\n\nclass ConvGRU(nn.Module):\n\n def __init__(self, input_size, hidden_sizes, kernel_sizes, n_layers):\n '''\n Generates a multi-layer convolutional GRU.\n Preserves spatial dimensions across cells, only altering depth.\n\n Parameters\n ----------\n input_size : integer. depth dimension of input tensors.\n hidden_sizes : integer or list. depth dimensions of hidden state.\n if integer, the same hidden size is used for all cells.\n kernel_sizes : integer or list. sizes of Conv2d gate kernels.\n if integer, the same kernel size is used for all cells.\n n_layers : integer. number of chained `ConvGRUCell`.\n '''\n\n super(ConvGRU, self).__init__()\n\n self.input_size = input_size\n\n if type(hidden_sizes) != list:\n self.hidden_sizes = [hidden_sizes]*n_layers\n else:\n assert len(hidden_sizes) == n_layers, '`hidden_sizes` must have the same length as n_layers'\n self.hidden_sizes = hidden_sizes\n if type(kernel_sizes) != list:\n self.kernel_sizes = [kernel_sizes]*n_layers\n else:\n assert len(kernel_sizes) == n_layers, '`kernel_sizes` must have the same length as n_layers'\n self.kernel_sizes = kernel_sizes\n\n self.n_layers = n_layers\n\n cells = []\n for i in range(self.n_layers):\n if i == 0:\n input_dim = self.input_size\n else:\n input_dim = self.hidden_sizes[i-1]\n\n cell = ConvGRUCell(input_dim, self.hidden_sizes[i], self.kernel_sizes[i])\n name = 'ConvGRUCell_' + str(i).zfill(2)\n\n setattr(self, name, cell)\n cells.append(getattr(self, name))\n\n self.cells = cells\n\n\n def forward(self, x, hidden=None):\n '''\n Parameters\n ----------\n x : 4D input tensor. (batch, channels, height, width).\n hidden : list of 4D hidden state representations. (batch, channels, height, width).\n\n Returns\n -------\n upd_hidden : 5D hidden representation. (layer, batch, channels, height, width).\n '''\n if not hidden:\n hidden = [None]*self.n_layers\n\n input_ = x\n\n upd_hidden = []\n\n for layer_idx in range(self.n_layers):\n cell = self.cells[layer_idx]\n cell_hidden = hidden[layer_idx]\n\n # pass through layer\n upd_cell_hidden = cell(input_, cell_hidden)\n upd_hidden.append(upd_cell_hidden)\n # update input_ to the last updated hidden layer for next pass\n input_ = upd_cell_hidden\n\n # retain tensors in list to allow different hidden sizes\n return upd_hidden\n", "'''\npusher_mil_data_generatory.py from original work is too slow\nThis is my implementation using pytorch data loaders class\n'''\nimport os\nimport os.path as osp\nimport pickle\n\nimport numpy as np\nimport imageio\n\nimport torch\nfrom torch.utils.data import Dataset, DataLoader\nfrom natsort import natsorted\nimport glob\n\nfrom rlkit.data_management.mil_utils import extract_demo_dict, Timer\n\n\ndef pusher_collate_fn(batch):\n new_dict = {}\n for k in batch[0]:\n new_dict[k] = np.array(\n [b[k] for b in batch]\n )\n return new_dict\n\n\nclass PusherDataset(Dataset):\n def __init__(\n self,\n demos,\n state_dim,\n act_dim,\n vid_folders,\n num_context_trajs,\n num_test_trajs,\n prefix,\n mode='video_and_state_and_action', # or 'video_and_state' or 'video_only',\n ):\n super().__init__()\n if mode != 'video_and_state_and_action': raise NotImplementedError()\n\n self.demos = demos\n self.state_dim = state_dim\n self.act_dim = act_dim\n self.num_context_trajs = num_context_trajs\n self.num_test_trajs = num_test_trajs\n self.total_num_trajs_per_task = self.num_context_trajs + self.num_test_trajs\n self.prefix = prefix\n\n vid_paths_dict = {}\n for task in vid_folders:\n task_folder = vid_folders[task]\n task_vid_paths = natsorted(\n [\n p for p in os.listdir(task_folder)\n if '.npy' in p\n # if '.gif' in p\n ]\n )\n # for 'sim_push' they aren't using all the demos\n task_vid_paths = task_vid_paths[6:-6]\n task_vid_paths = [\n osp.join(task_folder, p) for p in task_vid_paths\n ]\n try:\n assert len(task_vid_paths) == self.demos[task]['demoX'].shape[0]\n except AssertionError:\n import pdb; pdb.set_trace()\n vid_paths_dict[task] = task_vid_paths\n self.vid_paths_dict = vid_paths_dict\n self._size = len(list(vid_paths_dict.keys()))\n \n\n def __len__(self):\n return self._size\n\n \n def __getitem__(self, task):\n '''\n We use idx as meaning the task idx\n '''\n task = self.prefix + '_' + str(task)\n traj_idxs = np.random.choice(\n self.demos[task]['demoU'].shape[0],\n size=self.total_num_trajs_per_task,\n replace=False\n )\n\n # get the states\n U = [self.demos[task]['demoU'][v] for v in traj_idxs]\n U = np.array(U)\n X = [self.demos[task]['demoX'][v] for v in traj_idxs]\n X = np.array(X)\n assert U.shape[2] == self.act_dim\n assert X.shape[2] == self.state_dim\n\n # get the videos\n vids = []\n for idx in traj_idxs:\n # vid = imageio.mimread(self.vid_paths_dict[task][idx])\n\n # no need for transposing since I've already saved them\n # with correct ordering of dimensions\n vid = np.load(self.vid_paths_dict[task][idx])\n\n # we will do this on the GPU\n # .astype(np.float32)\n # vid /= 255.0\n vids.append(vid)\n # vids = np.array(vids)\n\n return {\n 'videos': vids,\n 'states': X,\n 'actions': U\n }\n \n\n def get_single_traj(self, task):\n '''\n We use idx as meaning the task idx\n '''\n sample_idx = np.random.choice(self.demos[task]['demoU'].shape[0])\n\n # get the states\n U = [self.demos[task]['demoU'][sample_idx]]\n U = np.array(U)\n X = [self.demos[task]['demoX'][sample_idx]]\n X = np.array(X)\n assert U.shape[2] == self.act_dim\n assert X.shape[2] == self.state_dim\n\n # get the videos\n vids = [np.load(self.vid_paths_dict[task][sample_idx])]\n\n return {\n 'videos': vids,\n 'states': X,\n 'actions': U\n }\n\n\ndef extract_supervised_data(\n demo_file,\n demo_gif_dir,\n gif_prefix,\n training_set_size,\n val_set_size,\n shuffle_val,\n T,\n):\n \"\"\"\n Taken and modified from the original work's data loader.\n This is fast so it's ok to use it.\n\n Load the states and actions of the demos into memory.\n Args:\n demo_file: list of demo files where each file contains expert's states and actions of one task.\n \"\"\"\n demo_file = natsorted(glob.glob(demo_file + '/*pkl'))\n dataset_size = len(demo_file)\n if training_set_size != -1:\n tmp = demo_file[:training_set_size]\n tmp.extend(demo_file[-val_set_size:])\n demo_file = tmp\n\n demos = extract_demo_dict(demo_file)\n # print(demos.keys())\n # We don't need the whole dataset of simulated pushing.\n for key in demos.keys():\n demos[key]['demoX'] = demos[key]['demoX'][6:-6, :, :].copy()\n # original\n demos[key]['demoU'] = demos[key]['demoU'][6:-6, :, :].copy()\n # the env's weird normalization and clipping effectively clips\n # the range of actions to 1 and -1\n # demos[key]['demoU'] = np.clip(demos[key]['demoU'][6:-6, :, :].copy(), -1.0, 1.0)\n\n n_folders = len(demos.keys())\n N_demos = np.sum(demo['demoX'].shape[0] for i, demo in demos.items())\n state_idx = range(demos[0]['demoX'].shape[-1])\n _dU = demos[0]['demoU'].shape[-1]\n print(\"Number of demos: %d\" % N_demos)\n idx = np.arange(n_folders)\n \n n_val = val_set_size # number of demos for testing\n if n_val != 0:\n if not shuffle_val:\n val_idx = idx[-n_val:]\n train_idx = idx[:-n_val]\n else:\n val_idx = np.sort(np.random.choice(idx, size=n_val, replace=False))\n mask = np.array([(i in val_idx) for i in idx])\n train_idx = np.sort(idx[~mask])\n else:\n assert False\n train_idx = idx\n val_idx = []\n # Normalize the states if it's training.\n with Timer('Normalizing states'):\n states = np.vstack((demos[i]['demoX'] for i in train_idx)) # hardcoded here to solve the memory issue\n states = states.reshape(-1, len(state_idx))\n\n # actions = np.vstack((demos[i]['demoU'] for i in train_idx)) # hardcoded here to solve the memory issue\n # actions = actions.reshape(-1, _dU)\n # print(np.mean(actions, axis=0))\n # print(np.std(actions, axis=0))\n # print(np.max(actions, axis=0))\n # print(np.min(actions, axis=0))\n # from rlkit.core.vistools import plot_histogram\n # for i in range(7):\n # plot_histogram(actions[:,i], 100, 'pusher_action_dim_%d'%i, 'plots/junk_vis/pusher_action_dim_%d.png'%i)\n # 1/0\n\n # 1e-3 to avoid infs if some state dimensions don't change in the\n # first batch of samples\n # original --------\n # scale = np.diag(\n # 1.0 / np.maximum(np.std(states, axis=0), 1e-3))\n # bias = - np.mean(\n # states.dot(scale), axis=0)\n # mine ------------\n # print(np.std(states, axis=0))\n # print(np.mean(states, axis=0))\n std = np.maximum(np.std(states, axis=0, keepdims=True), 1e-3)\n mean = np.mean(states, axis=0, keepdims=True)\n # print(np.max((states - mean) / std, axis=0))\n # print(np.min((states - mean) / std, axis=0))\n # 1/0\n # print(np.mean((states-mean)/std, axis=0))\n # print(np.std((states-mean)/std, axis=0))\n # print(mean)\n # print(std)\n # Save the scale and bias.\n with open('/h/kamyar/mil/data/scale_and_bias_%s.pkl' % 'sim_push', 'wb') as f:\n pickle.dump({'std': std, 'mean': mean}, f)\n \n for key in demos.keys():\n # original --------\n # demos[key]['demoX'] = demos[key]['demoX'].reshape(-1, len(state_idx))\n # demos[key]['demoX'] = demos[key]['demoX'].dot(scale) + bias\n # demos[key]['demoX'] = demos[key]['demoX'].reshape(-1, T, len(state_idx))\n # mine ------------\n # print(demos[key]['demoX'].shape)\n # print(len(state_idx))\n # prev = demos[key]['demoX'][0][:10]\n # print(prev)\n demos[key]['demoX'] = demos[key]['demoX'].reshape(-1, len(state_idx))\n # print(demos[key]['demoX'][:10])\n # print(demos[key]['demoX'].shape)\n demos[key]['demoX'] = (demos[key]['demoX'] - mean) / std\n # print(demos[key]['demoX'][:10])\n # print(demos[key]['demoX'].shape)\n demos[key]['demoX'] = demos[key]['demoX'].reshape(-1, T, len(state_idx))\n # print(demos[key]['demoX'].shape)\n # post_prev = demos[key]['demoX'][0]*std + mean\n # print(post_prev.shape)\n # print(post_prev == prev)\n # print(demos[key]['demoX'][0][:10])\n # print(prev.shape)\n\n train_demos = {'train_%d' % i: demos[i] for i in train_idx}\n val_demos = {'val_%d' % i: demos[i] for i in val_idx}\n\n if training_set_size != -1:\n offset = dataset_size - training_set_size - val_set_size\n else:\n offset = 0\n img_folders = natsorted(glob.glob(demo_gif_dir + gif_prefix + '_*'))\n train_img_folders = {'train_%d'%i: img_folders[i] for i in train_idx}\n val_img_folders = {'val_%d' % i: img_folders[i+offset] for i in val_idx}\n\n return train_demos, val_demos, train_img_folders, val_img_folders, train_idx, val_idx, state_idx, _dU, mean, std\n\n\ndef build_train_val_datasets(num_context_trajs, num_test_trajs):\n train_demos, val_demos, train_img_folders, val_img_folders, train_idx, val_idx, state_idx, _dU, mean, std = extract_supervised_data(\n '/scratch/ssd001/home/kamyar/mil/data/sim_push',\n '/scratch/ssd001/home/kamyar/mil/data/sim_push/',\n 'object',\n -1,\n 76,\n False,\n 100,\n )\n\n train_ds = PusherDataset(\n train_demos,\n len(state_idx),\n _dU,\n train_img_folders,\n num_context_trajs,\n num_test_trajs,\n 'train'\n )\n val_ds = PusherDataset(\n val_demos,\n len(state_idx),\n _dU,\n val_img_folders,\n num_context_trajs,\n num_test_trajs,\n 'val'\n )\n \n return train_ds, val_ds, train_idx, val_idx, len(state_idx), _dU, mean, std\n\n\n\nif __name__ == '__main__':\n train_demos, val_demos, train_img_folders, val_img_folders, train_idx, val_idx,state_idx, _dU = extract_supervised_data(\n '/scratch/ssd001/home/kamyar/mil/data/sim_push',\n '/scratch/ssd001/home/kamyar/mil/data/sim_push/',\n 'object',\n -1,\n 76,\n False,\n 100,\n )\n # k = list(train_img_folders.keys())\n # print(k)\n # print(train_img_folders[k[0]])\n\n ds = PusherDataset(\n train_demos,\n len(state_idx),\n _dU,\n train_img_folders,\n 1,\n 4\n )\n\n print(train_idx)\n print(val_idx)\n\n # for k,v in ds[4].items():\n # print(k, v.shape)\n\n # for i in range(len(ds)):\n # ds[i]\n # print(i)\n\n # dl = DataLoader(\n # ds,\n # batch_size=8,\n # shuffle=True,\n # num_workers=8,\n # collate_fn=pusher_collate_fn,\n # drop_last=True\n # )\n # for i, batch in enumerate(dl):\n # print(i)\n\n # for i in range(100):\n # print('now')\n # tasks = np.random.choice(100, size=8)\n # for task in tasks:\n # ds[task]\n", "import numpy as np\n\nWALL_LEN = 20.0\nNUM_PATHS = 8.0\nWALL_FROM_CENTER = 8.0\nTARGET_DIST = 25.0\n\nxml_block = '<body mocap=\\\"true\\\" pos=\\\"{x} {y} 1\\\" euler=\"0 0 {z_rot}\\\">\\n\\\n\\t<geom type=\\\"box\\\" size=\\\"{wall_len} 0.5 2\\\" group=\\\"1\\\" condim=\\\"3\\\" conaffinity=\\\"1\\\"/>\\n\\\n</body>'\n\nincrements = 2*np.pi / NUM_PATHS\nhalf_increments = np.pi / NUM_PATHS\nangles = np.linspace(0.0, 2*np.pi, num=NUM_PATHS, endpoint=False)\n\nfor a in angles:\n left_and_right = []\n for inc in [-half_increments, half_increments]:\n xy = np.array([np.cos(a+inc), np.sin(a+inc)]) * WALL_FROM_CENTER\n left_and_right.append(\n xy + np.array([np.cos(a), np.sin(a)]) * WALL_LEN\n )\n xy += np.array([np.cos(a), np.sin(a)]) * WALL_LEN / 2.0\n print(\n xml_block.format(\n **{\n 'x': '%.2f' % xy[0],\n 'y': '%.2f' % xy[1],\n 'z_rot': '%.2f' % (a * 360.0 / (2*np.pi)),\n 'wall_len': WALL_LEN / 2.0\n }\n )\n )\n \n end_block_len = np.linalg.norm(left_and_right[0] - left_and_right[1]) + 1.0\n mid_point = sum(left_and_right) / 2.0\n print(\n xml_block.format(\n **{\n 'x': '%.2f' % mid_point[0],\n 'y': '%.2f' % mid_point[1],\n 'z_rot': '%.2f' % ((a + np.pi/2.0) * 360.0 / (2*np.pi)),\n 'wall_len': end_block_len / 2.0\n }\n )\n )\n\n\n# print('\\n')\n\nfor i, a in enumerate(angles):\n xy = np.array([np.cos(a), np.sin(a)]) * TARGET_DIST\n print(\n \"<site name=\\\"target{num}\\\" pos=\\\"{x} {y} .01\\\" rgba=\\\"0.75 0 0.75 1\\\" type=\\\"sphere\\\" size=\\\"1\\\"/>\".format(\n num=i,\n x='%.2f' % xy[0],\n y='%.2f' % xy[1]\n )\n )\n", "import numpy as np\nfrom collections import OrderedDict\nfrom gym import utils\nfrom gym import spaces\nimport os\n\n# from rlkit.envs.mujoco_env import MujocoEnv\nfrom gym.envs.mujoco.mujoco_env import MujocoEnv\n\nfrom rlkit.core.vistools import plot_seaborn_heatmap, plot_scatter\n\n\nclass PickupTaskPointMassEnv():\n def __init__(self, env_bound=7.0, init_pos=np.array([0.0, 0.0]), episode_len=119):\n self.cur_pos = np.zeros([2])\n self.init_pos = init_pos.copy()\n\n self.max_action_magnitude = 1.0\n self.action_space = spaces.Box(-1.0, 1.0, shape=(2,), dtype='float32')\n self.observation_space = spaces.Box(-env_bound, env_bound, shape=(8,), dtype='float32')\n self.env_bound = env_bound\n\n self.episode_len = float(episode_len)\n\n self.num_items = 2\n self.min_angle_between_items = np.pi / 6.0\n self.radius = 10.0\n self.accept_radius = 1.0\n\n def seed(self, num):\n pass\n\n def step(self, a):\n a = np.clip(a, self.action_space.low, self.action_space.high)\n\n reward = 0.0 # we don't need a reward for what we want to do with this env\n\n self.cur_pos += a\n\n # if we want noisy dynamics\n # self.cur_pos += np.random.normal(loc=0.0, scale=0.2, size=2)\n\n # clipping to env bound\n # self.cur_pos = np.clip(self.cur_pos, -self.env_bound, self.env_bound)\n\n self.timestep += 1.0\n\n if self.timestep == self.episode_len:\n done = True\n else:\n done = False\n\n # check if you are in one of the target regions\n for i in range(self.obj_poses.shape[0]):\n if np.linalg.norm(self.cur_pos - self.obj_poses[i]) < self.accept_radius:\n self.visited[i] = 1.0\n \n # check success\n success = 1.0 if (np.mean(self.visited) == 1.0) else 0.0\n \n # np.array([self.cur_pos[0], self.cur_pos[1], self.timestep/self.episode_len])\n return self._get_obs() , reward, done, dict(\n xy_pos=self.cur_pos.copy(),\n timestep=self.timestep,\n success=success\n )\n\n def angles_check(self, prev_as, new_a):\n if len(prev_as) == 0:\n return True\n for a in prev_as:\n if abs(a - new_a) < self.min_angle_between_items:\n return False\n return True\n\n def reset(self):\n self.timestep = 0.0\n self.cur_pos = self.init_pos + np.random.normal(loc=0.0, scale=0.1, size=2)\n # return np.array([self.cur_pos[0], self.cur_pos[1], 0.0])\n\n # reset the object poses\n angles = []\n for _ in range(self.num_items):\n new_a = np.random.uniform(high=np.pi)\n while not self.angles_check(angles, new_a):\n new_a = np.random.uniform(high=np.pi)\n angles.append(new_a)\n \n angles = np.array(angles)\n self.obj_poses = np.stack([self.radius*np.cos(angles), self.radius*np.sin(angles)], axis=1)\n self.flat_obj_poses = self.obj_poses.flatten()\n\n # reset the visitations\n self.visited = np.zeros(self.num_items)\n\n return self._get_obs()\n \n def _get_obs(self):\n obs = np.concatenate((self.cur_pos, self.flat_obj_poses, self.visited)).copy()\n return obs\n\n def log_statistics(self, paths):\n is_success = [sum([d['success'] for d in path[\"env_infos\"]]) > 0 for path in paths]\n return {\n 'Success Rate': np.mean(is_success)\n }\n", "'''\ncheck the heatmap for ant airl and fairl hyperparameters\n'''\nimport joblib\nimport os\nfrom os import path as osp\nimport numpy as np\nfrom rlkit.core.vistools import plot_2dhistogram\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\n\nimport seaborn as sns; sns.set()\n\nimport json\n\nrews = [0.5, 1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0]\ngps = [0.5, 1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0]\nrew_ind = {}\nfor i in range(len(rews)):\n rew_ind[rews[i]] = i\ngp_ind = {}\nfor i in range(len(gps)):\n gp_ind[gps[i]] = i\n\n\ndef make_heatmap(grid, save_path, title):\n ax = sns.heatmap(grid, vmin=0, vmax=6500, cmap=\"YlGnBu\")\n ax.set(xlabel='Gradient Penalty', ylabel='Reward Scale', xticklabels=gps, yticklabels=rews, title=title)\n ax.figure.savefig(save_path)\n plt.close()\n\n\ndef extract_info(exp_path):\n grid = np.zeros((len(rews), len(gps)))\n for d in os.listdir(exp_path):\n sub_path = osp.join(exp_path, d)\n with open(osp.join(sub_path, 'variant.json')) as f:\n json_dict = json.load(f)\n rew_scale = json_dict['sac_params']['reward_scale']\n gp_weight = json_dict['adv_irl_params']['grad_pen_weight']\n test_ret = joblib.load(\n osp.join(sub_path, 'best.pkl')\n )['statistics']['Test Returns Mean']\n grid[rew_ind[rew_scale], gp_ind[gp_weight]] = test_ret\n return grid\n\nif __name__ == '__main__':\n # extract the info for airl\n exp_path = '/scratch/hdd001/home/kamyar/output/airl-ant-hype-search'\n airl_grid = extract_info(exp_path)\n make_heatmap(airl_grid, 'plots/junk_vis/airl_hype_grid.png', '')\n\n # extract the info for fairl\n exp_path = '/scratch/hdd001/home/kamyar/output/fairl-ant-hype-search'\n fairl_grid = extract_info(exp_path)\n make_heatmap(fairl_grid, 'plots/junk_vis/fairl_hype_grid.png', '')\n" ]
[ [ "numpy.clip", "numpy.linalg.norm", "numpy.zeros", "numpy.random.uniform" ], [ "torch.zeros", "torch.cat", "torch.nn.init.orthogonal", "torch.nn.init.constant", "torch.nn.Conv2d", "torch.cuda.is_available" ], [ "numpy.array", "numpy.random.choice", "numpy.load", "numpy.mean", "numpy.std", "numpy.arange", "numpy.sort", "numpy.vstack" ], [ "numpy.linspace", "numpy.linalg.norm", "numpy.sin", "numpy.cos" ], [ "numpy.concatenate", "numpy.random.normal", "numpy.array", "numpy.linalg.norm", "numpy.sin", "numpy.zeros", "numpy.mean", "numpy.random.uniform", "numpy.cos", "numpy.clip" ], [ "matplotlib.use", "matplotlib.pyplot.close" ] ]
Schmitze333/pandas
[ "165d5ee40862ba155b5988045164e21aaaefd556" ]
[ "pandas/core/groupby/ops.py" ]
[ "\"\"\"\nProvide classes to perform the groupby aggregate operations.\n\nThese are not exposed to the user and provide implementations of the grouping\noperations, primarily in cython. These classes (BaseGrouper and BinGrouper)\nare contained *in* the SeriesGroupBy and DataFrameGroupBy objects.\n\"\"\"\n\nimport collections\nfrom typing import List, Optional\n\nimport numpy as np\n\nfrom pandas._libs import NaT, iNaT, lib\nimport pandas._libs.groupby as libgroupby\nimport pandas._libs.reduction as libreduction\nfrom pandas.errors import AbstractMethodError\nfrom pandas.util._decorators import cache_readonly\n\nfrom pandas.core.dtypes.common import (\n ensure_float64,\n ensure_int64,\n ensure_int_or_float,\n ensure_platform_int,\n is_bool_dtype,\n is_categorical_dtype,\n is_complex_dtype,\n is_datetime64_any_dtype,\n is_datetime64tz_dtype,\n is_extension_array_dtype,\n is_integer_dtype,\n is_numeric_dtype,\n is_sparse,\n is_timedelta64_dtype,\n needs_i8_conversion,\n)\nfrom pandas.core.dtypes.missing import _maybe_fill, isna\n\nimport pandas.core.algorithms as algorithms\nfrom pandas.core.base import SelectionMixin\nimport pandas.core.common as com\nfrom pandas.core.frame import DataFrame\nfrom pandas.core.generic import NDFrame\nfrom pandas.core.groupby import base\nfrom pandas.core.index import Index, MultiIndex, ensure_index\nfrom pandas.core.series import Series\nfrom pandas.core.sorting import (\n compress_group_index,\n decons_obs_group_ids,\n get_flattened_iterator,\n get_group_index,\n get_group_index_sorter,\n get_indexer_dict,\n)\n\n\nclass BaseGrouper:\n \"\"\"\n This is an internal Grouper class, which actually holds\n the generated groups\n\n Parameters\n ----------\n axis : int\n the axis to group\n groupings : array of grouping\n all the grouping instances to handle in this grouper\n for example for grouper list to groupby, need to pass the list\n sort : boolean, default True\n whether this grouper will give sorted result or not\n group_keys : boolean, default True\n mutated : boolean, default False\n indexer : intp array, optional\n the indexer created by Grouper\n some groupers (TimeGrouper) will sort its axis and its\n group_info is also sorted, so need the indexer to reorder\n\n \"\"\"\n\n def __init__(\n self, axis, groupings, sort=True, group_keys=True, mutated=False, indexer=None\n ):\n self._filter_empty_groups = self.compressed = len(groupings) != 1\n self.axis = axis\n self.groupings = groupings\n self.sort = sort\n self.group_keys = group_keys\n self.mutated = mutated\n self.indexer = indexer\n\n @property\n def shape(self):\n return tuple(ping.ngroups for ping in self.groupings)\n\n def __iter__(self):\n return iter(self.indices)\n\n @property\n def nkeys(self):\n return len(self.groupings)\n\n def get_iterator(self, data, axis=0):\n \"\"\"\n Groupby iterator\n\n Returns\n -------\n Generator yielding sequence of (name, subsetted object)\n for each group\n \"\"\"\n splitter = self._get_splitter(data, axis=axis)\n keys = self._get_group_keys()\n for key, (i, group) in zip(keys, splitter):\n yield key, group\n\n def _get_splitter(self, data, axis=0):\n comp_ids, _, ngroups = self.group_info\n return get_splitter(data, comp_ids, ngroups, axis=axis)\n\n def _get_grouper(self):\n \"\"\"\n We are a grouper as part of another's groupings.\n\n We have a specific method of grouping, so cannot\n convert to a Index for our grouper.\n \"\"\"\n return self.groupings[0].grouper\n\n def _get_group_keys(self):\n if len(self.groupings) == 1:\n return self.levels[0]\n else:\n comp_ids, _, ngroups = self.group_info\n\n # provide \"flattened\" iterator for multi-group setting\n return get_flattened_iterator(comp_ids, ngroups, self.levels, self.labels)\n\n def apply(self, f, data, axis=0):\n mutated = self.mutated\n splitter = self._get_splitter(data, axis=axis)\n group_keys = self._get_group_keys()\n result_values = None\n\n sdata = splitter._get_sorted_data()\n if sdata.ndim == 2 and np.any(sdata.dtypes.apply(is_extension_array_dtype)):\n # calling splitter.fast_apply will raise TypeError via apply_frame_axis0\n # if we pass EA instead of ndarray\n # TODO: can we have a workaround for EAs backed by ndarray?\n pass\n\n elif (\n com.get_callable_name(f) not in base.plotting_methods\n and hasattr(splitter, \"fast_apply\")\n and axis == 0\n # with MultiIndex, apply_frame_axis0 would raise InvalidApply\n # TODO: can we make this check prettier?\n and not sdata.index._has_complex_internals\n ):\n try:\n result_values, mutated = splitter.fast_apply(f, group_keys)\n\n # If the fast apply path could be used we can return here.\n # Otherwise we need to fall back to the slow implementation.\n if len(result_values) == len(group_keys):\n return group_keys, result_values, mutated\n\n except libreduction.InvalidApply as err:\n # Cannot fast apply on MultiIndex (_has_complex_internals).\n # This Exception is also raised if `f` triggers an exception\n # but it is preferable to raise the exception in Python.\n if \"Let this error raise above us\" not in str(err):\n # TODO: can we infer anything about whether this is\n # worth-retrying in pure-python?\n raise\n\n for key, (i, group) in zip(group_keys, splitter):\n object.__setattr__(group, \"name\", key)\n\n # result_values is None if fast apply path wasn't taken\n # or fast apply aborted with an unexpected exception.\n # In either case, initialize the result list and perform\n # the slow iteration.\n if result_values is None:\n result_values = []\n\n # If result_values is not None we're in the case that the\n # fast apply loop was broken prematurely but we have\n # already the result for the first group which we can reuse.\n elif i == 0:\n continue\n\n # group might be modified\n group_axes = _get_axes(group)\n res = f(group)\n if not _is_indexed_like(res, group_axes):\n mutated = True\n result_values.append(res)\n\n return group_keys, result_values, mutated\n\n @cache_readonly\n def indices(self):\n \"\"\" dict {group name -> group indices} \"\"\"\n if len(self.groupings) == 1:\n return self.groupings[0].indices\n else:\n label_list = [ping.labels for ping in self.groupings]\n keys = [com.values_from_object(ping.group_index) for ping in self.groupings]\n return get_indexer_dict(label_list, keys)\n\n @property\n def labels(self):\n return [ping.labels for ping in self.groupings]\n\n @property\n def levels(self):\n return [ping.group_index for ping in self.groupings]\n\n @property\n def names(self):\n return [ping.name for ping in self.groupings]\n\n def size(self):\n \"\"\"\n Compute group sizes\n\n \"\"\"\n ids, _, ngroup = self.group_info\n ids = ensure_platform_int(ids)\n if ngroup:\n out = np.bincount(ids[ids != -1], minlength=ngroup)\n else:\n out = []\n return Series(out, index=self.result_index, dtype=\"int64\")\n\n @cache_readonly\n def groups(self):\n \"\"\" dict {group name -> group labels} \"\"\"\n if len(self.groupings) == 1:\n return self.groupings[0].groups\n else:\n to_groupby = zip(*(ping.grouper for ping in self.groupings))\n to_groupby = Index(to_groupby)\n return self.axis.groupby(to_groupby)\n\n @cache_readonly\n def is_monotonic(self):\n # return if my group orderings are monotonic\n return Index(self.group_info[0]).is_monotonic\n\n @cache_readonly\n def group_info(self):\n comp_ids, obs_group_ids = self._get_compressed_labels()\n\n ngroups = len(obs_group_ids)\n comp_ids = ensure_int64(comp_ids)\n return comp_ids, obs_group_ids, ngroups\n\n @cache_readonly\n def label_info(self):\n # return the labels of items in original grouped axis\n labels, _, _ = self.group_info\n if self.indexer is not None:\n sorter = np.lexsort((labels, self.indexer))\n labels = labels[sorter]\n return labels\n\n def _get_compressed_labels(self):\n all_labels = [ping.labels for ping in self.groupings]\n if len(all_labels) > 1:\n group_index = get_group_index(all_labels, self.shape, sort=True, xnull=True)\n return compress_group_index(group_index, sort=self.sort)\n\n ping = self.groupings[0]\n return ping.labels, np.arange(len(ping.group_index))\n\n @cache_readonly\n def ngroups(self):\n return len(self.result_index)\n\n @property\n def recons_labels(self):\n comp_ids, obs_ids, _ = self.group_info\n labels = (ping.labels for ping in self.groupings)\n return decons_obs_group_ids(comp_ids, obs_ids, self.shape, labels, xnull=True)\n\n @cache_readonly\n def result_index(self):\n if not self.compressed and len(self.groupings) == 1:\n return self.groupings[0].result_index.rename(self.names[0])\n\n codes = self.recons_labels\n levels = [ping.result_index for ping in self.groupings]\n result = MultiIndex(\n levels=levels, codes=codes, verify_integrity=False, names=self.names\n )\n return result\n\n def get_group_levels(self):\n if not self.compressed and len(self.groupings) == 1:\n return [self.groupings[0].result_index]\n\n name_list = []\n for ping, labels in zip(self.groupings, self.recons_labels):\n labels = ensure_platform_int(labels)\n levels = ping.result_index.take(labels)\n\n name_list.append(levels)\n\n return name_list\n\n # ------------------------------------------------------------\n # Aggregation functions\n\n _cython_functions = {\n \"aggregate\": {\n \"add\": \"group_add\",\n \"prod\": \"group_prod\",\n \"min\": \"group_min\",\n \"max\": \"group_max\",\n \"mean\": \"group_mean\",\n \"median\": \"group_median\",\n \"var\": \"group_var\",\n \"first\": \"group_nth\",\n \"last\": \"group_last\",\n \"ohlc\": \"group_ohlc\",\n },\n \"transform\": {\n \"cumprod\": \"group_cumprod\",\n \"cumsum\": \"group_cumsum\",\n \"cummin\": \"group_cummin\",\n \"cummax\": \"group_cummax\",\n \"rank\": \"group_rank\",\n },\n }\n\n _cython_arity = {\"ohlc\": 4} # OHLC\n\n _name_functions = {\"ohlc\": lambda *args: [\"open\", \"high\", \"low\", \"close\"]}\n\n def _is_builtin_func(self, arg):\n \"\"\"\n if we define an builtin function for this argument, return it,\n otherwise return the arg\n \"\"\"\n return SelectionMixin._builtin_table.get(arg, arg)\n\n def _get_cython_function(self, kind, how, values, is_numeric):\n\n dtype_str = values.dtype.name\n\n def get_func(fname):\n # see if there is a fused-type version of function\n # only valid for numeric\n f = getattr(libgroupby, fname, None)\n if f is not None and is_numeric:\n return f\n\n # otherwise find dtype-specific version, falling back to object\n for dt in [dtype_str, \"object\"]:\n f2 = getattr(\n libgroupby,\n \"{fname}_{dtype_str}\".format(fname=fname, dtype_str=dt),\n None,\n )\n if f2 is not None:\n return f2\n\n if hasattr(f, \"__signatures__\"):\n # inspect what fused types are implemented\n if dtype_str == \"object\" and \"object\" not in f.__signatures__:\n # return None so we get a NotImplementedError below\n # instead of a TypeError at runtime\n return None\n return f\n\n ftype = self._cython_functions[kind][how]\n\n func = get_func(ftype)\n\n if func is None:\n raise NotImplementedError(\n \"function is not implemented for this dtype: \"\n \"[how->{how},dtype->{dtype_str}]\".format(how=how, dtype_str=dtype_str)\n )\n\n return func\n\n def _cython_operation(self, kind: str, values, how, axis, min_count=-1, **kwargs):\n assert kind in [\"transform\", \"aggregate\"]\n orig_values = values\n\n # can we do this operation with our cython functions\n # if not raise NotImplementedError\n\n # we raise NotImplemented if this is an invalid operation\n # entirely, e.g. adding datetimes\n\n # categoricals are only 1d, so we\n # are not setup for dim transforming\n if is_categorical_dtype(values) or is_sparse(values):\n raise NotImplementedError(\n \"{dtype} dtype not supported\".format(dtype=values.dtype)\n )\n elif is_datetime64_any_dtype(values):\n if how in [\"add\", \"prod\", \"cumsum\", \"cumprod\"]:\n raise NotImplementedError(\n \"datetime64 type does not support {how} operations\".format(how=how)\n )\n elif is_timedelta64_dtype(values):\n if how in [\"prod\", \"cumprod\"]:\n raise NotImplementedError(\n \"timedelta64 type does not support {how} operations\".format(how=how)\n )\n\n if is_datetime64tz_dtype(values.dtype):\n # Cast to naive; we'll cast back at the end of the function\n # TODO: possible need to reshape? kludge can be avoided when\n # 2D EA is allowed.\n values = values.view(\"M8[ns]\")\n\n is_datetimelike = needs_i8_conversion(values.dtype)\n is_numeric = is_numeric_dtype(values.dtype)\n\n if is_datetimelike:\n values = values.view(\"int64\")\n is_numeric = True\n elif is_bool_dtype(values.dtype):\n values = ensure_float64(values)\n elif is_integer_dtype(values):\n # we use iNaT for the missing value on ints\n # so pre-convert to guard this condition\n if (values == iNaT).any():\n values = ensure_float64(values)\n else:\n values = ensure_int_or_float(values)\n elif is_numeric and not is_complex_dtype(values):\n values = ensure_float64(values)\n else:\n values = values.astype(object)\n\n arity = self._cython_arity.get(how, 1)\n\n vdim = values.ndim\n swapped = False\n if vdim == 1:\n values = values[:, None]\n out_shape = (self.ngroups, arity)\n else:\n if axis > 0:\n swapped = True\n assert axis == 1, axis\n values = values.T\n if arity > 1:\n raise NotImplementedError(\n \"arity of more than 1 is not supported for the 'how' argument\"\n )\n out_shape = (self.ngroups,) + values.shape[1:]\n\n try:\n func = self._get_cython_function(kind, how, values, is_numeric)\n except NotImplementedError:\n if is_numeric:\n try:\n values = ensure_float64(values)\n except TypeError:\n if lib.infer_dtype(values, skipna=False) == \"complex\":\n values = values.astype(complex)\n else:\n raise\n func = self._get_cython_function(kind, how, values, is_numeric)\n else:\n raise\n\n if how == \"rank\":\n out_dtype = \"float\"\n else:\n if is_numeric:\n out_dtype = \"{kind}{itemsize}\".format(\n kind=values.dtype.kind, itemsize=values.dtype.itemsize\n )\n else:\n out_dtype = \"object\"\n\n labels, _, _ = self.group_info\n\n if kind == \"aggregate\":\n result = _maybe_fill(\n np.empty(out_shape, dtype=out_dtype), fill_value=np.nan\n )\n counts = np.zeros(self.ngroups, dtype=np.int64)\n result = self._aggregate(\n result, counts, values, labels, func, is_datetimelike, min_count\n )\n elif kind == \"transform\":\n result = _maybe_fill(\n np.empty_like(values, dtype=out_dtype), fill_value=np.nan\n )\n\n # TODO: min_count\n result = self._transform(\n result, values, labels, func, is_datetimelike, **kwargs\n )\n\n if is_integer_dtype(result) and not is_datetimelike:\n mask = result == iNaT\n if mask.any():\n result = result.astype(\"float64\")\n result[mask] = np.nan\n\n if kind == \"aggregate\" and self._filter_empty_groups and not counts.all():\n assert result.ndim != 2\n result = result[counts > 0]\n\n if vdim == 1 and arity == 1:\n result = result[:, 0]\n\n if how in self._name_functions:\n names = self._name_functions[how]() # type: Optional[List[str]]\n else:\n names = None\n\n if swapped:\n result = result.swapaxes(0, axis)\n\n if is_datetime64tz_dtype(orig_values.dtype):\n result = type(orig_values)(result.astype(np.int64), dtype=orig_values.dtype)\n elif is_datetimelike and kind == \"aggregate\":\n result = result.astype(orig_values.dtype)\n\n return result, names\n\n def aggregate(self, values, how, axis=0, min_count=-1):\n return self._cython_operation(\n \"aggregate\", values, how, axis, min_count=min_count\n )\n\n def transform(self, values, how, axis=0, **kwargs):\n return self._cython_operation(\"transform\", values, how, axis, **kwargs)\n\n def _aggregate(\n self, result, counts, values, comp_ids, agg_func, is_datetimelike, min_count=-1\n ):\n if values.ndim > 2:\n # punting for now\n raise NotImplementedError(\"number of dimensions is currently limited to 2\")\n elif agg_func is libgroupby.group_nth:\n # different signature from the others\n # TODO: should we be using min_count instead of hard-coding it?\n agg_func(result, counts, values, comp_ids, rank=1, min_count=-1)\n else:\n agg_func(result, counts, values, comp_ids, min_count)\n\n return result\n\n def _transform(\n self, result, values, comp_ids, transform_func, is_datetimelike, **kwargs\n ):\n\n comp_ids, _, ngroups = self.group_info\n if values.ndim > 2:\n # punting for now\n raise NotImplementedError(\"number of dimensions is currently limited to 2\")\n else:\n transform_func(result, values, comp_ids, ngroups, is_datetimelike, **kwargs)\n\n return result\n\n def agg_series(self, obj, func):\n if is_extension_array_dtype(obj.dtype) and obj.dtype.kind != \"M\":\n # _aggregate_series_fast would raise TypeError when\n # calling libreduction.Slider\n # TODO: can we get a performant workaround for EAs backed by ndarray?\n # TODO: is the datetime64tz case supposed to go through here?\n return self._aggregate_series_pure_python(obj, func)\n\n elif obj.index._has_complex_internals:\n # MultiIndex; Pre-empt TypeError in _aggregate_series_fast\n return self._aggregate_series_pure_python(obj, func)\n\n try:\n return self._aggregate_series_fast(obj, func)\n except ValueError as err:\n if \"No result.\" in str(err):\n # raised in libreduction\n pass\n elif \"Function does not reduce\" in str(err):\n # raised in libreduction\n pass\n else:\n raise\n return self._aggregate_series_pure_python(obj, func)\n\n def _aggregate_series_fast(self, obj, func):\n func = self._is_builtin_func(func)\n\n # TODO: pre-empt this, also pre-empt get_result raising TypError if we pass a EA\n # for EAs backed by ndarray we may have a performant workaround\n if obj.index._has_complex_internals:\n raise TypeError(\"Incompatible index for Cython grouper\")\n\n group_index, _, ngroups = self.group_info\n\n # avoids object / Series creation overhead\n dummy = obj._get_values(slice(None, 0))\n indexer = get_group_index_sorter(group_index, ngroups)\n obj = obj.take(indexer)\n group_index = algorithms.take_nd(group_index, indexer, allow_fill=False)\n grouper = libreduction.SeriesGrouper(obj, func, group_index, ngroups, dummy)\n result, counts = grouper.get_result()\n return result, counts\n\n def _aggregate_series_pure_python(self, obj, func):\n\n group_index, _, ngroups = self.group_info\n\n counts = np.zeros(ngroups, dtype=int)\n result = None\n\n splitter = get_splitter(obj, group_index, ngroups, axis=self.axis)\n\n for label, group in splitter:\n res = func(group)\n if result is None:\n if isinstance(res, (Series, Index, np.ndarray)):\n raise ValueError(\"Function does not reduce\")\n result = np.empty(ngroups, dtype=\"O\")\n\n counts[label] = group.shape[0]\n result[label] = res\n\n result = lib.maybe_convert_objects(result, try_float=0)\n # TODO: try_cast back to EA?\n return result, counts\n\n\nclass BinGrouper(BaseGrouper):\n \"\"\"\n This is an internal Grouper class\n\n Parameters\n ----------\n bins : the split index of binlabels to group the item of axis\n binlabels : the label list\n filter_empty : boolean, default False\n mutated : boolean, default False\n indexer : a intp array\n\n Examples\n --------\n bins: [2, 4, 6, 8, 10]\n binlabels: DatetimeIndex(['2005-01-01', '2005-01-03',\n '2005-01-05', '2005-01-07', '2005-01-09'],\n dtype='datetime64[ns]', freq='2D')\n\n the group_info, which contains the label of each item in grouped\n axis, the index of label in label list, group number, is\n\n (array([0, 0, 1, 1, 2, 2, 3, 3, 4, 4]), array([0, 1, 2, 3, 4]), 5)\n\n means that, the grouped axis has 10 items, can be grouped into 5\n labels, the first and second items belong to the first label, the\n third and forth items belong to the second label, and so on\n\n \"\"\"\n\n def __init__(\n self, bins, binlabels, filter_empty=False, mutated=False, indexer=None\n ):\n self.bins = ensure_int64(bins)\n self.binlabels = ensure_index(binlabels)\n self._filter_empty_groups = filter_empty\n self.mutated = mutated\n self.indexer = indexer\n\n @cache_readonly\n def groups(self):\n \"\"\" dict {group name -> group labels} \"\"\"\n\n # this is mainly for compat\n # GH 3881\n result = {\n key: value\n for key, value in zip(self.binlabels, self.bins)\n if key is not NaT\n }\n return result\n\n @property\n def nkeys(self):\n return 1\n\n def _get_grouper(self):\n \"\"\"\n We are a grouper as part of another's groupings.\n\n We have a specific method of grouping, so cannot\n convert to a Index for our grouper.\n \"\"\"\n return self\n\n def get_iterator(self, data: NDFrame, axis: int = 0):\n \"\"\"\n Groupby iterator\n\n Returns\n -------\n Generator yielding sequence of (name, subsetted object)\n for each group\n \"\"\"\n slicer = lambda start, edge: data._slice(slice(start, edge), axis=axis)\n length = len(data.axes[axis])\n\n start = 0\n for edge, label in zip(self.bins, self.binlabels):\n if label is not NaT:\n yield label, slicer(start, edge)\n start = edge\n\n if start < length:\n yield self.binlabels[-1], slicer(start, None)\n\n @cache_readonly\n def indices(self):\n indices = collections.defaultdict(list)\n\n i = 0\n for label, bin in zip(self.binlabels, self.bins):\n if i < bin:\n if label is not NaT:\n indices[label] = list(range(i, bin))\n i = bin\n return indices\n\n @cache_readonly\n def group_info(self):\n ngroups = self.ngroups\n obs_group_ids = np.arange(ngroups)\n rep = np.diff(np.r_[0, self.bins])\n\n rep = ensure_platform_int(rep)\n if ngroups == len(self.bins):\n comp_ids = np.repeat(np.arange(ngroups), rep)\n else:\n comp_ids = np.repeat(np.r_[-1, np.arange(ngroups)], rep)\n\n return (\n comp_ids.astype(\"int64\", copy=False),\n obs_group_ids.astype(\"int64\", copy=False),\n ngroups,\n )\n\n @cache_readonly\n def result_index(self):\n if len(self.binlabels) != 0 and isna(self.binlabels[0]):\n return self.binlabels[1:]\n\n return self.binlabels\n\n @property\n def levels(self):\n return [self.binlabels]\n\n @property\n def names(self):\n return [self.binlabels.name]\n\n @property\n def groupings(self):\n from pandas.core.groupby.grouper import Grouping\n\n return [\n Grouping(lvl, lvl, in_axis=False, level=None, name=name)\n for lvl, name in zip(self.levels, self.names)\n ]\n\n def agg_series(self, obj, func):\n dummy = obj[:0]\n grouper = libreduction.SeriesBinGrouper(obj, func, self.bins, dummy)\n return grouper.get_result()\n\n\ndef _get_axes(group):\n if isinstance(group, Series):\n return [group.index]\n else:\n return group.axes\n\n\ndef _is_indexed_like(obj, axes) -> bool:\n if isinstance(obj, Series):\n if len(axes) > 1:\n return False\n return obj.index.equals(axes[0])\n elif isinstance(obj, DataFrame):\n return obj.index.equals(axes[0])\n\n return False\n\n\n# ----------------------------------------------------------------------\n# Splitting / application\n\n\nclass DataSplitter:\n def __init__(self, data, labels, ngroups, axis=0):\n self.data = data\n self.labels = ensure_int64(labels)\n self.ngroups = ngroups\n\n self.axis = axis\n\n @cache_readonly\n def slabels(self):\n # Sorted labels\n return algorithms.take_nd(self.labels, self.sort_idx, allow_fill=False)\n\n @cache_readonly\n def sort_idx(self):\n # Counting sort indexer\n return get_group_index_sorter(self.labels, self.ngroups)\n\n def __iter__(self):\n sdata = self._get_sorted_data()\n\n if self.ngroups == 0:\n # we are inside a generator, rather than raise StopIteration\n # we merely return signal the end\n return\n\n starts, ends = lib.generate_slices(self.slabels, self.ngroups)\n\n for i, (start, end) in enumerate(zip(starts, ends)):\n # Since I'm now compressing the group ids, it's now not \"possible\"\n # to produce empty slices because such groups would not be observed\n # in the data\n # if start >= end:\n # raise AssertionError('Start %s must be less than end %s'\n # % (str(start), str(end)))\n yield i, self._chop(sdata, slice(start, end))\n\n def _get_sorted_data(self):\n return self.data.take(self.sort_idx, axis=self.axis)\n\n def _chop(self, sdata, slice_obj):\n raise AbstractMethodError(self)\n\n def apply(self, f):\n raise AbstractMethodError(self)\n\n\nclass SeriesSplitter(DataSplitter):\n def _chop(self, sdata, slice_obj):\n return sdata._get_values(slice_obj)\n\n\nclass FrameSplitter(DataSplitter):\n def fast_apply(self, f, names):\n # must return keys::list, values::list, mutated::bool\n starts, ends = lib.generate_slices(self.slabels, self.ngroups)\n\n sdata = self._get_sorted_data()\n return libreduction.apply_frame_axis0(sdata, f, names, starts, ends)\n\n def _chop(self, sdata, slice_obj):\n if self.axis == 0:\n return sdata.iloc[slice_obj]\n else:\n return sdata._slice(slice_obj, axis=1)\n\n\ndef get_splitter(data, *args, **kwargs):\n if isinstance(data, Series):\n klass = SeriesSplitter\n elif isinstance(data, DataFrame):\n klass = FrameSplitter\n\n return klass(data, *args, **kwargs)\n" ]
[ [ "pandas._libs.reduction.SeriesBinGrouper", "pandas.core.sorting.get_group_index", "pandas.core.dtypes.common.is_datetime64_any_dtype", "pandas.core.sorting.get_group_index_sorter", "pandas.core.index.MultiIndex", "pandas.core.dtypes.common.ensure_platform_int", "numpy.bincount", "pandas.core.dtypes.missing.isna", "pandas.core.index.Index", "pandas._libs.lib.infer_dtype", "numpy.empty", "pandas.core.dtypes.common.is_datetime64tz_dtype", "pandas.core.dtypes.common.is_extension_array_dtype", "numpy.arange", "pandas.core.dtypes.common.is_integer_dtype", "numpy.empty_like", "pandas._libs.lib.maybe_convert_objects", "pandas.errors.AbstractMethodError", "numpy.zeros", "pandas.core.sorting.get_indexer_dict", "pandas.core.index.ensure_index", "numpy.lexsort", "pandas.core.groupby.grouper.Grouping", "pandas.core.common.values_from_object", "numpy.diff", "pandas.core.dtypes.common.is_timedelta64_dtype", "pandas.core.dtypes.common.ensure_int64", "pandas.core.dtypes.common.is_complex_dtype", "pandas.core.base.SelectionMixin._builtin_table.get", "pandas.core.sorting.decons_obs_group_ids", "pandas.core.sorting.compress_group_index", "pandas._libs.lib.generate_slices", "pandas.core.common.get_callable_name", "pandas.core.series.Series", "pandas.core.dtypes.common.is_sparse", "pandas._libs.reduction.SeriesGrouper", "pandas.core.sorting.get_flattened_iterator", "pandas.core.dtypes.common.is_numeric_dtype", "pandas.core.dtypes.common.ensure_float64", "pandas.core.dtypes.common.ensure_int_or_float", "pandas.core.dtypes.common.needs_i8_conversion", "pandas.core.dtypes.common.is_categorical_dtype", "pandas.core.algorithms.take_nd", "pandas.core.dtypes.common.is_bool_dtype", "pandas._libs.reduction.apply_frame_axis0" ] ]
angela18199/CORL_hyperparameter_search
[ "c2cfc4c4e34dedb65929a8b7d68c61e53681a67c" ]
[ "hyper_attention/run.py" ]
[ "#!/usr/bin/env python\n\nimport os\nimport json\nimport pprint as pp\nfrom time import time\n\nimport torch\nimport torch.optim as optim\nfrom tensorboard_logger import Logger as TbLogger\n\nfrom nets.critic_network import CriticNetwork\nfrom options import get_options\nfrom train import train_epoch, validate, get_inner_model\nfrom reinforce_baselines import NoBaseline, ExponentialBaseline, CriticBaseline, RolloutBaseline, WarmupBaseline\nfrom nets.attention_model import AttentionModel\nfrom nets.pointer_network import PointerNetwork, CriticNetworkLSTM\nfrom utils import torch_load_cpu, load_problem\nimport pickle\n\n# for hyperparameter tuning using wanb\n# https://docs.wandb.ai/sweeps/quickstart\nimport torch.nn.functional as F\nimport torchvision.datasets as datasets\nimport torch.nn as nn\nimport wandb\nfrom torchvision import datasets, transforms\n\ndef run(opts):\n # start time\n start_time = time()\n train_run = []\n opts.save_hrs.sort()\n run_name = opts.run_name\n\n # Pretty print the run args\n pp.pprint(vars(opts))\n\n # Set the random seed\n torch.manual_seed(opts.seed)\n\n # Optionally configure tensorboard\n tb_logger = None\n if not opts.no_tensorboard:\n tb_logger = TbLogger(os.path.join(opts.log_dir, \"{}_{}\".format(opts.problem, opts.graph_size), opts.run_name))\n\n os.makedirs(opts.save_dir)\n # Save arguments so exact configuration can always be found\n with open(os.path.join(opts.save_dir, \"args.json\"), 'w') as f:\n json.dump(vars(opts), f, indent=True)\n\n # Set the device\n opts.device = torch.device(\"cuda:0\" if opts.use_cuda else \"cpu\")\n\n # Figure out what's the problem\n problem = load_problem(opts.problem)\n\n # Load data from load_path\n load_data = {}\n assert opts.load_path is None or opts.resume is None, \"Only one of load path and resume can be given\"\n load_path = opts.load_path if opts.load_path is not None else opts.resume\n if load_path is not None:\n print(' [*] Loading data from {}'.format(load_path))\n load_data = torch_load_cpu(load_path)\n\n # hyperparameter search\n # default (user specified) config\n config_defaults = {\n 'batch_size': opts.batch_size,\n 'lr_model': opts.lr_model,\n 'lr_critic': opts.lr_critic,\n 'lr_decay': opts.lr_decay,\n }\n\n # determine the parameter space\n \"\"\"sweep_config = {\n 'parameters': {\n 'batch_size': {\n 'values': [256, 128, 64, 32]\n },\n 'lr_model': {\n 'values': [1e-2, 1e-3, 1e-4, 3e-4, 3e-5, 1e-5]\n },\n 'lr_critic': {\n 'values': [1e-2, 1e-3, 1e-4, 3e-4, 3e-5, 1e-5]\n },\n 'lr_decay': {\n 'lr_decay': [0.9, 0.95, 1.0, 1.05, 1.1, 1.15]\n },\n }\n }\"\"\"\n # initialize the sweep\n # sweep_id = wandb.sweep(sweep_config, project=\"Pytorch-sweeps\")\n\n # Initialize a new wandb run\n wandb.init(config=config_defaults)\n \n # Config is a variable that holds and saves hyperparameters and inputs\n config = wandb.config\n\n # ??? any code for setting up hyperparameters interested should use config.parameter to set instead of opt.parameter\n # including functions in other files-> pass config to other functions\n\n # Initialize model\n model_class = {\n 'attention': AttentionModel,\n 'pointer': PointerNetwork\n }.get(opts.model, None)\n assert model_class is not None, \"Unknown model: {}\".format(model_class)\n model = model_class(\n opts.embedding_dim,\n opts.hidden_dim,\n problem,\n n_encode_layers=opts.n_encode_layers,\n mask_inner=True,\n mask_logits=True,\n normalization=opts.normalization,\n tanh_clipping=opts.tanh_clipping,\n checkpoint_encoder=opts.checkpoint_encoder,\n shrink_size=opts.shrink_size\n ).to(opts.device)\n\n if opts.use_cuda and torch.cuda.device_count() > 1:\n model = torch.nn.DataParallel(model)\n\n # Overwrite model parameters by parameters to load\n model_ = get_inner_model(model)\n model_.load_state_dict({**model_.state_dict(), **load_data.get('model', {})})\n\n # Initialize baseline\n if opts.baseline == 'exponential':\n baseline = ExponentialBaseline(opts.exp_beta)\n elif opts.baseline == 'critic' or opts.baseline == 'critic_lstm':\n assert problem.NAME == 'tsp', \"Critic only supported for TSP\"\n baseline = CriticBaseline(\n (\n CriticNetworkLSTM(\n 2,\n opts.embedding_dim,\n opts.hidden_dim,\n opts.n_encode_layers,\n opts.tanh_clipping\n )\n if opts.baseline == 'critic_lstm'\n else\n CriticNetwork(\n 2,\n opts.embedding_dim,\n opts.hidden_dim,\n opts.n_encode_layers,\n opts.normalization\n )\n ).to(opts.device)\n )\n elif opts.baseline == 'rollout':\n baseline = RolloutBaseline(model, problem, opts)\n else:\n assert opts.baseline is None, \"Unknown baseline: {}\".format(opts.baseline)\n baseline = NoBaseline()\n\n if opts.bl_warmup_epochs > 0:\n baseline = WarmupBaseline(baseline, opts.bl_warmup_epochs, warmup_exp_beta=opts.exp_beta)\n\n # Load baseline from data, make sure script is called with same type of baseline\n if 'baseline' in load_data:\n baseline.load_state_dict(load_data['baseline'])\n\n # Initialize optimizer\n optimizer = optim.Adam(\n [{'params': model.parameters(), 'lr': config.lr_model}]\n + (\n [{'params': baseline.get_learnable_parameters(), 'lr': config.lr_critic}]\n if len(baseline.get_learnable_parameters()) > 0\n else []\n )\n )\n\n # Load optimizer state\n if 'optimizer' in load_data:\n optimizer.load_state_dict(load_data['optimizer'])\n for state in optimizer.state.values():\n for k, v in state.items():\n # if isinstance(v, torch.Tensor):\n if torch.is_tensor(v):\n state[k] = v.to(opts.device)\n\n # Initialize learning rate scheduler, decay by lr_decay once per epoch!\n lr_scheduler = optim.lr_scheduler.LambdaLR(optimizer, lambda epoch: config.lr_decay ** epoch)\n\n # Start the actual training loop\n val_dataset = problem.make_dataset(\n size=opts.graph_size, num_samples=opts.val_size, filename=opts.val_dataset, distribution=opts.data_distribution)\n\n if opts.resume:\n epoch_resume = int(os.path.splitext(os.path.split(opts.resume)[-1])[0].split(\"-\")[1])\n\n torch.set_rng_state(load_data['rng_state'])\n if opts.use_cuda:\n torch.cuda.set_rng_state_all(load_data['cuda_rng_state'])\n # Set the random states\n # Dumping of state was done before epoch callback, so do that now (model is loaded)\n baseline.epoch_callback(model, epoch_resume)\n print(\"Resuming after {}\".format(epoch_resume))\n opts.epoch_start = epoch_resume + 1\n\n torch.save(model, os.path.join('.', 'empty.pt'))\n if opts.eval_only:\n validate(model, val_dataset, opts)\n else:\n for epoch in range(opts.epoch_start, opts.epoch_start + opts.n_epochs):\n avg_time = train_epoch(\n model,\n optimizer,\n baseline,\n lr_scheduler,\n epoch,\n val_dataset,\n problem,\n tb_logger,\n opts,\n start_time,\n config\n )\n train_run.append(avg_time)\n for hr in opts.save_hrs:\n if (time() - start_time) > hr*3600:\n opts.save_hrs.remove(hr)\n print('Saving model and state...')\n hr_time = int(round((time()-start_time)/3600))\n with open('../models/att/hist_{}_{}hr.pickle'.format(run_name,hr_time), 'wb') as handle:\n pickle.dump(train_run, handle, protocol=pickle.HIGHEST_PROTOCOL)\n torch.save(\n {\n 'model': get_inner_model(model).state_dict(),\n 'optimizer': optimizer.state_dict(),\n 'rng_state': torch.get_rng_state(),\n 'cuda_rng_state': torch.cuda.get_rng_state_all(),\n 'baseline': baseline.state_dict()\n },\n os.path.join('../models/att', '{}_{}hr-model-att-only.pt'.format(run_name,hr_time))\n )\n torch.save(model, os.path.join('../models/att', '{}_{}hr-model.pt'.format(run_name,hr_time)))\nif __name__ == \"__main__\":\n run(get_options())\n" ]
[ [ "torch.device", "torch.cuda.get_rng_state_all", "torch.get_rng_state", "torch.cuda.set_rng_state_all", "torch.is_tensor", "torch.cuda.device_count", "torch.manual_seed", "torch.set_rng_state", "torch.optim.lr_scheduler.LambdaLR", "torch.nn.DataParallel" ] ]
CopperHu/tequila
[ "e361af51e9716b347f79640ce5a968e92b8585f8" ]
[ "src/tequila/quantumchemistry/qc_base.py" ]
[ "import os\nfrom dataclasses import dataclass\nfrom tequila import TequilaException, BitString, TequilaWarning\nfrom tequila.hamiltonian import QubitHamiltonian\nfrom tequila.wavefunction import QubitWaveFunction\nfrom tequila.hamiltonian.paulis import Sp, Sm, Qp, Qm\n\nfrom tequila.circuit import QCircuit, gates, _gates_impl\nfrom tequila.objective.objective import Variable, Variables, ExpectationValue\n\nfrom tequila.simulators.simulator_api import simulate\nfrom tequila.utils import to_float\n\nfrom tequila.objective import assign_variable\n\nfrom .encodings import known_encodings\n\nimport typing, numpy, numbers, copy\nfrom itertools import product\n\n# if you are experiencing import errors you need to update openfermion\n# required is version >= 1.0\n# otherwise replace with from openfermion.hamiltonians import MolecularData\nimport openfermion\nfrom openfermion.chem import MolecularData\n\nimport warnings\n\n\n@dataclass\nclass ActiveSpaceData:\n active_orbitals: list # active orbitals (spatial, c1)\n reference_orbitals: list # reference orbitals (spatial, c1)\n\n def __str__(self):\n result = \"Active Space Data:\\n\"\n result += \"{key:15} : {value:15} \\n\".format(key=\"active_orbitals\", value=str(self.active_orbitals))\n result += \"{key:15} : {value:15} \\n\".format(key=\"reference_orbitals\",\n value=str(self.reference_orbitals))\n result += \"{key:15} : {value:15} \\n\".format(key=\"frozen_docc\", value=str(self.frozen_docc))\n result += \"{key:15} : {value:15} \\n\".format(key=\"frozen_uocc\", value=str(self.frozen_uocc))\n return result\n\n @property\n def frozen_reference_orbitals(self):\n return [i for i in self.reference_orbitals if i not in self.active_orbitals]\n\n @property\n def active_reference_orbitals(self):\n return [i for i in self.reference_orbitals if i in self.active_orbitals]\n\n\nclass FermionicGateImpl(gates.QubitExcitationImpl):\n # keep the overview in circuits\n def __init__(self, generator, p0, transformation, *args, **kwargs):\n super().__init__(generator=generator, target=generator.qubits, p0=p0, *args, **kwargs)\n self._name = \"FermionicExcitation\"\n self.transformation=transformation\n\n def compile(self):\n return gates.Trotterized(generator=self.generator, control=self.control, angle=self.parameter, steps=1)\n\ndef prepare_product_state(state: BitString) -> QCircuit:\n \"\"\"Small convenience function\n\n Parameters\n ----------\n state :\n product state encoded into a bitstring\n state: BitString :\n\n\n Returns\n -------\n type\n unitary circuit which prepares the product state\n\n \"\"\"\n result = QCircuit()\n for i, v in enumerate(state.array):\n if v == 1:\n result += gates.X(target=i)\n return result\n\n\n@dataclass\nclass ParametersQC:\n \"\"\"Specialization of ParametersHamiltonian\"\"\"\n basis_set: str = None # Quantum chemistry basis set\n geometry: str = None # geometry of the underlying molecule (units: Angstrom!),\n # this can be a filename leading to an .xyz file or the geometry given as a string\n description: str = \"\"\n multiplicity: int = 1\n charge: int = 0\n name: str = None\n \n @property\n def n_electrons(self, *args, **kwargs):\n return self.get_nuc_charge() - self.charge\n \n def get_nuc_charge(self):\n return sum(self.get_atom_number(name=atom) for atom in self.get_atoms())\n\n def get_atom_number(self, name):\n atom_numbers={\"h\":1, \"he\":2, \"li\":3, \"be\":4, \"b\":5, \"c\":6, \"n\":7, \"o\":8, \"f\":9, \"ne\":10, \"na\":11, \"mg\":12, \"al\":13, \"si\":14, \"ph\":15, \"s\":16, \"cl\":17, \"ar\":18}\n if name.lower() in atom_numbers:\n return atom_numbers[name.lower()]\n try:\n import periodictable as pt\n atom=name.lower()\n atom[0]=atom[0].upper()\n element = pt.elements.symbol(atom)\n return element.number()\n except:\n raise TequilaException(\"can not assign atomic number to element {}\\npip install periodictable will fix it\".format(atom))\n\n\n def get_atoms(self):\n return [x[0] for x in self.get_geometry()]\n \n def __post_init__(self,*args, **kwargs):\n\n if self.name is None and self.geometry is None:\n raise TequilaException(\"no geometry or name given to molecule\\nprovide geometry=filename.xyz or geometry=`h 0.0 0.0 0.0\\\\n...`\\nor name=whatever with file whatever.xyz being present\")\n # auto naming\n if self.name is None:\n if \".xyz\" in self.geometry:\n self.name=self.geometry.split(\".xyz\")[0]\n if self.description is None:\n coord, description = self.read_xyz_from_file()\n self.description=description\n else:\n atoms=self.get_atoms()\n atom_names=sorted(list(set(atoms)), key=lambda x: self.get_atom_number(x), reverse=True)\n if self.name is None:\n drop_ones=lambda x: \"\" if x==1 else x\n self.name=\"\".join([\"{}{}\".format(x,drop_ones(atoms.count(x))) for x in atom_names])\n self.name = self.name.lower()\n \n if self.geometry is None:\n self.geometry=self.name+\".xyz\"\n \n if \".xyz\" in self.geometry and not os.path.isfile(self.geometry):\n raise TequilaException(\"could not find file for molecular coordinates {}\".format(self.geometry))\n\n @property\n def filename(self):\n \"\"\" \"\"\"\n return \"{}_{}\".format(self.name, self.basis_set)\n\n @property\n def molecular_data_param(self) -> dict:\n \"\"\":return: Give back all parameters for the MolecularData format from openfermion as dictionary\"\"\"\n return {'basis': self.basis_set, 'geometry': self.get_geometry(), 'description': self.description,\n 'charge': self.charge, 'multiplicity': self.multiplicity, 'filename': self.filename\n }\n\n @staticmethod\n def format_element_name(string):\n \"\"\"OpenFermion uses case sensitive hash tables for chemical elements\n I.e. you need to name Lithium: 'Li' and 'li' or 'LI' will not work\n this convenience function does the naming\n :return: first letter converted to upper rest to lower\n\n Parameters\n ----------\n string :\n\n\n Returns\n -------\n\n \"\"\"\n assert (len(string) > 0)\n assert (isinstance(string, str))\n fstring = string[0].upper() + string[1:].lower()\n return fstring\n\n @staticmethod\n def convert_to_list(geometry):\n \"\"\"Convert a molecular structure given as a string into a list suitable for openfermion\n\n Parameters\n ----------\n geometry :\n a string specifying a mol. structure. E.g. geometry=\"h 0.0 0.0 0.0\\n h 0.0 0.0 1.0\"\n\n Returns\n -------\n type\n A list with the correct format for openfermion E.g return [ ['h',[0.0,0.0,0.0], [..]]\n\n \"\"\"\n result = []\n # Remove blank lines\n lines = [l for l in geometry.split(\"\\n\") if l]\n\n for line in lines:\n words = line.split()\n \n # Pad coordinates\n if len(words) < 4:\n words += [0.0] * (4 - len(words))\n\n try:\n tmp = (ParametersQC.format_element_name(words[0]),\n (float(words[1]), float(words[2]), float(words[3])))\n result.append(tmp)\n except ValueError:\n print(\"get_geometry list unknown line:\\n \", line, \"\\n proceed with caution!\")\n return result\n\n def get_geometry_string(self) -> str:\n \"\"\"returns the geometry as a string\n :return: geometry string\n\n Parameters\n ----------\n\n Returns\n -------\n\n \"\"\"\n if self.geometry.split('.')[-1] == 'xyz':\n geomstring, comment = self.read_xyz_from_file(self.geometry)\n if comment is not None:\n self.description = comment\n return geomstring\n else:\n return self.geometry\n\n def get_geometry(self):\n \"\"\"Returns the geometry\n If a xyz filename was given the file is read out\n otherwise it is assumed that the geometry was given as string\n which is then reformatted as a list usable as input for openfermion\n :return: geometry as list\n e.g. [(h,(0.0,0.0,0.35)),(h,(0.0,0.0,-0.35))]\n Units: Angstrom!\n\n Parameters\n ----------\n\n Returns\n -------\n\n \"\"\"\n if self.geometry.split('.')[-1] == 'xyz':\n geomstring, comment = self.read_xyz_from_file(self.geometry)\n if self.description == '':\n self.description = comment\n return self.convert_to_list(geomstring)\n elif self.geometry is not None:\n return self.convert_to_list(self.geometry)\n else:\n raise Exception(\"Parameters.qc.geometry is None\")\n\n @staticmethod\n def read_xyz_from_file(filename):\n \"\"\"Read XYZ filetype for molecular structures\n https://en.wikipedia.org/wiki/XYZ_file_format\n Units: Angstrom!\n\n Parameters\n ----------\n filename :\n return:\n\n Returns\n -------\n\n \"\"\"\n with open(filename, 'r') as file:\n content = file.readlines()\n natoms = int(content[0])\n comment = str(content[1]).strip('\\n')\n coord = ''\n for i in range(natoms):\n coord += content[2 + i]\n return coord, comment\n\n\n@dataclass\nclass ClosedShellAmplitudes:\n \"\"\" \"\"\"\n tIjAb: numpy.ndarray = None\n tIA: numpy.ndarray = None\n\n def make_parameter_dictionary(self, threshold=1.e-8):\n \"\"\"\n\n Parameters\n ----------\n threshold :\n (Default value = 1.e-8)\n\n Returns\n -------\n\n \"\"\"\n variables = {}\n if self.tIjAb is not None:\n nvirt = self.tIjAb.shape[2]\n nocc = self.tIjAb.shape[0]\n assert (self.tIjAb.shape[1] == nocc and self.tIjAb.shape[3] == nvirt)\n for (I, J, A, B), value in numpy.ndenumerate(self.tIjAb):\n if not numpy.isclose(value, 0.0, atol=threshold):\n variables[(nocc + A, I, nocc + B, J)] = value\n if self.tIA is not None:\n nocc = self.tIA.shape[0]\n for (I, A), value, in numpy.ndenumerate(self.tIA):\n if not numpy.isclose(value, 0.0, atol=threshold):\n variables[(A + nocc, I)] = value\n return dict(sorted(variables.items(), key=lambda x: numpy.abs(x[1]), reverse=True))\n\n\n@dataclass\nclass Amplitudes:\n \"\"\"Coupled-Cluster Amplitudes\n We adopt the Psi4 notation for consistency\n I,A for alpha\n i,a for beta\n\n Parameters\n ----------\n\n Returns\n -------\n\n \"\"\"\n\n @classmethod\n def from_closed_shell(cls, cs: ClosedShellAmplitudes):\n \"\"\"\n Initialize from closed-shell Amplitude structure\n\n Parameters\n ----------\n cs: ClosedShellAmplitudes :\n\n\n Returns\n -------\n\n \"\"\"\n tijab = cs.tIjAb - numpy.einsum(\"ijab -> ijba\", cs.tIjAb, optimize='greedy')\n return cls(tIjAb=cs.tIjAb, tIA=cs.tIA, tiJaB=cs.tIjAb, tia=cs.tIA, tijab=tijab, tIJAB=tijab)\n\n tIjAb: numpy.ndarray = None\n tIA: numpy.ndarray = None\n tiJaB: numpy.ndarray = None\n tijab: numpy.ndarray = None\n tIJAB: numpy.ndarray = None\n tia: numpy.ndarray = None\n\n def make_parameter_dictionary(self, threshold=1.e-8):\n \"\"\"\n\n Parameters\n ----------\n threshold :\n (Default value = 1.e-8)\n Neglect amplitudes below the threshold\n\n Returns\n -------\n Dictionary of tequila variables (hash is in the style of (a,i,b,j))\n\n \"\"\"\n variables = {}\n if self.tIjAb is not None:\n nvirt = self.tIjAb.shape[2]\n nocc = self.tIjAb.shape[0]\n assert (self.tIjAb.shape[1] == nocc and self.tIjAb.shape[3] == nvirt)\n\n for (I, j, A, b), value in numpy.ndenumerate(self.tIjAb):\n if not numpy.isclose(value, 0.0, atol=threshold):\n variables[(2 * (nocc + A), 2 * I, 2 * (nocc + b) + 1, j + 1)] = value\n for (i, J, a, B), value in numpy.ndenumerate(self.tiJaB):\n if not numpy.isclose(value, 0.0, atol=threshold):\n variables[(2 * (nocc + a) + 1, 2 * i + 1, 2 * (nocc + B), J)] = value\n for (i, j, a, b), value in numpy.ndenumerate(self.tijab):\n if not numpy.isclose(value, 0.0, atol=threshold):\n variables[(2 * (nocc + a) + 1, 2 * i + 1, 2 * (nocc + b) + 1, j + 1)] = value\n for (I, J, A, B), value in numpy.ndenumerate(self.tijab):\n if not numpy.isclose(value, 0.0, atol=threshold):\n variables[(2 * (nocc + A), 2 * I, 2 * (nocc + B), J)] = value\n\n if self.tIA is not None:\n nocc = self.tIjAb.shape[0]\n assert (self.tia.shape[0] == nocc)\n for (I, A), value, in numpy.ndenumerate(self.tIA):\n if not numpy.isclose(value, 0.0, atol=threshold):\n variables[(2 * (A + nocc), 2 * I)] = value\n for (i, a), value, in numpy.ndenumerate(self.tIA):\n if not numpy.isclose(value, 0.0, atol=threshold):\n variables[(2 * (a + nocc) + 1, 2 * i + 1)] = value\n\n return variables\n\n\nclass NBodyTensor:\n \"\"\" Convenience class for handling N-body tensors \"\"\"\n\n class Ordering:\n def __init__(self, scheme):\n if hasattr(scheme, \"_scheme\"):\n scheme = scheme._scheme\n elif hasattr(scheme, \"scheme\"):\n scheme = scheme.scheme\n self._scheme = self.assign_scheme(scheme)\n\n def assign_scheme(self, scheme):\n if scheme is None:\n return \"chem\"\n else:\n scheme = str(scheme)\n\n if scheme.lower() in [\"mulliken\", \"chem\", \"c\", \"1122\"]:\n return \"chem\"\n elif scheme.lower() in [\"dirac\", \"phys\", \"p\", \"1212\"]:\n return \"phys\"\n elif scheme.lower() in [\"openfermion\", \"of\", \"o\", \"1221\"]:\n return \"of\"\n else:\n raise TequilaException(\n \"Unknown two-body tensor scheme {}. Supported are dirac, mulliken, and openfermion\".format(scheme))\n\n def is_phys(self):\n return self._scheme == \"phys\"\n\n def is_chem(self):\n return self._scheme == \"chem\"\n\n def is_of(self):\n return self._scheme == \"of\"\n\n def __init__(self, elems: numpy.ndarray = None, active_indices: list = None, ordering: str = None,\n size_full: int = None):\n \"\"\"\n Parameters\n ----------\n elems: Tensor data as numpy array\n active_indices: List of active indices in total ordering\n ordering: Ordering scheme for two body tensors\n \"dirac\" or \"phys\": <12|g|12>\n .. math::\n g_{pqrs} = \\\\int d1 d2 p(1)q(2) g(1,2) r(1)s(2)\n \"mulliken\" or \"chem\": (11|g|22)\n .. math::\n g_{pqrs} = \\\\int d1 d2 p(1)r(2) g(1,2) q(1)s(2)\n \"openfermion\":\n .. math:: [12|g|21]\n g_{gqprs} = \\\\int d1 d2 p(1)q(2) g(1,2) s(1)r(2)\n\n size_full\n \"\"\"\n\n # Set elements\n self.elems = elems\n # Active indices only as list of indices (e.g. spatial orbital indices), not as a dictionary of irreducible\n # representations\n if active_indices is not None:\n self.active_indices = active_indices\n self._passive_indices = None\n self._full_indices = None\n self._indices_set: bool = False\n\n # Determine order of tensor\n # Assume, that tensor is entered in desired shape, not as flat array.\n self.order = len(self.elems.shape)\n # Can use size_full < self.elems.shape[0] -> 'full' space is to be considered a subspace as well\n if size_full is None:\n self._size_full = self.elems.shape[0]\n else:\n self._size_full = size_full\n # 2-body tensors (<=> order 4) currently allow reordering\n if self.order == 4:\n self.ordering = self.Ordering(ordering)\n else:\n if ordering is not None:\n raise Exception(\"Ordering only implemented for tensors of order 4 / 2-body tensors.\")\n self.ordering = None\n\n def sub_lists(self, idx_lists: list = None) -> numpy.ndarray:\n \"\"\"\n Get subspace of tensor by a set of index lists\n according to hPQ.sub_lists(idx_lists=[p, q]) = [hPQ for P in p and Q in q]\n\n This essentially is an implementation of a non-contiguous slicing using numpy.take\n\n Parameters\n ----------\n idx_lists :\n List of lists, each defining the desired subspace per axis\n Size needs to match order of tensor, and lists successively correspond to axis=0,1,2,...,N\n\n Returns\n -------\n out :\n Sliced tensor as numpy.ndarray\n \"\"\"\n # Check if index list has correct size\n if len(idx_lists) != self.order:\n raise Exception(\"Need to pass an index list for each dimension!\" +\n \" Length of idx_lists needs to match order of tensor.\")\n\n # Perform slicing via numpy.take\n out = self.elems\n for ax in range(self.order):\n if idx_lists[ax] is not None: # None means, we want the full space in this direction\n out = numpy.take(out, idx_lists[ax], axis=ax)\n\n return out\n\n def set_index_lists(self):\n \"\"\" Set passive and full index lists based on class inputs \"\"\"\n tmp_size = self._size_full\n if self._size_full is None:\n tmp_size = self.elems.shape[0]\n\n self._passive_indices = [i for i in range(tmp_size)\n if i not in self.active_indices]\n self._full_indices = [i for i in range(tmp_size)]\n\n def sub_str(self, name: str) -> numpy.ndarray:\n \"\"\"\n Get subspace of tensor by a string\n Currently is able to resolve an active space, named 'a', full space 'f', and the complement 'p' = 'f' - 'a'.\n Full space in this context may also be smaller than actual tensor dimension.\n\n The specification of active space in this context only allows to pick a set from a list of orbitals, and\n is not able to resolve an active space from irreducible representations.\n\n Example for one-body tensor:\n hPQ.sub_lists(name='ap') = [hPQ for P in active_indices and Q in _passive_indices]\n\n Parameters\n ----------\n name :\n String specifying the desired subspace, elements need to be a (active), f (full), p (full - active)\n\n Returns\n -------\n out :\n Sliced tensor as numpy.ndarray\n \"\"\"\n if not self._indices_set:\n self.set_index_lists()\n self._indices_set = True\n\n if name is None:\n raise Exception(\"No name specified.\")\n if len(name) != self.order:\n raise Exception(\"Name does not match order of the tensor.\")\n if self.active_indices is None:\n raise Exception(\"Need to set an active space in order to call this function.\")\n\n idx_lists = []\n # Parse name as string of space indices\n for char in name:\n if char.lower() == 'a':\n idx_lists.append(self.active_indices)\n elif char.lower() == 'p':\n idx_lists.append(self._passive_indices)\n elif char.lower() == 'f':\n if self._size_full is None:\n idx_lists.append(None)\n else:\n idx_lists.append(self._full_indices)\n else:\n raise Exception(\"Need to specify a valid letter (a,p,f).\")\n\n out = self.sub_lists(idx_lists)\n\n return out\n\n def reorder(self, to: str = 'of'):\n \"\"\"\n Function to reorder tensors according to some convention.\n\n Parameters\n ----------\n to :\n Ordering scheme of choice.\n 'openfermion', 'of' (default) :\n openfermion - ordering, corresponds to integrals of the type\n h^pq_rs = int p(1)* q(2)* O(1,2) r(2) s(1) (O(1,2)\n with operators a^pq_rs = a^p a^q a_r a_s (a^p == a^dagger_p)\n currently needed for dependencies on openfermion-library\n 'chem', 'c' :\n quantum chemistry ordering, collect particle terms,\n more convenient for real-space methods\n h^pq_rs = int p(1) q(1) O(1,2) r(2) s(2)\n This is output by psi4\n 'phys', 'p' :\n typical physics ordering, integrals of type\n h^pq_rs = int p(1)* q(2)* O(1,2) r(1) s(2)\n with operators a^pq_rs = a^p a^q a_s a_r\n\n Returns\n -------\n \"\"\"\n if self.order != 4:\n raise Exception('Reordering currently only implemented for two-body tensors.')\n\n to = self.Ordering(to)\n\n if self.ordering == to:\n return self\n elif self.ordering.is_chem():\n if to.is_of():\n self.elems = numpy.einsum(\"psqr -> pqrs\", self.elems, optimize='greedy')\n elif to.is_phys():\n self.elems = numpy.einsum(\"prqs -> pqrs\", self.elems, optimize='greedy')\n elif self.ordering.is_of():\n if to.is_chem():\n self.elems = numpy.einsum(\"pqrs -> psqr\", self.elems, optimize='greedy')\n elif to.is_phys():\n self.elems = numpy.einsum(\"pqrs -> pqsr\", self.elems, optimize='greedy')\n elif self.ordering.is_phys():\n if to.is_chem():\n self.elems = numpy.einsum(\"pqrs -> prqs\", self.elems, optimize='greedy')\n elif to.is_of():\n self.elems = numpy.einsum(\"pqsr -> pqrs\", self.elems, optimize='greedy')\n\n return self\n\nclass QuantumChemistryBase:\n\n def __init__(self, parameters: ParametersQC,\n transformation: typing.Union[str, typing.Callable] = None,\n active_orbitals: list = None,\n *args,\n **kwargs):\n\n self.parameters = parameters\n\n if \"molecule\" in kwargs:\n self.molecule = kwargs[\"molecule\"]\n else:\n self.molecule = self.make_molecule(*args, **kwargs)\n\n assert (parameters.basis_set.lower() == self.molecule.basis.lower())\n assert (parameters.multiplicity == self.molecule.multiplicity)\n assert (parameters.charge == self.molecule.charge)\n\n self.active_space = None\n if active_orbitals is not None:\n self.active_space = self._make_active_space_data(active_orbitals=active_orbitals)\n\n self.transformation = self._initialize_transformation(transformation=transformation, *args, **kwargs)\n\n self._rdm1 = None\n self._rdm2 = None\n\n def _initialize_transformation(self, transformation=None, *args, **kwargs):\n\n if transformation is None:\n transformation = \"JordanWigner\"\n\n # filter out arguments to the transformation\n trafo_args = {k.split(\"__\")[1]: v for k, v in kwargs.items() if\n (hasattr(k, \"lower\") and \"transformation__\" in k.lower())}\n\n trafo_args[\"n_electrons\"] = self.n_electrons\n trafo_args[\"n_orbitals\"] = self.n_orbitals\n\n if hasattr(transformation, \"upper\"):\n # format to conventions\n transformation = transformation.replace(\"_\", \"\").replace(\"-\", \"\").upper()\n encodings = known_encodings()\n if transformation in encodings:\n transformation = encodings[transformation](**trafo_args)\n else:\n raise TequilaException(\n \"Unkown Fermion-to-Qubit encoding {}. Try something like: {}\".format(transformation,\n list(encodings.keys())))\n\n return transformation\n\n def _make_active_space_data(self, active_orbitals, reference=None):\n \"\"\"\n Small helper function\n Internal use only\n Parameters\n ----------\n active_orbitals: dictionary :\n list: Give a list of spatial orbital indices\n i.e. occ = [0,1,3] means that spatial orbital 0, 1 and 3 are used\n reference: (Default value=None)\n List of orbitals which form the reference\n Can be given in the same format as active_orbitals\n If given as None then the first N_electron/2 orbitals are taken\n for closed-shell systems.\n\n Returns\n -------\n Dataclass with active indices and reference indices (in spatial notation)\n\n \"\"\"\n\n if active_orbitals is None:\n return None\n\n if reference is None:\n # auto assignment only for closed-shell\n assert (self.n_electrons % 2 == 0)\n reference = sorted([i for i in range(self.n_electrons // 2)])\n\n return ActiveSpaceData(active_orbitals=sorted(active_orbitals),\n reference_orbitals=sorted(reference))\n\n @classmethod\n def from_openfermion(cls, molecule: openfermion.MolecularData,\n transformation: typing.Union[str, typing.Callable] = None,\n *args,\n **kwargs):\n \"\"\"\n Initialize direclty from openfermion MolecularData object\n\n Parameters\n ----------\n molecule\n The openfermion molecule\n Returns\n -------\n The Tequila molecule\n \"\"\"\n parameters = ParametersQC(basis_set=molecule.basis, geometry=molecule.geometry,\n description=molecule.description, multiplicity=molecule.multiplicity,\n charge=molecule.charge)\n return cls(parameters=parameters, transformation=transformation, molecule=molecule, *args, **kwargs)\n\n def make_excitation_generator(self,\n indices: typing.Iterable[typing.Tuple[int, int]],\n form: str = None,\n remove_constant_term: bool = True) -> QubitHamiltonian:\n \"\"\"\n Notes\n ----------\n Creates the transformed hermitian generator of UCC type unitaries:\n M(a^\\dagger_{a_0} a_{i_0} a^\\dagger{a_1}a_{i_1} ... - h.c.)\n where the qubit map M depends is self.transformation\n\n Parameters\n ----------\n indices : typing.Iterable[typing.Tuple[int, int]] :\n List of tuples [(a_0, i_0), (a_1, i_1), ... ] - recommended format, in spin-orbital notation (alpha odd numbers, beta even numbers)\n can also be given as one big list: [a_0, i_0, a_1, i_1 ...]\n form : str : (Default value None):\n Manipulate the generator to involution or projector\n set form='involution' or 'projector'\n the default is no manipulation which gives the standard fermionic excitation operator back\n remove_constant_term: bool: (Default value True):\n by default the constant term in the qubit operator is removed since it has no effect on the unitary it generates\n if the unitary is controlled this might not be true!\n Returns\n -------\n type\n 1j*Transformed qubit excitation operator, depends on self.transformation\n \"\"\"\n\n if type(self.transformation).__name__ == \"BravyiKitaevFast\":\n raise TequilaException(\n \"The Bravyi-Kitaev-Superfast transformation does not support general FermionOperators yet\")\n\n # check indices and convert to list of tuples if necessary\n if len(indices) == 0:\n raise TequilaException(\"make_excitation_operator: no indices given\")\n elif not isinstance(indices[0], typing.Iterable):\n if len(indices) % 2 != 0:\n raise TequilaException(\"make_excitation_generator: unexpected input format of indices\\n\"\n \"use list of tuples as [(a_0, i_0),(a_1, i_1) ...]\\n\"\n \"or list as [a_0, i_0, a_1, i_1, ... ]\\n\"\n \"you gave: {}\".format(indices))\n converted = [(indices[2 * i], indices[2 * i + 1]) for i in range(len(indices) // 2)]\n else:\n converted = indices\n\n # convert everything to native python int\n # otherwise openfermion will complain\n converted = [(int(pair[0]), int(pair[1])) for pair in converted]\n\n # convert to openfermion input format\n ofi = []\n dag = []\n for pair in converted:\n assert (len(pair) == 2)\n ofi += [(int(pair[0]), 1),\n (int(pair[1]), 0)] # openfermion does not take other types of integers like numpy.int64\n dag += [(int(pair[0]), 0), (int(pair[1]), 1)]\n\n op = openfermion.FermionOperator(tuple(ofi), 1.j) # 1j makes it hermitian\n op += openfermion.FermionOperator(tuple(reversed(dag)), -1.j)\n\n if isinstance(form, str) and form.lower() != 'fermionic':\n # indices for all the Na operators\n Na = [x for pair in converted for x in [(pair[0], 1), (pair[0], 0)]]\n # indices for all the Ma operators (Ma = 1 - Na)\n Ma = [x for pair in converted for x in [(pair[0], 0), (pair[0], 1)]]\n # indices for all the Ni operators\n Ni = [x for pair in converted for x in [(pair[1], 1), (pair[1], 0)]]\n # indices for all the Mi operators\n Mi = [x for pair in converted for x in [(pair[1], 0), (pair[1], 1)]]\n\n # can gaussianize as projector or as involution (last is default)\n if form.lower() == \"p+\":\n op *= 0.5\n op += openfermion.FermionOperator(Na + Mi, 0.5)\n op += openfermion.FermionOperator(Ni + Ma, 0.5)\n elif form.lower() == \"p-\":\n op *= 0.5\n op += openfermion.FermionOperator(Na + Mi, -0.5)\n op += openfermion.FermionOperator(Ni + Ma, -0.5)\n\n elif form.lower() == \"g+\":\n op += openfermion.FermionOperator([], 1.0) # Just for clarity will be subtracted anyway\n op += openfermion.FermionOperator(Na + Mi, -1.0)\n op += openfermion.FermionOperator(Ni + Ma, -1.0)\n elif form.lower() == \"g-\":\n op += openfermion.FermionOperator([], -1.0) # Just for clarity will be subtracted anyway\n op += openfermion.FermionOperator(Na + Mi, 1.0)\n op += openfermion.FermionOperator(Ni + Ma, 1.0)\n elif form.lower() == \"p0\":\n # P0: we only construct P0 and don't keep the original generator\n op = openfermion.FermionOperator([], 1.0) # Just for clarity will be subtracted anyway\n op += openfermion.FermionOperator(Na + Mi, -1.0)\n op += openfermion.FermionOperator(Ni + Ma, -1.0)\n else:\n raise TequilaException(\n \"Unknown generator form {}, supported are G, P+, P-, G+, G- and P0\".format(form))\n\n qop = self.transformation(op)\n\n # remove constant terms\n # they have no effect in the unitary (if not controlled)\n if remove_constant_term:\n qop.qubit_operator.terms[tuple()] = 0.0\n\n # check if the operator is hermitian and cast coefficients to floats\n # in order to avoid trouble with the simulation backends\n assert qop.is_hermitian()\n for k, v in qop.qubit_operator.terms.items():\n qop.qubit_operator.terms[k] = to_float(v)\n\n qop = qop.simplify()\n\n if len(qop) == 0:\n warnings.warn(\"Excitation generator is a unit operator.\\n\"\n \"Non-standard transformations might not work with general fermionic operators\\n\"\n \"indices = \" + str(indices), category=TequilaWarning)\n return qop\n\n def make_hardcore_boson_excitation_gate(self, indices, angle, control=None, assume_real=True, compile_options=\"optimize\"):\n target = []\n for pair in indices:\n assert len(pair) == 2\n target += [pair[0], pair[1]]\n consistency = [x < self.n_orbitals for x in target]\n if not all(consistency):\n raise TequilaException(\n \"make_hardcore_boson_excitation_gate: Inconsistencies in indices={}. Should be indexed from 0 ... n_orbitals={}\".format(\n indices, self.n_orbitals))\n return gates.QubitExcitation(angle=angle, target=target, assume_real=assume_real, control=control, compile_options=compile_options)\n\n def make_excitation_gate(self, indices, angle, control=None, assume_real=True, **kwargs):\n \"\"\"\n Initialize a fermionic excitation gate defined as\n\n .. math::\n e^{-i\\\\frac{a}{2} G}\n with generator defines by the indices [(p0,q0),(p1,q1),...]\n .. math::\n G = i(\\\\prod_{k} a_{p_k}^\\\\dagger a_{q_k} - h.c.)\n\n Parameters\n ----------\n indices:\n List of tuples that define the generator\n angle:\n Numeric or hashable type or tequila objective\n control:\n List of possible control qubits\n assume_real:\n Assume that the wavefunction will always stay real.\n Will reduce potential gradient costs by a factor of 2\n \"\"\"\n generator = self.make_excitation_generator(indices=indices, remove_constant_term=control is None)\n p0 = self.make_excitation_generator(indices=indices, form=\"P0\", remove_constant_term=control is None)\n\n return QCircuit.wrap_gate(\n FermionicGateImpl(angle=angle, generator=generator, p0=p0, transformation=type(self.transformation).__name__.lower(), assume_real=assume_real, control=control, **kwargs))\n\n def make_molecule(self, *args, **kwargs) -> MolecularData:\n \"\"\"Creates a molecule in openfermion format by running psi4 and extracting the data\n Will check for previous outputfiles before running\n Will not recompute if a file was found\n\n Parameters\n ----------\n parameters :\n An instance of ParametersQC, which also holds an instance of ParametersPsi4 via parameters.psi4\n The molecule will be saved in parameters.filename, if this file exists before the call the molecule will be imported from the file\n\n Returns\n -------\n type\n the molecule in openfermion.MolecularData format\n\n \"\"\"\n molecule = MolecularData(**self.parameters.molecular_data_param)\n # try to load\n\n do_compute = True\n try:\n import os\n if os.path.exists(self.parameters.filename):\n molecule.load()\n do_compute = False\n except OSError:\n do_compute = True\n\n if do_compute:\n molecule = self.do_make_molecule(*args, **kwargs)\n\n molecule.save()\n return molecule\n\n def do_make_molecule(self, *args, **kwargs):\n \"\"\"\n\n Parameters\n ----------\n args\n kwargs\n\n Returns\n -------\n\n \"\"\"\n # integrals need to be passed in base class\n assert (\"one_body_integrals\" in kwargs)\n assert (\"two_body_integrals\" in kwargs)\n one_body_integrals = kwargs[\"one_body_integrals\"]\n two_body_integrals = kwargs[\"two_body_integrals\"]\n \n # tequila assumes \"openfermion\" ordering, integrals can however be passed\n # down in other orderings, but it needs to be indicated by keyword\n if \"ordering\" in kwargs:\n two_body_integrals = NBodyTensor(two_body_integrals, ordering=kwargs[\"ordering\"])\n two_body_integrals.reorder(to=\"openfermion\")\n two_body_integrals = two_body_integrals.elems\n\n if \"nuclear_repulsion\" in kwargs:\n nuclear_repulsion = kwargs[\"nuclear_repulsion\"]\n else:\n nuclear_repulsion = 0.0\n warnings.warn(\"No nuclear_repulsion given for custom molecule, setting to zero\", category=TequilaWarning)\n\n if (\"n_orbitals\" in kwargs):\n n_orbitals = kwargs[\"n_orbitals\"]\n else:\n n_orbitals = one_body_integrals.shape[0]\n for i in [0, 1, 2, 3]:\n assert n_orbitals == two_body_integrals.shape[i]\n\n molecule = MolecularData(**self.parameters.molecular_data_param)\n\n molecule.one_body_integrals = one_body_integrals\n molecule.two_body_integrals = two_body_integrals\n molecule.nuclear_repulsion = nuclear_repulsion\n molecule.n_orbitals = n_orbitals\n if \"n_electrons\" in kwargs:\n molecule.n_electrons = kwargs[\"n_electrons\"]\n molecule.save()\n return molecule\n\n @property\n def n_orbitals(self) -> int:\n \"\"\" \"\"\"\n if self.active_space is None:\n return self.molecule.n_orbitals\n else:\n return len(self.active_space.active_orbitals)\n\n @property\n def n_electrons(self) -> int:\n \"\"\" \"\"\"\n if self.active_space is None:\n return self.molecule.n_electrons\n else:\n return 2 * len(self.active_space.active_reference_orbitals)\n\n def make_hamiltonian(self, occupied_indices=None, active_indices=None, threshold=1.e-8) -> QubitHamiltonian:\n \"\"\" \"\"\"\n if occupied_indices is None and self.active_space is not None:\n occupied_indices = self.active_space.frozen_reference_orbitals\n if active_indices is None and self.active_space is not None:\n active_indices = self.active_space.active_orbitals\n\n fop = openfermion.transforms.get_fermion_operator(\n self.molecule.get_molecular_hamiltonian(occupied_indices, active_indices))\n try:\n qop = self.transformation(fop)\n except TypeError:\n qop = self.transformation(openfermion.transforms.get_interaction_operator(fop))\n qop.is_hermitian()\n return qop\n\n def make_hardcore_boson_hamiltonian(self):\n if not self.transformation.up_then_down:\n warnings.warn(\n \"Hardcore-Boson Hamiltonian without reordering will result in non-consecutive Hamiltonians that are eventually not be combinable with other features of tequila. Try transformation=\\'ReorderedJordanWigner\\' or similar for more consistency\",\n TequilaWarning)\n # integrate with QubitEncoding at some point\n n_orbitals = self.n_orbitals\n c, obt, tbt = self.get_integrals()\n h = numpy.zeros(shape=[n_orbitals] * 2)\n g = numpy.zeros(shape=[n_orbitals] * 2)\n for p in range(n_orbitals):\n h[p, p] += 2 * obt[p, p]\n for q in range(n_orbitals):\n h[p, q] += + tbt[p, p, q, q]\n if p != q:\n g[p, q] += 2 * tbt[p, q, q, p] - tbt[p, q, p, q]\n\n H = c\n for p in range(n_orbitals):\n for q in range(n_orbitals):\n up = p\n uq = q\n H += h[p, q] * Sm(up) * Sp(uq) + g[p, q] * Sm(up) * Sp(up) * Sm(uq) * Sp(uq)\n\n return H\n\n def make_molecular_hamiltonian(self):\n if self.active_space:\n return self.molecule.get_molecular_hamiltonian(occupied_indices=self.active_space.frozen_reference_orbitals,\n active_indices=self.active_space.active_orbitals)\n else:\n return self.molecule.get_molecular_hamiltonian()\n\n def get_integrals(self, two_body_ordering=\"openfermion\"):\n \"\"\"\n Returns\n -------\n Tuple with:\n constant part (nuclear_repulsion + possible integrated parts from active-spaces)\n one_body_integrals\n two_body_integrals\n\n \"\"\"\n if self.active_space is not None and len(self.active_space.frozen_reference_orbitals) > 0:\n c, h1, h2 = self.molecule.get_active_space_integrals(active_indices=self.active_space.active_orbitals,\n occupied_indices=self.active_space.frozen_reference_orbitals)\n else:\n c = 0.0\n h1 = self.molecule.one_body_integrals\n h2 = self.molecule.two_body_integrals\n c += self.molecule.nuclear_repulsion\n h2 = NBodyTensor(h2, ordering=\"openfermion\")\n h2 = h2.reorder(to=two_body_ordering).elems\n\n return c, h1, h2\n\n def compute_one_body_integrals(self):\n \"\"\" convenience function \"\"\"\n c, h1, h2 = self.get_integrals()\n return h1\n\n def compute_two_body_integrals(self, two_body_ordering=\"openfermion\"):\n \"\"\" \"\"\"\n c, h1, h2 = self.get_integrals(two_body_ordering=two_body_ordering)\n return h2\n\n def compute_constant_part(self):\n c, h1, h2 = self.get_integrals()\n return c\n\n def compute_ccsd_amplitudes(self) -> ClosedShellAmplitudes:\n \"\"\" \"\"\"\n raise Exception(\"BaseClass Method\")\n\n def prepare_reference(self, state=None, *args, **kwargs):\n \"\"\"\n\n Returns\n -------\n A tequila circuit object which prepares the reference of this molecule in the chosen transformation\n \"\"\"\n if state is None:\n assert self.n_electrons %2 == 0\n state = [0]*(self.n_orbitals*2)\n for i in range(self.n_electrons):\n state[i]=1\n reference_state = BitString.from_array(self.transformation.map_state(state=state))\n U = prepare_product_state(reference_state)\n # prevent trace out in direct wfn simulation\n U.n_qubits = self.n_orbitals*2 # adapt when tapered transformations work\n return U\n\n def prepare_hardcore_boson_reference(self):\n # HF state in the HCB representation (paired electrons)\n U = gates.X(target=[i for i in range(self.n_electrons // 2)])\n U.n_qubits = self.n_orbitals\n return U\n\n def hcb_to_me(self, U=None):\n \"\"\"\n Transform a circuit in the hardcore-boson encoding (HCB)\n to the encoding of this molecule\n HCB is supposed to be encoded on the first n_orbitals qubits\n Parameters\n ----------\n U: HCB circuit (using the alpha qubits)\n Returns\n -------\n\n \"\"\"\n if U is None:\n U = QCircuit()\n\n # consistency\n consistency = [x < self.n_orbitals for x in U.qubits]\n if not all(consistency):\n warnings.warn(\n \"hcb_to_me: given circuit is not defined on the first {} qubits. Is this a HCB circuit?\".format(\n self.n_orbitals))\n\n # map to alpha qubits\n alpha_map = {k: self.transformation.up(k) for k in range(self.n_orbitals)}\n alpha_U = U.map_qubits(qubit_map=alpha_map)\n UX = self.transformation.hcb_to_me()\n if UX is None:\n raise TequilaException(\n \"transformation={} has no hcb_to_me function implemented\".format(self.transformation))\n return alpha_U + UX\n\n def get_pair_specific_indices(self,\n pair_info: str = None,\n include_singles: bool = True,\n general_excitations: bool = True) -> list:\n \"\"\"\n Assuming a pair-specific model, create a pair-specific index list\n to be used in make_upccgsd_ansatz(indices = ... )\n Excite from a set of references (i) to any pair coming from (i),\n i.e. any (i,j)/(j,i). If general excitations are allowed, also\n allow excitations from pairs to appendant pairs and reference.\n\n Parameters\n ----------\n pair_info\n file or list including information about pair structure\n references single number, pair double\n example: as file: \"0,1,11,11,00,10\" (hand over file name)\n in file, skip first row assuming some text with information\n as list:['0','1`','11','11','00','10']\n ~> two reference orbitals 0 and 1,\n then two orbitals from pair 11, one from 00, one mixed 10\n include_singles\n include single excitations\n general_excitations\n allow general excitations\n Returns\n -------\n list of indices with pair-specific ansatz\n \"\"\"\n\n if pair_info is None:\n raise TequilaException(\"Need to provide some pair information.\")\n # If pair-information given on file, load (layout see above)\n if isinstance(pair_info, str):\n pairs = numpy.loadtxt(pair_info, dtype=str, delimiter=\",\", skiprows=1)\n elif isinstance(pair_info, list):\n pairs = pair_info\n elif not isinstance(pair_info, list):\n raise TequilaException(\"Pair information needs to be contained in a list or filename.\")\n\n connect = [[]] * len(pairs)\n # determine \"connectivity\"\n generalized = 0\n for idx, p in enumerate(pairs):\n if len(p) == 1:\n connect[idx] = [i for i in range(len(pairs))\n if ((len(pairs[i]) == 2) and (str(idx) in pairs[i]))]\n elif (len(p) == 2) and general_excitations:\n connect[idx] = [i for i in range(len(pairs))\n if (((p[0] in pairs[i]) or (p[1] in pairs[i]) or str(i) in p)\n and not (i == idx))]\n elif len(p) > 2:\n raise TequilaException(\"Invalid reference of pair id.\")\n\n # create generating indices from connectivity\n indices = []\n for i, to in enumerate(connect):\n for a in to:\n indices.append(((2 * i, 2 * a), (2 * i + 1, 2 * a + 1)))\n if include_singles:\n indices.append(((2 * i, 2 * a)))\n indices.append(((2 * i + 1, 2 * a + 1)))\n\n return indices\n\n def format_excitation_indices(self, idx):\n \"\"\"\n Consistent formatting of excitation indices\n idx = [(p0,q0),(p1,q1),...,(pn,qn)]\n sorted as: p0<p1<pn and pi<qi\n :param idx: list of index tuples describing a single(!) fermionic excitation\n :return: tuple-list of index tuples\n \"\"\"\n\n idx = [tuple(sorted(x)) for x in idx]\n idx = sorted(idx, key=lambda x: x[0])\n return tuple(idx)\n\n def make_upccgsd_indices(self, key, reference_orbitals=None, *args, **kwargs):\n\n if reference_orbitals is None:\n reference_orbitals = [i for i in range(self.n_electrons // 2)]\n indices = []\n # add doubles in hcb encoding\n if hasattr(key, \"lower\") and key.lower() == \"ladder\":\n # ladder structure of the pair excitations\n # ensures local connectivity\n indices = [[(n, n + 1)] for n in range(self.n_orbitals - 1)]\n elif hasattr(key, \"lower\") and \"g\" not in key.lower():\n indices = [[(n, m)] for n in reference_orbitals for m in range(self.n_orbitals) if\n n < m and m not in reference_orbitals]\n elif hasattr(key, \"lower\") and \"g\" in key.lower():\n indices = [[(n, m)] for n in range(self.n_orbitals) for m in range(self.n_orbitals) if n < m]\n else:\n raise TequilaException(\"Unknown recipe: {}\".format(key))\n\n indices = [self.format_excitation_indices(idx) for idx in indices]\n\n return indices\n\n def make_hardcore_boson_upccgd_layer(self,\n indices: list = \"UpCCGD\",\n label: str = None,\n assume_real: bool = True,\n *args, **kwargs):\n\n if hasattr(indices, \"lower\"):\n indices = self.make_upccgsd_indices(key=indices.lower())\n\n UD = QCircuit()\n for idx in indices:\n UD += self.make_hardcore_boson_excitation_gate(indices=idx, angle=(idx, \"D\", label),\n assume_real=assume_real)\n\n return UD\n \n def make_ansatz(self, name:str, *args, **kwargs):\n\n name = name.lower()\n if name.strip()==\"\":\n return QCircuit()\n\n if \"+\" in name:\n U = QCircuit()\n subparts = name.split(\"+\")\n U = self.make_ansatz(name=subparts[0], *args ,**kwargs)\n if \"include_reference\" in kwargs:\n kwargs.pop(\"include_reference\")\n if \"hcb_optimization\" in kwargs:\n kwargs.pop(\"hcb_optimization\")\n for subpart in subparts[1:]:\n U += self.make_ansatz(name=subpart, *args, include_reference=False, hcb_optimization=False, **kwargs)\n return U\n \n if name==\"uccsd\":\n return self.make_uccsd_ansatz(*args, **kwargs)\n elif \"d\" in name or \"s\" in name:\n return self.make_upccgsd_ansatz(name=name, *args, **kwargs)\n else:\n raise TequilaException(\"unknown ansatz with name={}\".format(name))\n\n def make_upccgsd_ansatz(self,\n include_reference: bool = True,\n name: str = \"UpCCGSD\",\n label: str = None,\n order: int = None,\n assume_real: bool = True,\n hcb_optimization: bool = None,\n spin_adapt_singles: bool = True,\n neglect_z = False,\n *args, **kwargs):\n \"\"\"\n UpGCCSD Ansatz similar as described by Lee et. al.\n\n Parameters\n ----------\n include_singles\n include singles excitations. Is overwritten if indices are a string (i.e. indices=UpCCGSD will always include singles, UpCCGD will not)\n include_reference\n include the HF reference state as initial state\n indices\n pass custom defined set of indices from which the ansatz will be created\n List of tuples of tuples spin-indices e.g. [((2*p,2*q),(2*p+1,2*q+1)), ...]\n label\n An additional label that is set with the variables\n default is None and no label will be set: variables names will be\n (x, (p,q)) for x in range(order)\n with a label the variables will be named\n (label, (x, (p,q)))\n order\n Order of the ansatz (default is 1)\n determines how often the ordering gets repeated\n parameters of repeating layers are independent\n assume_real\n assume a real wavefunction (that is always the case if the reference state is real)\n reduces potential gradient costs from 4 to 2\n Returns\n -------\n UpGCCSD ansatz\n \"\"\"\n\n name = name.upper()\n\n if (\"A\" in name) and neglect_z is None:\n neglect_z = True\n else:\n neglect_z = False\n\n if order is None:\n try:\n if \"-\" in name:\n order = int(name.split(\"-\")[0])\n else:\n order = 1\n except:\n order = 1\n\n indices = self.make_upccgsd_indices(key=name)\n\n # check if the used qubit encoding has a hcb transformation\n have_hcb_trafo = self.transformation.hcb_to_me() is not None\n\n # consistency checks for optimization\n if have_hcb_trafo and hcb_optimization is None:\n hcb_optimization = True\n if \"HCB\" in name:\n hcb_optimization = True\n if hcb_optimization and not have_hcb_trafo and \"HCB\" not in name:\n raise TequilaException(\n \"use_hcb={} but transformation={} has no \\'hcb_to_me\\' function. Try transformation=\\'ReorderedJordanWigner\\'\".format(\n hcb_optimization, self.transformation))\n if \"S\" in name and \"HCB\" in name:\n if \"HCB\" in name and \"S\" in name:\n raise Exception(\n \"name={}, Singles can't be realized without mapping back to the standard encoding leave S or HCB out of the name\".format(\n name))\n\n # first layer\n if not hcb_optimization:\n U = QCircuit()\n if include_reference:\n U = self.prepare_reference()\n U += self.make_upccgsd_layer(include_singles=\"S\" in name, indices=indices, assume_real=assume_real,\n label=(label, 0), spin_adapt_singles=spin_adapt_singles, *args, **kwargs)\n else:\n U = QCircuit()\n if include_reference:\n U = self.prepare_hardcore_boson_reference()\n U += self.make_hardcore_boson_upccgd_layer(indices=indices, assume_real=assume_real, label=(label, 0),\n *args, **kwargs)\n if \"HCB\" not in name:\n U = self.hcb_to_me(U=U)\n\n if \"S\" in name:\n U += self.make_upccgsd_singles(indices=indices, assume_real=assume_real, label=(label, 0),\n spin_adapt_singles=spin_adapt_singles, neglect_z=neglect_z, *args, **kwargs)\n\n for k in range(1, order):\n U += self.make_upccgsd_layer(include_singles=\"S\" in name, indices=indices, label=(label, k),\n spin_adapt_singles=spin_adapt_singles, neglect_z=neglect_z)\n\n return U\n\n def make_upccgsd_layer(self, indices, include_singles=True, include_doubles=True, assume_real=True, label=None,\n spin_adapt_singles: bool = True, angle_transform=None, mix_sd=False, neglect_z=False, *args, **kwargs):\n U = QCircuit()\n for idx in indices:\n assert len(idx) == 1\n idx = idx[0]\n angle = (tuple([idx]), \"D\", label)\n if include_doubles:\n if \"jordanwigner\" in self.transformation.name.lower() and not self.transformation.up_then_down:\n # we can optimize with qubit excitations for the JW representation\n target=[self.transformation.up(idx[0]), self.transformation.up(idx[1]), self.transformation.down(idx[0]), self.transformation.down(idx[1])]\n U += gates.QubitExcitation(angle=angle, target=target, assume_real=assume_real, **kwargs)\n else:\n U += self.make_excitation_gate(angle=angle,\n indices=((2 * idx[0], 2 * idx[1]), (2 * idx[0] + 1, 2 * idx[1] + 1)),\n assume_real=assume_real, **kwargs)\n if include_singles and mix_sd:\n U += self.make_upccgsd_singles(indices=[idx], assume_real=assume_real, label=label,\n spin_adapt_singles=spin_adapt_singles, angle_transform=angle_transform, neglect_z=neglect_z)\n\n if include_singles and not mix_sd:\n U += self.make_upccgsd_singles(indices=indices, assume_real=assume_real, label=label,\n spin_adapt_singles=spin_adapt_singles, angle_transform=angle_transform, neglect_z=neglect_z)\n return U\n\n def make_upccgsd_singles(self, indices=\"UpCCGSD\", spin_adapt_singles=True, label=None, angle_transform=None,\n assume_real=True, neglect_z=False, *args, **kwargs):\n if neglect_z and \"jordanwigner\" not in self.transformation.name.lower():\n raise TequilaException(\"neglegt-z approximation in UpCCGSD singles needs the (Reversed)JordanWigner representation\")\n if hasattr(indices, \"lower\"):\n indices = self.make_upccgsd_indices(key=indices)\n\n U = QCircuit()\n for idx in indices:\n assert len(idx) == 1\n idx = idx[0]\n if spin_adapt_singles:\n angle = (idx, \"S\", label)\n if angle_transform is not None:\n angle = angle_transform(angle)\n if neglect_z:\n targeta=[self.transformation.up(idx[0]), self.transformation.up(idx[1])]\n targetb=[self.transformation.down(idx[0]), self.transformation.down(idx[1])]\n U += gates.QubitExcitation(angle=angle, target=targeta, assume_real=assume_real, **kwargs)\n U += gates.QubitExcitation(angle=angle, target=targetb, assume_real=assume_real, **kwargs)\n else:\n U += self.make_excitation_gate(angle=angle, indices=[(2 * idx[0], 2 * idx[1])], assume_real=assume_real, **kwargs)\n U += self.make_excitation_gate(angle=angle, indices=[(2 * idx[0] + 1, 2 * idx[1] + 1)],\n assume_real=assume_real, **kwargs)\n else:\n angle1 = (idx, \"SU\", label)\n angle2 = (idx, \"SD\", label)\n if angle_transform is not None:\n angle1 = angle_transform(angle1)\n angle2 = angle_transform(angle2)\n if neglect_z:\n targeta=[self.transformation.up(idx[0]), self.transformation.up(idx[1])]\n targetb=[self.transformation.down(idx[0]), self.transformation.down(idx[1])]\n U += gates.QubitExcitation(angle=angle1, target=targeta, assume_real=assume_real, *kwargs)\n U += gates.QubitExcitation(angle=angle2, target=targetb, assume_real=assume_real, *kwargs)\n else:\n U += self.make_excitation_gate(angle=angle1, indices=[(2 * idx[0], 2 * idx[1])],\n assume_real=assume_real, **kwargs)\n U += self.make_excitation_gate(angle=angle2, indices=[(2 * idx[0] + 1, 2 * idx[1] + 1)],\n assume_real=assume_real, **kwargs)\n\n return U\n\n def make_uccsd_ansatz(self, trotter_steps: int=1,\n initial_amplitudes: typing.Union[str, Amplitudes, ClosedShellAmplitudes] = \"mp2\",\n include_reference_ansatz=True,\n parametrized=True,\n threshold=1.e-8,\n add_singles=None,\n *args, **kwargs) -> QCircuit:\n \"\"\"\n\n Parameters\n ----------\n initial_amplitudes :\n initial amplitudes given as ManyBodyAmplitudes structure or as string\n where 'mp2', 'cc2' or 'ccsd' are possible initializations\n include_reference_ansatz :\n Also do the reference ansatz (prepare closed-shell Hartree-Fock) (Default value = True)\n parametrized :\n Initialize with variables, otherwise with static numbers (Default value = True)\n trotter_steps: int :\n\n initial_amplitudes: typing.Union[str :\n\n Amplitudes :\n\n ClosedShellAmplitudes] :\n (Default value = \"cc2\")\n\n Returns\n -------\n type\n Parametrized QCircuit\n\n \"\"\"\n \n if hasattr(initial_amplitudes, \"lower\"):\n if initial_amplitudes.lower() == \"mp2\" and add_singles is None:\n add_singles=True\n elif initial_amplitudes is not None and add_singles is not None:\n warnings.warn(\"make_uccsd_anstatz: add_singles has no effect when explicit amplitudes are passed down\", TequilaWarning)\n elif add_singles is None:\n add_singles=True\n \n if self.n_electrons % 2 != 0:\n raise TequilaException(\"make_uccsd_ansatz currently only for closed shell systems\")\n\n nocc = self.n_electrons // 2\n nvirt = self.n_orbitals - nocc\n\n Uref = QCircuit()\n if include_reference_ansatz:\n Uref = self.prepare_reference()\n\n amplitudes = initial_amplitudes\n if hasattr(initial_amplitudes, \"lower\"):\n if initial_amplitudes.lower() == \"mp2\":\n amplitudes = self.compute_mp2_amplitudes()\n elif initial_amplitudes.lower() == \"ccsd\":\n amplitudes = self.compute_ccsd_amplitudes()\n else:\n try:\n amplitudes = self.compute_amplitudes(method=initial_amplitudes.lower())\n except Exception as exc:\n raise TequilaException(\n \"{}\\nDon't know how to initialize \\'{}\\' amplitudes\".format(exc, initial_amplitudes))\n if amplitudes is None:\n tia=None\n if add_singles: tia=numpy.zeros(shape=[nocc, nvirt])\n amplitudes = ClosedShellAmplitudes(\n tIjAb=numpy.zeros(shape=[nocc, nocc, nvirt, nvirt]),\n tIA=tia)\n\n closed_shell = isinstance(amplitudes, ClosedShellAmplitudes)\n indices = {}\n\n if not isinstance(amplitudes, dict):\n amplitudes = amplitudes.make_parameter_dictionary(threshold=threshold)\n amplitudes = dict(sorted(amplitudes.items(), key=lambda x: numpy.fabs(x[1]), reverse=True))\n for key, t in amplitudes.items():\n assert (len(key) % 2 == 0)\n if not numpy.isclose(t, 0.0, atol=threshold):\n if closed_shell:\n \n if len(key) == 2 and add_singles:\n # singles\n angle=2.0*t\n if parametrized:\n angle=2.0*Variable(name=key)\n idx_a = (2*key[0], 2*key[1])\n idx_b = (2*key[0]+1, 2*key[1]+1)\n indices[idx_a]=angle\n indices[idx_b]=angle\n else:\n assert len(key)==4\n angle=2.0*t\n if parametrized:\n angle=2.0*Variable(name=key)\n idx_abab=(2 * key[0] + 1, 2 * key[1] + 1, 2 * key[2], 2 * key[3])\n indices[idx_abab]=angle\n if key[0]!=key[2] and key[1]!=key[3]: \n idx_aaaa=(2 * key[0], 2 * key[1], 2 * key[2], 2 * key[3])\n idx_bbbb=(2 * key[0] + 1, 2 * key[1] + 1, 2 * key[2]+1, 2 * key[3]+1)\n partner = tuple([key[2], key[1], key[0], key[3]]) \n anglex=2.0*(t - amplitudes[partner])\n if parametrized:\n anglex=2.0*(Variable(name=key) - Variable(partner))\n indices[idx_aaaa]=anglex\n indices[idx_bbbb]=anglex\n else:\n raise Exception(\"only closed-shell supported, please assemble yourself .... sorry :-)\")\n\n UCCSD = QCircuit()\n factor = 1.0 / trotter_steps\n for step in range(trotter_steps):\n for idx, angle in indices.items():\n UCCSD += self.make_excitation_gate(indices=idx, angle=factor * angle)\n if hasattr(initial_amplitudes,\"lower\") and initial_amplitudes.lower()==\"mp2\" and parametrized and add_singles:\n # mp2 has no singles, need to initialize them here (if not parametrized initializling as 0.0 makes no sense though)\n UCCSD += self.make_upccgsd_layer(indices=\"upccsd\", include_singles=True, include_doubles=False)\n return Uref + UCCSD\n\n def compute_amplitudes(self, method: str, *args, **kwargs):\n \"\"\"\n Compute closed-shell CC amplitudes\n\n Parameters\n ----------\n method :\n coupled-cluster methods like cc2, ccsd, cc3, ccsd(t)\n Success might depend on backend\n got an extra function for MP2\n *args :\n\n **kwargs :\n\n\n Returns\n -------\n\n \"\"\"\n raise TequilaException(\"compute amplitudes: Needs to be overwritten by backend\")\n\n def compute_mp2_amplitudes(self) -> ClosedShellAmplitudes:\n \"\"\"\n\n Compute closed-shell mp2 amplitudes\n\n .. math::\n t(a,i,b,j) = 0.25 * g(a,i,b,j)/(e(i) + e(j) -a(i) - b(j) )\n\n :return:\n\n Parameters\n ----------\n\n Returns\n -------\n\n \"\"\"\n g = self.molecule.two_body_integrals\n fij = self.molecule.orbital_energies\n nocc = self.molecule.n_electrons // 2 # this is never the active space\n ei = fij[:nocc]\n ai = fij[nocc:]\n abgij = g[nocc:, nocc:, :nocc, :nocc]\n amplitudes = abgij * 1.0 / (\n ei.reshape(1, 1, -1, 1) + ei.reshape(1, 1, 1, -1) - ai.reshape(-1, 1, 1, 1) - ai.reshape(1, -1, 1, 1))\n E = 2.0 * numpy.einsum('abij,abij->', amplitudes, abgij) - numpy.einsum('abji,abij', amplitudes, abgij,\n optimize='greedy')\n\n self.molecule.mp2_energy = E + self.molecule.hf_energy\n return ClosedShellAmplitudes(tIjAb=numpy.einsum('abij -> ijab', amplitudes, optimize='greedy'))\n\n def compute_cis_amplitudes(self):\n \"\"\"\n Compute the CIS amplitudes of the molecule\n \"\"\"\n\n @dataclass\n class ResultCIS:\n \"\"\" \"\"\"\n omegas: typing.List[numbers.Real] # excitation energies [omega0, ...]\n amplitudes: typing.List[ClosedShellAmplitudes] # corresponding amplitudes [x_{ai}_0, ...]\n\n def __getitem__(self, item):\n return (self.omegas[item], self.amplitudes[item])\n\n def __len__(self):\n return len(self.omegas)\n\n g = self.molecule.two_body_integrals\n fij = self.molecule.orbital_energies\n\n nocc = self.n_alpha_electrons\n nvirt = self.n_orbitals - nocc\n\n pairs = []\n for i in range(nocc):\n for a in range(nocc, nocc + nvirt):\n pairs.append((a, i))\n M = numpy.ndarray(shape=[len(pairs), len(pairs)])\n\n for xx, x in enumerate(pairs):\n eia = fij[x[0]] - fij[x[1]]\n a, i = x\n for yy, y in enumerate(pairs):\n b, j = y\n delta = float(y == x)\n gpart = 2.0 * g[a, i, b, j] - g[a, i, j, b]\n M[xx, yy] = eia * delta + gpart\n\n omega, xvecs = numpy.linalg.eigh(M)\n\n # convert amplitudes to ndarray sorted by excitation energy\n nex = len(omega)\n amplitudes = []\n for ex in range(nex):\n t = numpy.ndarray(shape=[nvirt, nocc])\n exvec = xvecs[ex]\n for xx, x in enumerate(pairs):\n a, i = x\n t[a - nocc, i] = exvec[xx]\n amplitudes.append(ClosedShellAmplitudes(tIA=t))\n\n return ResultCIS(omegas=list(omega), amplitudes=amplitudes)\n\n @property\n def rdm1(self):\n \"\"\" \n Returns RMD1 if computed with compute_rdms function before\n \"\"\"\n if self._rdm1 is not None:\n return self._rdm1\n else:\n print(\"1-RDM has not been computed. Return None for 1-RDM.\")\n return None\n\n @property\n def rdm2(self):\n \"\"\"\n Returns RMD2 if computed with compute_rdms function before\n This is returned in Dirac (physics) notation by default (can be changed in compute_rdms with keyword)!\n \"\"\"\n if self._rdm2 is not None:\n return self._rdm2\n else:\n print(\"2-RDM has not been computed. Return None for 2-RDM.\")\n return None\n\n def compute_rdms(self, U: QCircuit = None, variables: Variables = None, spin_free: bool = True,\n get_rdm1: bool = True, get_rdm2: bool = True, ordering=\"dirac\"):\n \"\"\"\n Computes the one- and two-particle reduced density matrices (rdm1 and rdm2) given\n a unitary U. This method uses the standard ordering in physics as denoted below.\n Note, that the representation of the density matrices depends on the qubit transformation\n used. The Jordan-Wigner encoding corresponds to 'classical' second quantized density\n matrices in the occupation picture.\n\n We only consider real orbitals and thus real-valued RDMs.\n The matrices are set as private members _rdm1, _rdm2 and can be accessed via the properties rdm1, rdm2.\n\n .. math :\n \\\\text{rdm1: } \\\\gamma^p_q = \\\\langle \\\\psi | a^p a_q | \\\\psi \\\\rangle\n = \\\\langle U 0 | a^p a_q | U 0 \\\\rangle\n \\\\text{rdm2: } \\\\gamma^{pq}_{rs} = \\\\langle \\\\psi | a^p a^q a_s a_r | \\\\psi \\\\rangle\n = \\\\langle U 0 | a^p a^q a_s a_r | U 0 \\\\rangle\n\n Parameters\n ----------\n U :\n Quantum Circuit to achieve the desired state \\\\psi = U |0\\\\rangle, non-optional\n variables :\n If U is parametrized, then need to hand over a set of fixed variables\n spin_free :\n Set whether matrices should be spin-free (summation over spin) or defined by spin-orbitals\n get_rdm1, get_rdm2 :\n Set whether either one or both rdm1, rdm2 should be computed. If both are needed at some point,\n it is recommended to compute them at once.\n\n Returns\n -------\n \"\"\"\n # Check whether unitary circuit is not 0\n if U is None:\n raise TequilaException('Need to specify a Quantum Circuit.')\n\n # Check whether transformation is BKSF.\n # Issue here: when a single operator acts only on a subset of qubits, BKSF might not yield the correct\n # transformation, because it computes the number of qubits incorrectly in this case.\n # A hotfix such as for symmetry_conserving_bravyi_kitaev would require deeper changes, thus omitted for now\n if type(self.transformation).__name__ == \"BravyiKitaevFast\":\n raise TequilaException(\n \"The Bravyi-Kitaev-Superfast transformation does not support general FermionOperators yet.\")\n\n # Set up number of spin-orbitals and molecular orbitals respectively\n n_SOs = 2 * self.n_orbitals\n n_MOs = self.n_orbitals\n\n # Check whether unitary circuit is not 0\n if U is None:\n raise TequilaException('Need to specify a Quantum Circuit.')\n\n def _get_of_op(operator_tuple):\n \"\"\" Returns operator given by a operator tuple as OpenFermion - Fermion operator \"\"\"\n op = openfermion.FermionOperator(operator_tuple)\n return op\n\n def _get_qop_hermitian(of_operator) -> QubitHamiltonian:\n \"\"\" Returns Hermitian part of Fermion operator as QubitHamiltonian \"\"\"\n qop = self.transformation(of_operator)\n #qop = QubitHamiltonian(self.transformation(of_operator))\n real, imag = qop.split(hermitian=True)\n if real:\n return real\n elif not real:\n raise TequilaException(\n \"Qubit Hamiltonian does not have a Hermitian part. Operator ={}\".format(of_operator))\n\n def _build_1bdy_operators_spinful() -> list:\n \"\"\" Returns spinful one-body operators as a symmetry-reduced list of QubitHamiltonians \"\"\"\n # Exploit symmetry pq = qp\n ops = []\n for p in range(n_SOs):\n for q in range(p + 1):\n op_tuple = ((p, 1), (q, 0))\n op = _get_of_op(op_tuple)\n ops += [op]\n\n return ops\n\n def _build_2bdy_operators_spinful() -> list:\n \"\"\" Returns spinful two-body operators as a symmetry-reduced list of QubitHamiltonians \"\"\"\n # Exploit symmetries pqrs = -pqsr = -qprs = qpsr\n # and = rspq\n ops = []\n for p in range(n_SOs):\n for q in range(p):\n for r in range(n_SOs):\n for s in range(r):\n if p * n_SOs + q >= r * n_SOs + s:\n op_tuple = ((p, 1), (q, 1), (s, 0), (r, 0))\n op = _get_of_op(op_tuple)\n ops += [op]\n\n return ops\n\n def _build_1bdy_operators_spinfree() -> list:\n \"\"\" Returns spinfree one-body operators as a symmetry-reduced list of QubitHamiltonians \"\"\"\n # Exploit symmetry pq = qp (not changed by spin-summation)\n ops = []\n for p in range(n_MOs):\n for q in range(p + 1):\n # Spin aa\n op_tuple = ((2 * p, 1), (2 * q, 0))\n op = _get_of_op(op_tuple)\n # Spin bb\n op_tuple = ((2 * p + 1, 1), (2 * q + 1, 0))\n op += _get_of_op(op_tuple)\n ops += [op]\n\n return ops\n\n def _build_2bdy_operators_spinfree() -> list:\n \"\"\" Returns spinfree two-body operators as a symmetry-reduced list of QubitHamiltonians \"\"\"\n # Exploit symmetries pqrs = qpsr (due to spin summation, '-pqsr = -qprs' drops out)\n # and = rspq\n ops = []\n for p, q, r, s in product(range(n_MOs), repeat=4):\n if p * n_MOs + q >= r * n_MOs + s and (p >= q or r >= s):\n # Spin aaaa\n op_tuple = ((2 * p, 1), (2 * q, 1), (2 * s, 0), (2 * r, 0)) if (p != q and r != s) else '0.0 []'\n op = _get_of_op(op_tuple)\n # Spin abab\n op_tuple = ((2 * p, 1), (2 * q + 1, 1), (2 * s + 1, 0), (2 * r, 0)) if (\n 2 * p != 2 * q + 1 and 2 * r != 2 * s + 1) else '0.0 []'\n op += _get_of_op(op_tuple)\n # Spin baba\n op_tuple = ((2 * p + 1, 1), (2 * q, 1), (2 * s, 0), (2 * r + 1, 0)) if (\n 2 * p + 1 != 2 * q and 2 * r + 1 != 2 * s) else '0.0 []'\n op += _get_of_op(op_tuple)\n # Spin bbbb\n op_tuple = ((2 * p + 1, 1), (2 * q + 1, 1), (2 * s + 1, 0), (2 * r + 1, 0)) if (\n p != q and r != s) else '0.0 []'\n op += _get_of_op(op_tuple)\n\n ops += [op]\n\n return ops\n\n def _assemble_rdm1(evals) -> numpy.ndarray:\n \"\"\"\n Returns spin-ful or spin-free one-particle RDM built by symmetry conditions\n Same symmetry with or without spin, so we can use the same function\n \"\"\"\n N = n_MOs if spin_free else n_SOs\n rdm1 = numpy.zeros([N, N])\n ctr: int = 0\n for p in range(N):\n for q in range(p + 1):\n rdm1[p, q] = evals[ctr]\n # Symmetry pq = qp\n rdm1[q, p] = rdm1[p, q]\n ctr += 1\n\n return rdm1\n\n def _assemble_rdm2_spinful(evals) -> numpy.ndarray:\n \"\"\" Returns spin-ful two-particle RDM built by symmetry conditions \"\"\"\n ctr: int = 0\n rdm2 = numpy.zeros([n_SOs, n_SOs, n_SOs, n_SOs])\n for p in range(n_SOs):\n for q in range(p):\n for r in range(n_SOs):\n for s in range(r):\n if p * n_SOs + q >= r * n_SOs + s:\n rdm2[p, q, r, s] = evals[ctr]\n # Symmetry pqrs = rspq\n rdm2[r, s, p, q] = rdm2[p, q, r, s]\n ctr += 1\n\n # Further permutational symmetries due to anticommutation relations\n for p in range(n_SOs):\n for q in range(p):\n for r in range(n_SOs):\n for s in range(r):\n rdm2[p, q, s, r] = -1 * rdm2[p, q, r, s] # pqrs = -pqsr\n rdm2[q, p, r, s] = -1 * rdm2[p, q, r, s] # pqrs = -qprs\n rdm2[q, p, s, r] = rdm2[p, q, r, s] # pqrs = qpsr\n\n return rdm2\n\n def _assemble_rdm2_spinfree(evals) -> numpy.ndarray:\n \"\"\" Returns spin-free two-particle RDM built by symmetry conditions \"\"\"\n ctr: int = 0\n rdm2 = numpy.zeros([n_MOs, n_MOs, n_MOs, n_MOs])\n for p, q, r, s in product(range(n_MOs), repeat=4):\n if p * n_MOs + q >= r * n_MOs + s and (p >= q or r >= s):\n rdm2[p, q, r, s] = evals[ctr]\n # Symmetry pqrs = rspq\n rdm2[r, s, p, q] = rdm2[p, q, r, s]\n ctr += 1\n\n # Further permutational symmetry: pqrs = qpsr\n for p, q, r, s in product(range(n_MOs), repeat=4):\n if p >= q or r >= s:\n rdm2[q, p, s, r] = rdm2[p, q, r, s]\n\n return rdm2\n\n # Build operator lists\n qops = []\n if spin_free:\n qops += _build_1bdy_operators_spinfree() if get_rdm1 else []\n qops += _build_2bdy_operators_spinfree() if get_rdm2 else []\n else:\n qops += _build_1bdy_operators_spinful() if get_rdm1 else []\n qops += _build_2bdy_operators_spinful() if get_rdm2 else []\n\n # Transform operator lists to QubitHamiltonians\n qops = [_get_qop_hermitian(op) for op in qops]\n # Compute expected values\n evals = simulate(ExpectationValue(H=qops, U=U, shape=[len(qops)]), variables=variables)\n\n # Assemble density matrices\n # If self._rdm1, self._rdm2 exist, reset them if they are of the other spin-type\n def _reset_rdm(rdm):\n if rdm is not None:\n if spin_free and rdm.shape[0] != n_MOs:\n return None\n if not spin_free and rdm.shape[0] != n_SOs:\n return None\n return rdm\n\n self._rdm1 = _reset_rdm(self._rdm1)\n self._rdm2 = _reset_rdm(self._rdm2)\n # Split expectation values in 1- and 2-particle expectation values\n if get_rdm1:\n len_1 = n_MOs * (n_MOs + 1) // 2 if spin_free else n_SOs * (n_SOs + 1) // 2\n else:\n len_1 = 0\n evals_1, evals_2 = evals[:len_1], evals[len_1:]\n # Build matrices using the expectation values\n self._rdm1 = _assemble_rdm1(evals_1) if get_rdm1 else self._rdm1\n if spin_free:\n self._rdm2 = _assemble_rdm2_spinfree(evals_2) if get_rdm2 else self._rdm2\n else:\n self._rdm2 = _assemble_rdm2_spinful(evals_2) if get_rdm2 else self._rdm2\n \n if get_rdm2:\n rdm2 = NBodyTensor(elems=self.rdm2, ordering=\"dirac\")\n rdm2.reorder(to=ordering)\n rdm2 = rdm2.elems\n self._rdm2 = rdm2\n\n if get_rdm1:\n if get_rdm2:\n return self.rdm1, self.rdm2\n else:\n return self.rdm1\n elif get_rdm2:\n return self.rdm2\n else:\n warnings.warn(\"compute_rdms called with instruction to not compute?\", TequilaWarning)\n\n def rdm_spinsum(self, sum_rdm1: bool = True, sum_rdm2: bool = True) -> tuple:\n \"\"\"\n Given the spin-ful 1- and 2-particle reduced density matrices, compute the spin-free RDMs by spin summation.\n\n Parameters\n ----------\n sum_rdm1, sum_rdm2 :\n If set to true, perform spin summation on rdm1, rdm2\n\n Returns\n -------\n rdm1_spinsum, rdm2_spinsum :\n The desired spin-free matrices\n \"\"\"\n n_MOs = self.n_orbitals\n rdm1_spinsum = None\n rdm2_spinsum = None\n\n # Spin summation on rdm1\n if sum_rdm1:\n # Check whether spin-rdm2 exists\n if self._rdm1 is None:\n raise TequilaException(\"The spin-RDM for the 1-RDM does not exist!\")\n # Check whether existing rdm1 is in spin-orbital basis\n if self._rdm1.shape[0] != 2 * n_MOs:\n raise TequilaException(\"The existing RDM needs to be in spin-orbital basis, it is already spin-free!\")\n # Do summation\n rdm1_spinsum = numpy.zeros([n_MOs, n_MOs])\n for p in range(n_MOs):\n for q in range(p + 1):\n rdm1_spinsum[p, q] += self._rdm1[2 * p, 2 * q]\n rdm1_spinsum[p, q] += self._rdm1[2 * p + 1, 2 * q + 1]\n for p in range(n_MOs):\n for q in range(p):\n rdm1_spinsum[q, p] = rdm1_spinsum[p, q]\n\n # Spin summation on rdm2\n if sum_rdm2:\n # Check whether spin-rdm2 exists\n if self._rdm2 is None:\n raise TequilaException(\"The spin-RDM for the 2-RDM does not exist!\")\n # Check whether existing rdm2 is in spin-orbital basis\n if self._rdm2.shape[0] != 2 * n_MOs:\n raise TequilaException(\"The existing RDM needs to be in spin-orbital basis, it is already spin-free!\")\n # Do summation\n rdm2_spinsum = numpy.zeros([n_MOs, n_MOs, n_MOs, n_MOs])\n for p, q, r, s in product(range(n_MOs), repeat=4):\n rdm2_spinsum[p, q, r, s] += self._rdm2[2 * p, 2 * q, 2 * r, 2 * s]\n rdm2_spinsum[p, q, r, s] += self._rdm2[2 * p + 1, 2 * q, 2 * r + 1, 2 * s]\n rdm2_spinsum[p, q, r, s] += self._rdm2[2 * p, 2 * q + 1, 2 * r, 2 * s + 1]\n rdm2_spinsum[p, q, r, s] += self._rdm2[2 * p + 1, 2 * q + 1, 2 * r + 1, 2 * s + 1]\n\n return rdm1_spinsum, rdm2_spinsum\n\n def perturbative_f12_correction(self, rdm1: numpy.ndarray = None, rdm2: numpy.ndarray = None,\n gamma: float = 1.4, n_ri: int = None,\n external_info: dict = None, **kwargs) -> float:\n \"\"\"\n Computes the spin-free [2]_R12 correction, needing only the 1- and 2-RDM of a reference method\n Requires either 1-RDM, 2-RDM or information to compute them in kwargs\n\n Parameters\n ----------\n rdm1 :\n 1-electron reduced density matrix\n rdm2 :\n 2-electron reduced density matrix\n gamma :\n f12-exponent, for a correlation factor f_12 = -1/gamma * exp[-gamma*r_12]\n n_ri :\n dimensionality of RI-basis; specify only, if want to truncate available RI-basis\n if None, then the maximum available via tensors / basis-set is used\n must not be larger than size of available RI-basis, and not smaller than size of OBS\n for n_ri==dim(OBS), the correction returns zero\n external_info :\n for usage in qc_base, need to provide information where to find one-body tensor f12-tensor <rs|f_12|pq>;\n pass dictionary with {\"f12_filename\": where to find f12-tensor, \"scheme\": ordering scheme of tensor}\n kwargs :\n e.g. RDM-information via {\"U\": QCircuit, \"variables\": optimal angles}, needs to be passed if rdm1,rdm2 not\n yet computed\n\n Returns\n -------\n the f12 correction for the energy\n \"\"\"\n from .f12_corrections._f12_correction_base import ExplicitCorrelationCorrection\n correction = ExplicitCorrelationCorrection(mol=self, rdm1=rdm1, rdm2=rdm2, gamma=gamma,\n n_ri=n_ri, external_info=external_info, **kwargs)\n return correction.compute()\n\n def __str__(self) -> str:\n result = str(type(self)) + \"\\n\"\n result += \"Qubit Encoding\\n\"\n result += str(self.transformation) + \"\\n\\n\"\n result += \"Parameters\\n\"\n for k, v in self.parameters.__dict__.items():\n result += \"{key:15} : {value:15} \\n\".format(key=str(k), value=str(v))\n result += \"\\n\"\n return result\n" ]
[ [ "numpy.ndenumerate", "numpy.isclose", "numpy.zeros", "numpy.linalg.eigh", "numpy.take", "numpy.ndarray", "numpy.fabs", "numpy.loadtxt", "numpy.einsum", "numpy.abs" ] ]
newTypeGeek/Network-Reconstruction
[ "135a07cc304dac0666a9d11d3548aee7a669eaad" ]
[ "gen_cov/logistic_diffusive.py" ]
[ "#!/usr/bin/env python3\n\nimport numpy as np\nfrom tqdm import tqdm\nimport os\nimport sys\n\nROOT_DIR = os.path.abspath(\"../\")\nsys.path.append(ROOT_DIR)\nfrom utils import network\n\n\ndef logistic_diffusive(W, r, sigma, int_dt, sample_dt, sample_start, data_num, get_ts=False):\n '''\n Simulate the coupled SDEs with\n - f(x) = rx(1-x)\n - h(x[i] - x[j]) = x[j] - x[i]\n\n and obtain the covariance matrix of the whole network.\n\n Arguments:\n 1. W: Weighted adjacency matrix of the whole network\n 2. r: Parameter of f(x)\n 3. sigma: Noise strength (standard deviation of Gaussian distribution)\n 4. int_dt: Integration time step\n 5. sample_dt: Sampling time step\n 6, start_sample: Time step to start sampling\n 7. data_num: Total number of sampled data for covariance matrix computation\n 8. get_ts: To sample time series of the first node or not (default: False)\n\n Returns:\n 1. cov: Covariance matrix of the whole network\n 2. x_ts: Sampled time series of the first node\n '''\n assert type(W) == np.ndarray, \"W must be of type 'numpy.ndarray'\"\n assert W.size > 0, \"W must not be empty\"\n assert W.dtype == int or W.dtype == float, \"W must of dtype 'int' or 'float'\"\n assert np.isfinite(W).all(), \"Elements in W must be finite real numbers\"\n size = W.shape\n assert len(size) == 2, \"W must be 2D shape\"\n assert size[0] == size[1], \"W must be a square matrix\"\n assert (np.diag(W) == 0).all(), \"W must not have self-loop\"\n\n assert (type(r) == int or type(r) == float) and np.isfinite(r) and r > 0, \"r must be a positive real number\"\n assert (type(sigma) == int or type(sigma) == float) and np.isfinite(sigma) and sigma > 0, \"sigma must be a positive real number\"\n assert (type(int_dt) == int or type(int_dt) == float) and np.isfinite(int_dt) and int_dt > 0, \"int_dt must be a positive real number\"\n assert (type(sample_dt) == int or type(sample_dt) == float) and np.isfinite(sample_dt) and sample_dt > int_dt, \"sample_dt step must be a positive real number, and greater than int_dt\"\n assert type(sample_start) == int and sample_start >= 0, \"sample_start must be a non-negative integer\"\n assert type(data_num) == int and data_num > sample_dt, \"data_num must be a positive integer, and greater than sample_dt\"\n\n assert type(get_ts) == bool, \"get_ts must be boolean\"\n\n # Compute weighted Laplacian matrix\n # This is used for simplifying the computation when\n # the coupling function h(x-y) = y - x\n L = network.laplacian(W)\n\n # Sampling time interval\n sample_inter = int(sample_dt/int_dt)\n\n # Total number of iteration\n T = int((data_num) * sample_inter + sample_start)\n\n # Initialize the current state of N nodes\n N = size[0]\n x = np.random.normal(loc=0.5, scale=0.01, size=(N,))\n\n # Initialize the 1st and 2nd moment matrix of the state vector x\n # They are used to compute the covariance matrix\n m_01 = np.zeros((N,))\n m_02 = np.zeros((N, N))\n\n # Initialize the sampled time series of the first node\n if get_ts:\n x_ts = np.zeros((int(T/sample_inter),))\n i = 0\n else:\n x_ts = None\n\n # Solve the coupled SDEs using Euler-Maruyama method\n for t in tqdm(range(T)):\n eta = np.random.normal(size=(N,))\n x += r*x*(1-x)*int_dt - np.matmul(L, x)*int_dt + sigma*np.sqrt(int_dt)*eta\n\n # Stop the program if there is at least one node blows up\n if np.isnan(x).any() or np.isinf(x).any():\n assert False, \"The dynamics blows up!\"\n\n # Sample the node states\n if t % sample_inter == 0:\n\n # Sample dynamics of the first node\n if get_ts:\n x_ts[i] = x[0]\n i += 1\n\n # Sample 1st and 2nd moment\n if t >= sample_start:\n m_01 += x/data_num\n m_02 += np.outer(x, x)/data_num\n\n # Compute the covariance matrix of the whole network\n cov = m_02 - np.outer(m_01, m_01)\n\n return cov, x_ts\n" ]
[ [ "numpy.isinf", "numpy.random.normal", "numpy.isnan", "numpy.matmul", "numpy.zeros", "numpy.isfinite", "numpy.sqrt", "numpy.outer", "numpy.diag" ] ]
greenrock21/test
[ "a0d97e6eb96c107a303cb1b897f746a37dc2d968" ]
[ "dbox_aux.py" ]
[ "import pandas as pd\r\nimport io\r\nimport dropbox\r\nimport streamlit as st\r\n\r\nTOKEN = st.secrets[\"TOKEN\"]\r\ndbx = dropbox.Dropbox(TOKEN)\r\n\r\ndef read_dbx_file(file):\r\n print('Getting latest file')\r\n _, f = dbx.files_download(file)\r\n with io.BytesIO(f.content) as stream:\r\n df = pd.read_csv(stream, index_col=0)\r\n return df\r\n" ]
[ [ "pandas.read_csv" ] ]
tiagokv/drlberkeley
[ "309b3d3f6b3334c8de8e41cce758423d16f7def9" ]
[ "hw2/plot.py" ]
[ "import seaborn as sns\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport json\nimport os\n\n\"\"\"\nUsing the plotter:\n\nCall it from the command line, and supply it with logdirs to experiments.\nSuppose you ran an experiment with name 'test', and you ran 'test' for 10 \nrandom seeds. The runner code stored it in the directory structure\n\n data\n L test_EnvName_DateTime\n L 0\n L log.txt\n L params.json\n L 1\n L log.txt\n L params.json\n .\n .\n .\n L 9\n L log.txt\n L params.json\n\nTo plot learning curves from the experiment, averaged over all random\nseeds, call\n\n python plot.py data/test_EnvName_DateTime --value AverageReturn\n\nand voila. To see a different statistics, change what you put in for\nthe keyword --value. You can also enter /multiple/ values, and it will \nmake all of them in order.\n\n\nSuppose you ran two experiments: 'test1' and 'test2'. In 'test2' you tried\na different set of hyperparameters from 'test1', and now you would like \nto compare them -- see their learning curves side-by-side. Just call\n\n python plot.py data/test1 data/test2\n\nand it will plot them both! They will be given titles in the legend according\nto their exp_name parameters. If you want to use custom legend titles, use\nthe --legend flag and then provide a title for each logdir.\n\n\"\"\"\n\ndef plot_data(data, value=\"AverageReturn\"):\n if isinstance(data, list):\n data = pd.concat(data, ignore_index=True)\n sns.set(style=\"darkgrid\", font_scale=1.5)\n # print(data)\n sns.tsplot(data=data, time=\"Iteration\", value=value, unit=\"Unit\", condition=\"Condition\")\n plt.legend(loc='best').draggable()\n plt.show()\n\n\ndef get_datasets(fpath, condition=None):\n unit = 0\n datasets = []\n for root, dir, files in os.walk(fpath):\n if 'log.txt' in files:\n param_path = open(os.path.join(root, 'params.json'))\n params = json.load(param_path)\n exp_name = params['exp_name']\n \n log_path = os.path.join(root, 'log.txt')\n experiment_data = pd.read_table(log_path)\n\n experiment_data.insert(\n len(experiment_data.columns),\n 'Unit',\n unit\n )\n experiment_data.insert(\n len(experiment_data.columns),\n 'Condition',\n condition or exp_name\n )\n datasets.append(experiment_data)\n unit += 1\n\n return datasets\n\n\ndef main():\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument('logdir', nargs='*')\n parser.add_argument('--legend', nargs='*')\n parser.add_argument('--value', default='AverageReturn', nargs='*')\n args = parser.parse_args()\n\n use_legend = False\n if args.legend is not None:\n assert len(args.legend) == len(args.logdir), \\\n \"Must give a legend title for each set of experiments.\"\n use_legend = True\n\n data = []\n if use_legend:\n for logdir, legend_title in zip(args.logdir, args.legend):\n data += get_datasets(logdir, legend_title)\n else:\n for logdir in args.logdir:\n data += get_datasets(logdir)\n\n if isinstance(args.value, list):\n values = args.value\n else:\n values = [args.value]\n for value in values:\n plot_data(data, value=value)\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "matplotlib.pyplot.show", "pandas.read_table", "matplotlib.pyplot.legend", "pandas.concat" ] ]
dylanv/unet
[ "31f0deac92c89fff9a86573439235efc09fb1b37" ]
[ "unet/data/synthetic_data.py" ]
[ "\"\"\"Utilities for generating synthetic segmentation datasets.\"\"\"\n\nimport os\nfrom typing import Tuple\nfrom pathlib import Path\n\nimport numpy as np\nfrom skimage.draw import random_shapes\nfrom skimage.transform import rotate\nfrom skimage.io import imsave\n\n\ndef gen_shape_image(im_size: Tuple[int, int], max_shapes: int=10, overlap: bool=False, rotation: bool=False):\n # Generate an image with random shapes\n img, shapes = random_shapes(im_size, max_shapes, min_size=25, max_size=150,\n multichannel=False, allow_overlap=overlap)\n\n # Find each shape and get the corresponding pixels for the label map\n labels = np.zeros(im_size)\n shape_map = {'circle': 1, 'rectangle': 2, 'triangle': 3}\n for shape, coords in shapes:\n rr, cc = coords\n shape_img = img[rr[0]:rr[1], cc[0]:cc[1]]\n colors = np.bincount(shape_img.ravel()).argsort()\n shape_color = colors[-1] if colors[-1] != 255 else colors[-2]\n shape_rr, shape_cc = np.where(shape_img == shape_color)\n shape_rr += rr[0]\n shape_cc += cc[0]\n labels[shape_rr, shape_cc] = shape_map[shape]\n\n # If we're rotating pick a random number between -180 and 180 and then rotate\n if rotation:\n angle = np.random.uniform(-180, 180)\n img = rotate(img, angle, preserve_range=True, resize=True, cval=255).astype(np.int)\n labels = rotate(labels, angle, preserve_range=True, resize=True).astype(np.int)\n\n # Swap the background color to a random color to make things interesting\n background = 255\n while background in np.unique(img):\n background = np.random.randint(0, 255)\n img[img == 255] = background\n\n return img.astype(np.int), labels.astype(np.int)\n\n\ndef generate_synthetic_dataset(path, num_samples: int, im_size=(256, 256),\n max_shapes: int=10, overlap: bool=False, p_rotate: float=0):\n path = Path(path)\n img_path = path / 'images'\n label_path = path / 'labels'\n os.makedirs(img_path, exist_ok=True)\n os.makedirs(label_path, exist_ok=True)\n for i in range(num_samples):\n rotation = bool(np.random.rand(1) < p_rotate)\n img, labels = gen_shape_image(im_size, max_shapes, overlap, rotation)\n img_name = f'{i}.png'\n imsave(img_path / img_name, img)\n imsave(label_path / img_name, labels)\n" ]
[ [ "numpy.random.rand", "numpy.zeros", "numpy.where", "numpy.random.uniform", "numpy.random.randint", "numpy.unique" ] ]
ealejo1/bigdata-machine-learning-challenge
[ "152de2c4245b4c303c4578cfc9f72176ad711af9" ]
[ "model.py" ]
[ "# Dependencies\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.neighbors import KNeighborsClassifier\nimport pickle\n\ndef train_model():\n # Read data set\n spotify_df = pd.read_csv(\"spotify_data_v4.csv\")\n\n # Extract the necessary columns we need for machine learning model\n spotify_df_clean = spotify_df[[\n 'genre', 'genre_label', 'loudness', 'energy', \n 'danceability', 'instrumentalness'\n ]]\n\n # Assign X (data) and y (target)\n X = spotify_df_clean.drop([\"genre\", \"genre_label\"], axis=1)\n y = spotify_df_clean[\"genre_label\"]\n\n # Create train and test sets\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)\n\n # Scale the data using MinMaxScaler\n # Create a MinMaxScaler model and fit it to the training data\n X_scaler = MinMaxScaler().fit(X_train)\n\n # Transform the training and testing data using the X_scaler\n X_train_scaled = X_scaler.transform(X_train)\n X_test_scaled = X_scaler.transform(X_test)\n\n return X_train_scaled, X_test_scaled, y_train, y_test\n\ndef scale_input(score_list):\n # Read data set\n spotify_df = pd.read_csv(\"spotify_data_v4.csv\")\n\n # Extract the necessary columns we need for machine learning model\n spotify_df_clean = spotify_df[[\n 'genre', 'genre_label', 'loudness', 'energy', \n 'danceability', 'instrumentalness'\n ]]\n\n # Assign X (data) and y (target)\n X = spotify_df_clean.drop([\"genre\", \"genre_label\"], axis=1)\n y = spotify_df_clean[\"genre_label\"]\n\n # Create train and test sets\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)\n\n # Scale the data using MinMaxScaler\n # Create a MinMaxScaler model and fit it to the training data\n X_scaler = MinMaxScaler().fit(X_train)\n\n # Need to scale and transform the input using X_scaler which the scaler we used while training the data\n score_list_scaled = X_scaler.transform([score_list])\n\n return score_list_scaled" ]
[ [ "sklearn.model_selection.train_test_split", "pandas.read_csv", "sklearn.preprocessing.MinMaxScaler" ] ]
weiguangcui/pymsz
[ "79d81ef070a02f4109f5307407e0f549f44a8ec7" ]
[ "pymsz/SZpack_models.py" ]
[ "\"\"\"\nProjection class for the Sunyaev-Zeldovich effect. Requires SZpack (version 1.1.1),\nwhich is included in SZpack.v1.1.1 and will be automatically installed.\nWebsite for the SZpack library: http://www.chluba.de/SZpack/\n\nFor details on the computations involved please refer to the following references:\nChluba, Nagai, Sazonov, Nelson, MNRAS, 2012, arXiv:1205.5778\nChluba, Switzer, Nagai, Nelson, MNRAS, 2012, arXiv:1211.3206\n\nMany thanks to John ZuHone, who wrote the yt part of this model.\n\"\"\"\n\nimport numpy as np\nfrom pymsz.SZpacklib import SZpack\n# I0 = (2 * (kboltz * Tcmb)**3 / ((hcgs * clight)**2) / units.sr).in_units(\"MJy/steradian\")\n\n\nclass SZpack_model(object):\n r\"\"\" Theoretical calculation of y and T_sz -map for the thermal SZ effect.\n model = TH_model(model_file, npixel, axis)\n\n Parameters\n ----------\n simudata : the simulation data from load_data\n freqs : The frequencies (in GHz) at which to compute the SZ spectral distortion. array_like\n npixel : number of pixels for your image, int.\n Assume that x-y have the same number of pixels\n axis : can be 'x', 'y', 'z', or a list of degrees [alpha, beta, gamma],\n which will rotate the data points by $\\alpha$ around the x-axis,\n $\\beta$ around the y-axis, and $\\gamma$ around the z-axis\n neighbours: this parameter only works with simulation data (not yt data).\n If this is set, it will force the SPH particles smoothed into nearby N\n neighbours, HSML from the simulation will be ignored.\n If no HSML provided in the simulation, neighbours = 27\n AR : angular resolution in arcsec.\n Default : None, which gives npixel = 2 * cluster radius\n and ignores the cluster's redshift.\n Otherwise, cluster's redshift with AR decides how large the cluster looks.\n redshift : The redshift where the cluster is at.\n Default : None, we will look it from simulation data.\n If redshift = 0, it will be automatically put into 0.02,\n unless AR is set to None.\n high_order : boolean, optional\n Should we calculate high-order moments of velocity and temperature?\n Returns\n -------\n Theoretical projected y-map in a given direction. 2D mesh data right now.\n\n See also\n --------\n SZ_models for the mock SZ signal at different frequencies.\n\n Notes\n -----\n\n Examples\n --------\n >>> freqs = [90., 180., 240.]\n >>> szprj = SZProjection(ds, freqs, high_order=True)\n \"\"\"\n\n def __init__(self, simudata, freqs, npixel=500, neighbours=None, axis='z', AR=None,\n redshift=None):\n self.npl = npixel\n self.ngb = neighbours\n self.ax = axis\n self.ar = AR\n self.red = redshift\n self.pxs = 0\n self.ydata = np.array([])\n self.freqs = np.asarray(freqs)\n\n if simudata.data_type == \"snapshot\":\n self._cal_ss(simudata)\n elif simudata.data_type == \"yt_data\":\n self._cal_yt(simudata)\n else:\n raise ValueError(\"Do not accept this data type %s\"\n \"Please try to use load_data to get the data\" % simudata.data_type)\n\n # def _cal_ss(self, simd):\n # Kpc = 3.0856775809623245e+21 # cm\n # simd.prep_ss_SZ()\n #\n # def _cal_yt(self, simd):\n # from yt.config import ytcfg\n # from yt.utilities.physical_constants import sigma_thompson, clight, mh\n # # kboltz, Tcmb, hcgs,\n # from yt.funcs import fix_axis, get_pbar\n # from yt.visualization.volume_rendering.off_axis_projection import \\\n # off_axis_projection\n # from yt.utilities.parallel_tools.parallel_analysis_interface import \\\n # communication_system, parallel_root_only\n # # from yt import units\n # from yt.utilities.on_demand_imports import _astropy\n #\n # def generate_beta_par(L):\n # def _beta_par(field, data):\n # vpar = data[\"density\"] * (data[\"velocity_x\"] * L[0] +\n # data[\"velocity_y\"] * L[1] +\n # data[\"velocity_z\"] * L[2])\n # return vpar / clight\n # return _beta_par\n # Ptype = simd.prep_yt_SZ()\n #\n # # self.ds = ds\n # # self.num_freqs = len(freqs)\n # # self.high_order = high_order\n # # self.freqs = ds.arr(freqs, \"GHz\")\n # # self.mueinv = 1. / mue\n # # self.xinit = hcgs * self.freqs.in_units(\"Hz\") / (kboltz * Tcmb)\n # # self.freq_fields = [\"%d_GHz\" % (int(freq)) for freq in freqs]\n # # self.data = {}\n # #\n # # self.display_names = {}\n # # self.display_names[\"TeSZ\"] = r\"$\\mathrm{T_e}$\"\n # # self.display_names[\"Tau\"] = r\"$\\mathrm{\\tau}$\"\n # #\n # # for f, field in zip(self.freqs, self.freq_fields):\n # # self.display_names[field] = r\"$\\mathrm{\\Delta{I}_{%d\\ GHz}}$\" % int(f)\n # #\n # # def on_axis(self, axis, center=\"c\", width=(1, \"unitary\"), nx=800, source=None):\n # # r\"\"\" Make an on-axis projection of the SZ signal.\n # #\n # # Parameters\n # # ----------\n # # axis : integer or string\n # # The axis of the simulation domain along which to make the SZprojection.\n # # center : A sequence of floats, a string, or a tuple.\n # # The coordinate of the center of the image. If set to 'c', 'center' or\n # # left blank, the plot is centered on the middle of the domain. If set to\n # # 'max' or 'm', the center will be located at the maximum of the\n # # ('gas', 'density') field. Centering on the max or min of a specific\n # # field is supported by providing a tuple such as (\"min\",\"temperature\") or\n # # (\"max\",\"dark_matter_density\"). Units can be specified by passing in *center*\n # # as a tuple containing a coordinate and string unit name or by passing\n # # in a YTArray. If a list or unitless array is supplied, code units are\n # # assumed.\n # # width : tuple or a float.\n # # Width can have four different formats to support windows with variable\n # # x and y widths. They are:\n # #\n # # ================================== =======================\n # # format example\n # # ================================== =======================\n # # (float, string) (10,'kpc')\n # # ((float, string), (float, string)) ((10,'kpc'),(15,'kpc'))\n # # float 0.2\n # # (float, float) (0.2, 0.3)\n # # ================================== =======================\n # #\n # # For example, (10, 'kpc') requests a plot window that is 10 kiloparsecs\n # # wide in the x and y directions, ((10,'kpc'),(15,'kpc')) requests a\n # # window that is 10 kiloparsecs wide along the x axis and 15\n # # kiloparsecs wide along the y axis. In the other two examples, code\n # # units are assumed, for example (0.2, 0.3) requests a plot that has an\n # # x width of 0.2 and a y width of 0.3 in code units. If units are\n # # provided the resulting plot axis labels will use the supplied units.\n # # nx : integer, optional\n # # The dimensions on a side of the projection image.\n # # source : yt.data_objects.data_containers.YTSelectionContainer, optional\n # # If specified, this will be the data source used for selecting regions to project.\n # #\n # # Examples\n # # --------\n # # >>> szprj.on_axis(\"y\", center=\"max\", width=(1.0, \"Mpc\"), source=my_sphere)\n # # \"\"\"\n #\n # axis = fix_axis(axis, self.ds)\n # ctr, dctr = self.ds.coordinates.sanitize_center(center, axis)\n # width = self.ds.coordinates.sanitize_width(axis, width, None)\n #\n # L = np.zeros(3)\n # L[axis] = 1.0\n #\n # beta_par = generate_beta_par(L)\n # self.ds.add_field((\"gas\", \"beta_par\"), function=beta_par, units=\"g/cm**3\")\n # setup_sunyaev_zeldovich_fields(self.ds)\n # proj = self.ds.proj(\"density\", axis, center=ctr, data_source=source)\n # frb = proj.to_frb(width[0], nx, height=width[1])\n # dens = frb[\"density\"]\n # Te = frb[\"t_sz\"] / dens\n # bpar = frb[\"beta_par\"] / dens\n # omega1 = frb[\"t_squared\"] / dens / (Te * Te) - 1.\n # bperp2 = np.zeros((nx, nx))\n # sigma1 = np.zeros((nx, nx))\n # kappa1 = np.zeros((nx, nx))\n # if self.high_order:\n # bperp2 = frb[\"beta_perp_squared\"] / dens\n # sigma1 = frb[\"t_beta_par\"] / dens / Te - bpar\n # kappa1 = frb[\"beta_par_squared\"] / dens - bpar * bpar\n # tau = sigma_thompson * dens * self.mueinv / mh\n #\n # nx, ny = frb.buff_size\n # self.bounds = frb.bounds\n # self.dx = (frb.bounds[1] - frb.bounds[0]) / nx\n # self.dy = (frb.bounds[3] - frb.bounds[2]) / ny\n # self.nx = nx\n #\n # self._compute_intensity(np.array(tau), np.array(Te), np.array(bpar),\n # np.array(omega1), np.array(sigma1),\n # np.array(kappa1), np.array(bperp2))\n #\n # self.ds.field_info.pop((\"gas\", \"beta_par\"))\n #\n # def off_axis(self, L, center=\"c\", width=(1.0, \"unitary\"), depth=(1.0, \"unitary\"),\n # nx=800, nz=800, north_vector=None, no_ghost=False, source=None):\n # r\"\"\" Make an off-axis projection of the SZ signal.\n #\n # Parameters\n # ----------\n # L : array_like\n # The normal vector of the projection.\n # center : A sequence of floats, a string, or a tuple.\n # The coordinate of the center of the image. If set to 'c', 'center' or\n # left blank, the plot is centered on the middle of the domain. If set to\n # 'max' or 'm', the center will be located at the maximum of the\n # ('gas', 'density') field. Centering on the max or min of a specific\n # field is supported by providing a tuple such as (\"min\",\"temperature\") or\n # (\"max\",\"dark_matter_density\"). Units can be specified by passing in *center*\n # as a tuple containing a coordinate and string unit name or by passing\n # in a YTArray. If a list or unitless array is supplied, code units are\n # assumed.\n # width : tuple or a float.\n # Width can have four different formats to support windows with variable\n # x and y widths. They are:\n #\n # ================================== =======================\n # format example\n # ================================== =======================\n # (float, string) (10,'kpc')\n # ((float, string), (float, string)) ((10,'kpc'),(15,'kpc'))\n # float 0.2\n # (float, float) (0.2, 0.3)\n # ================================== =======================\n #\n # For example, (10, 'kpc') requests a plot window that is 10 kiloparsecs\n # wide in the x and y directions, ((10,'kpc'),(15,'kpc')) requests a\n # window that is 10 kiloparsecs wide along the x axis and 15\n # kiloparsecs wide along the y axis. In the other two examples, code\n # units are assumed, for example (0.2, 0.3) requests a plot that has an\n # x width of 0.2 and a y width of 0.3 in code units. If units are\n # provided the resulting plot axis labels will use the supplied units.\n # depth : A tuple or a float\n # A tuple containing the depth to project through and the string\n # key of the unit: (width, 'unit'). If set to a float, code units\n # are assumed\n # nx : integer, optional\n # The dimensions on a side of the projection image.\n # nz : integer, optional\n # Deprecated, this is still in the function signature for API\n # compatibility\n # north_vector : a sequence of floats\n # A vector defining the 'up' direction in the plot. This\n # option sets the orientation of the slicing plane. If not\n # set, an arbitrary grid-aligned north-vector is chosen.\n # no_ghost: bool, optional\n # Optimization option for off-axis cases. If True, homogenized bricks will\n # extrapolate out from grid instead of interpolating from\n # ghost zones that have to first be calculated. This can\n # lead to large speed improvements, but at a loss of\n # accuracy/smoothness in resulting image. The effects are\n # less notable when the transfer function is smooth and\n # broad. Default: True\n # source : yt.data_objects.data_containers.YTSelectionContainer, optional\n # If specified, this will be the data source used for selecting regions\n # to project.\n #\n # Examples\n # --------\n # >>> L = np.array([0.5, 1.0, 0.75])\n # >>> szprj.off_axis(L, center=\"c\", width=(2.0, \"Mpc\"))\n # \"\"\"\n # wd = self.ds.coordinates.sanitize_width(L, width, depth)\n # w = tuple(el.in_units('code_length').v for el in wd)\n # ctr, dctr = self.ds.coordinates.sanitize_center(center, L)\n # res = (nx, nx)\n #\n # if source is None:\n # source = self.ds\n #\n # beta_par = generate_beta_par(L)\n # self.ds.add_field((\"gas\", \"beta_par\"), function=beta_par, units=\"g/cm**3\")\n # setup_sunyaev_zeldovich_fields(self.ds)\n #\n # dens = off_axis_projection(source, ctr, L, w, res, \"density\",\n # north_vector=north_vector, no_ghost=no_ghost)\n # Te = off_axis_projection(source, ctr, L, w, res, \"t_sz\",\n # north_vector=north_vector, no_ghost=no_ghost) / dens\n # bpar = off_axis_projection(source, ctr, L, w, res, \"beta_par\",\n # north_vector=north_vector, no_ghost=no_ghost) / dens\n # omega1 = off_axis_projection(source, ctr, L, w, res, \"t_squared\",\n # north_vector=north_vector, no_ghost=no_ghost) / dens\n # omega1 = omega1 / (Te * Te) - 1.\n # if self.high_order:\n # bperp2 = off_axis_projection(source, ctr, L, w, res, \"beta_perp_squared\",\n # north_vector=north_vector, no_ghost=no_ghost) / dens\n # sigma1 = off_axis_projection(source, ctr, L, w, res, \"t_beta_par\",\n # north_vector=north_vector, no_ghost=no_ghost) / dens\n # sigma1 = sigma1 / Te - bpar\n # kappa1 = off_axis_projection(source, ctr, L, w, res, \"beta_par_squared\",\n # north_vector=north_vector, no_ghost=no_ghost) / dens\n # kappa1 -= bpar\n # else:\n # bperp2 = np.zeros((nx, nx))\n # sigma1 = np.zeros((nx, nx))\n # kappa1 = np.zeros((nx, nx))\n # tau = sigma_thompson * dens * self.mueinv / mh\n #\n # self.bounds = (-0.5 * wd[0], 0.5 * wd[0], -0.5 * wd[1], 0.5 * wd[1])\n # self.dx = wd[0] / nx\n # self.dy = wd[1] / nx\n # self.nx = nx\n #\n # self._compute_intensity(np.array(tau), np.array(Te), np.array(bpar),\n # np.array(omega1), np.array(sigma1),\n # np.array(kappa1), np.array(bperp2))\n #\n # self.ds.field_info.pop((\"gas\", \"beta_par\"))\n #\n # def _compute_intensity(self, tau, Te, bpar, omega1, sigma1, kappa1, bperp2):\n #\n # # Bad hack, but we get NaNs if we don't do something like this\n # small_beta = np.abs(bpar) < 1.0e-20\n # bpar[small_beta] = 1.0e-20\n #\n # comm = communication_system.communicators[-1]\n #\n # nx, ny = self.nx, self.nx\n # signal = np.zeros((self.num_freqs, nx, ny))\n # xo = np.zeros(self.num_freqs)\n #\n # k = int(0)\n #\n # start_i = comm.rank * nx // comm.size\n # end_i = (comm.rank + 1) * nx // comm.size\n #\n # pbar = get_pbar(\"Computing SZ signal.\", nx * nx)\n #\n # for i in range(start_i, end_i):\n # for j in range(ny):\n # xo[:] = self.xinit[:]\n # SZpack.compute_combo_means(xo, tau[i, j], Te[i, j],\n # bpar[i, j], omega1[i, j],\n # sigma1[i, j], kappa1[i, j], bperp2[i, j])\n # signal[:, i, j] = xo[:]\n # pbar.update(k)\n # k += 1\n #\n # signal = comm.mpi_allreduce(signal)\n #\n # pbar.finish()\n #\n # for i, field in enumerate(self.freq_fields):\n # self.data[field] = I0 * self.xinit[i]**3 * signal[i, :, :]\n # self.data[\"Tau\"] = self.ds.arr(tau, \"dimensionless\")\n # self.data[\"TeSZ\"] = self.ds.arr(Te, \"keV\")\n #\n # def write_fits(self, filename, sky_scale=None, sky_center=None, clobber=True):\n # r\"\"\" Export images to a FITS file. Writes the SZ distortion in all\n # specified frequencies as well as the mass-weighted temperature and the\n # optical depth. Distance units are in kpc, unless *sky_center*\n # and *scale* are specified.\n #\n # Parameters\n # ----------\n # filename : string\n # The name of the FITS file to be written.\n # sky_scale : tuple\n # Conversion between an angle unit and a length unit, if sky\n # coordinates are desired, e.g. (1.0, \"arcsec/kpc\")\n # sky_center : tuple, optional\n # The (RA, Dec) coordinate in degrees of the central pixel. Must\n # be specified with *sky_scale*.\n # clobber : boolean, optional\n # If the file already exists, do we overwrite?\n #\n # Examples\n # --------\n # >>> # This example just writes out a FITS file with kpc coords\n # >>> szprj.write_fits(\"SZbullet.fits\", clobber=False)\n # >>> # This example uses sky coords\n # >>> sky_scale = (1., \"arcsec/kpc\") # One arcsec per kpc\n # >>> sky_center = (30., 45., \"deg\")\n # >>> szprj.write_fits(\"SZbullet.fits\", sky_center=sky_center, sky_scale=sky_scale)\n # \"\"\"\n # from yt.visualization.fits_image import FITSImageData\n #\n # dx = self.dx.in_units(\"kpc\")\n # dy = dx\n #\n # w = _astropy.pywcs.WCS(naxis=2)\n # w.wcs.crpix = [0.5 * (self.nx + 1)] * 2\n # w.wcs.cdelt = [dx.v, dy.v]\n # w.wcs.crval = [0.0, 0.0]\n # w.wcs.cunit = [\"kpc\"] * 2\n # w.wcs.ctype = [\"LINEAR\"] * 2\n #\n # fib = FITSImageData(self.data, fields=self.data.keys(), wcs=w)\n # if sky_scale is not None and sky_center is not None:\n # fib.create_sky_wcs(sky_center, sky_scale)\n # fib.writeto(filename, clobber=clobber)\n #\n # @parallel_root_only\n # def write_png(self, filename_prefix, cmap_name=None,\n # axes_units=\"kpc\", log_fields=None):\n # r\"\"\" Export images to PNG files. Writes the SZ distortion in all\n # specified frequencies as well as the mass-weighted temperature and the\n # optical depth. Distance units are in kpc.\n #\n # Parameters\n # ----------\n # filename_prefix : string\n # The prefix of the image filenames.\n #\n # Examples\n # --------\n # >>> szprj.write_png(\"SZsloshing\")\n # \"\"\"\n # if cmap_name is None:\n # cmap_name = ytcfg.get(\"yt\", \"default_colormap\")\n #\n # import matplotlib\n # matplotlib.use('Agg')\n # import matplotlib.pyplot as plt\n # if log_fields is None:\n # log_fields = {}\n # ticks_font = matplotlib.font_manager.FontProperties(family='serif', size=16)\n # extent = tuple([bound.in_units(axes_units).value for bound in self.bounds])\n # for field, image in self.items():\n # data = image.copy()\n # vmin, vmax = image.min(), image.max()\n # negative = False\n # crossover = False\n # if vmin < 0 and vmax < 0:\n # data *= -1\n # negative = True\n # if field in log_fields:\n # log_field = log_fields[field]\n # else:\n # log_field = True\n # if log_field:\n # formatter = matplotlib.ticker.LogFormatterMathtext()\n # norm = matplotlib.colors.LogNorm()\n # if vmin < 0 and vmax > 0:\n # crossover = True\n # linthresh = min(vmax, -vmin) / 100.\n # norm = matplotlib.colors.SymLogNorm(linthresh,\n # vmin=vmin, vmax=vmax)\n # else:\n # norm = None\n # formatter = None\n # filename = filename_prefix + \"_\" + field + \".png\"\n # cbar_label = self.display_names[field]\n # units = self.data[field].units.latex_representation()\n # if units is not None and units != \"\":\n # cbar_label += r'$\\ \\ (' + units + r')$'\n # fig = plt.figure(figsize=(10.0, 8.0))\n # ax = fig.add_subplot(111)\n # cax = ax.imshow(data.d, norm=norm, extent=extent, cmap=cmap_name, origin=\"lower\")\n # for label in ax.get_xticklabels():\n # label.set_fontproperties(ticks_font)\n # for label in ax.get_yticklabels():\n # label.set_fontproperties(ticks_font)\n # ax.set_xlabel(r\"$\\mathrm{x\\ (%s)}$\" % axes_units, fontsize=16)\n # ax.set_ylabel(r\"$\\mathrm{y\\ (%s)}$\" % axes_units, fontsize=16)\n # cbar = fig.colorbar(cax, format=formatter)\n # cbar.ax.set_ylabel(cbar_label, fontsize=16)\n # if negative:\n # cbar.ax.set_yticklabels([\"-\" + label.get_text()\n # for label in cbar.ax.get_yticklabels()])\n # if crossover:\n # yticks = list(-10**np.arange(np.floor(np.log10(-vmin)),\n # np.rint(np.log10(linthresh)) - 1, -1)) + [0] + \\\n # list(10**np.arange(np.rint(np.log10(linthresh)),\n # np.ceil(np.log10(vmax)) + 1))\n # cbar.set_ticks(yticks)\n # for label in cbar.ax.get_yticklabels():\n # label.set_fontproperties(ticks_font)\n # fig.tight_layout()\n # plt.savefig(filename)\n #\n # @parallel_root_only\n # def write_hdf5(self, filename):\n # r\"\"\"Export the set of S-Z fields to a set of HDF5 datasets.\n #\n # Parameters\n # ----------\n # filename : string\n # This file will be opened in \"write\" mode.\n #\n # Examples\n # --------\n # >>> szprj.write_hdf5(\"SZsloshing.h5\")\n # \"\"\"\n # for field, data in self.items():\n # data.write_hdf5(filename, dataset_name=field)\n #\n # def keys(self):\n # return self.data.keys()\n #\n # def items(self):\n # return self.data.items()\n #\n # def values(self):\n # return self.data.values()\n #\n # def has_key(self, key):\n # return key in self.data.keys()\n #\n # def __getitem__(self, key):\n # return self.data[key]\n #\n # @property\n # def shape(self):\n # return (self.nx, self.nx)\n" ]
[ [ "numpy.array", "numpy.asarray" ] ]
jerinka/voxelmorph_demo
[ "c7994b09049c286922a441bf5b9291ef00ed504e" ]
[ "register_basics.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"poc.ipynb\n\nAutomatically generated by Colaboratory.\n\nOriginal file is located at\n https://colab.research.google.com/drive/1fTzz1aT2sb8oAXRO1-dr6O_IR6dof36e\n\nA simple example for deep-learning-based non-rigid image registration\nwith the MNIST dataset.\n\n**README:** If the below error occurs, run the whole notebook again (Ctrl+F9).\n\n\n```\nValueError: tf.function-decorated function tried to create variables on non-first call.\n```\n\"\"\"\n\nimport tensorflow as tf\nimport tensorflow.keras.layers as layers\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nprint(tf.__version__)\nprint(tf.keras.backend.image_data_format())\n\n\"\"\"Loss functions\"\"\"\n\n@tf.function\ndef mse_loss(static, moving):\n \"\"\"Computes the mean squared error (MSE) loss.\n\n Currently, only 4-D inputs are supported.\n\n Parameters\n ----------\n static : tf.Tensor, shape (N, H, W, C)\n The static image to which the moving image is aligned.\n moving : tf.Tensor, shape (N, H, W, C)\n The moving image, the same shape as the static image.\n\n Returns\n -------\n loss : tf.Tensor, shape ()\n Mean squared error between the static and the moving images,\n averaged over the batch.\n \"\"\"\n loss = tf.reduce_mean(tf.square(moving - static)) # shape ()\n return loss\n\n@tf.function\ndef ncc_loss(static, moving):\n \"\"\"Computes the normalized cross-correlation (NCC) loss.\n\n Currently, only 4-D inputs are supported.\n\n Parameters\n ----------\n static : tf.Tensor, shape (N, H, W, C)\n The static image to which the moving image is aligned.\n moving : tf.Tensor, shape (N, H, W, C)\n The moving image, the same shape as the static image.\n\n Returns\n -------\n loss : tf.Tensor, shape ()\n Normalized cross-correlation loss between the static and the\n moving images, averaged over the batch. Range is [-1.0, 1.0].\n The best value is -1 (perfect match) and the worst is 1.\n\n References\n ----------\n .. [1] `Wikipedia entry for the Cross-correlation\n <https://en.wikipedia.org/wiki/Cross-correlation>`_\n \"\"\"\n eps = tf.constant(1e-9, 'float32')\n\n static_mean = tf.reduce_mean(static, axis=[1, 2], keepdims=True)\n moving_mean = tf.reduce_mean(moving, axis=[1, 2], keepdims=True)\n # shape (N, 1, 1, C)\n\n static_std = tf.math.reduce_std(static, axis=[1, 2], keepdims=True)\n moving_std = tf.math.reduce_std(moving, axis=[1, 2], keepdims=True)\n # shape (N, 1, 1, C)\n\n static_hat = (static - static_mean)/(static_std + eps)\n moving_hat = (moving - moving_mean)/(moving_std + eps)\n # shape (N, H, W, C)\n\n ncc = tf.reduce_mean(static_hat * moving_hat) # shape ()\n loss = -ncc\n return loss\n\n\"\"\"Define the model \"\"\"\n\ndef simple_cnn(input_shape=(32, 32, 2)):\n \"\"\"Creates a 2-D convolutional encoder-decoder network.\n\n Parameters\n ----------\n input_shape : sequence of ints, optional\n Input data shape of the form (H, W, C). Default is (32, 32, 2).\n\n Returns\n -------\n model\n An instance of Keras' Model class.\n\n Notes\n -----\n Given a concatenated pair of static and moving images as input, the\n CNN computes a dense displacement field that is used to warp the\n moving image to match with the static image.\n\n The number of channels in the output (displacement field) is equal\n to the dimensionality of the input data. For 3-D volumes, it is 3,\n and for 2-D images, it is 2. The first channel comprises\n displacement in the x-direction and the second comprises\n displacement in the y-direction.\n \"\"\"\n out_channels = 2\n inputs = layers.Input(shape=input_shape)\n\n # encoder\n x = layers.Conv2D(32, kernel_size=3, strides=2, padding='same',\n activation='relu')(inputs) # 32 --> 16\n x = layers.BatchNormalization()(x) # 16\n x = layers.Conv2D(32, kernel_size=3, strides=1, padding='same',\n activation='relu')(x) # 16\n x = layers.BatchNormalization()(x) # 16\n x = layers.MaxPool2D(pool_size=2)(x) # 16 --> 8\n x = layers.Conv2D(64, kernel_size=3, strides=1, padding='same',\n activation='relu')(x) # 8\n x = layers.BatchNormalization()(x) # 8\n x = layers.Conv2D(64, kernel_size=3, strides=1, padding='same',\n activation='relu')(x) # 8\n x = layers.BatchNormalization()(x) # 8\n x = layers.MaxPool2D(pool_size=2)(x) # 8 --> 4\n x = layers.Conv2D(128, kernel_size=3, strides=1, padding='same',\n activation='relu')(x) # 4\n x = layers.BatchNormalization()(x) # 4\n\n # decoder\n x = layers.Conv2DTranspose(64, kernel_size=2, strides=2,\n padding='same')(x) # 4 --> 8\n x = layers.Conv2D(64, kernel_size=3, strides=1, padding='same',\n activation='relu')(x) # 8\n x = layers.BatchNormalization()(x) # 8\n x = layers.Conv2DTranspose(32, kernel_size=2, strides=2,\n padding='same')(x) # 8 --> 16\n x = layers.Conv2D(32, kernel_size=3, strides=1, padding='same',\n activation='relu')(x) # 16\n x = layers.BatchNormalization()(x) # 16\n x = layers.Conv2DTranspose(16, kernel_size=2, strides=2,\n padding='same')(x) # 16 --> 32\n x = layers.Conv2D(16, kernel_size=3, strides=1, padding='same',\n activation='relu')(x) # 32\n x = layers.BatchNormalization()(x) # 32\n x = layers.Conv2D(out_channels, kernel_size=1, strides=1,\n padding='same')(x) # 32\n\n # Create the model.\n model = tf.keras.Model(inputs, x, name='simple_cnn')\n return model\n\n\n\n \"\"\"\n Differntiable image sampling\n References:\n 1. https://github.com/tensorflow/models/blob/master/research/transformer/spatial_transformer.py\n 2. Jaderberg, Max, Karen Simonyan, and Andrew Zisserman. \"Spatial\n transformer networks.\" Advances in neural information processing\n systems. 2015. https://arxiv.org/pdf/1506.02025.pdf\n 3. *Spatial* Transformer Networks by Kushagra Bhatnagar https://link.medium.com/0b2OrmqVO5\n \"\"\"\n\n@tf.function\ndef grid_sample(moving, grid):\n \"\"\"Given a moving image and a sampling grid as input, computes the\n transformed image by sampling the moving image at locations given by\n the grid.\n\n Currently, only 2-D images, i.e., 4-D inputs are supported.\n\n Parameters\n ----------\n moving : tf.Tensor, shape (N, H, W, C)\n The moving image.\n grid : tf.Tensor, shape (N, H, W, C)\n A tensor of sampling points (x, y). The x and y values should be\n normalized to [-1.0, 1.0] range.\n\n Returns\n -------\n moved : tf.Tensor, shape (N, H, W, C)\n The transformed image.\n\n Notes\n -----\n Let M be the moving image of shape (H, W, C), T be the transformed\n image of the same shape and G be the 2-D sampling grid of shape\n (H, W, 2). The value of T at a location (x, y) is T[y, x, :] =\n M[y', x', :] where [x', y'] = G[y, x, :].\n\n Further, [x', y'] = [x + dx, y + dy] where [dx, dy] are the\n displacements outputted by the CNN. When dx and dy are 0, the\n sampling grid G is a regular grid and the transformed image is the\n same as the moving image.\n\n Since the sampling point (x + dx, y + dy) can be non-integral, the\n value M[y', x'] is calculated using bi-linear interpolation.\n\n References\n ----------\n .. [1] `Jaderberg, Max, Karen Simonyan, and Andrew Zisserman. \"Spatial\n transformer networks.\" Advances in neural information processing\n systems. 2015. <https://arxiv.org/abs/1506.02025>`_\n .. [2] `TensorFlow implementation of spatial transformer networks.\n <https://github.com/tensorflow/models/tree/master/research/transformer>`_\n .. [3] `Spatial Transformer Networks by Kushagra Bhatnagar\n <https://link.medium.com/0b2OrmqVO5>`_\n \"\"\"\n nb, nh, nw, nc = moving.shape\n\n x = grid[..., 0] # shape (N, H, W)\n y = grid[..., 1]\n x = tf.cast(x, 'float32')\n y = tf.cast(y, 'float32')\n\n # Scale x and y from [-1.0, 1.0] to [0, W] and [0, H] respectively.\n x = (x + 1.0) * 0.5 * tf.cast(nw, 'float32')\n y = (y + 1.0) * 0.5 * tf.cast(nh, 'float32')\n\n y_max = tf.cast(nh - 1, 'int32')\n x_max = tf.cast(nw - 1, 'int32')\n zero = tf.constant(0, 'int32')\n\n # The value at (x, y) is a weighted average of the values at the\n # four nearest integer locations: (x0, y0), (x1, y0), (x0, y1) and\n # (x1, y1) where x0 = floor(x), x1 = ceil(x).\n x0 = tf.cast(tf.floor(x), 'int32')\n x1 = x0 + 1\n y0 = tf.cast(tf.floor(y), 'int32')\n y1 = y0 + 1\n\n # Make sure indices are within the boundaries of the image.\n x0 = tf.clip_by_value(x0, zero, x_max)\n x1 = tf.clip_by_value(x1, zero, x_max)\n y0 = tf.clip_by_value(y0, zero, y_max)\n y1 = tf.clip_by_value(y1, zero, y_max)\n\n # Collect indices of the four corners.\n b = tf.ones_like(x0) * tf.reshape(tf.range(nb), [nb, 1, 1])\n idx_a = tf.stack([b, y0, x0], axis=-1) # all top-left corners\n idx_b = tf.stack([b, y1, x0], axis=-1) # all bottom-left corners\n idx_c = tf.stack([b, y0, x1], axis=-1) # all top-right corners\n idx_d = tf.stack([b, y1, x1], axis=-1) # all bottom-right corners\n # shape (N, H, W, 3)\n\n # Collect values at the corners.\n moving_a = tf.gather_nd(moving, idx_a) # all top-left values\n moving_b = tf.gather_nd(moving, idx_b) # all bottom-left values\n moving_c = tf.gather_nd(moving, idx_c) # all top-right values\n moving_d = tf.gather_nd(moving, idx_d) # all bottom-right values\n # shape (N, H, W, C)\n\n x0_f = tf.cast(x0, 'float32')\n x1_f = tf.cast(x1, 'float32')\n y0_f = tf.cast(y0, 'float32')\n y1_f = tf.cast(y1, 'float32')\n\n # Calculate the weights.\n wa = tf.expand_dims((x1_f - x) * (y1_f - y), axis=-1)\n wb = tf.expand_dims((x1_f - x) * (y - y0_f), axis=-1)\n wc = tf.expand_dims((x - x0_f) * (y1_f - y), axis=-1)\n wd = tf.expand_dims((x - x0_f) * (y - y0_f), axis=-1)\n\n # Calculate the weighted sum.\n moved = tf.add_n([wa * moving_a, wb * moving_b, wc * moving_c,\n wd * moving_d])\n return moved\n\n@tf.function\ndef regular_grid(shape):\n \"\"\"Returns a batch of 2-D regular grids.\n\n Currently, only 2-D regular grids are supported.\n\n Parameters\n ----------\n shape : sequence of ints, shape (3, )\n The desired regular grid shape of the form (N, H, W).\n\n Returns\n -------\n grid : tf.Tensor, shape (N, H, W, 2)\n A batch of 2-D regular grids, values normalized to [-1.0, 1.0]\n range.\n\n Notes\n -----\n Sampling using the regular grid is an identity transformation, i.e.,\n it results in the same input and output images.\n\n References\n ----------\n .. [1] `NumPy, \"numpy.meshgrid\"\n <https://numpy.org/doc/stable/reference/generated/numpy.meshgrid.html>`_\n .. [2] `NumPy, \"numpy.indices\"\n <https://numpy.org/doc/stable/reference/generated/numpy.indices.html>`_\n \"\"\"\n nb, nh, nw = shape\n\n x = tf.linspace(-1.0, 1.0, nw) # shape (W, )\n y = tf.linspace(-1.0, 1.0, nh) # shape (H, )\n\n X, Y = tf.meshgrid(x, y) # shape (H, W), both X and Y\n\n grid = tf.stack([X, Y], axis=-1)\n grid = tf.expand_dims(grid, axis=0) # shape (1, H, W, 2)\n\n # Repeat the grids along the batch dim.\n multiples = tf.constant([nb, 1, 1, 1], tf.int32)\n grid = tf.tile(grid, multiples)\n return grid\n\n\"\"\"Training and testing functions\"\"\"\n\n@tf.function\ndef train_step(model, moving, static, criterion, optimizer):\n \"\"\"A generic training procedure for one iteration.\n\n Parameters\n ----------\n model\n A convolutional encoder-decoder network.\n moving : tf.Tensor, shape (N, H, W, C)\n A batch of moving images.\n static : tf.Tensor, shape (1, H, W, C)\n The static image.\n criterion\n The loss function.\n optimizer\n An optimzer.\n\n Returns\n -------\n loss : tf.Tensor, shape ()\n The average loss for the batch.\n \"\"\"\n nb, nh, nw, nc = moving.shape\n\n # Repeat the static image along the batch dim.\n multiples = tf.constant([nb, 1, 1, 1], tf.int32)\n static = tf.tile(static, multiples)\n\n # Define the GradientTape context for automatic differentiation.\n with tf.GradientTape() as tape:\n # Get the deformation field\n inputs = tf.concat([moving, static], axis=-1)\n deformation = model(inputs)\n\n # Compute the new sampling grid.\n grid = regular_grid([nb, nh, nw])\n grid_new = grid + deformation\n grid_new = tf.clip_by_value(grid_new, -1, 1)\n\n # Sample the moving image using the new sampling grid.\n moved = grid_sample(moving, grid_new)\n\n # Compute the loss.\n loss = criterion(moved, static)\n\n # Compute gradients.\n grads = tape.gradient(loss, model.trainable_variables)\n # Update the trainable parameters.\n optimizer.apply_gradients(zip(grads, model.trainable_variables))\n return loss\n\n@tf.function\ndef test_step(model, moving, static, criterion):\n \"\"\"A generic testing procedure.\n\n Parameters\n ----------\n model\n A convolutional encoder-decoder network.\n moving : tf.Tensor, shape (N, H, W, C)\n A batch of moving images.\n static : tf.Tensor, shape (1, H, W, C)\n The static image.\n criterion\n The loss function.\n\n Returns\n -------\n loss : tf.Tensor, shape ()\n The average loss for the batch.\n \"\"\"\n nb, nh, nw, nc = moving.shape\n\n # Repeat the static image along the batch dim.\n multiples = tf.constant([nb, 1, 1, 1], tf.int32)\n static = tf.tile(static, multiples)\n\n # Get the deformation field.\n inputs = tf.concat([moving, static], axis=-1)\n deformation = model(inputs, training=False)\n\n # Compute the new sampling grid.\n grid = regular_grid([nb, nh, nw])\n grid_new = grid + deformation\n grid_new = tf.clip_by_value(grid_new, -1, 1)\n\n # Sample the moving image using the new sampling grid.\n moved = grid_sample(moving, grid_new)\n\n # Compute the loss.\n loss = criterion(moved, static)\n return loss\n\n\"\"\"Data loading\"\"\"\n\ndef load_data(label=2):\n \"\"\"Loads the MNIST dataset and preprocesses it: scales to [0.0, 1.0]\n range, resizes the images from (28, 28) to (32, 32) and filters the\n dataset to keep images of just one class.\n\n Parameters\n ----------\n label : {2, 0, 1, 3, 4, 5, 6, 7, 8, 9}, default 2\n The class of images to train and test on.\n\n Returns\n -------\n (x_train, x_test) : tuple of ndarrays\n NumPy arrays of training and testing images.\n \"\"\"\n (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()\n\n # Discard digits which are not equal to label.\n ids_train = np.where(y_train == label)\n ids_test = np.where(y_test == label)\n\n x_train = x_train[ids_train]\n x_test = x_test[ids_test]\n\n # Scale the image to [0, 1] range.\n x_train = x_train.astype(np.float32) / 255.0\n x_test = x_test.astype(np.float32) / 255.0\n\n # Add the channel dim at the end. (N, H, W) --> (N, H, W, 1)\n x_train = x_train[..., None]\n x_test = x_test[..., None]\n\n # Resize images from (28, 28) to (32, 32).\n x_train = tf.image.resize(x_train, (32, 32))\n x_test = tf.image.resize(x_test, (32, 32))\n return x_train, x_test\n\n\"\"\"Sample results\"\"\"\n\ndef plot_images(model, moving, static):\n \"\"\"Visualize some images after training.\n\n Parameters\n ----------\n model\n The trained model.\n moving : tf.Tensor, shape (N, H, W, C)\n A batch of moving images.\n static : tf.Tensor, shape (1, H, W, C)\n The static image.\n \"\"\"\n nb, nh, nw, nc = moving.shape\n\n # Repeat the static image along the batch dim.\n multiples = tf.constant([nb, 1, 1, 1], tf.int32)\n static = tf.tile(static, multiples)\n\n # Get the deformation fields for the batch.\n inputs = tf.concat([moving, static], axis=-1)\n deformation = model(inputs, training=False)\n\n # Compute the new sampling grids.\n grid = regular_grid([nb, nh, nw])\n grid_new = grid + deformation\n grid_new = tf.clip_by_value(grid_new, -1, 1)\n\n # Sample the moving images using the new sampling grids.\n moved = grid_sample(moving, grid_new)\n\n # Convert the tensors to 8-bit images.\n moved = moved.numpy().squeeze(axis=-1) * 255.0\n moved = moved.astype(np.uint8)\n moving = moving.numpy().squeeze(axis=-1) * 255.0\n moving = moving.astype(np.uint8)\n static = static.numpy().squeeze(axis=-1) * 255.0\n static = static.astype(np.uint8)\n\n # Plot images.\n fig = plt.figure(figsize=(3 * 1.7, nb * 1.7))\n titles_list = ['Static', 'Moved', 'Moving']\n images_list = [static, moved, moving]\n for i in range(nb):\n for j in range(3):\n ax = fig.add_subplot(nb, 3, i * 3 + j + 1)\n if i == 0:\n ax.set_title(titles_list[j], fontsize=20)\n ax.set_axis_off()\n ax.imshow(images_list[j][i], cmap='gray')\n\n plt.tight_layout()\n plt.show()\n\n\nif __name__ == '__main__':\n\n class Args():\n batch_size = 8\n epochs = 50\n lr = 0.004\n label = 7 # which digit images to train on?\n num_samples = 5 # number of sample results to show\n save_model = False\n \n args = Args()\n \n # Load preprocessed training and testing data.\n x_train, x_test = load_data(label=args.label)\n\n # Randomly select an image as the static image from the test set.\n # idx = np.random.randint(x_test.shape[0])\n # static = tf.expand_dims(x_test[idx], axis=0)\n static = tf.expand_dims(x_test[0], axis=0)\n\n # Select some images from the test set to show sample results.\n # ids = tf.constant(np.random.choice(x_test.shape[0], replace=False,\n # size=args.num_samples))\n # x_sample = tf.gather(x_test, ids)\n x_sample = x_test[:args.num_samples]\n\n # Shuffle and batch the dataset.\n from_tensor_slices = tf.data.Dataset.from_tensor_slices\n # x_train = from_tensor_slices(x_train).shuffle(10000).batch(args.batch_size)\n # x_test = from_tensor_slices(x_test).shuffle(10000).batch(args.batch_size)\n x_train = from_tensor_slices(x_train).batch(args.batch_size)\n x_test = from_tensor_slices(x_test).batch(args.batch_size)\n\n # Create a model instance.\n model = simple_cnn(input_shape=(32, 32, 2))\n model.summary()\n tf.keras.utils.plot_model(model, show_shapes=True, dpi=50)\n\n # Select optimizer and loss function.\n optimizer = tf.keras.optimizers.SGD(learning_rate=args.lr)\n criterion = ncc_loss # normalized_cross_correlation_loss() # or mse_loss\n\n # Define the metrics to track training and testing losses.\n m_train = tf.keras.metrics.Mean(name='loss_train')\n m_test = tf.keras.metrics.Mean(name='loss_test')\n\n # Train and evaluate the model.\n for epoch in range(args.epochs):\n m_train.reset_states()\n m_test.reset_states()\n for i, moving in enumerate(x_train):\n loss_train = train_step(model, moving, static, criterion,\n optimizer)\n m_train.update_state(loss_train)\n\n for i, moving in enumerate(x_test):\n loss_test = test_step(model, moving, static, criterion)\n m_test.update_state(loss_test)\n\n print('Epoch: %3d/%d\\tTrain Loss: %.6f\\tTest Loss: %.6f'\n % (epoch + 1, args.epochs, m_train.result(), m_test.result()))\n print('\\n')\n\n # Show sample results.\n plot_images(model, x_sample, static)\n\n # Save the trained model.\n if args.save_model:\n model.save('saved_models/simple_cnn')\n\n\n" ]
[ [ "tensorflow.keras.optimizers.SGD", "tensorflow.keras.backend.image_data_format", "tensorflow.ones_like", "numpy.where", "tensorflow.keras.Model", "tensorflow.clip_by_value", "tensorflow.stack", "tensorflow.tile", "tensorflow.keras.layers.BatchNormalization", "tensorflow.cast", "tensorflow.concat", "tensorflow.GradientTape", "tensorflow.add_n", "tensorflow.keras.layers.Conv2D", "tensorflow.constant", "matplotlib.pyplot.tight_layout", "tensorflow.keras.utils.plot_model", "tensorflow.floor", "tensorflow.keras.datasets.mnist.load_data", "tensorflow.range", "tensorflow.expand_dims", "tensorflow.gather_nd", "tensorflow.keras.layers.MaxPool2D", "matplotlib.pyplot.figure", "tensorflow.keras.layers.Conv2DTranspose", "matplotlib.pyplot.show", "tensorflow.keras.metrics.Mean", "tensorflow.linspace", "tensorflow.keras.layers.Input", "tensorflow.math.reduce_std", "tensorflow.meshgrid", "tensorflow.image.resize", "tensorflow.reduce_mean", "tensorflow.square" ] ]
musicpiano/mlmicrophysics
[ "720e09b9003285e4e601df8befd58337bee691f5" ]
[ "scripts/search_ml_model_params.py" ]
[ "import numpy as np\nimport yaml\nfrom dask.distributed import Client, LocalCluster, as_completed\nimport argparse\nfrom os.path import exists, join\nfrom os import makedirs\nfrom mlmicrophysics.data import subset_data_files_by_date, assemble_data_files\nfrom sklearn.ensemble import RandomForestRegressor, RandomForestClassifier\nfrom sklearn.preprocessing import StandardScaler, RobustScaler, MaxAbsScaler, MinMaxScaler\nfrom sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error, accuracy_score\nfrom mlmicrophysics.metrics import hellinger_distance, heidke_skill_score, peirce_skill_score\nfrom sklearn.model_selection import ParameterSampler\nfrom scipy.stats import randint, uniform, expon\nimport pandas as pd\nimport traceback\n\nscalers = {\"MinMaxScaler\": MinMaxScaler,\n \"MaxAbsScaler\": MaxAbsScaler,\n \"StandardScaler\": StandardScaler,\n \"RobustScaler\": RobustScaler}\n\n\ndef sampler_generator(ps):\n for params in ps:\n yield params\n\n\ndef parse_model_config_params(model_params, num_settings, random_state):\n \"\"\"\n\n Args:\n model_params:\n num_settings:\n random_state:\n\n Returns:\n\n \"\"\"\n param_distributions = dict()\n dist_types = dict(randint=randint, expon=expon, uniform=uniform)\n for param, param_value in model_params.items():\n if param_value[0] in [\"randint\", \"expon\", \"uniform\"]:\n param_distributions[param] = dist_types[param_value[0]](*param_value[1:])\n else:\n param_distributions[param] = param_value\n return sampler_generator(ParameterSampler(param_distributions, n_iter=num_settings, random_state=random_state))\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"config\", help=\"Configuration yaml file\")\n parser.add_argument(\"-p\", \"--proc\", type=int, default=1, help=\"Number of processors\")\n args = parser.parse_args()\n if not exists(args.config):\n raise FileNotFoundError(args.config + \" not found.\")\n with open(args.config) as config_file:\n config = yaml.load(config_file)\n\n train_files, val_files, test_files = subset_data_files_by_date(config[\"data_path\"],\n config[\"data_end\"], **config[\"subset_data\"])\n input_scaler = scalers[config[\"input_scaler\"]]()\n train_input, \\\n train_output_labels, \\\n train_transformed_output, \\\n train_scaled_output, \\\n output_scalers = assemble_data_files(train_files,\n config[\"input_cols\"],\n config[\"output_cols\"],\n config[\"input_transforms\"],\n config[\"output_transforms\"],\n input_scaler,\n subsample=config[\"subsample\"])\n print(\"Train Input Size:\", train_input.shape)\n val_input, \\\n val_output_labels, \\\n val_transformed_output, \\\n val_scaled_output, \\\n output_scalers = assemble_data_files(val_files,\n config[\"input_cols\"],\n config[\"output_cols\"],\n config[\"input_transforms\"],\n config[\"output_transforms\"],\n input_scaler,\n output_scalers=output_scalers,\n train=False,\n subsample=config[\"subsample\"])\n print(\"Val Input Size:\", val_input.shape)\n cluster = LocalCluster(n_workers=args.proc, threads_per_worker=1)\n client = Client(cluster)\n print(client)\n train_input_link = client.scatter(train_input)\n train_labels_link = client.scatter(train_output_labels)\n train_scaled_output_link = client.scatter(train_scaled_output)\n val_input_link = client.scatter(val_input)\n val_output_labels_link = client.scatter(val_output_labels)\n val_scaled_output_link = client.scatter(val_scaled_output)\n submissions = []\n if not exists(config[\"out_path\"]):\n makedirs(config[\"out_path\"])\n for class_model_name, class_model_params in config[\"classifier_models\"].items():\n\n for reg_model_name, reg_model_params in config[\"regressor_models\"].items():\n rs = np.random.RandomState(config[\"random_seed\"])\n class_model_config_generator = parse_model_config_params(class_model_params,\n config[\"num_param_samples\"],\n rs)\n reg_model_config_generator = parse_model_config_params(reg_model_params,\n config[\"num_param_samples\"],\n rs)\n class_model_configs = []\n reg_model_configs = []\n for s in range(config[\"num_param_samples\"]):\n class_model_config = next(class_model_config_generator)\n reg_model_config = next(reg_model_config_generator)\n class_model_configs.append(class_model_config)\n reg_model_configs.append(reg_model_config)\n config_index = f\"{class_model_name}_{reg_model_name}_{s:04}\"\n submissions.append(client.submit(validate_model_configuration,\n class_model_name, class_model_config,\n reg_model_name, reg_model_config, config_index,\n train_input_link, train_labels_link,\n train_scaled_output_link,\n val_input_link, val_output_labels_link,\n val_scaled_output_link,\n config[\"classifier_metrics\"],\n config[\"regressor_metrics\"]))\n class_config_frame = pd.DataFrame(class_model_configs)\n reg_config_frame = pd.DataFrame(reg_model_configs)\n class_config_frame.to_csv(join(config[\"out_path\"],\n f\"{class_model_name}_{reg_model_name}_classifier_params.csv\"),\n index_label=\"Config\")\n reg_config_frame.to_csv(join(config[\"out_path\"],\n f\"{class_model_name}_{reg_model_name}_regressor_params.csv\"))\n result_count = 0\n for out in as_completed(submissions):\n if out.status == \"finished\":\n result = out.result()\n print(result)\n if result_count == 0:\n result.to_frame().T.to_csv(join(config[\"out_path\"],\n f\"{class_model_name}_{reg_model_name}_metrics.csv\"),\n index_label=\"Config\")\n else:\n result.to_frame().T.to_csv(join(config[\"out_path\"],\n f\"{class_model_name}_{reg_model_name}_metrics.csv\"),\n header=False,\n mode=\"a\")\n result_count += 1\n else:\n tb = out.traceback()\n for line in traceback.format_tb(tb):\n print(line)\n del submissions[:]\n client.close()\n cluster.close()\n return\n\n\ndef validate_model_configuration(classifier_model_name, classifier_model_config,\n regressor_model_name, regressor_model_config, config_index,\n train_scaled_input, train_labels, train_scaled_output,\n val_scaled_input, val_labels, val_scaled_output,\n classifier_metric_list, regressor_metric_list):\n \"\"\"\n Train a single machine learning model configuration to predict each microphysical tendency.\n\n Args:\n classifier_model_name:\n classifier_model_config:\n regressor_model_name:\n regressor_model_config:\n config_index:\n train_scaled_input:\n train_labels:\n train_scaled_output:\n val_scaled_input:\n val_labels:\n val_scaled_output:\n classifier_metric_list:\n regressor_metric_list:\n\n Returns:\n\n \"\"\"\n from mlmicrophysics.models import DenseNeuralNetwork, DenseGAN\n import keras.backend as K\n metrics = {\"mse\": mean_squared_error,\n \"mae\": mean_absolute_error,\n \"r2\": r2_score,\n \"hellinger\": hellinger_distance,\n \"acc\": accuracy_score,\n \"hss\": heidke_skill_score,\n \"pss\": peirce_skill_score}\n sess = K.tf.Session(config=K.tf.ConfigProto(intra_op_parallelism_threads=1, inter_op_parallelism_threads=1))\n K.set_session(sess)\n with sess.as_default():\n model_classes = {\"RandomForestRegressor\": RandomForestRegressor,\n \"RandomForestClassifier\": RandomForestClassifier,\n \"DenseNeuralNetwork\": DenseNeuralNetwork,\n \"DenseGAN\": DenseGAN}\n classifier_models = {}\n regressor_models = {}\n output_label_preds = pd.DataFrame(0, index=val_labels.index, columns=val_labels.columns,\n dtype=np.int32)\n output_preds = pd.DataFrame(0, index=val_scaled_output.index, columns=val_scaled_output.columns,\n dtype=np.float32)\n output_regressor_preds = pd.DataFrame(0, index=val_scaled_output.index, columns=val_scaled_output.columns,\n dtype=np.float32)\n output_metric_columns = []\n for output_col in train_scaled_output.columns:\n for metric in classifier_metric_list:\n output_metric_columns.append(output_col + \"_\" + metric)\n for metric in regressor_metric_list:\n output_metric_columns.append(output_col + \"_\" + metric)\n unique_labels = np.unique(train_labels[output_col])\n for unique_label in unique_labels:\n for metric in regressor_metric_list:\n output_metric_columns.append(f\"{output_col}_{unique_label}_{metric}\")\n output_metrics = pd.Series(index=output_metric_columns, name=config_index, dtype=np.float32)\n for output_col in train_scaled_output.columns:\n print(output_col)\n unique_labels = np.unique(train_labels[output_col])\n if unique_labels.size > 1:\n if classifier_model_name in [\"DenseNeuralNetwork\", \"DenseGAN\"]:\n classifier_models[output_col] = model_classes[classifier_model_name](outputs=unique_labels.size,\n classifier=True,\n **classifier_model_config)\n else:\n classifier_models[output_col] = model_classes[classifier_model_name](**classifier_model_config)\n classifier_models[output_col].fit(train_scaled_input, train_labels[output_col])\n output_label_preds.loc[:, output_col] = classifier_models[output_col].predict(val_scaled_input)\n for metric in classifier_metric_list:\n output_metrics[output_col + \"_\" + metric] = metrics[metric](val_labels[output_col].values,\n output_label_preds[output_col].values)\n else:\n output_label_preds.loc[:, output_col] = unique_labels[0]\n regressor_models[output_col] = {}\n for label in unique_labels:\n if label != 0:\n if regressor_model_name in [\"DenseNeuralNetwork\", \"DenseGAN\"]:\n regressor_models[output_col][label] = model_classes[regressor_model_name](classifier=False,\n **regressor_model_config)\n else:\n regressor_models[output_col][label] = model_classes[regressor_model_name](**regressor_model_config)\n regressor_models[output_col][label].fit(train_scaled_input.loc[train_labels[output_col] == label],\n train_scaled_output.loc[train_labels[output_col] == label,\n output_col])\n if np.count_nonzero(output_label_preds[output_col] == label) > 0:\n output_preds.loc[output_label_preds[output_col] == label,\n output_col] = regressor_models[output_col][\n label].predict(val_scaled_input.loc[output_label_preds[output_col] == label])\n output_regressor_preds.loc[val_labels[output_col] == label,\n output_col] = regressor_models[output_col][\n label].predict(val_scaled_input.loc[val_labels[output_col] == label])\n for metric in regressor_metric_list:\n output_metrics[f\"{output_col}_{label}_{metric}\"] = metrics[metric](val_scaled_output.loc[val_labels[output_col] == label, output_col].values,\n output_regressor_preds.loc[val_labels[output_col] == label, output_col].values)\n for metric in regressor_metric_list:\n output_metrics[output_col + \"_\" + metric] = metrics[metric](val_scaled_output[output_col].values,\n output_preds[output_col].values)\n return output_metrics\n\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "numpy.count_nonzero", "numpy.random.RandomState", "pandas.DataFrame", "sklearn.model_selection.ParameterSampler", "pandas.Series", "numpy.unique" ] ]
neukirchen-212/phonopy
[ "e34588dcb32fb15aa2a6604ffd3e62ebb0927c0f", "e34588dcb32fb15aa2a6604ffd3e62ebb0927c0f" ]
[ "phonopy/qha/core.py", "phonopy/phonon/thermal_properties.py" ]
[ "\"\"\"Phonopy QHA module.\"\"\"\n\n# Copyright (C) 2012 Atsushi Togo\n# All rights reserved.\n#\n# This file is part of phonopy.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n#\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in\n# the documentation and/or other materials provided with the\n# distribution.\n#\n# * Neither the name of the phonopy project nor the names of its\n# contributors may be used to endorse or promote products derived\n# from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\nimport warnings\nimport numpy as np\nfrom phonopy.units import Avogadro, EvTokJmol, EVAngstromToGPa\nfrom phonopy.qha.eos import get_eos, fit_to_eos\n\n\nclass BulkModulus(object):\n \"\"\"Bulk modulus class.\n\n This class is used to calculate bulk modulus only from temperature\n independent energy input.\n\n \"\"\"\n\n def __init__(self,\n volumes,\n energies,\n eos='vinet'):\n \"\"\"Init method.\n\n volumes : array_like\n Unit cell volumes where energies are obtained.\n shape=(volumes, ), dtype='double'.\n energies : array_like\n Energies obtained at volumes.\n shape=(volumes, ), dtype='double'.\n eos : str\n Identifier of equation of states function.\n\n \"\"\"\n self._volumes = volumes\n if np.array(energies).ndim == 1:\n self._energies = energies\n else:\n self._energies = energies[0]\n self._eos = get_eos(eos)\n\n self._energy = None\n self._bulk_modulus = None\n self._b_prime = None\n\n try:\n (self._energy,\n self._bulk_modulus,\n self._b_prime,\n self._volume) = fit_to_eos(volumes,\n self._energies,\n self._eos)\n except TypeError:\n msg = [\"Failed to fit to \\\"%s\\\" equation of states.\" % eos]\n if len(volumes) < 4:\n msg += [\"At least 4 volume points are needed for the fitting.\"]\n msg += [\"Careful choice of volume points is recommended.\"]\n raise RuntimeError(\"\\n\".join(msg))\n\n @property\n def bulk_modulus(self):\n \"\"\"Return bulk modulus.\"\"\"\n return self._bulk_modulus\n\n def get_bulk_modulus(self):\n \"\"\"Return bulk modulus.\"\"\"\n warnings.warn(\"BulkModulus.get_bulk_modulus() is deprecated.\"\n \"Use BulkModulus.bulk_modulus attribute.\",\n DeprecationWarning)\n return self.bulk_modulus\n\n @property\n def equilibrium_volume(self):\n \"\"\"Return volume at equilibrium.\"\"\"\n return self._volume\n\n def get_equilibrium_volume(self):\n \"\"\"Return volume at equilibrium.\"\"\"\n warnings.warn(\"BulkModulus.get_equilibrium_volume() is deprecated.\"\n \"Use BulkModulus.equilibrium_volume attribute.\",\n DeprecationWarning)\n return self.equilibrium_volume\n\n @property\n def b_prime(self):\n \"\"\"Return fitted parameter B'.\"\"\"\n return self._b_prime\n\n def get_b_prime(self):\n \"\"\"Return fitted parameter B'.\"\"\"\n warnings.warn(\"BulkModulus.get_b_prime() is deprecated.\"\n \"Use BulkModulus.b_prime attribute.\",\n DeprecationWarning)\n return self._b_prime\n\n @property\n def energy(self):\n \"\"\"Return fitted parameter of energy.\"\"\"\n return self._energy\n\n def get_energy(self):\n \"\"\"Return fitted parameter of energy.\"\"\"\n warnings.warn(\"BulkModulus.get_energy() is deprecated.\"\n \"Use BulkModulus.energy attribute.\",\n DeprecationWarning)\n return self._energy\n\n def get_parameters(self):\n \"\"\"Return fitted parameters.\"\"\"\n return (self._energy,\n self._bulk_modulus,\n self._b_prime,\n self._volume)\n\n def get_eos(self):\n \"\"\"Return EOS function as a python method.\"\"\"\n warnings.warn(\"BulkModulus.get_eos() is deprecated.\",\n DeprecationWarning)\n return self._eos\n\n def plot(self):\n \"\"\"Plot fitted EOS curve.\"\"\"\n import matplotlib.pyplot as plt\n ep = self.get_parameters()\n vols = self._volumes\n volume_points = np.linspace(min(vols), max(vols), 201)\n fig, ax = plt.subplots()\n ax.plot(volume_points, self._eos(volume_points, *ep), 'r-')\n ax.plot(vols, self._energies, 'bo', markersize=4)\n return plt\n\n\nclass QHA(object):\n \"\"\"Quasi harmonic approximation class.\"\"\"\n\n def __init__(self,\n volumes, # angstrom^3\n electronic_energies, # eV\n temperatures, # K\n cv, # J/K/mol\n entropy, # J/K/mol\n fe_phonon, # kJ/mol\n eos='vinet',\n t_max=None,\n energy_plot_factor=None):\n \"\"\"Init method.\n\n Parameters\n ----------\n volumes: array_like\n Unit cell volumes (V) in angstrom^3.\n dtype='double'\n shape=(volumes,)\n electronic_energies: array_like\n Electronic energies (U_el) or electronic free energies (F_el) in eV.\n It is assumed as formar if ndim==1 and latter if ndim==2.\n dtype='double'\n shape=(volumes,) or (temperatuers, volumes)\n temperatures: array_like\n Temperatures ascending order (T) in K.\n dtype='double'\n shape=(temperatures,)\n cv: array_like\n Phonon Heat capacity at constant volume in J/K/mol.\n dtype='double'\n shape=(temperatuers, volumes)\n entropy: array_like\n Phonon entropy at constant volume (S_ph) in J/K/mol.\n dtype='double'\n shape=(temperatuers, volumes)\n fe_phonon: array_like\n Phonon Helmholtz free energy (F_ph) in kJ/mol.\n dtype='double'\n shape=(temperatuers, volumes)\n eos: str\n Equation of state used for fitting F vs V.\n 'vinet', 'murnaghan' or 'birch_murnaghan'.\n t_max: float\n Maximum temperature to be calculated. This has to be not\n greater than the temperature of the third element from the\n end of 'temperatre' elements. If max_t=None, the temperature\n of the third element from the end is used.\n energy_plot_factor: float\n This value is multiplied to energy like values only in plotting.\n\n \"\"\"\n self._volumes = np.array(volumes)\n self._electronic_energies = np.array(electronic_energies)\n\n self._all_temperatures = np.array(temperatures)\n self._cv = np.array(cv)\n self._entropy = np.array(entropy)\n self._fe_phonon = np.array(fe_phonon) / EvTokJmol\n\n self._eos = get_eos(eos)\n self._t_max = t_max\n self._energy_plot_factor = energy_plot_factor\n\n self._temperatures = None\n self._equiv_volumes = None\n self._equiv_energies = None\n self._equiv_bulk_modulus = None\n self._equiv_parameters = None\n self._free_energies = None\n self._num_elems = None\n\n self._thermal_expansions = None\n self._cp_numerical = None\n self._volume_entropy_parameters = None\n self._volume_cv_parameters = None\n self._volume_entropy = None\n self._volume_cv = None\n self._cp_polyfit = None\n self._dsdv = None\n self._gruneisen_parameters = None\n self._len = None\n\n @property\n def thermal_expansion(self):\n \"\"\"Return volumetric thermal expansion coefficients at temperatures.\"\"\"\n return self._thermal_expansions[:self._len]\n\n @property\n def helmholtz_volume(self):\n \"\"\"Return Helmholtz free energies at temperatures and volumes.\"\"\"\n return self._free_energies[:self._len]\n\n @property\n def volume_temperature(self):\n \"\"\"Return equilibrium volumes at temperatures.\"\"\"\n return self._equiv_volumes[:self._len]\n\n @property\n def gibbs_temperature(self):\n \"\"\"Return Gibbs free energies at temperatures.\"\"\"\n return self._equiv_energies[:self._len]\n\n @property\n def bulk_modulus_temperature(self):\n \"\"\"Return bulk modulus vs temperature data.\"\"\"\n return self._equiv_bulk_modulus[:self._len]\n\n @property\n def heat_capacity_P_numerical(self):\n \"\"\"Return heat capacities at constant pressure at temperatures.\n\n Values are computed by numerical derivative of Gibbs free energy.\n\n \"\"\"\n return self._cp_numerical[:self._len]\n\n @property\n def heat_capacity_P_polyfit(self):\n \"\"\"Return heat capacities at constant pressure at temperatures.\n\n Volumes are computed in another way to heat_capacity_P_numerical\n for the better numerical behaviour. But this does not work\n when temperature dependent electronic_energies is supplied.\n\n \"\"\"\n if self._electronic_energies.ndim == 1:\n return self._cp_polyfit[:self._len]\n else:\n return None\n\n @property\n def gruneisen_temperature(self):\n \"\"\"Return Gruneisen parameters at temperatures.\"\"\"\n return self._gruneisen_parameters[:self._len]\n\n def run(self, verbose=False):\n \"\"\"Fit parameters to EOS at temperatures.\n\n Even if fitting failed, simply omit the volume point. In this case,\n the failed temperature point doesn't exist in the returned arrays.\n\n \"\"\"\n if verbose:\n print((\"#%11s\" + \"%14s\" * 4) % (\"T\", \"E_0\", \"B_0\", \"B'_0\", \"V_0\"))\n\n # Plus one temperature point is necessary for computing e.g. beta.\n num_elems = self._get_num_elems(self._all_temperatures) + 1\n if num_elems > len(self._all_temperatures):\n num_elems -= 1\n\n temperatures = []\n parameters = []\n free_energies = []\n\n for i in range(num_elems): # loop over temperaturs\n if self._electronic_energies.ndim == 1:\n el_energy = self._electronic_energies\n else:\n el_energy = self._electronic_energies[i]\n fe = [ph_e + el_e\n for ph_e, el_e in zip(self._fe_phonon[i], el_energy)]\n\n try:\n ep = fit_to_eos(self._volumes, fe, self._eos)\n except TypeError:\n print(\"Fitting failure at T=%.1f\" % self._all_temperatures[i])\n\n if ep is None:\n # Simply omit volume point where the fitting failed.\n continue\n else:\n [ee, eb, ebp, ev] = ep\n t = self._all_temperatures[i]\n temperatures.append(t)\n parameters.append(ep)\n free_energies.append(fe)\n\n if verbose:\n print((\"%14.6f\" * 5) %\n (t, ep[0], ep[1] * EVAngstromToGPa, ep[2], ep[3]))\n\n self._free_energies = np.array(free_energies)\n self._temperatures = np.array(temperatures)\n self._equiv_parameters = np.array(parameters)\n self._equiv_volumes = np.array(self._equiv_parameters[:, 3])\n self._equiv_energies = np.array(self._equiv_parameters[:, 0])\n self._equiv_bulk_modulus = np.array(\n self._equiv_parameters[:, 1] * EVAngstromToGPa)\n\n self._num_elems = len(self._temperatures)\n\n # For computing following values at temperatures, finite difference\n # method is used. Therefore number of temperature points are needed\n # larger than self._num_elems that nearly equals to the temparature\n # point we expect.\n self._set_thermal_expansion()\n self._set_heat_capacity_P_numerical()\n self._set_heat_capacity_P_polyfit()\n self._set_gruneisen_parameter() # To be run after thermal expansion.\n\n self._len = len(self._thermal_expansions)\n assert(self._len + 1 == self._num_elems)\n\n def plot(self, thin_number=10, volume_temp_exp=None):\n import matplotlib.pyplot as plt\n\n plt.rcParams['pdf.fonttype'] = 42\n plt.rcParams['font.family'] = 'serif'\n plt.rcParams['text.usetex'] = True\n\n fig, axs = plt.subplots(1, 3, figsize=(7, 3.5))\n axs[0].xaxis.set_ticks_position('both')\n axs[0].yaxis.set_ticks_position('both')\n axs[0].xaxis.set_tick_params(which='both', direction='in')\n axs[0].yaxis.set_tick_params(which='both', direction='in')\n self._plot_helmholtz_volume(axs[0], thin_number=thin_number)\n axs[1].xaxis.set_ticks_position('both')\n axs[1].yaxis.set_ticks_position('both')\n axs[1].xaxis.set_tick_params(which='both', direction='in')\n axs[1].yaxis.set_tick_params(which='both', direction='in')\n self._plot_volume_temperature(axs[1], exp_data=volume_temp_exp)\n axs[2].xaxis.set_ticks_position('both')\n axs[2].yaxis.set_ticks_position('both')\n axs[2].xaxis.set_tick_params(which='both', direction='in')\n axs[2].yaxis.set_tick_params(which='both', direction='in')\n self._plot_thermal_expansion(axs[2])\n plt.tight_layout()\n return plt\n\n def get_helmholtz_volume(self):\n warnings.warn(\"QHA.get_helmholtz_volume() is deprecated.\"\n \"Use helmholtz_volume attribute.\",\n DeprecationWarning)\n return self.helmholtz_volume\n\n def plot_helmholtz_volume(self,\n thin_number=10,\n xlabel=r'Volume $(\\AA^3)$',\n ylabel='Free energy'):\n import matplotlib.pyplot as plt\n\n fig, ax = plt.subplots()\n self._plot_helmholtz_volume(ax,\n thin_number=thin_number,\n xlabel=xlabel,\n ylabel=ylabel)\n return plt\n\n def plot_pdf_helmholtz_volume(self,\n thin_number=10,\n filename='helmholtz-volume.pdf'):\n import matplotlib.pyplot as plt\n\n self._set_rcParams(plt)\n\n fig, ax = plt.subplots()\n ax.xaxis.set_ticks_position('both')\n ax.yaxis.set_ticks_position('both')\n ax.xaxis.set_tick_params(which='both', direction='in')\n ax.yaxis.set_tick_params(which='both', direction='in')\n\n self._plot_helmholtz_volume(ax, thin_number=thin_number)\n plt.savefig(filename)\n plt.close()\n\n def write_helmholtz_volume(self, filename='helmholtz-volume.dat'):\n w = open(filename, 'w')\n for i, (t, ep, fe) in enumerate(zip(self._temperatures,\n self._equiv_parameters,\n self._free_energies)):\n if i == self._len:\n break\n\n w.write(\"# Temperature: %f\\n\" % t)\n w.write(\"# Parameters: %f %f %f %f\\n\" % tuple(ep))\n for j, v in enumerate(self._volumes):\n w.write(\"%20.15f %25.15f\\n\" % (v, fe[j]))\n w.write(\"\\n\\n\")\n w.close()\n\n def write_helmholtz_volume_fitted(self,\n thin_number,\n filename='helholtz-volume_fitted.dat'):\n\n if self._energy_plot_factor is None:\n _energy_plot_factor = 1\n else:\n _energy_plot_factor = self._energy_plot_factor\n\n volume_points = np.linspace(\n min(self._volumes), max(self._volumes), 201)\n selected_volumes = []\n selected_energies = []\n\n for i, t in enumerate(self._temperatures[:self._len]):\n if i % thin_number == 0:\n selected_volumes.append(self._equiv_volumes[i])\n selected_energies.append(self._equiv_energies[i])\n\n for i, t in enumerate(self._temperatures[:self._len]):\n if t >= 298:\n if i > 0:\n de = self._equiv_energies[i] - self._equiv_energies[i - 1]\n dt = t - self._temperatures[i - 1]\n e0 = ((298 - self._temperatures[i - 1]) / dt * de +\n self._equiv_energies[i - 1])\n else:\n e0 = 0\n break\n e0 *= _energy_plot_factor\n _data_vol_points = []\n _data_eos = []\n for i, t in enumerate(self._temperatures[:self._len]):\n if i % thin_number == 0:\n\n _data_vol_points.append(\n np.array(self._free_energies[i]) * _energy_plot_factor - e0)\n _data_eos.append(\n self._eos(volume_points, * self._equiv_parameters[i])\n * _energy_plot_factor - e0)\n\n data_eos = np.array(_data_eos).T\n data_vol_points = np.array(_data_vol_points).T\n data_min = (np.array(selected_energies) * _energy_plot_factor - e0)\n\n with open(filename, 'w') as w:\n w.write(\"# Volume points\\n\")\n for (j, k) in zip(self._volumes, data_vol_points):\n w.write(\"%10.5f \" % j)\n for l in k:\n w.write(\"%10.5f\" % l)\n w.write(\"\\n\")\n w.write(\"\\n# Fitted data\\n\")\n\n for (m, n) in zip(volume_points, data_eos):\n w.write(\"%10.5f \" % m)\n for ll in n:\n w.write(\"%10.5f\" % ll)\n w.write(\"\\n\")\n w.write(\"\\n# Minimas\\n\")\n for (a, b) in zip(selected_volumes, data_min):\n w.write(\"%10.5f %10.5f %s\" % (a, b, '\\n'))\n w.write('\\n')\n\n def get_volume_temperature(self):\n warnings.warn(\"QHA.get_volume_temperature() is deprecated.\"\n \"Use volume_temperature attribute.\",\n DeprecationWarning)\n return self.volume_temperature\n\n def plot_volume_temperature(self, exp_data=None):\n import matplotlib.pyplot as plt\n\n fig, ax = plt.subplots()\n self._plot_volume_temperature(ax, exp_data=exp_data)\n\n return plt\n\n def plot_pdf_volume_temperature(self,\n exp_data=None,\n filename='volume-temperature.pdf'):\n import matplotlib.pyplot as plt\n\n self._set_rcParams(plt)\n\n fig, ax = plt.subplots()\n ax.xaxis.set_ticks_position('both')\n ax.yaxis.set_ticks_position('both')\n ax.xaxis.set_tick_params(which='both', direction='in')\n ax.yaxis.set_tick_params(which='both', direction='in')\n\n self._plot_volume_temperature(ax, exp_data=exp_data)\n plt.savefig(filename)\n plt.close()\n\n def write_volume_temperature(self, filename='volume-temperature.dat'):\n w = open(filename, 'w')\n for i in range(self._len):\n w.write(\"%25.15f %25.15f\\n\" % (self._temperatures[i],\n self._equiv_volumes[i]))\n w.close()\n\n def get_thermal_expansion(self):\n warnings.warn(\"QHA.get_thermal_expansion() is deprecated.\"\n \"Use thermal_expansion attribute.\",\n DeprecationWarning)\n return self.thermal_expansion\n\n def plot_thermal_expansion(self):\n import matplotlib.pyplot as plt\n\n fig, ax = plt.subplots()\n self._plot_thermal_expansion(ax)\n\n return plt\n\n def plot_pdf_thermal_expansion(self, filename='thermal_expansion.pdf'):\n import matplotlib.pyplot as plt\n\n self._set_rcParams(plt)\n\n fig, ax = plt.subplots()\n ax.xaxis.set_ticks_position('both')\n ax.yaxis.set_ticks_position('both')\n ax.xaxis.set_tick_params(which='both', direction='in')\n ax.yaxis.set_tick_params(which='both', direction='in')\n\n self._plot_thermal_expansion(ax)\n plt.savefig(filename)\n plt.close()\n\n def write_thermal_expansion(self, filename='thermal_expansion.dat'):\n w = open(filename, 'w')\n for i in range(self._len):\n w.write(\"%25.15f %25.15f\\n\" % (self._temperatures[i],\n self._thermal_expansions[i]))\n w.close()\n\n def get_gibbs_temperature(self):\n return self.gibbs_temperature\n\n def plot_gibbs_temperature(self,\n xlabel='Temperature (K)',\n ylabel='Gibbs free energy'):\n import matplotlib.pyplot as plt\n\n fig, ax = plt.subplots()\n self._plot_gibbs_temperature(ax, xlabel=xlabel, ylabel=ylabel)\n\n return plt\n\n def plot_pdf_gibbs_temperature(self, filename='gibbs-temperature.pdf'):\n import matplotlib.pyplot as plt\n\n self._set_rcParams(plt)\n\n fig, ax = plt.subplots()\n ax.xaxis.set_ticks_position('both')\n ax.yaxis.set_ticks_position('both')\n ax.xaxis.set_tick_params(which='both', direction='in')\n ax.yaxis.set_tick_params(which='both', direction='in')\n\n self._plot_gibbs_temperature(ax)\n plt.savefig(filename)\n plt.close()\n\n def write_gibbs_temperature(self, filename='gibbs-temperature.dat'):\n w = open(filename, 'w')\n for i in range(self._len):\n w.write(\"%20.15f %25.15f\\n\" % (self._temperatures[i],\n self._equiv_energies[i]))\n w.close()\n\n def get_bulk_modulus_temperature(self):\n return self.bulk_modulus_temperature\n\n def plot_bulk_modulus_temperature(self,\n xlabel='Temperature (K)',\n ylabel='Bulk modulus'):\n import matplotlib.pyplot as plt\n\n fig, ax = plt.subplots()\n self._plot_bulk_modulus_temperature(ax,\n xlabel=xlabel,\n ylabel=ylabel)\n return plt\n\n def plot_pdf_bulk_modulus_temperature(\n self,\n filename='bulk_modulus-temperature.pdf'):\n import matplotlib.pyplot as plt\n\n self._set_rcParams(plt)\n\n fig, ax = plt.subplots()\n ax.xaxis.set_ticks_position('both')\n ax.yaxis.set_ticks_position('both')\n ax.xaxis.set_tick_params(which='both', direction='in')\n ax.yaxis.set_tick_params(which='both', direction='in')\n\n self._plot_bulk_modulus_temperature(ax)\n plt.savefig(filename)\n plt.close()\n\n def write_bulk_modulus_temperature(\n self,\n filename='bulk_modulus-temperature.dat'):\n w = open(filename, 'w')\n for i in range(self._len):\n w.write(\"%20.15f %25.15f\\n\" % (self._temperatures[i],\n self._equiv_bulk_modulus[i]))\n w.close()\n\n def get_heat_capacity_P_numerical(self):\n return self.heat_capacity_P_numerical\n\n def plot_heat_capacity_P_numerical(self, Z=1, exp_data=None):\n import matplotlib.pyplot as plt\n\n fig, ax = plt.subplots()\n self._plot_heat_capacity_P_numerical(ax, Z=Z, exp_data=exp_data)\n\n return plt\n\n def plot_pdf_heat_capacity_P_numerical(self,\n exp_data=None,\n filename='Cp-temperature.pdf'):\n import matplotlib.pyplot as plt\n\n self._set_rcParams(plt)\n\n fig, ax = plt.subplots()\n ax.xaxis.set_ticks_position('both')\n ax.yaxis.set_ticks_position('both')\n ax.xaxis.set_tick_params(which='both', direction='in')\n ax.yaxis.set_tick_params(which='both', direction='in')\n\n self._plot_heat_capacity_P_numerical(ax, exp_data=exp_data)\n plt.savefig(filename)\n plt.close()\n\n def write_heat_capacity_P_numerical(self, filename='Cp-temperature.dat'):\n w = open(filename, 'w')\n for i in range(self._len):\n w.write(\"%20.15f %20.15f\\n\" % (self._temperatures[i],\n self._cp_numerical[i]))\n w.close()\n\n def get_heat_capacity_P_polyfit(self):\n return self.heat_capacity_P_polyfit\n\n def plot_heat_capacity_P_polyfit(self, Z=1, exp_data=None):\n import matplotlib.pyplot as plt\n\n fig, ax = plt.subplots()\n self._plot_heat_capacity_P_polyfit(ax, Z=Z, exp_data=exp_data)\n\n return plt\n\n def plot_pdf_heat_capacity_P_polyfit(\n self,\n exp_data=None,\n filename='Cp-temperature_polyfit.pdf'):\n import matplotlib.pyplot as plt\n\n self._set_rcParams(plt)\n\n fig, ax = plt.subplots()\n ax.xaxis.set_ticks_position('both')\n ax.yaxis.set_ticks_position('both')\n ax.xaxis.set_tick_params(which='both', direction='in')\n ax.yaxis.set_tick_params(which='both', direction='in')\n\n self._plot_heat_capacity_P_polyfit(ax, exp_data=exp_data)\n plt.savefig(filename)\n plt.close()\n\n def write_heat_capacity_P_polyfit(self,\n filename='Cp-temperature_polyfit.dat',\n filename_ev='entropy-volume.dat',\n filename_cvv='Cv-volume.dat',\n filename_dsdvt='dsdv-temperature.dat'):\n wve = open(filename_ev, 'w')\n wvcv = open(filename_cvv, 'w')\n for i in range(1, self._len):\n t = self._temperatures[i]\n wve.write(\"# temperature %20.15f\\n\" % t)\n wve.write(\"# %20.15f %20.15f %20.15f %20.15f %20.15f\\n\" %\n tuple(self._volume_entropy_parameters[i - 1]))\n wvcv.write(\"# temperature %20.15f\\n\" % t)\n wvcv.write(\"# %20.15f %20.15f %20.15f %20.15f %20.15f\\n\" %\n tuple(self._volume_cv_parameters[i - 1]))\n for ve, vcv in zip(self._volume_entropy[i - 1],\n self._volume_cv[i - 1]):\n wve.write(\"%20.15f %20.15f\\n\" % tuple(ve))\n wvcv.write(\"%20.15f %20.15f\\n\" % tuple(vcv))\n wve.write(\"\\n\\n\")\n wvcv.write(\"\\n\\n\")\n wve.close()\n wvcv.close()\n\n w = open(filename, 'w')\n for i in range(self._len):\n w.write(\"%20.15f %20.15f\\n\" % (self._temperatures[i],\n self._cp_polyfit[i]))\n w.close()\n\n w = open(filename_dsdvt, 'w') # GPa\n for i in range(self._len):\n w.write(\"%20.15f %20.15f\\n\" % (self._temperatures[i],\n self._dsdv[i] * 1e21 / Avogadro))\n w.close()\n\n def get_gruneisen_temperature(self):\n return self.gruneisen_temperature\n\n def plot_gruneisen_temperature(self):\n import matplotlib.pyplot as plt\n\n fig, ax = plt.subplots()\n self._plot_gruneisen_temperature(ax)\n\n return plt\n\n def plot_pdf_gruneisen_temperature(self,\n filename='gruneisen-temperature.pdf'):\n import matplotlib.pyplot as plt\n\n self._set_rcParams(plt)\n\n fig, ax = plt.subplots()\n ax.xaxis.set_ticks_position('both')\n ax.yaxis.set_ticks_position('both')\n ax.xaxis.set_tick_params(which='both', direction='in')\n ax.yaxis.set_tick_params(which='both', direction='in')\n\n self._plot_gruneisen_temperature(ax)\n plt.savefig(filename)\n plt.close()\n\n def write_gruneisen_temperature(self,\n filename='gruneisen-temperature.dat'):\n w = open(filename, 'w')\n for i in range(self._len):\n w.write(\"%20.15f %25.15f\\n\" % (self._temperatures[i],\n self._gruneisen_parameters[i]))\n w.close()\n\n def _plot_helmholtz_volume(self,\n ax,\n thin_number=10,\n xlabel=r'Volume $(\\AA^3)$',\n ylabel='Free energy'):\n if self._energy_plot_factor is None:\n _energy_plot_factor = 1\n _ylabel = ylabel + ' (eV)'\n else:\n _energy_plot_factor = self._energy_plot_factor\n _ylabel = ylabel\n\n volume_points = np.linspace(min(self._volumes),\n max(self._volumes),\n 201)\n selected_volumes = []\n selected_energies = []\n\n thin_index = 0\n for i, t in enumerate(self._temperatures[:self._len]):\n if i % thin_number == 0:\n selected_volumes.append(self._equiv_volumes[i])\n selected_energies.append(self._equiv_energies[i])\n\n for i, t in enumerate(self._temperatures[:self._len]):\n if t >= 298:\n if i > 0:\n de = self._equiv_energies[i] - self._equiv_energies[i - 1]\n dt = t - self._temperatures[i - 1]\n e0 = ((298 - self._temperatures[i - 1]) / dt * de +\n self._equiv_energies[i - 1])\n else:\n e0 = 0\n break\n e0 *= _energy_plot_factor\n\n for i, t in enumerate(self._temperatures[:self._len]):\n if i % thin_number == 0:\n ax.plot(self._volumes,\n np.array(self._free_energies[i]) * _energy_plot_factor\n - e0,\n 'bo', markeredgecolor='b', markersize=3)\n ax.plot(volume_points,\n self._eos(volume_points, * self._equiv_parameters[i])\n * _energy_plot_factor - e0, 'b-')\n thin_index = i\n\n for i, j in enumerate((0, thin_index)):\n ax.text(self._volumes[-2],\n (self._free_energies[j, -1] + (1 - i * 2) * 0.1 - 0.05) *\n _energy_plot_factor - e0,\n \"%dK\" % int(self._temperatures[j]),\n fontsize=8)\n\n ax.plot(selected_volumes,\n np.array(selected_energies) * _energy_plot_factor - e0,\n 'ro-', markeredgecolor='r', markersize=3)\n ax.set_xlabel(xlabel)\n ax.set_ylabel(_ylabel)\n\n def _plot_volume_temperature(self,\n ax,\n exp_data=None,\n xlabel='Temperature (K)',\n ylabel=r'Volume $(\\AA^3)$'):\n ax.set_xlabel(xlabel)\n ax.set_ylabel(ylabel)\n ax.plot(self._temperatures[:self._len],\n self._equiv_volumes[:self._len],\n 'r-')\n ax.set_xlim(self._temperatures[0],\n self._temperatures[self._len - 1])\n # exp\n if exp_data:\n ax.plot(exp_data[0], exp_data[1], 'ro')\n\n def _plot_thermal_expansion(\n self,\n ax,\n xlabel='Temperature (K)',\n ylabel=r'Thermal expansion $(\\mathrm{K}^{-1})$'):\n from matplotlib.ticker import ScalarFormatter\n\n class FixedScaledFormatter(ScalarFormatter):\n def __init__(self):\n ScalarFormatter.__init__(self, useMathText=True)\n\n def _set_orderOfMagnitude(self, range):\n self.orderOfMagnitude = -6\n\n ax.yaxis.set_major_formatter(FixedScaledFormatter())\n ax.ticklabel_format(style=\"sci\", axis=\"y\", scilimits=(0, 0))\n\n beta = np.array(self._thermal_expansions)\n ax.plot(self._temperatures[:self._len],\n beta[:self._len],\n 'r-')\n ax.set_xlim(self._temperatures[0],\n self._temperatures[self._len - 1])\n ax.set_xlabel(xlabel)\n ax.set_ylabel(ylabel)\n\n def _plot_gibbs_temperature(self,\n ax,\n xlabel='Temperature (K)',\n ylabel='Gibbs free energy (eV)'):\n ax.set_xlabel(xlabel)\n ax.set_ylabel(ylabel)\n ax.plot(self._temperatures[:self._len],\n self._equiv_energies[:self._len],\n 'r-')\n ax.set_xlim(self._temperatures[0],\n self._temperatures[self._len - 1])\n\n def _plot_bulk_modulus_temperature(self,\n ax,\n xlabel='Temperature (K)',\n ylabel='Bulk modulus (GPa)'):\n ax.set_xlabel(xlabel)\n ax.set_ylabel(ylabel)\n ax.plot(self._temperatures[:self._len],\n self._equiv_bulk_modulus[:self._len],\n 'r-')\n ax.set_xlim(self._temperatures[0],\n self._temperatures[self._len - 1])\n\n def _plot_heat_capacity_P_numerical(\n self,\n ax,\n Z=1,\n exp_data=None,\n xlabel='Temperature (K)',\n ylabel=r'$C\\mathrm{_P}$ $\\mathrm{(J/mol\\cdot K)}$'):\n ax.set_xlabel(xlabel)\n ax.set_ylabel(ylabel)\n ax.plot(self._temperatures[:self._len],\n np.array(self._cp_numerical[:self._len]) / Z,\n 'r-')\n\n # exp\n if exp_data:\n ax.plot(exp_data[0], exp_data[1], 'ro')\n\n ax.set_xlim(self._temperatures[0],\n self._temperatures[self._len - 1])\n\n def _plot_heat_capacity_P_polyfit(\n self,\n ax,\n Z=1,\n exp_data=None,\n xlabel='Temperature (K)',\n ylabel=r'$C\\mathrm{_P}$ $\\mathrm{(J/mol\\cdot K)}$'):\n ax.set_xlabel(xlabel)\n ax.set_ylabel(ylabel)\n ax.plot(self._temperatures[:self._len],\n np.array(self._cp_polyfit[:self._len]) / Z,\n 'r-')\n\n # exp\n if exp_data:\n ax.plot(exp_data[0], exp_data[1], 'ro')\n\n ax.set_xlim(self._temperatures[0],\n self._temperatures[self._len - 1])\n\n def _plot_gruneisen_temperature(self,\n ax,\n xlabel='Temperature (K)',\n ylabel='Gruneisen parameter'):\n ax.set_xlabel(xlabel)\n ax.set_ylabel(ylabel)\n ax.plot(self._temperatures[:self._len],\n self._gruneisen_parameters[:self._len],\n 'r-')\n ax.set_xlim(self._temperatures[0],\n self._temperatures[self._len - 1])\n\n def _set_thermal_expansion(self):\n beta = [0.]\n for i in range(1, self._num_elems - 1):\n dt = self._temperatures[i + 1] - self._temperatures[i - 1]\n dv = self._equiv_volumes[i + 1] - self._equiv_volumes[i - 1]\n beta.append(dv / dt / self._equiv_volumes[i])\n\n self._thermal_expansions = beta\n\n def _set_heat_capacity_P_numerical(self):\n cp = []\n g = np.array(self._equiv_energies) * EvTokJmol * 1000\n cp.append(0.0)\n\n for i in range(1, self._num_elems - 1):\n t = self._temperatures[i]\n parameters = np.polyfit(self._temperatures[i - 1:i + 2],\n g[i - 1: i + 2], 2)\n cp.append(- (2 * parameters[0]) * t)\n\n self._cp_numerical = cp\n\n def _set_heat_capacity_P_polyfit(self):\n cp = [0.0]\n dsdv = [0.0]\n self._volume_entropy_parameters = []\n self._volume_cv_parameters = []\n self._volume_entropy = []\n self._volume_cv = []\n\n for j in range(1, self._num_elems - 1):\n t = self._temperatures[j]\n x = self._equiv_volumes[j]\n\n try:\n parameters = np.polyfit(self._volumes, self._cv[j], 4)\n except np.lib.polynomial.RankWarning:\n msg = [\n \"Failed to fit heat capacities to polynomial of degree 4.\"]\n if len(self._volumes) < 5:\n msg += [\n \"At least 5 volume points are needed for the fitting.\"]\n raise RuntimeError(\"\\n\".join(msg))\n\n cv_p = np.dot(parameters, np.array([x**4, x**3, x**2, x, 1]))\n self._volume_cv_parameters.append(parameters)\n\n try:\n parameters = np.polyfit(self._volumes, self._entropy[j], 4)\n except np.lib.polynomial.RankWarning:\n msg = [\n \"Failed to fit entropies to polynomial of degree 4.\"]\n if len(self._volumes) < 5:\n msg += [\n \"At least 5 volume points are needed for the fitting.\"]\n raise RuntimeError(\"\\n\".join(msg))\n\n dsdv_t = np.dot(parameters[:4], np.array(\n [4 * x**3, 3 * x**2, 2 * x, 1]))\n self._volume_entropy_parameters.append(parameters)\n\n try:\n parameters = np.polyfit(self._temperatures[j - 1:j + 2],\n self._equiv_volumes[j - 1: j + 2], 2)\n except np.lib.polynomial.RankWarning:\n msg = (\"Failed to fit equilibrium volumes vs T to \"\n \"polynomial of degree 2.\")\n raise RuntimeError(msg)\n dvdt = parameters[0] * 2 * t + parameters[1]\n\n cp.append(cv_p + t * dvdt * dsdv_t)\n dsdv.append(dsdv_t)\n\n self._volume_cv.append(np.array([self._volumes, self._cv[j]]).T)\n self._volume_entropy.append(np.array([self._volumes,\n self._entropy[j]]).T)\n\n self._cp_polyfit = cp\n self._dsdv = dsdv\n\n def _set_gruneisen_parameter(self):\n gamma = [0]\n for i in range(1, self._num_elems - 1):\n v = self._equiv_volumes[i]\n kt = self._equiv_bulk_modulus[i]\n beta = self._thermal_expansions[i]\n try:\n parameters = np.polyfit(self._volumes, self._cv[i], 4)\n except np.lib.polynomial.RankWarning:\n msg = [\n \"Failed to fit heat capacities to polynomial of degree 4.\"]\n if len(self._volumes) < 5:\n msg += [\n \"At least 5 volume points are needed for the fitting.\"]\n raise RuntimeError(\"\\n\".join(msg))\n cv = (np.dot(parameters, [v**4, v**3, v**2, v, 1]) /\n v / 1000 / EvTokJmol * EVAngstromToGPa)\n if cv < 1e-10:\n gamma.append(0.0)\n else:\n gamma.append(beta * kt / cv)\n self._gruneisen_parameters = gamma\n\n def _get_num_elems(self, temperatures):\n if self._t_max is None:\n return len(temperatures)\n else:\n i = np.argmin(np.abs(temperatures - self._t_max))\n return i + 1\n\n def _set_rcParams(self, plt):\n plt.rcParams['backend'] = 'PDF'\n plt.rcParams['pdf.fonttype'] = 42\n plt.rcParams['font.family'] = 'serif'\n plt.rcParams['axes.labelsize'] = 18\n plt.rcParams['figure.subplot.left'] = 0.25\n plt.rcParams['figure.subplot.bottom'] = 0.15\n plt.rcParams['figure.figsize'] = 4, 6\n plt.rcParams['text.usetex'] = True\n", "\"\"\"Phonon thermal properties at constant volume.\"\"\"\n# Copyright (C) 2011 Atsushi Togo\n# All rights reserved.\n#\n# This file is part of phonopy.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n#\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in\n# the documentation and/or other materials provided with the\n# distribution.\n#\n# * Neither the name of the phonopy project nor the names of its\n# contributors may be used to endorse or promote products derived\n# from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\nimport warnings\nimport numpy as np\nfrom phonopy.units import Kb, THz, THzToEv, EvTokJmol\n\n\ndef mode_cv(temp, freqs): # freqs (eV)\n \"\"\"Return mode heat capacity.\n\n Parameters\n ----------\n temp : float\n Temperature in K.\n freqs : float or ndarray\n Phonon frequency in eV.\n\n Returns\n -------\n float or ndarray\n Mode heat capacity in eV/K.\n\n \"\"\"\n x = freqs / Kb / temp\n expVal = np.exp(x)\n return Kb * x ** 2 * expVal / (expVal - 1.0) ** 2\n\n\ndef mode_F(temp, freqs):\n \"\"\"Return mode Helmholtz free energy.\n\n Parameters\n ----------\n temp : float\n Temperature in K.\n freqs : float or ndarray\n Phonon frequency in eV.\n\n Returns\n -------\n float or ndarray\n Mode Helmholtz free energy in eV.\n\n \"\"\"\n return (Kb * temp * np.log(1.0 - np.exp((- freqs) / (Kb * temp)))\n + freqs / 2)\n\n\ndef mode_S(temp, freqs):\n \"\"\"Return mode entropy.\n\n Parameters\n ----------\n temp : float\n Temperature in K.\n freqs : float or ndarray\n Phonon frequency in eV.\n\n Returns\n -------\n float or ndarray\n Mode entropy in eV/K.\n\n \"\"\"\n val = freqs / (2 * Kb * temp)\n return (1 / (2 * temp) * freqs * np.cosh(val) / np.sinh(val)\n - Kb * np.log(2 * np.sinh(val)))\n\n\ndef mode_ZPE(temp, freqs):\n \"\"\"Return half of phonon frequency as mode zero point energy.\n\n Parameters\n ----------\n temp :\n Dummy parameter. This is not used.\n freqs : float or ndarray\n Phonon frequency in eV.\n\n Returns\n -------\n float or ndarray\n Half of phonon frequency as mode zero point energy in eV.\n\n \"\"\"\n return freqs / 2\n\n\ndef mode_zero(temp, freqs):\n \"\"\"Return zero.\n\n Parameters\n ----------\n temp :\n Dummy parameter. This is not used.\n freqs : float or ndarray\n Dummy parameter. This is not used.\n\n Returns\n -------\n float or ndarray\n 0 or an array of zero.\n\n \"\"\"\n return np.zeros_like(freqs)\n\n\nclass ThermalPropertiesBase(object):\n \"\"\"Base class of thermal property calculation.\"\"\"\n\n def __init__(self,\n mesh,\n cutoff_frequency=None,\n pretend_real=False,\n band_indices=None,\n is_projection=False):\n \"\"\"Init method.\n\n Note\n ----\n Physical unit of Phonon frequency is eV throughout this class, for\n which phonon frequencies and cutoff frequency are stored as class\n instance variables by being transfomred to have eV unit.\n\n Parameters\n ----------\n See Phonopy.run_thermal_properties().\n\n \"\"\"\n self._is_projection = is_projection\n self._band_indices = None\n\n if cutoff_frequency is None or cutoff_frequency < 0:\n self._cutoff_frequency = 0.0\n else:\n self._cutoff_frequency = cutoff_frequency * THzToEv\n\n if band_indices is not None:\n bi = np.hstack(band_indices).astype('intc')\n self._band_indices = bi\n self._frequencies = np.array(mesh.frequencies[:, bi],\n dtype='double', order='C')\n if mesh.eigenvectors is not None:\n self._eigenvectors = np.array(mesh.eigenvectors[:, :, bi],\n dtype='double', order='C')\n else:\n self._frequencies = mesh.frequencies\n self._eigenvectors = mesh.eigenvectors\n\n if pretend_real:\n self._frequencies = abs(self._frequencies)\n self._frequencies = np.array(self._frequencies,\n dtype='double', order='C') * THzToEv\n self._weights = mesh.weights\n self._num_modes = self._frequencies.shape[1] * self._weights.sum()\n self._num_integrated_modes = np.sum(\n self._weights * (self._frequencies >\n self._cutoff_frequency).sum(axis=1))\n\n # When self._weights.dtype is 'uint', the number is casted to float.\n # In future version, self._weights.dtype will be 'int_', so this\n # treatment will be unnecessary.\n if isinstance(self._num_modes, float):\n self._num_modes = int(self._num_modes)\n if isinstance(self._num_integrated_modes, float):\n self._num_integrated_modes = int(self._num_integrated_modes)\n\n @property\n def cutoff_frequency(self):\n \"\"\"Return cutoff frequency in eV.\"\"\"\n return self._cutoff_frequency\n\n def run_free_energy(self, t):\n \"\"\"Calculate mode Helmholtz free energy in kJ/mol.\"\"\"\n if t > 0:\n free_energy = self._calculate_thermal_property(mode_F, t)\n else:\n free_energy = self._calculate_thermal_property(mode_ZPE, None)\n return free_energy / np.sum(self._weights) * EvTokJmol\n\n def run_heat_capacity(self, t):\n \"\"\"Calculate mode heat capacity in kJ/K/mol.\"\"\"\n if t > 0:\n cv = self._calculate_thermal_property(mode_cv, t)\n else:\n cv = self._calculate_thermal_property(mode_zero, None)\n return cv / np.sum(self._weights) * EvTokJmol\n\n def run_entropy(self, t):\n \"\"\"Calculate mode entropy in kJ/K/mol.\"\"\"\n if t > 0:\n entropy = self._calculate_thermal_property(mode_S, t)\n else:\n entropy = self._calculate_thermal_property(mode_zero, None)\n return entropy / np.sum(self._weights) * EvTokJmol\n\n def _calculate_thermal_property(self, func, t):\n if not self._is_projection:\n t_property = 0.0\n for freqs, w in zip(self._frequencies, self._weights):\n cond = freqs > self._cutoff_frequency\n t_property += np.sum(func(t, freqs[cond])) * w\n return t_property\n else:\n t_property = np.zeros(len(self._frequencies[0]), dtype='double')\n for freqs, eigvecs2, w in zip(self._frequencies,\n np.abs(self._eigenvectors) ** 2,\n self._weights):\n cond = freqs > self._cutoff_frequency\n t_property += np.dot(eigvecs2[:, cond],\n func(t, freqs[cond])) * w\n return t_property\n\n\nclass ThermalProperties(ThermalPropertiesBase):\n \"\"\"Phonon thermal property calculation.\"\"\"\n\n def __init__(self,\n mesh,\n cutoff_frequency=None,\n pretend_real=False,\n band_indices=None,\n is_projection=False):\n \"\"\"Init method.\n\n Note\n ----\n Physical unit of Phonon frequency is eV throughout this class, for\n which phonon frequencies and cutoff frequency are stored as class\n instance variables by being transfomred to have eV unit.\n\n Parameters\n ----------\n See Phonopy.run_thermal_properties().\n\n \"\"\"\n ThermalPropertiesBase.__init__(self,\n mesh,\n cutoff_frequency=cutoff_frequency,\n pretend_real=pretend_real,\n band_indices=band_indices,\n is_projection=is_projection)\n self._thermal_properties = None\n self._temperatures = None\n self._zero_point_energy = None\n self._projected_thermal_properties = None\n\n zp_energy = 0.0\n for freqs, w in zip(self._frequencies, self._weights):\n positive_fs = np.extract(freqs > 0.0, freqs)\n zp_energy += np.sum(positive_fs) * w / 2\n self._zero_point_energy = zp_energy / np.sum(self._weights) * EvTokJmol\n\n @ property\n def temperatures(self):\n \"\"\"Setter and getter of temperatures in K.\"\"\"\n return self._temperatures\n\n @ temperatures.setter\n def temperatures(self, temperatures):\n t_array = np.array(temperatures, dtype='double')\n self._temperatures = np.array(\n np.extract(np.invert(t_array < 0), t_array), dtype='double')\n\n def get_temperatures(self):\n \"\"\"Return temperatures.\"\"\"\n warnings.warn(\"ThermalProperties.get_temperatures is deprecated.\"\n \"Use temperatures attribute.\",\n DeprecationWarning)\n return self.temperatures\n\n def set_temperatures(self, temperatures):\n \"\"\"Set temperatures.\"\"\"\n warnings.warn(\"ThermalProperties.set_temperatures is deprecated.\"\n \"Use temperatures attribute.\",\n DeprecationWarning)\n self.temperatures = temperatures\n\n @ property\n def thermal_properties(self):\n \"\"\"Return thermal properties.\n\n Returns\n -------\n tuple :\n Temperatures in K,\n Helmholtz free energies in kJmol,\n Entropies in J/K/mol,\n Heat capacities. in J/K/mol.\n\n \"\"\"\n return self._thermal_properties\n\n def get_thermal_properties(self):\n \"\"\"Return thermal properties.\"\"\"\n warnings.warn(\"ThermalProperties.get_thermal_properties is deprecated.\"\n \"Use thermal_properties attribute.\",\n DeprecationWarning)\n return self.thermal_properties\n\n @ property\n def zero_point_energy(self):\n \"\"\"Return zero point energy in kJ/mol.\"\"\"\n return self._zero_point_energy\n\n def get_zero_point_energy(self):\n \"\"\"Return zero point energy in kJ/mol.\"\"\"\n warnings.warn(\"ThermalProperties.get_zero_point_energy is deprecated.\"\n \"Use zero_point_energy attribute.\",\n DeprecationWarning)\n return self.zero_point_energy\n\n @ property\n def number_of_integrated_modes(self):\n \"\"\"Return number of phonon modes integrated on mesh sampling grid.\"\"\"\n return self._num_integrated_modes\n\n def get_number_of_integrated_modes(self):\n \"\"\"Return number of phonon modes integrated on mesh sampling grid.\"\"\"\n warnings.warn(\"ThermalProperties.get_number_of_integrated_modes is \"\n \"deprecated. Use number_of_integrated_modes attribute.\",\n DeprecationWarning)\n return self.number_of_integrated_modes\n\n @ property\n def number_of_modes(self):\n \"\"\"Return total number of phonon modes on mesh sampling grid.\"\"\"\n return self._num_modes\n\n def get_number_of_modes(self):\n \"\"\"Return total number of phonon modes on mesh sampling grid.\"\"\"\n warnings.warn(\"ThermalProperties.get_number_of_modes is \"\n \"deprecated. Use number_of_modes attribute.\",\n DeprecationWarning)\n return self.number_of_modes\n\n def set_temperature_range(self, t_min=None, t_max=None, t_step=None):\n \"\"\"Set temperature range where thermal properties are calculated.\"\"\"\n if t_min is None:\n _t_min = 10\n elif t_min < 0:\n _t_min = 0\n else:\n _t_min = t_min\n\n if t_max is None:\n _t_max = 1000\n elif t_max > _t_min:\n _t_max = t_max\n else:\n _t_max = _t_min\n\n if t_step is None:\n _t_step = 10\n elif t_step > 0:\n _t_step = t_step\n else:\n _t_step = 10\n\n self._temperatures = np.arange(_t_min, _t_max + _t_step / 2.0, _t_step,\n dtype='double')\n\n def plot(self, plt):\n \"\"\"Plot thermal properties using matplotlib.\"\"\"\n temps, fe, entropy, cv = self._thermal_properties\n\n plt.plot(temps, fe, 'r-')\n plt.plot(temps, entropy, 'b-')\n plt.plot(temps, cv, 'g-')\n plt.legend(('Free energy [kJ/mol]', 'Entropy [J/K/mol]',\n r'C$_\\mathrm{V}$ [J/K/mol]'),\n loc='best')\n plt.grid(True)\n plt.xlabel('Temperature [K]')\n\n def run(self, t_step=None, t_max=None, t_min=None, lang='C'):\n \"\"\"Run thermal property calculation.\"\"\"\n if (t_step is not None or t_max is not None or t_min is not None):\n warnings.warn(\"keywords for this method are depreciated. \"\n \"Use \\'set_temperature_range\\' or \"\n \"\\'set_temperature_range\\' method instead.\",\n DeprecationWarning)\n self.set_temperature_range(t_min=t_min, t_max=t_max, t_step=t_step)\n\n if lang == 'C':\n import phonopy._phonopy as phonoc\n self._run_c_thermal_properties()\n else:\n self._run_py_thermal_properties()\n\n if self._is_projection:\n fe = []\n entropy = []\n cv = []\n for t in self._temperatures:\n fe.append(self.run_free_energy(t))\n entropy.append(self.run_entropy(t) * 1000)\n cv.append(self.run_heat_capacity(t) * 1000)\n\n self._projected_thermal_properties = (\n self._temperatures,\n np.array(fe, dtype='double'),\n np.array(entropy, dtype='double'),\n np.array(cv, dtype='double'))\n\n def write_yaml(self, filename='thermal_properties.yaml', volume=None):\n \"\"\"Write thermal properties in yaml file.\"\"\"\n lines = self._get_tp_yaml_lines(volume=volume)\n if self._is_projection:\n lines += self._get_projected_tp_yaml_lines()\n with open(filename, 'w') as w:\n w.write(\"\\n\".join(lines))\n\n def _run_c_thermal_properties(self):\n import phonopy._phonopy as phonoc\n\n props = np.zeros((len(self._temperatures), 3),\n dtype='double', order='C')\n phonoc.thermal_properties(props,\n self._temperatures,\n self._frequencies,\n self._weights,\n self._cutoff_frequency)\n # for f, w in zip(self._frequencies, self._weights):\n # phonoc.thermal_properties(\n # props,\n # self._temperatures,\n # np.array(f, dtype='double', order='C')[None, :],\n # np.array([w], dtype='intc'),\n # cutoff_frequency)\n\n props /= np.sum(self._weights)\n fe = props[:, 0] * EvTokJmol + self._zero_point_energy\n entropy = props[:, 1] * EvTokJmol * 1000\n cv = props[:, 2] * EvTokJmol * 1000\n self._thermal_properties = (self._temperatures, fe, entropy, cv)\n\n def _run_py_thermal_properties(self):\n fe = []\n entropy = []\n cv = []\n for t in self._temperatures:\n props = self._get_py_thermal_properties(t)\n fe.append(props[0])\n entropy.append(props[1] * 1000)\n cv.append(props[2] * 1000)\n self._thermal_properties = (self._temperatures,\n np.array(fe, dtype='double'),\n np.array(entropy, dtype='double'),\n np.array(cv, dtype='double'))\n\n def _get_tp_yaml_lines(self, volume=None):\n lines = []\n lines.append(\"# Thermal properties / unit cell (natom)\")\n lines.append(\"\")\n lines.append(\"unit:\")\n lines.append(\" temperature: K\")\n lines.append(\" free_energy: kJ/mol\")\n lines.append(\" entropy: J/K/mol\")\n lines.append(\" heat_capacity: J/K/mol\")\n lines.append(\"\")\n lines.append(\"natom: %-5d\" % (self._frequencies[0].shape[0] // 3))\n if volume is not None:\n lines.append(\"volume: %-20.10f\" % volume)\n lines.append(\"cutoff_frequency: %.5f\"\n % (self._cutoff_frequency / THzToEv))\n lines.append(\"num_modes: %d\" % self._num_modes)\n lines.append(\"num_integrated_modes: %d\" % self._num_integrated_modes)\n if self._band_indices is not None:\n bi = self._band_indices + 1\n lines.append(\"band_index: [ \" + (\"%d, \" * (len(bi) - 1)) %\n tuple(bi[:-1]) + (\"%d ]\" % bi[-1]))\n lines.append(\"\")\n lines.append(\"zero_point_energy: %15.7f\" % self._zero_point_energy)\n lines.append(\"\")\n lines.append(\"thermal_properties:\")\n temperatures, fe, entropy, cv = self._thermal_properties\n for i, t in enumerate(temperatures):\n lines.append(\"- temperature: %15.7f\" % t)\n lines.append(\" free_energy: %15.7f\" % fe[i])\n lines.append(\" entropy: %15.7f\" % entropy[i])\n # Sometimes 'nan' of C_V is returned at low temperature.\n if np.isnan(cv[i]):\n lines.append(\" heat_capacity: %15.7f\" % 0)\n else:\n lines.append(\" heat_capacity: %15.7f\" % cv[i])\n lines.append(\" energy: %15.7f\" %\n (fe[i] + entropy[i] * t / 1000))\n lines.append(\"\")\n return lines\n\n def _get_projected_tp_yaml_lines(self):\n lines = []\n lines.append(\"projected_thermal_properties:\")\n temperatures, fe, entropy, cv = self._projected_thermal_properties\n for i, t in enumerate(temperatures):\n lines.append(\"- temperature: %13.7f\" % t)\n line = \" free_energy: [ \"\n line += \", \".join([\"%13.7f\" % x for x in fe[i]])\n line += \" ] # %13.7f\" % np.sum(fe[i])\n lines.append(line)\n line = \" entropy: [ \"\n line += \", \".join([\"%13.7f\" % x for x in entropy[i]])\n line += \" ] # %13.7f\" % np.sum(entropy[i])\n lines.append(line)\n # Sometimes 'nan' of C_V is returned at low temperature.\n line = \" heat_capacity: [ \"\n sum_cv = 0.0\n for j, cv_i in enumerate(cv[i]):\n if np.isnan(cv_i):\n line += \"%13.7f\" % 0\n else:\n sum_cv += cv_i\n line += \"%13.7f\" % cv_i\n if j < len(cv[i]) - 1:\n line += \", \"\n else:\n line += \" ]\"\n line += \" # %13.7f\" % sum_cv\n lines.append(line)\n energy = fe[i] + entropy[i] * t / 1000\n line = \" energy: [ \"\n line += \", \".join([\"%13.7f\" % x for x in energy])\n line += \" ] # %13.7f\" % np.sum(energy)\n lines.append(line)\n return lines\n\n def _get_py_thermal_properties(self, t):\n return (self.run_free_energy(t),\n self.run_entropy(t),\n self.run_heat_capacity(t))\n" ]
[ [ "numpy.array", "numpy.dot", "matplotlib.pyplot.savefig", "matplotlib.pyplot.close", "matplotlib.pyplot.subplots", "matplotlib.pyplot.tight_layout", "numpy.polyfit", "numpy.abs", "matplotlib.ticker.ScalarFormatter.__init__" ], [ "numpy.extract", "numpy.array", "numpy.zeros_like", "numpy.isnan", "numpy.cosh", "numpy.sum", "numpy.exp", "numpy.invert", "numpy.arange", "numpy.sinh", "numpy.abs", "numpy.hstack" ] ]
hyunghunny/AutoDL-Projects
[ "a885090b153e6ccd7c77b94aceac5de857622829", "a885090b153e6ccd7c77b94aceac5de857622829" ]
[ "nas201bench/models/__init__.py", "exps/experimental/visualize-nas-bench-x.py" ]
[ "##################################################\n# Copyright (c) Xuanyi Dong [GitHub D-X-Y], 2019 #\n##################################################\nfrom os import path as osp\nfrom typing import List, Text\nimport torch\n\n__all__ = ['change_key', 'get_cell_based_tiny_net', 'get_search_spaces', 'get_cifar_models', 'get_imagenet_models', \\\n 'obtain_model', 'obtain_search_model', 'load_net_from_checkpoint', \\\n 'CellStructure', 'CellArchitectures'\n ]\n\n# useful modules\nfrom config_utils import dict2config\nfrom models.SharedUtils import change_key\nfrom models.cell_searchs import CellStructure, CellArchitectures\n\n\n# Cell-based NAS Models\ndef get_cell_based_tiny_net(config):\n if isinstance(config, dict): config = dict2config(config, None) # to support the argument being a dict\n super_type = getattr(config, 'super_type', 'basic')\n group_names = ['DARTS-V1', 'DARTS-V2', 'GDAS', 'SETN', 'ENAS', 'RANDOM', 'generic']\n if super_type == 'basic' and config.name in group_names:\n from .cell_searchs import nas201_super_nets as nas_super_nets\n try:\n return nas_super_nets[config.name](config.C, config.N, config.max_nodes, config.num_classes, config.space, config.affine, config.track_running_stats)\n except:\n return nas_super_nets[config.name](config.C, config.N, config.max_nodes, config.num_classes, config.space)\n elif super_type == 'search-shape':\n from .shape_searchs import GenericNAS301Model\n genotype = CellStructure.str2structure(config.genotype)\n return GenericNAS301Model(config.candidate_Cs, config.max_num_Cs, genotype, config.num_classes, config.affine, config.track_running_stats)\n elif super_type == 'nasnet-super':\n from .cell_searchs import nasnet_super_nets as nas_super_nets\n return nas_super_nets[config.name](config.C, config.N, config.steps, config.multiplier, \\\n config.stem_multiplier, config.num_classes, config.space, config.affine, config.track_running_stats)\n elif config.name == 'infer.tiny':\n from .cell_infers import TinyNetwork\n if hasattr(config, 'genotype'):\n genotype = config.genotype\n elif hasattr(config, 'arch_str'):\n genotype = CellStructure.str2structure(config.arch_str)\n else: raise ValueError('Can not find genotype from this config : {:}'.format(config))\n return TinyNetwork(config.C, config.N, genotype, config.num_classes)\n elif config.name == 'infer.shape.tiny':\n from .shape_infers import DynamicShapeTinyNet\n if isinstance(config.channels, str):\n channels = tuple([int(x) for x in config.channels.split(':')])\n else: channels = config.channels\n genotype = CellStructure.str2structure(config.genotype)\n return DynamicShapeTinyNet(channels, genotype, config.num_classes)\n elif config.name == 'infer.nasnet-cifar':\n from .cell_infers import NASNetonCIFAR\n raise NotImplementedError\n else:\n raise ValueError('invalid network name : {:}'.format(config.name))\n\n\n# obtain the search space, i.e., a dict mapping the operation name into a python-function for this op\ndef get_search_spaces(xtype, name) -> List[Text]:\n if xtype == 'cell' or xtype == 'tss': # The topology search space.\n from .cell_operations import SearchSpaceNames\n assert name in SearchSpaceNames, 'invalid name [{:}] in {:}'.format(name, SearchSpaceNames.keys())\n return SearchSpaceNames[name]\n elif xtype == 'sss': # The size search space.\n if name == 'nas-bench-301' or name == 'nats-bench' or name == 'nats-bench-size':\n return {'candidates': [8, 16, 24, 32, 40, 48, 56, 64],\n 'numbers': 5}\n else:\n raise ValueError('Invalid name : {:}'.format(name))\n else:\n raise ValueError('invalid search-space type is {:}'.format(xtype))\n\n\ndef get_cifar_models(config, extra_path=None):\n super_type = getattr(config, 'super_type', 'basic')\n if super_type == 'basic':\n from .CifarResNet import CifarResNet\n from .CifarDenseNet import DenseNet\n from .CifarWideResNet import CifarWideResNet\n if config.arch == 'resnet':\n return CifarResNet(config.module, config.depth, config.class_num, config.zero_init_residual)\n elif config.arch == 'densenet':\n return DenseNet(config.growthRate, config.depth, config.reduction, config.class_num, config.bottleneck)\n elif config.arch == 'wideresnet':\n return CifarWideResNet(config.depth, config.wide_factor, config.class_num, config.dropout)\n else:\n raise ValueError('invalid module type : {:}'.format(config.arch))\n elif super_type.startswith('infer'):\n from .shape_infers import InferWidthCifarResNet\n from .shape_infers import InferDepthCifarResNet\n from .shape_infers import InferCifarResNet\n from .cell_infers import NASNetonCIFAR\n assert len(super_type.split('-')) == 2, 'invalid super_type : {:}'.format(super_type)\n infer_mode = super_type.split('-')[1]\n if infer_mode == 'width':\n return InferWidthCifarResNet(config.module, config.depth, config.xchannels, config.class_num, config.zero_init_residual)\n elif infer_mode == 'depth':\n return InferDepthCifarResNet(config.module, config.depth, config.xblocks, config.class_num, config.zero_init_residual)\n elif infer_mode == 'shape':\n return InferCifarResNet(config.module, config.depth, config.xblocks, config.xchannels, config.class_num, config.zero_init_residual)\n elif infer_mode == 'nasnet.cifar':\n genotype = config.genotype\n if extra_path is not None: # reload genotype by extra_path\n if not osp.isfile(extra_path): raise ValueError('invalid extra_path : {:}'.format(extra_path))\n xdata = torch.load(extra_path)\n current_epoch = xdata['epoch']\n genotype = xdata['genotypes'][current_epoch-1]\n C = config.C if hasattr(config, 'C') else config.ichannel\n N = config.N if hasattr(config, 'N') else config.layers\n return NASNetonCIFAR(C, N, config.stem_multi, config.class_num, genotype, config.auxiliary)\n else:\n raise ValueError('invalid infer-mode : {:}'.format(infer_mode))\n else:\n raise ValueError('invalid super-type : {:}'.format(super_type))\n\n\ndef get_imagenet_models(config):\n super_type = getattr(config, 'super_type', 'basic')\n if super_type == 'basic':\n from .ImageNet_ResNet import ResNet\n from .ImageNet_MobileNetV2 import MobileNetV2\n if config.arch == 'resnet':\n return ResNet(config.block_name, config.layers, config.deep_stem, config.class_num, config.zero_init_residual, config.groups, config.width_per_group)\n elif config.arch == 'mobilenet_v2':\n return MobileNetV2(config.class_num, config.width_multi, config.input_channel, config.last_channel, 'InvertedResidual', config.dropout)\n else:\n raise ValueError('invalid arch : {:}'.format( config.arch ))\n elif super_type.startswith('infer'): # NAS searched architecture\n assert len(super_type.split('-')) == 2, 'invalid super_type : {:}'.format(super_type)\n infer_mode = super_type.split('-')[1]\n if infer_mode == 'shape':\n from .shape_infers import InferImagenetResNet\n from .shape_infers import InferMobileNetV2\n if config.arch == 'resnet':\n return InferImagenetResNet(config.block_name, config.layers, config.xblocks, config.xchannels, config.deep_stem, config.class_num, config.zero_init_residual)\n elif config.arch == \"MobileNetV2\":\n return InferMobileNetV2(config.class_num, config.xchannels, config.xblocks, config.dropout)\n else:\n raise ValueError('invalid arch-mode : {:}'.format(config.arch))\n else:\n raise ValueError('invalid infer-mode : {:}'.format(infer_mode))\n else:\n raise ValueError('invalid super-type : {:}'.format(super_type))\n\n\n# Try to obtain the network by config.\ndef obtain_model(config, extra_path=None):\n if config.dataset == 'cifar':\n return get_cifar_models(config, extra_path)\n elif config.dataset == 'imagenet':\n return get_imagenet_models(config)\n else:\n raise ValueError('invalid dataset in the model config : {:}'.format(config))\n\n\ndef obtain_search_model(config):\n if config.dataset == 'cifar':\n if config.arch == 'resnet':\n from .shape_searchs import SearchWidthCifarResNet\n from .shape_searchs import SearchDepthCifarResNet\n from .shape_searchs import SearchShapeCifarResNet\n if config.search_mode == 'width':\n return SearchWidthCifarResNet(config.module, config.depth, config.class_num)\n elif config.search_mode == 'depth':\n return SearchDepthCifarResNet(config.module, config.depth, config.class_num)\n elif config.search_mode == 'shape':\n return SearchShapeCifarResNet(config.module, config.depth, config.class_num)\n else: raise ValueError('invalid search mode : {:}'.format(config.search_mode))\n elif config.arch == 'simres':\n from .shape_searchs import SearchWidthSimResNet\n if config.search_mode == 'width':\n return SearchWidthSimResNet(config.depth, config.class_num)\n else: raise ValueError('invalid search mode : {:}'.format(config.search_mode))\n else:\n raise ValueError('invalid arch : {:} for dataset [{:}]'.format(config.arch, config.dataset))\n elif config.dataset == 'imagenet':\n from .shape_searchs import SearchShapeImagenetResNet\n assert config.search_mode == 'shape', 'invalid search-mode : {:}'.format( config.search_mode )\n if config.arch == 'resnet':\n return SearchShapeImagenetResNet(config.block_name, config.layers, config.deep_stem, config.class_num)\n else:\n raise ValueError('invalid model config : {:}'.format(config))\n else:\n raise ValueError('invalid dataset in the model config : {:}'.format(config))\n\n\ndef load_net_from_checkpoint(checkpoint):\n assert osp.isfile(checkpoint), 'checkpoint {:} does not exist'.format(checkpoint)\n checkpoint = torch.load(checkpoint)\n model_config = dict2config(checkpoint['model-config'], None)\n model = obtain_model(model_config)\n model.load_state_dict(checkpoint['base-model'])\n return model\n", "###############################################################\n# NAS-Bench-201, ICLR 2020 (https://arxiv.org/abs/2001.00326) #\n###############################################################\n# Copyright (c) Xuanyi Dong [GitHub D-X-Y], 2020.06 #\n###############################################################\n# Usage: python exps/experimental/visualize-nas-bench-x.py\n###############################################################\nimport os, sys, time, torch, argparse\nimport numpy as np\nfrom typing import List, Text, Dict, Any\nfrom shutil import copyfile\nfrom collections import defaultdict\nfrom copy import deepcopy\nfrom pathlib import Path\nimport matplotlib\nimport seaborn as sns\nmatplotlib.use('agg')\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as ticker\n\nlib_dir = (Path(__file__).parent / '..' / '..' / 'lib').resolve()\nif str(lib_dir) not in sys.path: sys.path.insert(0, str(lib_dir))\nfrom config_utils import dict2config, load_config\nfrom log_utils import time_string\nfrom models import get_cell_based_tiny_net\nfrom nats_bench import create\n\n\ndef visualize_info(api, vis_save_dir, indicator):\n vis_save_dir = vis_save_dir.resolve()\n # print ('{:} start to visualize {:} information'.format(time_string(), api))\n vis_save_dir.mkdir(parents=True, exist_ok=True)\n\n cifar010_cache_path = vis_save_dir / '{:}-cache-{:}-info.pth'.format('cifar10', indicator)\n cifar100_cache_path = vis_save_dir / '{:}-cache-{:}-info.pth'.format('cifar100', indicator)\n imagenet_cache_path = vis_save_dir / '{:}-cache-{:}-info.pth'.format('ImageNet16-120', indicator)\n cifar010_info = torch.load(cifar010_cache_path)\n cifar100_info = torch.load(cifar100_cache_path)\n imagenet_info = torch.load(imagenet_cache_path)\n indexes = list(range(len(cifar010_info['params'])))\n\n print ('{:} start to visualize relative ranking'.format(time_string()))\n\n cifar010_ord_indexes = sorted(indexes, key=lambda i: cifar010_info['test_accs'][i])\n cifar100_ord_indexes = sorted(indexes, key=lambda i: cifar100_info['test_accs'][i])\n imagenet_ord_indexes = sorted(indexes, key=lambda i: imagenet_info['test_accs'][i])\n\n cifar100_labels, imagenet_labels = [], []\n for idx in cifar010_ord_indexes:\n cifar100_labels.append( cifar100_ord_indexes.index(idx) )\n imagenet_labels.append( imagenet_ord_indexes.index(idx) )\n print ('{:} prepare data done.'.format(time_string()))\n\n dpi, width, height = 200, 1400, 800\n figsize = width / float(dpi), height / float(dpi)\n LabelSize, LegendFontsize = 18, 12\n resnet_scale, resnet_alpha = 120, 0.5\n\n fig = plt.figure(figsize=figsize)\n ax = fig.add_subplot(111)\n plt.xlim(min(indexes), max(indexes))\n plt.ylim(min(indexes), max(indexes))\n # plt.ylabel('y').set_rotation(30)\n plt.yticks(np.arange(min(indexes), max(indexes), max(indexes)//3), fontsize=LegendFontsize, rotation='vertical')\n plt.xticks(np.arange(min(indexes), max(indexes), max(indexes)//5), fontsize=LegendFontsize)\n ax.scatter(indexes, cifar100_labels, marker='^', s=0.5, c='tab:green', alpha=0.8)\n ax.scatter(indexes, imagenet_labels, marker='*', s=0.5, c='tab:red' , alpha=0.8)\n ax.scatter(indexes, indexes , marker='o', s=0.5, c='tab:blue' , alpha=0.8)\n ax.scatter([-1], [-1], marker='o', s=100, c='tab:blue' , label='CIFAR-10')\n ax.scatter([-1], [-1], marker='^', s=100, c='tab:green', label='CIFAR-100')\n ax.scatter([-1], [-1], marker='*', s=100, c='tab:red' , label='ImageNet-16-120')\n plt.grid(zorder=0)\n ax.set_axisbelow(True)\n plt.legend(loc=0, fontsize=LegendFontsize)\n ax.set_xlabel('architecture ranking in CIFAR-10', fontsize=LabelSize)\n ax.set_ylabel('architecture ranking', fontsize=LabelSize)\n save_path = (vis_save_dir / '{:}-relative-rank.pdf'.format(indicator)).resolve()\n fig.savefig(save_path, dpi=dpi, bbox_inches='tight', format='pdf')\n save_path = (vis_save_dir / '{:}-relative-rank.png'.format(indicator)).resolve()\n fig.savefig(save_path, dpi=dpi, bbox_inches='tight', format='png')\n print ('{:} save into {:}'.format(time_string(), save_path))\n\n\ndef visualize_sss_info(api, dataset, vis_save_dir):\n vis_save_dir = vis_save_dir.resolve()\n print ('{:} start to visualize {:} information'.format(time_string(), dataset))\n vis_save_dir.mkdir(parents=True, exist_ok=True)\n cache_file_path = vis_save_dir / '{:}-cache-sss-info.pth'.format(dataset)\n if not cache_file_path.exists():\n print ('Do not find cache file : {:}'.format(cache_file_path))\n params, flops, train_accs, valid_accs, test_accs = [], [], [], [], []\n for index in range(len(api)):\n cost_info = api.get_cost_info(index, dataset, hp='90')\n params.append(cost_info['params'])\n flops.append(cost_info['flops'])\n # accuracy\n info = api.get_more_info(index, dataset, hp='90', is_random=False)\n train_accs.append(info['train-accuracy'])\n test_accs.append(info['test-accuracy'])\n if dataset == 'cifar10':\n info = api.get_more_info(index, 'cifar10-valid', hp='90', is_random=False)\n valid_accs.append(info['valid-accuracy'])\n else:\n valid_accs.append(info['valid-accuracy'])\n info = {'params': params, 'flops': flops, 'train_accs': train_accs, 'valid_accs': valid_accs, 'test_accs': test_accs}\n torch.save(info, cache_file_path)\n else:\n print ('Find cache file : {:}'.format(cache_file_path))\n info = torch.load(cache_file_path)\n params, flops, train_accs, valid_accs, test_accs = info['params'], info['flops'], info['train_accs'], info['valid_accs'], info['test_accs']\n print ('{:} collect data done.'.format(time_string()))\n\n pyramid = ['8:16:32:48:64', '8:8:16:32:48', '8:8:16:16:32', '8:8:16:16:48', '8:8:16:16:64', '16:16:32:32:64', '32:32:64:64:64']\n pyramid_indexes = [api.query_index_by_arch(x) for x in pyramid]\n largest_indexes = [api.query_index_by_arch('64:64:64:64:64')]\n\n indexes = list(range(len(params)))\n dpi, width, height = 250, 8500, 1300\n figsize = width / float(dpi), height / float(dpi)\n LabelSize, LegendFontsize = 24, 24\n # resnet_scale, resnet_alpha = 120, 0.5\n xscale, xalpha = 120, 0.8\n\n fig, axs = plt.subplots(1, 4, figsize=figsize)\n # ax1, ax2, ax3, ax4, ax5 = axs\n for ax in axs:\n for tick in ax.xaxis.get_major_ticks():\n tick.label.set_fontsize(LabelSize)\n ax.yaxis.set_major_formatter(ticker.FormatStrFormatter('%.0f'))\n for tick in ax.yaxis.get_major_ticks():\n tick.label.set_fontsize(LabelSize)\n ax2, ax3, ax4, ax5 = axs\n # ax1.xaxis.set_ticks(np.arange(0, max(indexes), max(indexes)//5))\n # ax1.scatter(indexes, test_accs, marker='o', s=0.5, c='tab:blue')\n # ax1.set_xlabel('architecture ID', fontsize=LabelSize)\n # ax1.set_ylabel('test accuracy (%)', fontsize=LabelSize)\n\n ax2.scatter(params, train_accs, marker='o', s=0.5, c='tab:blue')\n ax2.scatter([params[x] for x in pyramid_indexes], [train_accs[x] for x in pyramid_indexes], marker='*', s=xscale, c='tab:orange', label='Pyramid Structure', alpha=xalpha)\n ax2.scatter([params[x] for x in largest_indexes], [train_accs[x] for x in largest_indexes], marker='x', s=xscale, c='tab:green', label='Largest Candidate', alpha=xalpha)\n ax2.set_xlabel('#parameters (MB)', fontsize=LabelSize)\n ax2.set_ylabel('train accuracy (%)', fontsize=LabelSize)\n ax2.legend(loc=4, fontsize=LegendFontsize)\n\n ax3.scatter(params, test_accs, marker='o', s=0.5, c='tab:blue')\n ax3.scatter([params[x] for x in pyramid_indexes], [test_accs[x] for x in pyramid_indexes], marker='*', s=xscale, c='tab:orange', label='Pyramid Structure', alpha=xalpha)\n ax3.scatter([params[x] for x in largest_indexes], [test_accs[x] for x in largest_indexes], marker='x', s=xscale, c='tab:green', label='Largest Candidate', alpha=xalpha)\n ax3.set_xlabel('#parameters (MB)', fontsize=LabelSize)\n ax3.set_ylabel('test accuracy (%)', fontsize=LabelSize)\n ax3.legend(loc=4, fontsize=LegendFontsize)\n\n ax4.scatter(flops, train_accs, marker='o', s=0.5, c='tab:blue')\n ax4.scatter([flops[x] for x in pyramid_indexes], [train_accs[x] for x in pyramid_indexes], marker='*', s=xscale, c='tab:orange', label='Pyramid Structure', alpha=xalpha)\n ax4.scatter([flops[x] for x in largest_indexes], [train_accs[x] for x in largest_indexes], marker='x', s=xscale, c='tab:green', label='Largest Candidate', alpha=xalpha)\n ax4.set_xlabel('#FLOPs (M)', fontsize=LabelSize)\n ax4.set_ylabel('train accuracy (%)', fontsize=LabelSize)\n ax4.legend(loc=4, fontsize=LegendFontsize)\n\n ax5.scatter(flops, test_accs, marker='o', s=0.5, c='tab:blue')\n ax5.scatter([flops[x] for x in pyramid_indexes], [test_accs[x] for x in pyramid_indexes], marker='*', s=xscale, c='tab:orange', label='Pyramid Structure', alpha=xalpha)\n ax5.scatter([flops[x] for x in largest_indexes], [test_accs[x] for x in largest_indexes], marker='x', s=xscale, c='tab:green', label='Largest Candidate', alpha=xalpha)\n ax5.set_xlabel('#FLOPs (M)', fontsize=LabelSize)\n ax5.set_ylabel('test accuracy (%)', fontsize=LabelSize)\n ax5.legend(loc=4, fontsize=LegendFontsize)\n\n save_path = vis_save_dir / 'sss-{:}.png'.format(dataset)\n fig.savefig(save_path, dpi=dpi, bbox_inches='tight', format='png')\n print ('{:} save into {:}'.format(time_string(), save_path))\n plt.close('all')\n\n\ndef visualize_tss_info(api, dataset, vis_save_dir):\n vis_save_dir = vis_save_dir.resolve()\n print ('{:} start to visualize {:} information'.format(time_string(), dataset))\n vis_save_dir.mkdir(parents=True, exist_ok=True)\n cache_file_path = vis_save_dir / '{:}-cache-tss-info.pth'.format(dataset)\n if not cache_file_path.exists():\n print ('Do not find cache file : {:}'.format(cache_file_path))\n params, flops, train_accs, valid_accs, test_accs = [], [], [], [], []\n for index in range(len(api)):\n cost_info = api.get_cost_info(index, dataset, hp='12')\n params.append(cost_info['params'])\n flops.append(cost_info['flops'])\n # accuracy\n info = api.get_more_info(index, dataset, hp='200', is_random=False)\n train_accs.append(info['train-accuracy'])\n test_accs.append(info['test-accuracy'])\n if dataset == 'cifar10':\n info = api.get_more_info(index, 'cifar10-valid', hp='200', is_random=False)\n valid_accs.append(info['valid-accuracy'])\n else:\n valid_accs.append(info['valid-accuracy'])\n print('')\n info = {'params': params, 'flops': flops, 'train_accs': train_accs, 'valid_accs': valid_accs, 'test_accs': test_accs}\n torch.save(info, cache_file_path)\n else:\n print ('Find cache file : {:}'.format(cache_file_path))\n info = torch.load(cache_file_path)\n params, flops, train_accs, valid_accs, test_accs = info['params'], info['flops'], info['train_accs'], info['valid_accs'], info['test_accs']\n print ('{:} collect data done.'.format(time_string()))\n\n resnet = ['|nor_conv_3x3~0|+|none~0|nor_conv_3x3~1|+|skip_connect~0|none~1|skip_connect~2|']\n resnet_indexes = [api.query_index_by_arch(x) for x in resnet]\n largest_indexes = [api.query_index_by_arch('|nor_conv_3x3~0|+|nor_conv_3x3~0|nor_conv_3x3~1|+|nor_conv_3x3~0|nor_conv_3x3~1|nor_conv_3x3~2|')]\n\n indexes = list(range(len(params)))\n dpi, width, height = 250, 8500, 1300\n figsize = width / float(dpi), height / float(dpi)\n LabelSize, LegendFontsize = 24, 24\n # resnet_scale, resnet_alpha = 120, 0.5\n xscale, xalpha = 120, 0.8\n\n fig, axs = plt.subplots(1, 4, figsize=figsize)\n # ax1, ax2, ax3, ax4, ax5 = axs\n for ax in axs:\n for tick in ax.xaxis.get_major_ticks():\n tick.label.set_fontsize(LabelSize)\n ax.yaxis.set_major_formatter(ticker.FormatStrFormatter('%.0f'))\n for tick in ax.yaxis.get_major_ticks():\n tick.label.set_fontsize(LabelSize)\n ax2, ax3, ax4, ax5 = axs\n # ax1.xaxis.set_ticks(np.arange(0, max(indexes), max(indexes)//5))\n # ax1.scatter(indexes, test_accs, marker='o', s=0.5, c='tab:blue')\n # ax1.set_xlabel('architecture ID', fontsize=LabelSize)\n # ax1.set_ylabel('test accuracy (%)', fontsize=LabelSize)\n\n ax2.scatter(params, train_accs, marker='o', s=0.5, c='tab:blue')\n ax2.scatter([params[x] for x in resnet_indexes] , [train_accs[x] for x in resnet_indexes], marker='*', s=xscale, c='tab:orange', label='ResNet', alpha=xalpha)\n ax2.scatter([params[x] for x in largest_indexes], [train_accs[x] for x in largest_indexes], marker='x', s=xscale, c='tab:green', label='Largest Candidate', alpha=xalpha)\n ax2.set_xlabel('#parameters (MB)', fontsize=LabelSize)\n ax2.set_ylabel('train accuracy (%)', fontsize=LabelSize)\n ax2.legend(loc=4, fontsize=LegendFontsize)\n\n ax3.scatter(params, test_accs, marker='o', s=0.5, c='tab:blue')\n ax3.scatter([params[x] for x in resnet_indexes] , [test_accs[x] for x in resnet_indexes], marker='*', s=xscale, c='tab:orange', label='ResNet', alpha=xalpha)\n ax3.scatter([params[x] for x in largest_indexes], [test_accs[x] for x in largest_indexes], marker='x', s=xscale, c='tab:green', label='Largest Candidate', alpha=xalpha)\n ax3.set_xlabel('#parameters (MB)', fontsize=LabelSize)\n ax3.set_ylabel('test accuracy (%)', fontsize=LabelSize)\n ax3.legend(loc=4, fontsize=LegendFontsize)\n\n ax4.scatter(flops, train_accs, marker='o', s=0.5, c='tab:blue')\n ax4.scatter([flops[x] for x in resnet_indexes], [train_accs[x] for x in resnet_indexes], marker='*', s=xscale, c='tab:orange', label='ResNet', alpha=xalpha)\n ax4.scatter([flops[x] for x in largest_indexes], [train_accs[x] for x in largest_indexes], marker='x', s=xscale, c='tab:green', label='Largest Candidate', alpha=xalpha)\n ax4.set_xlabel('#FLOPs (M)', fontsize=LabelSize)\n ax4.set_ylabel('train accuracy (%)', fontsize=LabelSize)\n ax4.legend(loc=4, fontsize=LegendFontsize)\n\n ax5.scatter(flops, test_accs, marker='o', s=0.5, c='tab:blue')\n ax5.scatter([flops[x] for x in resnet_indexes], [test_accs[x] for x in resnet_indexes], marker='*', s=xscale, c='tab:orange', label='ResNet', alpha=xalpha)\n ax5.scatter([flops[x] for x in largest_indexes], [test_accs[x] for x in largest_indexes], marker='x', s=xscale, c='tab:green', label='Largest Candidate', alpha=xalpha)\n ax5.set_xlabel('#FLOPs (M)', fontsize=LabelSize)\n ax5.set_ylabel('test accuracy (%)', fontsize=LabelSize)\n ax5.legend(loc=4, fontsize=LegendFontsize)\n\n save_path = vis_save_dir / 'tss-{:}.png'.format(dataset)\n fig.savefig(save_path, dpi=dpi, bbox_inches='tight', format='png')\n print ('{:} save into {:}'.format(time_string(), save_path))\n plt.close('all')\n\n\ndef visualize_rank_info(api, vis_save_dir, indicator):\n vis_save_dir = vis_save_dir.resolve()\n # print ('{:} start to visualize {:} information'.format(time_string(), api))\n vis_save_dir.mkdir(parents=True, exist_ok=True)\n\n cifar010_cache_path = vis_save_dir / '{:}-cache-{:}-info.pth'.format('cifar10', indicator)\n cifar100_cache_path = vis_save_dir / '{:}-cache-{:}-info.pth'.format('cifar100', indicator)\n imagenet_cache_path = vis_save_dir / '{:}-cache-{:}-info.pth'.format('ImageNet16-120', indicator)\n cifar010_info = torch.load(cifar010_cache_path)\n cifar100_info = torch.load(cifar100_cache_path)\n imagenet_info = torch.load(imagenet_cache_path)\n indexes = list(range(len(cifar010_info['params'])))\n\n print ('{:} start to visualize relative ranking'.format(time_string()))\n\n dpi, width, height = 250, 3800, 1200\n figsize = width / float(dpi), height / float(dpi)\n LabelSize, LegendFontsize = 14, 14\n\n fig, axs = plt.subplots(1, 3, figsize=figsize)\n ax1, ax2, ax3 = axs\n\n def get_labels(info):\n ord_test_indexes = sorted(indexes, key=lambda i: info['test_accs'][i])\n ord_valid_indexes = sorted(indexes, key=lambda i: info['valid_accs'][i])\n labels = []\n for idx in ord_test_indexes:\n labels.append(ord_valid_indexes.index(idx))\n return labels\n\n def plot_ax(labels, ax, name):\n for tick in ax.xaxis.get_major_ticks():\n tick.label.set_fontsize(LabelSize)\n for tick in ax.yaxis.get_major_ticks():\n tick.label.set_fontsize(LabelSize)\n tick.label.set_rotation(90)\n ax.set_xlim(min(indexes), max(indexes))\n ax.set_ylim(min(indexes), max(indexes))\n ax.yaxis.set_ticks(np.arange(min(indexes), max(indexes), max(indexes)//3))\n ax.xaxis.set_ticks(np.arange(min(indexes), max(indexes), max(indexes)//5))\n ax.scatter(indexes, labels , marker='^', s=0.5, c='tab:green', alpha=0.8)\n ax.scatter(indexes, indexes, marker='o', s=0.5, c='tab:blue' , alpha=0.8)\n ax.scatter([-1], [-1], marker='^', s=100, c='tab:green' , label='{:} test'.format(name))\n ax.scatter([-1], [-1], marker='o', s=100, c='tab:blue' , label='{:} validation'.format(name))\n ax.legend(loc=4, fontsize=LegendFontsize)\n ax.set_xlabel('ranking on the {:} validation'.format(name), fontsize=LabelSize)\n ax.set_ylabel('architecture ranking', fontsize=LabelSize)\n labels = get_labels(cifar010_info)\n plot_ax(labels, ax1, 'CIFAR-10')\n labels = get_labels(cifar100_info)\n plot_ax(labels, ax2, 'CIFAR-100')\n labels = get_labels(imagenet_info)\n plot_ax(labels, ax3, 'ImageNet-16-120')\n\n save_path = (vis_save_dir / '{:}-same-relative-rank.pdf'.format(indicator)).resolve()\n fig.savefig(save_path, dpi=dpi, bbox_inches='tight', format='pdf')\n save_path = (vis_save_dir / '{:}-same-relative-rank.png'.format(indicator)).resolve()\n fig.savefig(save_path, dpi=dpi, bbox_inches='tight', format='png')\n print ('{:} save into {:}'.format(time_string(), save_path))\n plt.close('all')\n\n\ndef calculate_correlation(*vectors):\n matrix = []\n for i, vectori in enumerate(vectors):\n x = []\n for j, vectorj in enumerate(vectors):\n x.append( np.corrcoef(vectori, vectorj)[0,1] )\n matrix.append( x )\n return np.array(matrix)\n\n\ndef visualize_all_rank_info(api, vis_save_dir, indicator):\n vis_save_dir = vis_save_dir.resolve()\n # print ('{:} start to visualize {:} information'.format(time_string(), api))\n vis_save_dir.mkdir(parents=True, exist_ok=True)\n\n cifar010_cache_path = vis_save_dir / '{:}-cache-{:}-info.pth'.format('cifar10', indicator)\n cifar100_cache_path = vis_save_dir / '{:}-cache-{:}-info.pth'.format('cifar100', indicator)\n imagenet_cache_path = vis_save_dir / '{:}-cache-{:}-info.pth'.format('ImageNet16-120', indicator)\n cifar010_info = torch.load(cifar010_cache_path)\n cifar100_info = torch.load(cifar100_cache_path)\n imagenet_info = torch.load(imagenet_cache_path)\n indexes = list(range(len(cifar010_info['params'])))\n\n print ('{:} start to visualize relative ranking'.format(time_string()))\n \n\n dpi, width, height = 250, 3200, 1400\n figsize = width / float(dpi), height / float(dpi)\n LabelSize, LegendFontsize = 14, 14\n\n fig, axs = plt.subplots(1, 2, figsize=figsize)\n ax1, ax2 = axs\n\n sns_size = 15\n CoRelMatrix = calculate_correlation(cifar010_info['valid_accs'], cifar010_info['test_accs'], cifar100_info['valid_accs'], cifar100_info['test_accs'], imagenet_info['valid_accs'], imagenet_info['test_accs'])\n \n sns.heatmap(CoRelMatrix, annot=True, annot_kws={'size':sns_size}, fmt='.3f', linewidths=0.5, ax=ax1,\n xticklabels=['C10-V', 'C10-T', 'C100-V', 'C100-T', 'I120-V', 'I120-T'],\n yticklabels=['C10-V', 'C10-T', 'C100-V', 'C100-T', 'I120-V', 'I120-T'])\n \n selected_indexes, acc_bar = [], 92\n for i, acc in enumerate(cifar010_info['test_accs']):\n if acc > acc_bar: selected_indexes.append( i )\n cifar010_valid_accs = np.array(cifar010_info['valid_accs'])[ selected_indexes ]\n cifar010_test_accs = np.array(cifar010_info['test_accs']) [ selected_indexes ]\n cifar100_valid_accs = np.array(cifar100_info['valid_accs'])[ selected_indexes ]\n cifar100_test_accs = np.array(cifar100_info['test_accs']) [ selected_indexes ]\n imagenet_valid_accs = np.array(imagenet_info['valid_accs'])[ selected_indexes ]\n imagenet_test_accs = np.array(imagenet_info['test_accs']) [ selected_indexes ]\n CoRelMatrix = calculate_correlation(cifar010_valid_accs, cifar010_test_accs, cifar100_valid_accs, cifar100_test_accs, imagenet_valid_accs, imagenet_test_accs)\n \n sns.heatmap(CoRelMatrix, annot=True, annot_kws={'size':sns_size}, fmt='.3f', linewidths=0.5, ax=ax2,\n xticklabels=['C10-V', 'C10-T', 'C100-V', 'C100-T', 'I120-V', 'I120-T'],\n yticklabels=['C10-V', 'C10-T', 'C100-V', 'C100-T', 'I120-V', 'I120-T'])\n ax1.set_title('Correlation coefficient over ALL candidates')\n ax2.set_title('Correlation coefficient over candidates with accuracy > {:}%'.format(acc_bar))\n save_path = (vis_save_dir / '{:}-all-relative-rank.png'.format(indicator)).resolve()\n fig.savefig(save_path, dpi=dpi, bbox_inches='tight', format='png')\n print ('{:} save into {:}'.format(time_string(), save_path))\n plt.close('all')\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='NAS-Bench-X', formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument('--save_dir', type=str, default='output/vis-nas-bench', help='Folder to save checkpoints and log.')\n # use for train the model\n args = parser.parse_args()\n\n to_save_dir = Path(args.save_dir)\n\n datasets = ['cifar10', 'cifar100', 'ImageNet16-120']\n api201 = create(None, 'tss', verbose=True)\n for xdata in datasets:\n visualize_tss_info(api201, xdata, to_save_dir)\n\n api301 = create(None, 'size', verbose=True)\n for xdata in datasets:\n visualize_sss_info(api301, xdata, to_save_dir)\n\n visualize_info(None, to_save_dir, 'tss')\n visualize_info(None, to_save_dir, 'sss')\n visualize_rank_info(None, to_save_dir, 'tss')\n visualize_rank_info(None, to_save_dir, 'sss')\n\n visualize_all_rank_info(None, to_save_dir, 'tss')\n visualize_all_rank_info(None, to_save_dir, 'sss')\n" ]
[ [ "torch.load" ], [ "matplotlib.use", "numpy.array", "matplotlib.pyplot.grid", "torch.save", "matplotlib.pyplot.legend", "matplotlib.pyplot.close", "matplotlib.pyplot.subplots", "matplotlib.pyplot.figure", "matplotlib.ticker.FormatStrFormatter", "torch.load", "numpy.corrcoef" ] ]
kaushikponnapalli/dymos
[ "3fba91d0fc2c0e8460717b1bec80774676287739", "3fba91d0fc2c0e8460717b1bec80774676287739" ]
[ "dymos/examples/vanderpol/vanderpol_ode.py", "dymos/examples/brachistochrone/doc/test_doc_brachistochrone_tandem_phases.py" ]
[ "import numpy as np\nimport openmdao.api as om\nimport time\nfrom openmdao.utils.array_utils import evenly_distrib_idxs\n\n\nclass VanderpolODE(om.ExplicitComponent):\n \"\"\"intentionally slow version of vanderpol_ode for effects of demonstrating distributed component calculations\n\n MPI can run this component in multiple processes, distributing the calculation of derivatives.\n This code has a delay in it to simulate a longer computation. It should run faster with more processes.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n self.progress_prints = False\n super().__init__(*args, **kwargs)\n\n def initialize(self):\n self.options.declare('num_nodes', types=int)\n self.options.declare('distrib', types=bool, default=False)\n self.options.declare('delay', types=(float,), default=0.0)\n\n def setup(self):\n nn = self.options['num_nodes']\n comm = self.comm\n rank = comm.rank\n\n sizes, offsets = evenly_distrib_idxs(comm.size, nn) # (#cpus, #inputs) -> (size array, offset array)\n self.start_idx = offsets[rank]\n self.io_size = sizes[rank] # number of inputs and outputs managed by this distributed process\n self.end_idx = self.start_idx + self.io_size\n\n # inputs: 2 states and a control\n self.add_input('x0', val=np.ones(nn), desc='derivative of Output', units='V/s')\n self.add_input('x1', val=np.ones(nn), desc='Output', units='V')\n self.add_input('u', val=np.ones(nn), desc='control', units=None)\n\n # outputs: derivative of states\n # the objective function will be treated as a state for computation, so its derivative is an output\n self.add_output('x0dot', val=np.ones(self.io_size), desc='second derivative of Output',\n units='V/s**2', distributed=self.options['distrib'])\n self.add_output('x1dot', val=np.ones(self.io_size), desc='derivative of Output',\n units='V/s', distributed=self.options['distrib'])\n self.add_output('Jdot', val=np.ones(self.io_size), desc='derivative of objective',\n units='1.0/s', distributed=self.options['distrib'])\n\n # self.declare_coloring(method='cs')\n # # partials\n r = np.arange(self.io_size, dtype=int)\n c = r + self.start_idx\n\n self.declare_partials(of='x0dot', wrt='x0', rows=r, cols=c)\n self.declare_partials(of='x0dot', wrt='x1', rows=r, cols=c)\n self.declare_partials(of='x0dot', wrt='u', rows=r, cols=c, val=1.0)\n\n self.declare_partials(of='x1dot', wrt='x0', rows=r, cols=c, val=1.0)\n\n self.declare_partials(of='Jdot', wrt='x0', rows=r, cols=c)\n self.declare_partials(of='Jdot', wrt='x1', rows=r, cols=c)\n self.declare_partials(of='Jdot', wrt='u', rows=r, cols=c)\n\n def compute(self, inputs, outputs):\n # introduce slowness proportional to size of computation\n time.sleep(self.options['delay'] * self.io_size)\n\n # The inputs contain the entire vector, be each rank will only operate on a portion of it.\n x0 = inputs['x0'][self.start_idx:self.end_idx]\n x1 = inputs['x1'][self.start_idx:self.end_idx]\n u = inputs['u'][self.start_idx:self.end_idx]\n\n outputs['x0dot'] = (1.0 - x1**2) * x0 - x1 + u\n outputs['x1dot'] = x0\n outputs['Jdot'] = x0**2 + x1**2 + u**2\n\n def compute_partials(self, inputs, jacobian):\n time.sleep(self.options['delay'] * self.io_size)\n\n x0 = inputs['x0'][self.start_idx:self.end_idx]\n x1 = inputs['x1'][self.start_idx:self.end_idx]\n u = inputs['u'][self.start_idx:self.end_idx]\n\n jacobian['x0dot', 'x0'] = 1.0 - x1 * x1\n jacobian['x0dot', 'x1'] = -2.0 * x1 * x0 - 1.0\n\n jacobian['Jdot', 'x0'] = 2.0 * x0\n jacobian['Jdot', 'x1'] = 2.0 * x1\n jacobian['Jdot', 'u'] = 2.0 * u\n", "import unittest\n\nimport numpy as np\nimport openmdao.api as om\nfrom dymos.utils.doc_utils import save_for_docs\nfrom openmdao.utils.testing_utils import use_tempdirs, require_pyoptsparse\n\n\nclass BrachistochroneArclengthODE(om.ExplicitComponent):\n\n def initialize(self):\n self.options.declare('num_nodes', types=int)\n\n def setup(self):\n nn = self.options['num_nodes']\n\n # Inputs\n self.add_input('v', val=np.zeros(nn), desc='velocity', units='m/s')\n self.add_input('theta', val=np.zeros(nn), desc='angle of wire', units='rad')\n self.add_output('Sdot', val=np.zeros(nn), desc='rate of change of arclength', units='m/s')\n\n # Setup partials\n arange = np.arange(nn)\n\n self.declare_partials(of='Sdot', wrt='v', rows=arange, cols=arange)\n self.declare_partials(of='Sdot', wrt='theta', rows=arange, cols=arange)\n\n def compute(self, inputs, outputs):\n theta = inputs['theta']\n v = inputs['v']\n outputs['Sdot'] = np.sqrt(1.0 + (1.0/np.tan(theta))**2) * v * np.sin(theta)\n\n def compute_partials(self, inputs, jacobian):\n theta = inputs['theta']\n v = inputs['v']\n cos_theta = np.cos(theta)\n sin_theta = np.sin(theta)\n tan_theta = np.tan(theta)\n cot_theta = 1.0 / tan_theta\n csc_theta = 1.0 / sin_theta\n\n jacobian['Sdot', 'v'] = sin_theta * np.sqrt(1.0 + cot_theta**2)\n jacobian['Sdot', 'theta'] = v * (cos_theta * (cot_theta**2 + 1) - cot_theta * csc_theta) / \\\n (np.sqrt(1 + cot_theta**2))\n\n\n@use_tempdirs\nclass TestBrachistochroneTandemPhases(unittest.TestCase):\n\n @save_for_docs\n @require_pyoptsparse(optimizer='SLSQP')\n def test_brachistochrone_tandem_phases(self):\n from dymos.examples.brachistochrone.brachistochrone_ode import BrachistochroneODE\n\n import numpy as np\n import matplotlib.pyplot as plt\n plt.switch_backend('Agg')\n import openmdao.api as om\n import dymos as dm\n\n from openmdao.utils.assert_utils import assert_near_equal\n\n p = om.Problem(model=om.Group())\n\n p.driver = om.pyOptSparseDriver()\n p.driver.options['optimizer'] = 'SLSQP'\n p.driver.declare_coloring()\n\n # The transcription of the first phase\n tx0 = dm.GaussLobatto(num_segments=10, order=3, compressed=False)\n\n # The transcription for the second phase (and the secondary timeseries outputs from the first phase)\n tx1 = dm.Radau(num_segments=20, order=9, compressed=False)\n\n #\n # First Phase: Integrate the standard brachistochrone ODE\n #\n phase0 = dm.Phase(ode_class=BrachistochroneODE, transcription=tx0)\n\n p.model.add_subsystem('phase0', phase0)\n\n phase0.set_time_options(fix_initial=True, duration_bounds=(.5, 10))\n\n phase0.add_state('x', fix_initial=True, fix_final=False)\n\n phase0.add_state('y', fix_initial=True, fix_final=False)\n\n phase0.add_state('v', fix_initial=True, fix_final=False)\n\n phase0.add_control('theta', continuity=True, rate_continuity=True,\n units='deg', lower=0.01, upper=179.9)\n\n phase0.add_parameter('g', units='m/s**2', val=9.80665)\n\n phase0.add_boundary_constraint('x', loc='final', equals=10)\n phase0.add_boundary_constraint('y', loc='final', equals=5)\n\n # Add alternative timeseries output to provide control inputs for the next phase\n phase0.add_timeseries('timeseries2', transcription=tx1, subset='control_input')\n\n #\n # Second Phase: Integration of ArcLength\n #\n phase1 = dm.Phase(ode_class=BrachistochroneArclengthODE, transcription=tx1)\n\n p.model.add_subsystem('phase1', phase1)\n\n phase1.set_time_options(fix_initial=True, input_duration=True)\n\n phase1.add_state('S', fix_initial=True, fix_final=False,\n rate_source='Sdot', units='m')\n\n phase1.add_control('theta', opt=False, units='deg', targets='theta')\n phase1.add_control('v', opt=False, units='m/s', targets='v')\n\n #\n # Connect the two phases\n #\n p.model.connect('phase0.t_duration', 'phase1.t_duration')\n\n p.model.connect('phase0.timeseries2.controls:theta', 'phase1.controls:theta')\n p.model.connect('phase0.timeseries2.states:v', 'phase1.controls:v')\n\n # Minimize arclength at the end of the second phase\n phase1.add_objective('S', loc='final', ref=1)\n\n p.model.linear_solver = om.DirectSolver()\n p.setup(check=True)\n\n p['phase0.t_initial'] = 0.0\n p['phase0.t_duration'] = 2.0\n\n p.set_val('phase0.states:x', phase0.interp('x', ys=[0, 10]))\n p.set_val('phase0.states:y', phase0.interp('y', ys=[10, 5]))\n p.set_val('phase0.states:v', phase0.interp('v', ys=[0, 9.9]))\n p.set_val('phase0.controls:theta', phase0.interp('theta', ys=[5, 100]))\n\n p['phase0.parameters:g'] = 9.80665\n\n p['phase1.states:S'] = 0.0\n\n dm.run_problem(p)\n\n expected = np.sqrt((10-0)**2 + (10 - 5)**2)\n assert_near_equal(p.get_val('phase1.timeseries.states:S')[-1], expected, tolerance=1.0E-3)\n\n fig, (ax0, ax1) = plt.subplots(2, 1)\n fig.tight_layout()\n ax0.plot(p.get_val('phase0.timeseries.states:x'), p.get_val('phase0.timeseries.states:y'), '.')\n ax0.set_xlabel('x (m)')\n ax0.set_ylabel('y (m)')\n ax1.plot(p.get_val('phase1.timeseries.time'), p.get_val('phase1.timeseries.states:S'), '+')\n ax1.set_xlabel('t (s)')\n ax1.set_ylabel('S (m)')\n plt.show()\n\n\nif __name__ == '__main__': # pragma: no cover\n unittest.main()\n" ]
[ [ "numpy.ones", "numpy.arange" ], [ "matplotlib.pyplot.switch_backend", "numpy.sin", "numpy.zeros", "numpy.tan", "matplotlib.pyplot.subplots", "numpy.arange", "numpy.cos", "numpy.sqrt", "matplotlib.pyplot.show" ] ]
bpkwee/metrics
[ "3aba057ad9ff87183aaaf5988b8ccfdab81b2095", "3aba057ad9ff87183aaaf5988b8ccfdab81b2095", "3aba057ad9ff87183aaaf5988b8ccfdab81b2095" ]
[ "tests/regression/test_tweedie_deviance.py", "torchmetrics/functional/retrieval/fall_out.py", "tests/classification/test_confusion_matrix.py" ]
[ "# Copyright The PyTorch Lightning team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nfrom collections import namedtuple\nfrom functools import partial\n\nimport pytest\nimport torch\nfrom sklearn.metrics import mean_tweedie_deviance\nfrom torch import Tensor\n\nfrom tests.helpers import seed_all\nfrom tests.helpers.testers import BATCH_SIZE, NUM_BATCHES, MetricTester\nfrom torchmetrics.functional.regression.tweedie_deviance import tweedie_deviance_score\nfrom torchmetrics.regression.tweedie_deviance import TweedieDevianceScore\n\nseed_all(42)\n\nInput = namedtuple(\"Input\", [\"preds\", \"targets\"])\n\n_single_target_inputs1 = Input(\n preds=torch.rand(NUM_BATCHES, BATCH_SIZE),\n targets=torch.rand(NUM_BATCHES, BATCH_SIZE),\n)\n\n_single_target_inputs2 = Input(\n preds=torch.rand(NUM_BATCHES, BATCH_SIZE),\n targets=torch.rand(NUM_BATCHES, BATCH_SIZE),\n)\n\n_multi_target_inputs = Input(\n preds=torch.rand(NUM_BATCHES, BATCH_SIZE, 5),\n targets=torch.rand(NUM_BATCHES, BATCH_SIZE, 5),\n)\n\n\ndef _sk_deviance(preds: Tensor, targets: Tensor, power: float):\n sk_preds = preds.view(-1).numpy()\n sk_target = targets.view(-1).numpy()\n return mean_tweedie_deviance(sk_target, sk_preds, power=power)\n\n\n@pytest.mark.parametrize(\"power\", [-0.5, 0, 1, 1.5, 2, 3])\n@pytest.mark.parametrize(\n \"preds, targets\",\n [\n (_single_target_inputs1.preds, _single_target_inputs1.targets),\n (_single_target_inputs2.preds, _single_target_inputs2.targets),\n (_multi_target_inputs.preds, _multi_target_inputs.targets),\n ],\n)\nclass TestDevianceScore(MetricTester):\n @pytest.mark.parametrize(\"ddp\", [True, False])\n @pytest.mark.parametrize(\"dist_sync_on_step\", [True, False])\n def test_deviance_scores_class(self, ddp, dist_sync_on_step, preds, targets, power):\n self.run_class_metric_test(\n ddp,\n preds,\n targets,\n TweedieDevianceScore,\n partial(_sk_deviance, power=power),\n dist_sync_on_step,\n metric_args=dict(power=power),\n )\n\n def test_deviance_scores_functional(self, preds, targets, power):\n self.run_functional_metric_test(\n preds,\n targets,\n tweedie_deviance_score,\n partial(_sk_deviance, power=power),\n metric_args=dict(power=power),\n )\n\n def test_pearson_corrcoef_differentiability(self, preds, targets, power):\n self.run_differentiability_test(\n preds, targets, metric_module=TweedieDevianceScore, metric_functional=tweedie_deviance_score\n )\n\n # Tweedie Deviance Score half + cpu does not work due to missing support in torch.log\n @pytest.mark.xfail(reason=\"TweedieDevianceScore metric does not support cpu + half precision\")\n def test_pearson_corrcoef_half_cpu(self, preds, targets, power):\n metric_args = {\"power\": power}\n self.run_precision_test_cpu(\n preds,\n targets,\n metric_module=TweedieDevianceScore,\n metric_functional=tweedie_deviance_score,\n metric_args=metric_args,\n )\n\n @pytest.mark.skipif(not torch.cuda.is_available(), reason=\"test requires cuda\")\n def test_pearson_corrcoef_half_gpu(self, preds, targets, power):\n metric_args = {\"power\": power}\n self.run_precision_test_gpu(\n preds,\n targets,\n metric_module=TweedieDevianceScore,\n metric_functional=tweedie_deviance_score,\n metric_args=metric_args,\n )\n\n\ndef test_error_on_different_shape(metric_class=TweedieDevianceScore):\n metric = metric_class()\n with pytest.raises(RuntimeError, match=\"Predictions and targets are expected to have the same shape\"):\n metric(torch.randn(100), torch.randn(50))\n\n\ndef test_error_on_invalid_inputs(metric_class=TweedieDevianceScore):\n with pytest.raises(ValueError, match=\"Deviance Score is not defined for power=0.5.\"):\n metric_class(power=0.5)\n\n metric = metric_class(power=1)\n with pytest.raises(\n ValueError, match=\"For power=1, 'preds' has to be strictly positive and 'targets' cannot be negative.\"\n ):\n metric(torch.tensor([-1.0, 2.0, 3.0]), torch.rand(3))\n\n with pytest.raises(\n ValueError, match=\"For power=1, 'preds' has to be strictly positive and 'targets' cannot be negative.\"\n ):\n metric(torch.rand(3), torch.tensor([-1.0, 2.0, 3.0]))\n\n metric = metric_class(power=2)\n with pytest.raises(ValueError, match=\"For power=2, both 'preds' and 'targets' have to be strictly positive.\"):\n metric(torch.tensor([-1.0, 2.0, 3.0]), torch.rand(3))\n\n with pytest.raises(ValueError, match=\"For power=2, both 'preds' and 'targets' have to be strictly positive.\"):\n metric(torch.rand(3), torch.tensor([-1.0, 2.0, 3.0]))\n\n\ndef test_corner_case_for_power_at_1(metric_class=TweedieDevianceScore):\n \"\"\"Test that corner case for power=1.0 produce valid result.\"\"\"\n metric = TweedieDevianceScore()\n targets = torch.tensor([0, 1, 0, 1])\n preds = torch.tensor([0.1, 0.1, 0.1, 0.1])\n val = metric(preds, targets)\n assert val != 0.0\n assert not torch.isnan(val)\n", "# Copyright The PyTorch Lightning team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nfrom typing import Optional\n\nimport torch\nfrom torch import Tensor, tensor\n\nfrom torchmetrics.utilities.checks import _check_retrieval_functional_inputs\n\n\ndef retrieval_fall_out(preds: Tensor, target: Tensor, k: Optional[int] = None) -> Tensor:\n \"\"\"Computes the Fall-out (for information retrieval), as explained in `IR Fall-out`_ Fall-out is the fraction\n of non-relevant documents retrieved among all the non-relevant documents.\n\n ``preds`` and ``target`` should be of the same shape and live on the same device. If no ``target`` is ``True``,\n ``0`` is returned. ``target`` must be either `bool` or `integers` and ``preds`` must be `float`,\n otherwise an error is raised. If you want to measure Fall-out@K, ``k`` must be a positive integer.\n\n Args:\n preds: estimated probabilities of each document to be relevant.\n target: ground truth about each document being relevant or not.\n k: consider only the top k elements (default: `None`, which considers them all)\n\n Returns:\n a single-value tensor with the fall-out (at ``k``) of the predictions ``preds`` w.r.t. the labels ``target``.\n\n Raises:\n ValueError:\n If ``k`` parameter is not `None` or an integer larger than 0\n\n Example:\n >>> from torchmetrics.functional import retrieval_fall_out\n >>> preds = tensor([0.2, 0.3, 0.5])\n >>> target = tensor([True, False, True])\n >>> retrieval_fall_out(preds, target, k=2)\n tensor(1.)\n \"\"\"\n preds, target = _check_retrieval_functional_inputs(preds, target)\n\n k = preds.shape[-1] if k is None else k\n\n if not (isinstance(k, int) and k > 0):\n raise ValueError(\"`k` has to be a positive integer or None\")\n\n target = 1 - target\n\n if not target.sum():\n return tensor(0.0, device=preds.device)\n\n relevant = target[torch.argsort(preds, dim=-1, descending=True)][:k].sum().float()\n return relevant / target.sum()\n", "# Copyright The PyTorch Lightning team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nfrom functools import partial\n\nimport numpy as np\nimport pytest\nimport torch\nfrom sklearn.metrics import confusion_matrix as sk_confusion_matrix\nfrom sklearn.metrics import multilabel_confusion_matrix as sk_multilabel_confusion_matrix\n\nfrom tests.classification.inputs import _input_binary, _input_binary_logits, _input_binary_prob\nfrom tests.classification.inputs import _input_multiclass as _input_mcls\nfrom tests.classification.inputs import _input_multiclass_logits as _input_mcls_logits\nfrom tests.classification.inputs import _input_multiclass_prob as _input_mcls_prob\nfrom tests.classification.inputs import _input_multidim_multiclass as _input_mdmc\nfrom tests.classification.inputs import _input_multidim_multiclass_prob as _input_mdmc_prob\nfrom tests.classification.inputs import _input_multilabel as _input_mlb\nfrom tests.classification.inputs import _input_multilabel_logits as _input_mlb_logits\nfrom tests.classification.inputs import _input_multilabel_prob as _input_mlb_prob\nfrom tests.helpers import seed_all\nfrom tests.helpers.testers import NUM_CLASSES, THRESHOLD, MetricTester\nfrom torchmetrics.classification.confusion_matrix import ConfusionMatrix\nfrom torchmetrics.functional import confusion_matrix\n\nseed_all(42)\n\n\ndef _sk_cm_binary_prob(preds, target, normalize=None):\n sk_preds = (preds.view(-1).numpy() >= THRESHOLD).astype(np.uint8)\n sk_target = target.view(-1).numpy()\n\n return sk_confusion_matrix(y_true=sk_target, y_pred=sk_preds, normalize=normalize)\n\n\ndef _sk_cm_binary(preds, target, normalize=None):\n sk_preds = preds.view(-1).numpy()\n sk_target = target.view(-1).numpy()\n\n return sk_confusion_matrix(y_true=sk_target, y_pred=sk_preds, normalize=normalize)\n\n\ndef _sk_cm_multilabel_prob(preds, target, normalize=None):\n sk_preds = (preds.numpy() >= THRESHOLD).astype(np.uint8)\n sk_target = target.numpy()\n\n cm = sk_multilabel_confusion_matrix(y_true=sk_target, y_pred=sk_preds)\n if normalize is not None:\n if normalize == \"true\":\n cm = cm / cm.sum(axis=1, keepdims=True)\n elif normalize == \"pred\":\n cm = cm / cm.sum(axis=0, keepdims=True)\n elif normalize == \"all\":\n cm = cm / cm.sum()\n cm[np.isnan(cm)] = 0\n return cm\n\n\ndef _sk_cm_multilabel(preds, target, normalize=None):\n sk_preds = preds.numpy()\n sk_target = target.numpy()\n\n cm = sk_multilabel_confusion_matrix(y_true=sk_target, y_pred=sk_preds)\n if normalize is not None:\n if normalize == \"true\":\n cm = cm / cm.sum(axis=1, keepdims=True)\n elif normalize == \"pred\":\n cm = cm / cm.sum(axis=0, keepdims=True)\n elif normalize == \"all\":\n cm = cm / cm.sum()\n cm[np.isnan(cm)] = 0\n return cm\n\n\ndef _sk_cm_multiclass_prob(preds, target, normalize=None):\n sk_preds = torch.argmax(preds, dim=len(preds.shape) - 1).view(-1).numpy()\n sk_target = target.view(-1).numpy()\n\n return sk_confusion_matrix(y_true=sk_target, y_pred=sk_preds, normalize=normalize)\n\n\ndef _sk_cm_multiclass(preds, target, normalize=None):\n sk_preds = preds.view(-1).numpy()\n sk_target = target.view(-1).numpy()\n\n return sk_confusion_matrix(y_true=sk_target, y_pred=sk_preds, normalize=normalize)\n\n\ndef _sk_cm_multidim_multiclass_prob(preds, target, normalize=None):\n sk_preds = torch.argmax(preds, dim=len(preds.shape) - 2).view(-1).numpy()\n sk_target = target.view(-1).numpy()\n\n return sk_confusion_matrix(y_true=sk_target, y_pred=sk_preds, normalize=normalize)\n\n\ndef _sk_cm_multidim_multiclass(preds, target, normalize=None):\n sk_preds = preds.view(-1).numpy()\n sk_target = target.view(-1).numpy()\n\n return sk_confusion_matrix(y_true=sk_target, y_pred=sk_preds, normalize=normalize)\n\n\n@pytest.mark.parametrize(\"normalize\", [\"true\", \"pred\", \"all\", None])\n@pytest.mark.parametrize(\n \"preds, target, sk_metric, num_classes, multilabel\",\n [\n (_input_binary_prob.preds, _input_binary_prob.target, _sk_cm_binary_prob, 2, False),\n (_input_binary_logits.preds, _input_binary_logits.target, _sk_cm_binary_prob, 2, False),\n (_input_binary.preds, _input_binary.target, _sk_cm_binary, 2, False),\n (_input_mlb_prob.preds, _input_mlb_prob.target, _sk_cm_multilabel_prob, NUM_CLASSES, True),\n (_input_mlb_logits.preds, _input_mlb_logits.target, _sk_cm_multilabel_prob, NUM_CLASSES, True),\n (_input_mlb.preds, _input_mlb.target, _sk_cm_multilabel, NUM_CLASSES, True),\n (_input_mcls_prob.preds, _input_mcls_prob.target, _sk_cm_multiclass_prob, NUM_CLASSES, False),\n (_input_mcls_logits.preds, _input_mcls_logits.target, _sk_cm_multiclass_prob, NUM_CLASSES, False),\n (_input_mcls.preds, _input_mcls.target, _sk_cm_multiclass, NUM_CLASSES, False),\n (_input_mdmc_prob.preds, _input_mdmc_prob.target, _sk_cm_multidim_multiclass_prob, NUM_CLASSES, False),\n (_input_mdmc.preds, _input_mdmc.target, _sk_cm_multidim_multiclass, NUM_CLASSES, False),\n ],\n)\nclass TestConfusionMatrix(MetricTester):\n @pytest.mark.parametrize(\"ddp\", [True, False])\n @pytest.mark.parametrize(\"dist_sync_on_step\", [True, False])\n def test_confusion_matrix(\n self, normalize, preds, target, sk_metric, num_classes, multilabel, ddp, dist_sync_on_step\n ):\n self.run_class_metric_test(\n ddp=ddp,\n preds=preds,\n target=target,\n metric_class=ConfusionMatrix,\n sk_metric=partial(sk_metric, normalize=normalize),\n dist_sync_on_step=dist_sync_on_step,\n metric_args={\n \"num_classes\": num_classes,\n \"threshold\": THRESHOLD,\n \"normalize\": normalize,\n \"multilabel\": multilabel,\n },\n )\n\n def test_confusion_matrix_functional(self, normalize, preds, target, sk_metric, num_classes, multilabel):\n self.run_functional_metric_test(\n preds=preds,\n target=target,\n metric_functional=confusion_matrix,\n sk_metric=partial(sk_metric, normalize=normalize),\n metric_args={\n \"num_classes\": num_classes,\n \"threshold\": THRESHOLD,\n \"normalize\": normalize,\n \"multilabel\": multilabel,\n },\n )\n\n def test_confusion_matrix_differentiability(self, normalize, preds, target, sk_metric, num_classes, multilabel):\n self.run_differentiability_test(\n preds=preds,\n target=target,\n metric_module=ConfusionMatrix,\n metric_functional=confusion_matrix,\n metric_args={\n \"num_classes\": num_classes,\n \"threshold\": THRESHOLD,\n \"normalize\": normalize,\n \"multilabel\": multilabel,\n },\n )\n\n\ndef test_warning_on_nan(tmpdir):\n preds = torch.randint(3, size=(20,))\n target = torch.randint(3, size=(20,))\n\n with pytest.warns(\n UserWarning,\n match=\".* nan values found in confusion matrix have been replaced with zeros.\",\n ):\n confusion_matrix(preds, target, num_classes=5, normalize=\"true\")\n" ]
[ [ "torch.rand", "torch.isnan", "sklearn.metrics.mean_tweedie_deviance", "torch.cuda.is_available", "torch.tensor", "torch.randn" ], [ "torch.argsort", "torch.tensor" ], [ "sklearn.metrics.multilabel_confusion_matrix", "sklearn.metrics.confusion_matrix", "torch.randint", "numpy.isnan" ] ]
2xyo/msticpy
[ "54c6d74e0bb25528dd0347edb40c693dd7b1eac7" ]
[ "msticpy/analysis/eventcluster.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# --------------------------------------------------------------------------\nr\"\"\"\neventcluster module.\n\nThis module is intended to be used to summarize large numbers of events\ninto clusters of different patterns. High volume repeating events can\noften make it difficult to see unique and interesting items.\n\nThe module contains functions to generate clusterable features from\nstring data. For example, an administration command that does some\nmaintenance on thousands of servers with a commandline such as:\n``install-update -hostname {host.fqdn} -tmp:/tmp/{GUID}/rollback``\\ can\nbe collapsed into a single cluster pattern by ignoring the character\nvalues in the string and using delimiters or tokens to group the values.\n\nThis is an unsupervised learning module implemented using SciKit Learn\nDBScan.\n\nContains:\ndbcluster_events: generic clustering method using DBSCAN designed to summarize\nprocess events and other similar data by grouping on common features.\n\nadd_process_features: derives numerical features from text features such as\ncommandline and process path.\n\n\"\"\"\nfrom binascii import crc32\nfrom functools import lru_cache\nfrom math import log10, floor\nimport re\nfrom typing import List, Any, Tuple, Union\n\nimport numpy as np\nimport pandas as pd\n\nfrom ..common.exceptions import MsticpyImportExtraError\nfrom ..common.utility import export\nfrom .._version import VERSION\n\ntry:\n from sklearn.cluster import DBSCAN\n from sklearn.preprocessing import Normalizer\n import matplotlib.pyplot as plt\n from matplotlib import cm\nexcept ImportError as imp_err:\n raise MsticpyImportExtraError(\n \"Cannot use this feature without Sklearn and matplotlib installed\",\n title=\"Error importing Scikit Learn and matplotlib\",\n extra=\"ml\",\n ) from imp_err\n\n__version__ = VERSION\n__author__ = \"Ian Hellen\"\n\n\n# pylint: disable=too-many-arguments, too-many-locals\n@export\ndef dbcluster_events(\n data: Any,\n cluster_columns: List[Any] = None,\n verbose: bool = False,\n normalize: bool = True,\n time_column: str = \"TimeCreatedUtc\",\n max_cluster_distance: float = 0.01,\n min_cluster_samples: int = 2,\n **kwargs,\n) -> Tuple[pd.DataFrame, DBSCAN, np.ndarray]:\n \"\"\"\n Cluster data set according to cluster_columns features.\n\n Parameters\n ----------\n data : Any\n Input data as a pandas DataFrame or numpy array\n cluster_columns : List[Any], optional\n List of columns to use for features\n - for DataFrame this is a list of column names\n - for numpy array this is a list of column indexes\n verbose : bool, optional\n Print additional information about clustering results (the default is False)\n normalize : bool, optional\n Normalize the input data (should probably always be True)\n time_column : str, optional\n If there is a time column the output data will be ordered by this\n (the default is 'TimeCreatedUtc')\n max_cluster_distance : float, optional\n DBSCAN eps (max cluster member distance) (the default is 0.01)\n min_cluster_samples : int, optional\n DBSCAN min_samples (the minimum cluster size) (the default is 2)\n\n Other Parameters\n ----------------\n kwargs: Other arguments are passed to DBSCAN constructor\n\n Returns\n -------\n Tuple[pd.DataFrame, DBSCAN, np.ndarray]\n Output dataframe with clustered rows\n DBSCAN model\n Normalized data set\n\n \"\"\"\n allowed_types = [np.ndarray, pd.DataFrame]\n\n x_input = None\n if isinstance(data, pd.DataFrame):\n if cluster_columns is None:\n x_input = data.values\n else:\n x_input = data[cluster_columns].values\n elif isinstance(data, np.ndarray):\n x_input = data if cluster_columns is None else data[:, cluster_columns].values\n if x_input is None:\n mssg = \"Input data not in expected format.\\n{} is not one of allowed types {}\"\n type_list = \", \".join(str(t) for t in allowed_types)\n mssg = mssg.format(str(type(data)), type_list)\n raise ValueError(mssg)\n\n # Create DBSCAN cluster object\n db_cluster = DBSCAN(\n eps=max_cluster_distance, min_samples=min_cluster_samples, **kwargs\n )\n\n # Normalize the data (most clustering algorithms don't do well with\n # unnormalized data)\n x_norm = Normalizer().fit_transform(x_input) if normalize else x_input\n # fit the data set\n db_cluster.fit(x_norm)\n labels = db_cluster.labels_\n cluster_set, counts = np.unique(labels, return_counts=True)\n if verbose:\n print(\n \"Clustering for set size \",\n len(x_norm),\n \" - \",\n len(cluster_set),\n \" clusters\",\n )\n print(\"Individual cluster sizes: \", \", \".join(str(c) for c in counts))\n\n clustered_events = _merge_clustered_items(\n cluster_set, labels, data, time_column, counts\n )\n\n if verbose:\n print(\"Cluster output rows: \", len(clustered_events))\n\n return clustered_events, db_cluster, x_norm\n\n\ndef _merge_clustered_items(\n cluster_set: np.array,\n labels: np.array,\n data: Union[pd.DataFrame, np.array],\n time_column: str,\n counts: np.array,\n) -> pd.DataFrame:\n \"\"\"\n Merge outliers and core clusters into single DataFrame.\n\n Parameters\n ----------\n cluster_set : np.array\n The set of clusters\n labels : np.array\n The cluster labels\n data : Union[pd.DataFrame, np.array]\n The source data\n time_column : str\n Name of the Time column\n counts : np.array\n The counts of members in each cluster\n\n Returns\n -------\n pd.DataFrame\n Merged dataframe\n\n \"\"\"\n tz_aware = data.iloc[0][time_column].tz\n ts_type = \"datetime64[ns, UTC]\" if tz_aware is not None else \"datetime64[ns]\"\n\n cluster_list = []\n # Iterate through clusters, adding exemplar to output frame\n # pylint: disable=consider-using-enumerate\n # we need to know the index of the item within the loop\n for idx in range(len(cluster_set)):\n cluster_id = cluster_set[idx]\n class_members = labels == cluster_id\n if isinstance(data, pd.DataFrame):\n time_ordered = data[class_members].sort_values(time_column, ascending=True)\n first_event_time = time_ordered[0:][time_column].iat[0]\n last_event_time = time_ordered[-1:][time_column].iat[0]\n else:\n first_event_time = None\n last_event_time = None\n\n if cluster_id == -1:\n # 'Noise' events are individual items that could not be assigned\n # to a cluster and so are unique\n cluster_list.append(\n data[class_members]\n .assign(\n Clustered=False,\n ClusterId=cluster_id,\n ClusterSize=1,\n TimeGenerated=first_event_time,\n FirstEventTime=first_event_time,\n LastEventTime=last_event_time,\n )\n .astype(\n dtype={\n \"TimeGenerated\": ts_type,\n \"FirstEventTime\": ts_type,\n \"LastEventTime\": ts_type,\n }\n )\n )\n else:\n # Otherwise, just choose the first example of the cluster set\n cluster_list.append(\n data[class_members]\n .assign(\n Clustered=True,\n ClusterId=cluster_id,\n ClusterSize=counts[idx],\n TimeGenerated=first_event_time,\n FirstEventTime=first_event_time,\n LastEventTime=last_event_time,\n )[0:1]\n .astype(\n dtype={\n \"TimeGenerated\": ts_type,\n \"FirstEventTime\": ts_type,\n \"LastEventTime\": ts_type,\n }\n )\n )\n # pylint: enable=consider-using-enumerate\n return pd.concat(cluster_list)\n\n\n@export\ndef add_process_features(\n input_frame: pd.DataFrame, path_separator: str = None, force: bool = False\n) -> pd.DataFrame:\n r\"\"\"\n Add numerical features based on patterns of command line and process name.\n\n Parameters\n ----------\n input_frame : pd.DataFrame\n The input dataframe\n path_separator : str, optional\n Path separator. If not supplied, try to determine\n from 'NewProcessName' column of first 10 rows\n (the default is None)\n force : bool, optional\n Forces re-calculation of feature columns even if they\n already exist (the default is False)\n\n Returns\n -------\n pd.DataFrame\n Copy of the dataframe with the additional numeric features\n\n Notes\n -----\n Features added:\n\n - processNameLen: length of process file name (inc path)\n - processNameTokens: the number of elements in the path\n - processName: the process file name (minus path)\n - commandlineTokens: number of space-separated tokens in the command line\n - commandlineLen: length of the command line\n - commandlineLogLen: log10 length of commandline\n - isSystemSession: 1 if session Id is 0x3e7 for Windows or -1 for Linux\n - commandlineTokensFull: counts number of token separators in commandline\n [\\\\s\\-\\\\/\\.,\"\\'\\|&:;%$()]\n - pathScore: sum of ord() value of characters in path\n - pathLogScore: log10 of pathScore\n - commandlineScore: sum of ord() value of characters in commandline\n - commandlineLogScore: log10 of commandlineScore\n\n \"\"\"\n output_df = input_frame.copy()\n\n # Set any NaN values to empty string\n if \"NewProcessName\" in output_df and \"CommandLine\" in output_df:\n output_df[[\"NewProcessName\", \"CommandLine\"]] = output_df[\n [\"NewProcessName\", \"CommandLine\"]\n ].fillna(value=\"\")\n\n # try to determine the path separator\n if path_separator is None:\n sample_df = output_df.head(10)\n lx_path = len(sample_df[sample_df[\"NewProcessName\"].str.contains(\"/\")])\n path_separator = \"/\" if lx_path else \"\\\\\"\n # Create features from process name and command line\n if \"NewProcessName\" in output_df:\n _add_processname_features(output_df, force, path_separator)\n\n if \"CommandLine\" in output_df:\n _add_commandline_features(output_df, force)\n\n if \"SubjectLogonId\" in output_df and (\"isSystemSession\" not in output_df or force):\n output_df[\"isSystemSession\"] = output_df[\"SubjectLogonId\"].isin([\"0x3e7\", \"-1\"])\n\n return output_df\n\n\ndef _add_processname_features(\n output_df: pd.DataFrame, force: bool, path_separator: str\n):\n \"\"\"\n Add process name default features.\n\n Parameters\n ----------\n output_df : pd.DataFrame\n The dataframe to add features to\n force : bool\n If True overwrite existing feature columns\n path_separator : str\n Path separator for OS\n\n \"\"\"\n if \"processName\" not in output_df or force:\n output_df[\"processName\"] = output_df.apply(\n lambda x: x.NewProcessName.split(path_separator)[-1], axis=1\n )\n if \"pathScore\" not in output_df or force:\n output_df[\"pathScore\"] = output_df.apply(\n lambda x: char_ord_score(x.NewProcessName), axis=1\n )\n if \"pathLogScore\" not in output_df or force:\n output_df[\"pathLogScore\"] = output_df.apply(\n lambda x: log10(x.pathScore) if x.pathScore else 0, axis=1\n )\n if \"pathHash\" not in output_df or force:\n output_df[\"pathHash\"] = output_df.apply(\n lambda x: crc32_hash(x.NewProcessName), axis=1\n )\n\n\ndef _add_commandline_features(output_df: pd.DataFrame, force: bool):\n \"\"\"\n Add commandline default features.\n\n Parameters\n ----------\n output_df : pd.DataFrame\n The dataframe to add features to\n force : bool\n If True overwrite existing feature columns\n\n \"\"\"\n if \"commandlineLen\" not in output_df or force:\n output_df[\"commandlineLen\"] = output_df.apply(\n lambda x: len(x.CommandLine), axis=1\n )\n if \"commandlineLogLen\" not in output_df or force:\n output_df[\"commandlineLogLen\"] = output_df.apply(\n lambda x: log10(x.commandlineLen) if x.commandlineLen else 0, axis=1\n )\n if \"commandlineTokensFull\" not in output_df or force:\n output_df[\"commandlineTokensFull\"] = output_df[[\"CommandLine\"]].apply(\n lambda x: delim_count(x.CommandLine), axis=1\n )\n\n if \"commandlineScore\" not in output_df or force:\n output_df[\"commandlineScore\"] = output_df.apply(\n lambda x: char_ord_score(x.CommandLine), axis=1\n )\n if \"commandlineTokensHash\" not in output_df or force:\n output_df[\"commandlineTokensHash\"] = output_df.apply(\n lambda x: delim_hash(x.CommandLine), axis=1\n )\n\n\n@export\n@lru_cache(maxsize=1024)\ndef delim_count(value: str, delim_list: str = r'[\\s\\-\\\\/\\.,\"\\'|&:;%$()]') -> int:\n r\"\"\"\n Count the delimiters in input column.\n\n Parameters\n ----------\n value : str\n Data to process\n delim_list : str, optional\n delimiters to use. (the default is r'[\\\\s\\\\\\\\-\\\\\\\\\\\\\\\\/\\.,\"\\\\\\\\'|&:;%$()]')\n\n Returns\n -------\n int\n Count of delimiters in the string.\n\n \"\"\"\n return len(re.findall(delim_list, value))\n\n\n@export\n@lru_cache(maxsize=1024)\ndef delim_hash(value: str, delim_list: str = r'[\\s\\-\\\\/\\.,\"\\'|&:;%$()]') -> int:\n r\"\"\"\n Return a hash (CRC32) of the delimiters from input column.\n\n Parameters\n ----------\n value : str\n Data to process\n delim_list : str, optional\n delimiters to use. (the default is r'[\\\\s\\\\\\\\-\\\\\\\\\\\\\\\\/\\.,\"\\\\\\\\'|&:;%$()]')\n\n Returns\n -------\n int\n Hash of delimiter set in the string.\n\n \"\"\"\n return crc32(bytes(\"\".join(re.findall(delim_list, value)), \"utf-8\"))\n\n\n@export\n@lru_cache(maxsize=1024)\ndef char_ord_score(value: str, scale: int = 1) -> int:\n \"\"\"\n Return sum of ord values of characters in string.\n\n Parameters\n ----------\n value : str\n Data to process\n scale : int, optional\n reduce the scale of the feature (reducing the\n influence of variations this feature on the clustering\n algorithm (the default is 1)\n\n Returns\n -------\n int\n [description]\n\n Notes\n -----\n This function sums the ordinal value of each character in the\n input string. Two strings with minor differences will result in\n a similar score. However, for strings with highly variable content\n (e.g. command lines or http requests containing GUIDs) this may result\n in too much variance to be useful when you are trying to detect\n similar patterns. You can use the scale parameter to reduce the\n influence of features using this function on clustering and anomaly\n algorithms.\n\n \"\"\"\n return floor(sum(ord(x) for x in value) / scale)\n\n\n@export\n@lru_cache(maxsize=1024)\ndef token_count(value: str, delimiter: str = \" \") -> int:\n \"\"\"\n Return count of delimiter-separated tokens pd.Series column.\n\n Parameters\n ----------\n value : str\n Data to process\n delimiter : str, optional\n Delimiter used to split the column string.\n (the default is ' ')\n\n Returns\n -------\n int\n count of tokens\n\n \"\"\"\n return len(value.split(delimiter))\n\n\ndef _string_score(input_str):\n \"\"\"Sum the ord(c) for characters in a string.\"\"\"\n return sum(ord(x) for x in input_str)\n\n\n@export\n@lru_cache(maxsize=1024)\ndef crc32_hash(value: str) -> int:\n \"\"\"\n Return the CRC32 hash of the input column.\n\n Parameters\n ----------\n value : str\n Data to process\n\n Returns\n -------\n int\n CRC32 hash\n\n \"\"\"\n return crc32(bytes(value.encode(\"utf-8\")))\n\n\n@export\ndef delim_count_df(\n data: pd.DataFrame, column: str, delim_list: str = r'[\\s\\-\\\\/\\.,\"\\'|&:;%$()]'\n) -> pd.Series:\n r\"\"\"\n Count the delimiters in input column.\n\n Parameters\n ----------\n data : pd.DataFrame\n The DataFrame to process\n column : str\n The name of the column to process\n delim_list : str, optional\n delimiters to use. (the default is r\\'[\\\\s\\\\\\\\-\\\\\\\\\\\\\\\\/\\.,\"\\\\\\\\'|&:;%$()]\\')\n\n Returns\n -------\n pd.Series\n Count of delimiters in the string in `column`.\n\n \"\"\"\n return data[column].str.count(delim_list)\n\n\n@export\ndef char_ord_score_df(data: pd.DataFrame, column: str, scale: int = 1) -> pd.Series:\n \"\"\"\n Return sum of ord values of characters in string.\n\n Parameters\n ----------\n data : pd.DataFrame\n The DataFrame to process\n column : str\n Column name to process\n scale : int, optional\n reduce the scale of the feature (reducing the\n influence of variations this feature on the clustering\n algorithm (the default is 1)\n\n Returns\n -------\n pd.Series\n The sum of the ordinal values of the characters\n in `column`.\n\n Notes\n -----\n This function sums the ordinal value of each character in the\n input string. Two strings with minor differences will result in\n a similar score. However, for strings with highly variable content\n (e.g. command lines or http requests containing GUIDs) this may result\n in too much variance to be useful when you are trying to detect\n similar patterns. You can use the scale parameter to reduce the\n influence of features using this function on clustering and anomaly\n algorithms.\n\n \"\"\"\n return data.apply(lambda x: sum(ord(char) for char in x[column]) / scale, axis=1)\n\n\n@export\ndef token_count_df(data: pd.DataFrame, column: str, delimiter: str = \" \") -> pd.Series:\n \"\"\"\n Return count of delimiter-separated tokens pd.Series column.\n\n Parameters\n ----------\n data : pd.DataFrame\n The DataFrame to process\n column : str\n Column name to process\n delimiter : str, optional\n Delimiter used to split the column string.\n (the default is ' ')\n\n Returns\n -------\n pd.Series\n count of tokens in strings in `column`\n\n \"\"\"\n return data.apply(lambda x: len(x[column].split(delimiter)), axis=1)\n\n\n@export\ndef crc32_hash_df(data: pd.DataFrame, column: str) -> pd.Series:\n \"\"\"\n Return the CRC32 hash of the input column.\n\n Parameters\n ----------\n data : pd.DataFrame\n The DataFrame to process\n column : str\n Column name to process\n\n Returns\n -------\n pd.Series\n CRC32 hash of input column\n\n \"\"\"\n return data.apply(lambda x: crc32(bytes(x[column].encode(\"utf-8\"))), axis=1)\n\n\n# pylint: disable=too-many-arguments, too-many-statements\n@export # noqa: C901, MC0001\ndef plot_cluster(\n db_cluster: DBSCAN,\n data: pd.DataFrame,\n x_predict: np.ndarray,\n plot_label: str = None,\n plot_features: Tuple[int, int] = (0, 1),\n verbose: bool = False,\n cut_off: int = 3,\n xlabel: str = None,\n ylabel: str = None,\n):\n \"\"\"\n Plot clustered data as scatter chart.\n\n Parameters\n ----------\n db_cluster : DBSCAN\n DBScan Cluster (from SkLearn DBSCAN).\n data : pd.DataFrame\n Dataframe containing original data.\n x_predict : np.ndarray\n The DBSCAN predict numpy array\n plot_label : str, optional\n If set the column to use to label data points\n (the default is None)\n plot_features : Tuple[int, int], optional\n Which two features in x_predict to plot (the default is (0, 1))\n verbose : bool, optional\n Verbose execution with some extra info\n (the default is False)\n cut_off : int, optional\n The cluster size below which items are considered outliers\n (the default is 3)\n xlabel : str, optional\n x-axis label (the default is None)\n ylabel : str, optional\n y-axis label (the default is None)\n\n \"\"\"\n max_idx = x_predict.shape[1] - 1\n if plot_features[0] >= x_predict.shape[1]:\n raise ValueError(\n \"plot_features[0] index must be a value from 0 to {}.\".format(max_idx)\n )\n if plot_features[1] >= x_predict.shape[1]:\n raise ValueError(\n \"plot_features[1] index must be a value from 0 to {}.\".format(max_idx)\n )\n if plot_features[0] == plot_features[1]:\n mssg = \"plot_features indexes must be 2 different values in range 0 to\"\n raise ValueError(mssg + f\" {max_idx}.\")\n\n labels = db_cluster.labels_\n core_samples_mask = np.zeros_like(labels, dtype=bool)\n\n # pylint: disable=unsupported-assignment-operation\n # (assignment of numpy array is valid)\n core_samples_mask[db_cluster.core_sample_indices_] = True\n unique_labels = set(labels)\n\n # pylint: disable=no-member\n # Spectral color map does exist\n colors = [cm.Spectral(each) for each in np.linspace(0, 1, len(unique_labels))]\n # Number of clusters in labels, ignoring noise if present.\n n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)\n n_noise_ = list(labels).count(-1)\n _, counts = np.unique(labels, return_counts=True)\n\n if verbose:\n print(\"Estimated number of clusters: %d\" % n_clusters_)\n print(\"Estimated number of noise points: %d\" % n_noise_)\n # print(\"Silhouette Coefficient: %0.3f\"\n # % metrics.silhouette_score(x_predict, labels))\n\n if (\n not isinstance(data, pd.DataFrame)\n or plot_label is not None\n and plot_label not in data\n ):\n plot_label = None\n p_label = None\n for cluster_id, color in zip(unique_labels, colors):\n if cluster_id == -1:\n # Black used for noise.\n color = [0, 0, 0, 1]\n class_member_mask = labels == cluster_id\n\n cluster_size = counts[cluster_id]\n marker_size = cluster_size\n marker = \"o\"\n font_size = \"small\"\n alpha = 0.4\n\n if cluster_size < cut_off:\n marker = \"+\"\n marker_size = 10\n font_size = \"large\"\n alpha = 1.0\n xy_pos = x_predict[class_member_mask & core_samples_mask]\n plt.plot(\n xy_pos[:, plot_features[0]],\n xy_pos[:, plot_features[1]],\n marker,\n markerfacecolor=tuple(color),\n markersize=marker_size,\n )\n\n if plot_label:\n first_row = data[class_member_mask].iloc[0]\n if not first_row.empty and plot_label in first_row:\n p_label = first_row[plot_label]\n try:\n plt.annotate(\n p_label,\n xy=(xy_pos[0, plot_features[0]], xy_pos[0, plot_features[1]]),\n fontsize=font_size,\n alpha=alpha,\n )\n except IndexError:\n pass\n\n plt.xlabel(xlabel)\n plt.ylabel(ylabel)\n plt.title(\"Estimated number of clusters: %d\" % n_clusters_)\n plt.show()\n return plt\n" ]
[ [ "numpy.zeros_like", "sklearn.preprocessing.Normalizer", "matplotlib.pyplot.annotate", "matplotlib.pyplot.xlabel", "matplotlib.cm.Spectral", "matplotlib.pyplot.title", "sklearn.cluster.DBSCAN", "matplotlib.pyplot.ylabel", "pandas.concat", "matplotlib.pyplot.show", "numpy.unique" ] ]
wyyy04/scene-graph-TF-release
[ "4c9e3c6a5cb0e6a241a92dc9b786f74e69ca35c4" ]
[ "lib/roi_data_layer/minibatch.py" ]
[ "# --------------------------------------------------------\n# Adapted from Faster R-CNN (https://github.com/rbgirshick/py-faster-rcnn)\n# Written by Danfei Xu\n# --------------------------------------------------------\n\n\"\"\"Compute minibatch blobs for training a Fast R-CNN network.\"\"\"\n\nimport numpy as np\nimport numpy.random as npr\nfrom fast_rcnn.config import cfg\nfrom utils.blob import prep_im_for_blob, im_list_to_blob\n#from datasets.viz import viz_scene_graph\nimport data_utils\nfrom IPython import embed\nfrom utils.timer import Timer\n\ndef get_minibatch(roidb, num_classes):\n \"\"\"Given a mini batch of roidb, construct a data blob from it.\"\"\"\n num_images = len(roidb)\n # Sample random scales to use for each image in this batch\n random_scale_inds = npr.randint(0, high=len(cfg.TRAIN.SCALES),\n size=num_images)\n assert(cfg.TRAIN.BATCH_SIZE % num_images == 0), \\\n 'num_images ({}) must divide BATCH_SIZE ({})'. \\\n format(num_images, cfg.TRAIN.BATCH_SIZE)\n rois_per_image = cfg.TRAIN.BATCH_SIZE / num_images\n fg_rois_per_image = np.round(cfg.TRAIN.FG_FRACTION * rois_per_image)\n\n im_timer = Timer()\n im_timer.tic()\n im_blob, im_scales = _get_image_blob(roidb, random_scale_inds)\n im_timer.toc()\n\n blobs = {'ims': im_blob}\n\n # Now, build the region of interest and label blobs\n rois_blob = np.zeros((0, 5), dtype=np.float32)\n labels_blob = np.zeros((0), dtype=np.float32)\n rels_blob = np.zeros((0, 3), dtype=np.int32)\n bbox_targets_blob = np.zeros((0, 4 * num_classes), dtype=np.float32)\n bbox_inside_blob = np.zeros(bbox_targets_blob.shape, dtype=np.float32)\n all_overlaps = []\n\n box_idx_offset = 0\n\n d_timer = Timer()\n d_timer.tic()\n for im_i in xrange(num_images):\n # sample graph\n roi_inds, rels = _sample_graph(roidb[im_i],\n fg_rois_per_image,\n rois_per_image,\n num_neg_rels=cfg.TRAIN.NUM_NEG_RELS)\n if rels.size == 0:\n print('batch skipped')\n return None\n\n # gather all samples based on the sampled graph\n rels, labels, overlaps, im_rois, bbox_targets, bbox_inside_weights =\\\n _gather_samples(roidb[im_i], roi_inds, rels, num_classes)\n\n # Add to RoIs blob\n rois = _project_im_rois(im_rois, im_scales[im_i])\n\n batch_ind = im_i * np.ones((rois.shape[0], 1)) #im id for roi_pooling\n rois_blob_this_image = np.hstack((batch_ind, rois))\n rois_blob = np.vstack((rois_blob, rois_blob_this_image))\n # Add to labels, bbox targets, and bbox loss blobs\n labels_blob = np.hstack((labels_blob, labels))\n bbox_targets_blob = np.vstack((bbox_targets_blob, bbox_targets))\n bbox_inside_blob = np.vstack((bbox_inside_blob, bbox_inside_weights))\n all_overlaps = np.hstack((all_overlaps, overlaps))\n\n # offset the relationship reference idx the number of previously\n # added box\n rels_offset = rels.copy()\n rels_offset[:, :2] += box_idx_offset\n rels_blob = np.vstack([rels_blob, rels_offset])\n box_idx_offset += rois.shape[0]\n\n #viz_inds = np.where(overlaps == 1)[0] # ground truth\n #viz_inds = npr.choice(np.arange(rois.shape[0]), size=50, replace=False) # random sample\n #viz_inds = np.where(overlaps > cfg.TRAIN.FG_THRESH)[0] # foreground\n #viz_scene_graph(im_blob[im_i], rois, labels, viz_inds, rels)\n\n blobs['rois'] = rois_blob.copy()\n blobs['labels'] = labels_blob.copy().astype(np.int32)\n blobs['relations'] = rels_blob[:,:2].copy().astype(np.int32)\n blobs['predicates'] = rels_blob[:,2].copy().astype(np.int32)\n blobs['bbox_targets'] = bbox_targets_blob.copy()\n blobs['bbox_inside_weights'] = bbox_inside_blob.copy()\n blobs['bbox_outside_weights'] = \\\n np.array(bbox_inside_blob > 0).astype(np.float32).copy()\n\n\n num_roi = rois_blob.shape[0]\n num_rel = rels_blob.shape[0]\n blobs['rel_rois'] = data_utils.compute_rel_rois(num_rel,\n rois_blob,\n rels_blob)\n\n d_timer.toc()\n graph_dict = data_utils.create_graph_data(num_roi, num_rel, rels_blob[:, :2])\n\n for k in graph_dict:\n blobs[k] = graph_dict[k]\n\n return blobs\n\ndef _gather_samples(roidb, roi_inds, rels, num_classes):\n \"\"\"\n join all samples and produce sampled items\n \"\"\"\n rois = roidb['boxes']\n labels = roidb['max_classes']\n overlaps = roidb['max_overlaps']\n\n # decide bg rois\n bg_inds = np.where(overlaps < cfg.TRAIN.FG_THRESH)[0]\n\n labels = labels.copy()\n labels[bg_inds] = 0\n labels = labels[roi_inds]\n # print('num bg = %i' % np.where(labels==0)[0].shape[0])\n\n # rois and bbox targets\n overlaps = overlaps[roi_inds]\n rois = rois[roi_inds]\n\n # convert rel index\n roi_ind_map = {}\n for i, roi_i in enumerate(roi_inds):\n roi_ind_map[roi_i] = i\n for i, rel in enumerate(rels):\n rels[i] = [roi_ind_map[rel[0]], roi_ind_map[rel[1]], rel[2]]\n\n bbox_targets, bbox_inside_weights = _get_bbox_regression_labels(\n roidb['bbox_targets'][roi_inds, :], num_classes)\n\n return rels, labels, overlaps, rois, bbox_targets, bbox_inside_weights\n\ndef _sample_graph(roidb, num_fg_rois, num_rois, num_neg_rels=128):\n \"\"\"\n Sample a graph from the foreground rois of an image\n\n roidb: roidb of an image\n rois_per_image: maximum number of rois per image\n \"\"\"\n\n gt_rels = roidb['gt_relations']\n # index of assigned gt box for foreground boxes\n fg_gt_ind_assignments = roidb['fg_gt_ind_assignments']\n\n # find all fg proposals that are mapped to a gt\n gt_to_fg_roi_inds = {}\n all_fg_roi_inds = []\n for ind, gt_ind in fg_gt_ind_assignments.items():\n if gt_ind not in gt_to_fg_roi_inds:\n gt_to_fg_roi_inds[gt_ind] = []\n gt_to_fg_roi_inds[gt_ind].append(ind)\n all_fg_roi_inds.append(ind)\n\n # print('gt rois = %i' % np.where(roidb['max_overlaps']==1)[0].shape[0])\n # print('assigned gt = %i' % len(gt_to_fg_roi_inds.keys()))\n # dedup the roi inds\n all_fg_roi_inds = np.array(list(set(all_fg_roi_inds)))\n\n # find all valid relations in fg objects\n pos_rels = []\n for rel in gt_rels:\n for sub_i in gt_to_fg_roi_inds[rel[0]]:\n for obj_i in gt_to_fg_roi_inds[rel[1]]:\n pos_rels.append([sub_i, obj_i, rel[2]])\n\n # print('num fg rois = %i' % all_fg_roi_inds.shape[0])\n\n rels = []\n rels_inds = []\n roi_inds = []\n\n if len(pos_rels) > 0:\n # de-duplicate the relations\n _, indices = np.unique([\"{} {}\".format(i, j) for i,j,k in pos_rels], return_index=True)\n pos_rels = np.array(pos_rels)[indices, :]\n # print('num pos rels = %i' % pos_rels.shape[0])\n\n # construct graph based on valid relations\n for rel in pos_rels:\n roi_inds += rel[:2].tolist()\n roi_inds = list(set(roi_inds)) # keep roi inds unique\n rels.append(rel)\n rels_inds.append(rel[:2].tolist())\n\n if len(roi_inds) >= num_fg_rois:\n break\n\n # print('sampled rels = %i' % len(rels))\n\n roi_candidates = np.setdiff1d(all_fg_roi_inds, roi_inds)\n num_rois_to_sample = min(num_fg_rois - len(roi_inds), len(roi_candidates))\n # if not enough rois, sample fg rois\n if num_rois_to_sample > 0:\n roi_sample = npr.choice(roi_candidates, size=num_rois_to_sample,\n replace=False)\n roi_inds = np.hstack([roi_inds, roi_sample])\n\n # sample background relations\n sample_rels = []\n sample_rels_inds = []\n for i in roi_inds:\n for j in roi_inds:\n if i != j and [i, j] not in rels_inds:\n sample_rels.append([i,j,0])\n sample_rels_inds.append([i,j])\n\n if len(sample_rels) > 0:\n # randomly sample negative edges to prevent no edges\n num_neg_rels = np.minimum(len(sample_rels), num_neg_rels)\n inds = npr.choice(np.arange(len(sample_rels)), size=num_neg_rels, replace=False)\n rels += [sample_rels[i] for i in inds]\n rels_inds += [sample_rels_inds[i] for i in inds]\n\n\n # if still not enough rois, sample bg rois\n num_rois_to_sample = num_rois - len(roi_inds)\n if num_rois_to_sample > 0:\n bg_roi_inds = _sample_bg_rois(roidb, num_rois_to_sample)\n roi_inds = np.hstack([roi_inds, bg_roi_inds])\n\n roi_inds = np.array(roi_inds).astype(np.int64)\n # print('sampled rois = %i' % roi_inds.shape[0])\n return roi_inds.astype(np.int64), np.array(rels).astype(np.int64)\n\ndef _sample_bg_rois(roidb, num_bg_rois):\n \"\"\"\n Sample rois from background\n \"\"\"\n # label = class RoI has max overlap with\n labels = roidb['max_classes']\n overlaps = roidb['max_overlaps']\n\n bg_inds = np.where(((overlaps < cfg.TRAIN.BG_THRESH_HI) &\n (overlaps >= cfg.TRAIN.BG_THRESH_LO)) |\n (labels == 0))[0]\n bg_rois_per_this_image = np.minimum(num_bg_rois, bg_inds.size)\n if bg_inds.size > 0:\n bg_inds = npr.choice(bg_inds, size=bg_rois_per_this_image, replace=False)\n\n return bg_inds\n\ndef _get_image_blob(roidb, scale_inds):\n \"\"\"Builds an input blob from the images in the roidb at the specified\n scales.\n \"\"\"\n num_images = len(roidb)\n processed_ims = []\n im_scales = []\n for i in xrange(num_images):\n im = roidb[i]['image']() # use image getter\n\n if roidb[i]['flipped']:\n im = im[:, ::-1, :]\n target_size = cfg.TRAIN.SCALES[scale_inds[i]]\n im, im_scale = prep_im_for_blob(im, cfg.PIXEL_MEANS, target_size,\n cfg.TRAIN.MAX_SIZE)\n im_scales.append(im_scale)\n processed_ims.append(im)\n\n # Create a blob to hold the input images\n blob = im_list_to_blob(processed_ims)\n\n return blob, im_scales\n\ndef _project_im_rois(im_rois, im_scale_factor):\n \"\"\"Project image RoIs into the rescaled training image.\"\"\"\n rois = im_rois * im_scale_factor\n return rois\n\ndef _get_bbox_regression_labels(bbox_target_data, num_classes):\n \"\"\"Bounding-box regression targets are stored in a compact form in the\n roidb.\n\n This function expands those targets into the 4-of-4*K representation used\n by the network (i.e. only one class has non-zero targets). The loss weights\n are similarly expanded.\n\n Returns:\n bbox_target_data (ndarray): N x 4K blob of regression targets\n bbox_inside_weights (ndarray): N x 4K blob of loss weights\n \"\"\"\n clss = bbox_target_data[:, 0]\n bbox_targets = np.zeros((clss.size, 4 * num_classes), dtype=np.float32)\n bbox_inside_weights = np.zeros(bbox_targets.shape, dtype=np.float32)\n inds = np.where(clss > 0)[0]\n for ind in inds:\n cls = clss[ind].astype(np.int64)\n start = 4 * cls\n end = start + 4\n bbox_targets[ind, start:end] = bbox_target_data[ind, 1:]\n bbox_inside_weights[ind, start:end] = cfg.TRAIN.BBOX_INSIDE_WEIGHTS\n return bbox_targets, bbox_inside_weights\n" ]
[ [ "numpy.array", "numpy.random.choice", "numpy.setdiff1d", "numpy.zeros", "numpy.minimum", "numpy.round", "numpy.ones", "numpy.where", "numpy.hstack", "numpy.vstack" ] ]
James-P-D/Maze
[ "95a142379bce4da21b3a49a7c0ece26f355e582c" ]
[ "src/MazePy/MazePy/MazePy.py" ]
[ "import pygame # Tested with pygame v1.9.6\nfrom UIControls import Button\nfrom constants import *\nimport numpy as np\nimport random\nimport time\nimport os\nfrom nodes import bfs_node\nimport sys\nimport threading\n\n\n###############################################\n# Globals\n###############################################\n\ninitial_cell_row = 0\ninitial_cell_col = 0\ninitial_cell_dragging = False\n\nterminal_cell_row = ROWS - 1\nterminal_cell_col = COLS - 1\nterminal_cell_dragging = False\n\ngrid = np.ndarray((COLS, ROWS), np.int8)\n\nscreen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))\n\nclear_button = Button((BUTTON_WIDTH * 0),\n BUTTON_STRIP_TOP,\n BUTTON_WIDTH,\n BUTTON_STRIP_HEIGHT,\n CLEAR_BUTTON_LABEL)\ncreate_button = Button((BUTTON_WIDTH * 1),\n BUTTON_STRIP_TOP,\n BUTTON_WIDTH,\n BUTTON_STRIP_HEIGHT,\n CREATE_BUTTON_LABEL)\ndfs_button = Button((BUTTON_WIDTH * 2),\n BUTTON_STRIP_TOP,\n BUTTON_WIDTH,\n BUTTON_STRIP_HEIGHT,\n DFS_BUTTON_LABEL)\nbfs_button = Button((BUTTON_WIDTH * 3),\n BUTTON_STRIP_TOP,\n BUTTON_WIDTH,\n BUTTON_STRIP_HEIGHT,\n BFS_BUTTON_LABEL)\nquit_button = Button((BUTTON_WIDTH * 4),\n BUTTON_STRIP_TOP,\n BUTTON_WIDTH,\n BUTTON_STRIP_HEIGHT,\n QUIT_BUTTON_LABEL)\n\nprocessing = False\n\n\n###############################################\n# initialise()\n###############################################\n\ndef initialise():\n global processing\n processing = True\n # Set all cells to EMPTY by default\n for col in range(COLS):\n for row in range(ROWS):\n grid[col, row] = EMPTY\n\n # Set the Initial and Terminal cells\n grid[initial_cell_col, initial_cell_row] = INITIAL\n grid[terminal_cell_col, terminal_cell_row] = TERMINAL\n # print(grid)\n\n processing = False\n\n\n###############################################\n# create_ui()\n###############################################\n\ndef create_ui():\n screen.fill(BLACK)\n\n clear_button.draw(screen)\n create_button.draw(screen)\n dfs_button.draw(screen)\n bfs_button.draw(screen)\n quit_button.draw(screen)\n\n draw_grid()\n\n\n###############################################\n# draw_grid()\n###############################################\n\ndef draw_grid():\n for col in range(COLS):\n for row in range(ROWS):\n # Only set the Initial cell if we are NOT dragging\n if (grid[col, row] == INITIAL and not initial_cell_dragging):\n draw_cell(INITIAL_CELL_COLOR, col, row)\n # Only set the Terminal cell if we are NOT dragging\n elif (grid[col, row] == TERMINAL and not terminal_cell_dragging):\n draw_cell(TERMINAL_CELL_COLOR, col, row)\n elif (grid[col, row] == WALL):\n draw_cell(WALL_CELL_COLOR, col, row)\n elif (grid[col, row] == VISITED):\n draw_cell(VISITED_CELL_COLOR, col, row)\n elif (grid[col, row] == PATH):\n draw_cell(PATH_CELL_COLOR, col, row)\n else: # (grid[col, row] == EMPTY)\n draw_cell(EMPTY_CELL_COLOR, col, row)\n\n if (initial_cell_dragging):\n (mouse_x, mouse_y) = pygame.mouse.get_pos()\n cell_col = int(mouse_x / CELL_WIDTH)\n cell_row = int(mouse_y / CELL_HEIGHT)\n # Check the current mouse-pointer for the dragging\n # motion is actually on the board\n if (valid_cell(cell_col, cell_row)):\n draw_cell(INITIAL_CELL_COLOR,\n cell_col,\n cell_row)\n elif (terminal_cell_dragging):\n (mouse_x, mouse_y) = pygame.mouse.get_pos()\n cell_col = int(mouse_x / CELL_WIDTH)\n cell_row = int(mouse_y / CELL_HEIGHT)\n # Check the current mouse-pointer for the dragging motion\n # is actually on the board\n if (valid_cell(cell_col, cell_row)):\n draw_cell(TERMINAL_CELL_COLOR, cell_col, cell_row)\n\n\n###############################################\n# game_loop()\n###############################################\n\ndef game_loop():\n game_exit = False\n clock = pygame.time.Clock()\n\n global initial_cell_row\n global initial_cell_col\n global initial_cell_dragging\n\n global terminal_cell_row\n global terminal_cell_col\n global terminal_cell_dragging\n\n while not game_exit:\n for event in pygame.event.get():\n if (event.type == pygame.QUIT) and (not processing):\n game_exit = True\n elif (event.type == pygame.MOUSEBUTTONDOWN) and (not processing):\n (mouse_x, mouse_y) = pygame.mouse.get_pos()\n cell_col = int(mouse_x / CELL_WIDTH)\n cell_row = int(mouse_y / CELL_HEIGHT)\n if (valid_cell(cell_col, cell_row)):\n if (grid[cell_col, cell_row] == INITIAL):\n # Set the flag for dragging the Initial cell\n initial_cell_dragging = True\n elif (grid[cell_col, cell_row] == TERMINAL):\n # Set the flag for dragging the Terminal cell\n terminal_cell_dragging = True\n elif (not (initial_cell_dragging\n or terminal_cell_dragging)):\n # Otherwise, if we have clicked with mouse and\n # we are not dragging anything, toggle\n # the current cell between EMPTY and WALL\n if (grid[cell_col, cell_row] == WALL):\n grid[cell_col, cell_row] = EMPTY\n elif (grid[cell_col, cell_row] == EMPTY):\n grid[cell_col, cell_row] = WALL\n elif (event.type == pygame.MOUSEBUTTONUP) and (not processing):\n if clear_button.is_over(mouse_x, mouse_y):\n thread = threading.Thread(target=initialise,\n args=())\n thread.start()\n elif create_button.is_over(mouse_x, mouse_y):\n thread = threading.Thread(target=create_maze,\n args=())\n thread.start()\n elif dfs_button.is_over(mouse_x, mouse_y):\n thread = threading.Thread(target=depth_first_search,\n args=())\n thread.start()\n elif bfs_button.is_over(mouse_x, mouse_y):\n thread = threading.Thread(target=breadth_first_search,\n args=())\n thread.start()\n elif quit_button.is_over(mouse_x, mouse_y):\n game_exit = True\n elif initial_cell_dragging:\n (mouse_x, mouse_y) = pygame.mouse.get_pos()\n cell_col = int(mouse_x / CELL_WIDTH)\n cell_row = int(mouse_y / CELL_HEIGHT)\n # Make sure we have not dragged the\n # Initial cell off the screen\n if (valid_cell(cell_col, cell_row)):\n # Also make sure we aren't trying to drag Initial\n # cell on top of Terminal cell\n if (not((cell_col == terminal_cell_col) and\n (cell_row == terminal_cell_row))):\n grid[initial_cell_col, initial_cell_row] = EMPTY\n initial_cell_col = cell_col\n initial_cell_row = cell_row\n grid[initial_cell_col, initial_cell_row] = INITIAL\n # Whatever happens, cancel the dragging flag\n initial_cell_dragging = False\n elif terminal_cell_dragging:\n (mouse_x, mouse_y) = pygame.mouse.get_pos()\n cell_col = int(mouse_x / CELL_WIDTH)\n cell_row = int(mouse_y / CELL_HEIGHT)\n # Make sure we have not dragged the\n # Terminal cell off the screen\n if (valid_cell(cell_col, cell_row)):\n # Also make sure we aren't trying to drag Terminal\n # cell on top of Initial cell\n if (not((cell_col == initial_cell_col) and\n (cell_row == initial_cell_row))):\n grid[terminal_cell_col, terminal_cell_row] = EMPTY\n terminal_cell_col = cell_col\n terminal_cell_row = cell_row\n grid[terminal_cell_col, terminal_cell_row] = TERMINAL\n # Whatever happens, cancel the dragging flag\n terminal_cell_dragging = False\n\n draw_grid()\n pygame.display.update()\n clock.tick(CLOCK_TICK)\n pygame.quit()\n\n\n###############################################\n# create_maze()\n###############################################\n\ndef create_maze():\n\n ###############################################\n # make_holes()\n ###############################################\n\n def make_holes(col1, row1, col2, row2, vertical, horizontal):\n # print(f\"\\tmake_holes({col1},\n # {row1},\n # {col2},\n # {row2},\n # {vertical},\n # {horizontal})\")\n\n all_lists = []\n\n list = []\n for row in range(row1, horizontal):\n if (has_horizontal_empty(vertical, row)):\n list.append((vertical, row))\n if (len(list) > 0):\n all_lists.append(list)\n\n list = []\n for row in range(horizontal + 1, row2):\n if (has_horizontal_empty(vertical, row)):\n list.append((vertical, row))\n if (len(list) > 0):\n all_lists.append(list)\n\n list = []\n for col in range(col1, vertical):\n if (has_vertical_empty(col, horizontal)):\n list.append((col, horizontal))\n if (len(list) > 0):\n all_lists.append(list)\n\n list = []\n for col in range(vertical + 1, col2):\n if (has_vertical_empty(col, horizontal)):\n list.append((col, horizontal))\n if (len(list) > 0):\n all_lists.append(list)\n\n if (len(all_lists) == 4):\n item_index_to_remove = random.randint(0, 3)\n del (all_lists[item_index_to_remove])\n\n for sub_list in all_lists:\n (hole_col, hole_row) = sub_list[\n random.randint(0, len(sub_list) - 1)]\n draw_cell(EMPTY_CELL_COLOR, hole_col, hole_row)\n grid[hole_col, hole_row] = EMPTY\n\n ###############################################\n # divide()\n ###############################################\n\n def divide(col1, row1, col2, row2):\n # print(f\"divide({col1}, {row1}, {col2}, {row2})\")\n vertical = col2\n if ((col2 - col1) > 2):\n vertical = int(((col2 - col1) / 2) + col1)\n\n for row in range(row1, row2):\n draw_cell(WALL_CELL_COLOR, vertical, row)\n grid[vertical, row] = WALL\n\n horizontal = row2\n if ((row2 - row1) > 2):\n horizontal = int(((row2 - row1) / 2) + row1)\n\n for col in range(col1, col2):\n draw_cell(WALL_CELL_COLOR, col, horizontal)\n grid[col, horizontal] = WALL\n\n # top-left\n new_col1 = col1\n new_row1 = row1\n new_col2 = vertical\n new_row2 = horizontal\n if (((new_col2 - new_col1) > 2) or ((new_row2 - new_row1) > 2)):\n (new_vertical, new_horizontal) = divide(new_col1,\n new_row1,\n new_col2,\n new_row2)\n make_holes(new_col1,\n new_row1,\n new_col2,\n new_row2,\n new_vertical,\n new_horizontal)\n\n # top-right\n new_col1 = vertical + 1\n new_row1 = row1\n new_col2 = col2\n new_row2 = horizontal\n if (((new_col2 - new_col1) > 2) or ((new_row2 - new_row1) > 2)):\n (new_vertical, new_horizontal) = divide(new_col1,\n new_row1,\n new_col2,\n new_row2)\n make_holes(new_col1,\n new_row1,\n new_col2,\n new_row2,\n new_vertical,\n new_horizontal)\n\n # bottom-left\n new_col1 = col1\n new_row1 = horizontal + 1\n new_col2 = vertical\n new_row2 = row2\n if (((new_col2 - new_col1) > 2) or ((new_row2 - new_row1) > 2)):\n (new_vertical, new_horizontal) = divide(new_col1,\n new_row1,\n new_col2,\n new_row2)\n make_holes(new_col1,\n new_row1,\n new_col2,\n new_row2,\n new_vertical,\n new_horizontal)\n\n # bottom-right\n new_col1 = vertical + 1\n new_row1 = horizontal + 1\n new_col2 = col2\n new_row2 = row2\n if (((new_col2 - new_col1) > 2) or ((new_row2 - new_row1) > 2)):\n (new_vertical, new_horizontal) = divide(new_col1,\n new_row1,\n new_col2,\n new_row2)\n make_holes(new_col1,\n new_row1,\n new_col2,\n new_row2,\n new_vertical,\n new_horizontal)\n\n time.sleep(SMALL_SLEEP)\n pygame.display.update()\n\n return (vertical, horizontal)\n\n global processing\n processing = True\n initialise()\n draw_grid()\n\n (new_vertical, new_horizontal) = divide(0, 0, COLS, ROWS)\n make_holes(0, 0, COLS, ROWS, new_vertical, new_horizontal)\n grid[initial_cell_col, initial_cell_row] = INITIAL\n grid[terminal_cell_col, terminal_cell_row] = TERMINAL\n\n processing = False\n\n\n###############################################\n# has_horizontal_neighbours()\n###############################################\n\ndef has_horizontal_neighbours(col, row, cell_types):\n left_col = col - 1\n right_col = col + 1\n if (left_col >= 0) and (right_col < COLS):\n return ((grid[left_col, row] in cell_types) and\n (grid[right_col, row] in cell_types))\n\n return False\n\n\n###############################################\n# has_vertical_neighbours()\n###############################################\n\ndef has_vertical_neighbours(col, row, cell_types):\n above_row = row - 1\n below_row = row + 1\n if (above_row >= 0) and (below_row < ROWS):\n return ((grid[col, above_row] in cell_types) and\n (grid[col, below_row] in cell_types))\n\n return False\n\n\n###############################################\n# has_horizontal_empty()\n###############################################\n\ndef has_horizontal_empty(col, row):\n return has_horizontal_neighbours(col, row, [EMPTY, INITIAL, TERMINAL])\n\n\n###############################################\n# has_vertical_empty()\n###############################################\n\ndef has_vertical_empty(col, row):\n return has_vertical_neighbours(col, row, [EMPTY, INITIAL, TERMINAL])\n\n\n###############################################\n# reset_maze()\n###############################################\n\ndef reset_maze():\n \"\"\"Resets any cells that are VISITED or PATH to EMPTY again, so that we\n can commence a search on a potentially partially completed board\"\"\"\n for col in range(COLS):\n for row in range(ROWS):\n grid[col, row] = EMPTY if (grid[col, row] in [VISITED, PATH]) else grid[col, row]\n\n\n###############################################\n# valid_cell()\n###############################################\n\ndef valid_cell(col, row):\n return ((col >= 0) and (row >= 0) and (col < COLS) and (row < ROWS))\n\n\n###############################################\n# depth_first_search()\n###############################################\n\ndef depth_first_search():\n\n ###############################################\n # check()\n ###############################################\n\n def check(col, row):\n if (valid_cell(col, row)):\n if (search(col, row)):\n return True\n return False\n\n ###############################################\n # search()\n ###############################################\n\n def search(col, row):\n print(f\"search({col}, {row})\")\n pygame.display.update()\n # time.sleep(SMALL_SLEEP)\n\n if (grid[col, row] == TERMINAL):\n return True\n if (grid[col, row] in [WALL, VISITED, PATH]):\n return False\n\n if (grid[col, row] != INITIAL):\n grid[col, row] = PATH\n draw_cell(PATH_CELL_COLOR, col, row)\n\n if (check(col - 1, row)):\n return True\n\n if (check(col + 1, row)):\n return True\n\n if (check(col, row - 1)):\n return True\n\n if (check(col, row + 1)):\n return True\n\n grid[col, row] = VISITED\n draw_cell(VISITED_CELL_COLOR, col, row)\n return False\n\n global processing\n processing = True\n reset_maze()\n draw_grid()\n\n if (check(initial_cell_col - 1, initial_cell_row)):\n processing = False\n return\n\n if (check(initial_cell_col + 1, initial_cell_row)):\n processing = False\n return\n\n if (check(initial_cell_col, initial_cell_row - 1)):\n processing = False\n return\n\n if (check(initial_cell_col, initial_cell_row + 1)):\n processing = False\n return\n processing = False\n\n\n###############################################\n# breadth_first_search()\n###############################################\n\ndef breadth_first_search():\n\n ###############################################\n # search()\n ###############################################\n\n def search(nodes):\n\n ###############################################\n # check()\n ###############################################\n\n def check(next_col, next_row, sub_nodes):\n if (valid_cell(next_col, next_row)):\n if (grid[next_col, next_row] == TERMINAL):\n backtrack_node = node\n\n while (backtrack_node is not None):\n if (backtrack_node.get_parent() is not None):\n grid[backtrack_node.get_col(),\n backtrack_node.get_row()] = PATH\n draw_cell(PATH_CELL_COLOR,\n backtrack_node.get_col(),\n backtrack_node.get_row())\n pygame.display.update()\n backtrack_node = backtrack_node.get_parent()\n\n return True\n elif ((grid[next_col, next_row] != WALL) and\n (grid[next_col, next_row] != VISITED) and\n (grid[next_col, next_row] != INITIAL)):\n grid[next_col, next_row] = VISITED\n draw_cell(VISITED_CELL_COLOR, next_col, next_row)\n pygame.display.update()\n child_node = bfs_node(next_col, next_row, node)\n sub_nodes.append(child_node)\n return False\n\n pygame.display.update()\n time.sleep(SMALL_SLEEP)\n\n sub_nodes = []\n\n for node in nodes:\n # print(f\"\\tNode at ({node.get_col()}, {node.get_row()})\")\n if (check(node.get_col() - 1, node.get_row(), sub_nodes)):\n return\n\n if (check(node.get_col() + 1, node.get_row(), sub_nodes)):\n return\n\n if (check(node.get_col(), node.get_row() + 1, sub_nodes)):\n return\n\n if (check(node.get_col(), node.get_row() - 1, sub_nodes)):\n return\n\n if(len(sub_nodes) > 0):\n return search(sub_nodes)\n else:\n return False\n\n global processing\n processing = True\n reset_maze()\n draw_grid()\n\n nodes = []\n nodes.append(bfs_node(initial_cell_col, initial_cell_row, None))\n search(nodes)\n\n processing = False\n\n\n###############################################\n# draw_cell()\n###############################################\n\ndef draw_cell(color, col, row):\n pygame.draw.rect(screen,\n color,\n (col * CELL_WIDTH,\n row * CELL_HEIGHT,\n CELL_WIDTH,\n CELL_HEIGHT),\n 0)\n\n\n###############################################\n# main()\n###############################################\n\ndef main():\n # Increase stack size (depth-first-search is stack intensive)\n sys.setrecursionlimit(10 ** 6)\n\n pygame.init()\n pygame.display.set_caption(\"Maze\")\n\n initialise()\n create_ui()\n\n game_loop()\n\n\n###############################################\n# Startup\n###############################################\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "numpy.ndarray" ] ]
chadwickbureau/data-boxscores
[ "225fb21072784f6709d6954bfe94d51992e50cdf" ]
[ "hgame/boxscore/extract.py" ]
[ "\"\"\"Extract data from transcription format.\"\"\"\nimport sys\nimport datetime\nimport io\nimport pathlib\nimport tabulate\n\nimport pandas as pd\n\nfrom . import config\n\n\nsubstitution_keys = (\"*\", \"+\", \"^\", \"&\", \"$\", \"%\")\n\n\ndef process_source(game, value):\n title, d = (x.strip() for x in value.split(\",\", 1))\n d = datetime.datetime.strptime(d, \"%B %d, %Y\")\n d = d.strftime(\"%Y-%m-%d\")\n game[\"source\"] = {\"title\": title, \"date\": d}\n return game\n\n\ndef process_status(game, status):\n if \",\" in status:\n status, reason = (x.strip() for x in status.split(\",\"))\n else:\n status, reason = status.strip(), \"\"\n if status in [\"postponed\", \"completed early\", \"abandoned\"]:\n game[\"status\"][\"code\"] = status\n else:\n print(f\"Unknown status '{status}'\")\n sys.exit(1)\n if reason:\n game[\"status\"][\"reason\"] = reason\n return game\n\n\ndef process_linescore(game: dict, value: str):\n try:\n club, score = (x.strip() for x in value.split(\":\"))\n except ValueError:\n print(f\"ERROR: Ill-formed linescore string '{value}'\")\n return\n\n for team in game[\"teams\"]:\n if club == team[\"name\"]:\n break\n else:\n print(f\"Unknown team '{club}' in linescore\")\n return\n \n byinning, total = map(lambda x: x.strip(), score.split(\"-\"))\n try:\n int(total)\n except ValueError:\n print(f\"ERROR: Ill-formed linescore string '{value}'\")\n\n team[\"score\"] = total\n team[\"innings\"] = [x.lower() for x in byinning.split(\" \")]\n return game\n\n\ndef parse_name(text: str) -> dict:\n \"\"\"Parse out a personal name in form 'last, first'. Return as a dict.\"\"\"\n if \",\" in text:\n return dict(zip(['last', 'first'],\n (x.strip() for x in text.split(\",\"))))\n else:\n return {'last': text.strip()}\n\n\ndef parse_umpires(game: dict, value: str):\n for name in value.split(\";\"):\n game[\"umpires\"].append(parse_name(name))\n\n\ndef parse_date(game: dict, value: str):\n game['data']['date'] = value\n game['data']['season'] = value[:4]\n\n\ndef parse_number(game: dict, value: str):\n game['data']['number'] = value\n\n\ndef parse_league(game: dict, value: str):\n if \"League\" not in value and \"Association\" not in value:\n value = value + \" League\"\n game['data']['league'] = value\n for team in game['teams']:\n team['league'] = value\n\n\ndef parse_status(game: dict, value: str):\n if \",\" in value:\n game['data']['status_code'], game['data']['status_reason'] = (\n (x.strip() for x in value.split(\",\"))\n )\n else:\n game['data']['status_code'] = value\n\n\ndef parse_team(game: dict, align: int, value: str):\n game['teams'][align]['name'] = value\n\n\ndef parse_duration(game: dict, value: str):\n game['data']['duration'] = value\n\n\ndef parse_player_table(team: dict, data):\n while True:\n try:\n k, v = next(data)\n except ValueError:\n print(f\"WARNING: Ill-formed player line after '{k}'\")\n if k == \"TOTALS\":\n break\n name, pos = (x.strip() for x in k.split(\"@\"))\n name = name.split(\")\")[-1]\n if name.startswith(substitution_keys):\n name = name[1:]\n team['players'].append(dict(\n **parse_name(name),\n **{'pos': pos}\n ))\n\n\ndef extract_pairs(text: str):\n for line in (x.strip() for x in text.split(\"\\n\")):\n if not line:\n continue\n yield tuple(x.strip() for x in line.split(\":\", 1))\n\n\ndef parse_game(text: str) -> dict:\n game = {\n \"data\": {'date': None, 'number': None, 'status_code': \"final\"},\n \"teams\": [\n {'alignment': \"away\", 'name': None, 'league': None,\n 'players': []},\n {'alignment': \"home\", 'name': None, 'league': None,\n 'players': []}\n ],\n \"umpires\": []\n }\n dispatch = {\n 'date': parse_date,\n 'number': parse_number,\n 'league': parse_league,\n 'status': parse_status,\n 'T': parse_duration,\n 'U': parse_umpires,\n 'away': lambda g, val: parse_team(g, 0, val),\n 'home': lambda g, val: parse_team(g, 1, val),\n 'line': process_linescore\n }\n data = extract_pairs(text)\n try:\n while True:\n k, v = next(data)\n for team in game['teams']:\n if k == team['name']:\n parse_player_table(team, data)\n try:\n fn = dispatch[k]\n except KeyError:\n continue\n fn(game, v)\n except StopIteration:\n pass\n print(f\"{game['data']['date']}#{game['data']['number']} \"\n f\"{game['teams'][0]['name']} at {game['teams'][1]['name']}\")\n return game\n\n\ndef separate_games(fn: pathlib.Path):\n \"\"\"Iterate over the games in 'fn' and separate the text of each.\"\"\"\n game = io.StringIO()\n with fn.open() as f:\n for line in f:\n if line.startswith(\"---\"):\n yield game.getvalue()\n game = io.StringIO()\n else:\n game.write(line)\n value = game.getvalue().strip()\n if value:\n yield value\n\n\ndef process_files(inpath: pathlib.Path):\n fnlist = [fn for fn in sorted(inpath.glob(\"*.txt\"))\n if fn.name.lower() not in [\"readme.txt\", \"notes.txt\"]]\n if not fnlist:\n print(f\"No files found at '{inpath}'\")\n sys.exit(1)\n return [\n parse_game(game)\n for fn in fnlist\n for game in separate_games(fn)\n ]\n\n\ndef index_games(games: list, source: str) -> pd.DataFrame:\n df = pd.DataFrame(\n [{'game.id': i,\n 'source': source,\n 'key': None,\n 'season': game['data']['season'],\n 'date': game['data']['date'],\n 'number': game['data']['number'],\n 'league': game['data']['league'],\n 'status_code': game['data']['status_code'],\n 'status_reason': game['data'].get('status_reason', None)}\n for (i, game) in enumerate(games)]\n )\n return df\n\n\ndef index_teams(games: list) -> pd.DataFrame:\n df = pd.DataFrame([\n {'game.id': i,\n 'team.name': team['name'],\n 'team.league': team['league'],\n 'team.align': team['alignment'][0],\n 'team.score': team.get('score', None)}\n for (i, game) in enumerate(games)\n for team in game['teams']\n ])\n return df\n\n\ndef index_players(games: list) -> pd.DataFrame:\n return pd.DataFrame([\n {'game.id': i,\n 'team.name': team['name'],\n 'team.league': team['league'],\n 'person.seq': f\"{prefix}{j:02d}\",\n 'person.name.last': player['last'],\n 'person.name.first': player.get('first', None),\n 'pos': player['pos']}\n for (i, game) in enumerate(games)\n for (prefix, team) in zip((\"a\", \"b\"), game['teams'])\n for (j, player) in enumerate(team['players'])\n ])\n\n\ndef identify_teams(df: pd.DataFrame, year: int) -> pd.DataFrame:\n index = pd.read_csv(f\"data/support/{year}/teams.csv\")\n df = df.merge(index, how='left', on=['team.league', 'team.name'])\n unmatched = (\n df.query(\"`team.key`.isnull()\")\n [['team.league', 'team.name']]\n .drop_duplicates()\n .sort_values(['team.league', 'team.name'])\n )\n if not unmatched.empty:\n print(\"The following teams were not matched to a key:\")\n print(tabulate.tabulate(unmatched, headers='keys', showindex=False))\n sys.exit(1)\n return df\n\n\ndef identify_games(df: pd.DataFrame, teams: pd.DataFrame) -> pd.DataFrame:\n return (\n df\n .merge(teams.query(\"`team.align` == 'a'\")\n [['game.id',\n 'team.name', 'team.align', 'team.score', 'team.key']]\n .rename(columns=lambda x: x.replace('team.', 'team1.')),\n how='left', on='game.id')\n .merge(teams.query(\"`team.align` == 'h'\")\n [['game.id',\n 'team.name', 'team.align', 'team.score', 'team.key']]\n .rename(columns=lambda x: x.replace('team.', 'team2.')),\n how='left', on='game.id')\n .assign(**{\n 'key': lambda x: (\n x['date'].str.replace(\"-\", \"\") + \"-\" +\n x[['team1.key', 'team2.key']].fillna(\"\").min(axis='columns') +\n \"-\" +\n x[['team1.key', 'team2.key']].fillna(\"\").max(axis='columns') +\n \"-\" +\n x['number']\n )\n })\n )\n\n\ndef update_game_index(path: pathlib.Path,\n source: str, league: str,\n df: pd.DataFrame) -> pd.DataFrame:\n \"\"\"Update the game index for league with data from source.\"\"\"\n league = league.replace(\" \", \"\").replace(\"-\", \"\")\n (path/league).mkdir(exist_ok=True, parents=True)\n dfcols = ['key', 'league', 'date', 'number', 'source',\n 'team1.name', 'team1.align', 'team1.score',\n 'team2.name', 'team2.align', 'team2.score',\n 'status_code', 'status_reason']\n\n try:\n index = pd.read_csv(path/league/\"games.csv\", usecols=dfcols).fillna(\"\")\n except FileNotFoundError:\n index = pd.DataFrame(columns=dfcols)\n index = (\n pd.concat([index.query(f\"source != '{source}'\"), df],\n ignore_index=True, sort=False)\n .reindex(columns=dfcols)\n .fillna(\"\")\n .sort_values(['league', 'key'])\n )\n index.to_csv(path/league/\"games.csv\", index=False, float_format='%d')\n return index\n\n\ndef update_player_index(path: pathlib.Path,\n source: str, league: str,\n df: pd.DataFrame) -> pd.DataFrame:\n \"\"\"Update the player index for league with data from source.\"\"\"\n league = league.replace(\" \", \"\").replace(\"-\", \"\")\n (path/league).mkdir(exist_ok=True, parents=True)\n dfcols = ['team.league', 'team.key',\n 'team.name', 'source',\n 'key',\n 'gloss.name.last', 'gloss.name.first',\n 'person.name.last', 'person.name.first',\n 'person.seq', 'pos']\n try:\n index = pd.read_csv(path/league/\"players.csv\", usecols=dfcols).fillna(\"\")\n except FileNotFoundError:\n index = pd.DataFrame(columns=dfcols)\n df = (\n df.fillna(\"\")\n .merge(index[['source', 'team.name', 'key',\n 'person.name.last', 'person.name.first',\n 'person.seq',\n 'gloss.name.last', 'gloss.name.first']],\n how='left',\n on=['source', 'team.name', 'key',\n 'person.name.last', 'person.name.first',\n 'person.seq'])\n )\n index = (\n pd.concat([index.query(f\"source != '{source}'\"), df],\n ignore_index=True, sort=False)\n .reindex(columns=dfcols)\n .fillna(\"\")\n .assign(\n sortlast=lambda x: (\n x['gloss.name.last'].replace(\"\", pd.NA)\n .fillna(x['person.name.last']).fillna(\"\")\n ),\n sortfirst=lambda x: (\n x['gloss.name.first'].replace(\"\", pd.NA)\n .fillna(x['person.name.first']).fillna(\"\"))\n )\n .sort_values(['team.name', 'sortlast', 'sortfirst', 'key', 'source'])\n .drop(columns=['sortlast', 'sortfirst'])\n )\n index.to_csv(path/league/\"players.csv\", index=False, float_format='%d')\n return index\n\n\ndef main(source: str):\n try:\n year, paper = source.split(\"-\")\n except ValueError:\n print(f\"Invalid source name '{source}'\")\n sys.exit(1)\n\n inpath = config.data_path/\"transcript\"/year/source\n outpath = pathlib.Path(f\"data/index/{year}\")\n outpath.mkdir(exist_ok=True, parents=True)\n\n data = process_files(inpath)\n games_teams = index_teams(data).pipe(identify_teams, year)\n # games_teams.to_csv(\"games_teams.csv\", index=False, float_format='%d')\n games = index_games(data, source).pipe(identify_games, games_teams)\n for (league, group) in games.groupby('league'):\n print(f\"Writing {len(group):5d} games for {league}\")\n update_game_index(outpath, source, league, group)\n players = (\n index_players(data).pipe(identify_teams, year)\n .merge(games[['game.id', 'source', 'key']], how='left', on='game.id')\n .reindex(columns=['team.league', 'team.key', 'team.name',\n 'source', 'key',\n 'person.name.last', 'person.name.first',\n 'person.seq', 'pos'])\n .sort_values(['team.league', 'team.name',\n 'person.name.last', 'key', 'source'])\n )\n for (league, group) in players.groupby('team.league'):\n print(f\"Writing {len(group):5d} players for {league}\")\n update_player_index(outpath, source, league, group)\n" ]
[ [ "pandas.DataFrame", "pandas.read_csv" ] ]
samgoldman97/icml18-jtnn
[ "20c7831a81a942bd9b98ee492951e7a5e3237a8d" ]
[ "jtnn/jtnn_vae.py" ]
[ "import torch\nimport torch.nn as nn\nfrom .mol_tree import Vocab, MolTree\nfrom .nnutils import create_var\nfrom .jtnn_enc import JTNNEncoder\nfrom .jtnn_dec import JTNNDecoder\nfrom .mpn import MPN, mol2graph\nfrom .jtmpn import JTMPN\n\nfrom .chemutils import enum_assemble, set_atommap, copy_edit_mol, attach_mols, atom_equal, decode_stereo\nimport rdkit\nimport rdkit.Chem as Chem\nfrom rdkit import DataStructs\nfrom rdkit.Chem import AllChem\nimport copy, math\nimport sys\n\ndef set_batch_nodeID(mol_batch, vocab):\n tot = 0\n for mol_tree in mol_batch:\n for node in mol_tree.nodes:\n node.idx = tot\n #node.wid = vocab.get_index(node.smiles)\n tot += 1\n\nclass JTNNVAE(nn.Module):\n\n def __init__(self, vocab, hidden_size, latent_size, depth, stereo=True):\n super(JTNNVAE, self).__init__()\n self.vocab = vocab\n self.hidden_size = hidden_size\n self.latent_size = latent_size\n self.depth = depth\n\n self.embedding = nn.Embedding(vocab.size(), hidden_size)\n self.jtnn = JTNNEncoder(vocab, hidden_size, self.embedding)\n self.jtmpn = JTMPN(hidden_size, depth)\n self.mpn = MPN(hidden_size, depth)\n self.decoder = JTNNDecoder(vocab, hidden_size, latent_size // 2, self.embedding)\n\n self.T_mean = nn.Linear(hidden_size, latent_size // 2)\n self.T_var = nn.Linear(hidden_size, latent_size // 2)\n self.G_mean = nn.Linear(hidden_size, latent_size // 2)\n self.G_var = nn.Linear(hidden_size, latent_size // 2)\n\n self.assm_loss = nn.CrossEntropyLoss(size_average=False)\n self.use_stereo = stereo\n if stereo:\n self.stereo_loss = nn.CrossEntropyLoss(size_average=False)\n\n def encode(self, mol_batch):\n set_batch_nodeID(mol_batch, self.vocab)\n #root_batch = [mol_tree.nodes[0] for mol_tree in mol_batch]\n #tree_mess,tree_vec = self.jtnn(root_batch)\n\n smiles_batch = [mol_tree.smiles for mol_tree in mol_batch]\n mol_vec = self.mpn(mol2graph(smiles_batch))\n #return tree_mess, tree_vec, mol_vec\n return mol_vec\n\n def encode_from_smiles(self, smiles_list):\n mol_batch, valid_idx = [], []\n for idx, s in enumerate(smiles_list):\n try:\n mol_batch.append(MolTree(s))\n valid_idx.append(idx)\n except:\n sys.stderr.write('Invalid SMILE string: {}\\n'.format(s))\n\n for mol_tree in mol_batch:\n mol_tree.recover()\n\n mol_vec = self.encode(mol_batch)\n mol_mean = self.G_mean(mol_vec)\n return mol_mean\n\n def encode_latent_mean(self, smiles_list):\n mol_batch, valid_idx = [], []\n for idx, s in enumerate(smiles_list):\n try:\n mol_batch.append(MolTree(s))\n valid_idx.append(idx)\n except:\n sys.stderr.write('Invalid SMILE string: {}\\n'.format(s))\n\n for mol_tree in mol_batch:\n mol_tree.recover()\n\n #_, tree_vec, mol_vec = self.encode(mol_batch)\n #tree_mean = self.T_mean(tree_vec)\n mol_vec = self.encode(mol_batch)\n mol_mean = self.G_mean(mol_vec)\n #return torch.cat([tree_mean,mol_mean], dim=1)\n return mol_mean, valid_idx\n\n def forward(self, mol_batch, beta=0):\n batch_size = len(mol_batch)\n\n tree_mess, tree_vec, mol_vec = self.encode(mol_batch)\n\n tree_mean = self.T_mean(tree_vec)\n tree_log_var = -torch.abs(self.T_var(tree_vec)) #Following Mueller et al.\n mol_mean = self.G_mean(mol_vec)\n mol_log_var = -torch.abs(self.G_var(mol_vec)) #Following Mueller et al.\n\n z_mean = torch.cat([tree_mean,mol_mean], dim=1)\n z_log_var = torch.cat([tree_log_var,mol_log_var], dim=1)\n kl_loss = -0.5 * torch.sum(1.0 + z_log_var - z_mean * z_mean - torch.exp(z_log_var)) / batch_size\n\n epsilon = create_var(torch.randn(batch_size, self.latent_size // 2), False)\n tree_vec = tree_mean + torch.exp(tree_log_var // 2) * epsilon\n epsilon = create_var(torch.randn(batch_size, self.latent_size // 2), False)\n mol_vec = mol_mean + torch.exp(mol_log_var // 2) * epsilon\n\n word_loss, topo_loss, word_acc, topo_acc = self.decoder(mol_batch, tree_vec)\n assm_loss, assm_acc = self.assm(mol_batch, mol_vec, tree_mess)\n if self.use_stereo:\n stereo_loss, stereo_acc = self.stereo(mol_batch, mol_vec)\n else:\n stereo_loss, stereo_acc = 0, 0\n\n all_vec = torch.cat([tree_vec, mol_vec], dim=1)\n loss = word_loss + topo_loss + assm_loss + 2 * stereo_loss + beta * kl_loss\n\n return loss, kl_loss.item(), word_acc, topo_acc, assm_acc, stereo_acc\n\n def assm(self, mol_batch, mol_vec, tree_mess):\n cands = []\n batch_idx = []\n for i,mol_tree in enumerate(mol_batch):\n for node in mol_tree.nodes:\n #Leaf node's attachment is determined by neighboring node's attachment\n if node.is_leaf or len(node.cands) == 1: continue\n cands.extend( [(cand, mol_tree.nodes, node) for cand in node.cand_mols] )\n batch_idx.extend([i] * len(node.cands))\n\n cand_vec = self.jtmpn(cands, tree_mess)\n cand_vec = self.G_mean(cand_vec)\n\n batch_idx = create_var(torch.LongTensor(batch_idx))\n mol_vec = mol_vec.index_select(0, batch_idx)\n\n mol_vec = mol_vec.view(-1, 1, self.latent_size // 2)\n cand_vec = cand_vec.view(-1, self.latent_size // 2, 1)\n scores = torch.bmm(mol_vec, cand_vec).squeeze()\n\n cnt,tot,acc = 0,0,0\n all_loss = []\n for i,mol_tree in enumerate(mol_batch):\n comp_nodes = [node for node in mol_tree.nodes if len(node.cands) > 1 and not node.is_leaf]\n cnt += len(comp_nodes)\n for node in comp_nodes:\n label = node.cands.index(node.label)\n ncand = len(node.cands)\n cur_score = scores.narrow(0, tot, ncand)\n tot += ncand\n\n if cur_score[label].item() >= cur_score.max().item():\n acc += 1\n\n label = create_var(torch.LongTensor([label]))\n all_loss.append( self.assm_loss(cur_score.view(1,-1), label) )\n\n #all_loss = torch.stack(all_loss).sum() / len(mol_batch)\n all_loss = sum(all_loss) / len(mol_batch)\n return all_loss, acc * 1.0 / cnt\n\n def stereo(self, mol_batch, mol_vec):\n stereo_cands,batch_idx = [],[]\n labels = []\n for i,mol_tree in enumerate(mol_batch):\n cands = mol_tree.stereo_cands\n if len(cands) == 1: continue\n if mol_tree.smiles3D not in cands:\n cands.append(mol_tree.smiles3D)\n stereo_cands.extend(cands)\n batch_idx.extend([i] * len(cands))\n labels.append( (cands.index(mol_tree.smiles3D), len(cands)) )\n\n if len(labels) == 0:\n return create_var(torch.zeros(1)), 1.0\n\n batch_idx = create_var(torch.LongTensor(batch_idx))\n stereo_cands = self.mpn(mol2graph(stereo_cands))\n stereo_cands = self.G_mean(stereo_cands)\n stereo_labels = mol_vec.index_select(0, batch_idx)\n scores = torch.nn.CosineSimilarity()(stereo_cands, stereo_labels)\n\n st,acc = 0,0\n all_loss = []\n for label,le in labels:\n cur_scores = scores.narrow(0, st, le)\n if cur_scores.data[label] >= cur_scores.max().data[0]:\n acc += 1\n label = create_var(torch.LongTensor([label]))\n all_loss.append( self.stereo_loss(cur_scores.view(1,-1), label) )\n st += le\n #all_loss = torch.cat(all_loss).sum() / len(labels)\n all_loss = sum(all_loss) / len(labels)\n return all_loss, acc * 1.0 / len(labels)\n\n def reconstruct(self, smiles, prob_decode=False):\n mol_tree = MolTree(smiles)\n mol_tree.recover()\n _,tree_vec,mol_vec = self.encode([mol_tree])\n\n tree_mean = self.T_mean(tree_vec)\n tree_log_var = -torch.abs(self.T_var(tree_vec)) #Following Mueller et al.\n mol_mean = self.G_mean(mol_vec)\n mol_log_var = -torch.abs(self.G_var(mol_vec)) #Following Mueller et al.\n\n epsilon = create_var(torch.randn(1, self.latent_size // 2), False)\n tree_vec = tree_mean + torch.exp(tree_log_var // 2) * epsilon\n epsilon = create_var(torch.randn(1, self.latent_size // 2), False)\n mol_vec = mol_mean + torch.exp(mol_log_var // 2) * epsilon\n return self.decode(tree_vec, mol_vec, prob_decode)\n\n def recon_eval(self, smiles):\n mol_tree = MolTree(smiles)\n mol_tree.recover()\n _,tree_vec,mol_vec = self.encode([mol_tree])\n\n tree_mean = self.T_mean(tree_vec)\n tree_log_var = -torch.abs(self.T_var(tree_vec)) #Following Mueller et al.\n mol_mean = self.G_mean(mol_vec)\n mol_log_var = -torch.abs(self.G_var(mol_vec)) #Following Mueller et al.\n\n all_smiles = []\n for i in range(10):\n epsilon = create_var(torch.randn(1, self.latent_size // 2), False)\n tree_vec = tree_mean + torch.exp(tree_log_var // 2) * epsilon\n epsilon = create_var(torch.randn(1, self.latent_size // 2), False)\n mol_vec = mol_mean + torch.exp(mol_log_var // 2) * epsilon\n for j in range(10):\n new_smiles = self.decode(tree_vec, mol_vec, prob_decode=True)\n all_smiles.append(new_smiles)\n return all_smiles\n\n def sample_prior(self, prob_decode=False):\n tree_vec = create_var(torch.randn(1, self.latent_size // 2), False)\n mol_vec = create_var(torch.randn(1, self.latent_size // 2), False)\n return self.decode(tree_vec, mol_vec, prob_decode)\n\n def sample_eval(self):\n tree_vec = create_var(torch.randn(1, self.latent_size // 2), False)\n mol_vec = create_var(torch.randn(1, self.latent_size // 2), False)\n all_smiles = []\n for i in range(100):\n s = self.decode(tree_vec, mol_vec, prob_decode=True)\n all_smiles.append(s)\n return all_smiles\n\n def decode(self, tree_vec, mol_vec, prob_decode):\n pred_root,pred_nodes = self.decoder.decode(tree_vec, prob_decode)\n\n #Mark nid & is_leaf & atommap\n for i,node in enumerate(pred_nodes):\n node.nid = i + 1\n node.is_leaf = (len(node.neighbors) == 1)\n if len(node.neighbors) > 1:\n set_atommap(node.mol, node.nid)\n\n tree_mess = self.jtnn([pred_root])[0]\n\n cur_mol = copy_edit_mol(pred_root.mol)\n global_amap = [{}] + [{} for node in pred_nodes]\n global_amap[1] = {atom.GetIdx():atom.GetIdx() for atom in cur_mol.GetAtoms()}\n\n cur_mol = self.dfs_assemble(tree_mess, mol_vec, pred_nodes, cur_mol, global_amap, [], pred_root, None, prob_decode)\n if cur_mol is None:\n return None\n\n cur_mol = cur_mol.GetMol()\n set_atommap(cur_mol)\n cur_mol = Chem.MolFromSmiles(Chem.MolToSmiles(cur_mol))\n if cur_mol is None: return None\n if self.use_stereo == False:\n return Chem.MolToSmiles(cur_mol)\n\n smiles2D = Chem.MolToSmiles(cur_mol)\n stereo_cands = decode_stereo(smiles2D)\n if len(stereo_cands) == 1:\n return stereo_cands[0]\n stereo_vecs = self.mpn(mol2graph(stereo_cands))\n stereo_vecs = self.G_mean(stereo_vecs)\n scores = nn.CosineSimilarity()(stereo_vecs, mol_vec)\n _,max_id = scores.max(dim=0)\n return stereo_cands[max_id.data.item()]\n\n def dfs_assemble(self, tree_mess, mol_vec, all_nodes, cur_mol, global_amap, fa_amap, cur_node, fa_node, prob_decode):\n fa_nid = fa_node.nid if fa_node is not None else -1\n prev_nodes = [fa_node] if fa_node is not None else []\n\n children = [nei for nei in cur_node.neighbors if nei.nid != fa_nid]\n neighbors = [nei for nei in children if nei.mol.GetNumAtoms() > 1]\n neighbors = sorted(neighbors, key=lambda x:x.mol.GetNumAtoms(), reverse=True)\n singletons = [nei for nei in children if nei.mol.GetNumAtoms() == 1]\n neighbors = singletons + neighbors\n\n cur_amap = [(fa_nid,a2,a1) for nid,a1,a2 in fa_amap if nid == cur_node.nid]\n cands = enum_assemble(cur_node, neighbors, prev_nodes, cur_amap)\n if len(cands) == 0:\n return None\n cand_smiles,cand_mols,cand_amap = zip(*cands)\n\n cands = [(candmol, all_nodes, cur_node) for candmol in cand_mols]\n\n cand_vecs = self.jtmpn(cands, tree_mess)\n cand_vecs = self.G_mean(cand_vecs)\n mol_vec = mol_vec.squeeze()\n scores = torch.mv(cand_vecs, mol_vec) * 20\n\n if prob_decode:\n probs = nn.Softmax()(scores.view(1,-1)).squeeze() + 1e-5 #prevent prob = 0\n cand_idx = torch.multinomial(probs, probs.numel())\n else:\n _,cand_idx = torch.sort(scores, descending=True)\n\n backup_mol = Chem.RWMol(cur_mol)\n for i in range(cand_idx.numel()):\n cur_mol = Chem.RWMol(backup_mol)\n pred_amap = cand_amap[cand_idx[i].item()]\n new_global_amap = copy.deepcopy(global_amap)\n\n for nei_id,ctr_atom,nei_atom in pred_amap:\n if nei_id == fa_nid:\n continue\n new_global_amap[nei_id][nei_atom] = new_global_amap[cur_node.nid][ctr_atom]\n\n cur_mol = attach_mols(cur_mol, children, [], new_global_amap) #father is already attached\n new_mol = cur_mol.GetMol()\n new_mol = Chem.MolFromSmiles(Chem.MolToSmiles(new_mol))\n\n if new_mol is None: continue\n\n result = True\n for nei_node in children:\n if nei_node.is_leaf: continue\n cur_mol = self.dfs_assemble(tree_mess, mol_vec, all_nodes, cur_mol, new_global_amap, pred_amap, nei_node, cur_node, prob_decode)\n if cur_mol is None:\n result = False\n break\n if result: return cur_mol\n\n return None\n" ]
[ [ "torch.nn.Linear", "torch.zeros", "torch.cat", "torch.nn.Softmax", "torch.mv", "torch.nn.CrossEntropyLoss", "torch.bmm", "torch.sort", "torch.LongTensor", "torch.nn.CosineSimilarity", "torch.exp", "torch.randn" ] ]
arvidl/gcn_metric_learning
[ "62750e15e0107fab9fc279b17dbc8f509d5dbbba" ]
[ "lib/abide_utils.py" ]
[ "# Copyright (c) 2017 Sofia Ira Ktena <ira.ktena@imperial.ac.uk>\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n\n\nimport os\n\nimport csv\nimport numpy as np\nimport scipy.io as sio\n\nfrom sklearn.covariance import GraphLassoCV\nimport nilearn\nfrom nilearn import connectome\n\n\n# Output path\nsave_path = '/vol/dhcp-hcp-data/ABIDE'\n\n# Number of subjects\nnum_subjects = 1000\n\n# Selected pipeline\npipeline = 'cpac'\n\n# Files to fetch\nderivatives = ['rois_ho']\n\n# Get the root folder\nroot_folder = os.path.join(save_path, 'ABIDE_pcp/cpac/filt_noglobal')\n\n\ndef get_ids(num_subjects=None, short=True):\n \"\"\"\n num_subjects : number of subject IDs to get\n short : True of False, specifies whether to get short or long subject IDs\n\n return:\n subject_IDs : list of subject IDs (length num_subjects)\n \"\"\"\n\n if short:\n subject_IDs = np.loadtxt(os.path.join(root_folder, 'subject_IDs.txt'), dtype=int)\n subject_IDs = subject_IDs.astype(str)\n else:\n subject_IDs = np.loadtxt(os.path.join(root_folder, 'full_IDs.txt'), dtype=str)\n\n if num_subjects is not None:\n subject_IDs = subject_IDs[:num_subjects]\n\n return subject_IDs\n\n\ndef fetch_filenames(subject_list, file_type):\n \"\"\"\n subject_list : list of short subject IDs in string format\n file_type : must be one of the available file types\n\n returns:\n\n filenames : list of filetypes (same length as subject_list)\n \"\"\"\n\n # Specify file mappings for the possible file types\n filemapping = {'func_preproc': '_func_preproc.nii.gz',\n 'rois_aal': '_rois_aal.1D',\n 'rois_cc200': '_rois_cc200.1D',\n 'rois_ho': '_rois_ho.1D'}\n\n # The list to be filled\n filenames = []\n\n # Load subject ID lists\n subject_IDs = get_ids(short=True)\n subject_IDs = subject_IDs.tolist()\n full_IDs = get_ids(short=False)\n\n # Fill list with requested file paths\n for s in subject_list:\n try:\n if file_type in filemapping:\n idx = subject_IDs.index(s)\n pattern = full_IDs[idx] + filemapping[file_type]\n else:\n pattern = s + file_type\n\n filenames.append(os.path.join(root_folder, s, pattern))\n except ValueError:\n # Return N/A if subject ID is not found\n filenames.append('N/A')\n\n return filenames\n\n\ndef fetch_subject_files(subjectID):\n \"\"\"\n subjectID : short subject ID for which list of available files are fetched\n\n returns:\n\n onlyfiles : list of absolute paths for available subject files\n \"\"\"\n\n # Load subject ID lists\n subject_IDs = get_ids(short=True)\n subject_IDs = subject_IDs.tolist()\n full_IDs = get_ids(short=False)\n\n try:\n idx = subject_IDs.index(subjectID)\n subject_folder = os.path.join(root_folder, subjectID)\n onlyfiles = [os.path.join(subject_folder, f) for f in os.listdir(subject_folder)\n if os.path.isfile(os.path.join(subject_folder, f))]\n except ValueError:\n onlyfiles = []\n\n return onlyfiles\n\n\ndef fetch_conn_matrices(subject_list, atlas_name, kind):\n \"\"\"\n subject_list : list of short subject IDs in string format\n atlas_name : the atlas based on which the timeseries are generated e.g. aal, cc200\n kind : the kind of correlation used to estimate the matrices, i.e.\n\n returns:\n connectivity : list of square connectivity matrices, one for each subject in subject_list\n \"\"\"\n\n conn_files = fetch_filenames(subject_list,\n '_' + atlas_name + '_' + kind.replace(' ', '_') + '.mat')\n\n conn_matrices = []\n\n for fl in conn_files:\n print(\"Reading connectivity file %s\" % fl)\n try:\n mat = sio.loadmat(fl)['connectivity']\n conn_matrices.append(mat)\n except IOError:\n print(\"File %s does not exist\" % fl)\n\n return conn_matrices\n\n\ndef get_timeseries(subject_list, atlas_name):\n \"\"\"\n subject_list : list of short subject IDs in string format\n atlas_name : the atlas based on which the timeseries are generated e.g. aal, cc200\n\n returns:\n ts : list of timeseries arrays, each of shape (timepoints x regions)\n \"\"\"\n\n ts_files = fetch_filenames(subject_list, 'rois_' + atlas_name)\n\n ts = []\n\n for fl in ts_files:\n print(\"Reading timeseries file %s\" % fl)\n ts.append(np.loadtxt(fl, skiprows=0))\n\n return ts\n\n\ndef norm_timeseries(ts_list):\n \"\"\"\n ts_list : list of timeseries arrays, each of shape (timepoints x regions)\n\n returns:\n norm_ts : list of normalised timeseries arrays, same shape as ts_list\n \"\"\"\n\n norm_ts = []\n\n for ts in ts_list:\n norm_ts.append(nilearn.signal.clean(ts, detrend=False))\n\n return norm_ts\n\n\ndef subject_connectivity(timeseries, subject, atlas_name, kind, save=True, save_path=root_folder):\n \"\"\"\n timeseries : timeseries table for subject (timepoints x regions)\n subject : the subject short ID\n atlas_name : name of the atlas used\n kind : the kind of connectivity to be used, e.g. lasso, partial correlation, correlation\n save : save the connectivity matrix to a file\n save_path : specify path to save the matrix if different from subject folder\n\n returns:\n connectivity : connectivity matrix (regions x regions)\n \"\"\"\n\n print(\"Estimating %s matrix for subject %s\" % (kind, subject))\n\n if kind == 'lasso':\n # Graph Lasso estimator\n covariance_estimator = GraphLassoCV(verbose=1)\n covariance_estimator.fit(timeseries)\n connectivity = covariance_estimator.covariance_\n print('Covariance matrix has shape {0}.'.format(connectivity.shape))\n\n elif kind in ['tangent', 'partial correlation', 'correlation']:\n conn_measure = connectome.ConnectivityMeasure(kind=kind)\n connectivity = conn_measure.fit_transform([timeseries])[0]\n\n if save:\n subject_file = os.path.join(save_path, subject,\n subject + '_' + atlas_name + '_' + kind.replace(' ', '_') + '.mat')\n sio.savemat(subject_file, {'connectivity': connectivity})\n\n return connectivity\n\n\ndef group_connectivity(timeseries, subject_list, atlas_name, kind, save=True, save_path=root_folder):\n \"\"\"\n timeseries : list of timeseries tables for subjects (timepoints x regions)\n subject_list : the subject short IDs list\n atlas_name : name of the atlas used\n kind : the kind of connectivity to be used, e.g. lasso, partial correlation, correlation\n save : save the connectivity matrix to a file\n save_path : specify path to save the matrix if different from subject folder\n\n returns:\n connectivity : connectivity matrix (regions x regions)\n \"\"\"\n\n if kind == 'lasso':\n # Graph Lasso estimator\n covariance_estimator = GraphLassoCV(verbose=1)\n connectivity_matrices = []\n\n for i, ts in enumerate(timeseries):\n covariance_estimator.fit(ts)\n connectivity = covariance_estimator.covariance_\n connectivity_matrices.append(connectivity)\n print('Covariance matrix has shape {0}.'.format(connectivity.shape))\n\n elif kind in ['tangent', 'partial correlation', 'correlation']:\n conn_measure = connectome.ConnectivityMeasure(kind=kind)\n connectivity_matrices = conn_measure.fit_transform(timeseries)\n\n if save:\n for i, subject in enumerate(subject_list):\n subject_file = os.path.join(save_path, subject_list[i],\n subject_list[i] + '_' + atlas_name + '_' + kind.replace(' ', '_') + '.mat')\n sio.savemat(subject_file, {'connectivity': connectivity_matrices[i]})\n print(\"Saving connectivity matrix to %s\" % subject_file)\n\n return connectivity_matrices\n\n\ndef get_subject_label(subject_list, label_name):\n \"\"\"\n subject_list : the subject short IDs list\n label_name : name of the label to be retrieved\n\n returns:\n label : dictionary of subject labels\n \"\"\"\n\n label = {}\n\n with open(os.path.join(save_path, 'ABIDE_pcp/Phenotypic_V1_0b_preprocessed1.csv')) as csvfile:\n reader = csv.DictReader(csvfile)\n\n for row in reader:\n if row['subject'] in subject_list:\n label[row['subject']] = row[label_name]\n\n return label\n\n\ndef load_all_networks(subject_list, kind, atlas_name=\"aal\"):\n \"\"\"\n subject_list : the subject short IDs list\n kind : the kind of connectivity to be used, e.g. lasso, partial correlation, correlation\n atlas_name : name of the atlas used\n\n returns:\n all_networks : list of connectivity matrices (regions x regions)\n \"\"\"\n\n all_networks = []\n\n for subject in subject_list:\n fl = os.path.join(root_folder, subject,\n subject + \"_\" + atlas_name + \"_\" + kind + \".mat\")\n matrix = sio.loadmat(fl)['connectivity']\n\n if atlas_name == 'ho':\n matrix = np.delete(matrix, 82, axis=0)\n matrix = np.delete(matrix, 82, axis=1)\n\n all_networks.append(matrix)\n # all_networks=np.array(all_networks)\n\n return all_networks\n\n\ndef get_net_vectors(subject_list, kind, atlas_name=\"aal\"):\n \"\"\"\n subject_list : the subject short IDs list\n kind : the kind of connectivity to be used, e.g. lasso, partial correlation, correlation\n atlas_name : name of the atlas used\n\n returns:\n matrix : matrix of connectivity vectors (num_subjects x num_connections)\n \"\"\"\n\n # This is an alternative implementation\n networks = load_all_networks(subject_list, kind, atlas_name=atlas_name)\n # Get Fisher transformed matrices\n norm_networks = [np.arctanh(mat) for mat in networks]\n # Get upper diagonal indices\n idx = np.triu_indices_from(norm_networks[0], 1)\n # Get vectorised matrices\n vec_networks = [mat[idx] for mat in norm_networks]\n # Each subject should be a row of the matrix\n matrix = np.vstack(vec_networks)\n\n return matrix\n\n\ndef get_atlas_coords(atlas_name='ho'):\n \"\"\"\n atlas_name : name of the atlas used\n\n returns:\n matrix : matrix of roi 3D coordinates in MNI space (num_rois x 3)\n \"\"\"\n\n coords_file = os.path.join(root_folder, atlas_name + '_coords.csv')\n coords = np.loadtxt(coords_file, delimiter=',')\n\n if atlas_name == 'ho':\n coords = np.delete(coords, 82, axis=0)\n\n return coords" ]
[ [ "numpy.delete", "numpy.triu_indices_from", "scipy.io.loadmat", "scipy.io.savemat", "numpy.loadtxt", "numpy.arctanh", "numpy.vstack", "sklearn.covariance.GraphLassoCV" ] ]
RosaliaTufano/rlgameauthors
[ "d18bedd82da66be1b222e86ff63344d85f1ba92a" ]
[ "CartPole/CartPole_RL-baseline_1k_episodes.py" ]
[ "# **********************************************************************************************************************\n# **********************************************************************************************************************\n# **********************************************************************************************************************\n# *** Using Reinforcement Learning for Load Testing of Video Games ***\n# *** Game: CartPole ***\n# *** RL-baseline: Cross Entropy Method ***\n# *** Play 1000 episodes (still training) and save injected bugs spotted ***\n# **********************************************************************************************************************\n# **********************************************************************************************************************\n# **********************************************************************************************************************\n\n\nimport gym\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom collections import namedtuple\n\n\nHIDDEN_SIZE = 128 # neural network size\nBATCH_SIZE = 16 # num episodes\nPERCENTILE = 70 # elite episodes\n\nclass Net(nn.Module):\n def __init__(self, obs_size, hidden_size, n_actions):\n super(Net, self).__init__()\n self.net = nn.Sequential(\n nn.Linear(obs_size, hidden_size),\n nn.ReLU(),\n nn.Linear(hidden_size, n_actions)\n )\n\n def forward(self, x):\n return self.net(x)\n\n\nEpisode = namedtuple('Episode', field_names=['reward', 'steps'])\nEpisodeStep = namedtuple('EpisodeStep', field_names=['observation', 'action'])\n\n\ndef iterate_batches(env, net, batch_size, file):\n batch = []\n episode_reward = 0.0\n episode_steps = []\n obs = env.reset()\n # OBSERVATION:\n # - x coordinate of the stick's center of mass\n # - speed\n # - angle to the platform\n # - angular speed\n sm = nn.Softmax(dim=1)\n flag_injected_bug_spotted = [False, False]\n while True:\n obs_v = torch.FloatTensor([obs])\n act_probs_v = sm(net(obs_v))\n act_probs = act_probs_v.data.numpy()[0]\n action = np.random.choice(len(act_probs), p=act_probs)\n next_obs, reward, is_done, _ = env.step(action)\n if -0.5 < next_obs[0] < -0.45 and not flag_injected_bug_spotted[0]: # and -0.01 < next_obs[2] < 0.00:\n file.write('BUG1 ')\n flag_injected_bug_spotted[0] = True\n if 0.45 < next_obs[0] < 0.5 and not flag_injected_bug_spotted[1]: # and -0.01 < next_obs[2] < 0.00:\n file.write('BUG2 ')\n flag_injected_bug_spotted[1] = True\n episode_reward += reward\n episode_steps.append(EpisodeStep(observation=obs, action=action))\n if is_done:\n file.write('\\n')\n batch.append(Episode(reward=episode_reward, steps=episode_steps))\n episode_reward = 0.0\n episode_steps = []\n next_obs = env.reset()\n flag_injected_bug_spotted = [False, False]\n if len(batch) == batch_size:\n yield batch\n batch = []\n obs = next_obs\n\n\ndef filter_batch(batch, percentile):\n rewards = list(map(lambda s: s.reward, batch))\n reward_bound = np.percentile(rewards, percentile)\n reward_mean = float(np.mean(rewards))\n\n train_obs = []\n train_act = []\n for example in batch:\n if example.reward < reward_bound:\n continue\n train_obs.extend(map(lambda step: step.observation, example.steps))\n train_act.extend(map(lambda step: step.action, example.steps))\n\n train_obs_v = torch.FloatTensor(train_obs)\n train_act_v = torch.LongTensor(train_act)\n return train_obs_v, train_act_v, reward_bound, reward_mean\n\n# **********************************************************************************************************************\n# * 1000 episodes start *\n# **********************************************************************************************************************\n\n\nif __name__ == \"__main__\":\n print('\\n\\n*****************************************************************')\n print(\"* RL-baseline model's playing 1000 episodes (still training)... *\")\n print('*****************************************************************\\n')\n env = gym.make(\"CartPole-v0\")\n env._max_episode_steps = 1000 # episode length\n\n obs_size = env.observation_space.shape[0]\n n_actions = env.action_space.n\n\n net = Net(obs_size, HIDDEN_SIZE, n_actions)\n net.load_state_dict(torch.load('./model_rl-baseline'))\n net.eval()\n\n objective = nn.CrossEntropyLoss()\n optimizer = optim.Adam(params=net.parameters(), lr=0.01)\n\n filename = 'injected_bugs_spotted_RL-baseline.txt'\n f = open(filename, 'w+')\n\n for iter_no, batch in enumerate(iterate_batches(env, net, BATCH_SIZE, f)):\n obs_v, acts_v, reward_b, reward_m = filter_batch(batch, PERCENTILE)\n optimizer.zero_grad()\n action_scores_v = net(obs_v)\n loss_v = objective(action_scores_v, acts_v)\n loss_v.backward()\n optimizer.step()\n print(\"%d: loss=%.3f, reward_mean=%.1f, reward_bound=%.1f\" % (iter_no, loss_v.item(), reward_m, reward_b))\n if iter_no == 63: # 63 * 16 (batch size) = 1008 episodes\n print('1k episodes end\\n\\n')\n break\n f.close()\n\n lines = [line for line in open(filename, 'r')]\n lines_1k = lines[:1000]\n\n count_0bug = 0\n count_1bug = 0\n count_2bug = 0\n\n for line in lines_1k:\n if line.strip() == '':\n count_0bug += 1\n elif len(line.strip().split()) == 1:\n count_1bug += 1\n elif len(line.strip().split()) == 2:\n count_2bug += 1\n print('Report injected bugs spotted:')\n print('0 injected bug spotted in %d episodes' % count_0bug)\n print('1 injected bug spotted in %d episodes' % count_1bug)\n print('2 injected bugs spotted in %d episodes' % count_2bug)\n print(\"\\ /\\ \\n ) ( ') meow!\\n( / )\\n \\(__)|\")\n\n# \\ /\\\n# ) ( ')\n# ( / )\n# \\(__)|\n" ]
[ [ "torch.nn.Linear", "torch.nn.Softmax", "numpy.percentile", "torch.FloatTensor", "numpy.mean", "torch.nn.ReLU", "torch.LongTensor", "torch.load", "torch.nn.CrossEntropyLoss" ] ]
kingsley1989/Parallel-Ultrametric
[ "12d690b2f7b206140bee826bc136fa1a71114df6" ]
[ "setup.py" ]
[ "from setuptools import setup\nfrom torch.utils.cpp_extension import BuildExtension, CUDAExtension\n\nsetup(\n\tname='ultmul', \n\text_modules=[\n\tCUDAExtension(\n\t\t'ultMul_cuda',\n[\n\t\t\t'ultMul_cuda.cpp',\n\t\t\t'ultMul_cuda_kernel.cu', #.cpp and .cu file must have different name\n\t\t])],\n\tcmdclass = {\n\t\t'build_ext': BuildExtension\n\t}\n)\n" ]
[ [ "torch.utils.cpp_extension.CUDAExtension" ] ]
deepakmuralidharan/tensorflow
[ "f40e41f9c71ef2865f96f3db3cea2909797fe2a3", "f40e41f9c71ef2865f96f3db3cea2909797fe2a3" ]
[ "tensorflow/python/kernel_tests/matmul_op_test.py", "tensorflow/g3doc/how_tos/reading_data/fully_connected_preloaded.py" ]
[ "# Copyright 2015 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"Tests for tensorflow.ops.math_ops.matmul.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow.python.platform\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom tensorflow.python.kernel_tests import gradient_checker as gc\n\n\nclass MatMulTest(tf.test.TestCase):\n\n def _testCpuMatmul(self, x, y, transpose_x=False, transpose_y=False):\n x_mat = np.matrix(x).T if transpose_x else np.matrix(x)\n y_mat = np.matrix(y).T if transpose_y else np.matrix(y)\n np_ans = x_mat * y_mat\n with self.test_session(use_gpu=False):\n tf_ans = tf.matmul(x, y, transpose_x, transpose_y).eval()\n self.assertAllClose(np_ans, tf_ans)\n self.assertAllEqual(np_ans.shape, tf_ans.shape)\n\n def _testGpuMatmul(self, x, y, transpose_x=False, transpose_y=False):\n x_mat = np.matrix(x).T if transpose_x else np.matrix(x)\n y_mat = np.matrix(y).T if transpose_y else np.matrix(y)\n np_ans = x_mat * y_mat\n with self.test_session(use_gpu=True):\n tf_ans = tf.matmul(x, y, transpose_x, transpose_y).eval()\n self.assertAllClose(np_ans, tf_ans)\n self.assertAllEqual(np_ans.shape, tf_ans.shape)\n\n def _randMatrix(self, rows, cols, dtype):\n if dtype is np.complex64:\n real = self._randMatrix(rows, cols, np.float32)\n imag = self._randMatrix(rows, cols, np.float32)\n return real + np.complex(0, 1) * imag\n else:\n return np.random.uniform(low=1.0, high=100.0, size=rows * cols).reshape(\n [rows, cols]).astype(dtype)\n\n # Basic test:\n # [ [1],\n # [2],\n # [3], * [1, 2]\n # [4] ]\n def testFloatBasic(self):\n x = np.arange(1., 5.).reshape([4, 1]).astype(np.float32)\n y = np.arange(1., 3.).reshape([1, 2]).astype(np.float32)\n self._testCpuMatmul(x, y)\n self._testGpuMatmul(x, y)\n\n def testDoubleBasic(self):\n x = np.arange(1., 5.).reshape([4, 1]).astype(np.float64)\n y = np.arange(1., 3.).reshape([1, 2]).astype(np.float64)\n self._testCpuMatmul(x, y)\n\n def testInt32Basic(self):\n x = np.arange(1., 5.).reshape([4, 1]).astype(np.int32)\n y = np.arange(1., 3.).reshape([1, 2]).astype(np.int32)\n self._testCpuMatmul(x, y)\n\n def testSComplexBasic(self):\n x = np.arange(1., 5.).reshape([4, 1]).astype(np.complex64)\n y = np.arange(1., 3.).reshape([1, 2]).astype(np.complex64)\n self._testCpuMatmul(x, y)\n\n # Tests testing random sized matrices.\n def testFloatRandom(self):\n for _ in range(10):\n n, k, m = np.random.randint(1, 100, size=3)\n x = self._randMatrix(n, k, np.float32)\n y = self._randMatrix(k, m, np.float32)\n self._testCpuMatmul(x, y)\n self._testGpuMatmul(x, y)\n\n def testDoubleRandom(self):\n for _ in range(10):\n n, k, m = np.random.randint(1, 100, size=3)\n x = self._randMatrix(n, k, np.float64)\n y = self._randMatrix(k, m, np.float64)\n self._testCpuMatmul(x, y)\n\n def testInt32Random(self):\n for _ in range(10):\n n, k, m = np.random.randint(1, 100, size=3)\n x = self._randMatrix(n, k, np.int32)\n y = self._randMatrix(k, m, np.int32)\n self._testCpuMatmul(x, y)\n\n def testSComplexRandom(self):\n for _ in range(10):\n n, k, m = np.random.randint(1, 100, size=3)\n x = self._randMatrix(n, k, np.complex64)\n y = self._randMatrix(k, m, np.complex64)\n self._testCpuMatmul(x, y)\n\n # Test the cases that transpose the matrices before multiplying.\n # NOTE(keveman): The cases where only one of the inputs is\n # transposed are covered by tf.matmul's gradient function.\n def testFloatRandomTransposeBoth(self):\n for _ in range(10):\n n, k, m = np.random.randint(1, 100, size=3)\n x = self._randMatrix(k, n, np.float32)\n y = self._randMatrix(m, k, np.float32)\n self._testCpuMatmul(x, y, True, True)\n self._testGpuMatmul(x, y, True, True)\n\n def testDoubleRandomTranposeBoth(self):\n for _ in range(10):\n n, k, m = np.random.randint(1, 100, size=3)\n x = self._randMatrix(k, n, np.float64)\n y = self._randMatrix(m, k, np.float64)\n self._testCpuMatmul(x, y, True, True)\n\n def testMatMul_OutEmpty_A(self):\n n, k, m = 0, 8, 3\n x = self._randMatrix(n, k, np.float32)\n y = self._randMatrix(k, m, np.float32)\n self._testCpuMatmul(x, y)\n self._testGpuMatmul(x, y)\n\n def testMatMul_OutEmpty_B(self):\n n, k, m = 3, 8, 0\n x = self._randMatrix(n, k, np.float32)\n y = self._randMatrix(k, m, np.float32)\n self._testCpuMatmul(x, y)\n self._testGpuMatmul(x, y)\n\n def testMatMul_Inputs_Empty(self):\n n, k, m = 3, 0, 4\n x = self._randMatrix(n, k, np.float32)\n y = self._randMatrix(k, m, np.float32)\n self._testCpuMatmul(x, y)\n self._testGpuMatmul(x, y)\n\n\n# TODO(zhifengc): Figures out how to test matmul gradients on GPU.\nclass MatMulGradientTest(tf.test.TestCase):\n\n def testGradientInput0(self):\n with self.test_session(use_gpu=False):\n x = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2],\n dtype=tf.float64, name=\"x\")\n y = tf.constant([1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7],\n shape=[2, 4], dtype=tf.float64, name=\"y\")\n m = tf.matmul(x, y, name=\"matmul\")\n err = gc.ComputeGradientError(x, [3, 2], m, [3, 4])\n print(\"matmul input0 gradient err = \", err)\n self.assertLess(err, 1e-10)\n\n def testGradientInput1(self):\n with self.test_session(use_gpu=False):\n x = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2],\n dtype=tf.float64, name=\"x\")\n y = tf.constant([1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7],\n shape=[2, 4], dtype=tf.float64, name=\"y\")\n m = tf.matmul(x, y, name=\"matmul\")\n err = gc.ComputeGradientError(y, [2, 4], m, [3, 4])\n print(\"matmul input1 gradient err = \", err)\n self.assertLess(err, 1e-10)\n\n def _VerifyInput0(self, transpose_a, transpose_b):\n shape_x = [3, 2]\n shape_y = [2, 4]\n if transpose_a:\n shape_x = list(reversed(shape_x))\n if transpose_b:\n shape_y = list(reversed(shape_y))\n with self.test_session(use_gpu=False):\n x = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=shape_x,\n dtype=tf.float64, name=\"x\")\n y = tf.constant([1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7],\n shape=shape_y, dtype=tf.float64, name=\"y\")\n m = tf.matmul(x, y, transpose_a, transpose_b, name=\"matmul\")\n err = gc.ComputeGradientError(x, shape_x, m, [3, 4])\n print(\"matmul input0 gradient err = \", err)\n self.assertLess(err, 1e-10)\n\n def testGradientInput0WithTranspose(self):\n self._VerifyInput0(transpose_a=True, transpose_b=False)\n self._VerifyInput0(transpose_a=False, transpose_b=True)\n self._VerifyInput0(transpose_a=True, transpose_b=True)\n\n def _VerifyInput1(self, transpose_a, transpose_b):\n shape_x = [3, 2]\n shape_y = [2, 4]\n if transpose_a:\n shape_x = list(reversed(shape_x))\n if transpose_b:\n shape_y = list(reversed(shape_y))\n with self.test_session(use_gpu=False):\n x = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=shape_x,\n dtype=tf.float64, name=\"x\")\n y = tf.constant([1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7],\n shape=shape_y, dtype=tf.float64, name=\"y\")\n m = tf.matmul(x, y, transpose_a, transpose_b, name=\"matmul\")\n err = gc.ComputeGradientError(y, shape_y, m, [3, 4])\n print(\"matmul input1 gradient err = \", err)\n self.assertLess(err, 1e-10)\n\n def testGradientInput1WithTranspose(self):\n self._VerifyInput1(transpose_a=True, transpose_b=False)\n self._VerifyInput1(transpose_a=False, transpose_b=True)\n self._VerifyInput1(transpose_a=True, transpose_b=True)\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n", "# Copyright 2015 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"Trains the MNIST network using preloaded data in a constant.\n\nCommand to run this py_binary target:\n\nbazel run -c opt \\\n <...>/tensorflow/g3doc/how_tos/reading_data:fully_connected_preloaded\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os.path\nimport time\n\nimport tensorflow.python.platform\nimport numpy\nimport tensorflow as tf\n\nfrom tensorflow.g3doc.tutorials.mnist import input_data\nfrom tensorflow.g3doc.tutorials.mnist import mnist\n\n\n# Basic model parameters as external flags.\nflags = tf.app.flags\nFLAGS = flags.FLAGS\nflags.DEFINE_float('learning_rate', 0.01, 'Initial learning rate.')\nflags.DEFINE_integer('num_epochs', 2, 'Number of epochs to run trainer.')\nflags.DEFINE_integer('hidden1', 128, 'Number of units in hidden layer 1.')\nflags.DEFINE_integer('hidden2', 32, 'Number of units in hidden layer 2.')\nflags.DEFINE_integer('batch_size', 100, 'Batch size. '\n 'Must divide evenly into the dataset sizes.')\nflags.DEFINE_string('train_dir', 'data', 'Directory to put the training data.')\nflags.DEFINE_boolean('fake_data', False, 'If true, uses fake data '\n 'for unit testing.')\n\n\ndef run_training():\n \"\"\"Train MNIST for a number of epochs.\"\"\"\n # Get the sets of images and labels for training, validation, and\n # test on MNIST.\n data_sets = input_data.read_data_sets(FLAGS.train_dir, FLAGS.fake_data)\n\n # Tell TensorFlow that the model will be built into the default Graph.\n with tf.Graph().as_default():\n with tf.name_scope('input'):\n # Input data\n input_images = tf.constant(data_sets.train.images)\n input_labels = tf.constant(data_sets.train.labels)\n\n image, label = tf.train.slice_input_producer(\n [input_images, input_labels], num_epochs=FLAGS.num_epochs)\n label = tf.cast(label, tf.int32)\n images, labels = tf.train.batch(\n [image, label], batch_size=FLAGS.batch_size)\n\n # Build a Graph that computes predictions from the inference model.\n logits = mnist.inference(images, FLAGS.hidden1, FLAGS.hidden2)\n\n # Add to the Graph the Ops for loss calculation.\n loss = mnist.loss(logits, labels)\n\n # Add to the Graph the Ops that calculate and apply gradients.\n train_op = mnist.training(loss, FLAGS.learning_rate)\n\n # Add the Op to compare the logits to the labels during evaluation.\n eval_correct = mnist.evaluation(logits, labels)\n\n # Build the summary operation based on the TF collection of Summaries.\n summary_op = tf.merge_all_summaries()\n\n # Create a saver for writing training checkpoints.\n saver = tf.train.Saver()\n\n # Create the op for initializing variables.\n init_op = tf.initialize_all_variables()\n\n # Create a session for running Ops on the Graph.\n sess = tf.Session()\n\n # Run the Op to initialize the variables.\n sess.run(init_op)\n\n # Instantiate a SummaryWriter to output summaries and the Graph.\n summary_writer = tf.train.SummaryWriter(FLAGS.train_dir,\n graph_def=sess.graph_def)\n\n # Start input enqueue threads.\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(sess=sess, coord=coord)\n\n # And then after everything is built, start the training loop.\n try:\n step = 0\n while not coord.should_stop():\n start_time = time.time()\n\n # Run one step of the model.\n _, loss_value = sess.run([train_op, loss])\n\n duration = time.time() - start_time\n\n # Write the summaries and print an overview fairly often.\n if step % 100 == 0:\n # Print status to stdout.\n print('Step %d: loss = %.2f (%.3f sec)' % (step, loss_value,\n duration))\n # Update the events file.\n summary_str = sess.run(summary_op)\n summary_writer.add_summary(summary_str, step)\n step += 1\n\n # Save a checkpoint periodically.\n if (step + 1) % 1000 == 0:\n print('Saving')\n saver.save(sess, FLAGS.train_dir, global_step=step)\n\n step += 1\n except tf.errors.OutOfRangeError:\n print('Saving')\n saver.save(sess, FLAGS.train_dir, global_step=step)\n print('Done training for %d epochs, %d steps.' % (FLAGS.num_epochs, step))\n finally:\n # When done, ask the threads to stop.\n coord.request_stop()\n\n # Wait for threads to finish.\n coord.join(threads)\n sess.close()\n\n\ndef main(_):\n run_training()\n\n\nif __name__ == '__main__':\n tf.app.run()\n" ]
[ [ "numpy.matrix", "tensorflow.matmul", "tensorflow.constant", "numpy.random.uniform", "numpy.random.randint", "numpy.arange", "tensorflow.test.main", "numpy.complex", "tensorflow.python.kernel_tests.gradient_checker.ComputeGradientError" ], [ "tensorflow.train.start_queue_runners", "tensorflow.train.slice_input_producer", "tensorflow.merge_all_summaries", "tensorflow.cast", "tensorflow.g3doc.tutorials.mnist.mnist.loss", "tensorflow.train.Saver", "tensorflow.constant", "tensorflow.g3doc.tutorials.mnist.mnist.training", "tensorflow.train.SummaryWriter", "tensorflow.app.run", "tensorflow.g3doc.tutorials.mnist.input_data.read_data_sets", "tensorflow.initialize_all_variables", "tensorflow.train.Coordinator", "tensorflow.g3doc.tutorials.mnist.mnist.evaluation", "tensorflow.train.batch", "tensorflow.Session", "tensorflow.g3doc.tutorials.mnist.mnist.inference", "tensorflow.name_scope", "tensorflow.Graph" ] ]
sourcery-ai-bot/scikit-learn
[ "0f7933a8f7527d13e822217cb2d42340be3cdfa4", "0f7933a8f7527d13e822217cb2d42340be3cdfa4" ]
[ "examples/cluster/plot_optics.py", "examples/cluster/plot_agglomerative_clustering_metrics.py" ]
[ "\"\"\"\n===================================\nDemo of OPTICS clustering algorithm\n===================================\n\n.. currentmodule:: sklearn\n\nFinds core samples of high density and expands clusters from them.\nThis example uses data that is generated so that the clusters have\ndifferent densities.\nThe :class:`~cluster.OPTICS` is first used with its Xi cluster detection\nmethod, and then setting specific thresholds on the reachability, which\ncorresponds to :class:`~cluster.DBSCAN`. We can see that the different\nclusters of OPTICS's Xi method can be recovered with different choices of\nthresholds in DBSCAN.\n\"\"\"\n\n\n# Authors: Shane Grigsby <refuge@rocktalus.com>\n# Adrin Jalali <adrin.jalali@gmail.com>\n# License: BSD 3 clause\n\n\nfrom sklearn.cluster import OPTICS, cluster_optics_dbscan\nimport matplotlib.gridspec as gridspec\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# Generate sample data\n\nnp.random.seed(0)\nn_points_per_cluster = 250\n\nC1 = [-5, -2] + .8 * np.random.randn(n_points_per_cluster, 2)\nC2 = [4, -1] + .1 * np.random.randn(n_points_per_cluster, 2)\nC3 = [1, -2] + .2 * np.random.randn(n_points_per_cluster, 2)\nC4 = [-2, 3] + .3 * np.random.randn(n_points_per_cluster, 2)\nC5 = [3, -2] + 1.6 * np.random.randn(n_points_per_cluster, 2)\nC6 = [5, 6] + 2 * np.random.randn(n_points_per_cluster, 2)\nX = np.vstack((C1, C2, C3, C4, C5, C6))\n\nclust = OPTICS(min_samples=50, xi=.05, min_cluster_size=.05)\n\n# Run the fit\nclust.fit(X)\n\nlabels_050 = cluster_optics_dbscan(reachability=clust.reachability_,\n core_distances=clust.core_distances_,\n ordering=clust.ordering_, eps=0.5)\nlabels_200 = cluster_optics_dbscan(reachability=clust.reachability_,\n core_distances=clust.core_distances_,\n ordering=clust.ordering_, eps=2)\n\nspace = np.arange(len(X))\nreachability = clust.reachability_[clust.ordering_]\nlabels = clust.labels_[clust.ordering_]\n\nplt.figure(figsize=(10, 7))\nG = gridspec.GridSpec(2, 3)\nax1 = plt.subplot(G[0, :])\nax2 = plt.subplot(G[1, 0])\nax3 = plt.subplot(G[1, 1])\nax4 = plt.subplot(G[1, 2])\n\n# Reachability plot\ncolors = ['g.', 'r.', 'b.', 'y.', 'c.']\nfor klass, color in zip(range(5), colors):\n Xk = space[labels == klass]\n Rk = reachability[labels == klass]\n ax1.plot(Xk, Rk, color, alpha=0.3)\nax1.plot(space[labels == -1], reachability[labels == -1], 'k.', alpha=0.3)\nax1.plot(space, np.full_like(space, 2., dtype=float), 'k-', alpha=0.5)\nax1.plot(space, np.full_like(space, 0.5, dtype=float), 'k-.', alpha=0.5)\nax1.set_ylabel('Reachability (epsilon distance)')\nax1.set_title('Reachability Plot')\n\n# OPTICS\ncolors = ['g.', 'r.', 'b.', 'y.', 'c.']\nfor klass, color in zip(range(5), colors):\n Xk = X[clust.labels_ == klass]\n ax2.plot(Xk[:, 0], Xk[:, 1], color, alpha=0.3)\nax2.plot(X[clust.labels_ == -1, 0], X[clust.labels_ == -1, 1], 'k+', alpha=0.1)\nax2.set_title('Automatic Clustering\\nOPTICS')\n\n# DBSCAN at 0.5\ncolors = ['g', 'greenyellow', 'olive', 'r', 'b', 'c']\nfor klass, color in zip(range(6), colors):\n Xk = X[labels_050 == klass]\n ax3.plot(Xk[:, 0], Xk[:, 1], color, alpha=0.3, marker='.')\nax3.plot(X[labels_050 == -1, 0], X[labels_050 == -1, 1], 'k+', alpha=0.1)\nax3.set_title('Clustering at 0.5 epsilon cut\\nDBSCAN')\n\n# DBSCAN at 2.\ncolors = ['g.', 'm.', 'y.', 'c.']\nfor klass, color in zip(range(4), colors):\n Xk = X[labels_200 == klass]\n ax4.plot(Xk[:, 0], Xk[:, 1], color, alpha=0.3)\nax4.plot(X[labels_200 == -1, 0], X[labels_200 == -1, 1], 'k+', alpha=0.1)\nax4.set_title('Clustering at 2.0 epsilon cut\\nDBSCAN')\n\nplt.tight_layout()\nplt.show()\n", "\"\"\"\nAgglomerative clustering with different metrics\n===============================================\n\nDemonstrates the effect of different metrics on the hierarchical clustering.\n\nThe example is engineered to show the effect of the choice of different\nmetrics. It is applied to waveforms, which can be seen as\nhigh-dimensional vector. Indeed, the difference between metrics is\nusually more pronounced in high dimension (in particular for euclidean\nand cityblock).\n\nWe generate data from three groups of waveforms. Two of the waveforms\n(waveform 1 and waveform 2) are proportional one to the other. The cosine\ndistance is invariant to a scaling of the data, as a result, it cannot\ndistinguish these two waveforms. Thus even with no noise, clustering\nusing this distance will not separate out waveform 1 and 2.\n\nWe add observation noise to these waveforms. We generate very sparse\nnoise: only 6% of the time points contain noise. As a result, the\nl1 norm of this noise (ie \"cityblock\" distance) is much smaller than it's\nl2 norm (\"euclidean\" distance). This can be seen on the inter-class\ndistance matrices: the values on the diagonal, that characterize the\nspread of the class, are much bigger for the Euclidean distance than for\nthe cityblock distance.\n\nWhen we apply clustering to the data, we find that the clustering\nreflects what was in the distance matrices. Indeed, for the Euclidean\ndistance, the classes are ill-separated because of the noise, and thus\nthe clustering does not separate the waveforms. For the cityblock\ndistance, the separation is good and the waveform classes are recovered.\nFinally, the cosine distance does not separate at all waveform 1 and 2,\nthus the clustering puts them in the same cluster.\n\"\"\"\n# Author: Gael Varoquaux\n# License: BSD 3-Clause or CC-0\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom sklearn.cluster import AgglomerativeClustering\nfrom sklearn.metrics import pairwise_distances\n\nnp.random.seed(0)\n\n# Generate waveform data\nn_features = 2000\nt = np.pi * np.linspace(0, 1, n_features)\n\n\ndef sqr(x):\n return np.sign(np.cos(x))\n\n\nX = []\ny = []\nfor i, (phi, a) in enumerate([(.5, .15), (.5, .6), (.3, .2)]):\n for _ in range(30):\n phase_noise = .01 * np.random.normal()\n amplitude_noise = .04 * np.random.normal()\n additional_noise = 1 - 2 * np.random.rand(n_features)\n # Make the noise sparse\n additional_noise[np.abs(additional_noise) < .997] = 0\n\n X.append(12 * ((a + amplitude_noise)\n * (sqr(6 * (t + phi + phase_noise)))\n + additional_noise))\n y.append(i)\n\nX = np.array(X)\ny = np.array(y)\n\nn_clusters = 3\n\nlabels = ('Waveform 1', 'Waveform 2', 'Waveform 3')\n\n# Plot the ground-truth labelling\nplt.figure()\nplt.axes([0, 0, 1, 1])\nfor l, c, n in zip(range(n_clusters), 'rgb',\n labels):\n lines = plt.plot(X[y == l].T, c=c, alpha=.5)\n lines[0].set_label(n)\n\nplt.legend(loc='best')\n\nplt.axis('tight')\nplt.axis('off')\nplt.suptitle(\"Ground truth\", size=20)\n\n\n# Plot the distances\nfor index, metric in enumerate([\"cosine\", \"euclidean\", \"cityblock\"]):\n avg_dist = np.zeros((n_clusters, n_clusters))\n plt.figure(figsize=(5, 4.5))\n for i in range(n_clusters):\n for j in range(n_clusters):\n avg_dist[i, j] = pairwise_distances(X[y == i], X[y == j],\n metric=metric).mean()\n avg_dist /= avg_dist.max()\n for i in range(n_clusters):\n for j in range(n_clusters):\n plt.text(i, j, '%5.3f' % avg_dist[i, j],\n verticalalignment='center',\n horizontalalignment='center')\n\n plt.imshow(avg_dist, interpolation='nearest', cmap=plt.cm.gnuplot2,\n vmin=0)\n plt.xticks(range(n_clusters), labels, rotation=45)\n plt.yticks(range(n_clusters), labels)\n plt.colorbar()\n plt.suptitle(\"Interclass %s distances\" % metric, size=18)\n plt.tight_layout()\n\n\n# Plot clustering results\nfor index, metric in enumerate([\"cosine\", \"euclidean\", \"cityblock\"]):\n model = AgglomerativeClustering(n_clusters=n_clusters,\n linkage=\"average\", affinity=metric)\n model.fit(X)\n plt.figure()\n plt.axes([0, 0, 1, 1])\n for l, c in zip(np.arange(model.n_clusters), 'rgbk'):\n plt.plot(X[model.labels_ == l].T, c=c, alpha=.5)\n plt.axis('tight')\n plt.axis('off')\n plt.suptitle(\"AgglomerativeClustering(affinity=%s)\" % metric, size=20)\n\n\nplt.show()\n" ]
[ [ "sklearn.cluster.cluster_optics_dbscan", "numpy.random.seed", "numpy.full_like", "numpy.random.randn", "matplotlib.pyplot.figure", "sklearn.cluster.OPTICS", "matplotlib.pyplot.tight_layout", "matplotlib.pyplot.show", "matplotlib.gridspec.GridSpec", "numpy.vstack", "matplotlib.pyplot.subplot" ], [ "matplotlib.pyplot.text", "numpy.random.rand", "numpy.cos", "numpy.random.normal", "matplotlib.pyplot.colorbar", "sklearn.cluster.AgglomerativeClustering", "sklearn.metrics.pairwise_distances", "numpy.arange", "matplotlib.pyplot.tight_layout", "matplotlib.pyplot.axes", "matplotlib.pyplot.axis", "numpy.array", "numpy.zeros", "matplotlib.pyplot.figure", "matplotlib.pyplot.show", "numpy.random.seed", "matplotlib.pyplot.suptitle", "matplotlib.pyplot.legend", "matplotlib.pyplot.plot", "numpy.abs", "numpy.linspace", "matplotlib.pyplot.imshow" ] ]
gameon67/tensorflow
[ "be647ad9512f7d2b891494ef8abbbde46e2e0663" ]
[ "tensorflow/contrib/tensor_forest/python/tensor_forest.py" ]
[ "# pylint: disable=g-bad-file-header\n# Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Extremely random forest graph builder. go/brain-tree.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport math\nimport random\n\nfrom tensorflow.contrib.tensor_forest.python import constants\nfrom tensorflow.contrib.tensor_forest.python.ops import inference_ops\nfrom tensorflow.contrib.tensor_forest.python.ops import training_ops\n\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import init_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import random_ops\nfrom tensorflow.python.ops import state_ops\nfrom tensorflow.python.ops import variable_scope\nfrom tensorflow.python.ops import variables as tf_variables\nfrom tensorflow.python.platform import tf_logging as logging\n\n\n# A convenience class for holding random forest hyperparameters.\n#\n# To just get some good default parameters, use:\n# hparams = ForestHParams(num_classes=2, num_features=40).fill()\n#\n# Note that num_classes can not be inferred and so must always be specified.\n# Also, either num_splits_to_consider or num_features should be set.\n#\n# To override specific values, pass them to the constructor:\n# hparams = ForestHParams(num_classes=5, num_trees=10, num_features=5).fill()\n#\n# TODO(thomaswc): Inherit from tf.HParams when that is publicly available.\nclass ForestHParams(object):\n \"\"\"A base class for holding hyperparameters and calculating good defaults.\"\"\"\n\n def __init__(self, num_trees=100, max_nodes=10000, bagging_fraction=1.0,\n max_depth=0, num_splits_to_consider=0,\n feature_bagging_fraction=1.0,\n max_fertile_nodes=0, split_after_samples=250,\n min_split_samples=5,\n valid_leaf_threshold=1, **kwargs):\n self.num_trees = num_trees\n self.max_nodes = max_nodes\n self.bagging_fraction = bagging_fraction\n self.feature_bagging_fraction = feature_bagging_fraction\n self.max_depth = max_depth\n self.num_splits_to_consider = num_splits_to_consider\n self.max_fertile_nodes = max_fertile_nodes\n self.split_after_samples = split_after_samples\n self.min_split_samples = min_split_samples\n self.valid_leaf_threshold = valid_leaf_threshold\n\n for name, value in kwargs.items():\n setattr(self, name, value)\n\n def values(self):\n return self.__dict__\n\n def fill(self):\n \"\"\"Intelligently sets any non-specific parameters.\"\"\"\n # Fail fast if num_classes or num_features isn't set.\n _ = getattr(self, 'num_classes')\n _ = getattr(self, 'num_features')\n\n self.bagged_num_features = int(self.feature_bagging_fraction *\n self.num_features)\n\n self.bagged_features = None\n if self.feature_bagging_fraction < 1.0:\n self.bagged_features = [random.sample(\n range(self.num_features),\n self.bagged_num_features) for _ in range(self.num_trees)]\n\n self.regression = getattr(self, 'regression', False)\n\n # Num_outputs is the actual number of outputs (a single prediction for\n # classification, a N-dimenensional point for regression).\n self.num_outputs = self.num_classes if self.regression else 1\n\n # Add an extra column to classes for storing counts, which is needed for\n # regression and avoids having to recompute sums for classification.\n self.num_output_columns = self.num_classes + 1\n\n # Allow each tree to be unbalanced by up to a factor of 2.\n self.max_depth = (self.max_depth or\n int(2 * math.ceil(math.log(self.max_nodes, 2))))\n\n # The Random Forest literature recommends sqrt(# features) for\n # classification problems, and p/3 for regression problems.\n # TODO(thomaswc): Consider capping this for large number of features.\n self.num_splits_to_consider = (\n self.num_splits_to_consider or\n max(10, int(math.ceil(math.sqrt(self.num_features)))))\n\n # max_fertile_nodes doesn't effect performance, only training speed.\n # We therefore set it primarily based upon space considerations.\n # Each fertile node takes up num_splits_to_consider times as much\n # as space as a non-fertile node. We want the fertile nodes to in\n # total only take up as much space as the non-fertile nodes, so\n num_fertile = int(math.ceil(self.max_nodes / self.num_splits_to_consider))\n # But always use at least 1000 accumulate slots.\n num_fertile = max(num_fertile, 1000)\n self.max_fertile_nodes = self.max_fertile_nodes or num_fertile\n # But it also never needs to be larger than the number of leaves,\n # which is max_nodes / 2.\n self.max_fertile_nodes = min(self.max_fertile_nodes,\n int(math.ceil(self.max_nodes / 2.0)))\n\n # We have num_splits_to_consider slots to fill, and we want to spend\n # approximately split_after_samples samples initializing them.\n num_split_initializiations_per_input = max(1, int(math.floor(\n self.num_splits_to_consider / self.split_after_samples)))\n self.split_initializations_per_input = getattr(\n self, 'split_initializations_per_input',\n num_split_initializiations_per_input)\n\n # If base_random_seed is 0, the current time will be used to seed the\n # random number generators for each tree. If non-zero, the i-th tree\n # will be seeded with base_random_seed + i.\n self.base_random_seed = getattr(self, 'base_random_seed', 0)\n\n return self\n\n\n# A simple container to hold the training variables for a single tree.\nclass TreeTrainingVariables(object):\n \"\"\"Stores tf.Variables for training a single random tree.\n\n Uses tf.get_variable to get tree-specific names so that this can be used\n with a tf.learn-style implementation (one that trains a model, saves it,\n then relies on restoring that model to evaluate).\n \"\"\"\n\n def __init__(self, params, tree_num, training):\n self.tree = variable_scope.get_variable(\n name=self.get_tree_name('tree', tree_num), dtype=dtypes.int32,\n shape=[params.max_nodes, 2],\n initializer=init_ops.constant_initializer(-2))\n self.tree_thresholds = variable_scope.get_variable(\n name=self.get_tree_name('tree_thresholds', tree_num),\n shape=[params.max_nodes],\n initializer=init_ops.constant_initializer(-1.0))\n self.tree_depths = variable_scope.get_variable(\n name=self.get_tree_name('tree_depths', tree_num),\n shape=[params.max_nodes],\n dtype=dtypes.int32,\n initializer=init_ops.constant_initializer(1))\n self.end_of_tree = variable_scope.get_variable(\n name=self.get_tree_name('end_of_tree', tree_num),\n dtype=dtypes.int32,\n initializer=constant_op.constant([1]))\n self.start_epoch = tf_variables.Variable(\n [0] * (params.max_nodes), name='start_epoch')\n\n if training:\n self.node_to_accumulator_map = variable_scope.get_variable(\n name=self.get_tree_name('node_to_accumulator_map', tree_num),\n shape=[params.max_nodes],\n dtype=dtypes.int32,\n initializer=init_ops.constant_initializer(-1))\n\n self.candidate_split_features = variable_scope.get_variable(\n name=self.get_tree_name('candidate_split_features', tree_num),\n shape=[params.max_fertile_nodes, params.num_splits_to_consider],\n dtype=dtypes.int32,\n initializer=init_ops.constant_initializer(-1))\n self.candidate_split_thresholds = variable_scope.get_variable(\n name=self.get_tree_name('candidate_split_thresholds', tree_num),\n shape=[params.max_fertile_nodes, params.num_splits_to_consider],\n initializer=init_ops.constant_initializer(0.0))\n\n # Statistics shared by classification and regression.\n self.node_sums = variable_scope.get_variable(\n name=self.get_tree_name('node_sums', tree_num),\n shape=[params.max_nodes, params.num_output_columns],\n initializer=init_ops.constant_initializer(0.0))\n\n if training:\n self.candidate_split_sums = variable_scope.get_variable(\n name=self.get_tree_name('candidate_split_sums', tree_num),\n shape=[params.max_fertile_nodes, params.num_splits_to_consider,\n params.num_output_columns],\n initializer=init_ops.constant_initializer(0.0))\n self.accumulator_sums = variable_scope.get_variable(\n name=self.get_tree_name('accumulator_sums', tree_num),\n shape=[params.max_fertile_nodes, params.num_output_columns],\n initializer=init_ops.constant_initializer(-1.0))\n\n # Regression also tracks second order stats.\n if params.regression:\n self.node_squares = variable_scope.get_variable(\n name=self.get_tree_name('node_squares', tree_num),\n shape=[params.max_nodes, params.num_output_columns],\n initializer=init_ops.constant_initializer(0.0))\n\n self.candidate_split_squares = variable_scope.get_variable(\n name=self.get_tree_name('candidate_split_squares', tree_num),\n shape=[params.max_fertile_nodes, params.num_splits_to_consider,\n params.num_output_columns],\n initializer=init_ops.constant_initializer(0.0))\n\n self.accumulator_squares = variable_scope.get_variable(\n name=self.get_tree_name('accumulator_squares', tree_num),\n shape=[params.max_fertile_nodes, params.num_output_columns],\n initializer=init_ops.constant_initializer(-1.0))\n\n else:\n self.node_squares = constant_op.constant(\n 0.0, name=self.get_tree_name('node_squares', tree_num))\n\n self.candidate_split_squares = constant_op.constant(\n 0.0, name=self.get_tree_name('candidate_split_squares', tree_num))\n\n self.accumulator_squares = constant_op.constant(\n 0.0, name=self.get_tree_name('accumulator_squares', tree_num))\n\n def get_tree_name(self, name, num):\n return '{0}-{1}'.format(name, num)\n\n\nclass ForestStats(object):\n\n def __init__(self, tree_stats, params):\n \"\"\"A simple container for stats about a forest.\"\"\"\n self.tree_stats = tree_stats\n self.params = params\n\n def get_average(self, thing):\n val = 0.0\n for i in range(self.params.num_trees):\n val += getattr(self.tree_stats[i], thing)\n\n return val / self.params.num_trees\n\n\nclass TreeStats(object):\n\n def __init__(self, num_nodes, num_leaves):\n self.num_nodes = num_nodes\n self.num_leaves = num_leaves\n\n\nclass ForestTrainingVariables(object):\n \"\"\"A container for a forests training data, consisting of multiple trees.\n\n Instantiates a TreeTrainingVariables object for each tree. We override the\n __getitem__ and __setitem__ function so that usage looks like this:\n\n forest_variables = ForestTrainingVariables(params)\n\n ... forest_variables.tree ...\n \"\"\"\n\n def __init__(self, params, device_assigner, training=True,\n tree_variables_class=TreeTrainingVariables):\n self.variables = []\n for i in range(params.num_trees):\n with ops.device(device_assigner.get_device(i)):\n self.variables.append(tree_variables_class(params, i, training))\n\n def __setitem__(self, t, val):\n self.variables[t] = val\n\n def __getitem__(self, t):\n return self.variables[t]\n\n\nclass RandomForestDeviceAssigner(object):\n \"\"\"A device assigner that uses the default device.\n\n Write subclasses that implement get_device for control over how trees\n get assigned to devices. This assumes that whole trees are assigned\n to a device.\n \"\"\"\n\n def __init__(self):\n self.cached = None\n\n def get_device(self, unused_tree_num):\n if not self.cached:\n dummy = constant_op.constant(0)\n self.cached = dummy.device\n\n return self.cached\n\n\nclass RandomForestGraphs(object):\n \"\"\"Builds TF graphs for random forest training and inference.\"\"\"\n\n def __init__(self, params, device_assigner=None,\n variables=None, tree_variables_class=TreeTrainingVariables,\n tree_graphs=None, training=True,\n t_ops=training_ops,\n i_ops=inference_ops):\n self.params = params\n self.device_assigner = device_assigner or RandomForestDeviceAssigner()\n logging.info('Constructing forest with params = ')\n logging.info(self.params.__dict__)\n self.variables = variables or ForestTrainingVariables(\n self.params, device_assigner=self.device_assigner, training=training,\n tree_variables_class=tree_variables_class)\n tree_graph_class = tree_graphs or RandomTreeGraphs\n self.trees = [\n tree_graph_class(\n self.variables[i], self.params,\n t_ops.Load(), i_ops.Load(), i)\n for i in range(self.params.num_trees)]\n\n def _bag_features(self, tree_num, input_data):\n split_data = array_ops.split(1, self.params.num_features, input_data)\n return array_ops.concat(\n 1, [split_data[ind] for ind in self.params.bagged_features[tree_num]])\n\n def training_graph(self, input_data, input_labels, data_spec=None,\n epoch=None, **tree_kwargs):\n \"\"\"Constructs a TF graph for training a random forest.\n\n Args:\n input_data: A tensor or SparseTensor or placeholder for input data.\n input_labels: A tensor or placeholder for labels associated with\n input_data.\n data_spec: A list of tf.dtype values specifying the original types of\n each column.\n epoch: A tensor or placeholder for the epoch the training data comes from.\n **tree_kwargs: Keyword arguments passed to each tree's training_graph.\n\n Returns:\n The last op in the random forest training graph.\n \"\"\"\n data_spec = ([constants.DATA_FLOAT] * self.params.num_features\n if data_spec is None else data_spec)\n tree_graphs = []\n for i in range(self.params.num_trees):\n with ops.device(self.device_assigner.get_device(i)):\n seed = self.params.base_random_seed\n if seed != 0:\n seed += i\n # If using bagging, randomly select some of the input.\n tree_data = input_data\n tree_labels = input_labels\n if self.params.bagging_fraction < 1.0:\n # TODO(thomaswc): This does sampling without replacment. Consider\n # also allowing sampling with replacement as an option.\n batch_size = array_ops.slice(array_ops.shape(input_data), [0], [1])\n r = random_ops.random_uniform(batch_size, seed=seed)\n mask = math_ops.less(\n r, array_ops.ones_like(r) * self.params.bagging_fraction)\n gather_indices = array_ops.squeeze(\n array_ops.where(mask), squeeze_dims=[1])\n # TODO(thomaswc): Calculate out-of-bag data and labels, and store\n # them for use in calculating statistics later.\n tree_data = array_ops.gather(input_data, gather_indices)\n tree_labels = array_ops.gather(input_labels, gather_indices)\n if self.params.bagged_features:\n tree_data = self._bag_features(i, tree_data)\n\n initialization = self.trees[i].tree_initialization()\n\n with ops.control_dependencies([initialization]):\n tree_graphs.append(\n self.trees[i].training_graph(\n tree_data, tree_labels, seed, data_spec=data_spec,\n epoch=([0] if epoch is None else epoch),\n **tree_kwargs))\n\n return control_flow_ops.group(*tree_graphs)\n\n def inference_graph(self, input_data, data_spec=None):\n \"\"\"Constructs a TF graph for evaluating a random forest.\n\n Args:\n input_data: A tensor or SparseTensor or placeholder for input data.\n data_spec: A list of tf.dtype values specifying the original types of\n each column.\n\n Returns:\n The last op in the random forest inference graph.\n \"\"\"\n data_spec = ([constants.DATA_FLOAT] * self.params.num_features\n if data_spec is None else data_spec)\n probabilities = []\n for i in range(self.params.num_trees):\n with ops.device(self.device_assigner.get_device(i)):\n tree_data = input_data\n if self.params.bagged_features:\n tree_data = self._bag_features(i, input_data)\n probabilities.append(self.trees[i].inference_graph(tree_data,\n data_spec))\n with ops.device(self.device_assigner.get_device(0)):\n all_predict = array_ops.pack(probabilities)\n return math_ops.reduce_sum(all_predict, 0) / self.params.num_trees\n\n def average_size(self):\n \"\"\"Constructs a TF graph for evaluating the average size of a forest.\n\n Returns:\n The average number of nodes over the trees.\n \"\"\"\n sizes = []\n for i in range(self.params.num_trees):\n with ops.device(self.device_assigner.get_device(i)):\n sizes.append(self.trees[i].size())\n return math_ops.reduce_mean(array_ops.pack(sizes))\n\n def training_loss(self):\n return math_ops.neg(self.average_size())\n\n # pylint: disable=unused-argument\n def validation_loss(self, features, labels):\n return math_ops.neg(self.average_size())\n\n def average_impurity(self):\n \"\"\"Constructs a TF graph for evaluating the leaf impurity of a forest.\n\n Returns:\n The last op in the graph.\n \"\"\"\n impurities = []\n for i in range(self.params.num_trees):\n with ops.device(self.device_assigner.get_device(i)):\n impurities.append(self.trees[i].average_impurity())\n return math_ops.reduce_mean(array_ops.pack(impurities))\n\n def get_stats(self, session):\n tree_stats = []\n for i in range(self.params.num_trees):\n with ops.device(self.device_assigner.get_device(i)):\n tree_stats.append(self.trees[i].get_stats(session))\n return ForestStats(tree_stats, self.params)\n\n\nclass RandomTreeGraphs(object):\n \"\"\"Builds TF graphs for random tree training and inference.\"\"\"\n\n def __init__(self, variables, params, t_ops, i_ops, tree_num):\n self.training_ops = t_ops\n self.inference_ops = i_ops\n self.variables = variables\n self.params = params\n self.tree_num = tree_num\n\n def tree_initialization(self):\n def _init_tree():\n return state_ops.scatter_update(self.variables.tree, [0], [[-1, -1]]).op\n\n def _nothing():\n return control_flow_ops.no_op()\n\n return control_flow_ops.cond(\n math_ops.equal(array_ops.squeeze(array_ops.slice(\n self.variables.tree, [0, 0], [1, 1])), -2),\n _init_tree, _nothing)\n\n def _gini(self, class_counts):\n \"\"\"Calculate the Gini impurity.\n\n If c(i) denotes the i-th class count and c = sum_i c(i) then\n score = 1 - sum_i ( c(i) / c )^2\n\n Args:\n class_counts: A 2-D tensor of per-class counts, usually a slice or\n gather from variables.node_sums.\n\n Returns:\n A 1-D tensor of the Gini impurities for each row in the input.\n \"\"\"\n smoothed = 1.0 + array_ops.slice(class_counts, [0, 1], [-1, -1])\n sums = math_ops.reduce_sum(smoothed, 1)\n sum_squares = math_ops.reduce_sum(math_ops.square(smoothed), 1)\n\n return 1.0 - sum_squares / (sums * sums)\n\n def _weighted_gini(self, class_counts):\n \"\"\"Our split score is the Gini impurity times the number of examples.\n\n If c(i) denotes the i-th class count and c = sum_i c(i) then\n score = c * (1 - sum_i ( c(i) / c )^2 )\n = c - sum_i c(i)^2 / c\n Args:\n class_counts: A 2-D tensor of per-class counts, usually a slice or\n gather from variables.node_sums.\n\n Returns:\n A 1-D tensor of the Gini impurities for each row in the input.\n \"\"\"\n smoothed = 1.0 + array_ops.slice(class_counts, [0, 1], [-1, -1])\n sums = math_ops.reduce_sum(smoothed, 1)\n sum_squares = math_ops.reduce_sum(math_ops.square(smoothed), 1)\n\n return sums - sum_squares / sums\n\n def _variance(self, sums, squares):\n \"\"\"Calculate the variance for each row of the input tensors.\n\n Variance is V = E[x^2] - (E[x])^2.\n\n Args:\n sums: A tensor containing output sums, usually a slice from\n variables.node_sums. Should contain the number of examples seen\n in index 0 so we can calculate expected value.\n squares: Same as sums, but sums of squares.\n\n Returns:\n A 1-D tensor of the variances for each row in the input.\n \"\"\"\n total_count = array_ops.slice(sums, [0, 0], [-1, 1])\n e_x = sums / total_count\n e_x2 = squares / total_count\n\n return math_ops.reduce_sum(e_x2 - math_ops.square(e_x), 1)\n\n def training_graph(self, input_data, input_labels, random_seed,\n data_spec, epoch=None):\n\n \"\"\"Constructs a TF graph for training a random tree.\n\n Args:\n input_data: A tensor or SparseTensor or placeholder for input data.\n input_labels: A tensor or placeholder for labels associated with\n input_data.\n random_seed: The random number generator seed to use for this tree. 0\n means use the current time as the seed.\n data_spec: A list of tf.dtype values specifying the original types of\n each column.\n epoch: A tensor or placeholder for the epoch the training data comes from.\n\n Returns:\n The last op in the random tree training graph.\n \"\"\"\n epoch = [0] if epoch is None else epoch\n\n sparse_indices = []\n sparse_values = []\n sparse_shape = []\n if isinstance(input_data, ops.SparseTensor):\n sparse_indices = input_data.indices\n sparse_values = input_data.values\n sparse_shape = input_data.shape\n input_data = []\n\n # Count extremely random stats.\n (node_sums, node_squares, splits_indices, splits_sums,\n splits_squares, totals_indices, totals_sums,\n totals_squares, input_leaves) = (\n self.training_ops.count_extremely_random_stats(\n input_data, sparse_indices, sparse_values, sparse_shape,\n data_spec, input_labels, self.variables.tree,\n self.variables.tree_thresholds,\n self.variables.node_to_accumulator_map,\n self.variables.candidate_split_features,\n self.variables.candidate_split_thresholds,\n self.variables.start_epoch, epoch,\n num_classes=self.params.num_output_columns,\n regression=self.params.regression))\n node_update_ops = []\n node_update_ops.append(\n state_ops.assign_add(self.variables.node_sums, node_sums))\n\n splits_update_ops = []\n splits_update_ops.append(self.training_ops.scatter_add_ndim(\n self.variables.candidate_split_sums,\n splits_indices, splits_sums))\n splits_update_ops.append(self.training_ops.scatter_add_ndim(\n self.variables.accumulator_sums, totals_indices,\n totals_sums))\n\n if self.params.regression:\n node_update_ops.append(state_ops.assign_add(self.variables.node_squares,\n node_squares))\n splits_update_ops.append(self.training_ops.scatter_add_ndim(\n self.variables.candidate_split_squares,\n splits_indices, splits_squares))\n splits_update_ops.append(self.training_ops.scatter_add_ndim(\n self.variables.accumulator_squares, totals_indices,\n totals_squares))\n\n # Sample inputs.\n update_indices, feature_updates, threshold_updates = (\n self.training_ops.sample_inputs(\n input_data, sparse_indices, sparse_values, sparse_shape,\n self.variables.node_to_accumulator_map,\n input_leaves, self.variables.candidate_split_features,\n self.variables.candidate_split_thresholds,\n split_initializations_per_input=(\n self.params.split_initializations_per_input),\n split_sampling_random_seed=random_seed))\n update_features_op = state_ops.scatter_update(\n self.variables.candidate_split_features, update_indices,\n feature_updates)\n update_thresholds_op = state_ops.scatter_update(\n self.variables.candidate_split_thresholds, update_indices,\n threshold_updates)\n\n # Calculate finished nodes.\n with ops.control_dependencies(splits_update_ops):\n children = array_ops.squeeze(array_ops.slice(\n self.variables.tree, [0, 0], [-1, 1]), squeeze_dims=[1])\n is_leaf = math_ops.equal(constants.LEAF_NODE, children)\n leaves = math_ops.to_int32(array_ops.squeeze(array_ops.where(is_leaf),\n squeeze_dims=[1]))\n finished, stale = self.training_ops.finished_nodes(\n leaves, self.variables.node_to_accumulator_map,\n self.variables.candidate_split_sums,\n self.variables.candidate_split_squares,\n self.variables.accumulator_sums,\n self.variables.accumulator_squares,\n self.variables.start_epoch, epoch,\n num_split_after_samples=self.params.split_after_samples,\n min_split_samples=self.params.min_split_samples)\n\n # Update leaf scores.\n non_fertile_leaves = array_ops.boolean_mask(\n leaves, math_ops.less(array_ops.gather(\n self.variables.node_to_accumulator_map, leaves), 0))\n\n # TODO(gilberth): It should be possible to limit the number of non\n # fertile leaves we calculate scores for, especially since we can only take\n # at most array_ops.shape(finished)[0] of them.\n with ops.control_dependencies(node_update_ops):\n sums = array_ops.gather(self.variables.node_sums, non_fertile_leaves)\n if self.params.regression:\n squares = array_ops.gather(self.variables.node_squares,\n non_fertile_leaves)\n non_fertile_leaf_scores = self._variance(sums, squares)\n else:\n non_fertile_leaf_scores = self._weighted_gini(sums)\n\n # Calculate best splits.\n with ops.control_dependencies(splits_update_ops):\n split_indices = self.training_ops.best_splits(\n finished, self.variables.node_to_accumulator_map,\n self.variables.candidate_split_sums,\n self.variables.candidate_split_squares,\n self.variables.accumulator_sums,\n self.variables.accumulator_squares,\n regression=self.params.regression)\n\n # Grow tree.\n with ops.control_dependencies([update_features_op, update_thresholds_op]):\n (tree_update_indices, tree_children_updates,\n tree_threshold_updates, tree_depth_updates, new_eot) = (\n self.training_ops.grow_tree(\n self.variables.end_of_tree, self.variables.tree_depths,\n self.variables.node_to_accumulator_map, finished, split_indices,\n self.variables.candidate_split_features,\n self.variables.candidate_split_thresholds))\n tree_update_op = state_ops.scatter_update(\n self.variables.tree, tree_update_indices, tree_children_updates)\n thresholds_update_op = state_ops.scatter_update(\n self.variables.tree_thresholds, tree_update_indices,\n tree_threshold_updates)\n depth_update_op = state_ops.scatter_update(\n self.variables.tree_depths, tree_update_indices, tree_depth_updates)\n # TODO(thomaswc): Only update the epoch on the new leaves.\n new_epoch_updates = epoch * array_ops.ones_like(tree_depth_updates)\n epoch_update_op = state_ops.scatter_update(\n self.variables.start_epoch, tree_update_indices,\n new_epoch_updates)\n\n # Update fertile slots.\n with ops.control_dependencies([depth_update_op]):\n (node_map_updates, accumulators_cleared, accumulators_allocated) = (\n self.training_ops.update_fertile_slots(\n finished, non_fertile_leaves,\n non_fertile_leaf_scores,\n self.variables.end_of_tree, self.variables.tree_depths,\n self.variables.accumulator_sums,\n self.variables.node_to_accumulator_map,\n stale,\n max_depth=self.params.max_depth,\n regression=self.params.regression))\n\n # Ensure end_of_tree doesn't get updated until UpdateFertileSlots has\n # used it to calculate new leaves.\n gated_new_eot, = control_flow_ops.tuple([new_eot],\n control_inputs=[node_map_updates])\n eot_update_op = state_ops.assign(self.variables.end_of_tree, gated_new_eot)\n\n updates = []\n updates.append(eot_update_op)\n updates.append(tree_update_op)\n updates.append(thresholds_update_op)\n updates.append(epoch_update_op)\n\n updates.append(state_ops.scatter_update(\n self.variables.node_to_accumulator_map,\n array_ops.squeeze(array_ops.slice(node_map_updates, [0, 0], [1, -1]),\n squeeze_dims=[0]),\n array_ops.squeeze(array_ops.slice(node_map_updates, [1, 0], [1, -1]),\n squeeze_dims=[0])))\n\n cleared_and_allocated_accumulators = array_ops.concat(\n 0, [accumulators_cleared, accumulators_allocated])\n # Calculate values to put into scatter update for candidate counts.\n # Candidate split counts are always reset back to 0 for both cleared\n # and allocated accumulators. This means some accumulators might be doubly\n # reset to 0 if the were released and not allocated, then later allocated.\n split_values = array_ops.tile(\n array_ops.expand_dims(array_ops.expand_dims(\n array_ops.zeros_like(cleared_and_allocated_accumulators,\n dtype=dtypes.float32), 1), 2),\n [1, self.params.num_splits_to_consider, self.params.num_output_columns])\n updates.append(state_ops.scatter_update(\n self.variables.candidate_split_sums,\n cleared_and_allocated_accumulators, split_values))\n if self.params.regression:\n updates.append(state_ops.scatter_update(\n self.variables.candidate_split_squares,\n cleared_and_allocated_accumulators, split_values))\n\n # Calculate values to put into scatter update for total counts.\n total_cleared = array_ops.tile(\n array_ops.expand_dims(\n math_ops.neg(array_ops.ones_like(accumulators_cleared,\n dtype=dtypes.float32)), 1),\n [1, self.params.num_output_columns])\n total_reset = array_ops.tile(\n array_ops.expand_dims(\n array_ops.zeros_like(accumulators_allocated,\n dtype=dtypes.float32), 1),\n [1, self.params.num_output_columns])\n accumulator_updates = array_ops.concat(0, [total_cleared, total_reset])\n updates.append(state_ops.scatter_update(\n self.variables.accumulator_sums,\n cleared_and_allocated_accumulators, accumulator_updates))\n if self.params.regression:\n updates.append(state_ops.scatter_update(\n self.variables.accumulator_squares,\n cleared_and_allocated_accumulators, accumulator_updates))\n\n # Calculate values to put into scatter update for candidate splits.\n split_features_updates = array_ops.tile(\n array_ops.expand_dims(\n math_ops.neg(array_ops.ones_like(\n cleared_and_allocated_accumulators)), 1),\n [1, self.params.num_splits_to_consider])\n updates.append(state_ops.scatter_update(\n self.variables.candidate_split_features,\n cleared_and_allocated_accumulators, split_features_updates))\n\n updates += self.finish_iteration()\n\n return control_flow_ops.group(*updates)\n\n def finish_iteration(self):\n \"\"\"Perform any operations that should be done at the end of an iteration.\n\n This is mostly useful for subclasses that need to reset variables after\n an iteration, such as ones that are used to finish nodes.\n\n Returns:\n A list of operations.\n \"\"\"\n return []\n\n def inference_graph(self, input_data, data_spec):\n \"\"\"Constructs a TF graph for evaluating a random tree.\n\n Args:\n input_data: A tensor or SparseTensor or placeholder for input data.\n data_spec: A list of tf.dtype values specifying the original types of\n each column.\n\n Returns:\n The last op in the random tree inference graph.\n \"\"\"\n sparse_indices = []\n sparse_values = []\n sparse_shape = []\n if isinstance(input_data, ops.SparseTensor):\n sparse_indices = input_data.indices\n sparse_values = input_data.values\n sparse_shape = input_data.shape\n input_data = []\n return self.inference_ops.tree_predictions(\n input_data, sparse_indices, sparse_values, sparse_shape, data_spec,\n self.variables.tree,\n self.variables.tree_thresholds,\n self.variables.node_sums,\n valid_leaf_threshold=self.params.valid_leaf_threshold)\n\n def average_impurity(self):\n \"\"\"Constructs a TF graph for evaluating the average leaf impurity of a tree.\n\n If in regression mode, this is the leaf variance. If in classification mode,\n this is the gini impurity.\n\n Returns:\n The last op in the graph.\n \"\"\"\n children = array_ops.squeeze(array_ops.slice(\n self.variables.tree, [0, 0], [-1, 1]), squeeze_dims=[1])\n is_leaf = math_ops.equal(constants.LEAF_NODE, children)\n leaves = math_ops.to_int32(array_ops.squeeze(array_ops.where(is_leaf),\n squeeze_dims=[1]))\n counts = array_ops.gather(self.variables.node_sums, leaves)\n gini = self._weighted_gini(counts)\n # Guard against step 1, when there often are no leaves yet.\n def impurity():\n return gini\n # Since average impurity can be used for loss, when there's no data just\n # return a big number so that loss always decreases.\n def big():\n return array_ops.ones_like(gini, dtype=dtypes.float32) * 10000000.\n return control_flow_ops.cond(math_ops.greater(\n array_ops.shape(leaves)[0], 0), impurity, big)\n\n def size(self):\n \"\"\"Constructs a TF graph for evaluating the current number of nodes.\n\n Returns:\n The current number of nodes in the tree.\n \"\"\"\n return self.variables.end_of_tree - 1\n\n def get_stats(self, session):\n num_nodes = self.variables.end_of_tree.eval(session=session) - 1\n num_leaves = array_ops.where(\n math_ops.equal(array_ops.squeeze(array_ops.slice(\n self.variables.tree, [0, 0], [-1, 1])), constants.LEAF_NODE)\n ).eval(session=session).shape[0]\n return TreeStats(num_nodes, num_leaves)\n" ]
[ [ "tensorflow.python.ops.variables.Variable", "tensorflow.python.ops.control_flow_ops.tuple", "tensorflow.python.ops.math_ops.equal", "tensorflow.python.ops.state_ops.assign_add", "tensorflow.python.ops.state_ops.assign", "tensorflow.python.ops.array_ops.where", "tensorflow.python.ops.math_ops.reduce_sum", "tensorflow.python.ops.array_ops.ones_like", "tensorflow.python.framework.ops.control_dependencies", "tensorflow.python.ops.array_ops.concat", "tensorflow.python.ops.init_ops.constant_initializer", "tensorflow.python.ops.array_ops.split", "tensorflow.python.ops.random_ops.random_uniform", "tensorflow.python.ops.array_ops.gather", "tensorflow.python.platform.tf_logging.info", "tensorflow.python.ops.control_flow_ops.no_op", "tensorflow.python.ops.math_ops.square", "tensorflow.python.ops.state_ops.scatter_update", "tensorflow.python.ops.control_flow_ops.group", "tensorflow.python.ops.array_ops.zeros_like", "tensorflow.python.framework.constant_op.constant", "tensorflow.python.ops.array_ops.shape", "tensorflow.python.ops.array_ops.pack", "tensorflow.python.ops.array_ops.slice" ] ]
ArgonneCPAC/dsps
[ "a08da74cf9df4b12197805531d0b273d98ed5da6" ]
[ "dsps/tests/test_stellar_ages.py" ]
[ "\"\"\"\n\"\"\"\nimport numpy as np\nfrom ..stellar_ages import _get_lg_age_bin_edges, _get_lgt_birth, T_BIRTH_MIN\nfrom ..stellar_ages import _get_sfh_tables, _get_age_weights_from_tables\nfrom ..sfh_model import DEFAULT_MAH_PARAMS, DEFAULT_MS_PARAMS, DEFAULT_Q_PARAMS\nfrom ..utils import _jax_get_dt_array\n\n\nFSPS_LG_AGES = np.arange(5.5, 10.2, 0.05) # log10 ages in years\n\n\ndef linear_sfr(t_gyr):\n return t_gyr * 1e9\n\n\ndef linear_smh(t0, t_gyr):\n return 1e9 * 0.5 * (t_gyr ** 2 - t0 ** 2)\n\n\ndef test_age_bin_edges_have_correct_array_shape():\n lgt_ages = np.linspace(5.5, 10.5, 50)\n lgt_age_bins = _get_lg_age_bin_edges(lgt_ages)\n assert lgt_age_bins.size == lgt_ages.size + 1\n\n\ndef test_age_weights_are_mathematically_sensible():\n t_obs = 11.0\n mah_params = np.array(list(DEFAULT_MAH_PARAMS.values()))\n ms_params = np.array(list(DEFAULT_MS_PARAMS.values()))\n q_params = np.array(list(DEFAULT_Q_PARAMS.values()))\n res = _get_sfh_tables(mah_params, ms_params, q_params)\n t_table, lgt_table, dt_table, sfh_table, logsm_table = res\n\n lgt_ages = np.linspace(5.5, 10.5, 50) - 9.0\n lgt_age_bin_edges = _get_lg_age_bin_edges(lgt_ages)\n lgt_birth_bin_edges = _get_lgt_birth(t_obs, lgt_age_bin_edges)\n age_weights = _get_age_weights_from_tables(\n lgt_birth_bin_edges, lgt_table, logsm_table\n )\n assert age_weights.shape == lgt_ages.shape\n assert np.allclose(age_weights.sum(), 1.0)\n\n\ndef test_age_weights_agree_with_analytical_calculation_of_constant_sfr_weights():\n constant_sfr = 1.0 * 1e9 # Msun/Gyr\n\n # Analytically calculate age distributions for constant SFR (independent of t_obs)\n log_ages_gyr = FSPS_LG_AGES - 9\n ages_gyr = 10 ** log_ages_gyr\n dt_ages = _jax_get_dt_array(ages_gyr)\n mstar_age_bins = dt_ages * constant_sfr\n correct_weights = mstar_age_bins / mstar_age_bins.sum()\n\n # Calculate age distributions with DSPS\n t_obs = 16.0\n t_table = np.linspace(T_BIRTH_MIN, t_obs, 50_000)\n lgt_table = np.log10(t_table)\n mstar_table = constant_sfr * t_table\n logsm_table = np.log10(mstar_table)\n\n lgt_age_bin_edges = _get_lg_age_bin_edges(log_ages_gyr)\n lgt_birth_bin_edges = _get_lgt_birth(t_obs, lgt_age_bin_edges)\n\n dsps_age_weights = _get_age_weights_from_tables(\n lgt_birth_bin_edges, lgt_table, logsm_table\n )\n assert np.allclose(dsps_age_weights, correct_weights, atol=0.01)\n\n\ndef test_age_weights_agree_with_analytical_calculation_of_linear_sfr_weights():\n\n t_obs = 16.0\n\n # Analytically calculate age distributions for SFR(t) = t\n log_ages_gyr = FSPS_LG_AGES - 9\n lgt_age_bin_edges = _get_lg_age_bin_edges(log_ages_gyr)\n t_age_bin_edges_gyr = 10 ** lgt_age_bin_edges\n t_births_bin_edges = t_obs - t_age_bin_edges_gyr\n mstar_at_age_bins = linear_smh(T_BIRTH_MIN, t_births_bin_edges)\n dmstar_ages = -np.diff(mstar_at_age_bins)\n correct_weights = dmstar_ages / dmstar_ages.sum()\n\n # Calculate age distributions with DSPS\n t_table = np.linspace(T_BIRTH_MIN, t_obs, 50_000)\n lgt_table = np.log10(t_table)\n\n logsm_table = np.log10(linear_smh(T_BIRTH_MIN, t_table[1:]))\n lgt_birth_bin_edges = _get_lgt_birth(t_obs, lgt_age_bin_edges)\n dsps_age_weights = _get_age_weights_from_tables(\n lgt_birth_bin_edges, lgt_table[1:], logsm_table\n )\n assert np.allclose(dsps_age_weights, correct_weights, atol=0.001)\n" ]
[ [ "numpy.linspace", "numpy.diff", "numpy.allclose", "numpy.arange", "numpy.log10" ] ]
VaibhaviMishra04/pyprobml
[ "2a4b9a267f64720cbba35dfa41af3e995ea006ca", "2a4b9a267f64720cbba35dfa41af3e995ea006ca" ]
[ "scripts/hbayes_binom_rats_pymc3.py", "scripts/ecdf_sample.py" ]
[ "\n#https://docs.pymc.io/notebooks/GLM-hierarchical-binominal-model.html\n\nimport matplotlib.pyplot as plt\nimport scipy.stats as stats\nimport numpy as np\nimport pandas as pd\n#import seaborn as sns\nimport pymc3 as pm\nimport arviz as az\nimport theano.tensor as tt\n\nnp.random.seed(123)\n\n\n\n\n# rat data (BDA3, p. 102)\ny = np.array([\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1,\n 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 5, 2,\n 5, 3, 2, 7, 7, 3, 3, 2, 9, 10, 4, 4, 4, 4, 4, 4, 4,\n 10, 4, 4, 4, 5, 11, 12, 5, 5, 6, 5, 6, 6, 6, 6, 16, 15,\n 15, 9, 4\n])\nn = np.array([\n 20, 20, 20, 20, 20, 20, 20, 19, 19, 19, 19, 18, 18, 17, 20, 20, 20,\n 20, 19, 19, 18, 18, 25, 24, 23, 20, 20, 20, 20, 20, 20, 10, 49, 19,\n 46, 27, 17, 49, 47, 20, 20, 13, 48, 50, 20, 20, 20, 20, 20, 20, 20,\n 48, 19, 19, 19, 22, 46, 49, 20, 20, 23, 19, 22, 20, 20, 20, 52, 46,\n 47, 24, 14\n])\n\nN = len(n)\n\ndef logp_ab(value):\n ''' prior density'''\n return tt.log(tt.pow(tt.sum(value), -5/2))\n\n\nwith pm.Model() as model:\n # Uninformative prior for alpha and beta\n ab = pm.HalfFlat('ab',\n shape=2,\n testval=np.asarray([1., 1.]))\n pm.Potential('p(a, b)', logp_ab(ab))\n alpha = pm.Deterministic('alpha', ab[0])\n beta = pm.Deterministic('beta', ab[1])\n X = pm.Deterministic('X', tt.log(ab[0]/ab[1]))\n Z = pm.Deterministic('Z', tt.log(tt.sum(ab)))\n\n theta = pm.Beta('theta', alpha=ab[0], beta=ab[1], shape=N)\n\n p = pm.Binomial('y', p=theta, observed=y, n=n)\n #trace = pm.sample(1000, tune=2000, target_accept=0.95)\n trace = pm.sample(1000, tune=500, cores=1)\n \n \n#az.plot_trace(trace)\n#plt.savefig('../figures/hbayes_binom_rats_trace.png', dpi=300)\n\nprint(az.summary(trace))\n\n\nJ = len(n)\npost_mean = np.zeros(J)\nsamples = trace[theta]\npost_mean = np.mean(samples, axis=0)\nprint('post mean')\nprint(post_mean)\n\nalphas = trace['alpha']\nbetas = trace['beta']\nalpha_mean = np.mean(alphas)\nbeta_mean = np.mean(betas)\nhyper_mean = alpha_mean/(alpha_mean + beta_mean)\nprint('hyper mean')\nprint(hyper_mean)\n\n\nmle = y / n\npooled_mle = np.sum(y) / np.sum(n)\n\nprint('pooled mle')\nprint(pooled_mle)\n\n\naxes = az.plot_forest(\n trace, var_names='theta', credible_interval=0.95, combined=True, colors='cycle')\ny_lims = axes[0].get_ylim()\naxes[0].vlines(hyper_mean, *y_lims)\nplt.savefig('../figures/hbayes_binom_rats_forest95.pdf', dpi=300)\n\n\nJ = len(n)\nfig, axs = plt.subplots(4,1, figsize=(10,10))\nplt.subplots_adjust(hspace=0.3)\naxs = np.reshape(axs, 4)\nxs = np.arange(J)\nax = axs[0]\nax.bar(xs, y)\nax.set_title('number of postives')\nax = axs[1]\nax.bar(xs, n)\nax.set_title('popn size')\nax = axs[2]\nax.bar(xs, mle)\nax.set_ylim(0, 0.5)\nax.hlines(pooled_mle, 0, J, 'r', lw=3)\nax.set_title('MLE (red line = pooled)')\nax = axs[3]\nax.bar(xs, post_mean)\nax.hlines(hyper_mean, 0, J, 'r', lw=3)\nax.set_ylim(0, 0.5)\nax.set_title('posterior mean (red line = hparam)')\nplt.savefig('../figures/hbayes_binom_rats_barplot.pdf', dpi=300)\n\n\nJ = len(n)\nxs = np.arange(J)\nfig, ax = plt.subplots(1,1)\nax.bar(xs, y)\nax.set_title('number of postives')\nplt.savefig('../figures/hbayes_binom_rats_outcomes.pdf', dpi=300)\n\nfig, ax = plt.subplots(1,1)\nax.bar(xs, n)\nax.set_title('popn size')\nplt.savefig('../figures/hbayes_binom_rats_popsize.pdf', dpi=300)\n\nfig, ax = plt.subplots(1,1)\nax.bar(xs, mle)\nax.set_ylim(0, 0.5)\nax.hlines(pooled_mle, 0, J, 'r', lw=3)\nax.set_title('MLE (red line = pooled)')\nplt.savefig('../figures/hbayes_binom_rats_MLE.pdf', dpi=300)\n\nfig, ax = plt.subplots(1,1)\nax.bar(xs, post_mean)\nax.hlines(hyper_mean, 0, J, 'r', lw=3)\nax.set_ylim(0, 0.5)\nax.set_title('posterior mean (red line = hparam)')\nplt.savefig('../figures/hbayes_binom_rats_postmean.pdf', dpi=300)\n\n", "# empirical cdf \n# fig 11.17 of 'Bayeysian Modeling and Computation'\n\nimport numpy as np\nimport matplotlib.pyplot as plt \nimport pyprobml_utils as pml\nimport arviz as az\nfrom scipy import stats\n\n\nimport matplotlib.pyplot as plt\nimport seaborn\nimport seaborn as sns\nseaborn.set()\nseaborn.set_style(\"whitegrid\")\n\n# Font sizes\nSIZE_SMALL = 14\nSIZE_MEDIUM = 18\nSIZE_LARGE = 24\n\n# https://stackoverflow.com/a/39566040\nplt.rc('font', size=SIZE_SMALL) # controls default text sizes\nplt.rc('axes', titlesize=SIZE_SMALL) # fontsize of the axes title\nplt.rc('axes', labelsize=SIZE_SMALL) # fontsize of the x and y labels\nplt.rc('xtick', labelsize=SIZE_SMALL) # fontsize of the tick labels\nplt.rc('ytick', labelsize=SIZE_SMALL) # fontsize of the tick labels\nplt.rc('legend', fontsize=SIZE_SMALL) # legend fontsize \nplt.rc('figure', titlesize=SIZE_LARGE) # fontsize of the figure title\n\nnp.random.seed(0)\n\nxs = (np.linspace(0, 20, 200), np.linspace(0, 1, 200), np.linspace(-4, 4, 200)) \ndists = (stats.expon(scale=5), stats.beta(0.5, 0.5), stats.norm(0, 1))\nfig, ax = plt.subplots(3, 3, figsize=(10,10))\nfor idx, (dist, x) in enumerate(zip(dists, xs)): \n draws = dist.rvs(100000)\n data = dist.cdf(draws)\n ax[idx, 0].plot(x, dist.pdf(x)) \n ax[idx, 1].plot(np.sort(data), np.linspace(0, 1, len(data)))\n az.plot_kde(data, ax=ax[idx, 2])\n if idx==0:\n ax[idx,0].set_title('pdf(X)')\n ax[idx,1].set_title('cdf(Y)')\n ax[idx,2].set_title('pdf(Y)')\n \nplt.tight_layout() \npml.savefig('ecdf_sample.pdf', dpi=300)\nplt.show()\n\nfor idx, (dist, x) in enumerate(zip(dists, xs)): \n draws = dist.rvs(100000)\n data = dist.cdf(draws)\n plt.figure()\n plt.plot(x, dist.pdf(x)) \n if idx==0: plt.title('pdf(X)')\n pml.savefig(f'ecdf_{idx}_pdfX.pdf', dpi=300)\n \n plt.figure()\n plt.plot(np.sort(data), np.linspace(0, 1, len(data)))\n if idx==0: plt.title('cdf(Y)')\n pml.savefig(f'ecdf_{idx}_cdfY.pdf', dpi=300)\n \n fig, ax = plt.subplots()\n az.plot_kde(data, ax=ax)\n if idx==0: plt.title('pdf(Y)')\n pml.savefig(f'ecdf_{idx}_pdfY.pdf', dpi=300)" ]
[ [ "numpy.array", "numpy.reshape", "numpy.zeros", "numpy.asarray", "numpy.random.seed", "matplotlib.pyplot.savefig", "numpy.sum", "numpy.mean", "matplotlib.pyplot.subplots", "numpy.arange", "matplotlib.pyplot.subplots_adjust" ], [ "scipy.stats.expon", "scipy.stats.norm", "numpy.random.seed", "matplotlib.pyplot.title", "matplotlib.pyplot.subplots", "matplotlib.pyplot.rc", "matplotlib.pyplot.figure", "matplotlib.pyplot.tight_layout", "numpy.sort", "matplotlib.pyplot.show", "numpy.linspace", "scipy.stats.beta" ] ]
k101w/phyre_ODE
[ "5d775d3722043725b254cc8be83cad56462d9bef" ]
[ "data/task_scripts/main/task01002.py" ]
[ "# Copyright (c) Facebook, Inc. and its affiliates.\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\"\"\"Catapult\"\"\"\n\"\"\"Template task in which you prevent something from falling so ball can roll into container.\"\"\"\nimport numpy as np\nimport phyre.creator as creator_lib\nimport phyre.virtual_tools as vt\n\n\n@creator_lib.define_task_template(\n seed=range(1000),\n version=\"2\",\n search_params=dict(\n max_search_tasks=250,\n required_flags=['BALL:GOOD_STABLE'],\n excluded_flags=['BALL:TRIVIAL'],\n ),\n)\ndef build_task(C, seed):\n rng = np.random.RandomState(seed=seed)\n cataWidth = [200, 400]\n cataHeight = [30, 100]\n ballRad = [5, 15]\n strutWidth = [10, 50]\n strutHeight = [60, 200]\n goalWidth = [60, 150]\n goalHeight = [60, 180]\n cataThick = [5, 10]\n spacing = [25, 100]\n strutPlace = [0, 150]\n\n ## Define the features first\n cW = rng.uniform(cataWidth[0], cataWidth[1])\n cH = 20.\n bR = rng.uniform(ballRad[0], ballRad[1])\n sW = rng.uniform(strutWidth[0], strutWidth[1])\n sH = rng.uniform(strutHeight[0], strutHeight[1])\n gW = rng.uniform(goalWidth[0], goalWidth[1])\n gH = rng.uniform(goalHeight[0], goalHeight[1])\n cT = rng.uniform(cataThick[0], cataThick[1])\n sp = rng.uniform(spacing[0], spacing[1])\n stP = rng.uniform(strutPlace[0], strutPlace[1])\n stP = min([stP, cW / 2])\n\n flip_lr = rng.uniform(0, 1) < 0.5\n ## Then fit together\n cataCent = vt.VT_SCALE - gW - sp - cW / 2\n cataLeft = cataCent - cW / 2\n\n ## Make the world\n strut = vt.add_box(\n C, [cataCent - sW / 2 + stP, 0, cataCent + sW / 2 + stP, sH],\n False,\n flip_lr=flip_lr)\n cradle = vt.add_box(C, [cataLeft, 0, cataLeft + 10, sH],\n False,\n flip_lr=flip_lr)\n container, _ = vt.add_container(\n C, [[vt.VT_SCALE - gW, gH], [vt.VT_SCALE - gW, 5], [vt.VT_SCALE - 5, 5],\n [vt.VT_SCALE - 5, gH]],\n 10,\n False,\n True,\n flip_lr=flip_lr)\n polys = [[[cataLeft, sH], [cataLeft, sH + cT], [cataLeft + cT, sH + cT],\n [cataLeft + cT, sH]],\n [[cataLeft, sH + cT], [cataLeft, sH + cH],\n [cataLeft + cT, sH + cH], [cataLeft + cT, sH + cT]],\n [[cataLeft + cT, sH], [cataLeft + cT, sH + cT],\n [cataLeft + cW, sH + cT], [cataLeft + cW, sH]]]\n for p in polys:\n p.reverse()\n\n if flip_lr:\n p = vt.flip_left_right(p)\n center_x = vt.flip_left_right(cataLeft + cT + bR + 30)\n else:\n center_x = cataLeft + cT + bR + 30\n converted_polylist = [\n vt.convert_phyre_tools_vertices(poly) for poly in polys\n ]\n catapult = C.add_multipolygons(polygons=converted_polylist, dynamic=True)\n\n ball = C.add('dynamic ball',\n bR * 2. / vt.VT_SCALE,\n center_x=center_x * C.scene.width / vt.VT_SCALE,\n center_y=(sH + cT + bR) * C.scene.width / vt.VT_SCALE)\n C.update_task(body1=ball,\n body2=container,\n relationships=[C.SpatialRelationship.TOUCHING])\n\n C.set_meta(C.SolutionTier.VIRTUAL_TOOLS)\n '''pgw.addBox('Strut', [cataCent - sW/2 + stP, 0, cataCent + sW/2 + stP, sH], 'black', 0)\n pgw.addBox('Cradle', [cataLeft, 0, cataLeft+10, sH], 'black', 0)\n pgw.addContainer('Goal', [[DIMS[0]-gW, 5], [DIMS[0]-gW, gH], [DIMS[0]-5, gH], [DIMS[0]-5, 5]], 10, 'green', 'black', 0)\n pgw.addCompound('Catapult', [\n [[cataLeft, sH], [cataLeft, sH+cT], [cataLeft+cT, sH+cT], [cataLeft+cT, sH]],\n [[cataLeft, sH+cT], [cataLeft, sH+cH], [cataLeft+cT, sH+cH], [cataLeft+cT, sH+cT]],\n [[cataLeft+cT, sH], [cataLeft+cT, sH+cT], [cataLeft+cW, sH+cT], [cataLeft+cW, sH]]\n ], 'blue', 1)\n pgw.addBall('Ball', [cataLeft+cT+bR+30, sH+cT+bR], bR, 'red', 1)\n pgw.attachSpecificInGoal('Goal', 'Ball', 1)\n return pgw'''\n" ]
[ [ "numpy.random.RandomState" ] ]
rbalda/neural_ocr
[ "140585a7e99f1d49e52b142811273b02c08c0675" ]
[ "env/lib/python2.7/site-packages/matplotlib/dates.py" ]
[ "#!/usr/bin/env python\n\"\"\"\nMatplotlib provides sophisticated date plotting capabilities, standing on the\nshoulders of python :mod:`datetime`, the add-on modules :mod:`pytz` and\n:mod:`dateutil`. :class:`datetime` objects are converted to floating point\nnumbers which represent time in days since 0001-01-01 UTC, plus 1. For\nexample, 0001-01-01, 06:00 is 1.25, not 0.25. The helper functions\n:func:`date2num`, :func:`num2date` and :func:`drange` are used to facilitate\neasy conversion to and from :mod:`datetime` and numeric ranges.\n\n.. note::\n\n Like Python's datetime, mpl uses the Gregorian calendar for all\n conversions between dates and floating point numbers. This practice\n is not universal, and calendar differences can cause confusing\n differences between what Python and mpl give as the number of days\n since 0001-01-01 and what other software and databases yield. For\n example, the US Naval Observatory uses a calendar that switches\n from Julian to Gregorian in October, 1582. Hence, using their\n calculator, the number of days between 0001-01-01 and 2006-04-01 is\n 732403, whereas using the Gregorian calendar via the datetime\n module we find::\n\n In [31]:date(2006,4,1).toordinal() - date(1,1,1).toordinal()\n Out[31]:732401\n\n\nA wide range of specific and general purpose date tick locators and\nformatters are provided in this module. See\n:mod:`matplotlib.ticker` for general information on tick locators\nand formatters. These are described below.\n\nAll the matplotlib date converters, tickers and formatters are\ntimezone aware, and the default timezone is given by the timezone\nparameter in your :file:`matplotlibrc` file. If you leave out a\n:class:`tz` timezone instance, the default from your rc file will be\nassumed. If you want to use a custom time zone, pass a\n:class:`pytz.timezone` instance with the tz keyword argument to\n:func:`num2date`, :func:`plot_date`, and any custom date tickers or\nlocators you create. See `pytz <http://pythonhosted.org/pytz/>`_ for\ninformation on :mod:`pytz` and timezone handling.\n\nThe `dateutil module <https://dateutil.readthedocs.org>`_ provides\nadditional code to handle date ticking, making it easy to place ticks\non any kinds of dates. See examples below.\n\nDate tickers\n------------\n\nMost of the date tickers can locate single or multiple values. For\nexample::\n\n # import constants for the days of the week\n from matplotlib.dates import MO, TU, WE, TH, FR, SA, SU\n\n # tick on mondays every week\n loc = WeekdayLocator(byweekday=MO, tz=tz)\n\n # tick on mondays and saturdays\n loc = WeekdayLocator(byweekday=(MO, SA))\n\nIn addition, most of the constructors take an interval argument::\n\n # tick on mondays every second week\n loc = WeekdayLocator(byweekday=MO, interval=2)\n\nThe rrule locator allows completely general date ticking::\n\n # tick every 5th easter\n rule = rrulewrapper(YEARLY, byeaster=1, interval=5)\n loc = RRuleLocator(rule)\n\nHere are all the date tickers:\n\n * :class:`MinuteLocator`: locate minutes\n\n * :class:`HourLocator`: locate hours\n\n * :class:`DayLocator`: locate specifed days of the month\n\n * :class:`WeekdayLocator`: Locate days of the week, e.g., MO, TU\n\n * :class:`MonthLocator`: locate months, e.g., 7 for july\n\n * :class:`YearLocator`: locate years that are multiples of base\n\n * :class:`RRuleLocator`: locate using a\n :class:`matplotlib.dates.rrulewrapper`. The\n :class:`rrulewrapper` is a simple wrapper around a\n :class:`dateutil.rrule` (`dateutil\n <https://dateutil.readthedocs.org>`_) which allow almost\n arbitrary date tick specifications. See `rrule example\n <../examples/pylab_examples/date_demo_rrule.html>`_.\n\n * :class:`AutoDateLocator`: On autoscale, this class picks the best\n :class:`MultipleDateLocator` to set the view limits and the tick\n locations.\n\nDate formatters\n---------------\n\nHere all all the date formatters:\n\n * :class:`AutoDateFormatter`: attempts to figure out the best format\n to use. This is most useful when used with the :class:`AutoDateLocator`.\n\n * :class:`DateFormatter`: use :func:`strftime` format strings\n\n * :class:`IndexDateFormatter`: date plots with implicit *x*\n indexing.\n\"\"\"\nfrom __future__ import (absolute_import, division, print_function,\n unicode_literals)\n\nfrom matplotlib.externals import six\nfrom matplotlib.externals.six.moves import xrange, zip\n\nimport re\nimport time\nimport math\nimport datetime\n\nimport warnings\n\n\nfrom dateutil.rrule import (rrule, MO, TU, WE, TH, FR, SA, SU, YEARLY,\n MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY,\n SECONDLY)\nfrom dateutil.relativedelta import relativedelta\nimport dateutil.parser\nimport numpy as np\n\n\nimport matplotlib\nimport matplotlib.units as units\nimport matplotlib.cbook as cbook\nimport matplotlib.ticker as ticker\n\n\n__all__ = ('date2num', 'num2date', 'drange', 'epoch2num',\n 'num2epoch', 'mx2num', 'DateFormatter',\n 'IndexDateFormatter', 'AutoDateFormatter', 'DateLocator',\n 'RRuleLocator', 'AutoDateLocator', 'YearLocator',\n 'MonthLocator', 'WeekdayLocator',\n 'DayLocator', 'HourLocator', 'MinuteLocator',\n 'SecondLocator', 'MicrosecondLocator',\n 'rrule', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU',\n 'YEARLY', 'MONTHLY', 'WEEKLY', 'DAILY',\n 'HOURLY', 'MINUTELY', 'SECONDLY', 'MICROSECONDLY', 'relativedelta',\n 'seconds', 'minutes', 'hours', 'weeks')\n\n\n# Make a simple UTC instance so we don't always have to import\n# pytz. From the python datetime library docs:\n\nclass _UTC(datetime.tzinfo):\n \"\"\"UTC\"\"\"\n\n def utcoffset(self, dt):\n return datetime.timedelta(0)\n\n def tzname(self, dt):\n return \"UTC\"\n\n def dst(self, dt):\n return datetime.timedelta(0)\n\nUTC = _UTC()\n\n\ndef _get_rc_timezone():\n \"\"\"\n Retrieve the preferred timeszone from the rcParams dictionary.\n \"\"\"\n s = matplotlib.rcParams['timezone']\n if s == 'UTC':\n return UTC\n import pytz\n return pytz.timezone(s)\n\n\"\"\"\nTime-related constants.\n\"\"\"\nEPOCH_OFFSET = float(datetime.datetime(1970, 1, 1).toordinal())\nJULIAN_OFFSET = 1721424.5 # Julian date at 0001-01-01\nMICROSECONDLY = SECONDLY + 1\nHOURS_PER_DAY = 24.\nMIN_PER_HOUR = 60.\nSEC_PER_MIN = 60.\nMONTHS_PER_YEAR = 12.\n\nDAYS_PER_WEEK = 7.\nDAYS_PER_MONTH = 30.\nDAYS_PER_YEAR = 365.0\n\nMINUTES_PER_DAY = MIN_PER_HOUR * HOURS_PER_DAY\n\nSEC_PER_HOUR = SEC_PER_MIN * MIN_PER_HOUR\nSEC_PER_DAY = SEC_PER_HOUR * HOURS_PER_DAY\nSEC_PER_WEEK = SEC_PER_DAY * DAYS_PER_WEEK\n\nMUSECONDS_PER_DAY = 1e6 * SEC_PER_DAY\n\nMONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY = (\n MO, TU, WE, TH, FR, SA, SU)\nWEEKDAYS = (MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY)\n\n\ndef _to_ordinalf(dt):\n \"\"\"\n Convert :mod:`datetime` or :mod:`date` to the Gregorian date as UTC float\n days, preserving hours, minutes, seconds and microseconds. Return value\n is a :func:`float`.\n \"\"\"\n\n if hasattr(dt, 'tzinfo') and dt.tzinfo is not None:\n delta = dt.tzinfo.utcoffset(dt)\n if delta is not None:\n dt -= delta\n\n base = float(dt.toordinal())\n if isinstance(dt, datetime.datetime):\n # Get a datetime object at midnight in the same time zone as dt.\n cdate = dt.date()\n midnight_time = datetime.time(0, 0, 0, tzinfo=dt.tzinfo)\n\n rdt = datetime.datetime.combine(cdate, midnight_time)\n td_remainder = _total_seconds(dt - rdt)\n\n if td_remainder > 0:\n base += td_remainder / SEC_PER_DAY\n\n return base\n\n\n# a version of _to_ordinalf that can operate on numpy arrays\n_to_ordinalf_np_vectorized = np.vectorize(_to_ordinalf)\n\ntry:\n # Available as a native method in Python >= 2.7.\n _total_seconds = datetime.timedelta.total_seconds\nexcept AttributeError:\n def _total_seconds(tdelta):\n \"\"\"\n Alias providing support for datetime.timedelta.total_seconds() function\n calls even in Python < 2.7.\n\n The input `tdelta` is a datetime.timedelta object, and returns a float\n containing the total number of seconds representing the `tdelta`\n duration. For large durations (> 270 on most platforms), this loses\n microsecond accuracy.\n \"\"\"\n return (tdelta.microseconds +\n (tdelta.seconds + tdelta.days * SEC_PER_DAY) * 1e6) * 1e-6\n\n\ndef _from_ordinalf(x, tz=None):\n \"\"\"\n Convert Gregorian float of the date, preserving hours, minutes,\n seconds and microseconds. Return value is a :class:`datetime`.\n\n The input date `x` is a float in ordinal days at UTC, and the output will\n be the specified :class:`datetime` object corresponding to that time in\n timezone `tz`, or if `tz` is `None`, in the timezone specified in\n `rcParams['timezone']`.\n \"\"\"\n if tz is None:\n tz = _get_rc_timezone()\n\n ix = int(x)\n dt = datetime.datetime.fromordinal(ix).replace(tzinfo=UTC)\n\n remainder = float(x) - ix\n\n # Round down to the nearest microsecond.\n dt += datetime.timedelta(microseconds=int(remainder * MUSECONDS_PER_DAY))\n\n # Compensate for rounding errors\n if dt.microsecond < 10:\n dt = dt.replace(microsecond=0)\n elif dt.microsecond > 999990:\n dt += datetime.timedelta(microseconds=1e6 - dt.microsecond)\n\n return dt.astimezone(tz)\n\n\n# a version of _from_ordinalf that can operate on numpy arrays\n_from_ordinalf_np_vectorized = np.vectorize(_from_ordinalf)\n\n\nclass strpdate2num(object):\n \"\"\"\n Use this class to parse date strings to matplotlib datenums when\n you know the date format string of the date you are parsing. See\n :file:`examples/load_demo.py`.\n \"\"\"\n def __init__(self, fmt):\n \"\"\" fmt: any valid strptime format is supported \"\"\"\n self.fmt = fmt\n\n def __call__(self, s):\n \"\"\"s : string to be converted\n return value: a date2num float\n \"\"\"\n return date2num(datetime.datetime(*time.strptime(s, self.fmt)[:6]))\n\n\nclass bytespdate2num(strpdate2num):\n \"\"\"\n Use this class to parse date strings to matplotlib datenums when\n you know the date format string of the date you are parsing. See\n :file:`examples/load_demo.py`.\n \"\"\"\n def __init__(self, fmt, encoding='utf-8'):\n \"\"\"\n Args:\n fmt: any valid strptime format is supported\n encoding: encoding to use on byte input (default: 'utf-8')\n \"\"\"\n super(bytespdate2num, self).__init__(fmt)\n self.encoding = encoding\n\n def __call__(self, b):\n \"\"\"\n Args:\n b: byte input to be converted\n Returns:\n A date2num float\n \"\"\"\n s = b.decode(self.encoding)\n return super(bytespdate2num, self).__call__(s)\n\n\n# a version of dateutil.parser.parse that can operate on nump0y arrays\n_dateutil_parser_parse_np_vectorized = np.vectorize(dateutil.parser.parse)\n\n\ndef datestr2num(d, default=None):\n \"\"\"\n Convert a date string to a datenum using\n :func:`dateutil.parser.parse`.\n\n Parameters\n ----------\n d : string or sequence of strings\n The dates to convert.\n\n default : datetime instance\n The default date to use when fields are missing in `d`.\n \"\"\"\n if cbook.is_string_like(d):\n dt = dateutil.parser.parse(d, default=default)\n return date2num(dt)\n else:\n if default is not None:\n d = [dateutil.parser.parse(s, default=default) for s in d]\n d = np.asarray(d)\n if not d.size:\n return d\n return date2num(_dateutil_parser_parse_np_vectorized(d))\n\n\ndef date2num(d):\n \"\"\"\n *d* is either a :class:`datetime` instance or a sequence of datetimes.\n\n Return value is a floating point number (or sequence of floats)\n which gives the number of days (fraction part represents hours,\n minutes, seconds) since 0001-01-01 00:00:00 UTC, *plus* *one*.\n The addition of one here is a historical artifact. Also, note\n that the Gregorian calendar is assumed; this is not universal\n practice. For details, see the module docstring.\n \"\"\"\n if not cbook.iterable(d):\n return _to_ordinalf(d)\n else:\n d = np.asarray(d)\n if not d.size:\n return d\n return _to_ordinalf_np_vectorized(d)\n\n\ndef julian2num(j):\n \"\"\"\n Convert a Julian date (or sequence) to a matplotlib date (or sequence).\n \"\"\"\n if cbook.iterable(j):\n j = np.asarray(j)\n return j - JULIAN_OFFSET\n\n\ndef num2julian(n):\n \"\"\"\n Convert a matplotlib date (or sequence) to a Julian date (or sequence).\n \"\"\"\n if cbook.iterable(n):\n n = np.asarray(n)\n return n + JULIAN_OFFSET\n\n\ndef num2date(x, tz=None):\n \"\"\"\n *x* is a float value which gives the number of days\n (fraction part represents hours, minutes, seconds) since\n 0001-01-01 00:00:00 UTC *plus* *one*.\n The addition of one here is a historical artifact. Also, note\n that the Gregorian calendar is assumed; this is not universal\n practice. For details, see the module docstring.\n\n Return value is a :class:`datetime` instance in timezone *tz* (default to\n rcparams TZ value).\n\n If *x* is a sequence, a sequence of :class:`datetime` objects will\n be returned.\n \"\"\"\n if tz is None:\n tz = _get_rc_timezone()\n if not cbook.iterable(x):\n return _from_ordinalf(x, tz)\n else:\n x = np.asarray(x)\n if not x.size:\n return x\n return _from_ordinalf_np_vectorized(x, tz).tolist()\n\n\ndef drange(dstart, dend, delta):\n \"\"\"\n Return a date range as float Gregorian ordinals. *dstart* and\n *dend* are :class:`datetime` instances. *delta* is a\n :class:`datetime.timedelta` instance.\n \"\"\"\n f1 = _to_ordinalf(dstart)\n f2 = _to_ordinalf(dend)\n step = _total_seconds(delta) / SEC_PER_DAY\n\n # calculate the difference between dend and dstart in times of delta\n num = int(np.ceil((f2 - f1) / step))\n\n # calculate end of the interval which will be generated\n dinterval_end = dstart + num * delta\n\n # ensure, that an half open interval will be generated [dstart, dend)\n if dinterval_end >= dend:\n # if the endpoint is greated than dend, just subtract one delta\n dinterval_end -= delta\n num -= 1\n\n f2 = _to_ordinalf(dinterval_end) # new float-endpoint\n return np.linspace(f1, f2, num + 1)\n\n### date tickers and formatters ###\n\n\nclass DateFormatter(ticker.Formatter):\n \"\"\"\n Tick location is seconds since the epoch. Use a :func:`strftime`\n format string.\n\n Python only supports :mod:`datetime` :func:`strftime` formatting\n for years greater than 1900. Thanks to Andrew Dalke, Dalke\n Scientific Software who contributed the :func:`strftime` code\n below to include dates earlier than this year.\n \"\"\"\n\n illegal_s = re.compile(r\"((^|[^%])(%%)*%s)\")\n\n def __init__(self, fmt, tz=None):\n \"\"\"\n *fmt* is a :func:`strftime` format string; *tz* is the\n :class:`tzinfo` instance.\n \"\"\"\n if tz is None:\n tz = _get_rc_timezone()\n self.fmt = fmt\n self.tz = tz\n\n def __call__(self, x, pos=0):\n if x == 0:\n raise ValueError('DateFormatter found a value of x=0, which is '\n 'an illegal date. This usually occurs because '\n 'you have not informed the axis that it is '\n 'plotting dates, e.g., with ax.xaxis_date()')\n dt = num2date(x, self.tz)\n return self.strftime(dt, self.fmt)\n\n def set_tzinfo(self, tz):\n self.tz = tz\n\n def _replace_common_substr(self, s1, s2, sub1, sub2, replacement):\n \"\"\"Helper function for replacing substrings sub1 and sub2\n located at the same indexes in strings s1 and s2 respectively,\n with the string replacement. It is expected that sub1 and sub2\n have the same length. Returns the pair s1, s2 after the\n substitutions.\n \"\"\"\n # Find common indexes of substrings sub1 in s1 and sub2 in s2\n # and make substitutions inplace. Because this is inplace,\n # it is okay if len(replacement) != len(sub1), len(sub2).\n i = 0\n while True:\n j = s1.find(sub1, i)\n if j == -1:\n break\n\n i = j + 1\n if s2[j:j + len(sub2)] != sub2:\n continue\n\n s1 = s1[:j] + replacement + s1[j + len(sub1):]\n s2 = s2[:j] + replacement + s2[j + len(sub2):]\n\n return s1, s2\n\n def strftime_pre_1900(self, dt, fmt=None):\n \"\"\"Call time.strftime for years before 1900 by rolling\n forward a multiple of 28 years.\n\n *fmt* is a :func:`strftime` format string.\n\n Dalke: I hope I did this math right. Every 28 years the\n calendar repeats, except through century leap years excepting\n the 400 year leap years. But only if you're using the Gregorian\n calendar.\n \"\"\"\n if fmt is None:\n fmt = self.fmt\n\n # Since python's time module's strftime implementation does not\n # support %f microsecond (but the datetime module does), use a\n # regular expression substitution to replace instances of %f.\n # Note that this can be useful since python's floating-point\n # precision representation for datetime causes precision to be\n # more accurate closer to year 0 (around the year 2000, precision\n # can be at 10s of microseconds).\n fmt = re.sub(r'((^|[^%])(%%)*)%f',\n r'\\g<1>{0:06d}'.format(dt.microsecond), fmt)\n\n year = dt.year\n # For every non-leap year century, advance by\n # 6 years to get into the 28-year repeat cycle\n delta = 2000 - year\n off = 6 * (delta // 100 + delta // 400)\n year = year + off\n\n # Move to between the years 1973 and 2000\n year1 = year + ((2000 - year) // 28) * 28\n year2 = year1 + 28\n timetuple = dt.timetuple()\n # Generate timestamp string for year and year+28\n s1 = time.strftime(fmt, (year1,) + timetuple[1:])\n s2 = time.strftime(fmt, (year2,) + timetuple[1:])\n\n # Replace instances of respective years (both 2-digit and 4-digit)\n # that are located at the same indexes of s1, s2 with dt's year.\n # Note that C++'s strftime implementation does not use padded\n # zeros or padded whitespace for %y or %Y for years before 100, but\n # uses padded zeros for %x. (For example, try the runnable examples\n # with .tm_year in the interval [-1900, -1800] on\n # http://en.cppreference.com/w/c/chrono/strftime.) For ease of\n # implementation, we always use padded zeros for %y, %Y, and %x.\n s1, s2 = self._replace_common_substr(s1, s2,\n \"{0:04d}\".format(year1),\n \"{0:04d}\".format(year2),\n \"{0:04d}\".format(dt.year))\n s1, s2 = self._replace_common_substr(s1, s2,\n \"{0:02d}\".format(year1 % 100),\n \"{0:02d}\".format(year2 % 100),\n \"{0:02d}\".format(dt.year % 100))\n return cbook.unicode_safe(s1)\n\n def strftime(self, dt, fmt=None):\n \"\"\"Refer to documentation for datetime.strftime.\n\n *fmt* is a :func:`strftime` format string.\n\n Warning: For years before 1900, depending upon the current\n locale it is possible that the year displayed with %x might\n be incorrect. For years before 100, %y and %Y will yield\n zero-padded strings.\n \"\"\"\n if fmt is None:\n fmt = self.fmt\n fmt = self.illegal_s.sub(r\"\\1\", fmt)\n fmt = fmt.replace(\"%s\", \"s\")\n if dt.year >= 1900:\n # Note: in python 3.3 this is okay for years >= 1000,\n # refer to http://bugs.python.org/issue177742\n return cbook.unicode_safe(dt.strftime(fmt))\n\n return self.strftime_pre_1900(dt, fmt)\n\n\nclass IndexDateFormatter(ticker.Formatter):\n \"\"\"\n Use with :class:`~matplotlib.ticker.IndexLocator` to cycle format\n strings by index.\n \"\"\"\n def __init__(self, t, fmt, tz=None):\n \"\"\"\n *t* is a sequence of dates (floating point days). *fmt* is a\n :func:`strftime` format string.\n \"\"\"\n if tz is None:\n tz = _get_rc_timezone()\n self.t = t\n self.fmt = fmt\n self.tz = tz\n\n def __call__(self, x, pos=0):\n 'Return the label for time *x* at position *pos*'\n ind = int(round(x))\n if ind >= len(self.t) or ind <= 0:\n return ''\n\n dt = num2date(self.t[ind], self.tz)\n\n return cbook.unicode_safe(dt.strftime(self.fmt))\n\n\nclass AutoDateFormatter(ticker.Formatter):\n \"\"\"\n This class attempts to figure out the best format to use. This is\n most useful when used with the :class:`AutoDateLocator`.\n\n\n The AutoDateFormatter has a scale dictionary that maps the scale\n of the tick (the distance in days between one major tick) and a\n format string. The default looks like this::\n\n self.scaled = {\n 365.0 : '%Y',\n 30. : '%b %Y',\n 1.0 : '%b %d %Y',\n 1./24. : '%H:%M:%S',\n 1. / (24. * 60.): '%H:%M:%S.%f',\n }\n\n\n The algorithm picks the key in the dictionary that is >= the\n current scale and uses that format string. You can customize this\n dictionary by doing::\n\n\n >>> formatter = AutoDateFormatter()\n >>> formatter.scaled[1/(24.*60.)] = '%M:%S' # only show min and sec\n\n A custom :class:`~matplotlib.ticker.FuncFormatter` can also be used.\n The following example shows how to use a custom format function to strip\n trailing zeros from decimal seconds and adds the date to the first\n ticklabel::\n\n >>> def my_format_function(x, pos=None):\n ... x = matplotlib.dates.num2date(x)\n ... if pos == 0:\n ... fmt = '%D %H:%M:%S.%f'\n ... else:\n ... fmt = '%H:%M:%S.%f'\n ... label = x.strftime(fmt)\n ... label = label.rstrip(\"0\")\n ... label = label.rstrip(\".\")\n ... return label\n >>> from matplotlib.ticker import FuncFormatter\n >>> formatter.scaled[1/(24.*60.)] = FuncFormatter(my_format_function)\n \"\"\"\n\n # This can be improved by providing some user-level direction on\n # how to choose the best format (precedence, etc...)\n\n # Perhaps a 'struct' that has a field for each time-type where a\n # zero would indicate \"don't show\" and a number would indicate\n # \"show\" with some sort of priority. Same priorities could mean\n # show all with the same priority.\n\n # Or more simply, perhaps just a format string for each\n # possibility...\n\n def __init__(self, locator, tz=None, defaultfmt='%Y-%m-%d'):\n \"\"\"\n Autoformat the date labels. The default format is the one to use\n if none of the values in ``self.scaled`` are greater than the unit\n returned by ``locator._get_unit()``.\n \"\"\"\n self._locator = locator\n self._tz = tz\n self.defaultfmt = defaultfmt\n self._formatter = DateFormatter(self.defaultfmt, tz)\n self.scaled = {DAYS_PER_YEAR: '%Y',\n DAYS_PER_MONTH: '%b %Y',\n 1.0: '%b %d %Y',\n 1. / HOURS_PER_DAY: '%H:%M:%S',\n 1. / (MINUTES_PER_DAY): '%H:%M:%S.%f'}\n\n def __call__(self, x, pos=None):\n locator_unit_scale = float(self._locator._get_unit())\n fmt = self.defaultfmt\n\n # Pick the first scale which is greater than the locator unit.\n for possible_scale in sorted(self.scaled):\n if possible_scale >= locator_unit_scale:\n fmt = self.scaled[possible_scale]\n break\n\n if isinstance(fmt, six.string_types):\n self._formatter = DateFormatter(fmt, self._tz)\n result = self._formatter(x, pos)\n elif six.callable(fmt):\n result = fmt(x, pos)\n else:\n raise TypeError('Unexpected type passed to {0!r}.'.format(self))\n\n return result\n\n\nclass rrulewrapper(object):\n\n def __init__(self, freq, **kwargs):\n self._construct = kwargs.copy()\n self._construct[\"freq\"] = freq\n self._rrule = rrule(**self._construct)\n\n def set(self, **kwargs):\n self._construct.update(kwargs)\n self._rrule = rrule(**self._construct)\n\n def __getattr__(self, name):\n if name in self.__dict__:\n return self.__dict__[name]\n return getattr(self._rrule, name)\n\n\nclass DateLocator(ticker.Locator):\n \"\"\"\n Determines the tick locations when plotting dates.\n \"\"\"\n hms0d = {'byhour': 0, 'byminute': 0, 'bysecond': 0}\n\n def __init__(self, tz=None):\n \"\"\"\n *tz* is a :class:`tzinfo` instance.\n \"\"\"\n if tz is None:\n tz = _get_rc_timezone()\n self.tz = tz\n\n def set_tzinfo(self, tz):\n \"\"\"\n Set time zone info.\n \"\"\"\n self.tz = tz\n\n def datalim_to_dt(self):\n \"\"\"\n Convert axis data interval to datetime objects.\n \"\"\"\n dmin, dmax = self.axis.get_data_interval()\n if dmin > dmax:\n dmin, dmax = dmax, dmin\n\n return num2date(dmin, self.tz), num2date(dmax, self.tz)\n\n def viewlim_to_dt(self):\n \"\"\"\n Converts the view interval to datetime objects.\n \"\"\"\n vmin, vmax = self.axis.get_view_interval()\n if vmin > vmax:\n vmin, vmax = vmax, vmin\n\n return num2date(vmin, self.tz), num2date(vmax, self.tz)\n\n def _get_unit(self):\n \"\"\"\n Return how many days a unit of the locator is; used for\n intelligent autoscaling.\n \"\"\"\n return 1\n\n def _get_interval(self):\n \"\"\"\n Return the number of units for each tick.\n \"\"\"\n return 1\n\n def nonsingular(self, vmin, vmax):\n \"\"\"\n Given the proposed upper and lower extent, adjust the range\n if it is too close to being singular (i.e. a range of ~0).\n\n \"\"\"\n unit = self._get_unit()\n interval = self._get_interval()\n if abs(vmax - vmin) < 1e-6:\n vmin -= 2 * unit * interval\n vmax += 2 * unit * interval\n return vmin, vmax\n\n\nclass RRuleLocator(DateLocator):\n # use the dateutil rrule instance\n\n def __init__(self, o, tz=None):\n DateLocator.__init__(self, tz)\n self.rule = o\n\n def __call__(self):\n # if no data have been set, this will tank with a ValueError\n try:\n dmin, dmax = self.viewlim_to_dt()\n except ValueError:\n return []\n\n return self.tick_values(dmin, dmax)\n\n def tick_values(self, vmin, vmax):\n delta = relativedelta(vmax, vmin)\n\n # We need to cap at the endpoints of valid datetime\n try:\n start = vmin - delta\n except ValueError:\n start = _from_ordinalf(1.0)\n\n try:\n stop = vmax + delta\n except ValueError:\n # The magic number!\n stop = _from_ordinalf(3652059.9999999)\n\n self.rule.set(dtstart=start, until=stop, count=self.MAXTICKS + 1)\n\n # estimate the number of ticks very approximately so we don't\n # have to do a very expensive (and potentially near infinite)\n # 'between' calculation, only to find out it will fail.\n nmax, nmin = date2num((vmax, vmin))\n estimate = (nmax - nmin) / (self._get_unit() * self._get_interval())\n # This estimate is only an estimate, so be really conservative\n # about bailing...\n if estimate > self.MAXTICKS * 2:\n raise RuntimeError(\n 'RRuleLocator estimated to generate %d ticks from %s to %s: '\n 'exceeds Locator.MAXTICKS * 2 (%d) ' % (estimate, vmin, vmax,\n self.MAXTICKS * 2))\n\n dates = self.rule.between(vmin, vmax, True)\n if len(dates) == 0:\n return date2num([vmin, vmax])\n return self.raise_if_exceeds(date2num(dates))\n\n def _get_unit(self):\n \"\"\"\n Return how many days a unit of the locator is; used for\n intelligent autoscaling.\n \"\"\"\n freq = self.rule._rrule._freq\n return self.get_unit_generic(freq)\n\n @staticmethod\n def get_unit_generic(freq):\n if freq == YEARLY:\n return DAYS_PER_YEAR\n elif freq == MONTHLY:\n return DAYS_PER_MONTH\n elif freq == WEEKLY:\n return DAYS_PER_WEEK\n elif freq == DAILY:\n return 1.0\n elif freq == HOURLY:\n return 1.0 / HOURS_PER_DAY\n elif freq == MINUTELY:\n return 1.0 / MINUTES_PER_DAY\n elif freq == SECONDLY:\n return 1.0 / SEC_PER_DAY\n else:\n # error\n return -1 # or should this just return '1'?\n\n def _get_interval(self):\n return self.rule._rrule._interval\n\n def autoscale(self):\n \"\"\"\n Set the view limits to include the data range.\n \"\"\"\n dmin, dmax = self.datalim_to_dt()\n delta = relativedelta(dmax, dmin)\n\n # We need to cap at the endpoints of valid datetime\n try:\n start = dmin - delta\n except ValueError:\n start = _from_ordinalf(1.0)\n\n try:\n stop = dmax + delta\n except ValueError:\n # The magic number!\n stop = _from_ordinalf(3652059.9999999)\n\n self.rule.set(dtstart=start, until=stop)\n dmin, dmax = self.datalim_to_dt()\n\n vmin = self.rule.before(dmin, True)\n if not vmin:\n vmin = dmin\n\n vmax = self.rule.after(dmax, True)\n if not vmax:\n vmax = dmax\n\n vmin = date2num(vmin)\n vmax = date2num(vmax)\n\n return self.nonsingular(vmin, vmax)\n\n\nclass AutoDateLocator(DateLocator):\n \"\"\"\n On autoscale, this class picks the best\n :class:`DateLocator` to set the view limits and the tick\n locations.\n \"\"\"\n def __init__(self, tz=None, minticks=5, maxticks=None,\n interval_multiples=False):\n \"\"\"\n *minticks* is the minimum number of ticks desired, which is used to\n select the type of ticking (yearly, monthly, etc.).\n\n *maxticks* is the maximum number of ticks desired, which controls\n any interval between ticks (ticking every other, every 3, etc.).\n For really fine-grained control, this can be a dictionary mapping\n individual rrule frequency constants (YEARLY, MONTHLY, etc.)\n to their own maximum number of ticks. This can be used to keep\n the number of ticks appropriate to the format chosen in\n :class:`AutoDateFormatter`. Any frequency not specified in this\n dictionary is given a default value.\n\n *tz* is a :class:`tzinfo` instance.\n\n *interval_multiples* is a boolean that indicates whether ticks\n should be chosen to be multiple of the interval. This will lock\n ticks to 'nicer' locations. For example, this will force the\n ticks to be at hours 0,6,12,18 when hourly ticking is done at\n 6 hour intervals.\n\n The AutoDateLocator has an interval dictionary that maps the\n frequency of the tick (a constant from dateutil.rrule) and a\n multiple allowed for that ticking. The default looks like this::\n\n self.intervald = {\n YEARLY : [1, 2, 4, 5, 10, 20, 40, 50, 100, 200, 400, 500,\n 1000, 2000, 4000, 5000, 10000],\n MONTHLY : [1, 2, 3, 4, 6],\n DAILY : [1, 2, 3, 7, 14],\n HOURLY : [1, 2, 3, 4, 6, 12],\n MINUTELY: [1, 5, 10, 15, 30],\n SECONDLY: [1, 5, 10, 15, 30],\n MICROSECONDLY: [1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000,\n 5000, 10000, 20000, 50000, 100000, 200000, 500000,\n 1000000],\n }\n\n The interval is used to specify multiples that are appropriate for\n the frequency of ticking. For instance, every 7 days is sensible\n for daily ticks, but for minutes/seconds, 15 or 30 make sense.\n You can customize this dictionary by doing::\n\n locator = AutoDateLocator()\n locator.intervald[HOURLY] = [3] # only show every 3 hours\n \"\"\"\n DateLocator.__init__(self, tz)\n self._locator = YearLocator()\n self._freq = YEARLY\n self._freqs = [YEARLY, MONTHLY, DAILY, HOURLY, MINUTELY,\n SECONDLY, MICROSECONDLY]\n self.minticks = minticks\n\n self.maxticks = {YEARLY: 11, MONTHLY: 12, DAILY: 11, HOURLY: 12,\n MINUTELY: 11, SECONDLY: 11, MICROSECONDLY: 8}\n if maxticks is not None:\n try:\n self.maxticks.update(maxticks)\n except TypeError:\n # Assume we were given an integer. Use this as the maximum\n # number of ticks for every frequency and create a\n # dictionary for this\n self.maxticks = dict(zip(self._freqs,\n [maxticks] * len(self._freqs)))\n self.interval_multiples = interval_multiples\n self.intervald = {\n YEARLY: [1, 2, 4, 5, 10, 20, 40, 50, 100, 200, 400, 500,\n 1000, 2000, 4000, 5000, 10000],\n MONTHLY: [1, 2, 3, 4, 6],\n DAILY: [1, 2, 3, 7, 14, 21],\n HOURLY: [1, 2, 3, 4, 6, 12],\n MINUTELY: [1, 5, 10, 15, 30],\n SECONDLY: [1, 5, 10, 15, 30],\n MICROSECONDLY: [1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000,\n 5000, 10000, 20000, 50000, 100000, 200000, 500000,\n 1000000]}\n self._byranges = [None, range(1, 13), range(1, 32),\n range(0, 24), range(0, 60), range(0, 60), None]\n\n def __call__(self):\n 'Return the locations of the ticks'\n self.refresh()\n return self._locator()\n\n def tick_values(self, vmin, vmax):\n return self.get_locator(vmin, vmax).tick_values(vmin, vmax)\n\n def nonsingular(self, vmin, vmax):\n # whatever is thrown at us, we can scale the unit.\n # But default nonsingular date plots at an ~4 year period.\n if vmin == vmax:\n vmin = vmin - DAYS_PER_YEAR * 2\n vmax = vmax + DAYS_PER_YEAR * 2\n return vmin, vmax\n\n def set_axis(self, axis):\n DateLocator.set_axis(self, axis)\n self._locator.set_axis(axis)\n\n def refresh(self):\n 'Refresh internal information based on current limits.'\n dmin, dmax = self.viewlim_to_dt()\n self._locator = self.get_locator(dmin, dmax)\n\n def _get_unit(self):\n if self._freq in [MICROSECONDLY]:\n return 1. / MUSECONDS_PER_DAY\n else:\n return RRuleLocator.get_unit_generic(self._freq)\n\n def autoscale(self):\n 'Try to choose the view limits intelligently.'\n dmin, dmax = self.datalim_to_dt()\n self._locator = self.get_locator(dmin, dmax)\n return self._locator.autoscale()\n\n def get_locator(self, dmin, dmax):\n 'Pick the best locator based on a distance.'\n delta = relativedelta(dmax, dmin)\n tdelta = dmax - dmin\n\n # take absolute difference\n if dmin > dmax:\n delta = -delta\n tdelta = -tdelta\n\n # The following uses a mix of calls to relativedelta and timedelta\n # methods because there is incomplete overlap in the functionality of\n # these similar functions, and it's best to avoid doing our own math\n # whenever possible.\n numYears = float(delta.years)\n numMonths = (numYears * MONTHS_PER_YEAR) + delta.months\n numDays = tdelta.days # Avoids estimates of days/month, days/year\n numHours = (numDays * HOURS_PER_DAY) + delta.hours\n numMinutes = (numHours * MIN_PER_HOUR) + delta.minutes\n numSeconds = np.floor(_total_seconds(tdelta))\n numMicroseconds = np.floor(_total_seconds(tdelta) * 1e6)\n\n nums = [numYears, numMonths, numDays, numHours, numMinutes,\n numSeconds, numMicroseconds]\n\n use_rrule_locator = [True] * 6 + [False]\n\n # Default setting of bymonth, etc. to pass to rrule\n # [unused (for year), bymonth, bymonthday, byhour, byminute,\n # bysecond, unused (for microseconds)]\n byranges = [None, 1, 1, 0, 0, 0, None]\n\n # Loop over all the frequencies and try to find one that gives at\n # least a minticks tick positions. Once this is found, look for\n # an interval from an list specific to that frequency that gives no\n # more than maxticks tick positions. Also, set up some ranges\n # (bymonth, etc.) as appropriate to be passed to rrulewrapper.\n for i, (freq, num) in enumerate(zip(self._freqs, nums)):\n # If this particular frequency doesn't give enough ticks, continue\n if num < self.minticks:\n # Since we're not using this particular frequency, set\n # the corresponding by_ to None so the rrule can act as\n # appropriate\n byranges[i] = None\n continue\n\n # Find the first available interval that doesn't give too many\n # ticks\n for interval in self.intervald[freq]:\n if num <= interval * (self.maxticks[freq] - 1):\n break\n else:\n # We went through the whole loop without breaking, default to\n # the last interval in the list and raise a warning\n warnings.warn('AutoDateLocator was unable to pick an '\n 'appropriate interval for this date range. '\n 'It may be necessary to add an interval value '\n \"to the AutoDateLocator's intervald dictionary.\"\n ' Defaulting to {0}.'.format(interval))\n\n # Set some parameters as appropriate\n self._freq = freq\n\n if self._byranges[i] and self.interval_multiples:\n byranges[i] = self._byranges[i][::interval]\n interval = 1\n else:\n byranges[i] = self._byranges[i]\n\n # We found what frequency to use\n break\n else:\n raise ValueError('No sensible date limit could be found in the '\n 'AutoDateLocator.')\n\n if use_rrule_locator[i]:\n _, bymonth, bymonthday, byhour, byminute, bysecond, _ = byranges\n\n rrule = rrulewrapper(self._freq, interval=interval,\n dtstart=dmin, until=dmax,\n bymonth=bymonth, bymonthday=bymonthday,\n byhour=byhour, byminute=byminute,\n bysecond=bysecond)\n\n locator = RRuleLocator(rrule, self.tz)\n else:\n locator = MicrosecondLocator(interval, tz=self.tz)\n\n locator.set_axis(self.axis)\n\n locator.set_view_interval(*self.axis.get_view_interval())\n locator.set_data_interval(*self.axis.get_data_interval())\n return locator\n\n\nclass YearLocator(DateLocator):\n \"\"\"\n Make ticks on a given day of each year that is a multiple of base.\n\n Examples::\n\n # Tick every year on Jan 1st\n locator = YearLocator()\n\n # Tick every 5 years on July 4th\n locator = YearLocator(5, month=7, day=4)\n \"\"\"\n def __init__(self, base=1, month=1, day=1, tz=None):\n \"\"\"\n Mark years that are multiple of base on a given month and day\n (default jan 1).\n \"\"\"\n DateLocator.__init__(self, tz)\n self.base = ticker.Base(base)\n self.replaced = {'month': month,\n 'day': day,\n 'hour': 0,\n 'minute': 0,\n 'second': 0,\n 'tzinfo': tz\n }\n\n def __call__(self):\n # if no data have been set, this will tank with a ValueError\n try:\n dmin, dmax = self.viewlim_to_dt()\n except ValueError:\n return []\n\n return self.tick_values(dmin, dmax)\n\n def tick_values(self, vmin, vmax):\n ymin = self.base.le(vmin.year)\n ymax = self.base.ge(vmax.year)\n\n ticks = [vmin.replace(year=ymin, **self.replaced)]\n while 1:\n dt = ticks[-1]\n if dt.year >= ymax:\n return date2num(ticks)\n year = dt.year + self.base.get_base()\n ticks.append(dt.replace(year=year, **self.replaced))\n\n def autoscale(self):\n \"\"\"\n Set the view limits to include the data range.\n \"\"\"\n dmin, dmax = self.datalim_to_dt()\n\n ymin = self.base.le(dmin.year)\n ymax = self.base.ge(dmax.year)\n vmin = dmin.replace(year=ymin, **self.replaced)\n vmax = dmax.replace(year=ymax, **self.replaced)\n\n vmin = date2num(vmin)\n vmax = date2num(vmax)\n return self.nonsingular(vmin, vmax)\n\n\nclass MonthLocator(RRuleLocator):\n \"\"\"\n Make ticks on occurances of each month month, e.g., 1, 3, 12.\n \"\"\"\n def __init__(self, bymonth=None, bymonthday=1, interval=1, tz=None):\n \"\"\"\n Mark every month in *bymonth*; *bymonth* can be an int or\n sequence. Default is ``range(1,13)``, i.e. every month.\n\n *interval* is the interval between each iteration. For\n example, if ``interval=2``, mark every second occurance.\n \"\"\"\n if bymonth is None:\n bymonth = range(1, 13)\n elif isinstance(bymonth, np.ndarray):\n # This fixes a bug in dateutil <= 2.3 which prevents the use of\n # numpy arrays in (among other things) the bymonthday, byweekday\n # and bymonth parameters.\n bymonth = [x.item() for x in bymonth.astype(int)]\n\n rule = rrulewrapper(MONTHLY, bymonth=bymonth, bymonthday=bymonthday,\n interval=interval, **self.hms0d)\n RRuleLocator.__init__(self, rule, tz)\n\n\nclass WeekdayLocator(RRuleLocator):\n \"\"\"\n Make ticks on occurances of each weekday.\n \"\"\"\n\n def __init__(self, byweekday=1, interval=1, tz=None):\n \"\"\"\n Mark every weekday in *byweekday*; *byweekday* can be a number or\n sequence.\n\n Elements of *byweekday* must be one of MO, TU, WE, TH, FR, SA,\n SU, the constants from :mod:`dateutil.rrule`, which have been\n imported into the :mod:`matplotlib.dates` namespace.\n\n *interval* specifies the number of weeks to skip. For example,\n ``interval=2`` plots every second week.\n \"\"\"\n if isinstance(byweekday, np.ndarray):\n # This fixes a bug in dateutil <= 2.3 which prevents the use of\n # numpy arrays in (among other things) the bymonthday, byweekday\n # and bymonth parameters.\n [x.item() for x in byweekday.astype(int)]\n\n rule = rrulewrapper(DAILY, byweekday=byweekday,\n interval=interval, **self.hms0d)\n RRuleLocator.__init__(self, rule, tz)\n\n\nclass DayLocator(RRuleLocator):\n \"\"\"\n Make ticks on occurances of each day of the month. For example,\n 1, 15, 30.\n \"\"\"\n def __init__(self, bymonthday=None, interval=1, tz=None):\n \"\"\"\n Mark every day in *bymonthday*; *bymonthday* can be an int or\n sequence.\n\n Default is to tick every day of the month: ``bymonthday=range(1,32)``\n \"\"\"\n if bymonthday is None:\n bymonthday = range(1, 32)\n elif isinstance(bymonthday, np.ndarray):\n # This fixes a bug in dateutil <= 2.3 which prevents the use of\n # numpy arrays in (among other things) the bymonthday, byweekday\n # and bymonth parameters.\n bymonthday = [x.item() for x in bymonthday.astype(int)]\n\n rule = rrulewrapper(DAILY, bymonthday=bymonthday,\n interval=interval, **self.hms0d)\n RRuleLocator.__init__(self, rule, tz)\n\n\nclass HourLocator(RRuleLocator):\n \"\"\"\n Make ticks on occurances of each hour.\n \"\"\"\n def __init__(self, byhour=None, interval=1, tz=None):\n \"\"\"\n Mark every hour in *byhour*; *byhour* can be an int or sequence.\n Default is to tick every hour: ``byhour=range(24)``\n\n *interval* is the interval between each iteration. For\n example, if ``interval=2``, mark every second occurrence.\n \"\"\"\n if byhour is None:\n byhour = range(24)\n\n rule = rrulewrapper(HOURLY, byhour=byhour, interval=interval,\n byminute=0, bysecond=0)\n RRuleLocator.__init__(self, rule, tz)\n\n\nclass MinuteLocator(RRuleLocator):\n \"\"\"\n Make ticks on occurances of each minute.\n \"\"\"\n def __init__(self, byminute=None, interval=1, tz=None):\n \"\"\"\n Mark every minute in *byminute*; *byminute* can be an int or\n sequence. Default is to tick every minute: ``byminute=range(60)``\n\n *interval* is the interval between each iteration. For\n example, if ``interval=2``, mark every second occurrence.\n \"\"\"\n if byminute is None:\n byminute = range(60)\n\n rule = rrulewrapper(MINUTELY, byminute=byminute, interval=interval,\n bysecond=0)\n RRuleLocator.__init__(self, rule, tz)\n\n\nclass SecondLocator(RRuleLocator):\n \"\"\"\n Make ticks on occurances of each second.\n \"\"\"\n def __init__(self, bysecond=None, interval=1, tz=None):\n \"\"\"\n Mark every second in *bysecond*; *bysecond* can be an int or\n sequence. Default is to tick every second: ``bysecond = range(60)``\n\n *interval* is the interval between each iteration. For\n example, if ``interval=2``, mark every second occurrence.\n\n \"\"\"\n if bysecond is None:\n bysecond = range(60)\n\n rule = rrulewrapper(SECONDLY, bysecond=bysecond, interval=interval)\n RRuleLocator.__init__(self, rule, tz)\n\n\nclass MicrosecondLocator(DateLocator):\n \"\"\"\n Make ticks on occurances of each microsecond.\n\n \"\"\"\n def __init__(self, interval=1, tz=None):\n \"\"\"\n *interval* is the interval between each iteration. For\n example, if ``interval=2``, mark every second microsecond.\n\n \"\"\"\n self._interval = interval\n self._wrapped_locator = ticker.MultipleLocator(interval)\n self.tz = tz\n\n def set_axis(self, axis):\n self._wrapped_locator.set_axis(axis)\n return DateLocator.set_axis(self, axis)\n\n def set_view_interval(self, vmin, vmax):\n self._wrapped_locator.set_view_interval(vmin, vmax)\n return DateLocator.set_view_interval(self, vmin, vmax)\n\n def set_data_interval(self, vmin, vmax):\n self._wrapped_locator.set_data_interval(vmin, vmax)\n return DateLocator.set_data_interval(self, vmin, vmax)\n\n def __call__(self):\n # if no data have been set, this will tank with a ValueError\n try:\n dmin, dmax = self.viewlim_to_dt()\n except ValueError:\n return []\n\n return self.tick_values(dmin, dmax)\n\n def tick_values(self, vmin, vmax):\n nmin, nmax = date2num((vmin, vmax))\n nmin *= MUSECONDS_PER_DAY\n nmax *= MUSECONDS_PER_DAY\n ticks = self._wrapped_locator.tick_values(nmin, nmax)\n ticks = [tick / MUSECONDS_PER_DAY for tick in ticks]\n return ticks\n\n def _get_unit(self):\n \"\"\"\n Return how many days a unit of the locator is; used for\n intelligent autoscaling.\n \"\"\"\n return 1. / MUSECONDS_PER_DAY\n\n def _get_interval(self):\n \"\"\"\n Return the number of units for each tick.\n \"\"\"\n return self._interval\n\n\ndef _close_to_dt(d1, d2, epsilon=5):\n \"\"\"\n Assert that datetimes *d1* and *d2* are within *epsilon* microseconds.\n \"\"\"\n delta = d2 - d1\n mus = abs(_total_seconds(delta) * 1e6)\n assert mus < epsilon\n\n\ndef _close_to_num(o1, o2, epsilon=5):\n \"\"\"\n Assert that float ordinals *o1* and *o2* are within *epsilon*\n microseconds.\n \"\"\"\n delta = abs((o2 - o1) * MUSECONDS_PER_DAY)\n assert delta < epsilon\n\n\ndef epoch2num(e):\n \"\"\"\n Convert an epoch or sequence of epochs to the new date format,\n that is days since 0001.\n \"\"\"\n return EPOCH_OFFSET + np.asarray(e) / SEC_PER_DAY\n\n\ndef num2epoch(d):\n \"\"\"\n Convert days since 0001 to epoch. *d* can be a number or sequence.\n \"\"\"\n return (np.asarray(d) - EPOCH_OFFSET) * SEC_PER_DAY\n\n\ndef mx2num(mxdates):\n \"\"\"\n Convert mx :class:`datetime` instance (or sequence of mx\n instances) to the new date format.\n \"\"\"\n scalar = False\n if not cbook.iterable(mxdates):\n scalar = True\n mxdates = [mxdates]\n ret = epoch2num([m.ticks() for m in mxdates])\n if scalar:\n return ret[0]\n else:\n return ret\n\n\ndef date_ticker_factory(span, tz=None, numticks=5):\n \"\"\"\n Create a date locator with *numticks* (approx) and a date formatter\n for *span* in days. Return value is (locator, formatter).\n \"\"\"\n\n if span == 0:\n span = 1 / HOURS_PER_DAY\n\n mins = span * MINUTES_PER_DAY\n hrs = span * HOURS_PER_DAY\n days = span\n wks = span / DAYS_PER_WEEK\n months = span / DAYS_PER_MONTH # Approx\n years = span / DAYS_PER_YEAR # Approx\n\n if years > numticks:\n locator = YearLocator(int(years / numticks), tz=tz) # define\n fmt = '%Y'\n elif months > numticks:\n locator = MonthLocator(tz=tz)\n fmt = '%b %Y'\n elif wks > numticks:\n locator = WeekdayLocator(tz=tz)\n fmt = '%a, %b %d'\n elif days > numticks:\n locator = DayLocator(interval=int(math.ceil(days / numticks)), tz=tz)\n fmt = '%b %d'\n elif hrs > numticks:\n locator = HourLocator(interval=int(math.ceil(hrs / numticks)), tz=tz)\n fmt = '%H:%M\\n%b %d'\n elif mins > numticks:\n locator = MinuteLocator(interval=int(math.ceil(mins / numticks)),\n tz=tz)\n fmt = '%H:%M:%S'\n else:\n locator = MinuteLocator(tz=tz)\n fmt = '%H:%M:%S'\n\n formatter = DateFormatter(fmt, tz=tz)\n return locator, formatter\n\n\ndef seconds(s):\n \"\"\"\n Return seconds as days.\n \"\"\"\n return float(s) / SEC_PER_DAY\n\n\ndef minutes(m):\n \"\"\"\n Return minutes as days.\n \"\"\"\n return float(m) / MINUTES_PER_DAY\n\n\ndef hours(h):\n \"\"\"\n Return hours as days.\n \"\"\"\n return h / HOURS_PER_DAY\n\n\ndef weeks(w):\n \"\"\"\n Return weeks as days.\n \"\"\"\n return w * DAYS_PER_WEEK\n\n\nclass DateConverter(units.ConversionInterface):\n \"\"\"\n Converter for datetime.date and datetime.datetime data,\n or for date/time data represented as it would be converted\n by :func:`date2num`.\n\n The 'unit' tag for such data is None or a tzinfo instance.\n \"\"\"\n\n @staticmethod\n def axisinfo(unit, axis):\n \"\"\"\n Return the :class:`~matplotlib.units.AxisInfo` for *unit*.\n\n *unit* is a tzinfo instance or None.\n The *axis* argument is required but not used.\n \"\"\"\n tz = unit\n\n majloc = AutoDateLocator(tz=tz)\n majfmt = AutoDateFormatter(majloc, tz=tz)\n datemin = datetime.date(2000, 1, 1)\n datemax = datetime.date(2010, 1, 1)\n\n return units.AxisInfo(majloc=majloc, majfmt=majfmt, label='',\n default_limits=(datemin, datemax))\n\n @staticmethod\n def convert(value, unit, axis):\n \"\"\"\n If *value* is not already a number or sequence of numbers,\n convert it with :func:`date2num`.\n\n The *unit* and *axis* arguments are not used.\n \"\"\"\n if units.ConversionInterface.is_numlike(value):\n return value\n return date2num(value)\n\n @staticmethod\n def default_units(x, axis):\n \"\"\"\n Return the tzinfo instance of *x* or of its first element, or None\n \"\"\"\n if isinstance(x, np.ndarray):\n x = x.ravel()\n\n try:\n x = cbook.safe_first_element(x)\n except (TypeError, StopIteration):\n pass\n\n try:\n return x.tzinfo\n except AttributeError:\n pass\n return None\n\n\nunits.registry[datetime.date] = DateConverter()\nunits.registry[datetime.datetime] = DateConverter()\n" ]
[ [ "numpy.ceil", "matplotlib.cbook.is_string_like", "matplotlib.ticker.MultipleLocator", "numpy.asarray", "numpy.vectorize", "matplotlib.externals.six.callable", "matplotlib.units.ConversionInterface.is_numlike", "matplotlib.cbook.iterable", "matplotlib.externals.six.moves.zip", "matplotlib.cbook.unicode_safe", "matplotlib.units.AxisInfo", "numpy.linspace", "matplotlib.cbook.safe_first_element", "matplotlib.ticker.Base" ] ]
soldfield/xyz_surfaces
[ "0685ba8f104df08f0f5180ea435425287960c039" ]
[ "StratWedge.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Aug 3 19:42:46 2017\n\nShort script to generate a two-dimensional fold, based on a cosine curve.\n\nOutputs xyz point cloud as a text file in the working directory.\n\n@author: Simon J. Oldfield\n\n Copyright 2016 Simon Oldfield\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n \n \n\"\"\"\n\n## Initially attemting to build a simple sin wave\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n## Name variables:\n#Xmin = 0.\n#Xmax = 4000.\n#Ymin = 0.\n#Ymax = 2000.\n#WaveXmin = 1000.\n#WaveXmax = 3000.\n#WaveAmp = 800.\n#Wavelength = 1600.\n#Spacing = 100.\n\n\ndef stratwedge(Xmin, Xmax, Ymin, Ymax, WaveXmin, WaveXmax, WaveAmp, Wavelength, Spacing):\n ## Calculate basic parameters\n Xrange = WaveXmax - WaveXmin\n Yrange = Ymax - Ymin\n XSamps = Xrange / Spacing\n YSamps = Yrange / Spacing\n \n ## Generate wavelet of desired size\n x = np.arange(WaveXmin, WaveXmax, Spacing)\n \n # Add *-1 for syncline\n z = ((np.cos(2 * np.pi * x / Xrange) / 2) + 0.5) * 1.\n z = z * WaveAmp\n \n# flat_x = np.arange(Xmin, Xmax, Spacing)\n# flat_z = np.zeros(flat_x)\n \n ## Add flats to either side of wavelet\n # Below X side\n x1 = np.arange(Xmin, WaveXmin, Spacing)\n z1 = np.zeros(int((WaveXmin - Xmin) / Spacing))\n \n # Above X side\n x2 = np.arange(WaveXmax, (Xmax + Spacing), Spacing)\n z2 = np.zeros(int(((Xmax - WaveXmax) + Spacing) / Spacing))\n \n # Append arrays for each coordinate\n Xall = np.hstack((x1, x, x2))\n Yall = np.zeros((len(Xall)))\n Zall = np.hstack((z1, z, z2))\n \n # Combine XYZ\n # ALL = np.vstack((Xall, Zall, Yall))\n xyz = np.column_stack((Xall, Yall, Zall))\n \n ## Stretch to pseudo-3D through the Y axis\n # Create loop to add sample offset for Y to each line and add output to the column stack\n\n Yarray = np.arange(Ymin, (Ymax + Spacing), Spacing)\n \n # Initialise array and iterate to duplicate teh first line for each value of y\n xyz_stk = np.array([0,0,0])\n \n for y in Yarray:\n xyz2 = xyz + [0, y, 0]\n xyz_stk = np.vstack(( xyz_stk, xyz2))\n \n # Delete the first row of the array generated in initiation\n xyz_stk = np.delete(xyz_stk, (0), axis = 0)\n \n ## Plot for reference\n plt.axis('equal')\n plt.plot(Xall, Zall)\n plt.xlabel('X Distance')\n plt.ylabel('Z Distance')\n #np.savetxt('anticline_xyz.txt', (xyz_stk), fmt='%16s')\n \n plt.show()\n \n #Output to text file in working directory, format 16 character string per column\n\ndef coswave(depth, width, height, spacing):\n xs = np.arange(0, width+1, spacing)\n ys= depth + (np.cos((2*np.pi*xs)/width)*0.5)*height+ height/2\n \n return xs, ys\n\ndef planehz(depth, width, spacing):\n xs = np.arange(0, width+spacing, spacing)\n ys = np.empty_like(xs)\n ys = np.full(xs.size, depth)\n \n return xs, ys\n\n\ndef CosLayerStk(depth_top, dx, dz_pinch, dz_model, xspacing, Nl=12):\n Sx = xspacing # x sample rate\n \n xlen = int(dx/Sx)+1\n stk = np.zeros([Nl+2, xlen])\n \n ### Set parameters for cosine curve\n costop = depth_top + dz_pinch\n dz_cos = dz_model - dz_pinch\n \n stk[0,:], stk[1,:]= coswave(costop, dx, dz_cos, Sx)\n \n stk[-1, :] = planehz(depth_top, dx, Sx)[1]\n \n for i in np.arange(xlen):\n z_int = (stk[1,i]-stk[-1, i])/Nl\n for j in np.arange(2, Nl+1):\n stk[j,i]=stk[-1,i]+z_int*(j-1)\n \n for i in np.arange(1,stk.shape[0]):\n plt.plot(stk[0,:], stk[i,:])\n \n return stk\n\n\n\ndepth = 2000\nwidth = 1000\ndz_model = 500\ndz_pinch = 50\nxspacing = 10\nNl = 12\n\n\nstk = CosLayerStk(depth, width, dz_pinch, dz_model, xspacing)\n\n\n\n\n" ]
[ [ "numpy.full", "numpy.array", "numpy.delete", "numpy.zeros", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "numpy.arange", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel", "numpy.empty_like", "numpy.vstack", "numpy.hstack", "numpy.column_stack", "numpy.cos", "matplotlib.pyplot.axis" ] ]
daochenzha/rapid
[ "1611e47fffac0f61e6c07ad5388eb2368a426f06" ]
[ "rapid/mujoco_envs/episode_hopper.py" ]
[ "import numpy as np\nfrom gym import utils\nfrom gym.envs.mujoco import mujoco_env\n\nclass EpisodeHopperEnv(mujoco_env.MujocoEnv, utils.EzPickle):\n def __init__(self):\n self.t = 0\n self.r = 0\n mujoco_env.MujocoEnv.__init__(self, 'hopper.xml', 4)\n utils.EzPickle.__init__(self)\n\n def step(self, a):\n posbefore = self.sim.data.qpos[0]\n self.do_simulation(a, self.frame_skip)\n posafter, height, ang = self.sim.data.qpos[0:3]\n alive_bonus = 1.0\n reward = (posafter - posbefore) / self.dt\n reward += alive_bonus\n reward -= 1e-3 * np.square(a).sum()\n s = self.state_vector()\n done = not (np.isfinite(s).all() and (np.abs(s[2:]) < 100).all() and\n (height > .7) and (abs(ang) < .2))\n ob = self._get_obs()\n self.t += 1\n self.r += reward\n if done:\n return_r = self.r\n self.r = 0\n self.t = 0\n else:\n return_r = 0\n return ob, return_r, done, {}\n\n def _get_obs(self):\n return np.concatenate([\n self.sim.data.qpos.flat[1:],\n np.clip(self.sim.data.qvel.flat, -10, 10)\n ])\n\n def reset_model(self):\n self.t = 0\n self.r = 0\n qpos = self.init_qpos + self.np_random.uniform(low=-.005, high=.005, size=self.model.nq)\n qvel = self.init_qvel + self.np_random.uniform(low=-.005, high=.005, size=self.model.nv)\n self.set_state(qpos, qvel)\n return self._get_obs()\n\n def viewer_setup(self):\n self.viewer.cam.trackbodyid = 2\n self.viewer.cam.distance = self.model.stat.extent * 0.75\n self.viewer.cam.lookat[2] = 1.15\n self.viewer.cam.elevation = -20\n" ]
[ [ "numpy.square", "numpy.abs", "numpy.isfinite", "numpy.clip" ] ]
edge-analytics/fpga-sleep-tracker
[ "50efd114500e134297be5229775a9ec6809abb53" ]
[ "fpga/test/featurize/actigraphy_counts/actigraphy_counts_tb.py" ]
[ "import cocotb\nfrom cocotb.clock import Clock\nfrom cocotb.triggers import ClockCycles, ReadWrite, NextTimeStep, RisingEdge, FallingEdge\nfrom cocotb.binary import BinaryValue\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom scipy.signal import butter, filtfilt\nfrom fixedpoint import FixedPoint\n\n\n@cocotb.test() \nasync def test_peak_detect(dut):\n num_samples_per_epoch = 15*50\n num_epochs = 10\n num_samples = num_samples_per_epoch * num_epochs\n data = np.loadtxt('46343_acceleration.txt', delimiter=' ')\n #count_feature = np.loadtxt('46343_cleaned_counts.out', delimiter=' ')\n fs = 50\n time = np.arange(np.amin(data[:, 0]), np.amax(data[:, 0]), 1.0 / fs)\n z_accel = np.interp(time, data[:, 0], data[:, 3])\n # cf_low = 3\n # cf_hi = 11\n # order = 5\n # w1 = cf_low / (fs / 2)\n # w2 = cf_hi / (fs / 2)\n # pass_band = [w1, w2]\n # b, a = butter(order, pass_band, 'bandpass')\n # z_filt = filtfilt(b, a, z_accel)\n start_offset_sec = 120\n offset = fs * start_offset_sec\n z_accel = z_accel[offset:offset+num_samples]\n\n print(f\"Number of samples to input {z_accel.shape[0]}\")\n #count_feature = count_feature[::num_epochs]\n clk = dut.clk\n dut.i_z_accel <= 0\n dut.i_valid <= 0\n cocotb.fork(Clock(clk, 25, units=\"ns\").start())\n # Reset logic\n await NextTimeStep()\n dut.reset <= 1\n await ClockCycles(clk, 1)\n await ReadWrite()\n dut.reset <= 0\n await ClockCycles(clk, 1)\n await ReadWrite()\n\n for i, z in enumerate(z_accel):\n dut.i_z_accel <= BinaryValue(str(FixedPoint(float(z/5), 1, 7)))\n dut.i_valid <= 1\n await ClockCycles(clk, 1)\n dut.i_valid <= 0\n await ClockCycles(clk, 10)\n \n dut.i_valid <= 0\n\n await ClockCycles(clk, 100)\n" ]
[ [ "numpy.loadtxt", "numpy.amax", "numpy.interp", "numpy.amin" ] ]
tehkillerbee/mmdetection-to-tensorrt
[ "b1532465ab1c6617b350981bbda2bc361fe291a6" ]
[ "mmdet2trt/models/dense_heads/fovea_head.py" ]
[ "import mmdet2trt.ops.util_ops as mm2trt_util\nimport torch\nfrom mmdet2trt.models.builder import register_wraper\nfrom mmdet2trt.models.dense_heads.anchor_free_head import AnchorFreeHeadWraper\n\n\n@register_wraper('mmdet.models.FoveaHead')\nclass FoveaHeadWraper(AnchorFreeHeadWraper):\n\n def __init__(self, module):\n super(FoveaHeadWraper, self).__init__(module)\n\n def forward(self, feat, x):\n img_shape = x.shape[2:]\n module = self.module\n cfg = self.test_cfg\n cls_scores, bbox_preds = module(feat)\n mlvl_points = self.get_points(cls_scores, flatten=True)\n\n mlvl_bboxes = []\n mlvl_scores = []\n for cls_score, bbox_pred, stride, base_len, (y, x) in zip(\n cls_scores, bbox_preds, module.strides, module.base_edge_list,\n mlvl_points):\n scores = cls_score.permute(0, 2, 3, 1).reshape(\n cls_score.shape[0], -1, module.cls_out_channels).sigmoid()\n bbox_pred = bbox_pred.permute(0, 2, 3,\n 1).reshape(bbox_pred.shape[0], -1,\n 4).exp()\n x = x.unsqueeze(0) + 0.5\n y = y.unsqueeze(0) + 0.5\n x = x.expand_as(bbox_pred[:, :, 0])\n y = y.expand_as(bbox_pred[:, :, 0])\n nms_pre = cfg.get('nms_pre', -1)\n if nms_pre > 0:\n # concate zero to enable topk,\n # dirty way, will find a better way in future\n scores = mm2trt_util.pad_with_value(scores, 1, nms_pre, 0.)\n bbox_pred = mm2trt_util.pad_with_value(bbox_pred, 1, nms_pre)\n y = mm2trt_util.pad_with_value(y, 1, nms_pre)\n x = mm2trt_util.pad_with_value(x, 1, nms_pre)\n\n # do topk\n max_scores, _ = (scores).max(dim=2)\n _, topk_inds = max_scores.topk(nms_pre, dim=1)\n bbox_pred = mm2trt_util.gather_topk(bbox_pred, 1, topk_inds)\n scores = mm2trt_util.gather_topk(scores, 1, topk_inds)\n y = mm2trt_util.gather_topk(y, 1, topk_inds)\n x = mm2trt_util.gather_topk(x, 1, topk_inds)\n\n x1 = (stride * x - base_len * bbox_pred[:, :, 0]).\\\n clamp(min=0, max=img_shape[1] - 1)\n y1 = (stride * y - base_len * bbox_pred[:, :, 1]).\\\n clamp(min=0, max=img_shape[0] - 1)\n x2 = (stride * x + base_len * bbox_pred[:, :, 2]).\\\n clamp(min=0, max=img_shape[1] - 1)\n y2 = (stride * y + base_len * bbox_pred[:, :, 3]).\\\n clamp(min=0, max=img_shape[0] - 1)\n bboxes = torch.stack([x1, y1, x2, y2], -1)\n mlvl_bboxes.append(bboxes)\n mlvl_scores.append(scores)\n\n mlvl_bboxes = torch.cat(mlvl_bboxes, dim=1)\n mlvl_scores = torch.cat(mlvl_scores, dim=1)\n\n mlvl_proposals = mlvl_bboxes.unsqueeze(2)\n\n max_scores, _ = mlvl_scores.max(dim=2)\n topk_pre = max(1000, nms_pre)\n _, topk_inds = max_scores.topk(\n min(topk_pre, mlvl_scores.shape[1]), dim=1)\n mlvl_proposals = mm2trt_util.gather_topk(mlvl_proposals, 1, topk_inds)\n mlvl_scores = mm2trt_util.gather_topk(mlvl_scores, 1, topk_inds)\n\n num_bboxes = mlvl_proposals.shape[1]\n num_detected, proposals, scores, cls_id = self.rcnn_nms(\n mlvl_scores, mlvl_proposals, num_bboxes, self.test_cfg.max_per_img)\n\n return num_detected, proposals, scores, cls_id\n" ]
[ [ "torch.cat", "torch.stack" ] ]
russellmendonca/RoboNet
[ "de30fa069dacb2888e62bd239e7a3471ea3aaa9d" ]
[ "robonet/video_prediction/utils/ffmpeg_gif.py" ]
[ "import os\n\nimport numpy as np\n\n\ndef save_gif(gif_fname, images, fps):\n \"\"\"\n To generate a gif from image files, first generate palette from images\n and then generate the gif from the images and the palette.\n ffmpeg -i input_%02d.jpg -vf palettegen -y palette.png\n ffmpeg -i input_%02d.jpg -i palette.png -lavfi paletteuse -y output.gif\n\n Alternatively, use a filter to map the input images to both the palette\n and gif commands, while also passing the palette to the gif command.\n ffmpeg -i input_%02d.jpg -filter_complex \"[0:v]split[x][z];[z]palettegen[y];[x][y]paletteuse\" -y output.gif\n\n To directly pass in numpy images, use rawvideo format and `-i -` option.\n \"\"\"\n from subprocess import Popen, PIPE\n head, tail = os.path.split(gif_fname)\n if head and not os.path.exists(head):\n os.makedirs(head)\n h, w, c = images[0].shape\n cmd = ['ffmpeg', '-y',\n '-f', 'rawvideo',\n '-vcodec', 'rawvideo',\n '-r', '%.02f' % fps,\n '-s', '%dx%d' % (w, h),\n '-pix_fmt', {1: 'gray', 3: 'rgb24', 4: 'rgba'}[c],\n '-i', '-',\n '-filter_complex', '[0:v]split[x][z];[z]palettegen[y];[x][y]paletteuse',\n '-r', '%.02f' % fps,\n '%s' % gif_fname]\n proc = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)\n for image in images:\n proc.stdin.write(image.tostring())\n out, err = proc.communicate()\n if proc.returncode:\n err = '\\n'.join([' '.join(cmd), err.decode('utf8')])\n raise IOError(err)\n del proc\n\n\ndef encode_gif(images, fps):\n from subprocess import Popen, PIPE\n h, w, c = images[0].shape\n cmd = ['ffmpeg', '-y',\n '-f', 'rawvideo',\n '-vcodec', 'rawvideo',\n '-r', '%.02f' % fps,\n '-s', '%dx%d' % (w, h),\n '-pix_fmt', {1: 'gray', 3: 'rgb24', 4: 'rgba'}[c],\n '-i', '-',\n '-filter_complex', '[0:v]split[x][z];[z]palettegen[y];[x][y]paletteuse',\n '-r', '%.02f' % fps,\n '-f', 'gif',\n '-']\n proc = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)\n for image in images:\n proc.stdin.write(image.tostring())\n out, err = proc.communicate()\n if proc.returncode:\n err = '\\n'.join([' '.join(cmd), err.decode('utf8')])\n raise IOError(err)\n del proc\n return out\n\n\ndef main():\n images_shape = (12, 64, 64, 3) # num_frames, height, width, channels\n images = np.random.randint(256, size=images_shape).astype(np.uint8)\n\n save_gif('output_save.gif', images, 4)\n with open('output_save.gif', 'rb') as f:\n string_save = f.read()\n\n string_encode = encode_gif(images, 4)\n with open('output_encode.gif', 'wb') as f:\n f.write(string_encode)\n\n print(np.all(string_save == string_encode))\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "numpy.all", "numpy.random.randint" ] ]
mathandy/functorch
[ "8d82eb3bb963e6d83d62df2f17b91ab6381dc1f0" ]
[ "examples/compilation/simple_function.py" ]
[ "# Copyright (c) Facebook, Inc. and its affiliates.\n# All rights reserved.\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.\n\nfrom functorch import grad, nnc_jit, make_fx, make_nnc\nimport torch\nimport time\n\n\ndef f(x):\n return torch.sin(x).sum()\n\n\ninp = torch.randn(100)\ngrad_pt = grad(f)\ngrad_fx = make_fx(grad_pt)(inp)\ngrad_nnc = nnc_jit(grad_pt, skip_specialization=True)\nloopnest = make_nnc(grad_pt)(inp)\nprint(loopnest)\n\n\ndef bench(name, f, iters=10000, warmup=3):\n for _ in range(warmup):\n f()\n begin = time.time()\n for _ in range(iters):\n f()\n print(f\"{name}: \", time.time() - begin)\n\n\nbench(\"Pytorch: \", lambda: grad_pt(inp))\nbench(\"FX: \", lambda: grad_fx(inp))\nbench(\"NNC: \", lambda: grad_nnc(inp))\n" ]
[ [ "torch.randn", "torch.sin" ] ]