repo_name
stringlengths 6
130
| hexsha
list | file_path
list | code
list | apis
list |
---|---|---|---|---|
azopticsinc/optical-neural-network
|
[
"28280014a6c1fc717a5077ed5e3c3496a4b103ac"
] |
[
"codes/ONNet/case_brain.py"
] |
[
"'''\n@Author: Yingshi Chen\n\n@Date: 2020-04-08 17:12:34\n@\n# Description: \n'''\nimport torch\nfrom torch.utils.data import Dataset\nfrom torchvision.transforms import ToPILImage\nimport os\nimport math\nimport hdf5storage\nfrom enum import Enum\nimport re\nfrom torchvision.transforms import transforms\nimport cv2\nimport numpy as np\n\ndef get_data_if_needed(data_path='./data/', url=\"https://ndownloader.figshare.com/articles/1512427/versions/5\"):\n if os.path.isdir(data_path):\n #_arrange_brain_tumor_data(data_path)\n print(\"Data directory already exists. \",\n \"if from some reason the data directory structure is wrong please remove the data dir and rerun this script\")\n return\n filename = \"all_data.zip\"\n download_url(url, data_path, filename)\n unzip_all_files(data_path)\n _arrange_brain_tumor_data(data_path)\n\ndef convert_landmark_to_bounding_box(landmark):\n x_min = x_max = y_min = y_max = None\n for x, y in landmark:\n if x_min is None:\n x_min = x_max = x\n y_min = y_max = y\n else:\n x_min, x_max = min(x, x_min), max(x, x_max)\n y_min, y_max = min(y, y_min), max(y, y_max)\n return [int(x_min), int(x_max), int(y_min), int(y_max)]\n\nclass ClassesLabels(Enum):\n Meningioma = 1\n Glioma = 2\n Pituitary = 3\n\n def __len__(self):\n return 3\n\ndef normalize(x, mean=470, std=None):\n mean_tansor = torch.ones_like(x) * mean\n x -= mean_tansor\n if std:\n x /= std\n return x\n\n# https://github.com/galprz/brain-tumor-segmentation\nclass BrainTumorDataset(Dataset): \n def __init__(self,config, root, train=True, download=True,\n classes=(ClassesLabels.Meningioma,\n ClassesLabels.Glioma,\n ClassesLabels.Pituitary)):\n super().__init__()\n self.config = config\n test_fr = 0.15\n if download:\n get_data_if_needed(root)\n self.root = root\n # List all data files\n items = []\n if ClassesLabels.Meningioma in classes:\n items += ['meningioma/' + item for item in os.listdir(root + 'meningioma/')]\n if ClassesLabels.Glioma in classes:\n items += ['glioma/' + item for item in os.listdir(root + 'glioma/')]\n if ClassesLabels.Meningioma in classes:\n items += ['pituitary/' + item for item in os.listdir(root + 'pituitary/')]\n\n if train:\n self.items = items[0:math.floor((1-test_fr) * len(items)) + 1]\n else:\n self.items = items[math.floor((1-test_fr) * len(items)) + 1:]\n\n def __len__(self):\n return len(self.items)\n\n def __getitem__(self, idx):\n if not (0 <= idx < len(self.items)):\n raise IndexError(\"Idx out of bound\") \n if False:\n data = hdf5storage.loadmat(self.root + self.items[idx])['cjdata'][0]\n # transform the tumor border to array of (x, y) tuple\n xy = data[3]\n landmarks = []\n for i in range(0, len(xy), 2):\n x = xy[i][0]\n y = xy[i + 1][0]\n landmarks.append((x, y))\n mask = data[4]\n data[2].dtype = 'uint16'\n image = data[2] #ToPILImage()(data[2])\n image_with_metadata = {\n \"label\": int(data[0][0]),\n \"image\": image,\n \"landmarks\": landmarks,\n \"mask\": mask,\n \"bounding_box\": convert_landmark_to_bounding_box(landmarks)\n }\n return image_with_metadata\n else:\n return load_mat_trans(self.root + self.items[idx],target_size=self.config.IMG_size ) #(128,128)\n\ndef ToUint8(arr):\n a_0,a_1 = np.min(arr),np.max(arr)\n arr = (arr-a_0)/(a_1-a_0)*255\n arr = arr.astype(np.uint8)\n a_0,a_1 = np.min(arr),np.max(arr)\n return arr\n\ndef load_mat_trans(path,target_size=None):\n data_mat = hdf5storage.loadmat(path)\n data = data_mat['cjdata'][0]\n xy = data[3]\n landmarks = []\n for i in range(0, len(xy), 2):\n x = xy[i][0]\n y = xy[i + 1][0]\n landmarks.append((x, y))\n mask = data[4].astype(np.float32)\n m_0,m_1 = np.min(mask),np.max(mask)\n #data[2].dtype = 'uint16'\n image = data[2].astype(np.float32) #ToPILImage()(data[2]) \n if target_size is not None:\n image = cv2.resize(image,target_size) \n #cv2.imshow(\"\",image); cv2.waitKey(0) \n mask = cv2.resize(mask,target_size) \n #cv2.imshow(\"\",mask*255); cv2.waitKey(0) \n image = ToUint8(image) \n mask = ToUint8(mask) \n image_with_metadata = {\n \"label\": int(data[0][0]),\n \"image\": image,\n \"landmarks\": landmarks,\n \"mask\": mask,\n \"bounding_box\": convert_landmark_to_bounding_box(landmarks)\n }\n return image_with_metadata\n\nmask_transformer = transforms.Compose([ \n transforms.ToTensor(), \n])\n\nimage_transformer_0 = transforms.Compose([ \n transforms.ToTensor(), \n transforms.Lambda(lambda x: normalize(x))\n])\nimage_transformer = transforms.Compose([ \n transforms.ToTensor(), \n])\n\nclass BrainTumorDatasetMask(BrainTumorDataset):\n def transform(self,image, mask): \n img = image_transformer(image).float()\n mask = mask_transformer(mask).float()\n return img,mask\n\n def __init__(self,config, root, train=True, transform=None, classes=(ClassesLabels.Meningioma,\n ClassesLabels.Glioma,\n ClassesLabels.Pituitary)):\n super().__init__(config,root, train, classes=classes)\n #self.transform = brain_transform\n\n def __getitem__(self, idx):\n item = super().__getitem__(idx)\n sample = (item[\"image\"], item[\"mask\"])\n #return sample if self.transform is None else self.transform(*sample)\n img,mask = self.transform(item[\"image\"], item[\"mask\"])\n #i_0,i_1 = torch.min(img),torch.max(img)\n #m_0,m_1 = torch.min(mask),torch.max(mask)\n return img,mask\n\ndef _arrange_brain_tumor_data(root):\n # Remove and split files\n items = [item for item in filter(lambda item: re.search(\"^[0-9]+\\.mat$\", item), os.listdir(root))]\n try:\n os.mkdir(root + 'meningioma/')\n except:\n print(\"Meningioma directory already exists\")\n try:\n os.mkdir(root + 'glioma/')\n except:\n print(\"Glioma directory already exists\")\n try:\n os.mkdir(root + 'pituitary/')\n except:\n print(\"Pituitary directory already exists\")\n\n for item in items:\n sample = hdf5storage.loadmat(root + item)['cjdata'][0]\n if sample[2].shape[0] == 512:\n if sample[0] == 1:\n os.rename(root + item, root + 'meningioma/' + item)\n if sample[0] == 2:\n os.rename(root + item, root + 'glioma/' + item)\n if sample[0] == 3:\n os.rename(root + item, root + 'pituitary/' + item)\n else:\n os.remove(root + item)\n\n"
] |
[
[
"numpy.max",
"torch.ones_like",
"numpy.min"
]
] |
hephaex/data-validation
|
[
"21543a6896e4630aeb8b569e79e7a7cc03a3c565"
] |
[
"tensorflow_data_validation/utils/bin_util_test.py"
] |
[
"# Copyright 2019 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Tests for bin_util functions.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom absl.testing import absltest\nfrom absl.testing import parameterized\nimport numpy as np\nimport pyarrow as pa\n\nfrom tensorflow_data_validation.utils import bin_util\n\n\nclass BinArrayTest(parameterized.TestCase):\n \"\"\"Tests for bin_array.\"\"\"\n\n @parameterized.named_parameters([\n ('simple', pa.array([0.1, 0.5, 0.75]), [0.25, 0.75], [0, 1, 2],\n [0, 1, 2]),\n ('negative_values', pa.array([-0.8, -0.5, -0.1]), [0.25], [0, 1, 2],\n [0, 0, 0]),\n ('inf_values', pa.array([float('-inf'), 0.5, float('inf')]),\n [0.25, 0.75], [0, 1, 2], [0, 1, 2]),\n ('nan_values', pa.array([np.nan, 0.5]), [0.25, 0.75], [1], [1]),\n ('negative_boundaries', pa.array([-0.8, -0.5]), [-0.75, -0.25], [0, 1],\n [0, 1]),\n ('empty_array', pa.array([]), [0.25], [], []),\n ('none_value', pa.array([None, 0.5]), [0.25], [1], [1]),\n ('null_array', pa.array([None, None], type=pa.null()), [0.25], [], [])\n ])\n def test_bin_array(self, array, boundaries, expected_indices, expected_bins):\n indices, bins = bin_util.bin_array(array, boundaries)\n np.testing.assert_array_equal(expected_indices, indices)\n np.testing.assert_array_equal(expected_bins, bins)\n\n\nif __name__ == '__main__':\n absltest.main()\n"
] |
[
[
"numpy.testing.assert_array_equal"
]
] |
ForrestPi/DefectDetection
|
[
"7e999335ffbd50519cdfaba7de0d6bfa306a579a"
] |
[
"RoadCrackSegmentation/get_plot.py"
] |
[
"# -*- coding: UTF-8 -*-\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport os\n\ndef get_loss_list(model):\n dir = os.path.join('checkpoint', model)\n files = os.listdir(dir)\n sorted(files)\n\n index =[]\n losses = []\n acc =[]\n for i,x in enumerate(files):\n index.append(i)\n losses.append(float(x.split(\"-\")[2].strip()))\n acc.append(float(x.split(\"-\")[3][:-3].strip()))\n\n return index, losses,acc\n\n\n\ndef plot(model1,model2,if_loss=1):\n\n x1,y1,z1 = get_loss_list(model1)\n x2,y2,z2 = get_loss_list(model2)\n\n assert x1 ==x2\n #开始画图\n\n if if_loss:\n pic_name = 'loss'\n plt.plot(x1, y1, color='green', label=model1,linewidth=1.0)\n plt.plot(x2, y2, color='red', label=model2,linewidth=1.0)\n\n else:\n pic_name = 'acc'\n plt.plot(x1, z1, color='blueviolet', label=model1,linewidth=1.0)\n plt.plot(x2, z2, color='chocolate', label=model2,linewidth=1.0)\n\n plt.grid(linestyle='-.')\n plt.legend() # 显示图例\n\n plt.xlabel('epoch')\n plt.ylabel('val_'+pic_name)\n # plt.show()\n plt.savefig(pic_name+'.png')\n\n\ndef plot1(model1, model2, name):\n x1, y1, z1 = get_loss_list(model1)\n x2, y2, z2 = get_loss_list(model2)\n\n assert x1 == x2\n # 开始画图\n fig = plt.figure(figsize=(12, 5))\n fig.add_subplot(1, 2, 1)\n\n pic_name = 'loss'\n plt.plot(x1, y1, color='green', label=model1, linewidth=1.0)\n plt.plot(x2, y2, color='red', label=model2, linewidth=1.0)\n plt.grid(linestyle='-.')\n plt.legend() # 显示图例\n plt.xlabel('epoch')\n plt.ylabel('val_' + pic_name)\n\n fig.add_subplot(1, 2, 2)\n pic_name = 'acc'\n plt.plot(x1, z1, color='blueviolet', label=model1, linewidth=1.0)\n plt.plot(x2, z2, color='chocolate', label=model2, linewidth=1.0)\n plt.grid(linestyle='-.')\n plt.legend() # 显示图例\n plt.xlabel('epoch')\n plt.ylabel('val_' + pic_name)\n # plt.show()\n plt.savefig(name + '.png')\n\nif __name__ == '__main__':\n model1 = 'Unet'\n model2 = 'GCUnet'\n\n # plot(model1,model2,if_loss=0)\n\n plot1(model1,model2,'result')\n\n"
] |
[
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.ylabel"
]
] |
Adrimeov/keras-malicious-url-detector
|
[
"22b8d075b41117f016100bb5ebff14a77907dacb"
] |
[
"keras_malicious_url_detector/library/utility/url_data_loader.py"
] |
[
"import pandas as pd\nimport os\n\n\ndef load_url_data(data_dir_path):\n url_data = pd.read_csv(data_dir_path, sep=',')\n\n url_data.columns = ['text', 'label']\n\n class_zero = url_data[url_data['label'] == 0].reset_index()\n class_one = url_data[url_data['label'] == 1].reset_index()\n\n class_zero = class_zero.truncate(before=1, after=class_one.shape[0])\n\n url_data = pd.concat([class_zero, class_one])\n url_data = url_data.sample(frac=1.0).reset_index()\n\n return url_data\n\n\ndef main():\n data_dir_path = './data'\n url_data = load_url_data(data_dir_path)\n\n print(url_data.head())\n\n\nif __name__ == '__main__':\n main()\n"
] |
[
[
"pandas.concat",
"pandas.read_csv"
]
] |
ska-telescope/katpoint
|
[
"0e94e17db179065835c701ddaba079854eb1e7e5"
] |
[
"katpoint/conversion.py"
] |
[
"################################################################################\n# Copyright (c) 2009-2020, National Research Foundation (SARAO)\n#\n# Licensed under the BSD 3-Clause License (the \"License\"); you may not use\n# this file except in compliance with the License. You may obtain a copy\n# of the License at\n#\n# https://opensource.org/licenses/BSD-3-Clause\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\"\"\"Geodetic and spherical coordinate transformations, and angle conversions.\"\"\"\n\nimport numpy as np\nimport astropy.units as u\nfrom astropy.coordinates import Angle\n\n# --------------------------------------------------------------------------------------------------\n# --- Angle conversion utilities\n# --------------------------------------------------------------------------------------------------\n\n\ndef to_angle(s, sexagesimal_unit=u.deg):\n \"\"\"Construct an `Angle` with default units.\n\n This creates an :class:`~astropy.coordinates.Angle` with the following\n default units:\n\n - A number is in radians.\n - A decimal string ('123.4') is in degrees.\n - A sexagesimal string ('12:34:56.7') or tuple has `sexagesimal_unit`.\n\n In addition, bytes are decoded to ASCII strings to normalize user inputs.\n\n Parameters\n ----------\n s : :class:`~astropy.coordinates.Angle` or equivalent, string, float, tuple\n Anything accepted by `Angle` and also unitless strings, numbers, tuples\n sexagesimal_unit : :class:`~astropy.units.UnitBase` or str, optional\n The unit applied to sexagesimal strings and tuples\n\n Returns\n -------\n angle : :class:`~astropy.coordinates.Angle`\n Astropy `Angle`\n \"\"\"\n try:\n return Angle(s)\n except u.UnitsError:\n # Bytes is a sequence of ints that will inadvertently end up as radians, so crash instead\n if isinstance(s, bytes):\n raise TypeError(f'Raw bytes {s} not supported: '\n 'first decode to string (or add unit)') from None\n # We now have a number, string or tuple without a unit\n if isinstance(s, str) and ':' in s or isinstance(s, tuple):\n return Angle(s, unit=sexagesimal_unit)\n elif isinstance(s, str):\n return Angle(s, unit=u.deg)\n else:\n # XXX Maybe deprecate this in future and only deal with strings here\n return Angle(s, unit=u.rad)\n\n\ndef strip_zeros(str_or_array_of_str):\n \"\"\"Remove trailing zeros and unnecessary decimal points from numerical strings.\"\"\"\n s = np.char.rstrip(str_or_array_of_str, '0')\n s = np.char.rstrip(s, '.')\n return s if s.ndim else s.item()\n\n\ndef angle_to_string(angle, show_unit=True, **kwargs):\n \"\"\"Convert an Angle to string(s) while maintaining precision and compatibility.\n\n This serialises angles to strings with high precision (1 micron @ 13000 km)\n while maintaining some compatibility with older katpoint angle strings.\n The main difference is that the numerical representation (sexagesimal or\n decimal) has a suffix indicating the unit ('d' for degree or 'h' for hour).\n This allows Astropy Angles to be constructed directly from it without the\n need for :func:`to_angle`. This suffix can be suppressed when generating\n strings for display purposes. Extra keyword arguments are passed on to\n :meth:`~astropy.coordinates.Angle.to_string` to control the appearance of\n the string to some extent.\n\n Parameters\n ----------\n angle : :class:`~astropy.coordinates.Angle`\n An `Angle` object (may be multidimensional)\n show_unit : bool, optional\n True if the unit of the angle ('h' or 'd') is appended to the string\n kwargs : dict, optional\n Extra keyword arguments for :meth:`~astropy.coordinates.Angle.to_string`\n\n Returns\n -------\n s : str or array of str\n String(s) representing `angle`\n\n Raises\n ------\n ValueError\n If angle / kwargs unit is not supported, or separator is not ':'\n \"\"\"\n unit = kwargs.setdefault('unit', angle.unit)\n if unit not in (u.deg, u.hour, u.hourangle):\n raise ValueError(f'The angle unit should be degree, hour or hourangle, not {unit}')\n sep = kwargs.setdefault('sep', ':')\n decimal = kwargs.get('decimal', False)\n if not decimal and sep != ':':\n raise ValueError(f\"The sexagesimal separator should be ':', not '{sep}'\")\n precision = kwargs.get('precision')\n if precision is None:\n # Sufficient precision to discern 1 micron at 13000 km\n precision = 12 if decimal else 8\n # Hour angle needs a bit more precision\n if unit != u.deg:\n precision += 1\n kwargs['precision'] = precision\n number = strip_zeros(angle.to_string(**kwargs))\n if not show_unit:\n return number\n suffix = 'd' if unit == u.deg else 'h'\n s = np.char.add(number, suffix)\n return s if s.ndim else s.item()\n\n# --------------------------------------------------------------------------------------------------\n# --- Geodetic coordinate transformations\n# --------------------------------------------------------------------------------------------------\n\n\ndef lla_to_ecef(lat_rad, lon_rad, alt_m):\n \"\"\"Convert WGS84 spherical coordinates to ECEF cartesian coordinates.\n\n This converts a position on the Earth specified in geodetic latitude,\n longitude and altitude to earth-centered, earth-fixed (ECEF) cartesian\n coordinates. This code assumes the WGS84 earth model, described in\n [NIMA2004]_.\n\n Parameters\n ----------\n lat_rad : float or array\n Latitude (customary geodetic, not geocentric), in radians\n lon_rad : float or array\n Longitude, in radians\n alt_m : float or array\n Altitude, in metres above WGS84 ellipsoid\n\n Returns\n -------\n x_m, y_m, z_m : float or array\n X, Y, Z coordinates, in metres\n\n References\n ----------\n\n .. [NIMA2004] National Imagery and Mapping Agency, \"Department of Defense\n World Geodetic System 1984,\" NIMA TR8350.2, Page 4-4, last updated\n June, 2004.\n \"\"\"\n # WGS84 Defining Parameters\n a = 6378137.0 # semi-major axis of Earth in m\n f = 1.0 / 298.257223563 # flattening of Earth\n\n # WGS84 derived geometric constants\n e2 = 2 * f - f ** 2 # first eccentricity squared\n\n # intermediate calculation\n # (normal, or prime vertical radius of curvature)\n R = a / np.sqrt(1.0 - e2 * np.sin(lat_rad) ** 2)\n\n x_m = (R + alt_m) * np.cos(lat_rad) * np.cos(lon_rad)\n y_m = (R + alt_m) * np.cos(lat_rad) * np.sin(lon_rad)\n z_m = ((1.0 - e2) * R + alt_m) * np.sin(lat_rad)\n\n return x_m, y_m, z_m\n\n\ndef ecef_to_lla(x_m, y_m, z_m):\n \"\"\"Convert ECEF cartesian coordinates to WGS84 spherical coordinates.\n\n This converts an earth-centered, earth-fixed (ECEF) cartesian position to a\n position on the Earth specified in geodetic latitude, longitude and altitude.\n This code assumes the WGS84 earth model.\n\n Parameters\n ----------\n x_m, y_m, z_m : float or array\n X, Y, Z coordinates, in metres\n\n Returns\n -------\n lat_rad : float or array\n Latitude (customary geodetic, not geocentric), in radians\n lon_rad : float or array\n Longitude, in radians\n alt_m : float or array\n Altitude, in metres above WGS84 ellipsoid\n\n Notes\n -----\n Based on the most accurate algorithm according to Zhu [zhu]_, which is\n summarised by Kaplan [kaplan]_ and described in the Wikipedia entry [geo]_.\n\n .. [zhu] J. Zhu, \"Conversion of Earth-centered Earth-fixed coordinates to\n geodetic coordinates,\" Aerospace and Electronic Systems, IEEE Transactions\n on, vol. 30, pp. 957-961, 1994.\n .. [kaplan] Kaplan, \"Understanding GPS: principles and applications,\" 1 ed.,\n Norwood, MA 02062, USA: Artech House, Inc, 1996.\n .. [geo] Wikipedia entry, \"Geodetic system\", 2009.\n \"\"\"\n # WGS84 Defining Parameters\n a = 6378137.0 # semi-major axis of Earth in m\n f = 1.0 / 298.257223563 # flattening of Earth\n\n # WGS84 derived geometric constants\n b = a * (1.0 - f) # semi-minor axis in m\n e2 = 2 * f - f ** 2 # first eccentricity squared\n ep2 = f * (2.0 - f) / (1.0 - f) ** 2 # second eccentricity squared\n\n # Define squared terms for convenience\n a2, b2 = a ** 2, b ** 2\n x2, y2, z2 = x_m ** 2, y_m ** 2, z_m ** 2\n\n r = np.sqrt(x2 + y2)\n E2 = a2 - b2\n F = 54.0 * b2 * z2\n G = r ** 2 + (1 - e2) * z2 - e2 * E2\n C = (e2 ** 2 * F * r ** 2) / (G ** 3)\n S = (1.0 + C + np.sqrt(C ** 2 + 2 * C)) ** (1. / 3.)\n P = F / (3.0 * (S + 1.0 / S + 1.0) ** 2 * G ** 2)\n Q = np.sqrt(1.0 + 2.0 * e2 ** 2 * P)\n r0 = - P * e2 * r / (1.0 + Q) + \\\n np.sqrt(0.5 * a2 * (1.0 + 1.0 / Q) - P * (1 - e2) * z2 / (Q * (1.0 + Q)) - 0.5 * P * r ** 2)\n U = np.sqrt((r - e2 * r0) ** 2 + z2)\n V = np.sqrt((r - e2 * r0) ** 2 + (1.0 - e2) * z2)\n z0 = (b2 * z_m) / (a * V)\n alt_m = U * (1.0 - b2 / (a * V))\n lat_rad = np.arctan2(z_m + ep2 * z0, r)\n lon_rad = np.arctan2(y_m, x_m)\n\n return lat_rad, lon_rad, alt_m\n\n\ndef ecef_to_lla2(x_m, y_m, z_m):\n \"\"\"Convert ECEF cartesian coordinates to WGS84 spherical coordinates.\n\n This converts an earth-centered, earth-fixed (ECEF) cartesian position to a\n position on the Earth specified in geodetic latitude, longitude and altitude.\n This code assumes the WGS84 earth model.\n\n Parameters\n ----------\n x_m, y_m, z_m : float or array\n X, Y, Z coordinates, in metres\n\n Returns\n -------\n lat_rad : float or array\n Latitude (customary geodetic, not geocentric), in radians\n lon_rad : float or array\n Longitude, in radians\n alt_m : float or array\n Altitude, in metres above WGS84 ellipsoid\n\n Notes\n -----\n This is a copy of the algorithm in the CONRAD codebase (from conradmisclib).\n It's nearly identical to :func:`ecef_to_lla`, but returns lon/lat in\n different ranges.\n \"\"\"\n # WGS84 ellipsoid constants\n a = 6378137.0 # semi-major axis of Earth in m\n e = 8.1819190842622e-2 # eccentricity of Earth\n\n b = np.sqrt(a**2 * (1.0 - e**2))\n ep = np.sqrt((a**2 - b**2) / b**2)\n p = np.sqrt(x_m**2 + y_m**2)\n th = np.arctan2(a * z_m, b * p)\n lon_rad = np.arctan2(y_m, x_m)\n lat_rad = np.arctan2((z_m + ep**2 * b * np.sin(th)**3), (p - e**2 * a * np.cos(th)**3))\n N = a / np.sqrt(1.0 - e**2 * np.sin(lat_rad)**2)\n alt_m = p / np.cos(lat_rad) - N\n\n # Return lon_rad in range [0, 2*pi)\n lon_rad = np.mod(lon_rad, 2.0 * np.pi)\n\n # Correct for numerical instability in altitude near exact poles\n # (after this correction, error is about 2 millimeters, which is about\n # the same as the numerical precision of the overall function)\n if np.isscalar(alt_m):\n if (abs(x_m) < 1.0) and (abs(y_m) < 1.0):\n alt_m = abs(z_m) - b\n else:\n near_poles = (np.abs(x_m) < 1.0) & (np.abs(y_m) < 1.0)\n alt_m[near_poles] = np.abs(z_m[near_poles]) - b\n\n return lat_rad, lon_rad, alt_m\n\n\ndef enu_to_ecef(ref_lat_rad, ref_lon_rad, ref_alt_m, e_m, n_m, u_m):\n \"\"\"Convert ENU coordinates relative to reference location to ECEF coordinates.\n\n This converts local east-north-up (ENU) coordinates relative to a given\n reference position to earth-centered, earth-fixed (ECEF) cartesian\n coordinates. The reference position is specified by its geodetic latitude,\n longitude and altitude.\n\n Parameters\n ----------\n ref_lat_rad, ref_lon_rad : float or array\n Geodetic latitude and longitude of reference position, in radians\n ref_alt_m : float or array\n Geodetic altitude of reference position, in metres above WGS84 ellipsoid\n e_m, n_m, u_m : float or array\n East, North, Up coordinates, in metres\n\n Returns\n -------\n x_m, y_m, z_m : float or array\n X, Y, Z coordinates, in metres\n \"\"\"\n # ECEF coordinates of reference point\n ref_x_m, ref_y_m, ref_z_m = lla_to_ecef(ref_lat_rad, ref_lon_rad, ref_alt_m)\n sin_lat, cos_lat = np.sin(ref_lat_rad), np.cos(ref_lat_rad)\n sin_lon, cos_lon = np.sin(ref_lon_rad), np.cos(ref_lon_rad)\n\n x_m = ref_x_m - sin_lon*e_m - sin_lat*cos_lon*n_m + cos_lat*cos_lon*u_m\n y_m = ref_y_m + cos_lon*e_m - sin_lat*sin_lon*n_m + cos_lat*sin_lon*u_m\n z_m = ref_z_m + cos_lat*n_m + sin_lat*u_m\n\n return x_m, y_m, z_m\n\n\ndef ecef_to_enu(ref_lat_rad, ref_lon_rad, ref_alt_m, x_m, y_m, z_m):\n \"\"\"Convert ECEF coordinates to ENU coordinates relative to reference location.\n\n This converts earth-centered, earth-fixed (ECEF) cartesian coordinates to\n local east-north-up (ENU) coordinates relative to a given reference position.\n The reference position is specified by its geodetic latitude, longitude and\n altitude.\n\n Parameters\n ----------\n ref_lat_rad, ref_lon_rad : float or array\n Geodetic latitude and longitude of reference position, in radians\n ref_alt_m : float or array\n Geodetic altitude of reference position, in metres above WGS84 ellipsoid\n x_m, y_m, z_m : float or array\n X, Y, Z coordinates, in metres\n\n Returns\n -------\n e_m, n_m, u_m : float or array\n East, North, Up coordinates, in metres\n \"\"\"\n # ECEF coordinates of reference point\n ref_x_m, ref_y_m, ref_z_m = lla_to_ecef(ref_lat_rad, ref_lon_rad, ref_alt_m)\n delta_x_m, delta_y_m, delta_z_m = x_m - ref_x_m, y_m - ref_y_m, z_m - ref_z_m\n sin_lat, cos_lat = np.sin(ref_lat_rad), np.cos(ref_lat_rad)\n sin_lon, cos_lon = np.sin(ref_lon_rad), np.cos(ref_lon_rad)\n\n e_m = -sin_lon*delta_x_m + cos_lon*delta_y_m\n n_m = -sin_lat*cos_lon*delta_x_m - sin_lat*sin_lon*delta_y_m + cos_lat*delta_z_m\n u_m = cos_lat*cos_lon*delta_x_m + cos_lat*sin_lon*delta_y_m + sin_lat*delta_z_m\n\n return e_m, n_m, u_m\n\n# --------------------------------------------------------------------------------------------------\n# --- Spherical coordinate transformations\n# --------------------------------------------------------------------------------------------------\n\n\ndef azel_to_enu(az_rad, el_rad):\n \"\"\"Convert (az, el) spherical coordinates to unit vector in ENU coordinates.\n\n This converts horizontal spherical coordinates (azimuth and elevation angle)\n to a unit vector in the corresponding local east-north-up (ENU) coordinate\n system.\n\n Parameters\n ----------\n az_rad, el_rad : float or array\n Azimuth and elevation angle, in radians\n\n Returns\n -------\n e, n, u : float or array\n East, North, Up coordinates of unit vector\n \"\"\"\n sin_az, cos_az = np.sin(az_rad), np.cos(az_rad)\n sin_el, cos_el = np.sin(el_rad), np.cos(el_rad)\n return sin_az * cos_el, cos_az * cos_el, sin_el\n\n\ndef enu_to_azel(east, north, up):\n \"\"\"Convert vector in ENU coordinates to (az, el) spherical coordinates.\n\n This converts a vector in the local east-north-up (ENU) coordinate system to\n the corresponding horizontal spherical coordinates (azimuth and elevation\n angle). The ENU coordinates can be in any unit, as the vector length will be\n normalised in the conversion process.\n\n Parameters\n ----------\n east, north, up : float or array\n East, North, Up coordinates (any unit)\n\n Returns\n -------\n az_rad, el_rad : float or array\n Azimuth and elevation angle, in radians\n \"\"\"\n return np.arctan2(east, north), np.arctan2(up, np.hypot(east, north))\n\n\ndef hadec_to_enu(ha_rad, dec_rad, lat_rad):\n \"\"\"Convert (ha, dec) spherical coordinates to unit vector in ENU coordinates.\n\n This converts equatorial spherical coordinates (hour angle and declination)\n to a unit vector in the corresponding local east-north-up (ENU) coordinate\n system. The geodetic latitude of the observer is also required.\n\n Parameters\n ----------\n ha_rad, dec_rad, lat_rad : float or array\n Hour angle, declination and geodetic latitude, in radians\n\n Returns\n -------\n e, n, u : float or array\n East, North, Up coordinates of unit vector\n \"\"\"\n sin_ha, cos_ha = np.sin(ha_rad), np.cos(ha_rad)\n sin_dec, cos_dec = np.sin(dec_rad), np.cos(dec_rad)\n sin_lat, cos_lat = np.sin(lat_rad), np.cos(lat_rad)\n return (-cos_dec * sin_ha,\n cos_lat * sin_dec - sin_lat * cos_dec * cos_ha,\n sin_lat * sin_dec + cos_lat * cos_dec * cos_ha)\n\n\ndef enu_to_xyz(east, north, up, lat_rad):\n \"\"\"Convert ENU to XYZ coordinates.\n\n This converts a vector in the local east-north-up (ENU) coordinate system to\n the XYZ coordinate system used in radio astronomy (see e.g. [TMS]_). The X\n axis is the intersection of the equatorial plane and the meridian plane\n through the reference point of the ENU system (and therefore is similar to\n 'up'). The Y axis also lies in the equatorial plane to the east of X, and\n coincides with 'east'. The Z axis points toward the north pole, and therefore\n is similar to 'north'. The XYZ system is therefore a local version of the\n Earth-centred Earth-fixed (ECEF) system.\n\n Parameters\n ----------\n east, north, up : float or array\n East, North, Up coordinates of input vector\n lat_rad : float or array\n Geodetic latitude of ENU / XYZ reference point, in radians\n\n Returns\n -------\n x, y, z : float or array\n X, Y, Z coordinates of output vector\n\n References\n ----------\n .. [TMS] Thompson, Moran, Swenson, \"Interferometry and Synthesis in Radio\n Astronomy,\" 2nd ed., Wiley-VCH, 2004, pp. 86-89.\n \"\"\"\n sin_lat, cos_lat = np.sin(lat_rad), np.cos(lat_rad)\n return (-sin_lat * north + cos_lat * up,\n east,\n cos_lat * north + sin_lat * up)\n"
] |
[
[
"numpy.sqrt",
"numpy.abs",
"numpy.char.rstrip",
"numpy.cos",
"numpy.sin",
"numpy.arctan2",
"numpy.isscalar",
"numpy.mod",
"numpy.hypot",
"numpy.char.add"
]
] |
nathangrinsztajn/RL_for_dynamic_scheduling
|
[
"04e7d7dda192a168aa22d226a348fb2114f4fba4"
] |
[
"a2c/a2c.py"
] |
[
"import itertools\nimport time\nimport numpy as np\nimport os\nimport pandas as pd\nimport random\nfrom copy import deepcopy\nimport torch\nimport torch.nn.functional as F\nfrom torch import optim\nfrom torch.optim.lr_scheduler import CyclicLR, LambdaLR\n# from torch_geometric.data import Batch\n\nfrom joblib import Parallel, delayed\nimport matplotlib.pyplot as plt\nimport gym\nfrom gym.wrappers import Monitor\n\nfrom collections import deque\n\n\ndef make_seed(seed):\n np.random.seed(seed=seed)\n torch.manual_seed(seed=seed)\n\n\n# use_cuda = torch.cuda.is_available()\nuse_cuda = False\nif use_cuda:\n device = torch.device('cuda')\n print(\"using GPU\")\nelse:\n device = torch.device('cpu')\n print(\"using CPU\")\n\n\nclass A2C:\n def __init__(self, config, env, model, writer=None):\n self.config = config\n self.env = env\n make_seed(config['seed'])\n # self.env.seed(config['seed'])\n self.gamma = config['gamma']\n self.entropy_cost = config[\"entropy_coef\"]\n self.noise = config['noise'] if 'noise' in config.keys() else config['env_settings']['noise']\n self.random_id = str(np.random.randint(0, 9, 10)).replace(' ', '_')\n # Our network\n # self.network = model(**config[\"network_parameters\"]).to(device)\n # model = model(11)\n\n # if 'network_parameters' in config.keys():\n # model = model(config['network_parameters'][\"input_dim\"])\n # else:\n # model = model(config['input_dim'])\n\n # if torch.cuda.device_count() > 1:\n # print(\"Let's use\", torch.cuda.device_count(), \"GPUs!\")\n # # dim = 0 [30, xxx] -> [10, ...], [10, ...], [10, ...] on 3 GPUs\n # model = torch.nn.DataParallel(model)\n\n self.network = model.to(device)\n if config[\"model_path\"] is not None and config[\"model_path\"] != 'none':\n # self.network.load_state_dict(torch.load(config['model_path']))\n self.network = torch.load(config['model_path'])\n # Their optimizers\n if config['optimizer'] == \"sgd\":\n self.optimizer = optim.SGD(self.network.parameters(), config['lr'])\n elif config['optimizer'] == 'adam':\n self.optimizer = optim.Adam(self.network.parameters(), lr=config['lr'])\n else:\n self.optimizer = optim.RMSprop(self.network.parameters(), config['lr'], eps=config['eps'])\n self.writer = writer\n\n if config['scheduler'] == 'cyclic':\n ratio = config['sched_ratio']\n self.scheduler = CyclicLR(self.optimizer, base_lr=config['lr']/ratio, max_lr=config['lr']*ratio,\n step_size_up=config['step_up'])\n elif config['scheduler'] == 'lambda':\n lambda2 = lambda epoch: 0.99 ** epoch\n self.scheduler = LambdaLR(self.optimizer, lr_lambda=[lambda2])\n else:\n self.scheduler = None\n\n # Hint: use it during training_batch\n def _returns_advantages(self, rewards, dones, values, next_value):\n \"\"\"Returns the cumulative discounted rewards at each time step\n\n Parameters\n ----------\n rewards : array\n An array of shape (batch_size,) containing the rewards given by the env\n dones : array\n An array of shape (batch_size,) containing the done bool indicator given by the env\n values : array\n An array of shape (batch_size,) containing the values given by the value network\n next_value : float\n The value of the next state given by the value network\n\n Returns\n -------\n returns : array\n The cumulative discounted rewards\n advantages : array\n The advantages\n \"\"\"\n\n returns = np.append(np.zeros_like(rewards), [next_value], axis=0)\n\n for t in reversed(range(rewards.shape[0])):\n returns[t] = rewards[t] + self.gamma * returns[t + 1] * (1 - dones[t])\n\n returns = returns[:-1]\n advantages = returns - values\n return returns, advantages\n\n def training_batch(self):\n \"\"\"Perform a training by batch\n\n Parameters\n ----------\n steps : int\n Number of steps\n batch_size : int\n The size of a batch\n \"\"\"\n start = time.time()\n reward_log = deque(maxlen=10)\n time_log = deque(maxlen=10)\n\n batch_size = self.config['trajectory_length']\n\n actions = np.empty((batch_size,), dtype=np.int)\n dones = np.empty((batch_size,), dtype=np.bool)\n rewards, values = np.empty((2, batch_size), dtype=np.float)\n observations = []\n observation = self.env.reset()\n observation['graph'] = observation['graph'].to(device)\n rewards_test = []\n best_reward_mean = -1000\n\n n_step = 0\n log_ratio = 0\n best_time = 100000\n\n while n_step < self.config['num_env_steps']:\n # Lets collect one batch\n\n probs = torch.zeros(batch_size, dtype=torch.float, device=device)\n vals = torch.zeros(batch_size, dtype=torch.float, device=device)\n probs_entropy = torch.zeros(batch_size, dtype=torch.float, device=device)\n\n for i in range(batch_size):\n observations.append(observation['graph'])\n policy, value = self.network(observation)\n values[i] = value.detach().cpu().numpy()\n vals[i] = value\n probs_entropy[i] = - (policy * policy.log()).sum(-1)\n try:\n action_raw = torch.multinomial(policy, 1).detach().cpu().numpy()\n except:\n print(\"chelou\")\n probs[i] = policy[action_raw]\n ready_nodes = observation['ready'].squeeze(1).to(torch.bool)\n actions[i] = -1 if action_raw == policy.shape[-1] -1 else observation['node_num'][ready_nodes][action_raw]\n observation, rewards[i], dones[i], info = self.env.step(actions[i])\n observation['graph'] = observation['graph'].to(device)\n n_step += 1\n\n if dones[i]:\n observation = self.env.reset()\n observation['graph'] = observation['graph'].to(device)\n reward_log.append(rewards[i])\n time_log.append(info['episode']['time'])\n\n # If our episode didn't end on the last step we need to compute the value for the last state\n if dones[i] and not info['bad_transition']:\n next_value = 0\n else:\n next_value = self.network(observation)[1].detach().cpu().numpy()[0]\n\n # Update episode_count\n\n # Compute returns and advantages\n returns, advantages = self._returns_advantages(rewards, dones, values, next_value)\n\n # TO DO: use rewards for train rewards\n\n # Learning step !\n loss_value, loss_actor, loss_entropy = self.optimize_model(observations, actions, probs, probs_entropy, vals, returns, advantages, step=n_step)\n if self.writer is not None and log_ratio * self.config['log_interval'] < n_step:\n print('saving model if better than the previous one')\n log_ratio += 1\n self.writer.add_scalar('reward', np.mean(reward_log), n_step)\n self.writer.add_scalar('time', np.mean(time_log), n_step)\n self.writer.add_scalar('critic_loss', loss_value, n_step)\n self.writer.add_scalar('actor_loss', loss_actor, n_step)\n self.writer.add_scalar('entropy', loss_entropy, n_step)\n\n if self.noise > 0:\n current_time = np.mean([self.evaluate(), self.evaluate(), self.evaluate()])\n else:\n current_time = self.evaluate()\n self.writer.add_scalar('test time', current_time, n_step)\n print(\"comparing current time: {} with previous best: {}\".format(current_time, best_time))\n if current_time < best_time:\n print(\"saving model\")\n string_save = os.path.join(str(self.writer.get_logdir()), 'model{}.pth'.format(self.random_id))\n torch.save(self.network, string_save)\n best_time = current_time\n # current_tab = []\n # for _ in range(10):\n # current_tab.append(self.evaluate())\n # current_mean = np.mean(current_tab)\n\n if len(reward_log) > 0:\n end = time.time()\n print('step ', n_step, '\\n reward: ', np.mean(reward_log))\n print('FPS: ', int(n_step / (end - start)))\n\n if self.scheduler is not None:\n print(self.scheduler.get_lr())\n self.scheduler.step(int(n_step/batch_size))\n\n self.network = torch.load(string_save)\n results_last_model = []\n if self.noise > 0:\n for _ in range(5):\n results_last_model.append(self.evaluate())\n else:\n results_last_model.append(self.evaluate())\n torch.save(self.network, os.path.join(str(self.writer.get_logdir()), 'model_{}.pth'.format(str(np.mean(results_last_model)))))\n os.remove(string_save)\n return best_time, np.mean(results_last_model)\n\n # # Test it every \"evaluate_every\" steps\n # if n_step > self.config['evaluate_every'] * (log_ratio + 1):\n # rewards_test.append(np.array([self.evaluate() for _ in range(50)]))\n # print(\n # f\"\"\"Steps {n_step}/{self.config['num_env_steps']}: Mean rewards: {round(rewards_test[-1].mean(), 2)}, Std: {round(rewards_test[-1].std(), 2)}\"\"\")\n # if self.writer:\n # self.writer.add_scalar('mean_reward', round(rewards_test[-1].mean(), 2), n_step)\n #\n # if rewards_test[-1].mean() >= best_reward_mean:\n # best_reward_mean = rewards_test[-1].mean()\n # str_file = str(self.writer.get_logdir()).split('/')[1]\n # torch.save(self.network.state_dict(), os.path.join(str(self.writer.get_logdir()),\n # 'model.pth'))\n #\n # observation = self.env.reset()\n #\n # # Plotting\n # r = pd.DataFrame(\n # (itertools.chain(*(itertools.product([i], rewards_test[i]) for i in range(len(rewards_test))))),\n # columns=['Steps', 'Reward'])\n # sns.lineplot(x=\"steps\", y=\"Reward\", data=r, ci='sd');\n #\n # print(f'The trainnig was done over a total of {n_step} steps')\n\n def optimize_model(self, observations, actions, probs, entropies, vals, returns, advantages, step=None):\n # actions = F.one_hot(torch.tensor(actions, device=device), self.env.action_space.n)\n returns = torch.tensor(returns[:, None], dtype=torch.float, device=device)\n advantages = torch.tensor(advantages, dtype=torch.float, device=device)\n # observations = torch.tensor(observations, dtype=torch.float, device=device)\n # observations = Batch().from_data_list(observations)\n\n\n # reset\n # self.network_optimizer.zero_grad()\n # policies, values = self.network(observations)\n\n # MSE for the values\n loss_value = 1 * F.mse_loss(vals.unsqueeze(-1), returns)\n if self.writer:\n self.writer.add_scalar('critic_loss', loss_value.data.item(), step)\n\n # Actor loss\n # loss_policy = ((probs.log()).sum(-1) * advantages).mean()\n loss_policy = ((probs.log()) * advantages).mean()\n loss_entropy = entropies.mean()\n loss_actor = - loss_policy - self.entropy_cost * loss_entropy\n if self.writer:\n self.writer.add_scalar('actor_loss', loss_actor.data.item(), step)\n\n total_loss = self.config[\"loss_ratio\"] * loss_value + loss_actor\n total_loss.backward()\n torch.nn.utils.clip_grad_norm_(self.network.parameters(), 10)\n self.optimizer.step()\n return loss_value.data.item(), loss_actor.data.item(), loss_entropy.data.item()\n\n def evaluate(self, render=False):\n env = self.monitor_env if render else deepcopy(self.env)\n\n observation = env.reset()\n done = False\n\n while not done:\n observation['graph'] = observation['graph'].to(device)\n policy, value = self.network(observation)\n # action_raw = torch.multinomial(policy, 1).detach().cpu().numpy()\n action_raw = policy.argmax().detach().cpu().numpy()\n ready_nodes = observation['ready'].squeeze(1).to(torch.bool)\n action = -1 if action_raw == policy.shape[-1] - 1 else \\\n observation['node_num'][ready_nodes][action_raw].detach().numpy()[0]\n try :\n observation, reward, done, info = env.step(action)\n except KeyError:\n print(chelou)\n return env.time\n\n"
] |
[
[
"torch.optim.lr_scheduler.CyclicLR",
"torch.optim.lr_scheduler.LambdaLR",
"numpy.random.seed",
"torch.load",
"torch.zeros",
"torch.manual_seed",
"torch.multinomial",
"torch.tensor",
"numpy.zeros_like",
"numpy.mean",
"torch.save",
"torch.device",
"numpy.empty",
"numpy.random.randint"
]
] |
adrianosantospb/estrutura_base_pytorch
|
[
"36a6a45d39c312513645337802dea95b78cdb9ab"
] |
[
"estrutura2/model.py"
] |
[
"# Estrutura básica para projetos de Machine Learning e Deep Learning\n# Por Adriano Santos.\n\nfrom torch import nn, relu\n\nclass Model(nn.Module):\n def __init__(self, input_size, hidden_1, hidden_2, output_size):\n super(Model, self).__init__()\n self.entry = nn.Linear(input_size, hidden_1)\n self.hidden = nn.Linear(hidden_1, hidden_2)\n self.out = nn.Linear(hidden_2, output_size)\n\n def forward(self, x):\n out = relu(self.entry(x))\n out = relu(self.hidden(out))\n out = self.out(out)\n return out"
] |
[
[
"torch.nn.Linear"
]
] |
jzitovsky/batch_rl
|
[
"ded5703784f896c0f3c31cfcf84514abe7f59606"
] |
[
"batch_rl/tests/atari_init_test.py"
] |
[
"# coding=utf-8\n# Copyright 2021 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\"\"\"A simple test for validating that the Atari env initializes.\"\"\"\n\nimport datetime\nimport os\nimport shutil\n\n\n\nfrom absl import flags\nfrom batch_rl.baselines import train\nimport tensorflow.compat.v1 as tf\n\nFLAGS = flags.FLAGS\n\n\nclass AtariInitTest(tf.test.TestCase):\n\n def setUp(self):\n super(AtariInitTest, self).setUp()\n FLAGS.base_dir = os.path.join(\n '/tmp/batch_rl_tests',\n datetime.datetime.utcnow().strftime('run_%Y_%m_%d_%H_%M_%S'))\n FLAGS.gin_files = ['batch_rl/baselines/configs/dqn.gin']\n # `num_iterations` set to zero to prevent runner execution.\n FLAGS.gin_bindings = [\n 'Runner.num_iterations=0',\n 'WrappedReplayBuffer.replay_capacity = 100' # To prevent OOM.\n ]\n FLAGS.alsologtostderr = True\n\n def test_atari_init(self):\n \"\"\"Tests that a DQN agent is initialized.\"\"\"\n train.main([])\n shutil.rmtree(FLAGS.base_dir)\n\n\nif __name__ == '__main__':\n tf.test.main()\n"
] |
[
[
"tensorflow.compat.v1.test.main"
]
] |
MoMagDii/VAUV-simulator
|
[
"56f55f9349e38e0a327a40feb5a437fcad511b00",
"56f55f9349e38e0a327a40feb5a437fcad511b00"
] |
[
"uuv_control/uuv_trajectory_control/scripts/rov_nmb_sm_controller.py",
"uuv_control/uuv_trajectory_control/scripts/rov_pid_controller.py"
] |
[
"#!/usr/bin/env python3\n# Copyright (c) 2020 The Plankton Authors.\n# All rights reserved.\n#\n# This source code is derived from UUV Simulator\n# (https://github.com/uuvsimulator/uuv_simulator)\n# Copyright (c) 2016-2019 The UUV Simulator Authors\n# licensed under the Apache license, Version 2.0\n# cf. 3rd-party-licenses.txt file in the root directory of this source tree.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport rclpy\nimport numpy as np\nimport traceback\n\nfrom utils.transform import get_world_ned_to_enu\nfrom uuv_control_interfaces import DPControllerBase\nfrom uuv_control_msgs.srv import *\nfrom plankton_utils.time import time_in_float_sec\nfrom plankton_utils.time import is_sim_time\n\n\nclass ROV_NMB_SMController(DPControllerBase):\n \"\"\"\n Model-free sliding mode controller based on the work published in [1] and\n [2], or model-free high order sliding mode controller.\n\n [1] Garcia-Valdovinos, Luis Govinda, et al. \"Modelling, design and robust\n control of a remotely operated underwater vehicle.\" International\n Journal of Advanced Robotic Systems 11.1 (2014): 1.\n [2] Salgado-Jimenez, Tomas, Luis G. Garcia-Valdovinos, and Guillermo\n Delgado-Ramirez. \"Control of ROVs using a Model-free 2nd-Order Sliding\n Mode Approach.\" Sliding Mode Control (2011): 347-368.\n \"\"\"\n\n _LABEL = 'Model-free Sliding Mode Controller'\n\n def __init__(self, node_name, **kwargs):\n DPControllerBase.__init__(self, node_name, is_model_based=False, **kwargs)\n \n self._logger.info('Initializing: ' + self._LABEL)\n self._first_pass = True\n self._t_init = 0.0\n self._s_linear_b_init = np.array([0, 0, 0])\n self._s_angular_b_init = np.array([0, 0, 0])\n\n # 'K' gains (help in the initial transient)\n self._K = np.zeros(6)\n # Derivative gains\n self._Kd = np.zeros(6)\n # Robustness gains\n self._Ki = np.zeros(6)\n # Overall proportional gains\n self._slope = np.zeros(6)\n\n if self.has_parameter('K'):\n coefs = self.get_parameter('K').value\n if len(coefs) == 6:\n self._K = np.array(coefs)\n else:\n raise RuntimeError('K coefficients: 6 coefficients '\n 'needed')\n\n self._logger.info('K=' + str(self._K))\n\n if self.has_parameter('Kd'):\n coefs = self.get_parameter('Kd').value\n if len(coefs) == 6:\n self._Kd = np.array(coefs)\n else:\n raise RuntimeError('Kd coefficients: 6 coefficients '\n 'needed')\n\n self._logger.info('Kd=' + str(self._Kd))\n\n if self.has_parameter('Ki'):\n coefs = self.get_parameter('Ki').value\n if len(coefs) == 6:\n self._Ki = np.array(coefs)\n else:\n raise RuntimeError('Ki coeffcients: 6 coefficients '\n 'needed')\n self._logger.info('Ki=' + str(self._Ki))\n\n if self.has_parameter('slope'):\n coefs = self.get_parameter('slope').value\n if len(coefs) == 6:\n self._slope = np.array(coefs)\n else:\n raise RuntimeError('Slope coefficients: 6 coefficients '\n 'needed')\n\n self._logger.info('slope=' + str(self._slope))\n\n self._sat_epsilon = 0.8\n if self.has_parameter('sat_epsilon'):\n self._sat_epsilon = max(0.0, self.get_parameter('sat_epsilon').value)\n\n self._logger.info('Saturation limits=' + str(self._sat_epsilon))\n\n self._summ_sign_sn_linear_b = np.array([0, 0, 0])\n self._summ_sign_sn_angular_b = np.array([0, 0, 0])\n\n self._prev_sign_sn_linear_b = np.array([0, 0, 0])\n self._prev_sign_sn_angular_b = np.array([0, 0, 0])\n\n self._tau = np.zeros(6)\n \n srv_name = 'set_sm_controller_params'\n self._services[srv_name] = self.create_service(\n SetSMControllerParams,\n srv_name,\n self.set_sm_controller_params_callback,\n callback_group=self._callback_group)\n \n srv_name = 'get_sm_controller_params'\n self._services[srv_name] = self.create_service(\n GetSMControllerParams,\n srv_name,\n self.get_sm_controller_params_callback,\n callback_group=self._callback_group)\n\n self._is_init = True\n self._logger.info(self._LABEL + ' ready')\n\n # =========================================================================\n def _reset_controller(self):\n super(ROV_NMB_SMController, self)._reset_controller()\n self._first_pass = True\n self._t_init = 0.0\n self._s_linear_b_init = np.array([0, 0, 0])\n self._s_angular_b_init = np.array([0, 0, 0])\n self._prev_t = time_in_float_sec(self.get_clock().now())\n self._summ_sign_sn_linear_b = np.array([0, 0, 0])\n self._summ_sign_sn_angular_b = np.array([0, 0, 0])\n self._prev_sign_sn_linear_b = np.array([0, 0, 0])\n self._prev_sign_sn_angular_b = np.array([0, 0, 0])\n self._tau = np.zeros(6)\n\n # =========================================================================\n def set_sm_controller_params_callback(self, request, response):\n response.success = True\n return response\n #return SetSMControllerParamsResponse(True)\n\n # =========================================================================\n def get_sm_controller_params_callback(self, request, response):\n response.k = self._K.tolist()\n response.kd = self._Kd.tolist()\n response.ki = self._Ki.tolist()\n response.slope = self._slope.tolist()\n\n return response\n\n # =========================================================================\n def update_controller(self):\n if not self._is_init:\n return False\n t = time_in_float_sec(self.get_clock().now())\n\n dt = t - self._prev_t\n if self._prev_t < 0.0:\n dt = 0.0\n\n # Get trajectory errors (reference - actual)\n e_p_linear_b = self._errors['pos']\n e_v_linear_b = self._errors['vel'][0:3]\n\n e_p_angular_b = self.error_orientation_rpy # check this\n e_v_angular_b = self._errors['vel'][3:6]\n\n # Compute sliding surface s wrt body frame\n s_linear_b = -e_v_linear_b - np.multiply(self._slope[0:3],\n e_p_linear_b)\n s_angular_b = -e_v_angular_b - np.multiply(self._slope[3:6],\n e_p_angular_b)\n\n # Compute exponential decay for transient improvement\n if self._first_pass == True:\n self._t_init, self._s_linear_b_init, self._s_angular_b_init = t, s_linear_b, s_angular_b\n self._first_pass = False\n\n sd_linear_b = np.multiply(self._s_linear_b_init,\n np.exp(-self._K[0:3] * (t - self._t_init)))\n sd_angular_b = np.multiply(self._s_angular_b_init,\n np.exp(-self._K[3:6] * (t - self._t_init)))\n\n # Compute sliding surface sn wrt body frame\n sn_linear_b = s_linear_b - sd_linear_b\n sn_angular_b = s_angular_b - sd_angular_b\n\n # Compute summation sign(sn) wrt body frame\n if self._prev_t > 0.0 and dt > 0.0:\n self._summ_sign_sn_linear_b = self._summ_sign_sn_linear_b + 0.5 * (\n self.sat(sn_linear_b, self._sat_epsilon) + self._prev_sign_sn_linear_b) * dt\n self._summ_sign_sn_angular_b = self._summ_sign_sn_angular_b + 0.5 * (\n self.sat(sn_angular_b, self._sat_epsilon) + self._prev_sign_sn_angular_b) * dt\n\n # Compute extended error wrt body frame\n sr_linear_b = sn_linear_b + np.multiply(self._Ki[0:3],\n self._summ_sign_sn_linear_b)\n sr_angular_b = sn_angular_b + np.multiply(self._Ki[3:6],\n self._summ_sign_sn_angular_b)\n\n # Compute required forces and torques wrt body frame\n force_b = -np.multiply(self._Kd[0:3], sr_linear_b)\n torque_b = -np.multiply(self._Kd[3:6], sr_angular_b)\n\n self._tau = np.hstack((force_b, torque_b))\n\n self.publish_control_wrench(self._tau)\n\n self._prev_sign_sn_linear_b = self.sat(sn_linear_b, self._sat_epsilon)\n self._prev_sign_sn_angular_b = self.sat(sn_angular_b, self._sat_epsilon)\n self._prev_t = t\n\n # =========================================================================\n @staticmethod\n def sat(value, epsilon=0.5):\n assert epsilon >= 0, 'Saturation constant must be greate or equal to zero'\n if epsilon == 0:\n return np.sign(value)\n\n vec = value / epsilon\n output = np.zeros(vec.size)\n for i in range(output.size):\n if vec[i] > epsilon:\n output[i] = 1\n elif vec[i] < -epsilon:\n output[i] = -1\n else:\n output[i] = vec[i]\n return output\n\n\n# =============================================================================\ndef main():\n print('Starting Non-model-based Sliding Mode Controller')\n rclpy.init()\n\n try:\n sim_time_param = is_sim_time()\n\n tf_world_ned_to_enu = get_world_ned_to_enu(sim_time_param)\n \n node = ROV_NMB_SMController(\n 'rov_nmb_sm_controller',\n world_ned_to_enu=tf_world_ned_to_enu,\n parameter_overrides=[sim_time_param])\n executor = rclpy.executors.MultiThreadedExecutor()\n executor.add_node(node)\n executor.spin()\n # rclpy.spin(node)\n except KeyboardInterrupt:\n pass\n except Exception as e:\n print('Caught exception: ' + repr(e))\n traceback.print_exc()\n finally:\n if rclpy.ok():\n rclpy.shutdown()\n \n print('Exiting')\n\n\n# =============================================================================\nif __name__ == '__main__':\n main()\n",
"#!/usr/bin/env python3\n# Copyright (c) 2020 The Plankton Authors.\n# All rights reserved.\n#\n# This source code is derived from UUV Simulator\n# (https://github.com/uuvsimulator/uuv_simulator)\n# Copyright (c) 2016-2019 The UUV Simulator Authors\n# licensed under the Apache license, Version 2.0\n# cf. 3rd-party-licenses.txt file in the root directory of this source tree.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport rclpy\nimport numpy as np\nimport traceback\n\nfrom utils.transform import get_world_ned_to_enu\nfrom uuv_control_interfaces import DPPIDControllerBase\nfrom plankton_utils.time import is_sim_time\n\n\nclass ROV_PIDController(DPPIDControllerBase):\n \"\"\"PID controller for the dynamic positioning of ROVs.\"\"\"\n\n _LABEL = 'PID'\n def __init__(self, node_name, **kwargs):\n self._tau = np.zeros(6)\n DPPIDControllerBase.__init__(self, node_name, False, **kwargs)\n self._is_init = True\n\n # =========================================================================\n def update_controller(self):\n if not self._is_init:\n return False\n # Update PID control action\n self._tau = self.update_pid()\n self.publish_control_wrench(self._tau)\n return True\n\n\n# =============================================================================\ndef main():\n print('Starting PID')\n rclpy.init()\n\n try:\n sim_time_param = is_sim_time()\n\n tf_world_ned_to_enu = get_world_ned_to_enu(sim_time_param)\n\n node = ROV_PIDController(\n 'rov_pid_controller',\n world_ned_to_enu=tf_world_ned_to_enu,\n parameter_overrides=[sim_time_param])\n \n rclpy.spin(node)\n except Exception as e:\n print('Caught exception: ' + repr(e))\n traceback.print_exc()\n finally:\n if rclpy.ok():\n rclpy.shutdown()\n print('Exiting')\n\n\n# =============================================================================\nif __name__ == '__main__':\n main()\n"
] |
[
[
"numpy.hstack",
"numpy.multiply",
"numpy.sign",
"numpy.array",
"numpy.exp",
"numpy.zeros"
],
[
"numpy.zeros"
]
] |
TRex22/picam
|
[
"591ffe3aaccb648e470f2335506f402f94fb34f4"
] |
[
"src/overlay_handler.py"
] |
[
"import numpy as np\r\nfrom PIL import Image\r\n\r\nimport math\r\n\r\nfrom picamerax import mmal\r\n\r\n# Modules\r\nimport mmal_handler\r\n\r\ndef compute_shutter_speed_from_us(us):\r\n one_second = 1000000\r\n\r\n if us == 0:\r\n return 'auto'\r\n\r\n converted_seconds = math.ceil(one_second/us)\r\n\r\n if us > one_second:\r\n return f'{converted_seconds} secs. ({us} us.)'\r\n else:\r\n return f'1/{converted_seconds} ({us} us.)'\r\n\r\ndef display_text(camera, text, config):\r\n # camera.annotate_text = f'{camera.annotate_text} - {camera.exposure_mode}'\r\n if config[\"video\"]:\r\n mode = \"Video Mode\"\r\n else:\r\n mode = \"Photo Mode\"\r\n\r\n menu_item = config[\"menu_item\"]\r\n\r\n selected_item = f'Selected Menu Item: {config[\"menu_item\"]}, delay: {config[\"delay_time\"]}'\r\n camera_settings = f\"exposure mode: {camera.exposure_mode}, iso: {camera.iso}, awb mode: {config['awb_mode']}\"\r\n\r\n shutter_text = ''\r\n\r\n parameter = mmal.MMAL_PARAMETER_SHUTTER_SPEED\r\n mmal_shutter_speed = camera._get_shutter_speed() # camera.shutter_speed\r\n\r\n if config['take_long_shutter_speed'] == True:\r\n shutter_speed = compute_shutter_speed_from_us(config[\"long_shutter_speed\"])\r\n shutter_text = f'Shutter Speed: {shutter_speed}, long_shutter: {config[\"take_long_shutter_speed\"]}'\r\n else:\r\n shutter_speed = compute_shutter_speed_from_us(config[\"shutter_speed\"])\r\n shutter_text = f'Shutter Speed: {shutter_speed}, set: {mmal_shutter_speed}, long_shutter: {config[\"take_long_shutter_speed\"]}'\r\n\r\n framerate = camera.framerate\r\n\r\n boolean_text = f'hdr: {config[\"hdr\"]}; hdr2: {config[\"hdr2\"]}, raw: {config[\"raw_convert\"]}, dpc: {config[\"dpc\"]}'\r\n output_text = f'{mode} - fps: {framerate} {config[\"set_zoom\"]}\\n{camera_settings}\\n{boolean_text}\\n{selected_item}\\n{shutter_text}\\n{text}'\r\n\r\n camera.annotate_text_size = config[\"annotate_text_size\"]\r\n camera.annotate_text = output_text\r\n\r\n# https://picamera.readthedocs.io/en/release-1.10/recipes1.html#overlaying-images-on-the-preview\r\ndef add_overlay(camera, overlay, config):\r\n if overlay != None:\r\n return overlay\r\n\r\n overlay_w = config[\"overlay_w\"] # 320\r\n overlay_h = config[\"overlay_h\"] # 280\r\n\r\n img = generate_overlay_image(overlay_h, overlay_w, config)\r\n image_bytes = img.tobytes()\r\n\r\n # Broken docs ...\r\n # overlay = camera.add_overlay(a.tobytes(), layer=3, alpha=64)\r\n\r\n # Image.new(\"RGB\", (320, 240))\r\n # overlay = camera.add_overlay(Image.fromarray(a, 'RGB'), size=(320,240), layer=3, alpha=64)\r\n overlay = camera.add_overlay(image_bytes, size=img.size, layer=3, alpha=64, format=\"rgba\")\r\n display_text(camera, '', config)\r\n\r\n camera.framerate = config[\"screen_fps\"]\r\n\r\n return overlay\r\n\r\ndef remove_overlay(camera, overlay, config):\r\n if camera != None and overlay != None:\r\n camera.remove_overlay(overlay)\r\n camera.annotate_text = None\r\n\r\n return None\r\n\r\ndef generate_overlay_image(overlay_h, overlay_w, config):\r\n # Create an array representing a wxh image of\r\n # a cross through the center of the display. The shape of\r\n # the array must be of the form (height, width, color)\r\n a = np.zeros((overlay_h, overlay_w, 4), dtype=np.uint8)\r\n half_height = int(overlay_h/2)\r\n half_width = int(overlay_w/2)\r\n\r\n a[half_height, :, :] = 0xff\r\n a[:, half_width, :] = 0xff\r\n\r\n # if config['fom'] == True:\r\n # # Adding on the left is done by the loop starting at the padded space\r\n # inner_box_width = overlay_w - config['fom_overlay_x_padding']\r\n # inner_box_height = overlay_h - config['fom_overlay_y_padding']\r\n\r\n # for i in range(inner_box_width - 1):\r\n # for j in range(inner_box_height - 1):\r\n # a[i,j] = [0, 0, 0, 0]\r\n\r\n return Image.fromarray(a)\r\n"
] |
[
[
"numpy.zeros"
]
] |
SethuEapen/Real_life_Sharingan
|
[
"fb7d7e2b29137a44ef396395a8e77177d0ebffc7"
] |
[
"sharingen_run.py"
] |
[
"import cv2\nimport tensorflow as tf\n\nfont = cv2.FONT_HERSHEY_SIMPLEX \norg = (50, 50)\nfontScale = 1\ncolor = (255, 0, 0)\nthickness = 2\nCATEGORIES = [\"boar\", \"ox\"]\nIMG_SIZE = 50\n\n\n\ndef prepare(image):\n\t#img_array = cv2.imread(image, cv2.IMREAD_GRAYSCALE)\n\tnew_array = cv2.resize(image, (IMG_SIZE, IMG_SIZE))\n\treturn new_array.reshape(-1, IMG_SIZE, IMG_SIZE, 1)\n\nmodel = tf.keras.models.load_model(\"64x3-CNN.model\")\n\ncap = cv2.VideoCapture('http://192.168.1.155:8080/video')\n\nwhile(True):\n ret, frame = cap.read()\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n print()\n viewer = cv2.resize(gray, (IMG_SIZE, IMG_SIZE))\n prediction = model.predict([prepare(viewer)])\n frame = cv2.resize(frame, (1920, 1080))\n frame = cv2.putText(frame, CATEGORIES[int(prediction[0][0])], org, font, \n fontScale, color, thickness, cv2.LINE_AA) \n cv2.imshow('frame',frame)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\ncap.release()\ncv2.destroyAllWindows()\n"
] |
[
[
"tensorflow.keras.models.load_model"
]
] |
mgeier/ipyvolume
|
[
"16ab04eaf7e27801aec1a43cbdcdb6a6063a9145"
] |
[
"ipyvolume/pylab.py"
] |
[
"from __future__ import absolute_import\nfrom __future__ import division\n_last_figure = None\nimport ipywidgets\nfrom IPython.display import display\nimport IPython\nimport ipyvolume as ipv\nimport ipyvolume.embed\nimport os\nimport numpy as np\nfrom . import utils\nimport time\nfrom . import examples\nimport warnings\nimport PIL.Image\nimport traitlets\nimport uuid\n\ntry:\n from io import BytesIO as StringIO\nexcept:\n from cStringIO import StringIO\nimport base64\n\n\ndef _docsubst(f):\n \"\"\"Perform docstring substitutions\"\"\"\n f.__doc__ = f.__doc__.format(**_doc_snippets)\n return f\n\n_seq_sn = \"If an (S, N) array, the first dimension will be used for frames in an animation.\"\n_seq_snm = \"If an (S, N, M) array, the first dimension will be used for frames in an animation.\"\n\n_doc_snippets = {}\n_doc_snippets[\n \"color\"] = \"color for each point/vertex/symbol, can be string format, examples for red:'red', '#f00', '#ff0000' or 'rgb(1,0,0), or rgb array of shape (N, 3 or 4) or (S, N, 3 or 4)\"\n_doc_snippets[\n \"color2d\"] = \"color for each point/vertex string format, examples for red:'red', '#f00', '#ff0000' or 'rgb(1,0,0), or rgb array of shape (2, N, 3 or 4) or (S, 2, N, 3 or 4)\"\n_doc_snippets[\n \"size\"] = \"float representing the size of the glyph in percentage of the viewport, where 100 is the full size of the viewport\"\n_doc_snippets[\"marker\"] = \"name of the marker, options are: 'arrow', 'box', 'diamond', 'sphere', 'point_2d', 'square_2d', 'triangle_2d', 'circle_2d'\"\n_doc_snippets[\"x\"] = \"numpy array of shape (N,) or (S, N) with x positions. {}\".format(_seq_sn)\n_doc_snippets[\"y\"] = \"idem for y\"\n_doc_snippets[\"z\"] = \"idem for z\"\n_doc_snippets[\"u_dir\"] = \"numpy array of shape (N,) or (S, N) indicating the x component of a vector. {}\".format(_seq_sn)\n_doc_snippets[\"v_dir\"] = \"idem for y\"\n_doc_snippets[\"w_dir\"] = \"idem for z\"\n_doc_snippets[\"u\"] = \"numpy array of shape (N,) or (S, N) indicating the u (x) coordinate for the texture. {}\".format(_seq_sn)\n_doc_snippets[\"v\"] = \"numpy array of shape (N,) or (S, N) indicating the v (y) coordinate for the texture. {}\".format(_seq_sn)\n_doc_snippets[\"x2d\"] = \"numpy array of shape (N,M) or (S, N, M) with x positions. {}\".format(_seq_snm)\n_doc_snippets[\"y2d\"] = \"idem for y\"\n_doc_snippets[\"z2d\"] = \"idem for z\"\n_doc_snippets[\"texture\"] = \"PIL.Image object or ipywebrtc.MediaStream (can be a seqence)\"\n\nclass current:\n figure = None\n container = None\n figures = {}\n containers = {}\n\n\ndef clear():\n \"\"\"Remove current figure (and container)\"\"\"\n current.container = None\n current.figure = None\n\ndef controls_light(return_widget=False):\n fig = gcf()\n ambient_coefficient = ipywidgets.FloatSlider(min=0, max=1, step=0.001, value=fig.ambient_coefficient,\n description=\"ambient\")\n diffuse_coefficient = ipywidgets.FloatSlider(min=0, max=1, step=0.001, value=fig.diffuse_coefficient,\n description=\"diffuse\")\n specular_coefficient = ipywidgets.FloatSlider(min=0, max=1, step=0.001, value=fig.specular_coefficient,\n description=\"specular\")\n specular_exponent = ipywidgets.FloatSlider(min=0, max=10, step=0.001, value=fig.specular_exponent,\n description=\"specular exp\")\n ipywidgets.jslink((fig, 'ambient_coefficient'), (ambient_coefficient, 'value'))\n ipywidgets.jslink((fig, 'diffuse_coefficient'), (diffuse_coefficient, 'value'))\n ipywidgets.jslink((fig, 'specular_coefficient'), (specular_coefficient, 'value'))\n ipywidgets.jslink((fig, 'specular_exponent'), (specular_exponent, 'value'))\n widgets_bottom = [ipywidgets.HBox([ambient_coefficient, diffuse_coefficient]),\n ipywidgets.HBox([specular_coefficient, specular_exponent])]\n current.container.children += tuple(widgets_bottom, )\n if return_widget: return widgets_bottom\n\ndef figure(key=None, width=400, height=500, lighting=True, controls=True, controls_vr=False, controls_light=False, debug=False, **kwargs):\n \"\"\"Create a new figure (if no key is given) or return the figure associated with key\n\n :param key: Python object that identifies this figure\n :param int width: pixel width of WebGL canvas\n :param int height: .. height ..\n :param bool lighting: use lighting or not\n :param bool controls: show controls or not\n :param bool controls_vr: show controls for VR or not\n :param bool debug: show debug buttons or not\n :return: :any:`Figure`\n \"\"\"\n if key is not None and key in current.figures:\n current.figure = current.figures[key]\n current.container = current.containers[key]\n elif isinstance(key, ipv.Figure) and key in current.figures.values():\n key_index = list(current.figures.values()).index(key)\n key = list(current.figures.keys())[key_index]\n current.figure = current.figures[key]\n current.container = current.containers[key]\n else:\n current.figure = ipv.Figure(width=width, height=height, **kwargs)\n current.container = ipywidgets.VBox()\n current.container.children = [current.figure]\n if key is None:\n key = uuid.uuid4().hex\n current.figures[key] = current.figure\n current.containers[key] = current.container\n if controls:\n #stereo = ipywidgets.ToggleButton(value=current.figure.stereo, description='stereo', icon='eye')\n #l1 = ipywidgets.jslink((current.figure, 'stereo'), (stereo, 'value'))\n #current.container.children += (ipywidgets.HBox([stereo, ]),)\n pass # stereo and fullscreen are now include in the js code (per view)\n if controls_vr:\n eye_separation = ipywidgets.FloatSlider(value=current.figure.eye_separation, min=-10, max=10, icon='eye')\n ipywidgets.jslink((eye_separation, 'value'), (current.figure, 'eye_separation'))\n current.container.children += (eye_separation,)\n if controls_light:\n globals()['controls_light']()\n if debug:\n show = ipywidgets.ToggleButtons(options=[\"Volume\", \"Back\", \"Front\", \"Coordinate\"])\n current.container.children += (show,)\n #ipywidgets.jslink((current.figure, 'show'), (show, 'value'))\n traitlets.link((current.figure, 'show'), (show, 'value'))\n return current.figure\n\n\ndef gcf():\n \"\"\"Get current figure, or create a new one\n\n :return: :any:`Figure`\n \"\"\"\n if current.figure is None:\n return figure()\n else:\n return current.figure\n\n\ndef _grow_limit(limits, values):\n if isinstance(values, (tuple, list)) and len(values) == 2:\n newvmin, newvmax = values\n else:\n try:\n values[0] # test if scalar\n except TypeError:\n newvmin = values\n newvmax = values\n else:\n finites = np.isfinite(values)\n newvmin = np.min(values[finites])\n newvmax = np.max(values[finites])\n if limits is None:\n return newvmin, newvmax\n else:\n vmin, vmax = limits\n return min(newvmin, vmin), max(newvmax, vmax)\n\n\ndef _grow_limits(x, y, z):\n fig = gcf()\n xlim(*_grow_limit(fig.xlim, x))\n ylim(*_grow_limit(fig.ylim, y))\n zlim(*_grow_limit(fig.zlim, z))\n\n\ndef xlim(xmin, xmax):\n \"\"\"Set limits of x axis\"\"\"\n fig = gcf()\n fig.xlim = [xmin, xmax]\n\n\ndef ylim(ymin, ymax):\n \"\"\"Set limits of y axis\"\"\"\n fig = gcf()\n fig.ylim = [ymin, ymax]\n\n\ndef zlim(zmin, zmax):\n \"\"\"Set limits of zaxis\"\"\"\n fig = gcf()\n fig.zlim = [zmin, zmax]\n\n\ndef xyzlim(vmin, vmax=None):\n \"\"\"Set limits or all axis the same, if vmax not given, use [-vmin, vmax]\"\"\"\n if vmax is None:\n vmin, vmax = -vmin, vmin\n xlim(vmin, vmax)\n ylim(vmin, vmax)\n zlim(vmin, vmax)\n\n\ndef squarelim():\n \"\"\"Sets all axes with equal aspect ratio, such that the space is 'square'\"\"\"\n fig = gcf()\n xmin, xmax = fig.xlim\n ymin, ymax = fig.ylim\n zmin, zmax = fig.zlim\n width = max([abs(xmax - xmin), abs(ymax - ymin), abs(zmax - zmin)])\n xc = (xmin + xmax) / 2\n yc = (ymin + ymax) / 2\n zc = (zmin + zmax) / 2\n xlim(xc - width / 2, xc + width / 2)\n ylim(yc - width / 2, yc + width / 2)\n zlim(zc - width / 2, zc + width / 2)\n\n\ndefault_color = \"red\"\ndefault_color_selected = \"white\"\ndefault_size = 2\ndefault_size_selected = default_size * 1.3\n\n\n@_docsubst\ndef plot_trisurf(x, y, z, triangles=None, lines=None, color=default_color, u=None, v=None, texture=None):\n \"\"\"Draws a polygon/triangle mesh defined by a coordinate and triangle indices\n\n The following example plots a rectangle in the z==2 plane, consisting of 2 triangles:\n\n >>> plot_trisurf([0, 0, 3., 3.], [0, 4., 0, 4.], 2,\n triangles=[[0, 2, 3], [0, 3, 1]])\n\n Note that the z value is constant, and thus not a list/array. For guidance, the triangles\n refer to the vertices in this manner::\n\n ^ ydir\n |\n 2 3\n 0 1 ---> x dir\n\n Note that if you want per face/triangle colors, you need to duplicate each vertex.\n\n\n :param x: {x}\n :param y: {y}\n :param z: {z}\n :param triangles: numpy array with indices referring to the vertices, defining the triangles, with shape (M, 3)\n :param lines: numpy array with indices referring to the vertices, defining the lines, with shape (K, 2)\n :param color: {color}\n :param u: {u}\n :param v: {v}\n :param texture: {texture}\n :return: :any:`Mesh`\n \"\"\"\n fig = gcf()\n if triangles is not None:\n triangles = np.array(triangles).astype(dtype=np.uint32)\n if lines is not None:\n lines = np.array(lines).astype(dtype=np.uint32)\n mesh = ipv.Mesh(x=x, y=y, z=z, triangles=triangles, lines=lines, color=color, u=u, v=v, texture=texture)\n _grow_limits(np.array(x).reshape(-1), np.array(y).reshape(-1), np.array(z).reshape(-1))\n fig.meshes = fig.meshes + [mesh]\n return mesh\n\n\n@_docsubst\ndef plot_surface(x, y, z, color=default_color, wrapx=False, wrapy=False):\n \"\"\"Draws a 2d surface in 3d, defined by the 2d ordered arrays x,y,z\n\n :param x: {x2d}\n :param y: {y2d}\n :param z: {z2d}\n :param color: {color2d}\n :param bool wrapx: when True, the x direction is assumed to wrap, and polygons are drawn between the end end begin points\n :param bool wrapy: simular for the y coordinate\n :return: :any:`Mesh`\n \"\"\"\n return plot_mesh(x, y, z, color=color, wrapx=wrapx, wrapy=wrapy, wireframe=False)\n\n\n@_docsubst\ndef plot_wireframe(x, y, z, color=default_color, wrapx=False, wrapy=False):\n \"\"\"Draws a 2d wireframe in 3d, defines by the 2d ordered arrays x,y,z\n\n See also :any:`ipyvolume.pylab.plot_mesh`\n\n :param x: {x2d}\n :param y: {y2d}\n :param z: {z2d}\n :param color: {color2d}\n :param bool wrapx: when True, the x direction is assumed to wrap, and polygons are drawn between the begin and end points\n :param bool wrapy: idem for y\n :return: :any:`Mesh`\n \"\"\"\n return plot_mesh(x, y, z, color=color, wrapx=wrapx, wrapy=wrapy, wireframe=True, surface=False)\n\n\ndef plot_mesh(x, y, z, color=default_color, wireframe=True, surface=True, wrapx=False, wrapy=False, u=None, v=None,\n texture=None):\n \"\"\"Draws a 2d wireframe+surface in 3d: generalization of :any:`plot_wireframe` and :any:`plot_surface`\n\n :param x: {x2d}\n :param y: {y2d}\n :param z: {z2d}\n :param color: {color2d}\n :param bool wireframe: draw lines between the vertices\n :param bool surface: draw faces/triangles between the vertices\n :param bool wrapx: when True, the x direction is assumed to wrap, and polygons are drawn between the begin and end points\n :param boool wrapy: idem for y\n :param u: {u}\n :param v: {v}\n :param texture: {texture}\n :return: :any:`Mesh`\n \"\"\"\n fig = gcf()\n\n # assert len(x.shape) == 2\n # assert len(y.shape) == 2\n # assert len(z.shape) == 2\n # if isinstance(color, np.ndarray):\n # \tassert len(color.shape) == 3\n # \tassert color.shape[:2] == x.shape\n # \tcolor = color.reshape(-1)\n\n def dim(x):\n d = 0\n el = x\n while True:\n try:\n el = el[0]\n d += 1\n except:\n break\n return d\n\n if dim(x) == 2:\n nx, ny = shape = x.shape\n else:\n nx, ny = shape = x[0].shape\n\n # assert len(x.shape) == 2, \"Array x must be 2 dimensional.\"\n # assert len(y.shape) == 2, \"Array y must be 2 dimensional.\"\n # assert len(z.shape) == 2, \"Array z must be 2 dimensional.\"\n # assert x.shape == y.shape, \"Arrays x and y must have same shape.\"\n # assert y.shape == z.shape, \"Arrays y and z must have same shape.\"\n # convert x, y, z from shape (nx, ny) to (nx * ny) or\n # (frame, nx, ny) to (frame, nx*ny)\n def reshape(ar):\n if dim(ar) == 3:\n return [k.reshape(-1) for k in ar]\n else:\n return ar.reshape(-1)\n x = reshape(x)\n y = reshape(y)\n z = reshape(z)\n # similar for texture coordinates\n if u is not None:\n u = reshape(u)\n if v is not None:\n v = reshape(v)\n\n # convert color from shape (nx, ny, {3,4}) to (nx * ny, {3, 4}) or\n # (frame, nx, ny, {3,4}) to (frame, nx*ny, {3,4})\n def reshape_color(ar):\n if dim(ar) == 4:\n return [k.reshape(-1, k.shape[-1]) for k in ar]\n else:\n return ar.reshape(-1, ar.shape[-1])\n\n if isinstance(color, np.ndarray):\n color = reshape_color(color)\n\n _grow_limits(np.array(x).reshape(-1), np.array(y).reshape(-1), np.array(z).reshape(-1))\n triangles, lines = _make_triangles_lines((nx,ny) ,wrapx,wrapy)\n mesh = ipv.Mesh(x=x, y=y, z=z, triangles=triangles if surface else None, color=color,\n lines=lines if wireframe else None,\n u=u, v=v, texture=texture)\n fig.meshes = fig.meshes + [mesh]\n return mesh\n\n@_docsubst\ndef plot(x, y, z, color=default_color, **kwargs):\n \"\"\"Plot a line in 3d\n\n :param x: {x}\n :param y: {y}\n :param z: {z}\n :param color: {color}\n :param kwargs: extra arguments passed to the Scatter constructor\n :return: :any:`Scatter`\n \"\"\"\n fig = gcf()\n _grow_limits(x, y, z)\n defaults = dict(visible_lines=True, color_selected=None, size_selected=1,\n size=1, connected=True, visible_markers=False)\n kwargs = dict(defaults, **kwargs)\n s = ipv.Scatter(x=x, y=y, z=z, color=color, **kwargs)\n s.material.visible = False\n fig.scatters = fig.scatters + [s]\n return s\n\n\n@_docsubst\ndef scatter(x, y, z, color=default_color, size=default_size,\n size_selected=default_size_selected,\n color_selected=default_color_selected, marker=\"diamond\",\n selection=None, grow_limits=True, **kwargs):\n \"\"\"Plots many markers/symbols in 3d\n\n :param x: {x}\n :param y: {y}\n :param z: {z}\n :param color: {color}\n :param size: {size}\n :param size_selected: like size, but for selected glyphs\n :param color_selected: like color, but for selected glyphs\n :param marker: {marker}\n :param selection: numpy array of shape (N,) or (S, N) with indices of x,y,z arrays of the selected markers, which can have a different size and color\n :param kwargs:\n :return: :any:`Scatter`\n \"\"\"\n fig = gcf()\n if grow_limits:\n _grow_limits(x, y, z)\n s = ipv.Scatter(x=x, y=y, z=z, color=color, size=size,\n color_selected=color_selected, size_selected=size_selected,\n geo=marker, selection=selection, **kwargs)\n fig.scatters = fig.scatters + [s]\n return s\n\n@_docsubst\ndef quiver(x, y, z, u, v, w, size=default_size * 10,\n size_selected=default_size_selected * 10, color=default_color,\n color_selected=default_color_selected, marker=\"arrow\", **kwargs):\n \"\"\"Create a quiver plot, which is like a scatter plot but with arrows pointing in the direction given by u, v and w\n\n :param x: {x}\n :param y: {y}\n :param z: {z}\n :param u: {u_dir}\n :param v: {v_dir}\n :param w: {w_dir}\n :param size: {size}\n :param size_selected: like size, but for selected glyphs\n :param color: {color}\n :param color_selected: like color, but for selected glyphs\n :param marker: (currently only 'arrow' would make sense)\n :param kwargs: extra arguments passed on to the Scatter constructor\n :return: :any:`Scatter`\n \"\"\"\n fig = gcf()\n _grow_limits(x, y, z)\n if 'vx' in kwargs or 'vy' in kwargs or 'vz' in kwargs:\n raise KeyError('Please use u, v, w instead of vx, vy, vz')\n s = ipv.Scatter(x=x, y=y, z=z, vx=u, vy=v, vz=w, color=color, size=size,\n color_selected=color_selected, size_selected=size_selected,\n geo=marker, **kwargs)\n fig.scatters = fig.scatters + [s]\n return s\n\n\ndef show(extra_widgets=[]):\n \"\"\"Display (like in IPython.display.dispay(...)) the current figure\"\"\"\n gcf() # make sure we have something..\n display(gcc())\n for widget in extra_widgets:\n display(widget)\n\n\ndef animate_glyphs(*args, **kwargs):\n \"\"\"Deprecated: please use animation_control\"\"\"\n warnings.warn(\"Please use animation_control(...)\", DeprecationWarning, stacklevel=2)\n animation_control(*args, **kwargs)\n\n\ndef animation_control(object, sequence_length=None, add=True, interval=200):\n \"\"\"Animate scatter, quiver or mesh by adding a slider and play button.\n\n :param object: :any:`Scatter` or :any:`Mesh` object (having an sequence_index property), or a list of these to control multiple.\n :param sequence_length: If sequence_length is None we try try our best to figure out, in case we do it badly,\n you can tell us what it should be. Should be equal to the S in the shape of the numpy arrays as for instance documented\n in :any:`scatter` or :any:`plot_mesh`.\n :param add: if True, add the widgets to the container, else return a HBox with the slider and play button. Useful when you\n want to customise the layout of the widgets yourself.\n :param interval: interval in msec between each frame\n :return: If add is False, if returns the ipywidgets.HBox object containing the controls\n \"\"\"\n if isinstance(object, (list, tuple)):\n objects = object\n else:\n objects = [object]\n del object\n if sequence_length is None:\n # get all non-None arrays\n sequence_lengths = []\n for object in objects:\n sequence_lengths_previous = list(sequence_lengths)\n values = [getattr(object, name) for name in \"x y z vx vy vz\".split() if hasattr(object, name)]\n values = [k for k in values if k is not None]\n # sort them such that the higest dim is first\n values.sort(key=lambda key: -len(key.shape))\n try:\n sequence_length = values[0].shape[0] # assume this defines the sequence length\n if isinstance(object, ipv.Mesh): # for a mesh, it does not make sense to have less than 1 dimension\n if len(values[0].shape) >= 2: # if just 1d, it is most likely not an animation\n sequence_lengths.append(sequence_length)\n else:\n sequence_lengths.append(sequence_length)\n except IndexError: # scalars get ignored\n pass\n if hasattr(object, 'color'):\n color = object.color\n if color is not None:\n shape = color.shape\n if len(shape) == 3: # would be the case for for (frame, point_index, color_index)\n sequence_lengths.append(shape[0])\n # TODO: maybe support arrays of string type of form (frame, point_index)\n if len(sequence_lengths) == len(sequence_lengths_previous):\n raise ValueError('no frame dimension found for object: {}'.format(object))\n sequence_length = max(sequence_lengths)\n fig = gcf()\n fig.animation = interval\n fig.animation_exponent = 1.\n play = ipywidgets.Play(min=0, max=sequence_length - 1, interval=interval, value=0, step=1)\n slider = ipywidgets.FloatSlider(min=0, max=play.max, step=1)\n ipywidgets.jslink((play, 'value'), (slider, 'value'))\n for object in objects:\n ipywidgets.jslink((slider, 'value'), (object, 'sequence_index'))\n control = ipywidgets.HBox([play, slider])\n if add:\n current.container.children += (control,)\n else:\n return control\n\n\ndef gcc():\n \"\"\"Return the current container, that is the widget holding the figure and all the control widgets, buttons etc.\"\"\"\n gcf() # make sure we have something..\n return current.container\n\n\ndef transfer_function(level=[0.1, 0.5, 0.9], opacity=[0.01, 0.05, 0.1], level_width=0.1, controls=True, max_opacity=0.2):\n \"\"\"Create a transfer function, see volshow\"\"\"\n tf_kwargs = {}\n # level, opacity and widths can be scalars\n try:\n level[0]\n except:\n level = [level]\n try:\n opacity[0]\n except:\n opacity = [opacity] * 3\n try:\n level_width[0]\n except:\n level_width = [level_width] * 3\n # clip off lists\n min_length = min(len(level), len(level_width), len(opacity))\n level = list(level[:min_length])\n opacity = list(opacity[:min_length])\n level_width = list(level_width[:min_length])\n # append with zeros\n while len(level) < 3:\n level.append(0)\n while len(opacity) < 3:\n opacity.append(0)\n while len(level_width) < 3:\n level_width.append(0)\n for i in range(1, 4):\n tf_kwargs[\"level\" + str(i)] = level[i - 1]\n tf_kwargs[\"opacity\" + str(i)] = opacity[i - 1]\n tf_kwargs[\"width\" + str(i)] = level_width[i - 1]\n tf = ipv.TransferFunctionWidgetJs3(**tf_kwargs)\n fig = gcf()\n if controls:\n current.container.children = (tf.control(max_opacity=max_opacity),) + current.container.children\n return tf\n\n\ndef plot_isosurface(data, level=None, color=default_color, wireframe=True, surface=True, controls=True, extent=None):\n \"\"\"Plot a surface at constant value (like a 2d contour)\n\n :param data: 3d numpy array\n :param float level: value where the surface should lie\n :param color: color of the surface, although it can be an array, the length is difficult to predict beforehand,\n if per vertex color are needed, it is better to set them on the returned mesh afterwards.\n :param bool wireframe: draw lines between the vertices\n :param bool surface: draw faces/triangles between the vertices\n :param bool controls: add controls to change the isosurface\n :param extent: list of [[xmin, xmax], [ymin, ymax], [zmin, zmax]] values that define the bounding box of the mesh, otherwise the viewport is used\n :return: :any:`Mesh`\n \"\"\"\n from skimage import measure\n if level is None:\n level = np.median(data)\n if hasattr(measure, 'marching_cubes_lewiner'):\n values = measure.marching_cubes_lewiner(data, level)\n else:\n values = measure.marching_cubes(data, level)\n verts, triangles = values[:2] # version 0.13 returns 4 values, normals, values\n # in the future we may want to support normals and the values (with colormap)\n # and require skimage >= 0.13\n x, y, z = verts.T\n\n # Rescale coordinates to given limits\n if extent:\n xlim, ylim, zlim = extent\n x = x * np.diff(xlim)/(data.shape[0]-1) + xlim[0]\n y = y * np.diff(ylim)/(data.shape[1]-1) + ylim[0]\n z = z * np.diff(zlim)/(data.shape[2]-1) + zlim[0]\n _grow_limits(*extent)\n\n mesh = plot_trisurf(x, y, z, triangles=triangles, color=color)\n if controls:\n vmin, vmax = np.percentile(data, 1), np.percentile(data, 99)\n step = (vmax - vmin)/250\n level_slider = ipywidgets.FloatSlider(value=level, min=vmin, max=vmax, step=step, icon='eye')\n recompute_button = ipywidgets.Button(description='update')\n controls = ipywidgets.HBox(children=[level_slider, recompute_button])\n current.container.children += (controls,)\n def recompute(*_ignore):\n level = level_slider.value\n recompute_button.description = \"updating...\"\n if hasattr(measure, 'marching_cubes_lewiner'):\n values = measure.marching_cubes_lewiner(data, level)\n else:\n values = measure.marching_cubes(data, level)\n verts, triangles = values[:2] # version 0.13 returns 4 values, normals, values\n # in the future we may want to support normals and the values (with colormap)\n # and require skimage >= 0.13\n x, y, z = verts.T\n with mesh.hold_sync():\n mesh.x = x\n mesh.y = y\n mesh.z = z\n mesh.triangles = triangles.astype(dtype=np.uint32)\n recompute_button.description = \"update\"\n\n recompute_button.on_click(recompute)\n return mesh\n\n\ndef volshow(data, lighting=False, data_min=None, data_max=None,\n max_shape=256, tf=None, stereo=False,\n ambient_coefficient=0.5, diffuse_coefficient=0.8,\n specular_coefficient=0.5, specular_exponent=5,\n downscale=1,\n level=[0.1, 0.5, 0.9], opacity=[0.01, 0.05, 0.1], level_width=0.1,\n controls=True, max_opacity=0.2, memorder='C', extent=None):\n \"\"\"Visualize a 3d array using volume rendering.\n\n Currently only 1 volume can be rendered.\n\n\n :param data: 3d numpy array\n :param origin: origin of the volume data, this is to match meshes which have a different origin\n :param domain_size: domain size is the size of the volume \n :param bool lighting: use lighting or not, if set to false, lighting parameters will be overriden\n :param float data_min: minimum value to consider for data, if None, computed using np.nanmin\n :param float data_max: maximum value to consider for data, if None, computed using np.nanmax\n :parap int max_shape: maximum shape for the 3d cube, if larger, the data is reduced by skipping/slicing (data[::N]), set to None to disable.\n :param tf: transfer function (or a default one)\n :param bool stereo: stereo view for virtual reality (cardboard and similar VR head mount)\n :param ambient_coefficient: lighting parameter\n :param diffuse_coefficient: lighting parameter\n :param specular_coefficient: lighting parameter\n :param specular_exponent: lighting parameter\n :param float downscale: downscale the rendering for better performance, for instance when set to 2, a 512x512 canvas will show a 256x256 rendering upscaled, but it will render twice as fast.\n :param level: level(s) for the where the opacity in the volume peaks, maximum sequence of length 3\n :param opacity: opacity(ies) for each level, scalar or sequence of max length 3\n :param level_width: width of the (gaussian) bumps where the opacity peaks, scalar or sequence of max length 3\n :param bool controls: add controls for lighting and transfer function or not\n :param float max_opacity: maximum opacity for transfer function controls\n :param extent: list of [[xmin, xmax], [ymin, ymax], [zmin, zmax]] values that define the bounds of the volume, otherwise the viewport is used\n :return:\n \"\"\"\n fig = gcf()\n\n if tf is None:\n tf = transfer_function(level, opacity, level_width, controls=controls, max_opacity=max_opacity)\n if data_min is None:\n data_min = np.nanmin(data)\n if data_max is None:\n data_max = np.nanmax(data)\n if memorder is 'F':\n data = data.T\n\n if extent is None:\n extent = [(0, k) for k in data.shape[::-1]]\n\n if extent:\n _grow_limits(*extent)\n\n vol = ipv.Volume(data_original = data,\n tf=tf,\n data_min = data_min,\n data_max = data_max,\n show_min = data_min,\n show_max = data_max,\n extent_original = extent,\n data_max_shape = max_shape,\n ambient_coefficient = ambient_coefficient,\n diffuse_coefficient = diffuse_coefficient,\n specular_coefficient = specular_coefficient,\n specular_exponent = specular_exponent,\n rendering_lighting = lighting)\n\n vol._listen_to(fig)\n\n if controls:\n widget_opacity_scale = ipywidgets.FloatLogSlider(base=10, min=-2, max=2, \n description=\"opacity\")\n widget_brightness = ipywidgets.FloatLogSlider(base=10, min=-1, max=1,\n description=\"brightness\")\n ipywidgets.jslink((vol, 'opacity_scale'), (widget_opacity_scale, 'value'))\n ipywidgets.jslink((vol, 'brightness'), (widget_brightness, 'value'))\n widgets_bottom = [ipywidgets.HBox([widget_opacity_scale, widget_brightness])]\n current.container.children += tuple(widgets_bottom, )\n\n fig.volumes = fig.volumes + [vol]\n\n return vol\n\n\ndef save(filepath, makedirs=True, title=u'IPyVolume Widget', all_states=False,\n offline=False, scripts_path='js',\n drop_defaults=False, template_options=((\"extra_script_head\", \"\"), (\"body_pre\", \"\"), (\"body_post\", \"\")),\n devmode=False, offline_cors=False):\n \"\"\"Save the current container to a HTML file\n\n By default the HTML file is not standalone and requires an internet connection to fetch a few javascript\n libraries. Use offline=True to download these and make the HTML file work without an internet connection.\n\n :param str filepath: The file to write the HTML output to.\n :param bool makedirs: whether to make directories in the filename path, if they do not already exist\n :param str title: title for the html page\n :param bool all_states: if True, the state of all widgets know to the widget manager is included, else only those in widgets\n :param bool offline: if True, use local urls for required js/css packages and download all js/css required packages\n (if not already available), such that the html can be viewed with no internet connection\n :param str scripts_path: the folder to save required js/css packages to (relative to the filepath)\n :param bool drop_defaults: Whether to drop default values from the widget states\n :param template_options: list or dict of additional template options\n :param bool devmode: if True, attempt to get index.js from local js/dist folder\n :param bool offline_cors: if True, sets crossorigin attribute of script tags to anonymous\n\n \"\"\"\n ipyvolume.embed.embed_html(filepath, current.container, makedirs=makedirs, title=title, all_states=all_states,\n offline=offline, scripts_path=scripts_path,\n drop_defaults=drop_defaults, template_options=template_options, devmode=devmode,\n offline_cors=offline_cors)\n\n\ndef _change_azimuth_angle(fig, frame, fraction):\n with fig:\n view(azimuth=fraction*360)\n\n\ndef movie(f=\"movie.mp4\", function=_change_azimuth_angle, fps=30, frames=30, endpoint=False, \\\n cmd_template_ffmpeg=\"ffmpeg -y -r {fps} -i {tempdir}/frame-%5d.png -vcodec h264 -pix_fmt yuv420p {filename}\",\n cmd_template_gif=\"convert -delay {delay} {loop} {tempdir}/frame-*.png {filename}\",\n gif_loop=0):\n \"\"\"Create a movie (mp4/gif) out of many frames\n\n If the filename ends in `.gif`, `convert` is used to convert all frames to an animated gif using the `cmd_template_gif`\n template. Otherwise `ffmpeg is assumed to know the file format`.\n\n Example:\n\n >>> def set_angles(fig, i, fraction):\n >>> fig.angley = fraction*np.pi*2\n >>> # 4 second movie, that rotates around the y axis\n >>> p3.movie('test2.gif', set_angles, fps=20, frames=20*4,\n endpoint=False)\n\n Note that in the example above we use `endpoint=False` to avoid to first and last frame to be the same\n\n :param str f: filename out output movie (e.g. 'movie.mp4' or 'movie.gif')\n :param function: function called before each frame with arguments (figure, framenr, fraction)\n :param fps: frames per seconds\n :param int frames: total number of frames\n :param bool endpoint: if fraction goes from [0, 1] (inclusive) or [0, 1) (endpoint=False is useful for loops/rotatations)\n :param str cmd_template_ffmpeg: template command when running ffmpeg (non-gif ending filenames)\n :param str cmd_template_gif: template command when running imagemagick's convert (if filename ends in .gif)\n :param gif_loop: None for no loop, otherwise the framenumber to go to after the last frame\n :return: the temp dir where the frames are stored\n \"\"\"\n movie_filename = f\n import tempfile\n tempdir = tempfile.mkdtemp()\n output = ipywidgets.Output()\n display(output)\n fig = gcf()\n for i in range(frames):\n with output:\n fraction = i / (frames - 1. if endpoint else frames)\n function(fig, i, fraction)\n frame_filename = os.path.join(tempdir, \"frame-%05d.png\" % i)\n savefig(frame_filename, output_widget=output)\n with output:\n if movie_filename.endswith(\".gif\"):\n if gif_loop is None:\n loop = \"\"\n else:\n loop = \"-loop %d\" % gif_loop\n delay = 100 / fps\n cmd = cmd_template_gif.format(delay=delay, loop=loop, tempdir=tempdir, filename=movie_filename)\n else:\n cmd = cmd_template_ffmpeg.format(fps=fps, tempdir=tempdir, filename=movie_filename)\n print(cmd)\n os.system(cmd)\n return tempdir\n\n\ndef _screenshot_data(timeout_seconds=10, output_widget=None, format=\"png\", width=None, height=None, fig=None, headless=False, devmode=False):\n if fig is None:\n fig = gcf()\n else:\n assert isinstance(fig, ipv.Figure)\n if headless:\n from . import headless\n import tempfile\n tempdir = tempfile.mkdtemp()\n tempfile = os.path.join(tempdir, 'headless.html')\n save(tempfile, offline=False, scripts_path=tempdir, devmode=devmode)\n data = headless._screenshot_data(\"file://\" + tempfile)\n if data is None:\n raise ValueError('Error capturing data from headless browser')\n else:\n if output_widget is None:\n output_widget = ipywidgets.Output()\n display(output_widget)\n # use lists to avoid globals\n done = [False]\n data = [None]\n\n def screenshot_handler(image_data):\n with output_widget:\n # print(\"data\")\n # print(data)\n done[0] = True\n data[0] = image_data\n\n fig.on_screenshot(screenshot_handler)\n try:\n fig.screenshot(width=width, height=height,mime_type=\"image/\"+format)\n t0 = time.time()\n timeout = False\n ipython = IPython.get_ipython()\n while (not done[0]) and not timeout:\n ipython.kernel.do_one_iteration()\n with output_widget:\n time.sleep(0.05)\n timeout = (time.time() - t0) > timeout_seconds\n with output_widget:\n if timeout and not done[0]:\n raise ValueError(\"timed out, no image data returned\")\n finally:\n with output_widget:\n fig.on_screenshot(screenshot_handler, remove=True)\n data = data[0]\n data = data[data.find(\",\") + 1:]\n return base64.b64decode(data)\n\ndef screenshot(width=None, height=None, format=\"png\", fig=None, timeout_seconds=10, output_widget=None, headless=False, devmode=False):\n \"\"\"Save the figure to a PIL.Image object.\n\n :param int width: the width of the image in pixels\n :param int height: the height of the image in pixels\n :param format: format of output data (png, jpeg or svg)\n :type fig: ipyvolume.widgets.Figure or None\n :param fig: if None use the current figure\n :type timeout_seconds: int\n :param timeout_seconds: maximum time to wait for image data to return\n :type output_widget: ipywidgets.Output\n :param output_widget: a widget to use as a context manager for capturing the data\n :param bool headless: if True, use headless chrome to take screenshot\n :param bool devmode: if True, attempt to get index.js from local js/dist folder\n :return: PIL.Image\n\n \"\"\"\n assert format in ['png','jpeg','svg'], \"image format must be png, jpeg or svg\"\n data = _screenshot_data(timeout_seconds=timeout_seconds, output_widget=output_widget,\n format=format, width=width, height=height, fig=fig, headless=headless, devmode=devmode)\n f = StringIO(data)\n return PIL.Image.open(f)\n\ndef savefig(filename, width=None, height=None, fig=None, timeout_seconds=10, output_widget=None, headless=False, devmode=False):\n \"\"\"Save the figure to an image file.\n\n :param str filename: must have extension .png, .jpeg or .svg\n :param int width: the width of the image in pixels\n :param int height: the height of the image in pixels\n :type fig: ipyvolume.widgets.Figure or None\n :param fig: if None use the current figure\n :param float timeout_seconds: maximum time to wait for image data to return\n :param ipywidgets.Output output_widget: a widget to use as a context manager for capturing the data\n :param bool headless: if True, use headless chrome to save figure\n :param bool devmode: if True, attempt to get index.js from local js/dist folder\n \"\"\"\n __, ext = os.path.splitext(filename)\n format = ext[1:]\n assert format in ['png','jpeg','svg'], \"image format must be png, jpeg or svg\"\n with open(filename, \"wb\") as f:\n f.write(_screenshot_data(timeout_seconds=timeout_seconds, output_widget=output_widget,\n format=format, width=width, height=height, fig=fig, headless=headless, devmode=devmode))\n\n\ndef xlabel(label):\n \"\"\"Set the labels for the x-axis\"\"\"\n fig = gcf()\n fig.xlabel = label\n\n\ndef ylabel(label):\n \"\"\"Set the labels for the y-axis\"\"\"\n fig = gcf()\n fig.ylabel = label\n\n\ndef zlabel(label):\n \"\"\"Set the labels for the z-axis\"\"\"\n fig = gcf()\n fig.zlabel = label\n\n\ndef xyzlabel(labelx, labely, labelz):\n \"\"\"Set all labels at once\"\"\"\n xlabel(labelx)\n ylabel(labely)\n zlabel(labelz)\n\ndef view(azimuth=None, elevation=None, distance=None):\n \"\"\"Sets camera angles and distance and returns the current.\n\n :param float azimuth: rotation around the axis pointing up in degrees\n :param float elevation: rotation where +90 means 'up', -90 means 'down', in degrees\n :param float distance: radial distance from the center to the camera.\n \"\"\"\n fig = gcf()\n # first calculate the current values\n x, y, z = fig.camera.position\n r = np.sqrt(x**2 + y**2 + z**2)\n az = np.degrees(np.arctan2(x, z))\n el = np.degrees(np.arcsin(y/r))\n if azimuth is None:\n azimuth = az\n if elevation is None:\n elevation = el\n if distance is None:\n distance = r\n cosaz = np.cos(np.radians(azimuth))\n sinaz = np.sin(np.radians(azimuth))\n sine = np.sin(np.radians(elevation))\n cose = np.cos(np.radians(elevation))\n fig.camera.position = (distance*sinaz*cose, distance*sine, distance*cosaz*cose)\n return azimuth, elevation, distance\n\n\n# mimic matplotlib namesace\nclass style:\n \"\"\"'Static class that mimics a matplotlib module.\n\n Example:\n\n >>> import ipyvolume as ipv\n >>> ipv.style.use('light'])\n >>> ipv.style.use('seaborn-darkgrid'])\n >>> ipv.style.use(['seaborn-darkgrid', {'axes.x.color':'orange'}])\n\n Possible style values:\n * figure.facecolor: background color\n * axes.color: color of the box around the volume/viewport\n * xaxis.color: color of xaxis\n * yaxis.color: color of xaxis\n * zaxis.color: color of xaxis\n\n \"\"\"\n\n @staticmethod\n def use(style):\n \"\"\"Set the style of the current figure/visualization\n\n :param style: matplotlib style name, or dict with values, or a sequence of these, where the last value overrides previous\n :return:\n \"\"\"\n import six\n def valid(value): # checks if json'able\n return isinstance(value, six.string_types)\n\n def translate(mplstyle):\n style = {}\n mapping = [\n ['figure.facecolor', 'background-color'],\n ['xtick.color', 'axes.x.color'], # TODO: is this the right thing?\n ['xtick.color', 'axes.z.color'], # map x to z as well\n ['ytick.color', 'axes.y.color'],\n ['axes.labelcolor', 'axes.label.color'],\n ['text.color', 'color'],\n ['axes.edgecolor', 'axes.color']\n ]\n for from_name, to_name in mapping:\n if from_name in mplstyle:\n value = mplstyle[from_name]\n if \"color\" in from_name:\n try: # threejs doesn't like a color like '.13', so try to convert to proper format\n value = float(value) * 255\n value = \"rgb(%d, %d, %d)\" % (value, value, value)\n except:\n pass\n\n utils.nested_setitem(style, to_name, value)\n return style\n\n if isinstance(style, six.string_types + (dict,)):\n styles = [style]\n else:\n styles = style\n fig = gcf()\n totalstyle = utils.dict_deep_update({}, fig.style)\n for style in styles:\n if isinstance(style, six.string_types):\n if hasattr(ipyvolume.styles, style):\n style = getattr(ipyvolume.styles, style)\n else:\n # lets see if we can copy matplotlib's style\n # we assume now it's a matplotlib style, get all properties that we understand\n import matplotlib.style\n cleaned_style = {key: value for key, value in dict(matplotlib.style.library[style]).items() if\n valid(value)}\n style = translate(cleaned_style)\n # totalstyle.update(cleaned_style)\n else:\n # otherwise assume it's a dict\n pass\n totalstyle = utils.dict_deep_update(totalstyle, style)\n\n fig = gcf()\n fig.style = totalstyle\n\n @staticmethod\n def axes_off():\n \"\"\"Do not draw the axes\"\"\"\n style.use({'axes': {'visible': False}})\n\n @staticmethod\n def axes_on():\n \"\"\"Draw the axes\"\"\"\n style.use({'axes': {'visible': True}})\n\n @staticmethod\n def box_off():\n \"\"\"Do not draw the box around the visible volume\"\"\"\n style.use({'box': {'visible': False}})\n\n @staticmethod\n def box_on():\n \"\"\"Draw a box around the visible volume\"\"\"\n style.use({'box': {'visible': True}})\n\n @staticmethod\n def background_color(color):\n \"\"\"Sets the background color\"\"\"\n style.use({'background-color': color})\n\nfor style_name, __ in ipv.styles.styles.items():\n def closure(style_name=style_name):\n def quick_set():\n style.use(style_name)\n attr_name = 'set_style_' + style_name\n attr = staticmethod(quick_set)\n setattr(style, attr_name, attr)\n getattr(style, attr_name).__doc__ = \"\"\"Short for style.use(%r)\"\"\" % style_name\n\n closure()\n\n@_docsubst\ndef plot_plane(where=\"back\", texture=None):\n \"\"\"Plots a plane at a particular location in the viewbox\n\n :param str where: 'back', 'front', 'left', 'right', 'top', 'bottom'\n :param texture: {texture}\n :return: :any:`Mesh`\n \"\"\"\n fig = gcf()\n xmin, xmax = fig.xlim\n ymin, ymax = fig.ylim\n zmin, zmax = fig.zlim\n if where == \"back\":\n x = [xmin, xmax, xmax, xmin]\n y = [ymin, ymin, ymax, ymax]\n z = [zmin, zmin, zmin, zmin]\n if where == \"front\":\n x = [xmin, xmax, xmax, xmin][::-1]\n y = [ymin, ymin, ymax, ymax]\n z = [zmax, zmax, zmax, zmax]\n if where == \"left\":\n x = [xmin, xmin, xmin, xmin]\n y = [ymin, ymin, ymax, ymax]\n z = [zmin, zmax, zmax, zmin]\n if where == \"right\":\n x = [xmax, xmax, xmax, xmax]\n y = [ymin, ymin, ymax, ymax]\n z = [zmin, zmax, zmax, zmin][::-1]\n if where == \"top\":\n x = [xmin, xmax, xmax, xmin]\n y = [ymax, ymax, ymax, ymax]\n z = [zmax, zmax, zmin, zmin]\n if where == \"bottom\":\n x = [xmax, xmin, xmin, xmax]\n y = [ymin, ymin, ymin, ymin]\n z = [zmin, zmin, zmax, zmax]\n triangles = [(0, 1, 2), (0, 2, 3)]\n u = v = None\n if texture is not None:\n u = [0., 1., 1., 0.]\n v = [0., 0., 1., 1.]\n mesh = plot_trisurf(x, y, z, triangles, texture=texture, u=u, v=v)\n return mesh\n\ndef selector_default(output_widget=None):\n \"\"\"Capture selection events from the current figure, and apply the selections to Scatter objects\n\n Example:\n\n >>> import ipyvolume as ipv\n >>> ipv.figure()\n >>> ipv.examples.gaussian()\n >>> ipv.selector_default()\n >>> ipv.show()\n\n Now hold the control key to do selections, type\n\n * 'C' for circle\n * 'R' for rectangle\n * 'L' for lasso\n * '=' for replace mode\n * '&' for logically and mode\n * '|' for logically or mode\n * '-' for subtract mode\n\n \"\"\"\n fig = gcf()\n if output_widget is None:\n output_widget = ipywidgets.Output()\n display(output_widget)\n def lasso(data, other=None, fig=fig):\n with output_widget:\n if data['device'] and data['type'] == 'lasso':\n import shapely.geometry\n region = shapely.geometry.Polygon(data['device'])\n @np.vectorize\n def inside(x, y):\n return region.contains(shapely.geometry.Point([x, y]))\n if data['device'] and data['type'] == 'circle':\n x1, y1 = data['device']['begin']\n x2, y2 = data['device']['end']\n dx = x2 - x1\n dy = y2 - y1\n r = (dx**2 + dy**2)**0.5\n def inside(x, y):\n return ((x-x1)**2 + (y-y1)**2) < r**2\n if data['device'] and data['type'] == 'rectangle':\n x1, y1 = data['device']['begin']\n x2, y2 = data['device']['end']\n x = [x1, x2]\n y = [y1, y2]\n xmin, xmax = min(x), max(x)\n ymin, ymax = min(y), max(y)\n def inside(x, y):\n return (x > xmin) & (x < xmax) & (y > ymin) & (y < ymax)\n def join(x, y, mode):\n N = np.max(x) if x is not None else np.max(y)\n N = max(N, np.max(y))\n xmask = np.zeros(N+1, np.bool)\n ymask = np.zeros(N+1, np.bool)\n if x is not None:\n xmask[x] = True\n ymask[y] = True\n if mode == \"replace\":\n return np.where(ymask)\n if mode == \"and\":\n mask = xmask & ymask\n return np.where(ymask if x is None else mask)\n if mode == \"or\":\n mask = xmask | ymask\n return np.where(ymask if x is None else mask)\n if mode == \"subtract\":\n mask = xmask & ~ymask\n return np.where(ymask if x is None else mask)\n for scatter in fig.scatters:\n x, y = fig.project(scatter.x, scatter.y, scatter.z)\n mask = inside(x, y)\n scatter.selected = join(scatter.selected, np.where(mask), fig.selection_mode)\n fig.on_selection(lasso)\n\n\n\ndef _make_triangles_lines(shape, wrapx=False, wrapy=False):\n \"\"\"Transform rectangular regular grid into triangles\n\n :param x: {x2d}\n :param y: {y2d}\n :param z: {z2d}\n :param bool wrapx: when True, the x direction is assumed to wrap, and polygons are drawn between the end end begin points\n :param bool wrapy: simular for the y coordinate\n :return: triangles and lines used to plot Mesh\n \"\"\"\n\n nx, ny = shape\n\n mx = nx if wrapx else nx - 1\n my = ny if wrapy else ny - 1\n\n \"\"\"\n create all pair of indices (i,j) of the rectangular grid\n minus last row if wrapx = False => mx\n minus last column if wrapy = False => my\n | (0,0) ... (0,j) ... (0,my-1) |\n | . . . . . |\n | (i,0) ... (i,j) ... (i,my-1) |\n | . . . . . |\n |(mx-1,0) ... (mx-1,j) ... (mx-1,my-1) |\n \"\"\"\n i, j = np.mgrid[0:mx, 0:my]\n\n \"\"\"\n collapsed i and j in one dimensional array, row-major order\n ex :\n array([[0, 1, 2], => array([0, 1, 2, 3, *4*, 5])\n [3, *4*, 5]])\n if we want vertex 4 at (i=1,j=1) we must transform it in i*ny+j = 4\n \"\"\"\n i, j = np.ravel(i), np.ravel(j)\n\n \"\"\"\n Let's go for the triangles :\n (i,j) - (i,j+1) -> y dir\n (i+1,j) - (i+1,j+1)\n |\n v\n x dir\n\n in flatten coordinates:\n i*ny+j - i*ny+j+1\n (i+1)*ny+j - (i+1)*ny+j+1\n \"\"\"\n\n t1 = (i * ny + j,\n (i + 1) % nx * ny + j,\n (i + 1) % nx * ny + (j + 1) % ny)\n t2 = (i * ny + j,\n (i + 1) % nx * ny + (j + 1) % ny,\n i * ny + (j + 1) % ny)\n\n \"\"\"\n %nx and %ny are used for wrapx and wrapy :\n if (i+1)=nx => (i+1)%nx=0 => close mesh in x direction\n if (j+1)=ny => (j+1)%ny=0 => close mesh in y direction\n \"\"\"\n\n nt = len(t1[0])\n\n triangles = np.zeros((nt * 2, 3), dtype=np.uint32)\n triangles[0::2, 0], triangles[0::2, 1], triangles[0::2, 2] = t1\n triangles[1::2, 0], triangles[1::2, 1], triangles[1::2, 2] = t2\n\n lines = np.zeros((nt * 4, 2), dtype=np.uint32)\n lines[::4,0], lines[::4,1] = t1[:2]\n lines[1::4,0], lines[1::4,1] = t1[0],t2[2]\n lines[2::4,0], lines[2::4,1] = t2[2:0:-1]\n lines[3::4,0], lines[3::4,1] = t1[1],t2[1]\n\n return triangles, lines\n"
] |
[
[
"numpy.nanmax",
"numpy.radians",
"numpy.sqrt",
"numpy.isfinite",
"numpy.arcsin",
"numpy.min",
"numpy.median",
"numpy.nanmin",
"numpy.percentile",
"numpy.arctan2",
"numpy.max",
"numpy.diff",
"numpy.ravel",
"numpy.array",
"numpy.zeros",
"numpy.where"
]
] |
johnehunt/PythonDataScienceIntro
|
[
"73dc6938c65c6b64486d3e6c6f968fa99976d90a"
] |
[
"06-pandas-data-wrangling/iris_data_processing.py"
] |
[
"import pandas as pd\n\niris_df = pd.read_csv('iris.csv')\n\nprint(iris_df.head())\nprint(iris_df.shape)\n\nprint('-' * 25)\n\n# find out information about unique values in the sample\nprint(iris_df.sepallength.unique()) # give the unique values\nprint(iris_df.sepallength.nunique()) # count the unique values\n\nprint('-' * 25)\n# Dealing with duplicate values\nprint(iris_df.duplicated())\n\n# Can drop all duplicate rows\niris_df.drop_duplicates(keep=\"first\", inplace=True)\nprint(iris_df.duplicated())\n\nprint('-' * 25)\n\n# Find NA down a row\nprint(iris_df['petallength'].isna().sum())\n# FOr all columns\nprint(iris_df.isna().sum())\n# For the whole dataset\nprint(iris_df.isna().sum().sum())\n\n# Across a row\nprint(iris_df.loc[[1]].isna().sum().sum())\n\n"
] |
[
[
"pandas.read_csv"
]
] |
geekpineapple/ElegantRL
|
[
"d8fe318a0dbba0a9f85be9291d8a5397823d5d33"
] |
[
"elegantrl_helloworld/agent.py"
] |
[
"import os\nimport numpy.random as rd\nfrom copy import deepcopy\nfrom elegantrl_helloworld.net import *\n\n\nclass AgentBase:\n def __init__(self):\n self.state = None\n self.device = None\n self.action_dim = None\n self.if_off_policy = None\n self.explore_noise = None\n self.trajectory_list = None\n\n self.criterion = torch.nn.SmoothL1Loss()\n self.cri = self.cri_target = self.if_use_cri_target = self.cri_optim = self.ClassCri = None\n self.act = self.act_target = self.if_use_act_target = self.act_optim = self.ClassAct = None\n\n def init(self, net_dim, state_dim, action_dim, learning_rate=1e-4, _if_per_or_gae=False, gpu_id=0):\n # explict call self.init() for multiprocessing\n self.device = torch.device(f\"cuda:{gpu_id}\" if (torch.cuda.is_available() and (gpu_id >= 0)) else \"cpu\")\n self.action_dim = action_dim\n\n self.cri = self.ClassCri(net_dim, state_dim, action_dim).to(self.device)\n self.act = self.ClassAct(net_dim, state_dim, action_dim).to(self.device) if self.ClassAct else self.cri\n self.cri_target = deepcopy(self.cri) if self.if_use_cri_target else self.cri\n self.act_target = deepcopy(self.act) if self.if_use_act_target else self.act\n\n self.cri_optim = torch.optim.Adam(self.cri.parameters(), learning_rate)\n self.act_optim = torch.optim.Adam(self.act.parameters(), learning_rate) if self.ClassAct else self.cri\n del self.ClassCri, self.ClassAct\n\n def select_action(self, state) -> np.ndarray:\n states = torch.as_tensor((state,), dtype=torch.float32, device=self.device)\n action = self.act(states)[0]\n action = (action + torch.randn_like(action) * self.explore_noise).clamp(-1, 1)\n return action.detach().cpu().numpy()\n\n def explore_env(self, env, target_step) -> list:\n state = self.state\n\n trajectory_list = list()\n for _ in range(target_step):\n action = self.select_action(state)\n next_s, reward, done, _ = env.step(action)\n trajectory_list.append((state, (reward, done, *action)))\n\n state = env.reset() if done else next_s\n self.state = state\n return trajectory_list\n\n @staticmethod\n def optim_update(optimizer, objective):\n optimizer.zero_grad()\n objective.backward()\n optimizer.step()\n\n @staticmethod\n def soft_update(target_net, current_net, tau):\n for tar, cur in zip(target_net.parameters(), current_net.parameters()):\n tar.data.copy_(cur.data * tau + tar.data * (1.0 - tau))\n\n def save_or_load_agent(self, cwd, if_save):\n def load_torch_file(model_or_optim, _path):\n state_dict = torch.load(_path, map_location=lambda storage, loc: storage)\n model_or_optim.load_state_dict(state_dict)\n\n name_obj_list = [('actor', self.act), ('act_target', self.act_target), ('act_optim', self.act_optim),\n ('critic', self.cri), ('cri_target', self.cri_target), ('cri_optim', self.cri_optim), ]\n name_obj_list = [(name, obj) for name, obj in name_obj_list if obj is not None]\n if if_save:\n for name, obj in name_obj_list:\n save_path = f\"{cwd}/{name}.pth\"\n torch.save(obj.state_dict(), save_path)\n else:\n for name, obj in name_obj_list:\n save_path = f\"{cwd}/{name}.pth\"\n load_torch_file(obj, save_path) if os.path.isfile(save_path) else None\n\n\nclass AgentDQN(AgentBase):\n def __init__(self):\n super().__init__()\n self.explore_rate = 0.25 # the probability of choosing action randomly in epsilon-greedy\n self.if_use_cri_target = True\n self.ClassCri = QNet\n\n def select_action(self, state) -> int: # for discrete action space\n if rd.rand() < self.explore_rate: # epsilon-greedy\n a_int = rd.randint(self.action_dim) # choosing action randomly\n else:\n states = torch.as_tensor((state,), dtype=torch.float32, device=self.device)\n action = self.act(states)[0]\n a_int = action.argmax(dim=0).detach().cpu().numpy()\n return a_int\n\n def explore_env(self, env, target_step) -> list:\n state = self.state\n\n trajectory_list = list()\n for _ in range(target_step):\n action = self.select_action(state) # assert isinstance(action, int)\n next_s, reward, done, _ = env.step(action)\n trajectory_list.append((state, (reward, done, action)))\n\n state = env.reset() if done else next_s\n self.state = state\n return trajectory_list\n\n def update_net(self, buffer, batch_size, repeat_times, soft_update_tau) -> tuple:\n buffer.update_now_len()\n obj_critic = q_value = None\n for _ in range(int(buffer.now_len / batch_size * repeat_times)):\n obj_critic, q_value = self.get_obj_critic(buffer, batch_size)\n self.optim_update(self.cri_optim, obj_critic)\n self.soft_update(self.cri_target, self.cri, soft_update_tau)\n return obj_critic.item(), q_value.mean().item()\n\n def get_obj_critic(self, buffer, batch_size) -> (torch.Tensor, torch.Tensor):\n with torch.no_grad():\n reward, mask, action, state, next_s = buffer.sample_batch(batch_size)\n next_q = self.cri_target(next_s).max(dim=1, keepdim=True)[0]\n q_label = reward + mask * next_q\n\n q_value = self.cri(state).gather(1, action.long())\n obj_critic = self.criterion(q_value, q_label)\n return obj_critic, q_value\n\n\nclass AgentDoubleDQN(AgentDQN):\n def __init__(self):\n super().__init__()\n self.softMax = torch.nn.Softmax(dim=1)\n self.ClassCri = QNetTwin\n\n def select_action(self, state) -> int: # for discrete action space\n states = torch.as_tensor((state,), dtype=torch.float32, device=self.device)\n actions = self.act(states)\n if rd.rand() < self.explore_rate: # epsilon-greedy\n a_prob = self.softMax(actions)[0].detach().cpu().numpy()\n a_int = rd.choice(self.action_dim, p=a_prob) # choose action according to Q value\n else:\n action = actions[0]\n a_int = action.argmax(dim=0).detach().cpu().numpy()\n return a_int\n\n def get_obj_critic(self, buffer, batch_size) -> (torch.Tensor, torch.Tensor):\n with torch.no_grad():\n reward, mask, action, state, next_s = buffer.sample_batch(batch_size)\n next_q = torch.min(*self.cri_target.get_q1_q2(next_s)).max(dim=1, keepdim=True)[0]\n q_label = reward + mask * next_q\n\n q1, q2 = [qs.gather(1, action.long()) for qs in self.act.get_q1_q2(state)]\n obj_critic = self.criterion(q1, q_label) + self.criterion(q2, q_label)\n return obj_critic, q1\n\n\nclass AgentDDPG(AgentBase):\n def __init__(self):\n super().__init__()\n self.explore_noise = 0.1 # explore noise of action\n self.if_use_cri_target = self.if_use_act_target = True\n self.ClassCri = Critic\n self.ClassAct = Actor\n\n def update_net(self, buffer, batch_size, repeat_times, soft_update_tau) -> (float, float):\n buffer.update_now_len()\n obj_critic = obj_actor = None\n for _ in range(int(buffer.now_len / batch_size * repeat_times)):\n obj_critic, state = self.get_obj_critic(buffer, batch_size)\n self.optim_update(self.cri_optim, obj_critic)\n self.soft_update(self.cri_target, self.cri, soft_update_tau)\n\n action_pg = self.act(state) # policy gradient\n obj_actor = -self.cri(state, action_pg).mean()\n self.optim_update(self.act_optim, obj_actor)\n self.soft_update(self.act_target, self.act, soft_update_tau)\n return obj_actor.item(), obj_critic.item()\n\n def get_obj_critic(self, buffer, batch_size) -> (torch.Tensor, torch.Tensor):\n with torch.no_grad():\n reward, mask, action, state, next_s = buffer.sample_batch(batch_size)\n next_q = self.cri_target(next_s, self.act_target(next_s))\n q_label = reward + mask * next_q\n q_value = self.cri(state, action)\n obj_critic = self.criterion(q_value, q_label)\n return obj_critic, state\n\n\nclass AgentTD3(AgentBase):\n def __init__(self):\n super().__init__()\n self.explore_noise = 0.1 # standard deviation of exploration noise\n self.policy_noise = 0.2 # standard deviation of policy noise\n self.update_freq = 2 # delay update frequency\n self.if_use_cri_target = self.if_use_act_target = True\n self.ClassCri = CriticTwin\n self.ClassAct = Actor\n\n def update_net(self, buffer, batch_size, repeat_times, soft_update_tau) -> tuple:\n buffer.update_now_len()\n obj_critic = obj_actor = None\n for update_c in range(int(buffer.now_len / batch_size * repeat_times)):\n obj_critic, state = self.get_obj_critic(buffer, batch_size)\n self.optim_update(self.cri_optim, obj_critic)\n\n action_pg = self.act(state) # policy gradient\n obj_actor = -self.cri_target(state, action_pg).mean() # use cri_target instead of cri for stable training\n self.optim_update(self.act_optim, obj_actor)\n if update_c % self.update_freq == 0: # delay update\n self.soft_update(self.cri_target, self.cri, soft_update_tau)\n self.soft_update(self.act_target, self.act, soft_update_tau)\n return obj_critic.item() / 2, obj_actor.item()\n\n def get_obj_critic(self, buffer, batch_size) -> (torch.Tensor, torch.Tensor):\n with torch.no_grad():\n reward, mask, action, state, next_s = buffer.sample_batch(batch_size)\n next_a = self.act_target.get_action(next_s, self.policy_noise) # policy noise\n next_q = torch.min(*self.cri_target.get_q1_q2(next_s, next_a)) # twin critics\n q_label = reward + mask * next_q\n\n q1, q2 = self.cri.get_q1_q2(state, action)\n obj_critic = self.criterion(q1, q_label) + self.criterion(q2, q_label) # twin critics\n return obj_critic, state\n\n\nclass AgentSAC(AgentBase):\n def __init__(self):\n super().__init__()\n self.ClassCri = CriticTwin\n self.ClassAct = ActorSAC\n self.if_use_cri_target = True\n self.if_use_act_target = False\n\n self.alpha_log = None\n self.alpha_optim = None\n self.target_entropy = None\n\n def init(self, net_dim, state_dim, action_dim, learning_rate=1e-4, _if_use_per=False, gpu_id=0, env_num=1):\n super().init(net_dim, state_dim, action_dim, learning_rate, _if_use_per, gpu_id)\n\n self.alpha_log = torch.tensor((-np.log(action_dim) * np.e,), dtype=torch.float32,\n requires_grad=True, device=self.device) # trainable parameter\n self.alpha_optim = torch.optim.Adam((self.alpha_log,), lr=learning_rate)\n self.target_entropy = np.log(action_dim)\n\n def select_action(self, state):\n states = torch.as_tensor((state,), dtype=torch.float32, device=self.device)\n actions = self.act.get_action(states)\n return actions.detach().cpu().numpy()[0]\n\n def explore_env(self, env, target_step):\n trajectory = list()\n\n state = self.state\n for _ in range(target_step):\n action = self.select_action(state)\n next_state, reward, done, _ = env.step(action)\n\n trajectory.append((state, (reward, done, *action)))\n state = env.reset() if done else next_state\n self.state = state\n return trajectory\n\n def update_net(self, buffer, batch_size, repeat_times, soft_update_tau):\n buffer.update_now_len()\n\n alpha = self.alpha_log.exp().detach()\n obj_critic = obj_actor = None\n for _ in range(int(buffer.now_len * repeat_times / batch_size)):\n '''objective of critic (loss function of critic)'''\n with torch.no_grad():\n reward, mask, action, state, next_s = buffer.sample_batch(batch_size)\n next_a, next_log_prob = self.act_target.get_action_logprob(next_s)\n next_q = torch.min(*self.cri_target.get_q1_q2(next_s, next_a))\n q_label = reward + mask * (next_q + next_log_prob * alpha)\n q1, q2 = self.cri.get_q1_q2(state, action)\n obj_critic = self.criterion(q1, q_label) + self.criterion(q2, q_label)\n self.optim_update(self.cri_optim, obj_critic)\n self.soft_update(self.cri_target, self.cri, soft_update_tau)\n\n '''objective of alpha (temperature parameter automatic adjustment)'''\n action_pg, log_prob = self.act.get_action_logprob(state) # policy gradient\n obj_alpha = (self.alpha_log * (log_prob - self.target_entropy).detach()).mean()\n self.optim_update(self.alpha_optim, obj_alpha)\n\n '''objective of actor'''\n alpha = self.alpha_log.exp().detach()\n with torch.no_grad():\n self.alpha_log[:] = self.alpha_log.clamp(-20, 2)\n obj_actor = -(torch.min(*self.cri_target.get_q1_q2(state, action_pg)) + log_prob * alpha).mean()\n self.optim_update(self.act_optim, obj_actor)\n\n self.soft_update(self.act_target, self.act, soft_update_tau)\n\n return obj_critic.item(), obj_actor.item(), alpha.item()\n\n\nclass AgentPPO(AgentBase):\n def __init__(self):\n super().__init__()\n self.ClassCri = CriticAdv\n self.ClassAct = ActorPPO\n\n self.if_off_policy = False\n self.ratio_clip = 0.2 # ratio.clamp(1 - clip, 1 + clip)\n self.lambda_entropy = 0.02 # could be 0.01~0.05\n self.lambda_gae_adv = 0.98 # could be 0.95~0.99, GAE (Generalized Advantage Estimation. ICLR.2016.)\n self.get_reward_sum = None # self.get_reward_sum_gae if if_use_gae else self.get_reward_sum_raw\n\n def init(self, net_dim, state_dim, action_dim, learning_rate=1e-4, if_use_gae=False, gpu_id=0, env_num=1):\n super().init(net_dim, state_dim, action_dim, learning_rate, if_use_gae, gpu_id)\n self.trajectory_list = list()\n self.get_reward_sum = self.get_reward_sum_gae if if_use_gae else self.get_reward_sum_raw\n\n def select_action(self, state):\n states = torch.as_tensor((state,), dtype=torch.float32, device=self.device)\n actions, noises = self.act.get_action(states)\n return actions[0].detach().cpu().numpy(), noises[0].detach().cpu().numpy()\n\n def explore_env(self, env, target_step):\n state = self.state\n\n trajectory_temp = list()\n last_done = 0\n for i in range(target_step):\n action, noise = self.select_action(state)\n next_state, reward, done, _ = env.step(np.tanh(action))\n trajectory_temp.append((state, reward, done, action, noise))\n if done:\n state = env.reset()\n last_done = i\n else:\n state = next_state\n self.state = state\n\n '''splice list'''\n trajectory_list = self.trajectory_list + trajectory_temp[:last_done + 1]\n self.trajectory_list = trajectory_temp[last_done:]\n return trajectory_list\n\n def update_net(self, buffer, batch_size, repeat_times, soft_update_tau):\n with torch.no_grad():\n buf_len = buffer[0].shape[0]\n buf_state, buf_action, buf_noise, buf_reward, buf_mask = [ten.to(self.device) for ten in buffer]\n # (ten_state, ten_action, ten_noise, ten_reward, ten_mask) = buffer\n\n '''get buf_r_sum, buf_logprob'''\n bs = 2 ** 10 # set a smaller 'BatchSize' when out of GPU memory.\n buf_value = [self.cri_target(buf_state[i:i + bs]) for i in range(0, buf_len, bs)]\n buf_value = torch.cat(buf_value, dim=0)\n buf_logprob = self.act.get_old_logprob(buf_action, buf_noise)\n\n buf_r_sum, buf_advantage = self.get_reward_sum(buf_len, buf_reward, buf_mask, buf_value) # detach()\n buf_advantage = (buf_advantage - buf_advantage.mean()) / (buf_advantage.std() + 1e-5)\n del buf_noise, buffer[:]\n\n '''PPO: Surrogate objective of Trust Region'''\n obj_critic = obj_actor = None\n for _ in range(int(buf_len / batch_size * repeat_times)):\n indices = torch.randint(buf_len, size=(batch_size,), requires_grad=False, device=self.device)\n\n state = buf_state[indices]\n action = buf_action[indices]\n r_sum = buf_r_sum[indices]\n logprob = buf_logprob[indices]\n advantage = buf_advantage[indices]\n\n new_logprob, obj_entropy = self.act.get_logprob_entropy(state, action) # it is obj_actor\n ratio = (new_logprob - logprob.detach()).exp()\n surrogate1 = advantage * ratio\n surrogate2 = advantage * ratio.clamp(1 - self.ratio_clip, 1 + self.ratio_clip)\n obj_surrogate = -torch.min(surrogate1, surrogate2).mean()\n obj_actor = obj_surrogate + obj_entropy * self.lambda_entropy\n self.optim_update(self.act_optim, obj_actor)\n\n value = self.cri(state).squeeze(1) # critic network predicts the reward_sum (Q value) of state\n obj_critic = self.criterion(value, r_sum) / (r_sum.std() + 1e-6)\n self.optim_update(self.cri_optim, obj_critic)\n self.soft_update(self.cri_target, self.cri, soft_update_tau) if self.cri_target is not self.cri else None\n\n a_std_log = getattr(self.act, 'a_std_log', torch.zeros(1))\n return obj_critic.item(), obj_actor.item(), a_std_log.mean().item() # logging_tuple\n\n def get_reward_sum_raw(self, buf_len, buf_reward, buf_mask, buf_value) -> (torch.Tensor, torch.Tensor):\n buf_r_sum = torch.empty(buf_len, dtype=torch.float32, device=self.device) # reward sum\n\n pre_r_sum = 0\n for i in range(buf_len - 1, -1, -1):\n buf_r_sum[i] = buf_reward[i] + buf_mask[i] * pre_r_sum\n pre_r_sum = buf_r_sum[i]\n buf_advantage = buf_r_sum - (buf_mask * buf_value[:, 0])\n return buf_r_sum, buf_advantage\n\n def get_reward_sum_gae(self, buf_len, ten_reward, ten_mask, ten_value) -> (torch.Tensor, torch.Tensor):\n buf_r_sum = torch.empty(buf_len, dtype=torch.float32, device=self.device) # old policy value\n buf_advantage = torch.empty(buf_len, dtype=torch.float32, device=self.device) # advantage value\n\n pre_r_sum = 0\n pre_advantage = 0 # advantage value of previous step\n for i in range(buf_len - 1, -1, -1):\n buf_r_sum[i] = ten_reward[i] + ten_mask[i] * pre_r_sum\n pre_r_sum = buf_r_sum[i]\n buf_advantage[i] = ten_reward[i] + ten_mask[i] * (pre_advantage - ten_value[i]) # fix a bug here\n pre_advantage = ten_value[i] + buf_advantage[i] * self.lambda_gae_adv\n return buf_r_sum, buf_advantage\n\n\nclass AgentDiscretePPO(AgentPPO):\n def __init__(self):\n super().__init__()\n self.ClassAct = ActorDiscretePPO\n\n def explore_env(self, env, target_step):\n state = self.state\n\n trajectory_temp = list()\n last_done = 0\n for i in range(target_step):\n # action, noise = self.select_action(state)\n # next_state, reward, done, _ = env.step(np.tanh(action))\n action, a_prob = self.select_action(state) # different from `action, noise`\n a_int = int(action) # different\n next_state, reward, done, _ = env.step(a_int) # different from `np.tanh(action)`\n trajectory_temp.append((state, reward, done, a_int, a_prob))\n if done:\n state = env.reset()\n last_done = i\n else:\n state = next_state\n self.state = state\n\n '''splice list'''\n trajectory_list = self.trajectory_list + trajectory_temp[:last_done + 1]\n self.trajectory_list = trajectory_temp[last_done:]\n return trajectory_list\n\n\nclass ReplayBuffer:\n def __init__(self, max_len, state_dim, action_dim, gpu_id=0):\n self.now_len = 0\n self.next_idx = 0\n self.if_full = False\n self.max_len = max_len\n self.data_type = torch.float32\n self.action_dim = action_dim\n self.device = torch.device(f\"cuda:{gpu_id}\" if (torch.cuda.is_available() and (gpu_id >= 0)) else \"cpu\")\n\n other_dim = 1 + 1 + self.action_dim\n self.buf_other = torch.empty((max_len, other_dim), dtype=torch.float32, device=self.device)\n\n if isinstance(state_dim, int): # state is pixel\n self.buf_state = torch.empty((max_len, state_dim), dtype=torch.float32, device=self.device)\n elif isinstance(state_dim, tuple):\n self.buf_state = torch.empty((max_len, *state_dim), dtype=torch.uint8, device=self.device)\n else:\n raise ValueError('state_dim')\n\n def extend_buffer(self, state, other): # CPU array to CPU array\n size = len(other)\n next_idx = self.next_idx + size\n\n if next_idx > self.max_len:\n self.buf_state[self.next_idx:self.max_len] = state[:self.max_len - self.next_idx]\n self.buf_other[self.next_idx:self.max_len] = other[:self.max_len - self.next_idx]\n self.if_full = True\n\n next_idx = next_idx - self.max_len\n self.buf_state[0:next_idx] = state[-next_idx:]\n self.buf_other[0:next_idx] = other[-next_idx:]\n else:\n self.buf_state[self.next_idx:next_idx] = state\n self.buf_other[self.next_idx:next_idx] = other\n self.next_idx = next_idx\n\n def sample_batch(self, batch_size) -> tuple:\n indices = rd.randint(self.now_len - 1, size=batch_size)\n r_m_a = self.buf_other[indices]\n return (r_m_a[:, 0:1],\n r_m_a[:, 1:2],\n r_m_a[:, 2:],\n self.buf_state[indices],\n self.buf_state[indices + 1])\n\n def update_now_len(self):\n self.now_len = self.max_len if self.if_full else self.next_idx\n\n def save_or_load_history(self, cwd, if_save, buffer_id=0):\n save_path = f\"{cwd}/replay_{buffer_id}.npz\"\n\n if if_save:\n self.update_now_len()\n state_dim = self.buf_state.shape[1]\n other_dim = self.buf_other.shape[1]\n buf_state = np.empty((self.max_len, state_dim), dtype=np.float16) # sometimes np.uint8\n buf_other = np.empty((self.max_len, other_dim), dtype=np.float16)\n\n temp_len = self.max_len - self.now_len\n buf_state[0:temp_len] = self.buf_state[self.now_len:self.max_len].detach().cpu().numpy()\n buf_other[0:temp_len] = self.buf_other[self.now_len:self.max_len].detach().cpu().numpy()\n\n buf_state[temp_len:] = self.buf_state[:self.now_len].detach().cpu().numpy()\n buf_other[temp_len:] = self.buf_other[:self.now_len].detach().cpu().numpy()\n\n np.savez_compressed(save_path, buf_state=buf_state, buf_other=buf_other)\n print(f\"| ReplayBuffer save in: {save_path}\")\n elif os.path.isfile(save_path):\n buf_dict = np.load(save_path)\n buf_state = buf_dict['buf_state']\n buf_other = buf_dict['buf_other']\n\n buf_state = torch.as_tensor(buf_state, dtype=torch.float32, device=self.device)\n buf_other = torch.as_tensor(buf_other, dtype=torch.float32, device=self.device)\n self.extend_buffer(buf_state, buf_other)\n self.update_now_len()\n print(f\"| ReplayBuffer load: {save_path}\")\n"
] |
[
[
"numpy.random.rand",
"numpy.random.choice",
"numpy.random.randint"
]
] |
andrekwr/numpy
|
[
"e564fcbecfb0b589e224e6e66e8894105a46aedf"
] |
[
"numpy/lib/tests/test_function_base.py"
] |
[
"import operator\nimport warnings\nimport sys\nimport decimal\nfrom fractions import Fraction\nimport math\nimport pytest\nimport hypothesis\nfrom hypothesis.extra.numpy import arrays\nimport hypothesis.strategies as st\n\n\nimport numpy as np\nfrom numpy import ma\nfrom numpy.testing import (\n assert_, assert_equal, assert_array_equal, assert_almost_equal,\n assert_array_almost_equal, assert_raises, assert_allclose, IS_PYPY,\n assert_warns, assert_raises_regex, suppress_warnings, HAS_REFCOUNT,\n )\nimport numpy.lib.function_base as nfb\nfrom numpy.random import rand\nfrom numpy.lib import (\n add_newdoc_ufunc, angle, average, bartlett, blackman, corrcoef, cov,\n delete, diff, digitize, extract, flipud, gradient, hamming, hanning,\n i0, insert, interp, kaiser, meshgrid, msort, piecewise, place, rot90,\n select, setxor1d, sinc, trapz, trim_zeros, unwrap, unique, vectorize\n )\n\n\ndef get_mat(n):\n data = np.arange(n)\n data = np.add.outer(data, data)\n return data\n\n\ndef _make_complex(real, imag):\n \"\"\"\n Like real + 1j * imag, but behaves as expected when imag contains non-finite\n values\n \"\"\"\n ret = np.zeros(np.broadcast(real, imag).shape, np.complex_)\n ret.real = real\n ret.imag = imag\n return ret\n\n\nclass TestRot90:\n def test_basic(self):\n assert_raises(ValueError, rot90, np.ones(4))\n assert_raises(ValueError, rot90, np.ones((2,2,2)), axes=(0,1,2))\n assert_raises(ValueError, rot90, np.ones((2,2)), axes=(0,2))\n assert_raises(ValueError, rot90, np.ones((2,2)), axes=(1,1))\n assert_raises(ValueError, rot90, np.ones((2,2,2)), axes=(-2,1))\n\n a = [[0, 1, 2],\n [3, 4, 5]]\n b1 = [[2, 5],\n [1, 4],\n [0, 3]]\n b2 = [[5, 4, 3],\n [2, 1, 0]]\n b3 = [[3, 0],\n [4, 1],\n [5, 2]]\n b4 = [[0, 1, 2],\n [3, 4, 5]]\n\n for k in range(-3, 13, 4):\n assert_equal(rot90(a, k=k), b1)\n for k in range(-2, 13, 4):\n assert_equal(rot90(a, k=k), b2)\n for k in range(-1, 13, 4):\n assert_equal(rot90(a, k=k), b3)\n for k in range(0, 13, 4):\n assert_equal(rot90(a, k=k), b4)\n\n assert_equal(rot90(rot90(a, axes=(0,1)), axes=(1,0)), a)\n assert_equal(rot90(a, k=1, axes=(1,0)), rot90(a, k=-1, axes=(0,1)))\n\n def test_axes(self):\n a = np.ones((50, 40, 3))\n assert_equal(rot90(a).shape, (40, 50, 3))\n assert_equal(rot90(a, axes=(0,2)), rot90(a, axes=(0,-1)))\n assert_equal(rot90(a, axes=(1,2)), rot90(a, axes=(-2,-1)))\n\n def test_rotation_axes(self):\n a = np.arange(8).reshape((2,2,2))\n\n a_rot90_01 = [[[2, 3],\n [6, 7]],\n [[0, 1],\n [4, 5]]]\n a_rot90_12 = [[[1, 3],\n [0, 2]],\n [[5, 7],\n [4, 6]]]\n a_rot90_20 = [[[4, 0],\n [6, 2]],\n [[5, 1],\n [7, 3]]]\n a_rot90_10 = [[[4, 5],\n [0, 1]],\n [[6, 7],\n [2, 3]]]\n\n assert_equal(rot90(a, axes=(0, 1)), a_rot90_01)\n assert_equal(rot90(a, axes=(1, 0)), a_rot90_10)\n assert_equal(rot90(a, axes=(1, 2)), a_rot90_12)\n\n for k in range(1,5):\n assert_equal(rot90(a, k=k, axes=(2, 0)),\n rot90(a_rot90_20, k=k-1, axes=(2, 0)))\n\n\nclass TestFlip:\n\n def test_axes(self):\n assert_raises(np.AxisError, np.flip, np.ones(4), axis=1)\n assert_raises(np.AxisError, np.flip, np.ones((4, 4)), axis=2)\n assert_raises(np.AxisError, np.flip, np.ones((4, 4)), axis=-3)\n assert_raises(np.AxisError, np.flip, np.ones((4, 4)), axis=(0, 3))\n\n def test_basic_lr(self):\n a = get_mat(4)\n b = a[:, ::-1]\n assert_equal(np.flip(a, 1), b)\n a = [[0, 1, 2],\n [3, 4, 5]]\n b = [[2, 1, 0],\n [5, 4, 3]]\n assert_equal(np.flip(a, 1), b)\n\n def test_basic_ud(self):\n a = get_mat(4)\n b = a[::-1, :]\n assert_equal(np.flip(a, 0), b)\n a = [[0, 1, 2],\n [3, 4, 5]]\n b = [[3, 4, 5],\n [0, 1, 2]]\n assert_equal(np.flip(a, 0), b)\n\n def test_3d_swap_axis0(self):\n a = np.array([[[0, 1],\n [2, 3]],\n [[4, 5],\n [6, 7]]])\n\n b = np.array([[[4, 5],\n [6, 7]],\n [[0, 1],\n [2, 3]]])\n\n assert_equal(np.flip(a, 0), b)\n\n def test_3d_swap_axis1(self):\n a = np.array([[[0, 1],\n [2, 3]],\n [[4, 5],\n [6, 7]]])\n\n b = np.array([[[2, 3],\n [0, 1]],\n [[6, 7],\n [4, 5]]])\n\n assert_equal(np.flip(a, 1), b)\n\n def test_3d_swap_axis2(self):\n a = np.array([[[0, 1],\n [2, 3]],\n [[4, 5],\n [6, 7]]])\n\n b = np.array([[[1, 0],\n [3, 2]],\n [[5, 4],\n [7, 6]]])\n\n assert_equal(np.flip(a, 2), b)\n\n def test_4d(self):\n a = np.arange(2 * 3 * 4 * 5).reshape(2, 3, 4, 5)\n for i in range(a.ndim):\n assert_equal(np.flip(a, i),\n np.flipud(a.swapaxes(0, i)).swapaxes(i, 0))\n\n def test_default_axis(self):\n a = np.array([[1, 2, 3],\n [4, 5, 6]])\n b = np.array([[6, 5, 4],\n [3, 2, 1]])\n assert_equal(np.flip(a), b)\n\n def test_multiple_axes(self):\n a = np.array([[[0, 1],\n [2, 3]],\n [[4, 5],\n [6, 7]]])\n\n assert_equal(np.flip(a, axis=()), a)\n\n b = np.array([[[5, 4],\n [7, 6]],\n [[1, 0],\n [3, 2]]])\n\n assert_equal(np.flip(a, axis=(0, 2)), b)\n\n c = np.array([[[3, 2],\n [1, 0]],\n [[7, 6],\n [5, 4]]])\n\n assert_equal(np.flip(a, axis=(1, 2)), c)\n\n\nclass TestAny:\n\n def test_basic(self):\n y1 = [0, 0, 1, 0]\n y2 = [0, 0, 0, 0]\n y3 = [1, 0, 1, 0]\n assert_(np.any(y1))\n assert_(np.any(y3))\n assert_(not np.any(y2))\n\n def test_nd(self):\n y1 = [[0, 0, 0], [0, 1, 0], [1, 1, 0]]\n assert_(np.any(y1))\n assert_array_equal(np.sometrue(y1, axis=0), [1, 1, 0])\n assert_array_equal(np.sometrue(y1, axis=1), [0, 1, 1])\n\n\nclass TestAll:\n\n def test_basic(self):\n y1 = [0, 1, 1, 0]\n y2 = [0, 0, 0, 0]\n y3 = [1, 1, 1, 1]\n assert_(not np.all(y1))\n assert_(np.all(y3))\n assert_(not np.all(y2))\n assert_(np.all(~np.array(y2)))\n\n def test_nd(self):\n y1 = [[0, 0, 1], [0, 1, 1], [1, 1, 1]]\n assert_(not np.all(y1))\n assert_array_equal(np.alltrue(y1, axis=0), [0, 0, 1])\n assert_array_equal(np.alltrue(y1, axis=1), [0, 0, 1])\n\n\nclass TestCopy:\n\n def test_basic(self):\n a = np.array([[1, 2], [3, 4]])\n a_copy = np.copy(a)\n assert_array_equal(a, a_copy)\n a_copy[0, 0] = 10\n assert_equal(a[0, 0], 1)\n assert_equal(a_copy[0, 0], 10)\n\n def test_order(self):\n # It turns out that people rely on np.copy() preserving order by\n # default; changing this broke scikit-learn:\n # github.com/scikit-learn/scikit-learn/commit/7842748cf777412c506a8c0ed28090711d3a3783 # noqa\n a = np.array([[1, 2], [3, 4]])\n assert_(a.flags.c_contiguous)\n assert_(not a.flags.f_contiguous)\n a_fort = np.array([[1, 2], [3, 4]], order=\"F\")\n assert_(not a_fort.flags.c_contiguous)\n assert_(a_fort.flags.f_contiguous)\n a_copy = np.copy(a)\n assert_(a_copy.flags.c_contiguous)\n assert_(not a_copy.flags.f_contiguous)\n a_fort_copy = np.copy(a_fort)\n assert_(not a_fort_copy.flags.c_contiguous)\n assert_(a_fort_copy.flags.f_contiguous)\n\n def test_subok(self):\n mx = ma.ones(5)\n assert_(not ma.isMaskedArray(np.copy(mx, subok=False)))\n assert_(ma.isMaskedArray(np.copy(mx, subok=True)))\n # Default behavior\n assert_(not ma.isMaskedArray(np.copy(mx)))\n\n\nclass TestAverage:\n\n def test_basic(self):\n y1 = np.array([1, 2, 3])\n assert_(average(y1, axis=0) == 2.)\n y2 = np.array([1., 2., 3.])\n assert_(average(y2, axis=0) == 2.)\n y3 = [0., 0., 0.]\n assert_(average(y3, axis=0) == 0.)\n\n y4 = np.ones((4, 4))\n y4[0, 1] = 0\n y4[1, 0] = 2\n assert_almost_equal(y4.mean(0), average(y4, 0))\n assert_almost_equal(y4.mean(1), average(y4, 1))\n\n y5 = rand(5, 5)\n assert_almost_equal(y5.mean(0), average(y5, 0))\n assert_almost_equal(y5.mean(1), average(y5, 1))\n\n def test_weights(self):\n y = np.arange(10)\n w = np.arange(10)\n actual = average(y, weights=w)\n desired = (np.arange(10) ** 2).sum() * 1. / np.arange(10).sum()\n assert_almost_equal(actual, desired)\n\n y1 = np.array([[1, 2, 3], [4, 5, 6]])\n w0 = [1, 2]\n actual = average(y1, weights=w0, axis=0)\n desired = np.array([3., 4., 5.])\n assert_almost_equal(actual, desired)\n\n w1 = [0, 0, 1]\n actual = average(y1, weights=w1, axis=1)\n desired = np.array([3., 6.])\n assert_almost_equal(actual, desired)\n\n # This should raise an error. Can we test for that ?\n # assert_equal(average(y1, weights=w1), 9./2.)\n\n # 2D Case\n w2 = [[0, 0, 1], [0, 0, 2]]\n desired = np.array([3., 6.])\n assert_array_equal(average(y1, weights=w2, axis=1), desired)\n assert_equal(average(y1, weights=w2), 5.)\n\n y3 = rand(5).astype(np.float32)\n w3 = rand(5).astype(np.float64)\n\n assert_(np.average(y3, weights=w3).dtype == np.result_type(y3, w3))\n\n def test_returned(self):\n y = np.array([[1, 2, 3], [4, 5, 6]])\n\n # No weights\n avg, scl = average(y, returned=True)\n assert_equal(scl, 6.)\n\n avg, scl = average(y, 0, returned=True)\n assert_array_equal(scl, np.array([2., 2., 2.]))\n\n avg, scl = average(y, 1, returned=True)\n assert_array_equal(scl, np.array([3., 3.]))\n\n # With weights\n w0 = [1, 2]\n avg, scl = average(y, weights=w0, axis=0, returned=True)\n assert_array_equal(scl, np.array([3., 3., 3.]))\n\n w1 = [1, 2, 3]\n avg, scl = average(y, weights=w1, axis=1, returned=True)\n assert_array_equal(scl, np.array([6., 6.]))\n\n w2 = [[0, 0, 1], [1, 2, 3]]\n avg, scl = average(y, weights=w2, axis=1, returned=True)\n assert_array_equal(scl, np.array([1., 6.]))\n\n def test_subclasses(self):\n class subclass(np.ndarray):\n pass\n a = np.array([[1,2],[3,4]]).view(subclass)\n w = np.array([[1,2],[3,4]]).view(subclass)\n\n assert_equal(type(np.average(a)), subclass)\n assert_equal(type(np.average(a, weights=w)), subclass)\n\n def test_upcasting(self):\n typs = [('i4', 'i4', 'f8'), ('i4', 'f4', 'f8'), ('f4', 'i4', 'f8'),\n ('f4', 'f4', 'f4'), ('f4', 'f8', 'f8')]\n for at, wt, rt in typs:\n a = np.array([[1,2],[3,4]], dtype=at)\n w = np.array([[1,2],[3,4]], dtype=wt)\n assert_equal(np.average(a, weights=w).dtype, np.dtype(rt))\n\n def test_object_dtype(self):\n a = np.array([decimal.Decimal(x) for x in range(10)])\n w = np.array([decimal.Decimal(1) for _ in range(10)])\n w /= w.sum()\n assert_almost_equal(a.mean(0), average(a, weights=w))\n\nclass TestSelect:\n choices = [np.array([1, 2, 3]),\n np.array([4, 5, 6]),\n np.array([7, 8, 9])]\n conditions = [np.array([False, False, False]),\n np.array([False, True, False]),\n np.array([False, False, True])]\n\n def _select(self, cond, values, default=0):\n output = []\n for m in range(len(cond)):\n output += [V[m] for V, C in zip(values, cond) if C[m]] or [default]\n return output\n\n def test_basic(self):\n choices = self.choices\n conditions = self.conditions\n assert_array_equal(select(conditions, choices, default=15),\n self._select(conditions, choices, default=15))\n\n assert_equal(len(choices), 3)\n assert_equal(len(conditions), 3)\n\n def test_broadcasting(self):\n conditions = [np.array(True), np.array([False, True, False])]\n choices = [1, np.arange(12).reshape(4, 3)]\n assert_array_equal(select(conditions, choices), np.ones((4, 3)))\n # default can broadcast too:\n assert_equal(select([True], [0], default=[0]).shape, (1,))\n\n def test_return_dtype(self):\n assert_equal(select(self.conditions, self.choices, 1j).dtype,\n np.complex_)\n # But the conditions need to be stronger then the scalar default\n # if it is scalar.\n choices = [choice.astype(np.int8) for choice in self.choices]\n assert_equal(select(self.conditions, choices).dtype, np.int8)\n\n d = np.array([1, 2, 3, np.nan, 5, 7])\n m = np.isnan(d)\n assert_equal(select([m], [d]), [0, 0, 0, np.nan, 0, 0])\n\n def test_deprecated_empty(self):\n assert_raises(ValueError, select, [], [], 3j)\n assert_raises(ValueError, select, [], [])\n\n def test_non_bool_deprecation(self):\n choices = self.choices\n conditions = self.conditions[:]\n conditions[0] = conditions[0].astype(np.int_)\n assert_raises(TypeError, select, conditions, choices)\n conditions[0] = conditions[0].astype(np.uint8)\n assert_raises(TypeError, select, conditions, choices)\n assert_raises(TypeError, select, conditions, choices)\n\n def test_many_arguments(self):\n # This used to be limited by NPY_MAXARGS == 32\n conditions = [np.array([False])] * 100\n choices = [np.array([1])] * 100\n select(conditions, choices)\n\n\nclass TestInsert:\n\n def test_basic(self):\n a = [1, 2, 3]\n assert_equal(insert(a, 0, 1), [1, 1, 2, 3])\n assert_equal(insert(a, 3, 1), [1, 2, 3, 1])\n assert_equal(insert(a, [1, 1, 1], [1, 2, 3]), [1, 1, 2, 3, 2, 3])\n assert_equal(insert(a, 1, [1, 2, 3]), [1, 1, 2, 3, 2, 3])\n assert_equal(insert(a, [1, -1, 3], 9), [1, 9, 2, 9, 3, 9])\n assert_equal(insert(a, slice(-1, None, -1), 9), [9, 1, 9, 2, 9, 3])\n assert_equal(insert(a, [-1, 1, 3], [7, 8, 9]), [1, 8, 2, 7, 3, 9])\n b = np.array([0, 1], dtype=np.float64)\n assert_equal(insert(b, 0, b[0]), [0., 0., 1.])\n assert_equal(insert(b, [], []), b)\n # Bools will be treated differently in the future:\n # assert_equal(insert(a, np.array([True]*4), 9), [9, 1, 9, 2, 9, 3, 9])\n with warnings.catch_warnings(record=True) as w:\n warnings.filterwarnings('always', '', FutureWarning)\n assert_equal(\n insert(a, np.array([True] * 4), 9), [1, 9, 9, 9, 9, 2, 3])\n assert_(w[0].category is FutureWarning)\n\n def test_multidim(self):\n a = [[1, 1, 1]]\n r = [[2, 2, 2],\n [1, 1, 1]]\n assert_equal(insert(a, 0, [1]), [1, 1, 1, 1])\n assert_equal(insert(a, 0, [2, 2, 2], axis=0), r)\n assert_equal(insert(a, 0, 2, axis=0), r)\n assert_equal(insert(a, 2, 2, axis=1), [[1, 1, 2, 1]])\n\n a = np.array([[1, 1], [2, 2], [3, 3]])\n b = np.arange(1, 4).repeat(3).reshape(3, 3)\n c = np.concatenate(\n (a[:, 0:1], np.arange(1, 4).repeat(3).reshape(3, 3).T,\n a[:, 1:2]), axis=1)\n assert_equal(insert(a, [1], [[1], [2], [3]], axis=1), b)\n assert_equal(insert(a, [1], [1, 2, 3], axis=1), c)\n # scalars behave differently, in this case exactly opposite:\n assert_equal(insert(a, 1, [1, 2, 3], axis=1), b)\n assert_equal(insert(a, 1, [[1], [2], [3]], axis=1), c)\n\n a = np.arange(4).reshape(2, 2)\n assert_equal(insert(a[:, :1], 1, a[:, 1], axis=1), a)\n assert_equal(insert(a[:1,:], 1, a[1,:], axis=0), a)\n\n # negative axis value\n a = np.arange(24).reshape((2, 3, 4))\n assert_equal(insert(a, 1, a[:,:, 3], axis=-1),\n insert(a, 1, a[:,:, 3], axis=2))\n assert_equal(insert(a, 1, a[:, 2,:], axis=-2),\n insert(a, 1, a[:, 2,:], axis=1))\n\n # invalid axis value\n assert_raises(np.AxisError, insert, a, 1, a[:, 2, :], axis=3)\n assert_raises(np.AxisError, insert, a, 1, a[:, 2, :], axis=-4)\n\n # negative axis value\n a = np.arange(24).reshape((2, 3, 4))\n assert_equal(insert(a, 1, a[:, :, 3], axis=-1),\n insert(a, 1, a[:, :, 3], axis=2))\n assert_equal(insert(a, 1, a[:, 2, :], axis=-2),\n insert(a, 1, a[:, 2, :], axis=1))\n\n def test_0d(self):\n a = np.array(1)\n with pytest.raises(np.AxisError):\n insert(a, [], 2, axis=0)\n with pytest.raises(TypeError):\n insert(a, [], 2, axis=\"nonsense\")\n\n def test_subclass(self):\n class SubClass(np.ndarray):\n pass\n a = np.arange(10).view(SubClass)\n assert_(isinstance(np.insert(a, 0, [0]), SubClass))\n assert_(isinstance(np.insert(a, [], []), SubClass))\n assert_(isinstance(np.insert(a, [0, 1], [1, 2]), SubClass))\n assert_(isinstance(np.insert(a, slice(1, 2), [1, 2]), SubClass))\n assert_(isinstance(np.insert(a, slice(1, -2, -1), []), SubClass))\n # This is an error in the future:\n a = np.array(1).view(SubClass)\n assert_(isinstance(np.insert(a, 0, [0]), SubClass))\n\n def test_index_array_copied(self):\n x = np.array([1, 1, 1])\n np.insert([0, 1, 2], x, [3, 4, 5])\n assert_equal(x, np.array([1, 1, 1]))\n\n def test_structured_array(self):\n a = np.array([(1, 'a'), (2, 'b'), (3, 'c')],\n dtype=[('foo', 'i'), ('bar', 'a1')])\n val = (4, 'd')\n b = np.insert(a, 0, val)\n assert_array_equal(b[0], np.array(val, dtype=b.dtype))\n val = [(4, 'd')] * 2\n b = np.insert(a, [0, 2], val)\n assert_array_equal(b[[0, 3]], np.array(val, dtype=b.dtype))\n\n def test_index_floats(self):\n with pytest.raises(IndexError):\n np.insert([0, 1, 2], np.array([1.0, 2.0]), [10, 20])\n with pytest.raises(IndexError):\n np.insert([0, 1, 2], np.array([], dtype=float), [])\n\n @pytest.mark.parametrize('idx', [4, -4])\n def test_index_out_of_bounds(self, idx):\n with pytest.raises(IndexError, match='out of bounds'):\n np.insert([0, 1, 2], [idx], [3, 4])\n\n\nclass TestAmax:\n\n def test_basic(self):\n a = [3, 4, 5, 10, -3, -5, 6.0]\n assert_equal(np.amax(a), 10.0)\n b = [[3, 6.0, 9.0],\n [4, 10.0, 5.0],\n [8, 3.0, 2.0]]\n assert_equal(np.amax(b, axis=0), [8.0, 10.0, 9.0])\n assert_equal(np.amax(b, axis=1), [9.0, 10.0, 8.0])\n\n\nclass TestAmin:\n\n def test_basic(self):\n a = [3, 4, 5, 10, -3, -5, 6.0]\n assert_equal(np.amin(a), -5.0)\n b = [[3, 6.0, 9.0],\n [4, 10.0, 5.0],\n [8, 3.0, 2.0]]\n assert_equal(np.amin(b, axis=0), [3.0, 3.0, 2.0])\n assert_equal(np.amin(b, axis=1), [3.0, 4.0, 2.0])\n\n\nclass TestPtp:\n\n def test_basic(self):\n a = np.array([3, 4, 5, 10, -3, -5, 6.0])\n assert_equal(a.ptp(axis=0), 15.0)\n b = np.array([[3, 6.0, 9.0],\n [4, 10.0, 5.0],\n [8, 3.0, 2.0]])\n assert_equal(b.ptp(axis=0), [5.0, 7.0, 7.0])\n assert_equal(b.ptp(axis=-1), [6.0, 6.0, 6.0])\n\n assert_equal(b.ptp(axis=0, keepdims=True), [[5.0, 7.0, 7.0]])\n assert_equal(b.ptp(axis=(0,1), keepdims=True), [[8.0]])\n\n\nclass TestCumsum:\n\n def test_basic(self):\n ba = [1, 2, 10, 11, 6, 5, 4]\n ba2 = [[1, 2, 3, 4], [5, 6, 7, 9], [10, 3, 4, 5]]\n for ctype in [np.int8, np.uint8, np.int16, np.uint16, np.int32,\n np.uint32, np.float32, np.float64, np.complex64,\n np.complex128]:\n a = np.array(ba, ctype)\n a2 = np.array(ba2, ctype)\n\n tgt = np.array([1, 3, 13, 24, 30, 35, 39], ctype)\n assert_array_equal(np.cumsum(a, axis=0), tgt)\n\n tgt = np.array(\n [[1, 2, 3, 4], [6, 8, 10, 13], [16, 11, 14, 18]], ctype)\n assert_array_equal(np.cumsum(a2, axis=0), tgt)\n\n tgt = np.array(\n [[1, 3, 6, 10], [5, 11, 18, 27], [10, 13, 17, 22]], ctype)\n assert_array_equal(np.cumsum(a2, axis=1), tgt)\n\n\nclass TestProd:\n\n def test_basic(self):\n ba = [1, 2, 10, 11, 6, 5, 4]\n ba2 = [[1, 2, 3, 4], [5, 6, 7, 9], [10, 3, 4, 5]]\n for ctype in [np.int16, np.uint16, np.int32, np.uint32,\n np.float32, np.float64, np.complex64, np.complex128]:\n a = np.array(ba, ctype)\n a2 = np.array(ba2, ctype)\n if ctype in ['1', 'b']:\n assert_raises(ArithmeticError, np.prod, a)\n assert_raises(ArithmeticError, np.prod, a2, 1)\n else:\n assert_equal(a.prod(axis=0), 26400)\n assert_array_equal(a2.prod(axis=0),\n np.array([50, 36, 84, 180], ctype))\n assert_array_equal(a2.prod(axis=-1),\n np.array([24, 1890, 600], ctype))\n\n\nclass TestCumprod:\n\n def test_basic(self):\n ba = [1, 2, 10, 11, 6, 5, 4]\n ba2 = [[1, 2, 3, 4], [5, 6, 7, 9], [10, 3, 4, 5]]\n for ctype in [np.int16, np.uint16, np.int32, np.uint32,\n np.float32, np.float64, np.complex64, np.complex128]:\n a = np.array(ba, ctype)\n a2 = np.array(ba2, ctype)\n if ctype in ['1', 'b']:\n assert_raises(ArithmeticError, np.cumprod, a)\n assert_raises(ArithmeticError, np.cumprod, a2, 1)\n assert_raises(ArithmeticError, np.cumprod, a)\n else:\n assert_array_equal(np.cumprod(a, axis=-1),\n np.array([1, 2, 20, 220,\n 1320, 6600, 26400], ctype))\n assert_array_equal(np.cumprod(a2, axis=0),\n np.array([[1, 2, 3, 4],\n [5, 12, 21, 36],\n [50, 36, 84, 180]], ctype))\n assert_array_equal(np.cumprod(a2, axis=-1),\n np.array([[1, 2, 6, 24],\n [5, 30, 210, 1890],\n [10, 30, 120, 600]], ctype))\n\n\nclass TestDiff:\n\n def test_basic(self):\n x = [1, 4, 6, 7, 12]\n out = np.array([3, 2, 1, 5])\n out2 = np.array([-1, -1, 4])\n out3 = np.array([0, 5])\n assert_array_equal(diff(x), out)\n assert_array_equal(diff(x, n=2), out2)\n assert_array_equal(diff(x, n=3), out3)\n\n x = [1.1, 2.2, 3.0, -0.2, -0.1]\n out = np.array([1.1, 0.8, -3.2, 0.1])\n assert_almost_equal(diff(x), out)\n\n x = [True, True, False, False]\n out = np.array([False, True, False])\n out2 = np.array([True, True])\n assert_array_equal(diff(x), out)\n assert_array_equal(diff(x, n=2), out2)\n\n def test_axis(self):\n x = np.zeros((10, 20, 30))\n x[:, 1::2, :] = 1\n exp = np.ones((10, 19, 30))\n exp[:, 1::2, :] = -1\n assert_array_equal(diff(x), np.zeros((10, 20, 29)))\n assert_array_equal(diff(x, axis=-1), np.zeros((10, 20, 29)))\n assert_array_equal(diff(x, axis=0), np.zeros((9, 20, 30)))\n assert_array_equal(diff(x, axis=1), exp)\n assert_array_equal(diff(x, axis=-2), exp)\n assert_raises(np.AxisError, diff, x, axis=3)\n assert_raises(np.AxisError, diff, x, axis=-4)\n\n x = np.array(1.11111111111, np.float64)\n assert_raises(ValueError, diff, x)\n\n def test_nd(self):\n x = 20 * rand(10, 20, 30)\n out1 = x[:, :, 1:] - x[:, :, :-1]\n out2 = out1[:, :, 1:] - out1[:, :, :-1]\n out3 = x[1:, :, :] - x[:-1, :, :]\n out4 = out3[1:, :, :] - out3[:-1, :, :]\n assert_array_equal(diff(x), out1)\n assert_array_equal(diff(x, n=2), out2)\n assert_array_equal(diff(x, axis=0), out3)\n assert_array_equal(diff(x, n=2, axis=0), out4)\n\n def test_n(self):\n x = list(range(3))\n assert_raises(ValueError, diff, x, n=-1)\n output = [diff(x, n=n) for n in range(1, 5)]\n expected = [[1, 1], [0], [], []]\n assert_(diff(x, n=0) is x)\n for n, (expected, out) in enumerate(zip(expected, output), start=1):\n assert_(type(out) is np.ndarray)\n assert_array_equal(out, expected)\n assert_equal(out.dtype, np.int_)\n assert_equal(len(out), max(0, len(x) - n))\n\n def test_times(self):\n x = np.arange('1066-10-13', '1066-10-16', dtype=np.datetime64)\n expected = [\n np.array([1, 1], dtype='timedelta64[D]'),\n np.array([0], dtype='timedelta64[D]'),\n ]\n expected.extend([np.array([], dtype='timedelta64[D]')] * 3)\n for n, exp in enumerate(expected, start=1):\n out = diff(x, n=n)\n assert_array_equal(out, exp)\n assert_equal(out.dtype, exp.dtype)\n\n def test_subclass(self):\n x = ma.array([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]],\n mask=[[False, False], [True, False],\n [False, True], [True, True], [False, False]])\n out = diff(x)\n assert_array_equal(out.data, [[1], [1], [1], [1], [1]])\n assert_array_equal(out.mask, [[False], [True],\n [True], [True], [False]])\n assert_(type(out) is type(x))\n\n out3 = diff(x, n=3)\n assert_array_equal(out3.data, [[], [], [], [], []])\n assert_array_equal(out3.mask, [[], [], [], [], []])\n assert_(type(out3) is type(x))\n\n def test_prepend(self):\n x = np.arange(5) + 1\n assert_array_equal(diff(x, prepend=0), np.ones(5))\n assert_array_equal(diff(x, prepend=[0]), np.ones(5))\n assert_array_equal(np.cumsum(np.diff(x, prepend=0)), x)\n assert_array_equal(diff(x, prepend=[-1, 0]), np.ones(6))\n\n x = np.arange(4).reshape(2, 2)\n result = np.diff(x, axis=1, prepend=0)\n expected = [[0, 1], [2, 1]]\n assert_array_equal(result, expected)\n result = np.diff(x, axis=1, prepend=[[0], [0]])\n assert_array_equal(result, expected)\n\n result = np.diff(x, axis=0, prepend=0)\n expected = [[0, 1], [2, 2]]\n assert_array_equal(result, expected)\n result = np.diff(x, axis=0, prepend=[[0, 0]])\n assert_array_equal(result, expected)\n\n assert_raises(ValueError, np.diff, x, prepend=np.zeros((3,3)))\n\n assert_raises(np.AxisError, diff, x, prepend=0, axis=3)\n\n def test_append(self):\n x = np.arange(5)\n result = diff(x, append=0)\n expected = [1, 1, 1, 1, -4]\n assert_array_equal(result, expected)\n result = diff(x, append=[0])\n assert_array_equal(result, expected)\n result = diff(x, append=[0, 2])\n expected = expected + [2]\n assert_array_equal(result, expected)\n\n x = np.arange(4).reshape(2, 2)\n result = np.diff(x, axis=1, append=0)\n expected = [[1, -1], [1, -3]]\n assert_array_equal(result, expected)\n result = np.diff(x, axis=1, append=[[0], [0]])\n assert_array_equal(result, expected)\n\n result = np.diff(x, axis=0, append=0)\n expected = [[2, 2], [-2, -3]]\n assert_array_equal(result, expected)\n result = np.diff(x, axis=0, append=[[0, 0]])\n assert_array_equal(result, expected)\n\n assert_raises(ValueError, np.diff, x, append=np.zeros((3,3)))\n\n assert_raises(np.AxisError, diff, x, append=0, axis=3)\n\n\nclass TestDelete:\n\n def setup(self):\n self.a = np.arange(5)\n self.nd_a = np.arange(5).repeat(2).reshape(1, 5, 2)\n\n def _check_inverse_of_slicing(self, indices):\n a_del = delete(self.a, indices)\n nd_a_del = delete(self.nd_a, indices, axis=1)\n msg = 'Delete failed for obj: %r' % indices\n assert_array_equal(setxor1d(a_del, self.a[indices, ]), self.a,\n err_msg=msg)\n xor = setxor1d(nd_a_del[0,:, 0], self.nd_a[0, indices, 0])\n assert_array_equal(xor, self.nd_a[0,:, 0], err_msg=msg)\n\n def test_slices(self):\n lims = [-6, -2, 0, 1, 2, 4, 5]\n steps = [-3, -1, 1, 3]\n for start in lims:\n for stop in lims:\n for step in steps:\n s = slice(start, stop, step)\n self._check_inverse_of_slicing(s)\n\n def test_fancy(self):\n self._check_inverse_of_slicing(np.array([[0, 1], [2, 1]]))\n with pytest.raises(IndexError):\n delete(self.a, [100])\n with pytest.raises(IndexError):\n delete(self.a, [-100])\n\n self._check_inverse_of_slicing([0, -1, 2, 2])\n\n self._check_inverse_of_slicing([True, False, False, True, False])\n\n # not legal, indexing with these would change the dimension\n with pytest.raises(ValueError):\n delete(self.a, True)\n with pytest.raises(ValueError):\n delete(self.a, False)\n\n # not enough items\n with pytest.raises(ValueError):\n delete(self.a, [False]*4)\n\n def test_single(self):\n self._check_inverse_of_slicing(0)\n self._check_inverse_of_slicing(-4)\n\n def test_0d(self):\n a = np.array(1)\n with pytest.raises(np.AxisError):\n delete(a, [], axis=0)\n with pytest.raises(TypeError):\n delete(a, [], axis=\"nonsense\")\n\n def test_subclass(self):\n class SubClass(np.ndarray):\n pass\n a = self.a.view(SubClass)\n assert_(isinstance(delete(a, 0), SubClass))\n assert_(isinstance(delete(a, []), SubClass))\n assert_(isinstance(delete(a, [0, 1]), SubClass))\n assert_(isinstance(delete(a, slice(1, 2)), SubClass))\n assert_(isinstance(delete(a, slice(1, -2)), SubClass))\n\n def test_array_order_preserve(self):\n # See gh-7113\n k = np.arange(10).reshape(2, 5, order='F')\n m = delete(k, slice(60, None), axis=1)\n\n # 'k' is Fortran ordered, and 'm' should have the\n # same ordering as 'k' and NOT become C ordered\n assert_equal(m.flags.c_contiguous, k.flags.c_contiguous)\n assert_equal(m.flags.f_contiguous, k.flags.f_contiguous)\n\n def test_index_floats(self):\n with pytest.raises(IndexError):\n np.delete([0, 1, 2], np.array([1.0, 2.0]))\n with pytest.raises(IndexError):\n np.delete([0, 1, 2], np.array([], dtype=float))\n\n\nclass TestGradient:\n\n def test_basic(self):\n v = [[1, 1], [3, 4]]\n x = np.array(v)\n dx = [np.array([[2., 3.], [2., 3.]]),\n np.array([[0., 0.], [1., 1.]])]\n assert_array_equal(gradient(x), dx)\n assert_array_equal(gradient(v), dx)\n\n def test_args(self):\n dx = np.cumsum(np.ones(5))\n dx_uneven = [1., 2., 5., 9., 11.]\n f_2d = np.arange(25).reshape(5, 5)\n\n # distances must be scalars or have size equal to gradient[axis]\n gradient(np.arange(5), 3.)\n gradient(np.arange(5), np.array(3.))\n gradient(np.arange(5), dx)\n # dy is set equal to dx because scalar\n gradient(f_2d, 1.5)\n gradient(f_2d, np.array(1.5))\n\n gradient(f_2d, dx_uneven, dx_uneven)\n # mix between even and uneven spaces and\n # mix between scalar and vector\n gradient(f_2d, dx, 2)\n\n # 2D but axis specified\n gradient(f_2d, dx, axis=1)\n\n # 2d coordinate arguments are not yet allowed\n assert_raises_regex(ValueError, '.*scalars or 1d',\n gradient, f_2d, np.stack([dx]*2, axis=-1), 1)\n\n def test_badargs(self):\n f_2d = np.arange(25).reshape(5, 5)\n x = np.cumsum(np.ones(5))\n\n # wrong sizes\n assert_raises(ValueError, gradient, f_2d, x, np.ones(2))\n assert_raises(ValueError, gradient, f_2d, 1, np.ones(2))\n assert_raises(ValueError, gradient, f_2d, np.ones(2), np.ones(2))\n # wrong number of arguments\n assert_raises(TypeError, gradient, f_2d, x)\n assert_raises(TypeError, gradient, f_2d, x, axis=(0,1))\n assert_raises(TypeError, gradient, f_2d, x, x, x)\n assert_raises(TypeError, gradient, f_2d, 1, 1, 1)\n assert_raises(TypeError, gradient, f_2d, x, x, axis=1)\n assert_raises(TypeError, gradient, f_2d, 1, 1, axis=1)\n\n def test_datetime64(self):\n # Make sure gradient() can handle special types like datetime64\n x = np.array(\n ['1910-08-16', '1910-08-11', '1910-08-10', '1910-08-12',\n '1910-10-12', '1910-12-12', '1912-12-12'],\n dtype='datetime64[D]')\n dx = np.array(\n [-5, -3, 0, 31, 61, 396, 731],\n dtype='timedelta64[D]')\n assert_array_equal(gradient(x), dx)\n assert_(dx.dtype == np.dtype('timedelta64[D]'))\n\n def test_masked(self):\n # Make sure that gradient supports subclasses like masked arrays\n x = np.ma.array([[1, 1], [3, 4]],\n mask=[[False, False], [False, False]])\n out = gradient(x)[0]\n assert_equal(type(out), type(x))\n # And make sure that the output and input don't have aliased mask\n # arrays\n assert_(x._mask is not out._mask)\n # Also check that edge_order=2 doesn't alter the original mask\n x2 = np.ma.arange(5)\n x2[2] = np.ma.masked\n np.gradient(x2, edge_order=2)\n assert_array_equal(x2.mask, [False, False, True, False, False])\n\n def test_second_order_accurate(self):\n # Testing that the relative numerical error is less that 3% for\n # this example problem. This corresponds to second order\n # accurate finite differences for all interior and boundary\n # points.\n x = np.linspace(0, 1, 10)\n dx = x[1] - x[0]\n y = 2 * x ** 3 + 4 * x ** 2 + 2 * x\n analytical = 6 * x ** 2 + 8 * x + 2\n num_error = np.abs((np.gradient(y, dx, edge_order=2) / analytical) - 1)\n assert_(np.all(num_error < 0.03) == True)\n\n # test with unevenly spaced\n np.random.seed(0)\n x = np.sort(np.random.random(10))\n y = 2 * x ** 3 + 4 * x ** 2 + 2 * x\n analytical = 6 * x ** 2 + 8 * x + 2\n num_error = np.abs((np.gradient(y, x, edge_order=2) / analytical) - 1)\n assert_(np.all(num_error < 0.03) == True)\n\n def test_spacing(self):\n f = np.array([0, 2., 3., 4., 5., 5.])\n f = np.tile(f, (6,1)) + f.reshape(-1, 1)\n x_uneven = np.array([0., 0.5, 1., 3., 5., 7.])\n x_even = np.arange(6.)\n\n fdx_even_ord1 = np.tile([2., 1.5, 1., 1., 0.5, 0.], (6,1))\n fdx_even_ord2 = np.tile([2.5, 1.5, 1., 1., 0.5, -0.5], (6,1))\n fdx_uneven_ord1 = np.tile([4., 3., 1.7, 0.5, 0.25, 0.], (6,1))\n fdx_uneven_ord2 = np.tile([5., 3., 1.7, 0.5, 0.25, -0.25], (6,1))\n\n # evenly spaced\n for edge_order, exp_res in [(1, fdx_even_ord1), (2, fdx_even_ord2)]:\n res1 = gradient(f, 1., axis=(0,1), edge_order=edge_order)\n res2 = gradient(f, x_even, x_even,\n axis=(0,1), edge_order=edge_order)\n res3 = gradient(f, x_even, x_even,\n axis=None, edge_order=edge_order)\n assert_array_equal(res1, res2)\n assert_array_equal(res2, res3)\n assert_almost_equal(res1[0], exp_res.T)\n assert_almost_equal(res1[1], exp_res)\n\n res1 = gradient(f, 1., axis=0, edge_order=edge_order)\n res2 = gradient(f, x_even, axis=0, edge_order=edge_order)\n assert_(res1.shape == res2.shape)\n assert_almost_equal(res2, exp_res.T)\n\n res1 = gradient(f, 1., axis=1, edge_order=edge_order)\n res2 = gradient(f, x_even, axis=1, edge_order=edge_order)\n assert_(res1.shape == res2.shape)\n assert_array_equal(res2, exp_res)\n\n # unevenly spaced\n for edge_order, exp_res in [(1, fdx_uneven_ord1), (2, fdx_uneven_ord2)]:\n res1 = gradient(f, x_uneven, x_uneven,\n axis=(0,1), edge_order=edge_order)\n res2 = gradient(f, x_uneven, x_uneven,\n axis=None, edge_order=edge_order)\n assert_array_equal(res1, res2)\n assert_almost_equal(res1[0], exp_res.T)\n assert_almost_equal(res1[1], exp_res)\n\n res1 = gradient(f, x_uneven, axis=0, edge_order=edge_order)\n assert_almost_equal(res1, exp_res.T)\n\n res1 = gradient(f, x_uneven, axis=1, edge_order=edge_order)\n assert_almost_equal(res1, exp_res)\n\n # mixed\n res1 = gradient(f, x_even, x_uneven, axis=(0,1), edge_order=1)\n res2 = gradient(f, x_uneven, x_even, axis=(1,0), edge_order=1)\n assert_array_equal(res1[0], res2[1])\n assert_array_equal(res1[1], res2[0])\n assert_almost_equal(res1[0], fdx_even_ord1.T)\n assert_almost_equal(res1[1], fdx_uneven_ord1)\n\n res1 = gradient(f, x_even, x_uneven, axis=(0,1), edge_order=2)\n res2 = gradient(f, x_uneven, x_even, axis=(1,0), edge_order=2)\n assert_array_equal(res1[0], res2[1])\n assert_array_equal(res1[1], res2[0])\n assert_almost_equal(res1[0], fdx_even_ord2.T)\n assert_almost_equal(res1[1], fdx_uneven_ord2)\n\n def test_specific_axes(self):\n # Testing that gradient can work on a given axis only\n v = [[1, 1], [3, 4]]\n x = np.array(v)\n dx = [np.array([[2., 3.], [2., 3.]]),\n np.array([[0., 0.], [1., 1.]])]\n assert_array_equal(gradient(x, axis=0), dx[0])\n assert_array_equal(gradient(x, axis=1), dx[1])\n assert_array_equal(gradient(x, axis=-1), dx[1])\n assert_array_equal(gradient(x, axis=(1, 0)), [dx[1], dx[0]])\n\n # test axis=None which means all axes\n assert_almost_equal(gradient(x, axis=None), [dx[0], dx[1]])\n # and is the same as no axis keyword given\n assert_almost_equal(gradient(x, axis=None), gradient(x))\n\n # test vararg order\n assert_array_equal(gradient(x, 2, 3, axis=(1, 0)),\n [dx[1]/2.0, dx[0]/3.0])\n # test maximal number of varargs\n assert_raises(TypeError, gradient, x, 1, 2, axis=1)\n\n assert_raises(np.AxisError, gradient, x, axis=3)\n assert_raises(np.AxisError, gradient, x, axis=-3)\n # assert_raises(TypeError, gradient, x, axis=[1,])\n\n def test_timedelta64(self):\n # Make sure gradient() can handle special types like timedelta64\n x = np.array(\n [-5, -3, 10, 12, 61, 321, 300],\n dtype='timedelta64[D]')\n dx = np.array(\n [2, 7, 7, 25, 154, 119, -21],\n dtype='timedelta64[D]')\n assert_array_equal(gradient(x), dx)\n assert_(dx.dtype == np.dtype('timedelta64[D]'))\n\n def test_inexact_dtypes(self):\n for dt in [np.float16, np.float32, np.float64]:\n # dtypes should not be promoted in a different way to what diff does\n x = np.array([1, 2, 3], dtype=dt)\n assert_equal(gradient(x).dtype, np.diff(x).dtype)\n\n def test_values(self):\n # needs at least 2 points for edge_order ==1\n gradient(np.arange(2), edge_order=1)\n # needs at least 3 points for edge_order ==1\n gradient(np.arange(3), edge_order=2)\n\n assert_raises(ValueError, gradient, np.arange(0), edge_order=1)\n assert_raises(ValueError, gradient, np.arange(0), edge_order=2)\n assert_raises(ValueError, gradient, np.arange(1), edge_order=1)\n assert_raises(ValueError, gradient, np.arange(1), edge_order=2)\n assert_raises(ValueError, gradient, np.arange(2), edge_order=2)\n\n @pytest.mark.parametrize('f_dtype', [np.uint8, np.uint16,\n np.uint32, np.uint64])\n def test_f_decreasing_unsigned_int(self, f_dtype):\n f = np.array([5, 4, 3, 2, 1], dtype=f_dtype)\n g = gradient(f)\n assert_array_equal(g, [-1]*len(f))\n\n @pytest.mark.parametrize('f_dtype', [np.int8, np.int16,\n np.int32, np.int64])\n def test_f_signed_int_big_jump(self, f_dtype):\n maxint = np.iinfo(f_dtype).max\n x = np.array([1, 3])\n f = np.array([-1, maxint], dtype=f_dtype)\n dfdx = gradient(f, x)\n assert_array_equal(dfdx, [(maxint + 1) // 2]*2)\n\n @pytest.mark.parametrize('x_dtype', [np.uint8, np.uint16,\n np.uint32, np.uint64])\n def test_x_decreasing_unsigned(self, x_dtype):\n x = np.array([3, 2, 1], dtype=x_dtype)\n f = np.array([0, 2, 4])\n dfdx = gradient(f, x)\n assert_array_equal(dfdx, [-2]*len(x))\n\n @pytest.mark.parametrize('x_dtype', [np.int8, np.int16,\n np.int32, np.int64])\n def test_x_signed_int_big_jump(self, x_dtype):\n minint = np.iinfo(x_dtype).min\n maxint = np.iinfo(x_dtype).max\n x = np.array([-1, maxint], dtype=x_dtype)\n f = np.array([minint // 2, 0])\n dfdx = gradient(f, x)\n assert_array_equal(dfdx, [0.5, 0.5])\n\n\nclass TestAngle:\n\n def test_basic(self):\n x = [1 + 3j, np.sqrt(2) / 2.0 + 1j * np.sqrt(2) / 2,\n 1, 1j, -1, -1j, 1 - 3j, -1 + 3j]\n y = angle(x)\n yo = [\n np.arctan(3.0 / 1.0),\n np.arctan(1.0), 0, np.pi / 2, np.pi, -np.pi / 2.0,\n -np.arctan(3.0 / 1.0), np.pi - np.arctan(3.0 / 1.0)]\n z = angle(x, deg=True)\n zo = np.array(yo) * 180 / np.pi\n assert_array_almost_equal(y, yo, 11)\n assert_array_almost_equal(z, zo, 11)\n\n def test_subclass(self):\n x = np.ma.array([1 + 3j, 1, np.sqrt(2)/2 * (1 + 1j)])\n x[1] = np.ma.masked\n expected = np.ma.array([np.arctan(3.0 / 1.0), 0, np.arctan(1.0)])\n expected[1] = np.ma.masked\n actual = angle(x)\n assert_equal(type(actual), type(expected))\n assert_equal(actual.mask, expected.mask)\n assert_equal(actual, expected)\n\n\nclass TestTrimZeros:\n\n a = np.array([0, 0, 1, 0, 2, 3, 4, 0])\n b = a.astype(float)\n c = a.astype(complex)\n d = a.astype(object)\n\n def values(self):\n attr_names = ('a', 'b', 'c', 'd')\n return (getattr(self, name) for name in attr_names)\n\n def test_basic(self):\n slc = np.s_[2:-1]\n for arr in self.values():\n res = trim_zeros(arr)\n assert_array_equal(res, arr[slc])\n\n def test_leading_skip(self):\n slc = np.s_[:-1]\n for arr in self.values():\n res = trim_zeros(arr, trim='b')\n assert_array_equal(res, arr[slc])\n\n def test_trailing_skip(self):\n slc = np.s_[2:]\n for arr in self.values():\n res = trim_zeros(arr, trim='F')\n assert_array_equal(res, arr[slc])\n\n def test_all_zero(self):\n for _arr in self.values():\n arr = np.zeros_like(_arr, dtype=_arr.dtype)\n\n res1 = trim_zeros(arr, trim='B')\n assert len(res1) == 0\n\n res2 = trim_zeros(arr, trim='f')\n assert len(res2) == 0\n\n def test_size_zero(self):\n arr = np.zeros(0)\n res = trim_zeros(arr)\n assert_array_equal(arr, res)\n\n @pytest.mark.parametrize(\n 'arr',\n [np.array([0, 2**62, 0]),\n np.array([0, 2**63, 0]),\n np.array([0, 2**64, 0])]\n )\n def test_overflow(self, arr):\n slc = np.s_[1:2]\n res = trim_zeros(arr)\n assert_array_equal(res, arr[slc])\n\n def test_no_trim(self):\n arr = np.array([None, 1, None])\n res = trim_zeros(arr)\n assert_array_equal(arr, res)\n\n\n def test_list_to_list(self):\n res = trim_zeros(self.a.tolist())\n assert isinstance(res, list)\n\nclass TestExtins:\n\n def test_basic(self):\n a = np.array([1, 3, 2, 1, 2, 3, 3])\n b = extract(a > 1, a)\n assert_array_equal(b, [3, 2, 2, 3, 3])\n\n def test_place(self):\n # Make sure that non-np.ndarray objects\n # raise an error instead of doing nothing\n assert_raises(TypeError, place, [1, 2, 3], [True, False], [0, 1])\n\n a = np.array([1, 4, 3, 2, 5, 8, 7])\n place(a, [0, 1, 0, 1, 0, 1, 0], [2, 4, 6])\n assert_array_equal(a, [1, 2, 3, 4, 5, 6, 7])\n\n place(a, np.zeros(7), [])\n assert_array_equal(a, np.arange(1, 8))\n\n place(a, [1, 0, 1, 0, 1, 0, 1], [8, 9])\n assert_array_equal(a, [8, 2, 9, 4, 8, 6, 9])\n assert_raises_regex(ValueError, \"Cannot insert from an empty array\",\n lambda: place(a, [0, 0, 0, 0, 0, 1, 0], []))\n\n # See Issue #6974\n a = np.array(['12', '34'])\n place(a, [0, 1], '9')\n assert_array_equal(a, ['12', '9'])\n\n def test_both(self):\n a = rand(10)\n mask = a > 0.5\n ac = a.copy()\n c = extract(mask, a)\n place(a, mask, 0)\n place(a, mask, c)\n assert_array_equal(a, ac)\n\n\n# _foo1 and _foo2 are used in some tests in TestVectorize.\n\ndef _foo1(x, y=1.0):\n return y*math.floor(x)\n\n\ndef _foo2(x, y=1.0, z=0.0):\n return y*math.floor(x) + z\n\n\nclass TestVectorize:\n\n def test_simple(self):\n def addsubtract(a, b):\n if a > b:\n return a - b\n else:\n return a + b\n\n f = vectorize(addsubtract)\n r = f([0, 3, 6, 9], [1, 3, 5, 7])\n assert_array_equal(r, [1, 6, 1, 2])\n\n def test_scalar(self):\n def addsubtract(a, b):\n if a > b:\n return a - b\n else:\n return a + b\n\n f = vectorize(addsubtract)\n r = f([0, 3, 6, 9], 5)\n assert_array_equal(r, [5, 8, 1, 4])\n\n def test_large(self):\n x = np.linspace(-3, 2, 10000)\n f = vectorize(lambda x: x)\n y = f(x)\n assert_array_equal(y, x)\n\n def test_ufunc(self):\n f = vectorize(math.cos)\n args = np.array([0, 0.5 * np.pi, np.pi, 1.5 * np.pi, 2 * np.pi])\n r1 = f(args)\n r2 = np.cos(args)\n assert_array_almost_equal(r1, r2)\n\n def test_keywords(self):\n\n def foo(a, b=1):\n return a + b\n\n f = vectorize(foo)\n args = np.array([1, 2, 3])\n r1 = f(args)\n r2 = np.array([2, 3, 4])\n assert_array_equal(r1, r2)\n r1 = f(args, 2)\n r2 = np.array([3, 4, 5])\n assert_array_equal(r1, r2)\n\n def test_keywords_with_otypes_order1(self):\n # gh-1620: The second call of f would crash with\n # `ValueError: invalid number of arguments`.\n f = vectorize(_foo1, otypes=[float])\n # We're testing the caching of ufuncs by vectorize, so the order\n # of these function calls is an important part of the test.\n r1 = f(np.arange(3.0), 1.0)\n r2 = f(np.arange(3.0))\n assert_array_equal(r1, r2)\n\n def test_keywords_with_otypes_order2(self):\n # gh-1620: The second call of f would crash with\n # `ValueError: non-broadcastable output operand with shape ()\n # doesn't match the broadcast shape (3,)`.\n f = vectorize(_foo1, otypes=[float])\n # We're testing the caching of ufuncs by vectorize, so the order\n # of these function calls is an important part of the test.\n r1 = f(np.arange(3.0))\n r2 = f(np.arange(3.0), 1.0)\n assert_array_equal(r1, r2)\n\n def test_keywords_with_otypes_order3(self):\n # gh-1620: The third call of f would crash with\n # `ValueError: invalid number of arguments`.\n f = vectorize(_foo1, otypes=[float])\n # We're testing the caching of ufuncs by vectorize, so the order\n # of these function calls is an important part of the test.\n r1 = f(np.arange(3.0))\n r2 = f(np.arange(3.0), y=1.0)\n r3 = f(np.arange(3.0))\n assert_array_equal(r1, r2)\n assert_array_equal(r1, r3)\n\n def test_keywords_with_otypes_several_kwd_args1(self):\n # gh-1620 Make sure different uses of keyword arguments\n # don't break the vectorized function.\n f = vectorize(_foo2, otypes=[float])\n # We're testing the caching of ufuncs by vectorize, so the order\n # of these function calls is an important part of the test.\n r1 = f(10.4, z=100)\n r2 = f(10.4, y=-1)\n r3 = f(10.4)\n assert_equal(r1, _foo2(10.4, z=100))\n assert_equal(r2, _foo2(10.4, y=-1))\n assert_equal(r3, _foo2(10.4))\n\n def test_keywords_with_otypes_several_kwd_args2(self):\n # gh-1620 Make sure different uses of keyword arguments\n # don't break the vectorized function.\n f = vectorize(_foo2, otypes=[float])\n # We're testing the caching of ufuncs by vectorize, so the order\n # of these function calls is an important part of the test.\n r1 = f(z=100, x=10.4, y=-1)\n r2 = f(1, 2, 3)\n assert_equal(r1, _foo2(z=100, x=10.4, y=-1))\n assert_equal(r2, _foo2(1, 2, 3))\n\n def test_keywords_no_func_code(self):\n # This needs to test a function that has keywords but\n # no func_code attribute, since otherwise vectorize will\n # inspect the func_code.\n import random\n try:\n vectorize(random.randrange) # Should succeed\n except Exception:\n raise AssertionError()\n\n def test_keywords2_ticket_2100(self):\n # Test kwarg support: enhancement ticket 2100\n\n def foo(a, b=1):\n return a + b\n\n f = vectorize(foo)\n args = np.array([1, 2, 3])\n r1 = f(a=args)\n r2 = np.array([2, 3, 4])\n assert_array_equal(r1, r2)\n r1 = f(b=1, a=args)\n assert_array_equal(r1, r2)\n r1 = f(args, b=2)\n r2 = np.array([3, 4, 5])\n assert_array_equal(r1, r2)\n\n def test_keywords3_ticket_2100(self):\n # Test excluded with mixed positional and kwargs: ticket 2100\n def mypolyval(x, p):\n _p = list(p)\n res = _p.pop(0)\n while _p:\n res = res * x + _p.pop(0)\n return res\n\n vpolyval = np.vectorize(mypolyval, excluded=['p', 1])\n ans = [3, 6]\n assert_array_equal(ans, vpolyval(x=[0, 1], p=[1, 2, 3]))\n assert_array_equal(ans, vpolyval([0, 1], p=[1, 2, 3]))\n assert_array_equal(ans, vpolyval([0, 1], [1, 2, 3]))\n\n def test_keywords4_ticket_2100(self):\n # Test vectorizing function with no positional args.\n @vectorize\n def f(**kw):\n res = 1.0\n for _k in kw:\n res *= kw[_k]\n return res\n\n assert_array_equal(f(a=[1, 2], b=[3, 4]), [3, 8])\n\n def test_keywords5_ticket_2100(self):\n # Test vectorizing function with no kwargs args.\n @vectorize\n def f(*v):\n return np.prod(v)\n\n assert_array_equal(f([1, 2], [3, 4]), [3, 8])\n\n def test_coverage1_ticket_2100(self):\n def foo():\n return 1\n\n f = vectorize(foo)\n assert_array_equal(f(), 1)\n\n def test_assigning_docstring(self):\n def foo(x):\n \"\"\"Original documentation\"\"\"\n return x\n\n f = vectorize(foo)\n assert_equal(f.__doc__, foo.__doc__)\n\n doc = \"Provided documentation\"\n f = vectorize(foo, doc=doc)\n assert_equal(f.__doc__, doc)\n\n def test_UnboundMethod_ticket_1156(self):\n # Regression test for issue 1156\n class Foo:\n b = 2\n\n def bar(self, a):\n return a ** self.b\n\n assert_array_equal(vectorize(Foo().bar)(np.arange(9)),\n np.arange(9) ** 2)\n assert_array_equal(vectorize(Foo.bar)(Foo(), np.arange(9)),\n np.arange(9) ** 2)\n\n def test_execution_order_ticket_1487(self):\n # Regression test for dependence on execution order: issue 1487\n f1 = vectorize(lambda x: x)\n res1a = f1(np.arange(3))\n res1b = f1(np.arange(0.1, 3))\n f2 = vectorize(lambda x: x)\n res2b = f2(np.arange(0.1, 3))\n res2a = f2(np.arange(3))\n assert_equal(res1a, res2a)\n assert_equal(res1b, res2b)\n\n def test_string_ticket_1892(self):\n # Test vectorization over strings: issue 1892.\n f = np.vectorize(lambda x: x)\n s = '0123456789' * 10\n assert_equal(s, f(s))\n\n def test_cache(self):\n # Ensure that vectorized func called exactly once per argument.\n _calls = [0]\n\n @vectorize\n def f(x):\n _calls[0] += 1\n return x ** 2\n\n f.cache = True\n x = np.arange(5)\n assert_array_equal(f(x), x * x)\n assert_equal(_calls[0], len(x))\n\n def test_otypes(self):\n f = np.vectorize(lambda x: x)\n f.otypes = 'i'\n x = np.arange(5)\n assert_array_equal(f(x), x)\n\n def test_parse_gufunc_signature(self):\n assert_equal(nfb._parse_gufunc_signature('(x)->()'), ([('x',)], [()]))\n assert_equal(nfb._parse_gufunc_signature('(x,y)->()'),\n ([('x', 'y')], [()]))\n assert_equal(nfb._parse_gufunc_signature('(x),(y)->()'),\n ([('x',), ('y',)], [()]))\n assert_equal(nfb._parse_gufunc_signature('(x)->(y)'),\n ([('x',)], [('y',)]))\n assert_equal(nfb._parse_gufunc_signature('(x)->(y),()'),\n ([('x',)], [('y',), ()]))\n assert_equal(nfb._parse_gufunc_signature('(),(a,b,c),(d)->(d,e)'),\n ([(), ('a', 'b', 'c'), ('d',)], [('d', 'e')]))\n\n # Tests to check if whitespaces are ignored\n assert_equal(nfb._parse_gufunc_signature('(x )->()'), ([('x',)], [()]))\n assert_equal(nfb._parse_gufunc_signature('( x , y )->( )'),\n ([('x', 'y')], [()]))\n assert_equal(nfb._parse_gufunc_signature('(x),( y) ->()'),\n ([('x',), ('y',)], [()]))\n assert_equal(nfb._parse_gufunc_signature('( x)-> (y ) '),\n ([('x',)], [('y',)]))\n assert_equal(nfb._parse_gufunc_signature(' (x)->( y),( )'),\n ([('x',)], [('y',), ()]))\n assert_equal(nfb._parse_gufunc_signature(\n '( ), ( a, b,c ) ,( d) -> (d , e)'),\n ([(), ('a', 'b', 'c'), ('d',)], [('d', 'e')]))\n\n with assert_raises(ValueError):\n nfb._parse_gufunc_signature('(x)(y)->()')\n with assert_raises(ValueError):\n nfb._parse_gufunc_signature('(x),(y)->')\n with assert_raises(ValueError):\n nfb._parse_gufunc_signature('((x))->(x)')\n\n def test_signature_simple(self):\n def addsubtract(a, b):\n if a > b:\n return a - b\n else:\n return a + b\n\n f = vectorize(addsubtract, signature='(),()->()')\n r = f([0, 3, 6, 9], [1, 3, 5, 7])\n assert_array_equal(r, [1, 6, 1, 2])\n\n def test_signature_mean_last(self):\n def mean(a):\n return a.mean()\n\n f = vectorize(mean, signature='(n)->()')\n r = f([[1, 3], [2, 4]])\n assert_array_equal(r, [2, 3])\n\n def test_signature_center(self):\n def center(a):\n return a - a.mean()\n\n f = vectorize(center, signature='(n)->(n)')\n r = f([[1, 3], [2, 4]])\n assert_array_equal(r, [[-1, 1], [-1, 1]])\n\n def test_signature_two_outputs(self):\n f = vectorize(lambda x: (x, x), signature='()->(),()')\n r = f([1, 2, 3])\n assert_(isinstance(r, tuple) and len(r) == 2)\n assert_array_equal(r[0], [1, 2, 3])\n assert_array_equal(r[1], [1, 2, 3])\n\n def test_signature_outer(self):\n f = vectorize(np.outer, signature='(a),(b)->(a,b)')\n r = f([1, 2], [1, 2, 3])\n assert_array_equal(r, [[1, 2, 3], [2, 4, 6]])\n\n r = f([[[1, 2]]], [1, 2, 3])\n assert_array_equal(r, [[[[1, 2, 3], [2, 4, 6]]]])\n\n r = f([[1, 0], [2, 0]], [1, 2, 3])\n assert_array_equal(r, [[[1, 2, 3], [0, 0, 0]],\n [[2, 4, 6], [0, 0, 0]]])\n\n r = f([1, 2], [[1, 2, 3], [0, 0, 0]])\n assert_array_equal(r, [[[1, 2, 3], [2, 4, 6]],\n [[0, 0, 0], [0, 0, 0]]])\n\n def test_signature_computed_size(self):\n f = vectorize(lambda x: x[:-1], signature='(n)->(m)')\n r = f([1, 2, 3])\n assert_array_equal(r, [1, 2])\n\n r = f([[1, 2, 3], [2, 3, 4]])\n assert_array_equal(r, [[1, 2], [2, 3]])\n\n def test_signature_excluded(self):\n\n def foo(a, b=1):\n return a + b\n\n f = vectorize(foo, signature='()->()', excluded={'b'})\n assert_array_equal(f([1, 2, 3]), [2, 3, 4])\n assert_array_equal(f([1, 2, 3], b=0), [1, 2, 3])\n\n def test_signature_otypes(self):\n f = vectorize(lambda x: x, signature='(n)->(n)', otypes=['float64'])\n r = f([1, 2, 3])\n assert_equal(r.dtype, np.dtype('float64'))\n assert_array_equal(r, [1, 2, 3])\n\n def test_signature_invalid_inputs(self):\n f = vectorize(operator.add, signature='(n),(n)->(n)')\n with assert_raises_regex(TypeError, 'wrong number of positional'):\n f([1, 2])\n with assert_raises_regex(\n ValueError, 'does not have enough dimensions'):\n f(1, 2)\n with assert_raises_regex(\n ValueError, 'inconsistent size for core dimension'):\n f([1, 2], [1, 2, 3])\n\n f = vectorize(operator.add, signature='()->()')\n with assert_raises_regex(TypeError, 'wrong number of positional'):\n f(1, 2)\n\n def test_signature_invalid_outputs(self):\n\n f = vectorize(lambda x: x[:-1], signature='(n)->(n)')\n with assert_raises_regex(\n ValueError, 'inconsistent size for core dimension'):\n f([1, 2, 3])\n\n f = vectorize(lambda x: x, signature='()->(),()')\n with assert_raises_regex(ValueError, 'wrong number of outputs'):\n f(1)\n\n f = vectorize(lambda x: (x, x), signature='()->()')\n with assert_raises_regex(ValueError, 'wrong number of outputs'):\n f([1, 2])\n\n def test_size_zero_output(self):\n # see issue 5868\n f = np.vectorize(lambda x: x)\n x = np.zeros([0, 5], dtype=int)\n with assert_raises_regex(ValueError, 'otypes'):\n f(x)\n\n f.otypes = 'i'\n assert_array_equal(f(x), x)\n\n f = np.vectorize(lambda x: x, signature='()->()')\n with assert_raises_regex(ValueError, 'otypes'):\n f(x)\n\n f = np.vectorize(lambda x: x, signature='()->()', otypes='i')\n assert_array_equal(f(x), x)\n\n f = np.vectorize(lambda x: x, signature='(n)->(n)', otypes='i')\n assert_array_equal(f(x), x)\n\n f = np.vectorize(lambda x: x, signature='(n)->(n)')\n assert_array_equal(f(x.T), x.T)\n\n f = np.vectorize(lambda x: [x], signature='()->(n)', otypes='i')\n with assert_raises_regex(ValueError, 'new output dimensions'):\n f(x)\n\n def test_subclasses(self):\n class subclass(np.ndarray):\n pass\n\n m = np.array([[1., 0., 0.],\n [0., 0., 1.],\n [0., 1., 0.]]).view(subclass)\n v = np.array([[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]]).view(subclass)\n # generalized (gufunc)\n matvec = np.vectorize(np.matmul, signature='(m,m),(m)->(m)')\n r = matvec(m, v)\n assert_equal(type(r), subclass)\n assert_equal(r, [[1., 3., 2.], [4., 6., 5.], [7., 9., 8.]])\n\n # element-wise (ufunc)\n mult = np.vectorize(lambda x, y: x*y)\n r = mult(m, v)\n assert_equal(type(r), subclass)\n assert_equal(r, m * v)\n\n\nclass TestLeaks:\n class A:\n iters = 20\n\n def bound(self, *args):\n return 0\n\n @staticmethod\n def unbound(*args):\n return 0\n\n @pytest.mark.skipif(not HAS_REFCOUNT, reason=\"Python lacks refcounts\")\n @pytest.mark.parametrize('name, incr', [\n ('bound', A.iters),\n ('unbound', 0),\n ])\n def test_frompyfunc_leaks(self, name, incr):\n # exposed in gh-11867 as np.vectorized, but the problem stems from\n # frompyfunc.\n # class.attribute = np.frompyfunc(<method>) creates a\n # reference cycle if <method> is a bound class method. It requires a\n # gc collection cycle to break the cycle (on CPython 3)\n import gc\n A_func = getattr(self.A, name)\n gc.disable()\n try:\n refcount = sys.getrefcount(A_func)\n for i in range(self.A.iters):\n a = self.A()\n a.f = np.frompyfunc(getattr(a, name), 1, 1)\n out = a.f(np.arange(10))\n a = None\n # A.func is part of a reference cycle if incr is non-zero\n assert_equal(sys.getrefcount(A_func), refcount + incr)\n for i in range(5):\n gc.collect()\n assert_equal(sys.getrefcount(A_func), refcount)\n finally:\n gc.enable()\n\nclass TestDigitize:\n\n def test_forward(self):\n x = np.arange(-6, 5)\n bins = np.arange(-5, 5)\n assert_array_equal(digitize(x, bins), np.arange(11))\n\n def test_reverse(self):\n x = np.arange(5, -6, -1)\n bins = np.arange(5, -5, -1)\n assert_array_equal(digitize(x, bins), np.arange(11))\n\n def test_random(self):\n x = rand(10)\n bin = np.linspace(x.min(), x.max(), 10)\n assert_(np.all(digitize(x, bin) != 0))\n\n def test_right_basic(self):\n x = [1, 5, 4, 10, 8, 11, 0]\n bins = [1, 5, 10]\n default_answer = [1, 2, 1, 3, 2, 3, 0]\n assert_array_equal(digitize(x, bins), default_answer)\n right_answer = [0, 1, 1, 2, 2, 3, 0]\n assert_array_equal(digitize(x, bins, True), right_answer)\n\n def test_right_open(self):\n x = np.arange(-6, 5)\n bins = np.arange(-6, 4)\n assert_array_equal(digitize(x, bins, True), np.arange(11))\n\n def test_right_open_reverse(self):\n x = np.arange(5, -6, -1)\n bins = np.arange(4, -6, -1)\n assert_array_equal(digitize(x, bins, True), np.arange(11))\n\n def test_right_open_random(self):\n x = rand(10)\n bins = np.linspace(x.min(), x.max(), 10)\n assert_(np.all(digitize(x, bins, True) != 10))\n\n def test_monotonic(self):\n x = [-1, 0, 1, 2]\n bins = [0, 0, 1]\n assert_array_equal(digitize(x, bins, False), [0, 2, 3, 3])\n assert_array_equal(digitize(x, bins, True), [0, 0, 2, 3])\n bins = [1, 1, 0]\n assert_array_equal(digitize(x, bins, False), [3, 2, 0, 0])\n assert_array_equal(digitize(x, bins, True), [3, 3, 2, 0])\n bins = [1, 1, 1, 1]\n assert_array_equal(digitize(x, bins, False), [0, 0, 4, 4])\n assert_array_equal(digitize(x, bins, True), [0, 0, 0, 4])\n bins = [0, 0, 1, 0]\n assert_raises(ValueError, digitize, x, bins)\n bins = [1, 1, 0, 1]\n assert_raises(ValueError, digitize, x, bins)\n\n def test_casting_error(self):\n x = [1, 2, 3 + 1.j]\n bins = [1, 2, 3]\n assert_raises(TypeError, digitize, x, bins)\n x, bins = bins, x\n assert_raises(TypeError, digitize, x, bins)\n\n def test_return_type(self):\n # Functions returning indices should always return base ndarrays\n class A(np.ndarray):\n pass\n a = np.arange(5).view(A)\n b = np.arange(1, 3).view(A)\n assert_(not isinstance(digitize(b, a, False), A))\n assert_(not isinstance(digitize(b, a, True), A))\n\n def test_large_integers_increasing(self):\n # gh-11022\n x = 2**54 # loses precision in a float\n assert_equal(np.digitize(x, [x - 1, x + 1]), 1)\n\n @pytest.mark.xfail(\n reason=\"gh-11022: np.core.multiarray._monoticity loses precision\")\n def test_large_integers_decreasing(self):\n # gh-11022\n x = 2**54 # loses precision in a float\n assert_equal(np.digitize(x, [x + 1, x - 1]), 1)\n\n\nclass TestUnwrap:\n\n def test_simple(self):\n # check that unwrap removes jumps greater that 2*pi\n assert_array_equal(unwrap([1, 1 + 2 * np.pi]), [1, 1])\n # check that unwrap maintains continuity\n assert_(np.all(diff(unwrap(rand(10) * 100)) < np.pi))\n\n def test_period(self):\n # check that unwrap removes jumps greater that 255\n assert_array_equal(unwrap([1, 1 + 256], period=255), [1, 2])\n # check that unwrap maintains continuity\n assert_(np.all(diff(unwrap(rand(10) * 1000, period=255)) < 255))\n # check simple case\n simple_seq = np.array([0, 75, 150, 225, 300])\n wrap_seq = np.mod(simple_seq, 255)\n assert_array_equal(unwrap(wrap_seq, period=255), simple_seq)\n # check custom discont value\n uneven_seq = np.array([0, 75, 150, 225, 300, 430])\n wrap_uneven = np.mod(uneven_seq, 250)\n no_discont = unwrap(wrap_uneven, period=250)\n assert_array_equal(no_discont, [0, 75, 150, 225, 300, 180])\n sm_discont = unwrap(wrap_uneven, period=250, discont=140)\n assert_array_equal(sm_discont, [0, 75, 150, 225, 300, 430])\n assert sm_discont.dtype == wrap_uneven.dtype\n\n\[email protected](\n \"dtype\", \"O\" + np.typecodes[\"AllInteger\"] + np.typecodes[\"Float\"]\n)\[email protected](\"M\", [0, 1, 10])\nclass TestFilterwindows:\n\n def test_hanning(self, dtype: str, M: int) -> None:\n scalar = np.array(M, dtype=dtype)[()]\n\n w = hanning(scalar)\n if dtype == \"O\":\n ref_dtype = np.float64\n else:\n ref_dtype = np.result_type(scalar.dtype, np.float64)\n assert w.dtype == ref_dtype\n\n # check symmetry\n assert_equal(w, flipud(w))\n\n # check known value\n if scalar < 1:\n assert_array_equal(w, np.array([]))\n elif scalar == 1:\n assert_array_equal(w, np.ones(1))\n else:\n assert_almost_equal(np.sum(w, axis=0), 4.500, 4)\n\n def test_hamming(self, dtype: str, M: int) -> None:\n scalar = np.array(M, dtype=dtype)[()]\n\n w = hamming(scalar)\n if dtype == \"O\":\n ref_dtype = np.float64\n else:\n ref_dtype = np.result_type(scalar.dtype, np.float64)\n assert w.dtype == ref_dtype\n\n # check symmetry\n assert_equal(w, flipud(w))\n\n # check known value\n if scalar < 1:\n assert_array_equal(w, np.array([]))\n elif scalar == 1:\n assert_array_equal(w, np.ones(1))\n else:\n assert_almost_equal(np.sum(w, axis=0), 4.9400, 4)\n\n def test_bartlett(self, dtype: str, M: int) -> None:\n scalar = np.array(M, dtype=dtype)[()]\n\n w = bartlett(scalar)\n if dtype == \"O\":\n ref_dtype = np.float64\n else:\n ref_dtype = np.result_type(scalar.dtype, np.float64)\n assert w.dtype == ref_dtype\n\n # check symmetry\n assert_equal(w, flipud(w))\n\n # check known value\n if scalar < 1:\n assert_array_equal(w, np.array([]))\n elif scalar == 1:\n assert_array_equal(w, np.ones(1))\n else:\n assert_almost_equal(np.sum(w, axis=0), 4.4444, 4)\n\n def test_blackman(self, dtype: str, M: int) -> None:\n scalar = np.array(M, dtype=dtype)[()]\n\n w = blackman(scalar)\n if dtype == \"O\":\n ref_dtype = np.float64\n else:\n ref_dtype = np.result_type(scalar.dtype, np.float64)\n assert w.dtype == ref_dtype\n\n # check symmetry\n assert_equal(w, flipud(w))\n\n # check known value\n if scalar < 1:\n assert_array_equal(w, np.array([]))\n elif scalar == 1:\n assert_array_equal(w, np.ones(1))\n else:\n assert_almost_equal(np.sum(w, axis=0), 3.7800, 4)\n\n def test_kaiser(self, dtype: str, M: int) -> None:\n scalar = np.array(M, dtype=dtype)[()]\n\n w = kaiser(scalar, 0)\n if dtype == \"O\":\n ref_dtype = np.float64\n else:\n ref_dtype = np.result_type(scalar.dtype, np.float64)\n assert w.dtype == ref_dtype\n\n # check symmetry\n assert_equal(w, flipud(w))\n\n # check known value\n if scalar < 1:\n assert_array_equal(w, np.array([]))\n elif scalar == 1:\n assert_array_equal(w, np.ones(1))\n else:\n assert_almost_equal(np.sum(w, axis=0), 10, 15)\n\n\nclass TestTrapz:\n\n def test_simple(self):\n x = np.arange(-10, 10, .1)\n r = trapz(np.exp(-.5 * x ** 2) / np.sqrt(2 * np.pi), dx=0.1)\n # check integral of normal equals 1\n assert_almost_equal(r, 1, 7)\n\n def test_ndim(self):\n x = np.linspace(0, 1, 3)\n y = np.linspace(0, 2, 8)\n z = np.linspace(0, 3, 13)\n\n wx = np.ones_like(x) * (x[1] - x[0])\n wx[0] /= 2\n wx[-1] /= 2\n wy = np.ones_like(y) * (y[1] - y[0])\n wy[0] /= 2\n wy[-1] /= 2\n wz = np.ones_like(z) * (z[1] - z[0])\n wz[0] /= 2\n wz[-1] /= 2\n\n q = x[:, None, None] + y[None,:, None] + z[None, None,:]\n\n qx = (q * wx[:, None, None]).sum(axis=0)\n qy = (q * wy[None, :, None]).sum(axis=1)\n qz = (q * wz[None, None, :]).sum(axis=2)\n\n # n-d `x`\n r = trapz(q, x=x[:, None, None], axis=0)\n assert_almost_equal(r, qx)\n r = trapz(q, x=y[None,:, None], axis=1)\n assert_almost_equal(r, qy)\n r = trapz(q, x=z[None, None,:], axis=2)\n assert_almost_equal(r, qz)\n\n # 1-d `x`\n r = trapz(q, x=x, axis=0)\n assert_almost_equal(r, qx)\n r = trapz(q, x=y, axis=1)\n assert_almost_equal(r, qy)\n r = trapz(q, x=z, axis=2)\n assert_almost_equal(r, qz)\n\n def test_masked(self):\n # Testing that masked arrays behave as if the function is 0 where\n # masked\n x = np.arange(5)\n y = x * x\n mask = x == 2\n ym = np.ma.array(y, mask=mask)\n r = 13.0 # sum(0.5 * (0 + 1) * 1.0 + 0.5 * (9 + 16))\n assert_almost_equal(trapz(ym, x), r)\n\n xm = np.ma.array(x, mask=mask)\n assert_almost_equal(trapz(ym, xm), r)\n\n xm = np.ma.array(x, mask=mask)\n assert_almost_equal(trapz(y, xm), r)\n\n\nclass TestSinc:\n\n def test_simple(self):\n assert_(sinc(0) == 1)\n w = sinc(np.linspace(-1, 1, 100))\n # check symmetry\n assert_array_almost_equal(w, flipud(w), 7)\n\n def test_array_like(self):\n x = [0, 0.5]\n y1 = sinc(np.array(x))\n y2 = sinc(list(x))\n y3 = sinc(tuple(x))\n assert_array_equal(y1, y2)\n assert_array_equal(y1, y3)\n\n\nclass TestUnique:\n\n def test_simple(self):\n x = np.array([4, 3, 2, 1, 1, 2, 3, 4, 0])\n assert_(np.all(unique(x) == [0, 1, 2, 3, 4]))\n assert_(unique(np.array([1, 1, 1, 1, 1])) == np.array([1]))\n x = ['widget', 'ham', 'foo', 'bar', 'foo', 'ham']\n assert_(np.all(unique(x) == ['bar', 'foo', 'ham', 'widget']))\n x = np.array([5 + 6j, 1 + 1j, 1 + 10j, 10, 5 + 6j])\n assert_(np.all(unique(x) == [1 + 1j, 1 + 10j, 5 + 6j, 10]))\n\n\nclass TestCheckFinite:\n\n def test_simple(self):\n a = [1, 2, 3]\n b = [1, 2, np.inf]\n c = [1, 2, np.nan]\n np.lib.asarray_chkfinite(a)\n assert_raises(ValueError, np.lib.asarray_chkfinite, b)\n assert_raises(ValueError, np.lib.asarray_chkfinite, c)\n\n def test_dtype_order(self):\n # Regression test for missing dtype and order arguments\n a = [1, 2, 3]\n a = np.lib.asarray_chkfinite(a, order='F', dtype=np.float64)\n assert_(a.dtype == np.float64)\n\n\nclass TestCorrCoef:\n A = np.array(\n [[0.15391142, 0.18045767, 0.14197213],\n [0.70461506, 0.96474128, 0.27906989],\n [0.9297531, 0.32296769, 0.19267156]])\n B = np.array(\n [[0.10377691, 0.5417086, 0.49807457],\n [0.82872117, 0.77801674, 0.39226705],\n [0.9314666, 0.66800209, 0.03538394]])\n res1 = np.array(\n [[1., 0.9379533, -0.04931983],\n [0.9379533, 1., 0.30007991],\n [-0.04931983, 0.30007991, 1.]])\n res2 = np.array(\n [[1., 0.9379533, -0.04931983, 0.30151751, 0.66318558, 0.51532523],\n [0.9379533, 1., 0.30007991, -0.04781421, 0.88157256, 0.78052386],\n [-0.04931983, 0.30007991, 1., -0.96717111, 0.71483595, 0.83053601],\n [0.30151751, -0.04781421, -0.96717111, 1., -0.51366032, -0.66173113],\n [0.66318558, 0.88157256, 0.71483595, -0.51366032, 1., 0.98317823],\n [0.51532523, 0.78052386, 0.83053601, -0.66173113, 0.98317823, 1.]])\n\n def test_non_array(self):\n assert_almost_equal(np.corrcoef([0, 1, 0], [1, 0, 1]),\n [[1., -1.], [-1., 1.]])\n\n def test_simple(self):\n tgt1 = corrcoef(self.A)\n assert_almost_equal(tgt1, self.res1)\n assert_(np.all(np.abs(tgt1) <= 1.0))\n\n tgt2 = corrcoef(self.A, self.B)\n assert_almost_equal(tgt2, self.res2)\n assert_(np.all(np.abs(tgt2) <= 1.0))\n\n def test_ddof(self):\n # ddof raises DeprecationWarning\n with suppress_warnings() as sup:\n warnings.simplefilter(\"always\")\n assert_warns(DeprecationWarning, corrcoef, self.A, ddof=-1)\n sup.filter(DeprecationWarning)\n # ddof has no or negligible effect on the function\n assert_almost_equal(corrcoef(self.A, ddof=-1), self.res1)\n assert_almost_equal(corrcoef(self.A, self.B, ddof=-1), self.res2)\n assert_almost_equal(corrcoef(self.A, ddof=3), self.res1)\n assert_almost_equal(corrcoef(self.A, self.B, ddof=3), self.res2)\n\n def test_bias(self):\n # bias raises DeprecationWarning\n with suppress_warnings() as sup:\n warnings.simplefilter(\"always\")\n assert_warns(DeprecationWarning, corrcoef, self.A, self.B, 1, 0)\n assert_warns(DeprecationWarning, corrcoef, self.A, bias=0)\n sup.filter(DeprecationWarning)\n # bias has no or negligible effect on the function\n assert_almost_equal(corrcoef(self.A, bias=1), self.res1)\n\n def test_complex(self):\n x = np.array([[1, 2, 3], [1j, 2j, 3j]])\n res = corrcoef(x)\n tgt = np.array([[1., -1.j], [1.j, 1.]])\n assert_allclose(res, tgt)\n assert_(np.all(np.abs(res) <= 1.0))\n\n def test_xy(self):\n x = np.array([[1, 2, 3]])\n y = np.array([[1j, 2j, 3j]])\n assert_allclose(np.corrcoef(x, y), np.array([[1., -1.j], [1.j, 1.]]))\n\n def test_empty(self):\n with warnings.catch_warnings(record=True):\n warnings.simplefilter('always', RuntimeWarning)\n assert_array_equal(corrcoef(np.array([])), np.nan)\n assert_array_equal(corrcoef(np.array([]).reshape(0, 2)),\n np.array([]).reshape(0, 0))\n assert_array_equal(corrcoef(np.array([]).reshape(2, 0)),\n np.array([[np.nan, np.nan], [np.nan, np.nan]]))\n\n def test_extreme(self):\n x = [[1e-100, 1e100], [1e100, 1e-100]]\n with np.errstate(all='raise'):\n c = corrcoef(x)\n assert_array_almost_equal(c, np.array([[1., -1.], [-1., 1.]]))\n assert_(np.all(np.abs(c) <= 1.0))\n\n @pytest.mark.parametrize(\"test_type\", [np.half, np.single, np.double, np.longdouble])\n def test_corrcoef_dtype(self, test_type):\n cast_A = self.A.astype(test_type)\n res = corrcoef(cast_A, dtype=test_type)\n assert test_type == res.dtype\n\n\nclass TestCov:\n x1 = np.array([[0, 2], [1, 1], [2, 0]]).T\n res1 = np.array([[1., -1.], [-1., 1.]])\n x2 = np.array([0.0, 1.0, 2.0], ndmin=2)\n frequencies = np.array([1, 4, 1])\n x2_repeats = np.array([[0.0], [1.0], [1.0], [1.0], [1.0], [2.0]]).T\n res2 = np.array([[0.4, -0.4], [-0.4, 0.4]])\n unit_frequencies = np.ones(3, dtype=np.int_)\n weights = np.array([1.0, 4.0, 1.0])\n res3 = np.array([[2. / 3., -2. / 3.], [-2. / 3., 2. / 3.]])\n unit_weights = np.ones(3)\n x3 = np.array([0.3942, 0.5969, 0.7730, 0.9918, 0.7964])\n\n def test_basic(self):\n assert_allclose(cov(self.x1), self.res1)\n\n def test_complex(self):\n x = np.array([[1, 2, 3], [1j, 2j, 3j]])\n res = np.array([[1., -1.j], [1.j, 1.]])\n assert_allclose(cov(x), res)\n assert_allclose(cov(x, aweights=np.ones(3)), res)\n\n def test_xy(self):\n x = np.array([[1, 2, 3]])\n y = np.array([[1j, 2j, 3j]])\n assert_allclose(cov(x, y), np.array([[1., -1.j], [1.j, 1.]]))\n\n def test_empty(self):\n with warnings.catch_warnings(record=True):\n warnings.simplefilter('always', RuntimeWarning)\n assert_array_equal(cov(np.array([])), np.nan)\n assert_array_equal(cov(np.array([]).reshape(0, 2)),\n np.array([]).reshape(0, 0))\n assert_array_equal(cov(np.array([]).reshape(2, 0)),\n np.array([[np.nan, np.nan], [np.nan, np.nan]]))\n\n def test_wrong_ddof(self):\n with warnings.catch_warnings(record=True):\n warnings.simplefilter('always', RuntimeWarning)\n assert_array_equal(cov(self.x1, ddof=5),\n np.array([[np.inf, -np.inf],\n [-np.inf, np.inf]]))\n\n def test_1D_rowvar(self):\n assert_allclose(cov(self.x3), cov(self.x3, rowvar=False))\n y = np.array([0.0780, 0.3107, 0.2111, 0.0334, 0.8501])\n assert_allclose(cov(self.x3, y), cov(self.x3, y, rowvar=False))\n\n def test_1D_variance(self):\n assert_allclose(cov(self.x3, ddof=1), np.var(self.x3, ddof=1))\n\n def test_fweights(self):\n assert_allclose(cov(self.x2, fweights=self.frequencies),\n cov(self.x2_repeats))\n assert_allclose(cov(self.x1, fweights=self.frequencies),\n self.res2)\n assert_allclose(cov(self.x1, fweights=self.unit_frequencies),\n self.res1)\n nonint = self.frequencies + 0.5\n assert_raises(TypeError, cov, self.x1, fweights=nonint)\n f = np.ones((2, 3), dtype=np.int_)\n assert_raises(RuntimeError, cov, self.x1, fweights=f)\n f = np.ones(2, dtype=np.int_)\n assert_raises(RuntimeError, cov, self.x1, fweights=f)\n f = -1 * np.ones(3, dtype=np.int_)\n assert_raises(ValueError, cov, self.x1, fweights=f)\n\n def test_aweights(self):\n assert_allclose(cov(self.x1, aweights=self.weights), self.res3)\n assert_allclose(cov(self.x1, aweights=3.0 * self.weights),\n cov(self.x1, aweights=self.weights))\n assert_allclose(cov(self.x1, aweights=self.unit_weights), self.res1)\n w = np.ones((2, 3))\n assert_raises(RuntimeError, cov, self.x1, aweights=w)\n w = np.ones(2)\n assert_raises(RuntimeError, cov, self.x1, aweights=w)\n w = -1.0 * np.ones(3)\n assert_raises(ValueError, cov, self.x1, aweights=w)\n\n def test_unit_fweights_and_aweights(self):\n assert_allclose(cov(self.x2, fweights=self.frequencies,\n aweights=self.unit_weights),\n cov(self.x2_repeats))\n assert_allclose(cov(self.x1, fweights=self.frequencies,\n aweights=self.unit_weights),\n self.res2)\n assert_allclose(cov(self.x1, fweights=self.unit_frequencies,\n aweights=self.unit_weights),\n self.res1)\n assert_allclose(cov(self.x1, fweights=self.unit_frequencies,\n aweights=self.weights),\n self.res3)\n assert_allclose(cov(self.x1, fweights=self.unit_frequencies,\n aweights=3.0 * self.weights),\n cov(self.x1, aweights=self.weights))\n assert_allclose(cov(self.x1, fweights=self.unit_frequencies,\n aweights=self.unit_weights),\n self.res1)\n\n @pytest.mark.parametrize(\"test_type\", [np.half, np.single, np.double, np.longdouble])\n def test_cov_dtype(self, test_type):\n cast_x1 = self.x1.astype(test_type)\n res = cov(cast_x1, dtype=test_type)\n assert test_type == res.dtype\n\n\nclass Test_I0:\n\n def test_simple(self):\n assert_almost_equal(\n i0(0.5),\n np.array(1.0634833707413234))\n\n # need at least one test above 8, as the implementation is piecewise\n A = np.array([0.49842636, 0.6969809, 0.22011976, 0.0155549, 10.0])\n expected = np.array([1.06307822, 1.12518299, 1.01214991, 1.00006049, 2815.71662847])\n assert_almost_equal(i0(A), expected)\n assert_almost_equal(i0(-A), expected)\n\n B = np.array([[0.827002, 0.99959078],\n [0.89694769, 0.39298162],\n [0.37954418, 0.05206293],\n [0.36465447, 0.72446427],\n [0.48164949, 0.50324519]])\n assert_almost_equal(\n i0(B),\n np.array([[1.17843223, 1.26583466],\n [1.21147086, 1.03898290],\n [1.03633899, 1.00067775],\n [1.03352052, 1.13557954],\n [1.05884290, 1.06432317]]))\n # Regression test for gh-11205\n i0_0 = np.i0([0.])\n assert_equal(i0_0.shape, (1,))\n assert_array_equal(np.i0([0.]), np.array([1.]))\n\n def test_non_array(self):\n a = np.arange(4)\n\n class array_like:\n __array_interface__ = a.__array_interface__\n\n def __array_wrap__(self, arr):\n return self\n\n # E.g. pandas series survive ufunc calls through array-wrap:\n assert isinstance(np.abs(array_like()), array_like)\n exp = np.i0(a)\n res = np.i0(array_like())\n\n assert_array_equal(exp, res)\n\n def test_complex(self):\n a = np.array([0, 1 + 2j])\n with pytest.raises(TypeError, match=\"i0 not supported for complex values\"):\n res = i0(a)\n\nclass TestKaiser:\n\n def test_simple(self):\n assert_(np.isfinite(kaiser(1, 1.0)))\n assert_almost_equal(kaiser(0, 1.0),\n np.array([]))\n assert_almost_equal(kaiser(2, 1.0),\n np.array([0.78984831, 0.78984831]))\n assert_almost_equal(kaiser(5, 1.0),\n np.array([0.78984831, 0.94503323, 1.,\n 0.94503323, 0.78984831]))\n assert_almost_equal(kaiser(5, 1.56789),\n np.array([0.58285404, 0.88409679, 1.,\n 0.88409679, 0.58285404]))\n\n def test_int_beta(self):\n kaiser(3, 4)\n\n\nclass TestMsort:\n\n def test_simple(self):\n A = np.array([[0.44567325, 0.79115165, 0.54900530],\n [0.36844147, 0.37325583, 0.96098397],\n [0.64864341, 0.52929049, 0.39172155]])\n assert_almost_equal(\n msort(A),\n np.array([[0.36844147, 0.37325583, 0.39172155],\n [0.44567325, 0.52929049, 0.54900530],\n [0.64864341, 0.79115165, 0.96098397]]))\n\n\nclass TestMeshgrid:\n\n def test_simple(self):\n [X, Y] = meshgrid([1, 2, 3], [4, 5, 6, 7])\n assert_array_equal(X, np.array([[1, 2, 3],\n [1, 2, 3],\n [1, 2, 3],\n [1, 2, 3]]))\n assert_array_equal(Y, np.array([[4, 4, 4],\n [5, 5, 5],\n [6, 6, 6],\n [7, 7, 7]]))\n\n def test_single_input(self):\n [X] = meshgrid([1, 2, 3, 4])\n assert_array_equal(X, np.array([1, 2, 3, 4]))\n\n def test_no_input(self):\n args = []\n assert_array_equal([], meshgrid(*args))\n assert_array_equal([], meshgrid(*args, copy=False))\n\n def test_indexing(self):\n x = [1, 2, 3]\n y = [4, 5, 6, 7]\n [X, Y] = meshgrid(x, y, indexing='ij')\n assert_array_equal(X, np.array([[1, 1, 1, 1],\n [2, 2, 2, 2],\n [3, 3, 3, 3]]))\n assert_array_equal(Y, np.array([[4, 5, 6, 7],\n [4, 5, 6, 7],\n [4, 5, 6, 7]]))\n\n # Test expected shapes:\n z = [8, 9]\n assert_(meshgrid(x, y)[0].shape == (4, 3))\n assert_(meshgrid(x, y, indexing='ij')[0].shape == (3, 4))\n assert_(meshgrid(x, y, z)[0].shape == (4, 3, 2))\n assert_(meshgrid(x, y, z, indexing='ij')[0].shape == (3, 4, 2))\n\n assert_raises(ValueError, meshgrid, x, y, indexing='notvalid')\n\n def test_sparse(self):\n [X, Y] = meshgrid([1, 2, 3], [4, 5, 6, 7], sparse=True)\n assert_array_equal(X, np.array([[1, 2, 3]]))\n assert_array_equal(Y, np.array([[4], [5], [6], [7]]))\n\n def test_invalid_arguments(self):\n # Test that meshgrid complains about invalid arguments\n # Regression test for issue #4755:\n # https://github.com/numpy/numpy/issues/4755\n assert_raises(TypeError, meshgrid,\n [1, 2, 3], [4, 5, 6, 7], indices='ij')\n\n def test_return_type(self):\n # Test for appropriate dtype in returned arrays.\n # Regression test for issue #5297\n # https://github.com/numpy/numpy/issues/5297\n x = np.arange(0, 10, dtype=np.float32)\n y = np.arange(10, 20, dtype=np.float64)\n\n X, Y = np.meshgrid(x,y)\n\n assert_(X.dtype == x.dtype)\n assert_(Y.dtype == y.dtype)\n\n # copy\n X, Y = np.meshgrid(x,y, copy=True)\n\n assert_(X.dtype == x.dtype)\n assert_(Y.dtype == y.dtype)\n\n # sparse\n X, Y = np.meshgrid(x,y, sparse=True)\n\n assert_(X.dtype == x.dtype)\n assert_(Y.dtype == y.dtype)\n\n def test_writeback(self):\n # Issue 8561\n X = np.array([1.1, 2.2])\n Y = np.array([3.3, 4.4])\n x, y = np.meshgrid(X, Y, sparse=False, copy=True)\n\n x[0, :] = 0\n assert_equal(x[0, :], 0)\n assert_equal(x[1, :], X)\n\n def test_nd_shape(self):\n a, b, c, d, e = np.meshgrid(*([0] * i for i in range(1, 6)))\n expected_shape = (2, 1, 3, 4, 5)\n assert_equal(a.shape, expected_shape)\n assert_equal(b.shape, expected_shape)\n assert_equal(c.shape, expected_shape)\n assert_equal(d.shape, expected_shape)\n assert_equal(e.shape, expected_shape)\n\n def test_nd_values(self):\n a, b, c = np.meshgrid([0], [1, 2], [3, 4, 5])\n assert_equal(a, [[[0, 0, 0]], [[0, 0, 0]]])\n assert_equal(b, [[[1, 1, 1]], [[2, 2, 2]]])\n assert_equal(c, [[[3, 4, 5]], [[3, 4, 5]]])\n\n def test_nd_indexing(self):\n a, b, c = np.meshgrid([0], [1, 2], [3, 4, 5], indexing='ij')\n assert_equal(a, [[[0, 0, 0], [0, 0, 0]]])\n assert_equal(b, [[[1, 1, 1], [2, 2, 2]]])\n assert_equal(c, [[[3, 4, 5], [3, 4, 5]]])\n\n\nclass TestPiecewise:\n\n def test_simple(self):\n # Condition is single bool list\n x = piecewise([0, 0], [True, False], [1])\n assert_array_equal(x, [1, 0])\n\n # List of conditions: single bool list\n x = piecewise([0, 0], [[True, False]], [1])\n assert_array_equal(x, [1, 0])\n\n # Conditions is single bool array\n x = piecewise([0, 0], np.array([True, False]), [1])\n assert_array_equal(x, [1, 0])\n\n # Condition is single int array\n x = piecewise([0, 0], np.array([1, 0]), [1])\n assert_array_equal(x, [1, 0])\n\n # List of conditions: int array\n x = piecewise([0, 0], [np.array([1, 0])], [1])\n assert_array_equal(x, [1, 0])\n\n x = piecewise([0, 0], [[False, True]], [lambda x:-1])\n assert_array_equal(x, [0, -1])\n\n assert_raises_regex(ValueError, '1 or 2 functions are expected',\n piecewise, [0, 0], [[False, True]], [])\n assert_raises_regex(ValueError, '1 or 2 functions are expected',\n piecewise, [0, 0], [[False, True]], [1, 2, 3])\n\n def test_two_conditions(self):\n x = piecewise([1, 2], [[True, False], [False, True]], [3, 4])\n assert_array_equal(x, [3, 4])\n\n def test_scalar_domains_three_conditions(self):\n x = piecewise(3, [True, False, False], [4, 2, 0])\n assert_equal(x, 4)\n\n def test_default(self):\n # No value specified for x[1], should be 0\n x = piecewise([1, 2], [True, False], [2])\n assert_array_equal(x, [2, 0])\n\n # Should set x[1] to 3\n x = piecewise([1, 2], [True, False], [2, 3])\n assert_array_equal(x, [2, 3])\n\n def test_0d(self):\n x = np.array(3)\n y = piecewise(x, x > 3, [4, 0])\n assert_(y.ndim == 0)\n assert_(y == 0)\n\n x = 5\n y = piecewise(x, [True, False], [1, 0])\n assert_(y.ndim == 0)\n assert_(y == 1)\n\n # With 3 ranges (It was failing, before)\n y = piecewise(x, [False, False, True], [1, 2, 3])\n assert_array_equal(y, 3)\n\n def test_0d_comparison(self):\n x = 3\n y = piecewise(x, [x <= 3, x > 3], [4, 0]) # Should succeed.\n assert_equal(y, 4)\n\n # With 3 ranges (It was failing, before)\n x = 4\n y = piecewise(x, [x <= 3, (x > 3) * (x <= 5), x > 5], [1, 2, 3])\n assert_array_equal(y, 2)\n\n assert_raises_regex(ValueError, '2 or 3 functions are expected',\n piecewise, x, [x <= 3, x > 3], [1])\n assert_raises_regex(ValueError, '2 or 3 functions are expected',\n piecewise, x, [x <= 3, x > 3], [1, 1, 1, 1])\n\n def test_0d_0d_condition(self):\n x = np.array(3)\n c = np.array(x > 3)\n y = piecewise(x, [c], [1, 2])\n assert_equal(y, 2)\n\n def test_multidimensional_extrafunc(self):\n x = np.array([[-2.5, -1.5, -0.5],\n [0.5, 1.5, 2.5]])\n y = piecewise(x, [x < 0, x >= 2], [-1, 1, 3])\n assert_array_equal(y, np.array([[-1., -1., -1.],\n [3., 3., 1.]]))\n\n def test_subclasses(self):\n class subclass(np.ndarray):\n pass\n x = np.arange(5.).view(subclass)\n r = piecewise(x, [x<2., x>=4], [-1., 1., 0.])\n assert_equal(type(r), subclass)\n assert_equal(r, [-1., -1., 0., 0., 1.])\n\n\nclass TestBincount:\n\n def test_simple(self):\n y = np.bincount(np.arange(4))\n assert_array_equal(y, np.ones(4))\n\n def test_simple2(self):\n y = np.bincount(np.array([1, 5, 2, 4, 1]))\n assert_array_equal(y, np.array([0, 2, 1, 0, 1, 1]))\n\n def test_simple_weight(self):\n x = np.arange(4)\n w = np.array([0.2, 0.3, 0.5, 0.1])\n y = np.bincount(x, w)\n assert_array_equal(y, w)\n\n def test_simple_weight2(self):\n x = np.array([1, 2, 4, 5, 2])\n w = np.array([0.2, 0.3, 0.5, 0.1, 0.2])\n y = np.bincount(x, w)\n assert_array_equal(y, np.array([0, 0.2, 0.5, 0, 0.5, 0.1]))\n\n def test_with_minlength(self):\n x = np.array([0, 1, 0, 1, 1])\n y = np.bincount(x, minlength=3)\n assert_array_equal(y, np.array([2, 3, 0]))\n x = []\n y = np.bincount(x, minlength=0)\n assert_array_equal(y, np.array([]))\n\n def test_with_minlength_smaller_than_maxvalue(self):\n x = np.array([0, 1, 1, 2, 2, 3, 3])\n y = np.bincount(x, minlength=2)\n assert_array_equal(y, np.array([1, 2, 2, 2]))\n y = np.bincount(x, minlength=0)\n assert_array_equal(y, np.array([1, 2, 2, 2]))\n\n def test_with_minlength_and_weights(self):\n x = np.array([1, 2, 4, 5, 2])\n w = np.array([0.2, 0.3, 0.5, 0.1, 0.2])\n y = np.bincount(x, w, 8)\n assert_array_equal(y, np.array([0, 0.2, 0.5, 0, 0.5, 0.1, 0, 0]))\n\n def test_empty(self):\n x = np.array([], dtype=int)\n y = np.bincount(x)\n assert_array_equal(x, y)\n\n def test_empty_with_minlength(self):\n x = np.array([], dtype=int)\n y = np.bincount(x, minlength=5)\n assert_array_equal(y, np.zeros(5, dtype=int))\n\n def test_with_incorrect_minlength(self):\n x = np.array([], dtype=int)\n assert_raises_regex(TypeError,\n \"'str' object cannot be interpreted\",\n lambda: np.bincount(x, minlength=\"foobar\"))\n assert_raises_regex(ValueError,\n \"must not be negative\",\n lambda: np.bincount(x, minlength=-1))\n\n x = np.arange(5)\n assert_raises_regex(TypeError,\n \"'str' object cannot be interpreted\",\n lambda: np.bincount(x, minlength=\"foobar\"))\n assert_raises_regex(ValueError,\n \"must not be negative\",\n lambda: np.bincount(x, minlength=-1))\n\n @pytest.mark.skipif(not HAS_REFCOUNT, reason=\"Python lacks refcounts\")\n def test_dtype_reference_leaks(self):\n # gh-6805\n intp_refcount = sys.getrefcount(np.dtype(np.intp))\n double_refcount = sys.getrefcount(np.dtype(np.double))\n\n for j in range(10):\n np.bincount([1, 2, 3])\n assert_equal(sys.getrefcount(np.dtype(np.intp)), intp_refcount)\n assert_equal(sys.getrefcount(np.dtype(np.double)), double_refcount)\n\n for j in range(10):\n np.bincount([1, 2, 3], [4, 5, 6])\n assert_equal(sys.getrefcount(np.dtype(np.intp)), intp_refcount)\n assert_equal(sys.getrefcount(np.dtype(np.double)), double_refcount)\n\n @pytest.mark.parametrize(\"vals\", [[[2, 2]], 2])\n def test_error_not_1d(self, vals):\n # Test that values has to be 1-D (both as array and nested list)\n vals_arr = np.asarray(vals)\n with assert_raises(ValueError):\n np.bincount(vals_arr)\n with assert_raises(ValueError):\n np.bincount(vals)\n\n\nclass TestInterp:\n\n def test_exceptions(self):\n assert_raises(ValueError, interp, 0, [], [])\n assert_raises(ValueError, interp, 0, [0], [1, 2])\n assert_raises(ValueError, interp, 0, [0, 1], [1, 2], period=0)\n assert_raises(ValueError, interp, 0, [], [], period=360)\n assert_raises(ValueError, interp, 0, [0], [1, 2], period=360)\n\n def test_basic(self):\n x = np.linspace(0, 1, 5)\n y = np.linspace(0, 1, 5)\n x0 = np.linspace(0, 1, 50)\n assert_almost_equal(np.interp(x0, x, y), x0)\n\n def test_right_left_behavior(self):\n # Needs range of sizes to test different code paths.\n # size ==1 is special cased, 1 < size < 5 is linear search, and\n # size >= 5 goes through local search and possibly binary search.\n for size in range(1, 10):\n xp = np.arange(size, dtype=np.double)\n yp = np.ones(size, dtype=np.double)\n incpts = np.array([-1, 0, size - 1, size], dtype=np.double)\n decpts = incpts[::-1]\n\n incres = interp(incpts, xp, yp)\n decres = interp(decpts, xp, yp)\n inctgt = np.array([1, 1, 1, 1], dtype=float)\n dectgt = inctgt[::-1]\n assert_equal(incres, inctgt)\n assert_equal(decres, dectgt)\n\n incres = interp(incpts, xp, yp, left=0)\n decres = interp(decpts, xp, yp, left=0)\n inctgt = np.array([0, 1, 1, 1], dtype=float)\n dectgt = inctgt[::-1]\n assert_equal(incres, inctgt)\n assert_equal(decres, dectgt)\n\n incres = interp(incpts, xp, yp, right=2)\n decres = interp(decpts, xp, yp, right=2)\n inctgt = np.array([1, 1, 1, 2], dtype=float)\n dectgt = inctgt[::-1]\n assert_equal(incres, inctgt)\n assert_equal(decres, dectgt)\n\n incres = interp(incpts, xp, yp, left=0, right=2)\n decres = interp(decpts, xp, yp, left=0, right=2)\n inctgt = np.array([0, 1, 1, 2], dtype=float)\n dectgt = inctgt[::-1]\n assert_equal(incres, inctgt)\n assert_equal(decres, dectgt)\n\n def test_scalar_interpolation_point(self):\n x = np.linspace(0, 1, 5)\n y = np.linspace(0, 1, 5)\n x0 = 0\n assert_almost_equal(np.interp(x0, x, y), x0)\n x0 = .3\n assert_almost_equal(np.interp(x0, x, y), x0)\n x0 = np.float32(.3)\n assert_almost_equal(np.interp(x0, x, y), x0)\n x0 = np.float64(.3)\n assert_almost_equal(np.interp(x0, x, y), x0)\n x0 = np.nan\n assert_almost_equal(np.interp(x0, x, y), x0)\n\n def test_non_finite_behavior_exact_x(self):\n x = [1, 2, 2.5, 3, 4]\n xp = [1, 2, 3, 4]\n fp = [1, 2, np.inf, 4]\n assert_almost_equal(np.interp(x, xp, fp), [1, 2, np.inf, np.inf, 4])\n fp = [1, 2, np.nan, 4]\n assert_almost_equal(np.interp(x, xp, fp), [1, 2, np.nan, np.nan, 4])\n\n @pytest.fixture(params=[\n lambda x: np.float_(x),\n lambda x: _make_complex(x, 0),\n lambda x: _make_complex(0, x),\n lambda x: _make_complex(x, np.multiply(x, -2))\n ], ids=[\n 'real',\n 'complex-real',\n 'complex-imag',\n 'complex-both'\n ])\n def sc(self, request):\n \"\"\" scale function used by the below tests \"\"\"\n return request.param\n\n def test_non_finite_any_nan(self, sc):\n \"\"\" test that nans are propagated \"\"\"\n assert_equal(np.interp(0.5, [np.nan, 1], sc([ 0, 10])), sc(np.nan))\n assert_equal(np.interp(0.5, [ 0, np.nan], sc([ 0, 10])), sc(np.nan))\n assert_equal(np.interp(0.5, [ 0, 1], sc([np.nan, 10])), sc(np.nan))\n assert_equal(np.interp(0.5, [ 0, 1], sc([ 0, np.nan])), sc(np.nan))\n\n def test_non_finite_inf(self, sc):\n \"\"\" Test that interp between opposite infs gives nan \"\"\"\n assert_equal(np.interp(0.5, [-np.inf, +np.inf], sc([ 0, 10])), sc(np.nan))\n assert_equal(np.interp(0.5, [ 0, 1], sc([-np.inf, +np.inf])), sc(np.nan))\n assert_equal(np.interp(0.5, [ 0, 1], sc([+np.inf, -np.inf])), sc(np.nan))\n\n # unless the y values are equal\n assert_equal(np.interp(0.5, [-np.inf, +np.inf], sc([ 10, 10])), sc(10))\n\n def test_non_finite_half_inf_xf(self, sc):\n \"\"\" Test that interp where both axes have a bound at inf gives nan \"\"\"\n assert_equal(np.interp(0.5, [-np.inf, 1], sc([-np.inf, 10])), sc(np.nan))\n assert_equal(np.interp(0.5, [-np.inf, 1], sc([+np.inf, 10])), sc(np.nan))\n assert_equal(np.interp(0.5, [-np.inf, 1], sc([ 0, -np.inf])), sc(np.nan))\n assert_equal(np.interp(0.5, [-np.inf, 1], sc([ 0, +np.inf])), sc(np.nan))\n assert_equal(np.interp(0.5, [ 0, +np.inf], sc([-np.inf, 10])), sc(np.nan))\n assert_equal(np.interp(0.5, [ 0, +np.inf], sc([+np.inf, 10])), sc(np.nan))\n assert_equal(np.interp(0.5, [ 0, +np.inf], sc([ 0, -np.inf])), sc(np.nan))\n assert_equal(np.interp(0.5, [ 0, +np.inf], sc([ 0, +np.inf])), sc(np.nan))\n\n def test_non_finite_half_inf_x(self, sc):\n \"\"\" Test interp where the x axis has a bound at inf \"\"\"\n assert_equal(np.interp(0.5, [-np.inf, -np.inf], sc([0, 10])), sc(10))\n assert_equal(np.interp(0.5, [-np.inf, 1 ], sc([0, 10])), sc(10))\n assert_equal(np.interp(0.5, [ 0, +np.inf], sc([0, 10])), sc(0))\n assert_equal(np.interp(0.5, [+np.inf, +np.inf], sc([0, 10])), sc(0))\n\n def test_non_finite_half_inf_f(self, sc):\n \"\"\" Test interp where the f axis has a bound at inf \"\"\"\n assert_equal(np.interp(0.5, [0, 1], sc([ 0, -np.inf])), sc(-np.inf))\n assert_equal(np.interp(0.5, [0, 1], sc([ 0, +np.inf])), sc(+np.inf))\n assert_equal(np.interp(0.5, [0, 1], sc([-np.inf, 10])), sc(-np.inf))\n assert_equal(np.interp(0.5, [0, 1], sc([+np.inf, 10])), sc(+np.inf))\n assert_equal(np.interp(0.5, [0, 1], sc([-np.inf, -np.inf])), sc(-np.inf))\n assert_equal(np.interp(0.5, [0, 1], sc([+np.inf, +np.inf])), sc(+np.inf))\n\n def test_complex_interp(self):\n # test complex interpolation\n x = np.linspace(0, 1, 5)\n y = np.linspace(0, 1, 5) + (1 + np.linspace(0, 1, 5))*1.0j\n x0 = 0.3\n y0 = x0 + (1+x0)*1.0j\n assert_almost_equal(np.interp(x0, x, y), y0)\n # test complex left and right\n x0 = -1\n left = 2 + 3.0j\n assert_almost_equal(np.interp(x0, x, y, left=left), left)\n x0 = 2.0\n right = 2 + 3.0j\n assert_almost_equal(np.interp(x0, x, y, right=right), right)\n # test complex non finite\n x = [1, 2, 2.5, 3, 4]\n xp = [1, 2, 3, 4]\n fp = [1, 2+1j, np.inf, 4]\n y = [1, 2+1j, np.inf+0.5j, np.inf, 4]\n assert_almost_equal(np.interp(x, xp, fp), y)\n # test complex periodic\n x = [-180, -170, -185, 185, -10, -5, 0, 365]\n xp = [190, -190, 350, -350]\n fp = [5+1.0j, 10+2j, 3+3j, 4+4j]\n y = [7.5+1.5j, 5.+1.0j, 8.75+1.75j, 6.25+1.25j, 3.+3j, 3.25+3.25j,\n 3.5+3.5j, 3.75+3.75j]\n assert_almost_equal(np.interp(x, xp, fp, period=360), y)\n\n def test_zero_dimensional_interpolation_point(self):\n x = np.linspace(0, 1, 5)\n y = np.linspace(0, 1, 5)\n x0 = np.array(.3)\n assert_almost_equal(np.interp(x0, x, y), x0)\n\n xp = np.array([0, 2, 4])\n fp = np.array([1, -1, 1])\n\n actual = np.interp(np.array(1), xp, fp)\n assert_equal(actual, 0)\n assert_(isinstance(actual, np.float64))\n\n actual = np.interp(np.array(4.5), xp, fp, period=4)\n assert_equal(actual, 0.5)\n assert_(isinstance(actual, np.float64))\n\n def test_if_len_x_is_small(self):\n xp = np.arange(0, 10, 0.0001)\n fp = np.sin(xp)\n assert_almost_equal(np.interp(np.pi, xp, fp), 0.0)\n\n def test_period(self):\n x = [-180, -170, -185, 185, -10, -5, 0, 365]\n xp = [190, -190, 350, -350]\n fp = [5, 10, 3, 4]\n y = [7.5, 5., 8.75, 6.25, 3., 3.25, 3.5, 3.75]\n assert_almost_equal(np.interp(x, xp, fp, period=360), y)\n x = np.array(x, order='F').reshape(2, -1)\n y = np.array(y, order='C').reshape(2, -1)\n assert_almost_equal(np.interp(x, xp, fp, period=360), y)\n\n\nclass TestPercentile:\n\n def test_basic(self):\n x = np.arange(8) * 0.5\n assert_equal(np.percentile(x, 0), 0.)\n assert_equal(np.percentile(x, 100), 3.5)\n assert_equal(np.percentile(x, 50), 1.75)\n x[1] = np.nan\n assert_equal(np.percentile(x, 0), np.nan)\n assert_equal(np.percentile(x, 0, interpolation='nearest'), np.nan)\n\n def test_fraction(self):\n x = [Fraction(i, 2) for i in range(8)]\n\n p = np.percentile(x, Fraction(0))\n assert_equal(p, Fraction(0))\n assert_equal(type(p), Fraction)\n\n p = np.percentile(x, Fraction(100))\n assert_equal(p, Fraction(7, 2))\n assert_equal(type(p), Fraction)\n\n p = np.percentile(x, Fraction(50))\n assert_equal(p, Fraction(7, 4))\n assert_equal(type(p), Fraction)\n\n p = np.percentile(x, [Fraction(50)])\n assert_equal(p, np.array([Fraction(7, 4)]))\n assert_equal(type(p), np.ndarray)\n\n def test_api(self):\n d = np.ones(5)\n np.percentile(d, 5, None, None, False)\n np.percentile(d, 5, None, None, False, 'linear')\n o = np.ones((1,))\n np.percentile(d, 5, None, o, False, 'linear')\n\n def test_2D(self):\n x = np.array([[1, 1, 1],\n [1, 1, 1],\n [4, 4, 3],\n [1, 1, 1],\n [1, 1, 1]])\n assert_array_equal(np.percentile(x, 50, axis=0), [1, 1, 1])\n\n @pytest.mark.parametrize(\"dtype\", np.typecodes[\"AllFloat\"])\n def test_linear_nan_1D(self, dtype):\n # METHOD 1 of H&F\n arr = np.asarray([15.0, np.NAN, 35.0, 40.0, 50.0], dtype=dtype)\n res = np.percentile(\n arr,\n 40.0,\n interpolation=\"linear\")\n np.testing.assert_equal(res, np.NAN)\n np.testing.assert_equal(res.dtype, arr.dtype)\n\n H_F_TYPE_CODES = [(int_type, np.float64)\n for int_type in np.typecodes[\"AllInteger\"]\n ] + [(np.float16, np.float64),\n (np.float32, np.float64),\n (np.float64, np.float64),\n (np.longdouble, np.longdouble),\n (np.complex64, np.complex128),\n (np.complex128, np.complex128),\n (np.clongdouble, np.clongdouble),\n (np.dtype(\"O\"), np.float64)]\n\n @pytest.mark.parametrize([\"input_dtype\", \"expected_dtype\"], H_F_TYPE_CODES)\n @pytest.mark.parametrize([\"interpolation\", \"expected\"],\n [(\"inverted_cdf\", 20),\n (\"averaged_inverted_cdf\", 27.5),\n (\"closest_observation\", 20),\n (\"interpolated_inverted_cdf\", 20),\n (\"hazen\", 27.5),\n (\"weibull\", 26),\n (\"linear\", 29),\n (\"median_unbiased\", 27),\n (\"normal_unbiased\", 27.125),\n ])\n def test_linear_interpolation(self,\n interpolation,\n expected,\n input_dtype,\n expected_dtype):\n arr = np.asarray([15.0, 20.0, 35.0, 40.0, 50.0], dtype=input_dtype)\n actual = np.percentile(arr, 40.0, interpolation=interpolation)\n\n np.testing.assert_almost_equal(actual, expected, 14)\n\n if interpolation in [\"inverted_cdf\", \"closest_observation\"]:\n if input_dtype == \"O\":\n np.testing.assert_equal(np.asarray(actual).dtype, np.float64)\n else:\n np.testing.assert_equal(np.asarray(actual).dtype,\n np.dtype(input_dtype))\n else:\n np.testing.assert_equal(np.asarray(actual).dtype,\n np.dtype(expected_dtype))\n\n TYPE_CODES = np.typecodes[\"AllInteger\"] + np.typecodes[\"AllFloat\"] + \"O\"\n\n @pytest.mark.parametrize(\"dtype\", TYPE_CODES)\n def test_lower_higher(self, dtype):\n assert_equal(np.percentile(np.arange(10, dtype=dtype), 50,\n interpolation='lower'), 4)\n assert_equal(np.percentile(np.arange(10, dtype=dtype), 50,\n interpolation='higher'), 5)\n\n @pytest.mark.parametrize(\"dtype\", TYPE_CODES)\n def test_midpoint(self, dtype):\n assert_equal(np.percentile(np.arange(10, dtype=dtype), 51,\n interpolation='midpoint'), 4.5)\n assert_equal(np.percentile(np.arange(9, dtype=dtype) + 1, 50,\n interpolation='midpoint'), 5)\n assert_equal(np.percentile(np.arange(11, dtype=dtype), 51,\n interpolation='midpoint'), 5.5)\n assert_equal(np.percentile(np.arange(11, dtype=dtype), 50,\n interpolation='midpoint'), 5)\n\n @pytest.mark.parametrize(\"dtype\", TYPE_CODES)\n def test_nearest(self, dtype):\n assert_equal(np.percentile(np.arange(10, dtype=dtype), 51,\n interpolation='nearest'), 5)\n assert_equal(np.percentile(np.arange(10, dtype=dtype), 49,\n interpolation='nearest'), 4)\n\n def test_linear_interpolation_extrapolation(self):\n arr = np.random.rand(5)\n\n actual = np.percentile(arr, 100)\n np.testing.assert_equal(actual, arr.max())\n\n actual = np.percentile(arr, 0)\n np.testing.assert_equal(actual, arr.min())\n\n def test_sequence(self):\n x = np.arange(8) * 0.5\n assert_equal(np.percentile(x, [0, 100, 50]), [0, 3.5, 1.75])\n\n def test_axis(self):\n x = np.arange(12).reshape(3, 4)\n\n assert_equal(np.percentile(x, (25, 50, 100)), [2.75, 5.5, 11.0])\n\n r0 = [[2, 3, 4, 5], [4, 5, 6, 7], [8, 9, 10, 11]]\n assert_equal(np.percentile(x, (25, 50, 100), axis=0), r0)\n\n r1 = [[0.75, 1.5, 3], [4.75, 5.5, 7], [8.75, 9.5, 11]]\n assert_equal(np.percentile(x, (25, 50, 100), axis=1), np.array(r1).T)\n\n # ensure qth axis is always first as with np.array(old_percentile(..))\n x = np.arange(3 * 4 * 5 * 6).reshape(3, 4, 5, 6)\n assert_equal(np.percentile(x, (25, 50)).shape, (2,))\n assert_equal(np.percentile(x, (25, 50, 75)).shape, (3,))\n assert_equal(np.percentile(x, (25, 50), axis=0).shape, (2, 4, 5, 6))\n assert_equal(np.percentile(x, (25, 50), axis=1).shape, (2, 3, 5, 6))\n assert_equal(np.percentile(x, (25, 50), axis=2).shape, (2, 3, 4, 6))\n assert_equal(np.percentile(x, (25, 50), axis=3).shape, (2, 3, 4, 5))\n assert_equal(\n np.percentile(x, (25, 50, 75), axis=1).shape, (3, 3, 5, 6))\n assert_equal(np.percentile(x, (25, 50),\n interpolation=\"higher\").shape, (2,))\n assert_equal(np.percentile(x, (25, 50, 75),\n interpolation=\"higher\").shape, (3,))\n assert_equal(np.percentile(x, (25, 50), axis=0,\n interpolation=\"higher\").shape, (2, 4, 5, 6))\n assert_equal(np.percentile(x, (25, 50), axis=1,\n interpolation=\"higher\").shape, (2, 3, 5, 6))\n assert_equal(np.percentile(x, (25, 50), axis=2,\n interpolation=\"higher\").shape, (2, 3, 4, 6))\n assert_equal(np.percentile(x, (25, 50), axis=3,\n interpolation=\"higher\").shape, (2, 3, 4, 5))\n assert_equal(np.percentile(x, (25, 50, 75), axis=1,\n interpolation=\"higher\").shape, (3, 3, 5, 6))\n\n def test_scalar_q(self):\n # test for no empty dimensions for compatibility with old percentile\n x = np.arange(12).reshape(3, 4)\n assert_equal(np.percentile(x, 50), 5.5)\n assert_(np.isscalar(np.percentile(x, 50)))\n r0 = np.array([4., 5., 6., 7.])\n assert_equal(np.percentile(x, 50, axis=0), r0)\n assert_equal(np.percentile(x, 50, axis=0).shape, r0.shape)\n r1 = np.array([1.5, 5.5, 9.5])\n assert_almost_equal(np.percentile(x, 50, axis=1), r1)\n assert_equal(np.percentile(x, 50, axis=1).shape, r1.shape)\n\n out = np.empty(1)\n assert_equal(np.percentile(x, 50, out=out), 5.5)\n assert_equal(out, 5.5)\n out = np.empty(4)\n assert_equal(np.percentile(x, 50, axis=0, out=out), r0)\n assert_equal(out, r0)\n out = np.empty(3)\n assert_equal(np.percentile(x, 50, axis=1, out=out), r1)\n assert_equal(out, r1)\n\n # test for no empty dimensions for compatibility with old percentile\n x = np.arange(12).reshape(3, 4)\n assert_equal(np.percentile(x, 50, interpolation='lower'), 5.)\n assert_(np.isscalar(np.percentile(x, 50)))\n r0 = np.array([4., 5., 6., 7.])\n c0 = np.percentile(x, 50, interpolation='lower', axis=0)\n assert_equal(c0, r0)\n assert_equal(c0.shape, r0.shape)\n r1 = np.array([1., 5., 9.])\n c1 = np.percentile(x, 50, interpolation='lower', axis=1)\n assert_almost_equal(c1, r1)\n assert_equal(c1.shape, r1.shape)\n\n out = np.empty((), dtype=x.dtype)\n c = np.percentile(x, 50, interpolation='lower', out=out)\n assert_equal(c, 5)\n assert_equal(out, 5)\n out = np.empty(4, dtype=x.dtype)\n c = np.percentile(x, 50, interpolation='lower', axis=0, out=out)\n assert_equal(c, r0)\n assert_equal(out, r0)\n out = np.empty(3, dtype=x.dtype)\n c = np.percentile(x, 50, interpolation='lower', axis=1, out=out)\n assert_equal(c, r1)\n assert_equal(out, r1)\n\n def test_exception(self):\n assert_raises(ValueError, np.percentile, [1, 2], 56,\n interpolation='foobar')\n assert_raises(ValueError, np.percentile, [1], 101)\n assert_raises(ValueError, np.percentile, [1], -1)\n assert_raises(ValueError, np.percentile, [1], list(range(50)) + [101])\n assert_raises(ValueError, np.percentile, [1], list(range(50)) + [-0.1])\n\n def test_percentile_list(self):\n assert_equal(np.percentile([1, 2, 3], 0), 1)\n\n def test_percentile_out(self):\n x = np.array([1, 2, 3])\n y = np.zeros((3,))\n p = (1, 2, 3)\n np.percentile(x, p, out=y)\n assert_equal(np.percentile(x, p), y)\n\n x = np.array([[1, 2, 3],\n [4, 5, 6]])\n\n y = np.zeros((3, 3))\n np.percentile(x, p, axis=0, out=y)\n assert_equal(np.percentile(x, p, axis=0), y)\n\n y = np.zeros((3, 2))\n np.percentile(x, p, axis=1, out=y)\n assert_equal(np.percentile(x, p, axis=1), y)\n\n x = np.arange(12).reshape(3, 4)\n # q.dim > 1, float\n r0 = np.array([[2., 3., 4., 5.], [4., 5., 6., 7.]])\n out = np.empty((2, 4))\n assert_equal(np.percentile(x, (25, 50), axis=0, out=out), r0)\n assert_equal(out, r0)\n r1 = np.array([[0.75, 4.75, 8.75], [1.5, 5.5, 9.5]])\n out = np.empty((2, 3))\n assert_equal(np.percentile(x, (25, 50), axis=1, out=out), r1)\n assert_equal(out, r1)\n\n # q.dim > 1, int\n r0 = np.array([[0, 1, 2, 3], [4, 5, 6, 7]])\n out = np.empty((2, 4), dtype=x.dtype)\n c = np.percentile(x, (25, 50), interpolation='lower', axis=0, out=out)\n assert_equal(c, r0)\n assert_equal(out, r0)\n r1 = np.array([[0, 4, 8], [1, 5, 9]])\n out = np.empty((2, 3), dtype=x.dtype)\n c = np.percentile(x, (25, 50), interpolation='lower', axis=1, out=out)\n assert_equal(c, r1)\n assert_equal(out, r1)\n\n def test_percentile_empty_dim(self):\n # empty dims are preserved\n d = np.arange(11 * 2).reshape(11, 1, 2, 1)\n assert_array_equal(np.percentile(d, 50, axis=0).shape, (1, 2, 1))\n assert_array_equal(np.percentile(d, 50, axis=1).shape, (11, 2, 1))\n assert_array_equal(np.percentile(d, 50, axis=2).shape, (11, 1, 1))\n assert_array_equal(np.percentile(d, 50, axis=3).shape, (11, 1, 2))\n assert_array_equal(np.percentile(d, 50, axis=-1).shape, (11, 1, 2))\n assert_array_equal(np.percentile(d, 50, axis=-2).shape, (11, 1, 1))\n assert_array_equal(np.percentile(d, 50, axis=-3).shape, (11, 2, 1))\n assert_array_equal(np.percentile(d, 50, axis=-4).shape, (1, 2, 1))\n\n assert_array_equal(np.percentile(d, 50, axis=2,\n interpolation='midpoint').shape,\n (11, 1, 1))\n assert_array_equal(np.percentile(d, 50, axis=-2,\n interpolation='midpoint').shape,\n (11, 1, 1))\n\n assert_array_equal(np.array(np.percentile(d, [10, 50], axis=0)).shape,\n (2, 1, 2, 1))\n assert_array_equal(np.array(np.percentile(d, [10, 50], axis=1)).shape,\n (2, 11, 2, 1))\n assert_array_equal(np.array(np.percentile(d, [10, 50], axis=2)).shape,\n (2, 11, 1, 1))\n assert_array_equal(np.array(np.percentile(d, [10, 50], axis=3)).shape,\n (2, 11, 1, 2))\n\n def test_percentile_no_overwrite(self):\n a = np.array([2, 3, 4, 1])\n np.percentile(a, [50], overwrite_input=False)\n assert_equal(a, np.array([2, 3, 4, 1]))\n\n a = np.array([2, 3, 4, 1])\n np.percentile(a, [50])\n assert_equal(a, np.array([2, 3, 4, 1]))\n\n def test_no_p_overwrite(self):\n p = np.linspace(0., 100., num=5)\n np.percentile(np.arange(100.), p, interpolation=\"midpoint\")\n assert_array_equal(p, np.linspace(0., 100., num=5))\n p = np.linspace(0., 100., num=5).tolist()\n np.percentile(np.arange(100.), p, interpolation=\"midpoint\")\n assert_array_equal(p, np.linspace(0., 100., num=5).tolist())\n\n def test_percentile_overwrite(self):\n a = np.array([2, 3, 4, 1])\n b = np.percentile(a, [50], overwrite_input=True)\n assert_equal(b, np.array([2.5]))\n\n b = np.percentile([2, 3, 4, 1], [50], overwrite_input=True)\n assert_equal(b, np.array([2.5]))\n\n def test_extended_axis(self):\n o = np.random.normal(size=(71, 23))\n x = np.dstack([o] * 10)\n assert_equal(np.percentile(x, 30, axis=(0, 1)), np.percentile(o, 30))\n x = np.moveaxis(x, -1, 0)\n assert_equal(np.percentile(x, 30, axis=(-2, -1)), np.percentile(o, 30))\n x = x.swapaxes(0, 1).copy()\n assert_equal(np.percentile(x, 30, axis=(0, -1)), np.percentile(o, 30))\n x = x.swapaxes(0, 1).copy()\n\n assert_equal(np.percentile(x, [25, 60], axis=(0, 1, 2)),\n np.percentile(x, [25, 60], axis=None))\n assert_equal(np.percentile(x, [25, 60], axis=(0,)),\n np.percentile(x, [25, 60], axis=0))\n\n d = np.arange(3 * 5 * 7 * 11).reshape((3, 5, 7, 11))\n np.random.shuffle(d.ravel())\n assert_equal(np.percentile(d, 25, axis=(0, 1, 2))[0],\n np.percentile(d[:,:,:, 0].flatten(), 25))\n assert_equal(np.percentile(d, [10, 90], axis=(0, 1, 3))[:, 1],\n np.percentile(d[:,:, 1,:].flatten(), [10, 90]))\n assert_equal(np.percentile(d, 25, axis=(3, 1, -4))[2],\n np.percentile(d[:,:, 2,:].flatten(), 25))\n assert_equal(np.percentile(d, 25, axis=(3, 1, 2))[2],\n np.percentile(d[2,:,:,:].flatten(), 25))\n assert_equal(np.percentile(d, 25, axis=(3, 2))[2, 1],\n np.percentile(d[2, 1,:,:].flatten(), 25))\n assert_equal(np.percentile(d, 25, axis=(1, -2))[2, 1],\n np.percentile(d[2,:,:, 1].flatten(), 25))\n assert_equal(np.percentile(d, 25, axis=(1, 3))[2, 2],\n np.percentile(d[2,:, 2,:].flatten(), 25))\n\n def test_extended_axis_invalid(self):\n d = np.ones((3, 5, 7, 11))\n assert_raises(np.AxisError, np.percentile, d, axis=-5, q=25)\n assert_raises(np.AxisError, np.percentile, d, axis=(0, -5), q=25)\n assert_raises(np.AxisError, np.percentile, d, axis=4, q=25)\n assert_raises(np.AxisError, np.percentile, d, axis=(0, 4), q=25)\n # each of these refers to the same axis twice\n assert_raises(ValueError, np.percentile, d, axis=(1, 1), q=25)\n assert_raises(ValueError, np.percentile, d, axis=(-1, -1), q=25)\n assert_raises(ValueError, np.percentile, d, axis=(3, -1), q=25)\n\n def test_keepdims(self):\n d = np.ones((3, 5, 7, 11))\n assert_equal(np.percentile(d, 7, axis=None, keepdims=True).shape,\n (1, 1, 1, 1))\n assert_equal(np.percentile(d, 7, axis=(0, 1), keepdims=True).shape,\n (1, 1, 7, 11))\n assert_equal(np.percentile(d, 7, axis=(0, 3), keepdims=True).shape,\n (1, 5, 7, 1))\n assert_equal(np.percentile(d, 7, axis=(1,), keepdims=True).shape,\n (3, 1, 7, 11))\n assert_equal(np.percentile(d, 7, (0, 1, 2, 3), keepdims=True).shape,\n (1, 1, 1, 1))\n assert_equal(np.percentile(d, 7, axis=(0, 1, 3), keepdims=True).shape,\n (1, 1, 7, 1))\n\n assert_equal(np.percentile(d, [1, 7], axis=(0, 1, 3),\n keepdims=True).shape, (2, 1, 1, 7, 1))\n assert_equal(np.percentile(d, [1, 7], axis=(0, 3),\n keepdims=True).shape, (2, 1, 5, 7, 1))\n\n def test_out(self):\n o = np.zeros((4,))\n d = np.ones((3, 4))\n assert_equal(np.percentile(d, 0, 0, out=o), o)\n assert_equal(np.percentile(d, 0, 0, interpolation='nearest', out=o), o)\n o = np.zeros((3,))\n assert_equal(np.percentile(d, 1, 1, out=o), o)\n assert_equal(np.percentile(d, 1, 1, interpolation='nearest', out=o), o)\n\n o = np.zeros(())\n assert_equal(np.percentile(d, 2, out=o), o)\n assert_equal(np.percentile(d, 2, interpolation='nearest', out=o), o)\n\n def test_out_nan(self):\n with warnings.catch_warnings(record=True):\n warnings.filterwarnings('always', '', RuntimeWarning)\n o = np.zeros((4,))\n d = np.ones((3, 4))\n d[2, 1] = np.nan\n assert_equal(np.percentile(d, 0, 0, out=o), o)\n assert_equal(\n np.percentile(d, 0, 0, interpolation='nearest', out=o), o)\n o = np.zeros((3,))\n assert_equal(np.percentile(d, 1, 1, out=o), o)\n assert_equal(\n np.percentile(d, 1, 1, interpolation='nearest', out=o), o)\n o = np.zeros(())\n assert_equal(np.percentile(d, 1, out=o), o)\n assert_equal(\n np.percentile(d, 1, interpolation='nearest', out=o), o)\n\n def test_nan_behavior(self):\n a = np.arange(24, dtype=float)\n a[2] = np.nan\n assert_equal(np.percentile(a, 0.3), np.nan)\n assert_equal(np.percentile(a, 0.3, axis=0), np.nan)\n assert_equal(np.percentile(a, [0.3, 0.6], axis=0),\n np.array([np.nan] * 2))\n\n a = np.arange(24, dtype=float).reshape(2, 3, 4)\n a[1, 2, 3] = np.nan\n a[1, 1, 2] = np.nan\n\n # no axis\n assert_equal(np.percentile(a, 0.3), np.nan)\n assert_equal(np.percentile(a, 0.3).ndim, 0)\n\n # axis0 zerod\n b = np.percentile(np.arange(24, dtype=float).reshape(2, 3, 4), 0.3, 0)\n b[2, 3] = np.nan\n b[1, 2] = np.nan\n assert_equal(np.percentile(a, 0.3, 0), b)\n\n # axis0 not zerod\n b = np.percentile(np.arange(24, dtype=float).reshape(2, 3, 4),\n [0.3, 0.6], 0)\n b[:, 2, 3] = np.nan\n b[:, 1, 2] = np.nan\n assert_equal(np.percentile(a, [0.3, 0.6], 0), b)\n\n # axis1 zerod\n b = np.percentile(np.arange(24, dtype=float).reshape(2, 3, 4), 0.3, 1)\n b[1, 3] = np.nan\n b[1, 2] = np.nan\n assert_equal(np.percentile(a, 0.3, 1), b)\n # axis1 not zerod\n b = np.percentile(\n np.arange(24, dtype=float).reshape(2, 3, 4), [0.3, 0.6], 1)\n b[:, 1, 3] = np.nan\n b[:, 1, 2] = np.nan\n assert_equal(np.percentile(a, [0.3, 0.6], 1), b)\n\n # axis02 zerod\n b = np.percentile(\n np.arange(24, dtype=float).reshape(2, 3, 4), 0.3, (0, 2))\n b[1] = np.nan\n b[2] = np.nan\n assert_equal(np.percentile(a, 0.3, (0, 2)), b)\n # axis02 not zerod\n b = np.percentile(np.arange(24, dtype=float).reshape(2, 3, 4),\n [0.3, 0.6], (0, 2))\n b[:, 1] = np.nan\n b[:, 2] = np.nan\n assert_equal(np.percentile(a, [0.3, 0.6], (0, 2)), b)\n # axis02 not zerod with nearest interpolation\n b = np.percentile(np.arange(24, dtype=float).reshape(2, 3, 4),\n [0.3, 0.6], (0, 2), interpolation='nearest')\n b[:, 1] = np.nan\n b[:, 2] = np.nan\n assert_equal(np.percentile(\n a, [0.3, 0.6], (0, 2), interpolation='nearest'), b)\n\n def test_nan_q(self):\n # GH18830\n with pytest.raises(ValueError, match=\"Percentiles must be in\"):\n np.percentile([1, 2, 3, 4.0], np.nan)\n with pytest.raises(ValueError, match=\"Percentiles must be in\"):\n np.percentile([1, 2, 3, 4.0], [np.nan])\n q = np.linspace(1.0, 99.0, 16)\n q[0] = np.nan\n with pytest.raises(ValueError, match=\"Percentiles must be in\"):\n np.percentile([1, 2, 3, 4.0], q)\n\n\nclass TestQuantile:\n # most of this is already tested by TestPercentile\n\n def test_max_ulp(self):\n x = [0.0, 0.2, 0.4]\n a = np.quantile(x, 0.45)\n # The default linear method would result in 0 + 0.2 * (0.45/2) = 0.18.\n # 0.18 is not exactly representable and the formula leads to a 1 ULP\n # different result. Ensure it is this exact within 1 ULP, see gh-20331.\n np.testing.assert_array_max_ulp(a, 0.18, maxulp=1)\n\n def test_basic(self):\n x = np.arange(8) * 0.5\n assert_equal(np.quantile(x, 0), 0.)\n assert_equal(np.quantile(x, 1), 3.5)\n assert_equal(np.quantile(x, 0.5), 1.75)\n\n @pytest.mark.xfail(reason=\"See gh-19154\")\n def test_correct_quantile_value(self):\n a = np.array([True])\n tf_quant = np.quantile(True, False)\n assert_equal(tf_quant, a[0])\n assert_equal(type(tf_quant), a.dtype)\n a = np.array([False, True, True])\n quant_res = np.quantile(a, a)\n assert_array_equal(quant_res, a)\n assert_equal(quant_res.dtype, a.dtype)\n\n def test_fraction(self):\n # fractional input, integral quantile\n x = [Fraction(i, 2) for i in range(8)]\n q = np.quantile(x, 0)\n assert_equal(q, 0)\n assert_equal(type(q), Fraction)\n\n q = np.quantile(x, 1)\n assert_equal(q, Fraction(7, 2))\n assert_equal(type(q), Fraction)\n\n q = np.quantile(x, Fraction(1, 2))\n assert_equal(q, Fraction(7, 4))\n assert_equal(type(q), Fraction)\n\n q = np.quantile(x, [Fraction(1, 2)])\n assert_equal(q, np.array([Fraction(7, 4)]))\n assert_equal(type(q), np.ndarray)\n\n q = np.quantile(x, [[Fraction(1, 2)]])\n assert_equal(q, np.array([[Fraction(7, 4)]]))\n assert_equal(type(q), np.ndarray)\n\n # repeat with integral input but fractional quantile\n x = np.arange(8)\n assert_equal(np.quantile(x, Fraction(1, 2)), Fraction(7, 2))\n\n def test_no_p_overwrite(self):\n # this is worth retesting, because quantile does not make a copy\n p0 = np.array([0, 0.75, 0.25, 0.5, 1.0])\n p = p0.copy()\n np.quantile(np.arange(100.), p, interpolation=\"midpoint\")\n assert_array_equal(p, p0)\n\n p0 = p0.tolist()\n p = p.tolist()\n np.quantile(np.arange(100.), p, interpolation=\"midpoint\")\n assert_array_equal(p, p0)\n\n @pytest.mark.parametrize(\"dtype\", np.typecodes[\"AllInteger\"])\n def test_quantile_preserve_int_type(self, dtype):\n res = np.quantile(np.array([1, 2], dtype=dtype), [0.5],\n interpolation=\"nearest\")\n assert res.dtype == dtype\n\n def test_quantile_monotonic(self):\n # GH 14685\n # test that the return value of quantile is monotonic if p0 is ordered\n p0 = np.arange(0, 1, 0.01)\n quantile = np.quantile(np.array([0, 1, 1, 2, 2, 3, 3, 4, 5, 5, 1, 1, 9, 9, 9,\n 8, 8, 7]) * 0.1, p0)\n assert_equal(np.sort(quantile), quantile)\n\n @hypothesis.given(\n arr=arrays(dtype=np.float64,\n shape=st.integers(min_value=3, max_value=1000),\n elements=st.floats(allow_infinity=False, allow_nan=False,\n min_value=-1e300, max_value=1e300)))\n def test_quantile_monotonic_hypo(self, arr):\n p0 = np.arange(0, 1, 0.01)\n quantile = np.quantile(arr, p0)\n assert_equal(np.sort(quantile), quantile)\n\n def test_quantile_scalar_nan(self):\n a = np.array([[10., 7., 4.], [3., 2., 1.]])\n a[0][1] = np.nan\n actual = np.quantile(a, 0.5)\n assert np.isscalar(actual)\n assert_equal(np.quantile(a, 0.5), np.nan)\n\nclass TestLerp:\n @hypothesis.given(t0=st.floats(allow_nan=False, allow_infinity=False,\n min_value=0, max_value=1),\n t1=st.floats(allow_nan=False, allow_infinity=False,\n min_value=0, max_value=1),\n a = st.floats(allow_nan=False, allow_infinity=False,\n min_value=-1e300, max_value=1e300),\n b = st.floats(allow_nan=False, allow_infinity=False,\n min_value=-1e300, max_value=1e300))\n def test_linear_interpolation_formula_monotonic(self, t0, t1, a, b):\n l0 = nfb._lerp(a, b, t0)\n l1 = nfb._lerp(a, b, t1)\n if t0 == t1 or a == b:\n assert l0 == l1 # uninteresting\n elif (t0 < t1) == (a < b):\n assert l0 <= l1\n else:\n assert l0 >= l1\n\n @hypothesis.given(t=st.floats(allow_nan=False, allow_infinity=False,\n min_value=0, max_value=1),\n a=st.floats(allow_nan=False, allow_infinity=False,\n min_value=-1e300, max_value=1e300),\n b=st.floats(allow_nan=False, allow_infinity=False,\n min_value=-1e300, max_value=1e300))\n def test_linear_interpolation_formula_bounded(self, t, a, b):\n if a <= b:\n assert a <= nfb._lerp(a, b, t) <= b\n else:\n assert b <= nfb._lerp(a, b, t) <= a\n\n @hypothesis.given(t=st.floats(allow_nan=False, allow_infinity=False,\n min_value=0, max_value=1),\n a=st.floats(allow_nan=False, allow_infinity=False,\n min_value=-1e300, max_value=1e300),\n b=st.floats(allow_nan=False, allow_infinity=False,\n min_value=-1e300, max_value=1e300))\n def test_linear_interpolation_formula_symmetric(self, t, a, b):\n # double subtraction is needed to remove the extra precision of t < 0.5\n left = nfb._lerp(a, b, 1 - (1 - t))\n right = nfb._lerp(b, a, 1 - t)\n assert left == right\n\n def test_linear_interpolation_formula_0d_inputs(self):\n a = np.array(2)\n b = np.array(5)\n t = np.array(0.2)\n assert nfb._lerp(a, b, t) == 2.6\n\n\nclass TestMedian:\n\n def test_basic(self):\n a0 = np.array(1)\n a1 = np.arange(2)\n a2 = np.arange(6).reshape(2, 3)\n assert_equal(np.median(a0), 1)\n assert_allclose(np.median(a1), 0.5)\n assert_allclose(np.median(a2), 2.5)\n assert_allclose(np.median(a2, axis=0), [1.5, 2.5, 3.5])\n assert_equal(np.median(a2, axis=1), [1, 4])\n assert_allclose(np.median(a2, axis=None), 2.5)\n\n a = np.array([0.0444502, 0.0463301, 0.141249, 0.0606775])\n assert_almost_equal((a[1] + a[3]) / 2., np.median(a))\n a = np.array([0.0463301, 0.0444502, 0.141249])\n assert_equal(a[0], np.median(a))\n a = np.array([0.0444502, 0.141249, 0.0463301])\n assert_equal(a[-1], np.median(a))\n # check array scalar result\n assert_equal(np.median(a).ndim, 0)\n a[1] = np.nan\n assert_equal(np.median(a).ndim, 0)\n\n def test_axis_keyword(self):\n a3 = np.array([[2, 3],\n [0, 1],\n [6, 7],\n [4, 5]])\n for a in [a3, np.random.randint(0, 100, size=(2, 3, 4))]:\n orig = a.copy()\n np.median(a, axis=None)\n for ax in range(a.ndim):\n np.median(a, axis=ax)\n assert_array_equal(a, orig)\n\n assert_allclose(np.median(a3, axis=0), [3, 4])\n assert_allclose(np.median(a3.T, axis=1), [3, 4])\n assert_allclose(np.median(a3), 3.5)\n assert_allclose(np.median(a3, axis=None), 3.5)\n assert_allclose(np.median(a3.T), 3.5)\n\n def test_overwrite_keyword(self):\n a3 = np.array([[2, 3],\n [0, 1],\n [6, 7],\n [4, 5]])\n a0 = np.array(1)\n a1 = np.arange(2)\n a2 = np.arange(6).reshape(2, 3)\n assert_allclose(np.median(a0.copy(), overwrite_input=True), 1)\n assert_allclose(np.median(a1.copy(), overwrite_input=True), 0.5)\n assert_allclose(np.median(a2.copy(), overwrite_input=True), 2.5)\n assert_allclose(np.median(a2.copy(), overwrite_input=True, axis=0),\n [1.5, 2.5, 3.5])\n assert_allclose(\n np.median(a2.copy(), overwrite_input=True, axis=1), [1, 4])\n assert_allclose(\n np.median(a2.copy(), overwrite_input=True, axis=None), 2.5)\n assert_allclose(\n np.median(a3.copy(), overwrite_input=True, axis=0), [3, 4])\n assert_allclose(np.median(a3.T.copy(), overwrite_input=True, axis=1),\n [3, 4])\n\n a4 = np.arange(3 * 4 * 5, dtype=np.float32).reshape((3, 4, 5))\n np.random.shuffle(a4.ravel())\n assert_allclose(np.median(a4, axis=None),\n np.median(a4.copy(), axis=None, overwrite_input=True))\n assert_allclose(np.median(a4, axis=0),\n np.median(a4.copy(), axis=0, overwrite_input=True))\n assert_allclose(np.median(a4, axis=1),\n np.median(a4.copy(), axis=1, overwrite_input=True))\n assert_allclose(np.median(a4, axis=2),\n np.median(a4.copy(), axis=2, overwrite_input=True))\n\n def test_array_like(self):\n x = [1, 2, 3]\n assert_almost_equal(np.median(x), 2)\n x2 = [x]\n assert_almost_equal(np.median(x2), 2)\n assert_allclose(np.median(x2, axis=0), x)\n\n def test_subclass(self):\n # gh-3846\n class MySubClass(np.ndarray):\n\n def __new__(cls, input_array, info=None):\n obj = np.asarray(input_array).view(cls)\n obj.info = info\n return obj\n\n def mean(self, axis=None, dtype=None, out=None):\n return -7\n\n a = MySubClass([1, 2, 3])\n assert_equal(np.median(a), -7)\n\n @pytest.mark.parametrize('arr',\n ([1., 2., 3.], [1., np.nan, 3.], np.nan, 0.))\n def test_subclass2(self, arr):\n \"\"\"Check that we return subclasses, even if a NaN scalar.\"\"\"\n class MySubclass(np.ndarray):\n pass\n\n m = np.median(np.array(arr).view(MySubclass))\n assert isinstance(m, MySubclass)\n\n def test_out(self):\n o = np.zeros((4,))\n d = np.ones((3, 4))\n assert_equal(np.median(d, 0, out=o), o)\n o = np.zeros((3,))\n assert_equal(np.median(d, 1, out=o), o)\n o = np.zeros(())\n assert_equal(np.median(d, out=o), o)\n\n def test_out_nan(self):\n with warnings.catch_warnings(record=True):\n warnings.filterwarnings('always', '', RuntimeWarning)\n o = np.zeros((4,))\n d = np.ones((3, 4))\n d[2, 1] = np.nan\n assert_equal(np.median(d, 0, out=o), o)\n o = np.zeros((3,))\n assert_equal(np.median(d, 1, out=o), o)\n o = np.zeros(())\n assert_equal(np.median(d, out=o), o)\n\n def test_nan_behavior(self):\n a = np.arange(24, dtype=float)\n a[2] = np.nan\n assert_equal(np.median(a), np.nan)\n assert_equal(np.median(a, axis=0), np.nan)\n\n a = np.arange(24, dtype=float).reshape(2, 3, 4)\n a[1, 2, 3] = np.nan\n a[1, 1, 2] = np.nan\n\n # no axis\n assert_equal(np.median(a), np.nan)\n assert_equal(np.median(a).ndim, 0)\n\n # axis0\n b = np.median(np.arange(24, dtype=float).reshape(2, 3, 4), 0)\n b[2, 3] = np.nan\n b[1, 2] = np.nan\n assert_equal(np.median(a, 0), b)\n\n # axis1\n b = np.median(np.arange(24, dtype=float).reshape(2, 3, 4), 1)\n b[1, 3] = np.nan\n b[1, 2] = np.nan\n assert_equal(np.median(a, 1), b)\n\n # axis02\n b = np.median(np.arange(24, dtype=float).reshape(2, 3, 4), (0, 2))\n b[1] = np.nan\n b[2] = np.nan\n assert_equal(np.median(a, (0, 2)), b)\n\n def test_empty(self):\n # mean(empty array) emits two warnings: empty slice and divide by 0\n a = np.array([], dtype=float)\n with warnings.catch_warnings(record=True) as w:\n warnings.filterwarnings('always', '', RuntimeWarning)\n assert_equal(np.median(a), np.nan)\n assert_(w[0].category is RuntimeWarning)\n assert_equal(len(w), 2)\n\n # multiple dimensions\n a = np.array([], dtype=float, ndmin=3)\n # no axis\n with warnings.catch_warnings(record=True) as w:\n warnings.filterwarnings('always', '', RuntimeWarning)\n assert_equal(np.median(a), np.nan)\n assert_(w[0].category is RuntimeWarning)\n\n # axis 0 and 1\n b = np.array([], dtype=float, ndmin=2)\n assert_equal(np.median(a, axis=0), b)\n assert_equal(np.median(a, axis=1), b)\n\n # axis 2\n b = np.array(np.nan, dtype=float, ndmin=2)\n with warnings.catch_warnings(record=True) as w:\n warnings.filterwarnings('always', '', RuntimeWarning)\n assert_equal(np.median(a, axis=2), b)\n assert_(w[0].category is RuntimeWarning)\n\n def test_object(self):\n o = np.arange(7.)\n assert_(type(np.median(o.astype(object))), float)\n o[2] = np.nan\n assert_(type(np.median(o.astype(object))), float)\n\n def test_extended_axis(self):\n o = np.random.normal(size=(71, 23))\n x = np.dstack([o] * 10)\n assert_equal(np.median(x, axis=(0, 1)), np.median(o))\n x = np.moveaxis(x, -1, 0)\n assert_equal(np.median(x, axis=(-2, -1)), np.median(o))\n x = x.swapaxes(0, 1).copy()\n assert_equal(np.median(x, axis=(0, -1)), np.median(o))\n\n assert_equal(np.median(x, axis=(0, 1, 2)), np.median(x, axis=None))\n assert_equal(np.median(x, axis=(0, )), np.median(x, axis=0))\n assert_equal(np.median(x, axis=(-1, )), np.median(x, axis=-1))\n\n d = np.arange(3 * 5 * 7 * 11).reshape((3, 5, 7, 11))\n np.random.shuffle(d.ravel())\n assert_equal(np.median(d, axis=(0, 1, 2))[0],\n np.median(d[:,:,:, 0].flatten()))\n assert_equal(np.median(d, axis=(0, 1, 3))[1],\n np.median(d[:,:, 1,:].flatten()))\n assert_equal(np.median(d, axis=(3, 1, -4))[2],\n np.median(d[:,:, 2,:].flatten()))\n assert_equal(np.median(d, axis=(3, 1, 2))[2],\n np.median(d[2,:,:,:].flatten()))\n assert_equal(np.median(d, axis=(3, 2))[2, 1],\n np.median(d[2, 1,:,:].flatten()))\n assert_equal(np.median(d, axis=(1, -2))[2, 1],\n np.median(d[2,:,:, 1].flatten()))\n assert_equal(np.median(d, axis=(1, 3))[2, 2],\n np.median(d[2,:, 2,:].flatten()))\n\n def test_extended_axis_invalid(self):\n d = np.ones((3, 5, 7, 11))\n assert_raises(np.AxisError, np.median, d, axis=-5)\n assert_raises(np.AxisError, np.median, d, axis=(0, -5))\n assert_raises(np.AxisError, np.median, d, axis=4)\n assert_raises(np.AxisError, np.median, d, axis=(0, 4))\n assert_raises(ValueError, np.median, d, axis=(1, 1))\n\n def test_keepdims(self):\n d = np.ones((3, 5, 7, 11))\n assert_equal(np.median(d, axis=None, keepdims=True).shape,\n (1, 1, 1, 1))\n assert_equal(np.median(d, axis=(0, 1), keepdims=True).shape,\n (1, 1, 7, 11))\n assert_equal(np.median(d, axis=(0, 3), keepdims=True).shape,\n (1, 5, 7, 1))\n assert_equal(np.median(d, axis=(1,), keepdims=True).shape,\n (3, 1, 7, 11))\n assert_equal(np.median(d, axis=(0, 1, 2, 3), keepdims=True).shape,\n (1, 1, 1, 1))\n assert_equal(np.median(d, axis=(0, 1, 3), keepdims=True).shape,\n (1, 1, 7, 1))\n\n\nclass TestAdd_newdoc_ufunc:\n\n def test_ufunc_arg(self):\n assert_raises(TypeError, add_newdoc_ufunc, 2, \"blah\")\n assert_raises(ValueError, add_newdoc_ufunc, np.add, \"blah\")\n\n def test_string_arg(self):\n assert_raises(TypeError, add_newdoc_ufunc, np.add, 3)\n\n\nclass TestAdd_newdoc:\n\n @pytest.mark.skipif(sys.flags.optimize == 2, reason=\"Python running -OO\")\n @pytest.mark.xfail(IS_PYPY, reason=\"PyPy does not modify tp_doc\")\n def test_add_doc(self):\n # test that np.add_newdoc did attach a docstring successfully:\n tgt = \"Current flat index into the array.\"\n assert_equal(np.core.flatiter.index.__doc__[:len(tgt)], tgt)\n assert_(len(np.core.ufunc.identity.__doc__) > 300)\n assert_(len(np.lib.index_tricks.mgrid.__doc__) > 300)\n\n @pytest.mark.skipif(sys.flags.optimize == 2, reason=\"Python running -OO\")\n def test_errors_are_ignored(self):\n prev_doc = np.core.flatiter.index.__doc__\n # nothing changed, but error ignored, this should probably\n # give a warning (or even error) in the future.\n np.add_newdoc(\"numpy.core\", \"flatiter\", (\"index\", \"bad docstring\"))\n assert prev_doc == np.core.flatiter.index.__doc__\n\n\nclass TestAddDocstring():\n # Test should possibly be moved, but it also fits to be close to\n # the newdoc tests...\n @pytest.mark.skipif(sys.flags.optimize == 2, reason=\"Python running -OO\")\n @pytest.mark.skipif(IS_PYPY, reason=\"PyPy does not modify tp_doc\")\n def test_add_same_docstring(self):\n # test for attributes (which are C-level defined)\n np.add_docstring(np.ndarray.flat, np.ndarray.flat.__doc__)\n # And typical functions:\n def func():\n \"\"\"docstring\"\"\"\n return\n\n np.add_docstring(func, func.__doc__)\n\n @pytest.mark.skipif(sys.flags.optimize == 2, reason=\"Python running -OO\")\n def test_different_docstring_fails(self):\n # test for attributes (which are C-level defined)\n with assert_raises(RuntimeError):\n np.add_docstring(np.ndarray.flat, \"different docstring\")\n # And typical functions:\n def func():\n \"\"\"docstring\"\"\"\n return\n\n with assert_raises(RuntimeError):\n np.add_docstring(func, \"different docstring\")\n\n\nclass TestSortComplex:\n\n @pytest.mark.parametrize(\"type_in, type_out\", [\n ('l', 'D'),\n ('h', 'F'),\n ('H', 'F'),\n ('b', 'F'),\n ('B', 'F'),\n ('g', 'G'),\n ])\n def test_sort_real(self, type_in, type_out):\n # sort_complex() type casting for real input types\n a = np.array([5, 3, 6, 2, 1], dtype=type_in)\n actual = np.sort_complex(a)\n expected = np.sort(a).astype(type_out)\n assert_equal(actual, expected)\n assert_equal(actual.dtype, expected.dtype)\n\n def test_sort_complex(self):\n # sort_complex() handling of complex input\n a = np.array([2 + 3j, 1 - 2j, 1 - 3j, 2 + 1j], dtype='D')\n expected = np.array([1 - 3j, 1 - 2j, 2 + 1j, 2 + 3j], dtype='D')\n actual = np.sort_complex(a)\n assert_equal(actual, expected)\n assert_equal(actual.dtype, expected.dtype)\n"
] |
[
[
"numpy.lib.unwrap",
"numpy.sqrt",
"numpy.cumsum",
"numpy.all",
"numpy.lib.blackman",
"numpy.broadcast",
"numpy.digitize",
"numpy.exp",
"numpy.lib.setxor1d",
"numpy.sin",
"numpy.diff",
"numpy.insert",
"numpy.zeros",
"numpy.testing.assert_raises_regex",
"numpy.multiply",
"numpy.median",
"numpy.cumprod",
"numpy.testing.assert_raises",
"numpy.array",
"numpy.sometrue",
"numpy.sum",
"numpy.gradient",
"numpy.lib.sinc",
"numpy.add_newdoc",
"numpy.lib.hanning",
"numpy.testing.assert_array_equal",
"numpy.float_",
"numpy.lib.function_base._parse_gufunc_signature",
"numpy.lib.flipud",
"numpy.lib.interp",
"numpy.arctan",
"numpy.asarray",
"numpy.lib.trapz",
"numpy.iinfo",
"numpy.var",
"numpy.lib.trim_zeros",
"numpy.lib.unique",
"numpy.lib.rot90",
"numpy.testing.suppress_warnings",
"numpy.ma.arange",
"numpy.copy",
"numpy.float32",
"numpy.lib.gradient",
"numpy.lib.i0",
"numpy.lib.select",
"numpy.amin",
"numpy.lib.extract",
"numpy.random.rand",
"numpy.testing.assert_",
"numpy.corrcoef",
"numpy.lib.piecewise",
"numpy.errstate",
"numpy.testing.assert_warns",
"numpy.i0",
"numpy.lib.average",
"numpy.ones",
"numpy.vectorize",
"numpy.isscalar",
"numpy.lib.meshgrid",
"numpy.empty",
"numpy.add_docstring",
"numpy.linspace",
"numpy.alltrue",
"numpy.zeros_like",
"numpy.moveaxis",
"numpy.random.randint",
"numpy.testing.assert_equal",
"numpy.interp",
"numpy.sort_complex",
"numpy.lib.vectorize",
"numpy.ma.ones",
"numpy.lib.angle",
"numpy.lib.hamming",
"numpy.testing.assert_array_almost_equal",
"numpy.isnan",
"numpy.quantile",
"numpy.testing.assert_allclose",
"numpy.tile",
"numpy.cos",
"numpy.percentile",
"numpy.dstack",
"numpy.bincount",
"numpy.lib.place",
"numpy.amax",
"numpy.lib.delete",
"numpy.testing.assert_array_max_ulp",
"numpy.lib.bartlett",
"numpy.dtype",
"numpy.any",
"numpy.ma.array",
"numpy.lib.cov",
"numpy.ones_like",
"numpy.arange",
"numpy.stack",
"numpy.testing.assert_almost_equal",
"numpy.lib.msort",
"numpy.lib.corrcoef",
"numpy.lib.asarray_chkfinite",
"numpy.lib.insert",
"numpy.meshgrid",
"numpy.flip",
"numpy.lib.diff",
"numpy.random.random",
"numpy.random.seed",
"numpy.abs",
"numpy.add.outer",
"numpy.lib.kaiser",
"numpy.sort",
"numpy.result_type",
"numpy.random.normal",
"numpy.float64",
"numpy.prod",
"numpy.mod",
"numpy.average",
"numpy.lib.function_base._lerp",
"numpy.lib.digitize"
]
] |
AndreaCeccarelli/gpu-monitor
|
[
"aad4dc88387a69235e9c370cb08da1f16ba4aa96"
] |
[
"mnist.py"
] |
[
"import torch as torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport numpy as np\nfrom art.utils import load_dataset\nimport art.attacks\nfrom art.classifiers import PyTorchClassifier\nfrom art.utils import load_mnist\nfrom art.utils import load_cifar10\nimport torchvision\nimport torchvision.transforms as transforms\nfrom sklearn.datasets import load_iris\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nimport datasetSTL10\nfrom datasetSTL10 import stl10\nfrom sklearn.utils import shuffle\n\n#mnist\nclass Net(nn.Module):\n\tdef __init__(self):\n\t\tsuper(Net, self).__init__()\n\t\tself.conv_1 = nn.Conv2d(in_channels=1, out_channels=4, kernel_size=5, stride=1)\n\t\tself.conv_2 = nn.Conv2d(in_channels=4, out_channels=10, kernel_size=5, stride=1)\n\t\tself.fc_1 = nn.Linear(in_features=4 * 4 * 10, out_features=100)\n\t\tself.fc_2 = nn.Linear(in_features=100, out_features=10)\n\n\tdef forward(self, x):\n\t\tx = F.relu(self.conv_1(x))\n\t\tx = F.max_pool2d(x, 2, 2)\n\t\tx = F.relu(self.conv_2(x))\n\t\tx = F.max_pool2d(x, 2, 2)\n\t\tx = x.view(-1, 4 * 4 * 10)\n\t\tx = F.relu(self.fc_1(x))\n\t\tx = self.fc_2(x)\n\t\treturn x\n"
] |
[
[
"torch.nn.Linear",
"torch.nn.Conv2d",
"torch.nn.functional.max_pool2d"
]
] |
udapy/applied-ml
|
[
"9cd4efb5ae4b201f10c92cc1f79b64c04e99b1f7"
] |
[
"tests/tagifai/test_data.py"
] |
[
"# tests/tagifai/test_data.py\n# Test tagifai/data.py components.\n\nimport itertools\nimport tempfile\nfrom argparse import Namespace\nfrom collections import Counter\nfrom pathlib import Path\n\nimport numpy as np\nimport pytest\n\nfrom app import config\nfrom tagifai import data, main, utils\n\n\[email protected](scope=\"module\")\ndef tags():\n # Load tags\n tags_url = \"https://raw.githubusercontent.com/GokuMohandas/MadeWithML/main/datasets/tags.json\"\n tags_dict = utils.load_json_from_url(url=tags_url)\n tags = [tag[\"tag\"] for tag in tags_dict]\n return tags\n\n\[email protected](scope=\"module\")\ndef df():\n # Load features\n params_fp = Path(config.CONFIG_DIR, \"params.json\")\n params = Namespace(**utils.load_dict(filepath=params_fp))\n df, _ = main.compute_features(params=params)\n return df\n\n\[email protected](\n \"items, include, filtered\",\n [\n # one item\n ([\"apple\"], [\"apple\"], [\"apple\"]),\n # multiple items\n (\n [\"apple\", \"banana\", \"grape\", \"orange\"],\n [\"apple\"],\n [\"apple\"],\n ),\n # multiple include\n (\n [\"apple\", \"banana\", \"grape\", \"orange\"],\n [\"apple\", \"grape\"],\n [\"apple\", \"grape\"],\n ),\n # no include\n (\n [\"apple\", \"banana\", \"grape\", \"orange\"],\n [],\n [],\n ),\n ],\n)\ndef test_filter_items(items, include, filtered):\n assert data.filter_items(items=items, include=include) == filtered\n\n\ndef test_clean(tags, df):\n min_tag_freq = 30\n df, tags_above_freq, tags_below_freq = data.prepare(\n df=df,\n include=tags,\n exclude=config.EXCLUDED_TAGS,\n min_tag_freq=min_tag_freq,\n )\n all_tags = list(itertools.chain.from_iterable(df.tags))\n assert Counter(all_tags).most_common()[-1][1] >= min_tag_freq\n\n\[email protected](\n \"text, lower, stem, filters, stopwords, preprocessed_text\",\n [\n (\"Hello worlds\", False, False, \"\", [], \"Hello worlds\"),\n (\"Hello worlds\", True, False, \"\", [], \"hello worlds\"),\n (\"Hello worlds\", False, True, \"\", [], \"Hello world\"),\n (\"Hello worlds\", True, True, \"\", [], \"hello world\"),\n (\"Hello worlds\", True, True, \"l\", [], \"heo word\"),\n (\"Hello worlds\", True, True, \"\", [\"world\"], \"hello world\"),\n (\"Hello worlds\", True, True, \"\", [\"worlds\"], \"hello\"),\n ],\n)\ndef test_preprocess(text, lower, stem, filters, stopwords, preprocessed_text):\n assert (\n data.preprocess(\n text=text,\n lower=lower,\n stem=stem,\n filters=filters,\n stopwords=stopwords,\n )\n == preprocessed_text\n )\n\n\nclass TestLabelEncoder:\n @classmethod\n def setup_class(cls):\n \"\"\"Called before every class initialization.\"\"\"\n pass\n\n @classmethod\n def teardown_class(cls):\n \"\"\"Called after every class initialization.\"\"\"\n pass\n\n def setup_method(self):\n \"\"\"Called before every method.\"\"\"\n self.label_encoder = data.LabelEncoder()\n\n def teardown_method(self):\n \"\"\"Called after every method.\"\"\"\n del self.label_encoder\n\n def test_empty_init(self):\n label_encoder = data.LabelEncoder()\n assert label_encoder.index_to_class == {}\n assert len(label_encoder.classes) == 0\n\n def test_dict_init(self):\n class_to_index = {\"apple\": 0, \"banana\": 1}\n label_encoder = data.LabelEncoder(class_to_index=class_to_index)\n assert label_encoder.index_to_class == {0: \"apple\", 1: \"banana\"}\n assert len(label_encoder.classes) == 2\n\n def test_len(self):\n assert len(self.label_encoder) == 0\n\n def test_save_and_load(self):\n with tempfile.TemporaryDirectory() as dp:\n fp = Path(dp, \"label_encoder.json\")\n self.label_encoder.save(fp=fp)\n label_encoder = data.LabelEncoder.load(fp=fp)\n assert len(label_encoder.classes) == 0\n\n @pytest.mark.parametrize(\n \"label_encoder, output\",\n [\n (data.MultiClassLabelEncoder(), \"<MultiClassLabelEncoder(num_classes=0)>\"),\n (data.MultiLabelLabelEncoder(), \"<MultiLabelLabelEncoder(num_classes=0)>\"),\n ],\n )\n def test_str(self, label_encoder, output):\n assert str(label_encoder) == output\n\n @pytest.mark.parametrize(\n \"label_encoder, y\",\n [\n (data.MultiClassLabelEncoder(), [\"apple\", \"apple\", \"banana\"]),\n (data.MultiLabelLabelEncoder(), [[\"apple\"], [\"apple\", \"banana\"]]),\n ],\n )\n def test_fit(self, label_encoder, y):\n label_encoder.fit(y)\n assert \"apple\" in label_encoder.class_to_index\n assert \"banana\" in label_encoder.class_to_index\n assert len(label_encoder.classes) == 2\n\n @pytest.mark.parametrize(\n \"label_encoder, y, y_encoded\",\n [\n (\n data.MultiClassLabelEncoder(class_to_index={\"apple\": 0, \"banana\": 1}),\n [\"apple\", \"apple\", \"banana\"],\n [0, 0, 1],\n ),\n (\n data.MultiLabelLabelEncoder(class_to_index={\"apple\": 0, \"banana\": 1}),\n [[\"apple\"], [\"apple\", \"banana\"]],\n [[1, 0], [1, 1]],\n ),\n ],\n )\n def test_encode_decode(self, label_encoder, y, y_encoded):\n label_encoder.fit(y)\n assert np.array_equal(label_encoder.encode(y), np.array(y_encoded))\n assert label_encoder.decode(y_encoded) == y\n\n\ndef test_iterative_train_test_split(tags, df):\n # Process\n df, tags_above_freq, tags_below_freq = data.prepare(df=df, include=tags, min_tag_freq=1)\n df.text = df.text.apply(data.preprocess)\n\n # Encode labels\n labels = df.tags\n label_encoder = data.MultiLabelLabelEncoder()\n label_encoder.fit(labels)\n y = label_encoder.encode(labels)\n\n # Split data\n X = df.text.to_numpy()\n X_train, X_, y_train, y_ = data.iterative_train_test_split(X=X, y=y, train_size=0.7)\n X_val, X_test, y_val, y_test = data.iterative_train_test_split(X=X_, y=y_, train_size=0.5)\n\n assert len(X_train) == len(y_train)\n assert len(X_val) == len(y_val)\n assert len(X_test) == len(y_test)\n assert len(X_train) / float(len(X)) == pytest.approx(0.7, abs=0.05) # 0.7 ± 0.05\n assert len(X_val) / float(len(X)) == pytest.approx(0.15, abs=0.05) # 0.15 ± 0.05\n assert len(X_test) / float(len(X)) == pytest.approx(0.15, abs=0.05) # 0.15 ± 0.05\n\n\nclass TestTokenizer:\n def setup_method(self):\n \"\"\"Called before every method.\"\"\"\n self.tokenizer = data.Tokenizer(char_level=True, num_tokens=None)\n\n def teardown_method(self):\n \"\"\"Called after every method.\"\"\"\n del self.tokenizer\n\n @pytest.mark.parametrize(\n \"char_level, num_tokens, separator, token_to_index, expected_token_to_index\",\n [\n (True, None, \"\", None, {\"<PAD>\": 0, \"<UNK>\": 1}),\n (False, None, \" \", None, {\"<PAD>\": 0, \"<UNK>\": 1}),\n (\n False,\n None,\n \" \",\n {\"<PAD>\": 0, \"<UNK>\": 1, \"hello\": 2},\n {\"<PAD>\": 0, \"<UNK>\": 1, \"hello\": 2},\n ),\n ],\n )\n def test_init(self, char_level, num_tokens, separator, token_to_index, expected_token_to_index):\n tokenizer = data.Tokenizer(\n char_level=char_level, num_tokens=num_tokens, token_to_index=token_to_index\n )\n assert tokenizer.separator == separator\n assert tokenizer.token_to_index == expected_token_to_index\n\n def test_len(self):\n assert len(self.tokenizer) == 2\n\n def test_str(self):\n assert str(self.tokenizer) == f\"<Tokenizer(num_tokens={len(self.tokenizer)})>\"\n\n @pytest.mark.parametrize(\n \"char_level, num_tokens, texts, vocab_size\",\n [(False, None, [\"hello world\", \"goodbye\"], 5), (False, 4, [\"hello world\", \"goodbye\"], 4)],\n )\n def test_fit_on_texts(self, char_level, num_tokens, texts, vocab_size):\n tokenizer = data.Tokenizer(char_level=char_level, num_tokens=num_tokens)\n tokenizer.fit_on_texts(texts=texts)\n assert len(tokenizer) == vocab_size\n\n @pytest.mark.parametrize(\n \"tokenizer, texts, sequences, decoded\",\n [\n (\n data.Tokenizer(\n char_level=False,\n token_to_index={\"<PAD>\": 0, \"<UNK>\": 1, \"hello\": 2, \"world\": 3},\n ),\n [\"hello world\", \"hi world\", \"apple\"],\n [[2, 3], [1, 3], [1]],\n [\"hello world\", \"<UNK> world\", \"<UNK>\"],\n ),\n (\n data.Tokenizer(\n char_level=True, token_to_index={\"<PAD>\": 0, \"<UNK>\": 1, \" \": 2, \"a\": 3, \"b\": 4}\n ),\n [\"ab\", \"b\", \"a x ab\"],\n [[3, 4], [4], [3, 2, 1, 2, 3, 4]],\n [\"ab\", \"b\", \"a <UNK> ab\"],\n ),\n ],\n )\n def test_encode_decode(self, tokenizer, texts, sequences, decoded):\n assert tokenizer.texts_to_sequences(texts=texts) == sequences\n assert tokenizer.sequences_to_texts(sequences=sequences) == decoded\n\n def test_save_and_load(self):\n with tempfile.TemporaryDirectory() as dp:\n tokenizer = data.Tokenizer(\n char_level=False, token_to_index={\"<PAD>\": 0, \"<UNK>\": 1, \"hello\": 2, \"world\": 3}\n )\n fp = Path(dp, \"label_encoder.json\")\n tokenizer.save(fp=fp)\n tokenizer = data.Tokenizer.load(fp=fp)\n assert len(tokenizer) == 4\n\n\ndef test_pad_sequences():\n # Explicit max len\n seq = np.array([[1, 2, 3], [1, 2]], dtype=object)\n padded_seq = data.pad_sequences(sequences=seq, max_seq_len=5)\n assert np.array_equal(padded_seq, np.array([[1, 2, 3, 0, 0], [1, 2, 0, 0, 0]]))\n\n # Implicit max len\n seq = np.array([[1, 2, 3], [1, 2]], dtype=object)\n padded_seq = data.pad_sequences(sequences=seq)\n assert np.array_equal(padded_seq, np.array([[1, 2, 3], [1, 2, 0]]))\n\n\nclass TestCNNTextDataset:\n def setup_method(self):\n \"\"\"Called before every method.\"\"\"\n self.X = [[4, 2, 3, 0], [2, 4, 3, 3], [2, 3, 0, 0]]\n self.y = [[0, 1], [1, 1], [1, 0]]\n self.max_filter_size = 2\n self.batch_size = 1\n self.dataset = data.CNNTextDataset(X=self.X, y=self.y, max_filter_size=self.max_filter_size)\n\n def teardown_method(self):\n \"\"\"Called after every method.\"\"\"\n del self.dataset\n\n def test_init(self):\n assert self.max_filter_size == self.dataset.max_filter_size\n\n def test_len(self):\n assert len(self.X) == len(self.dataset)\n\n def test_str(self):\n assert str(self.dataset) == f\"<Dataset(N={len(self.dataset)})>\"\n\n def test_get_item(self):\n assert self.dataset[0] == [self.X[0], self.y[0]]\n assert self.dataset[-1] == [self.X[-1], self.y[-1]]\n\n @pytest.mark.parametrize(\n \"batch_size, drop_last, num_batches\",\n [(1, False, 3), (2, False, 2), (2, True, 1), (3, False, 1)],\n )\n def test_create_dataloader(self, batch_size, drop_last, num_batches):\n dataloader = self.dataset.create_dataloader(batch_size=batch_size, drop_last=drop_last)\n assert len(dataloader) == num_batches\n\n def test_dataloader(self):\n batch_size = 2\n dataloader = self.dataset.create_dataloader(batch_size=batch_size, drop_last=False)\n max_seq_len = max(self.max_filter_size, max(len(sequence) for sequence in self.X))\n for batch in dataloader:\n assert len(batch) <= batch_size\n assert np.shape(batch[0])[-1] == max_seq_len\n"
] |
[
[
"numpy.array",
"numpy.shape"
]
] |
takoyaki1116/CGCNN2
|
[
"5a12c19135e36ea8a642d452cfc0f8c8da5ee435"
] |
[
"module/arguments.py"
] |
[
"import argparse\nimport sys\n\nimport torch\n\ndef arguments():\n parser = argparse.ArgumentParser('CGCNN Combined Model Transfer Learning')\n parser.add_argument('data_options', metavar='OPTIONS', nargs='+',\n help='dataset options, started with the path to root dir, '\n 'then other options')\n parser.add_argument('--property', '-P', default='', type=str, help='material property which you want model to learn')\n parser.add_argument('--task', choices=['regression', 'classification'],\n default='regression', help='complete a regression or '\n 'classification task (default: regression)')\n parser.add_argument('--disable-cuda', action='store_true',\n help='Disable CUDA')\n parser.add_argument('-j', '--workers', default=0, type=int, metavar='N',\n help='number of data loading workers (default: 0)')\n parser.add_argument('--epochs', default=30, type=int, metavar='N',\n help='number of total epochs to run (default: 30)')\n parser.add_argument('--start-epoch', default=0, type=int, metavar='N',\n help='manual epoch number (useful on restarts)')\n parser.add_argument('-b', '--batch-size', default=256, type=int,\n metavar='N', help='mini-batch size (default: 256)')\n parser.add_argument('--lr', '--learning-rate', default=0.01, type=float,\n metavar='LR', help='initial learning rate (default: '\n '0.01)')\n parser.add_argument('--lr-milestones', default=[100], nargs='+', type=int,\n metavar='N', help='milestones for scheduler (default: '\n '[100])')\n parser.add_argument('--momentum', default=0.9, type=float, metavar='M',\n help='momentum')\n parser.add_argument('--weight-decay', '--wd', default=0, type=float,\n metavar='W', help='weight decay (default: 0)')\n parser.add_argument('--print-freq', '-p', default=10, type=int,\n metavar='N', help='print frequency (default: 10)')\n parser.add_argument('--resume', default='', type=str, metavar='PATH',\n help='path to latest checkpoint (default: none)')\n train_group = parser.add_mutually_exclusive_group()\n train_group.add_argument('--train-ratio', default=None, type=float, metavar='N',\n help='number of training data to be loaded (default none)')\n train_group.add_argument('--train-size', default=None, type=int, metavar='N',\n help='number of training data to be loaded (default none)')\n valid_group = parser.add_mutually_exclusive_group()\n valid_group.add_argument('--val-ratio', default=0.1, type=float, metavar='N',\n help='percentage of validation data to be loaded (default '\n '0.1)')\n valid_group.add_argument('--val-size', default=None, type=int, metavar='N',\n help='number of validation data to be loaded (default '\n '1000)')\n test_group = parser.add_mutually_exclusive_group()\n test_group.add_argument('--test-ratio', default=0.1, type=float, metavar='N',\n help='percentage of test data to be loaded (default 0.1)')\n test_group.add_argument('--test-size', default=None, type=int, metavar='N',\n help='number of test data to be loaded (default 1000)')\n\n parser.add_argument('--optim', default='SGD', type=str, metavar='SGD',\n help='choose an optimizer, SGD or Adam, (default: SGD)')\n parser.add_argument('--atom-fea-len', default=64, type=int, metavar='N',\n help='number of hidden atom features in conv layers')\n parser.add_argument('--h-fea-len', default=128, type=int, metavar='N',\n help='number of hidden features after pooling')\n parser.add_argument('--n-conv', default=3, type=int, metavar='N',\n help='number of conv layers')\n parser.add_argument('--n-h', default=1, type=int, metavar='N',\n help='number of hidden layers after pooling')\n\n args = parser.parse_args(sys.argv[1:])\n\n args.cuda = not args.disable_cuda and torch.cuda.is_available()\n\n return args\n"
] |
[
[
"torch.cuda.is_available"
]
] |
Xiaziheng89/Spatial-Location-Constraint-Prototype-Loss-for-Open-Set-Recognition
|
[
"022b7e5a81360a8b448072999ecf2988b34055cc"
] |
[
"datasets/datasets.py"
] |
[
"import os\nimport torch\nimport torchvision\nfrom torch.utils.data import DataLoader\nimport torchvision.transforms as transforms\nfrom torchvision.datasets import MNIST, KMNIST\nfrom PIL import Image\n\n\nclass MNISTRGB(MNIST):\n \"\"\"MNIST Dataset.\n \"\"\"\n def __getitem__(self, index):\n img, target = self.data[index], int(self.targets[index])\n img = Image.fromarray(img.numpy(), mode='L')\n img = img.convert(\"RGB\")\n\n if self.transform is not None:\n img = self.transform(img)\n\n if self.target_transform is not None:\n target = self.target_transform(target)\n\n return img, target\n\n\nclass KMNISTRGB(KMNIST):\n \"\"\"KMNIST Dataset.\n \"\"\"\n def __getitem__(self, index):\n img, target = self.data[index], int(self.targets[index])\n img = Image.fromarray(img.numpy(), mode='L')\n img = img.convert(\"RGB\")\n\n if self.transform is not None:\n img = self.transform(img)\n\n if self.target_transform is not None:\n target = self.target_transform(target)\n\n return img, target\n\n\nclass MNIST(object):\n def __init__(self, **options):\n transform = transforms.Compose([\n transforms.Resize(32),\n transforms.ToTensor(),\n ])\n\n batch_size = options['batch_size']\n data_root = os.path.join(options['data_root'], 'mnist')\n\n pin_memory = True if options['use_gpu'] else False\n\n trainset = MNISTRGB(root=data_root, train=True, download=True, transform=transform)\n \n train_loader = torch.utils.data.DataLoader(\n trainset, batch_size=batch_size, shuffle=True,\n num_workers=options['workers'], pin_memory=pin_memory,\n )\n \n testset = MNISTRGB(root=data_root, train=False, download=True, transform=transform)\n \n test_loader = torch.utils.data.DataLoader(\n testset, batch_size=batch_size, shuffle=False,\n num_workers=options['workers'], pin_memory=pin_memory,\n )\n\n self.train_loader = train_loader\n self.test_loader = test_loader\n self.num_classes = 10\n\n\nclass KMNIST(object):\n def __init__(self, **options):\n transform = transforms.Compose([\n transforms.Resize(32),\n transforms.ToTensor(),\n ])\n\n batch_size = options['batch_size']\n data_root = os.path.join(options['data_root'], 'kmnist')\n\n pin_memory = True if options['use_gpu'] else False\n\n trainset = KMNISTRGB(root=data_root, train=True, download=True, transform=transform)\n \n train_loader = torch.utils.data.DataLoader(\n trainset, batch_size=batch_size, shuffle=True,\n num_workers=options['workers'], pin_memory=pin_memory,\n )\n \n testset = KMNISTRGB(root=data_root, train=False, download=True, transform=transform)\n \n test_loader = torch.utils.data.DataLoader(\n testset, batch_size=batch_size, shuffle=False,\n num_workers=options['workers'], pin_memory=pin_memory,\n )\n\n self.train_loader = train_loader\n self.test_loader = test_loader\n self.num_classes = 10\n\n\nclass CIFAR10(object):\n def __init__(self, **options):\n\n transform_train = transforms.Compose([\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n ])\n transform = transforms.Compose([\n transforms.ToTensor(),\n ])\n\n batch_size = options['batch_size']\n data_root = os.path.join(options['data_root'], 'cifar10')\n\n pin_memory = True if options['use_gpu'] else False\n\n trainset = torchvision.datasets.CIFAR10(root=data_root, train=True, download=True, transform=transform_train)\n\n train_loader = torch.utils.data.DataLoader(\n trainset, batch_size=batch_size, shuffle=True,\n num_workers=options['workers'], pin_memory=pin_memory,\n )\n \n testset = torchvision.datasets.CIFAR10(root=data_root, train=False, download=True, transform=transform)\n \n test_loader = torch.utils.data.DataLoader(\n testset, batch_size=batch_size, shuffle=False,\n num_workers=options['workers'], pin_memory=pin_memory,\n )\n\n self.num_classes = 10\n self.train_loader = train_loader\n self.test_loader = test_loader\n\n\nclass CIFAR100(object):\n def __init__(self, **options):\n transform_train = transforms.Compose([\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n ])\n transform = transforms.Compose([\n transforms.ToTensor(),\n ])\n\n batch_size = options['batch_size']\n data_root = os.path.join(options['data_root'], 'cifar100')\n\n pin_memory = True if options['use_gpu'] else False\n\n trainset = torchvision.datasets.CIFAR100(root=data_root, train=True, download=True, transform=transform_train)\n \n train_loader = torch.utils.data.DataLoader(\n trainset, batch_size=batch_size, shuffle=True,\n num_workers=options['workers'], pin_memory=pin_memory,\n )\n \n testset = torchvision.datasets.CIFAR100(root=data_root, train=False, download=True, transform=transform)\n \n test_loader = torch.utils.data.DataLoader(\n testset, batch_size=batch_size, shuffle=False,\n num_workers=options['workers'], pin_memory=pin_memory,\n )\n\n self.num_classes = 100\n self.train_loader = train_loader\n self.test_loader = test_loader\n\n\nclass SVHN(object):\n def __init__(self, **options):\n transform_train = transforms.Compose([\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n ])\n transform = transforms.Compose([\n transforms.ToTensor(),\n ])\n\n batch_size = options['batch_size']\n data_root = os.path.join(options['data_root'], 'svhn')\n\n pin_memory = True if options['use_gpu'] else False\n\n trainset = torchvision.datasets.SVHN(root=data_root, split='train', download=True, transform=transform_train)\n \n train_loader = torch.utils.data.DataLoader(\n trainset, batch_size=batch_size, shuffle=True,\n num_workers=options['workers'], pin_memory=pin_memory,\n )\n \n testset = torchvision.datasets.SVHN(root=data_root, split='test', download=True, transform=transform)\n \n test_loader = torch.utils.data.DataLoader(\n testset, batch_size=batch_size, shuffle=False,\n num_workers=options['workers'], pin_memory=pin_memory,\n )\n\n self.num_classes = 10\n self.train_loader = train_loader\n self.test_loader = test_loader\n\n\nclass ImageNet(object): # ImageNet2012\n def __init__(self, **options):\n transform_train = transforms.Compose([\n transforms.Resize((64, 64)),\n transforms.RandomCrop(64, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor()])\n\n transform = transforms.Compose([\n transforms.Resize((64, 64)),\n transforms.ToTensor()])\n\n batch_size = options['batch_size']\n data_root = os.path.join(options['data_root'], 'imagenet')\n pin_memory = True if options['use_gpu'] else False\n\n trainset = torchvision.datasets.ImageNet(root=data_root, split='train', download='True', transform=transform_train)\n train_loader = torch.utils.data.DataLoader(trainset, batch_size=batch_size, shuffle=True,\n num_workers=options['workers'], pin_memory=pin_memory)\n\n testset = torchvision.datasets.ImageNet(root=data_root, split='test', download='True', transform=transform)\n test_loader = torch.utils.data.DataLoader(testset, batch_size=batch_size, shuffle=False,\n num_workers=options['workers'], pin_memory=pin_memory)\n\n self.num_classes = 200\n self.train_loader = train_loader\n self.test_loader = test_loader\n\n\nclass Omniglot(object):\n def __init__(self, **options):\n transform_train = transforms.Compose([\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n ])\n transform = transforms.Compose([\n transforms.ToTensor(),\n ])\n\n batch_size = options['batch_size']\n data_root = os.path.join(options['data_root'], 'omniglot')\n\n pin_memory = True if options['use_gpu'] else False\n\n trainset = torchvision.datasets.Omniglot(root=data_root, download=True, transform=transform_train)\n # trainset = torchvision.datasets.\n\n train_loader = torch.utils.data.DataLoader(\n trainset, batch_size=batch_size, shuffle=True, num_workers=options['workers'], pin_memory=pin_memory)\n\n testset = torchvision.datasets.Omniglot(root=data_root, download=True, transform=transform)\n\n test_loader = torch.utils.data.DataLoader(\n testset, batch_size=batch_size, shuffle=False,\n num_workers=options['workers'], pin_memory=pin_memory,\n )\n\n # self.num_classes = 10\n self.train_loader = train_loader\n self.test_loader = test_loader\n\n\n__factory = {\n 'mnist': MNIST,\n 'kmnist': KMNIST,\n 'cifar10': CIFAR10,\n 'cifar100': CIFAR100,\n 'svhn': SVHN,\n 'imagenet': ImageNet,\n 'omniglot': Omniglot\n}\n\n\ndef create(name, **options):\n if name not in __factory.keys():\n raise KeyError(\"Unknown dataset: {}\".format(name))\n return __factory[name](**options)\n"
] |
[
[
"torch.utils.data.DataLoader"
]
] |
SimonasJocys/retina_net
|
[
"c2bd3851d3de50c7b624e983187ed28429552ab4"
] |
[
"keras-retinanet/keras_retinanet/bin/train.py"
] |
[
"#!/usr/bin/env python\n\n\"\"\"\nCopyright 2017-2018 Fizyr (https://fizyr.com)\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nimport argparse\nimport os\nimport sys\nimport warnings\n\nimport keras\nimport keras.preprocessing.image\nimport tensorflow as tf\n\n# Allow relative imports when being executed as script.\nif __name__ == \"__main__\" and __package__ is None:\n sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))\n import keras_retinanet.bin # noqa: F401\n __package__ = \"keras_retinanet.bin\"\n\n# Change these to absolute imports if you copy this script outside the keras_retinanet package.\nfrom .. import layers # noqa: F401\nfrom .. import losses\nfrom .. import models\nfrom ..callbacks import RedirectModel\nfrom ..callbacks.eval import Evaluate\nfrom ..models.retinanet import retinanet_bbox\nfrom ..preprocessing.csv_generator import CSVGenerator\nfrom ..preprocessing.kitti import KittiGenerator\nfrom ..preprocessing.open_images import OpenImagesGenerator\nfrom ..preprocessing.pascal_voc import PascalVocGenerator\nfrom ..utils.anchors import make_shapes_callback\nfrom ..utils.config import read_config_file, parse_anchor_parameters\nfrom ..utils.keras_version import check_keras_version\nfrom ..utils.model import freeze as freeze_model\nfrom ..utils.transform import random_transform_generator\n\n\ndef makedirs(path):\n # Intended behavior: try to create the directory,\n # pass if the directory exists already, fails otherwise.\n # Meant for Python 2.7/3.n compatibility.\n try:\n os.makedirs(path)\n except OSError:\n if not os.path.isdir(path):\n raise\n\n\ndef get_session():\n \"\"\" Construct a modified tf session.\n \"\"\"\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n return tf.Session(config=config)\n\n\ndef model_with_weights(model, weights, skip_mismatch):\n \"\"\" Load weights for model.\n\n Args\n model : The model to load weights for.\n weights : The weights to load.\n skip_mismatch : If True, skips layers whose shape of weights doesn't match with the model.\n \"\"\"\n if weights is not None:\n model.load_weights(weights, by_name=True, skip_mismatch=skip_mismatch)\n return model\n\n\ndef create_models(backbone_retinanet, num_classes, weights, multi_gpu=0, freeze_backbone=False, config=None):\n \"\"\" Creates three models (model, training_model, prediction_model).\n\n Args\n backbone_retinanet : A function to call to create a retinanet model with a given backbone.\n num_classes : The number of classes to train.\n weights : The weights to load into the model.\n multi_gpu : The number of GPUs to use for training.\n freeze_backbone : If True, disables learning for the backbone.\n config : Config parameters, None indicates the default configuration.\n\n Returns\n model : The base model. This is also the model that is saved in snapshots.\n training_model : The training model. If multi_gpu=0, this is identical to model.\n prediction_model : The model wrapped with utility functions to perform object detection (applies regression values and performs NMS).\n \"\"\"\n\n modifier = freeze_model if freeze_backbone else None\n\n # Keras recommends initialising a multi-gpu model on the CPU to ease weight sharing, and to prevent OOM errors.\n # optionally wrap in a parallel model\n if multi_gpu > 1:\n from keras.utils import multi_gpu_model\n with tf.device('/cpu:0'):\n model = model_with_weights(backbone_retinanet(num_classes, modifier=modifier), weights=weights, skip_mismatch=True)\n training_model = multi_gpu_model(model, gpus=multi_gpu)\n else:\n model = model_with_weights(backbone_retinanet(num_classes, modifier=modifier), weights=weights, skip_mismatch=True)\n training_model = model\n\n # make prediction model\n anchor_params = None\n if config and 'anchor_parameters' in config:\n anchor_params = parse_anchor_parameters(config)\n prediction_model = retinanet_bbox(model=model, anchor_params=anchor_params)\n\n # compile model\n training_model.compile(\n loss={\n 'regression' : losses.smooth_l1(),\n 'classification': losses.focal()\n },\n optimizer=keras.optimizers.adam(lr=1e-5, clipnorm=0.001)\n )\n\n return model, training_model, prediction_model\n\n\ndef create_callbacks(model, training_model, prediction_model, validation_generator, args):\n \"\"\" Creates the callbacks to use during training.\n\n Args\n model: The base model.\n training_model: The model that is used for training.\n prediction_model: The model that should be used for validation.\n validation_generator: The generator for creating validation data.\n args: parseargs args object.\n\n Returns:\n A list of callbacks used for training.\n \"\"\"\n callbacks = []\n\n tensorboard_callback = None\n\n if args.tensorboard_dir:\n tensorboard_callback = keras.callbacks.TensorBoard(\n log_dir = args.tensorboard_dir,\n histogram_freq = 0,\n batch_size = args.batch_size,\n write_graph = True,\n write_grads = False,\n write_images = False,\n embeddings_freq = 0,\n embeddings_layer_names = None,\n embeddings_metadata = None\n )\n callbacks.append(tensorboard_callback)\n\n if args.evaluation and validation_generator:\n if args.dataset_type == 'coco':\n from ..callbacks.coco import CocoEval\n\n # use prediction model for evaluation\n evaluation = CocoEval(validation_generator, tensorboard=tensorboard_callback)\n else:\n evaluation = Evaluate(validation_generator, tensorboard=tensorboard_callback, weighted_average=args.weighted_average)\n evaluation = RedirectModel(evaluation, prediction_model)\n callbacks.append(evaluation)\n\n # save the model\n if args.snapshots:\n # ensure directory created first; otherwise h5py will error after epoch.\n makedirs(args.snapshot_path)\n checkpoint = keras.callbacks.ModelCheckpoint(\n os.path.join(\n args.snapshot_path,\n '{backbone}_{dataset_type}_{{epoch:02d}}.h5'.format(backbone=args.backbone, dataset_type=args.dataset_type)\n ),\n verbose=1,\n # save_best_only=True,\n # monitor=\"mAP\",\n # mode='max'\n )\n checkpoint = RedirectModel(checkpoint, model)\n callbacks.append(checkpoint)\n\n callbacks.append(keras.callbacks.ReduceLROnPlateau(\n monitor = 'loss',\n factor = 0.1,\n patience = 2,\n verbose = 1,\n mode = 'auto',\n epsilon = 0.0001,\n cooldown = 0,\n min_lr = 0\n ))\n\n return callbacks\n\n\ndef create_generators(args, preprocess_image):\n \"\"\" Create generators for training and validation.\n\n Args\n args : parseargs object containing configuration for generators.\n preprocess_image : Function that preprocesses an image for the network.\n \"\"\"\n common_args = {\n 'batch_size' : args.batch_size,\n 'config' : args.config,\n 'image_min_side' : args.image_min_side,\n 'image_max_side' : args.image_max_side,\n 'preprocess_image' : preprocess_image,\n }\n\n # create random transform generator for augmenting training data\n if args.random_transform:\n transform_generator = random_transform_generator(\n min_rotation=-0.1,\n max_rotation=0.1,\n min_translation=(-0.1, -0.1),\n max_translation=(0.1, 0.1),\n min_shear=-0.1,\n max_shear=0.1,\n min_scaling=(0.9, 0.9),\n max_scaling=(1.1, 1.1),\n flip_x_chance=0.5,\n flip_y_chance=0.5,\n )\n else:\n transform_generator = random_transform_generator(flip_x_chance=0.5)\n\n if args.dataset_type == 'coco':\n # import here to prevent unnecessary dependency on cocoapi\n from ..preprocessing.coco import CocoGenerator\n\n train_generator = CocoGenerator(\n args.coco_path,\n 'train2017',\n transform_generator=transform_generator,\n **common_args\n )\n\n validation_generator = CocoGenerator(\n args.coco_path,\n 'val2017',\n **common_args\n )\n elif args.dataset_type == 'pascal':\n train_generator = PascalVocGenerator(\n args.pascal_path,\n 'trainval',\n transform_generator=transform_generator,\n **common_args\n )\n\n validation_generator = PascalVocGenerator(\n args.pascal_path,\n 'test',\n **common_args\n )\n elif args.dataset_type == 'csv':\n train_generator = CSVGenerator(\n args.annotations,\n args.classes,\n transform_generator=transform_generator,\n **common_args\n )\n\n if args.val_annotations:\n validation_generator = CSVGenerator(\n args.val_annotations,\n args.classes,\n **common_args\n )\n else:\n validation_generator = None\n elif args.dataset_type == 'oid':\n train_generator = OpenImagesGenerator(\n args.main_dir,\n subset='train',\n version=args.version,\n labels_filter=args.labels_filter,\n annotation_cache_dir=args.annotation_cache_dir,\n parent_label=args.parent_label,\n transform_generator=transform_generator,\n **common_args\n )\n\n validation_generator = OpenImagesGenerator(\n args.main_dir,\n subset='validation',\n version=args.version,\n labels_filter=args.labels_filter,\n annotation_cache_dir=args.annotation_cache_dir,\n parent_label=args.parent_label,\n **common_args\n )\n elif args.dataset_type == 'kitti':\n train_generator = KittiGenerator(\n args.kitti_path,\n subset='train',\n transform_generator=transform_generator,\n **common_args\n )\n\n validation_generator = KittiGenerator(\n args.kitti_path,\n subset='val',\n **common_args\n )\n else:\n raise ValueError('Invalid data type received: {}'.format(args.dataset_type))\n\n return train_generator, validation_generator\n\n\ndef check_args(parsed_args):\n \"\"\" Function to check for inherent contradictions within parsed arguments.\n For example, batch_size < num_gpus\n Intended to raise errors prior to backend initialisation.\n\n Args\n parsed_args: parser.parse_args()\n\n Returns\n parsed_args\n \"\"\"\n\n if parsed_args.multi_gpu > 1 and parsed_args.batch_size < parsed_args.multi_gpu:\n raise ValueError(\n \"Batch size ({}) must be equal to or higher than the number of GPUs ({})\".format(parsed_args.batch_size,\n parsed_args.multi_gpu))\n\n if parsed_args.multi_gpu > 1 and parsed_args.snapshot:\n raise ValueError(\n \"Multi GPU training ({}) and resuming from snapshots ({}) is not supported.\".format(parsed_args.multi_gpu,\n parsed_args.snapshot))\n\n if parsed_args.multi_gpu > 1 and not parsed_args.multi_gpu_force:\n raise ValueError(\"Multi-GPU support is experimental, use at own risk! Run with --multi-gpu-force if you wish to continue.\")\n\n if 'resnet' not in parsed_args.backbone:\n warnings.warn('Using experimental backbone {}. Only resnet50 has been properly tested.'.format(parsed_args.backbone))\n\n return parsed_args\n\n\ndef parse_args(args):\n \"\"\" Parse the arguments.\n \"\"\"\n parser = argparse.ArgumentParser(description='Simple training script for training a RetinaNet network.')\n subparsers = parser.add_subparsers(help='Arguments for specific dataset types.', dest='dataset_type')\n subparsers.required = True\n\n coco_parser = subparsers.add_parser('coco')\n coco_parser.add_argument('coco_path', help='Path to dataset directory (ie. /tmp/COCO).')\n\n pascal_parser = subparsers.add_parser('pascal')\n pascal_parser.add_argument('pascal_path', help='Path to dataset directory (ie. /tmp/VOCdevkit).')\n\n kitti_parser = subparsers.add_parser('kitti')\n kitti_parser.add_argument('kitti_path', help='Path to dataset directory (ie. /tmp/kitti).')\n\n def csv_list(string):\n return string.split(',')\n\n oid_parser = subparsers.add_parser('oid')\n oid_parser.add_argument('main_dir', help='Path to dataset directory.')\n oid_parser.add_argument('--version', help='The current dataset version is v4.', default='v4')\n oid_parser.add_argument('--labels-filter', help='A list of labels to filter.', type=csv_list, default=None)\n oid_parser.add_argument('--annotation-cache-dir', help='Path to store annotation cache.', default='.')\n oid_parser.add_argument('--parent-label', help='Use the hierarchy children of this label.', default=None)\n\n csv_parser = subparsers.add_parser('csv')\n csv_parser.add_argument('annotations', help='Path to CSV file containing annotations for training.')\n csv_parser.add_argument('classes', help='Path to a CSV file containing class label mapping.')\n csv_parser.add_argument('--val-annotations', help='Path to CSV file containing annotations for validation (optional).')\n\n group = parser.add_mutually_exclusive_group()\n group.add_argument('--snapshot', help='Resume training from a snapshot.')\n group.add_argument('--imagenet-weights', help='Initialize the model with pretrained imagenet weights. This is the default behaviour.', action='store_const', const=True, default=True)\n group.add_argument('--weights', help='Initialize the model with weights from a file.')\n group.add_argument('--no-weights', help='Don\\'t initialize the model with any weights.', dest='imagenet_weights', action='store_const', const=False)\n\n parser.add_argument('--backbone', help='Backbone model used by retinanet.', default='resnet50', type=str)\n parser.add_argument('--batch-size', help='Size of the batches.', default=1, type=int)\n parser.add_argument('--gpu', help='Id of the GPU to use (as reported by nvidia-smi).')\n parser.add_argument('--multi-gpu', help='Number of GPUs to use for parallel processing.', type=int, default=0)\n parser.add_argument('--multi-gpu-force', help='Extra flag needed to enable (experimental) multi-gpu support.', action='store_true')\n parser.add_argument('--epochs', help='Number of epochs to train.', type=int, default=50)\n parser.add_argument('--steps', help='Number of steps per epoch.', type=int, default=10000)\n parser.add_argument('--snapshot-path', help='Path to store snapshots of models during training (defaults to \\'./snapshots\\')', default='./snapshots')\n parser.add_argument('--tensorboard-dir', help='Log directory for Tensorboard output', default='./logs')\n parser.add_argument('--no-snapshots', help='Disable saving snapshots.', dest='snapshots', action='store_false')\n parser.add_argument('--no-evaluation', help='Disable per epoch evaluation.', dest='evaluation', action='store_false')\n parser.add_argument('--freeze-backbone', help='Freeze training of backbone layers.', action='store_true')\n parser.add_argument('--random-transform', help='Randomly transform image and annotations.', action='store_true')\n parser.add_argument('--image-min-side', help='Rescale the image so the smallest side is min_side.', type=int, default=800)\n parser.add_argument('--image-max-side', help='Rescale the image if the largest side is larger than max_side.', type=int, default=1333)\n parser.add_argument('--config', help='Path to a configuration parameters .ini file.')\n parser.add_argument('--weighted-average', help='Compute the mAP using the weighted average of precisions among classes.', action='store_true')\n\n return check_args(parser.parse_args(args))\n\n\ndef main(args=None):\n # parse arguments\n if args is None:\n args = sys.argv[1:]\n args = parse_args(args)\n\n # create object that stores backbone information\n backbone = models.backbone(args.backbone)\n\n # make sure keras is the minimum required version\n check_keras_version()\n\n # optionally choose specific GPU\n if args.gpu:\n os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu\n keras.backend.tensorflow_backend.set_session(get_session())\n\n # optionally load config parameters\n if args.config:\n args.config = read_config_file(args.config)\n\n # create the generators\n train_generator, validation_generator = create_generators(args, backbone.preprocess_image)\n\n # create the model\n if args.snapshot is not None:\n print('Loading model, this may take a second...')\n model = models.load_model(args.snapshot, backbone_name=args.backbone)\n training_model = model\n anchor_params = None\n if args.config and 'anchor_parameters' in args.config:\n anchor_params = parse_anchor_parameters(args.config)\n prediction_model = retinanet_bbox(model=model, anchor_params=anchor_params)\n else:\n weights = args.weights\n # default to imagenet if nothing else is specified\n if weights is None and args.imagenet_weights:\n weights = backbone.download_imagenet()\n\n print('Creating model, this may take a second...')\n model, training_model, prediction_model = create_models(\n backbone_retinanet=backbone.retinanet,\n num_classes=train_generator.num_classes(),\n weights=weights,\n multi_gpu=args.multi_gpu,\n freeze_backbone=args.freeze_backbone,\n config=args.config\n )\n\n # print model summary\n print(model.summary())\n\n # this lets the generator compute backbone layer shapes using the actual backbone model\n if 'vgg' in args.backbone or 'densenet' in args.backbone:\n train_generator.compute_shapes = make_shapes_callback(model)\n if validation_generator:\n validation_generator.compute_shapes = train_generator.compute_shapes\n\n # create the callbacks\n callbacks = create_callbacks(\n model,\n training_model,\n prediction_model,\n validation_generator,\n args,\n )\n\n # start training\n training_model.fit_generator(\n generator=train_generator,\n steps_per_epoch=args.steps,\n epochs=args.epochs,\n verbose=1,\n callbacks=callbacks,\n )\n\n\nif __name__ == '__main__':\n main()\n"
] |
[
[
"tensorflow.ConfigProto",
"tensorflow.device",
"tensorflow.Session"
]
] |
sdpython/covidsim
|
[
"765d43ac29831f1a630ef5e187cff10f3ddc5cf1"
] |
[
"examples/plot_covid_r0.py"
] |
[
"# coding: utf-8\n\"\"\"\nReprésentation du R0 par départements\n=====================================\n\nCet exemple reprend des données de tests par gouvernement\npour calculer le coefficient R0 de l'épidémie. La méthode\nde Cori est utilisée avec la formule proposée dans :epkg:`covidtracker` :\n\n.. math::\n\n R = \\\\frac{\\\\sum_{i=t-6}^{t}C_i}{\\\\sum_{i=t-13}^{t-7}C_i}\n\nOù :math:`C_i` est le nombre de cas positifs du jour *i*.\nCette méthode est implémentée dans le package R\n`EpiEstim <https://github.com/mrc-ide/EpiEstim>`_ ou\n:epkg:`epyestim` pour le langage python. Dans cet exemple,\nil sera calculé directement à partir des données.\n\nSources de données:\n\n* `Données relatives aux résultats des tests virologiques COVID-19 SI-DEP\n <https://www.data.gouv.fr/fr/datasets/\n donnees-relatives-aux-resultats-des-tests-virologiques-covid-19/>`_\n* `Contours géographiques des départements\n <https://www.data.gouv.fr/en/datasets/\n contours-geographiques-des-departements/>`_\n\n.. contents::\n :local:\n\nRécupération des données\n++++++++++++++++++++++++\n\"\"\"\n\nimport warnings\nfrom pandas import Timedelta, DataFrame\nfrom geopandas import GeoDataFrame\nfrom matplotlib.cbook.deprecation import MatplotlibDeprecationWarning\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nfrom aftercovid.data import (\n data_covid_france_departments_tests,\n data_france_departments)\n\n\ndef valid(df):\n \"Checks that a dataframe is not empty.\"\n if 0 in df.shape:\n raise ValueError(\n \"One dataframe is empty with shape=%r.\" % (df.shape, ))\n return df\n\n\ncase = data_covid_france_departments_tests(metropole=True)\ncase.tail()\n\n\n##########################################\n# Aggrégation par départements et par jour.\n\ncase = valid(\n case[case.cl_age90 != 0].groupby(['dep', 'jour'], as_index=False).sum()\n)\ncase.tail()\n\n\n##########################################\n# Quelques aggrégations, par département.\n\ndeps = valid(case.groupby([\"dep\", \"jour\"], as_index=False).sum())\ndeps.tail(n=10)\n\n###########################################\n# Sur tout le territoire.\n\nfrance = case.groupby([\"jour\"], as_index=False).sum()\nfrance.tail(n=10)\n\n############################################\n# Calcul du R\n# +++++++++++\n\n\ndef compute_r(df, col_day='jour', col='P', last_day=None):\n if last_day is None:\n last_day = df.jour.max()\n v1 = last_day - Timedelta(days=6)\n v2 = last_day\n p1 = last_day - Timedelta(days=13)\n p2 = last_day - Timedelta(days=7)\n w1 = df[(df[col_day] >= p1) & (df[col_day] <= p2)]\n w2 = df[(df[col_day] >= v1) & (df[col_day] <= v2)]\n return w2[col].sum() / w1[col].sum()\n\n\ncompute_r(france)\n\n#########################################\n# On regarde quelle tête ça a sur six mois.\n# Ce n'est pas le code le plus efficace mais c'est rapide à\n# écrire. Dans le cas idéal, il faudra s'assurer que toutes\n# les dates sont présents et les compléter le cas échéants\n# puis calculer l'estimateur sur des fenêtres glissantes.\n\nlast_day = france.jour.max()\nobs = []\nfor i in range(0, 180):\n ld = last_day - Timedelta(days=i)\n obs.append({'jour': ld, 'R': compute_r(france, last_day=ld)})\n\ngr = DataFrame(obs).sort_values(\"jour\")\ngr.tail()\n\n###################################\n# Et on dessine.\n\ngr.set_index('jour').plot(title=\"Evolution de R en Métropole\")\n\n\n########################################################\n# Carte du R par département\n# ++++++++++++++++++++++++++\n#\n# On calcule les R par départements.\n\nobs = []\nfor d in set(deps.dep):\n r = compute_r(deps[deps.dep == d])\n obs.append({'dep': d, 'R': r})\n\ndepdf = DataFrame(obs).sort_values(\"dep\")\ndepdf.tail()\n\n##############################################\n# On récupère les contours des départements français.\n\nloc = data_france_departments(metropole=True)\nloc.tail()\n\n###################################\n# On fusionne avec les R.\n\nlocdep = GeoDataFrame(depdf.merge(loc, left_on='dep', right_on='code_depart'))\nlocdep.tail()\n\n##################################\n# Et on dessine. Les départements en vert sont ceux pour lequel\n# le R est > 1.\n\nwith warnings.catch_warnings():\n warnings.filterwarnings(\"ignore\", category=UserWarning)\n warnings.filterwarnings(\"ignore\", category=MatplotlibDeprecationWarning)\n fig, axs = plt.subplots(\n 1, 2, figsize=(16, 10),\n gridspec_kw={'width_ratios': [2, 1]})\n\n # métropole\n ax = axs[0]\n cax = make_axes_locatable(ax).append_axes(\"right\", size=\"5%\", pad=0.1)\n locdep.plot(\n column=\"R\", ax=ax, edgecolor='black',\n legend=True, cax=cax, cmap=\"OrRd\")\n if (locdep.R < 1).sum() > 0:\n locdep[locdep.R < 1].geometry.boundary.plot(\n color=None, edgecolor='g', linewidth=2, ax=ax, label=\"R<1\")\n ax.set_title(\"R par départments de la métropole\\n%r\" % deps.jour.max())\n\n for _, row in locdep.iterrows():\n p = row['geometry'].representative_point()\n ax.annotate(\"%1.1f\" % row['R'], xy=(p.x, p.y),\n horizontalalignment='center', color=\"black\", fontsize=8)\n\n ax.legend()\n\n # Paris et sa région\n idf = set(['75', '77', '78', '91', '92', '93', '94', '95'])\n ax = axs[1]\n locdep2 = locdep[locdep.dep.isin(idf)]\n cax = make_axes_locatable(ax).append_axes(\"right\", size=\"5%\", pad=0.1)\n locdep2.plot(\n column=\"R\", ax=ax, edgecolor='black',\n legend=True, cax=cax, cmap=\"OrRd\")\n ax.set_title(\"R par départments de la métropole\\n%r\" % deps.jour.max())\n\n for _, row in locdep2.iterrows():\n p = row['geometry'].representative_point()\n ax.annotate(\"%1.1f\" % row['R'], xy=(p.x, p.y),\n horizontalalignment='center', color=\"black\", fontsize=8)\n\nplt.show()\n"
] |
[
[
"matplotlib.pyplot.show",
"matplotlib.pyplot.subplots",
"pandas.Timedelta",
"pandas.DataFrame"
]
] |
iliasprc/video-augment
|
[
"bd95f415a22f0abc4f85d7836857cd33b211c02e"
] |
[
"videoaugment/transforms/general.py"
] |
[
"\nimport PIL\nimport PIL.Image\nimport torch\nimport numpy as np\nimport torchvision.transforms.functional as TF\n\nfrom einops import rearrange\n\n\nclass RearrangeTensor:\n\n\n def __call__(self, input_tensor):\n return rearrange(input_tensor, 'h w c -> c h w')\n\nclass PILToNumpy:\n def __call__(self, image):\n \"\"\"\n\n Args:\n image ():\n\n Returns:\n\n \"\"\"\n return np.asarray(image)\n\n\nclass PILToTensor:\n def __call__(self, image):\n \"\"\"\n\n Args:\n image ():\n\n Returns:\n\n \"\"\"\n return torch.from_numpy(np.asarray(image))\n\n\nclass NumpyToTensor(object):\n \"\"\"Converts numpy array to tensor\n \"\"\"\n\n def __call__(self, array):\n \"\"\"\n\n Args:\n array ():\n\n Returns:\n\n \"\"\"\n tensor = torch.from_numpy(array)\n return tensor\n\n\nclass Normalize(object):\n\n def __init__(self, mean, std):\n \"\"\"\n\n Args:\n mean ():\n std ():\n \"\"\"\n self.mean = mean\n self.std = std\n\n def __call__(self, frame):\n \"\"\"\n\n Args:\n frame ():\n\n Returns:\n\n \"\"\"\n if isinstance(frame, torch.Tensor):\n return TF.normalize(frame, self.mean, self.std, False)\n elif isinstance(frame, np.ndarray):\n return TF.normalize(torch.from_numpy(frame), self.mean, self.std, False)\n elif isinstance(frame, PIL.Image.Image):\n return TF.normalize(torch.from_numpy(np.asarray(frame)), self.mean, self.std, False)\n\n\nclass ComposeSpatialTransforms(object):\n def __init__(self, transforms):\n self.transforms = transforms\n if not isinstance(self.transforms, list):\n self.transforms = [self.transforms]\n\n def __call__(self, frame):\n # print(self.transforms)\n for t in self.transforms:\n if t != None:\n frame = t(frame)\n return frame\n\n\nclass ComposeTemporalTransforms(object):\n def __init__(self, transforms):\n self.transforms = transforms\n if not isinstance(self.transforms, list):\n self.transforms = [self.transforms]\n\n def __call__(self, video):\n for t in self.transforms:\n video = t(video)\n return video\n\nclass VideoToTensor:\n\n\n def __call__(self, video):\n\n vid = torch.stack(video,dim=1)\n\n return vid\n\n\nclass VideoToNumpy:\n\n\n def __call__(self, video):\n\n vid = np.stack(video,axis=0)\n\n return vid\n\n\nclass VideoTransform(object):\n def __init__(self, spatial_transforms, temporal_transforms):\n self.spatial_transforms = ComposeSpatialTransforms(spatial_transforms)\n self.temporal_transforms = ComposeTemporalTransforms(temporal_transforms)\n\n def __call__(self, video):\n transformed_video = []\n for frame in video:\n # if self.spatial_transforms != None:\n frame = self.spatial_transforms(frame)\n transformed_video.append(frame)\n if self.temporal_transforms != None:\n transformed_video = self.temporal_transforms(transformed_video)\n\n\n return transformed_video\n"
] |
[
[
"numpy.asarray",
"torch.from_numpy",
"numpy.stack",
"torch.stack"
]
] |
cclauss/TensorFlowTTS
|
[
"cac7e27e9d2bf2144f6fef409675d16dd48bc158"
] |
[
"tensorflow_tts/trainers/base_trainer.py"
] |
[
"# -*- coding: utf-8 -*-\n# Copyright 2020 Minh Nguyen (@dathudeptrai)\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\"\"\"Based Trainer.\"\"\"\n\nimport abc\nimport logging\nimport os\n\nimport tensorflow as tf\nfrom tqdm import tqdm\n\n\nclass BasedTrainer(metaclass=abc.ABCMeta):\n \"\"\"Customized trainer module for all models.\"\"\"\n\n def __init__(self, steps, epochs, config):\n self.steps = steps\n self.epochs = epochs\n self.config = config\n self.finish_train = False\n self.writer = tf.summary.create_file_writer(config[\"outdir\"])\n self.train_data_loader = None\n self.eval_data_loader = None\n self.train_metrics = None\n self.eval_metrics = None\n self.list_metrics_name = None\n\n def init_train_eval_metrics(self, list_metrics_name):\n \"\"\"Init train and eval metrics to save it to tensorboard.\"\"\"\n self.train_metrics = {}\n self.eval_metrics = {}\n for name in list_metrics_name:\n self.train_metrics.update(\n {name: tf.keras.metrics.Mean(name=\"train_\" + name, dtype=tf.float32)}\n )\n self.eval_metrics.update(\n {name: tf.keras.metrics.Mean(name=\"eval_\" + name, dtype=tf.float32)}\n )\n\n def reset_states_train(self):\n \"\"\"Reset train metrics after save it to tensorboard.\"\"\"\n for metric in self.train_metrics.keys():\n self.train_metrics[metric].reset_states()\n\n def reset_states_eval(self):\n \"\"\"Reset eval metrics after save it to tensorboard.\"\"\"\n for metric in self.eval_metrics.keys():\n self.eval_metrics[metric].reset_states()\n\n def update_train_metrics(self, dict_metrics_losses):\n for name, value in dict_metrics_losses.items():\n self.train_metrics[name].update_state(value)\n\n def update_eval_metrics(self, dict_metrics_losses):\n for name, value in dict_metrics_losses.items():\n self.eval_metrics[name].update_state(value)\n\n def set_train_data_loader(self, train_dataset):\n \"\"\"Set train data loader (MUST).\"\"\"\n self.train_data_loader = train_dataset\n\n def get_train_data_loader(self):\n \"\"\"Get train data loader.\"\"\"\n return self.train_data_loader\n\n def set_eval_data_loader(self, eval_dataset):\n \"\"\"Set eval data loader (MUST).\"\"\"\n self.eval_data_loader = eval_dataset\n\n def get_eval_data_loader(self):\n \"\"\"Get eval data loader.\"\"\"\n return self.eval_data_loader\n\n @abc.abstractmethod\n def compile(self):\n pass\n\n @abc.abstractmethod\n def create_checkpoint_manager(self, saved_path=None, max_to_keep=10):\n \"\"\"Create checkpoint management.\"\"\"\n pass\n\n def run(self):\n \"\"\"Run training.\"\"\"\n self.tqdm = tqdm(\n initial=self.steps, total=self.config[\"train_max_steps\"], desc=\"[train]\"\n )\n while True:\n self._train_epoch()\n\n if self.finish_train:\n break\n\n self.tqdm.close()\n logging.info(\"Finish training.\")\n\n @abc.abstractmethod\n def save_checkpoint(self):\n \"\"\"Save checkpoint.\"\"\"\n pass\n\n @abc.abstractmethod\n def load_checkpoint(self, pretrained_path):\n \"\"\"Load checkpoint.\"\"\"\n pass\n\n def _train_epoch(self):\n \"\"\"Train model one epoch.\"\"\"\n for train_steps_per_epoch, batch in enumerate(self.train_data_loader, 1):\n # one step training\n self._train_step(batch)\n\n # check interval\n self._check_log_interval()\n self._check_eval_interval()\n self._check_save_interval()\n\n # check wheter training is finished\n if self.finish_train:\n return\n\n # update\n self.epochs += 1\n self.train_steps_per_epoch = train_steps_per_epoch\n logging.info(\n f\"(Steps: {self.steps}) Finished {self.epochs} epoch training \"\n f\"({self.train_steps_per_epoch} steps per epoch).\"\n )\n\n @abc.abstractmethod\n def _eval_epoch(self):\n \"\"\"One epoch evaluation.\"\"\"\n pass\n\n @abc.abstractmethod\n def _train_step(self, batch):\n \"\"\"One step training.\"\"\"\n pass\n\n @abc.abstractmethod\n def _check_log_interval(self):\n \"\"\"Save log interval.\"\"\"\n pass\n\n @abc.abstractmethod\n def fit(self):\n pass\n\n def _check_eval_interval(self):\n \"\"\"Evaluation interval step.\"\"\"\n if self.steps % self.config[\"eval_interval_steps\"] == 0:\n self._eval_epoch()\n\n def _check_save_interval(self):\n \"\"\"Save interval checkpoint.\"\"\"\n if self.steps % self.config[\"save_interval_steps\"] == 0:\n self.save_checkpoint()\n logging.info(f\"Successfully saved checkpoint @ {self.steps} steps.\")\n\n def generate_and_save_intermediate_result(self, batch):\n \"\"\"Generate and save intermediate result.\"\"\"\n pass\n\n def _write_to_tensorboard(self, list_metrics, stage=\"train\"):\n \"\"\"Write variables to tensorboard.\"\"\"\n with self.writer.as_default():\n for key, value in list_metrics.items():\n tf.summary.scalar(stage + \"/\" + key, value.result(), step=self.steps)\n self.writer.flush()\n\n\nclass GanBasedTrainer(BasedTrainer):\n \"\"\"Customized trainer module for GAN TTS training (MelGAN, GAN-TTS, ParallelWaveGAN).\"\"\"\n\n def __init__(\n self,\n steps,\n epochs,\n config,\n strategy,\n is_generator_mixed_precision=False,\n is_discriminator_mixed_precision=False,\n ):\n \"\"\"Initialize trainer.\n\n Args:\n steps (int): Initial global steps.\n epochs (int): Initial global epochs.\n config (dict): Config dict loaded from yaml format configuration file.\n\n \"\"\"\n super().__init__(steps, epochs, config)\n self._is_generator_mixed_precision = is_generator_mixed_precision\n self._is_discriminator_mixed_precision = is_discriminator_mixed_precision\n self._strategy = strategy\n self._already_apply_input_signature = False\n\n def init_train_eval_metrics(self, list_metrics_name):\n with self._strategy.scope():\n super().init_train_eval_metrics(list_metrics_name)\n\n def get_n_gpus(self):\n return self._strategy.num_replicas_in_sync\n\n def _get_train_element_signature(self):\n return self.train_data_loader.element_spec\n\n def _get_eval_element_signature(self):\n return self.eval_data_loader.element_spec\n\n def set_gen_model(self, generator_model):\n \"\"\"Set generator class model (MUST).\"\"\"\n self._generator = generator_model\n\n def get_gen_model(self):\n \"\"\"Get generator model.\"\"\"\n return self._generator\n\n def set_dis_model(self, discriminator_model):\n \"\"\"Set discriminator class model (MUST).\"\"\"\n self._discriminator = discriminator_model\n\n def get_dis_model(self):\n \"\"\"Get discriminator model.\"\"\"\n return self._discriminator\n\n def set_gen_optimizer(self, generator_optimizer):\n \"\"\"Set generator optimizer (MUST).\"\"\"\n self._gen_optimizer = generator_optimizer\n if self._is_generator_mixed_precision:\n self._gen_optimizer = tf.keras.mixed_precision.experimental.LossScaleOptimizer(\n self._gen_optimizer, \"dynamic\"\n )\n\n def get_gen_optimizer(self):\n \"\"\"Get generator optimizer.\"\"\"\n return self._gen_optimizer\n\n def set_dis_optimizer(self, discriminator_optimizer):\n \"\"\"Set discriminator optimizer (MUST).\"\"\"\n self._dis_optimizer = discriminator_optimizer\n if self._is_discriminator_mixed_precision:\n self._dis_optimizer = tf.keras.mixed_precision.experimental.LossScaleOptimizer(\n self._dis_optimizer, \"dynamic\"\n )\n\n def get_dis_optimizer(self):\n \"\"\"Get discriminator optimizer.\"\"\"\n return self._dis_optimizer\n\n def compile(self, gen_model, dis_model, gen_optimizer, dis_optimizer):\n self.set_gen_model(gen_model)\n self.set_dis_model(dis_model)\n self.set_gen_optimizer(gen_optimizer)\n self.set_dis_optimizer(dis_optimizer)\n\n def _train_step(self, batch):\n if self._already_apply_input_signature is False:\n train_element_signature = self._get_train_element_signature()\n eval_element_signature = self._get_eval_element_signature()\n self.one_step_forward = tf.function(\n self._one_step_forward, input_signature=[train_element_signature]\n )\n self.one_step_evaluate = tf.function(\n self._one_step_evaluate, input_signature=[eval_element_signature]\n )\n self.one_step_predict = tf.function(\n self._one_step_predict, input_signature=[eval_element_signature]\n )\n self._already_apply_input_signature = True\n\n # run one_step_forward\n self.one_step_forward(batch)\n\n # update counts\n self.steps += 1\n self.tqdm.update(1)\n self._check_train_finish()\n\n def _one_step_forward(self, batch):\n per_replica_losses = self._strategy.run(\n self._one_step_forward_per_replica, args=(batch,)\n )\n return self._strategy.reduce(\n tf.distribute.ReduceOp.SUM, per_replica_losses, axis=None\n )\n\n @abc.abstractmethod\n def compute_per_example_generator_losses(self, batch, outputs):\n \"\"\"Compute per example generator losses and return dict_metrics_losses\n Note that all element of the loss MUST has a shape [batch_size] and \n the keys of dict_metrics_losses MUST be in self.list_metrics_name.\n\n Args:\n batch: dictionary batch input return from dataloader\n outputs: outputs of the model\n \n Returns:\n per_example_losses: per example losses for each GPU, shape [B]\n dict_metrics_losses: dictionary loss.\n \"\"\"\n per_example_losses = 0.0\n dict_metrics_losses = {}\n return per_example_losses, dict_metrics_losses\n\n @abc.abstractmethod\n def compute_per_example_discriminator_losses(self, batch, gen_outputs):\n \"\"\"Compute per example discriminator losses and return dict_metrics_losses\n Note that all element of the loss MUST has a shape [batch_size] and \n the keys of dict_metrics_losses MUST be in self.list_metrics_name.\n\n Args:\n batch: dictionary batch input return from dataloader\n outputs: outputs of the model\n \n Returns:\n per_example_losses: per example losses for each GPU, shape [B]\n dict_metrics_losses: dictionary loss.\n \"\"\"\n per_example_losses = 0.0\n dict_metrics_losses = {}\n return per_example_losses, dict_metrics_losses\n\n def _one_step_forward_per_replica(self, batch):\n per_replica_gen_losses = 0.0\n per_replica_dis_losses = 0.0\n\n # one step generator.\n with tf.GradientTape() as g_tape:\n outputs = self._generator(**batch, training=True)\n (\n per_example_losses,\n dict_metrics_losses,\n ) = self.compute_per_example_generator_losses(batch, outputs)\n\n per_replica_gen_losses = tf.nn.compute_average_loss(\n per_example_losses,\n global_batch_size=self.config[\"batch_size\"] * self.get_n_gpus(),\n )\n\n if self._is_generator_mixed_precision:\n scaled_per_replica_gen_losses = self._gen_optimizer.get_scaled_loss(\n per_replica_gen_losses\n )\n\n if self._is_generator_mixed_precision:\n scaled_gradients = g_tape.gradient(\n scaled_per_replica_gen_losses, self._generator.trainable_variables\n )\n gradients = self._gen_optimizer.get_unscaled_gradients(scaled_gradients)\n else:\n gradients = g_tape.gradient(\n per_replica_gen_losses, self._generator.trainable_variables\n )\n\n self._gen_optimizer.apply_gradients(\n zip(gradients, self._generator.trainable_variables)\n )\n\n # accumulate loss into metrics\n self.update_train_metrics(dict_metrics_losses)\n\n # one step discriminator\n # recompute y_hat after 1 step generator for discriminator training.\n if self.steps >= self.config[\"discriminator_train_start_steps\"]:\n with tf.GradientTape() as d_tape:\n (\n per_example_losses,\n dict_metrics_losses,\n ) = self.compute_per_example_discriminator_losses(\n batch, self._generator(**batch)\n )\n\n per_replica_dis_losses = tf.nn.compute_average_loss(\n per_example_losses,\n global_batch_size=self.config[\"batch_size\"] * self.get_n_gpus(),\n )\n\n if self._is_discriminator_mixed_precision:\n scaled_per_replica_dis_losses = self._dis_optimizer.get_scaled_loss(\n per_replica_dis_losses\n )\n\n if self._is_discriminator_mixed_precision:\n scaled_gradients = d_tape.gradient(\n scaled_per_replica_dis_losses,\n self._discriminator.trainable_variables,\n )\n gradients = self._dis_optimizer.get_unscaled_gradients(scaled_gradients)\n else:\n gradients = d_tape.gradient(\n per_replica_dis_losses, self._discriminator.trainable_variables\n )\n\n self._dis_optimizer.apply_gradients(\n zip(gradients, self._discriminator.trainable_variables)\n )\n\n # accumulate loss into metrics\n self.update_train_metrics(dict_metrics_losses)\n\n return per_replica_gen_losses + per_replica_dis_losses\n\n def _eval_epoch(self):\n \"\"\"Evaluate model one epoch.\"\"\"\n logging.info(f\"(Steps: {self.steps}) Start evaluation.\")\n\n # calculate loss for each batch\n for eval_steps_per_epoch, batch in enumerate(\n tqdm(self.eval_data_loader, desc=\"[eval]\"), 1\n ):\n # eval one step\n self.one_step_evaluate(batch)\n\n if eval_steps_per_epoch <= self.config[\"num_save_intermediate_results\"]:\n # save intermedia\n self.generate_and_save_intermediate_result(batch)\n\n logging.info(\n f\"(Steps: {self.steps}) Finished evaluation \"\n f\"({eval_steps_per_epoch} steps per epoch).\"\n )\n\n # average loss\n for key in self.eval_metrics.keys():\n logging.info(\n f\"(Steps: {self.steps}) eval_{key} = {self.eval_metrics[key].result():.4f}.\"\n )\n\n # record\n self._write_to_tensorboard(self.eval_metrics, stage=\"eval\")\n\n # reset\n self.reset_states_eval()\n\n def _one_step_evalute_per_replica(self, batch):\n ################################################\n # one step generator.\n outputs = self._generator(**batch, training=False)\n _, dict_metrics_losses = self.compute_per_example_generator_losses(\n batch, outputs\n )\n\n # accumulate loss into metrics\n self.update_eval_metrics(dict_metrics_losses)\n\n ################################################\n # one step discriminator\n if self.steps >= self.config[\"discriminator_train_start_steps\"]:\n _, dict_metrics_losses = self.compute_per_example_discriminator_losses(\n batch, outputs\n )\n\n # accumulate loss into metrics\n self.update_eval_metrics(dict_metrics_losses)\n\n ################################################\n\n def _one_step_evaluate(self, batch):\n self._strategy.run(self._one_step_evalute_per_replica, args=(batch,))\n\n def _one_step_predict_per_replica(self, batch):\n outputs = self._generator(**batch, training=False)\n return outputs\n\n def _one_step_predict(self, batch):\n outputs = self._strategy.run(self._one_step_predict_per_replica, args=(batch,))\n return outputs\n\n @abc.abstractmethod\n def generate_and_save_intermediate_result(self, batch):\n return\n\n def create_checkpoint_manager(self, saved_path=None, max_to_keep=10):\n \"\"\"Create checkpoint management.\"\"\"\n if saved_path is None:\n saved_path = self.config[\"outdir\"] + \"/checkpoints/\"\n\n os.makedirs(saved_path, exist_ok=True)\n\n self.saved_path = saved_path\n self.ckpt = tf.train.Checkpoint(\n steps=tf.Variable(1),\n epochs=tf.Variable(1),\n gen_optimizer=self.get_gen_optimizer(),\n dis_optimizer=self.get_dis_optimizer(),\n )\n self.ckp_manager = tf.train.CheckpointManager(\n self.ckpt, saved_path, max_to_keep=max_to_keep\n )\n\n def save_checkpoint(self):\n \"\"\"Save checkpoint.\"\"\"\n self.ckpt.steps.assign(self.steps)\n self.ckpt.epochs.assign(self.epochs)\n self.ckp_manager.save(checkpoint_number=self.steps)\n self._generator.save_weights(\n self.saved_path + \"generator-{}.h5\".format(self.steps)\n )\n self._discriminator.save_weights(\n self.saved_path + \"discriminator-{}.h5\".format(self.steps)\n )\n\n def load_checkpoint(self, pretrained_path):\n \"\"\"Load checkpoint.\"\"\"\n self.ckpt.restore(pretrained_path)\n self.steps = self.ckpt.steps.numpy()\n self.epochs = self.ckpt.epochs.numpy()\n self._gen_optimizer = self.ckpt.gen_optimizer\n # re-assign iterations (global steps) for gen_optimizer.\n self._gen_optimizer.iterations.assign(tf.cast(self.steps, tf.int64))\n # re-assign iterations (global steps) for dis_optimizer.\n try:\n discriminator_train_start_steps = self.config[\n \"discriminator_train_start_steps\"\n ]\n discriminator_train_start_steps = tf.math.maximum(\n 0, discriminator_train_start_steps - self.steps\n )\n except Exception:\n discriminator_train_start_steps = self.steps\n self._dis_optimizer = self.ckpt.dis_optimizer\n self._dis_optimizer.iterations.assign(\n tf.cast(discriminator_train_start_steps, tf.int64)\n )\n\n # load weights.\n self._generator.load_weights(\n self.saved_path + \"generator-{}.h5\".format(self.steps)\n )\n self._discriminator.load_weights(\n self.saved_path + \"discriminator-{}.h5\".format(self.steps)\n )\n\n def _check_train_finish(self):\n \"\"\"Check training finished.\"\"\"\n if self.steps >= self.config[\"train_max_steps\"]:\n self.finish_train = True\n\n if (\n self.steps != 0\n and self.steps == self.config[\"discriminator_train_start_steps\"]\n ):\n self.finish_train = True\n logging.info(\n f\"Finished training only generator at {self.steps}steps, pls resume and continue training.\"\n )\n\n def _check_log_interval(self):\n \"\"\"Log to tensorboard.\"\"\"\n if self.steps % self.config[\"log_interval_steps\"] == 0:\n for metric_name in self.list_metrics_name:\n logging.info(\n f\"(Step: {self.steps}) train_{metric_name} = {self.train_metrics[metric_name].result():.4f}.\"\n )\n self._write_to_tensorboard(self.train_metrics, stage=\"train\")\n\n # reset\n self.reset_states_train()\n\n def fit(self, train_data_loader, valid_data_loader, saved_path, resume=None):\n self.set_train_data_loader(train_data_loader)\n self.set_eval_data_loader(valid_data_loader)\n self.train_data_loader = self._strategy.experimental_distribute_dataset(\n self.train_data_loader\n )\n self.eval_data_loader = self._strategy.experimental_distribute_dataset(\n self.eval_data_loader\n )\n with self._strategy.scope():\n self.create_checkpoint_manager(saved_path=saved_path, max_to_keep=10000)\n if len(resume) > 1:\n self.load_checkpoint(resume)\n logging.info(f\"Successfully resumed from {resume}.\")\n self.run()\n\n\nclass Seq2SeqBasedTrainer(BasedTrainer, metaclass=abc.ABCMeta):\n \"\"\"Customized trainer module for Seq2Seq TTS training (Tacotron, FastSpeech).\"\"\"\n\n def __init__(\n self, steps, epochs, config, strategy, is_mixed_precision=False,\n ):\n \"\"\"Initialize trainer.\n\n Args:\n steps (int): Initial global steps.\n epochs (int): Initial global epochs.\n config (dict): Config dict loaded from yaml format configuration file.\n strategy (tf.distribute): Strategy for distributed training.\n is_mixed_precision (bool): Use mixed_precision training or not.\n\n \"\"\"\n super().__init__(steps, epochs, config)\n self._is_mixed_precision = is_mixed_precision\n self._strategy = strategy\n\n # check if we already apply input_signature for train_step.\n self._already_apply_input_signature = False\n\n def init_train_eval_metrics(self, list_metrics_name):\n with self._strategy.scope():\n super().init_train_eval_metrics(list_metrics_name)\n\n def set_model(self, model):\n \"\"\"Set generator class model (MUST).\"\"\"\n self._model = model\n\n def get_model(self):\n \"\"\"Get generator model.\"\"\"\n return self._model\n\n def set_optimizer(self, optimizer):\n \"\"\"Set optimizer (MUST).\"\"\"\n self._optimizer = optimizer\n if self._is_mixed_precision:\n self._optimizer = tf.keras.mixed_precision.experimental.LossScaleOptimizer(\n self._optimizer, \"dynamic\"\n )\n\n def get_optimizer(self):\n \"\"\"Get optimizer.\"\"\"\n return self._optimizer\n\n def get_n_gpus(self):\n return self._strategy.num_replicas_in_sync\n\n def compile(self, model, optimizer):\n self.set_model(model)\n self.set_optimizer(optimizer)\n\n def _get_train_element_signature(self):\n return self.train_data_loader.element_spec\n\n def _get_eval_element_signature(self):\n return self.eval_data_loader.element_spec\n\n def _train_step(self, batch):\n if self._already_apply_input_signature is False:\n train_element_signature = self._get_train_element_signature()\n eval_element_signature = self._get_eval_element_signature()\n self.one_step_forward = tf.function(\n self._one_step_forward, input_signature=[train_element_signature]\n )\n self.one_step_evaluate = tf.function(\n self._one_step_evaluate, input_signature=[eval_element_signature]\n )\n self.one_step_predict = tf.function(\n self._one_step_predict, input_signature=[eval_element_signature]\n )\n self._already_apply_input_signature = True\n\n # run one_step_forward\n self.one_step_forward(batch)\n\n # update counts\n self.steps += 1\n self.tqdm.update(1)\n self._check_train_finish()\n\n def _one_step_forward(self, batch):\n per_replica_losses = self._strategy.run(\n self._one_step_forward_per_replica, args=(batch,)\n )\n return self._strategy.reduce(\n tf.distribute.ReduceOp.SUM, per_replica_losses, axis=None\n )\n\n def _one_step_forward_per_replica(self, batch):\n with tf.GradientTape() as tape:\n outputs = self._model(**batch, training=True)\n per_example_losses, dict_metrics_losses = self.compute_per_example_losses(\n batch, outputs\n )\n per_replica_losses = tf.nn.compute_average_loss(\n per_example_losses,\n global_batch_size=self.config[\"batch_size\"] * self.get_n_gpus(),\n )\n\n if self._is_mixed_precision:\n scaled_per_replica_losses = self._optimizer.get_scaled_loss(\n per_replica_losses\n )\n\n if self._is_mixed_precision:\n scaled_gradients = tape.gradient(\n scaled_per_replica_losses, self._model.trainable_variables\n )\n gradients = self._optimizer.get_unscaled_gradients(scaled_gradients)\n else:\n gradients = tape.gradient(\n per_replica_losses, self._model.trainable_variables\n )\n\n self._optimizer.apply_gradients(\n zip(gradients, self._model.trainable_variables), 1.0\n )\n\n # accumulate loss into metrics\n self.update_train_metrics(dict_metrics_losses)\n\n return per_replica_losses\n\n @abc.abstractmethod\n def compute_per_example_losses(self, batch, outputs):\n \"\"\"Compute per example losses and return dict_metrics_losses\n Note that all element of the loss MUST has a shape [batch_size] and \n the keys of dict_metrics_losses MUST be in self.list_metrics_name.\n\n Args:\n batch: dictionary batch input return from dataloader\n outputs: outputs of the model\n \n Returns:\n per_example_losses: per example losses for each GPU, shape [B]\n dict_metrics_losses: dictionary loss.\n \"\"\"\n per_example_losses = 0.0\n dict_metrics_losses = {}\n return per_example_losses, dict_metrics_losses\n\n def _eval_epoch(self):\n \"\"\"Evaluate model one epoch.\"\"\"\n logging.info(f\"(Steps: {self.steps}) Start evaluation.\")\n\n # calculate loss for each batch\n for eval_steps_per_epoch, batch in enumerate(\n tqdm(self.eval_data_loader, desc=\"[eval]\"), 1\n ):\n # eval one step\n self.one_step_evaluate(batch)\n\n if eval_steps_per_epoch <= self.config[\"num_save_intermediate_results\"]:\n # save intermedia\n self.generate_and_save_intermediate_result(batch)\n\n logging.info(\n f\"(Steps: {self.steps}) Finished evaluation \"\n f\"({eval_steps_per_epoch} steps per epoch).\"\n )\n\n # average loss\n for key in self.eval_metrics.keys():\n logging.info(\n f\"(Steps: {self.steps}) eval_{key} = {self.eval_metrics[key].result():.4f}.\"\n )\n\n # record\n self._write_to_tensorboard(self.eval_metrics, stage=\"eval\")\n\n # reset\n self.reset_states_eval()\n\n def _one_step_evalute_per_replica(self, batch):\n outputs = self._model(**batch, training=False)\n _, dict_metrics_losses = self.compute_per_example_losses(batch, outputs)\n\n self.update_eval_metrics(dict_metrics_losses)\n\n def _one_step_evaluate(self, batch):\n self._strategy.run(self._one_step_evalute_per_replica, args=(batch,))\n\n def _one_step_predict_per_replica(self, batch):\n outputs = self._model(**batch, training=False)\n return outputs\n\n def _one_step_predict(self, batch):\n outputs = self._strategy.run(self._one_step_predict_per_replica, args=(batch,))\n return outputs\n\n @abc.abstractmethod\n def generate_and_save_intermediate_result(self, batch):\n return\n\n def create_checkpoint_manager(self, saved_path=None, max_to_keep=10):\n \"\"\"Create checkpoint management.\"\"\"\n if saved_path is None:\n saved_path = self.config[\"outdir\"] + \"/checkpoints/\"\n\n os.makedirs(saved_path, exist_ok=True)\n\n self.saved_path = saved_path\n self.ckpt = tf.train.Checkpoint(\n steps=tf.Variable(1), epochs=tf.Variable(1), optimizer=self.get_optimizer()\n )\n self.ckp_manager = tf.train.CheckpointManager(\n self.ckpt, saved_path, max_to_keep=max_to_keep\n )\n\n def save_checkpoint(self):\n \"\"\"Save checkpoint.\"\"\"\n self.ckpt.steps.assign(self.steps)\n self.ckpt.epochs.assign(self.epochs)\n self.ckp_manager.save(checkpoint_number=self.steps)\n self._model.save_weights(self.saved_path + \"model-{}.h5\".format(self.steps))\n\n def load_checkpoint(self, pretrained_path):\n \"\"\"Load checkpoint.\"\"\"\n self.ckpt.restore(pretrained_path)\n self.steps = self.ckpt.steps.numpy()\n self.epochs = self.ckpt.epochs.numpy()\n self._optimizer = self.ckpt.optimizer\n # re-assign iterations (global steps) for optimizer.\n self._optimizer.iterations.assign(tf.cast(self.steps, tf.int64))\n\n # load weights.\n self._model.load_weights(self.saved_path + \"model-{}.h5\".format(self.steps))\n\n def _check_train_finish(self):\n \"\"\"Check training finished.\"\"\"\n if self.steps >= self.config[\"train_max_steps\"]:\n self.finish_train = True\n\n def _check_log_interval(self):\n \"\"\"Log to tensorboard.\"\"\"\n if self.steps % self.config[\"log_interval_steps\"] == 0:\n for metric_name in self.list_metrics_name:\n logging.info(\n f\"(Step: {self.steps}) train_{metric_name} = {self.train_metrics[metric_name].result():.4f}.\"\n )\n self._write_to_tensorboard(self.train_metrics, stage=\"train\")\n\n # reset\n self.reset_states_train()\n\n def fit(self, train_data_loader, valid_data_loader, saved_path, resume=None):\n self.set_train_data_loader(train_data_loader)\n self.set_eval_data_loader(valid_data_loader)\n self.train_data_loader = self._strategy.experimental_distribute_dataset(\n self.train_data_loader\n )\n self.eval_data_loader = self._strategy.experimental_distribute_dataset(\n self.eval_data_loader\n )\n with self._strategy.scope():\n self.create_checkpoint_manager(saved_path=saved_path, max_to_keep=10000)\n if len(resume) > 1:\n self.load_checkpoint(resume)\n logging.info(f\"Successfully resumed from {resume}.\")\n self.run()\n"
] |
[
[
"tensorflow.train.CheckpointManager",
"tensorflow.keras.mixed_precision.experimental.LossScaleOptimizer",
"tensorflow.Variable",
"tensorflow.summary.create_file_writer",
"tensorflow.cast",
"tensorflow.math.maximum",
"tensorflow.function",
"tensorflow.keras.metrics.Mean",
"tensorflow.GradientTape"
]
] |
alienbrett/numerical-eqs-collection
|
[
"23619bf379d53ce0facb63be08ee6a3902d404d5"
] |
[
"numerical_eqs/matrix/tridiag.py"
] |
[
"import numpy as np\n\n\n\n\nclass TriDiag:\n def __init__(self, a, d, b, n=None):\n if n is None:\n n = len(d)\n \n self.n = n\n self.a = np.asarray(a)\n self.b = np.asarray(b)\n self.d = np.asarray(d)\n \n \n\n\n\n\n def mult(self, x):\n '''Multiplies tridiagonal matrix by some vector of length n\n '''\n x = np.asarray(x)\n \n return (self.d * x) + \\\n np.concatenate([self.a * x[1:],[0]]) + \\\n np.concatenate([[0], self.b * x[:-1]])\n\n\n\n \n \n\n def solve(self, y, verbose=True):\n '''Finds solution to equation Ax=y for x\n verbose: print arrays after solving\n All changes to internal arrays will be reset after solving\n '''\n y = np.asarray(y)\n \n # Create checkpoint, so that internal arrays can be manipulated\n checkPoint = (self.a, self.b, self.d)\n \n if verbose:\n print(\"Matrix before solve:\")\n for label, array in [('a',self.a), ('d',self.d), ('b',self.b)]:\n print('{} array:'.format(label), array)\n print()\n \n # Forward solve\n for i in range(self.n):\n y[i] = y[i] / self.d[i]\n if i < self.n-1:\n self.a[i] = self.a[i] / self.d[i]\n self.d[i+1] = self.d[i+1] - self.b[i] * self.a[i]\n y[i+1] = y[i+1] - self.b[i] * y[i]\n \n # Backward solve\n k = self.n-1\n for j in range(k):\n i = k-j-1\n y[i] = y[i] - self.a[i] * y[i+1]\n \n if verbose:\n print(\"Matrix after solve:\")\n for label, array in [('a',self.a), ('d',self.d), ('b',self.b)]:\n print('{} array:'.format(label), array)\n print()\n \n # Restore the checkpoint\n self.a, self.b, self.d = checkPoint\n \n return y\n \n\n\n\n\n\n\n \n# Generate matrix according to specifications in description\ndef matGen (n):\n d = np.ones(n)*4 + 0.1 * np.arange(n)\n a = np.ones(n-1) + np.arange(n-1)**2 * 0.01\n b = 0.99 * np.ones(n-1) - 0.03 * np.arange(1,n)\n return d,a,b\n\n\n\n\n\n\n\n\nif __name__ == '__main__':\n\n\n\n # Test this size matrix\n k = 5\n\n # Generate matrix accordingly\n # We never actually use the full MxM matrix,\n # we just generate the diagonals\n d,a,b = matGen(k)\n\n # Our wrapper for matrix\n t = TriDiag(a,d,b)\n\n # Generate arbitrary x\n x = np.arange(k)\n\n # Pass X through matrix\n y = t.mult(x)\n\n\n # Try to solve for the X that generated Ax=y\n print(\"SOLVING MATRIX\")\n print(''.join(['#']*40))\n xp = t.solve(y, verbose=True)\n\n print(''.join(['#']*40))\n print('Original X:', x)\n print('Solution X:', xp)\n print('Norm of difference:', np.linalg.norm(x-xp))\n\n\n\n\n # Try to solve for the X that generated Ax=y\n print(\"SOLVING MATRIX\")\n print(''.join(['#']*40))\n xp = t.solve(y, verbose=True)\n\n print(''.join(['#']*40))\n print('Original X:', x)\n print('Solution X:', xp)\n print('Norm of difference:', np.linalg.norm(x-xp))\n"
] |
[
[
"numpy.asarray",
"numpy.arange",
"numpy.linalg.norm",
"numpy.ones",
"numpy.concatenate"
]
] |
xdeng7/redwood_open3d_3dreconstruction
|
[
"dda9b3a0129fa6c60f913672a70ff02483dcd0f3"
] |
[
"Open3D/examples/python/reconstruction_system/sensors/realsense_recorder.py"
] |
[
"# Open3D: www.open3d.org\n# The MIT License (MIT)\n# See license file or visit www.open3d.org for details\n\n# examples/python/reconstruction_system/sensors/realsense_recorder.py\n\n# pyrealsense2 is required.\n# Please see instructions in https://github.com/IntelRealSense/librealsense/tree/master/wrappers/python\nimport pyrealsense2 as rs\nimport numpy as np\nimport cv2\nimport argparse\nfrom os import makedirs\nfrom os.path import exists, join\nimport shutil\nimport json\nfrom enum import IntEnum\n\ntry:\n # Python 2 compatible\n input = raw_input\nexcept NameError:\n pass\n\n\nclass Preset(IntEnum):\n Custom = 0\n Default = 1\n Hand = 2\n HighAccuracy = 3\n HighDensity = 4\n MediumDensity = 5\n\n\ndef make_clean_folder(path_folder):\n if not exists(path_folder):\n makedirs(path_folder)\n else:\n user_input = input(\"%s not empty. Overwrite? (y/n) : \" % path_folder)\n if user_input.lower() == 'y':\n shutil.rmtree(path_folder)\n makedirs(path_folder)\n else:\n exit()\n\n\ndef save_intrinsic_as_json(filename, frame):\n intrinsics = frame.profile.as_video_stream_profile().intrinsics\n with open(filename, 'w') as outfile:\n obj = json.dump(\n {\n 'width':\n intrinsics.width,\n 'height':\n intrinsics.height,\n 'intrinsic_matrix': [\n intrinsics.fx, 0, 0, 0, intrinsics.fy, 0, intrinsics.ppx,\n intrinsics.ppy, 1\n ]\n },\n outfile,\n indent=4)\n\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser(\n description=\n \"Realsense Recorder. Please select one of the optional arguments\")\n parser.add_argument(\"--output_folder\",\n default='../dataset/realsense/',\n help=\"set output folder\")\n parser.add_argument(\"--record_rosbag\",\n action='store_true',\n help=\"Recording rgbd stream into realsense.bag\")\n parser.add_argument(\n \"--record_imgs\",\n action='store_true',\n help=\"Recording save color and depth images into realsense folder\")\n parser.add_argument(\"--playback_rosbag\",\n action='store_true',\n help=\"Play recorded realsense.bag file\")\n args = parser.parse_args()\n\n if sum(o is not False for o in vars(args).values()) != 2:\n parser.print_help()\n exit()\n\n path_output = args.output_folder\n path_depth = join(args.output_folder, \"depth\")\n path_color = join(args.output_folder, \"color\")\n if args.record_imgs:\n make_clean_folder(path_output)\n make_clean_folder(path_depth)\n make_clean_folder(path_color)\n\n path_bag = join(args.output_folder, \"realsense.bag\")\n if args.record_rosbag:\n if exists(path_bag):\n user_input = input(\"%s exists. Overwrite? (y/n) : \" % path_bag)\n if user_input.lower() == 'n':\n exit()\n\n # Create a pipeline\n pipeline = rs.pipeline()\n\n #Create a config and configure the pipeline to stream\n # different resolutions of color and depth streams\n config = rs.config()\n\n if args.record_imgs or args.record_rosbag:\n # note: using 640 x 480 depth resolution produces smooth depth boundaries\n # using rs.format.bgr8 for color image format for OpenCV based image visualization\n config.enable_stream(rs.stream.depth, 1280, 720, rs.format.z16, 30)\n config.enable_stream(rs.stream.color, 640, 480, rs.format.bgr8, 30)\n if args.record_rosbag:\n config.enable_record_to_file(path_bag)\n if args.playback_rosbag:\n config.enable_device_from_file(path_bag, repeat_playback=True)\n\n # Start streaming\n profile = pipeline.start(config)\n depth_sensor = profile.get_device().first_depth_sensor()\n\n # Using preset HighAccuracy for recording\n if args.record_rosbag or args.record_imgs:\n depth_sensor.set_option(rs.option.visual_preset, Preset.HighAccuracy)\n\n # Getting the depth sensor's depth scale (see rs-align example for explanation)\n depth_scale = depth_sensor.get_depth_scale()\n\n # We will not display the background of objects more than\n # clipping_distance_in_meters meters away\n clipping_distance_in_meters = 3 # 3 meter\n clipping_distance = clipping_distance_in_meters / depth_scale\n\n # Create an align object\n # rs.align allows us to perform alignment of depth frames to others frames\n # The \"align_to\" is the stream type to which we plan to align depth frames.\n align_to = rs.stream.color\n align = rs.align(align_to)\n\n # Streaming loop\n frame_count = 0\n try:\n while True:\n # Get frameset of color and depth\n frames = pipeline.wait_for_frames()\n\n # Align the depth frame to color frame\n aligned_frames = align.process(frames)\n\n # Get aligned frames\n aligned_depth_frame = aligned_frames.get_depth_frame()\n color_frame = aligned_frames.get_color_frame()\n\n # Validate that both frames are valid\n if not aligned_depth_frame or not color_frame:\n continue\n\n depth_image = np.asanyarray(aligned_depth_frame.get_data())\n color_image = np.asanyarray(color_frame.get_data())\n\n if args.record_imgs:\n if frame_count == 0:\n save_intrinsic_as_json(\n join(args.output_folder, \"camera_intrinsic.json\"),\n color_frame)\n cv2.imwrite(\"%s/%06d.png\" % \\\n (path_depth, frame_count), depth_image)\n cv2.imwrite(\"%s/%06d.jpg\" % \\\n (path_color, frame_count), color_image)\n print(\"Saved color + depth image %06d\" % frame_count)\n frame_count += 1\n\n # Remove background - Set pixels further than clipping_distance to grey\n grey_color = 153\n #depth image is 1 channel, color is 3 channels\n depth_image_3d = np.dstack((depth_image, depth_image, depth_image))\n bg_removed = np.where((depth_image_3d > clipping_distance) | \\\n (depth_image_3d <= 0), grey_color, color_image)\n\n # Render images\n depth_colormap = cv2.applyColorMap(\n cv2.convertScaleAbs(depth_image, alpha=0.09), cv2.COLORMAP_JET)\n images = np.hstack((bg_removed, depth_colormap))\n cv2.namedWindow('Recorder Realsense', cv2.WINDOW_AUTOSIZE)\n cv2.imshow('Recorder Realsense', images)\n key = cv2.waitKey(1)\n\n # if 'esc' button pressed, escape loop and exit program\n if key == 27:\n cv2.destroyAllWindows()\n break\n finally:\n pipeline.stop()\n"
] |
[
[
"numpy.hstack",
"numpy.where",
"numpy.dstack"
]
] |
toraud96/sqlalchemy-challenge
|
[
"9e5f0f4e57d435be68ede9def8384d372d415bdf"
] |
[
"sqlalchemy.app.py"
] |
[
"import numpy as np\n\nimport sqlalchemy\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import create_engine, func\nimport datetime as dt\n\nfrom flask import Flask, jsonify\n\n#################################################\n# Database Setup\n#################################################\n\n# reflect the tables\nengine = create_engine(\"sqlite:///Resources/hawaii.sqlite\")\nBase = automap_base()\nBase.prepare(engine, reflect=True)\n\n\n# reflect an existing database into a new model\n\n# reflect the tables\nBase.prepare(engine, reflect=True)\n\n# We can view all of the classes that automap found\nBase.classes.keys()\n\n# Save references to each table\nMeasurement = Base.classes.measurement\nStation = Base.classes.station\n\n# Create our session (link) from Python to the DB\nsession = Session(engine)\n\n#################################################\n# Flask Setup\n#################################################\napp = Flask(__name__)\n\n\n#################################################\n# Flask Routes\n#################################################\n\[email protected](\"/\")\ndef welcome():\n \"\"\"List all available api routes.\"\"\"\n return (\n f\"/api/v1.0/precipitation:<br/>\"\n f\"/api/v1.0/stations<br/>\"\n f\"/api/v1.0/tobs<br/>\"\n f\"/api/v1.0/<start><br/>\"\n f\"/api/v1.0/<start>/<end><br/>\"\n )\[email protected](\"/api/v1.0/precipitation\")\ndef names():\n # Create our session (link) from Python to the DB\n\n \"\"\"Return a list of all passenger names\"\"\"\n # Query all passengers\n\n # Convert list of tuples into normal list\n begin_point = dt.date(2017, 8, 23) - dt.timedelta(days=365)\n \n data = session.query(Measurement.date, Measurement.prcp).\\\n filter(Measurement.date >= begin_point).\\\n order_by(Measurement.date).all()\n\n all_names={date:prcp for date, prcp in data}\n\n return jsonify(all_names)\n\[email protected](\"/api/v1.0/stations\")\ndef stations():\n stations = session.query(Station.station).all()\n results=list(np.ravel(stations))\n return jsonify(results)\n\[email protected](\"/api/v1.0/tobs\")\ndef sel():\n sel = [Measurement.station, \n func.min(Measurement.tobs), \n func.max(Measurement.tobs), \n func.avg(Measurement.tobs)]\n sel=session.query(*sel).filter(Measurement.station=='USC00519281').all()\n results=list(np.ravel(sel))\n return jsonify(results)\n\[email protected](\"/api/v1.0/temp/begin_point\")\ndef stats(begin_point=None):\n temp=session.query(Measurement.tobs).\\\n filter(Measurement.station=='USC00519281').\\\n filter(Measurement.date >= begin_point).\\\n order_by(Measurement.date.desc()).all()\n results=list(np.ravel(temp))\n return jsonify(results)\n\n\n# @app.route(\"/api/v1.0/temp/<start>/<end>\")\n# def stats(vacay_start=None, vacay_end=None):\n# data4 = session.query(Measurement.date, Measurement.prcp).\\\n# filter(Measurement.date >= vacay_start).\\\n# filter(Measurement.date <= vacay_end).\\\n# order_by((Measurement.date).desc()).all()\n# results=list(np.ravel(data4))\n# return jsonify(results)\n\nif __name__ == '__main__':\n app.run(debug=True)"
] |
[
[
"numpy.ravel"
]
] |
HERA-Team/casa-imaging
|
[
"8cad11102f0a70b51ce9d73056d6c5dab16e1a73"
] |
[
"scripts/calfits_to_Bcal.py"
] |
[
"#!/usr/bin/env python2.7\n\"\"\"\ncalfits_to_Bcal.py\n----------------\n\nA CASA script for converting a\ncalfits gain file into a CASA\nbandpass cal table.\n\nRun as casa -c calfits_to_Bcal.py <args>\n\nNicholas Kern\nOct. 2018\n\"\"\"\nimport pyfits\nimport os\nimport shutil\nimport numpy as np\nimport argparse\n\n## Set Arguments\na = argparse.ArgumentParser(description=\"Run with casa as: casa -c calfits_to_Bcal.py <args>\")\na.add_argument('--script', '-c', type=str, help='name of this script', required=True)\na.add_argument('--cfits', default=None, type=str, help='Path to calfits FITS file.', required=True)\na.add_argument(\"--inp_cfile\", default=None, type=str, help=\"Path to CASA bandpass cal table.\", required=True)\na.add_argument(\"--out_cfile\", default=None, type=str, help=\"Name of output cal table. Default is overwrite input.\")\na.add_argument(\"--overwrite\", default=False, action='store_true', help='Overwrite output if True.')\n\n\ndef calfits_to_Bcal(cfits, inp_cfile, out_cfile=None, overwrite=False):\n \"\"\"\n Take a calfits antenna gain file and insert data into an existing\n CASA bandpass calibration table. Note that due to the obtuseness of CASA,\n this function is VERY rigid: the calfits file must be very similar in shape\n and order to the CASA Bcal table.\n\n It is only recommended to use this script on calfits files that were originally\n *B.cal tables, exported to B.cal.npz files by sky_cal.py and then converted to\n calfits via skynpz2calfits.py.\n\n Args:\n cfits : str, filepath to pyuvdata calfits file\n inp_cfile : str, filepath to CASA Bandpass calibration table to use as a template\n out_cfile : str, filepath for output CASA Bcal table with cfits data\n overwrite : bool, if True, overwrite output Bcal table\n \"\"\"\n # assert IO\n if out_cfile is None:\n out_cfile = inp_cfile \n if os.path.exists(out_cfile) and not overwrite:\n raise IOError(\"Output cal table {} exists and overwrite is False...\".format(out_cfile))\n\n # move inp_cfile to out_cfile\n if os.path.exists(out_cfile):\n shutil.rmtree(out_cfile)\n shutil.copytree(inp_cfile, out_cfile)\n\n # load cfits data and get metadata\n hdu = pyfits.open(cfits)\n head = hdu[0].header\n data = hdu[0].data\n\n # open out_cfile descriptor\n tb.open(out_cfile)\n assert \"CPARAM\" in tb.getdminfo()['*1']['COLUMNS'], \"{} is not a CASA bandpass table...\".format(inp_cfile)\n d = tb.getcol(\"CPARAM\")\n f = tb.getcol(\"FLAG\")\n a = tb.getcol(\"ANTENNA1\")\n\n # The pol axes must match in size\n assert head['NAXIS2'] == d.shape[0], \"Npols doesn't match between {} and {}\".format(inp_cfile, cfits)\n\n # real and imag are 0, 1 Image Array axes of fits file\n flags = data[:, 0, :, :, :, 2]\n data = data[:, 0, :, :, :, 0].astype(np.complex) - 1j * data[:, 0, :, :, :, 1] # CASA conjugates cal solutions...\n\n # extend to matching antennas\n Nants, Nfreqs, Ntimes, Npols = data.shape\n ants = hdu[1].data['ANTARR'].astype(np.int).tolist()\n _data, _flags = [], []\n for i, ant in enumerate(a):\n if ant in ants:\n aind = ants.index(ant)\n _data.append(data[aind])\n _flags.append(flags[aind])\n else:\n _data.append(np.ones((Nfreqs, Ntimes, Npols), dtype=np.complex))\n _flags.append(np.ones((Nfreqs, Ntimes, Npols), dtype=np.float))\n data = np.asarray(_data, dtype=np.complex)\n flags = np.asarray(_flags, dtype=np.float) \n\n # cal table is ordered as ant1_time1, ant2_time1, ... ant1_time2, ant2_time2\n Nants, Nfreqs, Ntimes, Npols = data.shape\n data = np.moveaxis(data, 2, 0).reshape(Nants * Ntimes, Nfreqs, Npols).T\n flags = np.moveaxis(flags, 2, 0).reshape(Nants * Ntimes, Nfreqs, Npols).T\n\n # now select frequencies that match cal table\n tb.close()\n tb.open(\"{}/SPECTRAL_WINDOW\".format(out_cfile))\n fr = tb.getcol(\"CHAN_FREQ\")[:, 0]\n tb.close()\n freqs = np.arange(head[\"NAXIS4\"]) * head[\"CDELT4\"] + head[\"CRVAL4\"]\n fselect = np.array([np.isclose(_f, fr).any() for _f in freqs])\n data = data[:, fselect, :]\n flags = flags[:, fselect, :]\n\n # the two arrays must match in shape now\n assert data.shape == d.shape, \"fits_data.shape != cal_data.shape...\"\n assert flags.shape == f.shape, \"fits_flags.shape != cal_flags.shape...\"\n\n # putcol\n print(\"...inserting {} data and flags into {}\".format(cfits, out_cfile))\n tb.open(out_cfile, nomodify=False)\n tb.putcol(\"CPARAM\", data)\n tb.putcol(\"FLAG\", flags)\n tb.close()\n\n return out_cfile\n\nif __name__ == \"__main__\":\n\n # parse args\n args = a.parse_args()\n kwargs = vars(args)\n del kwargs['script']\n cfits = kwargs.pop('cfits')\n inp_cfile = kwargs.pop('inp_cfile')\n\n # run script\n calfits_to_Bcal(cfits, inp_cfile, **kwargs)\n\n"
] |
[
[
"numpy.asarray",
"numpy.arange",
"numpy.ones",
"numpy.moveaxis",
"numpy.isclose"
]
] |
pranavjain594/Application-Rating-Prediction-and-User-Sentiment-Analysis
|
[
"051fa2eeb554b6764c612aaf688632afb85699a0"
] |
[
"Code/reviews.py"
] |
[
"# Natural Language Processing\n\n# Importing the libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# Importing the dataset\ndataset = pd.read_csv('googleplaystoreuserreviews.csv')\n\ndataset.dropna(inplace=True)\n\nX = dataset.iloc[:,0].values\n\n# Cleaning the texts\nimport re\nimport nltk\nnltk.download('stopwords')\nfrom nltk.corpus import stopwords\nfrom nltk.stem.porter import PorterStemmer\ncorpus = []\nfor i in range(0, 37427):\n review = re.sub('[^a-zA-Z]', ' ', str(X[i]))\n review = review.lower()\n review = review.split()\n ps = PorterStemmer()\n review = [ps.stem(word) for word in review if not word in set(stopwords.words('english'))]\n review = ' '.join(review)\n corpus.append(review)\n\n# Creating the Bag of Words model\nfrom sklearn.feature_extraction.text import CountVectorizer\ncv = CountVectorizer()\nx = cv.fit_transform(corpus).toarray()\ny = dataset.iloc[:, 1].values\n\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\nlabelencoder_X = LabelEncoder()\ny = labelencoder_X.fit_transform(y)\n\n# Splitting the dataset into the Training set and Test set\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(x, y, test_size = 0.20, random_state = 0)\n\nfrom sklearn.metrics import r2_score\n\n# Fitting Logistic regression to the Training set\nfrom sklearn.linear_model import LogisticRegression\nclassifier = LogisticRegression(random_state = 0)\nclassifier.fit(X_train, y_train)\ny_pred = classifier.predict(X_test)\nr2_score(y_test, y_pred)\n\n# Fitting Naive Bayes to the Training set\nfrom sklearn.naive_bayes import GaussianNB\nclassifier = GaussianNB()\nclassifier.fit(X_train, y_train)\ny_pred1 = classifier.predict(X_test)\nr2_score(y_test, y_pred1)\n\n# Making the Confusion Matrix\nfrom sklearn.metrics import confusion_matrix,accuracy_score\ncm = confusion_matrix(y_test, y_pred)\naccuracy_score(y_test, y_pred)\n\nfrom xgboost import XGBClassifier\nclassifier = XGBClassifier()\nclassifier.fit(X_train, y_train)\n\n# Predicting the Test set results\ny_pred = classifier.predict(X_test)\n\n# Making the Confusion Matrix\nfrom sklearn.metrics import confusion_matrix\ncm = confusion_matrix(y_test, y_pred)\n\n# Applying k-Fold Cross Validation\nfrom sklearn.model_selection import cross_val_score\naccuracies = cross_val_score(estimator = classifier, X = X_train, y = y_train, cv = 10)\naccuracies.mean()\naccuracies.std()\n"
] |
[
[
"pandas.read_csv",
"sklearn.metrics.r2_score",
"sklearn.linear_model.LogisticRegression",
"sklearn.naive_bayes.GaussianNB",
"sklearn.model_selection.cross_val_score",
"sklearn.model_selection.train_test_split",
"sklearn.metrics.confusion_matrix",
"sklearn.feature_extraction.text.CountVectorizer",
"sklearn.preprocessing.LabelEncoder",
"sklearn.metrics.accuracy_score"
]
] |
mirkobronzi/project20
|
[
"e7a9b52d87e21f436117c7020f167454ee78ffd6"
] |
[
"project20/models/my_model.py"
] |
[
"import logging\nimport torch.nn as nn\n\nfrom project20.utils.hp_utils import check_and_log_hp\n\nlogger = logging.getLogger(__name__)\n\n\nclass MyModel(nn.Module): # pragma: no cover\n \"\"\"Simple Model Class.\n\n Inherits from the given framework's model class. This is a simple MLP model.\n \"\"\"\n\n def __init__(self, hyper_params):\n \"\"\"__init__.\n\n Args:\n hyper_params (dict): hyper parameters from the config file.\n \"\"\"\n super(MyModel, self).__init__()\n\n check_and_log_hp(['size'], hyper_params)\n self.hyper_params = hyper_params\n self.linear1 = nn.Linear(5, hyper_params['size'])\n self.linear2 = nn.Linear(hyper_params['size'], 1)\n\n def forward(self, data):\n \"\"\"Forward method of the model.\n\n Args:\n data (tensor): The data to be passed to the model.\n\n Returns:\n tensor: the output of the model computation.\n\n \"\"\"\n hidden = nn.functional.relu(self.linear1(data))\n result = self.linear2(hidden)\n return result.squeeze()\n"
] |
[
[
"torch.nn.Linear"
]
] |
Morgan-Gan/Slowfast-TSM
|
[
"ca6783df0cc9577abb1735b2cab52653d569beff"
] |
[
"slowfast/datasets/utils.py"
] |
[
"#!/usr/bin/env python3\n\nimport logging\nimport numpy as np\nimport os\nimport random\nimport time\nfrom collections import defaultdict\nimport cv2\nimport torch\nfrom fvcore.common.file_io import PathManager\n\nfrom . import transform as transform\n\nlogger = logging.getLogger(__name__)\n\n\ndef retry_load_images(image_paths, retry=10, backend=\"pytorch\"):\n \"\"\"\n This function is to load images with support of retrying for failed load.\n\n Args:\n image_paths (list): paths of images needed to be loaded.\n retry (int, optional): maximum time of loading retrying. Defaults to 10.\n backend (str): `pytorch` or `cv2`.\n\n Returns:\n imgs (list): list of loaded images.\n \"\"\"\n for i in range(retry):\n imgs = []\n for image_path in image_paths:\n with PathManager.open(image_path, \"rb\") as f:\n img_str = np.frombuffer(f.read(), np.uint8)\n img = cv2.imdecode(img_str, flags=cv2.IMREAD_COLOR)\n imgs.append(img)\n\n if all(img is not None for img in imgs):\n if backend == \"pytorch\":\n imgs = torch.as_tensor(np.stack(imgs))\n return imgs\n else:\n logger.warn(\"Reading failed. Will retry.\")\n time.sleep(1.0)\n if i == retry - 1:\n raise Exception(\"Failed to load images {}\".format(image_paths))\n\n\ndef get_sequence(center_idx, half_len, sample_rate, num_frames):\n \"\"\"\n Sample frames among the corresponding clip.\n\n Args:\n center_idx (int): center frame idx for current clip\n half_len (int): half of the clip length\n sample_rate (int): sampling rate for sampling frames inside of the clip\n num_frames (int): number of expected sampled frames\n\n Returns:\n seq (list): list of indexes of sampled frames in this clip.\n \"\"\"\n seq = list(range(center_idx - half_len, center_idx + half_len, sample_rate))\n\n for seq_idx in range(len(seq)):\n if seq[seq_idx] < 0:\n seq[seq_idx] = 0\n elif seq[seq_idx] >= num_frames:\n seq[seq_idx] = num_frames - 1\n return seq\n\n\ndef pack_pathway_output(cfg, frames):\n \"\"\"\n Prepare output as a list of tensors. Each tensor corresponding to a\n unique pathway.\n Args:\n frames (tensor): frames of images sampled from the video. The\n dimension is `channel` x `num frames` x `height` x `width`.\n Returns:\n frame_list (list): list of tensors with the dimension of\n `channel` x `num frames` x `height` x `width`.\n \"\"\"\n if cfg.DATA.REVERSE_INPUT_CHANNEL: # frames:[3,8,224,224],RGB->BGR\n frames = frames[[2, 1, 0], :, :, :]\n if cfg.MODEL.ARCH in cfg.MODEL.SINGLE_PATHWAY_ARCH:\n frame_list = [frames]\n elif cfg.MODEL.ARCH in cfg.MODEL.MULTI_PATHWAY_ARCH:\n fast_pathway = frames\n # Perform temporal sampling from the fast pathway.\n slow_pathway = torch.index_select(\n frames,\n 1,\n torch.linspace(\n 0, frames.shape[1] - 1, frames.shape[1] // cfg.SLOWFAST.ALPHA\n ).long(),\n )\n frame_list = [slow_pathway, fast_pathway]\n else:\n raise NotImplementedError(\n \"Model arch {} is not in {}\".format(\n cfg.MODEL.ARCH,\n cfg.MODEL.SINGLE_PATHWAY_ARCH + cfg.MODEL.MULTI_PATHWAY_ARCH,\n )\n )\n return frame_list\n\n\ndef spatial_sampling(\n frames,\n spatial_idx=-1,\n min_scale=256,\n max_scale=320,\n crop_size=224,\n random_horizontal_flip=True,\n inverse_uniform_sampling=False,\n):\n \"\"\"\n Perform spatial sampling on the given video frames. If spatial_idx is\n -1, perform random scale, random crop, and random flip on the given\n frames. If spatial_idx is 0, 1, or 2, perform spatial uniform sampling\n with the given spatial_idx.\n Args:\n frames (tensor): frames of images sampled from the video. The\n dimension is `num frames` x `height` x `width` x `channel`.\n spatial_idx (int): if -1, perform random spatial sampling. If 0, 1,\n or 2, perform left, center, right crop if width is larger than\n height, and perform top, center, buttom crop if height is larger\n than width.\n min_scale (int): the minimal size of scaling.\n max_scale (int): the maximal size of scaling.\n crop_size (int): the size of height and width used to crop the\n frames.\n inverse_uniform_sampling (bool): if True, sample uniformly in\n [1 / max_scale, 1 / min_scale] and take a reciprocal to get the\n scale. If False, take a uniform sample from [min_scale,\n max_scale].\n Returns:\n frames (tensor): spatially sampled frames.\n \"\"\"\n assert spatial_idx in [-1, 0, 1, 2]\n if spatial_idx == -1:\n frames, _ = transform.random_short_side_scale_jitter(\n images=frames,\n min_size=min_scale,\n max_size=max_scale,\n inverse_uniform_sampling=inverse_uniform_sampling,\n )\n frames, _ = transform.random_crop(frames, crop_size)\n if random_horizontal_flip:\n frames, _ = transform.horizontal_flip(0.5, frames)\n else:\n # The testing is deterministic and no jitter should be performed.\n # min_scale, max_scale, and crop_size are expect to be the same.\n assert len({min_scale, max_scale, crop_size}) == 1\n frames, _ = transform.random_short_side_scale_jitter(\n frames, min_scale, max_scale\n )\n frames, _ = transform.uniform_crop(frames, crop_size, spatial_idx)\n return frames\n\n\ndef as_binary_vector(labels, num_classes):\n \"\"\"\n Construct binary label vector given a list of label indices.\n Args:\n labels (list): The input label list.\n num_classes (int): Number of classes of the label vector.\n Returns:\n labels (numpy array): the resulting binary vector.\n \"\"\"\n label_arr = np.zeros((num_classes,))\n\n for lbl in set(labels):\n label_arr[lbl] = 1.0\n return label_arr\n\n\ndef aggregate_labels(label_list):\n \"\"\"\n Join a list of label list.\n Args:\n labels (list): The input label list.\n Returns:\n labels (list): The joint list of all lists in input.\n \"\"\"\n all_labels = []\n for labels in label_list:\n for l in labels:\n all_labels.append(l)\n return list(set(all_labels))\n\n\ndef convert_to_video_level_labels(labels):\n \"\"\"\n Aggregate annotations from all frames of a video to form video-level labels.\n Args:\n labels (list): The input label list.\n Returns:\n labels (list): Same as input, but with each label replaced by\n a video-level one.\n \"\"\"\n for video_id in range(len(labels)):\n video_level_labels = aggregate_labels(labels[video_id])\n for i in range(len(labels[video_id])):\n labels[video_id][i] = video_level_labels\n return labels\n\n\ndef load_image_lists(frame_list_file, prefix=\"\", return_list=False):\n \"\"\"\n Load image paths and labels from a \"frame list\".\n Each line of the frame list contains:\n `original_vido_id video_id frame_id path labels`\n Args:\n frame_list_file (string): path to the frame list.\n prefix (str): the prefix for the path.\n return_list (bool): if True, return a list. If False, return a dict.\n Returns:\n image_paths (list or dict): list of list containing path to each frame.\n If return_list is False, then return in a dict form.\n labels (list or dict): list of list containing label of each frame.\n If return_list is False, then return in a dict form.\n \"\"\"\n image_paths = defaultdict(list)\n labels = defaultdict(list)\n with PathManager.open(frame_list_file, \"r\") as f:\n assert f.readline().startswith(\"original_vido_id\")\n for line in f:\n row = line.split()\n # original_vido_id video_id frame_id path labels\n assert len(row) == 5\n video_name = row[0]\n if prefix == \"\":\n path = row[3]\n else:\n path = os.path.join(prefix, row[3])\n image_paths[video_name].append(path)\n frame_labels = row[-1].replace('\"', \"\")\n if frame_labels != \"\":\n labels[video_name].append(\n [int(x) for x in frame_labels.split(\",\")]\n )\n else:\n labels[video_name].append([])\n\n if return_list:\n keys = image_paths.keys()\n image_paths = [image_paths[key] for key in keys]\n labels = [labels[key] for key in keys]\n return image_paths, labels\n return dict(image_paths), dict(labels)\n\n\ndef tensor_normalize(tensor, mean, std):\n \"\"\"\n Normalize a given tensor by subtracting the mean and dividing the std.\n Args:\n tensor (tensor): tensor to normalize.\n mean (tensor or list): mean value to subtract.\n std (tensor or list): std to divide.\n \"\"\"\n if tensor.dtype == torch.uint8:\n tensor = tensor.float()\n tensor = tensor / 255.0\n if type(mean) == list:\n mean = torch.tensor(mean)\n if type(std) == list:\n std = torch.tensor(std)\n tensor = tensor - mean\n tensor = tensor / std\n return tensor\n\n\ndef get_random_sampling_rate(long_cycle_sampling_rate, sampling_rate):\n \"\"\"\n When multigrid training uses a fewer number of frames, we randomly\n increase the sampling rate so that some clips cover the original span.\n \"\"\"\n if long_cycle_sampling_rate > 0:\n assert long_cycle_sampling_rate >= sampling_rate\n return random.randint(sampling_rate, long_cycle_sampling_rate)\n else:\n return sampling_rate\n\n\ndef revert_tensor_normalize(tensor, mean, std):\n \"\"\"\n Revert normalization for a given tensor by multiplying by the std and adding the mean.\n Args:\n tensor (tensor): tensor to revert normalization.\n mean (tensor or list): mean value to add.\n std (tensor or list): std to multiply.\n \"\"\"\n if type(mean) == list:\n mean = torch.tensor(mean)\n if type(std) == list:\n std = torch.tensor(std)\n tensor = tensor * std\n tensor = tensor + mean\n return tensor\n"
] |
[
[
"torch.linspace",
"numpy.zeros",
"numpy.stack",
"torch.tensor"
]
] |
DuaneNielsen/atari-representation-learning
|
[
"fe34f389768416deaa6a6ff0bdebba3d05762a55"
] |
[
"atariari/methods/pretrained_agents.py"
] |
[
"from a2c_ppo_acktr import utils\nfrom a2c_ppo_acktr.envs import make_vec_envs as mve\nfrom collections import deque\nfrom itertools import chain\nimport numpy as np\nimport torch\nimport wandb\nimport time\nimport os\n\nfrom atariari.benchmark.envs import make_vec_envs\nfrom atariari.benchmark.episodes import checkpointed_steps_full_sorted\nfrom .utils import get_argparser\nfrom atariari.benchmark.utils import download_run\n\n# elif collect_mode == \"pretrained_representations\":\n# # \"episodes\" are vectors from output of last layer of PPO agent\n# episodes, episode_labels = get_pretrained_rl_representations(args, steps)\n\ndef get_pretrained_rl_representations(args, steps):\n checkpoint = checkpointed_steps_full_sorted[args.checkpoint_index]\n episodes, episode_labels, mean_reward = get_ppo_representations(args, steps, checkpoint)\n wandb.log({\"reward\": mean_reward, \"checkpoint\": checkpoint})\n return episodes, episode_labels\n\n\ndef evaluate(actor_critic, env_name, seed, num_processes, eval_log_dir,\n device, num_evals):\n eval_envs = mve(env_name, seed + num_processes, num_processes,\n None, eval_log_dir, device, True, num_frame_stack=1)\n\n vec_norm = utils.get_vec_normalize(eval_envs)\n\n eval_episode_rewards = []\n\n obs = eval_envs.reset()\n eval_recurrent_hidden_states = torch.zeros(\n num_processes, actor_critic.recurrent_hidden_state_size, device=device)\n eval_masks = torch.zeros(num_processes, 1, device=device)\n\n while len(eval_episode_rewards) < num_evals:\n with torch.no_grad():\n _, action, _, eval_recurrent_hidden_states, _, _ = actor_critic.act(\n obs,\n eval_recurrent_hidden_states,\n eval_masks,\n deterministic=True)\n\n # Obser reward and next obs\n obs, _, done, infos = eval_envs.step(action)\n\n eval_masks = torch.tensor(\n [[0.0] if done_ else [1.0] for done_ in done],\n dtype=torch.float32,\n device=device)\n\n for info in infos:\n if 'episode' in info.keys():\n eval_episode_rewards.append(info['episode']['r'])\n\n eval_envs.close()\n\n print(\" Evaluation using {} episodes: mean reward {:.5f}\\n\".format(\n len(eval_episode_rewards), np.mean(eval_episode_rewards)))\n return np.mean(eval_episode_rewards)\n\n\ndef get_ppo_representations(args, steps, checkpoint_step):\n # Gives PPO represnetations over data collected by a random agent\n filepath = download_run(args, checkpoint_step)\n while not os.path.exists(filepath):\n time.sleep(5)\n\n envs = make_vec_envs(args, args.num_processes)\n\n actor_critic, ob_rms = \\\n torch.load(filepath, map_location=lambda storage, loc: storage)\n mean_reward = evaluate(actor_critic,\n env_name=args.env_name,\n seed=args.seed,\n num_processes=args.num_processes,\n eval_log_dir=\"./tmp\", device=\"cpu\", num_evals=args.num_rew_evals)\n print(mean_reward)\n episode_labels = [[[]] for _ in range(args.num_processes)]\n episode_rewards = deque(maxlen=10)\n episode_features = [[[]] for _ in range(args.num_processes)]\n\n\n masks = torch.zeros(1, 1)\n obs = envs.reset()\n for step in range(steps // args.num_processes):\n # Take action using a random policy\n if args.probe_collect_mode == 'random_agent':\n action = torch.tensor(\n np.array([np.random.randint(1, envs.action_space.n) for _ in range(args.num_processes)])) \\\n .unsqueeze(dim=1)\n else:\n with torch.no_grad():\n _, action, _, _, actor_features, _ = actor_critic.act(obs, None, masks, deterministic=False)\n action = torch.tensor([envs.action_space.sample() if np.random.uniform(0, 1) < 0.2 else action[i]\n for i in range(args.num_processes)]).unsqueeze(dim=1)\n\n obs, reward, done, infos = envs.step(action)\n for i, info in enumerate(infos):\n if 'episode' in info.keys():\n episode_rewards.append(info['episode']['r'])\n\n if done[i] != 1:\n episode_features[i][-1].append(actor_features[i].clone())\n if \"labels\" in info.keys():\n episode_labels[i][-1].append(info[\"labels\"])\n else:\n episode_features[i].append([actor_features[i].clone()])\n if \"labels\" in info.keys():\n episode_labels[i].append([info[\"labels\"]])\n\n # Convert to 2d list from 3d list\n episode_labels = list(chain.from_iterable(episode_labels))\n episode_features = list(chain.from_iterable(episode_features))\n return episode_features, episode_labels, mean_reward\n\n\nif __name__ == \"__main__\":\n parser = get_argparser()\n args = parser.parse_args()\n args.env_name = 'SeaquestNoFrameskip-v4'\n args.probe_steps = 2000\n episode_features, episode_labels, mean_reward = get_ppo_representations(args, 10753536)\n"
] |
[
[
"torch.load",
"torch.zeros",
"torch.tensor",
"torch.no_grad",
"numpy.mean",
"numpy.random.uniform",
"numpy.random.randint"
]
] |
khwilson/EconML
|
[
"80264390106a8c57e2286177a2c4f8a47b51a32e",
"80264390106a8c57e2286177a2c4f8a47b51a32e"
] |
[
"monte_carlo_tests/monte_carlo_statsmodels.py",
"econml/deepiv.py"
] |
[
"import numpy as np\r\nfrom econml.dml import LinearDMLCateEstimator\r\nfrom sklearn.linear_model import LinearRegression, MultiTaskLassoCV, MultiTaskLasso, Lasso\r\nfrom econml.inference import StatsModelsInference\r\nfrom econml.tests.test_statsmodels import _summarize\r\nfrom econml.sklearn_extensions.linear_model import WeightedLasso, WeightedMultiTaskLassoCV, WeightedMultiTaskLasso\r\nfrom sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor\r\nfrom statsmodels.tools.tools import add_constant\r\nfrom econml.utilities import cross_product\r\nimport matplotlib.pyplot as plt\r\nimport os\r\nimport time\r\nimport argparse\r\nimport warnings\r\nimport joblib\r\nfrom sklearn.model_selection import GridSearchCV\r\nfrom statsmodels.tools.tools import add_constant\r\nfrom econml.utilities import cross_product\r\nfrom sklearn.multioutput import MultiOutputRegressor\r\n\r\n\r\nclass GridSearchCVList:\r\n\r\n def __init__(self, estimator_list, param_grid_list, scoring=None,\r\n n_jobs=None, iid='warn', refit=True, cv='warn', verbose=0, pre_dispatch='2*n_jobs',\r\n error_score='raise-deprecating', return_train_score=False):\r\n self._gcv_list = [GridSearchCV(estimator, param_grid, scoring=scoring,\r\n n_jobs=n_jobs, iid=iid, refit=refit, cv=cv, verbose=verbose,\r\n pre_dispatch=pre_dispatch, error_score=error_score,\r\n return_train_score=return_train_score)\r\n for estimator, param_grid in zip(estimator_list, param_grid_list)]\r\n return\r\n\r\n def fit(self, X, y, **fit_params):\r\n self.best_ind_ = np.argmax([gcv.fit(X, y, **fit_params).best_score_ for gcv in self._gcv_list])\r\n self.best_estimator_ = self._gcv_list[self.best_ind_].best_estimator_\r\n self.best_score_ = self._gcv_list[self.best_ind_].best_score_\r\n self.best_params_ = self._gcv_list[self.best_ind_].best_params_\r\n return self\r\n\r\n def predict(self, X):\r\n return self.best_estimator_.predict(X)\r\n\r\n\r\ndef _coverage_profile(est, X_test, alpha, true_coef, true_effect):\r\n cov = {}\r\n d_t = true_coef.shape[1] // (X_test.shape[1] + 1)\r\n d_y = true_coef.shape[0]\r\n coef_interval = est.coef__interval(alpha=alpha)\r\n intercept_interval = est.intercept__interval(alpha=alpha)\r\n true_coef = true_coef.flatten()\r\n est_coef = np.concatenate((est.intercept_[..., np.newaxis], est.coef_), axis=-1).flatten()\r\n est_coef_lb = np.concatenate((intercept_interval[0][..., np.newaxis], coef_interval[0]), axis=-1).flatten()\r\n est_coef_ub = np.concatenate((intercept_interval[1][..., np.newaxis], coef_interval[1]), axis=-1).flatten()\r\n cov['coef'] = est_coef\r\n cov['coef_lower'] = est_coef_lb\r\n cov['coef_upper'] = est_coef_ub\r\n cov['true_coef'] = true_coef\r\n cov['coef_stderr'] = est.model_final.coef_stderr_.flatten()\r\n cov['coef_sqerror'] = (est_coef - true_coef)**2\r\n cov['coef_cov'] = ((true_coef >= est_coef_lb) & (true_coef <= est_coef_ub))\r\n cov['coef_length'] = est_coef_ub - est_coef_lb\r\n effect_interval = est.effect_interval(X_test, T0=np.zeros(\r\n (X_test.shape[0], d_t)), T1=np.ones((X_test.shape[0], d_t)), alpha=alpha)\r\n true_eff = true_effect(X_test, np.ones((X_test.shape[0], d_t))).reshape(effect_interval[0].shape)\r\n est_effect = est.effect(X_test, T0=np.zeros((X_test.shape[0], d_t)), T1=np.ones((X_test.shape[0], d_t)))\r\n cov['x_test'] = np.repeat(X_test, d_y, axis=0)\r\n cov['effect'] = est_effect.flatten()\r\n cov['effect_lower'] = effect_interval[0].flatten()\r\n cov['effect_upper'] = effect_interval[1].flatten()\r\n cov['true_effect'] = true_eff.flatten()\r\n cov['effect_sqerror'] = ((est_effect - true_eff)**2).flatten()\r\n cov['effect_stderr'] = est.model_final.prediction_stderr(\r\n cross_product(add_constant(X_test), np.ones((X_test.shape[0], d_t)))).flatten()\r\n cov['effect_cov'] = ((true_eff >= effect_interval[0]) & (true_eff <= effect_interval[1])).flatten()\r\n cov['effect_length'] = (effect_interval[1] - effect_interval[0]).flatten()\r\n return cov\r\n\r\n\r\ndef _append_coverage(key, coverage, est, X_test, alpha, true_coef, true_effect):\r\n cov = _coverage_profile(est, X_test, alpha, true_coef, true_effect)\r\n if key not in coverage:\r\n coverage[key] = {}\r\n for cov_key, value in cov.items():\r\n coverage[key][cov_key] = [value]\r\n else:\r\n for cov_key, value in cov.items():\r\n coverage[key][cov_key].append(value)\r\n\r\n\r\ndef _agg_coverage(coverage, qs=np.array([.005, .025, .1, .9, .975, .995])):\r\n mean_coverage_est = {}\r\n std_coverage_est = {}\r\n q_coverage_est = {}\r\n for key, cov_dict in coverage.items():\r\n mean_coverage_est[key] = {}\r\n std_coverage_est[key] = {}\r\n q_coverage_est[key] = {}\r\n for cov_key, cov_list in cov_dict.items():\r\n mean_coverage_est[key][cov_key] = np.mean(cov_list, axis=0)\r\n std_coverage_est[key][cov_key] = np.std(cov_list, axis=0)\r\n q_coverage_est[key][cov_key] = np.percentile(cov_list, qs * 100, axis=0)\r\n return mean_coverage_est, std_coverage_est, q_coverage_est\r\n\r\n\r\ndef plot_coverage(coverage, cov_key, n, n_exp, hetero_coef_list, d_list, d_x_list, p_list, t_list,\r\n cov_type_list, alpha_list, prefix=\"\", folder=\"\", print_matrix=False):\r\n if not os.path.exists('figures'):\r\n os.makedirs('figures')\r\n if not os.path.exists(os.path.join(\"figures\", folder)):\r\n os.makedirs(os.path.join(\"figures\", folder))\r\n joblib.dump(coverage, os.path.join(\"figures\", folder, \"{}data.jbl\".format(prefix)))\r\n for hetero_coef in hetero_coef_list:\r\n for d in d_list:\r\n for d_x in d_x_list:\r\n if d_x > d:\r\n continue\r\n for p in p_list:\r\n for d_t in t_list:\r\n for cov_type in cov_type_list:\r\n for alpha in alpha_list:\r\n key = \"n_{}_n_exp_{}_hetero_{}_d_{}_d_x_{}_p_{}_d_t_{}_cov_type_{}_alpha_{}\".format(\r\n n, n_exp, hetero_coef, d, d_x, p, d_t, cov_type, alpha)\r\n if print_matrix:\r\n print(coverage[key][cov_key])\r\n plt.figure()\r\n plt.title(\"{}{}_{}\".format(prefix, key, cov_key))\r\n plt.hist(coverage[key][cov_key].flatten())\r\n plt.savefig(os.path.join(\"figures\", folder, \"{}{}_{}.png\".format(prefix,\r\n key,\r\n cov_key)))\r\n plt.close()\r\n\r\n\r\ndef print_aggregate(mean_coverage, std_coverage, q_coverage, file_gen=lambda: None):\r\n for key, cov in mean_coverage.items():\r\n print(key, file=file_gen())\r\n with np.printoptions(formatter={'float': '{:.2f}'.format}, suppress=True):\r\n print(\"Mean Coef (True, RMSE) \\t (Coverage, Mean Length) \\t Mean StdErr (True, RMSE)\\t \"\r\n \"[Mean Lower (std), Mean Upper (std)]\\t (True Quantiles)\\r\\n{}\".format(\r\n \"\\r\\n\".join([\"{:.2f} ({:.2f}, {:.2f}) \\t ({:.2f}, {:.2f}) \\t {:.2f} ({:.2f}, {:.2f}) \"\r\n \" \\t [{:.2f} ({:.2f}), {:.2f} ({:.2f})] \\t {}\".format(est,\r\n true,\r\n np.sqrt(\r\n sqerr),\r\n coverage,\r\n length,\r\n stderr,\r\n true_stderr,\r\n np.sqrt(\r\n std_stderr**2 +\r\n (stderr -\r\n true_stderr)**2),\r\n lower,\r\n std_lower,\r\n upper,\r\n std_upper,\r\n true_qs)\r\n for (est, true, sqerr, coverage, length, stderr, std_stderr,\r\n true_stderr, lower, std_lower, upper, std_upper, true_qs)\r\n in zip(cov['coef'],\r\n cov['true_coef'],\r\n cov['coef_sqerror'],\r\n cov['coef_cov'],\r\n cov['coef_length'],\r\n cov['coef_stderr'],\r\n std_coverage[key]['coef_stderr'],\r\n std_coverage[key]['coef'],\r\n cov['coef_lower'],\r\n std_coverage[key]['coef_lower'],\r\n cov['coef_upper'],\r\n std_coverage[key]['coef_upper'],\r\n q_coverage[key]['coef'].T)])), file=file_gen())\r\n print(\"Effect SqError: {}\".format(np.mean(cov['effect_sqerror'])), file=file_gen())\r\n\r\n print(\"Point\\t Mean Coef (True, RMSE) \\t (Coverage, Mean Length)\\t Mean StdErr (True, RMSE)\\t \"\r\n \" [Mean Lower (std), Mean Upper (std)]\\t (True Quantiles)\\r\\n{}\".format(\r\n \"\\r\\n\".join([\"{}\\t {:.2f} ({:.2f}, {:.2f}) \\t ({:.2f}, {:.2f}) \\t {:.2f} ({:.2f}, {:.2f}) \\t \"\r\n \"[{:.2f} ({:.2f}), {:.2f} ({:.2f})] \\t \"\r\n \"{}\".format(','.join(x.astype(int).astype(str)),\r\n est,\r\n true,\r\n np.sqrt(\r\n sqerr),\r\n coverage,\r\n length,\r\n stderr,\r\n true_stderr,\r\n np.sqrt(\r\n std_stderr**2 + (stderr - true_stderr)**2),\r\n lower,\r\n std_lower,\r\n upper,\r\n std_upper,\r\n true_qs)\r\n for (x, est, true, sqerr, coverage, length, stderr, std_stderr,\r\n true_stderr, lower, std_lower, upper, std_upper, true_qs)\r\n in zip(cov['x_test'],\r\n cov['effect'],\r\n cov['true_effect'],\r\n cov['effect_sqerror'],\r\n cov['effect_cov'],\r\n cov['effect_length'],\r\n cov['effect_stderr'],\r\n std_coverage[key]['effect_stderr'],\r\n std_coverage[key]['effect'],\r\n cov['effect_lower'],\r\n std_coverage[key]['effect_lower'],\r\n cov['effect_upper'],\r\n std_coverage[key]['effect_upper'],\r\n q_coverage[key]['effect'].T)])), file=file_gen())\r\n print(\"Effect SqError: {}\".format(np.mean(cov['effect_sqerror'])), file=file_gen())\r\n\r\n\r\ndef run_all_mc(first_stage, folder, n_list, n_exp, hetero_coef_list, d_list,\r\n d_x_list, p_list, t_list, cov_type_list, alpha_list):\r\n\r\n if not os.path.exists(\"results\"):\r\n os.makedirs('results')\r\n results_filename = os.path.join(\"results\", \"{}.txt\".format(folder))\r\n\r\n np.random.seed(123)\r\n coverage_est = {}\r\n coverage_lr = {}\r\n n_tests = 0\r\n n_failed_coef = 0\r\n n_failed_effect = 0\r\n cov_tol = .04\r\n for n in n_list:\r\n for hetero_coef in hetero_coef_list:\r\n for d in d_list:\r\n for d_x in d_x_list:\r\n if d_x > d:\r\n continue\r\n for p in p_list:\r\n for d_t in t_list:\r\n X_test = np.unique(np.random.binomial(1, .5, size=(20, d_x)), axis=0)\r\n t0 = time.time()\r\n for it in range(n_exp):\r\n X = np.random.binomial(1, .8, size=(n, d))\r\n T = np.hstack([np.random.binomial(1, .5 * X[:, 0] + .25,\r\n size=(n,)).reshape(-1, 1) for _ in range(d_t)])\r\n true_coef = np.hstack([np.hstack([it + np.arange(p).reshape(-1, 1),\r\n it + np.ones((p, 1)), np.zeros((p, d_x - 1))])\r\n for it in range(d_t)])\r\n\r\n def true_effect(x, t):\r\n return cross_product(\r\n np.hstack([np.ones((x.shape[0], 1)), x[:, :d_x]]), t) @ true_coef.T\r\n y = true_effect(X, T) + X[:, [0] * p] +\\\r\n (hetero_coef * X[:, [0]] + 1) * np.random.normal(0, 1, size=(n, p))\r\n\r\n XT = np.hstack([X, T])\r\n X1, X2, y1, y2, X_final_first, X_final_sec, y_sum_first, y_sum_sec,\\\r\n n_sum_first, n_sum_sec, var_first, var_sec = _summarize(XT, y)\r\n X = np.vstack([X1, X2])\r\n y = np.concatenate((y1, y2))\r\n X_final = np.vstack([X_final_first, X_final_sec])\r\n y_sum = np.concatenate((y_sum_first, y_sum_sec))\r\n n_sum = np.concatenate((n_sum_first, n_sum_sec))\r\n var_sum = np.concatenate((var_first, var_sec))\r\n first_half_sum = len(y_sum_first)\r\n first_half = len(y1)\r\n for cov_type in cov_type_list:\r\n class SplitterSum:\r\n def __init__(self):\r\n return\r\n\r\n def split(self, X, T):\r\n return [(np.arange(0, first_half_sum),\r\n np.arange(first_half_sum, X.shape[0])),\r\n (np.arange(first_half_sum, X.shape[0]),\r\n np.arange(0, first_half_sum))]\r\n\r\n est = LinearDMLCateEstimator(model_y=first_stage(),\r\n model_t=first_stage(),\r\n n_splits=SplitterSum(),\r\n linear_first_stages=False,\r\n discrete_treatment=False)\r\n est.fit(y_sum,\r\n X_final[:, -d_t:],\r\n X_final[:, :d_x],\r\n X_final[:, d_x:-d_t],\r\n sample_weight=n_sum,\r\n sample_var=var_sum,\r\n inference=StatsModelsInference(cov_type=cov_type))\r\n\r\n class Splitter:\r\n def __init__(self):\r\n return\r\n\r\n def split(self, X, T):\r\n return [(np.arange(0, first_half), np.arange(first_half, X.shape[0])),\r\n (np.arange(first_half, X.shape[0]), np.arange(0, first_half))]\r\n\r\n lr = LinearDMLCateEstimator(model_y=first_stage(),\r\n model_t=first_stage(),\r\n n_splits=Splitter(),\r\n linear_first_stages=False,\r\n discrete_treatment=False)\r\n lr.fit(y, X[:, -d_t:], X[:, :d_x], X[:, d_x:-d_t],\r\n inference=StatsModelsInference(cov_type=cov_type))\r\n for alpha in alpha_list:\r\n key = (\"n_{}_n_exp_{}_hetero_{}_d_{}_d_x_\"\r\n \"{}_p_{}_d_t_{}_cov_type_{}_alpha_{}\").format(\r\n n, n_exp, hetero_coef, d, d_x, p, d_t, cov_type, alpha)\r\n _append_coverage(key, coverage_est, est, X_test,\r\n alpha, true_coef, true_effect)\r\n _append_coverage(key, coverage_lr, lr, X_test,\r\n alpha, true_coef, true_effect)\r\n if it == n_exp - 1:\r\n n_tests += 1\r\n mean_coef_cov = np.mean(coverage_est[key]['coef_cov'])\r\n mean_eff_cov = np.mean(coverage_est[key]['effect_cov'])\r\n mean_coef_cov_lr = np.mean(coverage_lr[key]['coef_cov'])\r\n mean_eff_cov_lr = np.mean(coverage_lr[key]['effect_cov'])\r\n [print(\"{}. Time: {:.2f}, Mean Coef Cov: ({:.4f}, {:.4f}), \"\r\n \"Mean Effect Cov: ({:.4f}, {:.4f})\".format(key,\r\n time.time() - t0,\r\n mean_coef_cov,\r\n mean_coef_cov_lr,\r\n mean_eff_cov,\r\n mean_eff_cov_lr),\r\n file=f)\r\n for f in [None, open(results_filename, \"a\")]]\r\n coef_cov_dev = mean_coef_cov - (1 - alpha)\r\n if np.abs(coef_cov_dev) >= cov_tol:\r\n n_failed_coef += 1\r\n [print(\"BAD coef coverage on \"\r\n \"average: deviation = {:.4f}\".format(coef_cov_dev), file=f)\r\n for f in [None, open(results_filename, \"a\")]]\r\n eff_cov_dev = mean_eff_cov - (1 - alpha)\r\n if np.abs(eff_cov_dev) >= cov_tol:\r\n n_failed_effect += 1\r\n [print(\"BAD effect coverage on \"\r\n \"average: deviation = {:.4f}\".format(eff_cov_dev), file=f)\r\n for f in [None, open(results_filename, \"a\")]]\r\n\r\n [print(\"Finished {} Monte Carlo Tests. Failed Coef Coverage Tests: {}/{}.\"\r\n \"Failed Effect Coverage Tests: {}/{}. (Coverage Tolerance={})\".format(n_tests,\r\n n_failed_coef,\r\n n_tests,\r\n n_failed_effect,\r\n n_tests,\r\n cov_tol),\r\n file=f) for f in [None, open(results_filename, \"a\")]]\r\n\r\n agg_coverage_est, std_coverage_est, q_coverage_est = _agg_coverage(coverage_est)\r\n agg_coverage_lr, std_coverage_lr, q_coverage_lr = _agg_coverage(coverage_lr)\r\n\r\n [print(\"\\nResults for: {}\\n--------------------------\\n\".format(folder), file=f)\r\n for f in [None, open(results_filename, \"a\")]]\r\n\r\n plot_coverage(agg_coverage_est, 'coef_cov', n, n_exp, hetero_coef_list, d_list, d_x_list,\r\n p_list, t_list, cov_type_list, alpha_list, prefix=\"sum_\", folder=folder)\r\n plot_coverage(agg_coverage_lr, 'coef_cov', n, n_exp, hetero_coef_list, d_list, d_x_list,\r\n p_list, t_list, cov_type_list, alpha_list, prefix=\"orig_\", folder=folder)\r\n plot_coverage(agg_coverage_est, 'effect_cov', n, n_exp, hetero_coef_list, d_list, d_x_list,\r\n p_list, t_list, cov_type_list, alpha_list, prefix=\"sum_\", folder=folder)\r\n plot_coverage(agg_coverage_lr, 'effect_cov', n, n_exp, hetero_coef_list, d_list, d_x_list,\r\n p_list, t_list, cov_type_list, alpha_list, prefix=\"orig_\", folder=folder)\r\n\r\n [print(\"Summarized Data\\n----------------\", file=f) for f in [None, open(results_filename, \"a\")]]\r\n print_aggregate(agg_coverage_est, std_coverage_est, q_coverage_est)\r\n print_aggregate(agg_coverage_est, std_coverage_est, q_coverage_est, lambda: open(results_filename, \"a\"))\r\n [print(\"\\nUn-Summarized Data\\n-----------------\", file=f) for f in [None, open(results_filename, \"a\")]]\r\n print_aggregate(agg_coverage_lr, std_coverage_lr, q_coverage_lr)\r\n print_aggregate(agg_coverage_lr, std_coverage_lr, q_coverage_lr, lambda: open(results_filename, \"a\"))\r\n\r\n\r\ndef monte_carlo(first_stage=lambda: LinearRegression(), folder='lr'):\r\n n_exp = 1000\r\n n_list = [500]\r\n hetero_coef_list = [0, 1]\r\n d_list = [1, 10]\r\n d_x_list = [1, 5]\r\n p_list = [1, 5]\r\n t_list = [1, 2]\r\n cov_type_list = ['HC1']\r\n alpha_list = [.01, .05, .2]\r\n run_all_mc(first_stage, folder, n_list, n_exp, hetero_coef_list,\r\n d_list, d_x_list, p_list, t_list, cov_type_list, alpha_list)\r\n\r\n\r\ndef monte_carlo_lasso(first_stage=lambda: WeightedLasso(alpha = 0.01,\r\n fit_intercept = True,\r\n tol = 1e-6, random_state = 123), folder='lasso'):\r\n n_exp = 1000\r\n n_list = [500]\r\n hetero_coef_list = [1]\r\n d_list = [20]\r\n d_x_list = [5]\r\n p_list = [1, 2]\r\n t_list = [1, 3]\r\n cov_type_list = ['HC1']\r\n alpha_list = [.01, .05, .2]\r\n run_all_mc(first_stage, folder, n_list, n_exp, hetero_coef_list,\r\n d_list, d_x_list, p_list, t_list, cov_type_list, alpha_list)\r\n\r\n\r\ndef monte_carlo_rf(first_stage=lambda: RandomForestRegressor(n_estimators = 100,\r\n max_depth = 3, min_samples_leaf = 10), folder='rf'):\r\n n_exp = 1000\r\n n_list = [500, 5000]\r\n hetero_coef_list = [1]\r\n d_list = [20]\r\n d_x_list = [5]\r\n p_list = [1]\r\n t_list = [2]\r\n cov_type_list = ['HC1']\r\n alpha_list = [.01, .05, .2]\r\n run_all_mc(first_stage, folder, n_list, n_exp, hetero_coef_list,\r\n d_list, d_x_list, p_list, t_list, cov_type_list, alpha_list)\r\n\r\n\r\ndef monte_carlo_gcv(folder='gcv'):\r\n def first_stage():\r\n return GridSearchCVList([LinearRegression(),\r\n WeightedMultiTaskLasso(alpha=0.05, fit_intercept=True,\r\n tol=1e-6, random_state=123),\r\n RandomForestRegressor(n_estimators=100, max_depth=3,\r\n min_samples_leaf=10, random_state=123),\r\n MultiOutputRegressor(GradientBoostingRegressor(n_estimators=20,\r\n max_depth=3,\r\n min_samples_leaf=10, random_state=123))],\r\n param_grid_list=[{},\r\n {},\r\n {},\r\n {}],\r\n cv=3,\r\n iid=True)\r\n n_exp = 1000\r\n n_list = [1000, 5000]\r\n hetero_coef_list = [1]\r\n d_list = [20]\r\n d_x_list = [5]\r\n p_list = [1]\r\n t_list = [2]\r\n cov_type_list = ['HC1']\r\n alpha_list = [.01, .05, .2]\r\n run_all_mc(first_stage, folder, n_list, n_exp, hetero_coef_list,\r\n d_list, d_x_list, p_list, t_list, cov_type_list, alpha_list)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n parser = argparse.ArgumentParser(description='Description of your program')\r\n parser.add_argument('-e', '--exp', help='What experiment (default=all)', required=False, default='all')\r\n args = vars(parser.parse_args())\r\n if args['exp'] in ['lr', 'all']:\r\n monte_carlo()\r\n if args['exp'] in ['lasso', 'all']:\r\n monte_carlo_lasso()\r\n if args['exp'] in ['rf', 'all']:\r\n monte_carlo_rf()\r\n if args['exp'] in ['gcv', 'all']:\r\n monte_carlo_gcv()\r\n",
"# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License.\n\n\"\"\"Deep IV estimator and related components.\"\"\"\n\nimport numpy as np\nimport keras\nfrom .cate_estimator import BaseCateEstimator\nfrom keras import backend as K\nimport keras.layers as L\nfrom keras.models import Model\n\n# TODO: make sure to use random seeds wherever necessary\n# TODO: make sure that the public API consistently uses \"T\" instead of \"P\" for the treatment\n\n# unfortunately with the Theano and Tensorflow backends,\n# the straightforward use of K.stop_gradient can cause an error\n# because the parameters of the intermediate layers are now disconnected from the loss;\n# therefore we add a pointless multiplication by 0 to the values in each of the variables in vs\n# so that those layers remain connected but with 0 gradient\n\n\ndef _zero_grad(e, vs):\n if K.backend() == 'cntk':\n return K.stop_gradient(e)\n else:\n z = 0 * K.sum(K.concatenate([K.batch_flatten(v) for v in vs]))\n return K.stop_gradient(e) + z\n\n\ndef mog_model(n_components, d_x, d_t):\n \"\"\"\n Create a mixture of Gaussians model with the specified number of components.\n\n Parameters\n ----------\n n_components : int\n The number of components in the mixture model\n\n d_x : int\n The number of dimensions in the layer used as input\n\n d_t : int\n The number of dimensions in the output\n\n Returns\n -------\n A Keras model that takes an input of dimension `d_t` and generates three outputs: pi, mu, and sigma\n\n \"\"\"\n x = L.Input((d_x,))\n pi = L.Dense(n_components, activation='softmax')(x)\n mu = L.Reshape((n_components, d_t))(L.Dense(n_components * d_t)(x))\n log_sig = L.Dense(n_components)(x)\n sig = L.Lambda(K.exp)(log_sig)\n return Model([x], [pi, mu, sig])\n\n\ndef mog_loss_model(n_components, d_t):\n \"\"\"\n Create a Keras model that computes the loss of a mixture of Gaussians model on data.\n\n Parameters\n ----------\n n_components : int\n The number of components in the mixture model\n\n d_t : int\n The number of dimensions in the output\n\n Returns\n -------\n A Keras model that takes as inputs pi, mu, sigma, and t and generates a single output containing the loss.\n\n \"\"\"\n pi = L.Input((n_components,))\n mu = L.Input((n_components, d_t))\n sig = L.Input((n_components,))\n t = L.Input((d_t,))\n\n # || t - mu_i || ^2\n d2 = L.Lambda(lambda d: K.sum(K.square(d), axis=-1),\n output_shape=(n_components,))(\n L.Subtract()([L.RepeatVector(n_components)(t), mu])\n )\n\n # LL = C - log(sum(pi_i/sig^d * exp(-d2/(2*sig^2))))\n # Use logsumexp for numeric stability:\n # LL = C - log(sum(exp(-d2/(2*sig^2) + log(pi_i/sig^d))))\n # TODO: does the numeric stability actually make any difference?\n def make_logloss(d2, sig, pi):\n return -K.logsumexp(-d2 / (2 * K.square(sig)) + K.log(pi / K.pow(sig, d_t)), axis=-1)\n\n ll = L.Lambda(lambda dsp: make_logloss(*dsp), output_shape=(1,))([d2, sig, pi])\n\n m = Model([pi, mu, sig, t], [ll])\n return m\n\n\ndef mog_sample_model(n_components, d_t):\n \"\"\"\n Create a model that generates samples from a mixture of Gaussians.\n\n Parameters\n ----------\n n_components : int\n The number of components in the mixture model\n\n d_t : int\n The number of dimensions in the output\n\n Returns\n -------\n A Keras model that takes as inputs pi, mu, and sigma, and generates a single output containing a sample.\n\n \"\"\"\n pi = L.Input((n_components,))\n mu = L.Input((n_components, d_t))\n sig = L.Input((n_components,))\n\n # CNTK backend can't randomize across batches and doesn't implement cumsum (at least as of June 2018,\n # see Known Issues on https://docs.microsoft.com/en-us/cognitive-toolkit/Using-CNTK-with-Keras)\n def sample(pi, mu, sig):\n batch_size = K.shape(pi)[0]\n if K.backend() == 'cntk':\n # generate cumulative sum via matrix multiplication\n cumsum = K.dot(pi, K.constant(np.triu(np.ones((n_components, n_components)))))\n else:\n cumsum = K.cumsum(pi, 1)\n cumsum_shift = K.concatenate([K.zeros_like(cumsum[:, 0:1]), cumsum])[:, :-1]\n if K.backend() == 'cntk':\n import cntk as C\n # Generate standard uniform values in shape (batch_size,1)\n # (since we can't use the dynamic batch_size with random.uniform in CNTK,\n # we use uniform_like instead with an input of an appropriate shape)\n rndSmp = C.random.uniform_like(pi[:, 0:1])\n else:\n rndSmp = K.random_uniform((batch_size, 1))\n cmp1 = K.less_equal(cumsum_shift, rndSmp)\n cmp2 = K.less(rndSmp, cumsum)\n\n # convert to floats and multiply to perform equivalent of logical AND\n rndIndex = K.cast(cmp1, K.floatx()) * K.cast(cmp2, K.floatx())\n\n if K.backend() == 'cntk':\n # Generate standard normal values in shape (batch_size,1,d_t)\n # (since we can't use the dynamic batch_size with random.normal in CNTK,\n # we use normal_like instead with an input of an appropriate shape)\n rndNorms = C.random.normal_like(mu[:, 0:1, :]) # K.random_normal((1,d_t))\n else:\n rndNorms = K.random_normal((batch_size, 1, d_t))\n\n rndVec = mu + K.expand_dims(sig) * rndNorms\n\n # exactly one entry should be nonzero for each b,d combination; use sum to select it\n return K.sum(K.expand_dims(rndIndex) * rndVec, 1)\n\n # prevent gradient from passing through sampling\n samp = L.Lambda(lambda pms: _zero_grad(sample(*pms), pms), output_shape=(d_t,))\n samp.trainable = False\n\n return Model([pi, mu, sig], samp([pi, mu, sig]))\n\n\n# three options: biased or upper-bound loss require a single number of samples;\n# unbiased can take different numbers for the network and its gradient\ndef response_loss_model(h, p, d_z, d_x, d_y, samples=1, use_upper_bound=False, gradient_samples=0):\n \"\"\"\n Create a Keras model that computes the loss of a response model on data.\n\n Parameters\n ----------\n h : (tensor, tensor) -> Layer\n Method for building a model of y given p and x\n\n p : (tensor, tensor) -> Layer\n Method for building a model of p given z and x\n\n d_z : int\n The number of dimensions in z\n\n d_x : int\n Tbe number of dimensions in x\n\n d_y : int\n The number of dimensions in y\n\n samples: int\n The number of samples to use\n\n use_upper_bound : bool\n Whether to use an upper bound to the true loss\n (equivalent to adding a regularization penalty on the variance of h)\n\n gradient_samples : int\n The number of separate additional samples to use when calculating the gradient.\n This can only be nonzero if user_upper_bound is False, in which case the gradient of\n the returned loss will be an unbiased estimate of the gradient of the true loss.\n\n Returns\n -------\n A Keras model that takes as inputs z, x, and y and generates a single output containing the loss.\n\n \"\"\"\n assert not(use_upper_bound and gradient_samples)\n\n # sample: (() -> Layer, int) -> Layer\n def sample(f, n):\n assert n > 0\n if n == 1:\n return f()\n else:\n return L.average([f() for _ in range(n)])\n z, x, y = [L.Input((d,)) for d in [d_z, d_x, d_y]]\n if gradient_samples:\n # we want to separately sample the gradient; we use stop_gradient to treat the sampled model as constant\n # the overall computation ensures that we have an interpretable loss (y-h̅(p,x))²,\n # but also that the gradient is -2(y-h̅(p,x))∇h̅(p,x) with *different* samples used for each average\n diff = L.subtract([y, sample(lambda: h(p(z, x), x), samples)])\n grad = sample(lambda: h(p(z, x), x), gradient_samples)\n\n def make_expr(grad, diff):\n return K.stop_gradient(diff) * (K.stop_gradient(diff + 2 * grad) - 2 * grad)\n expr = L.Lambda(lambda args: make_expr(*args))([grad, diff])\n elif use_upper_bound:\n expr = sample(lambda: L.Lambda(K.square)(L.subtract([y, h(p(z, x), x)])), samples)\n else:\n expr = L.Lambda(K.square)(L.subtract([y, sample(lambda: h(p(z, x), x), samples)]))\n return Model([z, x, y], [expr])\n\n\nclass DeepIVEstimator(BaseCateEstimator):\n \"\"\"\n The Deep IV Estimator (see http://proceedings.mlr.press/v70/hartford17a/hartford17a.pdf).\n\n Parameters\n ----------\n n_components : int\n Number of components in the mixture density network\n\n m : (tensor, tensor) -> Layer\n Method for building a Keras model that featurizes the z and x inputs\n\n h : (tensor, tensor) -> Layer\n Method for building a model of y given t and x\n\n n_samples : int\n The number of samples to use\n\n use_upper_bound_loss : bool, optional\n Whether to use an upper bound to the true loss\n (equivalent to adding a regularization penalty on the variance of h).\n Defaults to False.\n\n n_gradient_samples : int, optional\n The number of separate additional samples to use when calculating the gradient.\n This can only be nonzero if user_upper_bound is False, in which case the gradient of\n the returned loss will be an unbiased estimate of the gradient of the true loss.\n Defaults to 0.\n\n optimizer : string, optional\n The optimizer to use. Defaults to \"adam\"\n\n first_stage_options : dictionary, optional\n The keyword arguments to pass to Keras's `fit` method when training the first stage model.\n Defaults to `{\"epochs\": 100}`.\n\n second_stage_options : dictionary, optional\n The keyword arguments to pass to Keras's `fit` method when training the second stage model.\n Defaults to `{\"epochs\": 100}`.\n\n \"\"\"\n\n def __init__(self, n_components, m, h,\n n_samples, use_upper_bound_loss=False, n_gradient_samples=0,\n optimizer='adam',\n first_stage_options={\"epochs\": 100},\n second_stage_options={\"epochs\": 100}):\n self._n_components = n_components\n self._m = m\n self._h = h\n self._n_samples = n_samples\n self._use_upper_bound_loss = use_upper_bound_loss\n self._n_gradient_samples = n_gradient_samples\n self._optimizer = optimizer\n self._first_stage_options = first_stage_options\n self._second_stage_options = second_stage_options\n super().__init__()\n\n @BaseCateEstimator._wrap_fit\n def fit(self, Y, T, X, Z, inference=None):\n \"\"\"Estimate the counterfactual model from data.\n\n That is, estimate functions τ(·, ·, ·), ∂τ(·, ·).\n\n Parameters\n ----------\n Y: (n × d_y) matrix or vector of length n\n Outcomes for each sample\n T: (n × dₜ) matrix or vector of length n\n Treatments for each sample\n X: (n × dₓ) matrix\n Features for each sample\n Z: (n × d_z) matrix\n Instruments for each sample\n inference: string, :class:`.Inference` instance, or None\n Method for performing inference. This estimator supports 'bootstrap'\n (or an instance of :class:`.BootstrapInference`)\n\n Returns\n -------\n self\n\n \"\"\"\n assert 1 <= np.ndim(X) <= 2\n assert 1 <= np.ndim(Z) <= 2\n assert 1 <= np.ndim(T) <= 2\n assert 1 <= np.ndim(Y) <= 2\n assert np.shape(X)[0] == np.shape(Y)[0] == np.shape(T)[0] == np.shape(Z)[0]\n\n # in case vectors were passed for Y or T, keep track of trailing dims for reshaping effect output\n\n d_x, d_y, d_z, d_t = [np.shape(a)[1] if np.ndim(a) > 1 else 1 for a in [X, Y, Z, T]]\n x_in, y_in, z_in, t_in = [L.Input((d,)) for d in [d_x, d_y, d_z, d_t]]\n n_components = self._n_components\n\n treatment_network = self._m(z_in, x_in)\n\n # the dimensionality of the output of the network\n # TODO: is there a more robust way to do this?\n d_n = K.int_shape(treatment_network)[-1]\n\n pi, mu, sig = mog_model(n_components, d_n, d_t)([treatment_network])\n\n ll = mog_loss_model(n_components, d_t)([pi, mu, sig, t_in])\n\n model = Model([z_in, x_in, t_in], [ll])\n model.add_loss(L.Lambda(K.mean)(ll))\n model.compile(self._optimizer)\n # TODO: do we need to give the user more control over other arguments to fit?\n model.fit([Z, X, T], [], **self._first_stage_options)\n\n lm = response_loss_model(lambda t, x: self._h(t, x),\n lambda z, x: Model([z_in, x_in],\n # subtle point: we need to build a new model each time,\n # because each model encapsulates its randomness\n [mog_sample_model(n_components, d_t)([pi, mu, sig])])([z, x]),\n d_z, d_x, d_y,\n self._n_samples, self._use_upper_bound_loss, self._n_gradient_samples)\n\n rl = lm([z_in, x_in, y_in])\n response_model = Model([z_in, x_in, y_in], [rl])\n response_model.add_loss(L.Lambda(K.mean)(rl))\n response_model.compile(self._optimizer)\n # TODO: do we need to give the user more control over other arguments to fit?\n response_model.fit([Z, X, Y], [], **self._second_stage_options)\n\n self._effect_model = Model([t_in, x_in], [self._h(t_in, x_in)])\n\n # TODO: it seems like we need to sum over the batch because we can only apply gradient to a scalar,\n # not a general tensor (because of how backprop works in every framework)\n # (alternatively, we could iterate through the batch in addition to iterating through the output,\n # but this seems annoying...)\n # Therefore, it's important that we use a batch size of 1 when we call predict with this model\n def calc_grad(t, x):\n h = self._h(t, x)\n all_grads = K.concatenate([g\n for i in range(d_y)\n for g in K.gradients(K.sum(h[:, i]), [t])])\n return K.reshape(all_grads, (-1, d_y, d_t))\n\n self._marginal_effect_model = Model([t_in, x_in], L.Lambda(lambda tx: calc_grad(*tx))([t_in, x_in]))\n\n def effect(self, X=None, T0=0, T1=1):\n \"\"\"\n Calculate the heterogeneous treatment effect τ(·,·,·).\n\n The effect is calculated between the two treatment points\n conditional on a vector of features on a set of m test samples {T0ᵢ, T1ᵢ, Xᵢ}.\n\n Parameters\n ----------\n T0: (m × dₜ) matrix\n Base treatments for each sample\n T1: (m × dₜ) matrix\n Target treatments for each sample\n X: optional (m × dₓ) matrix\n Features for each sample\n\n Returns\n -------\n τ: (m × d_y) matrix\n Heterogeneous treatment effects on each outcome for each sample\n Note that when Y is a vector rather than a 2-dimensional array, the corresponding\n singleton dimension will be collapsed (so this method will return a vector)\n \"\"\"\n if np.ndim(T0) == 0:\n T0 = np.repeat(T0, 1 if X is None else np.shape(X)[0])\n if np.ndim(T1) == 0:\n T1 = np.repeat(T1, 1 if X is None else np.shape(X)[0])\n if X is None:\n X = np.empty((np.shape(T0)[0], 0))\n return (self._effect_model.predict([T1, X]) - self._effect_model.predict([T0, X])).reshape((-1,) + self._d_y)\n\n def marginal_effect(self, T, X=None):\n \"\"\"\n Calculate the marginal effect ∂τ(·, ·) around a base treatment point conditional on features.\n\n Parameters\n ----------\n T: (m × dₜ) matrix\n Base treatments for each sample\n X: optional(m × dₓ) matrix\n Features for each sample\n\n Returns\n -------\n grad_tau: (m × d_y × dₜ) array\n Heterogeneous marginal effects on each outcome for each sample\n Note that when Y or T is a vector rather than a 2-dimensional array,\n the corresponding singleton dimensions in the output will be collapsed\n (e.g. if both are vectors, then the output of this method will also be a vector)\n \"\"\"\n # TODO: any way to get this to work on batches of arbitrary size?\n return self._marginal_effect_model.predict([T, X], batch_size=1).reshape((-1,) + self._d_y + self._d_t)\n\n def predict(self, T, X):\n \"\"\"Predict outcomes given treatment assignments and features.\n\n Parameters\n ----------\n T: (m × dₜ) matrix\n Base treatments for each sample\n X: (m × dₓ) matrix\n Features for each sample\n\n Returns\n -------\n Y: (m × d_y) matrix\n Outcomes for each sample\n Note that when Y is a vector rather than a 2-dimensional array, the corresponding\n singleton dimension will be collapsed (so this method will return a vector)\n \"\"\"\n return self._effect_model.predict([T, X]).reshape((-1,) + self._d_y)\n"
] |
[
[
"sklearn.ensemble.RandomForestRegressor",
"numpy.sqrt",
"numpy.concatenate",
"numpy.mean",
"numpy.hstack",
"numpy.arange",
"sklearn.ensemble.GradientBoostingRegressor",
"numpy.std",
"matplotlib.pyplot.close",
"numpy.repeat",
"numpy.zeros",
"matplotlib.pyplot.figure",
"numpy.random.binomial",
"numpy.array",
"sklearn.model_selection.GridSearchCV",
"numpy.printoptions",
"numpy.abs",
"numpy.random.seed",
"numpy.percentile",
"numpy.ones",
"numpy.random.normal",
"sklearn.linear_model.LinearRegression",
"numpy.vstack"
],
[
"numpy.ndim",
"numpy.shape",
"numpy.ones"
]
] |
IvoAA/dl2
|
[
"f656d24b3d227a35b4fc9e0094150fbe17d055ce"
] |
[
"training/supervised/oracles.py"
] |
[
"import numpy as np\nimport torch\n\nclass DL2_Oracle:\n\n def __init__(self, learning_rate, net, constraint, use_cuda):\n self.learning_rate = learning_rate\n self.net = net\n self.constraint = constraint\n self.use_cuda = use_cuda\n\n def attack(self, x_batch, y_batch, domains, num_restarts, num_iters):\n n_batch = x_batch.size()[0]\n\n for retry in range(num_restarts):\n z_batch = np.concatenate([np.expand_dims(domains[i].sample(),axis=0) for i in range(n_batch)], axis=0)\n\n for it in range(num_iters):\n avg_neg_loss, avg_pos_loss, sat, z_inputs = self.loss(self.net, x_batch, y_batch, z_batch, self.use_cuda)\n avg_neg_loss.backward(retain_graph=True)\n z_batch_grad = np.sign(z_inputs.grad.data)\n z_batch -= self.learning_rate * z_batch_grad\n for i in range(n_batch):\n z_batch[i] = domains[i].project(z_batch[i])\n\n return z_batch\n\n def general_attack(self, x_batches, y_batches, domains, num_restarts, num_iters, args):\n \"\"\" Minimizes DL2 loss with respect to z_1, ..., z_M.\n\n :param x_batches: List of N tensors, each tensor has shape batch_size x D\n :param y_batches: List of N tensors, each tensor has shape batch_size x num_classes\n :param domains: Nested list of Domain objects of shape M x batch_size, D_i is domain of variable z_i\n :param num_restarts: Number of times to restart the sampling\n :param num_iters: Number of iterations to perform in each restart\n :return: List of values for each of variables z_1, ..., z_M\n \"\"\"\n n_batch = x_batches[0].size()[0]\n n_gvars = len(domains)\n\n for retry in range(num_restarts):\n z_batches = [np.concatenate([np.expand_dims(domains[j][i].sample(), axis=0) for i in range(n_batch)], axis=0)\n for j in range(n_gvars)]\n\n assert z_batches[0].shape[0] == n_batch, 'Batch size in x and z doesn not match'\n\n for it in range(num_iters):\n neg_losses, pos_losses, sat, z_inputs = self.constraint.loss(x_batches, y_batches, z_batches, args)\n\n avg_neg_loss = torch.mean(neg_losses)\n avg_neg_loss.backward()\n for i in range(n_gvars):\n z_grad = z_inputs[i].grad.data\n z_grad = z_grad.cpu().numpy()\n if domains[0][i].name == 'box':\n z_grad = np.sign(z_grad)\n z_batches[i] -= self.learning_rate * z_grad\n for j in range(n_gvars):\n for i in range(n_batch):\n z_batches[j][i] = domains[j][i].project(z_batches[j][i])\n\n return z_batches\n\n def evaluate(self, x_batches, y_batches, z_batches, args):\n neg_losses, pos_losses, sat, _ = self.constraint.loss(x_batches, y_batches, z_batches, args)\n if not isinstance(sat, np.ndarray):\n sat = sat.cpu().numpy()\n constr_acc = np.mean(sat)\n return torch.mean(neg_losses), torch.mean(pos_losses), constr_acc\n"
] |
[
[
"numpy.sign",
"torch.mean",
"numpy.mean"
]
] |
usc-isi-i2/datamart-upload
|
[
"c27a3d745daabb2d24681d8224bec140b6a4a7b9"
] |
[
"datamart_isi/upload/file_parsers/csv_parser.py"
] |
[
"import logging\nimport pandas as pd\nimport time\nimport wikifier\nimport typing\nimport hashlib\nimport json\nimport os\n\nfrom .parser_base import ParserBase, PreParsedResult\nfrom pandas.util import hash_pandas_object\n\nfrom datamart_isi.materializers.general_materializer import GeneralMaterializer\nfrom datamart_isi.materializers.wikitables_materializer import WikitablesMaterializer\nfrom datamart_isi.utilities.d3m_wikifier import save_wikifier_choice, check_is_q_node_column\nfrom datamart_isi.cache.general_search_cache import GeneralSearchCache\nfrom datamart_isi.utilities.utils import Utils as datamart_utils\nfrom datamart_isi import config as config_datamart\nfrom etk.wikidata.entity import *\nfrom etk.wikidata.value import *\nfrom io import StringIO\nfrom datetime import datetime\nfrom datetime import timezone\nfrom datetime import timedelta\nfrom wikifier.utils import remove_punctuation\nfrom datamart_isi.utilities.timeout import timeout_call\n\nSUPPORT_TYPE = [\"csv\"]\nMODULE_NAME = \"CSVParser\"\n\n\nclass CSVParser(ParserBase):\n def __init__(self):\n self._logger = logging.getLogger(__name__)\n self.cache_manager = GeneralSearchCache()\n\n def load_and_preprocess(self, **kwargs):\n input_dir = kwargs.get(\"input_dir\")\n file_type = kwargs.get(\"file_type\", \"csv\")\n job = kwargs.get(\"job\", None)\n wikifier_choice = kwargs.get(\"wikifier_choice\", \"auto\")\n start = time.time()\n self._logger.debug(\"Start loading from \" + input_dir)\n if job is not None:\n job.meta['step'] = \"materializing the dataset...\"\n job.save_meta()\n from_online_file = False\n if file_type == \"csv\":\n try:\n _ = [pd.read_csv(input_dir, dtype=str)]\n file_type = \"online_csv\"\n except Exception:\n raise ValueError(\"Reading csv from\" + input_dir + \"failed.\")\n\n if len(file_type) > 7 and file_type[:7] == \"online_\":\n from_online_file = True\n general_materializer = GeneralMaterializer()\n file_type = file_type[7:]\n # example: \"csv\"\n file_metadata = {\n \"materialization\": {\n \"arguments\": {\n \"url\": input_dir,\n \"file_type\": file_type\n }\n }\n }\n try:\n result = general_materializer.get(metadata=file_metadata).to_csv(index=False)\n except Exception as e:\n self._logger.debug(e, exc_info=True)\n raise ValueError(\"Loading online data from \" + input_dir + \" failed!\")\n # remove last \\n so that we will not get an extra useless row\n if result[-1] == \"\\n\":\n result = result[:-1]\n loaded_data = StringIO(result)\n loaded_data = [pd.read_csv(loaded_data, dtype=str)]\n\n elif file_type == \"wikitable\":\n from_online_file = True\n materializer = WikitablesMaterializer()\n loaded_data, xpaths = materializer.get(input_dir)\n else:\n raise ValueError(\"Unsupported file type\")\n end1 = time.time()\n self._logger.info(\"Loading finished. Totally take \" + str(end1 - start) + \" seconds.\")\n if job is not None:\n job.meta['step'] = \"materialization finished, start running wikifier...\"\n job.meta['loading dataset used'] = str(timedelta(seconds=end1 - start))\n job.save_meta()\n\n all_wikifier_res = []\n all_metadata = []\n for df_count, each_df in enumerate(loaded_data):\n if each_df.shape[0] == 0:\n raise ValueError(\"Detect empty when loading No.{} table, please check!\".format(str(df_count)))\n if wikifier_choice == \"false\":\n do_wikifier = False\n elif wikifier_choice == \"true\":\n do_wikifier = True\n else:\n do_wikifier = None\n\n # this function will also determine whether to do wikifier or not if do_wikifier = None\n do_wikifier = save_wikifier_choice(input_dataframe=each_df, choice=do_wikifier)\n\n if do_wikifier:\n self._logger.info(\"Will run wikifier!\")\n # not use cache during upload\n wikifier_res = wikifier.produce(each_df, use_cache=False)\n\n else:\n self._logger.info(\"Not run wikifier!\")\n wikifier_res = each_df\n # we also need to let the cache system know not to do wikifier\n produce_config = {\"target_columns\": None, \"target_p_nodes\": None,\n \"input_type\": \"pandas\", \"wikifier_choice\": None,\n \"threshold\": 0.7\n }\n\n cache_key = self.cache_manager.get_hash_key(each_df, json.dumps(produce_config))\n\n # add extra information after we calculate the correct hash tag\n produce_config[\"use_wikifier\"] = False\n response = self.cache_manager. \\\n add_to_memcache(supplied_dataframe=each_df,\n search_result_serialized=json.dumps(produce_config),\n augment_results=each_df,\n hash_key=cache_key\n )\n if not response:\n self._logger.warning(\"Push wikifier results to results failed!\")\n else:\n self._logger.info(\"Push wikifier results to memcache success!\")\n\n end2 = time.time()\n self._logger.info(\"Wikifier finished. Totally take \" + str(end2 - end1) + \" seconds.\")\n if job is not None:\n job.meta['step'] = \"wikifier running finished, start generating metadata...\"\n job.meta['wikifier used'] = str(timedelta(seconds=end2 - end1))\n job.save_meta()\n\n # process datetime column to standard datetime\n for col_name in wikifier_res.columns.values.tolist():\n if 'date' in col_name.lower() or 'time' in col_name.lower():\n try:\n temp = pd.to_datetime(wikifier_res[col_name])\n has_time_format_or_not = (pd.isnull(temp) == True).value_counts()\n if False in has_time_format_or_not.keys() and has_time_format_or_not[False] >= wikifier_res.shape[\n 0] * 0.7:\n wikifier_res[col_name] = temp\n except:\n pass\n\n # TODO: need update profiler here to generate better semantic type\n metadata = datamart_utils.generate_metadata_from_dataframe(data=wikifier_res)\n self._logger.info(\"The uploaded data's shape is \" + str(wikifier_res.shape))\n for i, each_column_meta in enumerate(metadata['variables']):\n self._logger.debug(\"Metadata for column No.{} is:\".format(str(i)))\n self._logger.debug(str(each_column_meta))\n # if 'http://schema.org/Text' in each_column_meta['semantic_type']:\n # self.columns_are_string[df_count].append(i)\n\n if from_online_file:\n metadata['url'] = input_dir\n title_cleaned = input_dir.split(\"/\")[-1]\n words_processed = remove_punctuation(title_cleaned)\n metadata['title'] = \" \".join(words_processed)\n metadata['file_type'] = file_type\n if file_type == \"wikitable\":\n metadata['xpath'] = xpaths[df_count]\n\n all_wikifier_res.append(wikifier_res)\n all_metadata.append(metadata)\n\n end2 = time.time()\n self._logger.info(\"Preprocess finished. Totally take \" + str(end2 - end1) + \" seconds.\")\n if job is not None:\n job.meta['step'] = \"metadata generating finished...\"\n job.meta['metadata generating used'] = str(timedelta(seconds=end2 - end1))\n job.save_meta()\n return PreParsedResult(all_wikifier_res, all_metadata)\n\n def model_data(self, doc, inputs: PreParsedResult, **kwargs):\n input_dfs = inputs.content\n metadata = inputs.metadata\n number = kwargs.get(\"number\") # an int\n uploader_information = kwargs.get(\"uploader_information\")\n self._logger.debug(\"Start modeling data into blazegraph format...\")\n start = time.time()\n job = kwargs.get(\"job\", None)\n need_process_columns = kwargs.get(\"need_process_columns\", None)\n if need_process_columns is None:\n need_process_columns = list(range(input_dfs[number].shape[1]))\n else:\n self._logger.info(\"Received specified target process columns as {}\".format(str(need_process_columns)))\n for each_column_number in need_process_columns:\n if each_column_number >= input_dfs[number].shape[1]:\n raise ValueError(\n \"The given column number {} exceed the dataset's column length as {}.\".format(each_column_number, str(\n input_dfs[number].shape[1])))\n\n for each_col in range(input_dfs[number].shape[1]):\n if each_col not in need_process_columns and check_is_q_node_column(input_dfs[number], each_col):\n self._logger.info(\"Automatically add Q node column at No.{} {} as index list!\".format(str(each_col), str(\n input_dfs[number].columns[each_col])))\n need_process_columns.append(each_col)\n\n # updated v2019.12.5: now use the md5 value of dataframe hash as the dataset id\n pandas_id = str(hash_pandas_object(input_dfs[number]).sum())\n hash_generator = hashlib.md5()\n hash_generator.update(pandas_id.encode('utf-8'))\n hash_url_key = hash_generator.hexdigest()\n modeled_data_id = hash_url_key\n\n if metadata is None or metadata[number] is None:\n metadata = {}\n extra_information = {}\n title = metadata[number].get(\"title\") or \"\"\n keywords = metadata[number].get(\"keywords\") or \"\"\n file_type = metadata[number].get(\"file_type\") or \"\"\n # TODO: if no url given?\n url = metadata[number].get(\"url\") or \"http://\"\n\n # update v2019.12.6, now adapt special requirement from keywords\n if type(keywords) is str:\n keywords_list = []\n if keywords.find(config_datamart.upload_special_requirement_mark, 0) != -1 and keywords.find(\n config_datamart.upload_special_requirement_mark, 0) != keywords.find(\n config_datamart.upload_special_requirement_mark, 1):\n keywords_list.append(keywords[keywords.find(config_datamart.upload_special_requirement_mark, 0):\n keywords.find(config_datamart.upload_special_requirement_mark, 1) +\n len(config_datamart.upload_special_requirement_mark)])\n keywords = keywords[keywords.find(config_datamart.upload_special_requirement_mark, 1) +\n len(config_datamart.upload_special_requirement_mark) + 1:]\n keywords_list.extend(keywords.split(\",\"))\n else:\n keywords_list = keywords\n words_processed = []\n for each in keywords_list:\n if each.startswith(\"*&#\") and each.endswith(\"*&#\"):\n self._logger.info(\"Special requirement from keyword area detected as {}\".format(each))\n special_requirement = json.loads(each[3: -3])\n extra_information['special_requirement'] = special_requirement\n else:\n words_processed.extend(remove_punctuation(each))\n # updated v2020.1.3: now also do keywords augmentation during uploading process\n words_processed = datamart_utils.keywords_augmentation(words_processed)\n # also augment title and save as keywords\n words_processed.extend(datamart_utils.keywords_augmentation(remove_punctuation(title, \"list\")))\n keywords = \" \".join(set(words_processed))\n\n node_id = 'D' + str(modeled_data_id)\n q = WDItem(node_id)\n if 'xpath' in metadata[number]:\n extra_information['xpath'] = metadata[number]['xpath']\n\n data_metadata = {'shape_0': input_dfs[number].shape[0], 'shape_1': input_dfs[number].shape[1]}\n for i, each in enumerate(metadata[number]['variables']):\n each_column_meta = {'semantic_type': each['semantic_type'], 'name': input_dfs[number].columns[i]}\n extra_information['column_meta_' + str(i)] = each_column_meta\n extra_information['data_metadata'] = data_metadata\n\n # updated v2019.10.14, add first 10 rows of each dataset in extra information for checking\n extra_information['first_10_rows'] = input_dfs[number].loc[:10].to_csv()\n # updated v2019.10.14, trying to save a local backup of the downloaded dataframe to increase the speed\n hash_generator = hashlib.md5()\n hash_generator.update(url.encode('utf-8'))\n hash_url_key = hash_generator.hexdigest()\n dataset_cache_loc = os.path.join(config_datamart.cache_file_storage_base_loc, \"datasets_cache\")\n cache_file_loc = os.path.join(dataset_cache_loc, hash_url_key + \".h5\")\n if not os.path.exists(dataset_cache_loc):\n os.mkdir(dataset_cache_loc)\n\n input_dfs[number].to_hdf(cache_file_loc, key='df', mode='w', format='fixed')\n extra_information['local_storage'] = cache_file_loc\n\n # for each_key in [\"\", ]:\n # if each_key not in uploader_information:\n # uploader_information[each_key] = \"None\"\n\n q.add_label(node_id, lang='en')\n q.add_statement('P31', Item('Q1172284')) # indicate it is subclass of a dataset\n q.add_statement('P2699', URLValue(url)) # url\n q.add_statement('P2701', StringValue(file_type)) # file type\n q.add_statement('P1476', MonolingualText(title, lang='en')) # title\n q.add_statement('C2001', StringValue(node_id)) # datamart identifier\n q.add_statement('C2004', StringValue(keywords)) # keywords\n q.add_statement('C2010', StringValue(json.dumps(extra_information)))\n q.add_statement('C2014', StringValue(json.dumps(uploader_information)))\n\n end1 = time.time()\n if job is not None:\n job.meta['step'] = \"Modeling abstract data finished.\"\n job.meta['modeling abstract'] = str(timedelta(seconds=end1 - start))\n job.save_meta()\n\n self._logger.info(\"Modeling abstract data finished. Totally take \" + str(end1 - start) + \" seconds.\")\n\n # each columns\n for i in need_process_columns:\n if job is not None:\n job.meta['step'] = \"Modeling ({}/{}) column ...\".format(str(i), str(input_dfs[number].shape[1]))\n job.save_meta()\n try:\n semantic_type = metadata[number]['variables'][i]['semantic_type']\n except IndexError:\n semantic_type = 'http://schema.org/Text'\n model_column_time_limit = 600\n self._logger.info(\n \"Currently setting modeling each column maximum time as \" + str(model_column_time_limit) + \" seconds.\")\n # use timeout to prevent stuck on some columns\n res = timeout_call(model_column_time_limit, self.process_one_column,\n [input_dfs[number].iloc[:, i], q, i, semantic_type])\n # res = self.process_one_column(column_data=input_dfs[number].iloc[:, i], item=q, column_number=i,\n # semantic_type=semantic_type)\n if res is None:\n self._logger.error(\"Error when modeling column \" + str(i) + \". Maybe timeout? Will skip.\")\n else:\n q = res\n doc.kg.add_subject(q)\n end2 = time.time()\n self._logger.info(\"Modeling detail data finished. Totally take \" + str(end2 - end1) + \" seconds.\")\n if job is not None:\n job.meta['step'] = \"Modeling finished. Start uploading...\"\n job.meta['modeling'] = str(timedelta(seconds=end2 - end1))\n job.save_meta()\n # return the updated etc doc and corresponding dataset id\n return doc, node_id\n\n def process_one_column(self, column_data: pd.Series, item: WDItem, column_number: int,\n semantic_type: typing.List[str]) -> typing.Union[WDItem, None]:\n \"\"\"\n :param column_data: a pandas series data\n :param item: the target q node aimed to add on\n :param column_number: the column number\n :param semantic_type: a list indicate the semantic type of this column\n :return: a bool indicate succeeded or not\n \"\"\"\n start = time.time()\n self._logger.debug(\"Start processing No.\" + str(column_number) + \" column.\")\n statement = item.add_statement('C2005', StringValue(column_data.name)) # variable measured\n try:\n # updated v2020.1.9, it seems dsbox profiler do not convert \"year\" only data, we need to check here\n if 'http://schema.org/Integer' in semantic_type and \"year\" in column_data.name:\n try:\n column_data = column_data.astype(\"int\")\n if max(column_data) < 2100 and min(column_data) > 1000:\n column_data = pd.to_datetime(column_data, format='%Y', errors=\"raise\")\n self._logger.info(\"Detect year data on column No.{}!\".format(str(column_number)))\n except:\n pass\n\n if 'http://schema.org/DateTime' in semantic_type or \"datetime\" in column_data.dtype.name:\n data_type = \"datetime\"\n semantic_type_url = \"http://schema.org/DateTime\"\n start_date = min(column_data)\n end_date = max(column_data)\n\n # updated v2019.12.12: check details, only treat as the granularity\n # if we found more than 1 values for this granularity\n time_granularity = datamart_utils.map_granularity_to_value(datamart_utils.get_time_granularity(column_data))\n start_time_str = datetime.fromtimestamp(start_date.timestamp(), tz=timezone.utc).strftime(\"%Y-%m-%dT%H:%M:%S\")\n end_time_str = datetime.fromtimestamp(end_date.timestamp(), tz=timezone.utc).strftime(\"%Y-%m-%dT%H:%M:%S\")\n\n start_time = TimeValue(Literal(start_time_str, type_=LiteralType.dateTime), Item('Q1985727'),\n time_granularity, 0)\n end_time = TimeValue(Literal(end_time_str, type_=LiteralType.dateTime), Item('Q1985727'),\n time_granularity, 0)\n\n statement.add_qualifier('C2011', start_time)\n statement.add_qualifier('C2012', end_time)\n statement.add_qualifier('C2013', QuantityValue(time_granularity))\n else:\n all_data = set(column_data.tolist())\n all_value_str_set = set()\n for each in all_data:\n # set to lower characters, remove punctuation and split by the space\n words_processed = remove_punctuation(each)\n for word in words_processed:\n all_value_str_set.add(word)\n all_value_str = \" \".join(all_value_str_set)\n\n statement.add_qualifier('C2006', StringValue(all_value_str)) # values\n if 'http://schema.org/Float' in semantic_type:\n semantic_type_url = 'http://schema.org/Float'\n data_type = \"float\"\n elif 'http://schema.org/Integer' in semantic_type:\n data_type = \"int\"\n semantic_type_url = 'http://schema.org/Integer'\n else: # 'http://schema.org/Text' in semantic_type:\n data_type = \"string\"\n semantic_type_url = 'http://schema.org/Text'\n\n statement.add_qualifier('C2007', Item(data_type)) # data structure type\n statement.add_qualifier('C2008', URLValue(semantic_type_url)) # semantic type identifier\n statement.add_qualifier('P1545', QuantityValue(column_number)) # column index\n end1 = time.time()\n self._logger.info(\"Processing finished, totally take \" + str(end1 - start) + \" seconds.\")\n return item\n\n except Exception as e:\n self._logger.error(\"[ERROR] processing column No.\" + str(column_number) + \" failed!\")\n self._logger.debug(e, exc_info=True)\n return None\n"
] |
[
[
"pandas.util.hash_pandas_object",
"pandas.read_csv",
"pandas.to_datetime",
"pandas.isnull"
]
] |
ege-k/nlp4nethack
|
[
"8b8b45a2f0be09c5233b33a47f421906e9e4b561",
"8b8b45a2f0be09c5233b33a47f421906e9e4b561"
] |
[
"nethack_baselines/torchbeast/models/baseline_tensorized.py",
"test_submission.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\nimport collections\nimport torch\nfrom torch import nn\nfrom torch.nn import functional as F\nfrom einops import rearrange\n\n\nfrom nle import nethack\n\nfrom .util import id_pairs_table\nimport numpy as np\n\nNUM_GLYPHS = nethack.MAX_GLYPH\nNUM_FEATURES = nethack.BLSTATS_SHAPE[0]\nPAD_CHAR = 0\nNUM_CHARS = 256\n\n\ndef get_action_space_mask(action_space, reduced_action_space):\n mask = np.array([int(a in reduced_action_space) for a in action_space])\n return torch.Tensor(mask)\n\n\ndef conv_outdim(i_dim, k, padding=0, stride=1, dilation=1):\n \"\"\"Return the dimension after applying a convolution along one axis\"\"\"\n return int(1 + (i_dim + 2 * padding - dilation * (k - 1) - 1) / stride)\n\n\ndef select(embedding_layer, x, use_index_select):\n \"\"\"Use index select instead of default forward to possible speed up embedding.\"\"\"\n if use_index_select:\n out = embedding_layer.weight.index_select(0, x.reshape(-1))\n # handle reshaping x to 1-d and output back to N-d\n return out.reshape(x.shape + (-1,))\n else:\n return embedding_layer(x)\n\n\nclass NetHackNet(nn.Module):\n \"\"\"This base class simply provides a skeleton for running with torchbeast.\"\"\"\n\n AgentOutput = collections.namedtuple(\"AgentOutput\", \"action policy_logits baseline\")\n\n def __init__(self):\n super(NetHackNet, self).__init__()\n self.register_buffer(\"reward_sum\", torch.zeros(()))\n self.register_buffer(\"reward_m2\", torch.zeros(()))\n self.register_buffer(\"reward_count\", torch.zeros(()).fill_(1e-8))\n\n def forward(self, inputs, core_state):\n raise NotImplementedError\n\n def initial_state(self, batch_size=1):\n return ()\n\n @torch.no_grad()\n def update_running_moments(self, reward_batch):\n \"\"\"Maintains a running mean of reward.\"\"\"\n new_count = len(reward_batch)\n new_sum = torch.sum(reward_batch)\n new_mean = new_sum / new_count\n\n curr_mean = self.reward_sum / self.reward_count\n new_m2 = torch.sum((reward_batch - new_mean) ** 2) + (\n (self.reward_count * new_count)\n / (self.reward_count + new_count)\n * (new_mean - curr_mean) ** 2\n )\n\n self.reward_count += new_count\n self.reward_sum += new_sum\n self.reward_m2 += new_m2\n\n @torch.no_grad()\n def get_running_std(self):\n \"\"\"Returns standard deviation of the running mean of the reward.\"\"\"\n return torch.sqrt(self.reward_m2 / self.reward_count)\n\n\nclass BaselineNet(NetHackNet):\n \"\"\"This model combines the encodings of the glyphs, top line message and\n blstats into a single fixed-size representation, which is then passed to\n an LSTM core before generating a policy and value head for use in an IMPALA\n like architecture.\n\n This model was based on 'neurips2020release' tag on the NLE repo, itself\n based on Kuttler et al, 2020\n The NetHack Learning Environment\n https://arxiv.org/abs/2006.13760\n \"\"\"\n\n def __init__(self, observation_shape, action_space, flags, device):\n super(BaselineNet, self).__init__()\n\n self.flags = flags\n\n self.corpus_attention = flags.corpus_attention\n self.attention_dim = flags.attention_dim\n\n \n self.register_buffer('doc_embeddings', torch.load(\"/home/ekarais/nethack/nlp4nethack/nethack_baselines/torchbeast/models/reduced_doc_embeddings.pt\"))\n embed_size = 128\n #self.doc_embeddings = torch.randn(1699, embed_size)\n #self.doc_embeddings.requires_grad = False\n \n self.attention = nn.MultiheadAttention(self.attention_dim, 4, kdim=128, vdim=128)\n\n self.observation_shape = observation_shape\n self.num_actions = len(action_space)\n\n self.H = observation_shape[0]\n self.W = observation_shape[1]\n\n self.use_lstm = flags.use_lstm\n self.h_dim = flags.hidden_dim\n\n # GLYPH + CROP MODEL\n self.glyph_model = GlyphEncoder(flags, self.H, self.W, flags.crop_dim, device)\n\n # MESSAGING MODEL\n self.msg_model = MessageEncoder(\n flags.msg.hidden_dim, flags.msg.embedding_dim, device\n )\n\n # BLSTATS MODEL\n self.blstats_model = BLStatsEncoder(NUM_FEATURES, flags.embedding_dim)\n\n \n out_dim = (\n self.blstats_model.hidden_dim\n + self.glyph_model.hidden_dim\n + self.msg_model.hidden_dim\n )\n\n self.fc = nn.Sequential(\n nn.Linear(out_dim, self.h_dim),\n nn.ReLU(),\n nn.Linear(self.h_dim, self.h_dim),\n nn.ReLU(),\n )\n\n if self.use_lstm:\n self.core = nn.LSTM(self.h_dim, self.h_dim, num_layers=1)\n\n if self.corpus_attention:\n #self.scaling = nn.Linear(self.h_dim, 256)\n self.policy = nn.Linear(self.h_dim + self.attention_dim, self.num_actions)\n self.baseline = nn.Linear(self.h_dim + self.attention_dim, 1)\n\n else:\n self.policy = nn.Linear(self.h_dim, self.num_actions)\n self.baseline = nn.Linear(self.h_dim, 1)\n\n if flags.restrict_action_space:\n reduced_space = nethack.USEFUL_ACTIONS\n logits_mask = get_action_space_mask(action_space, reduced_space)\n #self.policy_logits_mask = nn.parameter.Parameter(\n # logits_mask, requires_grad=False\n #)\n self.register_buffer('policy_logits_mask', logits_mask)\n\n def initial_state(self, batch_size=1):\n \n return tuple(\n torch.zeros(self.core.num_layers, batch_size, self.core.hidden_size)\n for _ in range(2)\n )\n \n\n def forward(self, glyphs, chars, colors, specials, blstats, message, done, core_state, learning=False):\n T, B, H, W = glyphs.shape\n \n reps = []\n\n # -- [B' x K] ; B' == (T x B)\n glyphs_rep = self.glyph_model(glyphs, chars, colors, specials, blstats)\n reps.append(glyphs_rep)\n\n # -- [B' x K]\n char_rep = self.msg_model(message)\n reps.append(char_rep)\n\n # -- [B' x K]\n features_emb = self.blstats_model(blstats)\n reps.append(features_emb)\n\n # -- [B' x K]\n st = torch.cat(reps, dim=1)\n\n # -- [B' x K]\n st = self.fc(st)\n \n \n if self.use_lstm:\n core_input = st.reshape(T, B, -1)\n core_output_list = []\n notdone = (~done).float()\n for input, nd in zip(core_input.unbind(), notdone.unbind()):\n # Reset core state to zero whenever an episode ended.\n # Make `done` broadcastable with (num_layers, B, hidden_size)\n # states:\n nd = nd.reshape(1, -1, 1)\n int_core_state = tuple(nd * t for t in core_state)\n output, new_core_state = self.core(input.unsqueeze(0), int_core_state)\n core_output_list.append(output)\n core_output = torch.flatten(torch.cat(core_output_list), 0, 1)\n else:\n core_output = st\n\n #print(\"q shape\", core_output.shape, flush=True)\n #print(\"k,v shape\", self.doc_embeddings.shape, flush=True)\n if self.corpus_attention:\n #scaled_output = self.scaling(core_output)\n self.doc_embeddings = self.doc_embeddings.to(core_output.get_device())\n batch_size = core_output.shape[0]\n attention_out, _ = self.attention(torch.unsqueeze(core_output, 0), \n torch.unsqueeze(self.doc_embeddings, 1).expand(-1, batch_size,-1), \n torch.unsqueeze(self.doc_embeddings, 1).expand(-1, batch_size,-1))\n \n #print(\"q shape\", core_output.shape, flush=True)\n #print(\"attention shape\", attention_out.shape, flush=True)\n core_output = torch.cat([core_output, attention_out[0]], dim=1)\n\n # -- [B' x A]\n policy_logits = self.policy(core_output)\n\n # -- [B' x 1]\n baseline = self.baseline(core_output)\n\n if self.flags.restrict_action_space:\n policy_logits = policy_logits * self.policy_logits_mask + (\n (1 - self.policy_logits_mask) * -1e10\n )\n\n if self.training:\n action = torch.multinomial(F.softmax(policy_logits, dim=1), num_samples=1)\n else:\n # Don't sample when testing.\n action = torch.argmax(policy_logits, dim=1)\n\n policy_logits = policy_logits.reshape(T, B, -1)\n baseline = baseline.reshape(T, B)\n action = action.reshape(T, B)\n\n output = dict(policy_logits=policy_logits, baseline=baseline, action=action)\n return (output, new_core_state, features_emb)\n\nclass GlyphEncoder(nn.Module):\n \"\"\"This glyph encoder first breaks the glyphs (integers up to 6000) to a\n more structured representation based on the qualities of the glyph: chars,\n colors, specials, groups and subgroup ids..\n Eg: invisible hell-hound: char (d), color (red), specials (invisible),\n group (monster) subgroup id (type of monster)\n Eg: lit dungeon floor: char (.), color (white), specials (none),\n group (dungeon) subgroup id (type of dungeon)\n\n An embedding is provided for each of these, and the embeddings are\n concatenated, before encoding with a number of CNN layers. This operation\n is repeated with a crop of the structured reprentations taken around the\n characters position, and the two representations are concatenated\n before returning.\n \"\"\"\n\n def __init__(self, flags, rows, cols, crop_dim, device=None):\n super(GlyphEncoder, self).__init__()\n\n \n\n self.crop = Crop(rows, cols, crop_dim, crop_dim, device)\n K = flags.embedding_dim # number of input filters\n L = flags.layers # number of convnet layers\n\n assert (\n K % 8 == 0\n ), \"This glyph embedding format needs embedding dim to be multiple of 8\"\n unit = K // 8\n self.chars_embedding = nn.Embedding(256, 2 * unit)\n self.colors_embedding = nn.Embedding(16, unit)\n self.specials_embedding = nn.Embedding(256, unit)\n\n #self.id_pairs_table = nn.parameter.Parameter(\n # torch.from_numpy(id_pairs_table()), requires_grad=False\n #)\n self.register_buffer('id_pairs_table', torch.from_numpy(id_pairs_table()))\n\n num_groups = self.id_pairs_table.select(1, 1).max().item() + 1\n num_ids = self.id_pairs_table.select(1, 0).max().item() + 1\n\n self.groups_embedding = nn.Embedding(num_groups, unit)\n self.ids_embedding = nn.Embedding(num_ids, 3 * unit)\n\n F = 3 # filter dimensions\n S = 1 # stride\n P = 1 # padding\n M = 16 # number of intermediate filters\n self.output_filters = 8\n\n in_channels = [K] + [M] * (L - 1)\n out_channels = [M] * (L - 1) + [self.output_filters]\n\n h, w, c = rows, cols, crop_dim\n conv_extract, conv_extract_crop = [], []\n for i in range(L):\n conv_extract.append(\n nn.Conv2d(\n in_channels=in_channels[i],\n out_channels=out_channels[i],\n kernel_size=(F, F),\n stride=S,\n padding=P,\n )\n )\n conv_extract.append(nn.ELU())\n\n conv_extract_crop.append(\n nn.Conv2d(\n in_channels=in_channels[i],\n out_channels=out_channels[i],\n kernel_size=(F, F),\n stride=S,\n padding=P,\n )\n )\n conv_extract_crop.append(nn.ELU())\n\n # Keep track of output shapes\n h = conv_outdim(h, F, P, S)\n w = conv_outdim(w, F, P, S)\n c = conv_outdim(c, F, P, S)\n\n self.hidden_dim = (h * w + c * c) * self.output_filters\n self.extract_representation = nn.Sequential(*conv_extract)\n self.extract_crop_representation = nn.Sequential(*conv_extract_crop)\n self.select = lambda emb, x: select(emb, x, flags.use_index_select)\n\n def glyphs_to_ids_groups(self, glyphs):\n T, B, H, W = glyphs.shape\n #ids_groups = self.id_pairs_table.index_select(0, glyphs.reshape(-1).long())\n ids_groups = self.id_pairs_table.index_select(0, glyphs.reshape(-1).long())\n ids = ids_groups.select(1, 0).reshape(T, B, H, W).long()\n groups = ids_groups.select(1, 1).reshape(T, B, H, W).long()\n return [ids, groups]\n\n def forward(self, glyphs, chars, colors, specials, blstats):\n T, B, H, W = glyphs.shape\n ids, groups = self.glyphs_to_ids_groups(glyphs)\n\n glyph_tensors = [\n self.select(self.chars_embedding, chars.long()),\n self.select(self.colors_embedding, colors.long()),\n self.select(self.specials_embedding, specials.long()),\n self.select(self.groups_embedding, groups),\n self.select(self.ids_embedding, ids),\n ]\n\n glyphs_emb = torch.cat(glyph_tensors, dim=-1)\n glyphs_emb = rearrange(glyphs_emb, \"T B H W K -> (T B) K H W\")\n\n #coordinates = blstats.reshape(T * B, -1).float()[:, :2]\n coordinates = blstats.reshape(T * B, -1).float()[:, :2]\n crop_emb = self.crop(glyphs_emb, coordinates)\n\n glyphs_rep = self.extract_representation(glyphs_emb)\n glyphs_rep = rearrange(glyphs_rep, \"B C H W -> B (C H W)\")\n assert glyphs_rep.shape[0] == T * B\n\n crop_rep = self.extract_crop_representation(crop_emb)\n crop_rep = rearrange(crop_rep, \"B C H W -> B (C H W)\")\n assert crop_rep.shape[0] == T * B\n\n st = torch.cat([glyphs_rep, crop_rep], dim=1)\n \n \n return st\n\n\nclass MessageEncoder(nn.Module):\n \"\"\"This model encodes the the topline message into a fixed size representation.\n\n It works by using a learnt embedding for each character before passing the\n embeddings through 6 CNN layers.\n\n Inspired by Zhang et al, 2016\n Character-level Convolutional Networks for Text Classification\n https://arxiv.org/abs/1509.01626\n \"\"\"\n\n def __init__(self, hidden_dim, embedding_dim, device=None):\n super(MessageEncoder, self).__init__()\n\n self.hidden_dim = hidden_dim\n self.msg_edim = embedding_dim\n\n self.char_lt = nn.Embedding(NUM_CHARS, self.msg_edim, padding_idx=PAD_CHAR)\n self.conv1 = nn.Conv1d(self.msg_edim, self.hidden_dim, kernel_size=7)\n self.conv2_6_fc = nn.Sequential(\n nn.ReLU(),\n nn.MaxPool1d(kernel_size=3, stride=3),\n # conv2\n nn.Conv1d(self.hidden_dim, self.hidden_dim, kernel_size=7),\n nn.ReLU(),\n nn.MaxPool1d(kernel_size=3, stride=3),\n # conv3\n nn.Conv1d(self.hidden_dim, self.hidden_dim, kernel_size=3),\n nn.ReLU(),\n # conv4\n nn.Conv1d(self.hidden_dim, self.hidden_dim, kernel_size=3),\n nn.ReLU(),\n # conv5\n nn.Conv1d(self.hidden_dim, self.hidden_dim, kernel_size=3),\n nn.ReLU(),\n # conv6\n nn.Conv1d(self.hidden_dim, self.hidden_dim, kernel_size=3),\n nn.ReLU(),\n nn.MaxPool1d(kernel_size=3, stride=3),\n # fc receives -- [ B x h_dim x 5 ]\n Flatten(),\n nn.Linear(5 * self.hidden_dim, 2 * self.hidden_dim),\n nn.ReLU(),\n nn.Linear(2 * self.hidden_dim, self.hidden_dim),\n ) # final output -- [ B x h_dim x 5 ]\n\n def forward(self, message):\n T, B, *_ = message.shape\n messages = message.long().reshape(T * B, -1)\n # [ T * B x E x 256 ]\n char_emb = self.char_lt(messages).transpose(1, 2)\n char_rep = self.conv2_6_fc(self.conv1(char_emb))\n return char_rep\n\n\nclass BLStatsEncoder(nn.Module):\n \"\"\"This model encodes the bottom line stats into a fixed size representation.\n\n It works by simply using two fully-connected layers with ReLU activations.\n \"\"\"\n\n def __init__(self, num_features, hidden_dim):\n super(BLStatsEncoder, self).__init__()\n self.num_features = num_features\n self.hidden_dim = hidden_dim\n self.embed_features = nn.Sequential(\n nn.Linear(self.num_features, self.hidden_dim),\n nn.ReLU(),\n nn.Linear(self.hidden_dim, self.hidden_dim),\n nn.ReLU(),\n )\n\n def forward(self, blstats):\n T, B, *_ = blstats.shape\n\n features = blstats\n # -- [B' x F]\n #features = features.reshape(T * B, -1).float()\n features = features.reshape(T * B, -1).float()\n # -- [B x K]\n features_emb = self.embed_features(features)\n\n assert features_emb.shape[0] == T * B\n return features_emb\n\n\nclass Crop(nn.Module):\n def __init__(self, height, width, height_target, width_target, device=None):\n super(Crop, self).__init__()\n self.width = width\n self.height = height\n self.width_target = width_target\n self.height_target = height_target\n\n width_grid = self._step_to_range(2 / (self.width - 1), self.width_target)\n self.width_grid = width_grid[None, :].expand(self.height_target, -1)\n\n height_grid = self._step_to_range(2 / (self.height - 1), height_target)\n self.height_grid = height_grid[:, None].expand(-1, self.width_target)\n\n \"\"\"\n if device is not None:\n self.width_grid = self.width_grid.to(device)\n self.height_grid = self.height_grid.to(device)\n \"\"\"\n \n def _step_to_range(self, step, num_steps):\n return torch.tensor([step * (i - num_steps // 2) for i in range(num_steps)])\n\n def forward(self, inputs, coordinates):\n \"\"\"Calculates centered crop around given x,y coordinates.\n\n Args:\n inputs [B x H x W] or [B x C x H x W]\n coordinates [B x 2] x,y coordinates\n\n Returns:\n [B x C x H' x W'] inputs cropped and centered around x,y coordinates.\n \"\"\"\n if inputs.dim() == 3:\n inputs = inputs.unsqueeze(1).float()\n\n assert inputs.shape[2] == self.height, \"expected %d but found %d\" % (\n self.height,\n inputs.shape[2],\n )\n assert inputs.shape[3] == self.width, \"expected %d but found %d\" % (\n self.width,\n inputs.shape[3],\n )\n\n self.width_grid = self.width_grid.to(inputs.get_device())\n self.height_grid = self.height_grid.to(inputs.get_device())\n\n x = coordinates[:, 0]\n y = coordinates[:, 1]\n\n x_shift = 2 / (self.width - 1) * (x.float() - self.width // 2)\n y_shift = 2 / (self.height - 1) * (y.float() - self.height // 2)\n\n grid = torch.stack(\n [\n self.width_grid[None, :, :] + x_shift[:, None, None],\n self.height_grid[None, :, :] + y_shift[:, None, None],\n ],\n dim=3,\n )\n\n crop = torch.round(F.grid_sample(inputs, grid, align_corners=True)).squeeze(1)\n return crop\n\n\nclass Flatten(nn.Module):\n def forward(self, input):\n return input.reshape(input.size(0), -1)\n",
"## This file is intended to emulate the evaluation on AIcrowd\n\n# IMPORTANT - Differences to expect\n# * All the environment's functions are not available\n# * The run might be slower than your local run\n# * Resources might vary from your local machine\n\nimport numpy as np\n\nfrom submission_config import SubmissionConfig, TestEvaluationConfig\n\nfrom rollout import run_batched_rollout\nfrom envs.batched_env import BatchedEnv\n\n\ndef evaluate():\n env_make_fn = SubmissionConfig.MAKE_ENV_FN\n num_envs = SubmissionConfig.NUM_ENVIRONMENTS\n Agent = SubmissionConfig.AGENT\n\n num_episodes = TestEvaluationConfig.NUM_EPISODES\n\n batched_env = BatchedEnv(env_make_fn=env_make_fn, num_envs=num_envs)\n\n agent = Agent(num_envs, batched_env.num_actions)\n\n ascensions, scores = run_batched_rollout(num_episodes, batched_env, agent)\n print(\n f\"Ascensions: {ascensions} \"\n f\"Median Score: {np.median(scores)}, \"\n f\"Mean Score: {np.mean(scores)}\"\n )\n\n\nif __name__ == \"__main__\":\n evaluate()\n"
] |
[
[
"torch.nn.functional.softmax",
"torch.cat",
"torch.zeros",
"torch.load",
"torch.nn.ELU",
"torch.sum",
"torch.nn.Embedding",
"torch.no_grad",
"torch.nn.MultiheadAttention",
"torch.sqrt",
"torch.nn.MaxPool1d",
"torch.nn.Sequential",
"torch.nn.Conv2d",
"torch.unsqueeze",
"torch.nn.Linear",
"torch.nn.Conv1d",
"torch.stack",
"torch.Tensor",
"torch.nn.LSTM",
"torch.nn.functional.grid_sample",
"torch.nn.ReLU",
"torch.argmax"
],
[
"numpy.median",
"numpy.mean"
]
] |
amirshnll/Wine
|
[
"673c879bbea6d0b5313f52f028ea983d0807830c"
] |
[
"knn.py"
] |
[
"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\n# Author : Amir Shokri\n# github link : https://github.com/amirshnll/Wine\n# dataset link : http://archive.ics.uci.edu/ml/datasets/Wine\n# email : [email protected]\n\n\n# In[1]:\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\n\n\n# In[2]:\n\n\n\ncol_names = ['class', 'Alcohol', 'Malic acid', 'Ash', 'Alcalinity of ash', 'Magnesium', 'Total phenols', 'Flavanoids', ' Nonflavanoid phenols','Proanthocyanins','Color intensity','Hue','OD280/OD315 of diluted wines','Proline']\nwine =pd.read_csv(\"wine.csv\",header=None, names=col_names)\n\n\n# In[3]:\n\n\nwine.head()\n\n\n# In[4]:\n\n\ninputs =wine.drop('class',axis='columns')\ntarget = wine['class']\n\n\n# In[5]:\n\n\ninputs\n\n\n# In[6]:\n\n\nX_train, X_test, y_train, y_test = train_test_split(inputs, target, test_size=0.3)\n\n\n# In[15]:\n\n\n\nfrom sklearn.neighbors import KNeighborsClassifier\nk=[1,3,5,7,9]\nfor i in range(len(k)):\n \n knn = KNeighborsClassifier(n_neighbors=k[i])\n\n \n knn.fit(X_train, y_train)\n\n \n y_pred = knn.predict(X_test)\n\n from sklearn import metrics\n print(\"Accuracy for k = \",k[i],\" : \",metrics.accuracy_score(y_test, y_pred))\n\n\n# In[64]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n"
] |
[
[
"pandas.read_csv",
"sklearn.metrics.accuracy_score",
"sklearn.model_selection.train_test_split",
"sklearn.neighbors.KNeighborsClassifier"
]
] |
nils-werner/pytorch-lightning
|
[
"f36b395c4eb4c8d113954d768444194b3729be28"
] |
[
"tests/utilities/test_auto_restart.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.\nimport math\nimport os\nimport random\nimport random as python_random\nfrom collections import defaultdict\nfrom collections.abc import Iterable\nfrom contextlib import suppress\nfrom copy import deepcopy\nfrom dataclasses import asdict\nfrom typing import List, Optional\nfrom unittest import mock\nfrom unittest.mock import ANY\n\nimport numpy as np\nimport pytest\nimport torch\nimport torch.distributed as dist\nimport torch.multiprocessing as mp\nfrom torch.utils.data import BatchSampler, DistributedSampler, RandomSampler, SequentialSampler\nfrom torch.utils.data._utils.worker import get_worker_info\nfrom torch.utils.data.dataloader import DataLoader, default_collate\nfrom torch.utils.data.dataset import Dataset, IterableDataset\n\nimport tests.helpers.utils as tutils\nfrom pytorch_lightning import Callback, LightningModule, seed_everything, Trainer\nfrom pytorch_lightning.trainer.states import TrainerState\nfrom pytorch_lightning.utilities.auto_restart import (\n _add_capture_metadata_collate,\n _dataloader_load_state_dict,\n _dataloader_to_state_dict,\n _MultiProcessingDataLoaderIterStateful,\n _patch_dataloader_get_iterators,\n _reload_dataloader_state_dict,\n _rotate_worker_indices,\n _SingleProcessDataLoaderIterStateful,\n _SupportsStateDict,\n _teardown_dataloader_get_iterators,\n CaptureIterableDataset,\n CaptureMapDataset,\n FastForwardSampler,\n MergedIteratorState,\n)\nfrom pytorch_lightning.utilities.enums import _FaultTolerantMode, AutoRestartBatchKeys\nfrom pytorch_lightning.utilities.exceptions import ExitGracefullyException, MisconfigurationException\nfrom pytorch_lightning.utilities.fetching import DataFetcher\nfrom pytorch_lightning.utilities.imports import _fault_tolerant_training\nfrom tests.helpers.boring_model import BoringModel, RandomDataset\nfrom tests.helpers.runif import RunIf\n\n\n# Credit to PyTorch Team.\n# Taken from:\n# https://github.com/pytorch/pytorch/blob/3b977a0d2834d300c0301a0c6af98c8e939019ce/torch/utils/data/_utils/worker.py#L151\n# Not available until torch 1.9.0\ndef _generate_state(base_seed, worker_id):\n INIT_A = 0x43B0D7E5\n MULT_A = 0x931E8875\n INIT_B = 0x8B51F9DD\n MULT_B = 0x58F38DED\n MIX_MULT_L = 0xCA01F9DD\n MIX_MULT_R = 0x4973F715\n XSHIFT = 4 * 8 // 2\n MASK32 = 0xFFFFFFFF\n\n entropy = [worker_id, base_seed & MASK32, base_seed >> 32, 0]\n pool = [0] * 4\n\n hash_const_A = INIT_A\n\n def hash(value):\n nonlocal hash_const_A\n value = (value ^ hash_const_A) & MASK32\n hash_const_A = (hash_const_A * MULT_A) & MASK32\n value = (value * hash_const_A) & MASK32\n value = (value ^ (value >> XSHIFT)) & MASK32\n return value\n\n def mix(x, y):\n result_x = (MIX_MULT_L * x) & MASK32\n result_y = (MIX_MULT_R * y) & MASK32\n result = (result_x - result_y) & MASK32\n result = (result ^ (result >> XSHIFT)) & MASK32\n return result\n\n # Add in the entropy to the pool.\n for i in range(len(pool)):\n pool[i] = hash(entropy[i])\n\n # Mix all bits together so late bits can affect earlier bits.\n for i_src in range(len(pool)):\n for i_dst in range(len(pool)):\n if i_src != i_dst:\n pool[i_dst] = mix(pool[i_dst], hash(pool[i_src]))\n\n hash_const_B = INIT_B\n state = []\n for i_dst in range(4):\n data_val = pool[i_dst]\n data_val = (data_val ^ hash_const_B) & MASK32\n hash_const_B = (hash_const_B * MULT_B) & MASK32\n data_val = (data_val * hash_const_B) & MASK32\n data_val = (data_val ^ (data_val >> XSHIFT)) & MASK32\n state.append(data_val)\n return state\n\n\ndef test_fast_forward_getattr():\n dataset = range(15)\n sampler = SequentialSampler(dataset)\n batch_sampler = BatchSampler(sampler, 3, False)\n index_batch_sampler = FastForwardSampler(batch_sampler)\n\n assert index_batch_sampler.batch_size == 3\n assert index_batch_sampler.sampler == sampler\n\n\ndef test_fast_forward_on_batch_sampler():\n \"\"\"This test ensures ``FastForwardSampler`` applied to ``BatchSampler`` correctly retrived the right next batch\n on restart.\"\"\"\n dataset = range(15)\n sampler = SequentialSampler(dataset)\n batch_sampler = BatchSampler(sampler, 3, False)\n index_batch_sampler = FastForwardSampler(batch_sampler)\n\n assert isinstance(index_batch_sampler, Iterable)\n\n index_batch_sampler_iter = iter(index_batch_sampler)\n\n assert next(index_batch_sampler_iter) == [0, 1, 2]\n assert next(index_batch_sampler_iter) == [3, 4, 5]\n\n state_dict = index_batch_sampler.state_dict(2)\n\n index_batch_sampler = FastForwardSampler(batch_sampler)\n index_batch_sampler.load_state_dict(state_dict)\n\n index_batch_sampler_iter = iter(index_batch_sampler)\n assert next(index_batch_sampler_iter) == [6, 7, 8]\n\n\ndef test_fast_forward_on_sequential_sampler():\n \"\"\"This test ensures ``FastForwardSampler`` applied to ``SequentialSampler`` correctly retrived the right next\n batch on restart.\"\"\"\n dataset = range(15)\n sequential_sampler = SequentialSampler(dataset)\n sampler = FastForwardSampler(sequential_sampler)\n sampler.setup(3)\n batch_sampler = BatchSampler(sampler, 3, False)\n\n batch_sampler_iter = iter(batch_sampler)\n\n assert next(batch_sampler_iter) == [0, 1, 2]\n assert next(batch_sampler_iter) == [3, 4, 5]\n\n state_dict = sampler.state_dict(2)\n assert state_dict[0][\"current_iteration\"] == 6\n\n sampler.load_state_dict(state_dict)\n\n batch_sampler_iter = iter(batch_sampler)\n assert next(batch_sampler_iter) == [6, 7, 8]\n\n\[email protected](torch.cuda.is_available(), reason=\"todo (tchaton) Need more investigation\")\ndef test_fast_forward_on_random_sampler():\n \"\"\"This test ensures ``FastForwardSampler`` applied to ``RandomSampler`` correctly retrived the right next\n batch on restart.\"\"\"\n seed = 42\n seed_everything(42)\n\n dataset = range(15)\n generator = torch.Generator().manual_seed(seed)\n values = list(RandomSampler(dataset, generator=generator))\n\n generator = torch.Generator().manual_seed(seed)\n random_sampler = RandomSampler(dataset, generator=generator)\n sampler = FastForwardSampler(random_sampler)\n sampler.setup(3)\n batch_sampler = BatchSampler(sampler, 3, False)\n\n batch_sampler_iter = iter(batch_sampler)\n\n assert next(batch_sampler_iter) == values[:3]\n assert next(batch_sampler_iter) == values[3:6]\n assert next(batch_sampler_iter) == values[6:9]\n\n state_dict = sampler.state_dict(3)\n assert state_dict[0][\"current_iteration\"] == 9\n state_dict[0][\"current_iteration\"] = 6\n\n seed_everything(42)\n generator = torch.Generator().manual_seed(seed)\n random_sampler = RandomSampler(dataset, generator=generator)\n sampler = FastForwardSampler(random_sampler)\n sampler.setup(3)\n batch_sampler = BatchSampler(sampler, 3, False)\n sampler.load_state_dict(state_dict)\n\n batch_sampler_iter = iter(batch_sampler)\n assert next(batch_sampler_iter) == values[6:9]\n has_raised = False\n try:\n for _ in range(5):\n next(batch_sampler_iter)\n except StopIteration:\n has_raised = True\n assert sampler._current_iteration == 0\n sampler.load_state_dict(sampler.state_dict(0))\n assert has_raised\n\n\nclass RangeIterableDataset(IterableDataset):\n def __init__(self, data, num_workers: int, batch_size: int, state_dict=None, attr_name: str = \"iter_sampler\"):\n self.data = list(data)\n self.batch_size = batch_size\n self.num_workers = num_workers\n self.state_dict = state_dict\n self.attr_name = attr_name\n\n def __iter__(self):\n worker_info = get_worker_info()\n if worker_info and self.num_workers == 2:\n id = worker_info.id\n num_samples = len(self.data)\n if id == 0:\n self.data = list(self.data)[: num_samples // 2]\n else:\n self.data = list(self.data)[num_samples // 2 :]\n self.user_sampler = RandomSampler(self.data)\n else:\n self.user_sampler = RandomSampler(self.data)\n\n setattr(self, self.attr_name, iter(self.user_sampler))\n return self\n\n def __next__(self):\n iter_sampler = getattr(self, self.attr_name)\n return self.data[next(iter_sampler)]\n\n\[email protected](os.environ, {\"PL_FAULT_TOLERANT_TRAINING\": \"1\"})\[email protected](torch.cuda.is_available(), reason=\"This test takes around 30 sec and should be skipped in Azure CI\")\[email protected](\"num_workers\", [0, 1, 2])\[email protected](os.environ, {\"PL_FAULT_TOLERANT_TRAINING\": \"1\"})\ndef test_fast_forward_sampler_over_iterable_dataset(num_workers):\n \"\"\"This test ensures ``FastForwardSampler`` and ``CaptureIterableDataset`` are properly being used to capture\n workers states.\"\"\"\n batch_size = 3\n initial_seed = seed_everything(42)\n generator = torch.Generator()\n generator.manual_seed(initial_seed)\n dataset = RangeIterableDataset(range(20), num_workers, batch_size, True)\n dataset = CaptureIterableDataset(dataset)\n\n dataloader = DataLoader(dataset, batch_size=batch_size, num_workers=num_workers, generator=generator)\n _add_capture_metadata_collate(dataloader)\n\n iter_dataloader = iter(dataloader)\n batches = []\n for _ in range(5):\n batches.append(next(iter_dataloader))\n\n # restarting on batch_1 and getting 3 extra batches\n\n state_dict = {\"iter_sampler\": {}}\n for batch in batches[:2]:\n batch, _state_dict = batch[\"data\"], batch[AutoRestartBatchKeys.PL_RESTART_META]\n for k, v in _state_dict.items():\n state_dict[k].update(v)\n\n assert len(state_dict[\"iter_sampler\"]) == (num_workers if num_workers > 1 else 1)\n\n initial_seed = seed_everything(42)\n generator.manual_seed(initial_seed)\n dataset = RangeIterableDataset(range(20), num_workers, batch_size, state_dict=state_dict)\n dataset = CaptureIterableDataset(dataset)\n dataset.load_state_dict(state_dict)\n dataloader = DataLoader(dataset, batch_size=batch_size, num_workers=num_workers, generator=generator)\n _add_capture_metadata_collate(dataloader)\n\n iter_dataloader = iter(dataloader)\n batches_restart = []\n for _ in range(3):\n batches_restart.append(next(iter_dataloader))\n\n assert torch.equal(batches_restart[0][\"data\"], batches[2][\"data\"])\n assert torch.equal(batches_restart[1][\"data\"], batches[3][\"data\"])\n assert torch.equal(batches_restart[2][\"data\"], batches[4][\"data\"])\n\n\ndef _setup_ddp(rank, worldsize):\n os.environ[\"MASTER_ADDR\"] = \"localhost\"\n\n # initialize the process group\n dist.init_process_group(\"gloo\", rank=rank, world_size=worldsize)\n\n\ndef _test_fast_forward_sampler_with_distributed_sampler(rank, worldsize):\n _setup_ddp(rank, worldsize)\n\n initial_seed = seed_everything(42)\n\n generator = torch.Generator()\n generator.manual_seed(initial_seed)\n\n num_workers = 2\n batch_size = 4\n\n dataset = range(30)\n sampler = FastForwardSampler(DistributedSampler(dataset, num_replicas=worldsize, rank=rank, seed=initial_seed))\n sampler.setup(batch_size)\n dataloader = DataLoader(\n dataset, batch_size=batch_size, num_workers=num_workers, generator=generator, sampler=sampler\n )\n\n iter_dataloader = iter(dataloader)\n\n num_yielded = 0\n batches = []\n while True:\n try:\n batches.append(next(iter_dataloader))\n num_yielded += 1\n except StopIteration:\n break\n\n expected = torch.tensor([17, 27, 24]) if rank == 0 else torch.tensor([19, 5, 3])\n assert torch.equal(batches[-1], expected)\n\n assert sampler.state_dict(num_yielded)[0][\"current_iteration\"] == 16\n\n reload_state_dict = sampler.state_dict(num_yielded - 1)\n assert reload_state_dict[0][\"current_iteration\"] == 12\n\n sampler = FastForwardSampler(DistributedSampler(dataset, num_replicas=worldsize, rank=rank, seed=initial_seed))\n sampler.setup(batch_size)\n sampler.load_state_dict(reload_state_dict)\n dataloader = DataLoader(\n dataset, batch_size=batch_size, num_workers=num_workers, generator=generator, sampler=sampler\n )\n\n iter_dataloader = iter(dataloader)\n\n batches = []\n while True:\n try:\n batches.append(next(iter_dataloader))\n except StopIteration:\n break\n\n assert torch.equal(batches[-1], expected)\n assert sampler.state_dict(num_yielded)[0][\"current_iteration\"] == 16\n\n\[email protected](torch.cuda.is_available(), reason=\"This test takes around 25 sec and should be skipped in Azure CI\")\n@RunIf(skip_windows=True)\ndef test_fast_forward_sampler_with_distributed_sampler():\n \"\"\"Make sure result logging works with DDP.\"\"\"\n tutils.set_random_main_port()\n worldsize = 2\n mp.spawn(_test_fast_forward_sampler_with_distributed_sampler, args=(worldsize,), nprocs=worldsize)\n\n\nclass MetaLearningDataset(IterableDataset):\n def __init__(\n self,\n dataset: Dataset,\n batch_size: int,\n drop_last: bool,\n task_num_classes: int = 5,\n num_workers: Optional[int] = None,\n global_rank: Optional[int] = None,\n world_size: Optional[int] = None,\n initial_seed: Optional[int] = None,\n shuffle: bool = True,\n debugging: bool = False,\n ):\n self.dataset = dataset\n self.batch_size = batch_size\n self.drop_last = drop_last\n self.num_workers = num_workers or 1\n self.global_rank = global_rank\n self.world_size = world_size\n self.task_num_classes = task_num_classes\n self.labels = labels = getattr(dataset, \"labels\")\n self.initial_seed = initial_seed\n self.generator: Optional[torch.Generator] = None\n self.current_task_iteration = 0\n self.shuffle = shuffle\n self.debugging = debugging\n\n if labels is None:\n raise MisconfigurationException(f\"Provided {self.dataset} should have an attribute labels.\")\n\n if len(labels) != len(dataset):\n raise MisconfigurationException(\"Found provided ``labels`` don't match the dataset length.\")\n\n if (isinstance(global_rank, int) and world_size is None) or (\n isinstance(world_size, int) and global_rank is None\n ):\n raise MisconfigurationException(\"Both ``world_size`` and ``global_rank`` should be provided !\")\n\n self.unique_labels = np.unique(self.labels)\n\n @property\n def worker_id(self) -> int:\n worker_info = get_worker_info()\n return worker_info.id if worker_info else 0\n\n @property\n def is_distributed(self) -> bool:\n return self.world_size is not None and self.world_size > 1\n\n def set_seed(self, shared: bool = False):\n initial_seed = self.initial_seed + self.current_task_iteration\n if shared:\n seed = initial_seed\n np_seed = _generate_state(initial_seed, 0)\n else:\n seed = initial_seed + self.worker_id + self.global_rank + self.current_task_iteration\n np_seed = _generate_state(initial_seed, self.worker_id + self.global_rank)\n\n random.seed(seed)\n torch.manual_seed(seed)\n np.random.seed(np_seed)\n\n def sample_task_indices(self):\n self.set_seed(shared=True)\n self.selected_indexes = np.random.choice(self.unique_labels, self.task_num_classes, replace=False)\n self.selected_indexes.sort()\n\n # subset of indices from the entire dataset where the labels are actually among the\n # task_num_classes selected_indexes\n\n self.task_indices = np.arange(len(self.dataset))[np.in1d(self.labels, self.selected_indexes)]\n self.task_length = len(self.task_indices)\n self.set_seed(shared=False)\n\n @property\n def worker_rank(self) -> int:\n worker_id = self.worker_id\n is_global_zero = self.global_rank == 0\n return self.global_rank + worker_id + int(not is_global_zero)\n\n def create_sampler(self):\n data = range(self.task_length)\n if self.world_size == 1 and self.num_workers in (0, 1):\n if self.shuffle:\n self.sampler = RandomSampler(data, generator=self.generator)\n else:\n self.sampler = SequentialSampler(data)\n else:\n num_workers = 1 if self.num_workers in (None, 0) else self.num_workers\n num_replicas = num_workers * self.world_size\n current_seed = self.initial_seed + self.current_task_iteration\n self.sampler = DistributedSampler(\n data, num_replicas=num_replicas, rank=self.worker_rank, shuffle=self.shuffle, seed=current_seed\n )\n\n def __iter__(self):\n if self.generator is None:\n self.generator = torch.Generator().manual_seed(self.initial_seed)\n self.sample_task_indices()\n self.create_sampler()\n self.batch_sampler = BatchSampler(self.sampler, batch_size=self.batch_size, drop_last=self.drop_last)\n self.iter_sampler = iter(self.batch_sampler)\n self.is_first_batch = True\n self.current_task_iteration += 1\n return self\n\n def increment_iteration(self):\n self.current_task_iteration += 1\n\n def __next__(self):\n # this is optional, but useful to accumulate gradient over the entire task.\n is_first_batch = self.is_first_batch if self.debugging else (self.is_first_batch and self.worker_id == 0)\n if is_first_batch:\n self.is_first_batch = False\n return {\"task_length\": len(self.batch_sampler), \"selected_indexes\": self.selected_indexes}\n\n random_indices = next(self.iter_sampler)\n task_indices = [self.task_indices[idx] for idx in random_indices]\n return default_collate([self.dataset[idx] for idx in task_indices])\n\n\nclass ClassificationDataset(Dataset):\n def __init__(self, inputs, labels):\n self.inputs = inputs\n self.labels = labels\n assert len(self.inputs) == len(self.labels)\n\n def __getitem__(self, index):\n return (self.inputs[index], self.labels[index])\n\n def __len__(self):\n return len(self.inputs)\n\n\ndef _test_fast_forward_sampler_with_distributed_sampler_and_iterative_dataset(rank, worldsize):\n if worldsize > 1:\n _setup_ddp(rank, worldsize)\n\n def all_gather(tensor, world_size):\n tensor_list = [torch.zeros_like(tensor, dtype=torch.int64) for _ in range(world_size)]\n torch.distributed.all_gather(tensor_list, tensor)\n return tensor_list\n\n initial_seed = seed_everything(42)\n\n generator = torch.Generator()\n generator.manual_seed(initial_seed)\n\n num_workers = 2\n batch_size = 4\n dataset_length = 60\n num_classes = 10\n\n labels = np.random.randint(0, num_classes, dataset_length)\n\n dataset = ClassificationDataset(range(dataset_length), labels)\n dataset = MetaLearningDataset(\n dataset,\n batch_size=batch_size,\n drop_last=True,\n num_workers=num_workers,\n global_rank=rank,\n world_size=worldsize,\n initial_seed=initial_seed,\n debugging=True,\n shuffle=True,\n )\n dataset = CaptureIterableDataset(dataset)\n dataloader = DataLoader(dataset, num_workers=num_workers, batch_size=1, generator=generator)\n _add_capture_metadata_collate(dataloader)\n\n epoch_results = []\n for _ in range(2):\n iter_dataloader = iter(dataloader)\n batches = []\n while True:\n try:\n batches.append(next(iter_dataloader))\n except StopIteration:\n break\n epoch_results.append(batches)\n dataloader.dataset.dataset.current_task_iteration += 1\n\n assert len(epoch_results) == 2\n\n assert len(epoch_results[0]) == math.ceil((dataset_length / (num_workers * worldsize)) / batch_size) + 2\n\n if worldsize == 1:\n assert epoch_results[0][0][\"data\"][\"task_length\"] == epoch_results[0][1][\"data\"][\"task_length\"]\n assert torch.equal(\n epoch_results[0][0][\"data\"][\"selected_indexes\"], epoch_results[0][1][\"data\"][\"selected_indexes\"]\n )\n assert 0 in epoch_results[0][2][AutoRestartBatchKeys.PL_RESTART_META][\"iter_sampler\"] # worker id 0\n assert 1 in epoch_results[0][3][AutoRestartBatchKeys.PL_RESTART_META][\"iter_sampler\"] # worker id 1\n assert not torch.equal(epoch_results[0][2][\"data\"][0], epoch_results[0][3][\"data\"][0])\n else:\n first_task_metadata = all_gather(epoch_results[0][0][\"data\"][\"task_length\"], worldsize)\n second_task_metadata = all_gather(epoch_results[0][1][\"data\"][\"task_length\"], worldsize)\n assert torch.equal(first_task_metadata[0], first_task_metadata[1])\n assert torch.equal(second_task_metadata[0], second_task_metadata[1])\n assert torch.equal(first_task_metadata[0], second_task_metadata[1])\n\n first_batch_list = all_gather(epoch_results[0][2][\"data\"][0], worldsize)\n assert not torch.equal(first_batch_list[0], first_batch_list[1])\n second_batch_list = all_gather(epoch_results[0][3][\"data\"][0], worldsize)\n assert not torch.equal(second_batch_list[0], second_batch_list[1])\n\n # restarting on epoch 0 / real batch 2\n state_dict = {\"iter_sampler\": {}}\n for batch in epoch_results[0][2:4]:\n batch, _state_dict = batch[\"data\"], batch[AutoRestartBatchKeys.PL_RESTART_META]\n for k, v in _state_dict.items():\n state_dict[k].update(v)\n\n dataset = ClassificationDataset(range(dataset_length), labels)\n dataset = MetaLearningDataset(\n dataset,\n batch_size=batch_size,\n drop_last=True,\n num_workers=num_workers,\n global_rank=rank,\n world_size=worldsize,\n initial_seed=initial_seed,\n debugging=True,\n shuffle=True,\n )\n\n dataset = CaptureIterableDataset(dataset)\n dataset.load_state_dict(state_dict)\n dataloader = DataLoader(dataset, num_workers=num_workers, batch_size=1, generator=generator)\n _add_capture_metadata_collate(dataloader)\n\n epoch_results_restart = []\n for _ in range(2):\n iter_dataloader = iter(dataloader)\n batches = []\n while True:\n try:\n batches.append(next(iter_dataloader))\n except StopIteration:\n break\n epoch_results_restart.append(batches)\n dataloader.dataset.dataset.increment_iteration()\n dataloader.dataset.reset_on_epoch()\n\n assert len(epoch_results_restart[0]) + 2 == len(epoch_results[0])\n epoch_tensors = [e[\"data\"][0] for e in epoch_results[0][4:]]\n epoch_tensors_restart = [e[\"data\"][0] for e in epoch_results_restart[0][2:]]\n\n for t, tr in zip(epoch_tensors, epoch_tensors_restart):\n assert torch.equal(t, tr)\n\n epoch_tensors = [e[\"data\"][0] for e in epoch_results[1][2:]]\n epoch_tensors_restart = [e[\"data\"][0] for e in epoch_results_restart[1][2:]]\n\n for t, tr in zip(epoch_tensors, epoch_tensors_restart):\n assert torch.equal(t, tr)\n\n\[email protected](os.environ, {\"PL_FAULT_TOLERANT_TRAINING\": \"1\"})\[email protected](torch.cuda.is_available(), reason=\"This test takes around 45 sec and should be skipped in Azure CI\")\ndef test_fast_forward_sampler_iterative_dataset():\n _test_fast_forward_sampler_with_distributed_sampler_and_iterative_dataset(0, 1)\n\n\[email protected](os.environ, {\"PL_FAULT_TOLERANT_TRAINING\": \"1\"})\[email protected](torch.cuda.is_available(), reason=\"This test takes around 55 sec and should be skipped in Azure CI\")\n@RunIf(skip_windows=True)\ndef test_fast_forward_sampler_with_distributed_sampler_and_iterative_dataset():\n \"\"\"Make sure result logging works with DDP.\"\"\"\n tutils.set_random_main_port()\n worldsize = 2\n mp.spawn(\n _test_fast_forward_sampler_with_distributed_sampler_and_iterative_dataset, args=(worldsize,), nprocs=worldsize\n )\n\n\[email protected](os.environ, {\"PL_FAULT_TOLERANT_TRAINING\": \"1\"})\n@RunIf(max_torch=\"1.7\")\ndef test_fault_tolerant_not_supported():\n assert not _fault_tolerant_training()\n\n\ndef create_iterable_dataset(batch_size, num_workers, attr_name=\"iter_sampler\", wrap: bool = True):\n dataset = RangeIterableDataset(range(50), num_workers=num_workers, batch_size=batch_size, attr_name=attr_name)\n if wrap:\n dataset = CaptureIterableDataset(dataset)\n return dataset\n\n\ndef test_dataloader_to_state_dict_and_reload():\n \"\"\"\n Note: Those utilities are used only with DataLoader wrapping a ``mapping`` based dataset.\n \"\"\"\n\n def create_dataloader():\n dataset = range(50)\n batch_size = 8\n sampler = FastForwardSampler(SequentialSampler(dataset))\n sampler.setup(batch_size)\n\n return DataLoader(dataset, sampler=sampler, batch_size=batch_size)\n\n dataloader = create_dataloader()\n iter_dataloader = iter(dataloader)\n _ = next(iter_dataloader)\n _ = next(iter_dataloader)\n\n state_dict = _dataloader_to_state_dict(dataloader, iter_dataloader)\n assert state_dict == {\n \"num_workers\": 0,\n \"previous_worker\": None,\n 0: {\"current_iteration\": 16},\n }\n\n dataloader = create_dataloader()\n dataloader = _dataloader_load_state_dict(dataloader, state_dict)\n iter_dataloader = iter(dataloader)\n _ = next(iter_dataloader)\n\n state_dict = _dataloader_to_state_dict(dataloader, iter_dataloader)\n assert state_dict == {\n \"num_workers\": 0,\n \"previous_worker\": None,\n 0: {\"current_iteration\": 24},\n }\n\n\[email protected](\"use_fault_tolerant\", [\"0\", \"1\"])\ndef test_data_loading_wraps_dataset_and_samplers(use_fault_tolerant, tmpdir):\n \"\"\"This test ensures the dataset and sampler are properly wrapped when fault tolerant is enabled.\"\"\"\n\n class CustomBatchSampler(BatchSampler):\n pass\n\n dataset = range(50)\n\n class TestModel(BoringModel):\n def train_dataloader(self):\n return {\n \"a\": [\n DataLoader(create_iterable_dataset(3, 1, wrap=False), num_workers=0, batch_size=3),\n DataLoader(dataset, batch_size=8),\n DataLoader(\n dataset,\n batch_sampler=CustomBatchSampler(SequentialSampler(dataset), batch_size=8, drop_last=False),\n ),\n ],\n \"b\": DataLoader(\n create_iterable_dataset(2, num_workers=1, attr_name=\"custom_sampler\", wrap=False),\n num_workers=0,\n batch_size=2,\n ),\n }\n\n def training_step(self, batch, batch_idx):\n assert batch == {\n \"a\": [ANY, ANY, ANY],\n \"b\": ANY,\n }\n\n def validation_step(self, batch, batch_idx):\n assert isinstance(batch, torch.Tensor)\n\n validation_epoch_end = None\n\n class Check(Callback):\n def on_train_batch_start(self, trainer, *_) -> None:\n loaders = trainer.train_dataloader.loaders\n if use_fault_tolerant == \"1\":\n assert isinstance(loaders[\"a\"][0].loader.dataset, CaptureIterableDataset)\n assert isinstance(loaders[\"a\"][1].loader.sampler, FastForwardSampler)\n assert isinstance(loaders[\"a\"][1].loader.dataset, CaptureMapDataset)\n assert isinstance(loaders[\"a\"][2].loader.batch_sampler, FastForwardSampler)\n assert isinstance(loaders[\"a\"][2].loader.dataset, CaptureMapDataset)\n assert isinstance(loaders[\"b\"].loader.dataset, CaptureIterableDataset)\n else:\n assert isinstance(loaders[\"a\"][0].loader.dataset, RangeIterableDataset)\n assert isinstance(loaders[\"a\"][1].loader.sampler, SequentialSampler)\n assert not isinstance(loaders[\"a\"][1].loader.dataset, CaptureMapDataset)\n assert isinstance(loaders[\"a\"][2].loader.batch_sampler, CustomBatchSampler)\n assert not isinstance(loaders[\"a\"][2].loader.dataset, CaptureMapDataset)\n assert isinstance(loaders[\"b\"].loader.dataset, RangeIterableDataset)\n\n with mock.patch.dict(os.environ, {\"PL_FAULT_TOLERANT_TRAINING\": use_fault_tolerant}):\n model = TestModel()\n model.training_epoch_end = None\n trainer = Trainer(default_root_dir=tmpdir, max_epochs=1, limit_train_batches=1, callbacks=Check())\n trainer.fit(model)\n\n\nclass SequentialGetItemDataset(Dataset):\n def __init__(self, length, *_):\n self.len = length\n\n def __getitem__(self, index):\n return torch.tensor([index]).float()\n\n def __len__(self):\n return self.len\n\n\nclass RandomGetItemDataset(Dataset):\n \"\"\"A dataset with random elements generated using global rng from torch, numpy and python.\"\"\"\n\n def __init__(self, length, size):\n self.size = size\n self.len = length\n\n def __getitem__(self, index):\n t = torch.rand(self.size)\n n = torch.from_numpy(np.random.rand(self.size))\n p = torch.tensor([python_random.random() for _ in range(self.size)])\n sample = (index + (t + n + p) / 10).float()\n return sample\n\n def __len__(self):\n return self.len\n\n\n# TODO: test with `RandomGeneratorGetItemDataset`\[email protected](os.environ, {\"PL_FAULT_TOLERANT_TRAINING\": \"1\"})\[email protected](\n \"dataset_class\",\n [\n SequentialGetItemDataset,\n RandomGetItemDataset,\n # RandomGeneratorGetItemDataset,\n ],\n)\[email protected](\"num_workers\", [0])\[email protected](\"batch_size\", [1, 2, 3])\ndef test_dataset_rng_states_restart(dataset_class, num_workers, batch_size):\n \"\"\"Test that the sequence of batches coming from a random number generator continues with the correct sequence\n after reloading the state.\"\"\"\n\n def create_dataset_sampler():\n dset = CaptureMapDataset(dataset_class(16, 8))\n random_sampler = RandomSampler(dset, generator=torch.Generator())\n return dset, random_sampler\n\n def create_dataloader_sampler(dset, sampler):\n sampler = FastForwardSampler(sampler)\n sampler.setup(batch_size)\n dl = DataLoader(dset, num_workers=num_workers, sampler=sampler, batch_size=batch_size)\n _add_capture_metadata_collate(dl)\n return dl, sampler\n\n def fetch(fetcher, prefetch_iter, num_batches_fetched):\n batch, _ = next(prefetch_iter)\n\n state: List[MergedIteratorState] = fetcher.state\n assert len(state) == 1\n assert isinstance(state[0], MergedIteratorState)\n\n assert len(fetcher.dataloader_iter.cache_states) == 1\n if num_workers == 0:\n assert state[0].state[0].num_batches_fetched == num_batches_fetched\n return state\n\n dataset, random_sampler = create_dataset_sampler()\n dataloader, ff_sampler = create_dataloader_sampler(dataset, random_sampler)\n\n fetcher = DataFetcher()\n fetcher.setup(dataloader)\n prefetch_iter = iter(fetcher)\n\n # fetch 4 batches\n fetch(fetcher, prefetch_iter, 1)\n fetch(fetcher, prefetch_iter, 2)\n fetch(fetcher, prefetch_iter, 3)\n\n # (A) capture the state after fetching 4 batches\n state = fetch(fetcher, prefetch_iter, 4)\n state = deepcopy(state[0])\n\n # (B) simulate 2 additional batches\n batch05, _ = next(prefetch_iter)\n batch06, _ = next(prefetch_iter)\n\n # start reloading\n dataset, random_sampler = create_dataset_sampler()\n dataloader, ff_sampler = create_dataloader_sampler(dataset, random_sampler)\n\n # load the state dict saved at (A)\n ff_sampler.load_state_dict(state.sampler_states)\n dataset.load_state_dict(state.dataset_states, latest_worker_id=state.latest_worker_id, num_workers=num_workers)\n\n prefetcher = DataFetcher()\n prefetcher.setup(dataloader)\n prefetch_iter = iter(prefetcher)\n\n # fetch 2 random batches, these should match exactly the batches seen at (B)\n batch05_restart, _ = next(prefetch_iter)\n batch06_restart, _ = next(prefetch_iter)\n\n assert torch.equal(batch05, batch05_restart)\n assert torch.equal(batch06, batch06_restart)\n\n\nclass CustomException(Exception):\n pass\n\n\nclass SequentialIterableDataset(IterableDataset):\n def __init__(self, length, *_):\n self.len = length\n self.sampler = SequentialSampler(range(self.len))\n\n def __iter__(self):\n self.sampler_iter = iter(self.sampler)\n return self\n\n def __next__(self):\n indices = next(self.sampler_iter)\n return torch.tensor([indices]).float()\n\n\nclass SequentialDictIterableDataset(SequentialIterableDataset):\n def __next__(self):\n indices = next(self.sampler_iter)\n return {\"data\": torch.tensor([indices]).float()}\n\n\nclass TestModel(LightningModule):\n def __init__(self, fail_on_step: int = -1):\n super().__init__()\n self.layer = torch.nn.Linear(1, 2)\n self.seen_batches = []\n self.fail_on_step = fail_on_step\n\n def training_step(self, batch, batch_idx):\n if self.global_step == self.fail_on_step:\n raise CustomException()\n batch = batch[\"data\"] if isinstance(batch, dict) else batch\n self.seen_batches.append(torch.stack(batch) if isinstance(batch, list) else batch)\n loss = sum(self.layer(b).sum() for b in batch)\n return loss\n\n def configure_optimizers(self):\n return torch.optim.SGD(self.layer.parameters(), lr=0.1)\n\n\ndef _run_training(trainer_kwargs, dataset_classes, fail_on_step: int = -1, ckpt_path=None):\n seed_everything(1)\n train_dataloader = [\n DataLoader(dataset_class(3, 1), batch_size=1, num_workers=0) for dataset_class in dataset_classes\n ]\n train_dataloader = train_dataloader[0] if len(train_dataloader) == 1 else train_dataloader\n model = TestModel(fail_on_step=fail_on_step)\n trainer = Trainer(**trainer_kwargs)\n with suppress(CustomException):\n trainer.fit(model, train_dataloaders=train_dataloader, ckpt_path=ckpt_path)\n return model.seen_batches, model.parameters()\n\n\[email protected](os.environ, {\"PL_FAULT_TOLERANT_TRAINING\": \"1\"})\[email protected](\n \"dataset_classes\",\n [\n # single training dataset\n [RandomGetItemDataset],\n [SequentialIterableDataset],\n [SequentialDictIterableDataset],\n # multiple training datasets (combinded dataloader)\n [SequentialGetItemDataset, SequentialIterableDataset],\n [SequentialIterableDataset, SequentialIterableDataset],\n # [RandomGetItemDataset, RandomGetItemDataset], # TODO: support in the future\n ],\n)\[email protected](\"multiple_trainloader_mode\", [\"min_size\", \"max_size_cycle\"])\ndef test_dataset_rng_states_restart_with_lightning(tmpdir, dataset_classes, multiple_trainloader_mode):\n \"\"\"Test that the Trainer can resume from a failed run in the case of several types of datasets.\"\"\"\n trainer_kwargs = dict(\n default_root_dir=tmpdir,\n max_epochs=3,\n enable_progress_bar=False,\n enable_model_summary=False,\n multiple_trainloader_mode=multiple_trainloader_mode,\n )\n\n all_batches, weights0 = _run_training(trainer_kwargs, dataset_classes)\n all_batches = torch.stack(all_batches)\n assert len(all_batches) == 9\n\n # Simulate 1st failure\n complete_batches, _ = _run_training(trainer_kwargs, dataset_classes, fail_on_step=4)\n assert len(complete_batches) == 4\n\n checkpoint_path = os.path.join(tmpdir, \".pl_auto_save.ckpt\")\n assert os.path.exists(checkpoint_path)\n\n # Resume after failure\n resumed_batches, weights1 = _run_training(\n trainer_kwargs, dataset_classes, fail_on_step=-1, ckpt_path=checkpoint_path\n )\n assert len(resumed_batches) == 5\n\n # the resumed batches should match the batches of the successful training\n all_batches_resumed = torch.stack(complete_batches + resumed_batches)\n assert len(all_batches_resumed) == 9\n assert torch.equal(all_batches, all_batches_resumed)\n\n # the final weights of a resumed training should equal the weights of an uninterrupted training\n for w0, w1 in zip(weights0, weights1):\n assert w0 is not w1\n assert torch.allclose(w0, w1)\n\n\[email protected](os.environ, {\"PL_FAULT_TOLERANT_TRAINING\": \"1\"})\[email protected](\n [\"train_datasets\", \"val_datasets\"],\n [\n ([RandomGetItemDataset], [RandomGetItemDataset]),\n ([RandomGetItemDataset], [RandomGetItemDataset, RandomGetItemDataset]),\n ],\n)\[email protected](\n \"val_check_interval\",\n [\n pytest.param(\n 0.5,\n marks=pytest.mark.xfail(\n reason=(\n \"TODO: the `train_dataloader` random state overrides the validation state when restarting training\"\n )\n ),\n ),\n 1.0,\n ],\n)\ndef test_auto_restart_within_validation_loop(train_datasets, val_datasets, val_check_interval, tmpdir):\n n_val_dataloaders = len(val_datasets)\n stop_dataloader = n_val_dataloaders - 1\n stop_batch = 1\n\n class ValidationLoopTestModel(LightningModule):\n def __init__(self, should_fail):\n super().__init__()\n self.layer = torch.nn.Linear(1, 2)\n self.should_fail = should_fail\n self.training_batches = []\n self.validation_batches = defaultdict(list)\n\n def step(self, batch):\n return sum(self.layer(b).sum() for b in batch)\n\n def training_step(self, batch, batch_idx):\n self.training_batches.append(batch)\n return self.step(batch)\n\n def validation_step(self, batch, batch_idx, dataloader_idx=0):\n if self.should_fail and stop_dataloader == dataloader_idx and batch_idx == stop_batch:\n raise CustomException\n self.validation_batches[dataloader_idx].append(batch)\n return self.step(batch)\n\n def configure_optimizers(self):\n return torch.optim.SGD(self.layer.parameters(), lr=0.1)\n\n def train_dataloader(self):\n return [DataLoader(cls(4, 1)) for cls in train_datasets]\n\n def val_dataloader(self):\n return [DataLoader(cls(4, 1)) for cls in val_datasets]\n\n def run(should_fail, resume):\n if not resume:\n seed_everything(42)\n\n model = ValidationLoopTestModel(should_fail)\n\n ckpt_path = str(tmpdir / \".pl_auto_save.ckpt\") if resume else None\n trainer = Trainer(\n default_root_dir=tmpdir,\n max_epochs=1,\n val_check_interval=val_check_interval,\n num_sanity_val_steps=0,\n )\n if should_fail:\n with pytest.raises(CustomException):\n trainer.fit(model, ckpt_path=ckpt_path)\n else:\n trainer.fit(model, ckpt_path=ckpt_path)\n\n return model.training_batches, model.validation_batches\n\n total_train_batches, total_val_batches = run(should_fail=False, resume=False)\n pre_fail_train_batches, pre_fail_val_batches = run(should_fail=True, resume=False)\n post_fail_train_batches, post_fail_val_batches = run(should_fail=False, resume=True)\n\n torch.testing.assert_allclose(total_train_batches, pre_fail_train_batches + post_fail_train_batches)\n for k in total_val_batches:\n torch.testing.assert_allclose(total_val_batches[k], pre_fail_val_batches[k] + post_fail_val_batches[k])\n\n\nclass TestAutoRestartModelUnderSignal(BoringModel):\n def __init__(self, should_signal: bool, failure_on_step: bool, failure_on_training: bool, on_last_batch: bool):\n super().__init__()\n self.should_signal = should_signal\n self.failure_on_step = failure_on_step\n self.failure_on_training = failure_on_training\n self.on_last_batch = on_last_batch\n self.seen_train_batches = []\n\n def _signal(self):\n if self.should_signal:\n # simulate `os.kill(os.getpid(), signal.SIGUSR1)`\n self.trainer._terminate_gracefully = True\n\n def training_step(self, batch, batch_idx):\n self.seen_train_batches.append(batch)\n should_signal = self.trainer.fit_loop.epoch_loop._is_training_done if self.on_last_batch else batch_idx == 2\n if self.failure_on_step and self.failure_on_training and should_signal:\n self._signal()\n return super().training_step(batch, batch_idx)\n\n def validation_step(self, batch, batch_idx):\n should_signal = (\n self.trainer.fit_loop.epoch_loop.val_loop.epoch_loop.batch_progress.is_last_batch\n if self.on_last_batch\n else batch_idx == 2\n )\n if self.failure_on_step and not self.failure_on_training and should_signal:\n self._signal()\n return super().validation_step(batch, batch_idx)\n\n def training_epoch_end(self, outputs) -> None:\n if not self.failure_on_step and self.failure_on_training:\n self._signal()\n\n def validation_epoch_end(self, outputs) -> None:\n if not self.failure_on_step and not self.failure_on_training:\n self._signal()\n\n def train_dataloader(self):\n return DataLoader(RandomDataset(32, 4))\n\n def val_dataloader(self):\n return DataLoader(RandomDataset(32, 4))\n\n\ndef _fit_model(\n tmpdir, should_signal, val_check_interval, failure_on_step, failure_on_training, on_last_batch, status=None\n):\n seed_everything(42)\n model = TestAutoRestartModelUnderSignal(should_signal, failure_on_step, failure_on_training, on_last_batch)\n\n trainer_kwargs = dict(\n default_root_dir=tmpdir,\n max_epochs=1,\n limit_train_batches=4,\n limit_val_batches=4,\n val_check_interval=val_check_interval,\n num_sanity_val_steps=0,\n )\n\n trainer = Trainer(**trainer_kwargs)\n if should_signal:\n with pytest.raises(ExitGracefullyException, match=status):\n trainer.fit(model)\n else:\n trainer.fit(model)\n assert trainer._terminate_gracefully == should_signal\n\n return model\n\n\[email protected](\"on_last_batch\", [False, True])\[email protected](\"val_check_interval\", [0.5, 1.0])\[email protected](\"failure_on_training\", [False, True])\[email protected](\"failure_on_step\", [False, True])\[email protected](os.environ, {\"PL_FAULT_TOLERANT_TRAINING\": \"1\"})\n@RunIf(skip_windows=True)\ndef test_auto_restart_under_signal(on_last_batch, val_check_interval, failure_on_training, failure_on_step, tmpdir):\n \"\"\"This test asserts that if a signal is being sent during the training / validation phase, the model should\n restart in a reproducible way.\"\"\"\n\n model_total = _fit_model(tmpdir, False, val_check_interval, failure_on_step, failure_on_training, on_last_batch)\n\n if failure_on_step:\n if on_last_batch:\n if failure_on_training:\n # Breaking on first validation batch.\n # This is done to capture the random state of the validation dataloader.\n status = \"EvaluationEpochLoop:advance\"\n else:\n # when breaking on last batch of validation, we should exist on `run_end` val_check_interval == 1.0\n status = (\n \"TrainingEpochLoop:on_run_end\" if val_check_interval == 1.0 else \"TrainingEpochLoop:on_advance_end\"\n )\n else:\n status = \"TrainingEpochLoop:on_advance_end\" if failure_on_training else \"EvaluationEpochLoop:advance\"\n else:\n if val_check_interval == 1.0:\n status = \"TrainingEpochLoop:on_run_end\"\n else:\n # `training_epoch_end` happens after `validation_epoch_end` since Lightning v1.4\n status = \"TrainingEpochLoop:on_run_end\" if failure_on_training else \"TrainingEpochLoop:on_advance_end\"\n\n model_signaled = _fit_model(\n tmpdir, True, val_check_interval, failure_on_step, failure_on_training, on_last_batch, status=status\n )\n checkpoint_path = str(tmpdir / \".pl_auto_save.ckpt\")\n assert os.path.exists(checkpoint_path)\n model_restarted = _fit_model(tmpdir, False, val_check_interval, failure_on_step, failure_on_training, on_last_batch)\n\n # check the batches\n actual = torch.cat(model_signaled.seen_train_batches + model_restarted.seen_train_batches)\n expected = torch.cat(model_total.seen_train_batches)\n assert torch.equal(actual, expected)\n\n # FIXME: why `on_last_batch` doesn't work ?\n if failure_on_step and failure_on_training and not on_last_batch:\n assert not torch.equal(model_total.layer.weight, model_signaled.layer.weight)\n assert torch.equal(model_restarted.layer.weight, model_total.layer.weight)\n\n checkpoint = torch.load(checkpoint_path)[\"loops\"][\"fit_loop\"]\n p = checkpoint[\"epoch_loop.batch_progress\"]\n if p[\"is_last_batch\"] and p[\"current\"][\"completed\"] == 4:\n assert \"dataloader_state_dict\" not in checkpoint[\"epoch_loop.state_dict\"]\n else:\n assert \"dataloader_state_dict\" in checkpoint[\"epoch_loop.state_dict\"]\n\n state_dict = checkpoint[\"epoch_loop.val_loop.epoch_loop.state_dict\"]\n p = checkpoint[\"epoch_loop.val_loop.epoch_loop.batch_progress\"]\n if (p[\"is_last_batch\"] and p[\"current\"][\"completed\"] == 4) or p[\"current\"][\"ready\"] == 0:\n assert \"dataloader_state_dict\" not in state_dict\n else:\n assert \"dataloader_state_dict\" in state_dict\n\n\ndef test_rotate_worker_indices():\n \"\"\"This test ensures `worker_id` are rotated properly depending on which one was the latest.\"\"\"\n state_dict = {0: 0, 1: 1}\n assert _rotate_worker_indices(state_dict, 0, 2) == {0: 1, 1: 0}\n assert _rotate_worker_indices(state_dict, 1, 2) == {0: 0, 1: 1}\n\n with pytest.raises(MisconfigurationException, match=\"The `latest_worker_id` should be within\"):\n _rotate_worker_indices(state_dict, 2, 2)\n\n with pytest.raises(MisconfigurationException, match=\"The `state` should contain\"):\n _rotate_worker_indices(state_dict, 2, 3)\n\n\ndef test_supports_state_dict_protocol():\n class StatefulClass:\n def state_dict(self):\n pass\n\n def load_state_dict(self, state_dict):\n pass\n\n assert isinstance(StatefulClass(), _SupportsStateDict)\n\n class NotStatefulClass:\n def state_dict(self):\n pass\n\n assert not isinstance(NotStatefulClass(), _SupportsStateDict)\n\n class NotStateful2Class:\n def load_state_dict(self, state_dict):\n pass\n\n assert not isinstance(NotStateful2Class(), _SupportsStateDict)\n\n\ndef test_fault_tolerant_mode_enum():\n with mock.patch.dict(os.environ, {\"PL_FAULT_TOLERANT_TRAINING\": \"0\"}):\n assert _FaultTolerantMode.DISABLED == _FaultTolerantMode.detect_current_mode()\n assert not TrainerState()._fault_tolerant_mode.is_enabled\n\n with mock.patch.dict(os.environ, {\"PL_FAULT_TOLERANT_TRAINING\": \"1\"}):\n assert _FaultTolerantMode.AUTOMATIC == _FaultTolerantMode.detect_current_mode()\n assert TrainerState()._fault_tolerant_mode.is_automatic\n\n with mock.patch.dict(os.environ, {\"PL_FAULT_TOLERANT_TRAINING\": \"MANUAL\"}):\n assert _FaultTolerantMode.MANUAL == _FaultTolerantMode.detect_current_mode()\n assert TrainerState()._fault_tolerant_mode.is_manual\n\n with pytest.raises(\n MisconfigurationException, match=\"The environment flag `PL_FAULT_TOLERANT_TRAINING` should be either\"\n ):\n with mock.patch.dict(os.environ, {\"PL_FAULT_TOLERANT_TRAINING\": \"3\"}):\n _FaultTolerantMode.detect_current_mode()\n\n\nclass StatefulRandomSampler(RandomSampler):\n\n counter = 0\n\n def state_dict(self):\n self.counter += 1\n return {\"counter\": self.counter}\n\n def load_state_dict(self, state_dict):\n self.counter = state_dict[\"counter\"]\n\n\nclass StatefulRandomDataset(RandomDataset):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.counter = 0\n\n def __getitem__(self, index):\n self.counter += 1\n return super().__getitem__(index)\n\n def state_dict(self):\n info = get_worker_info()\n if info:\n return {info.id: {\"counter\": self.counter}}\n return {\"counter\": self.counter}\n\n def load_state_dict(self, state_dict):\n self.counter = state_dict[0][\"counter\"]\n\n\[email protected](\"num_workers\", [0])\[email protected](os.environ, {\"PL_FAULT_TOLERANT_TRAINING\": \"2\"})\ndef test_stateful_workers(num_workers):\n\n seed_everything(42)\n\n _get_iterator_fn = DataLoader._get_iterator\n _patch_dataloader_get_iterators()\n assert DataLoader._ori_get_iterator is not None\n\n data_fetcher = DataFetcher()\n dataset = StatefulRandomDataset(1, 64)\n dataloader = DataLoader(dataset, sampler=StatefulRandomSampler(dataset), num_workers=num_workers)\n\n with pytest.raises(MisconfigurationException, match=\"A stateful iterator should be used\"):\n iter(dataloader)\n\n # This would attach the `data_fetcher` to the DataLoader.\n data_fetcher.setup(dataloader)\n\n data_fetcher_iter = iter(data_fetcher)\n\n dataloader_iter = data_fetcher.dataloader_iter\n worker_type = _SingleProcessDataLoaderIterStateful if num_workers == 0 else _MultiProcessingDataLoaderIterStateful\n assert isinstance(dataloader_iter, worker_type)\n\n next(data_fetcher_iter)\n\n reloaded_state = deepcopy(data_fetcher.dataloader_iter.state)\n state = reloaded_state.state\n assert state[0].dataset_state == {0: {\"counter\": 1}}\n assert state[0].sampler_state[\"sampler\"] == {\"counter\": 1}\n\n next(data_fetcher_iter)\n previous_state = data_fetcher.dataloader_iter.previous_state.state\n state = data_fetcher.dataloader_iter.state.state\n assert previous_state[0].dataset_state == {0: {\"counter\": 1}}\n assert previous_state[0].sampler_state[\"sampler\"] == {\"counter\": 1}\n # TODO: Resolve the previous `sampler_state` associated to `worker_id: 0`.\n worker_id = 1 if num_workers else 0\n assert state[worker_id].sampler_state[\"sampler\"] == {\"counter\": 2}\n\n # each worker has its own copy of the dataset\n assert state[0].dataset_state == ({0: {\"counter\": 2}} if num_workers == 0 else {0: {\"counter\": 1}})\n target_previous_state = deepcopy(state)\n\n next(data_fetcher_iter)\n latest_worker_id = data_fetcher.dataloader_iter.state.latest_worker_id\n assert latest_worker_id == 0\n previous_state = data_fetcher.dataloader_iter.previous_state.state\n state = data_fetcher.dataloader_iter.state.state\n\n assert target_previous_state == previous_state\n assert state[0].sampler_state[\"sampler\"] == {\"counter\": 3}\n assert state[0].dataset_state == ({0: {\"counter\": 3}} if num_workers == 0 else {0: {\"counter\": 2}})\n\n _teardown_dataloader_get_iterators()\n assert not hasattr(DataLoader, \"_ori_get_iterator\")\n assert DataLoader._get_iterator == _get_iterator_fn\n\n _reload_dataloader_state_dict(dataloader, asdict(reloaded_state))\n assert dataloader.sampler.counter == dataloader.dataset.counter == 1\n data_fetcher.teardown()\n"
] |
[
[
"torch.multiprocessing.spawn",
"torch.cat",
"torch.load",
"numpy.in1d",
"torch.cuda.is_available",
"torch.allclose",
"numpy.random.randint",
"torch.Generator",
"torch.utils.data.DistributedSampler",
"torch.distributed.init_process_group",
"torch.testing.assert_allclose",
"numpy.unique",
"torch.equal",
"torch.tensor",
"torch.rand",
"torch.utils.data.dataloader.DataLoader",
"torch.utils.data.dataloader.default_collate",
"numpy.random.choice",
"torch.zeros_like",
"torch.nn.Linear",
"numpy.random.rand",
"torch.stack",
"numpy.random.seed",
"torch.utils.data._utils.worker.get_worker_info",
"torch.manual_seed",
"torch.utils.data.SequentialSampler",
"torch.distributed.all_gather",
"torch.utils.data.RandomSampler",
"torch.utils.data.BatchSampler"
]
] |
NicholasCorrado/stable-baselines3
|
[
"77793947335c6b14747c2c5179a7c05c93289ffd"
] |
[
"stable_baselines3/td3_latent/td3_latent.py"
] |
[
"from typing import Any, Dict, List, Optional, Tuple, Type, Union\n\nimport gym\nimport numpy as np\nimport torch as th\nfrom torch.nn import functional as F\n\nfrom stable_baselines3.common.buffers import ReplayBuffer\nfrom stable_baselines3.common.noise import ActionNoise, OrnsteinUhlenbeckActionNoise\nfrom stable_baselines3.common.off_policy_algorithm import OffPolicyAlgorithm\nfrom stable_baselines3.common.type_aliases import GymEnv, MaybeCallback, Schedule\nfrom stable_baselines3.common.utils import polyak_update\nfrom stable_baselines3.td3_latent.policies import TD3LatentPolicy\n\n\nclass TD3Latent(OffPolicyAlgorithm):\n \"\"\"\n Twin Delayed DDPG (TD3)\n Addressing Function Approximation Error in Actor-Critic Methods.\n\n Original implementation: https://github.com/sfujim/TD3\n Paper: https://arxiv.org/abs/1802.09477\n Introduction to TD3: https://spinningup.openai.com/en/latest/algorithms/td3.html\n\n :param policy: The policy model to use (MlpPolicy, CnnPolicy, ...)\n :param env: The environment to learn from (if registered in Gym, can be str)\n :param learning_rate: learning rate for adam optimizer,\n the same learning rate will be used for all networks (Q-Values, Actor and Value function)\n it can be a function of the current progress remaining (from 1 to 0)\n :param buffer_size: size of the replay buffer\n :param learning_starts: how many steps of the model to collect transitions for before learning starts\n :param batch_size: Minibatch size for each gradient update\n :param tau: the soft update coefficient (\"Polyak update\", between 0 and 1)\n :param gamma: the discount factor\n :param train_freq: Update the model every ``train_freq`` steps. Alternatively pass a tuple of frequency and unit\n like ``(5, \"step\")`` or ``(2, \"episode\")``.\n :param gradient_steps: How many gradient steps to do after each rollout (see ``train_freq``)\n Set to ``-1`` means to do as many gradient steps as steps done in the environment\n during the rollout.\n :param action_noise: the action noise type (None by default), this can help\n for hard exploration problem. Cf common.noise for the different action noise type.\n :param replay_buffer_class: Replay buffer class to use (for instance ``HerReplayBuffer``).\n If ``None``, it will be automatically selected.\n :param replay_buffer_kwargs: Keyword arguments to pass to the replay buffer on creation.\n :param optimize_memory_usage: Enable a memory efficient variant of the replay buffer\n at a cost of more complexity.\n See https://github.com/DLR-RM/stable-baselines3/issues/37#issuecomment-637501195\n :param policy_delay: Policy and target networks will only be updated once every policy_delay steps\n per training steps. The Q values will be updated policy_delay more often (update every training step).\n :param target_policy_noise: Standard deviation of Gaussian noise added to target policy\n (smoothing noise)\n :param target_noise_clip: Limit for absolute value of target policy smoothing noise.\n :param create_eval_env: Whether to create a second environment that will be\n used for evaluating the agent periodically. (Only available when passing string for the environment)\n :param policy_kwargs: additional arguments to be passed to the policy on creation\n :param verbose: the verbosity level: 0 no output, 1 info, 2 debug\n :param seed: Seed for the pseudo random generators\n :param device: Device (cpu, cuda, ...) on which the code should be run.\n Setting it to auto, the code will be run on the GPU if possible.\n :param _init_setup_model: Whether or not to build the network at the creation of the instance\n \"\"\"\n\n def __init__(\n self,\n policy: Union[str, Type[TD3LatentPolicy]],\n env: Union[GymEnv, str],\n learning_rate: Union[float, Schedule] = 1e-3,\n buffer_size: int = 1_000_000, # 1e6\n learning_starts: int = 100,\n batch_size: int = 100,\n tau: float = 0.005,\n gamma: float = 0.99,\n train_freq: Union[int, Tuple[int, str]] = (1, \"episode\"),\n gradient_steps: int = -1,\n action_noise: Optional[ActionNoise] = None,\n replay_buffer_class: Optional[ReplayBuffer] = None,\n replay_buffer_kwargs: Optional[Dict[str, Any]] = None,\n optimize_memory_usage: bool = False,\n policy_delay: int = 2,\n target_policy_noise: float = 0.2,\n target_noise_clip: float = 0.5,\n tensorboard_log: Optional[str] = None,\n create_eval_env: bool = False,\n policy_kwargs: Optional[Dict[str, Any]] = None,\n verbose: int = 0,\n seed: Optional[int] = None,\n device: Union[th.device, str] = \"auto\",\n _init_setup_model: bool = True,\n ):\n\n env_id = env.envs[0].spec.id\n policy_kwargs['env_id'] = env_id\n policy_kwargs['action_noise'] = action_noise\n\n super(TD3Latent, self).__init__(\n policy,\n env,\n TD3LatentPolicy,\n learning_rate,\n buffer_size,\n learning_starts,\n batch_size,\n tau,\n gamma,\n train_freq,\n gradient_steps,\n action_noise=None,\n replay_buffer_class=replay_buffer_class,\n replay_buffer_kwargs=replay_buffer_kwargs,\n policy_kwargs=policy_kwargs,\n tensorboard_log=tensorboard_log,\n verbose=verbose,\n device=device,\n create_eval_env=create_eval_env,\n seed=seed,\n sde_support=False,\n optimize_memory_usage=optimize_memory_usage,\n supported_action_spaces=(gym.spaces.Box),\n support_multi_env=True,\n )\n\n self.policy_delay = policy_delay\n self.target_noise_clip = target_noise_clip\n self.target_policy_noise = target_policy_noise\n\n if _init_setup_model:\n self._setup_model()\n\n def _setup_model(self) -> None:\n super(TD3Latent, self)._setup_model()\n self._create_aliases()\n\n def _create_aliases(self) -> None:\n self.actor = self.policy.actor\n self.actor_target = self.policy.actor_target\n self.critic = self.policy.critic\n self.critic_target = self.policy.critic_target\n\n def train(self, gradient_steps: int, batch_size: int = 100) -> None:\n # Switch to train mode (this affects batch norm / dropout)\n self.policy.set_training_mode(True)\n\n # Update learning rate according to lr schedule\n self._update_learning_rate([self.actor.optimizer, self.critic.optimizer])\n\n actor_losses, critic_losses = [], []\n\n for _ in range(gradient_steps):\n\n self._n_updates += 1\n # Sample replay buffer\n replay_data = self.replay_buffer.sample(batch_size, env=self._vec_normalize_env)\n\n with th.no_grad():\n # Select action according to policy and add clipped noise\n noise = replay_data.actions.clone().data.normal_(0, self.target_policy_noise)\n noise = noise.clamp(-self.target_noise_clip, self.target_noise_clip)\n next_actions = th.tanh(th.atanh(self.actor_target(replay_data.next_observations)) + noise)\n\n # Compute the next Q-values: min over all critics targets\n next_q_values = th.cat(self.critic_target(replay_data.next_observations, next_actions), dim=1)\n next_q_values, _ = th.min(next_q_values, dim=1, keepdim=True)\n target_q_values = replay_data.rewards + (1 - replay_data.dones) * self.gamma * next_q_values\n\n # Get current Q-values estimates for each critic network\n current_q_values = self.critic(replay_data.observations, replay_data.actions)\n\n # Compute critic loss\n critic_loss = sum([F.mse_loss(current_q, target_q_values) for current_q in current_q_values])\n critic_losses.append(critic_loss.item())\n\n # Optimize the critics\n self.critic.optimizer.zero_grad()\n critic_loss.backward()\n self.critic.optimizer.step()\n\n # Delayed policy updates\n if self._n_updates % self.policy_delay == 0:\n # Compute actor loss\n actor_loss = -self.critic.q1_forward(replay_data.observations, self.actor(replay_data.observations)).mean()\n actor_losses.append(actor_loss.item())\n\n # Optimize the actor\n self.actor.optimizer.zero_grad()\n actor_loss.backward()\n self.actor.optimizer.step()\n\n polyak_update(self.critic.parameters(), self.critic_target.parameters(), self.tau)\n polyak_update(self.actor.parameters(), self.actor_target.parameters(), self.tau)\n\n self.logger.record(\"train/n_updates\", self._n_updates, exclude=\"tensorboard\")\n if len(actor_losses) > 0:\n self.logger.record(\"train/actor_loss\", np.mean(actor_losses))\n self.logger.record(\"train/critic_loss\", np.mean(critic_losses))\n\n def learn(\n self,\n total_timesteps: int,\n callback: MaybeCallback = None,\n log_interval: int = 4,\n eval_env: Optional[GymEnv] = None,\n eval_freq: int = -1,\n n_eval_episodes: int = 5,\n tb_log_name: str = \"TD3Latent\",\n eval_log_path: Optional[str] = None,\n reset_num_timesteps: bool = True,\n ) -> OffPolicyAlgorithm:\n\n return super(TD3Latent, self).learn(\n total_timesteps=total_timesteps,\n callback=callback,\n log_interval=log_interval,\n eval_env=eval_env,\n eval_freq=eval_freq,\n n_eval_episodes=n_eval_episodes,\n tb_log_name=tb_log_name,\n eval_log_path=eval_log_path,\n reset_num_timesteps=reset_num_timesteps,\n )\n\n def _excluded_save_params(self) -> List[str]:\n return super(TD3Latent, self)._excluded_save_params() + [\"actor\", \"critic\", \"actor_target\", \"critic_target\"]\n\n def _get_torch_save_params(self) -> Tuple[List[str], List[str]]:\n state_dicts = [\"policy\", \"actor.optimizer\", \"critic.optimizer\"]\n return state_dicts, []\n\n\n # super(TD3Latent, self).__init__(\n # policy=policy,\n # env=env,\n # learning_rate=learning_rate,\n # buffer_size=buffer_size,\n # learning_starts=learning_starts,\n # batch_size=batch_size,\n # tau=tau,\n # gamma=gamma,\n # train_freq=train_freq,\n # gradient_steps=gradient_steps,\n # action_noise=action_noise,\n # replay_buffer_class=replay_buffer_class,\n # replay_buffer_kwargs=replay_buffer_kwargs,\n # optimize_memory_usage=optimize_memory_usage,\n # policy_delay=policy_delay,\n # target_policy_noise=target_policy_noise,\n # target_noise_clip=target_noise_clip,\n # tensorboard_log=tensorboard_log,\n # create_eval_env=create_eval_env,\n # policy_kwargs=policy_kwargs,\n # verbose=verbose,\n # seed=seed,\n # device=device,\n # _init_setup_model=_init_setup_model,\n # )"
] |
[
[
"torch.nn.functional.mse_loss",
"torch.no_grad",
"torch.min",
"numpy.mean"
]
] |
Shreya2297/t4
|
[
"1e9d83feeb874d637f2a2742e8f2b34cc54b5465"
] |
[
"task- creating and merging images.py"
] |
[
"#!/usr/bin/env python\n# coding: utf-8\n\n# In[21]:\n\n\n#importing libraries\nimport numpy as np\nimport cv2 as cv\n\n\n# In[23]:\n\n\n#creating a blank black colored image\nblank=np.zeros((500,500,3),dtype='uint8') \n#creating a rectangle on left side vertically\nblank=cv.rectangle(blank,(0,0),(250,500),(49,99,53),thickness=-1)\n#creating a rectangle on right side vertically\nblank=cv.rectangle(blank,(250,0),(500,500),(99,53,49),thickness=-1)\n#drawing a big circle\nblank=cv.circle(blank,(250,250),250,(255,255,255),thickness=-1)\n#drawing a small circle\nblank=cv.circle(blank,(250,250),125,(27,27,27),thickness=-1)\n# Drawing an orange line top-left\ncv.line(blank, (0,250), (250,0), (0,100,255), (5))\n# Drawing an orange line bottom-right\ncv.line(blank, (500,250), (250,500), (0,100,255), (5))\n# Drawing an orange line top-right\ncv.line(blank, (250,0), (500,250), (0,100,255), (5))\n# Drawing an orange line bottom-right\ncv.line (blank, (0,250), (250,500), (0,100,255), (5))\n#drawing a smaller circle\ncv.circle(blank,(250,250),50,(255,255,255),thickness=-1)\ncv.imshow('Custom image', blank)\ncv.waitKey(0) #to hold the photo\ncv.destroyAllWindows() #to close the window\n\n\n# In[25]:\n\n\nimg1 = cv.imread('starry.jpg')\nimg2 = cv.imread('mlisa.jpg')\nprint(img1.shape)\nprint(img2.shape)\n\n \n\n\n# In[26]:\n\n\n#extracting starry image by cropping\ns_night=img1[20:180,50:200]\ncv.imshow('picture cropped image', s_night)\ncv.waitKey(0) #to hold the photo\ncv.destroyAllWindows() #to close the window\n\n\n# In[27]:\n\n\n#resizing s_night image\ns_night=cv.resize(s_night,(100, 100))\n#swaping it with one of the legs in the other picture\nimg2[100:200,0:100]=s_night\ncv.imshow('Swapped image', img2)\ncv.waitKey(0) #to hold the photo\ncv.destroyAllWindows() #to close the window\n\n\n# In[ ]:\n\n\nimg1 = cv.imread('pic1.jpg')\nimg2 = cv.imread('pic2.jpg')\nhorizontal = np.hstack((img2,img1))\ncv.imshow(\"Collage\",horizontal)\ncv.waitKey(0)\ncv.destroyAllWindows() #making collage\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n"
] |
[
[
"numpy.hstack",
"numpy.zeros"
]
] |
Dani7B/claimed
|
[
"d6323602337a7a5702432a547bf2b0e7177c76bd"
] |
[
"coursera_ml/fourier_transform/disc_ft.py"
] |
[
"\"\"\"\n(C) 2018 Nikolay Manchev\n\nThis work is licensed under the Creative Commons Attribution 4.0 International\nLicense. To view a copy of this license, visit http://creativecommons.org/licenses/by/4.0/.\n\"\"\"\n\n\nimport numpy as np\n\nimport matplotlib.pyplot as plt\n\nimport math\n\nfrom numpy.fft import fft\n\n\ndef gen_wave (freq, amp, T, sr):\n\n time = np.arange(0,T,1/sr)\n \n X = amp*np.sin(2*np.pi*freq*time)\n \n return time,X\n\n\nplt.style.use(\"seaborn\")\nplt.rcParams[\"xtick.labelsize\"] = 14\nplt.rcParams[\"ytick.labelsize\"] = 14\n\nf, axarr = plt.subplots(2, figsize=(20, 8))\n\nsr=50 #in Hz\n\nx,y = gen_wave(3,2,1,sr)\nx,y2 = gen_wave(5,3,1,sr)\n\ny = y + y2\n\naxarr[0].plot(x, y)\n\nn = len(y) \np = fft(y) # take the fourier transform \n\nmag = np.sqrt(p.real**2 + p.imag**2)\n\nmag = mag * 2 / n\n\nmag = mag[0:math.ceil((n)/2.0)]\n\nx = np.arange(0, len(mag), 1.0) * (sr / n)\n\naxarr[1].bar(x, mag, color='b')\naxarr[1].xaxis.set_ticks(np.arange(min(x), max(x)+1, 1.0))\n\nplt.show()\n\n\n\n\n\n"
] |
[
[
"numpy.sqrt",
"numpy.fft.fft",
"numpy.arange",
"matplotlib.pyplot.subplots",
"numpy.sin",
"matplotlib.pyplot.show",
"matplotlib.pyplot.style.use"
]
] |
wuweialways17/EE5904-neural-networks
|
[
"ec733a725de3631b3d364ceae13a76a24171f184"
] |
[
"HW1/Q4/LMS.py"
] |
[
"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jan 28 17:37:39 2021\r\n\r\n@author: wwis17\r\n\"\"\"\r\n\"\"\"LMS method\"\"\"\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n# x = [bias, x]\r\nX = np.array([[1,0.5],[1,1.5],[1,3.0],[1,4.0],[1,5.0]])\r\n\r\nd = np.array([8.0,6.0,5,2,0.5])\r\n\r\n#learning rate\r\nlr = 0.02\r\n\r\n\r\nw = np.array([1.0,1.0])\r\nprint(\"the initial weights is:\", w)\r\n\r\nweight_change = np.copy(w)\r\n\r\nfor j in range(100):\r\n for i in range(5):\r\n e = d[i]-np.dot(X[i,:],w)\r\n w += lr*e*X[i,:]\r\n weight_change = np.append(weight_change,w)\r\n \r\ntotal_iter = i*(j+1)\r\nweight_change = np.reshape(weight_change, (501,2))\r\n\r\n\r\nprint('Final weights is:',w)\r\n\r\n\r\nstep = np.arange(501)\r\nx = np.arange(6)\r\nfig, ax = plt.subplots(2, 1, figsize=(6, 8))\r\nax[0].plot(step,weight_change[:,0],label='weight')\r\nax[0].plot(step,weight_change[:,1],label='bias')\r\nax[0].set_xlabel('setp')\r\nax[0].set_ylabel('weight')\r\nax[0].legend()\r\nax[1].plot(x, w[0]+w[1]*x,label = 'LMS fitting result')\r\nax[1].scatter(X[:,1],d,color='red',label = 'given data pairs')\r\nax[1].set_xlabel('x')\r\nax[1].set_ylabel('y')\r\nax[1].legend()\r\nplt.tight_layout()\r\n\r\n"
] |
[
[
"numpy.dot",
"matplotlib.pyplot.tight_layout",
"numpy.reshape",
"numpy.arange",
"matplotlib.pyplot.subplots",
"numpy.copy",
"numpy.append",
"numpy.array"
]
] |
nicogab34/AudioMNIST
|
[
"39d8bf5eb2bf5d8a32d21d3d5549935cb4a62931"
] |
[
"audiomnist/io/preprocess_data.py"
] |
[
"# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport glob\nimport os\nimport sys\nimport scipy.io.wavfile as wavf\nimport scipy.signal\nimport h5py\nimport json\nimport librosa\nimport tensorflow as tf\nfrom tqdm import tqdm\n\ntf.enable_eager_execution()\n\n# The following functions can be used to convert a value to a type compatible\n# with tf.Example.\n\ndef _bytes_feature(value):\n \"\"\"Returns a bytes_list from a string / byte.\"\"\"\n return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))\n\ndef _float_feature(value):\n \"\"\"Returns a float_list from a float / double.\"\"\"\n return tf.train.Feature(float_list=tf.train.FloatList(value=[value]))\n\ndef _int64_feature(value):\n \"\"\"Returns an int64_list from a bool / enum / int / uint.\"\"\"\n return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))\n\ndef preprocess_data(src, dst, src_meta, n_processes=15):\n\n \"\"\"\n Calls for distibuted preprocessing of the data.\n\n Parameters:\n -----------\n src: string\n Path to data directory.\n dst: string\n Path to directory where preprocessed data shall be stored.\n stc_meta: string\n Path to meta_information file.\n n_processes: int\n number of simultaneous processes to use for data preprocessing.\n \"\"\"\n\n folders = []\n\n for folder in os.listdir(src):\n # only process folders\n if not os.path.isdir(os.path.join(src, folder)):\n continue\n folders.append(folder)\n\n audionet_writer=tf.python_io.TFRecordWriter(os.path.join(dst, \"audionet.tfrecords\"))\n alexnet_writer=tf.python_io.TFRecordWriter(os.path.join(dst, \"alexnet.tfrecords\"))\n for folder in tqdm(sorted(folders)):\n _preprocess_data(os.path.join(src, folder), \n audionet_writer,\n alexnet_writer, \n src_meta)\n\n\n\n\ndef _preprocess_data(src, audionet_writer, alexnet_writer, src_meta):\n\n \"\"\"\n Preprocessing for all data files in given directory.\n Preprocessing includes:\n\n AlexNet: resampling to 8000 Hz, \n embedding in zero vector, \n transformation to amplitute spectrogram representation in dB.\n \n AudioNet: resampling to 8000 Hz, \n embedding in zero vector, \n normalization at 95th percentile.\n\n Preprocessed data will be stored in hdf5 files with one datum per file.\n In terms of I/O, this is not very efficient but it allows to easily change\n training, validation, and test sets without re-preprocessing or redundant \n storage of preprocessed files.\n\n Parameters:\n -----------\n src_writer_meta: tuple of 3 strings\n Tuple (path to data directory, path to destination directory, path\n to meta file)\n \"\"\"\n\n metaData = json.load(open(src_meta))\n\n # loop over recordings\n for filepath in sorted(glob.glob(os.path.join(src, \"*.wav\"))):\n\n # infer sample info from name\n dig, vp, rep = filepath.rstrip(\".wav\").split(\"/\")[-1].split(\"_\")\n # read data\n fs, data = wavf.read(filepath)\n # resample\n data = librosa.core.resample(y=data.astype(np.float32), orig_sr=fs, target_sr=8000, res_type=\"scipy\")\n # zero padding\n if len(data) > 8000:\n raise ValueError(\"data length cannot exceed padding length.\")\n elif len(data) < 8000:\n embedded_data = np.zeros(8000)\n offset = np.random.randint(low = 0, high = 8000 - len(data))\n embedded_data[offset:offset+len(data)] = data\n elif len(data) == 8000:\n # nothing to do here\n embedded_data = data\n pass\n\n ##### AlexNet #####\n\n # stft, with seleced parameters, spectrogram will have shape (227,227)\n f, t, Zxx = scipy.signal.stft(embedded_data, 8000, nperseg = 455, noverlap = 420, window='hann')\n # get amplitude\n Zxx = np.abs(Zxx[0:227, 2:-1])\n Zxx = np.atleast_3d(Zxx).transpose(2,0,1)\n # convert to decibel\n Zxx = librosa.amplitude_to_db(Zxx, ref = np.max)\n # save as hdf5 file\n tmp_X = np.zeros([1, 227, 227, 1])\n tmp_X[0, :, :, 0] = Zxx\n\n alexnet_feature = {\n 'data' : tf.train.Feature(float_list=tf.train.FloatList(value=tmp_X.ravel())),\n 'shape' : tf.train.Feature(float_list=tf.train.FloatList(value=tmp_X.shape)),\n 'digit' : _int64_feature(int(dig)),\n 'gender' : _int64_feature(0 if metaData[vp][\"gender\"] == \"male\" else 1),\n 'vp' : _int64_feature(int(vp))\n }\n\n alexnet_example_proto = tf.train.Example(features=tf.train.Features(feature=alexnet_feature))\n\n alexnet_writer.write(alexnet_example_proto.SerializeToString())\n\n ##### AudioNet #####\n \n embedded_data /= (np.percentile(embedded_data, 95) + 0.001)\n \n tmp_X = np.zeros([1, 8000, 1, 1])\n\n tmp_X[0, :, 0, 0] = embedded_data\n audionet_feature = {\n 'data' : tf.train.Feature(float_list=tf.train.FloatList(value=tmp_X.ravel())),\n 'shape' : tf.train.Feature(float_list=tf.train.FloatList(value=tmp_X.shape)),\n 'digit' : _int64_feature(int(dig)),\n 'gender' : _int64_feature(0 if metaData[vp][\"gender\"] == \"male\" else 1),\n 'vp' : _int64_feature(int(vp))\n }\n\n audionet_example_proto = tf.train.Example(features=tf.train.Features(feature=audionet_feature))\n\n audionet_writer.write(audionet_example_proto.SerializeToString())\n\n return\n\n"
] |
[
[
"tensorflow.enable_eager_execution",
"numpy.abs",
"numpy.percentile",
"numpy.atleast_3d",
"tensorflow.train.BytesList",
"tensorflow.train.FloatList",
"tensorflow.train.Features",
"numpy.zeros",
"scipy.io.wavfile.read",
"tensorflow.train.Int64List"
]
] |
seqRep/dgl-lifesci
|
[
"c4bd45be6dbb59dc270957ed90bb19d9ed6dc157"
] |
[
"examples/molecule_embeddings/main.py"
] |
[
"# -*- coding: utf-8 -*-\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nimport dgl\nimport errno\nimport numpy as np\nimport os\nimport torch\n\nfrom dgl.nn.pytorch.glob import AvgPooling\nfrom dgllife.model import load_pretrained\nfrom dgllife.utils import mol_to_bigraph, PretrainAtomFeaturizer, PretrainBondFeaturizer\nfrom rdkit import Chem\nfrom torch.utils.data import DataLoader\n\ndef mkdir_p(path, log=True):\n \"\"\"Create a directory for the specified path.\n\n Parameters\n ----------\n path : str\n Path name\n log : bool\n Whether to print result for directory creation\n \"\"\"\n try:\n os.makedirs(path)\n if log:\n print('Created directory {}'.format(path))\n except OSError as exc:\n if exc.errno == errno.EEXIST and os.path.isdir(path) and log:\n print('Directory {} already exists.'.format(path))\n else:\n raise\n\ndef graph_construction_and_featurization(smiles):\n \"\"\"Construct graphs from SMILES and featurize them\n\n Parameters\n ----------\n smiles : list of str\n SMILES of molecules for embedding computation\n\n Returns\n -------\n list of DGLGraph\n List of graphs constructed and featurized\n list of bool\n Indicators for whether the SMILES string can be\n parsed by RDKit\n \"\"\"\n graphs = []\n success = []\n for smi in smiles:\n try:\n mol = Chem.MolFromSmiles(smi)\n if mol is None:\n success.append(False)\n continue\n g = mol_to_bigraph(mol, add_self_loop=True,\n node_featurizer=PretrainAtomFeaturizer(),\n edge_featurizer=PretrainBondFeaturizer(),\n canonical_atom_order=False)\n graphs.append(g)\n success.append(True)\n except:\n success.append(False)\n\n return graphs, success\n\ndef collate(graphs):\n return dgl.batch(graphs)\n\ndef main(args, dataset):\n data_loader = DataLoader(dataset, batch_size=args['batch_size'],\n collate_fn=collate, shuffle=False)\n model = load_pretrained(args['model']).to(args['device'])\n model.eval()\n readout = AvgPooling()\n\n mol_emb = []\n for batch_id, bg in enumerate(data_loader):\n print('Processing batch {:d}/{:d}'.format(batch_id + 1, len(data_loader)))\n nfeats = [bg.ndata.pop('atomic_number').to(args['device']),\n bg.ndata.pop('chirality_type').to(args['device'])]\n efeats = [bg.edata.pop('bond_type').to(args['device']),\n bg.edata.pop('bond_direction_type').to(args['device'])]\n with torch.no_grad():\n node_repr = model(bg, nfeats, efeats)\n mol_emb.append(readout(bg, node_repr))\n mol_emb = torch.cat(mol_emb, dim=0).detach().cpu().numpy()\n np.save(args['out_dir'] + '/mol_emb.npy', mol_emb)\n\nif __name__ == '__main__':\n import pandas as pd\n\n from argparse import ArgumentParser\n from dgllife.utils import load_smiles_from_txt\n\n parser = ArgumentParser(\"Molecule Embedding Computation with Pre-trained Models\")\n parser.add_argument('-fi', '--file', type=str,\n help=\"Path to the file of SMILES\")\n parser.add_argument('-fo', '--format', choices=['txt', 'csv'], default='txt',\n help=\"Format for the file of SMILES (default: 'txt')\")\n parser.add_argument('-sc', '--smiles-column', type=str,\n help=\"Column for SMILES in the CSV file.\")\n parser.add_argument('-m', '--model', choices=['gin_supervised_contextpred',\n 'gin_supervised_infomax',\n 'gin_supervised_edgepred',\n 'gin_supervised_masking'],\n help='Pre-trained model to use for computing molecule embeddings')\n parser.add_argument('-b', '--batch-size', type=int, default=256,\n help='Batch size for embedding computation')\n parser.add_argument('-o', '--out-dir', type=str, default='results',\n help='Path to the computation results')\n args = parser.parse_args().__dict__\n mkdir_p(args['out_dir'])\n\n if torch.cuda.is_available():\n args['device'] = torch.device('cuda:0')\n else:\n args['device'] = torch.device('cpu')\n\n if args['format'] == 'txt':\n smiles = load_smiles_from_txt(args['file'])\n else:\n df = pd.read_csv(args['file'])\n smiles = df[args['smiles_column']].tolist()\n dataset, success = graph_construction_and_featurization(smiles)\n np.save(args['out_dir'] + '/mol_parsed.npy', np.array(success))\n main(args, dataset)\n"
] |
[
[
"pandas.read_csv",
"torch.cat",
"torch.utils.data.DataLoader",
"numpy.save",
"torch.no_grad",
"torch.cuda.is_available",
"torch.device",
"numpy.array"
]
] |
mortendaehli/min-symaskin-inventory-utils
|
[
"a573f4723eb4153d0421272a55bcc50e5a78861e"
] |
[
"main.py"
] |
[
"import os\nimport pathlib\nimport logging\nfrom pathlib import Path\n\nimport pandas as pd\nimport shopify\nfrom dotenv import load_dotenv\n\nlogging.basicConfig(format='%(asctime)s | %(name)s | %(levelname)s | %(message)s')\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\n\n\ndef get_all_resources(resource_type, **kwargs):\n resource_count = resource_type.count(**kwargs)\n resources = []\n if resource_count > 0:\n page = resource_type.find(**kwargs)\n resources.extend(page)\n while page.has_next_page():\n page = page.next_page()\n resources.extend(page)\n return resources\n\n\ndef get_number_from_string(x):\n return float(x.__repr__().replace(',', '.').replace(r'\\xa0', '').replace(\"'\", ''))\n\n\ndef main(input_file: Path) -> None:\n # env_path = Path('.env')\n # load_dotenv(dotenv_path=env_path)\n load_dotenv()\n key = os.getenv('SHOPIFY_KEY')\n pwd = os.getenv('SHOPIFY_PWD')\n name = os.getenv('SHOPIFY_NAME')\n\n shop_url = f\"https://{key}:{pwd}@{name}.myshopify.com/admin\"\n shopify.ShopifyResource.set_site(value=shop_url)\n\n df = pd.read_excel(io=input_file, engine='openpyxl')\n df.columns = [x.lower() for x in df.columns]\n\n # Some basic validations to assert that we have the correct sheet.\n # The columns varying depending on where the dump is done :-\\\n assert len(df.columns) == 15, 'Expected 16 columns in Excel sheet.'\n assert df.columns[2] == 'id', 'Expected input data to have \"id\" in third column'\n\n df.dropna(subset=['id'], axis=0, inplace=True)\n\n df.columns = [\n 'sku',\n 'title',\n 'pos_id',\n 'active',\n 'recommended_product',\n 'inventory_quantity',\n 'product_type',\n 'product_subtype1',\n 'product_subtype2',\n 'price',\n 'price_discounted',\n 'discount_start',\n 'discount_end',\n 'hide_when_empty',\n 'lead_time'\n ]\n\n df.loc[:, 'sku'] = df.loc[:, 'sku'].map(lambda x: str(x))\n df.loc[:, 'title'] = df.loc[:, 'title'].astype(str).map(lambda x: x.replace(\"/xa0\", \"\"))\n df.loc[:, 'pos_id'] = df.loc[:, 'pos_id'].map(lambda x: str(int(float(x))))\n df.loc[:, 'active'] = df.loc[:, 'active'].astype(bool)\n df.loc[:, 'recommended_product'] = df.loc[:, 'recommended_product'].astype(str)\n df.loc[:, 'inventory_quantity'] = df.loc[:, 'inventory_quantity'].map(lambda x: int(get_number_from_string(x)))\n df.loc[:, 'product_type'] = df.loc[:, 'product_type'].astype(str)\n df.loc[:, 'product_subtype1'] = df.loc[:, 'product_subtype1'].astype(str)\n df.loc[:, 'product_subtype2'] = df.loc[:, 'product_subtype2'].astype(str)\n\n df.loc[:, 'price'] = df['price'].map(lambda x: float(get_number_from_string(x)))\n df.loc[:, 'price_discounted'] = df['price_discounted'].map(lambda x: float(get_number_from_string(x)))\n\n df.loc[:, 'discount_start'] = df.loc[:, 'discount_start'].map(lambda x: pd.to_datetime(x))\n df.loc[:, 'discount_end'] = df.loc[:, 'discount_end'].map(lambda x: pd.to_datetime(x))\n\n df.loc[:, 'hide_when_empty'] = df.loc[:, 'hide_when_empty'].astype(bool)\n df.loc[:, 'lead_time'] = df.loc[:, 'lead_time'].astype(int)\n\n # Filter by product type and active\n df = df.loc[df['product_type'].map(lambda x: x in ['Symaskiner', 'Symaskintilbehør']), :]\n # df = df.loc[df['active'].map(lambda x: x is True)]\n df = df.loc[df.apply(lambda x: x[\"active\"] or x[\"title\"].lower().startswith(\"brother\"), axis=1)]\n\n # Trying to figure out the vendor based on name for certain items.\n df.loc[:, 'vendor'] = None\n df.loc[df.loc[:, 'title'].map(lambda x: 'janome' in str(x).replace(' ', '').lower()), 'vendor'] = 'Janome'\n df.loc[df.loc[:, 'title'].map(lambda x: 'babylock' in str(x).replace(' ', '').lower()), 'vendor'] = 'Baby Lock'\n df.loc[df.loc[:, 'title'].map(lambda x: 'brother' in str(x).replace(' ', '').lower()), 'vendor'] = 'Brother'\n\n shop = shopify.Shop.current\n products = get_all_resources(shopify.Product)\n location = shopify.Location.find_first()\n\n skus = []\n # Updating existing products\n for product in products:\n for variant in product.variants:\n skus.append(variant.sku)\n if variant.sku in df['sku'].values:\n df_product = df.loc[df['sku'] == variant.sku].iloc[0]\n logger.info(f\"Updating: {product.title} - sku: {variant.sku}\")\n # product.title = df_product['title']\n product.vendor = df_product['vendor']\n product.product_type = df_product['product_type']\n variant.price = df_product['price']\n variant.option1 = \"Default Title\"\n variant.inventory_policy = \"deny\" if df_product['hide_when_empty'] else 'continue'\n shopify.InventoryLevel.set(location.id, variant.inventory_item_id, int(df_product['inventory_quantity']))\n variant.save()\n product.save()\n else:\n logger.warning(f\"Not matched with POS: {product.title} - sku: {variant.sku}\")\n # logger.warning(f\"Deleting - Not matched with POS: {product.title} - sku: {sku}\")\n # shopify.Variant.delete(variant.id)\n # shopify.Product.delete(product.id)\n\n for _, df_product in df.iterrows():\n if df_product.sku not in skus:\n logger.info(f\"Importing from POS: {df_product.title} - sku: {df_product.sku}\")\n new_product = shopify.Product()\n\n # Creating the product.\n new_product.title = df_product['title']\n new_product.vendor = df_product['vendor']\n new_product.product_type = df_product['product_type']\n new_product.inventory_quantity = df_product['inventory_quantity']\n new_product.save()\n\n # Then creating the (only) variant and saving....\n new_variant = shopify.Variant(\n {\n \"position\": 1,\n \"sku\": df_product['sku'],\n \"price\": df_product['price'],\n \"requires_shipping\": True,\n \"inventory_quantity\": df_product['inventory_quantity'],\n \"inventory_policy\": \"deny\" if df_product['hide_when_empty'] else 'continue',\n \"inventory_management\": \"shopify\",\n \"fulfillment_service\": \"manual\"\n }\n )\n\n new_product.variants = [new_variant]\n new_product.save()\n\n v = new_product.variants[0] # We only have 1 variant atm. So we don't vare about other variants\n shopify.InventoryLevel.set(location.id, v.inventory_item_id, int(df_product['inventory_quantity']))\n\n logger.info('Complete')\n\n\nif __name__ == '__main__':\n input_file = pathlib.Path().absolute() / 'data' / 'inventory.xlsx'\n main(input_file=input_file)\n"
] |
[
[
"pandas.read_excel",
"pandas.to_datetime"
]
] |
Miyembe/multiagent-particle-envs
|
[
"971756f6c99c8e18f34a4dadbf65486dea08d47a"
] |
[
"pheromone_multi.py"
] |
[
"#!/usr/bin/env python\n# Node that handles pheromone layer\n# Subscriber - Robot (x, y) position\n# Publisher - Pheromone value at (x, y)\nimport os\nimport numpy as np\n\nfrom math import *\nimport time\nfrom npsocket_sn import SocketNumpyArray\n\nclass Node():\n\n def __init__(self, phero):\n self.num_robots = 2\n self.pheromone = [None] * self.num_robots\n for i in range(len(phero)):\n self.pheromone[i] = phero[i]\n self.phero_max = 1.0\n self.phero_min = 0.0\n self.is_phero_inj = True\n\n # Socket Communication\n self.sock_receiver = SocketNumpyArray()\n self.sock_receiver.initalize_receiver(9999) # the 9999 is the port you can change it with your own.\n \n self.theta = 0 \n \n self.log_timer = time.clock()\n #self.log_file = open(\"phero_value.txt\", \"a+\")\n self.is_saved = False\n self.is_loaded = False\n self.is_reset = True # False for reset\n\n for i in range(len(phero)):\n self.pheromone[i].isDiffusion = False\n self.pheromone[i].isEvaporation = True\n self.startTime = time.time()\n\n # Robot positions\n self.positions = [0,0]*self.num_robots\n self.x_idx = [0, 0]\n self.y_idx = [0, 0]\n\n # PosToIndex for pheromone circle\n # x_2, y_0 = self.posToIndex(2,0)\n # x_n3, y_n3 = self.posToIndex(-3,-3)\n # x_0, y_0 = self.posToIndex(0,0)\n # Pheromone Initilaisation\n # self.pheromone.circle(x_2, y_0, 1, 1)\n # self.pheromone.circle(x_3, y_0, 1, 1)\n # self.pheromone.circle(x_n3, y_0, 1, 1)\n # self.pheromone.circle(x_0, y_3, 1, 1)\n # self.pheromone.circle(x_0,y_n3, 1, 1)\n print(\"Initialisation completed\")\n\n \n\n def posToIndex(self, x, y):\n phero = self.pheromone\n x_tmp = x\n y_tmp = y\n # Read pheromone value at the robot position\n x_index = [0]*len(phero)\n y_index = [0]*len(phero)\n for i in range(len(phero)):\n res = phero[i].resolution\n round_dp = int(log10(res))\n x_tmp[i] = round(x_tmp[i], round_dp) # round the position value so that they fit into the centre of the cell.\n y_tmp[i] = round(y_tmp[i], round_dp) # e.g. 0.13 -> 0.1\n x_tmp[i] = int(x_tmp[i]*res)\n y_tmp[i] = int(y_tmp[i]*res)\n \n # Position conversion from Robot into pheromone matrix (0, 0) -> (n+1, n+1) of 2n+1 matrix\n x_index[i] = int(x_tmp[i] + (phero[i].num_cell-1)/2)\n y_index[i] = int(y_tmp[i] + (phero[i].num_cell-1)/2)\n if x_index[i] < 0 or y_index[i] < 0 or x_index[i] > phero[i].num_cell-1 or y_index[i] > phero[i].num_cell-1:\n raise Exception(\"The pheromone matrix index is out of range.\")\n return x_index, y_index\n\n def indexToPos(self, x_index, y_index):\n phero = self.pheromone[0]\n x = x_index - (phero.num_cell-1)/2\n y = y_index - (phero.num_cell-1)/2\n\n x = float(x) / phero.resolution \n \n def pheroCallback(self):\n # Reading from arguments\n pos = self.sock_receiver.receive_array()\n # twist = message.twist[-[]\n # ori = pose.orientation\n #print(\"pos0x: {}\".format(pos[0].x))\n phero = self.pheromone\n x = [pos[0][0], pos[1][0]]\n y = [pos[0][1], pos[1][1]]\n print(\"x, y: {}, {}\".format(x, y))\n x_idx, y_idx = self.posToIndex(x, y)\n \n print(\"x_idx, y_idx: {}, {}\".format(x_idx, y_idx))\n # ========================================================================= #\n\t # Pheromone Reading #\n\t # ========================================================================= #\n\n '''\n Pheromone Value Reading\n '''\n\n '''2 pheromone values'''\n # Add two wheel position\n # wheel_distance = 0.2\n # pos_l = np.array([x+(cos(pi/2)*cos(self.theta)*(wheel_distance/2) - sin(pi/2)*sin(self.theta)*(wheel_distance/2)), y+(sin(pi/2)*cos(self.theta)*(wheel_distance/2) + cos(pi/2)*sin(self.theta)*(wheel_distance/2))])\n # pos_r = np.array([x+(cos(pi/2)*cos(self.theta)*(wheel_distance/2) + sin(pi/2)*sin(self.theta)*(wheel_distance/2)), y+(-sin(pi/2)*cos(self.theta)*(wheel_distance/2) + cos(pi/2)*sin(self.theta)*(wheel_distance/2))])\n \n # x_index, y_index = self.posToIndex(pos.x, pos.y)\n # x_l_index, y_l_index = self.posToIndex(pos_l[0], pos_l[1])\n # x_r_index, y_r_index = self.posToIndex(pos_r[0], pos_r[1]) \n\n # # Assign pheromone values from two positions and publish it\n # phero_val = Float32MultiArray()\n # phero_val.data = [phero.getPhero(x_l_index, y_l_index), phero.getPhero(x_r_index, y_r_index)]\n # self.pub_phero.publish(phero_val)\n\n '''9 pheromone values'''\n # Position of 9 cells surrounding the robot\n # x_index, y_index = self.posToIndex(x, y)\n # phero_val = Float32MultiArray()\n # #phero_arr = np.array( )\n # for i in range(3):\n # for j in range(3):\n # phero_val.data.append(self.pheromone[0].getPhero(x_index+i-1, y_index+j-1)) # TODO: Randomly select the cell if the values are equal\n #print(\"phero_avg: {}\".format(np.average(np.asarray(phero_val.data))))\n # self.pub_phero.publish(phero_val)\n # # Assign pheromone value and publish it\n # phero_val = phero.getPhero(x_index, y_index)\n # self.pub_phero.publish(phero_val)\n \n ''' Read Pheromone from each pheromone grid '''\n # 9 pheromone value for two robots read from the other's pheromone grid. \n\n phero_val = [None] * self.num_robots\n #phero_arr = np.array( )\n for n in range(self.num_robots):\n phero_val[n] = list() \n for i in range(3):\n for j in range(3):\n phero_val[n].append(self.pheromone[1-n].getPhero(x_idx[n]+i-1, y_idx[n]+j-1)) # Read the other's pheromone\n self.sock_receiver.return_to_client(np.asarray(phero_val))\n\n # ========================================================================= #\n\t # Pheromone Injection #\n\t # ========================================================================= #\n\n # Pheromone injection (uncomment it when injection is needed)\n ## Two robots inject pheromone in different grids\n if self.is_phero_inj is True:\n for i in range(len(self.pheromone)):\n #phero[i].injection(x_idx[i], y_idx[i], 1, 25, self.phero_max)\n phero[i].gradInjection(x_idx[i], y_idx[i], 1, 0.3, 1.2, self.phero_max)\n\n # ========================================================================= #\n\t # Pheromone Update #\n\t # ========================================================================= #\n\n # Update pheromone matrix in every 0.1s\n time_cur = time.clock()\n if time_cur-phero[0].step_timer >= 0.1: \n phero[0].update(self.phero_min, self.phero_max)\n phero[0].step_timer = time_cur\n\n #log_time_cur = time.clock()\n # Logging Pheromone grid\n # if log_time_cur - self.log_timer >= 2:\n # self.log_file = open(\"phero_value.txt\", \"a+\")\n # np.savetxt(self.log_file, self.pheromone.grid, delimiter=',')\n # self.log_file.close()\n\n # ========================================================================= #\n\t # Save Pheromone #\n\t # ========================================================================= #\n \n '''Saving pheromone'''\n # # Save after 20s\n # time_check = time.time()\n # if time_check - self.startTime >= 20 and self.is_saved is False:\n # self.pheromone.save(\"simple_collision_diffused\")\n # self.is_saved = True\n \n # Save the pheromone when robot return home.\n # distance_to_origin = sqrt(x**2+y**2)\n # if self.is_saved is False and distance_to_origin < 0.05:\n # self.pheromone.save(\"foraging_static\")\n # self.is_saved = True\n # self.is_phero_inj = False\n\n # ========================================================================= #\n\t # Load Pheromone #\n\t # ========================================================================= #\n \n '''Loading Pheromone'''\n # Load the pheromone\n # 1. When use continuous contoller. (1) It hasn't previously loaded, (2) pheromone injection is disabled, \n # (3) service is requested by continuous controller script\n # if self.is_loaded is False and self.is_phero_inj is False and self.is_service_requested is True:\n # try:\n # self.pheromone.load(\"foraging\")\n # self.is_loaded = True\n # except IOError as io:\n # print(\"No pheromone to load: %s\"%io)\n \n # 2. When reset is requested.\n if self.is_reset == True:\n try:\n for i in range(self.num_robots): # Reset the pheromone grid\n self.pheromone[i].reset()\n #self.pheromone.load(\"simple_collision_diffused\") # you can load any types of pheromone grid\n print(\"Pheromone grid reset!\")\n self.is_reset = False # Reset the flag for next use\n except IOError as io:\n print(\"No pheromone to load: %s\"%io)\n\n\nclass Pheromone():\n\n # ========================================================================= #\n\t# Pheromone Class #\n\t# ========================================================================= #\n '''\n Pheromone Class\n 1. Initialise Pheromone\n 2. Get Pheromone\n 3. Set Pheromone\n 4. Inject Pheromone at the specified position (Plain + Grad)\n 5. Circle (Plain + Grad) \n 6. Update Pheromone (Evaporation & Diffusion)\n 7. Save Pheormone Grid\n 8. Load Pheromone Grid\n '''\n\n def __init__(self, name, evaporation, diffusion):\n self.name = name\n self.resolution = 10 # grid cell size = 1 m / resolution\n self.size = 10 # m\n self.num_cell = self.resolution * self.size + 1\n if self.num_cell % 2 == 0:\n raise Exception(\"Number of cell is even. It needs to be an odd number\")\n self.grid = np.zeros((self.num_cell, self.num_cell))\n self.grid_copy = np.zeros((self.num_cell, self.num_cell))\n self.evaporation = evaporation # elapsed seconds for pheromone to be halved\n self.diffusion = diffusion\n self.isDiffusion = True\n self.isEvaporation = True\n\n # Timers\n self.update_timer = time.clock()\n self.step_timer = time.clock()\n self.injection_timer = time.clock()\n\n def getPhero(self, x, y):\n return self.grid[x, y]\n\n def setPhero(self, x, y, value):\n self.grid[x, y] = value\n\n # Inject pheromone at the robot position and nearby cells in square. Size must be an odd number. \n def injection(self, x, y, value, size, maxp):\n if size % 2 == 0:\n raise Exception(\"Pheromone injection size must be an odd number.\")\n time_cur = time.clock()\n if time_cur-self.injection_timer > 0.1:\n for i in range(size):\n for j in range(size):\n self.grid[x-(size-1)/2+i, y-(size-1)/2+j] += value\n if self.grid[x-(size-1)/2+i, y-(size-1)/2+j] >= maxp:\n self.grid[x-(size-1)/2+i, y-(size-1)/2+j] = maxp\n self.injection_timer = time_cur\n def gradInjection(self, x, y, value, min_val, rad, maxp):\n\n time_cur = time.clock()\n if time_cur-self.injection_timer > 0.1:\n radius = int(rad*self.resolution)\n #print(\"Radius: {}\".format(radius))\n for i in range(-radius, radius):\n for j in range(-radius, radius):\n if sqrt(i**2+j**2) <= radius and (x+i < self.num_cell-1 and x+i >= 0) and (y+i < self.num_cell-1 and y+i >= 0):\n self.grid[x+i, y+j] = value - value*(sqrt(i**2+j**2))/radius + min_val\n if self.grid[x+i, y+j] >= maxp:\n self.grid[x+i, y+j] = maxp\n self.injection_timer = time_cur\n\n def circle(self, x, y, value, radius):\n radius = int(radius*self.resolution)\n for i in range(-radius, radius):\n for j in range(-radius, radius):\n if sqrt(i**2+j**2) <= radius:\n self.grid[x+i, y+j] = value\n\n def gradCircle(self, x, y, value, radius):\n radius = int(radius*self.resolution)\n for i in range(-radius, radius):\n for j in range(-radius, radius):\n if sqrt(i**2+j**2) <= radius:\n self.grid[x+i, y+j] = value/(exp(sqrt(i**2+j**2))/10)\n\n \n # Update all the pheromone values depends on natural phenomena, e.g. evaporation\n def update(self, min, max):\n time_cur = time.clock()\n time_elapsed = time_cur - self.update_timer\n self.update_timer = time_cur\n\n if self.isDiffusion == True:\n # Diffusion \n for i in range(self.num_cell):\n for j in range(self.num_cell):\n self.grid_copy[i, j] += 0.9*self.grid[i, j]\n if i >= 1: self.grid_copy[i-1, j] += 0.025*self.grid[i, j]\n if j >= 1: self.grid_copy[i, j-1] += 0.025*self.grid[i, j]\n if i < self.num_cell-1: self.grid_copy[i+1, j] += 0.025*self.grid[i, j]\n if j < self.num_cell-1: self.grid_copy[i, j+1] += 0.025*self.grid[i, j] \n self.grid = np.copy(self.grid_copy)\n self.grid_copy = np.zeros((self.num_cell, self.num_cell))\n if self.isEvaporation == True:\n # Evaporation\n decay = 2**(-time_elapsed/self.evaporation)\n for i in range(self.num_cell):\n for j in range(self.num_cell):\n self.grid[i, j] = decay * self.grid[i, j]\n\n def reset(self):\n self.grid = np.zeros((self.num_cell, self.num_cell))\n\n def save(self, file_name):\n # dir_name = os.path.dirname('/home/swn/catkin_ws/src/turtlebot3_waypoint_navigation/tmp/{}.npy'.format(file_name))\n # if not os.path.exists(dir_name):\n # os.makedirs(dir_name)\n with open('/home/swn/catkin_ws/src/turtlebot3_waypoint_navigation/tmp/{}.npy'.format(file_name), 'wb') as f:\n np.save(f, self.grid)\n print(\"The pheromone matrix {} is successfully saved\".format(file_name))\n\n def load(self, file_name):\n with open('/home/swn/catkin_ws/src/turtlebot3_waypoint_navigation/tmp/{}.npy'.format(file_name), 'rb') as f:\n self.grid = np.load(f)\n #os.remove('/home/swn/catkin_ws/src/turtlebot3_waypoint_navigation/tmp/{}.npy'.format(file_name))\n print(\"The pheromone matrix {} is successfully loaded\".format(file_name))\n\n \nif __name__ == \"__main__\":\n Phero1 = Pheromone('1', 0.5, 0)\n Phero2 = Pheromone('2', 0.5, 0)\n Phero = [Phero1, Phero2]\n node1 = Node(Phero)\n while True:\n node1.pheroCallback()\n \n\n"
] |
[
[
"numpy.asarray",
"numpy.save",
"numpy.copy",
"numpy.load",
"numpy.zeros"
]
] |
StepNeverStop/Staged-Experience-Mechanism
|
[
"52bd0edf352b7d07f5d0ae25aac857f39976c523"
] |
[
"gym/gym/wrappers/pixel_observation.py"
] |
[
"\"\"\"An observation wrapper that augments observations by pixel values.\"\"\"\n\nimport collections\nimport copy\n\nimport numpy as np\n\nfrom gym import spaces\nfrom gym import ObservationWrapper\n\nSTATE_KEY = 'state'\n\n\nclass PixelObservationWrapper(ObservationWrapper):\n \"\"\"Augment observations by pixel values.\"\"\"\n\n def __init__(self,\n env,\n pixels_only=True,\n render_kwargs=None,\n pixel_keys=('pixels', )):\n \"\"\"Initializes a new pixel Wrapper.\n\n Args:\n env: The environment to wrap.\n pixels_only: If `True` (default), the original observation returned\n by the wrapped environment will be discarded, and a dictionary\n observation will only include pixels. If `False`, the\n observation dictionary will contain both the original\n observations and the pixel observations.\n render_kwargs: Optional `dict` containing keyword arguments passed\n to the `self.render` method.\n pixel_keys: Optional custom string specifying the pixel\n observation's key in the `OrderedDict` of observations.\n Defaults to 'pixels'.\n\n Raises:\n ValueError: If `env`'s observation spec is not compatible with the\n wrapper. Supported formats are a single array, or a dict of\n arrays.\n ValueError: If `env`'s observation already contains any of the\n specified `pixel_keys`.\n \"\"\"\n\n super(PixelObservationWrapper, self).__init__(env)\n\n if render_kwargs is None:\n render_kwargs = {}\n\n for key in pixel_keys:\n render_kwargs.setdefault(key, {})\n\n render_mode = render_kwargs[key].pop('mode', 'rgb_array')\n assert render_mode == 'rgb_array', render_mode\n render_kwargs[key]['mode'] = 'rgb_array'\n\n wrapped_observation_space = env.observation_space\n\n if isinstance(wrapped_observation_space, spaces.Box):\n self._observation_is_dict = False\n invalid_keys = set([STATE_KEY])\n elif isinstance(wrapped_observation_space,\n (spaces.Dict, collections.MutableMapping)):\n self._observation_is_dict = True\n invalid_keys = set(wrapped_observation_space.spaces.keys())\n else:\n raise ValueError(\"Unsupported observation space structure.\")\n\n if not pixels_only:\n # Make sure that now keys in the `pixel_keys` overlap with\n # `observation_keys`\n overlapping_keys = set(pixel_keys) & set(invalid_keys)\n if overlapping_keys:\n raise ValueError(\"Duplicate or reserved pixel keys {!r}.\"\n .format(overlapping_keys))\n\n if pixels_only:\n self.observation_space = spaces.Dict()\n elif self._observation_is_dict:\n self.observation_space = copy.deepcopy(wrapped_observation_space)\n else:\n self.observation_space = spaces.Dict()\n self.observation_space.spaces[STATE_KEY] = wrapped_observation_space\n\n # Extend observation space with pixels.\n\n pixels_spaces = {}\n for pixel_key in pixel_keys:\n pixels = self.env.render(**render_kwargs)\n\n if np.issubdtype(pixels.dtype, np.integer):\n low, high = (0, 255)\n elif np.issubdtype(pixels.dtype, np.float):\n low, high = (-float('inf'), float('inf'))\n else:\n raise TypeError(pixels.dtype)\n\n pixels_space = spaces.Box(\n shape=pixels.shape, low=low, high=high, dtype=pixels.dtype)\n pixels_spaces[pixel_key] = pixels_space\n\n self.observation_space.spaces.update(pixels_spaces)\n\n self._env = env\n self._pixels_only = pixels_only\n self._render_kwargs = render_kwargs\n self._pixel_keys = pixel_keys\n\n def observation(self, observation):\n pixel_observation = self._add_pixel_observation(observation)\n return pixel_observation\n\n def _add_pixel_observation(self, observation):\n if self._pixels_only:\n observation = collections.OrderedDict()\n elif self._observation_is_dict:\n observation = type(observation)(observation)\n else:\n observation = collections.OrderedDict()\n observation[STATE_KEY] = observation\n\n pixel_observations = {\n pixel_key: self.env.render(**self._render_kwargs[pixel_key])\n for pixel_key in self._pixel_keys\n }\n\n observation.update(pixel_observations)\n\n return observation\n"
] |
[
[
"numpy.issubdtype"
]
] |
ehthiede/python-pygelib
|
[
"8140ce7ab05a47dad202b2b7f1e8aee5309723e2"
] |
[
"src/pygelib/SO3TensorArray.py"
] |
[
"import torch\nimport operator\n\n\nclass SO3TensorArray(object):\n \"\"\"\n Base class for a collection of tensors, each of which is associated with a\n specific value of ell.\n \"\"\"\n def __init__(self, data):\n if isinstance(data, type(self)):\n data = data.data\n else:\n self._data = list(data)\n\n def __len__(self):\n \"\"\"\n Length of SO3Vec.\n \"\"\"\n return len(self._data)\n\n @property\n def maxl(self):\n \"\"\"\n Maximum ell of SO3 object.\n\n Returns\n -------\n int\n \"\"\"\n return len(self._data) - 1\n\n def truncate(self, maxl):\n \"\"\"\n Update the maximum ell by truncating parts of the\n :class:`SO3TensorArray` if they correspond to weights greater than `maxl`.\n\n Parameters\n ----------\n maxl : :obj:`int`\n Maximum weight to truncate the representation to.\n\n Returns\n -------\n :class:`SO3TensorArray` subclass\n Truncated :class:`SO3TensorArray`\n \"\"\"\n return self[:maxl+1]\n\n @property\n def shapes(self):\n \"\"\"\n Get a list of shapes of each :obj:`torch.Tensor` in the object.\n \"\"\"\n return [p.shape for p in self]\n\n @property\n def device(self):\n if any(self._data[0].device != part.device for part in self._data):\n raise ValueError('Not all parts on same device!')\n\n return self._data[0].device\n\n @property\n def dtype(self):\n if any(self._data[0].dtype != part.dtype for part in self._data):\n raise ValueError('Not all parts using same data type!')\n\n return self._data[0].dtype\n\n @property\n def real(self):\n output_class = type(self)\n return output_class([i[0] for i in self._data])\n\n @property\n def imag(self):\n output_class = type(self)\n return output_class([i[1] for i in self._data])\n\n def keys(self):\n return range(len(self))\n\n def values(self):\n return iter(self._data)\n\n def items(self):\n return zip(range(len(self)), self._data)\n\n def __iter__(self):\n \"\"\"\n Loop over contained :obj:`torch.tensor` objects\n \"\"\"\n for t in self._data:\n yield t\n\n def __getitem__(self, idx):\n \"\"\"\n Get a specific contained :obj:`torch.tensor` objects\n \"\"\"\n if type(idx) is slice:\n return self.__class__(self._data[idx])\n else:\n return self._data[idx]\n\n def __setitem__(self, idx, val):\n \"\"\"\n Set a specific contained :obj:`torch.tensor` objects\n \"\"\"\n self._data[idx] = val\n\n def __eq__(self, other):\n \"\"\"\n Check equality of two objects.\n \"\"\"\n if len(self) != len(other):\n return False\n return all((part1 == part2).all() for part1, part2 in zip(self, other))\n\n @staticmethod\n def allclose(rep1, rep2, **kwargs):\n if len(rep1) != len(rep2):\n raise ValueError('')\n return all(torch.allclose(part1, part2, **kwargs) for part1, part2 in zip(rep1, rep2))\n\n def __str__(self):\n return str(list(self._data))\n\n __datar__ = __str__\n\n @classmethod\n def requires_grad(cls):\n # WHAT IS THIS AND WHY IS IT HERE?\n return cls([t.requires_grad() for t in self._data])\n\n def requires_grad_(self, requires_grad=True):\n self._data = [t.requires_grad_(requires_grad) for t in self._data]\n return self\n\n def to(self, *args, **kwargs):\n self._data = [t.to(*args, **kwargs) for t in self._data]\n return self\n\n def cpu(self):\n self._data = [t.cpu() for t in self._data]\n return self\n\n def cuda(self, **kwargs):\n self._data = [t.cuda(**kwargs) for t in self._data]\n return self\n\n def long(self):\n self._data = [t.long() for t in self._data]\n return self\n\n def byte(self):\n self._data = [t.byte() for t in self._data]\n return self\n\n def bool(self):\n self._data = [t.bool() for t in self._data]\n return self\n\n def half(self):\n self._data = [t.half() for t in self._data]\n return self\n\n def float(self):\n self._data = [t.float() for t in self._data]\n return self\n\n def double(self):\n self._data = [t.double() for t in self._data]\n return self\n\n def clone(self):\n return type(self)([t.clone() for t in self])\n\n def detach(self):\n return type(self)([t.detach() for t in self])\n\n @property\n def data(self):\n return self._data\n\n @property\n def grad(self):\n return type(self)([t.grad for t in self])\n\n def __add__(self, other):\n \"\"\"\n Add element wise `torch.Tensors`\n \"\"\"\n op = operator.add\n if isinstance(other, SO3TensorArray):\n return _add_SO3TensorArrays(self, other, op)\n else:\n try:\n # Checks that real and imag parts are accessible\n # before we start multiplication.\n other.real\n other.imag\n return _add_SO3TensorArray_by_complex_scalar(self, other, op)\n except RuntimeError:\n return _add_SO3TensorArray_by_real_scalar(self, other, op)\n\n def __sub__(self, other):\n \"\"\"\n Add element wise `torch.Tensors`\n \"\"\"\n op = operator.sub\n if isinstance(other, SO3TensorArray):\n return _add_SO3TensorArrays(self, other, op)\n else:\n try:\n # Checks that real and imag parts are accessible\n # before we start multiplication.\n other.real\n other.imag\n return _add_SO3TensorArray_by_complex_scalar(self, other, op)\n except RuntimeError:\n return _add_SO3TensorArray_by_real_scalar(self, other, op)\n\n def __mul__(self, other):\n \"\"\"\n Add element wise `torch.Tensors`\n \"\"\"\n op = operator.mul\n if isinstance(other, SO3TensorArray):\n return _multiply_SO3TensorArrays(self, other, op)\n else:\n try:\n # Checks that real and imag parts are accessible\n # before we start multiplication.\n other.real\n other.imag\n return _multiply_SO3TensorArray_by_complex_scalar(self, other, op)\n except RuntimeError:\n return _multiply_SO3TensorArray_by_real_scalar(self, other, op)\n\n def __matmul__(self, other):\n \"\"\"\n Add element wise `torch.Tensors`\n \"\"\"\n op = operator.matmul\n if isinstance(other, SO3TensorArray):\n return _multiply_SO3TensorArrays(self, other, op)\n else:\n try:\n # Checks that real and imag parts are accessible\n # before we start multiplication.\n other.real\n other.imag\n return _multiply_SO3TensorArray_by_complex_scalar(self, other, op)\n except RuntimeError:\n return _multiply_SO3TensorArray_by_real_scalar(self, other, op)\n\n def __truediv__(self, other):\n if isinstance(other, SO3TensorArray):\n return _divide_SO3TensorArrays(self, other)\n else:\n try:\n # Checks that real and imag parts are accessible\n # before we start multiplication.\n other.real\n other.imag\n return _divide_SO3TensorArray_by_complex_scalar(self, other)\n except RuntimeError:\n return _divide_SO3TensorArray_by_real_scalar(self, other)\n\n\n# Base Addition Routines\ndef _add_SO3TensorArrays(tensor_array_1, tensor_array_2, op):\n output_class = type(tensor_array_1)\n output_parts = []\n for t1_r, t1_i, t2_r, t2_i in zip(tensor_array_1.real, tensor_array_1.imag, tensor_array_2.real, tensor_array_2.imag):\n output_parts.append(torch.stack([op(t1_r, t2_r), op(t1_i, t2_i)], dim=0))\n return output_class(output_parts)\n\n\ndef _add_SO3TensorArray_by_complex_scalar(tensor_array, scalar, op):\n output_class = type(tensor_array)\n output_parts = []\n for t_r, t_i, in zip(tensor_array.real, tensor_array.imag):\n output_parts.append(torch.stack([op(t_r,scalar.real), op(t_i,scalar.imag)], dim=0))\n return output_class(output_parts)\n\n\ndef _add_SO3TensorArray_by_real_scalar(tensor_array, scalar, op):\n output_class = type(tensor_array)\n output_parts = []\n for t_r, t_i in zip(tensor_array.real, tensor_array.imag):\n output_parts.append(torch.stack([op(t_r, scalar),\n t_i], dim=0))\n return output_class(output_parts)\n\n\n# Base Multiplication Routines\ndef _multiply_SO3TensorArrays(tensor_array_1, tensor_array_2, op):\n output_class = type(tensor_array_1)\n output_parts = []\n for t1_r, t1_i, t2_r, t2_i in zip(tensor_array_1.real, tensor_array_1.imag, tensor_array_2.real, tensor_array_2.imag):\n output_parts.append(torch.stack([op(t1_r, t2_r) - op(t1_i, t2_i),\n op(t1_r, t2_i) + op(t1_i, t2_r)], dim=0))\n return output_class(output_parts)\n\n\ndef _multiply_SO3TensorArray_by_complex_scalar(tensor_array, scalar, op):\n output_class = type(tensor_array)\n output_parts = []\n for t_r, t_i in zip(tensor_array.real, tensor_array.imag):\n output_parts.append(torch.stack([op(t_r, scalar.real) - op(t_i, scalar.imag),\n op(t_r, scalar.imag) + op(t_i, scalar.real)], dim=0))\n return output_class(output_parts)\n\n\ndef _multiply_SO3TensorArray_by_real_scalar(tensor_array, scalar, op):\n output_class = type(tensor_array)\n output_parts = []\n for t_r, t_i in zip(tensor_array.real, tensor_array.imag):\n product = op(t_r, scalar)\n output_parts.append(torch.stack([product,\n torch.zeros_like(product)], dim=0))\n return output_class(output_parts)\n\n\n# Base division Routines\ndef _divide_SO3TensorArrays(tensor_array_1, tensor_array_2):\n # op = operator.divide\n output_class = type(tensor_array_1)\n output_parts = []\n for t1_r, t1_i, t2_r, t2_i in zip(tensor_array_1.real, tensor_array_1.imag, tensor_array_2.real, tensor_array_2.imag):\n out_r = (t1_r * t2_r + t1_i * t2_i) / (t2_r * t2_r + t2_i * t2_i)\n out_i = (t1_i * t2_r - t1_r * t2_i) / (t2_r * t2_r + t2_i * t2_i)\n output_parts.append(torch.stack([out_r, out_i]))\n return output_class(output_parts)\n\n\ndef _divide_SO3TensorArray_by_complex_scalar(tensor_array, scalar, op):\n op = operator.divide\n output_class = type(tensor_array)\n output_parts = []\n for t_r, t_i in zip(tensor_array.real, tensor_array.imag):\n output_parts.append(torch.stack([op(t_r, scalar.real) - op(t_i, scalar.imag),\n op(t_r, scalar.imag) + op(t_i, scalar.real)], dim=0))\n return output_class(output_parts)\n\n\ndef _divide_SO3TensorArray_by_real_scalar(tensor_array, scalar, op):\n op = operator.divide\n output_class = type(tensor_array)\n output_parts = []\n for t_r, t_i in zip(tensor_array.real, tensor_array.imag):\n product = op(t_r, scalar)\n output_parts.append(torch.stack([product,\n torch.zeros_like(product)], dim=0))\n return output_class(output_parts)\n"
] |
[
[
"torch.stack",
"torch.allclose",
"torch.zeros_like"
]
] |
shrija14/Multilingual-Deep-Neural-Math-Word-Problem-Solver
|
[
"3d37cd3fd8e6493a87c95ed25406f65ad7070868"
] |
[
"FirstStage/src/model/attention_1.py"
] |
[
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass Attention_1(nn.Module):\n def __init__(self, dim):\n super(Attention_1, self).__init__()\n self.linear_out = nn.Linear(dim*2, dim)\n self.mask = None\n\n def set_mask(self, mask):\n self.mask = mask\n\n def forward(self, output, context):\n '''\n output: decoder, (batch, 1, hiddem_dim2)\n context: from encoder, (batch, n, hidden_dim1)\n actually, dim2 == dim1, otherwise cannot do matrix multiplication \n '''\n batch_size = output.size(0)\n hidden_size = output.size(2)\n input_size = context.size(1)\n # (b, o, dim) * (b, dim, i) -> (b, o, i)\n attn = torch.bmm(output, context.transpose(1,2))\n if self.mask is not None:\n attn.data.masked_fill_(self.mask, -float('inf'))\n attn = F.softmax(attn.view(-1, input_size), dim=1).view(batch_size, -1, input_size)\n\n # (b, o, i) * (b, i, dim) -> (b, o, dim)\n mix = torch.bmm(attn, context)\n\n combined = torch.cat((mix, output), dim=2)\n\n output = F.tanh(self.linear_out(combined.view(-1, 2*hidden_size)))\\\n .view(batch_size, -1, hidden_size)\n\n # output: (b, o, dim)\n # attn : (b, o, i)\n return output, attn\n\n"
] |
[
[
"torch.nn.Linear",
"torch.bmm",
"torch.cat"
]
] |
umbrellagong/VHGPR
|
[
"859c135f8a18be0a7e679d44cf292c2825ccd09d"
] |
[
"fourbranches.py"
] |
[
"import numpy as np\n\ndef f(X):\n return mean(X) + np.random.normal(0, std(X))\n\ndef mean(X, deviation=5): \n X = np.array(X)\n if X.ndim == 1:\n X=np.atleast_2d(X)\n X1 = 3 + 0.1*(X[:,0]-X[:,1])**2 - (X[:,0]+X[:,1])/np.sqrt(2)\n X2 = 3 + 0.1*(X[:,0]-X[:,1])**2 + (X[:,0]+X[:,1])/np.sqrt(2)\n X3 = (X[:,0]-X[:,1]) + 6/np.sqrt(2)\n X4 = (X[:,1]-X[:,0]) + 6/np.sqrt(2)\n mid=np.stack((X1,X2,X3,X4)) \n return -np.amin(mid,axis=0) + deviation\n\ndef std(X): \n return mean(X) / 6"
] |
[
[
"numpy.sqrt",
"numpy.amin",
"numpy.stack",
"numpy.atleast_2d",
"numpy.array"
]
] |
lvxingvir/template
|
[
"089f5817e031a7c2b2d82e239158a6a5488b3b26"
] |
[
"drutils/augmentation.py"
] |
[
"\"\"\"This file contains utility functions used for numpy-based input augmentation\n\nTODO: make more general for 3D images\n\"\"\"\n\nimport logging\nimport cv2\nimport random\nimport scipy.ndimage\nfrom skimage.filters import threshold_otsu, gaussian\ntry:\n import dicom\nexcept:\n import pydicom as dicom\nimport numpy as np\nfrom io import BytesIO\nfrom skimage.morphology import erosion, square, disk\nfrom skimage import measure\n\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')\n\n\ndef apply_mirroring(data, labels):\n \"\"\"\n Apply mirroring to left, right, top, and bottom\n Args:\n data: data array representing 1 image [h, w]\n labels: labels array [h, w, 2] (alphabet limited to (0, 1))\n\n Returns:\n Mirrored data and labels\n \"\"\"\n data_shape = data.shape[0:2]\n data = np.lib.pad(data, ((data_shape[0]-1, data_shape[0]-1), (data_shape[1]-1, data_shape[1]-1)), 'reflect')\n labels = np.lib.pad(labels, ((data_shape[0]-1, data_shape[0]-1), (data_shape[1]-1, data_shape[1]-1), (0, 0)), 'reflect')\n return data, labels\n\n\ndef random_rotation(data, labels):\n \"\"\"\n Perform random rotation on data and labels\n Args:\n data: data array representing 1 image [h, w]\n labels: labels array [h, w, 2] (alphabet limited to (0, 1))\n\n Returns:\n Rotated data and labels\n \"\"\"\n angle_deg = random.uniform(-180.0, 180.0)\n data = scipy.ndimage.interpolation.rotate(data, angle_deg, reshape=False)\n labels = scipy.ndimage.interpolation.rotate(labels, angle_deg, reshape=False)\n return data, labels\n\n\ndef random_flip_left_right(data, labels):\n \"\"\"\n Perform random flip left and right on data and labels\n Args:\n data: data array representing 1 image [h, w]\n labels: labels array [h, w, 2] (alphabet limited to (0, 1))\n\n Returns:\n Randomly flipped data and labels\n \"\"\"\n flip = bool(random.getrandbits(1))\n if flip:\n data = np.fliplr(data)\n labels = np.fliplr(labels)\n return data, labels\n\n\ndef get_next_dividable_shape(input_shape, block_shape):\n \"\"\"Get the minimum new_shape >= shape that is dividable by block_shape\n\n Args:\n input_shape: original shape\n block_shape: shape to be multiples of. Can be scalar, or a list with the same shape as input_shape\n\n Returns:\n new_shape\n \"\"\"\n input_shape = np.array(input_shape)\n block_shape = np.array(block_shape)\n residual_shape = input_shape - (input_shape // block_shape) * block_shape\n # if residual_shape == (0, 0), do not change shape\n new_shape = input_shape + (block_shape - residual_shape) % block_shape\n return new_shape\n\n\ndef crop_or_pad(image_array, target_shape):\n \"\"\"Crop or pad image_array to target_shape\n\n Use the top left corner (0, 0) as anchor and only pad or crop in the bottom right corner.\n\n NB: this only works for 2D for now\n\n Args:\n image_array:\n target_shape:\n\n Returns:\n\n \"\"\"\n dtype = image_array.dtype\n source_shape = image_array.shape[:2]\n target_shape = target_shape[:2]\n if tuple(source_shape) == tuple(target_shape):\n return image_array\n max_shape = tuple(np.max([source_shape, target_shape], axis=0).astype(np.int))\n image_array_new = np.zeros(max_shape, dtype=dtype)\n image_array_new[:source_shape[0], :source_shape[1]] = image_array\n image_array_new = image_array_new[:target_shape[0], :target_shape[1]]\n assert tuple(image_array_new.shape) == tuple(target_shape)\n return image_array_new\n\n\ndef center_pad(image, target_shape, mode='constant'):\n \"\"\"Pad image symmetrically to target_shape\n\n Args:\n image: input np array\n target_shape: final shape\n mode: np.pad mode\n\n \"\"\"\n target_shape = np.asarray(target_shape)\n source_shape = np.array(image.shape)\n # top/left padding and bottom/right padding\n padding_1 = (target_shape - source_shape) // 2\n padding_2 = (target_shape - source_shape) - (target_shape - source_shape) // 2\n image = np.pad(image, list(zip(padding_1, padding_2)), mode=mode)\n assert image.shape == tuple(target_shape)\n return image\n\n\ndef center_crop(data, crop_shape, labels=None):\n \"\"\"\n Perform random cropping after optional padding\n Args:\n data: data array representing 1 image [h, w]\n labels: labels array [h, w, 2] (unique values limited to (0, 1)), could be None\n crop_shape: target shape after cropping\n\n Returns:\n Randomly cropped data and labels\n \"\"\"\n data_shape = data.shape[0:2]\n assert (crop_shape[0] <= data_shape[0])\n assert (crop_shape[1] <= data_shape[1])\n\n nh = int((data_shape[0] - crop_shape[0]) / 2)\n nw = int((data_shape[1] - crop_shape[1]) / 2)\n data = data[nh:nh + crop_shape[0], nw:nw + crop_shape[1]]\n if labels is not None:\n labels = labels[nh:nh + crop_shape[0], nw:nw + crop_shape[1], :]\n return data, labels\n return data\n\n\ndef center_crop_or_pad(image, target_shape, mode='constant'):\n \"\"\"Center crop or pad to target_shape\n\n Only works for 2D images\n\n Args:\n image:\n target_shape:\n mode:\n\n Returns:\n\n \"\"\"\n pad_target_shape = np.maximum(np.array(target_shape)[:2], image.shape[:2])\n image = center_pad(image, target_shape=pad_target_shape, mode=mode)\n image = center_crop(image, crop_shape=target_shape)\n return image\n\n\ndef crop_around_point(image_array, center_yx, target_shape):\n \"\"\"Center crop an image array around a point\n\n Args:\n image_array:\n center_yx:\n target_shape:\n\n Returns:\n\n \"\"\"\n pad_y, pad_x = ((np.array(target_shape) + 1) // 2).astype(np.int)\n pad_width = ((pad_y, pad_y), (pad_x, pad_x))\n image_array = np.pad(image_array, pad_width=pad_width, mode='constant')\n ymin, xmin = (np.array(center_yx) + np.array([pad_y, pad_x]) - np.array(target_shape) // 2).astype(np.int)\n ymax, xmax = (np.array([ymin, xmin]) + np.array(target_shape)).astype(np.int)\n cropped_array = image_array[ymin:ymax, xmin:xmax]\n assert cropped_array.shape == tuple(target_shape)\n return cropped_array\n\n\ndef random_crop(data, labels, crop_shape, padding=None):\n \"\"\"\n Perform random cropping after optional padding\n Args:\n data: data array representing 1 image [h, w]\n labels: labels array [h, w, 2] (alphabet limited to (0, 1))\n crop_shape: target shape after cropping\n padding: how many pixels to pad before cropping\n\n Returns:\n Randomly cropped data and labels\n \"\"\"\n data_shape = data.shape[0:2]\n\n if padding:\n data_shape = (data_shape[0] + 2 * padding, data_shape[1] + 2 * padding)\n npad = ((padding, padding), (padding, padding), (0, 0))\n data = np.lib.pad(data, pad_width=npad, mode='constant', constant_values=0)\n labels = np.lib.pad(labels, pad_width=npad, mode='constant', constant_values=0)\n\n nh = random.randint(0, data_shape[0] - crop_shape[0])\n nw = random.randint(0, data_shape[1] - crop_shape[1])\n data = data[nh:nh + crop_shape[0], nw:nw + crop_shape[1]]\n labels = labels[nh:nh + crop_shape[0], nw:nw + crop_shape[1], :]\n return data, labels\n\n\ndef random_resize(data, labels):\n \"\"\"Perform random resizing\n\n Args:\n data: data array representing 1 image [h, w]\n labels: labels array [h, w, 2] (alphabet limited to (0, 1))\n\n Returns:\n Randomly resized data and labels, potentially with different shape\n \"\"\"\n data_shape = data.shape[0:2]\n resize_ratio = np.random.uniform(low=1.0, high=1.2, size=2)\n\n data = scipy.ndimage.interpolation.zoom(input=data, zoom=resize_ratio)\n labels = scipy.ndimage.interpolation.zoom(input=labels, zoom=np.append(resize_ratio, 1.0))\n labels = np.around(labels)\n return data, labels\n\n\ndef resize(image, scale=None, dst_shape=(0, 0), interpolation=None):\n \"\"\"Customize resize wrapper of cv2.resize\n\n Automatically select best interpolation method.\n Note: Pay special attention to the x and y dimension. Numpy uses (y, x) order but openCV\n uses (x, y) order.\n\n Args:\n image:\n scale:\n dst_shape: (x, y) order\n interpolation:\n \"\"\"\n src_shape = np.asarray(image.shape) # in the order of (y, x, ...)\n src_shape = src_shape[:2][::-1] # get the first two dimension and flip them\n if scale is not None:\n dst_shape = (src_shape * scale).astype(np.int)\n else:\n dst_shape = np.asarray(dst_shape).astype(np.int)\n if interpolation is None:\n if (scale is not None and scale >= 1) or np.any(dst_shape > src_shape):\n interpolation = cv2.INTER_LINEAR\n else:\n interpolation = cv2.INTER_AREA\n image_resized = cv2.resize(image, tuple(dst_shape), interpolation=interpolation)\n return image_resized\n\n\ndef soft_rescale(data):\n \"\"\"Soft scale data back to [0, 1]\n\n If data is in [0, 1], do nothing. Otherwise, scale the side outside this bound back to [0, 1]\n\n Args:\n data:\n\n Returns:\n\n \"\"\"\n a_max = max(data.max(), 1)\n a_min = min(data.min(), 0)\n data = (data - a_min) / (a_max - a_min)\n return data\n\n\ndef random_brightness(data, labels, max_delta=0.2):\n \"\"\"Perform random brightness adjustment. Add a random number to the image\n\n Args:\n data: a float array in [0, 1]\n labels:\n max_delta: maximum adjustment, in [-1, 1]\n\n Returns:\n\n \"\"\"\n delta = np.random.uniform(low=-max_delta, high=max_delta)\n data = data + delta\n # scale back to [0, 1]\n data = soft_rescale(data)\n return data, labels\n\n\ndef random_contrast(data, labels, lower=0.8, upper=1.2):\n \"\"\"Perform random contrast adjustment for 2d images\n For each `x` pixel in a channel, `(x - mean) * contrast_factor + mean`.\n\n Args:\n data: numpy array with values in [0, 1]\n labels:\n lower: lower bound of contrast adjustment, [0, 1]\n upper: upper bound of contrast adjustment, [1, inf]\n\n Returns:\n\n \"\"\"\n contast_factor = np.random.uniform(low=lower, high=upper)\n mean = data.mean()\n data = (data - mean) * contast_factor + mean\n # scale back to [0, 1]\n data = soft_rescale(data)\n return data, labels\n\n\ndef pad(image_array, padding=(0, 0)):\n \"\"\"Pad image with zero\n\n Args:\n image_array:\n padding:\n\n Returns:\n\n \"\"\"\n shape = np.array(image_array.shape)\n new_shape = shape + 2 * padding\n image_array_padded = np.zeros(new_shape)\n image_array_padded[padding[0]:(shape[0] - padding[0]), padding[1]:(shape[1] - padding[1])] = image_array\n return image_array_padded\n\n\ndef normalize(image_array, a_min=-np.inf, a_max=np.inf,\n how='extend', lower_sigma=3, upper_sigma=6, bg_thresh=None, force_otsu=False):\n \"\"\"Clip image and then normalize to [0, 1]\n\n Args:\n image_array: the input numpy array\n a_min:\n a_max:\n lower_sigma:\n upper_sigma:\n bg_thresh:\n how: the method to normalize, can be `optimize` or `extend`\n `optimize`: use automatic histogram normalization to optimize contrast\n `extend`: clip image and extend max to 1 and min to 0\n\n Returns:\n\n \"\"\"\n image_array = image_array.astype(np.float)\n if how == 'optimize':\n image_array = normalize_auto(image_array, lower_sigma=lower_sigma, upper_sigma=upper_sigma,\n bg_thresh=bg_thresh, force_otsu=force_otsu)\n elif how == 'extend':\n if 0 < a_min < 1 and 0 < a_max < 1:\n if bg_thresh:\n image_array_fg = image_array[image_array > bg_thresh]\n a_max = np.percentile(image_array_fg, a_max)\n a_min = np.percentile(image_array_fg, a_min)\n image_array = np.clip(np.fabs(image_array), a_min, a_max)\n image_array -= np.amin(image_array)\n if np.amax(image_array) == 0:\n # uniform image\n return np.ones_like(image_array)\n image_array /= np.amax(image_array)\n elif how == 'raw':\n image_array /= 255\n else:\n raise ValueError('Unknown option {}'.format(how))\n return image_array\n\n\ndef normalize_auto(image_array, lower_sigma=2, upper_sigma=4, bg_thresh=None, bg_percentile=20, force_otsu=False):\n \"\"\"Clip mammo to appropriate window\n\n Note: goals of this auto normalization algorithm:\n 1. Set backgound to 0\n 2. Maximize contrast while discarding minimum information\n 3. Applying this function twice should yield the same results, i.e., this function should be idempotent,\n f(f(x)) = f(x). https://en.wikipedia.org/wiki/Idempotence#Unary_operation\n\n Args:\n image_array: the input numpy array\n bg_thresh: ignore pixel values < bg_thresh in calculating 6\n lower_sigma:\n upper_sigma:\n auto_norm: boolean, whether to use automated normalization\n\n Returns:\n image_array_clipped: a numpy array with range [0, 1]\n \"\"\"\n # select the fg pixels\n image_array = image_array.astype(np.float)\n if not bg_thresh:\n # if 20 pct is 0, then background is 0, set bg_thresh = 0; otherwise use otsu to find bg_thresh\n if not force_otsu and np.percentile(image_array, bg_percentile) == 0:\n bg_thresh = 0\n else:\n bg_thresh = threshold_otsu(image_array)\n print('background threshold {}'.format(bg_thresh))\n image_array_fg = image_array[image_array > bg_thresh]\n # select 5 pct to 95 pct to perform robust normalization\n pct_5 = np.percentile(image_array_fg, 5)\n pct_95 = np.percentile(image_array_fg, 95)\n image_array_fg_robust = image_array_fg[(image_array_fg > pct_5) & (image_array_fg < pct_95)]\n std = np.std(image_array_fg_robust)\n mean = np.mean(image_array_fg_robust)\n # set (mean - lower_sigma * std) to 0, and (mean + upper_sigma * std) to 1\n a_min = mean - lower_sigma * std\n a_max = mean + upper_sigma * std\n # set bg pixels to a_min. Sometimes bg_threshold > a_min\n image_array[image_array <= bg_thresh] = a_min\n # clip\n image_array_clipped = np.clip(image_array, a_min=a_min, a_max=a_max)\n image_array_clipped = (image_array_clipped - a_min) / (a_max - a_min)\n return image_array_clipped\n\n\ndef binary_mask_to_probability_mask(image_array, ero_factor=4, blur_factor=12):\n \"\"\"Convert binary mask to probability\n\n Erode first and then blur with a Gaussian kernel to largely constrain non-zero values within the original mask\n\n Args:\n image_array:\n ero_factor: erosion kernel size is 1/ero_factor of mask size (geometric averaged size)\n blur_factor: blurring kernel size is 1/blur_factor of mask size (two dimensional size)\n\n Returns:\n\n \"\"\"\n assert len(np.unique(image_array)) <= 2, 'input is not binary array!'\n assert np.max(image_array) <= 1\n x, y = np.where(image_array == np.max(image_array))\n xmin, xmax = min(x), max(x)\n ymin, ymax = min(y), max(y)\n size = np.asarray([xmax - xmin, ymax - ymin])\n if ero_factor:\n erosion_size = int(np.sqrt(size[0] * size[1]) / ero_factor)\n image_array = dilate(image_array, -erosion_size)\n if blur_factor:\n image_array = gaussian(image_array, sigma=size / blur_factor)\n return image_array\n\n\ndef dilate(binary_array, dilation_kernel_size):\n \"\"\"\n\n Args:\n binary_array:\n dilation_kernel_size: an integer. Erode if negative, dilate if positive.\n This kernel size is diameter\n\n Returns:\n Dilated or eroded binary array\n \"\"\"\n if dilation_kernel_size == 0:\n return binary_array\n if dilation_kernel_size < 0:\n dilation_kernel_size = -dilation_kernel_size\n kernel = np.ones((dilation_kernel_size, dilation_kernel_size), np.uint8)\n binary_array = cv2.erode(binary_array.astype(np.uint8), kernel, iterations=1)\n else:\n kernel = np.ones((dilation_kernel_size, dilation_kernel_size), np.uint8)\n binary_array = cv2.dilate(binary_array.astype(np.uint8), kernel, iterations=1)\n binary_array = binary_array.astype(np.bool)\n return binary_array\n\n\ndef clean_bg_component(prob_array, threshold=0.5, anchor_patch=10):\n \"\"\"Keep the central connected component and set the rest of the pixels to 0\n\n Note that the current algorithm requires that the ceneral pixel\n\n Args:\n prob_array: a probability array with values between 0 and 1\n anchor_patch: collect all non-zero labels in this center patch and find connected component.\n Sometimes the center of the patch does not lie in any foreground connected component mask,\n and this serves as a temporary solution.\n\n Returns:\n masked_prob_array: the masked prob array\n \"\"\"\n binary_array = prob_array > threshold\n labeled_mask_array = measure.label(binary_array, connectivity=2)\n y_c, x_c = np.array(binary_array.shape) // 2\n central_component_idx = np.unique(\n labeled_mask_array[(y_c - anchor_patch // 2):(y_c + anchor_patch // 2),\n (x_c - anchor_patch // 2):(x_c + anchor_patch // 2)])\n central_component_idx = [x for x in central_component_idx if x]\n center_mask = np.zeros_like(binary_array)\n if not central_component_idx:\n # If cannot find central connected component, return the original input\n return prob_array, labeled_mask_array\n for idx in central_component_idx:\n center_mask[labeled_mask_array == idx] = 1\n masked_prob_array = prob_array * center_mask\n return masked_prob_array, labeled_mask_array\n\n\ndef opening(binary_array, open_kernel_size):\n \"\"\"\n\n Args:\n binary_array:\n open_kernel_size(int): Closing if negative, opening if positive\n\n Returns:\n\n \"\"\"\n if open_kernel_size == 0:\n return binary_array\n if open_kernel_size < 0:\n open_kernel_size = -open_kernel_size\n kernel = np.ones((open_kernel_size, open_kernel_size), np.uint8)\n binary_array = cv2.dilate(binary_array.astype(np.uint8), kernel, iterations=1)\n binary_array = cv2.erode(binary_array.astype(np.uint8), kernel, iterations=1)\n else:\n kernel = np.ones((open_kernel_size, open_kernel_size), np.uint8)\n binary_array = cv2.erode(binary_array.astype(np.uint8), kernel, iterations=1)\n binary_array = cv2.dilate(binary_array.astype(np.uint8), kernel, iterations=1)\n binary_array = binary_array.astype(np.bool)\n return binary_array\n\n\nclass DicomCorrector(object):\n def __init__(self, dicom_path, level):\n \"\"\"Correct dicom grayscale according to LUT\n Ref: http://dicom.nema.org/medical/dicom/2017a/output/chtml/part03/sect_C.11.html\n There 3 stages or transforms within the DICOM rendering pipeline with regards to applying Lookup tables that\n can alter input values for rendering. Used within these stages are 4 types of lookup table (LUT) which can be\n found within DICOM images are part of the standard, and one further type which exists in DicomObjects. These\n together with a number of other Pixel data modifiers are used within the pipeline to produce a flexible\n rendering chain.\n\n Args:\n dicom_path:\n level: gamma correction levels, could be `softer`, `normal` or `harder`\n \"\"\"\n self._dicom_path = dicom_path\n try:\n self._ds = dicom.read_file(dicom_path)\n self._image_array = self._ds.pixel_array\n except:\n print(\"Dicom reading error\")\n # Add preamble manually\n fp = BytesIO()\n fp.write(b'\\x00' * 128)\n fp.write(b'DICM')\n # Add the contents of the file\n f = open(dicom_path, 'rb')\n fp.write(f.read())\n f.close()\n fp.seek(0)\n # Read the dataset:\n self._ds = dicom.read_file(fp, force=True)\n import pydicom.uid\n self._ds.file_meta.TransferSyntaxUID = dicom.uid.ImplicitVRLittleEndian # or whatever is the correct transfer syntax for the file\n self._image_array = self._ds.pixel_array\n self._level = level\n # original array before correction\n self._raw_array = self._image_array.copy()\n\n @staticmethod\n def look_up_value(lut_sequence, image_array, level):\n \"\"\"\n\n Args:\n voi_lut_module: An element of VOILUTSequence\n image_array(np.array):\n\n Returns:\n\n \"\"\"\n for i in range(lut_sequence.VM):\n lut_descriptor = lut_sequence[i][0x28, 0x3002].value\n lut_explanation = lut_sequence[i][0x28, 0x3003].value\n lut_data = lut_sequence[i][0x28, 0x3006].value\n num_entries = lut_descriptor[0]\n offset = lut_descriptor[1]\n if lut_explanation.lower() == level.lower():\n image_array = np.clip(image_array, offset, num_entries + offset - 1)\n image_array = image_array - offset\n lut = np.asarray(lut_data)\n image_array = lut[image_array.astype(int)]\n return image_array\n\n def voi_lut_windowing(self, win_center, win_width, fun_type=\"linear\"):\n \"\"\"VOI LUT function is LINEAR\n\n Args:\n win_center:\n win_width:\n fun_type:\n\n Returns:\n\n \"\"\"\n assert fun_type.lower() in ['linear', 'sigmoid', 'linear_exact']\n print('Using windowing type `{}`'.format(fun_type))\n if fun_type.lower() == \"linear\":\n lower_bound = win_center - 0.5 - (win_width - 1) / 2\n upper_bound = win_center - 0.5 + (win_width - 1) / 2\n self._image_array[self._image_array <= lower_bound] = lower_bound\n self._image_array[self._image_array > upper_bound] = upper_bound\n self._image_array[(self._image_array > lower_bound) * (self._image_array <= upper_bound)] = \\\n ((self._image_array[(self._image_array > lower_bound) * (self._image_array <= upper_bound)]\n - (win_center - 0.5)) / (win_width - 1) + 0.5) * (upper_bound - lower_bound) + lower_bound\n elif fun_type.lower() == \"sigmoid\":\n bits_stored = self._ds[0x28, 0x101].value\n output_range = 2**bits_stored\n self._image_array = output_range / (1 + np.exp(-4*(self._image_array-win_center))/win_width)\n elif fun_type.lower() == \"linear_exact\":\n lower_bound = win_center - win_width / 2\n upper_bound = win_center + win_width / 2\n self._image_array[self._image_array <= lower_bound] = lower_bound\n self._image_array[self._image_array > upper_bound] = upper_bound\n self._image_array[(self._image_array > lower_bound)*(self._image_array<=upper_bound)] = \\\n (self._image_array - win_center) / win_width * (upper_bound - lower_bound) + lower_bound\n\n def modality_lut(self):\n \"\"\"This function transforms the manufacturer dependent pixel values into pixel values which are meaningful for\n the modality and which are manufacturer independent.\n Returns:\n\n \"\"\"\n try:\n modality_lut_sequence = self._ds[0x28, 0x3000]\n self._image_array = DicomCorrector.look_up_value(modality_lut_sequence, self._image_array, self._level)\n except:\n try:\n print(\"Use rescaling to do the modality lut\")\n intercept = self._ds[0x28, 0x1052].value\n slope = self._ds[0x28, 0x1053].value\n self._image_array = self._image_array * slope + intercept\n except:\n print(\"Unable to do the modaligy lut\", self._dicom_path)\n\n def voi_lut(self):\n \"\"\"The Value Of Interest(VOI) LUT transformation transforms the modality pixel values into pixel values which\n are meaningful for the user or the application.\n\n Args:\n level:\n\n Returns:\n\n \"\"\"\n try:\n voi_lut_sequence = self._ds[0x28, 0x3010]\n self._image_array = DicomCorrector.look_up_value(voi_lut_sequence, self._image_array, self._level)\n except:\n print(\"Render the gray scale into window\")\n try:\n win_center_list = self._ds[0x28, 0x1050].value\n win_width_list = self._ds[0x28, 0x1051].value\n if self._ds[0x28, 0x1051].VM == 1:\n win_center = win_center_list\n win_width = win_width_list\n else:\n zipped = zip(win_width_list, win_center_list)\n zipped_sorted = sorted(zipped, key=lambda t: t[0])\n if self._level.lower() == \"softer\":\n win_center = zipped_sorted[0][1]\n win_width = zipped_sorted[0][0]\n elif self._level.lower() == \"normal\":\n win_center = zipped_sorted[1][1]\n win_width = zipped_sorted[1][0]\n elif self._level.lower() == \"harder\":\n win_center = zipped_sorted[2][1]\n win_width = zipped_sorted[2][0]\n else:\n raise KeyError(\"Input level error, should be softer, normal or harder\")\n print('Level `{}` not found'.format(self._level))\n try:\n function_type = self._ds[0x28, 0x1056]\n self.voi_lut_windowing(win_center, win_width, function_type)\n except:\n self.voi_lut_windowing(win_center, win_width)\n except:\n print(\"Unable to do the voi lut\", self._dicom_path)\n\n def presentation_lut(self):\n \"\"\"The Presentation LUT transformation transforms the pixel values into P-Values, a device independent perceptually\n linear space.\n\n Returns:\n\n \"\"\"\n try:\n presentation_lut_shape = self._ds[0x2050, 0x0020].value\n if presentation_lut_shape.lower == \"invert\" or presentation_lut_shape.lower() == \"inverse\":\n self._image_array = np.max(self._image_array) - self._image_array\n except:\n print(\"Use photometric interpretation to check invert\", self._dicom_path)\n try:\n photometric_interpretation = self._ds[0x28, 0x4].value\n if photometric_interpretation == \"MONOCHROME1\":\n self._image_array = np.max(self._image_array) - self._image_array\n except:\n print(\"Unable to do the presentation lut\", self._dicom_path)\n\n def correct(self):\n \"\"\"The main function to correct dicom pixel_value error.\n\n Returns:\n\n \"\"\"\n try:\n self.modality_lut()\n self.voi_lut()\n self.presentation_lut()\n return self._image_array\n except:\n print(\"Correction Error\", self._dicom_path)\n"
] |
[
[
"numpy.amax",
"numpy.sqrt",
"numpy.asarray",
"numpy.around",
"numpy.max",
"numpy.mean",
"numpy.zeros_like",
"numpy.any",
"numpy.exp",
"numpy.ones_like",
"numpy.pad",
"numpy.clip",
"numpy.unique",
"numpy.fliplr",
"numpy.std",
"numpy.zeros",
"numpy.lib.pad",
"numpy.amin",
"numpy.append",
"numpy.array",
"numpy.percentile",
"numpy.ones",
"numpy.random.uniform",
"numpy.fabs"
]
] |
jmeyers314/astrophotoreduce
|
[
"814177f494bbe6bb7ef5cf1b09ab2083a119fa42"
] |
[
"cfa.py"
] |
[
"import numpy as np\n\ndef make_cfa(img):\n cfa = np.zeros_like(img[:,:,0])\n y, x = np.mgrid[0:cfa.shape[0], 0:cfa.shape[1]]\n Rloc = (np.mod(x, 2) == 0) & (np.mod(y, 2) == 0)\n Gloc = np.mod(x+y, 2) == 1\n Bloc = (np.mod(x, 2) == 1) & (np.mod(y, 2) == 1)\n cfa[Rloc] = img[Rloc,0]\n cfa[Gloc] = img[Gloc,1]\n cfa[Bloc] = img[Bloc,2]\n return cfa\n"
] |
[
[
"numpy.mod",
"numpy.zeros_like"
]
] |
PabloEduardoMartinezPicazo/Bootcamp-DataScience-2021
|
[
"0fa5288aec5fb14e3796877882e4f1ddc5ad4aea"
] |
[
"EDA/SRC/utils_/apis_tb.py"
] |
[
"#funciones para flasks para la lectura y el return del json\nimport pandas as pd \nimport numpy as np\nimport json\n\n\ndef read_json(fullpath):\n with open(fullpath, \"r\") as json_file_readed:\n json_readed = json.load(json_file_readed)\n return json_readed\n\ndef return_json(filepath):\n df = pd.read_csv(filepath)\n return df.to_json()"
] |
[
[
"pandas.read_csv"
]
] |
HypnosXC/mmaction2
|
[
"777546f27f8f5a3c83e10d966e2149be2fc9fa31"
] |
[
"mmaction/models/losses/nll_loss.py"
] |
[
"import torch.nn.functional as F\n\nfrom ..registry import LOSSES\nfrom .base import BaseWeightedLoss\n\n\[email protected]_module()\nclass NLLLoss(BaseWeightedLoss):\n \"\"\"NLL Loss.\n\n It will calculate NLL loss given cls_score and label.\n \"\"\"\n\n def _forward(self, cls_score, label, **kwargs):\n \"\"\"Forward function.\n\n Args:\n cls_score (torch.Tensor): The class score.\n label (torch.Tensor): The ground truth label.\n kwargs: Any keyword argument to be used to calculate nll loss.\n\n Returns:\n torch.Tensor: The returned nll loss.\n \"\"\"\n loss_cls = F.nll_loss(cls_score, label, **kwargs)\n return loss_cls\n"
] |
[
[
"torch.nn.functional.nll_loss"
]
] |
JoelPendleton/QDot-Detector
|
[
"e53b80c02fe95ceacd3dde9981dcd0481b907bdc"
] |
[
"tools/swa.py"
] |
[
"# -*- coding:utf-8 -*-\n\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nfrom __future__ import division\n\nimport tensorflow as tf\nimport tensorflow.contrib.slim as slim\nfrom tensorflow.python import pywrap_tensorflow\nimport numpy as np\nimport sys\nimport os\nsys.path.append('../')\nfrom libs.configs import cfgs\n\n\nclass SWA(object):\n\n \"\"\"\n SWA Object Detection\n https://arxiv.org/pdf/2012.12645.pdf\n \"\"\"\n\n def __init__(self, cfgs):\n self.cfgs = cfgs\n self.weight_paths = self.get_all_weights_path()\n\n def get_all_weights_path(self):\n with open(os.path.join('../output/trained_weights', self.cfgs.VERSION, 'checkpoint'), 'r') as fr:\n lines = fr.readlines()[1:]\n return [line.split(' ')[-1][1:-2] for line in lines]\n\n def average_weights(self, weight_paths):\n print(weight_paths)\n average_weights = {}\n for wp in weight_paths:\n print(wp)\n model_reader = pywrap_tensorflow.NewCheckpointReader(wp)\n var_dict = model_reader.get_variable_to_shape_map()\n for key in var_dict:\n if key not in average_weights.keys():\n average_weights[key] = model_reader.get_tensor(key)\n else:\n average_weights[key] += model_reader.get_tensor(key)\n for key in average_weights.keys():\n average_weights[key] /= len(weight_paths)\n return average_weights\n\n def save_swa_weight(self):\n # img_plac = tf.placeholder(dtype=tf.uint8, shape=[None, None, 3]) # is RGB. not BGR\n # img_batch = tf.cast(img_plac, tf.float32)\n #\n # if self.cfgs.NET_NAME in ['resnet152_v1d', 'resnet101_v1d', 'resnet50_v1d']:\n # img_batch = (img_batch / 255 - tf.constant(self.cfgs.PIXEL_MEAN_)) / tf.constant(self.cfgs.PIXEL_STD)\n # else:\n # img_batch = img_batch - tf.constant(self.cfgs.PIXEL_MEAN)\n #\n # img_batch = tf.expand_dims(img_batch, axis=0)\n #\n # _ = det_net.build_whole_detection_network(input_img_batch=img_batch)\n\n average_weights = self.average_weights(self.weight_paths)\n weights = {}\n for k in average_weights.keys():\n weights[k] = tf.get_variable(name=k, initializer=average_weights[k])\n\n init_op = tf.group(\n tf.global_variables_initializer(),\n tf.local_variables_initializer()\n )\n\n # average_weights = self.average_weights(weight_paths)\n\n # model_variables = slim.get_model_variables()\n # for i in range(len(model_variables)):\n # model_variables[i] = model_variables[i].assign(average_weights[model_variables[i].name.split(':')[0]])\n\n saver = tf.train.Saver()\n\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n\n with tf.Session(config=config) as sess:\n sess.run(init_op)\n # for i in range(len(model_variables)):\n # model_variables[i].op.run()\n saver.save(sess, \"../output/trained_weights/{}/swa_{}.ckpt\".format(self.cfgs.VERSION, len(self.weight_paths)))\n\n\nif __name__ == '__main__':\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = '3'\n swa = SWA(cfgs)\n swa.save_swa_weight()\n"
] |
[
[
"tensorflow.get_variable",
"tensorflow.local_variables_initializer",
"tensorflow.python.pywrap_tensorflow.NewCheckpointReader",
"tensorflow.ConfigProto",
"tensorflow.global_variables_initializer",
"tensorflow.Session",
"tensorflow.train.Saver"
]
] |
jqueguiner/haven
|
[
"7b2a5d46b08f48f1112f8903f1b97c6adadff3f4"
] |
[
"examples/minimal/models.py"
] |
[
"import torch\nimport tqdm\n\nfrom torch import nn\n\n\ndef get_model(model_name):\n if model_name == 'mlp':\n return MLP()\n\nclass MLP(nn.Module):\n def __init__(self, input_size=784, n_classes=10):\n \"\"\"Constructor.\"\"\"\n super().__init__()\n\n self.input_size = input_size\n self.hidden_layers = nn.ModuleList([nn.Linear(input_size, 256)])\n self.output_layer = nn.Linear(256, n_classes)\n\n self.opt = torch.optim.SGD(self.parameters(), lr=1e-3)\n\n def forward(self, x):\n \"\"\"Forward pass of one batch.\"\"\"\n x = x.view(-1, self.input_size)\n out = x\n for layer in self.hidden_layers:\n Z = layer(out)\n out = torch.nn.functional.relu(Z)\n logits = self.output_layer(out)\n\n return logits\n \n def get_state_dict(self):\n return {'model': self.state_dict(),\n 'opt': self.opt.state_dict()} \n\n def load_state_dict(self, state_dict):\n self.load_state_dict(state_dict['model'])\n self.opt.load_state_dict(state_dict['opt'])\n\n def train_on_loader(self, train_loader):\n \"\"\"Train for one epoch.\"\"\"\n self.train()\n loss_sum = 0.\n\n n_batches = len(train_loader)\n\n pbar = tqdm.tqdm(desc=\"Training\", total=n_batches, leave=False)\n for i, batch in enumerate(train_loader):\n loss_sum += float(self.train_on_batch(batch))\n\n pbar.set_description(\"Training - loss: %.4f \" % (loss_sum / (i + 1)))\n pbar.update(1)\n\n pbar.close()\n loss = loss_sum / n_batches\n\n return {\"train_loss\": loss}\n \n @torch.no_grad()\n def val_on_loader(self, val_loader):\n \"\"\"Validate the model.\"\"\"\n self.eval()\n se = 0.\n n_samples = 0\n\n n_batches = len(val_loader)\n pbar = tqdm.tqdm(desc=\"Validating\", total=n_batches, leave=False)\n\n for i, batch in enumerate(val_loader):\n gt_labels = batch[1]\n pred_labels = self.predict_on_batch(batch)\n\n se += float((pred_labels.cpu() == gt_labels).sum())\n n_samples += gt_labels.shape[0]\n \n pbar.set_description(\"Validating - %.4f acc\" % (se / n_samples))\n pbar.update(1)\n\n pbar.close()\n\n acc = se / n_samples\n\n return {\"val_acc\": acc}\n\n def train_on_batch(self, batch):\n \"\"\"Train for one batch.\"\"\"\n images, labels = batch\n images, labels = images, labels\n\n self.opt.zero_grad()\n probs = torch.nn.functional.log_softmax(self(images), dim=1)\n loss = torch.nn.functional.nll_loss(probs, labels, reduction=\"mean\")\n loss.backward()\n\n self.opt.step()\n\n return loss.item()\n\n def predict_on_batch(self, batch, **options):\n \"\"\"Predict for one batch.\"\"\"\n images, labels = batch\n images = images\n probs = torch.nn.functional.log_softmax(self(images), dim=1)\n\n return probs.argmax(dim=1)"
] |
[
[
"torch.nn.Linear",
"torch.nn.functional.relu",
"torch.no_grad",
"torch.nn.functional.nll_loss"
]
] |
GrigalashviliT/spoilerBlocker
|
[
"18a5e9689099d3b631a15ed20cc84a043f324055"
] |
[
"src/data_collection/preprocess_data/make_csv.py"
] |
[
"import pandas as pd\r\nimport glob\r\nfrom re import sub\r\n\r\ndct = {\r\n 'sentence': [],\r\n 'label': []\r\n}\r\n\r\ndef process_text(text):\r\n \r\n text = text.replace('\\r\\n', '.')\r\n text = text.replace('\\n', '.')\r\n text = text.replace('\\r', '.')\r\n text = text.lower()\r\n text = text.strip().split('.')\r\n\r\n return text\r\n\r\n\r\ndef clean_text(text):\r\n\r\n text = str(text)\r\n text = text.lower()\r\n\r\n # Clean the text\r\n text = sub(r\"[^A-Za-z0-9^,!.\\/'+-=]\", \" \", text)\r\n text = sub(r\"what's\", \"what is \", text)\r\n text = sub(r\"\\'s\", \" \", text)\r\n text = sub(r\"\\'ve\", \" have \", text)\r\n text = sub(r\"can't\", \"cannot \", text)\r\n text = sub(r\"n't\", \" not \", text)\r\n text = sub(r\"i'm\", \"i am \", text)\r\n text = sub(r\"\\'re\", \" are \", text)\r\n text = sub(r\"\\'d\", \" would \", text)\r\n text = sub(r\"\\'ll\", \" will \", text)\r\n text = sub(r\",\", \" \", text)\r\n text = sub(r\"\\.\", \" \", text)\r\n text = sub(r\"!\", \" ! \", text)\r\n text = sub(r\"\\/\", \" \", text)\r\n text = sub(r\"\\^\", \" ^ \", text)\r\n text = sub(r\"\\+\", \" + \", text)\r\n text = sub(r\"\\-\", \" - \", text)\r\n text = sub(r\"\\=\", \" = \", text)\r\n text = sub(r\"'\", \" \", text)\r\n text = sub(r\"(\\d+)(k)\", r\"\\g<1>000\", text)\r\n text = sub(r\":\", \" : \", text)\r\n text = sub(r\" e g \", \" eg \", text)\r\n text = sub(r\" b g \", \" bg \", text)\r\n text = sub(r\" u s \", \" american \", text)\r\n text = sub(r\"\\0s\", \"0\", text)\r\n text = sub(r\" 9 11 \", \"911\", text)\r\n text = sub(r\"e - mail\", \"email\", text)\r\n text = sub(r\"j k\", \"jk\", text)\r\n text = sub(r\"\\s{2,}\", \" \", text)\r\n\r\n line = text.split()\r\n\r\n text = ''\r\n\r\n for t in line:\r\n \r\n text += t + ' '\r\n\r\n return text[:-1]\r\n\r\nfor filename in glob.glob('sentence_labels/*.txt'):\r\n \r\n\r\n\r\n f = open(filename, 'r')\r\n \r\n text = f.read()\r\n\r\n text = process_text(text)\r\n\r\n filename = filename[filename.find('\\\\') + 1:]\r\n\r\n for line in text:\r\n\r\n line = clean_text(line)\r\n\r\n if len(line.split()) < 3 or len(line.split()) > 15:\r\n continue\r\n \r\n\r\n line = line[:-1]\r\n line = line.strip()\r\n\r\n dct['sentence'].append(line)\r\n dct['label'].append(filename[:filename.find('.')])\r\n\r\n\r\n\r\ndf = pd.DataFrame(dct)\r\n\r\ndf.to_csv('data.csv', encoding='utf-8')\r\n"
] |
[
[
"pandas.DataFrame"
]
] |
kyehyeon/SNIPER
|
[
"2b8723729bfb91275d598b55752f32d8a00a33ad"
] |
[
"init.py"
] |
[
"import sys\nimport logging\nimport os\nimport matplotlib\nmatplotlib.use('Agg')\n\nos.environ['PYTHONUNBUFFERED'] = '1'\nos.environ['MXNET_CUDNN_AUTOTUNE_DEFAULT'] = '0'\nlogging.basicConfig(level=logging.INFO)\nsys.path.insert(0,'lib')\nsys.path.insert(0,'SNIPER-mxnet/python')\n"
] |
[
[
"matplotlib.use"
]
] |
makaishi2/cplex-samples
|
[
"d798a8d2dc14826eb5b3f00e6f64a2a08b2bc5f1"
] |
[
"diet-ml/ml-submit.py"
] |
[
"# -*- coding: utf-8 -*-\n\n# コマンドによる事前準備\n# $ pip install -U ibm-watson-machine-learning \n\nimport sys\n\n# Watson ML credentails\napikey = 'xxxx'\nlocation = 'us-south'\n\nimport pandas as pd\n\n# Watson ML credentails\n\n# DO Deployment ID\ndeployment_uid = 'xxxx'\n\n# Input CSV File\ninput_data1 = 'diet_food.csv'\ninput_data2 = 'diet_nutrients.csv'\ninput_data3 = 'diet_food_nutrients.csv'\n\n# --------------------------------------------------------\n# メインルーチン\n# --------------------------------------------------------\nif __name__ == '__main__':\n\n # 引数の受け取り\n argv = sys.argv\n argc = len(argv)\n\n wml_credentials = {\n \"apikey\": apikey,\n \"url\": 'https://' + location + '.ml.cloud.ibm.com'\n }\n\n from ibm_watson_machine_learning import APIClient\n client = APIClient(wml_credentials)\n\n client.spaces.list()\n space_id = '20f3d4c5-1faa-4c80-a361-4da68d362b0f'\n client.set.default_space(space_id)\n\n input_df1 = pd.read_csv(input_data1)\n input_df2 = pd.read_csv(input_data2)\n input_df3 = pd.read_csv(input_data3)\n \n solve_payload = {\n client.deployments.DecisionOptimizationMetaNames.INPUT_DATA: [\n {\n \"id\": input_data1,\n \"values\" : input_df1\n },\n {\n \"id\": input_data2,\n \"values\" : input_df2\n },\n {\n \"id\": input_data3,\n \"values\" : input_df3\n }\n ],\n client.deployments.DecisionOptimizationMetaNames.OUTPUT_DATA: [\n {\n \"id\":\".*\\.csv\"\n }\n ]\n }\n\n # DO Job 投入\n job_details = client.deployments.create_job(deployment_uid, solve_payload)\n job_uid = client.deployments.get_job_uid(job_details)\n print( job_uid )\n\n\n # status確認\n from time import sleep\n while job_details['entity']['decision_optimization']['status']['state'] not in ['completed', 'failed', 'canceled']:\n print(job_details['entity']['decision_optimization']['status']['state'] + '...')\n sleep(5)\n job_details=client.deployments.get_job_details(job_uid)\n\n detail = job_details['entity']['decision_optimization']['output_data']\n\n # 結果確認\n import json\n detail2 = job_details['entity']['decision_optimization']\n \n # 最終ステータス表示\n print(json.dumps(detail2['status'], indent=2))\n \n for item in detail:\n id = item['id']\n fields = item['fields']\n values = item['values']\n df_work = pd.DataFrame(values, columns=fields)\n name = id[:id.index('.csv')]\n print('name = ', name)\n print(df_work.head())\n df_work.to_csv(id, index=False)\n"
] |
[
[
"pandas.read_csv",
"pandas.DataFrame"
]
] |
Ravirajanan/tennislive-visualization
|
[
"f5d555a9caea61c1286cc7bc3505281f52d37322"
] |
[
"plot.py"
] |
[
"#imports\nimport pandas as pd\nimport numpy as np\nimport re\nimport dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output\nimport plotly.express as px\nfrom plotly.subplots import make_subplots\nimport plotly.graph_objects as go\n\n#reads the input file which has data and converts it into a dataframe\ndataframe = pd.read_csv('Melbourne_060221_12_JuanSebastianCabalRobertFarah_MatthewEbdenJohnPatrickSmith.csv')\n\n#final result details\nresults_ = dataframe.result.unique()\n\n#the followinng code will find the max points reached in the game, so that we can plot that many columns on graph\nde = re.split('-|,| ',results_[0])\nde = [int(x) for x in de if x!= '']\n#columns_ = max(de)\n\n#Drops unrequired columns\ndataframe.drop(['player1_name','player2_name','tournament','round','break_point','result','surface','date'], axis=1, inplace=True)\n\n#Finds the players names\nplayernames = dataframe.server.unique()\n\n#sets a new column as servernumber denotes 0 or 1 on basis of who is playing\ndataframe['server_number'] = np.where(dataframe['server'] == playernames[0], 0, 1)\n\n#follwing code takes the points and splits the points into sepeate values for two players.\ndef split_it(point):\n x = point.split('-')\n return x\ndataframe['points_to_list'] = dataframe['points'].apply(split_it)\ndataframe[['points_of_1','points_of_2']] = pd.DataFrame(dataframe.points_to_list.tolist())\n\n#rename few columns name for further operation like set_index\ndataframe.rename(columns={'set_index':'set_details'}, inplace = True)\n\n#no_of_sets for use of no of plots.\nno_of_sets = dataframe.set_details.unique()\n\ndataframe['set_number']= 0\n\n#following code to create x axis, like only markers\ndef set_number_(lis,set_):\n global i,set_no\n if set_no != set_:\n i = 0\n set_no = set_\n if lis == ['0','0']:\n i = i+1\n return i\n\n#global variables i and set_no\ni = 0\nset_no = 0\ndataframe['set_number'] = dataframe.apply(lambda x: set_number_(x['points_to_list'],x['set_details']), axis = 1)\n\ncolumns_ = []\nfor k in no_of_sets:\n set_details_unique_ = dataframe.where(dataframe['set_details']==k).set_number.unique()\n cleanedList = [int(x) for x in set_details_unique_ if str(x) != 'nan']\n columns_.append(max(cleanedList))\n\n#plot\nfig = make_subplots(\n rows=len(no_of_sets), cols=max(columns_))\n\n\nfor k in no_of_sets:\n df= dataframe[dataframe['set_details']==k]\n for r in range(1,columns_[k-1]+1):\n \n final_df = (df[df['set_number'] == r])\n max_x= (len(final_df['set_number']))\n x_ = np.arange(0, max_x,1)\n fig.add_trace(\n go.Scatter(x=x_,y=final_df['points_of_1'],line_color = \"red\"),\n row=k, col=r)\n fig.add_trace(\n go.Scatter(x=x_, y=final_df['points_of_2'],line_color =\"blue\"),\n row=k, col=r)\n \n\n\n#Update height, width and title\nfig.update_layout(autosize=False,height=1000, width=3000, title_text=\"Tennis Scores\")\n\nfig.update_yaxes(tickvals=['0', '15', '30', '40'])\n\n#Make labels disappear on x axis\nfig.update_xaxes(showticklabels=False)\n\n#Don't display the trace values in the charts\nfig.update_layout(showlegend=False)\n\n#Make x axes disappear\nfig.update_xaxes(showgrid=False,zeroline=False)\n\n#Make y axes disappear\nfig.update_yaxes(showgrid=False,zeroline=False)\n\n#Display all charts\nfig.show()"
] |
[
[
"numpy.arange",
"pandas.read_csv",
"numpy.where"
]
] |
catmaid/catpy
|
[
"481d87591a6dfaedef2767dcddcbed7185ecc8b8"
] |
[
"tests/test_image.py"
] |
[
"from __future__ import absolute_import\n\nfrom itertools import cycle, chain\n\nimport pytest\nimport numpy as np\nimport requests\nfrom PIL import Image\nfrom io import BytesIO\nfrom concurrent.futures import Future\nfrom requests import HTTPError\n\ntry:\n import mock\nexcept ImportError:\n from unittest import mock\n\nfrom catpy.image import (\n TileCache,\n is_valid_format_url,\n response_to_array,\n as_future,\n fill_tiled_cuboid,\n dict_subtract,\n ImageFetcher,\n ROIMode,\n ThreadedImageFetcher,\n DummyResponse,\n)\nfrom catpy.stacks import (\n StackMirror,\n Stack,\n ProjectStack,\n TileSourceType,\n format_urls,\n TileIndex,\n)\n\nIMAGE_BASE = \"http://not-catmaid.org/\"\nTILE_SOURCE_TYPE = TileSourceType.FILE_BASED\nFORMAT_URL = format_urls[TILE_SOURCE_TYPE]\n\nIMAGE_MODES = [\n \"L\", # 8-bit uint greyscale pixels\n \"RGB\", # 3x8-bit\n \"RGBa\", # 3x8-bit with premultiplied alpha\n \"RGBA\", # 4x8-bit (transparency mask)\n \"CMYK\", # 4x8-bit\n]\n\n\[email protected]()\ndef row_maker():\n \"\"\"Generate a list of numbers from 1 to 254 inclusive, wrapping around\"\"\"\n\n def maker(length, start=1):\n if not 0 < start < 255:\n raise ValueError(\"Start must be between 0 and 254 inclusive\")\n it = chain(range(start, 255), cycle(range(1, 255)))\n out = []\n while len(out) < length:\n out.append(next(it))\n\n return out\n\n return maker\n\n\[email protected]\ndef gradient_h(row_maker):\n return np.array([row_maker(254)] * 128, dtype=np.uint8)\n\n\[email protected]\ndef vol_maker(row_maker):\n def maker(shape, x_offset=0):\n while x_offset >= 254:\n x_offset -= 254\n return np.array(\n [[row_maker(shape[2], x_offset + 1)] * shape[1]] * shape[0], dtype=np.uint8\n )\n\n return maker\n\n\[email protected](\n \"x_offset,shape,expected_final\",\n [\n (0, (1, 1, 1), 1),\n (1, (1, 1, 1), 2),\n (0, (10, 10, 10), 10),\n (0, (1, 1, 300), 46),\n (1, (1, 1, 300), 47),\n ],\n)\ndef test_vol_maker(vol_maker, x_offset, shape, expected_final):\n volume = vol_maker(shape, x_offset)\n assert volume.shape == shape\n assert volume[0, 0, 0] == x_offset + 1 # does not check large-offset\n assert volume[-1, -1, -1] == expected_final\n\n\ndef make_response_mock(content_arr, mode=\"L\", format=\"png\"):\n response = mock.Mock(spec=requests.Response)\n response.headers = {\"Content-Type\": \"image/\" + format}\n im = Image.fromarray(content_arr)\n converted_im = im.convert(mode)\n\n buffer = BytesIO()\n converted_im.save(buffer, format)\n buffer.seek(0)\n response.content = buffer.read()\n\n return response\n\n\n##########################\n# Utility function tests #\n##########################\n\n\[email protected](\"mode\", [\"L\", \"RGB\", \"RGBA\"])\ndef test_response_to_array_png(gradient_h, mode):\n response_mock = make_response_mock(gradient_h, mode, \"png\")\n returned_arr = response_to_array(response_mock)\n\n assert np.allclose(gradient_h, returned_arr)\n\n\[email protected](\"mode\", [\"L\", \"RGB\"])\ndef test_response_to_array_jpeg(gradient_h, mode):\n response_mock = make_response_mock(gradient_h, mode, \"jpeg\")\n returned_arr = response_to_array(response_mock)\n\n # jpeg compression means exact matching is not possible\n assert gradient_h.shape == returned_arr.shape\n # assert np.allclose(gradient_h.ptp(), returned_arr.ptp())\n\n\[email protected](\"tile_source_type,format_url\", format_urls.items())\ndef test_predefined_format_urls_are_valid(tile_source_type, format_url):\n assert is_valid_format_url(format_url), \"URL for {} is invalid\".format(\n tile_source_type\n )\n\n\ndef test_as_future_for_not_future():\n item = \"item\"\n\n not_future_as_future = as_future(item)\n assert isinstance(not_future_as_future, Future)\n assert not_future_as_future.result() == item\n\n\ndef test_as_future_for_future():\n item = \"item\"\n future = Future()\n future.set_result(item)\n\n future_as_future = as_future(future)\n assert isinstance(future_as_future, Future)\n assert future_as_future.result() == item\n\n\ndef test_fill_tiled_cuboid():\n kwargs = {\"zoom_level\": 1, \"height\": 2, \"width\": 3}\n\n min_tile = TileIndex(1, 2, 3, **kwargs)\n max_tile = TileIndex(2, 4, 3, **kwargs)\n\n results = fill_tiled_cuboid(min_tile, max_tile)\n\n expected_results = {\n TileIndex(1, 2, 3, **kwargs),\n TileIndex(2, 2, 3, **kwargs),\n TileIndex(1, 3, 3, **kwargs),\n TileIndex(2, 3, 3, **kwargs),\n TileIndex(1, 4, 3, **kwargs),\n TileIndex(2, 4, 3, **kwargs),\n }\n\n assert results == expected_results\n\n\ndef test_fill_tiled_cuboid_raises():\n min_tile = TileIndex(1, 2, 3, 1, 2, 3)\n max_tile = TileIndex(2, 4, 3, 4, 5, 6)\n\n with pytest.raises(ValueError):\n fill_tiled_cuboid(min_tile, max_tile)\n\n\ndef test_dict_subtract_mismatched_keys():\n d1 = {\"a\": 1, \"b\": 2}\n d2 = {\"a\": 5, \"c\": 10}\n\n with pytest.raises(ValueError):\n dict_subtract(d1, d2)\n\n\ndef test_dict_subtract():\n d1 = {\"a\": 1, \"b\": 2}\n d2 = {\"a\": 5, \"b\": 10}\n\n result = dict_subtract(d1, d2)\n assert result == {\"a\": -4, \"b\": -8}\n\n\n###################\n# TileIndex tests #\n###################\n\n\ndef test_tile_index_coords():\n idx = TileIndex(5, 2, 1, None, 10, 20)\n result = idx.coords\n\n expected_result = {\"z\": 5, \"y\": 20, \"x\": 20}\n\n assert result == expected_result\n\n\[email protected](\"name\", [\"zoom_level\", \"height\", \"width\"])\ndef test_tile_index_comparable(name):\n kwargs = {\"zoom_level\": 1, \"height\": 10, \"width\": 20}\n idx1 = TileIndex(1, 2, 3, **kwargs)\n idx2 = TileIndex(4, 5, 6, **kwargs)\n\n assert idx1.is_comparable(idx2)\n\n kwargs[name] = kwargs[name] * 2\n idx3 = TileIndex(7, 8, 9, **kwargs)\n\n assert not idx1.is_comparable(idx3)\n\n\ndef test_tile_index_url_kwargs():\n idx = TileIndex(1, 2, 3, 4, 5, 6)\n d = idx.url_kwargs\n for key in (\"depth\", \"row\", \"col\", \"zoom_level\"):\n assert key in d\n\n\n#####################\n# StackMirror tests #\n#####################\n\n\ndef test_stackmirror_corrects_image_base():\n other_args = (1, 1, 1, \"png\")\n mirror_slash = StackMirror(IMAGE_BASE, *other_args)\n mirror_no_slash = StackMirror(IMAGE_BASE[:-1], *other_args)\n\n assert mirror_slash.image_base == mirror_no_slash.image_base == IMAGE_BASE\n\n\ndef test_stackmirror_corrects_file_extension():\n other_args = (IMAGE_BASE, 1, 1, 1)\n mirror_dot = StackMirror(*other_args, file_extension=\".png\")\n mirror_no_dot = StackMirror(*other_args, file_extension=\"png\")\n\n assert mirror_dot.file_extension == mirror_no_dot.file_extension == \"png\"\n\n\[email protected](\"tile_source_type\", format_urls.keys())\ndef test_stackmirror_formats_url(tile_source_type):\n mirror = StackMirror(IMAGE_BASE, 256, 256, tile_source_type, \"png\")\n tile_idx = TileIndex(0, 0, 0, 0, 256, 256)\n\n response = mirror.generate_url(tile_idx)\n assert not set(\"{}\").issubset(response)\n\n\ndef test_stackmirror_raises_on_incompatible_tile_index():\n mirror = StackMirror(IMAGE_BASE, 512, 512, TILE_SOURCE_TYPE, \"png\")\n tile_idx = TileIndex(0, 0, 0, 0, 256, 256)\n\n with pytest.raises(ValueError):\n mirror.generate_url(tile_idx)\n\n\ndef test_stackmirror_get_tile_index():\n tile_side = 100\n mirror = StackMirror(IMAGE_BASE, tile_side, tile_side, TILE_SOURCE_TYPE, \"png\")\n tile_idx_kwargs = {\"zoom_level\": 0, \"height\": tile_side, \"width\": tile_side}\n\n # trivial case\n coords = {\"x\": 0, \"y\": 0, \"z\": 0}\n idx, offset = mirror.get_tile_index(coords)\n assert idx == TileIndex(0, 0, 0, **tile_idx_kwargs)\n assert offset == {\"x\": 0, \"y\": 0, \"z\": 0}\n\n # test offset\n coords = {\"x\": 50, \"y\": 50, \"z\": 0}\n idx, offset = mirror.get_tile_index(coords)\n assert idx == TileIndex(0, 0, 0, **tile_idx_kwargs)\n assert offset == {\"x\": 50, \"y\": 50, \"z\": 0}\n\n # test tile idx\n coords = {\"x\": tile_side, \"y\": tile_side, \"z\": 1}\n idx, offset = mirror.get_tile_index(coords)\n assert idx == TileIndex(1, 1, 1, **tile_idx_kwargs)\n assert offset == {\"x\": 0, \"y\": 0, \"z\": 0}\n\n # test row/col correctness\n coords = {\"x\": tile_side, \"y\": 0, \"z\": 0}\n idx, offset = mirror.get_tile_index(coords)\n assert idx == TileIndex(depth=0, row=0, col=1, **tile_idx_kwargs)\n assert offset == {\"x\": 0, \"y\": 0, \"z\": 0}\n\n\n###############\n# Stack tests #\n###############\n\n\ndef test_stack_sets_broken_slices_canary():\n stack = Stack(None)\n\n assert len(stack.broken_slices) == 0\n assert stack.canary_location == {\"x\": 0, \"y\": 0, \"z\": 0}\n\n\ndef test_stack_fastest_mirror_calls_get():\n stack = Stack(None)\n stack.mirrors = [StackMirror(IMAGE_BASE, 512, 512, TILE_SOURCE_TYPE, \"png\")] * 3\n\n with mock.patch(\"requests.get\") as mock_get:\n stack.get_fastest_mirror()\n\n assert mock_get.call_count == 3\n\n\ndef test_stack_fastest_mirror_raises():\n stack = Stack(None)\n stack.mirrors = [StackMirror(IMAGE_BASE, 512, 512, TILE_SOURCE_TYPE, \"png\")] * 3\n\n with pytest.raises(ValueError):\n stack.get_fastest_mirror(timeout=0.01)\n\n\[email protected](reason=\"Mock timeit doesn't work\", raises=ValueError)\ndef test_stack_fastest_mirror_gets_fastest():\n # todo\n stack = Stack(None)\n stack.mirrors = [\n StackMirror(IMAGE_BASE + \"2\", 512, 512, TILE_SOURCE_TYPE, \"png\"),\n StackMirror(IMAGE_BASE + \"1\", 512, 512, TILE_SOURCE_TYPE, \"png\"),\n StackMirror(IMAGE_BASE + \"3\", 512, 512, TILE_SOURCE_TYPE, \"png\"),\n ]\n\n with mock.patch(\"timeit.timeit\", side_effect=[2, 1, 3]):\n m = stack.get_fastest_mirror()\n\n assert m == stack.mirrors[1]\n\n\n###################\n# TileCache tests #\n###################\n\n\ndef test_tilecache_can_set():\n cache = TileCache(None, None)\n key = 1\n value = 1\n\n assert len(cache) == 0\n\n cache[key] = value\n assert len(cache) == 1\n\n\ndef test_tilecache_set_refreshes_old():\n \"\"\"Ensure that newly-pushed items get appended to the end, even if they already exist in the cache\"\"\"\n cache = TileCache(None, None)\n key = 1\n value = 1\n\n assert len(cache) == 0\n\n cache[key] = value\n cache[2] = 2\n assert list(cache) == [1, 2]\n cache[1] = 1\n assert list(cache) == [2, 1]\n\n\ndef test_tilecache_can_get():\n cache = TileCache(None, None)\n key = 1\n value = 1\n\n assert len(cache) == 0\n\n cache[key] = value\n assert len(cache) == 1\n\n response = cache[key]\n assert response == value\n\n\ndef test_tilecache_lru():\n cache = TileCache(None, None)\n cache[1] = 1\n cache[2] = 2\n val = cache[1]\n assert val == 1\n assert list(cache) == [2, 1]\n\n\ndef test_tilecache_can_clear():\n cache = TileCache(None, None)\n key = 1\n value = 1\n\n assert len(cache) == 0\n\n cache[key] = value\n assert len(cache) == 1\n\n cache.clear()\n assert len(cache) == 0\n\n\ndef test_tilecache_can_constrain_len():\n cache = TileCache(3, None)\n\n for key in range(3):\n cache[key] = str(key)\n assert set(cache) == {0, 1, 2}\n\n cache[3] = \"3\"\n assert set(cache) == {1, 2, 3}\n\n\ndef test_tilecache_can_constrain_bytes():\n arr = np.ones((10, 10))\n nbytes = arr.nbytes\n\n cache = TileCache(None, int(nbytes * 3.5))\n\n for key in range(3):\n cache[key] = arr\n assert set(cache) == {0, 1, 2}\n\n cache[3] = arr\n assert set(cache) == {1, 2, 3}\n\n\n######################\n# ImageFetcher tests #\n######################\n\n\ndef test_imagefetcher_can_instantiate():\n ImageFetcher(Stack(None))\n\n\ndef mirror_generator(count=5):\n for idx in range(count):\n yield StackMirror(\n IMAGE_BASE + str(idx),\n 100 + idx,\n 200 + idx,\n TILE_SOURCE_TYPE,\n \"png\",\n title=\"title\" + str(idx),\n position=idx * 2,\n )\n\n\[email protected]\ndef min_fetcher():\n stack = Stack(None)\n stack.mirrors.extend(mirror_generator())\n\n return ImageFetcher(stack)\n\n\ndef test_imagefetcher_mirror_fallback_warning(min_fetcher):\n min_fetcher._mirror = None\n with pytest.warns(UserWarning, match=\"title0\"):\n min_fetcher.mirror\n\n\ndef test_imagefetcher_set_mirror_none(min_fetcher):\n min_fetcher.mirror = None\n\n with pytest.warns(UserWarning, match=\"title0\"):\n min_fetcher.mirror\n\n assert min_fetcher._mirror is None\n\n\ndef test_imagefetcher_set_mirror_mirror(min_fetcher):\n min_fetcher.mirror = min_fetcher.stack.mirrors[1]\n assert min_fetcher._mirror == min_fetcher.stack.mirrors[1]\n\n\ndef test_imagefetcher_set_mirror_mirror_raises(min_fetcher):\n mirror = min_fetcher.stack.mirrors.pop()\n min_fetcher.stack.mirrors = []\n with pytest.raises(ValueError):\n min_fetcher.mirror = mirror\n\n\ndef test_imagefetcher_set_mirror_int(min_fetcher):\n min_fetcher.mirror = 2\n assert min_fetcher._mirror == min_fetcher.stack.mirrors[1]\n\n\ndef test_imagefetcher_set_mirror_int_as_str(min_fetcher):\n min_fetcher.mirror = \"2\"\n assert min_fetcher._mirror == min_fetcher.stack.mirrors[1]\n\n\ndef test_imagefetcher_set_mirror_position_warns_no_match(min_fetcher):\n with pytest.warns(UserWarning, match=\"does not exist\"):\n min_fetcher.mirror = 1000\n assert min_fetcher._mirror is None\n\n\ndef test_imagefetcher_set_mirror_position_warns_too_many(min_fetcher):\n min_fetcher.stack.mirrors.append(\n StackMirror(IMAGE_BASE, 1, 1, TILE_SOURCE_TYPE, \"png\", \"title5\", 0)\n )\n with pytest.warns(UserWarning, match=\"ore than one\"):\n min_fetcher.mirror = 0\n assert min_fetcher._mirror == min_fetcher.stack.mirrors[0]\n\n\ndef test_imagefetcher_set_mirror_title(min_fetcher):\n min_fetcher.mirror = \"title2\"\n assert min_fetcher._mirror == min_fetcher.stack.mirrors[2]\n\n\ndef test_imagefetcher_set_mirror_title_warns_no_match(min_fetcher):\n with pytest.warns(UserWarning, match=\"does not exist\"):\n min_fetcher.mirror = \"not a title\"\n assert min_fetcher._mirror is None\n\n\ndef test_imagefetcher_set_mirror_title_warns_too_many(min_fetcher):\n min_fetcher.stack.mirrors.append(\n StackMirror(IMAGE_BASE, 1, 1, TILE_SOURCE_TYPE, \"png\", \"title0\", 10)\n )\n with pytest.warns(UserWarning, match=\"ore than one\"):\n min_fetcher.mirror = \"title0\"\n assert min_fetcher._mirror == min_fetcher.stack.mirrors[0]\n\n\ndef test_imagefetcher_get_auth_default(min_fetcher):\n min_fetcher.mirror = min_fetcher.stack.mirrors[0]\n assert min_fetcher._session.auth is None\n\n\ndef test_imagefetcher_get_auth_from_mirror(min_fetcher):\n min_fetcher.stack.mirrors[0].auth = (\"name\", \"pass\")\n min_fetcher.mirror = min_fetcher.stack.mirrors[0]\n assert min_fetcher._session.auth == (\"name\", \"pass\")\n\n\ndef test_imagefetcher_get_auth_fallback(min_fetcher):\n min_fetcher.auth = (\"name\", \"pass\")\n min_fetcher.mirror = min_fetcher.stack.mirrors[0]\n assert min_fetcher._session.auth == (\"name\", \"pass\")\n\n\ndef test_imagefetcher_clear_cache(min_fetcher):\n min_fetcher._tile_cache.clear = mock.Mock()\n min_fetcher.clear_cache()\n min_fetcher._tile_cache.clear.assert_called_once()\n\n\ndef test_imagefetcher_map_dimensions(min_fetcher):\n min_fetcher.source_orientation = \"zyx\"\n min_fetcher.target_orientation = \"xyz\"\n\n assert min_fetcher._map_dimensions() == (2, 1, 0)\n\n\ndef test_imagefetcher_reorient(min_fetcher):\n min_fetcher.source_orientation = \"zyx\"\n min_fetcher.target_orientation = \"xyz\"\n min_fetcher._dimension_mappings = min_fetcher._map_dimensions()\n arr = np.ones((3, 4, 5))\n assert min_fetcher._reorient_volume_src_to_tgt(arr).shape == (5, 4, 3)\n\n\ndef test_imagefetcher_reorient_expands(min_fetcher):\n min_fetcher.source_orientation = \"zyx\"\n min_fetcher.target_orientation = \"xyz\"\n min_fetcher._dimension_mappings = min_fetcher._map_dimensions()\n arr = np.ones((3, 4))\n assert min_fetcher._reorient_volume_src_to_tgt(arr).shape == (4, 3, 1)\n\n\ndef test_imagefetcher_reorient_throws(min_fetcher):\n arr = np.ones((3, 4, 5, 6))\n\n with pytest.raises(ValueError):\n min_fetcher._reorient_volume_src_to_tgt(arr)\n\n\n# drc=depth,row,col\[email protected](\n \"roi,expected_drc,expected_yx_minmax\",\n [\n [[[0, 0, 0], [1, 1, 1]], [(0, 0, 0)], ((0, 0), (0, 0))],\n [[[0, 0, 0], [2, 1, 1]], [(0, 0, 0), (1, 0, 0)], ((0, 0), (0, 0))],\n [[[0, 0, 0], [1, 51, 51]], [(0, 0, 0)], ((0, 50), (0, 50))],\n [[[0, 20, 20], [1, 51, 51]], [(0, 0, 0)], ((20, 50), (20, 50))],\n [[[0, 20, 20], [1, 151, 51]], [(0, 0, 0), (0, 1, 0)], ((20, 50), (20, 50))],\n ],\n)\ndef test_imagefetcher_roi_to_tiles(min_fetcher, roi, expected_drc, expected_yx_minmax):\n tile_side = 100\n zoom_level = 0\n mirror = StackMirror(IMAGE_BASE, tile_side, tile_side, TILE_SOURCE_TYPE, \"png\")\n min_fetcher.stack.mirrors = [mirror]\n min_fetcher.mirror = mirror\n\n (min_y, max_y), (min_x, max_x) = expected_yx_minmax\n expected_bounds = {\n \"min\": {\"z\": 0, \"y\": min_y, \"x\": min_x},\n \"max\": {\"z\": 0, \"y\": max_y, \"x\": max_x},\n }\n\n expected_tiles = {\n TileIndex(*drc, zoom_level=zoom_level, height=tile_side, width=tile_side)\n for drc in expected_drc\n }\n\n tiles, slicing = min_fetcher._roi_to_tiles(roi, zoom_level)\n\n assert tiles == expected_tiles\n assert slicing == expected_bounds\n\n\[email protected]\ndef tile_gen(gradient_h):\n def generator():\n while True:\n yield gradient_h.copy()\n\n return generator()\n\n\[email protected]\ndef tile_response_future_gen(tile_gen):\n \"\"\"Endlessly generate a Future containing a Response containing gradient_h as a PNG\"\"\"\n\n def generator():\n for arr in tile_gen:\n future = Future()\n future.set_result(DummyResponse(arr))\n yield future\n\n return generator()\n\n\[email protected](params=[ImageFetcher, ThreadedImageFetcher])\ndef realistic_fetcher(request, gradient_h, tile_gen, tile_response_future_gen):\n tile_height, tile_width = gradient_h.shape\n stack = ProjectStack(\n dimension={\"z\": 100, \"y\": 200, \"x\": 300},\n translation={\"z\": 10, \"y\": 20, \"x\": 30},\n resolution={\"z\": 1, \"y\": 2, \"x\": 3},\n orientation=\"xy\",\n )\n mirror = StackMirror(\n IMAGE_BASE, tile_height, tile_width, TILE_SOURCE_TYPE, \"png\", \"title\", 0\n )\n stack.mirrors.append(mirror)\n\n fetcher = request.param(stack, preferred_mirror=0)\n\n side_effect = (\n tile_gen if request.param == ImageFetcher else tile_response_future_gen\n )\n fetcher._fetch = mock.Mock(side_effect=side_effect)\n\n return fetcher\n\n\[email protected](\n \"roi_mode,zoom_level,expected\",\n [\n [ROIMode.SCALED, 0, [[0, 0, 0], [10, 10, 10]]],\n [ROIMode.STACK, 0, [[0, 0, 0], [10, 10, 10]]],\n [ROIMode.STACK, -2, [[0, 2, 2], [10, 38, 38]]],\n [ROIMode.STACK, 1, [[0, 0, 0], [10, 5, 5]]],\n [ROIMode.PROJECT, 0, [[-10, -10, -10], [0, -5, -6]]],\n [ROIMode.PROJECT, -2, [[-10, -39, -40], [0, -21, -27]]],\n [ROIMode.PROJECT, 1, [[-10, -5, -5], [0, -2, -3]]],\n ],\n)\ndef test_imagefetcher_roi_to_scaled(realistic_fetcher, roi_mode, zoom_level, expected):\n input_roi = np.array([[0.5, 0.5, 0.5], [9.5, 9.5, 9.5]])\n result = realistic_fetcher.roi_to_scaled(input_roi, roi_mode, zoom_level)\n assert np.allclose(result, np.array(expected, dtype=int))\n\n\ndef test_imagefetcher_roi_to_scaled_raises(realistic_fetcher):\n with pytest.raises(NotImplementedError):\n realistic_fetcher.roi_to_scaled(\n [[0, 0, 0], [1, 1, 1]], roi_mode=ROIMode.SCALED, zoom_level=0.5\n )\n\n\[email protected](\n \"roi,expected_fetches\",\n [\n ([[0, 0, 0], [1, 20, 20]], 1),\n ([[0, 0, 0], [2, 20, 20]], 2),\n ([[0, 10, 10], [1, 20, 30]], 1),\n ([[0, 10, 10], [1, 20, 300]], 2),\n ([[0, 0, 0], [1, 20, 300]], 2),\n ([[0, 0, 0], [1, 200, 300]], 4),\n ([[10, 10, 10], [13, 200, 300]], 12),\n ],\n)\ndef test_imagefetcher_get(realistic_fetcher, vol_maker, roi, expected_fetches):\n zoom_level = 0\n roi_mode = ROIMode.SCALED\n\n realistic_fetcher.stack.broken_slices.add(100)\n\n roi = np.asarray(roi)\n\n expected = vol_maker(np.diff(roi, axis=0).squeeze(), roi[0, -1])\n\n output = realistic_fetcher.get(roi, roi_mode, zoom_level)\n\n assert output.shape == expected.shape\n assert np.allclose(expected, output)\n assert realistic_fetcher._fetch.call_count == expected_fetches\n\n\ndef test_imagefetcher_get_into_array(realistic_fetcher, vol_maker):\n zoom_level = 0\n roi_mode = ROIMode.SCALED\n roi = np.array([[10, 10, 10], [13, 200, 300]])\n shape = np.diff(roi, axis=0).squeeze()\n out = np.empty(shape)\n expected = vol_maker(shape, roi[0, -1])\n\n out2 = realistic_fetcher.get(roi, roi_mode, zoom_level, out)\n\n assert out is out2\n assert out2.shape == expected.shape\n assert np.allclose(expected, out2)\n assert realistic_fetcher._fetch.call_count == 12\n\n\ndef test_imagefetcher_get_tile_from_cache(realistic_fetcher, tile_gen):\n cached = next(tile_gen)\n height, width = cached.shape\n tile_index = TileIndex(0, 0, 0, 0, height, width)\n\n realistic_fetcher._tile_cache[tile_index] = cached\n out = realistic_fetcher.get([[0, 0, 0], [1, height, width]], ROIMode.SCALED, 0)\n realistic_fetcher._fetch.assert_not_called()\n assert np.allclose(out.squeeze(), cached)\n\n\ndef test_imagefetcher_get_tile_from_broken_slice(realistic_fetcher, tile_gen):\n height, width = next(tile_gen).shape\n realistic_fetcher.stack.broken_slices.add(0)\n shape = (1, height, width)\n out = realistic_fetcher.get([[0, 0, 0], shape], ROIMode.SCALED, 0)\n expected = np.zeros(shape)\n assert np.allclose(out, expected)\n realistic_fetcher._fetch.assert_not_called()\n\n\ndef test_imagefetcher_get_tile_from_fetch(min_fetcher):\n idx = TileIndex(0, 0, 0, 0, 100, 100)\n min_fetcher._fetch = mock.Mock()\n min_fetcher._get_tile(idx)\n min_fetcher._fetch.assert_called_with(idx)\n\n\ndef test_imagefetcher_fetch(min_fetcher):\n idx = TileIndex(0, 0, 0, 0, 100, 100)\n min_fetcher._session.get = mock.Mock()\n with mock.patch(\"catpy.image.response_to_array\", mock.Mock()):\n min_fetcher._fetch(idx)\n min_fetcher._session.get.assert_called_once()\n\n\[email protected](\"space\", list(ROIMode))\ndef test_imagefetcher_get_wrappers(min_fetcher, space):\n min_fetcher.get = mock.Mock()\n getattr(min_fetcher, \"get_{}_space\".format(space.value))(\"roi\", \"zoom_level\")\n min_fetcher.get.assert_called_with(\"roi\", space, \"zoom_level\", None)\n\n\ndef test_404_handled_correctly(min_fetcher):\n idx = TileIndex(0, 0, 0, 0, 100, 100)\n min_fetcher._session.get = mock.Mock(\n side_effect=HTTPError(response=mock.Mock(status_code=404))\n )\n with mock.patch(\"catpy.image.response_to_array\", mock.Mock()):\n tile = min_fetcher._fetch(idx)\n assert tile.shape == (100, 100)\n assert (tile == 0).sum() == tile.size\n\n\[email protected](reason=\"404 handling not implemented for threaded fetcher\")\ndef test_404_handled_correctly_threaded(min_fetcher):\n assert False\n"
] |
[
[
"numpy.allclose",
"numpy.asarray",
"numpy.ones",
"numpy.diff",
"numpy.array",
"numpy.zeros",
"numpy.empty"
]
] |
note-nota/ML_models
|
[
"e9ede1b5cc3ef7bab43f22467cb806043d86e451"
] |
[
"UNet/model.py"
] |
[
"from typing import Optional\nimport argparse\nimport tensorflow as tf\n\n\nclass conv_set:\n def __init__(self, filters: int):\n self.filters = filters\n\n def __call__(self, inputs: tf.Tensor) -> tf.Tensor:\n y = tf.keras.layers.Conv2D(\n self.filters, kernel_size=3, padding=\"SAME\", activation=\"relu\"\n )(inputs)\n y = tf.keras.layers.Conv2D(\n self.filters, kernel_size=3, padding=\"SAME\", activation=\"relu\"\n )(y)\n y = tf.keras.layers.BatchNormalization()(y)\n return y\n\n\nclass upsampling:\n def __init__(self, filters: int, cut: Optional[int] = 0):\n self.filters = filters\n self.cut = cut\n\n def __call__(self, inputs: tf.Tensor) -> tf.Tensor:\n upconv = tf.keras.layers.Conv2DTranspose(\n self.filters, kernel_size=2, strides=2\n )(inputs[0])\n\n conv_crop = tf.keras.layers.Cropping2D(self.cut)(inputs[1])\n concat = tf.keras.layers.concatenate([conv_crop, upconv])\n\n return concat\n\n\ndef UNet(args: \"argparse.Namespace\") -> tf.keras.Model:\n n_classes: int = args.n_classes\n decay: float = args.l2\n\n x = tf.keras.Input(shape=(224, 224, 3))\n\n # down sampling\n conv1 = conv_set(64)(x)\n max_pool1 = tf.keras.layers.MaxPool2D()(conv1)\n conv2 = conv_set(128)(max_pool1)\n max_pool2 = tf.keras.layers.MaxPool2D()(conv2)\n conv3 = conv_set(256)(max_pool2)\n max_pool3 = tf.keras.layers.MaxPool2D()(conv3)\n conv4 = conv_set(512)(max_pool3)\n max_pool4 = tf.keras.layers.MaxPool2D()(conv4)\n conv5 = conv_set(1024)(max_pool4)\n\n # up sampling\n concat1 = upsampling(512)([conv5, conv4])\n conv6 = conv_set(512)(concat1)\n concat2 = upsampling(256)([conv6, conv3])\n conv7 = conv_set(256)(concat2)\n concat3 = upsampling(128)([conv7, conv2])\n conv8 = conv_set(128)(concat3)\n concat4 = upsampling(64)([conv8, conv1])\n conv9 = conv_set(64)(concat4)\n\n output = tf.keras.layers.Conv2D(filters=n_classes, kernel_size=1)(conv9)\n output = tf.keras.layers.Softmax()(output)\n\n model = tf.keras.Model(inputs=x, outputs=output)\n for layer in model.layers:\n if \"kernel_regularizer\" in layer.__dict__:\n layer.kernel_regularizer = tf.keras.regularizers.l2(decay)\n\n if args.weights != \"\":\n model.load_weights(args.weights)\n\n return model\n"
] |
[
[
"tensorflow.keras.Input",
"tensorflow.keras.layers.Conv2DTranspose",
"tensorflow.keras.layers.Conv2D",
"tensorflow.keras.regularizers.l2",
"tensorflow.keras.layers.concatenate",
"tensorflow.keras.layers.MaxPool2D",
"tensorflow.keras.Model",
"tensorflow.keras.layers.Cropping2D",
"tensorflow.keras.layers.BatchNormalization",
"tensorflow.keras.layers.Softmax"
]
] |
Ch4nYH/dataset-distillation
|
[
"61effcfe8aa7a1a3d9f66ece1fa29bcb393472c2"
] |
[
"networks/networks.py"
] |
[
"import torch.nn as nn\nimport torch.nn.functional as F\n\nfrom . import utils\n\n\nclass LeNet(utils.ReparamModule):\n supported_dims = {28, 32}\n\n def __init__(self, state):\n if state.dropout:\n raise ValueError(\"LeNet doesn't support dropout\")\n super(LeNet, self).__init__()\n self.conv1 = nn.Conv2d(state.nc, 6, 5, padding=2 if state.input_size == 28 else 0)\n self.conv2 = nn.Conv2d(6, 16, 5)\n self.fc1 = nn.Linear(16 * 5 * 5, 120)\n self.fc2 = nn.Linear(120, 84)\n self.fc3 = nn.Linear(84, 1 if state.num_classes <= 2 else state.num_classes)\n\n def forward(self, x):\n out = F.relu(self.conv1(x), inplace=True)\n out = F.max_pool2d(out, 2)\n out = F.relu(self.conv2(out), inplace=True)\n out = F.max_pool2d(out, 2)\n out = out.view(out.size(0), -1)\n out = F.relu(self.fc1(out), inplace=True)\n out = F.relu(self.fc2(out), inplace=True)\n out = self.fc3(out)\n return out\n\n\nclass AlexCifarNet(utils.ReparamModule):\n supported_dims = {32}\n\n def __init__(self, state):\n super(AlexCifarNet, self).__init__()\n assert state.nc == 3\n self.features = nn.Sequential(\n nn.Conv2d(state.nc, 64, kernel_size=5, stride=1, padding=2),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=3, stride=2, padding=1),\n nn.LocalResponseNorm(4, alpha=0.001 / 9.0, beta=0.75, k=1),\n nn.Conv2d(64, 64, kernel_size=5, stride=1, padding=2),\n nn.ReLU(inplace=True),\n nn.LocalResponseNorm(4, alpha=0.001 / 9.0, beta=0.75, k=1),\n nn.MaxPool2d(kernel_size=3, stride=2, padding=1),\n )\n self.classifier = nn.Sequential(\n nn.Linear(4096, 384),\n nn.ReLU(inplace=True),\n nn.Linear(384, 192),\n nn.ReLU(inplace=True),\n nn.Linear(192, state.num_classes),\n )\n\n def forward(self, x):\n x = self.features(x)\n x = x.view(x.size(0), 4096)\n x = self.classifier(x)\n return x\n\n\n# ImageNet\nclass AlexNet(utils.ReparamModule):\n supported_dims = {224}\n\n class Idt(nn.Module):\n def forward(self, x):\n return x\n\n def __init__(self, state):\n super(AlexNet, self).__init__()\n self.use_dropout = state.dropout\n assert state.nc == 3 or state.nc == 1, \"AlexNet only supports nc = 1 or 3\"\n self.features = nn.Sequential(\n nn.Conv2d(state.nc, 64, kernel_size=11, stride=4, padding=2),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=3, stride=2),\n nn.Conv2d(64, 192, kernel_size=5, padding=2),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=3, stride=2),\n nn.Conv2d(192, 384, kernel_size=3, padding=1),\n nn.ReLU(inplace=True),\n nn.Conv2d(384, 256, kernel_size=3, padding=1),\n nn.ReLU(inplace=True),\n nn.Conv2d(256, 256, kernel_size=3, padding=1),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=3, stride=2),\n )\n if state.dropout:\n filler = nn.Dropout\n else:\n filler = AlexNet.Idt\n self.classifier = nn.Sequential(\n filler(),\n nn.Linear(256 * 6 * 6, 4096),\n nn.ReLU(inplace=True),\n filler(),\n nn.Linear(4096, 4096),\n nn.ReLU(inplace=True),\n nn.Linear(4096, 1 if state.num_classes <= 2 else state.num_classes),\n )\n\n def forward(self, x):\n x = self.features(x)\n x = x.view(x.size(0), 256 * 6 * 6)\n x = self.classifier(x)\n return x\n\n\n\nclass BottleNeck(nn.Module):\n \"\"\"Residual block for resnet over 50 layers\n \"\"\"\n expansion = 4\n def __init__(self, in_channels, out_channels, stride=1):\n super().__init__()\n self.residual_function = nn.Sequential(\n nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False),\n nn.BatchNorm2d(out_channels),\n nn.ReLU(inplace=True),\n nn.Conv2d(out_channels, out_channels, stride=stride, kernel_size=3, padding=1, bias=False),\n nn.BatchNorm2d(out_channels),\n nn.ReLU(inplace=True),\n nn.Conv2d(out_channels, out_channels * BottleNeck.expansion, kernel_size=1, bias=False),\n nn.BatchNorm2d(out_channels * BottleNeck.expansion),\n )\n\n self.shortcut = nn.Sequential()\n\n if stride != 1 or in_channels != out_channels * BottleNeck.expansion:\n self.shortcut = nn.Sequential(\n nn.Conv2d(in_channels, out_channels * BottleNeck.expansion, stride=stride, kernel_size=1, bias=False),\n nn.BatchNorm2d(out_channels * BottleNeck.expansion)\n )\n\n def forward(self, x):\n return nn.ReLU(inplace=True)(self.residual_function(x) + self.shortcut(x))\n\nclass BasicBlock(utils.ReparamModule):\n \"\"\"Basic Block for resnet 18 and resnet 34\n \"\"\"\n #BasicBlock and BottleNeck block\n #have different output size\n #we use class attribute expansion\n #to distinct\n expansion = 1\n def __init__(self, state, in_channels, out_channels, stride=1):\n super().__init__()\n #residual function\n self.residual_function = nn.Sequential(\n nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False),\n nn.BatchNorm2d(out_channels),\n nn.ReLU(inplace=True),\n nn.Conv2d(out_channels, out_channels * BasicBlock.expansion, kernel_size=3, padding=1, bias=False),\n nn.BatchNorm2d(out_channels * BasicBlock.expansion)\n )\n #shortcut\n self.shortcut = nn.Sequential()\n #the shortcut output dimension is not the same with residual function\n #use 1*1 convolution to match the dimension\n if stride != 1 or in_channels != BasicBlock.expansion * out_channels:\n self.shortcut = nn.Sequential(\n nn.Conv2d(in_channels, out_channels * BasicBlock.expansion, kernel_size=1, stride=stride, bias=False),\n nn.BatchNorm2d(out_channels * BasicBlock.expansion)\n )\n def forward(self, x):\n return nn.ReLU(inplace=True)(self.residual_function(x) + self.shortcut(x))\nclass ResNet18(utils.ReparamModule):\n supported_dims = {28, 32}\n\n def __init__(self, state, block = BasicBlock, num_block=[2, 2, 2, 2]):\n super().__init__()\n\n self.in_channels = 64\n self.state = state\n self.conv1 = nn.Sequential(\n nn.Conv2d(3, 64, kernel_size=3, padding=1, bias=False),\n nn.BatchNorm2d(64),\n nn.ReLU(inplace=True))\n #we use a different inputsize than the original paper\n #so conv2_x's stride is 1\n self.conv2_x = self._make_layer(block, 64, num_block[0], 1)\n self.conv3_x = self._make_layer(block, 128, num_block[1], 2)\n self.conv4_x = self._make_layer(block, 256, num_block[2], 2)\n self.conv5_x = self._make_layer(block, 512, num_block[3], 2)\n self.avg_pool = nn.AdaptiveAvgPool2d((1, 1))\n self.fc = nn.Linear(512 * block.expansion, state.num_classes)\n\n def _make_layer(self, block, out_channels, num_blocks, stride):\n \"\"\"make resnet layers(by layer i didnt mean this 'layer' was the\n same as a neuron netowork layer, ex. conv layer), one layer may\n contain more than one residual block\n Args:\n block: block type, basic block or bottle neck block\n out_channels: output depth channel number of this layer\n num_blocks: how many blocks per layer\n stride: the stride of the first block of this layer\n Return:\n return a resnet layer\n \"\"\"\n\n # we have num_block blocks per layer, the first block\n # could be 1 or 2, other blocks would always be 1\n strides = [stride] + [1] * (num_blocks - 1)\n layers = []\n for stride in strides:\n layers.append(block(self.state, self.in_channels, out_channels, stride))\n self.in_channels = out_channels * block.expansion\n\n return nn.Sequential(*layers)\n\n def forward(self, x):\n output = self.conv1(x)\n output = self.conv2_x(output)\n output = self.conv3_x(output)\n output = self.conv4_x(output)\n output = self.conv5_x(output)\n output = self.avg_pool(output)\n output = output.view(output.size(0), -1)\n output = self.fc(output)\n\n return output"
] |
[
[
"torch.nn.Sequential",
"torch.nn.LocalResponseNorm",
"torch.nn.Conv2d",
"torch.nn.Linear",
"torch.nn.MaxPool2d",
"torch.nn.AdaptiveAvgPool2d",
"torch.nn.BatchNorm2d",
"torch.nn.ReLU",
"torch.nn.functional.max_pool2d"
]
] |
ccbrain/hddm_upt
|
[
"153abccf20633811503aff5467097ad2cc3fa0e7"
] |
[
"hddm/tests/test_optimization.py"
] |
[
"\nfrom copy import copy\nimport itertools\nimport glob\nimport os\n\nimport unittest\nimport pymc as pm\nimport numpy as np\nimport pandas as pd\nimport nose\npd.set_printoptions(precision=4)\nfrom nose import SkipTest\n\nimport hddm\nfrom hddm.diag import check_model\n\n\ndef add_outliers(data, p_outlier):\n \"\"\"add outliers to data. half of the outliers will be fast, and the rest will be slow\n Input:\n data - data\n p_outliers - probability of outliers\n \"\"\"\n data = pd.DataFrame(data)\n\n #generating outliers\n n_outliers = int(len(data) * p_outlier)\n outliers = data[:n_outliers].copy()\n\n #fast outliers\n outliers.rt[:n_outliers//2] = np.random.rand(n_outliers//2) * (min(abs(data['rt'])) - 0.11) + 0.11\n\n #slow outliers\n outliers.rt[n_outliers//2:] = np.random.rand(n_outliers - n_outliers//2) * 2 + max(abs(data['rt']))\n outliers.response = np.random.randint(0,2,n_outliers)\n\n #combine data with outliers\n data = pd.concat((data, outliers), ignore_index=True)\n return data\n\ndef optimization_recovery_single_subject(repeats=10, seed=1, true_starting_point=True,\n optimization_method='ML'):\n \"\"\"\n recover parameters for single subjects model.\n The test does include recover of inter-variance variables since many times they have only small effect\n on logpable, which makes their recovery impossible.\n \"\"\"\n\n #init\n include_sets = [set(['a','v','t']),\n set(['a','v','t','z'])]\n\n #for each include set create a set of parametersm generate random data\n #and test the optimization function max_retries times.\n v = [0, 0.5, 0.75, 1.]\n np.random.seed(seed)\n for include in include_sets:\n for i in range(repeats):\n\n #generate params for experiment with n_conds conditions\n cond_params, merged_params = hddm.generate.gen_rand_params(include=include, cond_dict={'v':v})\n print(\"*** the true parameters ***\")\n print(merged_params)\n\n #generate samples\n samples, _ = hddm.generate.gen_rand_data(cond_params, size=10000)\n\n h = hddm.models.HDDMTruncated(samples, include=include, depends_on={'v':'condition'})\n\n #set the starting point of the optimization to the true value\n #of the parameters\n if true_starting_point:\n set_hddm_nodes_values(h, merged_params)\n\n #optimize\n if optimization_method == 'ML':\n recovered_params = h.optimize(method='ML')\n elif optimization_method == 'chisquare':\n recovered_params = h.optimize(method='chisquare', quantiles=np.linspace(0.05,0.95,10))\n elif optimization_method == 'gsquare':\n recovered_params = h.optimize(method='gsquare', quantiles=np.linspace(0.05,0.95,10))\n else:\n raise ValueError('unknown optimization method')\n\n #compare results to true values\n index = ['true', 'estimated']\n df = pd.DataFrame([merged_params, recovered_params], index=index, dtype=np.float).dropna(1)\n print(df)\n\n #assert\n np.testing.assert_allclose(df.values[0], df.values[1], atol=0.1)\n\n\ndef set_hddm_nodes_values(model, params_dict):\n \"\"\"\n set hddm nodes values according to the params_dict\n \"\"\"\n for (param_name, row) in model.iter_stochastics():\n if param_name in ('sv_trans', 'st_trans','t_trans','a_trans'):\n transform = np.log\n org_name = '%s' % list(row['node'].children)[0].__name__\n elif param_name in ('sz_trans', 'z_trans'):\n transform = pm.logit\n if param_name == 'z_trans':\n org_name = 'z'\n else:\n org_name = 'sz'\n else:\n org_name = param_name\n transform = lambda x:x\n try:\n model.nodes_db.ix[param_name]['node'].value = transform(params_dict[org_name])\n except KeyError:\n pass\n\n\ndef test_ML_recovery_single_subject_from_random_starting_point():\n optimization_recovery_single_subject(repeats=5, seed=1, true_starting_point=False, optimization_method='ML')\n\ndef test_ML_recovery_single_subject_from_true_starting_point():\n optimization_recovery_single_subject(repeats=5, seed=1, true_starting_point=True, optimization_method='ML')\n\ndef test_chisquare_recovery_single_subject_from_true_starting_point():\n optimization_recovery_single_subject(repeats=5, seed=1, true_starting_point=True, optimization_method='chisquare')\n\ndef test_gsquare_recovery_single_subject_from_true_starting_point():\n optimization_recovery_single_subject(repeats=5, seed=1, true_starting_point=True, optimization_method='gsquare')\n\ndef recovery_with_outliers(repeats=10, seed=1, random_p_outlier=True):\n \"\"\"\n recover parameters with outliers for single subjects model.\n The test does include recover of inter-variance variables since many times they have only small effect\n on logpable, which makes their recovery impossible.\n \"\"\"\n #init\n include_sets = [set(['a','v','t']),\n set(['a','v','t','z'])]\n p_outlier = 0.05\n\n #for each include set create a set of parametersm generate random data\n #and test the optimization function max_retries times.\n v = [0, 0.5, 0.75, 1.]\n np.random.seed(seed)\n for include in include_sets:\n for i in range(repeats):\n #generate params for experiment with n_conds conditions\n cond_params, merged_params = hddm.generate.gen_rand_params(include=include, cond_dict={'v':v})\n print(\"*** the true parameters ***\")\n print(merged_params)\n\n #generate samples\n samples, _ = hddm.generate.gen_rand_data(cond_params, size=200)\n\n #get best recovered_params\n h = hddm.models.HDDMTruncated(samples, include=include, p_outlier=p_outlier, depends_on={'v':'condition'})\n best_params = h.optimize(method='ML')\n\n #add outliers\n samples = add_outliers(samples, p_outlier=p_outlier)\n\n #init model\n if random_p_outlier is None:\n h = hddm.models.HDDM(samples, include=include, depends_on={'v':'condition'})\n elif random_p_outlier:\n h = hddm.models.HDDM(samples, include=include.union(['p_outlier']), depends_on={'v':'condition'})\n else:\n h = hddm.models.HDDM(samples, include=include, p_outlier=p_outlier, depends_on={'v':'condition'})\n\n #optimize\n recovered_params = h.optimize(method='ML')\n\n #compare results to true values\n index = ['best_estimate', 'current_estimate']\n df = pd.DataFrame([best_params, recovered_params], index=index, dtype=np.float).dropna(1)\n print(df)\n\n #assert\n np.testing.assert_allclose(df.values[0], df.values[1], atol=0.15)\n\[email protected](AssertionError)\ndef test_recovery_with_outliers():\n \"\"\"test recovery of data with outliers without modeling them (should fail)\"\"\"\n recovery_with_outliers(repeats=5, seed=1, random_p_outlier=None)\n\ndef test_recovery_with_random_p_outlier():\n \"\"\"test for recovery with o_outliers as random variable\"\"\"\n recovery_with_outliers(repeats=5, seed=1, random_p_outlier=True)\n\ndef test_recovery_with_fixed_p_outlier():\n \"\"\"test for recovery with o_outliers as a fixed value\"\"\"\n recovery_with_outliers(repeats=5, seed=1, random_p_outlier=False)"
] |
[
[
"pandas.concat",
"numpy.random.seed",
"numpy.linspace",
"pandas.DataFrame",
"pandas.set_printoptions",
"numpy.random.rand",
"numpy.testing.assert_allclose",
"numpy.random.randint"
]
] |
zhangzhimin/mace
|
[
"c28f093d719fd650a4308895cd045c26d0f198f6"
] |
[
"tools/python/run_micro.py"
] |
[
"# Copyright 2020 The MACE Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nimport copy\nimport numpy as np\nimport shutil\nimport tempfile\n\nfrom micro_converter import MicroConverter\nfrom py_proto import mace_pb2\nimport run_target\nfrom utils import util\nfrom utils import device\nfrom utils import config_parser\nfrom utils.target import Target\nfrom utils.config_parser import ModelKeys\nfrom utils.util import MaceLogger\nfrom utils.util import mace_check\nimport validate\nimport layers_validate\n\n\ndef join_2d_array(xs):\n return \":\".join([\",\".join([str(y) for y in x]) for x in xs])\n\n\ndef build_engine(model_name, data_type):\n mace_check(flags.model_name is not None and len(model_name) > 0,\n \"you should specify model name for build.\")\n command = (\"micro/tools/cmake/cmake-build-host.sh\"\n \" -DMICRO_MODEL_NAME=%s -DMACE_MICRO_ENABLE_CMSIS=ON\"\n \" -DMACE_MICRO_ENABLE_TOOLS=ON\"\n \" -DCMAKE_BUILD_TYPE=Release\" % model_name)\n if data_type == mace_pb2.DT_BFLOAT16:\n command += \" -DMACE_MICRO_ENABLE_BFLOAT16=ON\"\n print(\"The current engine's data type is bfloat16.\")\n else:\n command += \" -DMACE_MICRO_ENABLE_BFLOAT16=OFF\"\n\n device.execute(command)\n\n\ndef get_model_conf_by_name(flags, conf):\n for name, model_conf in conf[\"models\"].items():\n if not flags.model_name or name == flags.model_name:\n return model_conf\n return None\n\n\ndef run_model(flags, args, conf):\n model_conf = get_model_conf_by_name(flags, conf)\n mace_check(model_conf is not None, \"Get model conf failed.\")\n model_conf = config_parser.normalize_model_config(model_conf)\n run_model_with_conf(flags, args, flags.model_name, model_conf)\n\n\ndef gen_sub_model_conf(output_config, flags, conf):\n model_conf = copy.deepcopy(get_model_conf_by_name(flags, conf))\n model_conf['subgraphs'][0]['output_tensors'] = \\\n output_config['output_tensors']\n model_conf['subgraphs'][0]['output_shapes'] = \\\n output_config['output_shapes']\n return model_conf\n\n\ndef run_layers_validate(flags, args, original_conf):\n model_name = flags.model_name\n original_model_dir = flags.output + \"/\" + \\\n original_conf['library_name'] + \"/model\"\n model_dir = \"/tmp/micro_run/model\"\n device.execute(\"mkdir -p %s\" % model_dir)\n device.execute(\"cp -p %s/%s.pb %s\" %\n (original_model_dir, model_name, model_dir))\n params_file_path = \"%s/%s.data\" % (original_model_dir, model_name)\n output_configs = layers_validate.get_layers(\n model_dir, model_name, flags.layers)\n\n for i in range(len(output_configs)):\n sub_model_conf = gen_sub_model_conf(\n output_configs[i], flags, original_conf)\n with open(output_configs[i]['model_file_path'], \"rb\") as model_file:\n net_def = mace_pb2.NetDef()\n net_def.ParseFromString(model_file.read())\n with open(params_file_path, \"rb\") as params_file:\n weights = bytearray(params_file.read())\n micro_conf = \\\n config_parser.normalize_model_config(sub_model_conf)\n MicroConverter(micro_conf, net_def,\n weights, model_name).gen_code()\n build_engine(model_name, micro_conf[ModelKeys.data_type])\n run_model_with_conf(flags, args, model_name, micro_conf)\n\n\ndef run_model_with_conf(flags, args, model_name, model_conf):\n target_abi = \"host\"\n dev = device.HostDevice(\"host\", target_abi)\n install_dir = \"/tmp/micro_run/\" + model_name\n\n if ModelKeys.check_tensors in model_conf:\n model_conf[ModelKeys.output_tensors] = model_conf[\n ModelKeys.check_tensors]\n model_conf[ModelKeys.output_shapes] = model_conf[\n ModelKeys.check_shapes]\n\n model_args = {\"model_name\": model_name,\n \"input_node\": \",\".join(\n model_conf[ModelKeys.input_tensors]),\n \"input_shape\": join_2d_array(\n model_conf[ModelKeys.input_shapes]),\n \"output_node\": \",\".join(\n model_conf[ModelKeys.output_tensors]),\n \"output_shape\": join_2d_array(\n model_conf[ModelKeys.output_shapes]),\n \"input_data_format\": \",\".join(\n [df.name for df in\n model_conf[ModelKeys.input_data_formats]]),\n \"output_data_format\": \",\".join(\n [df.name for df in\n model_conf[ModelKeys.output_data_formats]])\n }\n\n opts = [\"--%s=%s\" % (arg_key, arg_val) for arg_key, arg_val in\n model_args.items()] + args\n\n # generate data start\n tmp_dir_name = tempfile.mkdtemp()\n input_file_prefix = tmp_dir_name + \"/\" + model_name\n if ModelKeys.validation_inputs_data in model_conf:\n input_tensor = model_conf[ModelKeys.input_tensors]\n input_data = model_conf[ModelKeys.validation_inputs_data]\n mace_check(len(input_tensor) == len(input_data),\n \"len(input_tensor) != len(validate_data\")\n\n for i in range(len(input_tensor)):\n util.download_or_get_file(\n model_conf[ModelKeys.validation_inputs_data][i], \"\",\n util.formatted_file_name(input_file_prefix,\n input_tensor[i]))\n else:\n generate_input_data(input_file_prefix,\n model_conf[ModelKeys.input_tensors],\n model_conf[ModelKeys.input_shapes],\n model_conf[ModelKeys.input_ranges],\n model_conf[ModelKeys.input_data_types])\n\n dev.install(Target(tmp_dir_name), install_dir + \"/validate_in\")\n target_input_file = \"%s/validate_in/%s\" % (\n install_dir, model_name)\n target_output_dir = \"%s/validate_out\" % install_dir\n dev.mkdir(target_output_dir)\n target_output_file = target_output_dir + \"/\" + model_name\n opts += [\"--input_file=%s\" % target_input_file,\n \"--output_file=%s\" % target_output_file]\n # generate data end\n\n envs = []\n if flags.vlog_level > 0:\n envs += [\"MACE_CPP_MIN_VLOG_LEVEL=%s\" % flags.vlog_level]\n\n target = Target(\"build/micro/host/tools/micro_run_static\", [],\n opts=opts,\n envs=envs)\n run_target.run_target(target_abi, install_dir, target,\n device_ids=\"host\")\n\n if flags.validate:\n validate_model_file = util.download_or_get_model(\n model_conf[ModelKeys.model_file_path],\n model_conf[ModelKeys.model_sha256_checksum],\n tmp_dir_name)\n\n validate_weight_file = \"\"\n if ModelKeys.weight_file_path in model_conf:\n validate_weight_file = util.download_or_get_model(\n model_conf[ModelKeys.weight_file_path],\n model_conf[ModelKeys.weight_sha256_checksum],\n tmp_dir_name)\n\n dev.pull(Target(target_output_dir), tmp_dir_name + \"/validate_out\")\n output_file_prefix = tmp_dir_name + \"/validate_out/\" + model_name\n validate.validate(model_conf[ModelKeys.platform],\n validate_model_file,\n validate_weight_file,\n input_file_prefix,\n output_file_prefix,\n model_conf[ModelKeys.input_shapes],\n model_conf[ModelKeys.output_shapes],\n model_conf[ModelKeys.input_data_formats],\n model_conf[ModelKeys.output_data_formats],\n model_conf[ModelKeys.input_tensors],\n model_conf[ModelKeys.output_tensors],\n flags.validate_threshold,\n model_conf[ModelKeys.input_data_types],\n flags.backend,\n \"\",\n \"\")\n shutil.rmtree(tmp_dir_name)\n\n\ndef generate_input_data(input_file, input_node, input_shape, input_ranges,\n input_data_type):\n np.random.seed()\n for i in range(len(input_node)):\n data = np.random.random(input_shape[i]) * (\n input_ranges[i][1] - input_ranges[i][0]) + input_ranges[i][0]\n input_file_name = util.formatted_file_name(input_file, input_node[i])\n MaceLogger.info('Generate input file: %s' % input_file_name)\n if input_data_type[i] == mace_pb2.DT_FLOAT:\n np_data_type = np.float32\n elif input_data_type[i] == mace_pb2.DT_INT32:\n np_data_type = np.int32\n\n data.astype(np_data_type).tofile(input_file_name)\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"--config\",\n type=str,\n default=\"\",\n help=\"yaml conf path\"\n )\n parser.add_argument(\n \"--model_name\",\n type=str,\n default=\"\",\n help=\"model name in yaml conf\"\n )\n parser.add_argument(\n \"--validate\",\n action=\"store_true\",\n help=\"enable validate\"\n )\n parser.add_argument(\n \"--validate_threshold\",\n type=float,\n default=\"0.99\",\n help=\"validate threshold\"\n )\n parser.add_argument(\n \"--layers\",\n type=str,\n default=\"-1\",\n help=\"'start_layer:end_layer' or 'layer', similar to python slice.\"\n \" Use with --validate flag.\")\n parser.add_argument(\n \"--backend\",\n type=str,\n default=\"tensorflow\",\n help=\"onnx backend framework\")\n parser.add_argument(\n \"--build\",\n action=\"store_true\",\n help=\"if build before run\"\n )\n parser.add_argument(\n '--output',\n type=str,\n default=\"build\",\n help=\"output dir\")\n parser.add_argument(\n '--vlog_level',\n type=int,\n default=\"0\",\n help=\"vlog level\")\n\n return parser.parse_known_args()\n\n\nif __name__ == \"__main__\":\n flags, args = parse_args()\n conf = config_parser.parse(flags.config)\n if flags.build or flags.validate:\n micro_conf = config_parser.normalize_model_config(\n conf[ModelKeys.models][flags.model_name])\n build_engine(flags.model_name, micro_conf[ModelKeys.data_type])\n if flags.validate and flags.layers != \"-1\":\n run_layers_validate(flags, args, conf)\n else:\n run_model(flags, args, conf)\n"
] |
[
[
"numpy.random.random",
"numpy.random.seed"
]
] |
WannabeSmith/betting-paper-simulations
|
[
"00a6d870c5d619add22b9710b9b43bb84df5d0c6"
] |
[
"simulations/Time-uniform/simulations.py"
] |
[
"import sys\nimport os\nsys.path.append(os.path.relpath(\"../../\"))\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.stats import binom\nfrom scipy.stats import beta\nfrom scipy.stats import multinomial\nimport matplotlib.cm as cm\n\nfrom confseq.cs_plots import ConfseqToPlot, DataGeneratingProcess, plot_CSs\nfrom confseq.predmix import predmix_empbern_cs, predmix_hoeffding_cs\nfrom confseq.betting import betting_cs\n\nfigures_location = os.path.relpath('figures/')\n\nN = 10000\nalpha = 0.05\n\ncs_list = [\n ConfseqToPlot(\n lambda x: predmix_hoeffding_cs(x, alpha=alpha,\n running_intersection=True),\n 'PM-H [Prop 1]',\n 'tab:orange',\n '-.'\n ),\n ConfseqToPlot(\n lambda x: predmix_empbern_cs(x, truncation=0.5, alpha=alpha,\n running_intersection=True),\n 'PM-EB [Thm 2]',\n 'tab:blue',\n '--'\n ),\n ConfseqToPlot(\n lambda x: betting_cs(x, breaks=1000, trunc_scale=1/2,\n alpha=alpha, parallel=True,\n running_intersection=True),\n r'Hedged [Thm 3]',\n 'tab:green',\n '-'\n ),\n\n]\n\ndgp_list = [\n DataGeneratingProcess(\n data_generator_fn = lambda: np.random.binomial(1, 0.5, N),\n dist_fn = lambda x: binom.pmf(x, 1, 0.5),\n mean = 0.5,\n name = 'Bernoulli_0.5_',\n discrete = True,\n title = '$X_i \\sim$ Bernoulli(1/2)'\n ),\n DataGeneratingProcess(\n data_generator_fn = lambda: np.random.binomial(1, 0.1, N),\n dist_fn = lambda x: binom.pmf(x, 1, 0.1),\n mean = 0.1,\n name = 'Bernoulli_0.1_',\n discrete = True,\n title = '$X_i \\sim$ Bernoulli(1/10)'\n ),\n DataGeneratingProcess(\n data_generator_fn = lambda: np.random.beta(1, 1, N),\n dist_fn = lambda x: beta.pdf(x, 1, 1),\n mean = 0.5,\n name = 'Beta_1,_1_',\n discrete = False,\n title = '$X_i \\sim$ Beta(1, 1)'\n ),\n DataGeneratingProcess(\n data_generator_fn = lambda: np.random.beta(10, 30, N),\n dist_fn = lambda x: beta.pdf(x, 10, 30),\n mean = 1/4,\n name = 'Beta_10,_30_',\n discrete = False,\n title = '$X_i \\sim$ Beta(10, 30)'\n ),\n]\n\nplot_CSs(dgp_list, cs_list, time_uniform=True,\n display_start=10,\n nsim=nsim, log_scale=True, folder=figures_location)\n\nprint('Done!')\n"
] |
[
[
"numpy.random.binomial",
"scipy.stats.binom.pmf",
"numpy.random.beta",
"scipy.stats.beta.pdf"
]
] |
aurmarsan/pyturbo
|
[
"b4f1c6e535b816fbb51b142f7a694aac9ff9b088"
] |
[
"exemples/exemple-lecteur-fnc-snc.py"
] |
[
"import numpy, scipy\nimport pyturbo as p\n\n\n######################################\n# pour lire un fichier surface SNC\npath_snc = \"indiquer.snc\"\nr = p.LecteurSNC(file_path = path_snc)\nr.lire_parametres()\nr.get_infos_temporelles() # ca affiche des trucs\nr.get_infos_variables() # ca affiche d'autres trucs\n\n# on peut lire le maillage (ca prend du temps parce qu'il faut reconstruire l'arbre de connectivite entre les voxels)\nr.lire_maillage()\n# dans ce cas, c'est une bonne idee de l'enregistrer au format VTK en utilisant le writer VTK\n# l'extension .vtm .vtp .vtk est ajoutee automatiquement\np.EcritureVTK(r.get_maillage(), 'lendroit-ou-enregistrer').ecrire()\n\n# ainsi, si on a deja lu le maillage, on peut simplement l'importer et ca va plus vite\n# penser a inclure l'extension .vtm .vtp .vtk dans le nom de fichier\nr.importer_maillage(p.LecteurVTK('lendroit-ou-enregistrer.vtm').get_output())\n\n# enfin on peut lire les donnees qu'on veut\n# le reader separe le domaine en deux blocs: 0 le rotor, 1 le stator. On peut aussi laisse numbloc=None pour lire rotor et stator. \n# ici on lit 'p' a la frame temporelle 10. On tourne le rotor pour le placer en position. On ajouter les faces_id qui peuvent\n# etre bien pratique pour afficher seulement des morceaux de la surface (hub, blade, etc...)\n# on ajoute les normales mais pas les surfaces des cellules. \nr.lire_datas(11, ['p'], rotation_rotor=True, numbloc=0, ajouter_faces_id=True, ajouter_normales=True, ajouter_surfaces=False)\n# on recupere la sortie du reader\ndata = r.get_output()\n\n######################################\n# pour lire un fichier FNC, c'est pas mal pareil. \npath_fnc = \"indiquer.fnc\"\nr = p.LecteurFNC(file_path = path_fnc)\nr.lire_parametres()\nr.get_infos_temporelles()\nr.get_infos_variables()\n\n# ici on va dire qu'on a deja lu et sauvegarde le maillage, alors on ne fait que l'importer.\nr.importer_maillage(p.LecteurVTK('tu-connais-le-chemin').get_output())\n\n# puis on lit les donnees de vitesse, on place le rotor en position. \n# on lit le stator et le rotor (numbloc = None)\nr.lire_datas(11, ['vx', 'vy', 'vz'], \n numbloc = None, \n rotation_rotor = True)\n\nvolume = r.get_output()\n\n\n\n######################################\n# ici un exemple un peu particulier. \n# on veut lire une surface, et la tourner du meme angle que le domaine du rotor (volume) est tourne a un certain instant. \n# C'est utile pour la visualisation quand les temps physique d'extraction de la surface et du volume ne sont pas les memes\nr = p.LecteurSNC(file_path = path_snc)\nr.lire_parametres()\nr.get_infos_temporelles()\nr.get_infos_variables()\nr.importer_maillage(p.LecteurVTK('{0}/VTK-maillages/{1}.vtm'\n .format(path_snc[:path_snc.rfind('/')], path_snc[path_snc.rfind('/') + 1 : ])\n ).get_output())\n# on lit seulement la surface rotor, sans tourner le rotor. On recupere ainsi le maillage a la position t=0. \nr.lire_datas(last_frame_index, [], rotation_rotor=False, numbloc=0, ajouter_faces_id=False, ajouter_normales=False, ajouter_surfaces=False)\nsurface = r.get_output()\n\n# on va chercher dans le fichier FNC les informations qui nous permettent de calculer de combien il faut tourner la surface\n# on ne lit pas les donnees ! Seulement les informations. \nrvol = p.LecteurFNC(file_path = path_fnc)\nrvol.lire_parametres()\nrvol.get_infos_temporelles()\nrvol.get_infos_variables()\n\n# Puis on tourne la surface de l'angle qui va bien. Et voila. \nsurface = p.rotation(surface, numpy.rad2deg(\n rvol.parameters['omega'] * rvol.parameters['sign_rotation'] * rvol.parameters['current_time'][ind] + rvol.parameters['init_angle']\n ))\n\n"
] |
[
[
"numpy.rad2deg"
]
] |
Fatmangh/VIDEO-ACTION-CLASSIFICATION-USING-PRETAINED-SELF-SUPERVISED-DEPTH-AWARE-DENSE-PREDICTIVE-CODING-
|
[
"13fac05601efed16ae8b29989aad487e04cd90a7"
] |
[
"packnet-sfm/packnet_sfm/utils/load.py"
] |
[
"# Copyright 2020 Toyota Research Institute. All rights reserved.\n\nimport importlib\nimport logging\nimport os\nimport warnings\nimport torch\n\nfrom inspect import signature\nfrom collections import OrderedDict\n\nimport sys\nsys.path.append('../packnet-sfm/packnet_sfm/utils')\nsys.path.append('../packnet-sfm/configs')\nsys.path.append('../packnet-sfm/packnet_sfm/models')\nsys.path.append('../packnet-sfm/packnet_sfm/networks/pose')\nsys.path.append('../packnet-sfm/packnet_sfm/networks/depth')\nfrom misc import make_list, same_shape\n#from logging import pcolor\n#from horovod import print0\n#from packnet_sfm.utils.types import is_str\nimport default_config\nimport SelfSupModel\nimport PackNet01\nimport PoseNet\n\ndef is_str(data):\n \"\"\"Checks if data is a string.\"\"\"\n return isinstance(data, str)\n\n\ndef set_debug(debug):\n \"\"\"\n Enable or disable debug terminal logging\n\n Parameters\n ----------\n debug : bool\n Debugging flag (True to enable)\n \"\"\"\n # Disable logging if requested\n if not debug:\n os.environ['NCCL_DEBUG'] = ''\n os.environ['WANDB_SILENT'] = 'false'\n warnings.filterwarnings(\"ignore\")\n logging.disable(logging.CRITICAL)\n\n\ndef filter_args(func, keys):\n \"\"\"\n Filters a dictionary so it only contains keys that are arguments of a function\n\n Parameters\n ----------\n func : Function\n Function for which we are filtering the dictionary\n keys : dict\n Dictionary with keys we are filtering\n\n Returns\n -------\n filtered : dict\n Dictionary containing only keys that are arguments of func\n \"\"\"\n filtered = {}\n sign = list(signature(func).parameters.keys())\n for k, v in {**keys}.items():\n if k in sign:\n filtered[k] = v\n return filtered\n\n\ndef filter_args_create(func, keys):\n \"\"\"\n Filters a dictionary so it only contains keys that are arguments of a function\n and creates a function with those arguments\n\n Parameters\n ----------\n func : Function\n Function for which we are filtering the dictionary\n keys : dict\n Dictionary with keys we are filtering\n\n Returns\n -------\n func : Function\n Function with filtered keys as arguments\n \"\"\"\n return func(**filter_args(func, keys))\n\n\ndef load_class(filename, paths, concat=True):\n \"\"\"\n Look for a file in different locations and return its method with the same name\n Optionally, you can use concat to search in path.filename instead\n\n Parameters\n ----------\n filename : str\n Name of the file we are searching for\n paths : str or list of str\n Folders in which the file will be searched\n concat : bool\n Flag to concatenate filename to each path during the search\n\n Returns\n -------\n method : Function\n Loaded method\n \"\"\"\n # for each path in paths\n for path in make_list(paths):\n # Create full path\n full_path = '{}.{}'.format(path, filename) if concat else path\n if full_path != \"\" and full_path[0] == '.':\n full_path = full_path[1:]\n #print(full_path)\n if importlib.util.find_spec(full_path):\n # Return method with same name as the file\n return getattr(importlib.import_module(full_path), filename)\n raise ValueError('Unknown class {}'.format(filename))\n\n\ndef load_class_args_create(filename, paths, args={}, concat=True):\n \"\"\"Loads a class (filename) and returns an instance with filtered arguments (args)\"\"\"\n class_type = load_class(filename, paths, concat)\n return filter_args_create(class_type, args)\n\n\ndef load_network(network, path, prefixes=''):\n \"\"\"\n Loads a pretrained network\n\n Parameters\n ----------\n network : nn.Module\n Network that will receive the pretrained weights\n path : str\n File containing a 'state_dict' key with pretrained network weights\n prefixes : str or list of str\n Layer name prefixes to consider when loading the network\n\n Returns\n -------\n network : nn.Module\n Updated network with pretrained weights\n \"\"\"\n prefixes = make_list(prefixes)\n # If path is a string\n if is_str(path):\n saved_state_dict = torch.load(path, map_location='cpu')['state_dict']\n if path.endswith('.pth.tar'):\n saved_state_dict = backwards_state_dict(saved_state_dict)\n # If state dict is already provided\n else:\n saved_state_dict = path\n # Get network state dict\n network_state_dict = network.state_dict()\n\n updated_state_dict = OrderedDict()\n n, n_total = 0, len(network_state_dict.keys())\n for key, val in saved_state_dict.items():\n for prefix in prefixes:\n prefix = prefix + '.'\n if prefix in key:\n idx = key.find(prefix) + len(prefix)\n key = key[idx:]\n if key in network_state_dict.keys() and \\\n same_shape(val.shape, network_state_dict[key].shape):\n updated_state_dict[key] = val\n n += 1\n\n network.load_state_dict(updated_state_dict, strict=False)\n base_color, attrs = 'cyan', ['bold', 'dark']\n color = 'green' if n == n_total else 'yellow' if n > 0 else 'red'\n print0(pcolor('###### Pretrained {} loaded:'.format(prefixes[0]), base_color, attrs=attrs) +\n pcolor(' {}/{} '.format(n, n_total), color, attrs=attrs) +\n pcolor('tensors', base_color, attrs=attrs))\n return network\n\n\ndef backwards_state_dict(state_dict):\n \"\"\"\n Modify the state dict of older models for backwards compatibility\n\n Parameters\n ----------\n state_dict : dict\n Model state dict with pretrained weights\n\n Returns\n -------\n state_dict : dict\n Updated model state dict with modified layer names\n \"\"\"\n # List of layer names to change\n changes = (('model.model', 'model'),\n ('pose_network', 'pose_net'),\n ('disp_network', 'depth_net'))\n # Iterate over all keys and values\n updated_state_dict = OrderedDict()\n for key, val in state_dict.items():\n # Ad hoc changes due to version changes\n key = '{}.{}'.format('model', key)\n if 'disp_network' in key:\n key = key.replace('conv3.0.weight', 'conv3.weight')\n key = key.replace('conv3.0.bias', 'conv3.bias')\n # Change layer names\n for change in changes:\n key = key.replace('{}.'.format(change[0]),\n '{}.'.format(change[1]))\n updated_state_dict[key] = val\n # Return updated state dict\n return updated_state_dict\n"
] |
[
[
"torch.load"
]
] |
space-physics/geomag-indices
|
[
"c989f7df05ac1082f7347cd32cfee7a916e3b30d"
] |
[
"src/geomagindices/io.py"
] |
[
"from __future__ import annotations\nfrom pathlib import Path\nimport pandas\nimport numpy as np\nfrom datetime import datetime, timedelta\nfrom dateutil.parser import parse\n\nfrom .web import URLmonthly, URL45dayfcast, URL20yearfcast\nfrom .utils import yeardec2datetime\n\n\ndef load(flist: Path | list[Path]) -> pandas.DataFrame:\n \"\"\"\n select data to load and collect into pandas.Dataframe by time\n \"\"\"\n\n if isinstance(flist, Path):\n flist = [flist]\n\n monthly_data = pandas.DataFrame(columns=[\"Ap\", \"f107\"])\n inds = []\n for fn in flist:\n if len(fn.name) == 4:\n inds.append(readdaily(fn))\n elif fn.name == URLmonthly[\"f107\"].split(\"/\")[-1]:\n monthly_data[\"f107\"] = read_monthly(fn)\n elif fn.name == URLmonthly[\"Ap\"].split(\"/\")[-1]:\n monthly_data[\"Ap\"] = read_monthly(fn)\n elif fn.name == URL45dayfcast.split(\"/\")[-1]:\n inds.append(read45dayfcast(fn))\n elif fn.name == URL20yearfcast.split(\"/\")[-1].split(\".\")[0] + \".txt\":\n inds.append(read20yearfcast(fn))\n else:\n raise OSError(fn)\n\n if monthly_data.size > 0:\n inds.append(monthly_data)\n\n dat = pandas.concat(inds, sort=True).sort_index() # destroys metadata\n\n return dat\n\n\n# not lru_cache b/c list[path]\n\n\ndef readdaily(flist: Path | list[Path]) -> pandas.DataFrame:\n kp_cols = [(12, 14), (14, 16), (16, 18), (18, 20), (20, 22), (22, 24), (24, 26), (26, 28)]\n ap_cols = [(31, 34), (34, 37), (37, 40), (40, 43), (43, 46), (46, 49), (49, 52), (52, 55)]\n f107_cols = (65, 70)\n\n rawAp: list[str] = []\n rawKp: list[str] = []\n rawf107: list[str] = []\n days = []\n\n if isinstance(flist, Path):\n flist = [flist]\n\n for fn in flist:\n with fn.open() as f:\n for line in f:\n # FIXME: century ambiguity of original data\n year = 2000 + int(line[:2]) if int(line[:2]) < 38 else 1900 + int(line[:2])\n days.append(datetime(year=year, month=int(line[2:4]), day=int(line[4:6])))\n rawAp += [line[i[0] : i[1]] for i in ap_cols]\n rawKp += [line[i[0] : i[1]] for i in kp_cols]\n\n # f10.7 is daily index\n # MUCH faster to generate here than to fill after DF generation\n rawf107 += [line[f107_cols[0] : f107_cols[1]]] * 8\n # %% construct time\n dtime = [day + timedelta(minutes=m) for day in days for m in range(90, 24 * 60 + 90, 3 * 60)]\n # %% build and fill array\n names = [\"Ap\", \"Kp\"]\n df = pandas.DataFrame(index=dtime, columns=names)\n # tolerate missing values\n df[\"Ap\"] = pandas.to_numeric(rawAp, errors=\"coerce\")\n\n # Kp / 10 as per ftp://ftp.ngdc.noaa.gov/STP/GEOMAGNETIC_DATA/INDICES/KP_AP/kp_ap.fmt (github issue #2)\n df[\"Kp\"] = pandas.to_numeric(rawKp, errors=\"coerce\") / 10.0\n df[\"f107\"] = pandas.to_numeric(rawf107, errors=\"coerce\")\n\n df[\"resolution\"] = \"d\"\n\n return df\n\n\ndef read20yearfcast(fn: Path) -> pandas.DataFrame:\n \"\"\"\n uses 50th percentile of Ap and f10.7\n \"\"\"\n dat = np.loadtxt(fn, usecols=(0, 3, 6), skiprows=11)\n\n time = yeardec2datetime(dat[:, 0])\n\n data = pandas.DataFrame(data=dat[:, 1:3], index=time, columns=[\"Ap\", \"f107\"])\n\n data[\"resolution\"] = \"m\"\n\n return data\n\n\ndef read_monthly(file: Path) -> pandas.Series:\n\n if file.suffix == \".json\":\n dat = pandas.read_json(file)\n\n date = [datetime(int(ym[:4]), int(ym[5:7]), 1) for ym in dat[\"time-tag\"]]\n data = pandas.Series(index=date, data=dat[\"f10.7\"].values)\n elif file.suffix == \".ave\":\n dat = np.genfromtxt(file, usecols=range(1, 14), missing_values=\".\")\n\n date = []\n for year in dat[:, 0]:\n for month in range(1, 13):\n date.append(datetime(int(year), month, 1))\n\n data = pandas.Series(index=date, data=dat[:, 1:].ravel())\n\n data[data < 0] = np.nan # by NOAA definition\n\n return data\n\n\ndef read45dayfcast(fn: Path) -> pandas.DataFrame:\n Ap: list[int] = []\n\n with fn.open(\"r\") as f:\n for line in f:\n if line[0] in (\"#\", \":\") or line.startswith(\"45-DAY AP FORECAST\"):\n continue\n elif line.startswith(\"45-DAY F10.7 CM FLUX FORECAST\"):\n break\n # %% Ap\n ls = line.split()\n # time += [parse(t) for t in ls[::2]] # duplicate of below\n Ap += [int(a) for a in ls[1::2]]\n # %% F10.7\n time: list[datetime] = []\n f107: list[float] = []\n for line in f:\n if line.startswith(\"FORECASTER\"):\n break\n\n ls = line.split()\n time += [parse(t) for t in ls[::2]]\n f107 += [float(a) for a in ls[1::2]]\n\n dat = pandas.DataFrame(data=np.column_stack((Ap, f107)), index=time, columns=[\"Ap\", \"f107\"])\n\n dat[\"resolution\"] = \"w\"\n\n return dat\n"
] |
[
[
"pandas.concat",
"pandas.Series",
"pandas.DataFrame",
"pandas.read_json",
"numpy.column_stack",
"pandas.to_numeric",
"numpy.loadtxt"
]
] |
jackstellwagen/deepcell-tf
|
[
"d9326b8aceb2f25637e0d3934646da8f6a9f9539"
] |
[
"deepcell/utils/export_utils.py"
] |
[
"# Copyright 2016-2019 The Van Valen Lab at the California Institute of\n# Technology (Caltech), with support from the Paul Allen Family Foundation,\n# Google, & National Institutes of Health (NIH) under Grant U24CA224309-01.\n# All rights reserved.\n#\n# Licensed under a modified 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.github.com/vanvalenlab/deepcell-tf/LICENSE\n#\n# The Work provided may be used for non-commercial academic purposes only.\n# For any other use of the Work, including commercial use, please contact:\n# [email protected]\n#\n# Neither the name of Caltech nor the names of its contributors may be used\n# to endorse or promote products derived from this software without specific\n# prior written permission.\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Functions for exporting convolutional neural networks for TF serving\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nfrom __future__ import division\n\nimport os\n\nimport tensorflow as tf\nfrom tensorflow.python.keras import backend as K\nfrom tensorflow.python.saved_model import tag_constants\nfrom tensorflow.python.saved_model import signature_constants\nfrom tensorflow.python.saved_model.builder import SavedModelBuilder\n\n\ndef export_model(keras_model, export_path, model_version=0, weights_path=None):\n \"\"\"Export a model for use with tensorflow-serving.\n\n Args:\n keras_model: instantiated Keras model to export\n export_path: destination to save the exported model files\n model_version: integer version of the model\n weights_path: path to a .h5 or .tf weights file for the model to load\n \"\"\"\n # Start the tensorflow session\n gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.8, allow_growth=False)\n sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))\n\n K.set_session(sess)\n K._LEARNING_PHASE = tf.constant(0)\n K.set_learning_phase(0)\n\n # Create export path if it doesn't exist\n export_path = os.path.join(export_path, str(model_version))\n builder = SavedModelBuilder(export_path)\n # legacy_init_op = tf.group(tf.tables_initializer(), name='legacy_init_op')\n\n # Initialize global variables and the model\n init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())\n sess.run(init_op)\n\n # Load the model and the weights\n if weights_path is not None:\n keras_model.load_weights(weights_path)\n\n if type(keras_model.input) is list:\n output = keras_model.output[-1]\n else:\n output = keras_model.output\n\n # Define prediction signature\n if type(keras_model.input) is list:\n input_map = {\"input{}\".format(i): input_tensor\n for i, input_tensor in enumerate(keras_model.input)}\n output_map = {\"prediction\": output}\n else:\n input_map = {\"input\": keras_model.input}\n output_map = {\"prediction\": output}\n\n prediction_signature = tf.saved_model.signature_def_utils.predict_signature_def(\n input_map,\n output_map\n )\n\n # Add the meta_graph and the variables to the builder\n builder.add_meta_graph_and_variables(\n sess, [tag_constants.SERVING],\n signature_def_map={\n signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY:\n prediction_signature\n })\n\n # Save the graph\n builder.save()\n"
] |
[
[
"tensorflow.python.saved_model.builder.SavedModelBuilder",
"tensorflow.constant",
"tensorflow.local_variables_initializer",
"tensorflow.ConfigProto",
"tensorflow.global_variables_initializer",
"tensorflow.GPUOptions",
"tensorflow.python.keras.backend.set_session",
"tensorflow.python.keras.backend.set_learning_phase",
"tensorflow.saved_model.signature_def_utils.predict_signature_def"
]
] |
nxihe/xhtools
|
[
"6cdebc576fe6d89f69a4ef8c5cfb23cd7036ab6c"
] |
[
"xhtools.py"
] |
[
"import pandas as pd\nimport numpy as np\n\nclass Xhtools:\n '''\n npproduct:求两个一维数组的笛卡尔积\n threesigmod:根据3Sigma法则求异常值\n numericoutlier:箱线图法求异常值\n cutbin:自定义分箱,woe、iv值计算\n '''\n def __init__(self):\n return None\n \n def npproduct(self,array1,array2):\n if len(array1) == len(array2):\n return np.transpose([np.repeat(array1, len(array1)), np.tile(array2, len(array2))])\n else:\n return 'array1、array2长度需一致'\n \n def threesigmod(self,array1,array2):\n avg = np.mean(array1)\n std = np.std(array1)\n threshold_up = float(avg + 3*std)\n threshold_down = float(avg -3*std)\n errornum = list(filter(lambda s:(s< threshold_down)|(s> threshold_up),array2))\n return errornum\n \n def numericoutlier(self,array1,array2):\n iqr = np.quantile(array1,0.75) - np.quantile(array1,0.25)\n q_down = float(np.quantile(array1,0.25)-1.5*iqr)\n q_up = float(np.quantile(array1,0.75)+1.5*iqr)\n errornum = list(filter(lambda s:(s<q_down)|(s>q_up),array2))\n return errornum\n \n def cutbin(self,x,y,cut): # x为待分箱的变量,y为target变量,cut为自定义的分箱(list)\n total = y.count() # 计算总样本数\n bad = y.sum() # 计算坏样本数\n good = y.count()-y.sum() # 计算好样本数\n d1 = pd.DataFrame({'x':x,'y':y,'bucket':pd.cut(x,cut)}) \n d2 = d1.groupby('bucket',as_index=True) # 按照分箱结果进行分组聚合\n d3 = pd.DataFrame(d2.x.min(),columns=['min_bin']) \n d3['min_bin'] = d2.x.min() # 箱体的左边界\n d3['max_bin'] = d2.x.max() # 箱体的右边界\n d3['bad'] = d2.y.sum() # 每个箱体中坏样本的数量\n d3['total'] = d2.y.count() # 每个箱体的总样本数\n d3['bad_rate'] = d3['bad']/d3['total'] # 每个箱体中坏样本所占总样本数的比例\n d3['badattr'] = d3['bad']/bad # 每个箱体中坏样本所占坏样本总数的比例\n d3['goodattr'] = (d3['total'] - d3['bad'])/good # 每个箱体中好样本所占好样本总数的比例\n d3['woe'] = np.log(d3['goodattr']/d3['badattr']) # 计算每个箱体的woe值\n iv = ((d3['goodattr']-d3['badattr'])*d3['woe']).sum() # 计算变量的iv值\n d4 = (d3.sort_values(by='min_bin')).reset_index(drop=True) # 对箱体从大到小进行排序\n woe = list(d4['woe'].round(3))\n return d4,iv,woe"
] |
[
[
"numpy.log",
"numpy.quantile",
"numpy.std",
"numpy.mean",
"pandas.cut"
]
] |
thibnoel/solo-collisions
|
[
"87bf492266578b7bfd04a6657675b1477d27b314"
] |
[
"src/python/collision_approx_fourier.py"
] |
[
"import numpy as np \nfrom scipy import signal\nimport matplotlib.pyplot as plt\nfrom solo12_shoulder_collision_utils import followBoundary, colMapToDistField\n\n# Load the collision map from file\nres = 200\ncol_map_file = './npy_data/collision_map_centered_res{}.npy'.format(res)\ndist_field_file = './npy_data/updated_collision_map_distance_res{}.npy'.format(res)\ncol_map = np.load(col_map_file, allow_pickle=True)\ncol_map = col_map.T\ndist_field = np.load(dist_field_file, allow_pickle=True)\n\n\"\"\"\ntraj1 = followBoundary(col_map.T)\ntraj2 = followBoundary(col_map.T, first_dir=2)\ntraj2 = [traj2[-i] for i in range(len(traj2))]\n\ntraj1X = np.array([t[0] for t in traj1])\ntraj1Y = np.array([t[1] for t in traj1])\n\ntraj2X = np.array([t[0] for t in traj2])\ntraj2Y = np.array([t[1] for t in traj2])\n#traj2X = np.concatenate([traj2X, traj2X + len(traj2X), traj2X + 2*len(traj2X)])\n#traj2Y = np.array(3*[t[1] for t in traj2])\n\ndef approxFourier(trajX, trajY, Nh, plot=True):\n complexTraj = np.array(trajX + 1j*trajY)\n period = len(complexTraj)\n time = np.array([i for i in range(period)])\n\n def cn(n):\n c = complexTraj*np.exp(-1j*2*n*np.pi*time/period)\n return c.sum()/c.size\n\n def f(x, Nh):\n f = np.array([cn(i)*np.exp(1j*2*i*np.pi*x/period) for i in range(-Nh-1,Nh+1)])\n return f.sum()\n\n traj_est = np.array([f(t,Nh) for t in time])\n #plt.figure()\n if(plot):\n plt.plot(complexTraj.real - complexTraj.real[int(len(complexTraj)/3)], complexTraj.imag, \n linewidth=2, \n c='limegreen')\n plt.plot(traj_est.real[10:-10] - complexTraj.real[int(len(complexTraj)/3)], traj_est.imag[10:-10], 'r-', linewidth=2,\n label=\"Fourier series - {} harmonics\".format(Nh))\n #plt.plot(trajX, trajY_est)\n return traj_est\n\ndef approxPolynom(trajX, trajY, deg, plot=True):\n polynCoeffs = np.polyfit(trajX, trajY, deg)\n polynEval = np.poly1d(polynCoeffs)\n\n if(plot):\n #plt.figure()\n #plt.plot(trajX, trajY)\n plt.plot(trajX, polynEval(trajX),linewidth=2, c='yellow',label=\"Polynom - deg. {}\".format(deg))\n return [trajX, polynEval(trajX)]\n\ndef newApproxFourier(colMap, Nh):\n period = [len(colMap), len(colMap[0])]\n xRange = np.linspace(0,period[0],period[0])\n yRange = np.linspace(0,period[1],period[1])\n gridX, gridY = np.meshgrid(xRange,yRange)\n\n # Compute the 2D fourier coeff of index (i,j)\n def c_mn(m,n):\n c = (1./(4*np.pi*np.pi))*colMap*np.exp(-1j*2*np.pi*m*gridX/period[0])*np.exp(-1j*2*np.pi*n*gridY/period[1])\n return c.sum()/c.size\n\n # Evaluate f based on the coeffs\n def f(x,y,Nh):\n f = np.array([ [c_mn(k,l)*np.exp(1j*2*np.pi*l*x/period[0])*np.exp(1j*2*np.pi*k*y/period[1]) for l in range(-Nh-1, Nh+1)] for k in range(-Nh-1, Nh+1)])\n return f.sum()\n\n estim = [[f(x, y, Nh) for y in yRange] for x in xRange]\n return estim\n\n\"\"\"\n\"\"\"\n#print(traj2)\n#plt.subplot(2,2,1)\n#approxFourier(traj1, 50, plot=False)\n#plt.subplot(2,2,2)\n#approxPolynom(traj1, 10, plot=False)\n#plt.subplot(2,2,3)\nplt.figure()\nplt.imshow(col_map)\nplt.plot(traj1X, traj1Y, 'r')\n\n#polynTraj1 = approxPolynom(traj1X, traj1Y, 101, plot=True)\n#traj1X = np.concatenate([traj1X, traj1X + len(traj1X), traj1X + 2*len(traj1X)])\n#traj1Y = np.array(3*[t[1] for t in traj1])\n#fourierTraj1 = approxFourier(traj1X, traj1Y, 10, plot=True)\n#fourierTraj2 = approxFourier(traj2X, traj2Y, 100, plot=True)\n#plt.subplot(2,2,4)\n\n#polynTraj2 = approxPolynom(traj2, 10, plot=True)\nplt.legend()\nplt.title('Collision boundary approximation')\n\nplt.figure()\nplt.grid(True)\nplt.plot(traj1X, traj1Y + 2*len(col_map)/4)\n#plt.plot(fourierTraj1.real[10:-10], fourierTraj1.imag[10:-10] + len(col_map)/4)\n#plt.plot(polynTraj1[0] + fourierTraj1.real[int(len(fourierTraj1)/3)], polynTraj1[1])\n#plt.plot(polynTraj1[0] , polynTraj1[1])\nplt.show()\n'''\n'''\ndist_field = np.array(colMapToDistField(col_map.T))\nnp.save('./npy_data/collision_map_distance_res1000', dist_field)\n\nplt.figure()\nplt.imshow(col_map.T)\nplt.plot(traj1X, traj1Y,'r')\nplt.plot(traj2X, traj2Y,'r')\n\nplt.figure()\nplt.imshow(dist_field, cmap=plt.cm.RdYlGn)\n#plt.plot(traj1X, traj1Y, 'r')\n#plt.plot(traj2X, traj2Y,'r')\nplt.colorbar(label='Dist. to boundary')\n\nplt.figure()\n#cumul_dist_field = (dist_field > 0).astype(float) + (dist_field > 10) + (dist_field > 20) + (dist_field > 30) + (dist_field > 40)\ncumul_dist_field = (dist_field > 0.1).astype(float) + (dist_field < -0.1)\nplt.imshow(cumul_dist_field)\n\nplt.show()\n\"\"\"\n\n\ndef thresholdFilter(threshold, fft):\n return (np.log(1 + abs(fft)) > threshold)*fft\n\ndef vBandFilter(bandwidth, fft):\n copy = np.fft.fftshift(fft)\n copy[:,0:bandwidth] = 0\n copy[:,len(copy) - bandwidth:len(copy)] = 0\n return np.fft.ifftshift(copy)\n\ndef computePredictionError(fft, dist_field, offset, optim=False, optimRate=1):\n def optimOffset(wrong_pred, pred_error, offset):\n while(wrong_pred > 0):\n offset = offset + max(wrong_pred*0.001, optimRate)\n pred_error = abs(np.fft.ifft2(fft) + np.min(dist_field) > offset) - np.asarray((dist_field > 0), dtype=float)\n wrong_pred = np.count_nonzero(pred_error > 0)\n return wrong_pred, pred_error, offset\n\n pred_error = abs(np.fft.ifft2(fft) + np.min(dist_field) > offset) - np.asarray((dist_field > 0), dtype=float)\n wrong_pred = np.count_nonzero(pred_error > 0)\n if(optim):\n wrong_pred, pred_error, offset = optimOffset(wrong_pred, pred_error, offset)\n lost_space = np.count_nonzero(pred_error != 0)\n\n return wrong_pred, lost_space, pred_error\n\ndef plotLostSpaceVsNbCoeff(fft, dist_field, thresholds):\n nb_coeffs = []\n lost_space = []\n\n cumul_lost = np.zeros(dist_field.shape)\n\n for t in thresholds:\n thresh_estim = thresholdFilter(t, fft)\n n_err, lost, error_map = computePredictionError(thresh_estim, dist_field, 5, optim=True, optimRate=0.05)\n nb_coeffs.append(np.count_nonzero(thresh_estim))\n lost_space.append(100*lost/np.count_nonzero(dist_field > 0))\n\n cumul_lost = cumul_lost - error_map\n\n plt.plot(nb_coeffs, lost_space, '-+')\n plt.grid(True)\n plt.xscale(\"log\")\n plt.xlabel(\"Nb. coeffs of the FFT to evaluate\")\n plt.ylabel(\"Lost range of motion (%)\")\n\n plt.figure()\n plt.imshow(cumul_lost)\n\nestim = np.fft.fft2(dist_field - np.min(dist_field))\n\nlog_threshold = 12\n#thresh_estim = vBandFilter(240,estim)\nthresh_estim = thresholdFilter(log_threshold, estim)\n\nplt.figure()\nplt.subplot(2,2,1)\n#plt.imshow(abs(np.fft.ifft2(estim)), cmap=plt.cm.RdYlGn)\nplt.imshow(dist_field, cmap=plt.cm.RdYlGn)\n\n#plt.figure()\nplt.subplot(2,2,2)\nplt.imshow(abs(np.fft.ifft2(thresh_estim)), cmap=plt.cm.RdYlGn)\nplt.title(\"Estimated distance (iFFT of thresholded transform)\")\n\n#error_map = (abs(np.fft.ifft2(thresh_estim)) + np.min(dist_field) > 0) - np.asarray((dist_field > 0), dtype=float)\nn_err, lost, error_map = computePredictionError(thresh_estim, dist_field, 5, optim=True)\n#plt.figure()\nplt.subplot(2,2,4)\nplt.imshow(error_map)\nplt.title(\"Prediction errors on binary collision check\\n{:.2f}% lost space\".format(100*lost/np.count_nonzero(dist_field > 0)))\n\n#plt.figure()\nplt.subplot(2,2,3)\nplt.imshow(np.fft.fftshift(np.log(1 + abs(thresh_estim))))\nplt.title(\"Filtered FFT : log(abs(F(fx,fy))) > {}\\n {} non zero coeff.\".format(log_threshold,np.count_nonzero(thresh_estim)))\n\n'''\n# Diff map\nplt.figure()\ndiff_map = abs(np.fft.ifft2(thresh_estim)) - dist_field + np.min(dist_field)\nplt.imshow(diff_map)\n'''\n\nprint(\"FFT non zero values : \")\nprint(np.count_nonzero(thresh_estim))\n\nprint(\"Error ratio : \")\nprint(np.count_nonzero(error_map)/error_map.size)\n\n'''\n# Periodic view\nplt.figure()\nwideview = np.concatenate([np.concatenate([abs(np.fft.ifft2(thresh_estim)),abs(np.fft.ifft2(thresh_estim))]),\n np.concatenate([abs(np.fft.ifft2(thresh_estim)),abs(np.fft.ifft2(thresh_estim))])], axis=1)\nplt.imshow(wideview, cmap=plt.cm.RdYlGn)\n'''\n\nplt.figure()\nplotLostSpaceVsNbCoeff(estim, dist_field, [0,5,8,10,11,12,12.5,13,13.5,14,14.5,15,15.5,16])\n#plotLostSpaceVsNbCoeff(estim, dist_field, [0,5,10,15])\n\nplt.show()\n\n\n"
] |
[
[
"matplotlib.pyplot.imshow",
"numpy.fft.ifft2",
"matplotlib.pyplot.title",
"numpy.min",
"numpy.asarray",
"matplotlib.pyplot.xscale",
"numpy.fft.fftshift",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.subplot",
"numpy.fft.ifftshift",
"matplotlib.pyplot.xlabel",
"numpy.count_nonzero",
"matplotlib.pyplot.grid",
"numpy.load",
"matplotlib.pyplot.show",
"numpy.zeros",
"matplotlib.pyplot.figure"
]
] |
GusevMihail/dlcourse_ai
|
[
"7f20c625e09f92f20f2da9304abb1a4edd4ae93c"
] |
[
"assignments/assignment1/knn.py"
] |
[
"import numpy as np\n\n\nclass KNN:\n \"\"\"\n K-neariest-neighbor classifier using L1 loss\n \"\"\"\n\n def __init__(self, k=1):\n self.k = k\n\n def fit(self, X, y):\n self.train_X = X\n self.train_y = y\n\n def predict(self, X, num_loops=0):\n '''\n Uses the KNN model to predict clases for the data samples provided\n \n Arguments:\n X, np array (num_samples, num_features) - samples to run\n through the model\n num_loops, int - which implementation to use\n\n Returns:\n predictions, np array of ints (num_samples) - predicted class\n for each sample\n '''\n if num_loops == 0:\n dists = self.compute_distances_no_loops(X)\n elif num_loops == 1:\n dists = self.compute_distances_one_loop(X)\n else:\n dists = self.compute_distances_two_loops(X)\n\n if self.train_y.dtype == np.bool:\n return self.predict_labels_binary(dists)\n else:\n return self.predict_labels_multiclass(dists)\n\n def compute_distances_two_loops(self, X: np.ndarray):\n '''\n Computes L1 distance from every sample of X to every training sample\n Uses simplest implementation with 2 Python loops\n\n Arguments:\n X, np array (num_test_samples, num_features) - samples to run\n \n Returns:\n dists, np array (num_test_samples, num_train_samples) - array\n with distances between each test and each train sample\n '''\n num_train = self.train_X.shape[0]\n num_test = X.shape[0]\n dists = np.zeros((num_test, num_train), np.float32)\n for i_test in range(num_test):\n for i_train in range(num_train):\n dists[i_test, i_train] = np.sum(np.abs(X[i_test, :] - self.train_X[i_train, :]))\n return dists\n\n def compute_distances_one_loop(self, X):\n '''\n Computes L1 distance from every sample of X to every training sample\n Vectorizes some of the calculations, so only 1 loop is used\n\n Arguments:\n X, np array (num_test_samples, num_features) - samples to run\n \n Returns:\n dists, np array (num_test_samples, num_train_samples) - array\n with distances between each test and each train sample\n '''\n num_train = self.train_X.shape[0]\n num_test = X.shape[0]\n dists = np.zeros((num_test, num_train), np.float32)\n for i_test in range(num_test):\n dists[i_test, :] = np.sum(np.abs(X[i_test] - self.train_X), axis=1)\n return dists\n\n def compute_distances_no_loops(self, X):\n '''\n Computes L1 distance from every sample of X to every training sample\n Fully vectorizes the calculations using numpy\n\n Arguments:\n X, np array (num_test_samples, num_features) - samples to run\n \n Returns:\n dists, np array (num_test_samples, num_train_samples) - array\n with distances between each test and each train sample\n '''\n X_tests_ext = X[:, np.newaxis, :]\n X_train_ext = self.train_X[np.newaxis, :, :]\n dists = np.sum(np.abs(X_tests_ext - X_train_ext), axis=2)\n return dists\n\n def predict_labels_binary(self, dists):\n '''\n Returns model predictions for binary classification case\n \n Arguments:\n dists, np array (num_test_samples, num_train_samples) - array\n with distances between each test and each train sample\n\n Returns:\n pred, np array of bool (num_test_samples) - binary predictions \n for every test sample\n '''\n from collections import Counter\n\n num_test = dists.shape[0]\n pred = np.zeros(num_test, np.bool)\n arg_dist = np.argsort(dists)\n for i in range(num_test):\n # TODO: Implement choosing best class based on k\n # nearest training samples\n\n nearests = list(self.train_y[j] for j in arg_dist[i, 0:self.k])\n # print(nearests)\n # print(Counter(nearests).most_common())\n\n # print(Counter(nearests).most_common(1)[0][0])\n pred[i] = Counter(nearests).most_common(1)[0][0]\n\n # (values, counts) = np.unique(nearests, return_counts=True)\n # print(values[0])\n # ind = np.argmax(counts)\n # pred[i] = values[ind] == 9\n # print(values[ind])\n # print(Counter(pred))\n return pred\n\n def predict_labels_multiclass(self, dists):\n '''\n Returns model predictions for multi-class classification case\n \n Arguments:\n dists, np array (num_test_samples, num_train_samples) - array\n with distances between each test and each train sample\n\n Returns:\n pred, np array of int (num_test_samples) - predicted class index \n for every test sample\n '''\n num_test = dists.shape[0]\n pred = np.zeros(num_test, np.int)\n arg_dist = np.argsort(dists)\n for i in range(num_test):\n # TODO: Implement choosing best class based on k\n # nearest training samples\n # for j in arg_dist[i, :]:\n # nearests[j] =self.train_y[j]\n nearests = (self.train_y[j] for j in arg_dist[i, 0:self.k])\n from collections import Counter\n # print(f'{Counter(nearests).most_common(1)[0][0]}')\n pred[i] = Counter(nearests).most_common(1)[0][0]\n # (values, counts) = np.unique(nearests, return_counts=True)\n # ind = np.argmax(counts)\n # pred[i] = values[ind]\n return pred\n"
] |
[
[
"numpy.argsort",
"numpy.zeros",
"numpy.abs"
]
] |
rohitgirdhar/ActionVLAD
|
[
"08d3d65301940991e0a0cdca2c0534edf6749f41",
"08d3d65301940991e0a0cdca2c0534edf6749f41"
] |
[
"datasets/mnist.py",
"preprocessing/vgg_preprocessing.py"
] |
[
"# ------------------------------------------------------------------------------\n# ActionVLAD: Learning spatio-temporal aggregation for action classification\n# Copyright (c) 2017 Carnegie Mellon University and Adobe Systems Incorporated\n# Please see LICENSE on https://github.com/rohitgirdhar/ActionVLAD/ for details\n# ------------------------------------------------------------------------------\n# Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Provides data for the MNIST dataset.\n\nThe dataset scripts used to create the dataset can be found at:\ntensorflow/models/slim/data/create_mnist_dataset.py\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport tensorflow as tf\n\nfrom datasets import dataset_utils\n\nslim = tf.contrib.slim\n\n_FILE_PATTERN = 'mnist_%s.tfrecord'\n\n_SPLITS_TO_SIZES = {'train': 60000, 'test': 10000}\n\n_NUM_CLASSES = 10\n\n_ITEMS_TO_DESCRIPTIONS = {\n 'image': 'A [28 x 28 x 1] grayscale image.',\n 'label': 'A single integer between 0 and 9',\n}\n\n\ndef get_split(split_name, dataset_dir, file_pattern=None, reader=None):\n \"\"\"Gets a dataset tuple with instructions for reading MNIST.\n\n Args:\n split_name: A train/test split name.\n dataset_dir: The base directory of the dataset sources.\n file_pattern: The file pattern to use when matching the dataset sources.\n It is assumed that the pattern contains a '%s' string so that the split\n name can be inserted.\n reader: The TensorFlow reader type.\n\n Returns:\n A `Dataset` namedtuple.\n\n Raises:\n ValueError: if `split_name` is not a valid train/test split.\n \"\"\"\n if split_name not in _SPLITS_TO_SIZES:\n raise ValueError('split name %s was not recognized.' % split_name)\n\n if not file_pattern:\n file_pattern = _FILE_PATTERN\n file_pattern = os.path.join(dataset_dir, file_pattern % split_name)\n\n # Allowing None in the signature so that dataset_factory can use the default.\n if reader is None:\n reader = tf.TFRecordReader\n\n keys_to_features = {\n 'image/encoded': tf.FixedLenFeature((), tf.string, default_value=''),\n 'image/format': tf.FixedLenFeature((), tf.string, default_value='raw'),\n 'image/class/label': tf.FixedLenFeature(\n [1], tf.int64, default_value=tf.zeros([1], dtype=tf.int64)),\n }\n\n items_to_handlers = {\n 'image': slim.tfexample_decoder.Image(shape=[28, 28, 1], channels=1),\n 'label': slim.tfexample_decoder.Tensor('image/class/label', shape=[]),\n }\n\n decoder = slim.tfexample_decoder.TFExampleDecoder(\n keys_to_features, items_to_handlers)\n\n labels_to_names = None\n if dataset_utils.has_labels(dataset_dir):\n labels_to_names = dataset_utils.read_label_file(dataset_dir)\n\n return slim.dataset.Dataset(\n data_sources=file_pattern,\n reader=reader,\n decoder=decoder,\n num_samples=_SPLITS_TO_SIZES[split_name],\n num_classes=_NUM_CLASSES,\n items_to_descriptions=_ITEMS_TO_DESCRIPTIONS,\n labels_to_names=labels_to_names)\n",
"# ------------------------------------------------------------------------------\n# ActionVLAD: Learning spatio-temporal aggregation for action classification\n# Copyright (c) 2017 Carnegie Mellon University and Adobe Systems Incorporated\n# Please see LICENSE on https://github.com/rohitgirdhar/ActionVLAD/ for details\n# ------------------------------------------------------------------------------\n# Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Provides utilities to preprocess images.\n\nThe preprocessing steps for VGG were introduced in the following technical\nreport:\n\n Very Deep Convolutional Networks For Large-Scale Image Recognition\n Karen Simonyan and Andrew Zisserman\n arXiv technical report, 2015\n PDF: http://arxiv.org/pdf/1409.1556.pdf\n ILSVRC 2014 Slides: http://www.robots.ox.ac.uk/~karen/pdf/ILSVRC_2014.pdf\n CC-BY-4.0\n\nMore information can be obtained from the VGG website:\nwww.robots.ox.ac.uk/~vgg/research/very_deep/\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\n\nfrom tensorflow.python.ops import control_flow_ops\nfrom preprocessing.utils import _mean_image_subtraction\n\nslim = tf.contrib.slim\n\n_R_MEAN = 123.68\n_G_MEAN = 116.78\n_B_MEAN = 103.94\n\n_RESIZE_SIDE_MIN = 256\n_RESIZE_SIDE_MAX = 512\n\n\ndef _crop(image, offset_height, offset_width, crop_height, crop_width):\n \"\"\"Crops the given image using the provided offsets and sizes.\n\n Note that the method doesn't assume we know the input image size but it does\n assume we know the input image rank.\n\n Args:\n image: an image of shape [height, width, channels].\n offset_height: a scalar tensor indicating the height offset.\n offset_width: a scalar tensor indicating the width offset.\n crop_height: the height of the cropped image.\n crop_width: the width of the cropped image.\n\n Returns:\n the cropped (and resized) image.\n\n Raises:\n InvalidArgumentError: if the rank is not 3 or if the image dimensions are\n less than the crop size.\n \"\"\"\n original_shape = tf.shape(image)\n\n rank_assertion = tf.Assert(\n tf.equal(tf.rank(image), 3),\n ['Rank of image must be equal to 3.'])\n cropped_shape = control_flow_ops.with_dependencies(\n [rank_assertion],\n tf.pack([crop_height, crop_width, original_shape[2]]))\n\n size_assertion = tf.Assert(\n tf.logical_and(\n tf.greater_equal(original_shape[0], crop_height),\n tf.greater_equal(original_shape[1], crop_width)),\n ['Crop size greater than the image size.'])\n\n offsets = tf.to_int32(tf.pack([offset_height, offset_width, 0]))\n\n # Use tf.slice instead of crop_to_bounding box as it accepts tensors to\n # define the crop size.\n image = control_flow_ops.with_dependencies(\n [size_assertion],\n tf.slice(image, offsets, cropped_shape))\n return tf.reshape(image, cropped_shape)\n\n\ndef _random_crop(image_list, crop_height, crop_width):\n \"\"\"Crops the given list of images.\n\n The function applies the same crop to each image in the list. This can be\n effectively applied when there are multiple image inputs of the same\n dimension such as:\n\n image, depths, normals = _random_crop([image, depths, normals], 120, 150)\n\n Args:\n image_list: a list of image tensors of the same dimension but possibly\n varying channel.\n crop_height: the new height.\n crop_width: the new width.\n\n Returns:\n the image_list with cropped images.\n\n Raises:\n ValueError: if there are multiple image inputs provided with different size\n or the images are smaller than the crop dimensions.\n \"\"\"\n if not image_list:\n raise ValueError('Empty image_list.')\n\n # Compute the rank assertions.\n rank_assertions = []\n for i in range(len(image_list)):\n image_rank = tf.rank(image_list[i])\n rank_assert = tf.Assert(\n tf.equal(image_rank, 3),\n ['Wrong rank for tensor %s [expected] [actual]',\n image_list[i].name, 3, image_rank])\n rank_assertions.append(rank_assert)\n\n image_shape = control_flow_ops.with_dependencies(\n [rank_assertions[0]],\n tf.shape(image_list[0]))\n image_height = image_shape[0]\n image_width = image_shape[1]\n crop_size_assert = tf.Assert(\n tf.logical_and(\n tf.greater_equal(image_height, crop_height),\n tf.greater_equal(image_width, crop_width)),\n ['Crop size greater than the image size.'])\n\n asserts = [rank_assertions[0], crop_size_assert]\n\n for i in range(1, len(image_list)):\n image = image_list[i]\n asserts.append(rank_assertions[i])\n shape = control_flow_ops.with_dependencies([rank_assertions[i]],\n tf.shape(image))\n height = shape[0]\n width = shape[1]\n\n height_assert = tf.Assert(\n tf.equal(height, image_height),\n ['Wrong height for tensor %s [expected][actual]',\n image.name, height, image_height])\n width_assert = tf.Assert(\n tf.equal(width, image_width),\n ['Wrong width for tensor %s [expected][actual]',\n image.name, width, image_width])\n asserts.extend([height_assert, width_assert])\n\n # Create a random bounding box.\n #\n # Use tf.random_uniform and not numpy.random.rand as doing the former would\n # generate random numbers at graph eval time, unlike the latter which\n # generates random numbers at graph definition time.\n max_offset_height = control_flow_ops.with_dependencies(\n asserts, tf.reshape(image_height - crop_height + 1, []))\n max_offset_width = control_flow_ops.with_dependencies(\n asserts, tf.reshape(image_width - crop_width + 1, []))\n offset_height = tf.random_uniform(\n [], maxval=max_offset_height, dtype=tf.int32)\n offset_width = tf.random_uniform(\n [], maxval=max_offset_width, dtype=tf.int32)\n\n return [_crop(image, offset_height, offset_width,\n crop_height, crop_width) for image in image_list]\n\n\ndef _central_crop(image_list, crop_height, crop_width):\n \"\"\"Performs central crops of the given image list.\n\n Args:\n image_list: a list of image tensors of the same dimension but possibly\n varying channel.\n crop_height: the height of the image following the crop.\n crop_width: the width of the image following the crop.\n\n Returns:\n the list of cropped images.\n \"\"\"\n outputs = []\n for image in image_list:\n image_height = tf.shape(image)[0]\n image_width = tf.shape(image)[1]\n\n offset_height = (image_height - crop_height) / 2\n offset_width = (image_width - crop_width) / 2\n\n outputs.append(_crop(image, offset_height, offset_width,\n crop_height, crop_width))\n return outputs\n\n\ndef _smallest_size_at_least(height, width, smallest_side):\n \"\"\"Computes new shape with the smallest side equal to `smallest_side`.\n\n Computes new shape with the smallest side equal to `smallest_side` while\n preserving the original aspect ratio.\n\n Args:\n height: an int32 scalar tensor indicating the current height.\n width: an int32 scalar tensor indicating the current width.\n smallest_side: A python integer or scalar `Tensor` indicating the size of\n the smallest side after resize.\n\n Returns:\n new_height: an int32 scalar tensor indicating the new height.\n new_width: and int32 scalar tensor indicating the new width.\n \"\"\"\n smallest_side = tf.convert_to_tensor(smallest_side, dtype=tf.int32)\n\n height = tf.to_float(height)\n width = tf.to_float(width)\n smallest_side = tf.to_float(smallest_side)\n\n scale = tf.cond(tf.greater(height, width),\n lambda: smallest_side / width,\n lambda: smallest_side / height)\n new_height = tf.to_int32(height * scale)\n new_width = tf.to_int32(width * scale)\n return new_height, new_width\n\n\ndef _aspect_preserving_resize(image, smallest_side):\n \"\"\"Resize images preserving the original aspect ratio.\n\n Args:\n image: A 3-D image `Tensor`.\n smallest_side: A python integer or scalar `Tensor` indicating the size of\n the smallest side after resize.\n\n Returns:\n resized_image: A 3-D tensor containing the resized image.\n \"\"\"\n smallest_side = tf.convert_to_tensor(smallest_side, dtype=tf.int32)\n\n shape = tf.shape(image)\n height = shape[0]\n width = shape[1]\n new_height, new_width = _smallest_size_at_least(height, width, smallest_side)\n image = tf.expand_dims(image, 0)\n resized_image = tf.image.resize_bilinear(image, [new_height, new_width],\n align_corners=False)\n resized_image = tf.squeeze(resized_image)\n resized_image.set_shape([None, None, 3])\n return resized_image\n\n\ndef preprocess_for_train(image,\n output_height,\n output_width,\n resize_side_min=_RESIZE_SIDE_MIN,\n resize_side_max=_RESIZE_SIDE_MAX):\n \"\"\"Preprocesses the given image for training.\n\n Note that the actual resizing scale is sampled from\n [`resize_size_min`, `resize_size_max`].\n\n Args:\n image: A `Tensor` representing an image of arbitrary size.\n output_height: The height of the image after preprocessing.\n output_width: The width of the image after preprocessing.\n resize_side_min: The lower bound for the smallest side of the image for\n aspect-preserving resizing.\n resize_side_max: The upper bound for the smallest side of the image for\n aspect-preserving resizing.\n\n Returns:\n A preprocessed image.\n \"\"\"\n resize_side = tf.random_uniform(\n [], minval=resize_side_min, maxval=resize_side_max+1, dtype=tf.int32)\n\n image = _aspect_preserving_resize(image, resize_side)\n image = _random_crop([image], output_height, output_width)[0]\n image.set_shape([output_height, output_width, 3])\n image = tf.to_float(image)\n image = tf.image.random_flip_left_right(image)\n return _mean_image_subtraction(image, [_R_MEAN, _G_MEAN, _B_MEAN])\n\n\ndef preprocess_for_eval(image, output_height, output_width, resize_side):\n \"\"\"Preprocesses the given image for evaluation.\n\n Args:\n image: A `Tensor` representing an image of arbitrary size.\n output_height: The height of the image after preprocessing.\n output_width: The width of the image after preprocessing.\n resize_side: The smallest side of the image for aspect-preserving resizing.\n\n Returns:\n A preprocessed image.\n \"\"\"\n image = _aspect_preserving_resize(image, resize_side)\n image = _central_crop([image], output_height, output_width)[0]\n image.set_shape([output_height, output_width, 3])\n image = tf.to_float(image)\n return _mean_image_subtraction(image, [_R_MEAN, _G_MEAN, _B_MEAN])\n\n\ndef preprocess_image(image, output_height, output_width, is_training=False,\n resize_side_min=_RESIZE_SIDE_MIN,\n resize_side_max=_RESIZE_SIDE_MAX):\n \"\"\"Preprocesses the given image.\n\n Args:\n image: A `Tensor` representing an image of arbitrary size.\n output_height: The height of the image after preprocessing.\n output_width: The width of the image after preprocessing.\n is_training: `True` if we're preprocessing the image for training and\n `False` otherwise.\n resize_side_min: The lower bound for the smallest side of the image for\n aspect-preserving resizing. If `is_training` is `False`, then this value\n is used for rescaling.\n resize_side_max: The upper bound for the smallest side of the image for\n aspect-preserving resizing. If `is_training` is `False`, this value is\n ignored. Otherwise, the resize side is sampled from\n [resize_size_min, resize_size_max].\n\n Returns:\n A preprocessed image.\n \"\"\"\n if is_training:\n return preprocess_for_train(image, output_height, output_width,\n resize_side_min, resize_side_max)\n else:\n return preprocess_for_eval(image, output_height, output_width,\n resize_side_min)\n"
] |
[
[
"tensorflow.FixedLenFeature",
"tensorflow.zeros"
],
[
"tensorflow.convert_to_tensor",
"tensorflow.image.resize_bilinear",
"tensorflow.image.random_flip_left_right",
"tensorflow.shape",
"tensorflow.slice",
"tensorflow.greater",
"tensorflow.reshape",
"tensorflow.equal",
"tensorflow.expand_dims",
"tensorflow.squeeze",
"tensorflow.pack",
"tensorflow.to_float",
"tensorflow.rank",
"tensorflow.to_int32",
"tensorflow.greater_equal",
"tensorflow.random_uniform"
]
] |
doudoune144/openpilot
|
[
"25fbad410d51e48d9189d5b3ef8a05a6e75f037c"
] |
[
"selfdrive/controls/lib/longitudinal_planner.py"
] |
[
"#!/usr/bin/env python3\nimport math\nimport numpy as np\nfrom common.numpy_fast import interp\n\nimport cereal.messaging as messaging\nfrom common.conversions import Conversions as CV\nfrom common.filter_simple import FirstOrderFilter\nfrom common.realtime import DT_MDL\nfrom selfdrive.modeld.constants import T_IDXS\nfrom selfdrive.controls.lib.longcontrol import LongCtrlState\nfrom selfdrive.controls.lib.longitudinal_mpc_lib.long_mpc import LongitudinalMpc\nfrom selfdrive.controls.lib.longitudinal_mpc_lib.long_mpc import T_IDXS as T_IDXS_MPC\nfrom selfdrive.controls.lib.drive_helpers import V_CRUISE_MAX, CONTROL_N\nfrom selfdrive.swaglog import cloudlog\nfrom common.params import Params\n\nLON_MPC_STEP = 0.2 # first step is 0.2s\nAWARENESS_DECEL = -0.2 # car smoothly decel at .2m/s^2 when user is distracted\nA_CRUISE_MIN = -1.2\nA_CRUISE_MAX_VALS = [1.7, 1.3, 0.8, 0.6]\nA_CRUISE_MAX_BP = [0., 15., 25., 40.]\n\n# Lookup table for turns\n_A_TOTAL_MAX_V = [1.7, 3.2]\n_A_TOTAL_MAX_BP = [20., 40.]\n\n\ndef get_max_accel(v_ego):\n return interp(v_ego, A_CRUISE_MAX_BP, A_CRUISE_MAX_VALS)\n\n\ndef limit_accel_in_turns(v_ego, angle_steers, a_target, CP):\n \"\"\"\n This function returns a limited long acceleration allowed, depending on the existing lateral acceleration\n this should avoid accelerating when losing the target in turns\n \"\"\"\n\n a_total_max = interp(v_ego, _A_TOTAL_MAX_BP, _A_TOTAL_MAX_V)\n a_y = v_ego ** 2 * angle_steers * CV.DEG_TO_RAD / (CP.steerRatio * CP.wheelbase)\n a_x_allowed = math.sqrt(max(a_total_max ** 2 - a_y ** 2, 0.))\n\n return [a_target[0], min(a_target[1], a_x_allowed)]\n\n\nclass Planner:\n def __init__(self, CP, init_v=0.0, init_a=0.0):\n self.CP = CP\n self.mpc = LongitudinalMpc()\n\n self.fcw = False\n\n self.a_desired = init_a\n self.v_desired_filter = FirstOrderFilter(init_v, 2.0, DT_MDL)\n\n self.v_desired_trajectory = np.zeros(CONTROL_N)\n self.a_desired_trajectory = np.zeros(CONTROL_N)\n self.j_desired_trajectory = np.zeros(CONTROL_N)\n self.solverExecutionTime = 0.0\n\n self.use_cluster_speed = Params().get_bool('UseClusterSpeed')\n self.long_control_enabled = Params().get_bool('LongControlEnabled')\n\n def update(self, sm):\n v_ego = sm['carState'].vEgo\n\n v_cruise_kph = sm['controlsState'].vCruise\n v_cruise_kph = min(v_cruise_kph, V_CRUISE_MAX)\n v_cruise = v_cruise_kph * CV.KPH_TO_MS\n\n # neokii\n if not self.use_cluster_speed:\n vCluRatio = sm['carState'].vCluRatio\n if vCluRatio > 0.5:\n v_cruise *= vCluRatio\n v_cruise = int(v_cruise * CV.MS_TO_KPH + 0.25) * CV.KPH_TO_MS\n\n long_control_state = sm['controlsState'].longControlState\n force_slow_decel = sm['controlsState'].forceDecel\n\n # Reset current state when not engaged, or user is controlling the speed\n reset_state = long_control_state == LongCtrlState.off\n reset_state = reset_state or sm['carState'].gasPressed\n\n # No change cost when user is controlling the speed, or when standstill\n prev_accel_constraint = not (reset_state or sm['carState'].standstill)\n\n if reset_state:\n self.v_desired_filter.x = v_ego\n self.a_desired = 0.0\n\n # Prevent divergence, smooth in current v_ego\n self.v_desired_filter.x = max(0.0, self.v_desired_filter.update(v_ego))\n\n accel_limits = [A_CRUISE_MIN, get_max_accel(v_ego)]\n accel_limits_turns = limit_accel_in_turns(v_ego, sm['carState'].steeringAngleDeg, accel_limits, self.CP)\n if force_slow_decel:\n # if required so, force a smooth deceleration\n accel_limits_turns[1] = min(accel_limits_turns[1], AWARENESS_DECEL)\n accel_limits_turns[0] = min(accel_limits_turns[0], accel_limits_turns[1])\n # clip limits, cannot init MPC outside of bounds\n accel_limits_turns[0] = min(accel_limits_turns[0], self.a_desired + 0.05)\n accel_limits_turns[1] = max(accel_limits_turns[1], self.a_desired - 0.05)\n\n self.mpc.set_weights(prev_accel_constraint)\n self.mpc.set_accel_limits(accel_limits_turns[0], accel_limits_turns[1])\n self.mpc.set_cur_state(self.v_desired_filter.x, self.a_desired)\n self.mpc.update(sm['carState'], sm['radarState'], v_cruise)\n\n self.v_desired_trajectory = np.interp(T_IDXS[:CONTROL_N], T_IDXS_MPC, self.mpc.v_solution)\n self.a_desired_trajectory = np.interp(T_IDXS[:CONTROL_N], T_IDXS_MPC, self.mpc.a_solution)\n self.j_desired_trajectory = np.interp(T_IDXS[:CONTROL_N], T_IDXS_MPC[:-1], self.mpc.j_solution)\n\n # TODO counter is only needed because radar is glitchy, remove once radar is gone\n self.fcw = self.mpc.crash_cnt > 5\n if self.fcw:\n cloudlog.info(\"FCW triggered\")\n\n # Interpolate 0.05 seconds and save as starting point for next iteration\n a_prev = self.a_desired\n self.a_desired = float(interp(DT_MDL, T_IDXS[:CONTROL_N], self.a_desired_trajectory))\n self.v_desired_filter.x = self.v_desired_filter.x + DT_MDL * (self.a_desired + a_prev) / 2.0\n\n def publish(self, sm, pm):\n plan_send = messaging.new_message('longitudinalPlan')\n\n plan_send.valid = sm.all_alive_and_valid(service_list=['carState', 'controlsState'])\n\n longitudinalPlan = plan_send.longitudinalPlan\n longitudinalPlan.modelMonoTime = sm.logMonoTime['modelV2']\n longitudinalPlan.processingDelay = (plan_send.logMonoTime / 1e9) - sm.logMonoTime['modelV2']\n\n longitudinalPlan.speeds = self.v_desired_trajectory.tolist()\n longitudinalPlan.accels = self.a_desired_trajectory.tolist()\n longitudinalPlan.jerks = self.j_desired_trajectory.tolist()\n\n longitudinalPlan.hasLead = sm['radarState'].leadOne.status\n longitudinalPlan.longitudinalPlanSource = self.mpc.source\n longitudinalPlan.fcw = self.fcw\n\n longitudinalPlan.solverExecutionTime = self.mpc.solve_time\n\n pm.send('longitudinalPlan', plan_send)\n"
] |
[
[
"numpy.zeros",
"numpy.interp"
]
] |
Hser2bio/ViLight
|
[
"e8c4179d13178fe61796e8f9ae264e697d599664"
] |
[
"lib/plot.py"
] |
[
"from PyQt5.QtGui import *\nfrom .i18n import _\n\n\nimport datetime\nfrom collections import defaultdict\nfrom .bitcoin import COIN\n\nimport matplotlib\nmatplotlib.use('Qt5Agg')\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as md\nfrom matplotlib.patches import Ellipse\nfrom matplotlib.offsetbox import AnchoredOffsetbox, TextArea, DrawingArea, HPacker\n\n\ndef plot_history(wallet, history):\n hist_in = defaultdict(int)\n hist_out = defaultdict(int)\n for item in history:\n tx_hash, height, confirmations, timestamp, value, balance = item\n if not confirmations:\n continue\n if timestamp is None:\n continue\n value = value*1./COIN\n date = datetime.datetime.fromtimestamp(timestamp)\n datenum = int(md.date2num(datetime.date(date.year, date.month, 1)))\n if value > 0:\n hist_in[datenum] += value\n else:\n hist_out[datenum] -= value\n\n f, axarr = plt.subplots(2, sharex=True)\n plt.subplots_adjust(bottom=0.2)\n plt.xticks( rotation=25 )\n ax = plt.gca()\n plt.ylabel('VITAE')\n plt.xlabel('Month')\n xfmt = md.DateFormatter('%Y-%m-%d')\n ax.xaxis.set_major_formatter(xfmt)\n axarr[0].set_title('Monthly Volume')\n xfmt = md.DateFormatter('%Y-%m')\n ax.xaxis.set_major_formatter(xfmt)\n width = 20\n dates, values = zip(*sorted(hist_in.items()))\n r1 = axarr[0].bar(dates, values, width, label='incoming')\n axarr[0].legend(loc='upper left')\n dates, values = zip(*sorted(hist_out.items()))\n r2 = axarr[1].bar(dates, values, width, color='r', label='outgoing')\n axarr[1].legend(loc='upper left')\n return plt\n"
] |
[
[
"matplotlib.pyplot.gca",
"matplotlib.dates.DateFormatter",
"matplotlib.use",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.subplots_adjust",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.ylabel"
]
] |
raikonenfnu/mlir-npcomp
|
[
"29e1b2fe89848d58c9bc07e7df7ce651850a5244",
"29e1b2fe89848d58c9bc07e7df7ce651850a5244"
] |
[
"frontends/pytorch/test/ivalue_import/list.py",
"frontends/pytorch/python/torch_mlir_torchscript/e2e_test/framework.py"
] |
[
"# -*- Python -*-\n# This file is licensed under a pytorch-style license\n# See frontends/pytorch/LICENSE for license information.\n\nimport typing\n\nimport torch\nimport torch_mlir\n\n# RUN: %PYTHON %s | npcomp-opt | FileCheck %s\n\nmb = torch_mlir.ModuleBuilder()\n\nclass TestModule(torch.nn.Module):\n def __init__(self):\n super().__init__()\n self.l = [1, 2]\n# CHECK: torch.class_type @[[CLASSTYPE:.*]] {\n# CHECK: torch.attr \"l\" : !torch.list<!torch.int>\n# CHECK: }\n# CHECK: %[[N1:.*]] = torch.constant.int 1\n# CHECK: %[[N2:.*]] = torch.constant.int 2\n# CHECK: %[[LIST:.*]] = torch.prim.ListConstruct %[[N1]], %[[N2]] : (!torch.int, !torch.int) -> !torch.list<!torch.int>\n# CHECK: torch.nn_module {\n# CHECK: torch.slot \"l\", %[[LIST]] : !torch.list<!torch.int>\n# CHECK: } : !torch.nn.Module<\"[[CLASSTYPE]]\">\n\n\ntest_module = TestModule()\nrecursivescriptmodule = torch.jit.script(test_module)\n# TODO: Automatically handle unpacking Python class RecursiveScriptModule into the underlying ScriptModule.\nmb.import_module(recursivescriptmodule._c)\nmb.module.operation.print()\n",
"# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n# See https://llvm.org/LICENSE.txt for license information.\n# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n\"\"\"\n# End-to-end testing framework for TorchScript.\n\nFor the purposes of this framework, \"end to end\" means the first \"end\" is\na `torch.nn.Module`, and the second \"end\" is execution.\n\n## Architecture\n\nA program for this testing framework is considered to be a `torch.nn.Module`,\nwhich has a public interface consisting of its methods and instance attributes.\n\nA test in the framework consists conceputally of a list of calls into\nthe methods of a module (TODO: extend to instance attributes). It is expected\nthat the outputs match between the program run on a backend (controlled by\na TestConfig) and a golden trace obtained by running on native Torch (without\ncompiling or TorchScript'ing).\n\"\"\"\n\nimport abc\nfrom typing import Any, Callable, List, NamedTuple, Optional, TypeVar, Union, Dict\n\nimport io\nimport pickle\n\nimport torch\n\nfrom ..annotations import apply_serializable_annotations\n\n\nTorchScriptValue = Union[int, float, List['TorchScriptValue'],\n Dict['TorchScriptValue',\n 'TorchScriptValue'], torch.Tensor]\n\n\nclass TraceItem(NamedTuple):\n # The externally visible symbol name that is called.\n # For example `\"forward\"` or `\"submodule.forward\"`.\n symbol: str\n # The inputs to the call.\n inputs: List[TorchScriptValue]\n # The output from the call.\n # In Python, there is only one output from a function. It might be a tuple\n # in case of \"multiple results\".\n # Sometimes this field is treated as golden outputs from a test.\n # Sometimes this field is treated as ignored, such as the input trace\n # provided to `TestConfig.run`.\n output: TorchScriptValue\n\n\n# A trace of invocations to the program.\n# This is an ordered sequence of external invocations to a program's\n# public boundary.\nTrace = List[TraceItem]\n\n# A type shared between the result of `TestConfig.compile` and the input\n# to `TestConfig.run`. Each backend will likely have a different definition of\n# this type.\nCompiledArtifact = TypeVar('CompiledArtifact')\n\n\nclass TestConfig(abc.ABC):\n \"\"\"The interface implemented by backends to run tests.\n\n The testing framework expects to be able to call `compile` to compile\n a torch.nn.Module, and then pass the compiled artifact to `run` to run it.\n\n Note that the definition of \"compiled artifact\" here is quite loose, and\n this interface allows for many different use cases besides simple testing.\n\n For example, this interface can be overridden to be a \"data collector\"\n to gather information across all the test cases. For example,\n a compiler backend could override \"compile\" to just return some IR at a\n useful intermediate abstraction level (rather than the final compiled\n artifact), and then have \"run\" save this intermediate IR + the trace as\n input to some lower-level software stack's testing format.\n\n The set of TestConfig's is expected to be pluggable and provided by\n users to suit their own needs. We provide a few configs out of the box\n in the `configs` submodule of this package, but those are intended\n to be for basic inspiration and enough for our own testing.\n Backends to npcomp will likely have more elaborate TestConfig's, such\n as `compile` being \"compile for such-and-such DSP with these vectorization\n cost model flags\" and `run` being \"connect to Android phone with\n device ID 1234 and upload a program to run on it's DSP core, and also set\n power throttling settings to 'performance'\".\n\n That is also why this class is not called \"backend\", as it\n encapsulates potentially many specific details of the test configuration\n process as well. There isn't a general way to disentangle test configuration\n from the compile/run process specific to a logical backend, since each\n backend (compiler backend and runtime target) will have an arbitrarily\n wild and wonderful set of possible configurations that we cannot predict.\n \"\"\"\n # This is not a frontend-lowered module, to allow various testing at the PyTorch level.\n # We can have a helper class NpcompBackendTestConfig which does that.\n @abc.abstractmethod\n def compile(self, program: torch.nn.Module) -> CompiledArtifact:\n \"\"\"Compile the provided torch.nn.Module into a compiled artifact\"\"\"\n pass\n\n # Any should match result of `compile`.\n\n @abc.abstractmethod\n def run(self, artifact: CompiledArtifact, trace: Trace) -> Trace:\n \"\"\"Run the compiled artifact produced by `compile`.\n\n The backend should load the compiled artifact and call the\n symbol names listed in `trace` with their respective inputs (the outputs\n of `trace` should be ignored). A new identical trace with outputs\n populated should be returned.\n\n This method should assume that `artifact` is being shared with\n multiple parallel invocations of `run`, and so it should not be mutated.\n This property is typicaly trivially satisfied for a true\n \"compiled artifact\", but some backends don't directly involve a\n compiled artifact per se (like a backend for which `CompiledArtifact` is\n `torch.nn.Module` and `run` just invokes the torch.nn.Module itself)\n\n Args:\n artifact: a compiled artifact produced by `compile`.\n trace: The external invocations to stimulate the module.\n Returns:\n A trace with outputs recorded according to the results of running\n on this backend.\n \"\"\"\n pass\n\n\n# Utilities for common testing trace generation.\n# Also, resets the random seed for reproducibility.\n# TODO: If generating in parallel, how to have manual_seed be local?\nclass TestUtils:\n \"\"\"Utilities for executing a test.\n\n Test cases are provided an instance of this class to make test cases\n more succinct.\n\n For reproducibility, this class also resets the random seed.\n TODO: Figure out how to seed reset properly scoped to just a test case\n (such as when running tests in parallel)\n \"\"\"\n def __init__(self):\n torch.manual_seed(0)\n\n # TODO: Add zeros/ones/etc. as convenient.\n def rand(self, *sizes):\n if len(sizes) == 0:\n return torch.rand([])\n return torch.rand(*sizes)\n\n\nclass Test(NamedTuple):\n \"\"\"A description of a test as produced by the test frontend.\n \"\"\"\n # Stable name for error reporting.\n #\n # This name's stability is also useful for backend, which want to\n # generate their own lower-level test suites based on this framework.\n #\n # It is expected that those backends will need additional\n # metadata to describe their test configurations, so having a unique\n # key to keep that information associated is important.\n unique_name: str\n # A callable which produces the module under test.\n # This is a callable to allow lazily creating the module.\n program_factory: Callable[[], torch.nn.Module]\n # A callable which provides external stimuli to the module.\n # The first parameter is a torch.nn.Module (or a `_Tracer` wrapping that\n # module, actually).\n # The secon parameter is a `TestUtils` instance for convenience.\n program_invoker: Callable[[Any, TestUtils], None]\n\n\nclass SerializableTest(NamedTuple):\n \"\"\"A self-contained representation of a test that can be pickled.\n\n We use serialized TorchScript programs here for two reasons:\n 1. The PyTorch pickling story isn't great, so in order to reliably pickle\n this class, we rely on having the serialized bytes for the TorchScript\n module already given to us.\n 2. The choice of a TorchScript module vs `torch.nn.Module` boils down to\n the fact that `torch.nn.Module` cannot be deserialized without pulling\n in the same set of Python dependencies that were used to serialize it\n in the first place. This would defeat one of the\n main use cases of this class, which is to transport a test from an\n environment with a set of heavy dependencies to a dependency-light one.\n Since TorchScript modules are self-contained, they fit the bill\n perfectly.\n \"\"\"\n # See unique_name on `Test`.\n unique_name: str\n # Serialized TorchScript program.\n program: bytes\n # Trace for execution testing.\n trace: Trace\n\n def as_test(self) -> Test:\n \"\"\"Create a `Test` from this class.\"\"\"\n # Conform the serialized program to the interface expected by Test.\n # This is a bit of a hack, but it's the only way to keep the layering\n # straight.\n def factory():\n _extra_files = {\"annotations.pkl\": \"\"}\n module = torch.jit.load(io.BytesIO(self.program),\n _extra_files=_extra_files)\n # Load the pickled annotations.\n annotations = pickle.loads(_extra_files[\"annotations.pkl\"])\n apply_serializable_annotations(module, annotations)\n return module\n\n def invoker(module, tu):\n for item in self.trace:\n attr = module\n for part in item.symbol.split(\".\"):\n attr = getattr(attr, part)\n attr(*item.inputs)\n\n return Test(\n unique_name=self.unique_name,\n program_factory=factory,\n program_invoker=invoker,\n )\n\n\nclass TestResult(NamedTuple):\n # Stable unique name for error reporting and test suite configuration.\n #\n # Tests frequently need some additional data (such as expected pass/fail\n # status, desired test configurations, etc.), and this gives a key to\n # associate to. This avoids extending this class arbitrarily for every\n # possible requirement from the test framework.\n #\n # This name is also useful for backends that are generating their own\n # lower-level test suites from this framework for the same reasons, though\n # those reasons are stronger because we cannot simply extend this\n # class.\n unique_name: str # Should match Test.unique_name for corresponding test.\n # If compilation failed, a string describing the failure.\n # If this is not None, then the `trace` and `golden_trace` fields are None,\n # and vice-versa.\n compilation_error: Optional[str]\n # The trace produced by the backend.\n trace: Optional[Trace]\n # The golden trace which `trace` is expected to match.\n golden_trace: Optional[Trace]\n\n\nclass _Tracer:\n \"\"\"Wrapper around a `torch.nn.Module` that records calls into it.\n\n The inputs and outputs of each call are recorded in a Trace. Recursive\n property accesses are also traced.\n \"\"\"\n def __init__(self, wrapped, property_base_path: List[str], trace: Trace):\n self.__wrapped__ = wrapped\n self.__trace__ = trace\n self.__property_base_path__ = property_base_path\n\n def __call__(self, *args, **kwargs):\n output = self.__wrapped__(*args, **kwargs)\n self.__trace__.append(\n TraceItem(symbol=\".\".join(self.__property_base_path__),\n inputs=args,\n output=output))\n return output\n\n def __getattr__(self, name):\n return _Tracer(getattr(self.__wrapped__, name),\n self.__property_base_path__ + [name], self.__trace__)\n\n\ndef generate_golden_trace(test: Test) -> Trace:\n \"\"\"Generate a trace with the original program.\n\n If the original program is deterministic, then this the produced trace is\n suitable as a golden trace to compare against.\n \"\"\"\n trace = []\n tracer = _Tracer(test.program_factory(), [], trace)\n test.program_invoker(tracer, TestUtils())\n return trace\n\n\ndef run_tests(tests: List[Test], config: TestConfig) -> List[TestResult]:\n \"\"\"Invoke the given `Test`'s with the provided `TestConfig`.\"\"\"\n results = []\n for test in tests:\n # TODO: Precompile everything in parallel.\n try:\n golden_trace = generate_golden_trace(test)\n compiled = config.compile(test.program_factory())\n except Exception as e:\n # Useful for debugging:\n # ```\n # raise\n # ```\n # This will give the full traceback rather than giving just\n # the stringified exception in the report.\n # TODO: Capture the traceback and make it available in the report.\n results.append(\n TestResult(unique_name=test.unique_name,\n compilation_error=str(e),\n trace=None,\n golden_trace=None))\n continue\n # TODO: Run in parallel.\n trace = config.run(compiled, golden_trace)\n results.append(\n TestResult(unique_name=test.unique_name,\n compilation_error=None,\n trace=trace,\n golden_trace=golden_trace))\n return results\n"
] |
[
[
"torch.jit.script"
],
[
"torch.manual_seed",
"torch.rand"
]
] |
austinmroczek/pauser
|
[
"4e81808be98d3495ad93c3270a8a43584b62b8cd"
] |
[
"listener.py"
] |
[
"#import unicodedata\n\nclass Listener:\n\n def __init__(self):\n import log\n self.myLog = log.Log('listener.log')\n\n # files and paths\n self.fileName = 'rectest.wav' # default file name\n\n import os\n if not os.path.isfile(self.fileName):\n file = open(self.fileName,'w')\n file.write(\"\")\n file.close() \n \n \n \n self.teachPath = 'recordings/'\n\n # check that teachPath folder exists and create it if necessary\n import os\n if not os.path.isdir(self.teachPath):\n os.makedirs(self.teachPath) \n\n # audio data \n self.max_freq = 11025 \n self.fs = 0\n self.numSamples = 0\n self.bitsPerSample = 16 # number of bits per sample in the file...assumed to be 16\n self.rawData = [] # raw data from wave file\n self.normalizedData = [] # wave file data normalized on -1 to 1\n self.normalizedDataDB = [] # normalized data coverted to decibels\n\n # FFT data\n self.fftData = []\n self.fftDataABS = []\n self.fftNumUsefulBins = 11026 # set when FFT performed or when FFT data read from file\n self.fftBinSize = 0.0\n\n # A-weight data\n self.fftDataAweight = []\n self.normalized_aWeight = []\n self.statsRMSdB_A = 0.0\n\n\n\n #stats\n self.statsMaxAmplitudeDB = 0.0\n self.statsRMSdB = 0.0\n self.statsCorrelation = 0.0\n\n def audioCapture(self):\n # captures audio into a file\n # from http://www.g7smy.co.uk/?p=283\n\n #SAVEFILE='rectest.wav'\n #DURATION='1'\n #RATE='22050'\n #FORMAT='S16_LE' # see manual for arecord\n #CHANNELS='1'\n\n from subprocess import call\n # this function won't work in python 3.5\n call('/usr/bin/arecord -D plughw:1 -f S16_LE -c1 -r22050 --duration=1 ' + self.fileName + ' > /dev/null 2>&1', shell=True)\n\n def saveFFT(self, newFile, myFFT):\n # save FFT data to a file\n file = open(newFile,'w') # open the file in write mode\n \n # only save useful data\n for x in range(self.fftNumUsefulBins):\n file.write(str(abs(myFFT[x])) + '\\n')\n \n file.close() # be nice and close out the file\n\n def getAudioData(self, audioFile=\"\"):\n # get audio data out of the file\n if audioFile==\"\":\n audioFile = self.fileName\n \n from scipy.io import wavfile \n\n import os\n if not os.path.isfile(audioFile):\n self.myLog.add(\"ERROR: audioFile does not exist\")\n exit()\n \n # https://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.io.wavfile.read.html\n self.fs, self.rawData = wavfile.read(audioFile) # load the data\n\n # from http://samcarcagno.altervista.org/blog/basic-sound-processing-python/\n if self.rawData.dtype == \"int16\":\n self.bitsPerSample = 16\n elif self.rawData.dtype == \"int32\":\n self.bitsPerSample = 32\n else: # unknown....we asked for 16 so assume it...but log an error\n self.bitsPerSample = 16\n self.myLog.add(\"WARNING in getAudioData(): unknown number of bits per sample: \" + self.rawData.dtype + \" continuing with 16 bits\")\n\n self.numSamples=len(self.rawData)\n \n self.normalizeData()\n \n def normalizeData(self): # normalize audio data \n # normalize wave data between -1 and 1\n \n normalizeFactor = 2**(self.bitsPerSample-1)\n\n self.normalizedData = []\n self.normalizedDataDB = []\n \n #self.normalizedData=[x/normalizeFactor for x in self.rawData] \n for x in self.rawData:\n self.normalizedData.append(x/normalizeFactor)\n self.normalizedDataDB.append(self.calculateDecibels(abs(x/normalizeFactor)))\n\n def getFFTData(self, filename):\n \n # read data from a file\n data = []\n file = open(filename,'r')\n # TODO: file error checks\n\n\n for line in file:\n data.append(float(line))\n file.close()\n return data\n\n def printStats(self): #print stats about data\n #print('Sample freq: ' + str(self.fs) + ' Hz')\n #print('FFT # useful bins: ' + str(self.fftNumUsefulBins))\n #print('FFT bin size: ' + str(self.fftBinSize) + ' Hz/bin')\n #print('Correlation data points: ' + str(len(self.correlationData)))\n #print('Max Amplitude: ' + str(round(self.statsMaxAmplitudeDB,1)) + ' dB\\tRMS: ' + str(round(self.statsRMSdB,1)) + ' dB\\tRMS: ' + str(round(self.statsRMSdB_A,1)) + ' dB(A)')\n print('Max Amplitude: ' + str(round(self.statsMaxAmplitudeDB,1)) + ' dB\\tRMS: ' + str(round(self.statsRMSdB,1)) + ' dB')\n def doFFT(self):\n # from https://stackoverflow.com/questions/23377665/python-scipy-fft-wav-files\n from scipy.fftpack import rfft\n self.fftData = rfft(self.normalizedData) # calculate real FFT\n\n self.setFFTnumUsefulBins()\n self.setFFTbinSize()\n \n self.calculateFFTABS()\n\n def calculateFFTABS(self):\n # use absolute value of data because only care about amplitude\n self.fftDataABS = [abs(x) for x in self.fftData] \n\n def setFFTnumUsefulBins(self):\n if self.numSamples == 0:\n self.myLog.add(\"ERROR in setFFTnumUsefulBins(): numSamples == 0 --> about to divide by zero\")\n exit()\n \n # from https://docs.scipy.org/doc/scipy/reference/tutorial/fftpack.html#one-dimensional-discrete-fourier-transforms\n if self.numSamples % 2 == 0: # even number of samples\n # n/2 + 1 \n # item [0] is the zero-frequency term\n # item [1]....[n/2] are the positive frequency terms\n self.fftNumUsefulBins = int((self.numSamples / 2)) + 1\n\n else: # odd number of samples\n #...which is odd because we should have an even number\n #...because the audio sample rates are even\n #...and the number of seconds to record using 'arecord' is an integer\n # TODO: can probaby do error checking...but not expecting to get here\n self.myLog.add(\"ERROR in doFFT(): odd number of audio samples\")\n exit()\n \n def setFFTbinSize(self):\n if self.fftNumUsefulBins == 0: # don't divide by zero\n self.fftBinSize = 0\n else:\n self.fftBinSize = float(self.fs/2)/self.fftNumUsefulBins # max frequency found is Fs/2 divided by number of real bins\n\n \n def calculateAweight(self): # calculate A-weight of current FFT\n \n # TODO: make sure this is even correct...probably NOT\n \n \n \n # lookup aWeight for each frequency bin from FFT data\n # https://stackoverflow.com/questions/4364823/how-do-i-obtain-the-frequencies-of-each-value-in-an-fft\n data = []\n\n \n for binNum in range(0,int(self.fftNumUsefulBins/2)):\n data.append(self.aWeightLookup(binNum*self.fftBinSize) * self.fftData[binNum])\n \n self.fftDataAweight = data\n \n \n # do inverse transform to get aWeight wave data\n from scipy.fftpack import irfft\n self.normalized_aWeight = irfft(self.fftDataAweight)\n # do RMS on data to get dB(A)\n \n self.statsRMSdB_A = self.calculateRMS(self.normalized_aWeight) \n \n pass\n\n def aWeightLookup(self,frequency): # look up A-weight for a frequency and return the coefficient to multiply by\n \n # http://www.diracdelta.co.uk/science/source/a/w/aweighting/source.html\n coefficient = 1.0 # placeholder until we know the forumula\n\n if frequency > 0:\n \n f2 = frequency ** 2\n f4 = frequency ** 4\n \n from math import log10\n \n# a = 10*log10(1.562339*f4/((f2 + 11589.0930520225)*(f2 + 544440.6704605728)))\n# b = 10*log10(2.242881e+16*f4/((f2 + 424.31867740600904)*(f2 + 148699001.40839997)))\n\n # skip the log10() because we're not in dB yet\n# a = (1.562339*f4/((f2 + 11589.0930520225)*(f2 + 544440.6704605728)))\n# b = (2.242881e+16*f4/((f2 + 424.31867740600904)*(f2 + 148699001.40839997)))\n\n a = (1.562339*f4)/(((f2 + 11589.0930520225)*(f2 + 544440.6704605728)))\n b = (2.242881e+16*f4/((f2 + 424.31867740600904)*(f2 + 148699001.40839997)))\n\n\n\n# print(\"Freq: \" + str(frequency) + '\\tA-factor: ' + str(a+b))\n# print(\"Freq: \" + str(frequency) + '\\tA-factor db: ' + str(self.calculateDecibels(a)+self.calculateDecibels(b)))\n \n return (a + b) \n \n else:\n return -1E+32\n \n def calculateStats(self): # calculate stats about the wave file\n\n maxDB=-100.0\n for x in self.normalizedDataDB:\n if x>maxDB:\n maxDB = x\n self.statsMaxAmplitudeDB = maxDB\n \n self.statsRMSdB = self.calculateDecibels(self.calculateRMS(self.normalizedData))\n \n# self.calculateAweight()\n\n def calculateRMS(self,data):\n # https://stackoverflow.com/questions/5613244/root-mean-square-in-numpy\n from numpy import mean, sqrt, square\n return sqrt(mean(square(data)))\n\n def calculateDecibels(self,ratio):\n from math import log10 \n if ratio==0:\n self.myLog.add(\"MATH ERROR: log10(zero) in calculateDecibels() \")\n return -100.0\n else:\n # TODO: age old question ....10 or 20 x log10(ratio)\n # think it's 20 times\n return 20 * log10(ratio) \n \n9"
] |
[
[
"numpy.square",
"scipy.fftpack.irfft",
"scipy.io.wavfile.read",
"scipy.fftpack.rfft"
]
] |
hydrogo/FIT_ML
|
[
"4c3f4abd707baf9eb83e061f84d183630264c96b"
] |
[
"code/examples/scripts/21_ML_glacier_wise_weekly_jjas.py"
] |
[
"import numpy as np\nimport pandas as pd\n\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import LeaveOneOut\nfrom sklearn.metrics import r2_score\n\nimport pickle\n\n\nglacier_ids = np.load(\"../results/misc/glacier_ids_valid.npy\")\n\n\ntsl_path = \"../results/tsl_csv/\"\nmeteo_path = \"../data/FIT_forcing/meteo/\"\n\n\ndef read_tsl(rgi_id, path=tsl_path):\n \n tsl = pd.read_csv(f\"{tsl_path}{rgi_id}.csv\", index_col=0, parse_dates=True)\n \n return tsl\n\n\ndef read_meteo(rgi_id, path=meteo_path):\n \n meteo = pd.read_hdf(f\"{meteo_path}{rgi_id}.h5\")\n \n return meteo\n\n\ndef create_features(dataframe, back_to=12):\n \n # convert circular wind_dir_mean \n # to two components of cos() and sin()\n # source: https://stats.stackexchange.com/questions/336613/\n # regression-using-circular-variable-hour-from-023-as-predictor\n \n # copy for safety\n df = dataframe.copy()\n \n # create cos() and sin() components\n df[\"wind_dir_mean_cos\"] = np.cos(np.deg2rad(df[\"wind_dir_mean\"]))\n df[\"wind_dir_mean_sin\"] = np.sin(np.deg2rad(df[\"wind_dir_mean\"]))\n \n # drop \"wind_dir_mean\"\n df = df.drop([\"wind_dir_mean\"], axis=1)\n \n # make shifts and rolling means\n cols = df.columns\n for col in cols:\n for shift in range(1, back_to+1, 1):\n df[\"{}-{}\".format(col, shift)] = df[col].shift(shift).values\n for rol in range(1, back_to+1, 1):\n df[\"{}rol-{}\".format(col, rol)] = df[col].rolling(window=rol).mean().values\n \n # delete NaNs\n df = df.dropna()\n \n return df\n\n\ndef datasets_construction(rgi_id, freq, subset_jjas):\n \n # get raw TSL measurements\n tsl = read_tsl(rgi_id)\n \n # resample to specific frequency\n tsl_resample = tsl.resample(freq).mean()\n \n # get raw ERA5-Land forcing\n meteo = read_meteo(rgi_id)\n \n # resample to specific frequency\n meteo_resample = pd.DataFrame({'t2m_min': meteo['t2m_min'].resample(freq).min(), \n 't2m_max': meteo['t2m_max'].resample(freq).max(), \n 't2m_mean': meteo['t2m_mean'].resample(freq).mean(), \n 'tp': meteo['tp'].resample(freq).sum(), \n 'sf': meteo['sf'].resample(freq).sum(),\n 'ssrd': meteo['ssrd'].resample(freq).sum(), \n 'strd': meteo['strd_mean'].resample(freq).sum(),\n 'wind_max': meteo['wind_max'].resample(freq).max(), \n 'wind_mean': meteo['wind_mean'].resample(freq).mean(), \n 'wind_dir_mean': meteo['wind_dir_mean'].resample(freq).mean(),\n 'tcc': meteo['tcc'].resample(freq).mean()})\n \n # enrich meteo features\n if freq == \"M\":\n meteo_enrich = create_features(meteo_resample, back_to=12)\n elif freq == \"W\":\n meteo_enrich = create_features(meteo_resample, back_to=48) #12 months back considering 4 weeks in each month\n \n \n # meteo for the entire period\n # for model evaluation\n meteo_full = meteo_enrich.dropna()\n \n # merge datasets\n dataset = pd.concat([tsl_resample, meteo_enrich], axis=1)\n \n # drop NaNs\n dataset = dataset.dropna()\n \n if subset_jjas:\n dataset = dataset[(dataset.index.month == 6) | (dataset.index.month == 7) | \n (dataset.index.month == 8) | (dataset.index.month == 9)]\n \n return dataset, meteo_full\n\n\ndef tiny_prep(df):\n \n df_X = df.drop([\"TSL_normalized\"], axis=1)\n df_y = df[\"TSL_normalized\"]\n \n return df_X, df_y\n\n\ndef calculate_importances(imp_instance):\n \n cols = imp_instance.columns.tolist()\n \n # temperature-based\n t2m_min_cols = [i for i in cols if \"t2m_min\" in i]\n t2m_max_cols = [i for i in cols if \"t2m_max\" in i]\n t2m_mean_cols = [i for i in cols if \"t2m_mean\" in i]\n \n # precipitation-based\n tp_cols = [i for i in cols if \"tp\" in i]\n sf_cols = [i for i in cols if \"sf\" in i]\n \n # surface solar radiation downwards\n ssrd_cols = [i for i in cols if \"ssrd\" in i]\n \n # surface thermal radiation downwards\n strd_cols = [i for i in cols if \"strd\" in i]\n \n # wind-based\n wind_max_cols = [i for i in cols if \"wind_max\" in i]\n wind_mean_cols = [i for i in cols if \"wind_mean\" in i]\n wind_dir_mean_cols = [i for i in cols if \"wind_dir_mean\" in i]\n \n # total cloud cover\n tcc_cols = [i for i in cols if \"tcc\" in i]\n \n var_importances = []\n \n for var in [t2m_min_cols, \n t2m_max_cols, \n t2m_mean_cols, \n tp_cols, \n sf_cols,\n ssrd_cols, \n strd_cols, \n wind_max_cols, \n wind_mean_cols, \n wind_dir_mean_cols,\n tcc_cols]:\n \n var_importances.append(imp_instance[var].sum(axis=0).sum())\n \n var_importances = np.array(var_importances)\n \n var_importances = var_importances / var_importances.sum()\n \n return var_importances\n\n\ndef ML_me(rgi_id, freq, subset_jjas):\n \n # data: features and target\n df, meteo_full = datasets_construction(rgi_id, freq, subset_jjas)\n \n features_df, target_df = tiny_prep(df)\n features, target = features_df.values, target_df.values \n \n # model: RandomForest for regression\n # parsimonious model with low complexity\n # n_estimators is better to be multiple of available CPU threads\n # 8 for monthly, 40 for weekly temporal resolution\n model = RandomForestRegressor(random_state=76, n_estimators=8, n_jobs=-1)\n \n # holders for each step predictions/observations\n obs = []\n prd = []\n \n # leave-one-out cross-validation\n loo = LeaveOneOut()\n \n # predictions for whole interval\n full_preds = []\n \n # feature importances holder\n importances = []\n \n # misc prefixes\n if freq == \"M\":\n freq_prefix = \"monthly\"\n elif freq == \"W\":\n freq_prefix = \"weekly\"\n \n if subset_jjas:\n subset_prefix = \"JJAS\"\n else:\n subset_prefix = \"full\"\n \n # training loop\n for train, test in loo.split(target): \n \n # split data on train/test\n X_train, y_train, X_test, y_test = features[train], target[train], features[test], target[test]\n \n # fir data on train\n model.fit(X_train, y_train)\n \n # calculate test prediction\n y_pred = model.predict(X_test)\n \n # calculate prediction for the entire dataset\n full_pred = model.predict(meteo_full.values)\n \n # add test and predicted values to holders\n obs.append(y_test[0])\n prd.append(y_pred[0])\n full_preds.append(full_pred)\n \n # fit eli5 to calculate permutation imporatnces\n #pi = PermutationImportance(estimator=model, cv=\"prefit\", n_iter=1).fit(X_train, y_train)\n \n # get feature importances from eli5\n #fi = pi.feature_importances_\n \n # get feature importances from native model\n fi = model.feature_importances_\n \n # convert importances to dataframe\n fi_df = pd.DataFrame({0: fi}, index=features_df.columns).T\n \n # collect\n importances.append(fi_df)\n \n # save model instance\n #pickle.dump(model, open(f\"../results/tsl_ML/{freq_prefix}_{subset_prefix}/trained_models/{rgi_id}_{test}.pkl\", 'wb'))\n \n \n # grab predictions together\n obs = np.array(obs)\n prd = np.array(prd)\n \n # calculate r2 LOO score\n loo_score = r2_score(obs, prd)\n \n # grab loo obs and preds together\n loo_sim = pd.DataFrame({\"obs\": obs, \"sim\": prd}, index=features_df.index)\n # save loo predicitions\n loo_sim.to_csv(f\"../results/tsl_ML/{freq_prefix}_{subset_prefix}/tsl_simulated/{rgi_id}_loo.csv\", \n compression=\"gzip\")\n \n # postprocessing of entire predictions\n full_preds = np.array(full_preds).reshape(len(target), -1)\n ensemble_mean = full_preds.mean(axis=0)\n tsl_for_meteo_full = pd.DataFrame({\"TSL_sim\": ensemble_mean}, index=meteo_full.index)\n # save ensemble mean for the entire meteo ts\n tsl_for_meteo_full.to_csv(f\"../results/tsl_ML/{freq_prefix}_{subset_prefix}/tsl_simulated/{rgi_id}_ens.csv\", \n compression=\"gzip\")\n \n # get importances together\n all_importances = pd.concat(importances, axis=0, ignore_index=True)\n \n # calculate relative importances\n rel_importances = calculate_importances(all_importances)\n \n #return loo_sim, loo_score, rel_importances, tsl_for_meteo_full\n return loo_score, rel_importances\n\n\nlist_loo_scores = []\nlist_importances = []\n\nbroken = []\n\nfor num, idx in enumerate(glacier_ids):\n \n try:\n individual_loo_score, individual_importances = ML_me(idx, \"W\", True)\n \n except:\n print(idx, \"Warning\")\n broken.append(idx)\n \n list_loo_scores.append(individual_loo_score)\n list_importances.append(individual_importances)\n \n print(num, \n idx, \n np.round(individual_loo_score, 2), \n np.argmax(individual_importances))\n\n\nscores_loo_arr = np.array(list_loo_scores)\nimportances_arr = np.array(list_importances)\n\n\nres = pd.DataFrame({\"id\": glacier_ids, \n \"t2m_min\": importances_arr[:, 0], \n 't2m_max': importances_arr[:, 1],\n 't2m_mean': importances_arr[:, 2],\n 'tp': importances_arr[:, 3], \n 'sf': importances_arr[:, 4],\n 'ssrd': importances_arr[:, 5],\n 'strd': importances_arr[:, 6],\n 'wind_max': importances_arr[:, 7],\n 'wind_mean':importances_arr[:, 8], \n \"wind_dir_mean\": importances_arr[:, 9],\n 'tcc': importances_arr[:, 10],\n \"score_loo\":scores_loo_arr})\n\n\nprint(res.describe())\n\ntry:\n res.to_csv(\"../results/tsl_ML/weekly_JJAS/misc/weekly_jjas_drivers.csv\")\nexcept:\n res.to_csv(\"weekly_jjas_drivers.csv\")\n"
] |
[
[
"sklearn.ensemble.RandomForestRegressor",
"pandas.read_hdf",
"pandas.read_csv",
"pandas.concat",
"sklearn.metrics.r2_score",
"sklearn.model_selection.LeaveOneOut",
"pandas.DataFrame",
"numpy.round",
"numpy.deg2rad",
"numpy.argmax",
"numpy.load",
"numpy.array"
]
] |
rousik/pudl
|
[
"52db209ff83d1b2c8ef0f93d599a844f12a715ef"
] |
[
"src/pudl/output/eia860.py"
] |
[
"\"\"\"Functions for pulling data primarily from the EIA's Form 860.\"\"\"\n\n# import datetime\n\nimport pandas as pd\nimport sqlalchemy as sa\n\nimport pudl\n\n\ndef utilities_eia860(pudl_engine, start_date=None, end_date=None):\n \"\"\"Pull all fields from the EIA860 Utilities table.\n\n Args:\n pudl_engine (sqlalchemy.engine.Engine): SQLAlchemy connection engine\n for the PUDL DB.\n start_date (date-like): date-like object, including a string of the\n form 'YYYY-MM-DD' which will be used to specify the date range of\n records to be pulled. Dates are inclusive.\n end_date (date-like): date-like object, including a string of the\n form 'YYYY-MM-DD' which will be used to specify the date range of\n records to be pulled. Dates are inclusive.\n\n Returns:\n pandas.DataFrame: A DataFrame containing all the fields of the EIA 860\n Utilities table.\n\n \"\"\"\n pt = pudl.output.pudltabl.get_table_meta(pudl_engine)\n # grab the entity table\n utils_eia_tbl = pt['utilities_entity_eia']\n utils_eia_select = sa.sql.select([utils_eia_tbl])\n utils_eia_df = pd.read_sql(utils_eia_select, pudl_engine)\n\n # grab the annual eia entity table\n utils_eia860_tbl = pt['utilities_eia860']\n utils_eia860_select = sa.sql.select([utils_eia860_tbl])\n\n if start_date is not None:\n start_date = pd.to_datetime(start_date)\n utils_eia860_select = utils_eia860_select.where(\n utils_eia860_tbl.c.report_date >= start_date\n )\n if end_date is not None:\n end_date = pd.to_datetime(end_date)\n utils_eia860_select = utils_eia860_select.where(\n utils_eia860_tbl.c.report_date <= end_date\n )\n utils_eia860_df = pd.read_sql(utils_eia860_select, pudl_engine)\n\n # grab the glue table for the utility_id_pudl\n utils_g_eia_tbl = pt['utilities_eia']\n utils_g_eia_select = sa.sql.select([\n utils_g_eia_tbl.c.utility_id_eia,\n utils_g_eia_tbl.c.utility_id_pudl,\n ])\n utils_g_eia_df = pd.read_sql(utils_g_eia_select, pudl_engine)\n\n out_df = pd.merge(utils_eia_df, utils_eia860_df,\n how='left', on=['utility_id_eia'])\n out_df = pd.merge(out_df, utils_g_eia_df,\n how='left', on=['utility_id_eia'])\n out_df = (\n out_df.assign(report_date=lambda x: pd.to_datetime(x.report_date))\n .dropna(subset=[\"report_date\", \"utility_id_eia\"])\n .astype({\"utility_id_pudl\": \"Int64\"})\n .drop(['id'], axis='columns')\n )\n first_cols = [\n 'report_date',\n 'utility_id_eia',\n 'utility_id_pudl',\n 'utility_name_eia',\n ]\n\n out_df = pudl.helpers.organize_cols(out_df, first_cols)\n return out_df\n\n\ndef plants_eia860(pudl_engine, start_date=None, end_date=None):\n \"\"\"Pull all fields from the EIA Plants tables.\n\n Args:\n pudl_engine (sqlalchemy.engine.Engine): SQLAlchemy connection engine\n for the PUDL DB.\n start_date (date-like): date-like object, including a string of the\n form 'YYYY-MM-DD' which will be used to specify the date range of\n records to be pulled. Dates are inclusive.\n end_date (date-like): date-like object, including a string of the\n form 'YYYY-MM-DD' which will be used to specify the date range of\n records to be pulled. Dates are inclusive.\n\n Returns:\n pandas.DataFrame: A DataFrame containing all the fields of the EIA 860\n Plants table.\n\n \"\"\"\n pt = pudl.output.pudltabl.get_table_meta(pudl_engine)\n # grab the entity table\n plants_eia_tbl = pt['plants_entity_eia']\n plants_eia_select = sa.sql.select([plants_eia_tbl])\n plants_eia_df = pd.read_sql(plants_eia_select, pudl_engine)\n\n # grab the annual table select\n plants_eia860_tbl = pt['plants_eia860']\n plants_eia860_select = sa.sql.select([plants_eia860_tbl])\n if start_date is not None:\n start_date = pd.to_datetime(start_date)\n plants_eia860_select = plants_eia860_select.where(\n plants_eia860_tbl.c.report_date >= start_date\n )\n if end_date is not None:\n end_date = pd.to_datetime(end_date)\n plants_eia860_select = plants_eia860_select.where(\n plants_eia860_tbl.c.report_date <= end_date\n )\n plants_eia860_df = (\n pd.read_sql(plants_eia860_select, pudl_engine)\n .assign(report_date=lambda x: pd.to_datetime(x.report_date))\n )\n\n # plant glue table\n plants_g_eia_tbl = pt['plants_eia']\n plants_g_eia_select = sa.sql.select([\n plants_g_eia_tbl.c.plant_id_eia,\n plants_g_eia_tbl.c.plant_id_pudl,\n ])\n plants_g_eia_df = pd.read_sql(plants_g_eia_select, pudl_engine)\n\n out_df = pd.merge(\n plants_eia_df, plants_eia860_df, how='left', on=['plant_id_eia'])\n out_df = pd.merge(out_df, plants_g_eia_df, how='left', on=['plant_id_eia'])\n\n utils_eia_tbl = pt['utilities_eia']\n utils_eia_select = sa.sql.select([\n utils_eia_tbl.c.utility_id_eia,\n utils_eia_tbl.c.utility_id_pudl,\n ])\n utils_eia_df = pd.read_sql(utils_eia_select, pudl_engine)\n\n out_df = (\n pd.merge(out_df, utils_eia_df, how='left', on=['utility_id_eia', ])\n .drop(['id'], axis='columns')\n .dropna(subset=[\"report_date\", \"plant_id_eia\"])\n .astype({\n \"plant_id_eia\": \"Int64\",\n \"plant_id_pudl\": \"Int64\",\n \"utility_id_eia\": \"Int64\",\n \"utility_id_pudl\": \"Int64\",\n })\n )\n return out_df\n\n\ndef plants_utils_eia860(pudl_engine, start_date=None, end_date=None):\n \"\"\"Create a dataframe of plant and utility IDs and names from EIA 860.\n\n Returns a pandas dataframe with the following columns:\n - report_date (in which data was reported)\n - plant_name_eia (from EIA entity)\n - plant_id_eia (from EIA entity)\n - plant_id_pudl\n - utility_id_eia (from EIA860)\n - utility_name_eia (from EIA860)\n - utility_id_pudl\n\n Args:\n pudl_engine (sqlalchemy.engine.Engine): SQLAlchemy connection engine\n for the PUDL DB.\n start_date (date-like): date-like object, including a string of the\n form 'YYYY-MM-DD' which will be used to specify the date range of\n records to be pulled. Dates are inclusive.\n end_date (date-like): date-like object, including a string of the\n form 'YYYY-MM-DD' which will be used to specify the date range of\n records to be pulled. Dates are inclusive.\n\n Returns:\n pandas.DataFrame: A DataFrame containing plant and utility IDs and\n names from EIA 860.\n\n \"\"\"\n # Contains the one-to-one mapping of EIA plants to their operators, but\n # we only have the 860 data integrated for 2011 forward right now.\n plants_eia = (\n plants_eia860(pudl_engine, start_date=start_date, end_date=end_date)\n .drop(['utility_id_pudl', 'city', 'state', # Avoid dupes in merge\n 'zip_code', 'street_address'], axis='columns')\n .dropna(subset=[\"utility_id_eia\"]) # Drop unmergable records\n )\n utils_eia = utilities_eia860(pudl_engine,\n start_date=start_date,\n end_date=end_date)\n\n # to avoid duplicate columns on the merge...\n out_df = pd.merge(plants_eia, utils_eia,\n how='left', on=['report_date', 'utility_id_eia'])\n\n out_df = (\n out_df.loc[:, ['report_date',\n 'plant_id_eia',\n 'plant_name_eia',\n 'plant_id_pudl',\n 'utility_id_eia',\n 'utility_name_eia',\n 'utility_id_pudl']\n ]\n .dropna(subset=[\"report_date\", \"plant_id_eia\", \"utility_id_eia\"])\n .astype({\n \"plant_id_eia\": \"Int64\",\n \"plant_id_pudl\": \"Int64\",\n \"utility_id_eia\": \"Int64\",\n \"utility_id_pudl\": \"Int64\",\n })\n )\n return out_df\n\n\ndef generators_eia860(pudl_engine, start_date=None, end_date=None):\n \"\"\"Pull all fields reported in the generators_eia860 table.\n\n Merge in other useful fields including the latitude & longitude of the\n plant that the generators are part of, canonical plant & operator names and\n the PUDL IDs of the plant and operator, for merging with other PUDL data\n sources.\n\n Fill in data for adjacent years if requested, but never fill in earlier\n than the earliest working year of data for EIA923, and never add more than\n one year on after the reported data (since there should at most be a one\n year lag between EIA923 and EIA860 reporting)\n\n Args:\n pudl_engine (sqlalchemy.engine.Engine): SQLAlchemy connection engine\n for the PUDL DB.\n start_date (date-like): date-like object, including a string of the\n form 'YYYY-MM-DD' which will be used to specify the date range of\n records to be pulled. Dates are inclusive.\n end_date (date-like): date-like object, including a string of the\n form 'YYYY-MM-DD' which will be used to specify the date range of\n records to be pulled. Dates are inclusive.\n\n Returns:\n pandas.DataFrame: A DataFrame containing all the fields of the EIA 860\n Generators table.\n \"\"\"\n # pudl_settings = pudl.workspace.setup.get_defaults()\n # pudl_engine = sa.create_engine(pudl_settings[\"pudl_db\"])\n\n pt = pudl.output.pudltabl.get_table_meta(pudl_engine)\n # Almost all the info we need will come from here.\n gens_eia860_tbl = pt['generators_eia860']\n gens_eia860_select = sa.sql.select([gens_eia860_tbl, ])\n # To get plant age\n generators_entity_eia_tbl = pt['generators_entity_eia']\n generators_entity_eia_select = sa.sql.select([\n generators_entity_eia_tbl.c.plant_id_eia,\n generators_entity_eia_tbl.c.generator_id,\n generators_entity_eia_tbl.c.operating_date,\n # generators_entity_eia_tbl.c.report_date\n ])\n # To get the Lat/Lon coordinates\n plants_entity_eia_tbl = pt['plants_entity_eia']\n plants_entity_eia_select = sa.sql.select([\n plants_entity_eia_tbl.c.plant_id_eia,\n plants_entity_eia_tbl.c.plant_name_eia,\n plants_entity_eia_tbl.c.latitude,\n plants_entity_eia_tbl.c.longitude,\n plants_entity_eia_tbl.c.state,\n plants_entity_eia_tbl.c.balancing_authority_code,\n plants_entity_eia_tbl.c.balancing_authority_name,\n plants_entity_eia_tbl.c.iso_rto_code,\n plants_entity_eia_tbl.c.city,\n plants_entity_eia_tbl.c.nerc_region,\n ])\n\n if start_date is not None:\n start_date = pd.to_datetime(start_date)\n gens_eia860_select = gens_eia860_select.where(\n gens_eia860_tbl.c.report_date >= start_date\n )\n\n if end_date is not None:\n end_date = pd.to_datetime(end_date)\n gens_eia860_select = gens_eia860_select.where(\n gens_eia860_tbl.c.report_date <= end_date\n )\n\n # breakpoint()\n gens_eia860 = pd.read_sql(gens_eia860_select, pudl_engine)\n generators_entity_eia_df = pd.read_sql(\n generators_entity_eia_select, pudl_engine)\n\n plants_entity_eia_df = pd.read_sql(plants_entity_eia_select, pudl_engine)\n\n out_df = pd.merge(gens_eia860, plants_entity_eia_df,\n how='left', on=['plant_id_eia'])\n out_df = pd.merge(out_df, generators_entity_eia_df,\n how='left', on=['plant_id_eia', 'generator_id'])\n\n out_df.report_date = pd.to_datetime(out_df.report_date)\n\n # Bring in some generic plant & utility information:\n pu_eia = (\n plants_utils_eia860(\n pudl_engine, start_date=start_date, end_date=end_date)\n .drop([\"plant_name_eia\", \"utility_id_eia\"], axis=\"columns\")\n )\n out_df = pd.merge(out_df, pu_eia,\n on=['report_date', 'plant_id_eia'],\n how=\"left\")\n # ,'plant_name_eia', 'utility_id_eia'])\n\n # Drop a few extraneous fields...\n out_df = out_df.drop(['id'], axis='columns')\n\n # In order to be able to differentiate between single and multi-fuel\n # plants, we need to count how many different simple energy sources there\n # are associated with plant's generators. This allows us to do the simple\n # lumping of an entire plant's fuel & generation if its primary fuels\n # are homogeneous, and split out fuel & generation by fuel if it is\n # hetereogeneous.\n ft_count = out_df[['plant_id_eia', 'fuel_type_code_pudl', 'report_date']].\\\n drop_duplicates().groupby(['plant_id_eia', 'report_date']).count()\n ft_count = ft_count.reset_index()\n ft_count = ft_count.rename(\n columns={'fuel_type_code_pudl': 'fuel_type_count'})\n out_df = (\n pd.merge(out_df, ft_count, how='left',\n on=['plant_id_eia', 'report_date'])\n .dropna(subset=[\"report_date\", \"plant_id_eia\", \"generator_id\"])\n .astype({\n \"plant_id_eia\": \"Int64\",\n \"plant_id_pudl\": \"Int64\",\n \"utility_id_eia\": \"Int64\",\n \"utility_id_pudl\": \"Int64\",\n })\n )\n\n first_cols = [\n 'report_date',\n 'plant_id_eia',\n 'plant_id_pudl',\n 'plant_name_eia',\n 'utility_id_eia',\n 'utility_id_pudl',\n 'utility_name_eia',\n 'generator_id',\n ]\n\n # Re-arrange the columns for easier readability:\n out_df = (\n pudl.helpers.organize_cols(out_df, first_cols)\n .sort_values(['report_date', 'plant_id_eia', 'generator_id'])\n )\n\n return out_df\n\n\ndef boiler_generator_assn_eia860(pudl_engine, start_date=None, end_date=None):\n \"\"\"Pull all fields from the EIA 860 boiler generator association table.\n\n Args:\n pudl_engine (sqlalchemy.engine.Engine): SQLAlchemy connection engine\n for the PUDL DB.\n start_date (date-like): date-like object, including a string of the\n form 'YYYY-MM-DD' which will be used to specify the date range of\n records to be pulled. Dates are inclusive.\n end_date (date-like): date-like object, including a string of the\n form 'YYYY-MM-DD' which will be used to specify the date range of\n records to be pulled. Dates are inclusive.\n\n Returns:\n pandas.DataFrame: A DataFrame containing all the fields from the EIA\n 860 boiler generator association table.\n\n \"\"\"\n pt = pudl.output.pudltabl.get_table_meta(pudl_engine)\n bga_eia860_tbl = pt['boiler_generator_assn_eia860']\n bga_eia860_select = sa.sql.select([bga_eia860_tbl])\n\n if start_date is not None:\n start_date = pd.to_datetime(start_date)\n bga_eia860_select = bga_eia860_select.where(\n bga_eia860_tbl.c.report_date >= start_date\n )\n if end_date is not None:\n end_date = pd.to_datetime(end_date)\n bga_eia860_select = bga_eia860_select.where(\n bga_eia860_tbl.c.report_date <= end_date\n )\n out_df = (\n pd.read_sql(bga_eia860_select, pudl_engine)\n .assign(report_date=lambda x: pd.to_datetime(x.report_date))\n .drop(['id'], axis='columns')\n )\n return out_df\n\n\ndef ownership_eia860(pudl_engine, start_date=None, end_date=None):\n \"\"\"Pull a useful set of fields related to ownership_eia860 table.\n\n Args:\n pudl_engine (sqlalchemy.engine.Engine): SQLAlchemy connection engine\n for the PUDL DB.\n start_date (date-like): date-like object, including a string of the\n form 'YYYY-MM-DD' which will be used to specify the date range of\n records to be pulled. Dates are inclusive.\n end_date (date-like): date-like object, including a string of the\n form 'YYYY-MM-DD' which will be used to specify the date range of\n records to be pulled. Dates are inclusive.\n\n Returns:\n pandas.DataFrame: A DataFrame containing a useful set of fields related\n to the EIA 860 Ownership table.\n\n \"\"\"\n # breakpoint()\n pt = pudl.output.pudltabl.get_table_meta(pudl_engine)\n own_eia860_tbl = pt[\"ownership_eia860\"]\n own_eia860_select = sa.sql.select([own_eia860_tbl])\n\n if start_date is not None:\n start_date = pd.to_datetime(start_date)\n own_eia860_select = own_eia860_select.where(\n own_eia860_tbl.c.report_date >= start_date\n )\n if end_date is not None:\n end_date = pd.to_datetime(end_date)\n own_eia860_select = own_eia860_select.where(\n own_eia860_tbl.c.report_date <= end_date\n )\n own_eia860_df = (\n pd.read_sql(own_eia860_select, pudl_engine)\n .drop(['id'], axis='columns')\n .assign(report_date=lambda x: pd.to_datetime(x[\"report_date\"]))\n )\n\n pu_eia = (\n plants_utils_eia860(\n pudl_engine, start_date=start_date, end_date=end_date)\n .loc[:, ['plant_id_eia', 'plant_id_pudl', 'plant_name_eia',\n 'utility_name_eia', 'utility_id_pudl', 'report_date']]\n )\n\n out_df = (\n pd.merge(own_eia860_df, pu_eia,\n how='left', on=['report_date', 'plant_id_eia'])\n .dropna(subset=[\n \"report_date\",\n \"plant_id_eia\",\n \"generator_id\",\n \"owner_utility_id_eia\",\n ])\n .astype({\n \"plant_id_eia\": \"Int64\",\n \"plant_id_pudl\": \"Int64\",\n \"utility_id_eia\": \"Int64\",\n \"utility_id_pudl\": \"Int64\",\n })\n )\n\n first_cols = [\n 'report_date',\n 'plant_id_eia',\n 'plant_id_pudl',\n 'plant_name_eia',\n 'utility_id_eia',\n 'utility_id_pudl',\n 'utility_name_eia',\n 'generator_id',\n 'owner_utility_id_eia',\n 'owner_name',\n ]\n\n # Re-arrange the columns for easier readability:\n out_df = (\n pudl.helpers.organize_cols(out_df, first_cols)\n )\n\n return out_df\n"
] |
[
[
"pandas.merge",
"pandas.to_datetime",
"pandas.read_sql"
]
] |
tangyisheng2/mne-python
|
[
"740fcb89b9910ef2fa84cffe402a06b4da643374"
] |
[
"mne/minimum_norm/inverse.py"
] |
[
"# -*- coding: utf-8 -*-\n# Authors: Alexandre Gramfort <[email protected]>\n# Matti Hämäläinen <[email protected]>\n# Teon Brooks <[email protected]>\n#\n# License: BSD (3-clause)\n\nfrom copy import deepcopy\nfrom math import sqrt\nimport numpy as np\nfrom scipy import linalg\n\nfrom ._eloreta import _compute_eloreta\nfrom ..fixes import _safe_svd\nfrom ..io.base import BaseRaw\nfrom ..io.constants import FIFF\nfrom ..io.open import fiff_open\nfrom ..io.tag import find_tag\nfrom ..io.matrix import (_read_named_matrix, _transpose_named_matrix,\n write_named_matrix)\nfrom ..io.proj import (_read_proj, make_projector, _write_proj,\n _needs_eeg_average_ref_proj)\nfrom ..io.tree import dir_tree_find\nfrom ..io.write import (write_int, write_float_matrix, start_file,\n start_block, end_block, end_file, write_float,\n write_coord_trans, write_string)\n\nfrom ..io.pick import channel_type, pick_info, pick_types, pick_channels\nfrom ..cov import (compute_whitener, _read_cov, _write_cov, Covariance,\n prepare_noise_cov)\nfrom ..epochs import BaseEpochs\nfrom ..evoked import EvokedArray, Evoked\nfrom ..forward import (compute_depth_prior, _read_forward_meas_info,\n is_fixed_orient, compute_orient_prior,\n convert_forward_solution, _select_orient_forward)\nfrom ..forward.forward import write_forward_meas_info, _triage_loose\nfrom ..source_space import (_read_source_spaces_from_tree, _get_src_nn,\n find_source_space_hemi, _get_vertno,\n _write_source_spaces_to_fid, label_src_vertno_sel)\nfrom ..surface import _normal_orth\nfrom ..transforms import _ensure_trans, transform_surface_to\nfrom ..source_estimate import _make_stc, _get_src_type\nfrom ..utils import (check_fname, logger, verbose, warn, _validate_type,\n _check_compensation_grade, _check_option,\n _check_depth, _check_src_normal)\n\n\nINVERSE_METHODS = ('MNE', 'dSPM', 'sLORETA', 'eLORETA')\n\n\nclass InverseOperator(dict):\n \"\"\"InverseOperator class to represent info from inverse operator.\"\"\"\n\n def copy(self):\n \"\"\"Return a copy of the InverseOperator.\"\"\"\n return InverseOperator(deepcopy(self))\n\n def __repr__(self): # noqa: D105\n \"\"\"Summarize inverse info instead of printing all.\"\"\"\n entr = '<InverseOperator'\n\n nchan = len(pick_types(self['info'], meg=True, eeg=False))\n entr += ' | ' + 'MEG channels: %d' % nchan\n nchan = len(pick_types(self['info'], meg=False, eeg=True))\n entr += ' | ' + 'EEG channels: %d' % nchan\n\n entr += (' | Source space: %s with %d sources'\n % (self['src'].kind, self['nsource']))\n source_ori = {FIFF.FIFFV_MNE_UNKNOWN_ORI: 'Unknown',\n FIFF.FIFFV_MNE_FIXED_ORI: 'Fixed',\n FIFF.FIFFV_MNE_FREE_ORI: 'Free'}\n entr += ' | Source orientation: %s' % source_ori[self['source_ori']]\n entr += '>'\n\n return entr\n\n\ndef _pick_channels_inverse_operator(ch_names, inv):\n \"\"\"Return data channel indices to be used knowing an inverse operator.\n\n Unlike ``pick_channels``, this respects the order of ch_names.\n \"\"\"\n sel = list()\n for name in inv['noise_cov'].ch_names:\n try:\n sel.append(ch_names.index(name))\n except ValueError:\n raise ValueError('The inverse operator was computed with '\n 'channel %s which is not present in '\n 'the data. You should compute a new inverse '\n 'operator restricted to the good data '\n 'channels.' % name)\n return sel\n\n\n@verbose\ndef read_inverse_operator(fname, verbose=None):\n \"\"\"Read the inverse operator decomposition from a FIF file.\n\n Parameters\n ----------\n fname : str\n The name of the FIF file, which ends with -inv.fif or -inv.fif.gz.\n %(verbose)s\n\n Returns\n -------\n inv : instance of InverseOperator\n The inverse operator.\n\n See Also\n --------\n write_inverse_operator, make_inverse_operator\n \"\"\"\n check_fname(fname, 'inverse operator', ('-inv.fif', '-inv.fif.gz',\n '_inv.fif', '_inv.fif.gz'))\n\n #\n # Open the file, create directory\n #\n logger.info('Reading inverse operator decomposition from %s...'\n % fname)\n f, tree, _ = fiff_open(fname)\n with f as fid:\n #\n # Find all inverse operators\n #\n invs = dir_tree_find(tree, FIFF.FIFFB_MNE_INVERSE_SOLUTION)\n if invs is None or len(invs) < 1:\n raise Exception('No inverse solutions in %s' % fname)\n\n invs = invs[0]\n #\n # Parent MRI data\n #\n parent_mri = dir_tree_find(tree, FIFF.FIFFB_MNE_PARENT_MRI_FILE)\n if len(parent_mri) == 0:\n raise Exception('No parent MRI information in %s' % fname)\n parent_mri = parent_mri[0] # take only first one\n\n logger.info(' Reading inverse operator info...')\n #\n # Methods and source orientations\n #\n tag = find_tag(fid, invs, FIFF.FIFF_MNE_INCLUDED_METHODS)\n if tag is None:\n raise Exception('Modalities not found')\n\n inv = dict()\n inv['methods'] = int(tag.data)\n\n tag = find_tag(fid, invs, FIFF.FIFF_MNE_SOURCE_ORIENTATION)\n if tag is None:\n raise Exception('Source orientation constraints not found')\n\n inv['source_ori'] = int(tag.data)\n\n tag = find_tag(fid, invs, FIFF.FIFF_MNE_SOURCE_SPACE_NPOINTS)\n if tag is None:\n raise Exception('Number of sources not found')\n\n inv['nsource'] = int(tag.data)\n inv['nchan'] = 0\n #\n # Coordinate frame\n #\n tag = find_tag(fid, invs, FIFF.FIFF_MNE_COORD_FRAME)\n if tag is None:\n raise Exception('Coordinate frame tag not found')\n\n inv['coord_frame'] = tag.data\n\n #\n # Units\n #\n tag = find_tag(fid, invs, FIFF.FIFF_MNE_INVERSE_SOURCE_UNIT)\n unit_dict = {FIFF.FIFF_UNIT_AM: 'Am',\n FIFF.FIFF_UNIT_AM_M2: 'Am/m^2',\n FIFF.FIFF_UNIT_AM_M3: 'Am/m^3'}\n inv['units'] = unit_dict.get(int(getattr(tag, 'data', -1)), None)\n\n #\n # The actual source orientation vectors\n #\n tag = find_tag(fid, invs, FIFF.FIFF_MNE_INVERSE_SOURCE_ORIENTATIONS)\n if tag is None:\n raise Exception('Source orientation information not found')\n\n inv['source_nn'] = tag.data\n logger.info(' [done]')\n #\n # The SVD decomposition...\n #\n logger.info(' Reading inverse operator decomposition...')\n tag = find_tag(fid, invs, FIFF.FIFF_MNE_INVERSE_SING)\n if tag is None:\n raise Exception('Singular values not found')\n\n inv['sing'] = tag.data\n inv['nchan'] = len(inv['sing'])\n #\n # The eigenleads and eigenfields\n #\n inv['eigen_leads_weighted'] = False\n inv['eigen_leads'] = _read_named_matrix(\n fid, invs, FIFF.FIFF_MNE_INVERSE_LEADS, transpose=True)\n if inv['eigen_leads'] is None:\n inv['eigen_leads_weighted'] = True\n inv['eigen_leads'] = _read_named_matrix(\n fid, invs, FIFF.FIFF_MNE_INVERSE_LEADS_WEIGHTED,\n transpose=True)\n if inv['eigen_leads'] is None:\n raise ValueError('Eigen leads not found in inverse operator.')\n #\n # Having the eigenleads as cols is better for the inverse calcs\n #\n inv['eigen_fields'] = _read_named_matrix(fid, invs,\n FIFF.FIFF_MNE_INVERSE_FIELDS)\n logger.info(' [done]')\n #\n # Read the covariance matrices\n #\n inv['noise_cov'] = Covariance(\n **_read_cov(fid, invs, FIFF.FIFFV_MNE_NOISE_COV, limited=True))\n logger.info(' Noise covariance matrix read.')\n\n inv['source_cov'] = _read_cov(fid, invs, FIFF.FIFFV_MNE_SOURCE_COV)\n logger.info(' Source covariance matrix read.')\n #\n # Read the various priors\n #\n inv['orient_prior'] = _read_cov(fid, invs,\n FIFF.FIFFV_MNE_ORIENT_PRIOR_COV)\n if inv['orient_prior'] is not None:\n logger.info(' Orientation priors read.')\n\n inv['depth_prior'] = _read_cov(fid, invs,\n FIFF.FIFFV_MNE_DEPTH_PRIOR_COV)\n if inv['depth_prior'] is not None:\n logger.info(' Depth priors read.')\n\n inv['fmri_prior'] = _read_cov(fid, invs, FIFF.FIFFV_MNE_FMRI_PRIOR_COV)\n if inv['fmri_prior'] is not None:\n logger.info(' fMRI priors read.')\n\n #\n # Read the source spaces\n #\n inv['src'] = _read_source_spaces_from_tree(fid, tree,\n patch_stats=False)\n\n for s in inv['src']:\n s['id'] = find_source_space_hemi(s)\n\n #\n # Get the MRI <-> head coordinate transformation\n #\n tag = find_tag(fid, parent_mri, FIFF.FIFF_COORD_TRANS)\n if tag is None:\n raise Exception('MRI/head coordinate transformation not found')\n mri_head_t = _ensure_trans(tag.data, 'mri', 'head')\n\n inv['mri_head_t'] = mri_head_t\n\n #\n # get parent MEG info\n #\n inv['info'] = _read_forward_meas_info(tree, fid)\n\n #\n # Transform the source spaces to the correct coordinate frame\n # if necessary\n #\n if inv['coord_frame'] not in (FIFF.FIFFV_COORD_MRI,\n FIFF.FIFFV_COORD_HEAD):\n raise Exception('Only inverse solutions computed in MRI or '\n 'head coordinates are acceptable')\n\n #\n # Number of averages is initially one\n #\n inv['nave'] = 1\n #\n # We also need the SSP operator\n #\n inv['projs'] = _read_proj(fid, tree)\n\n #\n # Some empty fields to be filled in later\n #\n inv['proj'] = [] # This is the projector to apply to the data\n inv['whitener'] = [] # This whitens the data\n # This the diagonal matrix implementing regularization and the inverse\n inv['reginv'] = []\n inv['noisenorm'] = [] # These are the noise-normalization factors\n #\n nuse = 0\n for k in range(len(inv['src'])):\n try:\n inv['src'][k] = transform_surface_to(inv['src'][k],\n inv['coord_frame'],\n mri_head_t)\n except Exception as inst:\n raise Exception('Could not transform source space (%s)' % inst)\n\n nuse += inv['src'][k]['nuse']\n\n logger.info(' Source spaces transformed to the inverse solution '\n 'coordinate frame')\n #\n # Done!\n #\n\n return InverseOperator(inv)\n\n\n@verbose\ndef write_inverse_operator(fname, inv, verbose=None):\n \"\"\"Write an inverse operator to a FIF file.\n\n Parameters\n ----------\n fname : str\n The name of the FIF file, which ends with -inv.fif or -inv.fif.gz.\n inv : dict\n The inverse operator.\n %(verbose)s\n\n See Also\n --------\n read_inverse_operator\n \"\"\"\n check_fname(fname, 'inverse operator', ('-inv.fif', '-inv.fif.gz',\n '_inv.fif', '_inv.fif.gz'))\n _validate_type(inv, InverseOperator, 'inv')\n\n #\n # Open the file, create directory\n #\n logger.info('Write inverse operator decomposition in %s...' % fname)\n\n # Create the file and save the essentials\n fid = start_file(fname)\n start_block(fid, FIFF.FIFFB_MNE)\n\n #\n # Parent MEG measurement info\n #\n write_forward_meas_info(fid, inv['info'])\n\n #\n # Parent MRI data\n #\n start_block(fid, FIFF.FIFFB_MNE_PARENT_MRI_FILE)\n write_string(fid, FIFF.FIFF_MNE_FILE_NAME, inv['info']['mri_file'])\n write_coord_trans(fid, inv['mri_head_t'])\n end_block(fid, FIFF.FIFFB_MNE_PARENT_MRI_FILE)\n\n #\n # Write SSP operator\n #\n _write_proj(fid, inv['projs'])\n\n #\n # Write the source spaces\n #\n if 'src' in inv:\n _write_source_spaces_to_fid(fid, inv['src'])\n\n start_block(fid, FIFF.FIFFB_MNE_INVERSE_SOLUTION)\n\n logger.info(' Writing inverse operator info...')\n\n write_int(fid, FIFF.FIFF_MNE_INCLUDED_METHODS, inv['methods'])\n write_int(fid, FIFF.FIFF_MNE_COORD_FRAME, inv['coord_frame'])\n\n udict = {'Am': FIFF.FIFF_UNIT_AM,\n 'Am/m^2': FIFF.FIFF_UNIT_AM_M2,\n 'Am/m^3': FIFF.FIFF_UNIT_AM_M3}\n if 'units' in inv and inv['units'] is not None:\n write_int(fid, FIFF.FIFF_MNE_INVERSE_SOURCE_UNIT, udict[inv['units']])\n\n write_int(fid, FIFF.FIFF_MNE_SOURCE_ORIENTATION, inv['source_ori'])\n write_int(fid, FIFF.FIFF_MNE_SOURCE_SPACE_NPOINTS, inv['nsource'])\n if 'nchan' in inv:\n write_int(fid, FIFF.FIFF_NCHAN, inv['nchan'])\n elif 'nchan' in inv['info']:\n write_int(fid, FIFF.FIFF_NCHAN, inv['info']['nchan'])\n write_float_matrix(fid, FIFF.FIFF_MNE_INVERSE_SOURCE_ORIENTATIONS,\n inv['source_nn'])\n write_float(fid, FIFF.FIFF_MNE_INVERSE_SING, inv['sing'])\n\n #\n # write the covariance matrices\n #\n logger.info(' Writing noise covariance matrix.')\n _write_cov(fid, inv['noise_cov'])\n\n logger.info(' Writing source covariance matrix.')\n _write_cov(fid, inv['source_cov'])\n\n #\n # write the various priors\n #\n logger.info(' Writing orientation priors.')\n if inv['depth_prior'] is not None:\n _write_cov(fid, inv['depth_prior'])\n if inv['orient_prior'] is not None:\n _write_cov(fid, inv['orient_prior'])\n if inv['fmri_prior'] is not None:\n _write_cov(fid, inv['fmri_prior'])\n\n write_named_matrix(fid, FIFF.FIFF_MNE_INVERSE_FIELDS, inv['eigen_fields'])\n\n #\n # The eigenleads and eigenfields\n #\n if inv['eigen_leads_weighted']:\n kind = FIFF.FIFF_MNE_INVERSE_LEADS_WEIGHTED\n else:\n kind = FIFF.FIFF_MNE_INVERSE_LEADS\n _transpose_named_matrix(inv['eigen_leads'])\n write_named_matrix(fid, kind, inv['eigen_leads'])\n _transpose_named_matrix(inv['eigen_leads'])\n\n #\n # Done!\n #\n logger.info(' [done]')\n\n end_block(fid, FIFF.FIFFB_MNE_INVERSE_SOLUTION)\n end_block(fid, FIFF.FIFFB_MNE)\n end_file(fid)\n\n fid.close()\n\n###############################################################################\n# Compute inverse solution\n\n\ndef combine_xyz(vec, square=False):\n \"\"\"Compute the three Cartesian components of a vector or matrix together.\n\n Parameters\n ----------\n vec : 2d array of shape [3 n x p]\n Input [ x1 y1 z1 ... x_n y_n z_n ] where x1 ... z_n\n can be vectors\n\n Returns\n -------\n comb : array\n Output vector [sqrt(x1^2+y1^2+z1^2), ..., sqrt(x_n^2+y_n^2+z_n^2)]\n \"\"\"\n if vec.ndim != 2:\n raise ValueError('Input must be 2D')\n if (vec.shape[0] % 3) != 0:\n raise ValueError('Input must have 3N rows')\n if np.iscomplexobj(vec):\n vec = np.abs(vec)\n comb = vec[0::3] ** 2\n comb += vec[1::3] ** 2\n comb += vec[2::3] ** 2\n if not square:\n comb = np.sqrt(comb)\n return comb\n\n\ndef _check_ch_names(inv, info):\n \"\"\"Check that channels in inverse operator are measurements.\"\"\"\n inv_ch_names = inv['eigen_fields']['col_names']\n\n if inv['noise_cov'].ch_names != inv_ch_names:\n raise ValueError('Channels in inverse operator eigen fields do not '\n 'match noise covariance channels.')\n data_ch_names = info['ch_names']\n\n missing_ch_names = sorted(set(inv_ch_names) - set(data_ch_names))\n n_missing = len(missing_ch_names)\n if n_missing > 0:\n raise ValueError('%d channels in inverse operator ' % n_missing +\n 'are not present in the data (%s)' % missing_ch_names)\n _check_compensation_grade(inv['info'], info, 'inverse')\n\n\ndef _check_or_prepare(inv, nave, lambda2, method, method_params, prepared,\n copy=True):\n \"\"\"Check if inverse was prepared, or prepare it.\"\"\"\n if not prepared:\n inv = prepare_inverse_operator(\n inv, nave, lambda2, method, method_params, copy=copy)\n elif 'colorer' not in inv:\n raise ValueError('inverse operator has not been prepared, but got '\n 'argument prepared=True. Either pass prepared=False '\n 'or use prepare_inverse_operator.')\n return inv\n\n\n@verbose\ndef prepare_inverse_operator(orig, nave, lambda2, method='dSPM',\n method_params=None, copy=True, verbose=None):\n \"\"\"Prepare an inverse operator for actually computing the inverse.\n\n Parameters\n ----------\n orig : dict\n The inverse operator structure read from a file.\n nave : int\n Number of averages (scales the noise covariance).\n lambda2 : float\n The regularization factor. Recommended to be 1 / SNR**2.\n method : \"MNE\" | \"dSPM\" | \"sLORETA\" | \"eLORETA\"\n Use minimum norm, dSPM (default), sLORETA, or eLORETA.\n method_params : dict | None\n Additional options for eLORETA. See Notes of :func:`apply_inverse`.\n\n .. versionadded:: 0.16\n copy : bool | str\n If True (default), copy the inverse. False will not copy.\n Can be \"non-src\" to avoid copying the source space, which typically\n is not modified and can be large in memory.\n\n .. versionadded:: 0.21\n %(verbose)s\n\n Returns\n -------\n inv : instance of InverseOperator\n Prepared inverse operator.\n \"\"\"\n if nave <= 0:\n raise ValueError('The number of averages should be positive')\n\n _validate_type(copy, (bool, str), 'copy')\n if isinstance(copy, str):\n _check_option('copy', copy, ('non-src',), extra='when a string')\n logger.info('Preparing the inverse operator for use...')\n inv = orig\n if copy:\n src = orig['src']\n if copy == 'non-src':\n orig['src'] = None\n try:\n inv = orig.copy()\n finally:\n orig['src'] = src\n if copy == 'non-src':\n inv['src'] = src\n del orig\n\n #\n # Scale some of the stuff\n #\n scale = float(inv['nave']) / nave\n inv['noise_cov']['data'] = scale * inv['noise_cov']['data']\n # deal with diagonal case\n if inv['noise_cov']['data'].ndim == 1:\n logger.info(' Diagonal noise covariance found')\n inv['noise_cov']['eig'] = inv['noise_cov']['data']\n inv['noise_cov']['eigvec'] = np.eye(len(inv['noise_cov']['data']))\n\n inv['noise_cov']['eig'] = scale * inv['noise_cov']['eig']\n inv['source_cov']['data'] = scale * inv['source_cov']['data']\n #\n if inv['eigen_leads_weighted']:\n inv['eigen_leads']['data'] = sqrt(scale) * inv['eigen_leads']['data']\n\n logger.info(' Scaled noise and source covariance from nave = %d to'\n ' nave = %d' % (inv['nave'], nave))\n inv['nave'] = nave\n #\n # Create the diagonal matrix for computing the regularized inverse\n #\n inv['reginv'] = _compute_reginv(inv, lambda2)\n logger.info(' Created the regularized inverter')\n #\n # Create the projection operator\n #\n inv['proj'], ncomp, _ = make_projector(inv['projs'],\n inv['noise_cov']['names'])\n if ncomp > 0:\n logger.info(' Created an SSP operator (subspace dimension = %d)'\n % ncomp)\n else:\n logger.info(' The projection vectors do not apply to these '\n 'channels.')\n\n #\n # Create the whitener\n #\n\n inv['whitener'], _, inv['colorer'] = compute_whitener(\n inv['noise_cov'], pca='white', return_colorer=True)\n\n #\n # Finally, compute the noise-normalization factors\n #\n inv['noisenorm'] = []\n if method == 'eLORETA':\n _compute_eloreta(inv, lambda2, method_params)\n elif method != 'MNE':\n logger.info(' Computing noise-normalization factors (%s)...'\n % method)\n # Here we have::\n #\n # inv['reginv'] = sing / (sing ** 2 + lambda2)\n #\n # where ``sing`` are the singular values of the whitened gain matrix.\n if method == \"dSPM\":\n # dSPM normalization\n noise_weight = inv['reginv']\n elif method == 'sLORETA':\n # sLORETA normalization is given by the square root of the\n # diagonal entries of the resolution matrix R, which is\n # the product of the inverse and forward operators as:\n #\n # w = diag(diag(R)) ** 0.5\n #\n noise_weight = (inv['reginv'] *\n np.sqrt((1. + inv['sing'] ** 2 / lambda2)))\n\n noise_norm = np.zeros(inv['eigen_leads']['nrow'])\n nrm2, = linalg.get_blas_funcs(('nrm2',), (noise_norm,))\n if inv['eigen_leads_weighted']:\n for k in range(inv['eigen_leads']['nrow']):\n one = inv['eigen_leads']['data'][k, :] * noise_weight\n noise_norm[k] = nrm2(one)\n else:\n for k in range(inv['eigen_leads']['nrow']):\n one = (sqrt(inv['source_cov']['data'][k]) *\n inv['eigen_leads']['data'][k, :] * noise_weight)\n noise_norm[k] = nrm2(one)\n\n #\n # Compute the final result\n #\n if inv['source_ori'] == FIFF.FIFFV_MNE_FREE_ORI:\n #\n # The three-component case is a little bit more involved\n # The variances at three consecutive entries must be squared and\n # added together\n #\n # Even in this case return only one noise-normalization factor\n # per source location\n #\n noise_norm = combine_xyz(noise_norm[:, None]).ravel()\n inv['noisenorm'] = 1.0 / np.abs(noise_norm)\n logger.info('[done]')\n else:\n inv['noisenorm'] = []\n\n return InverseOperator(inv)\n\n\n@verbose\ndef _assemble_kernel(inv, label, method, pick_ori, use_cps=True, verbose=None):\n \"\"\"Assemble the kernel.\n\n Simple matrix multiplication followed by combination of the current\n components. This does all the data transformations to compute the weights\n for the eigenleads.\n\n Parameters\n ----------\n inv : instance of InverseOperator\n The inverse operator to use. This object contains the matrices that\n will be multiplied to assemble the kernel.\n label : Label | None\n Restricts the source estimates to a given label. If None,\n source estimates will be computed for the entire source space.\n method : \"MNE\" | \"dSPM\" | \"sLORETA\" | \"eLORETA\"\n Use minimum norm, dSPM, sLORETA, or eLORETA.\n pick_ori : None | \"normal\" | \"vector\"\n Which orientation to pick (only matters in the case of 'normal').\n %(use_cps_restricted)s\n\n Returns\n -------\n K : array, shape (n_vertices, n_channels) | (3 * n_vertices, n_channels)\n The kernel matrix. Multiply this with the data to obtain the source\n estimate.\n noise_norm : array, shape (n_vertices, n_samples) | (3 * n_vertices, n_samples)\n Normalization to apply to the source estimate in order to obtain dSPM\n or sLORETA solutions.\n vertices : list of length 2\n Vertex numbers for lh and rh hemispheres that correspond to the\n vertices in the source estimate. When the label parameter has been\n set, these correspond to the vertices in the label. Otherwise, all\n vertex numbers are returned.\n source_nn : array, shape (3 * n_vertices, 3)\n The direction in carthesian coordicates of the direction of the source\n dipoles.\n \"\"\" # noqa: E501\n eigen_leads = inv['eigen_leads']['data']\n source_cov = inv['source_cov']['data']\n if method in ('dSPM', 'sLORETA'):\n noise_norm = inv['noisenorm'][:, np.newaxis]\n else:\n noise_norm = None\n\n src = inv['src']\n vertno = _get_vertno(src)\n source_nn = inv['source_nn']\n\n if label is not None:\n vertno, src_sel = label_src_vertno_sel(label, src)\n\n if method not in [\"MNE\", \"eLORETA\"]:\n noise_norm = noise_norm[src_sel]\n\n if inv['source_ori'] == FIFF.FIFFV_MNE_FREE_ORI:\n src_sel = 3 * src_sel\n src_sel = np.c_[src_sel, src_sel + 1, src_sel + 2]\n src_sel = src_sel.ravel()\n\n eigen_leads = eigen_leads[src_sel]\n source_cov = source_cov[src_sel]\n source_nn = source_nn[src_sel]\n\n # vector or normal, might need to rotate\n if pick_ori == 'normal' and all(s['type'] == 'surf' for s in src) and \\\n np.allclose(inv['source_nn'].reshape(inv['nsource'], 3, 3),\n np.eye(3), atol=1e-6):\n offset = 0\n eigen_leads = np.reshape(\n eigen_leads, (-1, 3, eigen_leads.shape[1])).copy()\n source_nn = np.reshape(source_nn, (-1, 3, 3)).copy()\n for s, v in zip(src, vertno):\n sl = slice(offset, offset + len(v))\n source_nn[sl] = _normal_orth(_get_src_nn(s, use_cps, v))\n eigen_leads[sl] = np.matmul(source_nn[sl], eigen_leads[sl])\n # No need to rotate source_cov because it should be uniform\n # (loose=1., and depth weighting is uniform across columns)\n offset = sl.stop\n eigen_leads.shape = (-1, eigen_leads.shape[2])\n source_nn.shape = (-1, 3)\n\n if pick_ori == \"normal\":\n if not inv['source_ori'] == FIFF.FIFFV_MNE_FREE_ORI:\n raise ValueError('Picking normal orientation can only be done '\n 'with a free orientation inverse operator.')\n\n is_loose = 0 < inv['orient_prior']['data'][0] <= 1\n if not is_loose:\n raise ValueError('Picking normal orientation can only be done '\n 'when working with loose orientations.')\n\n trans = np.dot(inv['eigen_fields']['data'],\n np.dot(inv['whitener'], inv['proj']))\n trans *= inv['reginv'][:, None]\n\n #\n # Transformation into current distributions by weighting the eigenleads\n # with the weights computed above\n #\n K = np.dot(eigen_leads, trans)\n if inv['eigen_leads_weighted']:\n #\n # R^0.5 has been already factored in\n #\n logger.info(' Eigenleads already weighted ... ')\n else:\n #\n # R^0.5 has to be factored in\n #\n logger.info(' Eigenleads need to be weighted ...')\n K *= np.sqrt(source_cov)[:, np.newaxis]\n\n if pick_ori == 'normal':\n K = K[2::3]\n\n return K, noise_norm, vertno, source_nn\n\n\ndef _check_ori(pick_ori, source_ori, src, allow_vector=True):\n \"\"\"Check pick_ori.\"\"\"\n _check_option('pick_ori', pick_ori, [None, 'normal', 'vector'])\n _check_src_normal(pick_ori, src)\n\n\ndef _check_reference(inst, ch_names=None):\n \"\"\"Check for EEG ref.\"\"\"\n info = inst.info\n if ch_names is not None:\n picks = [ci for ci, ch_name in enumerate(info['ch_names'])\n if ch_name in ch_names]\n info = pick_info(info, sel=picks)\n if _needs_eeg_average_ref_proj(info):\n raise ValueError('EEG average reference is mandatory for inverse '\n 'modeling, use set_eeg_reference method.')\n if info['custom_ref_applied']:\n raise ValueError('Custom EEG reference is not allowed for inverse '\n 'modeling.')\n\n\ndef _subject_from_inverse(inverse_operator):\n \"\"\"Get subject id from inverse operator.\"\"\"\n return inverse_operator['src']._subject\n\n\n@verbose\ndef apply_inverse(evoked, inverse_operator, lambda2=1. / 9., method=\"dSPM\",\n pick_ori=None, prepared=False, label=None,\n method_params=None, return_residual=False, use_cps=True,\n verbose=None):\n \"\"\"Apply inverse operator to evoked data.\n\n Parameters\n ----------\n evoked : Evoked object\n Evoked data.\n inverse_operator : instance of InverseOperator\n Inverse operator.\n lambda2 : float\n The regularization parameter.\n method : \"MNE\" | \"dSPM\" | \"sLORETA\" | \"eLORETA\"\n Use minimum norm :footcite:`HamalainenIlmoniemi1994`,\n dSPM (default) :footcite:`DaleEtAl2000`,\n sLORETA :footcite:`Pascual-Marqui2002`, or\n eLORETA :footcite:`Pascual-Marqui2011`.\n %(pick_ori)s\n prepared : bool\n If True, do not call :func:`prepare_inverse_operator`.\n label : Label | None\n Restricts the source estimates to a given label. If None,\n source estimates will be computed for the entire source space.\n method_params : dict | None\n Additional options for eLORETA. See Notes for details.\n\n .. versionadded:: 0.16\n return_residual : bool\n If True (default False), return the residual evoked data.\n Cannot be used with ``method=='eLORETA'``.\n\n .. versionadded:: 0.17\n %(use_cps_restricted)s\n\n .. versionadded:: 0.20\n %(verbose)s\n\n Returns\n -------\n stc : SourceEstimate | VectorSourceEstimate | VolSourceEstimate\n The source estimates.\n residual : instance of Evoked\n The residual evoked data, only returned if return_residual is True.\n\n See Also\n --------\n apply_inverse_raw : Apply inverse operator to raw object.\n apply_inverse_epochs : Apply inverse operator to epochs object.\n\n Notes\n -----\n Currently only the ``method='eLORETA'`` has additional options.\n It performs an iterative fit with a convergence criterion, so you can\n pass a ``method_params`` :class:`dict` with string keys mapping to values\n for:\n\n 'eps' : float\n The convergence epsilon (default 1e-6).\n 'max_iter' : int\n The maximum number of iterations (default 20).\n If less regularization is applied, more iterations may be\n necessary.\n 'force_equal' : bool\n Force all eLORETA weights for each direction for a given\n location equal. The default is None, which means ``True`` for\n loose-orientation inverses and ``False`` for free- and\n fixed-orientation inverses. See below.\n\n The eLORETA paper :footcite:`Pascual-Marqui2011` defines how to compute\n inverses for fixed- and\n free-orientation inverses. In the free orientation case, the X/Y/Z\n orientation triplet for each location is effectively multiplied by a\n 3x3 weight matrix. This is the behavior obtained with\n ``force_equal=False`` parameter.\n\n However, other noise normalization methods (dSPM, sLORETA) multiply all\n orientations for a given location by a single value.\n Using ``force_equal=True`` mimics this behavior by modifying the iterative\n algorithm to choose uniform weights (equivalent to a 3x3 diagonal matrix\n with equal entries).\n\n It is necessary to use ``force_equal=True``\n with loose orientation inverses (e.g., ``loose=0.2``), otherwise the\n solution resembles a free-orientation inverse (``loose=1.0``).\n It is thus recommended to use ``force_equal=True`` for loose orientation\n and ``force_equal=False`` for free orientation inverses. This is the\n behavior used when the parameter ``force_equal=None`` (default behavior).\n\n References\n ----------\n .. footbibliography::\n \"\"\"\n out = _apply_inverse(\n evoked, inverse_operator, lambda2, method, pick_ori, prepared, label,\n method_params, return_residual, use_cps)\n logger.info('[done]')\n return out\n\n\ndef _apply_inverse(evoked, inverse_operator, lambda2, method, pick_ori,\n prepared, label, method_params, return_residual, use_cps):\n _validate_type(evoked, Evoked, 'evoked')\n _check_reference(evoked, inverse_operator['info']['ch_names'])\n _check_option('method', method, INVERSE_METHODS)\n _check_ori(pick_ori, inverse_operator['source_ori'],\n inverse_operator['src'])\n #\n # Set up the inverse according to the parameters\n #\n nave = evoked.nave\n\n _check_ch_names(inverse_operator, evoked.info)\n\n inv = _check_or_prepare(inverse_operator, nave, lambda2, method,\n method_params, prepared, copy='non-src')\n del inverse_operator\n\n #\n # Pick the correct channels from the data\n #\n sel = _pick_channels_inverse_operator(evoked.ch_names, inv)\n logger.info('Applying inverse operator to \"%s\"...' % (evoked.comment,))\n logger.info(' Picked %d channels from the data' % len(sel))\n logger.info(' Computing inverse...')\n K, noise_norm, vertno, source_nn = _assemble_kernel(\n inv, label, method, pick_ori, use_cps=use_cps)\n sol = np.dot(K, evoked.data[sel]) # apply imaging kernel\n logger.info(' Computing residual...')\n # x̂(t) = G ĵ(t) = C ** 1/2 U Π w(t)\n # where the diagonal matrix Π has elements πk = λk γk\n Pi = inv['sing'] * inv['reginv']\n data_w = np.dot(inv['whitener'], # C ** -0.5\n np.dot(inv['proj'], evoked.data[sel]))\n w_t = np.dot(inv['eigen_fields']['data'], data_w) # U.T @ data\n data_est = np.dot(inv['colorer'], # C ** 0.5\n np.dot(inv['eigen_fields']['data'].T, # U\n Pi[:, np.newaxis] * w_t))\n data_est_w = np.dot(inv['whitener'], np.dot(inv['proj'], data_est))\n res_w = data_w - data_est_w\n var_exp = 1 - ((res_w * res_w.conj()).sum().real /\n (data_w * data_w.conj()).sum().real)\n logger.info(' Explained %5.1f%% variance' % (100 * var_exp,))\n\n if return_residual:\n residual = evoked.copy()\n residual.data[sel] -= data_est\n is_free_ori = (inv['source_ori'] == FIFF.FIFFV_MNE_FREE_ORI and\n pick_ori != 'normal')\n\n if is_free_ori and pick_ori != 'vector':\n logger.info(' Combining the current components...')\n sol = combine_xyz(sol)\n\n if noise_norm is not None:\n logger.info(' %s...' % (method,))\n if is_free_ori and pick_ori == 'vector':\n noise_norm = noise_norm.repeat(3, axis=0)\n sol *= noise_norm\n\n tstep = 1.0 / evoked.info['sfreq']\n tmin = float(evoked.times[0])\n subject = _subject_from_inverse(inv)\n src_type = _get_src_type(inv['src'], vertno)\n stc = _make_stc(sol, vertno, tmin=tmin, tstep=tstep, subject=subject,\n vector=(pick_ori == 'vector'), source_nn=source_nn,\n src_type=src_type)\n\n return (stc, residual) if return_residual else stc\n\n\n@verbose\ndef apply_inverse_raw(raw, inverse_operator, lambda2, method=\"dSPM\",\n label=None, start=None, stop=None, nave=1,\n time_func=None, pick_ori=None, buffer_size=None,\n prepared=False, method_params=None, use_cps=True,\n verbose=None):\n \"\"\"Apply inverse operator to Raw data.\n\n Parameters\n ----------\n raw : Raw object\n Raw data.\n inverse_operator : dict\n Inverse operator.\n lambda2 : float\n The regularization parameter.\n method : \"MNE\" | \"dSPM\" | \"sLORETA\" | \"eLORETA\"\n Use minimum norm, dSPM (default), sLORETA, or eLORETA.\n label : Label | None\n Restricts the source estimates to a given label. If None,\n source estimates will be computed for the entire source space.\n start : int\n Index of first time sample (index not time is seconds).\n stop : int\n Index of first time sample not to include (index not time is seconds).\n nave : int\n Number of averages used to regularize the solution.\n Set to 1 on raw data.\n time_func : callable\n Linear function applied to sensor space time series.\n %(pick_ori)s\n buffer_size : int (or None)\n If not None, the computation of the inverse and the combination of the\n current components is performed in segments of length buffer_size\n samples. While slightly slower, this is useful for long datasets as it\n reduces the memory requirements by approx. a factor of 3 (assuming\n buffer_size << data length).\n Note that this setting has no effect for fixed-orientation inverse\n operators.\n prepared : bool\n If True, do not call :func:`prepare_inverse_operator`.\n method_params : dict | None\n Additional options for eLORETA. See Notes of :func:`apply_inverse`.\n\n .. versionadded:: 0.16\n %(use_cps_restricted)s\n\n .. versionadded:: 0.20\n %(verbose)s\n\n Returns\n -------\n stc : SourceEstimate | VectorSourceEstimate | VolSourceEstimate\n The source estimates.\n\n See Also\n --------\n apply_inverse_epochs : Apply inverse operator to epochs object.\n apply_inverse : Apply inverse operator to evoked object.\n \"\"\"\n _validate_type(raw, BaseRaw, 'raw')\n _check_reference(raw, inverse_operator['info']['ch_names'])\n _check_option('method', method, INVERSE_METHODS)\n _check_ori(pick_ori, inverse_operator['source_ori'],\n inverse_operator['src'])\n _check_ch_names(inverse_operator, raw.info)\n\n #\n # Set up the inverse according to the parameters\n #\n inv = _check_or_prepare(inverse_operator, nave, lambda2, method,\n method_params, prepared)\n\n #\n # Pick the correct channels from the data\n #\n sel = _pick_channels_inverse_operator(raw.ch_names, inv)\n logger.info('Applying inverse to raw...')\n logger.info(' Picked %d channels from the data' % len(sel))\n logger.info(' Computing inverse...')\n\n data, times = raw[sel, start:stop]\n\n if time_func is not None:\n data = time_func(data)\n\n K, noise_norm, vertno, source_nn = _assemble_kernel(\n inv, label, method, pick_ori, use_cps)\n\n is_free_ori = (inverse_operator['source_ori'] ==\n FIFF.FIFFV_MNE_FREE_ORI and pick_ori != 'normal')\n\n if buffer_size is not None and is_free_ori:\n # Process the data in segments to conserve memory\n n_seg = int(np.ceil(data.shape[1] / float(buffer_size)))\n logger.info(' computing inverse and combining the current '\n 'components (using %d segments)...' % (n_seg))\n\n # Allocate space for inverse solution\n n_times = data.shape[1]\n\n n_dipoles = K.shape[0] if pick_ori == 'vector' else K.shape[0] // 3\n sol = np.empty((n_dipoles, n_times), dtype=np.result_type(K, data))\n\n for pos in range(0, n_times, buffer_size):\n sol_chunk = np.dot(K, data[:, pos:pos + buffer_size])\n if pick_ori != 'vector':\n sol_chunk = combine_xyz(sol_chunk)\n sol[:, pos:pos + buffer_size] = sol_chunk\n\n logger.info(' segment %d / %d done..'\n % (pos / buffer_size + 1, n_seg))\n else:\n sol = np.dot(K, data)\n if is_free_ori and pick_ori != 'vector':\n logger.info(' combining the current components...')\n sol = combine_xyz(sol)\n if noise_norm is not None:\n if pick_ori == 'vector' and is_free_ori:\n noise_norm = noise_norm.repeat(3, axis=0)\n sol *= noise_norm\n\n tmin = float(times[0])\n tstep = 1.0 / raw.info['sfreq']\n subject = _subject_from_inverse(inverse_operator)\n src_type = _get_src_type(inverse_operator['src'], vertno)\n stc = _make_stc(sol, vertno, tmin=tmin, tstep=tstep, subject=subject,\n vector=(pick_ori == 'vector'), source_nn=source_nn,\n src_type=src_type)\n logger.info('[done]')\n\n return stc\n\n\ndef _apply_inverse_epochs_gen(epochs, inverse_operator, lambda2, method='dSPM',\n label=None, nave=1, pick_ori=None,\n prepared=False, method_params=None,\n use_cps=True, verbose=None):\n \"\"\"Generate inverse solutions for epochs. Used in apply_inverse_epochs.\"\"\"\n _validate_type(epochs, BaseEpochs, 'epochs')\n _check_option('method', method, INVERSE_METHODS)\n _check_ori(pick_ori, inverse_operator['source_ori'],\n inverse_operator['src'])\n _check_ch_names(inverse_operator, epochs.info)\n\n #\n # Set up the inverse according to the parameters\n #\n inv = _check_or_prepare(inverse_operator, nave, lambda2, method,\n method_params, prepared)\n\n #\n # Pick the correct channels from the data\n #\n sel = _pick_channels_inverse_operator(epochs.ch_names, inv)\n logger.info('Picked %d channels from the data' % len(sel))\n logger.info('Computing inverse...')\n K, noise_norm, vertno, source_nn = _assemble_kernel(\n inv, label, method, pick_ori, use_cps)\n\n tstep = 1.0 / epochs.info['sfreq']\n tmin = epochs.times[0]\n\n is_free_ori = not (is_fixed_orient(inverse_operator) or\n pick_ori == 'normal')\n\n if pick_ori == 'vector' and noise_norm is not None:\n noise_norm = noise_norm.repeat(3, axis=0)\n\n if not is_free_ori and noise_norm is not None:\n # premultiply kernel with noise normalization\n K *= noise_norm\n\n subject = _subject_from_inverse(inverse_operator)\n try:\n total = ' / %d' % (len(epochs),) # len not always defined\n except RuntimeError:\n total = ' / %d (at most)' % (len(epochs.events),)\n for k, e in enumerate(epochs):\n logger.info('Processing epoch : %d%s' % (k + 1, total))\n if is_free_ori:\n # Compute solution and combine current components (non-linear)\n sol = np.dot(K, e[sel]) # apply imaging kernel\n\n if pick_ori != 'vector':\n logger.info('combining the current components...')\n sol = combine_xyz(sol)\n\n if noise_norm is not None:\n sol *= noise_norm\n else:\n # Linear inverse: do computation here or delayed\n if len(sel) < K.shape[1]:\n sol = (K, e[sel])\n else:\n sol = np.dot(K, e[sel])\n\n src_type = _get_src_type(inverse_operator['src'], vertno)\n stc = _make_stc(sol, vertno, tmin=tmin, tstep=tstep, subject=subject,\n vector=(pick_ori == 'vector'), source_nn=source_nn,\n src_type=src_type)\n\n yield stc\n\n logger.info('[done]')\n\n\n@verbose\ndef apply_inverse_epochs(epochs, inverse_operator, lambda2, method=\"dSPM\",\n label=None, nave=1, pick_ori=None,\n return_generator=False, prepared=False,\n method_params=None, use_cps=True, verbose=None):\n \"\"\"Apply inverse operator to Epochs.\n\n Parameters\n ----------\n epochs : Epochs object\n Single trial epochs.\n inverse_operator : dict\n Inverse operator.\n lambda2 : float\n The regularization parameter.\n method : \"MNE\" | \"dSPM\" | \"sLORETA\" | \"eLORETA\"\n Use minimum norm, dSPM (default), sLORETA, or eLORETA.\n label : Label | None\n Restricts the source estimates to a given label. If None,\n source estimates will be computed for the entire source space.\n nave : int\n Number of averages used to regularize the solution.\n Set to 1 on single Epoch by default.\n %(pick_ori)s\n return_generator : bool\n Return a generator object instead of a list. This allows iterating\n over the stcs without having to keep them all in memory.\n prepared : bool\n If True, do not call :func:`prepare_inverse_operator`.\n method_params : dict | None\n Additional options for eLORETA. See Notes of :func:`apply_inverse`.\n\n .. versionadded:: 0.16\n %(use_cps_restricted)s\n\n .. versionadded:: 0.20\n %(verbose)s\n\n Returns\n -------\n stc : list of (SourceEstimate | VectorSourceEstimate | VolSourceEstimate)\n The source estimates for all epochs.\n\n See Also\n --------\n apply_inverse_raw : Apply inverse operator to raw object.\n apply_inverse : Apply inverse operator to evoked object.\n \"\"\"\n stcs = _apply_inverse_epochs_gen(\n epochs, inverse_operator, lambda2, method=method, label=label,\n nave=nave, pick_ori=pick_ori, verbose=verbose, prepared=prepared,\n method_params=method_params, use_cps=use_cps)\n\n if not return_generator:\n # return a list\n stcs = [stc for stc in stcs]\n\n return stcs\n\n\n@verbose\ndef apply_inverse_cov(cov, info, inverse_operator, nave=1, lambda2=1 / 9,\n method=\"dSPM\", pick_ori=None, prepared=False,\n label=None, method_params=None, use_cps=True,\n verbose=None):\n \"\"\"Apply inverse operator to covariance data.\n\n Parameters\n ----------\n cov : instance of Covariance\n Covariance data, computed on the time segment for which to compute\n source power.\n info : dict\n The measurement info to specify the channels to include.\n inverse_operator : instance of InverseOperator\n Inverse operator.\n nave : int\n Number of averages used to regularize the solution.\n lambda2 : float\n The regularization parameter.\n method : \"MNE\" | \"dSPM\" | \"sLORETA\" | \"eLORETA\"\n Use minimum norm, dSPM (default), sLORETA, or eLORETA.\n %(pick_ori-novec)s\n prepared : bool\n If True, do not call :func:`prepare_inverse_operator`.\n label : Label | None\n Restricts the source estimates to a given label. If None,\n source estimates will be computed for the entire source space.\n method_params : dict | None\n Additional options for eLORETA. See Notes for details.\n %(use_cps)s\n %(verbose)s\n\n Returns\n -------\n stc : SourceEstimate | VectorSourceEstimate | VolSourceEstimate\n The source estimates.\n\n See Also\n --------\n apply_inverse : Apply inverse operator to evoked object.\n apply_inverse_raw : Apply inverse operator to raw object.\n apply_inverse_epochs : Apply inverse operator to epochs object.\n\n Notes\n -----\n .. versionadded:: 0.20\n \"\"\"\n _validate_type(cov, Covariance, cov)\n _validate_type(inverse_operator, InverseOperator, 'inverse_operator')\n sel = _pick_channels_inverse_operator(cov['names'], inverse_operator)\n use_names = [cov['names'][idx] for idx in sel]\n info = pick_info(\n info, pick_channels(info['ch_names'], use_names, ordered=True))\n evoked = EvokedArray(\n np.eye(len(info['ch_names'])), info, nave=nave, comment='cov')\n is_free_ori = (inverse_operator['source_ori'] == FIFF.FIFFV_MNE_FREE_ORI)\n _check_option('pick_ori', pick_ori, (None, 'normal'))\n if is_free_ori and pick_ori is None:\n use_ori = 'vector'\n combine = True\n else:\n use_ori = pick_ori\n combine = False\n stc = _apply_inverse(\n evoked, inverse_operator, lambda2, method, use_ori, prepared, label,\n method_params, return_residual=False, use_cps=use_cps)\n # apply (potentially rotated in the vector case) operator twice\n K = np.reshape(stc.data, (-1, stc.data.shape[-1]))\n # diagonal entries of A @ B are given by (A * B.T).sum(axis=1), so this is\n # equivalent to np.diag(K @ cov.data[sel][:, sel] @ K.T)[:, np.newaxis]:\n sol = cov.data[sel][:, sel] @ K.T\n sol = np.sum(K * sol.T, axis=1, keepdims=True)\n # Reshape back to (n_src, ..., 1)\n sol.shape = stc.data.shape[:-1] + (1,)\n stc = stc.__class__(\n sol, stc.vertices, stc.tmin, stc.tstep, stc.subject, stc.verbose)\n if combine: # combine the three directions\n logger.info(' Combining the current components...')\n np.sqrt(stc.data, out=stc.data)\n stc = stc.magnitude()\n stc.data *= stc.data\n logger.info('[done]')\n return stc\n\n\n###############################################################################\n# Assemble the inverse operator\n\ndef _prepare_forward(forward, info, noise_cov, fixed, loose, rank, pca,\n use_cps, exp, limit_depth_chs, combine_xyz,\n allow_fixed_depth, limit):\n \"\"\"Prepare a gain matrix and noise covariance for localization.\"\"\"\n # Steps (according to MNE-C, we change the order of various steps\n # because our I/O is already done, and we create the objects\n # on the fly more easily):\n #\n # 1. Read the bad channels\n # 2. Read the necessary data from the forward solution matrix file\n # 3. Load the projection data\n # 4. Load the sensor noise covariance matrix and attach it to the forward\n # 5. Compose the depth-weighting matrix\n # 6. Compose the source covariance matrix\n # 7. Apply fMRI weighting (not done)\n # 8. Apply the linear projection to the forward solution\n # 9. Apply whitening to the forward computation matrix\n # 10. Exclude the source space points within the labels (not done)\n # 11. Do appropriate source weighting to the forward computation matrix\n #\n\n # make a copy immediately so we do it exactly once\n forward = forward.copy()\n\n # Deal with \"fixed\" and \"loose\"\n loose = _triage_loose(forward['src'], loose, fixed)\n del fixed\n\n # Deal with \"depth\"\n if exp is not None:\n exp = float(exp)\n if not (0 <= exp <= 1):\n raise ValueError('depth exponent should be a scalar between '\n '0 and 1, got %s' % (exp,))\n exp = exp or None # alias 0. -> None\n\n # put the forward solution in correct orientation\n # (delaying for the case of fixed ori with depth weighting if\n # allow_fixed_depth is True)\n if loose.get('surface', 1.) == 0. and len(loose) == 1:\n if not is_fixed_orient(forward):\n if allow_fixed_depth:\n # can convert now\n logger.info('Converting forward solution to fixed orietnation')\n convert_forward_solution(\n forward, force_fixed=True, use_cps=True, copy=False)\n elif exp is not None and not allow_fixed_depth:\n raise ValueError(\n 'For a fixed orientation inverse solution with depth '\n 'weighting, the forward solution must be free-orientation and '\n 'in surface orientation')\n else: # loose or free ori\n if is_fixed_orient(forward):\n raise ValueError(\n 'Forward operator has fixed orientation and can only '\n 'be used to make a fixed-orientation inverse '\n 'operator.')\n if loose.get('surface', 1.) < 1. and not forward['surf_ori']:\n logger.info('Converting forward solution to surface orientation')\n convert_forward_solution(\n forward, surf_ori=True, use_cps=use_cps, copy=False)\n\n forward, info_picked = _select_orient_forward(forward, info, noise_cov,\n copy=False)\n logger.info(\"Selected %d channels\" % (len(info_picked['ch_names'],)))\n\n if exp is None:\n depth_prior = None\n else:\n depth_prior = compute_depth_prior(\n forward, info_picked, exp=exp, limit_depth_chs=limit_depth_chs,\n combine_xyz=combine_xyz, limit=limit, noise_cov=noise_cov)\n\n # Deal with fixed orientation forward / inverse\n if loose.get('surface', 1.) == 0. and len(loose) == 1:\n orient_prior = None\n if not is_fixed_orient(forward):\n if depth_prior is not None:\n # Convert the depth prior into a fixed-orientation one\n logger.info(' Picked elements from a free-orientation '\n 'depth-weighting prior into the fixed-orientation '\n 'one')\n depth_prior = depth_prior[2::3]\n convert_forward_solution(\n forward, surf_ori=True, force_fixed=True,\n use_cps=use_cps, copy=False)\n else:\n if loose.get('surface', 1.) < 1:\n assert forward['surf_ori']\n # In theory we could have orient_prior=None for loose=1., but\n # the MNE-C code does not do this\n orient_prior = compute_orient_prior(forward, loose=loose)\n\n logger.info('Whitening the forward solution.')\n noise_cov = prepare_noise_cov(\n noise_cov, info, info_picked['ch_names'], rank)\n whitener, _ = compute_whitener(\n noise_cov, info, info_picked['ch_names'], pca=pca, verbose=False,\n rank=rank)\n gain = np.dot(whitener, forward['sol']['data'])\n\n logger.info('Creating the source covariance matrix')\n source_std = np.ones(gain.shape[1], dtype=gain.dtype)\n if depth_prior is not None:\n source_std *= depth_prior\n if orient_prior is not None:\n source_std *= orient_prior\n np.sqrt(source_std, out=source_std)\n gain *= source_std\n # Adjusting Source Covariance matrix to make trace of G*R*G' equal\n # to number of sensors.\n logger.info('Adjusting source covariance matrix.')\n trace_GRGT = linalg.norm(gain, ord='fro') ** 2\n n_nzero = (noise_cov['eig'] > 0).sum()\n scale = np.sqrt(n_nzero / trace_GRGT)\n source_std *= scale\n gain *= scale\n\n return (forward, info_picked, gain, depth_prior, orient_prior, source_std,\n trace_GRGT, noise_cov, whitener)\n\n\n@verbose\ndef make_inverse_operator(info, forward, noise_cov, loose='auto', depth=0.8,\n fixed='auto', rank=None, use_cps=True, verbose=None):\n \"\"\"Assemble inverse operator.\n\n Parameters\n ----------\n info : dict\n The measurement info to specify the channels to include.\n Bad channels in info['bads'] are not used.\n forward : dict\n Forward operator.\n noise_cov : instance of Covariance\n The noise covariance matrix.\n %(loose)s\n %(depth)s\n fixed : bool | 'auto'\n Use fixed source orientations normal to the cortical mantle. If True,\n the loose parameter must be \"auto\" or 0. If 'auto', the loose value\n is used.\n %(rank_None)s\n %(use_cps)s\n %(verbose)s\n\n Returns\n -------\n inv : instance of InverseOperator\n Inverse operator.\n\n Notes\n -----\n For different sets of options (**loose**, **depth**, **fixed**) to work,\n the forward operator must have been loaded using a certain configuration\n (i.e., with **force_fixed** and **surf_ori** set appropriately). For\n example, given the desired inverse type (with representative choices\n of **loose** = 0.2 and **depth** = 0.8 shown in the table in various\n places, as these are the defaults for those parameters):\n\n +---------------------+-----------+-----------+-----------+-----------------+--------------+\n | Inverse desired | Forward parameters allowed |\n +=====================+===========+===========+===========+=================+==============+\n | | **loose** | **depth** | **fixed** | **force_fixed** | **surf_ori** |\n +---------------------+-----------+-----------+-----------+-----------------+--------------+\n | | Loose constraint, | 0.2 | 0.8 | False | False | True |\n | | Depth weighted | | | | | |\n +---------------------+-----------+-----------+-----------+-----------------+--------------+\n | | Loose constraint | 0.2 | None | False | False | True |\n +---------------------+-----------+-----------+-----------+-----------------+--------------+\n | | Free orientation, | 1.0 | 0.8 | False | False | True |\n | | Depth weighted | | | | | |\n +---------------------+-----------+-----------+-----------+-----------------+--------------+\n | | Free orientation | 1.0 | None | False | False | True | False |\n +---------------------+-----------+-----------+-----------+-----------------+--------------+\n | | Fixed constraint, | 0.0 | 0.8 | True | False | True |\n | | Depth weighted | | | | | |\n +---------------------+-----------+-----------+-----------+-----------------+--------------+\n | | Fixed constraint | 0.0 | None | True | True | True |\n +---------------------+-----------+-----------+-----------+-----------------+--------------+\n\n Also note that, if the source space (as stored in the forward solution)\n has patch statistics computed, these are used to improve the depth\n weighting. Thus slightly different results are to be expected with\n and without this information.\n \"\"\" # noqa: E501\n # For now we always have pca='white'. It does not seem to affect\n # calculations and is also backward-compatible with MNE-C\n depth = _check_depth(depth, 'depth_mne')\n forward, gain_info, gain, depth_prior, orient_prior, source_std, \\\n trace_GRGT, noise_cov, _ = _prepare_forward(\n forward, info, noise_cov, fixed, loose, rank, pca='white',\n use_cps=use_cps, **depth)\n # no need to copy any attributes of forward here because there is\n # a deepcopy in _prepare_forward\n inv = dict(\n projs=deepcopy(gain_info['projs']), eigen_leads_weighted=False,\n source_ori=forward['source_ori'], mri_head_t=forward['mri_head_t'],\n nsource=forward['nsource'], units='Am',\n coord_frame=forward['coord_frame'], source_nn=forward['source_nn'],\n src=forward['src'], fmri_prior=None, info=deepcopy(forward['info']))\n inv['info']['bads'] = [bad for bad in info['bads']\n if bad in forward['info']['ch_names']]\n inv['info']._check_consistency()\n del fixed, loose, depth, use_cps, forward\n\n # Decompose the combined matrix\n logger.info('Computing SVD of whitened and weighted lead field matrix.')\n eigen_fields, sing, eigen_leads = _safe_svd(gain, full_matrices=False)\n del gain\n logger.info(' largest singular value = %g' % np.max(sing))\n logger.info(' scaling factor to adjust the trace = %g' % trace_GRGT)\n\n # MNE-ify everything for output\n eigen_fields = dict(data=eigen_fields.T, col_names=gain_info['ch_names'],\n row_names=[], nrow=eigen_fields.shape[1],\n ncol=eigen_fields.shape[0])\n eigen_leads = dict(data=eigen_leads.T, nrow=eigen_leads.shape[1],\n ncol=eigen_leads.shape[0], row_names=[],\n col_names=[])\n has_meg = False\n has_eeg = False\n for idx in range(gain_info['nchan']):\n ch_type = channel_type(gain_info, idx)\n if ch_type == 'eeg':\n has_eeg = True\n if (ch_type == 'mag') or (ch_type == 'grad'):\n has_meg = True\n if has_eeg and has_meg:\n methods = FIFF.FIFFV_MNE_MEG_EEG\n elif has_meg:\n methods = FIFF.FIFFV_MNE_MEG\n else:\n methods = FIFF.FIFFV_MNE_EEG\n\n if orient_prior is not None:\n orient_prior = dict(data=orient_prior,\n kind=FIFF.FIFFV_MNE_ORIENT_PRIOR_COV,\n bads=[], diag=True, names=[], eig=None,\n eigvec=None, dim=orient_prior.size, nfree=1,\n projs=[])\n if depth_prior is not None:\n depth_prior = dict(data=depth_prior,\n kind=FIFF.FIFFV_MNE_DEPTH_PRIOR_COV,\n bads=[], diag=True, names=[], eig=None,\n eigvec=None, dim=depth_prior.size, nfree=1,\n projs=[])\n source_cov = dict(data=source_std * source_std, dim=source_std.size,\n kind=FIFF.FIFFV_MNE_SOURCE_COV, diag=True,\n names=[], projs=[], eig=None, eigvec=None,\n nfree=1, bads=[])\n inv.update(\n eigen_fields=eigen_fields, eigen_leads=eigen_leads, sing=sing, nave=1.,\n depth_prior=depth_prior, source_cov=source_cov, noise_cov=noise_cov,\n orient_prior=orient_prior, methods=methods)\n return InverseOperator(inv)\n\n\ndef _compute_reginv(inv, lambda2):\n \"\"\"Safely compute reginv from sing.\"\"\"\n sing = np.array(inv['sing'], dtype=np.float64)\n reginv = np.zeros_like(sing)\n n_nzero = compute_rank_inverse(inv)\n sing = sing[:n_nzero]\n with np.errstate(invalid='ignore'): # if lambda2==0\n reginv[:n_nzero] = np.where(\n sing > 0, sing / (sing ** 2 + lambda2), 0)\n return reginv\n\n\ndef compute_rank_inverse(inv):\n \"\"\"Compute the rank of a linear inverse operator (MNE, dSPM, etc.).\n\n Parameters\n ----------\n inv : instance of InverseOperator\n The inverse operator.\n\n Returns\n -------\n rank : int\n The rank of the inverse operator.\n \"\"\"\n # this code shortened from prepare_inverse_operator\n eig = inv['noise_cov']['eig']\n if not inv['noise_cov']['diag']:\n rank = np.sum(eig > 0)\n else:\n ncomp = make_projector(inv['projs'], inv['noise_cov']['names'])[1]\n rank = inv['noise_cov']['dim'] - ncomp\n return rank\n\n\n# #############################################################################\n# SNR Estimation\n\n@verbose\ndef estimate_snr(evoked, inv, verbose=None):\n r\"\"\"Estimate the SNR as a function of time for evoked data.\n\n Parameters\n ----------\n evoked : instance of Evoked\n Evoked instance.\n inv : instance of InverseOperator\n The inverse operator.\n %(verbose)s\n\n Returns\n -------\n snr : ndarray, shape (n_times,)\n The SNR estimated from the whitened data (i.e., GFP of whitened data).\n snr_est : ndarray, shape (n_times,)\n The SNR estimated using the mismatch between the unregularized\n solution and the regularized solution.\n\n Notes\n -----\n ``snr_est`` is estimated by using different amounts of inverse\n regularization and checking the mismatch between predicted and\n measured whitened data.\n\n In more detail, given our whitened inverse obtained from SVD:\n\n .. math::\n\n \\tilde{M} = R^\\frac{1}{2}V\\Gamma U^T\n\n The values in the diagonal matrix :math:`\\Gamma` are expressed in terms\n of the chosen regularization :math:`\\lambda\\approx\\frac{1}{\\rm{SNR}^2}`\n and singular values :math:`\\lambda_k` as:\n\n .. math::\n\n \\gamma_k = \\frac{1}{\\lambda_k}\\frac{\\lambda_k^2}{\\lambda_k^2 + \\lambda^2}\n\n We also know that our predicted data is given by:\n\n .. math::\n\n \\hat{x}(t) = G\\hat{j}(t)=C^\\frac{1}{2}U\\Pi w(t)\n\n And thus our predicted whitened data is just:\n\n .. math::\n\n \\hat{w}(t) = U\\Pi w(t)\n\n Where :math:`\\Pi` is diagonal with entries entries:\n\n .. math::\n\n \\lambda_k\\gamma_k = \\frac{\\lambda_k^2}{\\lambda_k^2 + \\lambda^2}\n\n If we use no regularization, note that :math:`\\Pi` is just the\n identity matrix. Here we test the squared magnitude of the difference\n between unregularized solution and regularized solutions, choosing the\n biggest regularization that achieves a :math:`\\chi^2`-test significance\n of 0.001.\n\n .. versionadded:: 0.9.0\n \"\"\" # noqa: E501\n from scipy.stats import chi2\n _check_reference(evoked, inv['info']['ch_names'])\n _check_ch_names(inv, evoked.info)\n inv = prepare_inverse_operator(inv, evoked.nave, 1. / 9., 'MNE',\n copy='non-src')\n sel = _pick_channels_inverse_operator(evoked.ch_names, inv)\n logger.info('Picked %d channels from the data' % len(sel))\n data_white = np.dot(inv['whitener'], np.dot(inv['proj'], evoked.data[sel]))\n data_white_ef = np.dot(inv['eigen_fields']['data'], data_white)\n n_ch, n_times = data_white.shape\n\n # Adapted from mne_analyze/regularization.c, compute_regularization\n n_ch_eff = compute_rank_inverse(inv)\n n_zero = n_ch - n_ch_eff\n logger.info('Effective nchan = %d - %d = %d'\n % (n_ch, n_zero, n_ch_eff))\n del n_ch\n signal = np.sum(data_white ** 2, axis=0) # sum of squares across channels\n snr = signal / n_ch_eff\n\n # Adapted from noise_regularization\n lambda2_est = np.empty(n_times)\n lambda2_est.fill(10.)\n remaining = np.ones(n_times, bool)\n\n # deal with low SNRs\n bad = (snr <= 1)\n lambda2_est[bad] = np.inf\n remaining[bad] = False\n\n # parameters\n lambda_mult = 0.99\n sing2 = (inv['sing'] * inv['sing'])[:, np.newaxis]\n val = chi2.isf(1e-3, n_ch_eff)\n for n_iter in range(1000):\n # get_mne_weights (ew=error_weights)\n # (split newaxis creation here for old numpy)\n f = sing2 / (sing2 + lambda2_est[np.newaxis][:, remaining])\n f[inv['sing'] == 0] = 0\n ew = data_white_ef[:, remaining] * (1.0 - f)\n # check condition\n err = np.sum(ew * ew, axis=0)\n remaining[np.where(remaining)[0][err < val]] = False\n if not remaining.any():\n break\n lambda2_est[remaining] *= lambda_mult\n else:\n warn('SNR estimation did not converge')\n snr_est = 1.0 / np.sqrt(lambda2_est)\n snr = np.sqrt(snr)\n return snr, snr_est\n"
] |
[
[
"numpy.dot",
"scipy.linalg.get_blas_funcs",
"numpy.sqrt",
"numpy.max",
"numpy.zeros_like",
"numpy.iscomplexobj",
"numpy.where",
"numpy.reshape",
"numpy.eye",
"numpy.matmul",
"scipy.linalg.norm",
"numpy.zeros",
"numpy.errstate",
"numpy.array",
"numpy.sum",
"scipy.stats.chi2.isf",
"numpy.abs",
"numpy.ones",
"numpy.result_type",
"numpy.empty"
]
] |
alanphys/pylinac
|
[
"9b2dabe85d3038a9ec922c77bbb943b4e06dbdda"
] |
[
"pylinac/field_analysis.py"
] |
[
"\"\"\"Module for performing analysis of images or 2D arrays for parameters such as flatness and symmetry.\"\"\"\nimport dataclasses\nimport io\nimport os.path as osp\nimport warnings\nfrom dataclasses import dataclass\nfrom enum import Enum\nfrom math import floor, ceil\nfrom typing import Union, Optional, Tuple, BinaryIO\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom pylinac.core.utilities import open_path, ResultBase\nfrom .core import image, pdf\nfrom .core.exceptions import NotAnalyzed\nfrom .core.geometry import Rectangle\nfrom .core.hill import Hill\nfrom .core.io import retrieve_demo_file, SNCProfiler\nfrom .core.profile import SingleProfile, Edge, Interpolation, Normalization\nfrom .settings import get_dicom_cmap\n\n\ndef flatness_dose_difference(profile: SingleProfile, in_field_ratio: float = 0.8, **kwargs) -> float:\n \"\"\"The Varian specification for calculating flatness. See :ref:`varian_protocol`. \"\"\"\n try:\n dmax = profile.field_calculation(in_field_ratio=in_field_ratio, calculation='max')\n dmin = profile.field_calculation(in_field_ratio=in_field_ratio, calculation='min')\n except IOError:\n raise ValueError(\n \"An error was encountered in the flatness calculation. The image is likely inverted. Try inverting the image before analysis with <instance>.image.invert().\")\n flatness = 100 * abs(dmax - dmin) / (dmax + dmin)\n return flatness\n\n\ndef flatness_dose_ratio(profile: SingleProfile, in_field_ratio: float = 0.8, **kwargs) -> float:\n \"\"\"The Elekta specification for calculating flatness. See :ref:`elekta_protocol`. \"\"\"\n try:\n dmax = profile.field_calculation(in_field_ratio=in_field_ratio, calculation='max')\n dmin = profile.field_calculation(in_field_ratio=in_field_ratio, calculation='min')\n except ValueError:\n raise ValueError(\n \"An error was encountered in the flatness calculation. The image is likely inverted. Try inverting the image before analysis with <instance>.image.invert().\")\n flatness = 100 * (dmax / dmin)\n return flatness\n\n\ndef plot_flatness(instance, profile: SingleProfile, axis: plt.Axes) -> None:\n \"\"\"Plot flatness parameters. Applies to both flatness dose ratio and dose difference.\"\"\"\n data = profile.field_data(in_field_ratio=instance._in_field_ratio)\n axis.axhline(np.max(data['field values']), color='g', linestyle='-.', label='Flatness region')\n axis.axhline(np.min(data['field values']), color='g', linestyle='-.')\n\n\ndef symmetry_point_difference(profile: SingleProfile, in_field_ratio: float, **kwargs) -> float:\n \"\"\"Calculation of symmetry by way of point difference equidistant from the CAX. See :ref:`varian_protocol`.\n\n A negative value means the right side is higher. A positive value means the left side is higher.\n \"\"\"\n field = profile.field_data(in_field_ratio=in_field_ratio)\n field_values = field['field values']\n cax_value = field['beam center value (@rounded)']\n\n def calc_sym(lt, rt, cax) -> float:\n return 100 * (lt - rt) / cax\n\n # get value w/ max magnitude\n sym_vals = [calc_sym(lt, rt, cax_value) for lt, rt in zip(field_values, field_values[::-1])]\n max_sym_idx = np.argmax(np.abs(sym_vals))\n return sym_vals[max_sym_idx]\n\n\ndef plot_symmetry_point_difference(instance, profile: SingleProfile, axis: plt.Axes) -> None:\n \"\"\"Plotting of the symmetry point difference.\"\"\"\n\n def calc_sym(lt, rt, cax) -> float:\n return 100 * abs(lt - rt) / cax\n\n _plot_sym_common(instance, calc_sym, profile, axis, label='Symmetry (%)', padding=(5, 0.5))\n\n\ndef _plot_sym_common(instance, calc_func: callable, profile: SingleProfile, axis: plt.Axes, label: str, padding: tuple) -> None:\n field = profile.field_data(in_field_ratio=instance._in_field_ratio)\n field_values = field['field values']\n left_idx = field['left index (rounded)']\n right_idx = field['right index (rounded)']\n cax_value = field['beam center value (@rounded)']\n\n # same calc as PDQ and point difference, except we find the INDEX where the symmetry is maximum\n sym_values = [calc_func(lt, rt, cax_value) for lt, rt, _ in zip(field_values, field_values[::-1], range(int(round(len(field_values)/2))))]\n\n idx = np.argmax(sym_values)\n axis.plot(field['left index (rounded)']+idx, profile.values[field['left index (rounded)']+idx], '*', color='red', label='Symmetry max')\n axis.plot(field['right index (rounded)']-idx, profile.values[field['right index (rounded)']-idx], '*', color='red')\n sec_ax = axis.twinx()\n sec_ax.set_ylabel(label)\n\n # squish the secondary graph so it's not so large-looking\n ylim_top = max(sym_values) + padding[0]\n ylim_bottom = min(sym_values) - padding[1]\n sec_ax.set_ylim(ylim_bottom, ylim_top)\n left_end = int(round(left_idx+(right_idx-left_idx)/2))\n sec_ax.plot(range(left_end, left_end + len(sym_values)), sym_values[::-1])\n\n\ndef plot_symmetry_pdq(instance, profile: SingleProfile, axis: plt.Axes) -> None:\n \"\"\"Plotting of the symmetry point difference quotient.\"\"\"\n\n def calc_sym(lt, rt, _) -> float:\n return max(abs(lt / rt), abs(rt / lt))\n\n _plot_sym_common(instance, calc_sym, profile, axis, label='Symmetry (AU)', padding=(0.05, 0.01))\n\n\ndef symmetry_pdq_iec(profile: SingleProfile, in_field_ratio: float, **kwargs) -> float:\n \"\"\"Symmetry calculation by way of PDQ IEC. See :ref:`elekta_protocol`.\n\n A negative value means the right side is higher. A positive value means the left side is higher.\n \"\"\"\n field = profile.field_data(in_field_ratio=in_field_ratio)\n field_values = field['field values']\n\n def calc_sym(lt, rt) -> float:\n sym1 = lt/rt\n sym2 = rt/lt\n if abs(sym1) > abs(sym2):\n sign = np.sign(sym1)\n else:\n sign = np.sign(sym2)\n return max(abs(lt / rt), abs(rt / lt)) * sign\n\n sym_values = [calc_sym(lt, rt) for lt, rt in zip(field_values, field_values[::-1])]\n sym_idx = np.argmax(np.abs(sym_values))\n\n return sym_values[sym_idx]\n\n\ndef symmetry_area(profile: SingleProfile, in_field_ratio: float, **kwargs) -> float:\n \"\"\"Ratio of the area under the left and right profile segments. See :ref:`siemens_protocol`.\n\n A negative value indicates the right side is higher; a positive value indicates the left side is higher.\n \"\"\"\n data = profile.field_data(in_field_ratio=in_field_ratio)\n cax_idx = data['beam center index (exact)'] - data['left index (exact)']\n area_left = np.sum(data['field values'][:floor(cax_idx)])\n area_right = np.sum(data['field values'][ceil(cax_idx):])\n symmetry = 100 * (area_left - area_right) / (area_left + area_right)\n return symmetry\n\n\ndef plot_symmetry_area(instance, profile: SingleProfile, axis: plt.Axes) -> None:\n \"\"\"PLot the symmetry area.\"\"\"\n data = profile.field_data(in_field_ratio=instance._in_field_ratio)\n cax_idx = data['beam center index (exact)']\n left_idx = data['left index (rounded)']\n right_idx = data['right index (rounded)']\n\n axis.fill_between(range(left_idx, floor(cax_idx)), data['field values'][:floor(cax_idx)-left_idx], color='green', alpha=0.1, label='Left Area')\n axis.fill_between(range(ceil(cax_idx), right_idx), data['field values'][ceil(cax_idx)-left_idx:], color='slateblue', alpha=0.1, label='Right Area')\n\n\nvarian_protocol = {\n 'symmetry': {'calc': symmetry_point_difference, 'unit': '%', 'plot': plot_symmetry_point_difference},\n 'flatness': {'calc': flatness_dose_difference, 'unit': '%', 'plot': plot_flatness},\n}\nelekta_protocol = {\n 'symmetry': {'calc': symmetry_pdq_iec, 'unit': '', 'plot': plot_symmetry_pdq},\n 'flatness': {'calc': flatness_dose_ratio, 'unit': '', 'plot': plot_flatness},\n}\nsiemens_protocol = {\n 'symmetry': {'calc': symmetry_area, 'unit': '', 'plot': plot_symmetry_area},\n 'flatness': {'calc': flatness_dose_difference, 'unit': '', 'plot': plot_flatness},\n}\n\n\nclass Protocol(Enum):\n \"\"\"Protocols to analyze additional metrics of the field. See :ref:`analysis_definitions`\"\"\"\n NONE = {} #:\n VARIAN = varian_protocol #:\n SIEMENS = siemens_protocol #:\n ELEKTA = elekta_protocol #:\n\n\nclass Centering(Enum):\n \"\"\"See :ref:`centering`\"\"\"\n MANUAL = 'manual' #:\n BEAM_CENTER = 'Beam center' #:\n GEOMETRIC_CENTER = 'Geometric center' #:\n\n\n@dataclass\nclass FieldResults(ResultBase):\n \"\"\"This class should not be called directly. It is returned by the ``results_data()`` method.\n It is a dataclass under the hood and thus comes with all the dunder magic.\n\n Use the following attributes as normal class attributes.\n\n In addition to the below attrs, custom protocol data will also be attached as\n ``<protocol name>_vertical`` and ``<protocol name>_horizontal`` for each protocol item.\n\n E.g. a protocol item of ``symmetry`` will result in ``symmetry_vertical`` and ``symmetry_horizontal``.\n \"\"\"\n protocol: Protocol #:\n centering_method: Centering #:\n normalization_method: Normalization #:\n interpolation_method: Interpolation #:\n edge_detection_method: Edge #:\n top_penumbra_mm: float #:\n bottom_penumbra_mm: float #:\n left_penumbra_mm: float #:\n right_penumbra_mm: float #:\n geometric_center_index_x_y: Tuple[float, float] #:\n beam_center_index_x_y: Tuple[float, float] #:\n field_size_vertical_mm: float #:\n field_size_horizontal_mm: float #:\n beam_center_to_top_mm: float #:\n beam_center_to_bottom_mm: float #:\n beam_center_to_left_mm: float #:\n beam_center_to_right_mm: float #:\n cax_to_top_mm: float #:\n cax_to_bottom_mm: float #:\n cax_to_left_mm: float #:\n cax_to_right_mm: float #:\n top_position_index_x_y: Tuple[float, float] #:\n top_horizontal_distance_from_cax_mm: float #:\n top_vertical_distance_from_cax_mm: float #:\n top_horizontal_distance_from_beam_center_mm: float #:\n top_vertical_distance_from_beam_center_mm: float #:\n left_slope_percent_mm: float #:\n right_slope_percent_mm: float #:\n top_slope_percent_mm: float #:\n bottom_slope_percent_mm: float #:\n top_penumbra_percent_mm: float = 0 #:\n bottom_penumbra_percent_mm: float = 0 #:\n left_penumbra_percent_mm: float = 0 #:\n right_penumbra_percent_mm: float = 0 #:\n\n\nclass FieldAnalysis:\n \"\"\"Class for analyzing the various parameters of a radiation image, most commonly an open image from a linac.\n \"\"\"\n\n def __init__(self, path: Union[str, BinaryIO], filter: Optional[int] = None):\n \"\"\"\n\n\n Parameters\n ----------\n path\n The path to the image.\n filter\n If None, no filter is applied. If an int, a median filter of size n pixels is applied. Generally, a good idea.\n Default is None for backwards compatibility.\n \"\"\"\n self._path: str = path\n self.image: image.ImageLike = image.load(path) #:\n if filter:\n self.image.filter(size=filter)\n self.vert_profile: SingleProfile #:\n self.horiz_profile: SingleProfile #:\n self._is_analyzed: bool = False\n self._from_device: bool = False\n self.image.check_inversion_by_histogram()\n\n @classmethod\n def from_demo_image(cls):\n \"\"\"Load the demo image into an instance.\"\"\"\n demo_file = retrieve_demo_file(url='flatsym_demo.dcm')\n return cls(demo_file)\n\n @staticmethod\n def run_demo() -> None:\n \"\"\"Run the Field Analysis demo by loading the demo image, print results, and plot the profiles.\"\"\"\n fs = FieldAnalysis.from_demo_image()\n fs.analyze(protocol=Protocol.VARIAN)\n print(fs.results())\n fs.plot_analyzed_image()\n\n def _determine_center(self, centering: Centering) -> Tuple[float, float]:\n \"\"\"Determine the position ratio using a centering technique.\"\"\"\n vert_sum = np.sum(self.image.array, axis=1)\n horiz_sum = np.sum(self.image.array, axis=0)\n v_prof = SingleProfile(vert_sum)\n h_prof = SingleProfile(horiz_sum)\n if centering == Centering.GEOMETRIC_CENTER:\n # horiz and vert appear switched, but it's because the center of the vert profile\n # is where to take the horizontal profile and vic versa\n horiz_ratio = v_prof.geometric_center()['index (exact)'] / len(v_prof.values)\n vert_ratio = h_prof.geometric_center()['index (exact)'] / len(h_prof.values)\n elif centering == Centering.BEAM_CENTER:\n horiz_ratio = v_prof.beam_center()['index (exact)'] / len(v_prof.values)\n vert_ratio = h_prof.beam_center()['index (exact)'] / len(h_prof.values)\n return vert_ratio, horiz_ratio\n\n def _extract_profiles(self, horiz_position, horiz_width, interpolation_resolution_mm, vert_position, vert_width,\n edge_detection_method, edge_smoothing_ratio, ground, interpolation,\n interpolation_resolution, normalization_method, centering, hill_window_ratio) -> None:\n \"\"\"Figures out 1) where to extract the profiles from the image and 2) sets the profiles to instance attrs\"\"\"\n\n # calculate the horiz/vert extraction positions if necessary\n if centering in (Centering.BEAM_CENTER, Centering.GEOMETRIC_CENTER):\n vert_position, horiz_position = self._determine_center(centering)\n\n # calculate the profiles\n horiz_values, upper_h_idx, lower_h_idx = self._get_horiz_values(horiz_position, horiz_width)\n self._upper_h_index = upper_h_idx\n self._lower_h_index = lower_h_idx\n self.horiz_profile = SingleProfile(horiz_values, dpmm=self.image.dpmm, interpolation=interpolation,\n interpolation_resolution_mm=interpolation_resolution_mm, ground=ground,\n edge_detection_method=edge_detection_method,\n normalization_method=normalization_method,\n edge_smoothing_ratio=edge_smoothing_ratio,\n hill_window_ratio=hill_window_ratio)\n\n vert_values, left_v_idx, right_v_idx = self._get_vert_values(vert_position, vert_width)\n self._left_v_index = left_v_idx\n self._right_v_index = right_v_idx\n self.vert_profile = SingleProfile(vert_values, dpmm=self.image.dpmm, interpolation=interpolation,\n interpolation_resolution_mm=interpolation_resolution_mm, ground=ground,\n edge_detection_method=edge_detection_method,\n normalization_method=normalization_method,\n edge_smoothing_ratio=edge_smoothing_ratio,\n hill_window_ratio=hill_window_ratio)\n\n def analyze(self, protocol: Enum = Protocol.VARIAN,\n centering: Centering = Centering.BEAM_CENTER,\n vert_position: float = 0.5, horiz_position: float = 0.5,\n vert_width: float = 0, horiz_width: float = 0,\n in_field_ratio: float = 0.8,\n slope_exclusion_ratio: float = 0.2,\n invert: bool = False,\n is_FFF: bool = False,\n penumbra: Tuple[float, float] = (20, 80),\n interpolation: Interpolation = Interpolation.LINEAR, interpolation_resolution_mm: float = 0.1,\n ground: bool = True,\n normalization_method: Normalization = Normalization.BEAM_CENTER,\n edge_detection_method: Edge = Edge.INFLECTION_DERIVATIVE,\n edge_smoothing_ratio: float = 0.003,\n hill_window_ratio: float = 0.15,\n **kwargs) -> None:\n \"\"\"Analyze the image to determine parameters such as field edges, penumbra, and/or flatness & symmetry.\n\n Parameters\n ----------\n protocol : :class:`~pylinac.field_analysis.Protocol`\n The analysis protocol. See :ref:`analysis_definitions` for equations.\n centering : :class:`~pylinac.field_analysis.Centering`\n The profile extraction position technique. Beam center will determine the beam center and take profiles through the middle.\n Geometric center will simply take profiles centered about the image in both axes.\n Manual will use the values of `vert_position` and `horiz_position` as the position.\n See :ref:`centering`.\n vert_position\n The distance ratio of the image to sample. E.g. at the default of 0.5 the profile is extracted\n in the middle of the image. 0.0 is at the left edge of the image and 1.0 is at the right edge of the image.\n\n .. note::\n\n This value only applies when centering is MANUAL.\n\n horiz_position\n The distance ratio of the image to sample. E.g. at the default of 0.5 the profile is extracted\n in the middle of the image. 0.0 is at the top edge of the image and 1.0 is at the bottom edge of the image.\n\n .. note::\n\n This value only applies when centering is MANUAL.\n\n vert_width\n The width ratio of the image to sample. E.g. at the default of 0.0 a 1 pixel wide profile is extracted.\n 0.0 would be 1 pixel wide and 1.0 would be the vertical image width.\n horiz_width\n The width ratio of the image to sample. E.g. at the default of 0.0 a 1 pixel wide profile is extracted.\n 0.0 would be 1 pixel wide and 1.0 would be the horizontal image width.\n in_field_ratio\n The ratio of the field width to use for protocol values. E.g. 0.8 means use the 80% field width.\n slope_exclusion_ratio\n This is the ratio of the field to use to 1) calculate the \"top\" of an FFF field as well as 2) exclude from the\n \"slope\" calculation of each side of the field. Alternatively, this also defines the area to use for the\n slope calculation. E.g. an `in_field_ratio` of 0.8 and `slope_exclusion_ratio` of 0.2 means the central 20% of the\n field is used to fit and calculate the \"top\", while the region on either side of the central 20% between the central\n 80% is used to calculate a slope on either side using linear regression.\n\n .. note::\n\n While the \"top\" is always calculated, it will not be displayed in plots if the `is_FFF` parameter is false.\n\n invert\n Whether to invert the image. Setting this to True will override the default inversion. This is useful if\n pylinac's automatic inversion is incorrect.\n is_FFF\n This is a flag to display the \"top\" calculation and slopes on either side of the field.\n penumbra\n A tuple of (lower, higher) % of the penumbra to calculate. E.g. (20, 80) will calculate the penumbra width at 20% and 80%.\n\n .. note::\n\n The exact height of the penumbra depends on the edge detection method. E.g. FWHM will result in\n calculating penumbra at 20/80% of the field max, but if something like inflection is used, the penumbra\n height will be 20/50*100*inflection height and 80/50*100*inflection height.\n\n ground\n Whether to ground the profile (set min value to 0). Helpful most of the time.\n interpolation\n Interpolation technique to use. See :ref:`Interpolation`.\n interpolation_resolution_mm\n The resolution that the interpolation will scale to.\n E.g. if the native dpmm is 2 and the resolution is set to 0.1mm the data will be interpolated to have a new dpmm of 10 (1/0.1).\n normalization_method\n How to pick the point to normalize the data to. See :ref:`Normalization`.\n edge_detection_method\n The method by which to detect the field edge. FWHM is reasonable most of the time except for FFF beams.\n Inflection-derivative will use the max gradient to determine the field edge. Note that this may not be the\n 50% height. In fact, for FFF beams it shouldn't be. Inflection methods are better for FFF and other unusual\n beam shapes. See :ref:`edge`.\n edge_smoothing_ratio\n The ratio of the length of the values to use as the sigma for a Gaussian filter applied before searching for\n the inflection. E.g. 0.005 with a profile of 1000 points will result in a sigma of 5.\n This helps make the inflection point detection more robust to noise. Increase for noisy data.\n hill_window_ratio\n The ratio of the field size to use as the window to fit the Hill function. E.g. 0.2 will using a window\n centered about each edge with a width of 20% the size of the field width. Only applies when the edge\n detection is ``INFLECTION_HILL``.\n kwargs\n Use these to pass parameters to custom protocol functions. See :ref:`custom_protocols`.\n \"\"\"\n if is_FFF and edge_detection_method == Edge.FWHM:\n warnings.warn(\"Using FWHM for an FFF beam is not advised. Consider using INFLECTION_DERIVATIVE or INFLECTION_HILL\")\n if invert:\n self.image.invert()\n\n self._analyze(edge_detection_method, edge_smoothing_ratio, ground, horiz_position, horiz_width, in_field_ratio,\n interpolation, interpolation_resolution_mm, is_FFF, kwargs, normalization_method, penumbra,\n protocol, slope_exclusion_ratio, vert_position, vert_width, centering, hill_window_ratio)\n\n def _analyze(self, edge_detection_method, edge_smoothing_ratio, ground, horiz_position, horiz_width, in_field_ratio,\n interpolation, interpolation_resolution_mm, is_FFF, kwargs, normalization_method, penumbra, protocol,\n slope_exclusion_ratio, vert_position, vert_width, centering, hill_window_ratio):\n self._protocol = protocol\n self._penumbra = penumbra\n self._centering = centering\n self._is_FFF: bool = is_FFF\n self._edge_detection = edge_detection_method\n self._in_field_ratio = in_field_ratio\n self._slope_exclusion_ratio = slope_exclusion_ratio\n self._hill_window_ratio = hill_window_ratio\n self._interpolation_method = interpolation\n self._extract_profiles(horiz_position, horiz_width, interpolation_resolution_mm, vert_position, vert_width,\n edge_detection_method, edge_smoothing_ratio, ground, interpolation,\n interpolation_resolution_mm,\n normalization_method, centering, hill_window_ratio)\n self._results = {}\n # calculate common field info\n v_pen = self.vert_profile.penumbra(penumbra[0], penumbra[1])\n h_pen = self.horiz_profile.penumbra(penumbra[0], penumbra[1])\n self._results['top_penumbra_mm'] = v_pen['left penumbra width (exact) mm']\n self._results['bottom_penumbra_mm'] = v_pen['right penumbra width (exact) mm']\n self._results['left_penumbra_mm'] = h_pen['left penumbra width (exact) mm']\n self._results['right_penumbra_mm'] = h_pen['right penumbra width (exact) mm']\n if edge_detection_method == Edge.INFLECTION_HILL:\n self._results['top_penumbra_percent_mm'] = abs(v_pen['left gradient (exact) %/mm'])\n self._results['bottom_penumbra_percent_mm'] = abs(v_pen['right gradient (exact) %/mm'])\n self._results['left_penumbra_percent_mm'] = abs(h_pen['left gradient (exact) %/mm'])\n self._results['right_penumbra_percent_mm'] = abs(h_pen['right gradient (exact) %/mm'])\n self._results['geometric_center_index_x_y'] = (self.horiz_profile.geometric_center()['index (exact)'],\n self.vert_profile.geometric_center()['index (exact)'])\n self._results['beam_center_index_x_y'] = (self.horiz_profile.beam_center()['index (exact)'],\n self.vert_profile.beam_center()['index (exact)'])\n self._results['field_size_vertical_mm'] = self.vert_profile.field_data(in_field_ratio=1.0)['width (exact) mm']\n self._results['field_size_horizontal_mm'] = self.horiz_profile.field_data(in_field_ratio=1.0)[\n 'width (exact) mm']\n self._results['beam_center_to_top_mm'] = self.vert_profile.field_data(in_field_ratio=1.0)[\n 'left distance->beam center (exact) mm']\n self._results['beam_center_to_bottom_mm'] = self.vert_profile.field_data(in_field_ratio=1.0)[\n 'right distance->beam center (exact) mm']\n self._results['beam_center_to_left_mm'] = self.horiz_profile.field_data(in_field_ratio=1.0)[\n 'left distance->beam center (exact) mm']\n self._results['beam_center_to_right_mm'] = self.horiz_profile.field_data(in_field_ratio=1.0)[\n 'right distance->beam center (exact) mm']\n self._results['cax_to_top_mm'] = self.vert_profile.field_data(in_field_ratio=1.0)[\n 'left distance->CAX (exact) mm']\n self._results['cax_to_bottom_mm'] = self.vert_profile.field_data(in_field_ratio=1.0)[\n 'right distance->CAX (exact) mm']\n self._results['cax_to_left_mm'] = self.horiz_profile.field_data(in_field_ratio=1.0)[\n 'left distance->CAX (exact) mm']\n self._results['cax_to_right_mm'] = self.horiz_profile.field_data(in_field_ratio=1.0)[\n 'right distance->CAX (exact) mm']\n\n h_field_data = self.horiz_profile.field_data(in_field_ratio=in_field_ratio,\n slope_exclusion_ratio=slope_exclusion_ratio)\n v_field_data = self.vert_profile.field_data(in_field_ratio=in_field_ratio,\n slope_exclusion_ratio=slope_exclusion_ratio)\n self._results['top_position_index_x_y'] = (\n h_field_data['\"top\" index (exact)'], v_field_data['\"top\" index (exact)'])\n self._results['top_horizontal_distance_from_cax_mm'] = h_field_data['\"top\"->CAX (exact) mm']\n self._results['top_vertical_distance_from_cax_mm'] = v_field_data['\"top\"->CAX (exact) mm']\n self._results['top_horizontal_distance_from_beam_center_mm'] = h_field_data['\"top\"->beam center (exact) mm']\n self._results['top_vertical_distance_from_beam_center_mm'] = v_field_data['\"top\"->beam center (exact) mm']\n self._results['left_slope_percent_mm'] = h_field_data['left slope (%/mm)']\n self._results['right_slope_percent_mm'] = h_field_data['right slope (%/mm)']\n self._results['top_slope_percent_mm'] = v_field_data['left slope (%/mm)']\n self._results['bottom_slope_percent_mm'] = v_field_data['right slope (%/mm)']\n\n # calculate protocol info\n self._extra_results = {}\n for name, item in protocol.value.items():\n self._extra_results[f\"{name}_horizontal\"] = item['calc'](self.horiz_profile, in_field_ratio, **kwargs)\n self._extra_results[f\"{name}_vertical\"] = item['calc'](self.vert_profile, in_field_ratio, **kwargs)\n self._is_analyzed = True\n\n def results(self, as_str=True) -> str:\n \"\"\"Get the results of the analysis.\n\n Parameters\n ----------\n as_str\n If True, return a simple string. If False, return a list of each line of text.\n \"\"\"\n if not self._is_analyzed:\n raise NotAnalyzed(\"Image is not analyzed yet. Use analyze() first.\")\n\n results = [\n 'Field Analysis Results',\n '----------------------',\n f'File: {self._path}',\n f\"Protocol: {self._protocol.name}\",\n ]\n if not self._from_device:\n results += [f\"Centering method: {self._centering.value}\",]\n results += [\n f\"Normalization method: {self.horiz_profile._norm_method.value}\",\n f\"Interpolation: {self.horiz_profile._interp_method.value}\",\n f\"Edge detection method: {self.horiz_profile._edge_method.value}\",\n \"\",\n f\"Penumbra width ({self._penumbra[0]}/{self._penumbra[1]}):\",\n f\"Left: {self._results['left_penumbra_mm']:3.1f}mm\",\n f\"Right: {self._results['right_penumbra_mm']:3.1f}mm\",\n f\"Top: {self._results['top_penumbra_mm']:3.1f}mm\",\n f\"Bottom: {self._results['bottom_penumbra_mm']:3.1f}mm\",\n \"\",\n ]\n if self._edge_detection == Edge.INFLECTION_HILL:\n results += [\n \"Penumbra gradients:\",\n f\"Left gradient: {self._results['left_penumbra_percent_mm']:3.2f}%/mm\",\n f\"Right gradient: {self._results['right_penumbra_percent_mm']:3.2f}%/mm\",\n f\"Top gradient: {self._results['top_penumbra_percent_mm']:3.2f}%/mm\",\n f\"Bottom gradient: {self._results['bottom_penumbra_percent_mm']:3.2f}%/mm\",\n \"\",\n ]\n results += [\n \"Field Size:\",\n f\"Horizontal: {self._results['field_size_horizontal_mm']:3.1f}mm\",\n f\"Vertical: {self._results['field_size_vertical_mm']:3.1f}mm\",\n \"\",\n \"CAX to edge distances:\",\n f\"CAX -> Top edge: {self._results['cax_to_top_mm']:3.1f}mm\",\n f\"CAX -> Bottom edge: {self._results['cax_to_bottom_mm']:3.1f}mm\",\n f\"CAX -> Left edge: {self._results['cax_to_left_mm']:3.1f}mm\",\n f\"CAX -> Right edge: {self._results['cax_to_right_mm']:3.1f}mm\",\n \"\"]\n if self._is_FFF:\n results += [\n \"'Top' vertical distance from CAX: {:3.1f}mm\".format(\n self._results['top_vertical_distance_from_cax_mm']),\n \"'Top' horizontal distance from CAX: {:3.1f}mm\".format(\n self._results['top_horizontal_distance_from_cax_mm']),\n \"'Top' vertical distance from beam center: {:3.1f}mm\".format(\n self._results['top_vertical_distance_from_beam_center_mm']),\n \"'Top' horizontal distance from beam center: {:3.1f}mm\".format(\n self._results['top_horizontal_distance_from_beam_center_mm']),\n \"\", ]\n results += [\n f\"Top slope: {self._results['top_slope_percent_mm']:3.3f}%/mm\",\n f\"Bottom slope: {self._results['bottom_slope_percent_mm']:3.3f}%/mm\",\n f\"Left slope: {self._results['left_slope_percent_mm']:3.3f}%/mm\",\n f\"Right slope: {self._results['right_slope_percent_mm']:3.3f}%/mm\",\n \"\",\n \"Protocol data:\",\n \"--------------\",\n ]\n\n for name, item in self._protocol.value.items():\n results.append(f\"Vertical {name}: {self._extra_results[name + '_vertical']:3.3f}{item['unit']}\")\n results.append(\n f\"Horizontal {name}: {self._extra_results[name + '_horizontal']:3.3f}{item['unit']}\")\n results.append('')\n\n if as_str:\n results = '\\n'.join(result for result in results)\n return results\n\n def results_data(self, as_dict: bool = False) -> Union[FieldResults, dict]:\n \"\"\"Present the results data and metadata as a dataclass or dict.\n The default return type is a dataclass.\"\"\"\n data = FieldResults(**self._results, protocol=self._protocol.name,\n centering_method=getattr(self._centering, 'value', None),\n normalization_method=self.horiz_profile._norm_method.value,\n interpolation_method=self.horiz_profile._interp_method.value,\n edge_detection_method=self.horiz_profile._edge_method.value)\n # add custom data\n for key, value in self._extra_results.items():\n setattr(data, key, value)\n if as_dict:\n return dataclasses.asdict(data)\n return data\n\n def _get_vert_values(self, vert_position: float, vert_width: float) -> (np.ndarray, float, float):\n \"\"\"Get the raw values of the profile to pass to SingleProfile\"\"\"\n left_edge = int(round(self.image.array.shape[1] * vert_position - self.image.array.shape[1] * vert_width / 2))\n left_edge = max(left_edge, 0) # clip to 0\n right_edge = int(\n round(self.image.array.shape[1] * vert_position + self.image.array.shape[1] * vert_width / 2) + 1)\n right_edge = min(right_edge, self.image.array.shape[1]) # clip to image limit\n return np.mean(self.image.array[:, left_edge:right_edge], 1), left_edge, right_edge\n\n def _get_horiz_values(self, horiz_position: float, horiz_width: float) -> (np.ndarray, float, float):\n \"\"\"Get the raw values of the profile to pass to SingleProfile\"\"\"\n bottom_edge = int(round(self.image.array.shape[0] * horiz_position - self.image.array.shape[0] * horiz_width / 2))\n bottom_edge = max(bottom_edge, 0)\n top_edge = int(\n round(self.image.array.shape[0] * horiz_position + self.image.array.shape[0] * horiz_width / 2) + 1)\n top_edge = min(top_edge, self.image.array.shape[0])\n return np.mean(self.image.array[bottom_edge:top_edge, :], 0), bottom_edge, top_edge\n\n def publish_pdf(self, filename: str, notes: Union[str, list] = None, open_file: bool = False,\n metadata: dict = None) -> None:\n \"\"\"Publish (print) a PDF containing the analysis, images, and quantitative results.\n\n Parameters\n ----------\n filename : (str, file-like object}\n The file to write the results to.\n notes : str, list of strings\n Text; if str, prints single line.\n If list of strings, each list item is printed on its own line.\n open_file : bool\n Whether to open the file using the default program after creation.\n metadata : dict\n Extra stream to be passed and shown in the PDF. The key and value will be shown with a colon.\n E.g. passing {'Author': 'James', 'Unit': 'TrueBeam'} would result in text in the PDF like:\n --------------\n Author: James\n Unit: TrueBeam\n --------------\n \"\"\"\n plt.ioff()\n if not self._is_analyzed:\n raise NotAnalyzed(\"Image is not analyzed yet. Use analyze() first.\")\n canvas = pdf.PylinacCanvas(filename, page_title=\"Field Analysis\",\n metadata=metadata, metadata_location=(2, 5))\n # draw result text\n text = self.results(as_str=False)\n number_of_lines = len(text)\n i = 0\n while i < number_of_lines:\n if i > number_of_lines - 1:\n i = number_of_lines - 1\n canvas.add_text(text=text[i:i + 50], location=(2, 25.5), font_size=10)\n canvas.add_new_page()\n i = i + 50\n\n # draw vertical profile\n stream = io.BytesIO()\n self._save_plot(self._plot_vert, stream)\n canvas.add_image(stream, location=(-4, 13), dimensions=(28, 12))\n\n # draw horizontal profile\n stream = io.BytesIO()\n self._save_plot(self._plot_horiz, stream)\n canvas.add_image(stream, location=(-4, 1), dimensions=(28, 12))\n\n # draw image on last page\n canvas.add_new_page()\n stream = io.BytesIO()\n self._save_plot(self._plot_image, stream, title=\"Image\")\n canvas.add_image(stream, location=(1, 2), dimensions=(18, 20))\n if notes is not None:\n canvas.add_text(text=\"Notes:\", location=(1, 5.5), font_size=14)\n canvas.add_text(text=notes, location=(1, 5))\n canvas.finish()\n\n if open_file:\n open_path(filename)\n\n def plot_analyzed_image(self, show: bool = True, grid: bool = True):\n \"\"\"Plot the analyzed image. Shows parameters such as flatness & symmetry.\n\n Parameters\n ----------\n show\n Whether to show the plot when called.\n grid\n Whether to show a grid on the profile plots\n \"\"\"\n if not self._is_analyzed:\n raise NotAnalyzed(\"Image is not analyzed yet. Use analyze() first.\")\n # set up axes\n plt.ioff()\n if not self._from_device:\n image_ax = plt.subplot2grid((2, 2), (0, 1))\n vert_ax = plt.subplot2grid((2, 2), (1, 1))\n horiz_ax = plt.subplot2grid((2, 2), (0, 0))\n else:\n vert_ax = plt.subplot2grid((1, 2), (0, 1))\n horiz_ax = plt.subplot2grid((1, 2), (0, 0))\n\n # plot image and profile lines\n if not self._from_device:\n self._plot_image(image_ax, title=osp.basename(self._path))\n self._plot_vert(vert_ax, grid)\n self._plot_horiz(horiz_ax, grid)\n\n # plot legend\n lines = []\n labels = []\n v_lines, v_labels = vert_ax.get_legend_handles_labels()\n h_lines, h_labels = horiz_ax.get_legend_handles_labels()\n for label, line in zip(v_labels, v_lines):\n if label not in labels:\n lines.append(line)\n labels.append(label)\n for label, line in zip(h_labels, h_lines):\n if label not in labels:\n lines.append(line)\n labels.append(label)\n if not self._from_device:\n legend_ax = plt.subplot2grid((2, 2), (1, 0))\n legend_ax.legend(lines, labels, loc=\"center\")\n legend_ax.axis('off')\n\n _remove_ticklabels(legend_ax)\n\n else:\n vert_ax.legend(lines, labels, loc='best',)\n plt.suptitle(\"Field Profile Analysis\")\n if show:\n plt.show()\n\n def _plot_image(self, axis: plt.Axes = None, title: str = '') -> None:\n \"\"\"Plot the image and profile extraction overlay\"\"\"\n if axis is None:\n fig, axis = plt.subplots()\n axis.imshow(self.image.array, cmap=get_dicom_cmap())\n\n # vertical line/rect\n width = abs(self._left_v_index-self._right_v_index)\n center = (width / 2 + self._left_v_index, self.image.shape[0]/2)\n r = Rectangle(width=width,\n height=self.image.shape[0],\n center=center)\n r.plot2axes(axis, edgecolor='b', fill=True, alpha=0.2, facecolor='b', label=\"Profile Extraction Area\")\n\n # horizontal line/rect\n width_h = abs(self._upper_h_index-self._lower_h_index)\n center_h = (self.image.shape[1]/2, width / 2 + self._upper_h_index)\n r = Rectangle(width=self.image.shape[1],\n height=width_h,\n center=center_h)\n r.plot2axes(axis, edgecolor='b', fill=True, alpha=0.2, facecolor='b')\n\n # cleanup\n _remove_ticklabels(axis)\n axis.set_title(title)\n axis.legend()\n\n def _plot_vert(self, axis: plt.Axes = None, grid: bool = True) -> None:\n \"\"\"Plot vertical profile\"\"\"\n if axis is None:\n fig, axis = plt.subplots()\n axis.grid(grid)\n axis.set_title(\"Vertical Profile\")\n if self._from_device:\n axis.set_xlabel(\"detector\")\n if self._interpolation_method == Interpolation.NONE:\n markers = \"b+\"\n else:\n markers = \"b\"\n else:\n axis.set_xlabel(\"pixels\")\n markers = \"b\"\n axis.plot(self.vert_profile.values, markers, label='Profile')\n axis.set_ylabel(\"Normalized Response\")\n\n # plot second axis w/ physical distance\n sec_y = axis.twiny()\n physical_distance = np.array(range(int(len(self.vert_profile.values)))) / self.vert_profile.dpmm\n sec_y.plot(physical_distance, self.vert_profile.values, markers)\n sec_y.set_xlabel(\"mm\")\n\n # plot basic parameters on profile\n self._plot_penumbra(self.vert_profile, axis)\n self._plot_field_edges(self.vert_profile, axis)\n if self._is_FFF:\n self._plot_top(self.vert_profile, axis)\n self._plot_infield_slope(self.vert_profile, axis)\n\n for name, item in self._protocol.value.items():\n if item.get(\"plot\"):\n item['plot'](self, self.vert_profile, axis)\n\n def _plot_horiz(self, axis: plt.Axes = None, grid: bool = True) -> None:\n \"\"\"Plot horizontal profile\"\"\"\n if axis is None:\n fig, axis = plt.subplots()\n axis.grid(grid)\n axis.set_title(\"Horizontal Profile\")\n if self._from_device:\n axis.set_xlabel(\"detector\")\n if self._interpolation_method == Interpolation.NONE:\n markers = \"b+\"\n else:\n markers = \"b\"\n else:\n axis.set_xlabel(\"pixels\")\n markers = \"b\"\n axis.plot(self.horiz_profile.values, markers, label='Profile')\n axis.set_ylabel(\"Normalized Response\")\n\n # plot second axis w/ physical distance\n sec_y = axis.twiny()\n physical_distance = np.array(range(int(len(self.horiz_profile.values)))) / self.horiz_profile.dpmm\n sec_y.plot(physical_distance, self.horiz_profile.values, markers)\n sec_y.set_xlabel(\"mm\")\n\n # plot basic parameters on profile\n self._plot_penumbra(self.horiz_profile, axis)\n self._plot_field_edges(self.horiz_profile, axis)\n if self._is_FFF:\n self._plot_top(self.horiz_profile, axis)\n self._plot_infield_slope(self.horiz_profile, axis)\n\n for name, item in self._protocol.value.items():\n if item.get(\"plot\"):\n item['plot'](self, self.horiz_profile, axis)\n\n @staticmethod\n def _save_plot(func, filename: Union[str, io.BytesIO], **kwargs) -> None:\n func(**kwargs)\n # plt.tight_layout(1.2)\n plt.savefig(filename)\n\n def _plot_penumbra(self, profile: SingleProfile, axis: plt.Axes = None) -> None:\n \"\"\"Plot the non-linear regression fit against the profile\"\"\"\n data = profile.penumbra(self._penumbra[0], self._penumbra[1])\n axis.axvline(x=data[f'left {self._penumbra[0]}% index (exact)'], color='pink')\n axis.axvline(x=data[f'left {self._penumbra[1]}% index (exact)'], color='pink', label='Penumbra region')\n axis.axvline(x=data[f'right {self._penumbra[0]}% index (exact)'], color='pink')\n axis.axvline(x=data[f'right {self._penumbra[1]}% index (exact)'], color='pink')\n if self._edge_detection == Edge.INFLECTION_HILL:\n # plot left side Hill fit\n fw = profile.field_data(in_field_ratio=1.0)['width (exact)'] * self._hill_window_ratio / 2\n left_hill_idx = int(round(data[f'left {self._penumbra[0]}% index (exact)'] - fw))\n right_hill_idx = int(round(data[f'left {self._penumbra[1]}% index (exact)'] + fw))\n infl_data = profile.inflection_data()\n hill_fit = Hill.from_params(infl_data['left Hill params'])\n l_x_data = np.linspace(left_hill_idx, right_hill_idx, 200)\n axis.plot(l_x_data, hill_fit.y(l_x_data), color='black', label=\"Hill fit\")\n\n # plot right side Hill fit\n left_hill_idx = int(round(data[f'right {self._penumbra[1]}% index (exact)'] - fw))\n right_hill_idx = int(round(data[f'right {self._penumbra[0]}% index (exact)'] + fw))\n hill_fit = Hill.from_params(infl_data['right Hill params'])\n r_x_data = np.linspace(left_hill_idx, right_hill_idx, 200)\n axis.plot(r_x_data, hill_fit.y(r_x_data), color='black', label=\"Hill fit\")\n\n def _plot_field_edges(self, profile: SingleProfile, axis: plt.Axes) -> None:\n data = profile.field_data(in_field_ratio=1.0, slope_exclusion_ratio=self._slope_exclusion_ratio)\n axis.plot(data['left index (rounded)'], data['left value (@rounded)'], 'x', color='green', label='Field edge')\n axis.plot(data['right index (rounded)'], data['right value (@rounded)'], 'x', color='green')\n\n def _plot_infield_slope(self, profile: SingleProfile, axis: plt.Axes) -> None:\n data = profile.field_data(self._in_field_ratio, self._slope_exclusion_ratio)\n # left slope\n left_x_values = range(data['left index (rounded)'], data['left inner index (rounded)'])\n left_y_values = data['left slope'] * left_x_values + data['left intercept']\n axis.plot(left_x_values, left_y_values, color='tomato', label='in-field slope')\n # right slope\n right_x_values = range(data['right inner index (rounded)'], data['right index (rounded)'])\n right_y_values = data['right slope'] * right_x_values + data['right intercept']\n axis.plot(right_x_values, right_y_values, color='tomato')\n\n def _plot_top(self, profile: SingleProfile, axis: plt.Axes = None) -> None:\n \"\"\"Plot a second order polynomial to the peak of the FFF field\"\"\"\n data = profile.field_data(self._in_field_ratio, self._slope_exclusion_ratio)\n x_model = np.linspace(data['left inner index (rounded)'], data['right inner index (rounded)'], 1000)\n y_model = data['top params'][0] * x_model ** 2 + data['top params'][1] * x_model + data['top params'][2]\n axis.plot(x_model, y_model, color='magenta', label='\"top\" polynomial fit')\n axis.plot(data['\"top\" index (exact)'], data['\"top\" value (@exact)'], 'x', color='magenta', label='\"top\" position')\n\n\nclass Device(Enum):\n \"\"\"2D array device Enum.\n \"\"\"\n PROFILER = {'device': SNCProfiler, 'detector spacing (mm)': 5} #:\n\n\nclass DeviceFieldAnalysis(FieldAnalysis):\n \"\"\"Field analysis using a device array.\"\"\"\n\n def __init__(self, path: str, device: Device):\n \"\"\"\n Parameters\n ----------\n path\n Path to the file of the device output\n device\n The array device. Currently, the Profiler is supported. See :ref:`loading_device_data`.\n \"\"\"\n self.device: Device = device.value['device'](path=path) #:\n self._path = path\n self._from_device = True\n self._dpmm = 1/device.value['detector spacing (mm)']\n\n @classmethod\n def from_demo_image(cls) -> None:\n \"\"\"Load the demo image into an instance.\"\"\"\n demo_file = retrieve_demo_file(url='6fff.prm')\n return cls(demo_file, device=Device.PROFILER)\n\n @staticmethod\n def run_demo() -> None:\n \"\"\"Run the Field analysis demo by loading the demo device dataset, print results, and plot the profiles.\"\"\"\n fs = DeviceFieldAnalysis.from_demo_image()\n fs.analyze(protocol=Protocol.VARIAN, is_FFF=True)\n print(fs.results())\n fs.plot_analyzed_image()\n\n def analyze(self, protocol: Protocol = Protocol.VARIAN,\n in_field_ratio: float = 0.8,\n slope_exclusion_ratio: float = 0.3,\n is_FFF: bool = False,\n penumbra: tuple = (20, 80),\n interpolation: Interpolation = Interpolation.NONE, interpolation_resolution_mm: float = 0.1,\n ground: bool = True,\n normalization_method: Normalization = Normalization.GEOMETRIC_CENTER,\n edge_detection_method: Edge = Edge.INFLECTION_HILL,\n edge_smoothing_ratio: float = 0.003,\n hill_window_ratio: float = 0.15,\n **kwargs) -> None:\n \"\"\"Analyze the device profiles to determine parameters such as field edges, penumbra, and/or flatness & symmetry.\n\n Parameters\n ----------\n protocol\n The analysis protocol. See :ref:`analysis_definitions` for equations and options.\n in_field_ratio\n The ratio of the field width to use for protocol values. E.g. 0.8 means use the 80% field width.\n slope_exclusion_ratio\n This is the ratio of the field to use to 1) calculate the \"top\" of an FFF field as well as 2) exclude from the\n \"slope\" calculation of each side of the field. Alternatively, this also defines the area to use for the\n slope calculation. E.g. an `in_field_ratio` of 0.8 and `slope_exclusion_ratio` of 0.2 means the central 20% of the\n field is used to fit and calculate the \"top\", while the region on either side of the central 20% between the central\n 80% is used to calculate a slope on either side using linear regression.\n\n .. note::\n\n While the \"top\" is always calculated, it will not be displayed in plots if the `is_FFF` parameter is false.\n\n is_FFF\n This is a flag to display the \"top\" calculation and slopes on either side of the field.\n penumbra\n A tuple of (lower, higher) % of the penumbra to calculate. E.g. (20, 80) will calculate the penumbra width at 20% and 80%.\n\n .. note::\n\n The exact height of the penumbra depends on the edge detection method. E.g. FWHM will result in\n calculating penumbra at 20/80% of the field max, but if something like inflection is used, the penumbra\n height will be 20/50*100*inflection height and 80/50*100*inflection height.\n\n interpolation\n Interpolation technique to use. Must be one of the enum options of ``Interpolation``.\n ground\n Whether to ground the profile (set min value to 0). Helpful most of the time.\n interpolation_resolution_mm\n The resolution that the interpolation will scale to.\n E.g. if the native dpmm is 2 and the resolution is set to 0.1mm the data will be interpolated to have a new dpmm of 10 (1/0.1).\n normalization_method\n How to pick the point to normalize the data to.\n edge_detection_method\n The method by which to detect the field edge. FWHM is reasonable most of the time except for FFF beams.\n Inflection-derivative will use the max gradient to determine the field edge. Note that this may not be the\n 50% height. In fact, for FFF beams it shouldn't be. Inflection methods are better for FFF and other unusual\n beam shapes.\n edge_smoothing_ratio\n The ratio of the length of the values to use as the sigma for a Gaussian filter applied before searching for\n the inflection. E.g. 0.005 with a profile of 1000 points will result in a sigma of 5.\n This helps make the inflection point detection more robust to noise. Increase for noisy data.\n hill_window_ratio\n The ratio of the field size to use as the window to fit the Hill function. E.g. 0.2 will using a window\n centered about each edge with a width of 20% the size of the field width. Only applies when the edge\n detection is ``INFLECTION_HILL``.\n kwargs\n Use these to pass parameters to custom protocol functions. See :ref:`custom_protocols`.\n \"\"\"\n self._analyze(edge_detection_method, edge_smoothing_ratio, ground, None, None, in_field_ratio, interpolation,\n interpolation_resolution_mm, is_FFF, kwargs, normalization_method, penumbra, protocol,\n slope_exclusion_ratio, None, None, None, hill_window_ratio)\n\n def _extract_profiles(self, horiz_position, horiz_width, interpolation_resolution_mm, vert_position, vert_width,\n edge_detection_method, edge_smoothing_ratio, ground, interpolation,\n interpolation_resolution, normalization_method, centering, hill_window_ratio):\n # calculate the profiles from the device. Since it's not an image, there's no position values\n x_prof, y_prof, _, _ = self.device.to_profiles(dpmm=self._dpmm, interpolation=interpolation,\n interpolation_resolution_mm=interpolation_resolution,\n ground=ground, edge_detection_method=edge_detection_method,\n normalization_method=normalization_method,\n edge_smoothing_ratio=edge_smoothing_ratio,\n hill_window_ratio=hill_window_ratio)\n self.vert_profile = y_prof\n self.horiz_profile = x_prof\n\n\ndef _remove_ticklabels(axis: plt.Axes):\n axis.get_yaxis().set_ticklabels([])\n axis.get_xaxis().set_ticklabels([])\n"
] |
[
[
"numpy.abs",
"numpy.linspace",
"numpy.min",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.savefig",
"numpy.sign",
"numpy.max",
"matplotlib.pyplot.ioff",
"numpy.argmax",
"numpy.mean",
"matplotlib.pyplot.subplot2grid",
"matplotlib.pyplot.suptitle",
"numpy.sum",
"matplotlib.pyplot.show"
]
] |
KoryakovDmitry/DewarpNet
|
[
"6b5c687548d9db3b5bcfd1503b7a8997c875ea1f"
] |
[
"utils.py"
] |
[
"'''\nMisc Utility functions\n'''\nfrom collections import OrderedDict\nimport os\nimport numpy as np\nimport torch\nimport random\nimport torchvision\n\ndef recursive_glob(rootdir='.', suffix=''):\n \"\"\"Performs recursive glob with given suffix and rootdir \n :param rootdir is the root directory\n :param suffix is the suffix to be searched\n \"\"\"\n return [os.path.join(looproot, filename)\n for looproot, _, filenames in os.walk(rootdir)\n for filename in filenames if filename.endswith(suffix)]\n\ndef poly_lr_scheduler(optimizer, init_lr, iter, lr_decay_iter=1, max_iter=30000, power=0.9,):\n \"\"\"Polynomial decay of learning rate\n :param init_lr is base learning rate\n :param iter is a current iteration\n :param lr_decay_iter how frequently decay occurs, default is 1\n :param max_iter is number of maximum iterations\n :param power is a polymomial power\n\n \"\"\"\n if iter % lr_decay_iter or iter > max_iter:\n return optimizer\n\n for param_group in optimizer.param_groups:\n param_group['lr'] = init_lr*(1 - iter/max_iter)**power\n\n\ndef adjust_learning_rate(optimizer, init_lr, epoch):\n \"\"\"Sets the learning rate to the initial LR decayed by 10 every 30 epochs\"\"\"\n lr = init_lr * (0.1 ** (epoch // 30))\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n\n\ndef alpha_blend(input_image, segmentation_mask, alpha=0.5):\n \"\"\"Alpha Blending utility to overlay RGB masks on RBG images \n :param input_image is a np.ndarray with 3 channels\n :param segmentation_mask is a np.ndarray with 3 channels\n :param alpha is a float value\n\n \"\"\"\n blended = np.zeros(input_image.size, dtype=np.float32)\n blended = input_image * alpha + segmentation_mask * (1 - alpha)\n return blended\n\ndef convert_state_dict(state_dict):\n \"\"\"Converts a state dict saved from a dataParallel module to normal \n module state_dict inplace\n :param state_dict is the loaded DataParallel model_state\n \n \"\"\"\n new_state_dict = OrderedDict()\n for k, v in state_dict.items():\n name = k[7:] # remove `module.`\n new_state_dict[name] = v\n return new_state_dict\n\n\nclass ImagePool():\n def __init__(self, pool_size):\n self.pool_size = pool_size\n if self.pool_size > 0:\n self.num_imgs = 0\n self.images = []\n\n def query(self, images):\n if self.pool_size == 0:\n return images\n return_images = []\n for image in images:\n image = torch.unsqueeze(image.data, 0)\n if self.num_imgs < self.pool_size:\n self.num_imgs = self.num_imgs + 1\n self.images.append(image)\n return_images.append(image)\n else:\n p = random.uniform(0, 1)\n if p > 0.5:\n random_id = random.randint(0, self.pool_size - 1) # randint is inclusive\n tmp = self.images[random_id].clone()\n self.images[random_id] = image\n return_images.append(tmp)\n else:\n return_images.append(image)\n return_images = torch.cat(return_images, 0)\n return return_images\n\n\ndef set_requires_grad(nets, requires_grad=False):\n if not isinstance(nets, list):\n nets = [nets]\n for net in nets:\n if net is not None:\n for param in net.parameters():\n param.requires_grad = requires_grad\n\n\n\ndef get_lr(optimizer):\n for param_group in optimizer.param_groups:\n return float(param_group['lr'])\n\ndef visualize(epoch,model,layer): \n #get conv layers\n conv_layers=[]\n for m in model.modules():\n if isinstance(m,torch.nn.modules.conv.Conv2d):\n conv_layers.append(m)\n\n # print conv_layers[layer].weight.data.cpu().numpy().shape\n tensor=conv_layers[layer].weight.data.cpu()\n vistensor(tensor, epoch, ch=0, allkernels=False, nrow=8, padding=1)\n\n\ndef vistensor(tensor, epoch, ch=0, allkernels=False, nrow=8, padding=1): \n '''\n vistensor: visuzlization tensor\n @ch: visualization channel \n @allkernels: visualization all tensors\n https://github.com/pedrodiamel/pytorchvision/blob/a14672fe4b07995e99f8af755de875daf8aababb/pytvision/visualization.py#L325\n ''' \n \n n,c,w,h = tensor.shape\n if allkernels: tensor = tensor.view(n*c,-1,w,h )\n elif c != 3: tensor = tensor[:,ch,:,:].unsqueeze(dim=1)\n \n rows = np.min( (tensor.shape[0]//nrow + 1, 64 ) )\n # print rows\n # print tensor.shape\n grid = utils.make_grid(tensor, nrow=8, normalize=True, padding=padding)\n # print grid.shape\n plt.figure( figsize=(10,10), dpi=200 )\n plt.imshow(grid.numpy().transpose((1, 2, 0)))\n plt.savefig('./generated/filters_layer1_dwuv_'+str(epoch)+'.png')\n plt.close()\n\n\ndef show_uloss(uwpred,uworg,inp_img, samples=7):\n \n n,c,h,w=inp_img.shape\n # print(labels.shape)\n uwpred=uwpred.detach().cpu().numpy()\n uworg=uworg.detach().cpu().numpy()\n inp_img=inp_img.detach().cpu().numpy()\n\n #NCHW->NHWC\n uwpred=uwpred.transpose((0, 2, 3, 1))\n uworg=uworg.transpose((0, 2, 3, 1))\n\n choices=random.sample(range(n), min(n,samples))\n f, axarr = plt.subplots(samples, 3)\n for j in range(samples):\n # print(np.min(labels[j]))\n # print imgs[j].shape\n img=inp_img[j].transpose(1,2,0)\n axarr[j][0].imshow(img[:,:,::-1])\n axarr[j][1].imshow(uworg[j])\n axarr[j][2].imshow(uwpred[j])\n \n plt.savefig('./generated/unwarp.png')\n plt.close()\n\n\ndef show_uloss_visdom(vis,uwpred,uworg,labels_win,out_win,labelopts,outopts,args):\n samples=7\n n,c,h,w=uwpred.shape\n uwpred=uwpred.detach().cpu().numpy()\n uworg=uworg.detach().cpu().numpy()\n out_arr=np.full((samples,3,args.img_rows,args.img_cols),0.0)\n label_arr=np.full((samples,3,args.img_rows,args.img_cols),0.0)\n choices=random.sample(range(n), min(n,samples))\n idx=0\n for c in choices:\n out_arr[idx,:,:,:]=uwpred[c]\n label_arr[idx,:,:,:]=uworg[c]\n idx+=1\n\n vis.images(out_arr,\n win=out_win,\n opts=outopts)\n vis.images(label_arr,\n win=labels_win,\n opts=labelopts)\n\ndef show_unwarp_tnsboard(global_step,writer,uwpred,uworg,grid_samples,gt_tag,pred_tag):\n idxs=torch.LongTensor(random.sample(range(images.shape[0]), min(grid_samples,images.shape[0])))\n grid_uworg = torchvision.utils.make_grid(uworg[idxs],normalize=True, scale_each=True)\n writer.add_image(gt_tag, grid_uworg, global_step)\n grid_uwpr = torchvision.utils.make_grid(uwpred[idxs],normalize=True, scale_each=True)\n writer.add_image(pred_tag, grid_uwpr, global_step)\n\ndef show_wc_tnsboard(global_step,writer,images,labels, pred, grid_samples,inp_tag, gt_tag, pred_tag):\n idxs=torch.LongTensor(random.sample(range(images.shape[0]), min(grid_samples,images.shape[0])))\n grid_inp = torchvision.utils.make_grid(images[idxs],normalize=True, scale_each=True)\n writer.add_image(inp_tag, grid_inp, global_step)\n grid_lbl = torchvision.utils.make_grid(labels[idxs],normalize=True, scale_each=True)\n writer.add_image(gt_tag, grid_lbl, global_step)\n grid_pred = torchvision.utils.make_grid(pred[idxs],normalize=True, scale_each=True)\n writer.add_image(pred_tag, grid_pred, global_step)\n"
] |
[
[
"torch.cat",
"numpy.min",
"torch.unsqueeze",
"numpy.full",
"numpy.zeros"
]
] |
LarryShamalama/scikit-mobility
|
[
"d58324c20d8a1651c97feb988619ce4405e78278"
] |
[
"tutorial/stats_utils.py"
] |
[
"#!/usr/bin/env python\n\n# ciacia_stats.py\n# Filippo Simini\n# Created: 20131021\n\nimport sys,os\nimport math\nimport random\n#import mpmath\nimport operator\nimport csv\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.pylab as pyl\nimport itertools\nimport scipy as sp\nfrom scipy import stats\nfrom scipy import optimize\nfrom scipy.integrate import quad\n#import scikits.statsmodels as sm\n\n\ndef segno(x):\n \"\"\"\n Input: x, a number\n Return: 1.0 if x>0,\n -1.0 if x<0,\n 0.0 if x==0\n \"\"\"\n if x > 0.0: return 1.0\n elif x < 0.0: return -1.0\n elif x == 0.0: return 0.0\n\n\ndef standard_dev(list):\n ll = len(list)\n m = 1.0 * sum(list)/ll\n return ( sum([(elem-m)**2.0 for elem in list]) / ll )**0.5\n\n\ndef list_check(lista):\n \"\"\"\n If a list has only one element, return that element. Otherwise return the whole list.\n \"\"\"\n try:\n e2 = lista[1]\n return lista\n except IndexError:\n return lista[0]\n\n\n #______________________________________#\n # #\n # Probability distributions #\n #______________________________________#\n # #\n\ndef pdf(binsize, input, out='no', normalize=True, include_zeros=False, vmin='NA', vmax='NA',start_from='NA', closing_bin=False):\n \"\"\"\n Return the probability density function of \"input\"\n using linear bins of size \"binsize\"\n\n Input format: one column of numbers\n\n Example:\n ---------\n a, m = 0.5, 1.\n data = np.random.pareto(a, 1000) + m\n xy = pdf(10.0, data)\n \"\"\"\n # Detect input type:\n if input == sys.stdin:\n # the data come form standard input\n d = [ list_check(map(float,l.split())) for l in sys.stdin ]\n # d = [ float(l) for l in sys.stdin if l.strip() ]\n elif isinstance(input, str):\n # the data come from a file\n d = [ list_check(map(float,l.split())) for l in open(input,'r') ]\n # d = [ float(w) for w in open(input,'r') if w.split()]\n else:\n # the data are in a list\n try:\n iterator = iter(input)\n d = list(input)\n except TypeError:\n print(\"The input is not iterable.\")\n\n bin = 1.0*binsize\n d.sort()\n lend = len(d)\n hist = []\n if out != 'no' and out != 'stdout': f = open(out,'wb')\n\n j = 0\n if not isinstance(start_from, str):\n i = int(start_from / bin)+ 1.0 * segno(start_from)\n else:\n i = int(d[j] / bin) + 1.0 *segno(d[j])\n\n while True:\n cont = 0\n average = 0.0\n if i>=0: ii = i-1\n else: ii = i\n # To include the lower end in the previous bin, substitute \"<\" with \"<=\"\n while d[j] < bin*(ii+1):\n cont += 1.0\n average += 1.0\n j += 1\n if j == lend: break\n if cont > 0 or include_zeros==True:\n if normalize == True and i != 0:\n hist += [[ bin*(ii)+bin/2.0 , average/(lend*bin) ]]\n elif i != 0:\n hist += [[ bin*(ii)+bin/2.0 , average/bin ]]\n if j == lend: break\n i += 1\n if closing_bin:\n # Add the \"closing\" bin\n hist += [[ hist[-1][0]+bin , 0.0 ]]\n if out == 'stdout':\n for l in hist:\n print(\"%s %s\" % (l[0],l[1]))\n elif out != 'no':\n for l in hist:\n f.write(\"%s %s\\n\" % (l[0],l[1]))\n f.close()\n if out == 'no': return hist\n\n\ndef lbpdf(binsize, input, out='no'):\n \"\"\"\n Return the probability density function of \"input\"\n using logarithmic bins of size \"binsize\"\n\n Input format: one column of numbers\n\n Example:\n ---------\n a, m = 0.5, 1.\n data = np.random.pareto(a, 1000) + m\n xy = lbpdf(1.5, data)\n \"\"\"\n # Detect input type:\n if input == sys.stdin:\n # the data come form standard input\n d = [ list_check(map(float,l.split())) for l in sys.stdin ]\n # d = [ float(l) for l in sys.stdin if l.strip() ]\n elif isinstance(input, str):\n # the data come from a file\n d = [ list_check(map(float,l.split())) for l in open(input,'r') ]\n # d = [ float(w) for w in open(input,'r') if w.split()]\n else:\n # the data are in a list\n try:\n iterator = iter(input)\n d = list(input)\n except TypeError:\n print(\"The input is not iterable.\")\n\n bin = 1.0*binsize\n d.sort()\n # The following removes elements too close to zero\n while d[0] < 1e-12:\n del(d[0])\n lend = len(d)\n tot = 0\n hist = []\n\n j = 0\n i = 1.0\n previous = min(d)\n\n while True:\n cont = 0\n average = 0.0\n next = previous * bin\n # To include the lower end in the previous bin, substitute \"<\" with \"<=\"\n while d[j] < next:\n cont += 1.0\n average += 1.0\n j += 1\n if j == lend: break\n if cont > 0:\n hist += [[previous+(next-previous)/2.0 , average/(next-previous)]]\n tot += average\n if j == lend: break\n i += 1\n previous = next\n\n if out != 'no' and out != 'stdout': f = open(out,'wb')\n if out == 'stdout':\n for x,y in hist:\n print(\"%s %s\" % (x,y/tot))\n elif out != 'no':\n f = open(out,'wb')\n for x,y in hist:\n f.write(\"%s %s\\n\" % (x,y/tot))\n f.close()\n if out == 'no': return [[x,y/tot] for x,y in hist]\n\n\n #______________________________________#\n # #\n # Least Squares Fit #\n #______________________________________#\n # #\n\nclass Parameter:\n def __init__(self, value):\n self.value = value\n\n def set(self, value):\n self.value = value\n\n def __call__(self):\n return self.value\n\ndef LSfit(function, parameters, y, x):\n \"\"\"\n *** ATTENTION! ***\n *** _x_ and _y_ MUST be NUMPY arrays !!! ***\n *** and use NUMPY FUNCTIONS, e.g. np.exp() and not math.exp() ***\n\n _function_ -> Used to calculate the sum of the squares:\n min sum( (y - function(x, parameters))**2 )\n {params}\n\n _parameters_ -> List of elements of the Class \"Parameter\"\n _y_ -> List of observations: [ y0, y1, ... ]\n _x_ -> List of variables: [ [x0,z0], [x1,z1], ... ]\n\n Then _function_ must be function of xi=x[0] and zi=x[1]:\n def f(x): return x[0] * x[1] / mu()\n\n # Gaussian\n np.exp( -(x-mu())**2.0/sigma()**2.0/2.0)/(2.0*sigma()**2.0*np.pi)**0.5\n # Lognormal\n np.exp( -(np.log(x)-mu())**2.0/sigma()**2.0/2.0)/(2.0*sigma()**2.0*np.pi)**0.5/x\n\n Example:\n x=[np.random.normal() for i in range(1000)]\n variables,data = map(np.array,zip(*pdf(0.4,x)))\n\n # giving INITIAL _PARAMETERS_:\n mu = Parameter(7)\n sigma = Parameter(3)\n\n # define your _FUNCTION_:\n def function(x): return np.exp( -(x-mu())**2.0/sigma()**2.0/2.0)/(2.0*sigma()**2.0*np.pi)**0.5\n\n ######################################################################################\n USA QUESTE FORMULE\n #Gaussian formula\n #np.exp( -(x-mu())**2.0/sigma()**2.0/2.0)/(2.0*np.pi)**0.5/sigma()\n # Lognormal formula\n #np.exp( -(np.log(x)-mu())**2.0/sigma()**2.0/2.0)/(2.0*np.pi)**0.5/x/sigma()\n ######################################################################################\n\n\n np.exp( -(x-mu())**2.0/sigma()**2.0/2.0)/(2.0*np.pi)**0.5/sigma()\n\n # fit! (given that data is an array with the data to fit)\n popt,cov,infodict,mesg,ier,pcov,chi2 = LSfit(function, [mu, sigma], data, variables)\n \"\"\"\n x = np.array(x)\n y = np.array(y)\n\n def f(params):\n i = 0\n for p in parameters:\n p.set(params[i])\n i += 1\n return y - function(x)\n\n p = [param() for param in parameters]\n popt,cov,infodict,mesg,ier = optimize.leastsq(f, p, maxfev=10000, full_output=1) #, warning=True) #, args=(x, y))\n\n if (len(y) > len(p)) and cov is not None:\n #s_sq = (f(popt)**2).sum()/(len(y)-len(p))\n s_sq = (infodict['fvec']**2).sum()/(len(y)-len(p))\n pcov = cov * s_sq\n else:\n pcov = float('Inf')\n\n R2 = 1.0 - (infodict['fvec']**2.0).sum() / standard_dev(y)**2.0 / len(y)\n\n # Detailed Output: p,cov,infodict,mesg,ier,pcov,R2\n return popt,cov,infodict,mesg,ier,pcov,R2\n\n\n\n #______________________________________#\n # #\n # Maximum Likelihood Fit #\n #______________________________________#\n # #\n\ndef maximum_likelihood(function, parameters, data, full_output=True, verbose=True):\n \"\"\"\n function -> callable: Distribution from which data are drawn. Args: (parameters, x)\n parameters -> np.array: initial parameters\n data -> np.array: Data\n\n Example:\n\n m=0.5\n v=0.5\n parameters = numpy.array([m,v])\n\n data = [random.normalvariate(m,v**0.5) for i in range(1000)]\n\n def function(p,x): return numpy.exp(-(x-p[0])**2.0/2.0/p[1])/(2.0*numpy.pi*p[1])**0.5\n\n maximum_likelihood(function, parameters, data)\n\n\n # # Check that is consistent with Least Squares when \"function\" is a gaussian:\n # mm=Parameter(0.1)\n # vv=Parameter(0.1)\n # def func(x): return numpy.exp(-(x-mm())**2.0/2.0/vv())/(2.0*numpy.pi*vv())**0.5\n # x,y = zip(*pdf(0.1,data,out='no'))\n # popt,cov,infodict,mesg,ier,pcov,chi2 = LSfit(func, [mm,vv], y, x)\n # popt\n #\n # # And with the exact M-L values:\n # mm = sum(data)/len(data)\n # vv = standard_dev(data)\n # mm, vv**2.0\n \"\"\"\n\n def MLprod(p, data, function):\n return -np.sum(np.array([np.log(function(p,x)) for x in data]))\n\n return optimize.fmin(MLprod, parameters, args=(data,function), full_output=full_output, disp=verbose)\n\n"
] |
[
[
"scipy.optimize.fmin",
"scipy.optimize.leastsq",
"numpy.array"
]
] |
coolerking/caterpillar
|
[
"f8d02d48963759118b6acfcf9b5d73a9f061a24b"
] |
[
"manage_cat.py"
] |
[
"# -*- coding: utf-8 -*-\n#!/usr/bin/env python3\n\"\"\"\nScripts to drive a donkey 2 car\n\nUsage:\n manage_cat.py (drive) [--model=<model>] [--js] [--type=(linear|categorical|rnn|imu|behavior|3d|localizer|latent)] [--camera=(single|stereo)] [--meta=<key:value> ...] [--debug]\n manage_cat.py (train) [--tub=<tub1,tub2,..tubn>] [--file=<file> ...] (--model=<model>) [--transfer=<model>] [--type=(linear|categorical|rnn|imu|behavior|3d|localizer)] [--continuous] [--aug]\n\n\nOptions:\n -h --help Show this screen.\n --js Use physical joystick.\n --debug Use debug option\n -f --file=<file> A text file containing paths to tub files, one per line. Option may be used more than once.\n --meta=<key:value> Key/Value strings describing describing a piece of meta data about this drive. Option may be used more than once.\n\"\"\"\nimport os\nimport time\n\nfrom docopt import docopt\nimport numpy as np\n\nimport donkeycar as dk\n\n#import parts\nfrom donkeycar.parts.transform import Lambda, TriggeredCallback, DelayedTrigger\nfrom donkeycar.parts.datastore import TubHandler\nfrom donkeycar.parts.controller import LocalWebController, JoystickController\nfrom donkeycar.parts.throttle_filter import ThrottleFilter\nfrom donkeycar.parts.behavior import BehaviorPart\nfrom donkeycar.parts.file_watcher import FileWatcher\nfrom donkeycar.parts.launch import AiLaunch\nfrom donkeycar.utils import *\n\ndef drive(cfg, model_path=None, use_joystick=False, model_type=None, camera_type='single', use_debug=False, meta=[] ):\n '''\n Construct a working robotic vehicle from many parts.\n Each part runs as a job in the Vehicle loop, calling either\n it's run or run_threaded method depending on the constructor flag `threaded`.\n All parts are updated one after another at the framerate given in\n cfg.DRIVE_LOOP_HZ assuming each part finishes processing in a timely manner.\n Parts may have named outputs and inputs. The framework handles passing named outputs\n to parts requesting the same named input.\n '''\n\n if cfg.DONKEY_GYM:\n #the simulator will use cuda and then we usually run out of resources\n #if we also try to use cuda. so disable for donkey_gym.\n os.environ[\"CUDA_VISIBLE_DEVICES\"]=\"-1\" \n\n if model_type is None:\n if cfg.TRAIN_LOCALIZER:\n model_type = \"localizer\"\n elif cfg.TRAIN_BEHAVIORS:\n model_type = \"behavior\"\n else:\n model_type = cfg.DEFAULT_MODEL_TYPE\n \n #Initialize car\n V = dk.vehicle.Vehicle()\n\n if camera_type == \"stereo\":\n\n if cfg.CAMERA_TYPE == \"WEBCAM\":\n from donkeycar.parts.camera import Webcam \n\n camA = Webcam(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH, iCam = 0)\n camB = Webcam(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH, iCam = 1)\n\n elif cfg.CAMERA_TYPE == \"CVCAM\":\n from donkeycar.parts.cv import CvCam\n\n camA = CvCam(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH, iCam = 0)\n camB = CvCam(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH, iCam = 1)\n else:\n raise(Exception(\"Unsupported camera type: %s\" % cfg.CAMERA_TYPE))\n\n V.add(camA, outputs=['cam/image_array_a'], threaded=True)\n V.add(camB, outputs=['cam/image_array_b'], threaded=True)\n\n from donkeycar.parts.image import StereoPair\n\n V.add(StereoPair(), inputs=['cam/image_array_a', 'cam/image_array_b'], \n outputs=['cam/image_array'])\n\n else:\n print(\"cfg.CAMERA_TYPE\", cfg.CAMERA_TYPE)\n if cfg.DONKEY_GYM:\n from donkeycar.parts.dgym import DonkeyGymEnv \n \n inputs = []\n threaded = True\n print(\"cfg.CAMERA_TYPE\", cfg.CAMERA_TYPE)\n if cfg.DONKEY_GYM:\n from donkeycar.parts.dgym import DonkeyGymEnv \n cam = DonkeyGymEnv(cfg.DONKEY_SIM_PATH, env_name=cfg.DONKEY_GYM_ENV_NAME)\n threaded = True\n inputs = ['angle', 'throttle']\n elif cfg.CAMERA_TYPE == \"PICAM\":\n from donkeycar.parts.camera import PiCamera\n cam = PiCamera(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH)\n elif cfg.CAMERA_TYPE == \"WEBCAM\":\n from donkeycar.parts.camera import Webcam\n cam = Webcam(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH)\n elif cfg.CAMERA_TYPE == \"CVCAM\":\n from donkeycar.parts.cv import CvCam\n cam = CvCam(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH)\n elif cfg.CAMERA_TYPE == \"CSIC\":\n from donkeycar.parts.camera import CSICamera\n cam = CSICamera(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH, framerate=cfg.CAMERA_FRAMERATE, gstreamer_flip=cfg.CSIC_CAM_GSTREAMER_FLIP_PARM)\n elif cfg.CAMERA_TYPE == \"V4L\":\n from donkeycar.parts.camera import V4LCamera\n cam = V4LCamera(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH, framerate=cfg.CAMERA_FRAMERATE)\n elif cfg.CAMERA_TYPE == \"MOCK\":\n from donkeycar.parts.camera import MockCamera\n cam = MockCamera(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH)\n else:\n raise(Exception(\"Unkown camera type: %s\" % cfg.CAMERA_TYPE))\n \n V.add(cam, inputs=inputs, outputs=['cam/image_array'], threaded=threaded)\n \n if use_joystick or cfg.USE_JOYSTICK_AS_DEFAULT:\n #modify max_throttle closer to 1.0 to have more power\n #modify steering_scale lower than 1.0 to have less responsive steering\n # 独自のファクトリ関数に変更\n #from donkeycar.parts.controller import get_js_controller\n from parts import get_js_controller\n \n ctr = get_js_controller(cfg)\n \n if cfg.USE_NETWORKED_JS:\n from donkeycar.parts.controller import JoyStickSub\n netwkJs = JoyStickSub(cfg.NETWORK_JS_SERVER_IP)\n V.add(netwkJs, threaded=True)\n ctr.js = netwkJs\n\n else: \n #This web controller will create a web server that is capable\n #of managing steering, throttle, and modes, and more.\n ctr = LocalWebController()\n\n \n V.add(ctr, \n inputs=['cam/image_array'],\n outputs=['user/angle', 'user/throttle', 'user/mode', 'recording'],\n threaded=True)\n\n #this throttle filter will allow one tap back for esc reverse\n th_filter = ThrottleFilter()\n V.add(th_filter, inputs=['user/throttle'], outputs=['user/throttle'])\n \n #See if we should even run the pilot module. \n #This is only needed because the part run_condition only accepts boolean\n class PilotCondition:\n def run(self, mode):\n if mode == 'user':\n return False\n else:\n return True \n\n V.add(PilotCondition(), inputs=['user/mode'], outputs=['run_pilot'])\n \n class LedConditionLogic:\n def __init__(self, cfg):\n self.cfg = cfg\n\n def run(self, mode, recording, recording_alert, behavior_state, model_file_changed, track_loc):\n #returns a blink rate. 0 for off. -1 for on. positive for rate.\n \n if track_loc is not None:\n led.set_rgb(*self.cfg.LOC_COLORS[track_loc])\n return -1\n\n if model_file_changed:\n led.set_rgb(self.cfg.MODEL_RELOADED_LED_R, self.cfg.MODEL_RELOADED_LED_G, self.cfg.MODEL_RELOADED_LED_B)\n return 0.1\n else:\n led.set_rgb(self.cfg.LED_R, self.cfg.LED_G, self.cfg.LED_B)\n\n if recording_alert:\n led.set_rgb(*recording_alert)\n return self.cfg.REC_COUNT_ALERT_BLINK_RATE\n else:\n led.set_rgb(self.cfg.LED_R, self.cfg.LED_G, self.cfg.LED_B)\n \n if behavior_state is not None and model_type == 'behavior':\n r, g, b = self.cfg.BEHAVIOR_LED_COLORS[behavior_state]\n led.set_rgb(r, g, b)\n return -1 #solid on\n\n if recording:\n return -1 #solid on\n elif mode == 'user':\n return 1\n elif mode == 'local_angle':\n return 0.5\n elif mode == 'local':\n return 0.1\n return 0\n\n if cfg.HAVE_RGB_LED and not cfg.DONKEY_GYM:\n from donkeycar.parts.led_status import RGB_LED\n led = RGB_LED(cfg.LED_PIN_R, cfg.LED_PIN_G, cfg.LED_PIN_B, cfg.LED_INVERT)\n led.set_rgb(cfg.LED_R, cfg.LED_G, cfg.LED_B) \n \n V.add(LedConditionLogic(cfg), inputs=['user/mode', 'recording', \"records/alert\", 'behavior/state', 'modelfile/modified', \"pilot/loc\"],\n outputs=['led/blink_rate'])\n\n V.add(led, inputs=['led/blink_rate'])\n \n\n def get_record_alert_color(num_records):\n col = (0, 0, 0)\n for count, color in cfg.RECORD_ALERT_COLOR_ARR:\n if num_records >= count:\n col = color\n return col \n\n class RecordTracker:\n def __init__(self):\n self.last_num_rec_print = 0\n self.dur_alert = 0\n self.force_alert = 0\n\n def run(self, num_records):\n if num_records is None:\n return 0\n \n if self.last_num_rec_print != num_records or self.force_alert:\n self.last_num_rec_print = num_records\n\n if num_records % 10 == 0:\n print(\"recorded\", num_records, \"records\")\n \n if num_records % cfg.REC_COUNT_ALERT == 0 or self.force_alert:\n self.dur_alert = num_records // cfg.REC_COUNT_ALERT * cfg.REC_COUNT_ALERT_CYC\n self.force_alert = 0\n \n if self.dur_alert > 0:\n self.dur_alert -= 1\n\n if self.dur_alert != 0:\n return get_record_alert_color(num_records)\n\n return 0\n\n rec_tracker_part = RecordTracker()\n V.add(rec_tracker_part, inputs=[\"tub/num_records\"], outputs=['records/alert'])\n\n if cfg.AUTO_RECORD_ON_THROTTLE and isinstance(ctr, JoystickController):\n #then we are not using the circle button. hijack that to force a record count indication\n def show_record_acount_status():\n rec_tracker_part.last_num_rec_print = 0\n rec_tracker_part.force_alert = 1\n ctr.set_button_down_trigger('circle', show_record_acount_status)\n\n #Sombrero\n if cfg.HAVE_SOMBRERO:\n from donkeycar.parts.sombrero import Sombrero\n s = Sombrero()\n\n #IMU\n if cfg.HAVE_IMU:\n from donkeycar.parts.imu import Mpu6050\n imu = Mpu6050()\n V.add(imu, outputs=['imu/acl_x', 'imu/acl_y', 'imu/acl_z',\n 'imu/gyr_x', 'imu/gyr_y', 'imu/gyr_z'], threaded=True)\n\n class ImgPreProcess():\n '''\n preprocess camera image for inference.\n normalize and crop if needed.\n '''\n def __init__(self, cfg):\n self.cfg = cfg\n\n def run(self, img_arr):\n return normalize_and_crop(img_arr, self.cfg)\n\n if \"coral\" in model_type:\n inf_input = 'cam/image_array'\n else:\n inf_input = 'cam/normalized/cropped'\n V.add(ImgPreProcess(cfg),\n inputs=['cam/image_array'],\n outputs=[inf_input],\n run_condition='run_pilot')\n\n #Behavioral state\n if cfg.TRAIN_BEHAVIORS:\n bh = BehaviorPart(cfg.BEHAVIOR_LIST)\n V.add(bh, outputs=['behavior/state', 'behavior/label', \"behavior/one_hot_state_array\"])\n try:\n ctr.set_button_down_trigger('L1', bh.increment_state)\n except:\n pass\n\n inputs = [inf_input, \"behavior/one_hot_state_array\"] \n #IMU\n elif model_type == \"imu\":\n assert(cfg.HAVE_IMU)\n #Run the pilot if the mode is not user.\n inputs=[inf_input,\n 'imu/acl_x', 'imu/acl_y', 'imu/acl_z',\n 'imu/gyr_x', 'imu/gyr_y', 'imu/gyr_z']\n else:\n inputs=[inf_input]\n\n def load_model(kl, model_path):\n start = time.time()\n print('loading model', model_path)\n kl.load(model_path)\n print('finished loading in %s sec.' % (str(time.time() - start)) )\n\n def load_weights(kl, weights_path):\n start = time.time()\n try:\n print('loading model weights', weights_path)\n kl.model.load_weights(weights_path)\n print('finished loading in %s sec.' % (str(time.time() - start)) )\n except Exception as e:\n print(e)\n print('ERR>> problems loading weights', weights_path)\n\n def load_model_json(kl, json_fnm):\n start = time.time()\n print('loading model json', json_fnm)\n try:\n from tensorflow.python import keras\n except:\n raise\n try:\n with open(json_fnm, 'r') as handle:\n contents = handle.read()\n kl.model = keras.models.model_from_json(contents)\n print('finished loading json in %s sec.' % (str(time.time() - start)) )\n except Exception as e:\n print(e)\n print(\"ERR>> problems loading model json\", json_fnm)\n\n if model_path:\n #When we have a model, first create an appropriate Keras part\n kl = dk.utils.get_model_by_type(model_type, cfg)\n\n model_reload_cb = None\n\n if '.h5' in model_path or '.uff' in model_path or 'tflite' in model_path or '.pkl' in model_path:\n #when we have a .h5 extension\n #load everything from the model file\n load_model(kl, model_path)\n\n def reload_model(filename):\n load_model(kl, filename)\n\n model_reload_cb = reload_model\n\n elif '.json' in model_path:\n #when we have a .json extension\n #load the model from there and look for a matching\n #.wts file with just weights\n load_model_json(kl, model_path)\n weights_path = model_path.replace('.json', '.weights')\n load_weights(kl, weights_path)\n\n def reload_weights(filename):\n weights_path = filename.replace('.json', '.weights')\n load_weights(kl, weights_path)\n \n model_reload_cb = reload_weights\n\n else:\n print(\"ERR>> Unknown extension type on model file!!\")\n return\n\n #this part will signal visual LED, if connected\n V.add(FileWatcher(model_path, verbose=True), outputs=['modelfile/modified'])\n\n #these parts will reload the model file, but only when ai is running so we don't interrupt user driving\n V.add(FileWatcher(model_path), outputs=['modelfile/dirty'], run_condition=\"ai_running\")\n V.add(DelayedTrigger(100), inputs=['modelfile/dirty'], outputs=['modelfile/reload'], run_condition=\"ai_running\")\n V.add(TriggeredCallback(model_path, model_reload_cb), inputs=[\"modelfile/reload\"], run_condition=\"ai_running\")\n\n outputs=['pilot/angle', 'pilot/throttle']\n\n if cfg.TRAIN_LOCALIZER:\n outputs.append(\"pilot/loc\")\n \n V.add(kl, inputs=inputs, \n outputs=outputs,\n run_condition='run_pilot') \n \n #Choose what inputs should change the car.\n class DriveMode:\n def run(self, mode, \n user_angle, user_throttle,\n pilot_angle, pilot_throttle):\n if mode == 'user': \n return user_angle, user_throttle\n \n elif mode == 'local_angle':\n return pilot_angle, user_throttle\n \n else: \n return pilot_angle, pilot_throttle * cfg.AI_THROTTLE_MULT\n \n V.add(DriveMode(), \n inputs=['user/mode', 'user/angle', 'user/throttle',\n 'pilot/angle', 'pilot/throttle'], \n outputs=['angle', 'throttle'])\n\n \n #to give the car a boost when starting ai mode in a race.\n aiLauncher = AiLaunch(cfg.AI_LAUNCH_DURATION, cfg.AI_LAUNCH_THROTTLE, cfg.AI_LAUNCH_KEEP_ENABLED)\n \n V.add(aiLauncher,\n inputs=['user/mode', 'throttle'],\n outputs=['throttle'])\n\n if isinstance(ctr, JoystickController):\n ctr.set_button_down_trigger(cfg.AI_LAUNCH_ENABLE_BUTTON, aiLauncher.enable_ai_launch)\n\n\n class AiRunCondition:\n '''\n A bool part to let us know when ai is running.\n '''\n def run(self, mode):\n if mode == \"user\":\n return False\n return True\n\n V.add(AiRunCondition(), inputs=['user/mode'], outputs=['ai_running'])\n\n #Ai Recording\n class AiRecordingCondition:\n '''\n return True when ai mode, otherwize respect user mode recording flag\n '''\n def run(self, mode, recording):\n if mode == 'user':\n return recording\n return True\n\n if cfg.RECORD_DURING_AI:\n V.add(AiRecordingCondition(), inputs=['user/mode', 'recording'], outputs=['recording'])\n \n #Drive train setup\n if cfg.DONKEY_GYM:\n pass\n\n elif cfg.DRIVE_TRAIN_TYPE == \"SERVO_ESC\":\n from donkeycar.parts.actuator import PCA9685, PWMSteering, PWMThrottle\n\n steering_controller = PCA9685(cfg.STEERING_CHANNEL, cfg.PCA9685_I2C_ADDR, busnum=cfg.PCA9685_I2C_BUSNUM)\n steering = PWMSteering(controller=steering_controller,\n left_pulse=cfg.STEERING_LEFT_PWM, \n right_pulse=cfg.STEERING_RIGHT_PWM)\n \n throttle_controller = PCA9685(cfg.THROTTLE_CHANNEL, cfg.PCA9685_I2C_ADDR, busnum=cfg.PCA9685_I2C_BUSNUM)\n throttle = PWMThrottle(controller=throttle_controller,\n max_pulse=cfg.THROTTLE_FORWARD_PWM,\n zero_pulse=cfg.THROTTLE_STOPPED_PWM, \n min_pulse=cfg.THROTTLE_REVERSE_PWM)\n\n V.add(steering, inputs=['angle'])\n V.add(throttle, inputs=['throttle'])\n \n\n elif cfg.DRIVE_TRAIN_TYPE == \"DC_STEER_THROTTLE\":\n from donkeycar.parts.actuator import Mini_HBridge_DC_Motor_PWM\n \n steering = Mini_HBridge_DC_Motor_PWM(cfg.HBRIDGE_PIN_LEFT, cfg.HBRIDGE_PIN_RIGHT)\n throttle = Mini_HBridge_DC_Motor_PWM(cfg.HBRIDGE_PIN_FWD, cfg.HBRIDGE_PIN_BWD)\n\n V.add(steering, inputs=['angle'])\n V.add(throttle, inputs=['throttle'])\n \n\n elif cfg.DRIVE_TRAIN_TYPE == \"DC_TWO_WHEEL\":\n from donkeycar.parts.actuator import TwoWheelSteeringThrottle, Mini_HBridge_DC_Motor_PWM\n\n left_motor = Mini_HBridge_DC_Motor_PWM(cfg.HBRIDGE_PIN_LEFT_FWD, cfg.HBRIDGE_PIN_LEFT_BWD)\n right_motor = Mini_HBridge_DC_Motor_PWM(cfg.HBRIDGE_PIN_RIGHT_FWD, cfg.HBRIDGE_PIN_RIGHT_BWD)\n two_wheel_control = TwoWheelSteeringThrottle()\n\n V.add(two_wheel_control, \n inputs=['throttle', 'angle'],\n outputs=['left_motor_speed', 'right_motor_speed'])\n\n V.add(left_motor, inputs=['left_motor_speed'])\n V.add(right_motor, inputs=['right_motor_speed'])\n\n elif cfg.DRIVE_TRAIN_TYPE == \"SERVO_HBRIDGE_PWM\":\n from donkeycar.parts.actuator import ServoBlaster, PWMSteering\n steering_controller = ServoBlaster(cfg.STEERING_CHANNEL) #really pin\n #PWM pulse values should be in the range of 100 to 200\n assert(cfg.STEERING_LEFT_PWM <= 200)\n assert(cfg.STEERING_RIGHT_PWM <= 200)\n steering = PWMSteering(controller=steering_controller,\n left_pulse=cfg.STEERING_LEFT_PWM, \n right_pulse=cfg.STEERING_RIGHT_PWM)\n \n\n from donkeycar.parts.actuator import Mini_HBridge_DC_Motor_PWM\n motor = Mini_HBridge_DC_Motor_PWM(cfg.HBRIDGE_PIN_FWD, cfg.HBRIDGE_PIN_BWD)\n\n V.add(steering, inputs=['angle'])\n V.add(motor, inputs=[\"throttle\"])\n # DC2モータ pigpio制御、TB6612 ジャンパ設定無し\n elif cfg.DRIVE_TRAIN_TYPE == \"DC_TWO_WHEEL_PIGPIO\":\n try:\n import pigpio\n except:\n raise\n # pigpio 制御開始\n pgio = pigpio.pi()\n\n from parts import PIGPIO_OUT, PIGPIO_PWM, CaterpillerMotorDriver\n\n # TB6612 STBY ピン初期化\n stby = PIGPIO_OUT(pin=cfg.TB6612_STBY_GPIO, pgio=pgio, debug=use_debug)\n stby.run(1)\n\n # ジョイスティック出力値をDCモータ入力値に変換\n driver = CaterpillerMotorDriver(\n left_balance=cfg.LEFT_PWM_BALANCE, \n right_balance=cfg.RIGHT_PWM_BALANCE,\n debug=use_debug)\n V.add(driver, \n inputs=['throttle', 'angle'],\n outputs=['left_motor_vref', 'left_motor_in1', 'left_motor_in2',\n 'right_motor_vref', 'right_motor_in1', 'right_motor_in2'])\n\n # 左モータ制御\n left_in1 = PIGPIO_OUT(pin=cfg.LEFT_MOTOR_IN1_GPIO, pgio=pgio, debug=use_debug)\n left_in2 = PIGPIO_OUT(pin=cfg.LEFT_MOTOR_IN2_GPIO, pgio=pgio, debug=use_debug)\n left_vref = PIGPIO_PWM(pin=cfg.LEFT_MOTOR_PWM_GPIO, pgio=pgio, freq=cfg.PWM_FREQ, range=cfg.PWM_RANGE, debug=use_debug)\n V.add(left_in1, inputs=['left_motor_in1'])\n V.add(left_in2, inputs=['left_motor_in2'])\n V.add(left_vref, inputs=['left_motor_vref']) \n\n # 右モータ制御\n right_in1 = PIGPIO_OUT(pin=cfg.RIGHT_MOTOR_IN1_GPIO, pgio=pgio, debug=use_debug)\n right_in2 = PIGPIO_OUT(pin=cfg.RIGHT_MOTOR_IN2_GPIO, pgio=pgio, debug=use_debug)\n right_vref = PIGPIO_PWM(pin=cfg.RIGHT_MOTOR_PWM_GPIO, pgio=pgio, freq=cfg.PWM_FREQ, range=cfg.PWM_RANGE, debug=use_debug)\n V.add(right_in1, inputs=['right_motor_in1'])\n V.add(right_in2, inputs=['right_motor_in2'])\n V.add(right_vref, inputs=['right_motor_vref'])\n\n \n #add tub to save data\n\n inputs=['cam/image_array',\n 'user/angle', 'user/throttle', \n 'user/mode']\n\n types=['image_array',\n 'float', 'float',\n 'str']\n\n if cfg.TRAIN_BEHAVIORS:\n inputs += ['behavior/state', 'behavior/label', \"behavior/one_hot_state_array\"]\n types += ['int', 'str', 'vector']\n \n if cfg.HAVE_IMU:\n inputs += ['imu/acl_x', 'imu/acl_y', 'imu/acl_z',\n 'imu/gyr_x', 'imu/gyr_y', 'imu/gyr_z']\n\n types +=['float', 'float', 'float',\n 'float', 'float', 'float']\n\n if cfg.RECORD_DURING_AI:\n inputs += ['pilot/angle', 'pilot/throttle']\n types += ['float', 'float']\n \n th = TubHandler(path=cfg.DATA_PATH)\n tub = th.new_tub_writer(inputs=inputs, types=types, user_meta=meta)\n V.add(tub, inputs=inputs, outputs=[\"tub/num_records\"], run_condition='recording')\n\n if cfg.PUB_CAMERA_IMAGES:\n from donkeycar.parts.network import TCPServeValue\n from donkeycar.parts.image import ImgArrToJpg\n pub = TCPServeValue(\"camera\")\n V.add(ImgArrToJpg(), inputs=['cam/image_array'], outputs=['jpg/bin'])\n V.add(pub, inputs=['jpg/bin'])\n\n if type(ctr) is LocalWebController:\n print(\"You can now go to <your pis hostname.local>:8887 to drive your car.\")\n elif isinstance(ctr, JoystickController):\n print(\"You can now move your joystick to drive your car.\")\n #tell the controller about the tub \n ctr.set_tub(tub)\n \n if cfg.BUTTON_PRESS_NEW_TUB:\n \n def new_tub_dir():\n V.parts.pop()\n tub = th.new_tub_writer(inputs=inputs, types=types, user_meta=meta)\n V.add(tub, inputs=inputs, outputs=[\"tub/num_records\"], run_condition='recording')\n ctr.set_tub(tub)\n \n ctr.set_button_down_trigger('cross', new_tub_dir)\n ctr.print_controls()\n\n try:\n print('Start driving')\n #run the vehicle for 20 seconds\n V.start(rate_hz=cfg.DRIVE_LOOP_HZ, max_loop_count=cfg.MAX_LOOPS)\n except KeyboardInterrupt:\n print('Halt driving')\n finally:\n if stby is not None:\n stby.run(0)\n if use_debug:\n print('Stop TB6612 STBY')\n if pgio is not None:\n pgio.stop()\n if use_debug:\n print('Stop pigpio controll')\n print('Stop driving')\n\nif __name__ == '__main__':\n args = docopt(__doc__)\n cfg = dk.load_config()\n \n if args['drive']:\n model_type = args['--type']\n camera_type = args['--camera']\n drive(cfg, model_path=args['--model'], use_joystick=args['--js'], model_type=model_type, camera_type=camera_type,\n use_debug=args['--debug'], meta=args['--meta'])\n \n if args['train']:\n from train import multi_train, preprocessFileList\n \n tub = args['--tub']\n model = args['--model']\n transfer = args['--transfer']\n model_type = args['--type']\n continuous = args['--continuous']\n aug = args['--aug'] \n\n dirs = preprocessFileList( args['--file'] )\n if tub is not None:\n tub_paths = [os.path.expanduser(n) for n in tub.split(',')]\n dirs.extend( tub_paths )\n\n multi_train(cfg, dirs, model, transfer, model_type, continuous, aug)\n\n"
] |
[
[
"tensorflow.python.keras.models.model_from_json"
]
] |
opietx/core_tools
|
[
"d5bd2d4beed74791b80ff5bdabd67774403763ef"
] |
[
"core_tools/GUI/virt_gate_matrix_qml/gui_controller.py"
] |
[
"from core_tools.GUI.virt_gate_matrix_qml.models import attenuation_model, table_header_model, vg_matrix_model\nfrom core_tools.drivers.hardware.hardware import hardware\n\nfrom PyQt5 import QtCore, QtQuick, QtGui, QtWidgets, QtQml\n\nimport core_tools.GUI.virt_gate_matrix_qml as qml_in\nimport os, sys\n\nclass virt_gate_matrix_GUI:\n def __init__(self):\n super().__init__()\n # self.app = QtGui.QGuiApplication(sys.argv)\n self.app = QtCore.QCoreApplication.instance()\n self.instance_ready = True\n if self.app is None:\n self.instance_ready = False\n self.app = QtWidgets.QApplication([])\n\n hw = hardware()\n self.engine = QtQml.QQmlApplicationEngine()\n\n self.attenuation_model = attenuation_model(hw.awg2dac_ratios)\n self.engine.rootContext().setContextProperty(\"attenuation_model\", self.attenuation_model)\n \n if len(hw.virtual_gates) > 0:\n self.row_header_model = table_header_model(hw.virtual_gates[0].gates)\n self.column_header_model = table_header_model(hw.virtual_gates[0].v_gates)\n self.vg_matrix_model = vg_matrix_model(hw.virtual_gates[0])\n\n self.engine.rootContext().setContextProperty('row_header_model', self.row_header_model)\n self.engine.rootContext().setContextProperty('column_header_model', self.column_header_model)\n self.engine.rootContext().setContextProperty('vg_matrix_model', self.vg_matrix_model)\n # grab directory from the import!\n\n filename = os.path.join(qml_in.__file__[:-12], \"virt_gate_matrix_gui.qml\")\n self.engine.load(QtCore.QUrl.fromLocalFile(filename))\n self.win = self.engine.rootObjects()[0]\n\n timer = QtCore.QTimer()\n timer.timeout.connect(lambda: None)\n timer.start(100)\n\n if self.instance_ready == False:\n self.app.exec_()\n print('exec')\n \n\n def update_data(self):\n self.singal_hander.update_data()\n\n def set_data(self):\n '''just update all...'''\n self.singal_hander.set_data()\n\n\nif __name__ == \"__main__\":\n import numpy as np\n\n\n from core_tools.data.SQL.connect import set_up_local_storage, set_up_remote_storage, set_up_local_and_remote_storage\n from core_tools.drivers.hardware.hardware import hardware\n set_up_local_storage('stephan', 'magicc', 'test', 'test_project1', 'test_set_up', 'test_sample')\n\n h = hardware()\n h.dac_gate_map = {\n # dacs for creating the quantum dots -- syntax, \"gate name\": (dac module number, dac index)\n 'B0': (0, 1), 'P1': (0, 2), \n 'B1': (0, 3), 'P2': (0, 4),\n 'B2': (0, 5), 'P3': (0, 6), \n 'B3': (0, 7), 'P4': (0, 8), \n 'B4': (0, 9), 'P5': (0, 10),\n 'B5': (0, 11),'P6': (0, 12),\n 'B6': (0, 13)}\n\n h.boundaries = {'B0' : (0, 2000), 'B1' : (0, 2500)}\n h.awg2dac_ratios.add(['P1', 'P2', 'P3', 'P4', 'P5', 'P6', 'B0', 'B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'S6', 'SD1_P', 'SD2_P'])\n h.virtual_gates.add('test', ['B0', 'P1', 'B1', 'P2', 'B2', 'P3', 'B3', 'P4', 'B4', 'P5', 'B5', 'P6', 'B6', 'S6', 'SD1_P', 'SD2_P', 'COMP1', 'COMP2', 'COMP3'])\n \n a = np.array([[ 1.00000000e+00, 0.00000000e+00, 0.00000000e+00,0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00],\n [ 6.49707806e-02, 2.82481655e-01, 4.90827766e-02, 7.81982372e-02, 3.10296188e-02, 3.77927331e-02, 2.04070954e-02, 1.92595334e-02, 5.77896842e-03, 5.23641473e-03, 1.07451230e-03, 1.20437539e-03, 1.08393785e-04, 4.03374906e-01, -5.72633650e-18,-1.75608355e-18],\n [ 0.00000000e+00, 0.00000000e+00, 1.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00],\n [ 2.02412952e-02, 8.80056311e-02, 3.92602899e-02, 1.95568069e-01, 7.67383245e-02, 8.68695232e-02, 1.71876988e-02, 3.15420382e-02, 1.04634263e-02, 8.57586683e-03, 1.75976787e-03, 1.97244937e-03, 1.77520443e-04, 4.21638099e-01, -6.07292953e-18,-1.83177706e-18],\n [ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 1.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00],\n [ 8.60939992e-03, 3.74321735e-02, 1.66989085e-02, 8.31826079e-02, 6.54671507e-02, 2.13066308e-01, 3.27095776e-02, 7.33179851e-02, 2.47674300e-02, 1.99341993e-02, 4.09049770e-03, 4.58486584e-03, 4.12637926e-04, 4.15726257e-01, -6.28931174e-18,-1.80691524e-18],\n [ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 1.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00],\n [ 4.58831882e-03, 1.99492123e-02, 8.89956525e-03, 4.43315828e-02, 2.80054449e-02, 1.13552183e-01, 3.98079716e-02, 2.11194559e-01, 5.13356355e-02, 5.74210329e-02, 1.17827960e-02, 1.32068376e-02, 1.18861538e-03, 3.94736245e-01, -6.75019910e-18,-1.87957376e-18],\n [-1.13747604e-18, -2.83748185e-18, -7.02765838e-18,-4.57657416e-18, -4.04289212e-18, 2.25759347e-18, 6.47263042e-19, 9.97668597e-19, 1.00000000e+00, 1.73576902e-18, 3.49023532e-18, 1.32946821e-19, 7.14528222e-19, -5.41853938e-18, -1.12757026e-17, 7.80625564e-18],\n [ 2.21371708e-03, 9.62485689e-03, 4.29375560e-03, 2.13885709e-02, 1.35117315e-02, 5.47852965e-02, 1.92060731e-02, 1.01894620e-01, 7.54102430e-02, 1.96511948e-01, 4.03242517e-02, 4.51977480e-02, 4.06779732e-03, 4.11569391e-01, -8.93461466e-18,-3.14152001e-18],\n [-8.35738386e-19, -6.33704886e-19, 4.92852218e-18, 1.05218305e-18, 7.04962177e-19, -5.48017677e-18,-5.04760983e-18, -4.34445449e-18, -4.09613329e-18, 6.19746588e-18, 1.00000000e+00, -1.69256457e-18, 1.76562364e-18, -2.67784151e-17, -1.60461922e-17,-3.46944695e-18],\n [ 6.76113171e-04, 2.93962248e-03, 1.31139825e-03, 6.53249440e-03, 4.12675119e-03, 1.67325178e-02, 5.86591624e-03, 3.11206410e-02, 3.44094639e-02, 9.79442448e-02, 7.65184375e-02, 2.57611670e-01, 2.31850503e-02, 4.41025679e-01, -1.22523239e-17,-5.10733335e-18],\n [-2.36436087e-18, -5.90153867e-18, -1.45662517e-17,-9.52365278e-18, -8.66682292e-18, 4.83219219e-18,-1.51760539e-18, -6.44912262e-18, -1.31916453e-18,-6.73012624e-18, -1.09864362e-18, -4.47246990e-19, 1.00000000e+00, -2.79469603e-17, -2.34187669e-17,-2.60208521e-18],\n [-3.66373083e-17, -2.93006203e-17, -2.40292394e-17,-7.56924908e-17, -2.66398315e-17, 4.13863597e-17, 4.98254165e-18, -7.91675124e-18, -1.66866457e-16, 1.46595361e-16, 7.40710493e-16, 3.33829987e-17,-1.01078939e-16, 1.00000000e+00, -1.38777878e-17,-4.33680869e-18],\n [ 3.94710178e-02, 4.92640444e-02, 4.00235624e-03, 9.13044283e-03, 3.35657030e-03, 3.06239735e-03, 3.05006789e-03, 2.15866106e-03, 6.00781938e-04, 5.86911653e-04, 1.20434271e-04, 1.34989680e-04, 1.21490712e-05, 2.30623884e-01, 6.54425292e-01,-2.13653863e-18],\n [ 1.66746471e-04, 7.24984657e-04, 3.23423711e-04, 1.61107701e-03, 1.01776038e-03, 4.12665870e-03, 1.44668212e-03, 7.67513087e-03, 5.87574735e-03, 1.54538756e-02, 1.14956970e-02, 5.93898666e-02, 7.06073317e-02, 9.49489762e-02, -1.25916980e-17, 7.25136042e-01]])\n \n # h.virtual_gates.test.matrix = a #np.linalg.inv(a)\n\n\n g = virt_gate_matrix_GUI()\n\n\n\n\n\n "
] |
[
[
"numpy.array"
]
] |
xieyulai/MSP-STTN-BJ
|
[
"d691a20e32963330a6024c77284fed6c00b68fed"
] |
[
"record/3548/pre_main_short.py"
] |
[
"import warnings\nwarnings.filterwarnings('ignore')\nimport pickle\nimport numpy as np\nimport time\nimport sys\nimport cv2\nimport random\nimport torch\nimport torch.optim as optim\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.utils.data import Dataset, DataLoader, TensorDataset\nimport argparse\nimport os\nimport math\nfrom time import localtime, strftime\nfrom sklearn import metrics\nfrom einops import rearrange\nimport matplotlib.pyplot as plt\n\ntorch.backends.cudnn.benchmark = True\nfrom util.util import timeSince, get_yaml_data\nfrom util.util import weights_init, VALRMSE, VALMAPE\nfrom tensorboardX import SummaryWriter\nimport shutil\n\nprint('TORCH_VERSION',torch.__version__)\nprint('CUDNN VERSION',torch.backends.cudnn.version())\nprint('CUDNN AVAILIABlE',torch.backends.cudnn.is_available())\ntorch.backends.cudnn.enabled = True\ntorch.backends.cudnn.deterministic = False\ntorch.backends.cudnn.benchmark = True\n#print('CUDNN DETERMINISTIC', torch.are_deterministic_algorithms_enabled())\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0,1,2,3\"\n\nTORCH_VERSION = torch.__version__\n\nlog_name = 'logs/taxibj_'\n\n# seed = 777\n\n\nclass DataConfiguration:\n def __init__(self, Len_close, Len_period, Len_trend):\n super().__init__()\n\n # Data\n self.name = 'TaxiBJ'\n self.portion = 1. # portion of data\n\n self.len_close = Len_close\n self.len_period = Len_period\n self.len_trend = Len_trend\n self.pad_forward_period = 0\n self.pad_back_period = 0\n self.pad_forward_trend = 0\n self.pad_back_trend = 0\n\n self.len_all_close = self.len_close * 1\n self.len_all_period = self.len_period * (1 + self.pad_back_period + self.pad_forward_period)\n self.len_all_trend = self.len_trend * (1 + self.pad_back_trend + self.pad_forward_trend)\n\n self.len_seq = self.len_all_close + self.len_all_period + self.len_all_trend\n self.cpt = [self.len_all_close, self.len_all_period, self.len_all_trend]\n\n self.interval_period = 1\n self.interval_trend = 7\n\n self.ext_flag = True\n self.ext_time_flag = True\n self.rm_incomplete_flag = True\n self.fourty_eight = True\n self.previous_meteorol = True\n\n self.dim_h = 32\n self.dim_w = 32\n\n\ndef run(mcof):\n IS_TRAIN = 0\n IS_VAL = 0\n ####SETTING####\n TASK_TYPE = mcof.task\n INP_TYPE = mcof.inp_type\n DATA_TYPE = mcof.dataset_type\n CONTEXT_TYPE = mcof.context_type\n RECORD_ID = mcof.record\n PRESUME_RECORD_ID = mcof.presume_record\n EPOCH_S = mcof.epoch_s\n PRESUME_EPOCH_S = mcof.presume_epoch_s\n IS_REMOVE = mcof.is_remove\n IS_BEST = mcof.best\n\n if len(mcof.mode) > 1:\n if mcof.mode == 'train':\n IS_TRAIN = 1\n setting = get_yaml_data(\"./pre_setting_bj.yaml\")\n BATCH_SIZE = setting['TRAIN']['BATCH_SIZE']\n if mcof.mode == 'val':\n IS_VAL = 1\n RECORD_ID = mcof.record\n setting = get_yaml_data(f\"./record/{RECORD_ID}/pre_setting_bj.yaml\")\n EVAL_BATCH = setting['TRAIN']['EVAL_BATCH']\n\n ####SETTING####\n IS_BEST_EVAL = setting['TRAIN']['IS_BEST_EVAL']\n DROPOUT = setting['TRAIN']['DROPOUT']\n MERGE = setting['TRAIN']['MERGE']\n PATCH_LIST = setting['TRAIN']['PATCH_LIST']\n IS_USING_SKIP = setting['TRAIN']['IS_USING_SKIP']\n MODEL_DIM = setting['TRAIN']['MODEL_DIM']\n ATT_NUM = setting['TRAIN']['ATT_NUM']\n CROSS_ATT_NUM = setting['TRAIN']['CROSS_ATT_NUM']\n IS_MASK_ATT = setting['TRAIN']['IS_MASK_ATT']\n IS_SCALE = setting['TRAIN']['IS_SCALE']\n LR_G = setting['TRAIN']['LR_G']\n EPOCH_E = setting['TRAIN']['EPOCH']\n WARMUP_EPOCH = setting['TRAIN']['WARMUP_EPOCH']\n MILE_STONE = setting['TRAIN']['MILE_STONE']\n LOSS_GEN = setting['TRAIN']['LOSS_GEN']\n LOSS_TIME = setting['TRAIN']['LOSS_TIME']\n LOSS_TYP = setting['TRAIN']['LOSS_TYP']\n # LOSS_VGG = setting['TRAIN']['LOSS_VGG']\n LEN_CLOSE = setting['TRAIN']['LEN_CLOSE']\n LEN_PERIOD = setting['TRAIN']['LEN_PERIOD']\n LEN_TREND = setting['TRAIN']['LEN_TREND']\n LENGTH = setting['TRAIN']['LENGTH']\n IS_SEQ = setting['TRAIN']['IS_SEQ']\n SEQ_LEN_TEST = setting['TRAIN']['SEQ_LEN_TEST']\n SEQ_LEN_TRAIN = setting['TRAIN']['SEQ_LEN_TRAIN']\n OUT_STYLE = setting['TRAIN']['OUT_STYLE']\n CAT_STYLE = setting['TRAIN']['CAT_STYLE']\n IS_AUX = setting['TRAIN']['IS_AUX']\n IS_C3D = setting['TRAIN']['IS_C3D']\n ONLY_CONV6 = setting['TRAIN']['ONLY_CONV6']\n TRANS_RESIDUAL = setting['TRAIN']['TRANS_RESIDUAL']\n #IS_REDUCE = setting['TRAIN']['IS_REDUCE']\n EVAL_START_EPOCH = setting['TRAIN']['EVAL_START_EPOCH']\n seed = setting['TRAIN']['SEED']\n IS_DETERMINISTIC = setting['TRAIN']['IS_DETERMINISTIC']\n BATCH_SIZE = setting['TRAIN']['BATCH_SIZE']\n EVAL_MODE = setting['TRAIN']['EVAL_MODE']\n ITERATION_STEP = setting['TRAIN']['ITERATION_STEP']\n\n print(setting)\n\n C = 2\n H = 32\n W = 32\n\n if CONTEXT_TYPE == 'cpte':\n from dataset.dataset_cpte import DatasetFactory\n else:\n from dataset.dataset import DatasetFactory\n\n dconf = DataConfiguration(Len_close=LEN_CLOSE,\n Len_period=LEN_PERIOD,\n Len_trend=LEN_TREND,\n )\n ds_factory = DatasetFactory(dconf, INP_TYPE, DATA_TYPE, LENGTH, IS_SEQ)\n\n if IS_TRAIN:\n\n try:\n if os.path.exists('./record/{}/'.format(RECORD_ID)):\n shutil.rmtree('./record/{}/'.format(RECORD_ID))\n os.makedirs('./record/{}/'.format(RECORD_ID))\n\n oldname = os.getcwd() + os.sep\n newname = f'./record/{RECORD_ID}/'\n shutil.copyfile(oldname + 'pre_setting_bj.yaml', newname + 'pre_setting_bj.yaml')\n shutil.copyfile(oldname + 'pre_main_short.py', newname + 'pre_main_short.py')\n shutil.copytree(oldname + 'net', newname + 'net')\n shutil.copytree(oldname + 'dataset', newname + 'dataset')\n except:\n raise print('record directory not find!')\n\n record = open(\"record/{}/log.txt\".format(RECORD_ID), \"w\")\n\n curr_time = strftime('%y%m%d%H%M%S', localtime())\n Keep_Train = mcof.keep_train\n\n if IS_DETERMINISTIC:\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n torch.backends.cudnn.enabled = True\n torch.backends.cudnn.benchmark = True\n torch.backends.cudnn.deterministic = True\n #torch.backends.cudnn.benchmark = True\n #### 数据加载和预处理 ###\n # np.random.seed(seed)\n # torch.manual_seed(seed)\n # torch.backends.cudnn.deterministic = True\n # torch.backends.cudnn.benchmark = False\n\n train_ds = ds_factory.get_train_dataset()\n #train_ds = ds_factory.get_test_dataset()\n\n train_loader = DataLoader(\n dataset=train_ds,\n batch_size=BATCH_SIZE,\n shuffle=True,\n num_workers=1\n )\n\n ####MODEL####\n input_channels = C\n\n P_list = eval(PATCH_LIST)\n Is_scaling = IS_SCALE\n\n from net.imp_pos_cl_heat2heat import Prediction_Model as Model\n\n net = Model(\n mcof,\n Length=LENGTH, # 8\n Width=W, # 200\n Height=H, # 200\n Input_dim=input_channels, # 1\n Patch_list=P_list, # 小片段的大小\n Dropout=DROPOUT,\n Att_num=ATT_NUM, # 2\n Cross_att_num=CROSS_ATT_NUM, # 2\n Using_skip=IS_USING_SKIP, # 1\n Encoding_dim=MODEL_DIM, # 256\n Embedding_dim=MODEL_DIM, # 256\n Is_mask=IS_MASK_ATT, # 1\n #Is_reduce=IS_REDUCE,\n Is_scaling=Is_scaling, # 1\n Debugging=0, # 0\n Merge=MERGE, # cross-attention\n Out_style=OUT_STYLE,\n Cat_style=CAT_STYLE,\n Is_aux=IS_AUX,\n IS_C3D=IS_C3D,\n ONLY_CONV6=ONLY_CONV6,\n TRANS_RESIDUAL=TRANS_RESIDUAL,\n )\n\n ####TRAINING####\n print('SHORT TRAINING START')\n print('-' * 30)\n\n writer_gen = SummaryWriter(f'runs/exp_gen/{curr_time[2:]}')\n writer_val = SummaryWriter(f'runs/exp_val/{curr_time[2:]}')\n print(f'Runs procedure in {curr_time[2:]} file')\n\n start = time.time()\n\n device = torch.device('cuda:0') if torch.cuda.is_available() else torch.device('cpu')\n device_ids = [i for i in range(torch.cuda.device_count())]\n\n #### Optimizer ####\n optimizer = optim.Adam(net.parameters(), lr=eval(LR_G))\n # scheduler = optim.lr_scheduler.MultiStepLR(optimizer, milestones=eval(MILE_STONE), gamma=0.1)\n\n gamma = 0.5\n warm_up_with_multistep_lr = lambda epoch: epoch / int(WARMUP_EPOCH) if epoch <= int(\n WARMUP_EPOCH) else gamma ** len([m for m in eval(MILE_STONE) if m <= epoch])\n scheduler = optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=warm_up_with_multistep_lr)\n\n #### Loss Function ####\n # criterion = torch.nn.MSELoss()\n criterion = torch.nn.L1Loss()\n class_criterion = nn.CrossEntropyLoss()\n\n if Keep_Train:\n path = './model/All/MinMax/Short/Imp_{}/pre_model_ep_{}.pth'.format(PRESUME_RECORD_ID, PRESUME_EPOCH_S)\n #path = './model/{}/MinMax/Short/Imp_{}/pre_model_{}.pth'.format(DATA_TYPE, PRESUME_RECORD_ID, PRESUME_EPOCH_S)\n # net.load_state_dict(torch.load(path))\n print(path)\n pretrained_dict = torch.load(path)\n net_dict = net.state_dict()\n pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in net_dict}\n net_dict.update(pretrained_dict)\n net.load_state_dict(net_dict)\n else:\n pass\n\n #### 训练设备准备\n net = net.to(device)\n net = nn.DataParallel(net, device_ids=device_ids)\n\n #### Training ####\n it = 0\n for epoch in range(0, EPOCH_E):\n\n if IS_DETERMINISTIC == 0:\n train_loader = DataLoader(\n dataset=train_ds,\n batch_size=BATCH_SIZE,\n shuffle=True,\n num_workers=1\n )\n\n epoch_start = time.time()\n\n net.train()\n epoch_rmse_list = []\n for i, data in enumerate(train_loader):\n\n con, ave, ave_q, label, tim_cls, typ_cls = data\n\n B, T, C, H, W = con.shape\n ave = ave.to(device)\n ave_q = ave_q.to(device)\n con = con.to(device)\n label = label.to(device)\n tim_cls = tim_cls.squeeze().to(device)\n typ_cls = typ_cls.squeeze().to(device)\n\n optimizer.zero_grad()\n\n out, tim_out, typ_out,att_map = net(ave, ave_q, con)\n\n out = out.reshape(B, T, C, H, W)\n\n #### 将模型输出进行均值处理 ####\n #train\n if IS_SEQ:\n oup = out[:,:SEQ_LEN_TRAIN]\n label = label[:,:SEQ_LEN_TRAIN]\n else:\n oup = out[:, 0].to(device)\n label = label\n\n loss_gen = criterion(oup, label)\n loss_tim = class_criterion(tim_out, tim_cls.long())\n loss_typ = class_criterion(typ_out, typ_cls.long())\n\n loss = LOSS_GEN * loss_gen + LOSS_TIME * loss_tim + LOSS_TYP * loss_typ\n\n loss.backward()\n optimizer.step()\n\n net.eval()\n out, tim_out, typ_out,att_map = net(ave, ave_q, con)\n\n _, out_tim = torch.max(torch.softmax(tim_out, 1), 1)\n out_tim = out_tim.cpu().numpy()\n cls_tim = tim_cls.long().cpu().numpy()\n tim_score = round(metrics.accuracy_score(out_tim, cls_tim) * 100, 2)\n\n _, out_typ = torch.max(torch.softmax(typ_out, 1), 1)\n out_typ = out_typ.cpu().numpy()\n cls_typ = typ_cls.long().cpu().numpy()\n typ_score = round(metrics.accuracy_score(out_typ, cls_typ) * 100, 2)\n\n net.train()\n\n rmse = VALRMSE(oup, label, ds_factory.ds, ds_factory.dataset.m_factor)\n epoch_rmse_list.append(rmse.item())\n #if it % 20 == 0:\n if i % ITERATION_STEP == 0:\n c_lr = scheduler.get_last_lr()\n loss_info = 'TT:{:.6f},G: {:.6f},C:{:.6f},T:{:.6f}'.format(loss.item(), loss_gen.item(),loss_tim.item(), loss_typ.item())\n _it = '{0:03d}'.format(i)\n info = '-- It:{}/{},<bat_RMSE>:{:.2f},{},Tim:{},Typ:{},lr:{}'.format(_it,len(train_loader),rmse, loss_info, tim_score, typ_score, c_lr)\n print(info)\n record.write(info + '\\n')\n\n info_matrix = \"[epoch %d][%d/%d] mse: %.4f rmse: %.4f RECORD:%s\" % (\n epoch, i + 1, len(train_loader), loss_gen.item(), rmse.item(),RECORD_ID)\n record.write(info_matrix + '\\n')\n #print(info_matrix)\n writer_val.add_scalar('mse', loss_gen.item(), it)\n writer_val.add_scalar('rmse', rmse.item(), it)\n writer_val.add_scalar('Tim classifier accuracy', metrics.accuracy_score(out_tim, cls_tim) * 100, it)\n\n writer_gen.add_scalar('Union', loss.item() * 10, it)\n writer_gen.add_scalar('Generator', loss_gen.item() * 10, it)\n writer_gen.add_scalar('Tim Classifier', loss_tim.item() * 10, it)\n writer_gen.add_scalar('TYP Classifier', loss_typ.item() * 10, it)\n writer_gen.add_scalar('lr', optimizer.param_groups[0]['lr'], it)\n\n if it % ITERATION_STEP == 0:\n dirs = './model/All/MinMax/Short/Imp_{}'.format(RECORD_ID)\n if not os.path.exists(dirs):os.makedirs(dirs)\n model_path = os.path.join(dirs, f'pre_model_it_{it}.pth')\n if TORCH_VERSION == '1.6.0' or TORCH_VERSION == '1.7.0':\n torch.save(net.cpu().module.state_dict(), model_path, _use_new_zipfile_serialization=False)\n else:\n torch.save(net.cpu().module.state_dict(), model_path)\n net = net.to(device)\n\n it += 1\n\n\n mean_rmse = np.mean(np.array(epoch_rmse_list))\n t = timeSince(start)\n epoch_t = timeSince(epoch_start)\n loss_info = 'D:{:.6f}'.format(loss.item())\n info = 'EPOCH:{}/{},Mean_RMSE {},Loss {} Time {},Epoch_Time {}'.format(epoch+1, EPOCH_E, mean_rmse,loss_info, t,epoch_t)\n print(info)\n record.write(info + '\\n')\n scheduler.step()\n\n if (epoch + 1) % 1 == 0:\n\n dirs = './model/{}/MinMax/Short/Imp_{}'.format(DATA_TYPE, RECORD_ID)\n if not os.path.exists(dirs):\n os.makedirs(dirs)\n model_path = os.path.join(dirs, f'pre_model_ep_{epoch + 1}.pth')\n\n if TORCH_VERSION == '1.6.0' or TORCH_VERSION == '1.7.0':\n torch.save(net.cpu().module.state_dict(), model_path, _use_new_zipfile_serialization=False)\n else:\n torch.save(net.cpu().module.state_dict(), model_path)\n\n net = net.to(device)\n\n record.close()\n\n if IS_VAL:\n\n train_len = 13728\n epoch_iteartion = train_len//BATCH_SIZE\n total_iteation = EPOCH_E * epoch_iteartion\n iteration_step = ITERATION_STEP\n iteration_test_num = total_iteation // iteration_step\n\n if EVAL_MODE == 'Iteration':\n EPOCH_E = iteration_test_num\n EVAL_START_EPOCH = (EVAL_START_EPOCH * epoch_iteartion) // iteration_step\n NAME = \"Iter\"\n MUL = iteration_step\n else:\n NAME = \"Epoch\"\n MUL = 1\n\n ### TEST DATASET ###\n test_ds = ds_factory.get_test_dataset()\n\n if IS_BEST:\n EVAL_BATCH = 1\n\n test_loader = DataLoader(\n dataset=test_ds,\n #batch_size=1,\n batch_size=EVAL_BATCH,\n shuffle=False,\n num_workers=1\n )\n\n #### MODEL ####\n input_channels = C\n P_list = eval(PATCH_LIST)\n Is_scaling = IS_SCALE\n\n from net.imp_pos_cl_heat2heat import Prediction_Model as Model\n\n print('EVALUATION START')\n print('-' * 30)\n\n record = open(\"record/{}/log_eval.txt\".format(RECORD_ID), \"w\") ###xie\n\n if 1:\n\n rmse_list = [] ###xie\n mae_list = [] ###xie\n for epoch in range(EVAL_START_EPOCH, EPOCH_E):\n test_t = time.time()\n\n net = Model(\n mcof,\n Length=LENGTH,\n Width=W,\n Height=H,\n Input_dim=input_channels,\n Patch_list=P_list,\n Dropout=DROPOUT,\n Att_num=ATT_NUM,\n Cross_att_num=CROSS_ATT_NUM,\n Using_skip=IS_USING_SKIP,\n Encoding_dim=MODEL_DIM,\n Embedding_dim=MODEL_DIM,\n Is_mask=IS_MASK_ATT,\n #Is_reduce=IS_REDUCE,\n Is_scaling=Is_scaling,\n Debugging=0,\n Merge=MERGE,\n Out_style=OUT_STYLE,\n Cat_style=CAT_STYLE,\n Is_aux=IS_AUX,\n IS_C3D=IS_C3D,\n ONLY_CONV6=ONLY_CONV6,\n TRANS_RESIDUAL=TRANS_RESIDUAL,\n )\n\n if IS_BEST_EVAL:\n model_path = 'model/best_model/pre_model_best_{}.pth'.format('B')\n else:\n if EVAL_MODE == 'Iteration':\n model_path = './model/All/MinMax/Short/Imp_{}/pre_model_it_{}.pth'.format(RECORD_ID,(epoch + 1)*ITERATION_STEP)\n else:\n model_path = './model/All/MinMax/Short/Imp_{}/pre_model_ep_{}.pth'.format(RECORD_ID,epoch + 1)\n #model_path = './model/All/MinMax/Short/Imp_{}/pre_model_{}.pth'.format(RECORD_ID,epoch + 1)\n print(model_path)\n\n #try:\n\n #pretrained_dict = torch.load(model_path)\n #net_dict = net.state_dict()\n #pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in net_dict}\n #net_dict.update(pretrained_dict)\n #net.load_state_dict(net_dict)\n\n net.load_state_dict(torch.load(model_path))\n #except:\n #print('error!')\n #net = torch.load(model_path)\n\n device = torch.device('cuda:0') if torch.cuda.is_available() else torch.device('cpu')\n net = net.to(device)\n net = nn.DataParallel(net)\n\n criterion = nn.MSELoss().to(device)\n\n net.eval()\n mse = 0.0\n mse_in = 0.0\n mse_out = 0.0\n mae = 0.0\n target = []\n pred = []\n mmn = ds_factory.ds.mmn\n ts_Y_test = ds_factory.ds.ts_Y_test\n if IS_BEST:\n test_rmse_list = []\n with torch.no_grad():\n for i, data in enumerate(test_loader, 0):\n\n # (1,28,6,2,32,32) (1,28,6,2,32,32) (1,28,2,32,32)or(1,28,6,2,32,32) (1,28), (1,28)\n con, ave, ave_q, label, tim_cls, typ_cls = data\n\n ave = ave.to(device)\n ave_q = ave_q.to(device)\n con = con.to(device)\n\n gen_out, tim_out, typ_out,att_map = net(ave, ave_q, con)\n\n #eval\n if IS_SEQ:\n tar = label[:,:SEQ_LEN_TEST]\n oup = gen_out[:, :SEQ_LEN_TEST]\n else:\n tar = label ##niu\n oup = gen_out[:, 0]\n\n tar = tar.to(device)\n\n loss = criterion(oup, tar) # 所有样本损失的平均值\n rmse_ = math.sqrt(loss) * (mmn.max - mmn.min) / 2. * ds_factory.dataset.m_factor\n\n if IS_BEST:\n\n if rmse_ > 70:\n print('->','timestamp',i,ts_Y_test[i],'rmse',rmse_,'abnormal')\n rmse_ = 0\n else:\n print('->','timestamp',i,ts_Y_test[i],'rmse',rmse_)\n test_rmse_list.append(rmse_)\n\n f = open(\"test/attention/{}.pkl\".format(i),'wb')\n pickle.dump(att_map,f)\n f.close()\n\n # 411\n if IS_REMOVE and i in range(792, 816):\n pass\n else:\n mse += con.shape[0] * loss.item() # 所有样本损失的总和\n mae += con.shape[0] * torch.mean(\n torch.abs(oup - tar)).item() # mean()不加维度时,返回所有值的平均\n\n ##niu\n mse_in += con.shape[0] * torch.mean(\n (tar[:, 0] - oup[:, 0]) * (tar[:, 0] - oup[:, 0])).item()\n mse_out += con.shape[0] * torch.mean(\n (tar[:, 1] - oup[:, 1]) * (tar[:, 1] - oup[:, 1])).item()\n\n _, out_cls = torch.max(torch.softmax(tim_out, 1), 1)\n out_class = out_cls.cpu().numpy()\n lab_class = tim_cls.long().cpu().numpy()\n\n target.append(lab_class)\n pred.append(out_class)\n\n if IS_BEST:\n np.save('test/our_short_test_taxibj.npy',np.stack(test_rmse_list))\n f = open(\"test/short_bj_timestamp.pkl\",'wb')\n pickle.dump(ts_Y_test[:48],f)\n f.close()\n\n\n\n #print(len(att_map))\n #print(len(att_map[0]))\n #print(len(att_map[0][0]))\n #print((att_map[0][0].shape))\n #print((att_map[0][2].shape))\n #print((att_map[0][4].shape))\n\n\n\n\n ## Validation\n\n target = np.concatenate(target)\n pred = np.concatenate(pred)\n tim_acc = metrics.accuracy_score(pred, target) * 100\n\n if IS_REMOVE:\n cnt = ds_factory.ds.X_con_tes.shape[0] - 24\n else:\n cnt = ds_factory.ds.X_con_tes.shape[0]\n\n mae /= cnt\n mae = mae * (mmn.max - mmn.min) / 2. * ds_factory.dataset.m_factor\n\n mse /= cnt\n rmse = math.sqrt(mse) * (mmn.max - mmn.min) / 2. * ds_factory.dataset.m_factor\n #print(\"mae: %.4f\" % (mae))\n #print(\"rmse: %.4f\" % (rmse))\n\n rmse_list.append(rmse) ##xie\n mae_list.append(mae) ##xie\n\n mse_in /= cnt\n rmse_in = math.sqrt(mse_in) * (mmn.max - mmn.min) / 2. * ds_factory.dataset.m_factor\n mse_out /= cnt\n rmse_out = math.sqrt(mse_out) * (mmn.max - mmn.min) / 2. * ds_factory.dataset.m_factor\n\n #info = \"inflow rmse: %.5f outflow rmse: %.4f\" % (rmse_in, rmse_out) ###xie\n test_epoch_time = timeSince(test_t)\n if EVAL_MODE == 'Iteration':\n TOT = total_iteation\n else:\n TOT = EPOCH_E\n\n\n min_idx = rmse_list.index(min(rmse_list)) ###xie\n rmse_min = round(rmse_list[min_idx], 2) ###xie\n mae_min = round(mae_list[min_idx], 2) ###xie\n ITorEP = (min_idx + 1+ EVAL_START_EPOCH)*MUL\n if EVAL_MODE == 'Iteration':\n EP = ITorEP//epoch_iteartion\n C_EP = ((i + 1+ EVAL_START_EPOCH)*MUL)//epoch_iteartion\n else:\n EP = '-'\n C_EP = '-'\n\n info = \"=%s= %s:%s/%s ep:%s MAE: %.4f RMSE: [%.4f] IN: %.4f OUT: %.4f TIM: %.4f Dur:%s\" % (RECORD_ID,NAME,(epoch+1)*MUL,TOT,str(C_EP),mae,rmse,rmse_in, rmse_out,tim_acc,test_epoch_time)###xie\n #print(info) ###xie\n\n info = ' {} Best:MAE:{},RMSE:{},{}:{},EP:{}'.format(info, mae_min,rmse_min, NAME,ITorEP,EP) ###xie\n print(info) ###xie\n record.write(info + '\\n') ###xie\n print('-----------------------') ###xie\n record.write('-----------------------' + '\\n') ###xie\n record.write(info + '\\n') ###xie\n\n record.close() ###xie\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Pass in some training parameters')\n parser.add_argument('--mode', type=str, default='train', help='The processing phase of the model')\n parser.add_argument('--record', type=str, help='Recode ID')\n parser.add_argument('--presume_record', type=str, help='Presume Recode ID')\n parser.add_argument('--task', type=str, default='B', help='Processing task type')\n parser.add_argument('--keep_train', type=int, default=0, help='Model keep training')\n parser.add_argument('--epoch_s', type=int, default=0, help='Continue training on the previous model')\n parser.add_argument('--presume_epoch_s', type=int, default=0, help='Continue training on the previous model')\n parser.add_argument('--inp_type', type=str, default='external',\n choices=['external', 'train', 'accumulate', 'accumulate_avg', 'holiday', 'windspeed', 'weather',\n 'temperature'])\n parser.add_argument('--patch_method', type=str, default='STTN', choices=['EINOPS', 'UNFOLD', 'STTN'])\n parser.add_argument('--dataset_type', type=str, default='Sub', choices=['Sub', 'All'],\n help='datasets type is sub_datasets or all_datasets')\n parser.add_argument('--context_type', type=str, default='cpt', choices=['cpt', 'cpte'],\n help='components of contextual data')\n\n parser.add_argument('--is_remove', default=0, help='whether to remove the problematic label')\n\n parser.add_argument('--ext_inp_type', type=str, default='external', choices=['external'])\n parser.add_argument('--debug', type=int, default=0, help='Model debug')\n parser.add_argument('--pretrained_class_model_path', type=str, default=None,\n help='freeze encoder param,using pretrain param')\n parser.add_argument('--finetune_class_encoder', dest='finetune_class_encoder',\n action='store_true', default=False)\n parser.add_argument('--pos_en', type=int, default=1, help='positional encoding')\n parser.add_argument('--pos_en_mode', type=str, default='cat', help='positional encoding mode')\n parser.add_argument('--best', type=int, default=0, help='best test')\n mcof = parser.parse_args()\n\n run(mcof)\n"
] |
[
[
"torch.mean",
"torch.abs",
"torch.optim.lr_scheduler.LambdaLR",
"torch.load",
"torch.utils.data.DataLoader",
"numpy.concatenate",
"torch.no_grad",
"torch.cuda.manual_seed_all",
"torch.cuda.is_available",
"torch.device",
"torch.nn.L1Loss",
"torch.nn.CrossEntropyLoss",
"torch.softmax",
"torch.backends.cudnn.version",
"numpy.stack",
"torch.cuda.device_count",
"numpy.array",
"numpy.random.seed",
"torch.manual_seed",
"torch.backends.cudnn.is_available",
"torch.nn.DataParallel",
"torch.nn.MSELoss",
"sklearn.metrics.accuracy_score"
]
] |
dimthe/rasa
|
[
"90f37c70d982cac0bad38ecd8a082041f813cc25"
] |
[
"rasa/utils/common.py"
] |
[
"import logging\nimport os\nfrom typing import Any, Callable, Dict, List, Text, Optional, Union\n\nimport rasa.core.utils\nimport rasa.utils.io\nfrom rasa.constants import (\n GLOBAL_USER_CONFIG_PATH,\n DEFAULT_LOG_LEVEL,\n ENV_LOG_LEVEL,\n DEFAULT_LOG_LEVEL_LIBRARIES,\n ENV_LOG_LEVEL_LIBRARIES,\n)\n\nlogger = logging.getLogger(__name__)\n\n\ndef arguments_of(func: Callable) -> List[Text]:\n \"\"\"Return the parameters of the function `func` as a list of names.\"\"\"\n import inspect\n\n return list(inspect.signature(func).parameters.keys())\n\n\ndef read_global_config() -> Dict[Text, Any]:\n \"\"\"Read global Rasa configuration.\"\"\"\n # noinspection PyBroadException\n try:\n return rasa.utils.io.read_config_file(GLOBAL_USER_CONFIG_PATH)\n except Exception:\n # if things go south we pretend there is no config\n return {}\n\n\ndef write_global_config_value(name: Text, value: Any) -> None:\n \"\"\"Read global Rasa configuration.\"\"\"\n\n try:\n os.makedirs(os.path.dirname(GLOBAL_USER_CONFIG_PATH), exist_ok=True)\n\n c = read_global_config()\n c[name] = value\n rasa.core.utils.dump_obj_as_yaml_to_file(GLOBAL_USER_CONFIG_PATH, c)\n except Exception as e:\n logger.warning(\n \"Failed to write global config. Error: {}. Skipping.\" \"\".format(e)\n )\n\n\ndef read_global_config_value(name: Text, unavailable_ok: bool = True) -> Any:\n \"\"\"Read a value from the global Rasa configuration.\"\"\"\n\n def not_found():\n if unavailable_ok:\n return None\n else:\n raise ValueError(\"Configuration '{}' key not found.\".format(name))\n\n if not os.path.exists(GLOBAL_USER_CONFIG_PATH):\n return not_found()\n\n c = read_global_config()\n\n if name in c:\n return c[name]\n else:\n return not_found()\n\n\ndef set_log_level(log_level: Optional[int] = None):\n \"\"\"Set log level of Rasa and Tensorflow either to the provided log level or\n to the log level specified in the environment variable 'LOG_LEVEL'. If none is set\n a default log level will be used.\"\"\"\n import logging\n\n if not log_level:\n log_level = os.environ.get(ENV_LOG_LEVEL, DEFAULT_LOG_LEVEL)\n log_level = logging.getLevelName(log_level)\n\n logging.getLogger(\"rasa\").setLevel(log_level)\n\n update_tensorflow_log_level()\n update_asyncio_log_level()\n update_apscheduler_log_level()\n\n os.environ[ENV_LOG_LEVEL] = logging.getLevelName(log_level)\n\n\ndef update_apscheduler_log_level():\n log_level = os.environ.get(ENV_LOG_LEVEL_LIBRARIES, DEFAULT_LOG_LEVEL_LIBRARIES)\n\n logging.getLogger(\"apscheduler.scheduler\").setLevel(log_level)\n logging.getLogger(\"apscheduler.scheduler\").propagate = False\n logging.getLogger(\"apscheduler.executors.default\").setLevel(log_level)\n logging.getLogger(\"apscheduler.executors.default\").propagate = False\n\n\ndef update_tensorflow_log_level():\n \"\"\"Set the log level of Tensorflow to the log level specified in the environment\n variable 'LOG_LEVEL_LIBRARIES'.\"\"\"\n import tensorflow as tf\n\n log_level = os.environ.get(ENV_LOG_LEVEL_LIBRARIES, DEFAULT_LOG_LEVEL_LIBRARIES)\n\n os.environ[\"TF_CPP_MIN_LOG_LEVEL\"] = \"2\" # disables AVX2 FMA warnings (CPU support)\n if log_level == \"DEBUG\":\n tf_log_level = tf.logging.DEBUG\n elif log_level == \"INFO\":\n tf_log_level = tf.logging.INFO\n elif log_level == \"WARNING\":\n tf_log_level = tf.logging.WARN\n else:\n tf_log_level = tf.logging.ERROR\n\n tf.logging.set_verbosity(tf_log_level)\n logging.getLogger(\"tensorflow\").propagate = False\n\n\ndef update_sanic_log_level(log_file: Optional[Text] = None):\n \"\"\"Set the log level of sanic loggers to the log level specified in the environment\n variable 'LOG_LEVEL_LIBRARIES'.\"\"\"\n from sanic.log import logger, error_logger, access_logger\n\n log_level = os.environ.get(ENV_LOG_LEVEL_LIBRARIES, DEFAULT_LOG_LEVEL_LIBRARIES)\n\n logger.setLevel(log_level)\n error_logger.setLevel(log_level)\n access_logger.setLevel(log_level)\n\n logger.propagate = False\n error_logger.propagate = False\n access_logger.propagate = False\n\n if log_file is not None:\n formatter = logging.Formatter(\"%(asctime)s [%(levelname)-5.5s] %(message)s\")\n file_handler = logging.FileHandler(log_file)\n file_handler.setFormatter(formatter)\n\n logger.addHandler(file_handler)\n error_logger.addHandler(file_handler)\n access_logger.addHandler(file_handler)\n\n\ndef update_asyncio_log_level():\n \"\"\"Set the log level of asyncio to the log level specified in the environment\n variable 'LOG_LEVEL_LIBRARIES'.\"\"\"\n log_level = os.environ.get(ENV_LOG_LEVEL_LIBRARIES, DEFAULT_LOG_LEVEL_LIBRARIES)\n logging.getLogger(\"asyncio\").setLevel(log_level)\n\n\ndef obtain_verbosity() -> int:\n \"\"\"Returns a verbosity level according to the set log level.\"\"\"\n log_level = os.environ.get(ENV_LOG_LEVEL, DEFAULT_LOG_LEVEL)\n\n verbosity = 0\n if log_level == \"DEBUG\":\n verbosity = 2\n if log_level == \"INFO\":\n verbosity = 1\n\n return verbosity\n\n\ndef is_logging_disabled() -> bool:\n \"\"\"Returns true, if log level is set to WARNING or ERROR, false otherwise.\"\"\"\n log_level = os.environ.get(ENV_LOG_LEVEL, DEFAULT_LOG_LEVEL)\n\n return log_level == \"ERROR\" or log_level == \"WARNING\"\n\n\ndef sort_list_of_dicts_by_first_key(dicts: List[Dict]) -> List[Dict]:\n \"\"\"Sorts a list of dictionaries by their first key.\"\"\"\n return sorted(dicts, key=lambda d: list(d.keys())[0])\n\n\n# noinspection PyUnresolvedReferences\ndef class_from_module_path(\n module_path: Text, lookup_path: Optional[Text] = None\n) -> Any:\n \"\"\"Given the module name and path of a class, tries to retrieve the class.\n\n The loaded class can be used to instantiate new objects. \"\"\"\n import importlib\n\n # load the module, will raise ImportError if module cannot be loaded\n if \".\" in module_path:\n module_name, _, class_name = module_path.rpartition(\".\")\n m = importlib.import_module(module_name)\n # get the class, will raise AttributeError if class cannot be found\n return getattr(m, class_name)\n else:\n module = globals().get(module_path, locals().get(module_path))\n if module is not None:\n return module\n\n if lookup_path:\n # last resort: try to import the class from the lookup path\n m = importlib.import_module(lookup_path)\n return getattr(m, module_path)\n else:\n raise ImportError(\"Cannot retrieve class from path {}.\".format(module_path))\n"
] |
[
[
"tensorflow.logging.set_verbosity"
]
] |
y894577/FocusDiscrimination
|
[
"b8c44cce0a0a61e5c86bcdbace970e5b7813c2a7"
] |
[
"CK.py"
] |
[
"from __future__ import print_function\nfrom PIL import Image\nimport numpy as np\nimport h5py\nimport torch.utils.data as data\nimport pickle\n\n\nclass CK(data.Dataset):\n \"\"\"`CK+ Dataset.\n\n Args:\n train (bool, optional): If True, creates dataset from training set, otherwise\n creates from test set.\n transform (callable, optional): A function/transform that takes in an PIL image\n and returns a transformed version. E.g, ``transforms.RandomCrop``\n\n there are 135,177,75,207,84,249,54 images in data\n we choose 123,159,66,186,75,225,48 images for training\n we choose 12,8,9,21,9,24,6 images for testing\n the split are in order according to the fold number\n \"\"\"\n\n def __init__(self, split='Training', fold=1, transform=None):\n self.transform = transform\n self.split = split # training set or test set\n self.fold = fold # the k-fold cross validation\n self.data = h5py.File('./data/CK_data.h5', 'r', driver='core')\n\n number = len(self.data['data_label']) # 981\n sum_number = [0, 135, 312, 387, 594, 678, 927, 981] # the sum of class number\n test_number = [12, 18, 9, 21, 9, 24, 6] # the number of each class\n\n test_index = []\n train_index = []\n\n for j in range(len(test_number)):\n for k in range(test_number[j]):\n if self.fold != 10: # the last fold start from the last element\n test_index.append(sum_number[j] + (self.fold - 1) * test_number[j] + k)\n else:\n test_index.append(sum_number[j + 1] - 1 - k)\n\n for i in range(number):\n if i not in test_index:\n train_index.append(i)\n\n print(len(train_index), len(test_index))\n\n # now load the picked numpy arrays\n if self.split == 'Training':\n self.train_data = []\n self.train_labels = []\n for ind in range(len(train_index)):\n self.train_data.append(self.data['data_pixel'][train_index[ind]])\n self.train_labels.append(self.data['data_label'][train_index[ind]])\n\n elif self.split == 'Testing':\n self.test_data = []\n self.test_labels = []\n for ind in range(len(test_index)):\n self.test_data.append(self.data['data_pixel'][test_index[ind]])\n self.test_labels.append(self.data['data_label'][test_index[ind]])\n\n def __getitem__(self, index):\n \"\"\"\n Args:\n index (int): Index\n\n Returns:\n tuple: (image, target) where target is index of the target class.\n \"\"\"\n if self.split == 'Training':\n img, target = self.train_data[index], self.train_labels[index]\n elif self.split == 'Testing':\n img, target = self.test_data[index], self.test_labels[index]\n # doing this so that it is consistent with all other datasets\n # to return a PIL Image\n img = img[:, :, np.newaxis]\n img = np.concatenate((img, img, img), axis=2)\n img = Image.fromarray(img)\n if self.transform is not None:\n img = self.transform(img)\n return img, target\n\n def __len__(self):\n if self.split == 'Training':\n return len(self.train_data)\n elif self.split == 'Testing':\n return len(self.test_data)\n"
] |
[
[
"numpy.concatenate"
]
] |
existentmember7/TEMP_monitor
|
[
"b8116f4c134793c4caa22eda78f90dd24d0cad30"
] |
[
"align/reID/aligned_reid/dataset/__init__.py"
] |
[
"from .TestSet import TestSet\nfrom .TrainSet import TrainSet\nfrom ..utils.dataset_utils import parse_im_name\nfrom ..utils.utils import load_pickle\nimport numpy as np\nimport os.path as osp\nospj = osp.join\nospeu = osp.expanduser\n\n\ndef create_dataset(\n name='market1501',\n part='trainval',\n **kwargs):\n assert name in ['market1501', 'cuhk03', 'duke', 'combined'], \\\n \"Unsupported Dataset {}\".format(name)\n\n assert part in ['trainval', 'train', 'val', 'test'], \\\n \"Unsupported Dataset Part {}\".format(part)\n\n ########################################\n # Specify Directory and Partition File #\n ########################################\n\n if name == 'market1501':\n im_dir = ospeu('/home/hteam/Desktop/Dataset/market1501/images')\n partition_file = ospeu(\n '/home/hteam/Desktop/Dataset/market1501/partitions.pkl')\n\n elif name == 'cuhk03':\n im_type = ['detected', 'labeled'][0]\n im_dir = ospeu(\n ospj('/home/hteam/Desktop/Dataset/cuhk03', im_type, 'images'))\n partition_file = ospeu(\n ospj('/home/hteam/Desktop/Dataset/cuhk03', im_type, 'partitions.pkl'))\n\n elif name == 'duke':\n im_dir = ospeu('/home/hteam/Desktop/Dataset/duke/images')\n partition_file = ospeu(\n '/home/hteam/Desktop/Dataset/duke/partitions.pkl')\n\n elif name == 'combined':\n assert part in ['trainval'], \\\n \"Only trainval part of the combined dataset is available now.\"\n im_dir = ospeu(\n '/home/hteam/Desktop/Dataset/market1501_cuhk03_duke/trainval_images')\n partition_file = ospeu(\n '/home/hteam/Desktop/Dataset/market1501_cuhk03_duke/partitions.pkl')\n\n ##################\n # Create Dataset #\n ##################\n\n # Use standard Market1501 CMC settings for all datasets here.\n cmc_kwargs = dict(separate_camera_set=False,\n single_gallery_shot=False,\n first_match_break=True)\n\n partitions = load_pickle(partition_file)\n im_names = partitions['{}_im_names'.format(part)]\n\n if part == 'trainval':\n ids2labels = partitions['trainval_ids2labels']\n\n ret_set = TrainSet(\n im_dir=im_dir,\n im_names=im_names,\n ids2labels=ids2labels,\n **kwargs)\n\n elif part == 'train':\n ids2labels = partitions['train_ids2labels']\n\n ret_set = TrainSet(\n im_dir=im_dir,\n im_names=im_names,\n ids2labels=ids2labels,\n **kwargs)\n\n elif part == 'val':\n marks = partitions['val_marks']\n kwargs.update(cmc_kwargs)\n\n ret_set = TestSet(\n im_dir=im_dir,\n im_names=im_names,\n marks=marks,\n **kwargs)\n\n elif part == 'test':\n marks = partitions['test_marks']\n kwargs.update(cmc_kwargs)\n\n ret_set = TestSet(\n im_dir=im_dir,\n im_names=im_names,\n marks=marks,\n **kwargs)\n\n if part in ['trainval', 'train']:\n num_ids = len(ids2labels)\n elif part in ['val', 'test']:\n ids = [parse_im_name(n, 'id') for n in im_names]\n num_ids = len(list(set(ids)))\n num_query = np.sum(np.array(marks) == 0)\n num_gallery = np.sum(np.array(marks) == 1)\n num_multi_query = np.sum(np.array(marks) == 2)\n\n # Print dataset information\n print('-' * 40)\n print('{} {} set'.format(name, part))\n print('-' * 40)\n print('NO. Images: {}'.format(len(im_names)))\n print('NO. IDs: {}'.format(num_ids))\n\n try:\n print('NO. Query Images: {}'.format(num_query))\n print('NO. Gallery Images: {}'.format(num_gallery))\n print('NO. Multi-query Images: {}'.format(num_multi_query))\n except:\n pass\n\n print('-' * 40)\n\n return ret_set\n"
] |
[
[
"numpy.array"
]
] |
ecell/scopyon
|
[
"99436fbfd34bb684966846eba75b206c2806f69c"
] |
[
"test/test_epifm.py"
] |
[
"import unittest\n\n\nclass TestEPIFM(unittest.TestCase):\n\n def setUp(self):\n self.radial_cutoff = 1000.0e-9\n self.radial_resolution = 1.0e-9\n\n def tearDown(self):\n pass\n\n def test1(self):\n import scopyon._epifm\n\n def test2(self):\n print('Testing TRITC ...')\n import numpy\n from scopyon._epifm import PointSpreadingFunction\n psf = PointSpreadingFunction(psf_radial_cutoff=self.radial_cutoff, psf_radial_width=None, psf_depth_cutoff=1000.0e-9, fluorophore_type=\"Tetramethylrhodamine(TRITC)\", psf_wavelength=5.78e-07)\n\n depth = 0.0\n radial = numpy.arange(0.0, self.radial_cutoff, self.radial_resolution, dtype=float)\n psf_r = psf.get_distribution(radial, depth)\n self.assertIs(type(psf_r), numpy.ndarray)\n self.assertEqual(psf_r.ndim, 1)\n self.assertEqual(psf_r.size, radial.size)\n self.assertTrue((psf_r >= 0.0).all())\n\n tot_r = numpy.sum(2 * numpy.pi * radial * psf_r) * self.radial_resolution\n print(f'Integral of radial distribution = {tot_r}')\n\n psf_cart = psf.radial_to_cartesian(radial, psf_r, self.radial_cutoff, self.radial_resolution)\n tot_cart = psf_cart.sum() * (self.radial_resolution * self.radial_resolution)\n print(f'Integral of cartesian distribution = {tot_cart}')\n\n camera = numpy.zeros((512, 512))\n pixel_length = 4.444444444444444e-08\n psf.overlay_signal_(camera, psf_cart, numpy.zeros(3, dtype=float), pixel_length, self.radial_resolution, 1.0)\n # tot_camera = camera.sum() * (self.radial_resolution * self.radial_resolution)\n tot_camera = camera.sum()\n print(f'Integral of detected = {tot_camera}')\n\n def test3(self):\n print('Testing Gaussian ...')\n import numpy\n from scopyon._epifm import PointSpreadingFunction\n psf = PointSpreadingFunction(psf_radial_cutoff=self.radial_cutoff, psf_radial_width=1.0e-7, psf_depth_cutoff=1000.0e-9, fluorophore_type=\"Gaussian\", psf_wavelength=6.0e-7)\n\n depth = 0.0\n radial = numpy.arange(0.0, self.radial_cutoff, self.radial_resolution, dtype=float)\n psf_r = psf.get_distribution(radial, depth)\n self.assertIs(type(psf_r), numpy.ndarray)\n self.assertEqual(psf_r.ndim, 1)\n self.assertEqual(psf_r.size, radial.size)\n self.assertTrue((psf_r >= 0.0).all())\n\n tot_r = numpy.sum(2 * numpy.pi * radial * psf_r) * self.radial_resolution\n print(f'Integral of radial distribution = {tot_r}')\n\n psf_cart = psf.radial_to_cartesian(radial, psf_r, self.radial_cutoff, self.radial_resolution)\n tot_cart = psf_cart.sum() * (self.radial_resolution * self.radial_resolution)\n print(f'Integral of cartesian distribution = {tot_cart}')\n\n camera = numpy.zeros((512, 512))\n pixel_length = 4.444444444444444e-08\n psf.overlay_signal_(camera, psf_cart, numpy.zeros(3, dtype=float), pixel_length, self.radial_resolution, 1.0)\n # tot_camera = camera.sum() * (self.radial_resolution * self.radial_resolution)\n tot_camera = camera.sum()\n print(f'Integral of detected = {tot_camera}')\n\n\nif __name__ == '__main__':\n unittest.main()\n"
] |
[
[
"numpy.arange",
"numpy.zeros",
"numpy.sum"
]
] |
donguk-dev/pycls
|
[
"31355a3473fd9389313527cf7e1bf5ad31466aad"
] |
[
"pycls/datasets/cifar10.py"
] |
[
"#!/usr/bin/env python3\n\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n\"\"\"CIFAR10 dataset.\"\"\"\n\nimport os\nimport pickle\n\nimport numpy as np\nimport pycls.core.logging as logging\nimport torch.utils.data\nfrom iopath.common.file_io import g_pathmgr\nfrom pycls.core.config import cfg\n\n\nlogger = logging.get_logger(__name__)\n\n# Per-channel mean and standard deviation values on CIFAR\n_MEAN = [125.3, 123.0, 113.9]\n_STD = [63.0, 62.1, 66.7]\n\n\nclass Cifar10(torch.utils.data.Dataset):\n \"\"\"CIFAR-10 dataset.\"\"\"\n\n def __init__(self, data_path, split):\n assert g_pathmgr.exists(data_path), \"Data path '{}' not found\".format(data_path)\n splits = [\"train\", \"test\"]\n assert split in splits, \"Split '{}' not supported for cifar\".format(split)\n logger.info(\"Constructing CIFAR-10 {}...\".format(split))\n self._im_size = cfg.TRAIN.IM_SIZE\n self._data_path, self._split = data_path, split\n self._inputs, self._labels = self._load_data()\n\n def _load_data(self):\n \"\"\"Loads data into memory.\"\"\"\n logger.info(\"{} data path: {}\".format(self._split, self._data_path))\n # Compute data batch names\n if self._split == \"train\":\n batch_names = [\"data_batch_{}\".format(i) for i in range(1, 6)]\n else:\n batch_names = [\"test_batch\"]\n # Load data batches\n inputs, labels = [], []\n for batch_name in batch_names:\n batch_path = os.path.join(self._data_path, batch_name)\n with g_pathmgr.open(batch_path, \"rb\") as f:\n data = pickle.load(f, encoding=\"bytes\")\n inputs.append(data[b\"data\"])\n labels += data[b\"labels\"]\n # Combine and reshape the inputs\n inputs = np.vstack(inputs).astype(np.float32)\n inputs = inputs.reshape((-1, 3, self._im_size, self._im_size))\n return inputs, labels\n\n def _prepare_im(self, im):\n \"\"\"Prepares the image for network input.\"\"\"\n for i in range(3):\n # Perform per-channel normalization on CHW image\n im[i] = (im[i] - _MEAN[i]) / _STD[i]\n if self._split == \"train\":\n # Randomly flip and crop center patch from CHW image\n size = self._im_size\n im = im[:, :, ::-1] if np.random.uniform() < 0.5 else im\n im = np.pad(im, ((0, 0), (4, 4), (4, 4)), mode=\"constant\")\n y = np.random.randint(0, im.shape[1] - size)\n x = np.random.randint(0, im.shape[2] - size)\n im = im[:, y : (y + size), x : (x + size)]\n return im\n\n def __getitem__(self, index):\n im, label = self._inputs[index, ...].copy(), self._labels[index]\n im = self._prepare_im(im)\n return im, label\n\n def __len__(self):\n return self._inputs.shape[0]\n"
] |
[
[
"numpy.random.uniform",
"numpy.pad",
"numpy.vstack",
"numpy.random.randint"
]
] |
thorjohnsen/onnxruntime
|
[
"81101c9efd15a69342dec94362cf7c29a4e41be9"
] |
[
"orttraining/orttraining/test/python/orttraining_run_glue.py"
] |
[
"# adapted from run_glue.py of huggingface transformers\n\nimport dataclasses\nimport logging\nimport os\nfrom dataclasses import dataclass, field\nfrom typing import Dict, Optional\nimport unittest\nimport numpy as np\n\nfrom transformers import (\n AutoConfig,\n AutoModelForSequenceClassification,\n AutoTokenizer,\n EvalPrediction,\n GlueDataset,\n GlueDataTrainingArguments,\n TrainingArguments,\n glue_compute_metrics,\n glue_output_modes,\n glue_tasks_num_labels,\n set_seed,\n)\n\nimport onnxruntime\nfrom onnxruntime.capi.ort_trainer import ORTTrainer, LossScaler, ModelDescription, IODescription\n\nfrom orttraining_transformer_trainer import ORTTransformerTrainer\n\nimport torch\n\nlogger = logging.getLogger(__name__)\n\n@dataclass\nclass ModelArguments:\n \"\"\"\n Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.\n \"\"\"\n\n model_name_or_path: str = field(\n metadata={\"help\": \"model identifier from huggingface.co/models\"}\n )\n config_name: Optional[str] = field(\n default=None, metadata={\"help\": \"Pretrained config name or path if not the same as model_name\"}\n )\n tokenizer_name: Optional[str] = field(\n default=None, metadata={\"help\": \"Pretrained tokenizer name or path if not the same as model_name\"}\n )\n cache_dir: Optional[str] = field(\n default=None, metadata={\"help\": \"Where do you want to store the pretrained models downloaded from s3\"}\n )\n\nclass ORTGlueTest(unittest.TestCase):\n\n def setUp(self):\n # configurations not to be changed accoss tests\n self.max_seq_length = 128\n self.train_batch_size = 8\n self.learning_rate = 2e-5\n self.num_train_epochs = 3.0\n self.local_rank = -1\n self.overwrite_output_dir = True\n self.gradient_accumulation_steps = 1\n self.data_dir = \"/bert_data/hf_data/glue_data/\"\n self.output_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"glue_test_output/\")\n self.cache_dir = '/tmp/glue/'\n self.logging_steps = 10\n\n def test_bert_with_mrpc(self):\n results = self.run_glue(model_name=\"bert-base-cased\", task_name=\"MRPC\", fp16=False)\n self.assertTrue(results['acc'] > 0.83)\n self.assertTrue(results['f1'] > 0.88)\n self.assertTrue(results['acc_and_f1'] > 0.86)\n self.assertTrue(results['loss'] < 0.47)\n\n def test_bert_fp16_with_mrpc(self):\n results = self.run_glue(model_name=\"bert-base-cased\", task_name=\"MRPC\", fp16=True)\n self.assertTrue(results['acc'] > 0.84)\n self.assertTrue(results['f1'] > 0.89)\n self.assertTrue(results['acc_and_f1'] > 0.87)\n self.assertTrue(results['loss'] < 0.46)\n\n def run_glue(self, model_name, task_name, fp16):\n model_args = ModelArguments(model_name_or_path=model_name, cache_dir=self.cache_dir)\n data_args = GlueDataTrainingArguments(task_name=task_name, data_dir=self.data_dir + \"/\" + task_name,\n max_seq_length=self.max_seq_length)\n \n training_args = TrainingArguments(output_dir=self.output_dir + \"/\" + task_name, do_train=True, do_eval=True,\n per_gpu_train_batch_size=self.train_batch_size,\n learning_rate=self.learning_rate, num_train_epochs=self.num_train_epochs,local_rank=self.local_rank,\n overwrite_output_dir=self.overwrite_output_dir, gradient_accumulation_steps=self.gradient_accumulation_steps,\n fp16=fp16, logging_steps=self.logging_steps)\n\n # Setup logging\n logging.basicConfig(\n format=\"%(asctime)s - %(levelname)s - %(name)s - %(message)s\",\n datefmt=\"%m/%d/%Y %H:%M:%S\",\n level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN,\n )\n logger.warning(\n \"Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s\",\n training_args.local_rank,\n training_args.device,\n training_args.n_gpu,\n bool(training_args.local_rank != -1),\n training_args.fp16,\n )\n logger.info(\"Training/evaluation parameters %s\", training_args)\n\n set_seed(training_args.seed)\n onnxruntime.set_seed(training_args.seed)\n\n try:\n num_labels = glue_tasks_num_labels[data_args.task_name]\n output_mode = glue_output_modes[data_args.task_name]\n except KeyError:\n raise ValueError(\"Task not found: %s\" % (data_args.task_name))\n\n config = AutoConfig.from_pretrained(\n model_args.config_name if model_args.config_name else model_args.model_name_or_path,\n num_labels=num_labels,\n finetuning_task=data_args.task_name,\n cache_dir=model_args.cache_dir,\n )\n tokenizer = AutoTokenizer.from_pretrained(\n model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,\n cache_dir=model_args.cache_dir,\n )\n model = AutoModelForSequenceClassification.from_pretrained(\n model_args.model_name_or_path,\n from_tf=bool(\".ckpt\" in model_args.model_name_or_path),\n config=config,\n cache_dir=model_args.cache_dir,\n )\n\n train_dataset = (\n GlueDataset(data_args, tokenizer=tokenizer)\n if training_args.do_train\n else None\n )\n\n print(data_args)\n print(training_args.local_rank)\n eval_dataset = (\n GlueDataset(data_args, tokenizer=tokenizer, mode=\"dev\")\n if training_args.do_eval\n else None\n )\n\n def compute_metrics(p: EvalPrediction) -> Dict:\n if output_mode == \"classification\":\n preds = np.argmax(p.predictions, axis=1)\n elif output_mode == \"regression\":\n preds = np.squeeze(p.predictions)\n return glue_compute_metrics(data_args.task_name, preds, p.label_ids)\n\n model_desc = ModelDescription([\n IODescription('input_ids', ['batch', 'max_seq_len_in_batch'], torch.int64, num_classes=model.config.vocab_size),\n IODescription('attention_mask', ['batch', 'max_seq_len_in_batch'], torch.int64, num_classes=2),\n IODescription('token_type_ids', ['batch', 'max_seq_len_in_batch'], torch.int64, num_classes=2),\n IODescription('labels', ['batch',], torch.int64, num_classes=2)], [\n IODescription('loss', [], torch.float32),\n IODescription('logits', ['batch', 2], torch.float32)])\n\n # Initialize the ORTTrainer within ORTTransformerTrainer\n trainer = ORTTransformerTrainer(\n model=model,\n model_desc=model_desc,\n args=training_args,\n train_dataset=train_dataset,\n eval_dataset=eval_dataset,\n compute_metrics=compute_metrics,\n )\n\n # Training\n if training_args.do_train:\n trainer.train()\n trainer.save_model()\n\n # Evaluation\n results = {}\n if training_args.do_eval and training_args.local_rank in [-1, 0]:\n logger.info(\"*** Evaluate ***\")\n\n result = trainer.evaluate()\n\n logger.info(\"***** Eval results {} *****\".format(data_args.task_name))\n for key, value in result.items():\n logger.info(\" %s = %s\", key, value)\n\n results.update(result)\n\n return results\n\nif __name__ == \"__main__\":\n unittest.main()\n"
] |
[
[
"numpy.squeeze",
"numpy.argmax"
]
] |
vipasi/indiacovid19
|
[
"08c5799cb0ad531b26b63a0faaeb22cdf45a80a8"
] |
[
"py/plot.py"
] |
[
"#!/usr/bin/python3\n\n# Copyright (c) 2020 Susam Pal\n# Licensed under the terms of the MIT License.\n\n# The MIT License (MIT)\n#\n# Copyright (c) 2020 Susam Pal\n#\n# Permission is hereby granted, free of charge, to any person obtaining\n# a copy of this software and associated documentation files (the\n# \"Software\"), to deal in the Software without restriction, including\n# without limitation the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the Software, and to\n# permit persons to whom the Software is furnished to do so, subject to\n# the following conditions:\n#\n# The above copyright notice and this permission notice shall be\n# included in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\nimport argparse\nimport os\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom py import archive, log\n\n\ntotal_color = '#06c'\nactive_color = '#f60'\ncured_color = '#393'\ndeath_color = '#c33'\nrecent_days = 30\n\n\ndef plot_begin(data):\n \"\"\"Set up a new plot.\"\"\"\n global formatted_dates\n formatted_dates = [d.strftime('%d %b') for d in data.datetimes]\n plt.clf()\n\n\ndef plot_end(data, img_name, recent, aspect):\n \"\"\"Configure current plot and export it to an image file.\"\"\"\n if recent:\n filename = img_name + '-recent.png'\n legend_size = 'small'\n else:\n filename = img_name + '.png'\n legend_size = 'medium'\n\n if aspect == 'square':\n plot_size = 4.8, 4.8\n elif aspect == 'wide':\n plot_size = 9.4, 4.8\n else:\n plot_size = 0.16 * len(data.dates), 4.8\n\n plt.gcf().set_size_inches(plot_size)\n plt.grid(which='major', linewidth='0.4')\n plt.grid(which='minor', linewidth='0.1')\n plt.xlabel('Date')\n plt.xticks(rotation='vertical', size='x-small')\n plt.yticks(size='small')\n plt.tick_params(which='both', length=0)\n plt.legend(shadow=True, fontsize=legend_size)\n os.makedirs('_site/img/', exist_ok=True)\n plt.savefig('_site/img/' + filename,\n dpi=300, bbox_inches='tight')\n\n\ndef plot_total_cases_linear(data, recent, aspect):\n \"\"\"Plot line chart for all case numbers (linear scale).\"\"\"\n m = len(data.dates) - recent_days - 1 if recent else 0\n tick_gap = 10000\n ylim_pad = 6\n title_x, title_y = (0.63, 0.9) if recent else (0.5, 0.9)\n\n plot_begin(data)\n plt.plot(formatted_dates[m:], data.total_cases[m:],\n marker='.', color=total_color, label='Total Cases', zorder=5)\n plt.plot(formatted_dates[m:], data.active_cases[m:],\n marker='.', color=active_color, label='Active Cases', zorder=4)\n plt.plot(formatted_dates[m:], data.cured_cases[m:],\n marker='.', color=cured_color, label='Cured Cases', zorder=3)\n plt.plot(formatted_dates[m:], data.death_cases[m:],\n marker='.', color=death_color,label='Death Cases', zorder=2)\n ax = plt.gca()\n ax.yaxis.set_major_locator(mpl.ticker.MultipleLocator(tick_gap * 5))\n ax.yaxis.set_minor_locator(mpl.ticker.MultipleLocator(tick_gap))\n ax.yaxis.set_major_formatter(mpl.ticker.FuncFormatter(comma_formatter))\n plt.ylabel('Count')\n plt.xlim(left=0.2 if recent else -0.8, right=len(data.dates[m:]) - 0.2)\n plt.ylim(top=top_ylim(data.total_cases[m:], tick_gap * ylim_pad, tick_gap))\n plt.ylim(bottom=0)\n plt.title('COVID-19 Cases in India', x=title_x, y=title_y, size='medium')\n plot_end(data, 'total-cases-linear', recent, aspect)\n\n\ndef plot_total_cases_log(data, recent, aspect):\n \"\"\"Plot line chart for all case numbers (log scale).\"\"\"\n m = len(data.dates) - recent_days - 1 if recent else 0\n ylim_top = max(data.total_cases[m:]) * 2\n title_x, title_y = (0.3, 0.90) if recent else (0.5, 0.90)\n\n total_cases = data.total_cases\n active_cases = data.active_cases\n cured_cases = data.cured_cases\n death_cases = data.death_cases\n\n total_cases, active_cases = shift(total_cases, active_cases, 0.05, -0.05)\n total_cases, cured_cases = shift(total_cases, cured_cases, 0.05, -0.05)\n cured_cases, active_cases = shift(cured_cases, active_cases, 0, -0.1)\n\n plot_begin(data)\n plt.yscale('log')\n plt.plot(formatted_dates[m:], total_cases[m:],\n marker='.', color=total_color, label='Total Cases', zorder=5)\n plt.plot(formatted_dates[m:], active_cases[m:],\n marker='.', color=active_color, label='Active Cases', zorder=4)\n plt.plot(formatted_dates[m:], cured_cases[m:],\n marker='.', color=cured_color, label='Cured Cases', zorder=3)\n plt.plot(formatted_dates[m:], death_cases[m:],\n marker='.', color=death_color,label='Death Cases', zorder=2)\n ax = plt.gca()\n ax.yaxis.set_major_locator(mpl.ticker.LogLocator())\n ax.yaxis.set_major_formatter(mpl.ticker.FuncFormatter(log_label_formatter))\n ax.yaxis.set_minor_formatter(mpl.ticker.FuncFormatter(log_label_formatter))\n plt.tick_params(which='minor', labelsize='x-small')\n plt.ylabel('Count')\n plt.xlim(left=0.2 if recent else -0.8, right=len(data.dates[m:]) - 0.2)\n plt.ylim(top=ylim_top)\n plt.ylim(bottom=1)\n plt.title('COVID-19 cases in India', x=title_x, y=title_y, size='medium')\n plot_end(data, 'total-cases-log', recent, aspect)\n\n\ndef plot_new_cases(data, recent, aspect):\n \"\"\"Plot bar chart for new cases on each day.\"\"\"\n m = len(data.dates) - recent_days if recent else 0\n tick_gap = 400\n text_gap = 1.0\n ylim_pad = 14 if recent else 15\n\n plot_begin(data)\n plt.bar(formatted_dates[m:], data.total_diffs[m:],\n color=total_color, zorder=2,\n label='New COVID-19 Cases in India on each day')\n for i, value in enumerate(data.total_diffs[m:]):\n plt.text(i, value + text_gap * tick_gap, value, ha='center',\n rotation='vertical', size='x-small', color=total_color)\n ax = plt.gca()\n ax.yaxis.set_major_locator(mpl.ticker.MultipleLocator(tick_gap * 5))\n ax.yaxis.set_minor_locator(mpl.ticker.MultipleLocator(tick_gap))\n plt.ylabel('Count')\n plt.xlim(left=-0.8, right=len(data.dates[m:]) - 0.2)\n plt.ylim(top=top_ylim(data.total_diffs[m:], tick_gap * ylim_pad, tick_gap))\n plt.ylim(bottom=0)\n plot_end(data, 'new-cases', recent, aspect)\n\n\ndef plot_growth_percents(data, recent, aspect):\n \"\"\"Plot growth rate for each day.\"\"\"\n m = len(data.dates) - recent_days - 1 if recent else 0\n tick_gap = 0.2 if recent else 10\n text_gap = 1.5 if recent else 1.2\n ylim_gap = 17 if recent else 5\n\n # Preprocess data for plotting.\n growths = data.total_growths\n growth_nan = [float('nan') if g == -1 else g for g in growths]\n\n # Plot graph.\n plot_begin(data)\n plt.plot(formatted_dates[m:], growth_nan[m:],\n marker='.', color=total_color,\n label='Growth percent in number of total\\n'\n 'COVID-19 cases in India on each day\\n'\n 'compared to the previous day')\n\n # Tweak the position of text values on the graph.\n tweaks = [(0, 0)] * len(data.dates)\n if recent:\n tweaks[data.dates.index('2020-04-15')] = (+0.8, -1.0)\n tweaks[data.dates.index('2020-04-16')] = (+0.0, -6.0)\n tweaks[data.dates.index('2020-04-18')] = ( 0.0, -6.0)\n tweaks[data.dates.index('2020-04-21')] = ( 0.0, -6.0)\n tweaks[data.dates.index('2020-04-23')] = ( 0.0, -6.0)\n tweaks[data.dates.index('2020-04-25')] = ( 0.0, -6.0)\n tweaks[data.dates.index('2020-04-27')] = ( 0.0, -6.0)\n tweaks[data.dates.index('2020-05-01')] = ( 0.0, -6.0)\n tweaks[data.dates.index('2020-05-04')] = ( 0.0, -6.0)\n tweaks[data.dates.index('2020-05-06')] = ( 0.0, -6.0)\n tweaks[data.dates.index('2020-05-08')] = (+0.2, 0.0)\n tweaks[data.dates.index('2020-05-10')] = ( 0.0, -6.0)\n tweaks[data.dates.index('2020-05-12')] = ( 0.0, -6.0)\n tweaks[data.dates.index('2020-05-19')] = (+0.1, +0.3)\n tweaks[data.dates.index('2020-05-16')] = ( 0.0, -6.0)\n else:\n tweaks[data.dates.index('2020-02-03')] = (+0.3, +0.0)\n tweaks[data.dates.index('2020-02-04')] = (+0.5, +0.0)\n tweaks[data.dates.index('2020-03-03')] = (+0.6, -0.5)\n tweaks[data.dates.index('2020-03-05')] = (-0.6, -1.2)\n tweaks[data.dates.index('2020-03-14')] = (-0.1, +0.1)\n tweaks[data.dates.index('2020-03-16')] = (+0.1, +0.1)\n tweaks[data.dates.index('2020-03-22')] = (+0.1, +0.0)\n\n # Show text values on the graph.\n prev_val = -1\n for i, val in enumerate(growths[m:]):\n if m != 0 and i == 0:\n continue\n if val != -1 and abs(val - prev_val) > 0.0001:\n x = i + tweaks[m:][i][0]\n y = val + (text_gap + tweaks[m:][i][1]) * tick_gap\n v = percent_str(val)\n plt.text(x, y, v, ha='center', rotation='vertical',\n size='x-small', color=total_color)\n prev_val = val\n\n # Format axes.\n ax = plt.gca()\n ax.yaxis.set_major_locator(mpl.ticker.MultipleLocator(tick_gap * 5))\n ax.yaxis.set_minor_locator(mpl.ticker.MultipleLocator(tick_gap))\n ax.yaxis.set_major_formatter(mpl.ticker.FuncFormatter(percent_formatter))\n plt.ylabel('Growth percent')\n plt.xlim(left=0.2 if recent else -0.8, right=len(data.dates[m:]) - 0.2)\n plt.ylim(top=top_ylim(growths[m:], tick_gap * ylim_gap, tick_gap))\n plt.ylim(bottom=0)\n plot_end(data, 'growth-percent', recent, aspect)\n\n\ndef percent_str(x):\n \"\"\"Format percent string with apt number of decimal places.\"\"\"\n if x < 10:\n return '{:.1f}%'.format(x)\n else:\n return '{:.0f}%'.format(x)\n\n\ndef plus_percent_str(x):\n \"\"\"Format percent string with sign and apt number of decimal places.\"\"\"\n if x < 10:\n return '{:+.1f}%'.format(x)\n else:\n return '{:+.0f}%'.format(x)\n\n\ndef plot_doubling_times(data, recent, aspect):\n \"\"\"Plot line chart for all case numbers (linear scale).\"\"\"\n m = len(data.dates) - recent_days - 1 if recent else 0\n tick_gap = 0.2 if recent else 1.0\n text_gap = 2.0 if recent else 1.0\n ylim_pad = 22 if recent else 5\n\n # Preprocess data for plotting.\n doubling_times = data.doubling_times\n days_nan = [float('nan') if x == -1 else x for x in doubling_times]\n\n # Plot graph.\n plot_begin(data)\n plt.plot(formatted_dates[m:], days_nan[m:],\n marker='.', color=total_color,\n label='Number of days it took for the number of\\n'\n 'total COVID-19 cases in India to double')\n\n # Tweak the position of text values on the graph.\n tweaks = [(0, 0)] * len(data.dates)\n if recent:\n tweaks[data.dates.index('2020-03-21')] = (+0.0, -4.2)\n tweaks[data.dates.index('2020-03-23')] = (+0.0, -4.2)\n tweaks[data.dates.index('2020-04-01')] = (+0.0, -4.2)\n tweaks[data.dates.index('2020-04-04')] = (-0.1, -0.0)\n tweaks[data.dates.index('2020-04-06')] = (-0.1, -0.0)\n tweaks[data.dates.index('2020-04-14')] = (+0.1, -0.0)\n tweaks[data.dates.index('2020-04-15')] = (-0.1, -0.0)\n else:\n tweaks[data.dates.index('2020-02-04')] = (+0.8, -1.3)\n tweaks[data.dates.index('2020-02-21')] = (+0.8, -1.3)\n tweaks[data.dates.index('2020-02-27')] = (-0.1, +0.1)\n tweaks[data.dates.index('2020-03-03')] = (+0.8, -1.3)\n tweaks[data.dates.index('2020-03-04')] = (+0.3, +0.0)\n\n # Show text values on the graph.\n prev_val = -1\n for i, val in enumerate(doubling_times[m:]):\n if m != 0 and i == 0:\n continue\n if val != -1 and abs(val - prev_val) > 0.0001:\n x = i + tweaks[m:][i][0]\n y = val + (text_gap + tweaks[m:][i][1]) * tick_gap\n v = '{:.1f}'.format(val)\n plt.text(x, y, v, ha='center', rotation='vertical',\n size='x-small', color=total_color)\n prev_val = val\n\n # Format axes.\n ax = plt.gca()\n ax.yaxis.set_major_locator(mpl.ticker.MultipleLocator(tick_gap * 5))\n ax.yaxis.set_minor_locator(mpl.ticker.MultipleLocator(tick_gap))\n plt.ylabel('Days')\n plt.xlim(left=0.2 if recent else -0.8, right=len(data.dates[m:]) - 0.2)\n plt.ylim(top=top_ylim(doubling_times[m:], tick_gap * ylim_pad, tick_gap))\n plt.ylim(bottom=0)\n plot_end(data, 'doubling-time', recent, aspect)\n\n\ndef plot_cured_percents(data, recent, aspect):\n \"\"\"Plot line chart for cured and death percents.\"\"\"\n m = len(data.dates) - recent_days - 1 if recent else 0\n tick_gap = 2\n cured_text_gap = -3.7\n death_text_gap = 1.5\n\n # Preprocess data for plotting.\n cured_nan = [float('nan') if x == -1 else x for x in data.cured_percents]\n death_nan = [float('nan') if x == -1 else x for x in data.death_percents]\n\n # Plot graph.\n plot_begin(data)\n plt.plot(formatted_dates[m:], cured_nan[m:],\n marker='.', color=cured_color,\n label='Percent of closed cases that are cured cases')\n plt.plot(formatted_dates[m:], death_nan[m:],\n marker='.', color=death_color,\n label='Percent of closed cases that are death cases')\n\n # Tweak the position of text values on the graph.\n cured_tweaks = [(0, 0)] * len(data.dates)\n death_tweaks = [(0, 0)] * len(data.dates)\n if recent:\n pass\n else:\n cured_tweaks[data.dates.index('2020-03-13')] = (+0.3, +0.0)\n death_tweaks[data.dates.index('2020-03-13')] = (+0.3, +0.0)\n\n # Show values on the graph.\n prev_cured = -1\n for i, (cured, death) in enumerate(zip(data.cured_percents[m:],\n data.death_percents[m:])):\n if m != 0 and i == 0:\n continue\n if cured != -1 and abs(cured - prev_cured) > 0.001:\n # Print cured value.\n x = i + cured_tweaks[i][0]\n y = cured + (cured_text_gap + cured_tweaks[m:][i][1]) * tick_gap\n v = '{:.0f}%'.format(cured)\n plt.text(x, y, v, ha='center', rotation='vertical',\n size='x-small', color=cured_color)\n # Print death value.\n x = i + death_tweaks[i][0]\n y = death + (death_text_gap + death_tweaks[m:][i][1]) * tick_gap\n v = '{:.0f}%'.format(death)\n plt.text(x, y, v, ha='center', rotation='vertical',\n size='x-small', color=death_color)\n prev_cured = cured\n\n # Format axes.\n ax = plt.gca()\n ax.yaxis.set_major_locator(mpl.ticker.MultipleLocator(tick_gap * 5))\n ax.yaxis.set_minor_locator(mpl.ticker.MultipleLocator(tick_gap))\n ax.yaxis.set_major_formatter(mpl.ticker.FuncFormatter(percent_formatter))\n plt.ylabel('Percent')\n plt.xlim(left=0.2 if recent else -0.8, right=len(data.dates[m:]) - 0.2)\n plt.ylim(top=100)\n plt.ylim(bottom=0)\n plot_end(data, 'cured-percent', recent, aspect)\n\n\ndef plot_cured_ratios(data, recent, aspect):\n \"\"\"Plot line chart for cured ratio.\"\"\"\n m = len(data.dates) - recent_days - 1 if recent else 0\n tick_gap = 0.2\n text_gap = 2.5\n ylim_pad = 28 if recent else 31\n\n # Preprocess data for plotting.\n ratios = data.cured_ratios\n cured_nan = [float('nan') if x == -1 else x for x in ratios]\n\n # Plot graph.\n plot_begin(data)\n plt.plot(formatted_dates[m:], cured_nan[m:],\n marker='.', color=cured_color,\n label='Number of cured cases per death case\\n'\n 'among closed COVID-19 cases in India')\n\n # Print values on the graph.\n tweaks = [(0, 0)] * len(data.dates)\n tweaks[data.dates.index('2020-03-12')] = (+0.8, -4.0)\n tweaks[data.dates.index('2020-03-17')] = (+0.5, +0.0)\n tweaks[data.dates.index('2020-03-19')] = (-0.3, +0.0)\n tweaks[data.dates.index('2020-03-22')] = (+0.0, -9.0)\n tweaks[data.dates.index('2020-03-26')] = (+0.0, -9.0)\n tweaks[data.dates.index('2020-03-27')] = (-0.2, +0.0)\n tweaks[data.dates.index('2020-03-29')] = (+0.3, +0.0)\n tweaks[data.dates.index('2020-04-02')] = (+0.2, +0.0)\n tweaks[data.dates.index('2020-04-04')] = (-0.2, +0.0)\n tweaks[data.dates.index('2020-04-06')] = (+0.2, +0.0)\n tweaks[data.dates.index('2020-04-21')] = (-0.2, +0.2)\n tweaks[data.dates.index('2020-05-16')] = (-0.1, +0.1)\n tweaks[data.dates.index('2020-05-29')] = (-0.1, +0.9)\n tweaks[data.dates.index('2020-06-17')] = (-0.0, -10.0)\n prev_val = -1\n for i, val in enumerate(ratios[m:]):\n if m != 0 and i == 0:\n continue\n if val != -1 and abs(val - prev_val) > 0.0001:\n x = i + tweaks[m:][i][0]\n y = val + (text_gap + tweaks[m:][i][1]) * tick_gap\n v = '{:.1f}'.format(val)\n plt.text(x, y, v, ha='center', rotation='vertical',\n size='x-small', color=cured_color)\n prev_val = val\n\n # Format axes.\n ax = plt.gca()\n ax.yaxis.set_major_locator(mpl.ticker.MultipleLocator(tick_gap * 5))\n ax.yaxis.set_minor_locator(mpl.ticker.MultipleLocator(tick_gap))\n plt.ylabel('Ratio')\n plt.xlim(left=0.2 if recent else -0.8, right=len(data.dates[m:]) - 0.2)\n plt.ylim(top=top_ylim(ratios[m:], tick_gap * ylim_pad, tick_gap))\n plt.ylim(bottom=0)\n plot_end(data, 'cured-ratio', recent, aspect)\n\n\ndef plot_all(data):\n \"\"\"Plot all graphs.\"\"\"\n log.log('Rendering total-cases-linear-recent plot ...')\n plot_total_cases_linear(data, recent=True, aspect='square')\n\n log.log('Rendering total-cases-linear plot ...')\n plot_total_cases_linear(data, recent=False, aspect=None)\n\n log.log('Rendering total-cases-log-recent plot ...')\n plot_total_cases_log(data, recent=True, aspect='square')\n\n log.log('Rendering total-cases-log plot ...')\n plot_total_cases_log(data, recent=False, aspect=None)\n\n log.log('Rendering new-cases-recent plot ...')\n plot_new_cases(data, recent=True, aspect='square')\n\n log.log('Rendering new-cases plot ...')\n plot_new_cases(data, recent=False, aspect=None)\n\n log.log('Rendering growth-percents-recent plot ...')\n plot_growth_percents(data, recent=True, aspect='square')\n\n log.log('Rendering growth-percents plot ...')\n plot_growth_percents(data, recent=False, aspect=None)\n\n log.log('Rendering doubling-times-recent plot ...')\n plot_doubling_times(data, recent=True, aspect='square')\n\n log.log('Rendering doubling-times plot ...')\n plot_doubling_times(data, recent=False, aspect=None)\n\n log.log('Rendering cured-percents-recent plot ...')\n plot_cured_percents(data, recent=True, aspect='square')\n\n log.log('Rendering cured-percents plot ...')\n plot_cured_percents(data, recent=False, aspect=None)\n\n log.log('Rendering cured-ratios-percent plot ...')\n plot_cured_ratios(data, recent=True, aspect='square')\n\n log.log('Rendering cured-ratios plot ...')\n plot_cured_ratios(data, recent=False, aspect=None)\n\n\ndef plot_recent_wide(data):\n \"\"\"Plot recent graphs only in approx. with 16:9 aspect ratio.\"\"\"\n log.log('Rendering total-cases-linear-recent plot ...')\n plot_total_cases_linear(data, recent=True, aspect='wide')\n\n log.log('Rendering total-cases-log-recent plot ...')\n plot_total_cases_log(data, recent=True, aspect='wide')\n\n log.log('Rendering new-cases-recent plot ...')\n plot_new_cases(data, recent=True, aspect='wide')\n\n log.log('Rendering growth-percents-recent plot ...')\n plot_growth_percents(data, recent=True, aspect='wide')\n\n log.log('Rendering doubling-times-recent plot ...')\n plot_doubling_times(data, recent=True, aspect='wide')\n\n log.log('Rendering cured-percents-recent plot ...')\n plot_cured_percents(data, recent=True, aspect='wide')\n\n log.log('Rendering cured-ratios-percent plot ...')\n plot_cured_ratios(data, recent=True, aspect='wide')\n\n\ndef comma_formatter(x, pos):\n \"\"\"Return tick label for Indian-style comma delimited numbers.\"\"\"\n x = str(int(x))\n result = x[-3:]\n i = len(x) - 3\n while i > 0:\n i -= 2\n j = i + 2\n if i < 0: i = 0\n result = x[i:j] + ',' + result\n return result\n\n\ndef log_label_formatter(x, pos):\n \"\"\"Return tick label for log scale.\"\"\"\n if str(x)[0] in ['1', '2', '4', '6']:\n return comma_formatter(int(x), None)\n\n\ndef bar_label_formatter(x, pos):\n \"\"\"Return tick label for bar chart.\"\"\"\n return int(x)\n\n\ndef percent_formatter(x, pos):\n \"\"\"Return tick label for growth percent graph.\"\"\"\n return str(int(x)) + '%'\n\n\ndef top_ylim(data, padding, round_to):\n \"\"\"Calculate top ylim by adding padding to max data value.\"\"\"\n y = max(data) + padding\n y = y - (y % round_to)\n return y\n\n\ndef shift(a, b, shift_a, shift_b):\n \"\"\"Shift overlapping values in lists a and b to make them different.\"\"\"\n new_a = a[:]\n new_b = b[:]\n for i, (total, active) in enumerate(zip(a, b)):\n if total == active:\n new_a[i] += shift_a\n new_b[i] += shift_b\n return new_a, new_b\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('-w', action='store_true',\n help='Plot recent graphs only with 16:9 aspect ratio')\n args = parser.parse_args()\n\n data = archive.load()\n if args.w:\n plot_recent_wide(data)\n else:\n plot_all(data)\n\n\nif __name__ == '__main__':\n main()\n"
] |
[
[
"matplotlib.pyplot.legend",
"matplotlib.ticker.MultipleLocator",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.gca",
"matplotlib.pyplot.gcf",
"matplotlib.ticker.FuncFormatter",
"matplotlib.pyplot.text",
"matplotlib.pyplot.title",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.yscale",
"matplotlib.ticker.LogLocator",
"matplotlib.pyplot.clf",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.bar",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.yticks",
"matplotlib.pyplot.tick_params"
]
] |
mzmzm/taichi
|
[
"39129820a922fdd936728d6feb7944ae208345a5"
] |
[
"tests/python/test_mpm88.py"
] |
[
"import os\n\nimport pytest\n\nimport taichi as ti\nfrom taichi import approx\n\n\ndef run_mpm88_test():\n dim = 2\n N = 64\n n_particles = N * N\n n_grid = 128\n dx = 1 / n_grid\n inv_dx = 1 / dx\n dt = 2.0e-4\n p_vol = (dx * 0.5)**2\n p_rho = 1\n p_mass = p_vol * p_rho\n E = 400\n\n x = ti.Vector.field(dim, dtype=ti.f32, shape=n_particles)\n v = ti.Vector.field(dim, dtype=ti.f32, shape=n_particles)\n C = ti.Matrix.field(dim, dim, dtype=ti.f32, shape=n_particles)\n J = ti.field(dtype=ti.f32, shape=n_particles)\n grid_v = ti.Vector.field(dim, dtype=ti.f32, shape=(n_grid, n_grid))\n grid_m = ti.field(dtype=ti.f32, shape=(n_grid, n_grid))\n\n @ti.kernel\n def substep():\n for p in x:\n base = (x[p] * inv_dx - 0.5).cast(int)\n fx = x[p] * inv_dx - base.cast(float)\n w = [0.5 * (1.5 - fx)**2, 0.75 - (fx - 1)**2, 0.5 * (fx - 0.5)**2]\n stress = -dt * p_vol * (J[p] - 1) * 4 * inv_dx * inv_dx * E\n affine = ti.Matrix([[stress, 0], [0, stress]]) + p_mass * C[p]\n for i in ti.static(range(3)):\n for j in ti.static(range(3)):\n offset = ti.Vector([i, j])\n dpos = (offset.cast(float) - fx) * dx\n weight = w[i][0] * w[j][1]\n grid_v[base + offset].atomic_add(\n weight * (p_mass * v[p] + affine @ dpos))\n grid_m[base + offset].atomic_add(weight * p_mass)\n\n for i, j in grid_m:\n if grid_m[i, j] > 0:\n bound = 3\n inv_m = 1 / grid_m[i, j]\n grid_v[i, j] = inv_m * grid_v[i, j]\n grid_v[i, j][1] -= dt * 9.8\n if i < bound and grid_v[i, j][0] < 0:\n grid_v[i, j][0] = 0\n if i > n_grid - bound and grid_v[i, j][0] > 0:\n grid_v[i, j][0] = 0\n if j < bound and grid_v[i, j][1] < 0:\n grid_v[i, j][1] = 0\n if j > n_grid - bound and grid_v[i, j][1] > 0:\n grid_v[i, j][1] = 0\n\n for p in x:\n base = (x[p] * inv_dx - 0.5).cast(int)\n fx = x[p] * inv_dx - base.cast(float)\n w = [\n 0.5 * (1.5 - fx)**2, 0.75 - (fx - 1.0)**2, 0.5 * (fx - 0.5)**2\n ]\n new_v = ti.Vector.zero(ti.f32, 2)\n new_C = ti.Matrix.zero(ti.f32, 2, 2)\n for i in ti.static(range(3)):\n for j in ti.static(range(3)):\n dpos = ti.Vector([i, j]).cast(float) - fx\n g_v = grid_v[base + ti.Vector([i, j])]\n weight = w[i][0] * w[j][1]\n new_v += weight * g_v\n new_C += 4 * weight * g_v.outer_product(dpos) * inv_dx\n v[p] = new_v\n x[p] += dt * v[p]\n J[p] *= 1 + dt * new_C.trace()\n C[p] = new_C\n\n # gui = ti._lib.core.GUI(\"MPM88\", ti.core_veci(512, 512))\n # canvas = gui.get_canvas()\n\n for i in range(n_particles):\n x[i] = [i % N / N * 0.4 + 0.2, i / N / N * 0.4 + 0.05]\n v[i] = [0, -3]\n J[i] = 1\n\n for frame in range(10):\n for s in range(50):\n grid_v.fill([0, 0])\n grid_m.fill(0)\n substep()\n\n pos = x.to_numpy()\n pos[:, 1] *= 2\n regression = [\n 0.31722742,\n 0.15826741,\n 0.10224003,\n 0.07810827,\n ]\n for i in range(4):\n assert (pos**(i + 1)).mean() == approx(regression[i], rel=1e-2)\n\n\[email protected]()\ndef test_mpm88():\n run_mpm88_test()\n\n\ndef _is_appveyor():\n # AppVeyor adds `APPVEYOR=True` ('true' on Ubuntu)\n # https://www.appveyor.com/docs/environment-variables/\n return os.getenv('APPVEYOR', '').lower() == 'true'\n\n\n#TODO: Remove exclude of ti.metal\[email protected](_is_appveyor(), reason='Stuck on Appveyor.')\[email protected](require=ti.extension.async_mode, exclude=[ti.metal], async_mode=True)\ndef test_mpm88_async():\n # It seems that all async tests on Appveyor run super slow. For example,\n # on Appveyor, 10+ tests have passed during the execution of\n # test_fuse_dense_x2y2z. Maybe thread synchronizations are expensive?\n run_mpm88_test()\n\n\[email protected](arch=[ti.cpu, ti.cuda, ti.opengl])\ndef test_mpm88_numpy_and_ndarray():\n import numpy as np\n\n dim = 2\n N = 64\n n_particles = N * N\n n_grid = 128\n dx = 1 / n_grid\n inv_dx = 1 / dx\n dt = 2.0e-4\n p_vol = (dx * 0.5)**2\n p_rho = 1\n p_mass = p_vol * p_rho\n E = 400\n\n @ti.kernel\n def substep(x: ti.any_arr(element_dim=1), v: ti.any_arr(element_dim=1),\n C: ti.any_arr(element_dim=2), J: ti.any_arr(),\n grid_v: ti.any_arr(element_dim=1), grid_m: ti.any_arr()):\n for p in x:\n base = (x[p] * inv_dx - 0.5).cast(int)\n fx = x[p] * inv_dx - base.cast(float)\n w = [0.5 * (1.5 - fx)**2, 0.75 - (fx - 1)**2, 0.5 * (fx - 0.5)**2]\n stress = -dt * p_vol * (J[p] - 1) * 4 * inv_dx * inv_dx * E\n affine = ti.Matrix([[stress, 0], [0, stress]]) + p_mass * C[p]\n for i in ti.static(range(3)):\n for j in ti.static(range(3)):\n offset = ti.Vector([i, j])\n dpos = (offset.cast(float) - fx) * dx\n weight = w[i][0] * w[j][1]\n grid_v[base + offset].atomic_add(\n weight * (p_mass * v[p] + affine @ dpos))\n grid_m[base + offset].atomic_add(weight * p_mass)\n\n for i, j in grid_m:\n if grid_m[i, j] > 0:\n bound = 3\n inv_m = 1 / grid_m[i, j]\n grid_v[i, j] = inv_m * grid_v[i, j]\n grid_v[i, j][1] -= dt * 9.8\n if i < bound and grid_v[i, j][0] < 0:\n grid_v[i, j][0] = 0\n if i > n_grid - bound and grid_v[i, j][0] > 0:\n grid_v[i, j][0] = 0\n if j < bound and grid_v[i, j][1] < 0:\n grid_v[i, j][1] = 0\n if j > n_grid - bound and grid_v[i, j][1] > 0:\n grid_v[i, j][1] = 0\n\n for p in x:\n base = (x[p] * inv_dx - 0.5).cast(int)\n fx = x[p] * inv_dx - base.cast(float)\n w = [\n 0.5 * (1.5 - fx)**2, 0.75 - (fx - 1.0)**2, 0.5 * (fx - 0.5)**2\n ]\n new_v = ti.Vector.zero(ti.f32, 2)\n new_C = ti.Matrix.zero(ti.f32, 2, 2)\n for i in ti.static(range(3)):\n for j in ti.static(range(3)):\n dpos = ti.Vector([i, j]).cast(float) - fx\n g_v = grid_v[base + ti.Vector([i, j])]\n weight = w[i][0] * w[j][1]\n new_v += weight * g_v\n new_C += 4 * weight * g_v.outer_product(dpos) * inv_dx\n v[p] = new_v\n x[p] += dt * v[p]\n J[p] *= 1 + dt * new_C.trace()\n C[p] = new_C\n\n def run_test(x, v, C, J, grid_v, grid_m):\n for i in range(n_particles):\n x[i] = [i % N / N * 0.4 + 0.2, i / N / N * 0.4 + 0.05]\n v[i] = [0, -3]\n J[i] = 1\n\n for frame in range(10):\n for s in range(50):\n grid_v.fill(0)\n grid_m.fill(0)\n substep(x, v, C, J, grid_v, grid_m)\n\n pos = x if isinstance(x, np.ndarray) else x.to_numpy()\n pos[:, 1] *= 2\n regression = [\n 0.31722742,\n 0.15826741,\n 0.10224003,\n 0.07810827,\n ]\n for i in range(4):\n assert (pos**(i + 1)).mean() == approx(regression[i], rel=1e-2)\n\n def test_numpy():\n x = np.zeros((n_particles, dim), dtype=np.float32)\n v = np.zeros((n_particles, dim), dtype=np.float32)\n C = np.zeros((n_particles, dim, dim), dtype=np.float32)\n J = np.zeros(n_particles, dtype=np.float32)\n grid_v = np.zeros((n_grid, n_grid, dim), dtype=np.float32)\n grid_m = np.zeros((n_grid, n_grid), dtype=np.float32)\n run_test(x, v, C, J, grid_v, grid_m)\n\n def test_ndarray():\n x = ti.Vector.ndarray(dim, ti.f32, n_particles)\n v = ti.Vector.ndarray(dim, ti.f32, n_particles)\n C = ti.Matrix.ndarray(dim, dim, ti.f32, n_particles)\n J = ti.ndarray(ti.f32, n_particles)\n grid_v = ti.Vector.ndarray(dim, ti.f32, (n_grid, n_grid))\n grid_m = ti.ndarray(ti.f32, (n_grid, n_grid))\n run_test(x, v, C, J, grid_v, grid_m)\n\n test_numpy()\n test_ndarray()\n"
] |
[
[
"numpy.zeros"
]
] |
Kumaken/fyp-vehicle-counting-system
|
[
"51adb3bfc762d5489bc643da5f79bec3fa9eeb84"
] |
[
"test.py"
] |
[
"import torch\n\n# Model\nmodel = torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=True)\n\n# Images\ndir = 'https://github.com/ultralytics/yolov5/raw/master/data/images/'\nimgs = [dir + f for f in ('zidane.jpg', 'bus.jpg')] # batched list of images\n\n# Inference\nresults = model(imgs)\nprint(results.xyxy[0])\nresults.show() # or .show(), .save()"
] |
[
[
"torch.hub.load"
]
] |
JuanAsensioAyesa/ProyectoCGEIM_2021
|
[
"9025c23fa7e2429a9846dae1146fbbf6314685cb"
] |
[
"progressive_photon_mapping.py"
] |
[
"import os\nimport numpy\nimport random\nimport PIL\nfrom PIL import Image\nif __name__ == \"__main__\":\n lista = [10,15,20,25,30,35,40,50,100,200]\n lista = numpy.arange(100)\n for i in numpy.arange(len(lista)):\n command = \"./bin/yscene render\"\n out_file = \"imagen_\"+str(lista[i])\n photons = str(lista[i])\n samples = str(1)\n\n scene = \"iluminacion_vertical\"\n seed = random.randrange(1000000)\n command = command + \" --sampler photon_map --photon_mapping --samples \"+samples\n command = command + \" --seed \"+str(seed)\n command = command + \" --photon_neighbours \"+str(lista[i] + 1)\n command = command + \" --output ./imagenes/\"+out_file+'.png'\n command = command + \" ./tests/\"+scene+\"/\"+scene+\".json\"\n #print(command)\n os.system(command + \" > /dev/null\")\n print(i)\n \n\n # Access all PNG files in directory\n allfiles=os.listdir(\"./imagenes\")\n imlist=[\"./imagenes/\"+filename for filename in allfiles if filename[-4:] in [\".png\",\".PNG\"]]\n\n # Assuming all images are the same size, get dimensions of first image\n w,h=Image.open(imlist[0]).size\n N=len(imlist)\n\n # Create a numpy array of floats to store the average (assume RGB images)\n imarr_shape=numpy.array(Image.open(imlist[0]),dtype=numpy.float).shape\n arr=numpy.zeros(imarr_shape,numpy.float)\n\n # Build up average pixel intensities, casting each image as an array of floats\n for im in imlist:\n imarr=numpy.array(Image.open(im),dtype=numpy.float)\n print(arr.shape,\"Imarr \",imarr.shape)\n arr=arr+imarr/N\n\n # Round values in array and cast as 8-bit integer\n arr=numpy.array(numpy.round(arr),dtype=numpy.uint8)\n\n # Generate, save and preview final image\n out=Image.fromarray(arr,mode=\"RGBA\")\n out.save(\"Average.png\")\n out.show()"
] |
[
[
"numpy.round",
"numpy.arange",
"numpy.zeros"
]
] |
ronen85/causal_inference_project
|
[
"aa2688ba0629f9984aa714fe07e9c319228bb461"
] |
[
"visualization.py"
] |
[
"from collections import defaultdict\nfrom matplotlib.pylab import plt\nfrom matplotlib import pyplot as mp\nfrom utilities import *\n\n\ndef bar_graph(category, age_grp, sex, x, y, year=None, country=None):\n\n plt.figure()\n plt.ylabel('ATE = Y1 - Y0')\n plt.xlabel('Years')\n plt.bar(range(len(x)), x, align='center')\n plt.xticks(range(len(x)), y, rotation='vertical')\n\n if country:\n plt.title(\"%s Suicide Rates for WC; %s ages %s\" % (country, sex, age_grp))\n name = country + sex + age_grp + '.png'\n # plt.show()\n plt.tight_layout()\n plt.savefig('./graphs/Countries' + '/' + sex + '/' + name.replace(' ', '_'))\n\n elif year:\n plt.title(\"Change in Suicide Rates per Country in %s; %s ages %s\" % (year, sex, age_grp))\n name = category + sex + str(year) + age_grp + '.png'\n # plt.show()\n plt.tight_layout()\n plt.savefig('./graphs/' + category + '/' + sex + '/' + str(year) + '/' + name.replace(' ', ''))\n else:\n plt.title(\"Change in Suicide Rates in %s Countries; %s ages %s\" % (category, sex, age_grp))\n name = category + sex + age_grp + '.png'\n # plt.show()\n plt.tight_layout()\n plt.savefig('./graphs/' + category + '/' + sex + '/' + name.replace(' ',''))\n"
] |
[
[
"matplotlib.pylab.plt.tight_layout",
"matplotlib.pylab.plt.title",
"matplotlib.pylab.plt.figure",
"matplotlib.pylab.plt.ylabel",
"matplotlib.pylab.plt.xlabel"
]
] |
NavarreCML/National-EAT-Lancet-Diets
|
[
"d61ffb59829a64d1bfca3f43e593e656d4543f33"
] |
[
"functions/POM_build.py"
] |
[
"import pandas as pd\nimport numpy as np\nfrom functions import fao_regions as regions\n\ndata = 'data/'\n\ndef data_build(crop_proxie, diet_div_crop, diet_source_crop, diet_ls_only, diet_ls_only_source, min_waste):\n\n \"\"\"*** Import of country data to build national diets ***\"\"\"\n WPR_height = pd.read_csv(r\"data/worldpopulationreview_height_data.csv\")\n WPR_height.loc[WPR_height.Area == \"North Korea\", \"Area\"] = \"Democratic People's Republic of Korea\"\n Countrycodes = pd.read_csv(r\"data/countrycodes.csv\", sep = \";\")\n #FAO_pop = pd.read_excel(data+\"/FAOSTAT_Population_v3.xlsx\")\n FAO_pop = pd.read_excel(data+\"/FAOSTAT_2018_population.xlsx\")\n FAO_pop.loc[FAO_pop.Area == \"Cote d'Ivoire\", \"Area\"] = \"Côte d'Ivoire\"\n FAO_pop.loc[FAO_pop.Area == \"French Guyana\", \"Area\"] = \"French Guiana\"\n FAO_pop.loc[FAO_pop.Area == \"Réunion\", \"Area\"] = \"Réunion\"\n \n \"\"\"*** Import and sorting of data ***\"\"\"\n FAO_crops = pd.read_csv(data+\"/FAOSTAT_crop Production.csv\")\n FAO_crops[\"group\"] = FAO_crops.apply(lambda x: regions.group(x[\"Item Code\"]), axis=1)\n FAO_crops = FAO_crops.rename(columns={\"Value\" : \"Production\"})\n FAO_crops[\"Production\"] = FAO_crops[\"Production\"] / 1000\n FAO_crops[\"Unit\"] = \"1000 tonnes\"\n \n FAO_animals = pd.read_csv(data+\"/FAO_animal_prod_2016.csv\")\n FAO_animals[\"group\"] = FAO_animals.apply(lambda x: regions.group(x[\"Item Code\"]), axis=1)\n FAO_animals.loc[FAO_animals.Area == \"United Kingdom of Great Britain and Northern Ireland\", \"Area\"] = \"United Kingdom\"\n FAO_animals = FAO_animals.rename(columns={\"Value\" : \"Production\"})\n FAO_animals.drop(FAO_animals[FAO_animals.Unit != 'tonnes'].index, inplace = True)\n FAO_animals[\"Production\"] = FAO_animals[\"Production\"] / 1000\n FAO_animals[\"Unit\"] = \"1000 tonnes\"\n \n FAO_animals_5 = pd.read_csv(data+\"/FAOSTAT_animal_prod_5.csv\")\n FAO_animals_5[\"group\"] = FAO_animals_5.apply(lambda x: regions.group(x[\"Item Code (FAO)\"]), axis=1)\n FAO_animals_5.loc[FAO_animals_5.Area == \"United Kingdom of Great Britain and Northern Ireland\", \"Area\"] = \"United Kingdom\"\n FAO_animals_5 = FAO_animals_5.rename(columns={\"Value\" : \"Production\"})\n FAO_animals_5.drop(FAO_animals_5[FAO_animals_5.Unit != 'tonnes'].index, inplace = True)\n FAO_animals_5[\"Production\"] = FAO_animals_5[\"Production\"] / 1000\n FAO_animals_5[\"Unit\"] = \"1000 tonnes\"\n FAO_animals_5 = FAO_animals_5.groupby(['Area', 'Item']).mean().reset_index()\n \n FAO_animals = pd.merge(FAO_animals, FAO_animals_5[['Area', 'Item', 'Production']], on = [\"Area\", \"Item\"], how = 'left')\n FAO_animals[\"Production\"] = FAO_animals[\"Production_y\"]\n FAO_animals = FAO_animals.drop(columns = [\"Production_x\", \"Production_y\"])\n\n \n FAO_fish = pd.read_csv(data+\"FAOSTAT_Fish.csv\")\n FAO_fish = FAO_fish.rename(columns={\"Value\" : \"Production\"})\n FAO_fish[\"group\"] = FAO_fish.apply(lambda x: regions.group(x[\"Item Code\"]), axis=1)\n \n meat_products = [\"eggs\", \"beef and lamb\", \"chicken and other poultry\",\\\n \"pork\", \"whole milk or derivative equivalents\"]\n \n fish_products = [\"Freshwater Fish\", \"Demersal Fish\", \"Pelagic Fish\",\\\n \"Marine Fish, Other\", \"Crustaceans\", \"Cephalopods\",\\\n \"Molluscs, Other\", \"Meat, Aquatic Mammals\", \"Aquatic Animals, Others\",\n \"Aquatic Plants\", \"Fish, Body Oil\", \"Fish, Liver Oil\"]\n \n other_items = [\"Honey, natural\", \"Beeswax\", \"Silk-worm cocoons, reelable\"]\n other_items = [\"Beeswax\", \"Silk-worm cocoons, reelable\"]\n\n \"\"\"*** Import of protein data ***\"\"\"\n FAO_Protein = pd.read_csv(data+\"protein.csv\")\n FAO_Protein[\"group\"] = FAO_Protein[\"group\"].str.replace(\"dairy\", \"whole milk or derivative equivalents\")\n FAO_Protein = FAO_Protein.rename(columns = {\"Country\": \"Area\"})\n \n \"\"\"*** Build main dataframe ***\"\"\"\n POM_data = pd.concat([FAO_crops])\n FAO_pop_temp = FAO_pop.set_index(\"Area\")\n if crop_proxie == True:\n for i,j in zip(diet_ls_only, diet_ls_only_source):\n fao_fix = POM_data.loc[POM_data.Area == j]\n fao_fix['Area'] = i\n \n factor = FAO_pop_temp['Value'][i] / FAO_pop_temp['Value'][j]\n fao_fix['Production'] *= factor\n \n POM_data = POM_data[POM_data.Area != i]\n POM_data = pd.concat([POM_data,fao_fix])\n\n \n POM_data = pd.concat([POM_data, FAO_animals, FAO_fish])\n \n if crop_proxie == True:\n for i,j in zip (diet_div_crop, diet_source_crop): \n fao_fix = POM_data.loc[POM_data.Area == j]\n fao_fix['Area'] = i\n \n factor = FAO_pop_temp['Value'][i] / FAO_pop_temp['Value'][j]\n \n fao_fix['Production'] *= factor\n \n POM_data = POM_data[POM_data.Area != i]\n POM_data = pd.concat([POM_data,fao_fix])\n\n \n \n POM_data = POM_data.reset_index()\n \"\"\"*** Food source scenarios ***\"\"\"\n \n POM_data = POM_data.reset_index(drop = True)\n POM_data = POM_data[~POM_data.Item.isin(other_items)]\n POM_data = POM_data.rename(columns={\"group\" : \"group_nf\"})\n POM_data[\"Production\"].clip(lower = 0, inplace = True)\n \n POM_data = pd.merge(POM_data, WPR_height, on = [\"Area\"], how = 'left')\n POM_data = pd.merge(POM_data, Countrycodes, left_on = \"Area\", right_on = \"COUNTRY\", how = 'left')\n POM_data = pd.merge(POM_data, FAO_pop[[\"Area\", \"Value\"]], on = [\"Area\"], how = 'left')\n POM_data = POM_data.rename(columns={\"Value\" : \"Population (2016), 1000person\"})\n \n \n \"\"\"*** Fix China data from China to China, mainland to seperate out Taiwan ***\"\"\"\n POM_data.loc[POM_data.Area == 'China, mainland', 'REGION'] = 'CHN'\n POM_data.loc[POM_data.Area == 'China, mainland', 'CODE'] = '156'\n temp_height = POM_data['avg height'][1761]\n temp_weight = POM_data['avg weight'][1761]\n POM_data.loc[POM_data.Area == 'China, mainland', 'avg height'] = temp_height\n POM_data.loc[POM_data.Area == 'China, mainland', 'avg weight'] = temp_weight\n POM_data.drop(POM_data[POM_data.Area == 'China'].index)\n POM_data = POM_data.reset_index(drop = True)\n \n \"\"\" Remove microstates \"\"\"\n FAO_land = pd.read_csv(data+\"FAOSTAT_Ag Land.csv\")\n FAO_land = FAO_land.rename(columns={\"Value\" : \"1000 Ha\"})\n POM_data = pd.merge(POM_data, FAO_land[[\"Area\", \"1000 Ha\"]], on = [\"Area\"], how = 'left')\n \n France_ot = ['French Guiana', 'Guadeloupe', 'Martinique', 'Réunion']\n for overseas in France_ot: \n x = POM_data.loc[POM_data.Area == overseas, 'Population (2016), 1000person'].unique()[0]\n POM_data.loc[POM_data.Area == 'France', 'Population (2016), 1000person'] += x\n \n y = POM_data.loc[POM_data.Area == overseas, '1000 Ha'].unique()[0]\n POM_data.loc[POM_data.Area == 'France', '1000 Ha'] += y\n \n \n POM_micro = POM_data.loc[(POM_data[\"1000 Ha\"] <= 100)]\n POM_micro = POM_micro[~POM_micro[\"Area\"].isin(France_ot)]\n POM_micro = POM_micro[['Area', '1000 Ha', 'Population (2016), 1000person']]\n POM_micro = POM_micro.drop_duplicates()\n\n POM_data = POM_data.loc[(POM_data[\"1000 Ha\"] > 0)]\n POM_data = POM_data[~POM_data[\"Area\"].isin(France_ot)]\n\n \n POM_data[\"GROUP\"] = POM_data.apply(lambda row: regions.region(row), axis = 1)\n POM_data[\"IMAGEGROUP\"] = POM_data.apply(lambda row: regions.imageregion(row), axis = 1)\n \n \"\"\"*** Calculate remaining body weights based on GROUP average ***\"\"\"\n POM_Group_Data = POM_data.groupby([\"GROUP\"]).apply(lambda x: x[\"avg height\"].mean())\n \n for i in POM_data[\"avg height\"].index:\n if np.isnan(POM_data[\"avg height\"][i]) == True:\n POM_data[\"avg height\"][i] = POM_Group_Data[POM_data[\"GROUP\"][i]]\n POM_data[\"avg weight\"][i] = POM_data[\"avg height\"][i]**2*22\n \n POM_data = POM_data.drop([\"cca2\", \"maleMetricHeight\", \"femaleMetricHeight\", \"Unnamed: 7\", \"Year\",\\\n \"COUNTRY\",\"Area Code\", \"pop2019\", \"Domain\", \"Domain Code\", \"Element\", \"Flag\", \"Flag Description\", \"Year Code\", \"REGION\", \"CODE\"], axis = 1 )\n \n POM_data = POM_data.rename(columns={\"Production\" : \"POM\"})\n \n \"\"\"*** Add in protein data ***\"\"\"\n POM_data = pd.merge(POM_data, FAO_Protein[[\"Area\", \"g protein per g product\", \"Item\", \"Item Code\"]], on = [\"Area\", \"Item\", \"Item Code\"], how = 'left')\n POM_data = POM_data.rename(columns = {\"g protein per g product\": \"% Protein\" })\n POM_data = POM_data.drop_duplicates()\n POM_data = POM_data.drop([\"Element Code\"],axis =1)\n POM_data [\"% Protein\"] = POM_data [\"% Protein\"]*100\n \n \"\"\"*** Determine the % of groups production of each item based on POM ***\"\"\"\n POM_data[\"group\"] = POM_data.apply(lambda x: regions.group(x[\"Item Code\"]), axis=1)\n \n \"\"\"*** Remove the waste fraction to get a snapshot of what people eat ***\"\"\"\n wastefractions = pd.read_csv(data+\"waste_fractions.csv\", sep = \";\")\n for i in wastefractions.index:\n if wastefractions['Region'][i] == 'LatinAmerica':\n wastefractions['Region'][i] = 'South&CentralAmerica'\n \n groups = wastefractions.groupby([\"Region\"])\n POM_data[\"POM no waste\"] = POM_data[\"POM\"]\n for n, gr in POM_data.groupby(\"GROUP\"):\n if n == 'Other':\n continue\n POM_data.loc[(POM_data[\"GROUP\"] == n) & (POM_data[\"group\"] == \"potatoes and cassava\"), \"POM no waste\"] *= (1 - wastefractions.loc[(wastefractions[\"Region\"] == n) & (wastefractions[\"Foodtype\"] == \"Rootsandtubers\"), \"Total\"].values)\n POM_data.loc[(POM_data[\"GROUP\"] == n) & (POM_data[\"group\"].isin([\"dry beans lentils and peas\", \"soy foods\", \"peanuts\", \"tree nuts\", \"palm oil\", \"unsaturated oils\", \"all sweeteners\"])), \"POM no waste\"] *= (1 - wastefractions.loc[(wastefractions[\"Region\"] == n) & (wastefractions[\"Foodtype\"] == \"Oilseedsandpulses\"), \"Total\"].values)\n POM_data.loc[(POM_data[\"GROUP\"] == n) & (POM_data[\"group\"] == \"rice wheat corn and other\"), \"POM no waste\"] *= (1 - wastefractions.loc[(wastefractions[\"Region\"] == n) & (wastefractions[\"Foodtype\"] == \"Cereals\"), \"Total\"].values)\n POM_data.loc[(POM_data[\"GROUP\"] == n) & (POM_data[\"group\"].isin([\"all fruit\", \"all vegetables\", \"dark green vegetables\", \"red and orange vegetables\"])), \"POM no waste\"] *= (1 - wastefractions.loc[(wastefractions[\"Region\"] == n) & (wastefractions[\"Foodtype\"] == \"Fruitsandvegetables\"), \"Total\"].values)\n POM_data.loc[(POM_data[\"GROUP\"] == n) & (POM_data[\"group\"].isin([\"eggs\", \"beef and lamb\", \"chicken and other poultry\", \"pork\"])), \"POM no waste\"] *= (1 - wastefractions.loc[(wastefractions[\"Region\"] == n) & (wastefractions[\"Foodtype\"] == \"Meat\"), \"Total\"].values)\n POM_data.loc[(POM_data[\"GROUP\"] == n) & (POM_data[\"group\"].isin([\"whole milk or derivative equivalents\"])), \"POM no waste\"] *= (1 - wastefractions.loc[(wastefractions[\"Region\"] == n) & (wastefractions[\"Foodtype\"] == \"Milk\"), \"Total\"].values)\n POM_data.loc[(POM_data[\"GROUP\"] == n) & (POM_data[\"group\"].isin([\"fish\"])), \"POM no waste\"] *= (1 - wastefractions.loc[(wastefractions[\"Region\"] == n) & (wastefractions[\"Foodtype\"] == \"Fishandseafood\"), \"Total\"].values)\n\n extra_nations = ['Puerto Rico', 'Palestine', 'Greenland', 'Falkland Islands (Malvinas)'\\\n 'New Caledonia', 'China', 'China, Taiwan Province of' ]\n POM_data = POM_data[~POM_data['Area'].isin(extra_nations)]\n \n\n \"\"\"*** Adjust waste fraction based on scenario ***\"\"\"\n if min_waste == True:\n for i in wastefractions:\n if i in ['Foodtype', 'Region']:\n continue\n for j in wastefractions.Foodtype:\n wastefractions.loc[wastefractions.Foodtype == j, i] = wastefractions[i].loc[wastefractions.Foodtype == j].min()\n\n wastefractions['Total'] = wastefractions['Agricultural_production'] + wastefractions['Postharvest_handling_and_storage']\\\n + wastefractions['Processing_and_packaging'] + wastefractions[\"Distribution\"] + wastefractions[\"Consumption\"]\n\n\n\n return POM_data, meat_products, fish_products, FAO_animals, wastefractions, FAO_pop, POM_micro\n\n\ndef bau_diet_ratios(POM_data):\n POM_data[\"POM with waste\"] = POM_data[\"POM\"]\n POM_percent = POM_data.groupby([\"group\", \"Area\"]).apply(lambda x: x[\"POM no waste\"]/x[\"POM no waste\"].sum()*100)\n POM_percent = POM_percent.reset_index(level = [\"group\", \"Area\"])\n POM_percent = POM_percent.fillna(value = 0)\n POM_percent = POM_percent.rename(columns = {\"POM no waste\": \"POM (no waste) group %\"})\n \n POM_data = POM_data.merge(POM_percent[\"POM (no waste) group %\"].to_frame(), left_index=True, right_index=True)\n \n POM_percent = POM_data.groupby([\"Area\"]).apply(lambda x: (x[\"POM no waste\"]/x[\"POM no waste\"].sum())*100)\n POM_percent = POM_percent.reset_index(level = [\"Area\"])\n POM_percent = POM_percent.fillna(value = 0)\n \n POM_data = POM_data.merge(POM_percent[\"POM no waste\"].to_frame(), left_index=True, right_index=True)\n POM_data = POM_data.rename(columns = {\"POM no waste_x\": \"POM (no waste)\", \"POM no waste_y\":\"POM (no waste) total %\"})\n \n return POM_data\n \n\ndef nutrition(POM_data):\n Nutrition_values = pd.read_csv(r\"data/nutritionvalues.csv\", sep = \";\")\n Nutrition_values = Nutrition_values.rename(columns = {\"type\": \"group\"})\n \n N_to_P_conversion = pd.read_csv(data+\"FAOnitrogen_protein_conversion_factors.csv\", sep = \";\")\n Nutrition_values[\"nitrogen(%)\"] = np.where(Nutrition_values[\"item number\"].eq(N_to_P_conversion[\"item number\"]),\\\n Nutrition_values[\"protein(%)\"]/N_to_P_conversion[\"conversion factor\"], 0)\n \n Protein_percent = Nutrition_values.groupby([\"group\"]).apply(lambda x: x[\"protein(%)\"].mean())\n Nutrient_percent = Protein_percent.reset_index(level = [\"group\"])\n Nutrient_percent = Nutrient_percent.fillna(value = 0)\n Nutrient_percent = Nutrient_percent.rename(columns = {0: \"%protein\"})\n \n Calorie_percent = Nutrition_values.groupby([\"group\"]).apply(lambda x: x[\"calories (100g)\"].mean()/100)\n Calorie_percent = Calorie_percent.reset_index(level = [\"group\"])\n Calorie_percent = Calorie_percent.fillna(value = 0)\n Calorie_percent = Calorie_percent.rename(columns = {0: \"calories per g\"})\n \n Fat_percent = Nutrition_values.groupby([\"group\"]).apply(lambda x: x[\"fat(%)\"].mean())\n Fat_percent = Fat_percent.reset_index(level = [\"group\"])\n Fat_percent = Fat_percent.fillna(value = 0)\n Fat_percent = Fat_percent.rename(columns = {0: \"%fat\"})\n \n \n Nutrient_percent[\"calories per g\"] = Calorie_percent[\"calories per g\"]\n Nutrient_percent[\"%fat\"] = Fat_percent['%fat']\n \n POM_data = pd.merge(POM_data, Nutrient_percent, on = [\"group\"])\n POM_data[\"% Protein\"].fillna(POM_data[\"%protein\"], inplace = True)\n POM_data = POM_data.drop([\"%protein\"], axis = 1)\n POM_data = POM_data.dropna(subset = ['POM'])\n \n \"\"\"*** Calculate protein and calorie demand of each nation ***\"\"\"\n POM_data[\"Protein Needed (g)\"] = POM_data[\"avg weight\"] * 1.6\n POM_data[\"Calories Needed (cal)\"] = POM_data[\"avg weight\"] * 15 + 587.5\n \n \n \"\"\"*** Determine the ratio of what people eat based on EAT Lancet Categories *** \"\"\"\n POM_data[\"EAT_group\"] = POM_data.apply(lambda x: regions.EAT_Lancet_Group(x[\"group\"]), axis =1)\n POM_data[\"POM CAL (no waste)\"] = POM_data['POM (no waste)']*POM_data['calories per g']\n POM_data[\"POM fat (no waste)\"] = POM_data['POM (no waste)']*POM_data['%fat']/100\n \n #POM_data[\"POM EAT Group %\"] = POM_data[\"EAT_group\"]\n POM_eat_group = POM_data.groupby([\"Area\", \"EAT_group\"]).apply(lambda x: (x[\"POM CAL (no waste)\"])/(x[\"POM CAL (no waste)\"]).sum()) #fix the last definition of POM group %\n POM_eat_group = POM_eat_group.to_frame() #set_index(\"Index\", inplace = True)\n POM_eat_group = POM_eat_group.reset_index(level = [\"Area\", \"EAT_group\"])\n POM_eat_group = POM_eat_group.rename(columns={0 : \"POM CAL (no waste)\"})\n #POM_eat_group.set_index(\"Index\", inplace = True)\n POM_data = POM_data.merge(POM_eat_group[\"POM CAL (no waste)\"], left_index=True, right_index = True)\n POM_data = POM_data.rename(columns={\"POM CAL (no waste)_x\" : \"POM CAL (no waste)\",\\\n \"POM CAL (no waste)_y\" : \"POM EAT Group cal %\"})\n \n POM_eat_group = POM_data.groupby([\"Area\", \"EAT_group\"]).apply(lambda x: x[\"POM (no waste)\"]/x[\"POM (no waste)\"].sum()) #fix the last definition of POM group %\n POM_eat_group = POM_eat_group.to_frame() #set_index(\"Index\", inplace = True)\n POM_eat_group = POM_eat_group.reset_index(level = [\"Area\", \"EAT_group\"])\n \n POM_data = POM_data.merge(POM_eat_group[\"POM (no waste)\"], left_index=True, right_index = True)\n POM_data = POM_data.rename(columns={\"POM (no waste)_x\" : \"POM (no waste)\",\\\n \"POM (no waste)_y\" : \"POM EAT Group g %\"})\n \n POM_data[\"POM EAT Group cal %\"] = POM_data[\"POM EAT Group cal %\"] * 100 \n POM_data[\"POM EAT Group g %\"] = POM_data[\"POM EAT Group g %\"] * 100 \n \n return POM_data\n\n\ndef eat_diet_build(POM_data, wastefractions, diet_main):\n Lancet_Targets = {\"group\": [\"whole grains\", \"tubers or starchy vegetables\", \"vegetables\",\\\n \"all fruit\", \"dairy foods\", \"beef, lamb and pork\", \"chicken and other poultry\",\\\n \"eggs\", \"fish\", \"legumes\", \"nuts\", \"added fats\", \"added sugars\"],\n\n \"caloric intake\": diet_main}\n Lancet_Targets = pd.DataFrame(Lancet_Targets)\n\n Lancet_percent = pd.DataFrame()\n Lancet_percent [\"group total\"] = Lancet_Targets.groupby([\"group\"]).apply(lambda x: x[\"caloric intake\"].sum())\n Lancet_percent [\"% of total\"] = (Lancet_percent[\"group total\"]/Lancet_Targets[\"caloric intake\"].sum())*100\n Lancet_percent = Lancet_percent.rename(index={\"tubers or starchy vegetables\" : \"potatoes and cassava\"})\n\n POM_data [\"EAT CAL %\"] = POM_data [\"POM (no waste) total %\"]\n for n, gr in POM_data.groupby(\"EAT_group\"):\n POM_data.loc[(POM_data[\"EAT_group\"] == n), \"EAT CAL %\"] = Lancet_percent.loc[(Lancet_percent.index == n), \"% of total\"].values[0]\n\n\n POM_data['EAT Cons Cal'] = POM_data [\"EAT CAL %\"] * POM_data['POM EAT Group cal %']/100\n POM_data['gP/cal'] = (POM_data['% Protein']/100)/POM_data['calories per g']\n POM_data['gP'] = POM_data['gP/cal'] * POM_data['EAT Cons Cal']/100\n POM_data['p factor'] = 0\n for i in POM_data.Area.unique().tolist():\n POM_data.loc[POM_data.Area == i, 'p factor'] = float(POM_data.loc[POM_data.Area == i, 'Protein Needed (g)'].unique() / POM_data.loc[POM_data.Area == i, 'gP'].sum())\n #POM_data['gP'] *= POM_data['p factor']\n POM_data['gP Needed'] = POM_data['gP'] * POM_data['p factor']\n POM_data['Cal Needed'] = POM_data['gP Needed']/POM_data['gP/cal']\n\n for i in POM_data.Area.unique().tolist():\n POM_data.loc[(POM_data.gP == 0)&(POM_data.Area == i), 'Cal Needed' ] = POM_data.loc[(POM_data.Area == i),'Cal Needed'].sum() * POM_data.loc[(POM_data.gP == 0)&(POM_data.Area == i),'EAT Cons Cal']/100\n \n POM_data['gF Needed'] = POM_data['Cal Needed']/POM_data['calories per g']\n POM_data['EAT POM'] = (POM_data[\"gF Needed\"])*POM_data[\"Population (2016), 1000person\"]*1000*365/(10**9)\n POM_data[\"EAT POM fat (no waste)\"] = POM_data['gF Needed']*POM_data['%fat']/100\n \n POM_data['gF per Capita'] = 0\n POM_data['Cal Provided'] = 0\n for i in POM_data.Area.unique().tolist():\n POM_data.loc[POM_data.Area == i, 'Cal Provided'] = float(POM_data.loc[(POM_data.Area == i),'Cal Needed'].sum())\n POM_data.loc[POM_data.Area == i, 'gF per Capita'] = float(POM_data.loc[(POM_data.Area == i),'gF Needed'].sum())\n POM_data.loc[POM_data.Area == i, 'Fat Provided'] = float(POM_data.loc[(POM_data.Area == i),'EAT POM fat (no waste)'].sum())\n\n\n\n \"\"\"***Determine the WASTE fraction of foods regionally and on the supply chain.***\"\"\"\n POM_data[\"EAT POM (with waste)\"] = POM_data[\"EAT POM\"]\n for n, gr in POM_data.groupby(\"GROUP\"):\n if n == 'Other':\n continue\n POM_data.loc[(POM_data[\"GROUP\"] == n) & (POM_data[\"group\"] == \"potatoes and cassava\"), \"EAT POM (with waste)\"] /= (1 - wastefractions.loc[(wastefractions[\"Region\"] == n) & (wastefractions[\"Foodtype\"] == \"Rootsandtubers\"), \"Total\"].values)\n POM_data.loc[(POM_data[\"GROUP\"] == n) & (POM_data[\"group\"].isin([\"dry beans lentils and peas\", \"soy foods\", \"peanuts\", \"tree nuts\", \"palm oil\", \"unsaturated oils\", \"all sweeteners\"])), \"EAT POM (with waste)\"] /= (1 - wastefractions.loc[(wastefractions[\"Region\"] == n) & (wastefractions[\"Foodtype\"] == \"Oilseedsandpulses\"), \"Total\"].values)\n POM_data.loc[(POM_data[\"GROUP\"] == n) & (POM_data[\"group\"] == \"rice wheat corn and other\"), \"EAT POM (with waste)\"] /= (1 - wastefractions.loc[(wastefractions[\"Region\"] == n) & (wastefractions[\"Foodtype\"] == \"Cereals\"), \"Total\"].values)\n POM_data.loc[(POM_data[\"GROUP\"] == n) & (POM_data[\"group\"].isin([\"all fruit\", \"all vegetables\", \"dark green vegetables\", \"red and orange vegetables\"])), \"EAT POM (with waste)\"] /= (1 - wastefractions.loc[(wastefractions[\"Region\"] == n) & (wastefractions[\"Foodtype\"] == \"Fruitsandvegetables\"), \"Total\"].values)\n POM_data.loc[(POM_data[\"GROUP\"] == n) & (POM_data[\"group\"].isin([\"eggs\", \"beef and lamb\", \"chicken and other poultry\", \"pork\"])), \"EAT POM (with waste)\"] /= (1 - wastefractions.loc[(wastefractions[\"Region\"] == n) & (wastefractions[\"Foodtype\"] == \"Meat\"), \"Total\"].values)\n POM_data.loc[(POM_data[\"GROUP\"] == n) & (POM_data[\"group\"].isin([\"whole milk or derivative equivalents\"])), \"EAT POM (with waste)\"] /= (1 - wastefractions.loc[(wastefractions[\"Region\"] == n) & (wastefractions[\"Foodtype\"] == \"Milk\"), \"Total\"].values)\n POM_data.loc[(POM_data[\"GROUP\"] == n) & (POM_data[\"group\"].isin([\"fish\"])), \"EAT POM (with waste)\"]/= (1 - wastefractions.loc[(wastefractions[\"Region\"] == n) & (wastefractions[\"Foodtype\"] == \"Fishandseafood\"), \"Total\"].values)\n\n POM_percent = POM_data.groupby([\"Area\"]).apply(lambda x: (x[\"EAT POM (with waste)\"]/x[\"EAT POM (with waste)\"].sum())*100)\n POM_percent = POM_percent.reset_index(level = [\"Area\"])\n POM_percent = POM_percent.fillna(value = 0)\n POM_data = POM_data.merge(POM_percent[\"EAT POM (with waste)\"].to_frame(), left_index=True, right_index=True)\n POM_data = POM_data.rename(columns = {\"EAT POM (with waste)_x\": \"EAT POM (with waste)\",\\\n \"EAT POM (with waste)_y\": \"EAT POM Total %\"})\n \n return POM_data"
] |
[
[
"pandas.merge",
"pandas.read_excel",
"pandas.read_csv",
"pandas.concat",
"numpy.isnan",
"pandas.DataFrame"
]
] |
Dragon-hxl/LARC
|
[
"e13295d7217b621e6e2691b57cd58c88cded5830"
] |
[
"dreamcoder/grammar.py"
] |
[
"from frozendict import frozendict\nfrom collections import defaultdict\n\nfrom dreamcoder.frontier import *\nfrom dreamcoder.program import *\nfrom dreamcoder.type import *\nfrom dreamcoder.utilities import *\n\nimport time\n\nimport itertools\n\nclass GrammarFailure(Exception):\n pass\n\nclass SketchEnumerationFailure(Exception):\n pass\n\nclass NoCandidates(Exception):\n pass\n\n\nclass Grammar(object):\n def __init__(self, logVariable, productions, continuationType=None):\n self.logVariable = logVariable\n self.productions = productions\n\n self.continuationType = continuationType\n\n self.expression2likelihood = dict((p, l) for l, _, p in productions)\n self.expression2likelihood[Index(0)] = self.logVariable\n\n def randomWeights(self, r):\n \"\"\"returns a new grammar with random weights drawn from r. calls `r` w/ old weight\"\"\"\n return Grammar(logVariable=r(self.logVariable),\n productions=[(r(l),t,p)\n for l,t,p in self.productions ],\n continuationType=self.continuationType)\n\n def strip_primitive_values(self):\n return Grammar(logVariable=self.logVariable,\n productions=[(l,t,strip_primitive_values(p))\n for l,t,p in self.productions ],\n continuationType=self.continuationType)\n\n def unstrip_primitive_values(self):\n return Grammar(logVariable=self.logVariable,\n productions=[(l,t,unstrip_primitive_values(p))\n for l,t,p in self.productions ],\n continuationType=self.continuationType)\n\n def __setstate__(self, state):\n \"\"\"\n Legacy support for loading grammar objects without the imperative type filled in\n \"\"\"\n assert 'logVariable' in state\n assert 'productions' in state\n if 'continuationType' in state:\n continuationType = state['continuationType']\n else:\n if any( 'turtle' in str(t) for l,t,p in state['productions'] ):\n continuationType = baseType(\"turtle\")\n elif any( 'tower' in str(t) for l,t,p in state['productions'] ):\n continuationType = baseType(\"tower\")\n else:\n continuationType = None\n \n self.__init__(state['logVariable'], state['productions'], continuationType=continuationType)\n\n @staticmethod\n def fromProductions(productions, logVariable=0.0, continuationType=None):\n \"\"\"Make a grammar from primitives and their relative logpriors.\"\"\"\n return Grammar(logVariable, [(l, p.infer(), p)\n for l, p in productions],\n continuationType=continuationType)\n\n @staticmethod\n def uniform(primitives, continuationType=None):\n return Grammar(0.0, [(0.0, p.infer(), p) for p in primitives], continuationType=continuationType)\n\n def __len__(self): return len(self.productions)\n\n def __str__(self):\n def productionKey(xxx_todo_changeme):\n (l, t, p) = xxx_todo_changeme\n return not isinstance(p, Primitive), l is not None and -l\n if self.continuationType is not None:\n lines = [\"continuation : %s\"%self.continuationType]\n else:\n lines = []\n lines += [\"%f\\tt0\\t$_\" % self.logVariable]\n for l, t, p in sorted(self.productions, key=productionKey):\n if l is not None:\n l = \"%f\\t%s\\t%s\" % (l, t, p)\n else:\n l = \"-Inf\\t%s\\t%s\" % (t, p)\n if not t.isArrow() and isinstance(p, Invented):\n try:\n l += \"\\teval = %s\" % (p.evaluate([]))\n except BaseException:\n pass\n\n lines.append(l)\n return \"\\n\".join(lines)\n\n def json(self):\n j = {\"logVariable\": self.logVariable,\n \"productions\": [{\"expression\": str(p), \"logProbability\": l}\n for l, _, p in self.productions]}\n if self.continuationType is not None:\n j[\"continuationType\"] = self.continuationType.json()\n return j\n\n def _immutable_code(self): return self.logVariable, tuple(self.productions)\n\n def __eq__(self, o): return self._immutable_code() == o._immutable_code()\n\n def __ne__(self, o): return not (self == o)\n\n def __hash__(self): return hash(self._immutable_code())\n\n @property\n def primitives(self):\n return [p for _, _, p in self.productions]\n\n def removeProductions(self, ps):\n return Grammar(\n self.logVariable, [\n (l, t, p) for (\n l, t, p) in self.productions if p not in ps],\n continuationType=self.continuationType)\n\n def buildCandidates(self, request, context, environment,\n # Should the log probabilities be normalized?\n normalize=True,\n # Should be returned a table mapping primitives to\n # their candidate entry?\n returnTable=False,\n # Should we return probabilities vs log probabilities?\n returnProbabilities=False,\n # Must be a leaf (have no arguments)?\n mustBeLeaf=False):\n \"\"\"Primitives that are candidates for being used given a requested type\n If returnTable is false (default): returns [((log)likelihood, tp, primitive, context)]\n if returntable is true: returns {primitive: ((log)likelihood, tp, context)}\"\"\"\n if returnProbabilities:\n assert normalize\n\n candidates = []\n variableCandidates = []\n for l, t, p in self.productions:\n try:\n newContext, t = t.instantiate(context)\n newContext = newContext.unify(t.returns(), request)\n t = t.apply(newContext)\n if mustBeLeaf and t.isArrow():\n continue\n candidates.append((l, t, p, newContext))\n except UnificationFailure:\n continue\n for j, t in enumerate(environment):\n try:\n newContext = context.unify(t.returns(), request)\n t = t.apply(newContext)\n if mustBeLeaf and t.isArrow():\n continue\n variableCandidates.append((t, Index(j), newContext))\n except UnificationFailure:\n continue\n\n if self.continuationType == request:\n terminalIndices = [v.i for t,v,k in variableCandidates if not t.isArrow()]\n if terminalIndices:\n smallestIndex = Index(min(terminalIndices))\n variableCandidates = [(t,v,k) for t,v,k in variableCandidates\n if t.isArrow() or v == smallestIndex]\n \n candidates += [(self.logVariable - log(len(variableCandidates)), t, p, k)\n for t, p, k in variableCandidates]\n if candidates == []:\n raise NoCandidates()\n #eprint(\"candidates inside buildCandidates before norm:\")\n #eprint(candidates)\n\n if normalize:\n z = lse([l for l, t, p, k in candidates])\n if returnProbabilities:\n candidates = [(exp(l - z), t, p, k)\n for l, t, p, k in candidates]\n else:\n candidates = [(l - z, t, p, k) for l, t, p, k in candidates]\n\n #eprint(\"candidates inside buildCandidates after norm:\")\n #eprint(candidates)\n\n if returnTable:\n return {p: (l, t, k) for l, t, p, k in candidates}\n else:\n return candidates\n\n\n def sample(self, request, maximumDepth=6, maxAttempts=None):\n attempts = 0\n\n while True:\n try:\n _, e = self._sample(\n request, Context.EMPTY, [], maximumDepth=maximumDepth)\n return e\n except NoCandidates:\n if maxAttempts is not None:\n attempts += 1\n if attempts > maxAttempts:\n return None\n continue\n\n def _sample(self, request, context, environment, maximumDepth):\n if request.isArrow():\n context, expression = self._sample(\n request.arguments[1], context, [\n request.arguments[0]] + environment, maximumDepth)\n return context, Abstraction(expression)\n\n candidates = self.buildCandidates(request, context, environment,\n normalize=True,\n returnProbabilities=True,\n # Force it to terminate in a\n # leaf; a primitive with no\n # function arguments\n mustBeLeaf=maximumDepth <= 1)\n #eprint(\"candidates:\")\n #eprint(candidates)\n newType, chosenPrimitive, context = sampleDistribution(candidates)\n\n # Sample the arguments\n xs = newType.functionArguments()\n returnValue = chosenPrimitive\n\n for x in xs:\n x = x.apply(context)\n context, x = self._sample(x, context, environment, maximumDepth - 1)\n returnValue = Application(returnValue, x)\n\n return context, returnValue\n\n def likelihoodSummary(self, context, environment, request, expression, silent=False):\n if request.isArrow():\n if not isinstance(expression, Abstraction):\n if not silent:\n eprint(\"Request is an arrow but I got\", expression)\n return context, None\n return self.likelihoodSummary(context,\n [request.arguments[0]] + environment,\n request.arguments[1],\n expression.body,\n silent=silent)\n # Build the candidates\n candidates = self.buildCandidates(request, context, environment,\n normalize=False,\n returnTable=True)\n\n # A list of everything that would have been possible to use here\n possibles = [p for p in candidates.keys() if not p.isIndex]\n numberOfVariables = sum(p.isIndex for p in candidates.keys())\n if numberOfVariables > 0:\n possibles += [Index(0)]\n\n f, xs = expression.applicationParse()\n\n if f not in candidates:\n if self.continuationType is not None and f.isIndex:\n ls = LikelihoodSummary()\n ls.constant = NEGATIVEINFINITY\n return ls\n \n if not silent:\n eprint(f, \"Not in candidates\")\n eprint(\"Candidates is\", candidates)\n #eprint(\"grammar:\", grammar.productions)\n eprint(\"request is\", request)\n eprint(\"xs\", xs)\n eprint(\"environment\", environment)\n assert False\n return context, None\n\n thisSummary = LikelihoodSummary()\n thisSummary.record(f, possibles,\n constant= -math.log(numberOfVariables) if f.isIndex else 0)\n\n _, tp, context = candidates[f]\n argumentTypes = tp.functionArguments()\n if len(xs) != len(argumentTypes):\n eprint(\"PANIC: not enough arguments for the type\")\n eprint(\"request\", request)\n eprint(\"tp\", tp)\n eprint(\"expression\", expression)\n eprint(\"xs\", xs)\n eprint(\"argumentTypes\", argumentTypes)\n # This should absolutely never occur\n raise GrammarFailure((context, environment, request, expression))\n\n for argumentType, argument in zip(argumentTypes, xs):\n argumentType = argumentType.apply(context)\n context, newSummary = self.likelihoodSummary(\n context, environment, argumentType, argument, silent=silent)\n if newSummary is None:\n return context, None\n thisSummary.join(newSummary)\n\n return context, thisSummary\n\n def bestFirstEnumeration(self, request):\n from heapq import heappush, heappop\n\n pq = []\n\n def choices(parentCost, xs):\n for c, x in xs:\n heappush(pq, (parentCost + c, x))\n\n def g(parentCost, request, _=None,\n context=None, environment=[],\n k=None):\n \"\"\"\n k is a continuation.\n k: Expects to be called with MDL, context, expression.\n \"\"\"\n\n assert k is not None\n if context is None:\n context = Context.EMPTY\n\n if request.isArrow():\n g(parentCost,\n request.arguments[1],\n context=context,\n environment=[request.arguments[0]] + environment,\n k=lambda MDL,\n newContext,\n p: k(MDL,\n newContext,\n Abstraction(p)))\n else:\n candidates = self.buildCandidates(request,\n context,\n environment,\n normalize=True,\n returnProbabilities=False,\n returnTable=True)\n choices(parentCost,\n [(-f_ll_tp_newContext[1][0],\n lambda: ga(parentCost - f_ll_tp_newContext[1][0],\n f_ll_tp_newContext[0],\n f_ll_tp_newContext[1][1].functionArguments(),\n context=f_ll_tp_newContext[1][2],\n environment=environment,\n k=k)) for f_ll_tp_newContext in iter(candidates.items())])\n\n def ga(costSoFar, f, argumentTypes, _=None,\n context=None, environment=None,\n k=None):\n if argumentTypes == []:\n k(costSoFar, context, f)\n else:\n t1 = argumentTypes[0].apply(context)\n g(costSoFar, t1, context=context, environment=environment,\n k=lambda newCost, newContext, argument:\n ga(newCost, Application(f, argument), argumentTypes[1:],\n context=newContext, environment=environment,\n k=k))\n\n def receiveResult(MDL, _, expression):\n heappush(pq, (MDL, expression))\n\n g(0., request, context=Context.EMPTY, environment=[], k=receiveResult)\n frontier = []\n while len(frontier) < 10**3:\n MDL, action = heappop(pq)\n if isinstance(action, Program):\n expression = action\n frontier.append(expression)\n #eprint(\"Enumerated program\",expression,-MDL,self.closedLogLikelihood(request, expression))\n else:\n action()\n\n def closedLikelihoodSummary(self, request, expression, silent=False):\n try:\n context, summary = self.likelihoodSummary(Context.EMPTY, [], request, expression, silent=silent)\n except GrammarFailure as e:\n failureExport = 'failures/grammarFailure%s.pickle' % (\n time.time() + getPID())\n eprint(\"PANIC: Grammar failure, exporting to \", failureExport)\n with open(failureExport, 'wb') as handle:\n pickle.dump((e, self, request, expression), handle)\n assert False\n\n return summary\n\n def logLikelihood(self, request, expression):\n summary = self.closedLikelihoodSummary(request, expression)\n if summary is None:\n eprint(\n \"FATAL: program [ %s ] does not have a likelihood summary.\" %\n expression, \"r = \", request, \"\\n\", self)\n assert False\n return summary.logLikelihood(self)\n\n def rescoreFrontier(self, frontier):\n return Frontier([FrontierEntry(e.program,\n logPrior=self.logLikelihood(frontier.task.request, e.program),\n logLikelihood=e.logLikelihood)\n for e in frontier],\n frontier.task)\n\n def productionUses(self, frontiers):\n \"\"\"Returns the expected number of times that each production was used. {production: expectedUses}\"\"\"\n frontiers = [self.rescoreFrontier(f).normalize()\n for f in frontiers if not f.empty]\n uses = {p: 0. for p in self.primitives}\n for f in frontiers:\n for e in f:\n summary = self.closedLikelihoodSummary(f.task.request,\n e.program)\n for p, u in summary.uses:\n uses[p] += u * math.exp(e.logPosterior)\n return uses\n\n def insideOutside(self, frontiers, pseudoCounts, iterations=1):\n # Replace programs with (likelihood summary, uses)\n frontiers = [ Frontier([ FrontierEntry((summary, summary.toUses()),\n logPrior=summary.logLikelihood(self),\n logLikelihood=e.logLikelihood)\n for e in f\n for summary in [self.closedLikelihoodSummary(f.task.request, e.program)] ],\n task=f.task)\n for f in frontiers ]\n\n g = self\n for i in range(iterations):\n u = Uses()\n for f in frontiers:\n f = f.normalize()\n for e in f:\n _, eu = e.program\n u += math.exp(e.logPosterior) * eu\n\n lv = math.log(u.actualVariables + pseudoCounts) - \\\n math.log(u.possibleVariables + pseudoCounts)\n g = Grammar(lv,\n [ (math.log(u.actualUses.get(p,0.) + pseudoCounts) - \\\n math.log(u.possibleUses.get(p,0.) + pseudoCounts),\n t,p)\n for _,t,p in g.productions ],\n continuationType=self.continuationType)\n if i < iterations - 1:\n frontiers = [Frontier([ FrontierEntry((summary, uses),\n logPrior=summary.logLikelihood(g),\n logLikelihood=e.logLikelihood)\n for e in f\n for (summary, uses) in [e.program] ],\n task=f.task)\n for f in frontiers ]\n return g\n\n def frontierMDL(self, frontier):\n return max( e.logLikelihood + self.logLikelihood(frontier.task.request, e.program)\n for e in frontier ) \n\n\n def enumeration(self,context,environment,request,upperBound,\n maximumDepth=20,\n lowerBound=0.):\n '''Enumerates all programs whose MDL satisfies: lowerBound <= MDL < upperBound'''\n if upperBound < 0 or maximumDepth == 1:\n return\n\n if request.isArrow():\n v = request.arguments[0]\n for l, newContext, b in self.enumeration(context, [v] + environment,\n request.arguments[1],\n upperBound=upperBound,\n lowerBound=lowerBound,\n maximumDepth=maximumDepth):\n yield l, newContext, Abstraction(b)\n\n else:\n candidates = self.buildCandidates(request, context, environment,\n normalize=True)\n\n for l, t, p, newContext in candidates:\n mdl = -l\n if not (mdl < upperBound):\n continue\n\n xs = t.functionArguments()\n for aL, aK, application in\\\n self.enumerateApplication(newContext, environment, p, xs,\n upperBound=upperBound + l,\n lowerBound=lowerBound + l,\n maximumDepth=maximumDepth - 1):\n yield aL + l, aK, application\n\n def enumerateApplication(self, context, environment,\n function, argumentRequests,\n # Upper bound on the description length of all of\n # the arguments\n upperBound,\n # Lower bound on the description length of all of\n # the arguments\n lowerBound=0.,\n maximumDepth=20,\n originalFunction=None,\n argumentIndex=0):\n if upperBound < 0. or maximumDepth == 1:\n return\n if originalFunction is None:\n originalFunction = function\n\n if argumentRequests == []:\n if lowerBound <= 0. and 0. < upperBound:\n yield 0., context, function\n else:\n return\n else:\n argRequest = argumentRequests[0].apply(context)\n laterRequests = argumentRequests[1:]\n for argL, newContext, arg in self.enumeration(context, environment, argRequest,\n upperBound=upperBound,\n lowerBound=0.,\n maximumDepth=maximumDepth):\n if violatesSymmetry(originalFunction, arg, argumentIndex):\n continue\n\n newFunction = Application(function, arg)\n for resultL, resultK, result in self.enumerateApplication(newContext, environment, newFunction,\n laterRequests,\n upperBound=upperBound + argL,\n lowerBound=lowerBound + argL,\n maximumDepth=maximumDepth,\n originalFunction=originalFunction,\n argumentIndex=argumentIndex + 1):\n yield resultL + argL, resultK, result\n\n def sketchEnumeration(self,context,environment,request,sk,upperBound,\n maximumDepth=20,\n lowerBound=0.):\n '''Enumerates all sketch instantiations whose MDL satisfies: lowerBound <= MDL < upperBound'''\n if upperBound < 0. or maximumDepth == 1:\n return\n\n if sk.isHole:\n yield from self.enumeration(context, environment, request, upperBound,\n maximumDepth=maximumDepth,\n lowerBound=lowerBound)\n elif request.isArrow():\n assert sk.isAbstraction\n v = request.arguments[0]\n for l, newContext, b in self.sketchEnumeration(context, [v] + environment,\n request.arguments[1],\n sk.body,\n upperBound=upperBound,\n lowerBound=lowerBound,\n maximumDepth=maximumDepth):\n yield l, newContext, Abstraction(b)\n\n else:\n f, xs = sk.applicationParse()\n if f.isIndex:\n ft = environment[f.i].apply(context)\n elif f.isInvented or f.isPrimitive:\n context, ft = f.tp.instantiate(context)\n elif f.isAbstraction:\n assert False, \"sketch is not in beta longform\"\n elif f.isHole:\n assert False, \"hole as function not yet supported\"\n elif f.isApplication:\n assert False, \"should never happen - bug in applicationParse\"\n else: assert False\n\n try: context = context.unify(ft.returns(), request) \n except UnificationFailure:\n eprint(\"Exception: sketch is ill-typed\")\n return #so that we can continue evaluating\n # raise SketchEnumerationFailure() #\"sketch is ill-typed\"\n ft = ft.apply(context)\n argumentRequests = ft.functionArguments()\n\n assert len(argumentRequests) == len(xs)\n\n yield from self.sketchApplication(context, environment,\n f, xs, argumentRequests,\n upperBound=upperBound,\n lowerBound=lowerBound,\n maximumDepth=maximumDepth - 1)\n\n\n def sketchApplication(self, context, environment,\n function, arguments, argumentRequests,\n # Upper bound on the description length of all of\n # the arguments\n upperBound,\n # Lower bound on the description length of all of\n # the arguments\n lowerBound=0.,\n maximumDepth=20):\n if upperBound < 0. or maximumDepth == 1:\n return\n\n if argumentRequests == []:\n if lowerBound <= 0. and 0. < upperBound:\n yield 0., context, function\n else:\n return\n else:\n argRequest = argumentRequests[0].apply(context)\n laterRequests = argumentRequests[1:]\n firstSketch = arguments[0]\n laterSketches = arguments[1:]\n for argL, newContext, arg in self.sketchEnumeration(context, environment, argRequest,\n firstSketch,\n upperBound=upperBound,\n lowerBound=0.,\n maximumDepth=maximumDepth):\n\n newFunction = Application(function, arg)\n for resultL, resultK, result in self.sketchApplication(newContext, environment, newFunction,\n laterSketches, laterRequests,\n upperBound=upperBound + argL,\n lowerBound=lowerBound + argL,\n maximumDepth=maximumDepth):\n\n yield resultL + argL, resultK, result\n\n def sketchLogLikelihood(self, request, full, sk, context=Context.EMPTY, environment=[]):\n \"\"\"\n calculates mdl of full program 'full' from sketch 'sk'\n \"\"\"\n if sk.isHole:\n _, summary = self.likelihoodSummary(context, environment, request, full)\n if summary is None:\n eprint(\n \"FATAL: program [ %s ] does not have a likelihood summary.\" %\n full, \"r = \", request, \"\\n\", self)\n assert False\n return summary.logLikelihood(self), context\n\n elif request.isArrow():\n assert sk.isAbstraction and full.isAbstraction\n #assert sk.f == full.f #is this right? or do i need to recurse?\n v = request.arguments[0]\n return self.sketchLogLikelihood(request.arguments[1], full.body, sk.body, context=context, environment=[v] + environment)\n\n else:\n sk_f, sk_xs = sk.applicationParse()\n full_f, full_xs = full.applicationParse()\n if sk_f.isIndex:\n assert sk_f == full_f, \"sketch and full program don't match on an index\"\n ft = environment[sk_f.i].apply(context)\n elif sk_f.isInvented or sk_f.isPrimitive:\n assert sk_f == full_f, \"sketch and full program don't match on a primitive\"\n context, ft = sk_f.tp.instantiate(context)\n elif sk_f.isAbstraction:\n assert False, \"sketch is not in beta longform\"\n elif sk_f.isHole:\n assert False, \"hole as function not yet supported\"\n elif sk_f.isApplication:\n assert False, \"should never happen - bug in applicationParse\"\n else: assert False\n\n try: context = context.unify(ft.returns(), request) \n except UnificationFailure: assert False, \"sketch is ill-typed\"\n ft = ft.apply(context)\n argumentRequests = ft.functionArguments()\n\n assert len(argumentRequests) == len(sk_xs) == len(full_xs) #this might not be true if holes??\n\n return self.sketchllApplication(context, environment,\n sk_f, sk_xs, full_f, full_xs, argumentRequests)\n\n def sketchllApplication(self, context, environment,\n sk_function, sk_arguments, full_function, full_arguments, argumentRequests):\n if argumentRequests == []:\n return torch.tensor([0.]).cuda(), context #does this make sense?\n else:\n argRequest = argumentRequests[0].apply(context)\n laterRequests = argumentRequests[1:]\n\n sk_firstSketch = sk_arguments[0]\n full_firstSketch = full_arguments[0]\n sk_laterSketches = sk_arguments[1:]\n full_laterSketches = full_arguments[1:]\n\n argL, newContext = self.sketchLogLikelihood(argRequest, full_firstSketch, sk_firstSketch, context=context, environment=environment)\n\n #finish this...\n sk_newFunction = Application(sk_function, sk_firstSketch) # is this redundant? maybe \n full_newFunction = Application(full_function, full_firstSketch)\n\n resultL, context = self.sketchllApplication(newContext, environment, sk_newFunction, sk_laterSketches,\n full_newFunction, full_laterSketches, laterRequests)\n\n return resultL + argL, context\n\n \n def enumerateNearby(self, request, expr, distance=3.0):\n \"\"\"Enumerate programs with local mutations in subtrees with small description length\"\"\"\n if distance <= 0:\n yield expr\n else:\n def mutations(tp, loss):\n for l, _, expr in self.enumeration(\n Context.EMPTY, [], tp, distance - loss):\n yield expr, l\n yield from Mutator(self, mutations).execute(expr, request)\n\n\n def enumerateHoles(self, request, expr, k=3, return_obj=Hole):\n \"\"\"Enumerate programs with a single hole within mdl distance\"\"\"\n #TODO: make it possible to enumerate sketches with multiple holes\n def mutations(tp, loss, is_left_application=False):\n \"\"\"\n to allow applications lhs to become a hole, \n remove the condition below and ignore all the is_left_application kwds \n \"\"\"\n if not is_left_application: \n yield return_obj(), 0\n top_k = []\n for expr, l in Mutator(self, mutations).execute(expr, request):\n if len(top_k) > 0:\n i, v = min(enumerate(top_k), key=lambda x:x[1][1])\n if l > v[1]:\n if len(top_k) >= k:\n top_k[i] = (expr, l)\n else:\n top_k.append((expr, l))\n elif len(top_k) < k:\n top_k.append((expr, l))\n else:\n top_k.append((expr, l))\n return sorted(top_k, key=lambda x:-x[1])\n\n def untorch(self):\n return Grammar(self.logVariable.data.tolist()[0], \n [ (l.data.tolist()[0], t, p)\n for l, t, p in self.productions],\n continuationType=self.continuationType)\n\nclass LikelihoodSummary(object):\n '''Summarizes the terms that will be used in a likelihood calculation'''\n\n def __init__(self):\n self.uses = {}\n self.normalizers = {}\n self.constant = 0.\n\n def __str__(self):\n return \"\"\"LikelihoodSummary(constant = %f,\nuses = {%s},\nnormalizers = {%s})\"\"\" % (self.constant,\n \", \".join(\n \"%s: %d\" % (k,\n v) for k,\n v in self.uses.items()),\n \", \".join(\n \"%s: %d\" % (k,\n v) for k,\n v in self.normalizers.items()))\n\n def record(self, actual, possibles, constant=0.):\n # Variables are all normalized to be $0\n if isinstance(actual, Index):\n actual = Index(0)\n\n # Make it something that we can hash\n possibles = frozenset(sorted(possibles, key=hash))\n\n self.constant += constant\n self.uses[actual] = self.uses.get(actual, 0) + 1\n self.normalizers[possibles] = self.normalizers.get(possibles, 0) + 1\n\n def join(self, other):\n self.constant += other.constant\n for k, v in other.uses.items():\n self.uses[k] = self.uses.get(k, 0) + v\n for k, v in other.normalizers.items():\n self.normalizers[k] = self.normalizers.get(k, 0) + v\n\n def logLikelihood(self, grammar):\n return self.constant + \\\n sum(count * grammar.expression2likelihood[p] for p, count in self.uses.items()) - \\\n sum(count * lse([grammar.expression2likelihood[p] for p in ps])\n for ps, count in self.normalizers.items())\n def logLikelihood_overlyGeneral(self, grammar):\n \"\"\"Calculates log likelihood of this summary, given that the summary might refer to productions that don't occur in the grammar\"\"\"\n return self.constant + \\\n sum(count * grammar.expression2likelihood[p] for p, count in self.uses.items()) - \\\n sum(count * lse([grammar.expression2likelihood.get(p,NEGATIVEINFINITY) for p in ps])\n for ps, count in self.normalizers.items()) \n def numerator(self, grammar):\n return self.constant + \\\n sum(count * grammar.expression2likelihood[p] for p, count in self.uses.items())\n def denominator(self, grammar):\n return \\\n sum(count * lse([grammar.expression2likelihood[p] for p in ps])\n for ps, count in self.normalizers.items())\n def toUses(self):\n from collections import Counter\n \n possibleVariables = sum( count if Index(0) in ps else 0\n for ps, count in self.normalizers.items() )\n actualVariables = self.uses.get(Index(0), 0.)\n actualUses = {k: v\n for k, v in self.uses.items()\n if not k.isIndex }\n possibleUses = dict(Counter(p\n for ps, count in self.normalizers.items()\n for p_ in ps\n if not p_.isIndex\n for p in [p_]*count ))\n return Uses(possibleVariables, actualVariables,\n possibleUses, actualUses)\n\n\nclass Uses(object):\n '''Tracks uses of different grammar productions'''\n\n def __init__(self, possibleVariables=0., actualVariables=0.,\n possibleUses={}, actualUses={}):\n self.actualVariables = actualVariables\n self.possibleVariables = possibleVariables\n self.possibleUses = possibleUses\n self.actualUses = actualUses\n\n def __str__(self):\n return \"Uses(actualVariables = %f, possibleVariables = %f, actualUses = %s, possibleUses = %s)\" %\\\n (self.actualVariables, self.possibleVariables, self.actualUses, self.possibleUses)\n\n def __repr__(self): return str(self)\n\n def __mul__(self, a):\n return Uses(a * self.possibleVariables,\n a * self.actualVariables,\n {p: a * u for p, u in self.possibleUses.items()},\n {p: a * u for p, u in self.actualUses.items()})\n\n def __imul__(self, a):\n self.possibleVariables *= a\n self.actualVariables *= a\n for p in self.possibleUses:\n self.possibleUses[p] *= a\n for p in self.actualUses:\n self.actualUses[p] *= a\n return self\n\n def __rmul__(self, a):\n return self * a\n\n def __radd__(self, o):\n if o == 0:\n return self\n return self + o\n\n def __add__(self, o):\n if o == 0:\n return self\n\n def merge(x, y):\n z = x.copy()\n for k, v in y.items():\n z[k] = v + x.get(k, 0.)\n return z\n return Uses(self.possibleVariables + o.possibleVariables,\n self.actualVariables + o.actualVariables,\n merge(self.possibleUses, o.possibleUses),\n merge(self.actualUses, o.actualUses))\n\n def __iadd__(self, o):\n self.possibleVariables += o.possibleVariables\n self.actualVariables += o.actualVariables\n for k, v in o.possibleUses.items():\n self.possibleUses[k] = self.possibleUses.get(k, 0.) + v\n for k, v in o.actualUses.items():\n self.actualUses[k] = self.actualUses.get(k, 0.) + v\n return self\n\n @staticmethod\n def join(z, *weightedUses):\n \"\"\"Consumes weightedUses\"\"\"\n if not weightedUses:\n Uses.empty\n if len(weightedUses) == 1:\n return weightedUses[0][1]\n for w, u in weightedUses:\n u *= exp(w - z)\n total = Uses()\n total.possibleVariables = sum(\n u.possibleVariables for _, u in weightedUses)\n total.actualVariables = sum(u.actualVariables for _, u in weightedUses)\n total.possibleUses = defaultdict(float)\n total.actualUses = defaultdict(float)\n for _, u in weightedUses:\n for k, v in u.possibleUses.items():\n total.possibleUses[k] += v\n for k, v in u.actualUses.items():\n total.actualUses[k] += v\n return total\n\n\nUses.empty = Uses()\n\nclass ContextualGrammar:\n def __init__(self, noParent, variableParent, library):\n self.noParent, self.variableParent, self.library = noParent, variableParent, library\n\n self.productions = [(None,t,p) for _,t,p in self.noParent.productions ]\n self.primitives = [p for _,_2,p in self.productions ]\n\n self.continuationType = noParent.continuationType\n assert variableParent.continuationType == self.continuationType\n\n assert set(noParent.primitives) == set(variableParent.primitives)\n assert set(variableParent.primitives) == set(library.keys())\n for e,gs in library.items():\n assert len(gs) == len(e.infer().functionArguments())\n for g in gs:\n assert set(g.primitives) == set(library.keys())\n assert g.continuationType == self.continuationType\n\n def untorch(self):\n return ContextualGrammar(self.noParent.untorch(), self.variableParent.untorch(),\n {e: [g.untorch() for g in gs ]\n for e,gs in self.library.items() })\n\n def randomWeights(self, r):\n \"\"\"returns a new grammar with random weights drawn from r. calls `r` w/ old weight\"\"\"\n return ContextualGrammar(self.noParent.randomWeights(r),\n self.variableParent.randomWeights(r),\n {e: [g.randomWeights(r) for g in gs]\n for e,gs in self.library.items() })\n def __str__(self):\n lines = [\"No parent:\",str(self.noParent),\"\",\n \"Variable parent:\",str(self.variableParent),\"\",\n \"\"]\n for e,gs in self.library.items():\n for j,g in enumerate(gs):\n lines.extend([\"Parent %s, argument index %s\"%(e,j),\n str(g),\n \"\"])\n return \"\\n\".join(lines)\n\n def json(self):\n return {\"noParent\": self.noParent.json(),\n \"variableParent\": self.variableParent.json(),\n \"productions\": [{\"program\": str(e),\n \"arguments\": [gp.json() for gp in gs ]}\n for e,gs in self.library.items() ]}\n\n @staticmethod\n def fromGrammar(g):\n return ContextualGrammar(g, g,\n {e: [g]*len(e.infer().functionArguments())\n for e in g.primitives })\n \n\n class LS: # likelihood summary\n def __init__(self, owner):\n self.noParent = LikelihoodSummary()\n self.variableParent = LikelihoodSummary()\n self.library = {e: [LikelihoodSummary() for _ in gs] for e,gs in owner.library.items() }\n\n def record(self, parent, parentIndex, actual, possibles, constant):\n if parent is None: ls = self.noParent\n elif parent.isIndex: ls = self.variableParent\n else: ls = self.library[parent][parentIndex]\n ls.record(actual, possibles, constant=constant)\n\n def join(self, other):\n self.noParent.join(other.noParent)\n self.variableParent.join(other.variableParent)\n for e,gs in self.library.items():\n for g1,g2 in zip(gs, other.library[e]):\n g1.join(g2)\n\n def logLikelihood(self, owner):\n return self.noParent.logLikelihood(owner.noParent) + \\\n self.variableParent.logLikelihood(owner.variableParent) + \\\n sum(r.logLikelihood(g)\n for e, rs in self.library.items()\n for r,g in zip(rs, owner.library[e]) ) \n def numerator(self, owner):\n return self.noParent.numerator(owner.noParent) + \\\n self.variableParent.numerator(owner.variableParent) + \\\n sum(r.numerator(g)\n for e, rs in self.library.items()\n for r,g in zip(rs, owner.library[e]) ) \n def denominator(self, owner):\n return self.noParent.denominator(owner.noParent) + \\\n self.variableParent.denominator(owner.variableParent) + \\\n sum(r.denominator(g)\n for e, rs in self.library.items()\n for r,g in zip(rs, owner.library[e]) ) \n\n def likelihoodSummary(self, parent, parentIndex, context, environment, request, expression):\n if request.isArrow():\n assert expression.isAbstraction\n return self.likelihoodSummary(parent, parentIndex,\n context,\n [request.arguments[0]] + environment,\n request.arguments[1],\n expression.body)\n if parent is None: g = self.noParent\n elif parent.isIndex: g = self.variableParent\n else: g = self.library[parent][parentIndex] \n candidates = g.buildCandidates(request, context, environment,\n normalize=False, returnTable=True)\n\n # A list of everything that would have been possible to use here\n possibles = [p for p in candidates.keys() if not p.isIndex]\n numberOfVariables = sum(p.isIndex for p in candidates.keys())\n if numberOfVariables > 0:\n possibles += [Index(0)]\n\n f, xs = expression.applicationParse()\n\n assert f in candidates\n\n thisSummary = self.LS(self)\n thisSummary.record(parent, parentIndex,\n f, possibles,\n constant= -math.log(numberOfVariables) if f.isIndex else 0)\n\n _, tp, context = candidates[f]\n argumentTypes = tp.functionArguments()\n assert len(xs) == len(argumentTypes)\n\n for i, (argumentType, argument) in enumerate(zip(argumentTypes, xs)):\n argumentType = argumentType.apply(context)\n context, newSummary = self.likelihoodSummary(f, i,\n context, environment, argumentType, argument)\n thisSummary.join(newSummary)\n\n return context, thisSummary\n\n def closedLikelihoodSummary(self, request, expression):\n return self.likelihoodSummary(None,None,\n Context.EMPTY,[],\n request, expression)[1]\n\n def logLikelihood(self, request, expression):\n return self.closedLikelihoodSummary(request, expression).logLikelihood(self)\n\n def sample(self, request, maximumDepth=8, maxAttempts=None):\n attempts = 0\n while True:\n try:\n _, e = self._sample(None, None, Context.EMPTY, [], request, maximumDepth)\n return e\n except NoCandidates:\n if maxAttempts is not None:\n attempts += 1\n if attempts > maxAttempts: return None\n continue\n \n def _sample(self, parent, parentIndex, context, environment, request, maximumDepth):\n if request.isArrow():\n context, body = self._sample(parent, parentIndex, context,\n [request.arguments[0]] + environment,\n request.arguments[1],\n maximumDepth)\n return context, Abstraction(body)\n if parent is None: g = self.noParent\n elif parent.isIndex: g = self.variableParent\n else: g = self.library[parent][parentIndex]\n candidates = g.buildCandidates(request, context, environment,\n normalize=True, returnProbabilities=True,\n mustBeLeaf=(maximumDepth <= 1))\n newType, chosenPrimitive, context = sampleDistribution(candidates)\n\n xs = newType.functionArguments()\n returnValue = chosenPrimitive\n\n for j,x in enumerate(xs):\n x = x.apply(context)\n context, x = self._sample(chosenPrimitive, j, context, environment, x, maximumDepth - 1)\n returnValue = Application(returnValue, x)\n \n return context, returnValue\n\n def expectedUsesMonteCarlo(self, request, debug=None):\n import numpy as np\n n = 0\n u = [0.]*len(self.primitives)\n primitives = list(sorted(self.primitives, key=str))\n noInventions = all( not p.isInvented for p in primitives )\n primitive2index = {primitive: i\n for i, primitive in enumerate(primitives)\n if primitive.isInvented or noInventions }\n eprint(primitive2index)\n ns = 10000\n with timing(f\"calculated expected uses using Monte Carlo simulation w/ {ns} samples\"):\n for _ in range(ns):\n p = self.sample(request, maxAttempts=0)\n if p is None: continue\n n += 1\n if debug and n < 10:\n eprint(debug, p)\n for _, child in p.walk():\n if child not in primitive2index: continue\n u[primitive2index[child]] += 1.0\n u = np.array(u)/n\n if debug:\n eprint(f\"Got {n} samples. Feature vector:\\n{u}\")\n eprint(f\"Likely used primitives: {[p for p,i in primitive2index.items() if u[i] > 0.5]}\")\n eprint(f\"Likely used primitive indices: {[i for p,i in primitive2index.items() if u[i] > 0.5]}\")\n return u\n\n def featureVector(self, _=None, requests=None, onlyInventions=True, normalize=True):\n \"\"\"\n Returns the probabilities licensed by the type system.\n This is like the grammar productions, but with irrelevant junk removed.\n Its intended use case is for clustering; it should be strictly better than the raw transition matrix.\n \"\"\"\n if requests is None:\n if self.continuationType: requests = {self.continuationType}\n elif any( 'REAL' == str(p) for p in self.primitives ): requests = set()\n elif any( 'STRING' == str(p) for p in self.primitives ): requests = {tlist(tcharacter)}\n else: requests = set()\n requests = {r.returns() for r in requests}\n features = []\n logWeights = []\n for l,t,p in sorted(self.noParent.productions,\n key=lambda z: str(z[2])):\n if onlyInventions and not p.isInvented: continue\n if any( canUnify(r, t.returns()) for r in requests ) or len(requests) == 0:\n logWeights.append(l)\n features.append(logWeights)\n for parent in sorted(self.primitives, key=str):\n if onlyInventions and not parent.isInvented: continue\n if parent not in self.library: continue\n argumentTypes = parent.infer().functionArguments()\n for j,g in enumerate(self.library[parent]):\n argumentType = argumentTypes[j]\n logWeights = []\n for l,t,p in sorted(g.productions,\n key=lambda z: str(z[2])):\n if onlyInventions and not p.isInvented: continue\n if canUnify(argumentType.returns(), t.returns()):\n logWeights.append(l)\n features.append(logWeights)\n\n if normalize:\n features = [ [math.exp(w - z) for w in lw ]\n for lw in features\n if lw\n for z in [lse(lw)] ]\n import numpy as np\n return np.array([f\n for lw in features\n for f in lw])\n\n def enumeration(self,context,environment,request,upperBound,\n parent=None, parentIndex=None,\n maximumDepth=20,\n lowerBound=0.):\n '''Enumerates all programs whose MDL satisfies: lowerBound <= MDL < upperBound'''\n if upperBound < 0 or maximumDepth == 1:\n return\n\n if request.isArrow():\n v = request.arguments[0]\n for l, newContext, b in self.enumeration(context, [v] + environment,\n request.arguments[1],\n parent=parent, parentIndex=parentIndex,\n upperBound=upperBound,\n lowerBound=lowerBound,\n maximumDepth=maximumDepth):\n yield l, newContext, Abstraction(b)\n else:\n if parent is None: g = self.noParent\n elif parent.isIndex: g = self.variableParent\n else: g = self.library[parent][parentIndex]\n\n candidates = g.buildCandidates(request, context, environment,\n normalize=True)\n\n for l, t, p, newContext in candidates:\n mdl = -l\n if not (mdl < upperBound):\n continue\n\n xs = t.functionArguments()\n for aL, aK, application in\\\n self.enumerateApplication(newContext, environment, p, xs,\n parent=p,\n upperBound=upperBound + l,\n lowerBound=lowerBound + l,\n maximumDepth=maximumDepth - 1):\n yield aL + l, aK, application\n\n def enumerateApplication(self, context, environment,\n function, argumentRequests,\n # Upper bound on the description length of all of\n # the arguments\n upperBound,\n # Lower bound on the description length of all of\n # the arguments\n lowerBound=0.,\n maximumDepth=20,\n parent=None, \n originalFunction=None,\n argumentIndex=0):\n assert parent is not None\n if upperBound < 0. or maximumDepth == 1:\n return\n if originalFunction is None:\n originalFunction = function\n\n if argumentRequests == []:\n if lowerBound <= 0. and 0. < upperBound:\n yield 0., context, function\n else:\n return\n else:\n argRequest = argumentRequests[0].apply(context)\n laterRequests = argumentRequests[1:]\n for argL, newContext, arg in self.enumeration(context, environment, argRequest,\n parent=parent, parentIndex=argumentIndex,\n upperBound=upperBound,\n lowerBound=0.,\n maximumDepth=maximumDepth):\n if violatesSymmetry(originalFunction, arg, argumentIndex):\n continue\n\n newFunction = Application(function, arg)\n for resultL, resultK, result in self.enumerateApplication(newContext, environment, newFunction,\n laterRequests,\n parent=parent,\n upperBound=upperBound + argL,\n lowerBound=lowerBound + argL,\n maximumDepth=maximumDepth,\n originalFunction=originalFunction,\n argumentIndex=argumentIndex + 1):\n yield resultL + argL, resultK, result\n \n \n\n\ndef violatesSymmetry(f, x, argumentIndex):\n if not f.isPrimitive:\n return False\n while x.isApplication:\n x = x.f\n if not x.isPrimitive:\n return False\n f = f.name\n x = x.name\n if f == \"car\":\n return x == \"cons\" or x == \"empty\"\n if f == \"cdr\":\n return x == \"cons\" or x == \"empty\"\n if f == \"+\":\n return x == \"0\" or (argumentIndex == 1 and x == \"+\")\n if f == \"-\":\n return argumentIndex == 1 and x == \"0\"\n if f == \"empty?\":\n return x == \"cons\" or x == \"empty\"\n if f == \"zero?\":\n return x == \"0\" or x == \"1\"\n if f == \"index\" or f == \"map\" or f == \"zip\":\n return x == \"empty\"\n if f == \"range\":\n return x == \"0\"\n if f == \"fold\":\n return argumentIndex == 1 and x == \"empty\"\n return False\n\ndef batchLikelihood(jobs):\n \"\"\"Takes as input a set of (program, request, grammar) and returns a dictionary mapping each of these to its likelihood under the grammar\"\"\"\n superGrammar = Grammar.uniform(list({p for _1,_2,g in jobs for p in g.primitives}),\n continuationType=list(jobs)[0][-1].continuationType)\n programsAndRequests = {(program, request)\n for program, request, grammar in jobs}\n with timing(f\"Calculated {len(programsAndRequests)} likelihood summaries\"):\n summary = {(program, request): superGrammar.closedLikelihoodSummary(request, program)\n for program, request in programsAndRequests}\n with timing(f\"Calculated log likelihoods from summaries\"):\n response = {}\n for program, request, grammar in jobs:\n fast = summary[(program, request)].logLikelihood_overlyGeneral(grammar)\n if False: # debugging\n slow = grammar.logLikelihood(request, program)\n print(program)\n eprint(grammar.closedLikelihoodSummary(request, program))\n eprint(superGrammar.closedLikelihoodSummary(request, program))\n print()\n assert abs(fast - slow) < 0.0001\n response[(program, request, grammar)] = fast\n return response\n\nclass PCFG():\n def __init__(self, productions, start_symbol, number_of_arguments):\n # productions: nonterminal -> [(log probability, constructor, [(#lambdas, nonterminal)])]\n self.number_of_arguments = number_of_arguments\n self.productions = productions\n self.start_symbol = start_symbol\n\n \n \n\n @staticmethod\n def from_grammar(g, request, maximum_type=3, maximum_environment=2):\n kinds = set()\n\n def process_type(t):\n if t.isArrow():\n process_type(t.arguments[0])\n process_type(t.arguments[1])\n elif isinstance(t, TypeVariable):\n return\n else:\n kinds.add((t.name, len(t.arguments)))\n for a in t.arguments:\n process_type(a)\n\n process_type(request)\n for _, t, _ in g.productions:\n process_type(t)\n\n\n def types_of_size(s):\n if s<=1:\n yield from { TypeConstructor(n, []) for n, a in kinds if a==0 }\n return \n\n for n, a in kinds:\n assert a<3\n if a==0: continue\n if a==1:\n yield from { TypeConstructor(n, [t]) for t in types_of_size(s-1) }\n if a==2:\n yield from { TypeConstructor(n, [t1, t2])\n for s1 in range(1, s)\n for s2 in range(1, s-s1)\n for t1 in types_of_size(s1)\n for t2 in types_of_size(s2) }\n\n def size_of_type(t):\n if isinstance(t, TypeVariable):\n return 0\n if t.isArrow():\n return max(size_of_type(t.arguments[0]),\n size_of_type(t.arguments[1]))\n return 1 + sum(size_of_type(a) for a in t.arguments)\n\n environment = tuple(reversed(request.functionArguments()))\n maximum_environment += len(environment)\n request = request.returns()\n possible_types = {t for s in range(1, maximum_type+1) for t in types_of_size(s)}|{request}\n\n _instantiations = {}\n def instantiations(t):\n if not t.isPolymorphic:\n return [t]\n\n if t in _instantiations:\n return _instantiations[t]\n \n t=t.canonical()\n variables = t.free_type_variables()\n \n return_value = []\n for substitution in itertools.product(possible_types, repeat=len(variables)):\n context = Context(substitution=list(zip(range(len(variables)), substitution)))\n new_type = t.apply(context)\n if size_of_type(new_type) <= maximum_type:\n return_value.append(new_type)\n _instantiations[t] = return_value\n return return_value\n\n # for _, t, p in g.productions:\n # print(p, t)\n # for i in instantiations(t):\n # print(\"\\t\", i)\n\n def push_environment(tp, e):\n if len(e)==0:\n return (tp,)\n else:\n return tuple([tp]+list(e))\n e=dict(e)\n if tp in e: e[tp]+=1\n else: e[tp]=1\n return frozendict(e)\n def push_multiple_environment(ts, e):\n for t in ts: e=push_environment(t, e)\n return e\n \n\n rules = {}\n def make_rules(request, environment):\n if (request, environment) in rules: return\n rules[(request, environment)] = []\n variable_candidates = [(g.logVariable, tp, Index(i))\n # for t, count in environment.items()\n # for i in range(count)\n for i, t in enumerate(environment) \n for tp in instantiations(t)\n if tp.returns()==request]\n if g.continuationType == request:\n variable_candidates = [min(variable_candidates, key=lambda vc: vc[-1].i)]\n variable_candidates = [(lp-math.log(len(variable_candidates)), t, p)\n for lp, t, p in variable_candidates ]\n \n for lp, t, p in g.productions + variable_candidates:\n for i in instantiations(t):\n if i.returns() == request:\n arguments = i.functionArguments()\n argument_symbols = []\n for a in arguments:\n new_environment = push_multiple_environment(a.functionArguments(),\n environment)\n argument_symbols.append((len(a.functionArguments()),\n (a.returns(), new_environment)))\n\n if all( len(new_environment) <= maximum_environment\n for _, (_, new_environment) in argument_symbols ):\n rules[(request, environment)].append((lp, p, argument_symbols))\n \n for _, p, argument_symbols in rules[(request, environment)]:\n for _, symbol in argument_symbols:\n make_rules(*symbol)\n\n start_environment = push_multiple_environment(environment, {})\n start_symbol = (request, start_environment)\n make_rules(*start_symbol)\n eprint(len(rules), \"nonterminal symbols\")\n eprint(sum(len(productions) for productions in rules.values()), \"production rules\")\n return PCFG(rules, start_symbol, len(start_environment)).normalize()\n\n def normalize(self):\n def norm(distribution):\n z = lse([x[0] for x in distribution])\n return [(x[0]-z, *x[1:]) for x in distribution]\n if isinstance(self.productions, list):\n self.productions = [ norm(rs) for rs in self.productions ]\n elif isinstance(self.productions, dict):\n self.productions = {k:norm(rs) for k, rs in self.productions.items()}\n else:\n assert False\n return self\n\n def __str__(self):\n return f\"start symbol: {self.start_symbol}\\n\\n%s\"%(\"\\n\\n\".join(\n \"\\n\".join(f\"{nt} ::= {k}\\t%s\\t\\t{l}\"%(\" \".join(f\"{n}x{s}\" for n, s in ar ))\n for l, k, ar in rs)\n for nt, rs in self.productions.items()))\n \n def number_rules(self):\n if isinstance(self.productions, list):\n return self\n \n mapping = dict(zip(self.productions.keys(), range(len(self.productions))))\n reverse_mapping = {v:k for k,v in mapping.items() }\n\n new_productions = [ [ (lp, k, [(nl, mapping[nt]) for nl, nt in arguments ])\n for lp, k, arguments in self.productions[reverse_mapping[i]] ]\n for i in range(len(self.productions)) ]\n\n return PCFG(new_productions, mapping[self.start_symbol], self.number_of_arguments)\n\n \n \n\n def json(self):\n self = self.number_rules()\n return {\"rules\": [ [ {\"probability\": lp, \n \"constructor\": str(k),\n \"arguments\": [ {\"n_lambda\": nl, \"nt\": nt}\n for nl, nt in arguments ]}\n for (lp, k, arguments) in rules ]\n for rules in self.productions ],\n \"number_of_arguments\": self.number_of_arguments,\n \"start_symbol\": self.start_symbol\n }\n\n def log_probability(self, program, symbol=None):\n\n if symbol is None:\n symbol = self.start_symbol\n\n while isinstance(program, Program) and program.isAbstraction:\n program = program.body\n\n if isinstance(program, NamedHole):\n program = program.name\n \n if not isinstance(program, Program):\n # assume it is a nonterminal\n assert isinstance(program, int) and 0<=program<len(self.productions) or \\\n program in self.productions, f\"failure to type production: {program}:{symbol}\"\n\n if program == symbol:\n return 0.\n else:\n return float(\"-inf\")\n \n \n \n\n rules = self.productions[symbol]\n\n \n f, xs = program.applicationParse()\n\n lp = float(\"-inf\")\n for p, k, arguments in rules:\n if f==k:\n _lp=p+sum(self.log_probability(a, at)\n for a, (_, at) in zip(xs, arguments) )\n lp = lse(lp, _lp)\n return lp\n\n def best_first_enumeration(self, partial=False):\n h=PQ()\n\n h.push(0., (0., NamedHole(self.start_symbol).wrap_in_abstractions(self.number_of_arguments)))\n\n def next_nonterminal(expression):\n if isinstance(expression, NamedHole):\n return expression.name\n \n if expression.isAbstraction:\n return next_nonterminal(expression.body)\n if expression.isApplication:\n f=next_nonterminal(expression.f)\n if f is None:\n return next_nonterminal(expression.x)\n return f\n return None\n\n def substitute(expression, value):\n if isinstance(expression, NamedHole):\n return value\n \n if expression.isAbstraction:\n body = substitute(expression.body, value)\n if body is None: return None\n return Abstraction(body)\n if expression.isApplication:\n f = substitute(expression.f, value)\n if f is None:\n x = substitute(expression.x, value)\n if x is None: return None\n return Application(expression.f, x)\n return Application(f, expression.x)\n return None\n\n \n\n while len(h)>0:\n lp, e = h.popMaximum()\n \n nt=next_nonterminal(e)\n \n if nt is None:\n yield e, lp\n else:\n for lpp, k, arguments in self.productions[nt]:\n rewrite = k\n for nl, at in arguments:\n at = NamedHole(at).wrap_in_abstractions(nl)\n rewrite = Application(rewrite, at)\n #eprint(e, \">>\", substitute(e, rewrite))\n ep = substitute(e, rewrite)\n h.push(lp+lpp, (lp+lpp, ep))\n if partial:\n yield ep, lp+lpp\n\n def split(self, nc):\n \n \n def expansions(expression):\n if isinstance(expression, NamedHole):\n for _, k, arguments in self.productions[expression.name]:\n arguments = [NamedHole(at).wrap_in_abstractions(nl)\n for nl, at in arguments ]\n for a in arguments:\n k = Application(k, a)\n yield k\n \n if expression.isAbstraction:\n for b in expansions(expression.body):\n yield Abstraction(b)\n \n if expression.isApplication:\n \n for f in expansions(expression.f):\n yield Application(f, expression.x)\n for x in expansions(expression.x):\n yield Application(expression.f, x)\n\n initial_split = [NamedHole(self.start_symbol).wrap_in_abstractions(self.number_of_arguments)]\n while len(initial_split) < nc:\n biggest=max(initial_split, key=lambda pp: self.log_probability(pp))\n initial_split = list(expansions(biggest)) + [pp for pp in initial_split if pp!=biggest]\n\n split = [[] for _ in range(nc) ]\n for i, pp in enumerate(initial_split):\n split[i%nc].append(pp)\n\n return split\n\n \n # def quality(s):\n # mass = [ lse([self.log_probability(pp) for pp in pps ])\n # for pps in s ]\n # eprint(mass)\n # return exp(min(mass)-max(mass))\n\n # def find_swap(s):\n # i = max(range(s), key=lambda i: lse([self.log_probability(pp) for pp in s[i] ]))\n \n # eprint(quality(split))\n # import pdb; pdb.set_trace()\n \n\n \n\n \n\n def quantized_enumeration(self, resolution=0.5, skeletons=None): \n self = self.number_rules()\n\n if skeletons is None:\n skeletons = [NamedHole(self.start_symbol).wrap_in_abstractions(self.number_of_arguments)]\n skeletons = [pp for pps in self.split(10) for pp in pps ]\n eprint(skeletons)\n skeleton_costs=[int(-self.log_probability(pp)/resolution+0.5)\n for pp in skeletons ]\n\n # replace probabilities with quantized costs \n productions = [[ (max(int(-lp/resolution+0.5), 1), k, arguments)\n for lp, k, arguments in right_hand_sides ]\n for right_hand_sides in self.productions]\n \n nonterminals = len(productions)\n\n expressions = [ [None for _ in range(int(100/resolution))]\n for _ in range(nonterminals) ]\n\n def expressions_of_size(symbol, size):\n nonlocal expressions\n \n \n if size <= 0:\n return []\n \n if expressions[symbol][size] is None:\n new=[]\n for cost, k, arguments in productions[symbol]:\n if cost>size: continue\n \n if len(arguments) == 0:\n if cost==size:\n new.append(k)\n elif len(arguments) == 1:\n nl1, at1 = arguments[0]\n for a1 in expressions_of_size(at1, size-cost):\n a1 = a1.wrap_in_abstractions(nl1)\n new.append(Application(k, a1))\n elif len(arguments) == 2:\n nl1, at1 = arguments[0]\n nl2, at2 = arguments[1]\n for c1 in range(size-cost):\n for a1 in expressions_of_size(at1, c1):\n a1 = a1.wrap_in_abstractions(nl1)\n for a2 in expressions_of_size(at2, size-cost-c1):\n a2 = a2.wrap_in_abstractions(nl2)\n new.append(Application(Application(k, a1), a2))\n elif len(arguments) == 3:\n nl1, at1 = arguments[0]\n nl2, at2 = arguments[1]\n nl3, at3 = arguments[2]\n for c1 in range(size-cost):\n for a1 in expressions_of_size(at1, c1):\n a1 = a1.wrap_in_abstractions(nl1)\n for c2 in range(size-cost-c1):\n for a2 in expressions_of_size(at2, c2):\n a2 = a2.wrap_in_abstractions(nl2)\n for a3 in expressions_of_size(at3, size-cost-c1-c2):\n a3 = a3.wrap_in_abstractions(nl3)\n new.append(Application(Application(Application(k, a1), a2), a3))\n elif len(arguments) == 4:\n nl1, at1 = arguments[0]\n nl2, at2 = arguments[1]\n nl3, at3 = arguments[2]\n nl4, at4 = arguments[3]\n for c1 in range(size-cost):\n for a1 in expressions_of_size(at1, c1):\n a1 = a1.wrap_in_abstractions(nl1)\n for c2 in range(size-cost-c1):\n for a2 in expressions_of_size(at2, c2):\n a2 = a2.wrap_in_abstractions(nl2)\n for c3 in range(size-cost-c1-c2):\n for a3 in expressions_of_size(at3, c3):\n a3 = a3.wrap_in_abstractions(nl3)\n for a4 in expressions_of_size(at3, size-cost-c1-c2-c3):\n a4 = a4.wrap_in_abstractions(nl4)\n new.append(Application(Application(Application(Application(k, a1), a2), a3), a4))\n elif len(arguments) == 5:\n nl1, at1 = arguments[0]\n nl2, at2 = arguments[1]\n nl3, at3 = arguments[2]\n nl4, at4 = arguments[3]\n nl5, at5 = arguments[4]\n for c1 in range(size-cost):\n for a1 in expressions_of_size(at1, c1):\n a1 = a1.wrap_in_abstractions(nl1)\n for c2 in range(size-cost-c1):\n for a2 in expressions_of_size(at2, c2):\n a2 = a2.wrap_in_abstractions(nl2)\n for c3 in range(size-cost-c1-c2):\n for a3 in expressions_of_size(at3, c3):\n a3 = a3.wrap_in_abstractions(nl3)\n for c4 in range(size-cost-c1-c2-c3):\n for a4 in expressions_of_size(at3, c4):\n a4 = a4.wrap_in_abstractions(nl4)\n for a5 in expressions_of_size(at3, size-cost-c1-c2-c3-c4):\n a5 = a4.wrap_in_abstractions(nl5)\n new.append(Application(Application(Application(Application(Application(k, a1), a2), a3), a4), a5))\n else:\n assert False, \"more than five arguments not supported for the enumeration algorithm but that is not for any good reason\"\n expressions[symbol][size] = new\n \n return expressions[symbol][size]\n\n def complete_skeleton(cost, skeleton):\n if skeleton.isAbstraction:\n for b in complete_skeleton(cost, skeleton.body):\n yield Abstraction(b)\n elif skeleton.isApplication:\n for function_cost in range(cost+1):\n for f in complete_skeleton(function_cost, skeleton.f):\n for x in complete_skeleton(cost-function_cost, skeleton.x):\n yield Application(f, x)\n elif skeleton.isNamedHole:\n yield from expressions_of_size(skeleton.name, cost)\n else:\n if cost==0:\n yield skeleton\n\n \n \n\n expressions = [ [None for _ in range(int(100/resolution))]\n for _ in range(nonterminals) ]\n for cost in range(int(100/resolution)):\n for skeleton, skeleton_cost in zip(skeletons, skeleton_costs):\n for e in complete_skeleton(cost-skeleton_cost, skeleton): \n yield e\n\n \n\n \n"
] |
[
[
"numpy.array"
]
] |
r-b-g-b/spacy-ann-linker
|
[
"3a625052686fc745fa1508c238fc68a5c7f50053"
] |
[
"spacy_ann/ann_kb.py"
] |
[
"from pathlib import Path\nfrom timeit import default_timer as timer\nfrom typing import List, Set, Tuple\n\nimport joblib\nimport nmslib\nimport numpy as np\nimport scipy\nimport srsly\nfrom nmslib.dist import FloatIndex\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom spacy.kb import KnowledgeBase\nfrom spacy.util import ensure_path, from_disk, to_disk\nfrom spacy.vocab import Vocab\nfrom spacy_ann.types import AliasCandidate\nfrom wasabi import Printer\n\n\nclass AnnKnowledgeBase(KnowledgeBase):\n def __init__(\n self,\n vocab: Vocab,\n entity_vector_length: int = 64,\n k: int = 1,\n m_parameter: int = 100,\n ef_search: int = 200,\n ef_construction: int = 2000,\n n_threads: int = 60,\n ):\n \"\"\"Initialize a CandidateGenerator\n\n k (int): Number of neighbors to query\n m_parameter (int): M parameter value for nmslib hnsw algorithm\n ef_search (int): Set to the maximum recommended value.\n Improves recall at the expense of longer **inference** time\n ef_construction (int): Set to the maximum recommended value.\n Improves recall at the expense of longer **indexing** time\n n_threads (int): Number of threads to use when creating the index.\n Change based on your machine.\n \"\"\"\n super().__init__(vocab, entity_vector_length)\n self.k = k\n self.m_parameter = m_parameter\n self.ef_search = ef_search\n self.ef_construction = ef_construction\n self.n_threads = n_threads\n self.ann_index = None\n\n def _initialize(\n self,\n aliases: List[str],\n short_aliases: Set[str],\n ann_index: FloatIndex,\n vectorizer: TfidfVectorizer,\n alias_tfidfs: scipy.sparse.csr_matrix,\n ):\n \"\"\"Used in `fit` and `from_disk` to initialize the CandidateGenerator with computed\n # TF-IDF Vectorizer and ANN Index\n\n aliases (List[str]): Aliases with vectors contained in the ANN Index\n short_aliases (Set[str]): Aliases too short for a TF-IDF representation\n ann_index (FloatIndex): Computed ANN Index of TF-IDF representations for aliases\n vectorizer (TfidfVectorizer): TF-IDF Vectorizer to get vector representation of aliases\n alias_tfidfs (scipy.sparse.csr_matrix): Computed TF-IDF Sparse Vectors for aliases\n \"\"\"\n self.aliases = aliases\n self.short_aliases = short_aliases\n self.ann_index = ann_index\n self.vectorizer = vectorizer\n self.alias_tfidfs = alias_tfidfs\n\n def fit_index(self, verbose: bool = True):\n msg = Printer(no_print=verbose)\n\n kb_aliases = self.get_alias_strings()\n short_aliases = set([a for a in kb_aliases if len(a) < 4])\n\n # nmslib hyperparameters (very important)\n # guide: https://github.com/nmslib/nmslib/blob/master/python_bindings/parameters.md\n # m_parameter = 100\n # # `C` for Construction. Set to the maximum recommended value\n # # Improves recall at the expense of longer indexing time\n # construction = 2000\n # num_threads = 60 # set based on the machine\n index_params = {\n \"M\": self.m_parameter,\n \"indexThreadQty\": self.n_threads,\n \"efConstruction\": self.ef_construction,\n \"post\": 0,\n }\n\n # NOTE: here we are creating the tf-idf vectorizer with float32 type, but we can serialize the\n # resulting vectors using float16, meaning they take up half the memory on disk. Unfortunately\n # we can't use the float16 format to actually run the vectorizer, because of this bug in sparse\n # matrix representations in scipy: https://github.com/scipy/scipy/issues/7408\n\n msg.text(f\"Fitting tfidf vectorizer on {len(kb_aliases)} aliases\")\n tfidf_vectorizer = TfidfVectorizer(\n analyzer=\"char_wb\", ngram_range=(3, 3), min_df=2, dtype=np.float32\n )\n start_time = timer()\n alias_tfidfs = tfidf_vectorizer.fit_transform(kb_aliases)\n end_time = timer()\n total_time = end_time - start_time\n msg.text(f\"Fitting and saving vectorizer took {round(total_time)} seconds\")\n\n msg.text(f\"Finding empty (all zeros) tfidf vectors\")\n empty_tfidfs_boolean_flags = np.array(alias_tfidfs.sum(axis=1) != 0).reshape(\n -1,\n )\n number_of_non_empty_tfidfs = sum(\n empty_tfidfs_boolean_flags == False\n ) # pylint: disable=singleton-comparison\n total_number_of_tfidfs = np.size(alias_tfidfs, 0)\n\n msg.text(\n f\"Deleting {number_of_non_empty_tfidfs}/{total_number_of_tfidfs} aliases because their tfidf is empty\"\n )\n # remove empty tfidf vectors, otherwise nmslib will crash\n aliases = [\n alias for alias, flag in zip(kb_aliases, empty_tfidfs_boolean_flags) if flag\n ]\n alias_tfidfs = alias_tfidfs[empty_tfidfs_boolean_flags]\n assert len(aliases) == np.size(alias_tfidfs, 0)\n\n msg.text(f\"Fitting ann index on {len(aliases)} aliases\")\n start_time = timer()\n ann_index = nmslib.init(\n method=\"hnsw\",\n space=\"cosinesimil_sparse\",\n data_type=nmslib.DataType.SPARSE_VECTOR,\n )\n ann_index.addDataPointBatch(alias_tfidfs)\n ann_index.createIndex(index_params, print_progress=verbose)\n query_time_params = {\"efSearch\": self.ef_search}\n ann_index.setQueryTimeParams(query_time_params)\n end_time = timer()\n total_time = end_time - start_time\n msg.text(f\"Fitting ann index took {round(total_time)} seconds\")\n\n self._initialize(\n aliases, short_aliases, ann_index, tfidf_vectorizer, alias_tfidfs\n )\n return self\n\n def _nmslib_knn_with_zero_vectors(\n self, vectors: np.ndarray, k: int\n ) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"ann_index.knnQueryBatch crashes if any of the vectors is all zeros.\n This function is a wrapper around `ann_index.knnQueryBatch` that solves this problem. It works as follows:\n - remove empty vectors from `vectors`.\n - call `ann_index.knnQueryBatch` with the non-empty vectors only. This returns `neighbors`,\n a list of list of neighbors. `len(neighbors)` equals the length of the non-empty vectors.\n - extend the list `neighbors` with `None`s in place of empty vectors.\n - return the extended list of neighbors and distances.\n\n vectors (np.ndarray): Vectors used to query index for neighbors and distances\n k (int): k neighbors to consider\n\n RETURNS (Tuple[np.ndarray, np.ndarray]): Tuple of [neighbors, distances]\n \"\"\"\n\n empty_vectors_boolean_flags = np.array(vectors.sum(axis=1) != 0).reshape(-1,)\n empty_vectors_count = vectors.shape[0] - sum(empty_vectors_boolean_flags)\n\n # init extended_neighbors with a list of Nones\n extended_neighbors = np.empty((len(empty_vectors_boolean_flags),), dtype=object)\n extended_distances = np.empty((len(empty_vectors_boolean_flags),), dtype=object)\n\n if vectors.shape[0] - empty_vectors_count == 0:\n return extended_neighbors, extended_distances\n\n # remove empty vectors before calling `ann_index.knnQueryBatch`\n vectors = vectors[empty_vectors_boolean_flags]\n\n # call `knnQueryBatch` to get neighbors\n original_neighbours = self.ann_index.knnQueryBatch(vectors, k=k)\n\n neighbors, distances = zip(\n *[(x[0].tolist(), x[1].tolist()) for x in original_neighbours]\n )\n neighbors = list(neighbors)\n distances = list(distances)\n\n # neighbors need to be converted to an np.array of objects instead of ndarray of dimensions len(vectors)xk\n # Solution: add a row to `neighbors` with any length other than k. This way, calling np.array(neighbors)\n # returns an np.array of objects\n neighbors.append([])\n distances.append([])\n # interleave `neighbors` and Nones in `extended_neighbors`\n extended_neighbors[empty_vectors_boolean_flags] = np.array(neighbors, dtype=object)[:-1]\n extended_distances[empty_vectors_boolean_flags] = np.array(distances, dtype=object)[:-1]\n\n return extended_neighbors, extended_distances\n\n def require_ann_index(self):\n \"\"\"Raise an error if the ann_index is not initialized\n\n RAISES:\n ValueError: ann_index not initialized\n \"\"\"\n if self.ann_index is None:\n raise ValueError(f\"ann_index not initialized. Have you run `cg.train` yet?\")\n\n def get_alias_candidates(self, mention_texts: List[str]):\n self.require_ann_index()\n\n tfidfs = self.vectorizer.transform(mention_texts)\n start_time = timer()\n\n # `ann_index.knnQueryBatch` crashes if one of the vectors is all zeros.\n # `nmslib_knn_with_zero_vectors` is a wrapper around `ann_index.knnQueryBatch`\n # that addresses this issue.\n batch_neighbors, batch_distances = self._nmslib_knn_with_zero_vectors(\n tfidfs, self.k\n )\n end_time = timer()\n end_time - start_time\n\n batch_candidates = []\n for mention, neighbors, distances in zip(\n mention_texts, batch_neighbors, batch_distances\n ):\n if mention in self.short_aliases:\n batch_candidates.append([AliasCandidate(alias=mention, similarity=1.0)])\n continue\n if neighbors is None:\n neighbors = []\n if distances is None:\n distances = []\n\n alias_candidates = []\n for neighbor_index, distance in zip(neighbors, distances):\n alias = self.aliases[neighbor_index]\n similarity = 1.0 - distance\n alias_candidates.append(\n AliasCandidate(alias=alias, similarity=similarity)\n )\n\n batch_candidates.append(alias_candidates)\n\n return batch_candidates\n\n def get_candidates(self, alias: str):\n \"\"\"\n Return candidate entities for an alias. Each candidate defines the entity, the original alias,\n and the prior probability of that alias resolving to that entity.\n If the alias is not known in the KB, and empty list is returned.\n \"\"\"\n if self.contains_alias(alias):\n candidates = super().get_candidates(alias)\n else:\n alias_candidates = self.get_alias_candidates([alias])[0]\n if alias_candidates:\n nearest_alias = alias_candidates[0].alias\n candidates = self.get_candidates(nearest_alias)\n else:\n candidates = []\n return candidates\n\n def dump(self, path: Path):\n path = ensure_path(path)\n\n super().dump(str(path / \"kb\"))\n\n cfg = {\n \"k\": self.k,\n \"m_parameter\": self.m_parameter,\n \"ef_search\": self.ef_search,\n \"ef_construction\": self.ef_construction,\n \"n_threads\": self.n_threads,\n }\n\n cg_cfg_path = path / \"cg_cfg\"\n aliases_path = path / \"aliases.json\"\n short_aliases_path = path / \"short_aliases.json\"\n ann_index_path = path / \"ann_index.bin\"\n tfidf_vectorizer_path = path / \"tfidf_vectorizer.joblib\"\n tfidf_vectors_path = path / \"tfidf_vectors_sparse.npz\"\n\n srsly.write_json(cg_cfg_path, cfg)\n srsly.write_json(aliases_path, self.aliases)\n srsly.write_json(short_aliases_path, list(self.short_aliases))\n\n self.ann_index.saveIndex(str(ann_index_path))\n joblib.dump(self.vectorizer, tfidf_vectorizer_path)\n scipy.sparse.save_npz(tfidf_vectors_path, self.alias_tfidfs.astype(np.float16))\n\n def load_bulk(self, path: Path):\n path = ensure_path(path)\n\n super().load_bulk(str(path / \"kb\"))\n\n aliases_path = path / \"aliases.json\"\n short_aliases_path = path / \"short_aliases.json\"\n ann_index_path = path / \"ann_index.bin\"\n tfidf_vectorizer_path = path / \"tfidf_vectorizer.joblib\"\n tfidf_vectors_path = path / \"tfidf_vectors_sparse.npz\"\n\n cfg = srsly.read_json(path / \"cg_cfg\")\n\n self.k = cfg.get(\"k\", 5)\n self.m_parameter = cfg.get(\"m_parameter\", 100)\n self.ef_search = cfg.get(\"ef_search\", 200)\n self.ef_construction = cfg.get(\"ef_construction\", 2000)\n self.n_threads = cfg.get(\"n_threads\", 60)\n\n aliases = srsly.read_json(aliases_path)\n short_aliases = set(srsly.read_json(short_aliases_path))\n tfidf_vectorizer = joblib.load(tfidf_vectorizer_path)\n alias_tfidfs = scipy.sparse.load_npz(tfidf_vectors_path).astype(np.float32)\n ann_index = nmslib.init(\n method=\"hnsw\",\n space=\"cosinesimil_sparse\",\n data_type=nmslib.DataType.SPARSE_VECTOR,\n )\n ann_index.addDataPointBatch(alias_tfidfs)\n ann_index.loadIndex(str(ann_index_path))\n query_time_params = {\"efSearch\": self.ef_search}\n ann_index.setQueryTimeParams(query_time_params)\n\n self._initialize(\n aliases, short_aliases, ann_index, tfidf_vectorizer, alias_tfidfs\n )\n\n return self\n"
] |
[
[
"scipy.sparse.load_npz",
"numpy.size",
"numpy.array",
"sklearn.feature_extraction.text.TfidfVectorizer"
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.