repo_name
stringlengths
6
130
hexsha
list
file_path
list
code
list
apis
list
possible_versions
list
Randal1936/FinancialSupervision
[ "3d78b1cc662a2c0675ace880a772cc38eaf7672f" ]
[ "tools/PolicyAnalysis/Businesses.py" ]
[ "import pandas as pd\nimport numpy as np\nimport xlwings as xw\nfrom PolicyAnalysis import cptj as cj\n\n\"\"\"\n————————————————————\n以下是使用 re 检索+ DFC 映射的数据处理写法\n————————————————————\n\"\"\"\n\nclass businesses_re:\n\n def __init__(self, Data, userdict):\n self.Data = Data\n self.userdict = userdict\n\n data = Data.copy()\n # 先获取关键词字典\n n = cj.txt_to_list(self.userdict)\n\n # 把被监管的业务分类,做成字典映射\n # 首先生成一个列表,标记一下关键词所在的位置\n loc = [(0, 4), (4, 10), (10, 15), (15, 19), (19, 22), (22, 26), (26, 29), (29, 31), (31, 40),\n (40, 41), (41, 42), (42, 43), (43, 44), (44, 45)]\n\n # 然后遍历列表,按照标记的位置生成关键词切片,把同类的关键词映射到相同的数值\n i = 0\n keymap = {}\n for rank in loc:\n lst = n[rank[0]: rank[1]]\n for item in lst:\n keymap[item] = i\n i += 1\n\n # 情况一,对全部正文进行检索\n result1 = cj.words_docs_freq(n, data)\n dfc1 = result1['DFC']\n dtm1_class = result1['DTM']\n dtm1_final = cj.dfc_sort_filter(dfc1, keymap, '被监管业务-正文分类统计.xlsx')\n\n # 情况二,对正文前十句话进行检索\n # 造一个正文栏只包括正文前十句话的样本矩阵\n tf = data\n for i in range(0, data.shape[0]):\n tf.iloc[i, 2] = cj.top_n_sent(10, data.iloc[i, 2])\n\n result2 = cj.words_docs_freq(n, tf)\n dfc2 = result2['DFC']\n dtm2_class = result2['DTM']\n dtm2_final = cj.dfc_sort_filter(dfc2, keymap, '被监管业务-前十句话分类统计.xlsx')\n\n # 情况三,仅对标题进行检索\n # 首先把样本弄成一样的格式\n # 建议用这种赋值+循环 iloc 赋值来新建样本\n # 否则会报乱七八糟的错:不能用 slice 来更改原 DataFrame 值啊 blablabla\n tf3 = data\n for i in range(0, data.shape[0]):\n tf3.iloc[i, 2] = data.iloc[i, 1]\n # 生成词频统计结果\n result3 = cj.words_docs_freq(n, tf3)\n dfc3 = result3['DFC']\n dtm3_class = result3['DTM']\n dtm3_final = cj.dfc_sort_filter(dfc3, keymap, '被监管业务-标题分类统计.xlsx')\n\n dtm_final = pd.concat([dtm1_final, dtm2_final, dtm3_final], axis=1)\n dtm_final.columns = ['被监管业务数(正文)', '被监管业务数(前十句)', '被监管业务数(标题)']\n\n dtm_aver_class = dtm_final.agg(np.mean, axis=1)\n dtm_aver_class = pd.DataFrame(dtm_aver_class, columns=['被监管业务数'])\n\n self.DTM_aver = dtm_aver_class # DTM 1、2、3 被监管业务数求均值\n self.DTM_final = dtm_final # DTM 1、2、3 被监管业务种类数汇总\n self.DTM1_class = dtm1_class # 按正文检索得到的 Doc-Term Matrix\n self.DTM2_class = dtm2_class # 按前十句话检索的 Doc-Term Matrix\n self.DTM3_class = dtm3_class # 按标题检索得到的 Doc-Term Matrix\n\n\n\"\"\"\n——————————————————————\n以下是使用 jieba 检索+ DTM 映射的数据处理写法\n——————————————————————\n\"\"\"\n\nclass business_jieba:\n\n def __init__(self, Data, userdict, indifile, indisheet, stopwords):\n self.Data = Data\n self.userdict = userdict\n self.indifile = indifile\n self.indisheet = indisheet\n self.stopwords = stopwords\n\n data = Data.copy()\n\n # 导入指标文件\n app = xw.App(visible=False, add_book=False)\n app.screen_updating = False\n app.display_alerts = False\n try:\n wb = app.books.open(self.indifile)\n sht = wb.sheets[self.indisheet]\n df_indi = sht.used_range.value\n df_indi = pd.DataFrame(df_indi)\n df_indi.columns = df_indi.loc[0]\n df_indi.drop(0, axis=0, inplace=True)\n df_indi.dropna(axis=0, how='all', inplace=True)\n finally:\n app.quit()\n\n # 生成 Business 分类字典, {'Institution': [keyword1, keyword2, keyword3, ....], ....}\n keymap = {}\n for i in range(df_indi.shape[1]):\n keymap[df_indi.columns[i]] = list(df_indi.iloc[:, i].dropna(''))\n\n # 情况一,对全部正文进行检索\n dtm1 = cj.jieba_vectorizer(data, self.userdict, self.stopwords).DTM\n dtm1_result = cj.dtm_sort_filter(dtm1, keymap, '被监管业务-正文分类统计.xlsx')\n dtm1_class = dtm1_result['DTM_class']\n dtm1_final = dtm1_result['DTM_final']\n\n # 情况二,对正文前十句话进行检索\n # 造一个正文栏只包括正文前十句话的样本矩阵\n tf = data.copy()\n for i in range(0, data.shape[0]):\n tf.iloc[i, 2] = cj.top_n_sent(10, data.iloc[i, 2])\n\n dtm2 = cj.jieba_vectorizer(tf, self.userdict, self.stopwords).DTM\n dtm2_result = cj.dtm_sort_filter(dtm2, keymap, '被监管业务-前十句话分类统计.xlsx')\n dtm2_class = dtm2_result['DTM_class']\n dtm2_final = dtm2_result['DTM_final']\n\n # 情况三,仅对标题进行检索\n # 首先把样本弄成一样的格式\n # 建议用这种赋值+循环 iloc 赋值来新建样本\n # 否则会报乱七八糟的错:不能用 slice 来更改原 DataFrame 值啊 blablabla\n tf3 = data.copy()\n for i in range(0, data.shape[0]):\n tf3.iloc[i, 2] = data.iloc[i, 1]\n # 生成词频统计结果\n\n dtm3 = cj.jieba_vectorizer(tf3, self.userdict, self.stopwords).DTM\n dtm3_result = cj.dtm_sort_filter(dtm3, keymap)\n dtm3_class = dtm3_result['DTM_class']\n dtm3_final = dtm3_result['DTM_final']\n\n dtm_final = pd.concat([dtm1_final, dtm2_final, dtm3_final], axis=1)\n dtm_final.columns = ['被监管业务数(正文)', '被监管业务数(前十句)', '被监管业务数(标题)']\n\n dtm_aver_class = dtm_final.agg(np.mean, axis=1)\n dtm_aver_class = pd.DataFrame(dtm_aver_class, columns=['被监管业务种类数'])\n\n self.DTM_aver = dtm_aver_class # DTM 1、2、3 被监管业务数求均值\n self.DTM_final = dtm_final # DTM 1、2、3 被监管业务种类数汇总\n self.DTM1_class = dtm1_class # 按正文检索得到的 Doc-Term Matrix\n self.DTM2_class = dtm2_class # 按前十句话检索的 Doc-Term Matrix\n self.DTM3_class = dtm3_class # 按标题检索得到的 Doc-Term Matrix\n" ]
[ [ "pandas.concat", "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.3", "0.19", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] } ]
simbilod/gdsfactory
[ "4d76db32674c3edb4d16260e3177ee29ef9ce11d", "4d76db32674c3edb4d16260e3177ee29ef9ce11d" ]
[ "gdsfactory/simulation/simphony/components/ring_double_siepic.py", "gdsfactory/simulation/modes/tests/test_find_modes_dispersion.py" ]
[ "from simphony.library import siepic\nfrom simphony.netlist import Subcircuit\n\n\ndef ring_double_siepic(\n wg_width=0.5,\n gap=0.2,\n length_x=4,\n bend_radius=5,\n length_y=2,\n coupler=siepic.ebeam_dc_halfring_straight,\n straight=siepic.ebeam_wg_integral_1550,\n terminator=siepic.ebeam_terminator_te1550,\n):\n r\"\"\"Return double bus ring made of two couplers (ct: top, cb: bottom).\n\n connected with two vertical straights (wyl: left, wyr: right)\n\n .. code::\n\n --==ct==--\n | |\n wl wr length_y\n | |\n --==cb==-- gap\n\n length_x\n\n\n drop n1 _ _ n3 cdrop\n \\______/\n ______\n in n2 _/ \\_n4\n | |\n n1 | | n3\n \\______/\n ______\n in n2 _/ \\_n4 output\n\n\n \"\"\"\n straight = straight() if callable(straight) else straight\n coupler = coupler() if callable(coupler) else coupler\n\n # Create the circuit, add all individual instances\n circuit = Subcircuit(\"mzi\")\n circuit.add([(coupler, \"ct\"), (coupler, \"cb\"), (straight, \"wl\"), (straight, \"wr\")])\n\n # Circuits can be connected using the elements' string names:\n circuit.connect_many(\n [\n (\"cb\", \"n1\", \"wl\", \"n1\"),\n (\"wl\", \"n2\", \"ct\", \"n2\"),\n (\"ct\", \"n4\", \"wr\", \"n1\"),\n (\"wr\", \"n2\", \"cb\", \"n3\"),\n ]\n )\n circuit.elements[\"cb\"].pins[\"n2\"] = \"input\"\n circuit.elements[\"cb\"].pins[\"n4\"] = \"output\"\n circuit.elements[\"ct\"].pins[\"n1\"] = \"drop\"\n circuit.elements[\"ct\"].pins[\"n3\"] = \"cdrop\"\n return circuit\n\n\nif __name__ == \"__main__\":\n import matplotlib.pyplot as plt\n\n from gdsfactory.simulationsimphony import plot_circuit\n\n c = ring_double_siepic()\n plot_circuit(c)\n plt.show()\n", "import numpy as np\n\nfrom gdsfactory.simulation.modes.find_mode_dispersion import find_mode_dispersion\n\n\ndef test_find_modes_waveguide_dispersion() -> None:\n modes = find_mode_dispersion(wg_width=0.45, resolution=20, cache=None)\n m1 = modes\n\n # print(f\"neff1 = {m1.neff}\")\n # print(f\"ng1 = {m1.ng}\")\n\n # neff1 = 2.3948\n # ng1 = 4.23194\n\n neff1 = 2.362907833437435\n ng1 = 4.202169359808116\n\n assert np.isclose(m1.neff, neff1), (m1.neff, neff1)\n assert np.isclose(m1.ng, ng1), (m1.ng, ng1)\n\n\nif __name__ == \"__main__\":\n test_find_modes_waveguide_dispersion()\n" ]
[ [ "matplotlib.pyplot.show" ], [ "numpy.isclose" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
layumi/dgcnn
[ "a7b58796ffe549f2d8bdb06a84f62aba03e1d3a1" ]
[ "pytorch/data.py" ]
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n@Author: Yue Wang\n@Contact: [email protected]\n@File: data.py\n@Time: 2018/10/13 6:21 PM\n\nModified by \n@Author: An Tao\n@Contact: [email protected]\n@Time: 2020/2/27 9:32 PM\n\"\"\"\n\n\nimport os\nimport sys\nimport glob\nimport h5py\nimport numpy as np\nimport torch\nfrom torch.utils.data import Dataset\n\n\ndef download_modelnet40():\n BASE_DIR = os.path.dirname(os.path.abspath(__file__))\n DATA_DIR = os.path.join(BASE_DIR, 'data')\n if not os.path.exists(DATA_DIR):\n os.mkdir(DATA_DIR)\n if not os.path.exists(os.path.join(DATA_DIR, 'modelnet40_ply_hdf5_2048')):\n www = 'https://shapenet.cs.stanford.edu/media/modelnet40_ply_hdf5_2048.zip'\n zipfile = os.path.basename(www)\n os.system('wget %s; unzip %s' % (www, zipfile))\n os.system('mv %s %s' % (zipfile[:-4], DATA_DIR))\n os.system('rm %s' % (zipfile))\n\n\ndef download_shapenetpart():\n BASE_DIR = os.path.dirname(os.path.abspath(__file__))\n DATA_DIR = os.path.join(BASE_DIR, 'data')\n if not os.path.exists(DATA_DIR):\n os.mkdir(DATA_DIR)\n if not os.path.exists(os.path.join(DATA_DIR, 'shapenet_part_seg_hdf5_data')):\n www = 'https://shapenet.cs.stanford.edu/media/shapenet_part_seg_hdf5_data.zip'\n zipfile = os.path.basename(www)\n os.system('wget %s --no-check-certificate; unzip %s' % (www, zipfile))\n os.system('mv %s %s' % (zipfile[:-4], os.path.join(DATA_DIR, 'shapenet_part_seg_hdf5_data')))\n os.system('rm %s' % (zipfile))\n\n\ndef download_S3DIS():\n BASE_DIR = os.path.dirname(os.path.abspath(__file__))\n DATA_DIR = os.path.join(BASE_DIR, 'data')\n if not os.path.exists(DATA_DIR):\n os.mkdir(DATA_DIR)\n if not os.path.exists(os.path.join(DATA_DIR, 'indoor3d_sem_seg_hdf5_data')):\n www = 'https://shapenet.cs.stanford.edu/media/indoor3d_sem_seg_hdf5_data.zip'\n zipfile = os.path.basename(www)\n os.system('wget --no-check-certificate %s; unzip %s' % (www, zipfile))\n os.system('mv %s %s' % (zipfile[:-4], DATA_DIR))\n os.system('rm %s' % (zipfile))\n if not os.path.exists(os.path.join(DATA_DIR, 'Stanford3dDataset_v1.2_Aligned_Version')):\n if not os.path.exists(os.path.join(DATA_DIR, 'Stanford3dDataset_v1.2_Aligned_Version.zip')):\n print('Please download Stanford3dDataset_v1.2_Aligned_Version.zip \\\n from https://goo.gl/forms/4SoGp4KtH1jfRqEj2 and place it under data/')\n sys.exit(0)\n else:\n zippath = os.path.join(DATA_DIR, 'Stanford3dDataset_v1.2_Aligned_Version.zip')\n os.system('unzip %s' % (zippath))\n os.system('rm %s' % (zippath))\n\n\ndef load_data_cls(partition):\n download_modelnet40()\n BASE_DIR = os.path.dirname(os.path.abspath(__file__))\n DATA_DIR = os.path.join(BASE_DIR, 'data')\n all_data = []\n all_label = []\n for h5_name in glob.glob(os.path.join(DATA_DIR, 'modelnet40*hdf5_2048', '*%s*.h5'%partition)):\n f = h5py.File(h5_name, 'r+')\n data = f['data'][:].astype('float32')\n label = f['label'][:].astype('int64')\n f.close()\n all_data.append(data)\n all_label.append(label)\n all_data = np.concatenate(all_data, axis=0)\n all_label = np.concatenate(all_label, axis=0)\n return all_data, all_label\n\n\ndef load_data_partseg(partition):\n download_shapenetpart()\n BASE_DIR = os.path.dirname(os.path.abspath(__file__))\n DATA_DIR = os.path.join(BASE_DIR, 'data')\n all_data = []\n all_label = []\n all_seg = []\n if partition == 'trainval':\n file = glob.glob(os.path.join(DATA_DIR, 'shapenet*hdf5*', '*train*.h5')) \\\n + glob.glob(os.path.join(DATA_DIR, 'shapenet*hdf5*', '*val*.h5'))\n else:\n file = glob.glob(os.path.join(DATA_DIR, 'shapenet*hdf5*', '*%s*.h5'%partition))\n for h5_name in file:\n f = h5py.File(h5_name, 'r+')\n data = f['data'][:].astype('float32')\n label = f['label'][:].astype('int64')\n seg = f['pid'][:].astype('int64')\n f.close()\n all_data.append(data)\n all_label.append(label)\n all_seg.append(seg)\n all_data = np.concatenate(all_data, axis=0)\n all_label = np.concatenate(all_label, axis=0)\n all_seg = np.concatenate(all_seg, axis=0)\n return all_data, all_label, all_seg\n\n\ndef prepare_test_data_semseg():\n BASE_DIR = os.path.dirname(os.path.abspath(__file__))\n DATA_DIR = os.path.join(BASE_DIR, 'data')\n if not os.path.exists(os.path.join(DATA_DIR, 'stanford_indoor3d')):\n os.system('python prepare_data/collect_indoor3d_data.py')\n if not os.path.exists(os.path.join(DATA_DIR, 'indoor3d_sem_seg_hdf5_data_test')):\n os.system('python prepare_data/gen_indoor3d_h5.py')\n\n\ndef load_data_semseg(partition, test_area):\n BASE_DIR = os.path.dirname(os.path.abspath(__file__))\n DATA_DIR = os.path.join(BASE_DIR, 'data')\n download_S3DIS()\n prepare_test_data_semseg()\n if partition == 'train':\n data_dir = os.path.join(DATA_DIR, 'indoor3d_sem_seg_hdf5_data')\n else:\n data_dir = os.path.join(DATA_DIR, 'indoor3d_sem_seg_hdf5_data_test')\n with open(os.path.join(data_dir, \"all_files.txt\")) as f:\n all_files = [line.rstrip() for line in f]\n with open(os.path.join(data_dir, \"room_filelist.txt\")) as f:\n room_filelist = [line.rstrip() for line in f]\n data_batchlist, label_batchlist = [], []\n for f in all_files:\n file = h5py.File(os.path.join(DATA_DIR, f), 'r+')\n data = file[\"data\"][:]\n label = file[\"label\"][:]\n data_batchlist.append(data)\n label_batchlist.append(label)\n data_batches = np.concatenate(data_batchlist, 0)\n seg_batches = np.concatenate(label_batchlist, 0)\n test_area_name = \"Area_\" + test_area\n train_idxs, test_idxs = [], []\n for i, room_name in enumerate(room_filelist):\n if test_area_name in room_name:\n test_idxs.append(i)\n else:\n train_idxs.append(i)\n if partition == 'train':\n all_data = data_batches[train_idxs, ...]\n all_seg = seg_batches[train_idxs, ...]\n else:\n all_data = data_batches[test_idxs, ...]\n all_seg = seg_batches[test_idxs, ...]\n return all_data, all_seg\n\n\ndef translate_pointcloud(pointcloud):\n xyz1 = np.random.uniform(low=2./3., high=3./2., size=[3])\n xyz2 = np.random.uniform(low=-0.2, high=0.2, size=[3])\n \n translated_pointcloud = np.add(np.multiply(pointcloud, xyz1), xyz2).astype('float32')\n return translated_pointcloud\n\n\ndef jitter_pointcloud(pointcloud, sigma=0.01, clip=0.02):\n N, C = pointcloud.shape\n pointcloud += np.clip(sigma * np.random.randn(N, C), -1*clip, clip)\n return pointcloud\n\n\ndef rotate_pointcloud(pointcloud):\n theta = np.pi*2 * np.random.uniform()\n rotation_matrix = np.array([[np.cos(theta), -np.sin(theta)],[np.sin(theta), np.cos(theta)]])\n pointcloud[:,[0,2]] = pointcloud[:,[0,2]].dot(rotation_matrix) # random rotation (x,z)\n return pointcloud\n\n\nclass ModelNet40(Dataset):\n def __init__(self, num_points, partition='train'):\n self.data, self.label = load_data_cls(partition)\n self.num_points = num_points\n self.partition = partition \n\n def __getitem__(self, item):\n pointcloud = self.data[item][:self.num_points]\n label = self.label[item]\n if self.partition == 'train':\n pointcloud = translate_pointcloud(pointcloud)\n np.random.shuffle(pointcloud)\n return pointcloud, label\n\n def __len__(self):\n return self.data.shape[0]\n\n\nclass ShapeNetPart(Dataset):\n def __init__(self, num_points, partition='train', class_choice=None):\n self.data, self.label, self.seg = load_data_partseg(partition)\n self.cat2id = {'airplane': 0, 'bag': 1, 'cap': 2, 'car': 3, 'chair': 4, \n 'earphone': 5, 'guitar': 6, 'knife': 7, 'lamp': 8, 'laptop': 9, \n 'motor': 10, 'mug': 11, 'pistol': 12, 'rocket': 13, 'skateboard': 14, 'table': 15}\n self.seg_num = [4, 2, 2, 4, 4, 3, 3, 2, 4, 2, 6, 2, 3, 3, 3, 3]\n self.index_start = [0, 4, 6, 8, 12, 16, 19, 22, 24, 28, 30, 36, 38, 41, 44, 47]\n self.num_points = num_points\n self.partition = partition \n self.class_choice = class_choice\n\n if self.class_choice != None:\n id_choice = self.cat2id[self.class_choice]\n indices = (self.label == id_choice).squeeze()\n self.data = self.data[indices]\n self.label = self.label[indices]\n self.seg = self.seg[indices]\n self.seg_num_all = self.seg_num[id_choice]\n self.seg_start_index = self.index_start[id_choice]\n else:\n self.seg_num_all = 50\n self.seg_start_index = 0\n\n def __getitem__(self, item):\n pointcloud = self.data[item][:self.num_points]\n label = self.label[item]\n seg = self.seg[item][:self.num_points]\n if self.partition == 'trainval':\n # pointcloud = translate_pointcloud(pointcloud)\n indices = list(range(pointcloud.shape[0]))\n np.random.shuffle(indices)\n pointcloud = pointcloud[indices]\n seg = seg[indices]\n return pointcloud, label, seg\n\n def __len__(self):\n return self.data.shape[0]\n\n\nclass S3DIS(Dataset):\n def __init__(self, num_points=4096, partition='train', test_area='1'):\n self.data, self.seg = load_data_semseg(partition, test_area)\n self.num_points = num_points\n self.partition = partition \n\n def __getitem__(self, item):\n pointcloud = self.data[item][:self.num_points]\n seg = self.seg[item][:self.num_points]\n if self.partition == 'train':\n indices = list(range(pointcloud.shape[0]))\n np.random.shuffle(indices)\n pointcloud = pointcloud[indices]\n seg = seg[indices]\n seg = torch.LongTensor(seg)\n return pointcloud, seg\n\n def __len__(self):\n return self.data.shape[0]\n\n\nif __name__ == '__main__':\n train = ModelNet40(1024)\n test = ModelNet40(1024, 'test')\n data, label = train[0]\n print(data.shape)\n print(label.shape)\n\n trainval = ShapeNetPart(2048, 'trainval')\n test = ShapeNetPart(2048, 'test')\n data, label, seg = trainval[0]\n print(data.shape)\n print(label.shape)\n print(seg.shape)\n\n train = S3DIS(4096)\n test = S3DIS(4096, 'test')\n data, seg = train[0]\n print(data.shape)\n print(seg.shape)\n" ]
[ [ "torch.LongTensor", "numpy.multiply", "numpy.cos", "numpy.random.shuffle", "numpy.sin", "numpy.concatenate", "numpy.random.randn", "numpy.random.uniform" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
wip-abramson/PySyft
[ "2940bfebb3e0f37a1b7451cf9581c41917534ed6" ]
[ "packages/syft/tests/syft/lib/sklearn/model_serialize_test.py" ]
[ "# third party\nimport numpy as np\nimport pytest\nfrom sklearn.linear_model import LogisticRegression\n\n# syft absolute\nimport syft as sy\nfrom syft.experimental_flags import flags\n\nsy.load(\"sklearn\")\nsy.load(\"numpy\")\n\n\[email protected](lib=\"sklearn\")\[email protected](\"arrow_backend\", [True, False])\ndef test_logistic_model_serde(\n arrow_backend: bool, root_client: sy.VirtualMachineClient\n) -> None:\n flags.APACHE_ARROW_TENSOR_SERDE = arrow_backend\n X = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]])\n y = np.array([0, 0, 1, 1])\n clf = LogisticRegression(random_state=0).fit(X, y)\n\n clf_remote = clf.send(root_client)\n\n clf_2 = clf_remote.get()\n\n dict_1 = vars(clf)\n dict_2 = vars(clf_2)\n\n for key in dict_1.keys():\n if type(dict_1[key]) == float:\n assert abs(dict_1[key] - dict_2[key]) < 0.0001\n elif type(dict_1[key]) == np.ndarray:\n assert dict_1[key].all() == dict_2[key].all()\n else:\n assert dict_1[key] == dict_2[key]\n" ]
[ [ "numpy.array", "sklearn.linear_model.LogisticRegression" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
3D-semantic-Sgmentation/pointnet
[ "029c0217143e6b69e685ab57cf243e322d47860f", "029c0217143e6b69e685ab57cf243e322d47860f" ]
[ "models/pointnet_seg.py", "newtrain.py" ]
[ "# import tensorflow as tf\nimport numpy as np\nimport math\nimport sys\nimport os\nimport tensorflow.compat.v1 as tf\nimport tensorflow as tf2\n\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\nsys.path.append(BASE_DIR)\nsys.path.append(os.path.join(BASE_DIR, '../utils'))\nimport tf_util\nfrom transform_nets import input_transform_net, feature_transform_net\n\ndef placeholder_inputs(batch_size, num_point):\n tf.compat.v1.disable_eager_execution()\n pointclouds_pl = tf.placeholder(tf.float32,\n shape=(batch_size, num_point, 3))\n labels_pl = tf.placeholder(tf.int32,\n shape=(batch_size, num_point))\n return pointclouds_pl, labels_pl\n\n\ndef get_model(point_cloud, is_training, bn_decay=None):\n \"\"\" Classification PointNet, input is BxNx3, output BxNx50 \"\"\"\n batch_size = point_cloud.get_shape()[0]\n num_point = point_cloud.get_shape()[1]\n end_points = {}\n\n with tf.variable_scope('transform_net1') as sc:\n transform = input_transform_net(point_cloud, is_training, bn_decay, K=3)\n point_cloud_transformed = tf.matmul(point_cloud, transform)\n input_image = tf.expand_dims(point_cloud_transformed, -1)\n\n net = tf_util.conv2d(input_image, 64, [1,3],\n padding='VALID', stride=[1,1],\n bn=True, is_training=is_training,\n scope='conv1', bn_decay=bn_decay)\n net = tf_util.conv2d(net, 64, [1,1],\n padding='VALID', stride=[1,1],\n bn=True, is_training=is_training,\n scope='conv2', bn_decay=bn_decay)\n\n with tf.variable_scope('transform_net2') as sc:\n transform = feature_transform_net(net, is_training, bn_decay, K=64)\n end_points['transform'] = transform\n net_transformed = tf.matmul(tf.squeeze(net, axis=[2]), transform)\n point_feat = tf.expand_dims(net_transformed, [2])\n print(point_feat)\n\n net = tf_util.conv2d(point_feat, 64, [1,1],\n padding='VALID', stride=[1,1],\n bn=True, is_training=is_training,\n scope='conv3', bn_decay=bn_decay)\n net = tf_util.conv2d(net, 128, [1,1],\n padding='VALID', stride=[1,1],\n bn=True, is_training=is_training,\n scope='conv4', bn_decay=bn_decay)\n net = tf_util.conv2d(net, 1024, [1,1],\n padding='VALID', stride=[1,1],\n bn=True, is_training=is_training,\n scope='conv5', bn_decay=bn_decay)\n global_feat = tf_util.max_pool2d(net, [num_point,1],\n padding='VALID', scope='maxpool')\n print(global_feat)\n\n global_feat_expand = tf.tile(global_feat, [1, num_point, 1, 1])\n concat_feat = tf.concat(axis=3, values=[point_feat, global_feat_expand])\n print(concat_feat)\n\n net = tf_util.conv2d(concat_feat, 512, [1,1],\n padding='VALID', stride=[1,1],\n bn=True, is_training=is_training,\n scope='conv6', bn_decay=bn_decay)\n net = tf_util.conv2d(net, 256, [1,1],\n padding='VALID', stride=[1,1],\n bn=True, is_training=is_training,\n scope='conv7', bn_decay=bn_decay)\n net = tf_util.conv2d(net, 128, [1,1],\n padding='VALID', stride=[1,1],\n bn=True, is_training=is_training,\n scope='conv8', bn_decay=bn_decay)\n net = tf_util.conv2d(net, 128, [1,1],\n padding='VALID', stride=[1,1],\n bn=True, is_training=is_training,\n scope='conv9', bn_decay=bn_decay)\n\n net = tf_util.conv2d(net, 9, [1,1],\n padding='VALID', stride=[1,1], activation_fn=None,\n scope='conv10')\n net = tf.squeeze(net, [2]) # BxNxC\n\n return net, end_points\n\n\ndef get_loss(pred, label, end_points, reg_weight=0.001):\n \"\"\" pred: BxNxC,\n label: BxN, \"\"\"\n\n loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=pred, labels=label)\n classify_loss = tf.reduce_mean(loss)\n tf2.summary.scalar('classify loss', classify_loss)\n\n # Enforce the transformation as orthogonal matrix\n transform = end_points['transform'] # BxKxK\n K = transform.get_shape()[1]\n mat_diff = tf.matmul(transform, tf.transpose(transform, perm=[0,2,1]))\n mat_diff -= tf.constant(np.eye(K), dtype=tf.float32)\n mat_diff_loss = tf.nn.l2_loss(mat_diff) \n tf2.summary.scalar('mat_loss', mat_diff_loss)\n\n return classify_loss + mat_diff_loss * reg_weight\n\n\nif __name__=='__main__':\n with tf.Graph().as_default():\n inputs = tf.zeros((32,1024,3))\n labels = tf.zeros((32,1024))\n print(labels.shape.rank)\n pred, end_points = get_model(inputs, tf.constant(True))\n loss = get_loss(pred, labels, end_points)\n print(outputs)\n", "import os\nimport sys\nimport json\nimport datetime\nimport numpy as np\nimport tensorflow.compat.v1 as tf\nimport multiprocessing as mp\nimport argparse\nimport time\nfrom datetime import datetime\n\nimport utils.metric as metric\n\nfrom data.tum_mls_dataset import TUMMLSDataset\nimport importlib\nfrom models import pointnet_seg\n\n\n# Two global arg collections\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--train_set\", default=\"train\", help=\"train, train_full\")\nparser.add_argument(\"--config_file\", default=\"semantic_no_color.json\", help=\"config file path\")\nparser.add_argument('--model', default='pointnet_seg',\n help='Model name: pointnet_cls or pointnet_cls_basic [default: pointnet_cls]')\nFLAGS = parser.parse_args()\nPARAMS = json.loads(open(FLAGS.config_file).read())\nos.makedirs(PARAMS[\"logdir\"], exist_ok=True)\n# Import dataset\nTRAIN_DATASET = TUMMLSDataset(\n num_points_per_sample=PARAMS[\"num_point\"],\n split=\"train\",\n box_size_x=PARAMS[\"box_size_x\"],\n box_size_y=PARAMS[\"box_size_y\"],\n use_color=PARAMS[\"use_color\"],\n path=PARAMS[\"data_path\"],\n)\nVALIDATION_DATASET = TUMMLSDataset(\n num_points_per_sample=PARAMS[\"num_point\"],\n split=\"validation\",\n box_size_x=PARAMS[\"box_size_x\"],\n box_size_y=PARAMS[\"box_size_y\"],\n use_color=PARAMS[\"use_color\"],\n path=PARAMS[\"data_path\"],\n)\nprint(TRAIN_DATASET.get_total_num_points())\nprint(VALIDATION_DATASET.get_total_num_points())\n\nNUM_CLASSES = TRAIN_DATASET.num_classes\n\n# Start logging\nLOG_FOUT = open(os.path.join(PARAMS[\"logdir\"], \"log_train.txt\"), \"w\")\nEPOCH_CNT = 0\n\nMODEL = importlib.import_module(FLAGS.model) # import network module\n\ndef log_string(out_str):\n LOG_FOUT.write(out_str + \"\\n\")\n LOG_FOUT.flush()\n print(out_str)\n\n\ndef update_progress(progress):\n \"\"\"\n Displays or updates a console progress bar\n Args:\n progress: A float between 0 and 1. Any int will be converted to a float.\n A value under 0 represents a 'halt'.\n A value at 1 or bigger represents 100%\n \"\"\"\n barLength = 10 # Modify this to change the length of the progress bar\n if isinstance(progress, int):\n progress = round(float(progress), 2)\n if not isinstance(progress, float):\n progress = 0\n if progress < 0:\n progress = 0\n if progress >= 1:\n progress = 1\n block = int(round(barLength * progress))\n text = \"\\rProgress: [{}] {}%\".format(\n \"#\" * block + \"-\" * (barLength - block), progress * 100\n )\n sys.stdout.write(text)\n sys.stdout.flush()\n\n\ndef get_learning_rate(batch):\n \"\"\"Compute the learning rate for a given batch size and global parameters\n\n Args:\n batch (tf.Variable): the batch size\n\n Returns:\n scalar tf.Tensor: the decayed learning rate\n \"\"\"\n\n learning_rate = tf.train.exponential_decay(\n PARAMS[\"learning_rate\"], # Base learning rate.\n batch * PARAMS[\"batch_size\"], # Current index into the dataset.\n PARAMS[\"decay_step\"], # Decay step.\n PARAMS[\"learning_rate_decay_rate\"], # Decay rate.\n staircase=True,\n )\n learning_rate = tf.maximum(learning_rate, 0.00001) # CLIP THE LEARNING RATE!\n return learning_rate\n\n\ndef get_bn_decay(batch):\n \"\"\"Compute the batch normalisation exponential decay\n\n Args:\n batch (tf.Variable): the batch size\n\n Returns:\n scalar tf.Tensor: the batch norm decay\n \"\"\"\n\n bn_momentum = tf.train.exponential_decay(\n PARAMS[\"bn_init_decay\"],\n batch * PARAMS[\"batch_size\"],\n float(PARAMS[\"decay_step\"]),\n PARAMS[\"bn_decay_decay_rate\"],\n staircase=True,\n )\n bn_decay = tf.minimum(PARAMS[\"bn_decay_clip\"], 1 - bn_momentum)\n return bn_decay\n\n\ndef get_batch(split):\n np.random.seed()\n if split == \"train\":\n return TRAIN_DATASET.sample_batch_in_all_files(\n PARAMS[\"batch_size\"], augment=True\n )\n else:\n return VALIDATION_DATASET.sample_batch_in_all_files(\n PARAMS[\"batch_size\"], augment=False\n )\n\n\ndef fill_queues(\n stack_train, stack_validation, num_train_batches, num_validation_batches\n):\n \"\"\"\n Args:\n stack_train: mp.Queue to be filled asynchronously\n stack_validation: mp.Queue to be filled asynchronously\n num_train_batches: total number of training batches\n num_validation_batches: total number of validationation batches\n \"\"\"\n pool = mp.Pool(processes=mp.cpu_count())\n launched_train = 0\n launched_validation = 0\n results_train = [] # Temp buffer before filling the stack_train\n results_validation = [] # Temp buffer before filling the stack_validation\n # Launch as much as n\n while True:\n if stack_train.qsize() + launched_train < num_train_batches:\n results_train.append(pool.apply_async(get_batch, args=(\"train\",)))\n launched_train += 1\n elif stack_validation.qsize() + launched_validation < num_validation_batches:\n results_validation.append(pool.apply_async(get_batch, args=(\"validation\",)))\n launched_validation += 1\n for p in results_train:\n if p.ready():\n stack_train.put(p.get())\n results_train.remove(p)\n launched_train -= 1\n for p in results_validation:\n if p.ready():\n stack_validation.put(p.get())\n results_validation.remove(p)\n launched_validation -= 1\n # Stability\n time.sleep(0.01)\n\n\ndef init_stacking():\n \"\"\"\n Returns:\n stacker: mp.Process object\n stack_validation: mp.Queue, use stack_validation.get() to read a batch\n stack_train: mp.Queue, use stack_train.get() to read a batch\n \"\"\"\n with tf.device(\"/cpu:0\"):\n # Queues that contain several batches in advance\n num_train_batches = TRAIN_DATASET.get_num_batches(PARAMS[\"batch_size\"])\n num_validation_batches = VALIDATION_DATASET.get_num_batches(\n PARAMS[\"batch_size\"]\n )\n stack_train = mp.Queue(num_train_batches)\n stack_validation = mp.Queue(num_validation_batches)\n stacker = mp.Process(\n target=fill_queues,\n args=(\n stack_train,\n stack_validation,\n num_train_batches,\n num_validation_batches,\n ),\n )\n stacker.start()\n return stacker, stack_validation, stack_train\n\n\ndef train_one_epoch(sess, ops, train_writer, stack):\n \"\"\"Train one epoch\n\n Args:\n sess (tf.Session): the session to evaluate Tensors and ops\n ops (dict of tf.Operation): contain multiple operation mapped with with strings\n train_writer (tf.FileSaver): enable to log the training with TensorBoard\n compute_class_iou (bool): it takes time to compute the iou per class, so you can\n disable it here\n \"\"\"\n\n is_training = True\n\n num_batches = TRAIN_DATASET.get_num_batches(PARAMS[\"batch_size\"])\n\n log_string(str(datetime.now()))\n update_progress(0)\n # Reset metrics\n loss_sum = 0\n confusion_matrix = metric.ConfusionMatrix(NUM_CLASSES)\n\n # Train over num_batches batches\n for batch_idx in range(num_batches):\n # Refill more batches if empty\n progress = float(batch_idx) / float(num_batches)\n update_progress(round(progress, 2))\n batch_data, batch_label, batch_weights = stack.get()\n\n # Get predicted labels\n feed_dict = {\n ops[\"pointclouds_pl\"]: batch_data,\n ops[\"labels_pl\"]: batch_label,\n # ops[\"smpws_pl\"]: batch_weights,\n ops[\"is_training_pl\"]: is_training,\n }\n summary, step, _, loss_val, pred_val, _ = sess.run(\n [\n ops[\"merged\"],\n ops[\"step\"],\n ops[\"train_op\"],\n ops[\"loss\"],\n ops[\"pred\"],\n ops[\"update_iou\"],\n ],\n feed_dict=feed_dict,\n )\n train_writer.add_summary(summary, step)\n pred_val = np.argmax(pred_val, 2)\n\n # Update metrics\n for i in range(len(pred_val)):\n for j in range(len(pred_val[i])):\n confusion_matrix.increment(batch_label[i][j], pred_val[i][j])\n loss_sum += loss_val\n update_progress(1)\n log_string(\"mean loss: %f\" % (loss_sum / float(num_batches)))\n log_string(\"Overall accuracy : %f\" % (confusion_matrix.get_accuracy()))\n log_string(\"Average IoU : %f\" % (confusion_matrix.get_mean_iou()))\n iou_per_class = confusion_matrix.get_per_class_ious()\n iou_per_class = [0] + iou_per_class # label 0 is ignored\n for i in range(1, NUM_CLASSES):\n log_string(\"IoU of %s : %f\" % (TRAIN_DATASET.labels_names[i], iou_per_class[i]))\n\n\ndef eval_one_epoch(sess, ops, validation_writer, stack):\n \"\"\"Evaluate one epoch\n\n Args:\n sess (tf.Session): the session to evaluate tensors and operations\n ops (tf.Operation): the dict of operations\n validation_writer (tf.summary.FileWriter): enable to log the evaluation on TensorBoard\n\n Returns:\n float: the overall accuracy computed on the validationation set\n \"\"\"\n\n global EPOCH_CNT\n\n is_training = False\n\n num_batches = VALIDATION_DATASET.get_num_batches(PARAMS[\"batch_size\"])\n\n # Reset metrics\n loss_sum = 0\n confusion_matrix = metric.ConfusionMatrix(NUM_CLASSES)\n\n log_string(str(datetime.now()))\n\n log_string(\"---- EPOCH %03d EVALUATION ----\" % (EPOCH_CNT))\n\n update_progress(0)\n\n for batch_idx in range(num_batches):\n progress = float(batch_idx) / float(num_batches)\n update_progress(round(progress, 2))\n batch_data, batch_label, batch_weights = stack.get()\n\n feed_dict = {\n ops[\"pointclouds_pl\"]: batch_data,\n ops[\"labels_pl\"]: batch_label,\n # ops[\"smpws_pl\"]: batch_weights,\n ops[\"is_training_pl\"]: is_training,\n }\n summary, step, loss_val, pred_val = sess.run(\n [ops[\"merged\"], ops[\"step\"], ops[\"loss\"], ops[\"pred\"]], feed_dict=feed_dict\n )\n\n validation_writer.add_summary(summary, step)\n pred_val = np.argmax(pred_val, 2) # BxN\n\n # Update metrics\n for i in range(len(pred_val)):\n for j in range(len(pred_val[i])):\n confusion_matrix.increment(batch_label[i][j], pred_val[i][j])\n loss_sum += loss_val\n\n update_progress(1)\n\n iou_per_class = confusion_matrix.get_per_class_ious()\n\n # Display metrics\n log_string(\"mean loss: %f\" % (loss_sum / float(num_batches)))\n log_string(\"Overall accuracy : %f\" % (confusion_matrix.get_accuracy()))\n log_string(\"Average IoU : %f\" % (confusion_matrix.get_mean_iou()))\n iou_per_class = [0] + iou_per_class # label 0 is ignored\n for i in range(1, NUM_CLASSES):\n log_string(\n \"IoU of %s : %f\" % (VALIDATION_DATASET.labels_names[i], iou_per_class[i])\n )\n\n EPOCH_CNT += 5\n return confusion_matrix.get_accuracy()\n\n\ndef train():\n \"\"\"Train the model on a single GPU\n \"\"\"\n with tf.Graph().as_default():\n stacker, stack_validation, stack_train = init_stacking()\n\n with tf.device(\"/gpu:\" + str(PARAMS[\"gpu\"])):\n pointclouds_pl, labels_pl = MODEL.placeholder_inputs(PARAMS[\"batch_size\"], PARAMS[\"num_point\"])\n\n is_training_pl = tf.placeholder(tf.bool, shape=())\n\n # Note the global_step=batch parameter to minimize.\n # That tells the optimizer to helpfully increment the 'batch' parameter for\n # you every time it trains.\n batch = tf.Variable(0)\n bn_decay = get_bn_decay(batch)\n tf.summary.scalar(\"bn_decay\", bn_decay)\n\n print(\"--- Get model and loss\")\n # Get model and loss\n pred, end_points = MODEL.get_model(pointclouds_pl, is_training_pl, bn_decay=bn_decay)\n loss = MODEL.get_loss(pred, labels_pl, end_points)\n tf.summary.scalar('loss', loss)\n\n\n # Compute accuracy\n correct = tf.equal(tf.argmax(pred, 2), tf.to_int64(labels_pl))\n accuracy = tf.reduce_sum(tf.cast(correct, tf.float32)) / float(PARAMS[\"batch_size\"])\n tf.summary.scalar('accuracy', accuracy) \n\n # Computer mean intersection over union\n mean_intersection_over_union, update_iou_op = tf.metrics.mean_iou(\n tf.to_int32(labels_pl), tf.to_int32(tf.argmax(pred, 2)), NUM_CLASSES\n )\n tf.summary.scalar(\"mIoU\", tf.to_float(mean_intersection_over_union))\n\n print(\"--- Get training operator\")\n # Get training operator\n learning_rate = get_learning_rate(batch)\n tf.summary.scalar(\"learning_rate\", learning_rate)\n if PARAMS[\"optimizer\"] == \"momentum\":\n optimizer = tf.train.MomentumOptimizer(\n learning_rate, momentum=PARAMS[\"momentum\"]\n )\n else:\n assert PARAMS[\"optimizer\"] == \"adam\"\n optimizer = tf.train.AdamOptimizer(learning_rate)\n train_op = optimizer.minimize(loss, global_step=batch)\n\n # Add ops to save and restore all the variables.\n saver = tf.train.Saver()\n\n # Create a session\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n config.allow_soft_placement = True\n config.log_device_placement = False\n sess = tf.Session(config=config)\n\n # Add summary writers\n merged = tf.summary.merge_all()\n train_writer = tf.summary.FileWriter(\n os.path.join(PARAMS[\"logdir\"], \"train\"), sess.graph\n )\n validation_writer = tf.summary.FileWriter(\n os.path.join(PARAMS[\"logdir\"], \"validation\"), sess.graph\n )\n \n\n # Init variables\n sess.run(tf.global_variables_initializer())\n sess.run(tf.local_variables_initializer()) # important for mIoU\n\n ops = {\n \"pointclouds_pl\": pointclouds_pl,\n \"labels_pl\": labels_pl,\n # \"smpws_pl\": smpws_pl,\n \"is_training_pl\": is_training_pl,\n \"pred\": pred,\n \"loss\": loss,\n \"train_op\": train_op,\n \"merged\": merged,\n \"step\": batch,\n \"end_points\": end_points,\n \"update_iou\": update_iou_op,\n }\n\n # Train for hyper_params[\"max_epoch\"] epochs\n best_acc = 0\n for epoch in range(PARAMS[\"max_epoch\"]):\n print(\"in epoch\", epoch)\n # print(\"max_epoch\", PARAMS[\"max_epoch\"])\n\n log_string(\"**** EPOCH %03d ****\" % (epoch))\n sys.stdout.flush()\n\n # Train one epoch\n train_one_epoch(sess, ops, train_writer, stack_train)\n\n # Evaluate, save, and compute the accuracy\n if epoch % 5 == 0:\n acc = eval_one_epoch(sess, ops, validation_writer, stack_validation)\n\n if acc > best_acc:\n best_acc = acc\n save_path = saver.save(\n sess,\n os.path.join(\n PARAMS[\"logdir\"], \"best_model_epoch_%03d.ckpt\" % (epoch)\n ),\n )\n log_string(\"Model saved in file: %s\" % save_path)\n print(\"Model saved in file: %s\" % save_path)\n\n # Save the variables to disk.\n if epoch % 10 == 0:\n save_path = saver.save(\n sess, os.path.join(PARAMS[\"logdir\"], \"model.ckpt\")\n )\n log_string(\"Model saved in file: %s\" % save_path)\n print(\"Model saved in file: %s\" % save_path)\n\n # Kill the process, close the file and exit\n stacker.terminate()\n LOG_FOUT.close()\n sys.exit()\n\n\nif __name__ == \"__main__\":\n train()\n" ]
[ [ "tensorflow.summary.scalar", "tensorflow.compat.v1.expand_dims", "tensorflow.compat.v1.concat", "tensorflow.compat.v1.reduce_mean", "numpy.eye", "tensorflow.compat.v1.zeros", "tensorflow.compat.v1.matmul", "tensorflow.compat.v1.placeholder", "tensorflow.compat.v1.tile", "tensorflow.compat.v1.variable_scope", "tensorflow.compat.v1.compat.v1.disable_eager_execution", "tensorflow.compat.v1.Graph", "tensorflow.compat.v1.nn.l2_loss", "tensorflow.compat.v1.squeeze", "tensorflow.compat.v1.transpose", "tensorflow.compat.v1.nn.sparse_softmax_cross_entropy_with_logits", "tensorflow.compat.v1.constant" ], [ "tensorflow.compat.v1.train.Saver", "tensorflow.compat.v1.summary.merge_all", "tensorflow.compat.v1.to_int32", "tensorflow.compat.v1.train.AdamOptimizer", "tensorflow.compat.v1.to_int64", "tensorflow.compat.v1.maximum", "numpy.argmax", "tensorflow.compat.v1.local_variables_initializer", "tensorflow.compat.v1.train.exponential_decay", "tensorflow.compat.v1.minimum", "tensorflow.compat.v1.Graph", "tensorflow.compat.v1.summary.scalar", "tensorflow.compat.v1.cast", "tensorflow.compat.v1.ConfigProto", "tensorflow.compat.v1.device", "tensorflow.compat.v1.Variable", "numpy.random.seed", "tensorflow.compat.v1.argmax", "tensorflow.compat.v1.global_variables_initializer", "tensorflow.compat.v1.Session", "tensorflow.compat.v1.to_float", "tensorflow.compat.v1.placeholder", "tensorflow.compat.v1.train.MomentumOptimizer" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
vedashree29296/BentoML
[ "79f94d543a0684e04551207d102a2d254b770ad3" ]
[ "tests/adapters/test_dataframe_input.py" ]
[ "# pylint: disable=redefined-outer-name\n\nimport itertools\nimport json\nimport math\nimport time\n\nimport flask\nimport numpy as np\nimport pandas as pd\nimport psutil # noqa # pylint: disable=unused-import\nimport pytest\n\nfrom bentoml.adapters import DataframeInput\nfrom bentoml.adapters.dataframe_input import read_dataframes_from_json_n_csv\nfrom bentoml.utils.csv import csv_splitlines\nfrom bentoml.utils.dataframe_util import guess_orient\n\ntry:\n from unittest.mock import MagicMock\nexcept ImportError:\n from mock import MagicMock\n\n\ndef test_dataframe_request_schema():\n input_adapter = DataframeInput(\n dtype={\"col1\": \"int\", \"col2\": \"float\", \"col3\": \"string\"}\n )\n\n schema = input_adapter.request_schema[\"application/json\"][\"schema\"]\n assert \"object\" == schema[\"type\"]\n assert 3 == len(schema[\"properties\"])\n assert \"array\" == schema[\"properties\"][\"col1\"][\"type\"]\n assert \"integer\" == schema[\"properties\"][\"col1\"][\"items\"][\"type\"]\n assert \"number\" == schema[\"properties\"][\"col2\"][\"items\"][\"type\"]\n assert \"string\" == schema[\"properties\"][\"col3\"][\"items\"][\"type\"]\n\n\ndef test_dataframe_handle_cli(capsys, make_api, tmpdir):\n def test_func(df):\n return df[\"name\"]\n\n input_adapter = DataframeInput()\n api = make_api(input_adapter, test_func)\n\n json_file = tmpdir.join(\"test.json\")\n with open(str(json_file), \"w\") as f:\n f.write('[{\"name\": \"john\",\"game\": \"mario\",\"city\": \"sf\"}]')\n\n test_args = [\"--input-file\", str(json_file)]\n api.handle_cli(test_args)\n out, _ = capsys.readouterr()\n assert \"john\" in out\n\n\ndef test_dataframe_handle_aws_lambda_event(make_api):\n test_content = '[{\"name\": \"john\",\"game\": \"mario\",\"city\": \"sf\"}]'\n\n def test_func(df):\n return df[\"name\"]\n\n input_adapter = DataframeInput()\n api = make_api(input_adapter, test_func)\n event = {\n \"headers\": {\"Content-Type\": \"application/json\"},\n \"body\": test_content,\n }\n response = api.handle_aws_lambda_event(event)\n assert response[\"statusCode\"] == 200\n assert response[\"body\"] == '[{\"name\":\"john\"}]'\n\n event_without_content_type_header = {\n \"headers\": {},\n \"body\": test_content,\n }\n response = api.handle_aws_lambda_event(event_without_content_type_header)\n assert response[\"statusCode\"] == 200\n assert response[\"body\"] == '[{\"name\":\"john\"}]'\n\n event_with_bad_input = {\n \"headers\": {},\n \"body\": \"bad_input_content\",\n }\n response = api.handle_aws_lambda_event(event_with_bad_input)\n assert response[\"statusCode\"] == 400\n\n\ndef test_dataframe_handle_request_csv(make_api):\n def test_func(df):\n return df[\"name\"]\n\n input_adapter = DataframeInput()\n api = make_api(input_adapter, test_func)\n csv_data = b'name,game,city\\njohn,mario,sf'\n request = MagicMock(spec=flask.Request)\n request.headers = {'Content-Type': 'text/csv'}\n request.get_data.return_value = csv_data\n\n result = api.handle_request(request)\n assert result.get_data().decode('utf-8') == '[{\"name\":\"john\"}]'\n\n\ndef assert_df_equal(left: pd.DataFrame, right: pd.DataFrame):\n '''\n Compare two instances of pandas.DataFrame ignoring index and columns\n '''\n try:\n left_array = left.values\n right_array = right.values\n if right_array.dtype == np.float:\n np.testing.assert_array_almost_equal(left_array, right_array)\n else:\n np.testing.assert_array_equal(left_array, right_array)\n except AssertionError:\n raise AssertionError(\n f\"\\n{left.to_string()}\\n is not equal to \\n{right.to_string()}\\n\"\n )\n\n\nDF_CASES = (\n pd.DataFrame(np.random.rand(1, 3)),\n pd.DataFrame(np.random.rand(2, 3)),\n pd.DataFrame(np.random.rand(2, 3), columns=['A', 'B', 'C']),\n pd.DataFrame([\"str1\", \"str2\", \"str3\"]), # single dim sting array\n pd.DataFrame([np.nan]), # special values\n pd.DataFrame([math.nan]), # special values\n pd.DataFrame([\" \", 'a\"b', \"a,b\", \"a\\nb\"]), # special values\n pd.DataFrame({\"test\": [\" \", 'a\"b', \"a,b\", \"a\\nb\"]}), # special values\n # pd.Series(np.random.rand(2)), # TODO: Series support\n # pd.DataFrame([\"\"]), # TODO: -> NaN\n)\n\n\[email protected](params=DF_CASES)\ndef df(request):\n return request.param\n\n\[email protected](params=pytest.DF_ORIENTS)\ndef orient(request):\n return request.param\n\n\ndef test_batch_read_dataframes_from_mixed_json_n_csv(df):\n test_datas = []\n test_types = []\n\n # test content_type=application/json with various orients\n for orient in pytest.DF_ORIENTS:\n try:\n assert_df_equal(df, pd.read_json(df.to_json(orient=orient)))\n except (AssertionError, ValueError):\n # skip cases not supported by official pandas\n continue\n\n test_datas.extend([df.to_json(orient=orient).encode()] * 3)\n test_types.extend(['json'] * 3)\n\n test_datas.extend([df.to_csv(index=False).encode()] * 3)\n test_types.extend(['csv'] * 3)\n\n df_merged, counts = read_dataframes_from_json_n_csv(test_datas, test_types)\n i = 0\n for count in counts:\n assert_df_equal(df_merged[i : i + count], df)\n i += count\n\n\ndef test_batch_read_dataframes_from_csv_other_CRLF(df):\n csv_str = df.to_csv(index=False)\n\n if '\\r\\n' in csv_str:\n csv_str = '\\n'.join(csv_splitlines(csv_str)).encode()\n else:\n csv_str = '\\r\\n'.join(csv_splitlines(csv_str)).encode()\n df_merged, _ = read_dataframes_from_json_n_csv([csv_str], ['csv'])\n assert_df_equal(df_merged, df)\n\n\ndef test_batch_read_dataframes_from_json_of_orients(df, orient):\n test_datas = [df.to_json(orient=orient).encode()] * 3\n test_types = ['json'] * 3\n df_merged, counts = read_dataframes_from_json_n_csv(test_datas, test_types, orient)\n i = 0\n for count in counts:\n assert_df_equal(df_merged[i : i + count], df)\n i += count\n\n\ndef test_batch_read_dataframes_from_json_with_wrong_orients(df, orient):\n test_datas = [df.to_json(orient='table').encode()] * 3\n test_types = ['json'] * 3\n\n df_merged, counts = read_dataframes_from_json_n_csv(test_datas, test_types, orient)\n assert not df_merged\n for count in counts:\n assert not count\n\n\ndef test_batch_read_dataframes_from_json_in_mixed_order():\n # different column order when orient=records\n df_json = b'[{\"A\": 1, \"B\": 2, \"C\": 3}, {\"C\": 6, \"A\": 2, \"B\": 4}]'\n df_merged, counts = read_dataframes_from_json_n_csv([df_json], ['json'])\n i = 0\n for count in counts:\n assert_df_equal(df_merged[i : i + count], pd.read_json(df_json))\n i += count\n\n # different row/column order when orient=columns\n df_json1 = b'{\"A\": {\"1\": 1, \"2\": 2}, \"B\": {\"1\": 2, \"2\": 4}, \"C\": {\"1\": 3, \"2\": 6}}'\n df_json2 = b'{\"B\": {\"1\": 2, \"2\": 4}, \"A\": {\"1\": 1, \"2\": 2}, \"C\": {\"1\": 3, \"2\": 6}}'\n df_json3 = b'{\"A\": {\"1\": 1, \"2\": 2}, \"B\": {\"2\": 4, \"1\": 2}, \"C\": {\"1\": 3, \"2\": 6}}'\n df_merged, counts = read_dataframes_from_json_n_csv(\n [df_json1, df_json2, df_json3], ['json'] * 3\n )\n i = 0\n for count in counts:\n assert_df_equal(\n df_merged[i : i + count][[\"A\", \"B\", \"C\"]],\n pd.read_json(df_json1)[[\"A\", \"B\", \"C\"]],\n )\n i += count\n\n\ndef test_guess_orient(df, orient):\n json_str = df.to_json(orient=orient)\n guessed_orient = guess_orient(json.loads(json_str), strict=True)\n assert orient == guessed_orient or orient in guessed_orient\n\n\[email protected]('not psutil.POSIX')\ndef test_benchmark_load_dataframes():\n '''\n read_dataframes_from_json_n_csv should be 30x faster than pd.read_json + pd.concat\n '''\n test_count = 50\n\n dfs = [pd.DataFrame(np.random.rand(10, 100)) for _ in range(test_count)]\n inputs = [df.to_json().encode() for df in dfs]\n\n time_st = time.time()\n dfs = [pd.read_json(i) for i in inputs]\n result1 = pd.concat(dfs)\n time1 = time.time() - time_st\n\n time_st = time.time()\n result2, _ = read_dataframes_from_json_n_csv(\n inputs, itertools.repeat('json'), 'columns'\n )\n\n time2 = time.time() - time_st\n assert_df_equal(result1, result2)\n\n # 5 is just an estimate on the smaller end, which should be true for most\n # development machines and Github actions CI environment, the actual ratio depends\n # on the hardware and available computing resource\n assert time1 / time2 > 5\n" ]
[ [ "pandas.concat", "pandas.DataFrame", "numpy.testing.assert_array_equal", "numpy.random.rand", "pandas.read_json", "numpy.testing.assert_array_almost_equal" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.3", "0.19", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] } ]
SsisyphusTao/TensorRT
[ "69f5a5093a39184e137a55c908d5c4d1340b009a" ]
[ "tools/Polygraphy/tests/comparator/test_comparator.py" ]
[ "#\n# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nimport subprocess as sp\n\nimport numpy as np\nimport pytest\nimport tensorrt as trt\nfrom polygraphy.backend.onnx import BytesFromOnnx, OnnxFromTfGraph, GsFromOnnx\nfrom polygraphy.backend.onnxrt import OnnxrtRunner, SessionFromOnnx\nfrom polygraphy.backend.pluginref import PluginRefRunner\nfrom polygraphy.backend.tf import SessionFromGraph, TfRunner\nfrom polygraphy.backend.trt import EngineFromNetwork, NetworkFromOnnxBytes, TrtRunner\nfrom polygraphy.exception import PolygraphyException\nfrom polygraphy.comparator import Comparator, CompareFunc, DataLoader, IterationResult, PostprocessFunc, RunResults\nfrom polygraphy import mod\nfrom tests.models.meta import ONNX_MODELS, TF_MODELS\n\n\nclass TestComparator(object):\n def test_warmup_runs(self):\n onnx_loader = ONNX_MODELS[\"identity\"].loader\n runner = OnnxrtRunner(SessionFromOnnx(onnx_loader))\n run_results = Comparator.run([runner], warm_up=2)\n assert len(run_results[runner.name]) == 1\n\n def test_list_as_data_loader(self):\n onnx_loader = ONNX_MODELS[\"identity\"].loader\n runner = OnnxrtRunner(SessionFromOnnx(onnx_loader), name=\"onnx_runner\")\n\n data = [{\"x\": np.ones((1, 1, 2, 2), dtype=np.float32)}] * 2\n run_results = Comparator.run([runner], data_loader=data)\n iter_results = run_results[\"onnx_runner\"]\n assert len(iter_results) == 2\n for actual, expected in zip(iter_results, data):\n assert np.all(actual[\"y\"] == expected[\"x\"])\n\n def test_generator_as_data_loader(self):\n onnx_loader = ONNX_MODELS[\"identity\"].loader\n runner = OnnxrtRunner(SessionFromOnnx(onnx_loader), name=\"onnx_runner\")\n\n def data():\n for feed_dict in [{\"x\": np.ones((1, 1, 2, 2), dtype=np.float32)}] * 2:\n yield feed_dict\n\n run_results = Comparator.run([runner], data_loader=data())\n iter_results = run_results[\"onnx_runner\"]\n assert len(iter_results) == 2\n for actual, expected in zip(iter_results, data()):\n assert np.all(actual[\"y\"] == expected[\"x\"])\n\n def test_multiple_runners(self):\n load_tf = TF_MODELS[\"identity\"].loader\n build_tf_session = SessionFromGraph(load_tf)\n onnx_model = OnnxFromTfGraph(load_tf)\n load_serialized_onnx = BytesFromOnnx(onnx_model)\n build_onnxrt_session = SessionFromOnnx(load_serialized_onnx)\n load_engine = EngineFromNetwork(NetworkFromOnnxBytes(load_serialized_onnx))\n gs_graph = GsFromOnnx(onnx_model)\n\n runners = [\n TfRunner(build_tf_session),\n OnnxrtRunner(build_onnxrt_session),\n PluginRefRunner(gs_graph),\n TrtRunner(load_engine),\n ]\n\n run_results = Comparator.run(runners)\n compare_func = CompareFunc.simple(check_shapes=mod.version(trt.__version__) >= mod.version(\"7.0\"))\n assert bool(Comparator.compare_accuracy(run_results, compare_func=compare_func))\n assert len(list(run_results.values())[0]) == 1 # Default number of iterations\n\n def test_postprocess(self):\n onnx_loader = ONNX_MODELS[\"identity\"].loader\n run_results = Comparator.run([OnnxrtRunner(SessionFromOnnx(onnx_loader))], use_subprocess=True)\n # Output shape is (1, 1, 2, 2)\n postprocessed = Comparator.postprocess(run_results, postprocess_func=PostprocessFunc.topk_func(k=1, axis=-1))\n for _, results in postprocessed.items():\n for result in results:\n for _, output in result.items():\n assert output.shape == (1, 1, 2, 1)\n\n def test_errors_do_not_hang(self):\n # Should error because interface is not implemented correctly.\n class FakeRunner(object):\n def __init__(self):\n self.name = \"fake\"\n\n runners = [FakeRunner()]\n with pytest.raises(PolygraphyException):\n Comparator.run(runners, use_subprocess=True, subprocess_polling_interval=1)\n\n def test_segfault_does_not_hang(self):\n def raise_called_process_error():\n class FakeSegfault(sp.CalledProcessError):\n pass\n\n raise FakeSegfault(-11, [\"simulate\", \"segfault\"])\n\n runners = [TrtRunner(EngineFromNetwork(raise_called_process_error))]\n with pytest.raises(PolygraphyException):\n Comparator.run(runners, use_subprocess=True, subprocess_polling_interval=1)\n\n def test_multirun_outputs_are_different(self):\n onnx_loader = ONNX_MODELS[\"identity\"].loader\n runner = TrtRunner(EngineFromNetwork(NetworkFromOnnxBytes(onnx_loader)))\n run_results = Comparator.run([runner], data_loader=DataLoader(iterations=2))\n\n iteration0 = run_results[runner.name][0]\n iteration1 = run_results[runner.name][1]\n for name in iteration0.keys():\n assert np.any(iteration0[name] != iteration1[name])\n\n def test_validate_nan(self):\n run_results = RunResults()\n run_results[\"fake-runner\"] = [IterationResult(outputs={\"x\": np.array(np.nan)})]\n assert not Comparator.validate(run_results)\n\n def test_validate_inf(self):\n run_results = RunResults()\n run_results[\"fake-runner\"] = [IterationResult(outputs={\"x\": np.array(np.inf)})]\n assert not Comparator.validate(run_results, check_inf=True)\n\n def test_dim_param_trt_onnxrt(self):\n load_onnx_bytes = ONNX_MODELS[\"dim_param\"].loader\n build_onnxrt_session = SessionFromOnnx(load_onnx_bytes)\n load_engine = EngineFromNetwork(NetworkFromOnnxBytes(load_onnx_bytes))\n\n runners = [\n OnnxrtRunner(build_onnxrt_session),\n TrtRunner(load_engine),\n ]\n\n run_results = Comparator.run(runners)\n compare_func = CompareFunc.simple(check_shapes=mod.version(trt.__version__) >= mod.version(\"7.0\"))\n assert bool(Comparator.compare_accuracy(run_results, compare_func=compare_func))\n assert len(list(run_results.values())[0]) == 1 # Default number of iterations\n" ]
[ [ "numpy.all", "numpy.array", "numpy.any", "numpy.ones" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
larssl780/thin_wrappers
[ "c0791d76a734303708892a25cce2e237caf9920a" ]
[ "tests/test_db_utils.py" ]
[ "import pytest\nimport pathlib\nimport sys\n\nimport requests\nimport io\nimport zipfile\nimport tempfile\nimport pandas as pd\nimport os\nHERE = pathlib.Path(__file__).resolve().parent\n\n\n\n# insert at 1, 0 is the script path (or '' in REPL)\n# temporary hack until package is published and we can inherit from there:\n\nsys.path.insert(1, '%s/thin_wrappers' % HERE.parent)\nimport db_utils as db # NOQA: E402\n\n\n\ndef headers():\n return {'Accept': 'application/json, text/plain, */*',\n 'Accept-Language': 'en-US,en;q=0.5',\n 'Cache-Control': 'no-cache',\n 'Connection': 'keep-alive',\n 'DNT': '1',\n 'Pragma': 'no-cache',\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.75.14 (KHTML, like Gecko) Version/7.0.3 Safari/7046A194A',\n }\n\n\ndef download_data():\n url = 'https://eforexcel.com/wp/wp-content/uploads/2017/07/100-CC-Records.zip'\n res = requests.get(url, headers=headers())\n filebytes = io.BytesIO(res.content)\n tmp = zipfile.ZipFile(filebytes)\n temp = tempfile.NamedTemporaryFile(delete=False, suffix='.csv')\n with open(temp.name, 'wb') as fp:\n fp.write(tmp.read('100 CC Records.csv'))\n datum = pd.read_csv(temp.name, encoding='cp1252')\n return datum\n\n\ndef test_database():\n \"\"\"Test that it works writig data to an sqlite db and then read it.\n \"\"\"\n df = download_data()\n\n db.write_db_table('dummy', df, 'replace', 'test_db.sqlite')\n\n assert os.path.exists('test_db.sqlite'), \"Did not find database?!\"\n\n n_records = len(df)\n from_db = db.read_sql_table('dummy', 'test_db.sqlite')\n assert len(\n from_db) == n_records, \"Number of records does not match between database and data!\"\n db.write_db_table('dummy', df, 'append', 'test_db.sqlite')\n from_db = db.read_sql_table('dummy', 'test_db.sqlite')\n assert len(from_db) == (\n 2 * n_records), \"Number of records does not match between database and data!\"\n\n\nif __name__ == '__main__':\n pytest.main([__file__])\n" ]
[ [ "pandas.read_csv" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
rdenise/virome_pipeline
[ "3c629aef75b184bf39f2d14043f94e8787e3ea14" ]
[ "workflow/scripts/combine_virsorter_virfinder.py" ]
[ "from Bio import SeqIO\nimport pandas as pd\nimport sys\nimport os\n\n# Put error and out into the log file\nsys.stderr = sys.stdout = open(snakemake.log[0], \"w\")\n\n###########################################################\n###########################################################\n\n# List that will contains all the contigs to filter\nall_contig_ids = []\n\n# Dataframe that contains all the informations about\noutput_df = pd.DataFrame(columns=[\"contig_id\", \"virsorter_cat\", \"deepvirfinder\"])\n\n# Get all the names from the virsorter keep2 list\nids_virsorter_keep2 = snakemake.input.ids_virsorter_keep2_checked\n\nwith open(ids_virsorter_keep2) as r_file:\n r_file.readline()\n\n for line in r_file:\n rstrip_line = line.rstrip()\n rstrip_line = rstrip_line.split(\"||\")[0]\n\n all_contig_ids.append(rstrip_line)\n\n output_df.at[rstrip_line, \"contig_id\"] = rstrip_line\n output_df.at[rstrip_line, \"virsorter_cat\"] = \"keep2_checked\"\n\n# Get all the names from the virsorter keep1 list and remove redondant name\nids_virsorter_keep1 = snakemake.input.ids_virsorter_keep1\n\nwith open(ids_virsorter_keep1) as r_file:\n r_file.readline()\n\n for line in r_file:\n rstrip_line = line.rstrip()\n rstrip_line = rstrip_line.split(\"||\")[0]\n\n if rstrip_line not in all_contig_ids:\n all_contig_ids.append(rstrip_line)\n\n output_df.at[rstrip_line, \"contig_id\"] = rstrip_line\n output_df.at[rstrip_line, \"virsorter_cat\"] = \"keep1\"\n\n# Get all the names from the deepvirfinder list and remove redondant name\nids_virfinder = snakemake.input.ids_virfinder\n\nwith open(ids_virfinder) as r_file:\n r_file.readline()\n\n for line in r_file:\n rstrip_line = line.rstrip()\n\n output_df.at[rstrip_line, \"contig_id\"] = rstrip_line\n output_df.at[rstrip_line, \"deepvirfinder\"] = \"Yes\"\n\n if rstrip_line not in all_contig_ids:\n all_contig_ids.append(rstrip_line)\n\n# Fill the informations missing now the list of contigs we keep is set\ndict_map_virsorter = {}\n\nfiles_with_info = {\n snakemake.input.ids_virsorter_keep2_suspicious: \"keep2_suspicious\",\n snakemake.input.ids_virsorter_manual_check: \"to_manual_check\",\n snakemake.input.ids_virsorter_discarded: \"discarded\",\n}\n\nfor file_ids in files_with_info:\n with open(file_ids) as r_file:\n r_file.readline()\n\n for line in r_file:\n rstrip_line = line.rstrip()\n rstrip_line = rstrip_line.split(\"||\")[0]\n\n if rstrip_line not in all_contig_ids:\n dict_map_virsorter[rstrip_line] = files_with_info[file_ids]\n\n# Fill the dataframe\nlist_contig2add_virsorter_cat = list(dict_map_virsorter.keys())\noutput_df.loc[\n output_df.contig_id.isin(list_contig2add_virsorter_cat), \"virsorter_cat\"\n] = output_df.loc[\n output_df.contig_id.isin(list_contig2add_virsorter_cat), \"contig_id\"\n].map(\n dict_map_virsorter\n)\n\noutput_df.fillna(\"No\", inplace=True)\n\n# Parse the fasta of the contig and create the new one\nfasta_contigs = snakemake.input.contigs\n\nwith open(snakemake.output.fasta, \"w\") as w_file:\n with open(snakemake.output.translation_table, \"w\") as tsv_file:\n tsv_file.write(\"old_contig_name\\tnew_contig_name\\n\")\n\n parser = SeqIO.parse(fasta_contigs, \"fasta\")\n\n for contig in parser:\n if contig.id in all_contig_ids:\n contig_id = f\"{snakemake.wildcards.sample}-{contig.id}\".replace(\n \"_\", \"-\"\n )\n\n tsv_file.write(f\"{contig.id}\\t{contig_id}\\n\")\n\n contig.id = contig_id\n contig.name = \"\"\n contig.description = \"\"\n\n SeqIO.write(contig, w_file, \"fasta\")\n\noutput_df.to_csv(snakemake.output.tsv, sep=\"\\t\", index=False)\n\n###########################################################\n###########################################################\n" ]
[ [ "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
CipiOrhei/eecvf
[ "759fb2127c8d65a570ba2df536ff8429ccf5bdf2" ]
[ "Benchmarking/CM_Benchmark/basic_benchmark/rde.py" ]
[ "import math\r\nimport os\r\nfrom math import log10\r\n# noinspection PyPackageRequirements\r\nimport cv2\r\nimport numpy as np\r\nfrom scipy.ndimage import distance_transform_edt\r\n\r\nimport config_main\r\nfrom Utils.log_handler import log_setup_info_to_console, log_error_to_console, log_benchmark_info_to_console\r\nfrom Benchmarking.Util.image_parsing import find_img_extension\r\nfrom Benchmarking.Config.create_benchmark_job import set_gt_location, set_image_set, set_input_location, job_set\r\n\r\n\r\ndef rde_calc(img, img_gt, k_value):\r\n \"\"\"\r\n Dubuisson, M.P.; Jain, A.K. A modified Hausdorff distance for object matching. IEEE ICPR 1994, 1, 566-568\r\n http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.1.8155&rep=rep1&type=pdf\r\n :param img: edge map resulting of algorithm\r\n :param img_gt: ground truth image\r\n :return: psnr value for image\r\n \"\"\"\r\n # calculate distances\r\n dist_gt = distance_transform_edt(np.invert(img_gt))\r\n dist_dc = distance_transform_edt(np.invert(img))\r\n\r\n # calculate sum(d^k(D))\r\n sum_dc = 0.0\r\n sum_gt = 0.0\r\n left = 0.0\r\n right = 0.0\r\n\r\n for i in range(0, img_gt.shape[0]):\r\n for j in range(0, img_gt.shape[1]):\r\n if img_gt[i, j]:\r\n sum_dc += dist_dc[i, j] ** k_value\r\n\r\n for i in range(0, img.shape[0]):\r\n for j in range(0, img.shape[1]):\r\n if img[i, j]:\r\n sum_gt += dist_gt[i, j] ** k_value\r\n\r\n cn_cd = np.count_nonzero(img)\r\n cn_gt = np.count_nonzero(img_gt)\r\n\r\n if cn_cd != 0 :\r\n left = math.pow(sum_gt / cn_cd, 1.0/k_value)\r\n if cn_gt != 0:\r\n right = math.pow(sum_dc / cn_gt, 1.0/k_value)\r\n\r\n if cn_cd==0:\r\n rde = 1000\r\n else:\r\n rde = left + right\r\n\r\n return rde\r\n\r\n\r\n# noinspection PyPep8Naming\r\ndef run_RDE_benchmark(input_location: str, gt_location: str,\r\n raw_image: str, jobs_set: list,\r\n k: int):\r\n \"\"\"\r\n xxx\r\n :param input_location: location of algorithm images\r\n :param gt_location: location of gt images\r\n :param raw_image: location of raw images\r\n :param jobs_set: algo sets to evaluate\r\n :return: None\r\n \"\"\"\r\n\r\n set_gt_location(gt_location)\r\n set_input_location(input_location)\r\n set_image_set(raw_image)\r\n job_set(jobs_set)\r\n\r\n run_CM_benchmark_RDE(k)\r\n\r\n\r\ndef run_CM_benchmark_RDE(k_value):\r\n \"\"\"\r\n :return:\r\n \"\"\"\r\n log_setup_info_to_console(\"BENCHMARKING CM RDEK\" + int(k_value).__str__())\r\n idx = 0\r\n\r\n for set in config_main.BENCHMARK_SETS:\r\n log_benchmark_info_to_console('Current set: {number}\\{total} : {set}'.format(number=idx, total=len(config_main.BENCHMARK_SETS), set=set))\r\n idx += 1\r\n\r\n # try:\r\n if True:\r\n # Write results to disk\r\n results_path = os.path.join(os.getcwd(), config_main.BENCHMARK_RESULTS, \"RDEK\" + int(k_value).__str__())\r\n\r\n if not os.path.exists(results_path):\r\n os.makedirs(results_path)\r\n\r\n csv = open(os.path.join(results_path, set + '.log'), \"w+\")\r\n csv.write('Per image (#, RDEK' + int(k_value).__str__() + ':\\n')\r\n # log_benchmark_info_to_console('Per image (#, RDE):\\n')\r\n\r\n avg = 0\r\n count = 0\r\n\r\n for file in config_main.BENCHMARK_SAMPLE_NAMES:\r\n # find extension of images and gt_images\r\n if config_main.APPL_SAVE_JOB_NAME is True:\r\n img_extension = find_img_extension(os.path.join(config_main.BENCHMARK_INPUT_LOCATION, set, set + '_' + file))\r\n else:\r\n img_extension = find_img_extension(os.path.join(config_main.BENCHMARK_INPUT_LOCATION, set, file))\r\n\r\n gt_extension = find_img_extension(os.path.join(config_main.BENCHMARK_GT_LOCATION, file))\r\n\r\n path_img_gt = os.path.join(config_main.BENCHMARK_GT_LOCATION, file + gt_extension)\r\n\r\n if config_main.APPL_SAVE_JOB_NAME is True:\r\n path_img_al = os.path.join(config_main.BENCHMARK_INPUT_LOCATION, set, set + '_' + file + img_extension)\r\n else:\r\n path_img_al = os.path.join(config_main.BENCHMARK_INPUT_LOCATION, set, file + img_extension)\r\n\r\n img_gt = cv2.cvtColor(cv2.imread(path_img_gt), cv2.COLOR_BGR2GRAY)\r\n img_al = cv2.cvtColor(cv2.imread(path_img_al), cv2.COLOR_BGR2GRAY)\r\n\r\n try:\r\n val = rde_calc(img_al, img_gt, k_value)\r\n avg += val\r\n count += 1\r\n csv.write('{:<10s} {:<10.6f}\\n'.format(file, val))\r\n # log_benchmark_info_to_console('{:<10s} {:<10.6f}\\n'.format(file, val))\r\n except Exception as ex:\r\n log_error_to_console(\"BENCHMARK CM RDEK{val}: {file}\".format(val=int(k_value).__str__(), file=file), ex.__str__())\r\n\r\n log_benchmark_info_to_console('RDEK{val}: {set:<10s} {cnt:<10.6f}\\n'.format(val=int(k_value).__str__(), set=set, cnt=avg / count))\r\n csv.write('RDEK{val}: {set:<10s} {cnt:<10.6f}\\n'.format(val=int(k_value).__str__(), set=set, cnt=avg / count))\r\n\r\n # except Exception as ex:\r\n # log_error_to_console('BENCHMARK CM RDEK' + int(k_value).__str__() + 'NOK', ex.__str__())\r\n\r\n\r\nif __name__ == \"__main__\":\r\n pass\r\n" ]
[ [ "numpy.invert", "numpy.count_nonzero" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
zhousanfu/paddle-demo
[ "56860c5241874fe6111def46ea2f3f91e3ba80de" ]
[ "PaddleCV/tracking/ltr/data/loader.py" ]
[ "import os\nimport sys\n\nimport dataflow as df\nimport numpy as np\n\n\nclass LTRLoader(df.DataFlow):\n \"\"\"\n Data loader. Combines a dataset and a sampler, and provides\n single- or multi-process iterators over the dataset.\n\n Note: an additional option stack_dim is available to\n select along which dimension the data should be stacked to form a batch.\n\n Arguments:\n dataset (Dataset): dataset from which to load the data.\n batch_size (int, optional): how many samples per batch to load\n (default: 1).\n shuffle (bool, optional): set to ``True`` to have the data reshuffled\n at every epoch (default: False).\n sampler (Sampler, optional): defines the strategy to draw samples from\n the dataset. If specified, ``shuffle`` must be False.\n batch_sampler (Sampler, optional): like sampler, but returns a batch of\n indices at a time. Mutually exclusive with batch_size, shuffle,\n sampler, and drop_last.\n num_workers (int, optional): how many subprocesses to use for data\n loading. 0 means that the data will be loaded in the main process.\n (default: 0)\n collate_fn (callable, optional): merges a list of samples to form a mini-batch.\n stack_dim (int): Dimension along which to stack to form the batch. (default: 0)\n pin_memory (bool, optional): If ``True``, the data loader will copy tensors\n into CUDA pinned memory before returning them.\n drop_last (bool, optional): set to ``True`` to drop the last incomplete batch,\n if the dataset size is not divisible by the batch size. If ``False`` and\n the size of dataset is not divisible by the batch size, then the last batch\n will be smaller. (default: False)\n timeout (numeric, optional): if positive, the timeout value for collecting a batch\n from workers. Should always be non-negative. (default: 0)\n worker_init_fn (callable, optional): If not None, this will be called on each\n worker subprocess with the worker id (an int in ``[0, num_workers - 1]``) as\n input, after seeding and before data loading. (default: None)\n\n\n .. warning:: If ``spawn`` start method is used, :attr:`worker_init_fn` cannot be an\n unpicklable object, e.g., a lambda function.\n \"\"\"\n\n __initialized = False\n\n def __init__(self,\n name,\n dataset,\n training=True,\n batch_size=1,\n shuffle=False,\n sampler=None,\n batch_sampler=None,\n num_workers=0,\n epoch_interval=1,\n collate_fn=None,\n stack_dim=0,\n pin_memory=False,\n drop_last=False,\n timeout=0,\n worker_init_fn=None):\n\n super().__init__()\n\n ds = df.RepeatedData(dataset, -1)\n ds = df.MultiProcessRunnerZMQ(ds, num_proc=num_workers, hwm=300)\n # ds = df.MultiThreadRunner(lambda: ds, num_prefetch=1024, num_thread=num_workers)\n ds = df.BatchData(ds, batch_size)\n self.ds = ds\n\n self.name = name\n self.training = training\n self.epoch_interval = epoch_interval\n self.stack_dim = stack_dim\n self.batches_per_epoch = len(dataset) // batch_size\n\n def __len__(self):\n return self.batches_per_epoch\n\n def __iter__(self):\n if not self.__initialized:\n self.reset_state()\n self.__initialized = True\n\n for d in self.ds:\n if self.stack_dim > 0:\n for k, v in d.items():\n if len(v.shape) >= self.stack_dim + 1:\n d[k] = np.swapaxes(v, 0, self.stack_dim)\n yield d\n\n def reset_state(self):\n self.ds.reset_state()\n" ]
[ [ "numpy.swapaxes" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ximingxing/Learning-To-Learn
[ "0135cb41521a61d1f3248cf3fe409e51f824fe25" ]
[ "learningTolearn/backbone/common.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\n Description : Common routines for models in PyTorch.\n Author : xxm\n\"\"\"\n\n__all__ = ['round_channels', 'Identity', 'Swish', 'HSigmoid', 'HSwish', 'get_activation_layer', 'conv1x1', 'conv3x3',\n 'depthwise_conv3x3', 'ConvBlock', 'conv1x1_block', 'conv3x3_block', 'conv7x7_block', 'dwconv_block',\n 'dwconv3x3_block', 'dwconv5x5_block', 'dwsconv3x3_block', 'PreConvBlock', 'pre_conv1x1_block',\n 'pre_conv3x3_block', 'InterpolationBlock', 'ChannelShuffle', 'ChannelShuffle2', 'SEBlock', 'IBN',\n 'DualPathSequential', 'Concurrent', 'SequentialConcurrent', 'ParametricSequential', 'ParametricConcurrent',\n 'Hourglass', 'SesquialteralHourglass', 'MultiOutputSequential', 'Flatten']\n\nimport math\nfrom inspect import isfunction\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torchmeta.modules import MetaModule, MetaSequential, MetaConv2d, MetaBatchNorm2d\n\n\ndef round_channels(channels,\n divisor=8):\n \"\"\"\n Round weighted channel number (make divisible operation).\n Parameters:\n ----------\n channels : int or float\n Original number of channels.\n divisor : int, default 8\n Alignment value.\n Returns\n -------\n int\n Weighted number of channels.\n \"\"\"\n rounded_channels = max(int(channels + divisor / 2.0) // divisor * divisor, divisor)\n if float(rounded_channels) < 0.9 * channels:\n rounded_channels += divisor\n return rounded_channels\n\n\nclass Identity(nn.Module):\n \"\"\"\n Identity block.\n \"\"\"\n\n def __init__(self):\n super(Identity, self).__init__()\n\n def forward(self, x):\n return x\n\n\nclass Swish(nn.Module):\n \"\"\"\n Swish activation function from 'Searching for Activation Functions,' https://arxiv.org/abs/1710.05941.\n \"\"\"\n\n def forward(self, x):\n return x * torch.sigmoid(x)\n\n\nclass HSigmoid(nn.Module):\n \"\"\"\n Approximated sigmoid function, so-called hard-version of sigmoid from 'Searching for MobileNetV3,'\n https://arxiv.org/abs/1905.02244.\n \"\"\"\n\n def forward(self, x):\n return F.relu6(x + 3.0, inplace=True) / 6.0\n\n\nclass HSwish(nn.Module):\n \"\"\"\n H-Swish activation function from 'Searching for MobileNetV3,' https://arxiv.org/abs/1905.02244.\n Parameters:\n ----------\n inplace : bool\n Whether to use inplace version of the module.\n \"\"\"\n\n def __init__(self, inplace=False):\n super(HSwish, self).__init__()\n self.inplace = inplace\n\n def forward(self, x):\n return x * F.relu6(x + 3.0, inplace=self.inplace) / 6.0\n\n\ndef get_activation_layer(activation):\n \"\"\"\n Create activation layer from string/function.\n Parameters:\n ----------\n activation : function, or str, or nn.Module\n Activation function or name of activation function.\n Returns\n -------\n nn.Module\n Activation layer.\n \"\"\"\n assert (activation is not None)\n if isfunction(activation):\n return activation()\n elif isinstance(activation, str):\n if activation == \"relu\":\n return nn.ReLU(inplace=True)\n elif activation == \"relu6\":\n return nn.ReLU6(inplace=True)\n elif activation == \"swish\":\n return Swish()\n elif activation == \"hswish\":\n return HSwish(inplace=True)\n elif activation == \"sigmoid\":\n return nn.Sigmoid()\n elif activation == \"hsigmoid\":\n return HSigmoid()\n elif activation == \"identity\":\n return Identity()\n else:\n raise NotImplementedError()\n else:\n assert (isinstance(activation, nn.Module))\n return activation\n\n\ndef conv1x1(in_channels,\n out_channels,\n stride=1,\n groups=1,\n bias=False):\n \"\"\"\n Convolution 1x1 layer.\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n stride : int or tuple/list of 2 int, default 1\n Strides of the convolution.\n groups : int, default 1\n Number of groups.\n bias : bool, default False\n Whether the layer uses a bias vector.\n \"\"\"\n return nn.Conv2d(\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=1,\n stride=stride,\n groups=groups,\n bias=bias)\n\n\ndef conv3x3(in_channels,\n out_channels,\n stride=1,\n padding=1,\n dilation=1,\n groups=1,\n bias=False):\n \"\"\"\n Convolution 3x3 layer.\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n stride : int or tuple/list of 2 int, default 1\n Strides of the convolution.\n padding : int or tuple/list of 2 int, default 1\n Padding value for convolution layer.\n groups : int, default 1\n Number of groups.\n bias : bool, default False\n Whether the layer uses a bias vector.\n \"\"\"\n return nn.Conv2d(\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=3,\n stride=stride,\n padding=padding,\n dilation=dilation,\n groups=groups,\n bias=bias)\n\n\ndef depthwise_conv3x3(channels,\n stride):\n \"\"\"\n Depthwise convolution 3x3 layer.\n Parameters:\n ----------\n channels : int\n Number of input/output channels.\n strides : int or tuple/list of 2 int\n Strides of the convolution.\n \"\"\"\n return nn.Conv2d(\n in_channels=channels,\n out_channels=channels,\n kernel_size=3,\n stride=stride,\n padding=1,\n groups=channels,\n bias=False)\n\n\nclass ConvBlock(nn.Module):\n \"\"\"\n Standard convolution block with Batch normalization and activation.\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n kernel_size : int or tuple/list of 2 int\n Convolution window size.\n stride : int or tuple/list of 2 int\n Strides of the convolution.\n padding : int or tuple/list of 2 int\n Padding value for convolution layer.\n dilation : int or tuple/list of 2 int, default 1\n Dilation value for convolution layer.\n groups : int, default 1\n Number of groups.\n bias : bool, default False\n Whether the layer uses a bias vector.\n use_bn : bool, default True\n Whether to use BatchNorm layer.\n bn_eps : float, default 1e-5\n Small float added to variance in Batch norm.\n activation : function or str or None, default nn.ReLU(inplace=True)\n Activation function or name of activation function.\n \"\"\"\n\n def __init__(self,\n in_channels,\n out_channels,\n kernel_size,\n stride,\n padding,\n dilation=1,\n groups=1,\n bias=False,\n use_bn=True,\n bn_eps=1e-5,\n activation=(lambda: nn.ReLU(inplace=True))):\n super(ConvBlock, self).__init__()\n self.activate = (activation is not None)\n self.use_bn = use_bn\n\n self.conv = nn.Conv2d(\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=kernel_size,\n stride=stride,\n padding=padding,\n dilation=dilation,\n groups=groups,\n bias=bias)\n if self.use_bn:\n self.bn = nn.BatchNorm2d(\n num_features=out_channels,\n eps=bn_eps)\n if self.activate:\n self.activ = get_activation_layer(activation)\n\n def forward(self, x):\n x = self.conv(x)\n if self.use_bn:\n x = self.bn(x)\n if self.activate:\n x = self.activ(x)\n return x\n\n\nclass MetaConvBlock(MetaModule):\n \"\"\"\n Meta convolution block with Batch normalization and activation.\n Weight and\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n kernel_size : int or tuple/list of 2 int\n Convolution window size.\n stride : int or tuple/list of 2 int\n Strides of the convolution.\n padding : int or tuple/list of 2 int\n Padding value for convolution layer.\n dilation : int or tuple/list of 2 int, default 1\n Dilation value for convolution layer.\n groups : int, default 1\n Number of groups.\n bias : bool, default False\n Whether the layer uses a bias vector.\n use_bn : bool, default True\n Whether to use BatchNorm layer.\n bn_eps : float, default 1e-5\n Small float added to variance in Batch norm.\n activation : function or str or None, default nn.ReLU(inplace=True)\n Activation function or name of activation function.\n \"\"\"\n\n def __init__(self,\n in_channels,\n out_channels,\n kernel_size,\n stride,\n padding,\n dilation=1,\n groups=1,\n bias=False,\n use_bn=True,\n bn_eps=1e-5,\n activation=(lambda: nn.ReLU(inplace=True))):\n super(MetaConvBlock, self).__init__()\n self.activate = (activation is not None)\n self.use_bn = use_bn\n\n self.conv = MetaConv2d(\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=kernel_size,\n stride=stride,\n padding=padding,\n dilation=dilation,\n groups=groups,\n bias=bias)\n if self.use_bn:\n self.bn = MetaBatchNorm2d(\n num_features=out_channels,\n eps=bn_eps)\n if self.activate:\n self.activ = get_activation_layer(activation)\n\n def forward(self, x, params=None):\n x = self.conv(x, params=self.get_subdict(params, 'conv'))\n if self.use_bn:\n x = self.bn(x, params=self.get_subdict(params, 'bn'))\n if self.activate:\n x = self.activ(x)\n return x\n\n\ndef conv1x1_block(in_channels,\n out_channels,\n stride=1,\n padding=0,\n groups=1,\n bias=False,\n use_bn=True,\n bn_eps=1e-5,\n activation=(lambda: nn.ReLU(inplace=True)),\n mode=''):\n \"\"\"\n 1x1 version of the standard convolution block.\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n stride : int or tuple/list of 2 int, default 1\n Strides of the convolution.\n padding : int or tuple/list of 2 int, default 0\n Padding value for convolution layer.\n groups : int, default 1\n Number of groups.\n bias : bool, default False\n Whether the layer uses a bias vector.\n use_bn : bool, default True\n Whether to use BatchNorm layer.\n bn_eps : float, default 1e-5\n Small float added to variance in Batch norm.\n activation : function or str or None, default nn.ReLU(inplace=True)\n Activation function or name of activation function.\n \"\"\"\n if mode == 'maml':\n return MetaConvBlock(\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=1,\n stride=stride,\n padding=padding,\n groups=groups,\n bias=bias,\n use_bn=use_bn,\n bn_eps=bn_eps,\n activation=activation)\n else:\n return ConvBlock(\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=1,\n stride=stride,\n padding=padding,\n groups=groups,\n bias=bias,\n use_bn=use_bn,\n bn_eps=bn_eps,\n activation=activation)\n\n\ndef conv3x3_block(in_channels,\n out_channels,\n stride=1,\n padding=1,\n dilation=1,\n groups=1,\n bias=False,\n use_bn=True,\n bn_eps=1e-5,\n activation=(lambda: nn.ReLU(inplace=True)),\n mode=''):\n \"\"\"\n 3x3 version of the standard convolution block.\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n stride : int or tuple/list of 2 int, default 1\n Strides of the convolution.\n padding : int or tuple/list of 2 int, default 1\n Padding value for convolution layer.\n dilation : int or tuple/list of 2 int, default 1\n Dilation value for convolution layer.\n groups : int, default 1\n Number of groups.\n bias : bool, default False\n Whether the layer uses a bias vector.\n use_bn : bool, default True\n Whether to use BatchNorm layer.\n bn_eps : float, default 1e-5\n Small float added to variance in Batch norm.\n activation : function or str or None, default nn.ReLU(inplace=True)\n Activation function or name of activation function.\n \"\"\"\n if mode == 'maml':\n return MetaConvBlock(\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=3,\n stride=stride,\n padding=padding,\n dilation=dilation,\n groups=groups,\n bias=bias,\n use_bn=use_bn,\n bn_eps=bn_eps,\n activation=activation)\n else:\n return ConvBlock(\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=3,\n stride=stride,\n padding=padding,\n dilation=dilation,\n groups=groups,\n bias=bias,\n use_bn=use_bn,\n bn_eps=bn_eps,\n activation=activation)\n\n\ndef conv5x5_block(in_channels,\n out_channels,\n stride=1,\n padding=2,\n dilation=1,\n groups=1,\n bias=False,\n bn_eps=1e-5,\n activation=(lambda: nn.ReLU(inplace=True)),\n mode=''):\n \"\"\"\n 5x5 version of the standard convolution block.\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n stride : int or tuple/list of 2 int, default 1\n Strides of the convolution.\n padding : int or tuple/list of 2 int, default 2\n Padding value for convolution layer.\n dilation : int or tuple/list of 2 int, default 1\n Dilation value for convolution layer.\n groups : int, default 1\n Number of groups.\n bias : bool, default False\n Whether the layer uses a bias vector.\n bn_eps : float, default 1e-5\n Small float added to variance in Batch norm.\n activation : function or str or None, default nn.ReLU(inplace=True)\n Activation function or name of activation function.\n \"\"\"\n if mode == 'maml':\n return MetaConvBlock(\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=5,\n stride=stride,\n padding=padding,\n dilation=dilation,\n groups=groups,\n bias=bias,\n bn_eps=bn_eps,\n activation=activation)\n else:\n return ConvBlock(\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=5,\n stride=stride,\n padding=padding,\n dilation=dilation,\n groups=groups,\n bias=bias,\n bn_eps=bn_eps,\n activation=activation)\n\n\ndef conv7x7_block(in_channels,\n out_channels,\n stride=1,\n padding=3,\n bias=False,\n use_bn=True,\n activation=(lambda: nn.ReLU(inplace=True)),\n mode='maml'):\n \"\"\"\n 7x7 version of the standard convolution block.\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n stride : int or tuple/list of 2 int, default 1\n Strides of the convolution.\n padding : int or tuple/list of 2 int, default 3\n Padding value for convolution layer.\n bias : bool, default False\n Whether the layer uses a bias vector.\n use_bn : bool, default True\n Whether to use BatchNorm layer.\n activation : function or str or None, default nn.ReLU(inplace=True)\n Activation function or name of activation function.\n \"\"\"\n if mode == 'maml':\n return MetaSequential(MetaConvBlock(\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=7,\n stride=stride,\n padding=padding,\n bias=bias,\n use_bn=use_bn,\n activation=activation))\n else:\n return ConvBlock(\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=7,\n stride=stride,\n padding=padding,\n bias=bias,\n use_bn=use_bn,\n activation=activation)\n\n\ndef dwconv_block(in_channels,\n out_channels,\n kernel_size,\n stride=1,\n padding=1,\n dilation=1,\n bias=False,\n use_bn=True,\n bn_eps=1e-5,\n activation=(lambda: nn.ReLU(inplace=True))):\n \"\"\"\n Depthwise version of the standard convolution block.\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n kernel_size : int or tuple/list of 2 int\n Convolution window size.\n stride : int or tuple/list of 2 int, default 1\n Strides of the convolution.\n padding : int or tuple/list of 2 int, default 1\n Padding value for convolution layer.\n dilation : int or tuple/list of 2 int, default 1\n Dilation value for convolution layer.\n bias : bool, default False\n Whether the layer uses a bias vector.\n use_bn : bool, default True\n Whether to use BatchNorm layer.\n bn_eps : float, default 1e-5\n Small float added to variance in Batch norm.\n activation : function or str or None, default nn.ReLU(inplace=True)\n Activation function or name of activation function.\n \"\"\"\n return ConvBlock(\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=kernel_size,\n stride=stride,\n padding=padding,\n dilation=dilation,\n groups=out_channels,\n bias=bias,\n use_bn=use_bn,\n bn_eps=bn_eps,\n activation=activation)\n\n\ndef dwconv3x3_block(in_channels,\n out_channels,\n stride=1,\n padding=1,\n dilation=1,\n bias=False,\n bn_eps=1e-5,\n activation=(lambda: nn.ReLU(inplace=True))):\n \"\"\"\n 3x3 depthwise version of the standard convolution block.\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n stride : int or tuple/list of 2 int, default 1\n Strides of the convolution.\n padding : int or tuple/list of 2 int, default 1\n Padding value for convolution layer.\n dilation : int or tuple/list of 2 int, default 1\n Dilation value for convolution layer.\n bias : bool, default False\n Whether the layer uses a bias vector.\n bn_eps : float, default 1e-5\n Small float added to variance in Batch norm.\n activation : function or str or None, default nn.ReLU(inplace=True)\n Activation function or name of activation function.\n \"\"\"\n return dwconv_block(\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=3,\n stride=stride,\n padding=padding,\n dilation=dilation,\n bias=bias,\n bn_eps=bn_eps,\n activation=activation)\n\n\ndef dwconv5x5_block(in_channels,\n out_channels,\n stride=1,\n padding=2,\n dilation=1,\n bias=False,\n bn_eps=1e-5,\n activation=(lambda: nn.ReLU(inplace=True))):\n \"\"\"\n 5x5 depthwise version of the standard convolution block.\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n stride : int or tuple/list of 2 int, default 1\n Strides of the convolution.\n padding : int or tuple/list of 2 int, default 2\n Padding value for convolution layer.\n dilation : int or tuple/list of 2 int, default 1\n Dilation value for convolution layer.\n bias : bool, default False\n Whether the layer uses a bias vector.\n bn_eps : float, default 1e-5\n Small float added to variance in Batch norm.\n activation : function or str or None, default nn.ReLU(inplace=True)\n Activation function or name of activation function.\n \"\"\"\n return dwconv_block(\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=5,\n stride=stride,\n padding=padding,\n dilation=dilation,\n bias=bias,\n bn_eps=bn_eps,\n activation=activation)\n\n\nclass DwsConvBlock(nn.Module):\n \"\"\"\n Depthwise separable convolution block with BatchNorms and activations at each convolution layers.\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n kernel_size : int or tuple/list of 2 int\n Convolution window size.\n stride : int or tuple/list of 2 int\n Strides of the convolution.\n padding : int or tuple/list of 2 int\n Padding value for convolution layer.\n dilation : int or tuple/list of 2 int, default 1\n Dilation value for convolution layer.\n bias : bool, default False\n Whether the layer uses a bias vector.\n use_bn : bool, default True\n Whether to use BatchNorm layer.\n bn_eps : float, default 1e-5\n Small float added to variance in Batch norm.\n dw_activation : function or str or None, default nn.ReLU(inplace=True)\n Activation function after the depthwise convolution block.\n pw_activation : function or str or None, default nn.ReLU(inplace=True)\n Activation function after the pointwise convolution block.\n \"\"\"\n\n def __init__(self,\n in_channels,\n out_channels,\n kernel_size,\n stride,\n padding,\n dilation=1,\n bias=False,\n use_bn=True,\n bn_eps=1e-5,\n dw_activation=(lambda: nn.ReLU(inplace=True)),\n pw_activation=(lambda: nn.ReLU(inplace=True))):\n super(DwsConvBlock, self).__init__()\n self.dw_conv = dwconv_block(\n in_channels=in_channels,\n out_channels=in_channels,\n kernel_size=kernel_size,\n stride=stride,\n padding=padding,\n dilation=dilation,\n bias=bias,\n use_bn=use_bn,\n bn_eps=bn_eps,\n activation=dw_activation)\n self.pw_conv = conv1x1_block(\n in_channels=in_channels,\n out_channels=out_channels,\n bias=bias,\n use_bn=use_bn,\n bn_eps=bn_eps,\n activation=pw_activation)\n\n def forward(self, x):\n x = self.dw_conv(x)\n x = self.pw_conv(x)\n return x\n\n\ndef dwsconv3x3_block(in_channels,\n out_channels,\n stride=1,\n padding=1,\n dilation=1,\n bias=False,\n bn_eps=1e-5,\n dw_activation=(lambda: nn.ReLU(inplace=True)),\n pw_activation=(lambda: nn.ReLU(inplace=True))):\n \"\"\"\n 3x3 depthwise separable version of the standard convolution block.\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n stride : int or tuple/list of 2 int, default 1\n Strides of the convolution.\n padding : int or tuple/list of 2 int, default 1\n Padding value for convolution layer.\n dilation : int or tuple/list of 2 int, default 1\n Dilation value for convolution layer.\n bias : bool, default False\n Whether the layer uses a bias vector.\n bn_eps : float, default 1e-5\n Small float added to variance in Batch norm.\n dw_activation : function or str or None, default nn.ReLU(inplace=True)\n Activation function after the depthwise convolution block.\n pw_activation : function or str or None, default nn.ReLU(inplace=True)\n Activation function after the pointwise convolution block.\n \"\"\"\n return DwsConvBlock(\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=3,\n stride=stride,\n padding=padding,\n dilation=dilation,\n bias=bias,\n bn_eps=bn_eps,\n dw_activation=dw_activation,\n pw_activation=pw_activation)\n\n\nclass PreConvBlock(nn.Module):\n \"\"\"\n Convolution block with Batch normalization and ReLU pre-activation.\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n kernel_size : int or tuple/list of 2 int\n Convolution window size.\n stride : int or tuple/list of 2 int\n Strides of the convolution.\n padding : int or tuple/list of 2 int\n Padding value for convolution layer.\n dilation : int or tuple/list of 2 int, default 1\n Dilation value for convolution layer.\n bias : bool, default False\n Whether the layer uses a bias vector.\n return_preact : bool, default False\n Whether return pre-activation. It's used by PreResNet.\n activate : bool, default True\n Whether activate the convolution block.\n \"\"\"\n\n def __init__(self,\n in_channels,\n out_channels,\n kernel_size,\n stride,\n padding,\n dilation=1,\n bias=False,\n return_preact=False,\n activate=True):\n super(PreConvBlock, self).__init__()\n self.return_preact = return_preact\n self.activate = activate\n\n self.bn = nn.BatchNorm2d(num_features=in_channels)\n if self.activate:\n self.activ = nn.ReLU(inplace=True)\n self.conv = nn.Conv2d(\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=kernel_size,\n stride=stride,\n padding=padding,\n dilation=dilation,\n bias=bias)\n\n def forward(self, x):\n x = self.bn(x)\n if self.activate:\n x = self.activ(x)\n if self.return_preact:\n x_pre_activ = x\n x = self.conv(x)\n if self.return_preact:\n return x, x_pre_activ\n else:\n return x\n\n\ndef pre_conv1x1_block(in_channels,\n out_channels,\n stride=1,\n bias=False,\n return_preact=False,\n activate=True):\n \"\"\"\n 1x1 version of the pre-activated convolution block.\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n stride : int or tuple/list of 2 int, default 1\n Strides of the convolution.\n bias : bool, default False\n Whether the layer uses a bias vector.\n return_preact : bool, default False\n Whether return pre-activation.\n activate : bool, default True\n Whether activate the convolution block.\n \"\"\"\n return PreConvBlock(\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=1,\n stride=stride,\n padding=0,\n bias=bias,\n return_preact=return_preact,\n activate=activate)\n\n\ndef pre_conv3x3_block(in_channels,\n out_channels,\n stride=1,\n padding=1,\n dilation=1,\n return_preact=False,\n activate=True):\n \"\"\"\n 3x3 version of the pre-activated convolution block.\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n stride : int or tuple/list of 2 int, default 1\n Strides of the convolution.\n padding : int or tuple/list of 2 int, default 1\n Padding value for convolution layer.\n dilation : int or tuple/list of 2 int, default 1\n Dilation value for convolution layer.\n return_preact : bool, default False\n Whether return pre-activation.\n activate : bool, default True\n Whether activate the convolution block.\n \"\"\"\n return PreConvBlock(\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=3,\n stride=stride,\n padding=padding,\n dilation=dilation,\n return_preact=return_preact,\n activate=activate)\n\n\nclass InterpolationBlock(nn.Module):\n \"\"\"\n Interpolation upsampling block.\n Parameters:\n ----------\n scale_factor : float\n Multiplier for spatial size.\n mode : str, default 'bilinear'\n Algorithm used for upsampling.\n align_corners : bool, default True\n Whether to align the corner pixels of the input and output tensors\n \"\"\"\n\n def __init__(self,\n scale_factor,\n mode=\"bilinear\",\n align_corners=True):\n super(InterpolationBlock, self).__init__()\n self.scale_factor = scale_factor\n self.mode = mode\n self.align_corners = align_corners\n\n def forward(self, x):\n return F.interpolate(\n input=x,\n scale_factor=self.scale_factor,\n mode=self.mode,\n align_corners=self.align_corners)\n\n def __repr__(self):\n s = '{name}(scale_factor={scale_factor}, mode={mode}, align_corners={align_corners})'\n return s.format(\n name=self.__class__.__name__,\n scale_factor=self.scale_factor,\n mode=self.mode,\n align_corners=self.align_corners)\n\n def calc_flops(self, x):\n assert (x.shape[0] == 1)\n if self.mode == \"bilinear\":\n num_flops = 9 * x.numel()\n else:\n num_flops = 4 * x.numel()\n num_macs = 0\n return num_flops, num_macs\n\n\ndef channel_shuffle(x,\n groups):\n \"\"\"\n Channel shuffle operation from 'ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile Devices,'\n https://arxiv.org/abs/1707.01083.\n Parameters:\n ----------\n x : Tensor\n Input tensor.\n groups : int\n Number of groups.\n Returns\n -------\n Tensor\n Resulted tensor.\n \"\"\"\n batch, channels, height, width = x.size()\n # assert (channels % groups == 0)\n channels_per_group = channels // groups\n x = x.view(batch, groups, channels_per_group, height, width)\n x = torch.transpose(x, 1, 2).contiguous()\n x = x.view(batch, channels, height, width)\n return x\n\n\nclass ChannelShuffle(nn.Module):\n \"\"\"\n Channel shuffle layer. This is a wrapper over the same operation. It is designed to save the number of groups.\n Parameters:\n ----------\n channels : int\n Number of channels.\n groups : int\n Number of groups.\n \"\"\"\n\n def __init__(self,\n channels,\n groups):\n super(ChannelShuffle, self).__init__()\n # assert (channels % groups == 0)\n if channels % groups != 0:\n raise ValueError('channels must be divisible by groups')\n self.groups = groups\n\n def forward(self, x):\n return channel_shuffle(x, self.groups)\n\n\ndef channel_shuffle2(x,\n groups):\n \"\"\"\n Channel shuffle operation from 'ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile Devices,'\n https://arxiv.org/abs/1707.01083. The alternative version.\n Parameters:\n ----------\n x : Tensor\n Input tensor.\n groups : int\n Number of groups.\n Returns\n -------\n Tensor\n Resulted tensor.\n \"\"\"\n batch, channels, height, width = x.size()\n # assert (channels % groups == 0)\n channels_per_group = channels // groups\n x = x.view(batch, channels_per_group, groups, height, width)\n x = torch.transpose(x, 1, 2).contiguous()\n x = x.view(batch, channels, height, width)\n return x\n\n\nclass ChannelShuffle2(nn.Module):\n \"\"\"\n Channel shuffle layer. This is a wrapper over the same operation. It is designed to save the number of groups.\n The alternative version.\n Parameters:\n ----------\n channels : int\n Number of channels.\n groups : int\n Number of groups.\n \"\"\"\n\n def __init__(self,\n channels,\n groups):\n super(ChannelShuffle2, self).__init__()\n # assert (channels % groups == 0)\n if channels % groups != 0:\n raise ValueError('channels must be divisible by groups')\n self.groups = groups\n\n def forward(self, x):\n return channel_shuffle2(x, self.groups)\n\n\nclass SEBlock(nn.Module):\n \"\"\"\n Squeeze-and-Excitation block from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.\n Parameters:\n ----------\n channels : int\n Number of channels.\n reduction : int, default 16\n Squeeze reduction value.\n round_mid : bool, default False\n Whether to round middle channel number (make divisible by 8).\n activation : function, or str, or nn.Module, default 'relu'\n Activation function after the first convolution.\n out_activation : function, or str, or nn.Module, default 'sigmoid'\n Activation function after the last convolution.\n \"\"\"\n\n def __init__(self,\n channels,\n reduction=16,\n round_mid=False,\n mid_activation=(lambda: nn.ReLU(inplace=True)),\n out_activation=(lambda: nn.Sigmoid())):\n super(SEBlock, self).__init__()\n mid_channels = channels // reduction if not round_mid else round_channels(float(channels) / reduction)\n\n self.pool = nn.AdaptiveAvgPool2d(output_size=1)\n self.conv1 = conv1x1(\n in_channels=channels,\n out_channels=mid_channels,\n bias=True)\n self.activ = get_activation_layer(mid_activation)\n self.conv2 = conv1x1(\n in_channels=mid_channels,\n out_channels=channels,\n bias=True)\n self.sigmoid = get_activation_layer(out_activation)\n\n def forward(self, x):\n w = self.pool(x)\n w = self.conv1(w)\n w = self.activ(w)\n w = self.conv2(w)\n w = self.sigmoid(w)\n x = x * w\n return x\n\n\nclass IBN(nn.Module):\n \"\"\"\n Instance-Batch Normalization block from 'Two at Once: Enhancing Learning and Generalization Capacities via IBN-Net,'\n https://arxiv.org/abs/1807.09441.\n Parameters:\n ----------\n channels : int\n Number of channels.\n inst_fraction : float, default 0.5\n The first fraction of channels for normalization.\n inst_first : bool, default True\n Whether instance normalization be on the first part of channels.\n \"\"\"\n\n def __init__(self,\n channels,\n first_fraction=0.5,\n inst_first=True):\n super(IBN, self).__init__()\n self.inst_first = inst_first\n h1_channels = int(math.floor(channels * first_fraction))\n h2_channels = channels - h1_channels\n self.split_sections = [h1_channels, h2_channels]\n\n if self.inst_first:\n self.inst_norm = nn.InstanceNorm2d(\n num_features=h1_channels,\n affine=True)\n self.batch_norm = nn.BatchNorm2d(num_features=h2_channels)\n else:\n self.batch_norm = nn.BatchNorm2d(num_features=h1_channels)\n self.inst_norm = nn.InstanceNorm2d(\n num_features=h2_channels,\n affine=True)\n\n def forward(self, x):\n x1, x2 = torch.split(x, split_size_or_sections=self.split_sections, dim=1)\n if self.inst_first:\n x1 = self.inst_norm(x1.contiguous())\n x2 = self.batch_norm(x2.contiguous())\n else:\n x1 = self.batch_norm(x1.contiguous())\n x2 = self.inst_norm(x2.contiguous())\n x = torch.cat((x1, x2), dim=1)\n return x\n\n\nclass DualPathSequential(nn.Sequential):\n \"\"\"\n A sequential container for modules with dual inputs/outputs.\n Modules will be executed in the order they are added.\n Parameters:\n ----------\n return_two : bool, default True\n Whether to return two output after execution.\n first_ordinals : int, default 0\n Number of the first modules with single input/output.\n last_ordinals : int, default 0\n Number of the final modules with single input/output.\n dual_path_scheme : function\n Scheme of dual path response for a module.\n dual_path_scheme_ordinal : function\n Scheme of dual path response for an ordinal module.\n \"\"\"\n\n def __init__(self,\n return_two=True,\n first_ordinals=0,\n last_ordinals=0,\n dual_path_scheme=(lambda module, x1, x2: module(x1, x2)),\n dual_path_scheme_ordinal=(lambda module, x1, x2: (module(x1), x2))):\n super(DualPathSequential, self).__init__()\n self.return_two = return_two\n self.first_ordinals = first_ordinals\n self.last_ordinals = last_ordinals\n self.dual_path_scheme = dual_path_scheme\n self.dual_path_scheme_ordinal = dual_path_scheme_ordinal\n\n def forward(self, x1, x2=None):\n length = len(self._modules.values())\n for i, module in enumerate(self._modules.values()):\n if (i < self.first_ordinals) or (i >= length - self.last_ordinals):\n x1, x2 = self.dual_path_scheme_ordinal(module, x1, x2)\n else:\n x1, x2 = self.dual_path_scheme(module, x1, x2)\n if self.return_two:\n return x1, x2\n else:\n return x1\n\n\nclass Concurrent(nn.Sequential):\n \"\"\"\n A container for concatenation of modules on the base of the sequential container.\n Parameters:\n ----------\n axis : int, default 1\n The axis on which to concatenate the outputs.\n stack : bool, default False\n Whether to concatenate tensors along a new dimension.\n \"\"\"\n\n def __init__(self,\n axis=1,\n stack=False):\n super(Concurrent, self).__init__()\n self.axis = axis\n self.stack = stack\n\n def forward(self, x):\n out = []\n for module in self._modules.values():\n out.append(module(x))\n if self.stack:\n out = torch.stack(tuple(out), dim=self.axis)\n else:\n out = torch.cat(tuple(out), dim=self.axis)\n return out\n\n\nclass SequentialConcurrent(nn.Sequential):\n \"\"\"\n A sequential container with concatenated outputs.\n Modules will be executed in the order they are added.\n Parameters:\n ----------\n axis : int, default 1\n The axis on which to concatenate the outputs.\n stack : bool, default False\n Whether to concatenate tensors along a new dimension.\n cat_input : bool, default True\n Whether to concatenate input tensor.\n \"\"\"\n\n def __init__(self,\n axis=1,\n stack=False,\n cat_input=True):\n super(SequentialConcurrent, self).__init__()\n self.axis = axis\n self.stack = stack\n self.cat_input = cat_input\n\n def forward(self, x):\n out = [x] if self.cat_input else []\n for module in self._modules.values():\n x = module(x)\n out.append(x)\n if self.stack:\n out = torch.stack(tuple(out), dim=self.axis)\n else:\n out = torch.cat(tuple(out), dim=self.axis)\n return out\n\n\nclass ParametricSequential(nn.Sequential):\n \"\"\"\n A sequential container for modules with parameters.\n Modules will be executed in the order they are added.\n \"\"\"\n\n def __init__(self, *args):\n super(ParametricSequential, self).__init__(*args)\n\n def forward(self, x, **kwargs):\n for module in self._modules.values():\n x = module(x, **kwargs)\n return x\n\n\nclass ParametricConcurrent(nn.Sequential):\n \"\"\"\n A container for concatenation of modules with parameters.\n Parameters:\n ----------\n axis : int, default 1\n The axis on which to concatenate the outputs.\n \"\"\"\n\n def __init__(self, axis=1):\n super(ParametricConcurrent, self).__init__()\n self.axis = axis\n\n def forward(self, x, **kwargs):\n out = []\n for module in self._modules.values():\n out.append(module(x, **kwargs))\n out = torch.cat(tuple(out), dim=self.axis)\n return out\n\n\nclass Hourglass(nn.Module):\n \"\"\"\n A hourglass block.\n Parameters:\n ----------\n down_seq : nn.Sequential\n Down modules as sequential.\n up_seq : nn.Sequential\n Up modules as sequential.\n skip_seq : nn.Sequential\n Skip connection modules as sequential.\n merge_type : str, default 'add'\n Type of concatenation of up and skip outputs.\n return_first_skip : bool, default False\n Whether return the first skip connection output. Used in ResAttNet.\n \"\"\"\n\n def __init__(self,\n down_seq,\n up_seq,\n skip_seq,\n merge_type=\"add\",\n return_first_skip=False):\n super(Hourglass, self).__init__()\n assert (len(up_seq) == len(down_seq))\n assert (len(skip_seq) == len(down_seq))\n assert (merge_type in [\"add\"])\n self.merge_type = merge_type\n self.return_first_skip = return_first_skip\n self.depth = len(down_seq)\n\n self.down_seq = down_seq\n self.up_seq = up_seq\n self.skip_seq = skip_seq\n\n def forward(self, x, **kwargs):\n y = None\n down_outs = [x]\n for down_module in self.down_seq._modules.values():\n x = down_module(x)\n down_outs.append(x)\n for i in range(len(down_outs)):\n if i != 0:\n y = down_outs[self.depth - i]\n skip_module = self.skip_seq[self.depth - i]\n y = skip_module(y)\n if (y is not None) and (self.merge_type == \"add\"):\n x = x + y\n if i != len(down_outs) - 1:\n up_module = self.up_seq[self.depth - 1 - i]\n x = up_module(x)\n if self.return_first_skip:\n return x, y\n else:\n return x\n\n\nclass SesquialteralHourglass(nn.Module):\n \"\"\"\n A sesquialteral hourglass block.\n Parameters:\n ----------\n down1_seq : nn.Sequential\n The first down modules as sequential.\n skip1_seq : nn.Sequential\n The first skip connection modules as sequential.\n up_seq : nn.Sequential\n Up modules as sequential.\n skip2_seq : nn.Sequential\n The second skip connection modules as sequential.\n down2_seq : nn.Sequential\n The second down modules as sequential.\n merge_type : str, default 'con'\n Type of concatenation of up and skip outputs.\n \"\"\"\n\n def __init__(self,\n down1_seq,\n skip1_seq,\n up_seq,\n skip2_seq,\n down2_seq,\n merge_type=\"cat\"):\n super(SesquialteralHourglass, self).__init__()\n assert (len(down1_seq) == len(up_seq))\n assert (len(down1_seq) == len(down2_seq))\n assert (len(skip1_seq) == len(skip2_seq))\n assert (len(down1_seq) == len(skip1_seq) - 1)\n assert (merge_type in [\"cat\", \"add\"])\n self.merge_type = merge_type\n self.depth = len(down1_seq)\n\n self.down1_seq = down1_seq\n self.skip1_seq = skip1_seq\n self.up_seq = up_seq\n self.skip2_seq = skip2_seq\n self.down2_seq = down2_seq\n\n def _merge(self, x, y):\n if y is not None:\n if self.merge_type == \"cat\":\n x = torch.cat((x, y), dim=1)\n elif self.merge_type == \"add\":\n x = x + y\n return x\n\n def forward(self, x, **kwargs):\n y = self.skip1_seq[0](x)\n skip1_outs = [y]\n for i in range(self.depth):\n x = self.down1_seq[i](x)\n y = self.skip1_seq[i + 1](x)\n skip1_outs.append(y)\n x = skip1_outs[self.depth]\n y = self.skip2_seq[0](x)\n skip2_outs = [y]\n for i in range(self.depth):\n x = self.up_seq[i](x)\n y = skip1_outs[self.depth - 1 - i]\n x = self._merge(x, y)\n y = self.skip2_seq[i + 1](x)\n skip2_outs.append(y)\n x = self.skip2_seq[self.depth](x)\n for i in range(self.depth):\n x = self.down2_seq[i](x)\n y = skip2_outs[self.depth - 1 - i]\n x = self._merge(x, y)\n return x\n\n\nclass MultiOutputSequential(nn.Sequential):\n \"\"\"\n A sequential container with multiple outputs.\n Modules will be executed in the order they are added.\n \"\"\"\n\n def __init__(self):\n super(MultiOutputSequential, self).__init__()\n\n def forward(self, x):\n outs = []\n for module in self._modules.values():\n x = module(x)\n if hasattr(module, \"do_output\") and module.do_output:\n outs.append(x)\n return [x] + outs\n\n\nclass Flatten(nn.Module):\n \"\"\"\n Simple flatten module.\n \"\"\"\n\n def forward(self, x):\n return x.view(x.size(0), -1)\n" ]
[ [ "torch.sigmoid", "torch.transpose", "torch.nn.ReLU6", "torch.cat", "torch.split", "torch.nn.functional.relu6", "torch.nn.Conv2d", "torch.nn.Sigmoid", "torch.nn.AdaptiveAvgPool2d", "torch.nn.InstanceNorm2d", "torch.nn.functional.interpolate", "torch.nn.BatchNorm2d", "torch.nn.ReLU" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
invertedv/utilities
[ "42c331893b1beee73b2d21df6cb2bad73b872bb7" ]
[ "muti/glmu.py" ]
[ "from muti import genu\nimport clickhouse_driver\nimport pandas as pd\nfrom modeling.glm import glm\nimport numpy as np\nimport math\n\n\ndef build_model_formula(features_dict: dict, target: str):\n \"\"\"\n Builds the model formula for glm from modeling based on the features_dict specification.\n Does not included embedded features\n \n :param features_dict: features dictionary\n :param target: dependent variable\n :return: model formula\n :rtype str\n \"\"\"\n ms = target + '~'\n extra = ''\n for feature in features_dict:\n if features_dict[feature][0] == 'cts':\n ms += extra + feature\n elif features_dict[feature][0] == 'spl':\n ms += extra + 'h(' + feature + ',' + features_dict[feature][1] + ',0)'\n elif features_dict[feature][0] == 'cat':\n ms += extra + 'c(' + feature + ',' + features_dict[feature][2] + ')'\n extra = ' + '\n return ms\n\n\ndef incr_build(model: str, target_var: str, start_list: list, add_list: list, get_data_fn, sample_size: int,\n client: clickhouse_driver.Client, global_valid_df_in: pd.DataFrame, family='normal'):\n\n \"\"\"\n This function builds a sequence of GLM models. The get_data_fn takes a list of values as contained in\n start_list and add_list and returns data subset to those values. The initial model is built on the\n values of start_list and then evaluated on the data subset to the first value of add_list.\n\n At the next step, the data in the first element of add_list is added to the start_list data, the model\n is updated and the evaluation is conducted on the second element of add_list.\n\n This function is the GLM counterpart to incr_build\n\n :param model: model specification for glm\n :param target_var: response variable we're modeling\n :param start_list: list of (general) time periods for model build for the first model build\n :param add_list: list of out-of-time periods to evaluate\n :param get_data_fn: function to get a pandas DataFrame of data to work on\n :param sample_size: size of pandas DataFrames to get\n :param client: db connector\n :param family: family of the model ('normal' or 'binomial')\n :param global_valid_df_in: pandas DataFrame covering all the values of add_list for validation\n :return: lists of out-of-sample values:\n add_list\n rmse root mean squared error\n corr correlation\n \"\"\"\n \n build_list = start_list\n global_valid_df = global_valid_df_in.copy()\n global_valid_df['model_glm_inc'] = np.full((global_valid_df.shape[0]), 0.0)\n rmse_valid = []\n corr_valid = []\n segs = []\n for j, valid in enumerate(add_list):\n segs += [valid]\n model_df = get_data_fn(build_list, sample_size, client)\n valid_df = get_data_fn([valid], sample_size, client)\n print('Data sizes for out-of-sample value {0}: build {1}, validate {2}'.format(valid, model_df.shape[0],\n valid_df.shape[0]))\n # print('Build list: {0}'.format(build_list))\n \n glm_model = glm(model, model_df, family=family)\n build_list += [valid]\n\n gyh = glm_model.predict(global_valid_df)\n i = global_valid_df['vintage'] == valid\n global_valid_df.loc[i, 'model_glm_inc'] = gyh[i]\n\n yh = glm_model.predict(valid_df)\n res = valid_df[target_var] - np.array(yh).flatten()\n rmse_valid += [math.sqrt(np.square(res).mean())]\n valid_df['yh'] = yh\n cor = genu.r_square(valid_df['yh'], valid_df[target_var])\n corr_valid += [cor]\n \n return segs, rmse_valid, corr_valid, global_valid_df\n" ]
[ [ "numpy.square", "numpy.array", "numpy.full" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
nelhage/data
[ "50a1ab91b786c9f89a8ff6ff10ea57ea5335490d" ]
[ "src/pipelines/epidemiology/nl_authority.py" ]
[ "# Copyright 2020 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\nfrom datetime import datetime\nfrom typing import Any, Dict, List\nfrom pandas import DataFrame, concat, merge\nfrom lib.pipeline import DataSource\nfrom lib.time import datetime_isoformat\nfrom lib.utils import grouped_diff\n\n\nclass NetherlandsDataSource(DataSource):\n def parse_dataframes(\n self, dataframes: List[DataFrame], aux: Dict[str, DataFrame], **parse_opts\n ) -> DataFrame:\n\n # Rename the appropriate columns\n data = dataframes[0].rename(\n columns={\n \"Date_of_report\": \"date\",\n \"Municipality_code\": \"subregion2_code\",\n \"Municipality_name\": \"subregion2_name\",\n \"Province\": \"subregion1_name\",\n \"Total_reported\": \"confirmed\",\n \"Hospital_admission\": \"hospitalized\",\n \"Deceased\": \"deceased\",\n }\n )\n\n # Drop data without a clear demarcation\n data = data[~data.subregion1_name.isna()]\n data = data[~data.subregion2_code.isna()]\n data = data[~data.subregion2_name.isna()]\n\n # Get date in ISO format\n data.date = data.date.apply(lambda x: datetime.fromisoformat(x).date().isoformat())\n\n # Make sure the region code is zero-padded and without prefix\n data[\"subregion2_code\"] = data[\"subregion2_code\"].apply(lambda x: x[2:])\n\n data = data.drop(columns=[\"subregion1_name\", \"subregion2_name\"])\n data = data.merge(aux[\"metadata\"], on=\"subregion2_code\")\n\n # We only need to keep key-date pair for identification\n data = data[[\"date\", \"key\", \"confirmed\", \"deceased\", \"hospitalized\"]]\n\n # Compute the daily counts\n data = grouped_diff(data, [\"key\", \"date\"])\n\n # Group by level 2 region, and add the parts\n l2 = data.copy()\n l2[\"key\"] = l2.key.apply(lambda x: x[:5])\n l2 = l2.groupby([\"key\", \"date\"]).sum().reset_index()\n\n # Group by country level, and add the parts\n l1 = l2.copy().drop(columns=[\"key\"])\n l1 = l1.groupby(\"date\").sum().reset_index()\n l1[\"key\"] = \"NL\"\n\n # Output the results\n return concat([l1, l2, data])\n" ]
[ [ "pandas.concat" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
BensonRen/idlm_Ben
[ "0d83780232d6341575daf88792959542aef82132", "5ba93da0d9b5d9313a9ce968e3593fefd0a05fc9", "0d83780232d6341575daf88792959542aef82132" ]
[ "Pytorch/class_wrapper.py", "Backprop/Backprop_network_maker.py", "VAE/evaluate.py" ]
[ "\"\"\"\nThe class wrapper for the networks\n\"\"\"\n# Built-in\nimport os\nimport time\n\n# Torch\nimport torch\nfrom torch import nn\nfrom torch.utils.tensorboard import SummaryWriter\nfrom torchsummary import summary\n\n# Libs\nimport numpy as np\n\n# Own module\n\n\nclass Network(object):\n def __init__(self, model_fn, flags, train_loader, test_loader,\n ckpt_dir=os.path.join(os.path.abspath(''), 'models'),\n inference_mode=False, saved_model=None):\n self.model_fn = model_fn # The model maker function\n self.flags = flags # The Flags containing the specs\n if inference_mode: # If inference mode, use saved model\n self.ckpt_dir = os.path.join(ckpt_dir, saved_model)\n self.saved_model = saved_model\n else: # training mode, create a new ckpt folder\n self.ckpt_dir = os.path.join(ckpt_dir, time.strftime('%Y%m%d_%H%M%S', time.localtime()))\n self.model = self.create_model() # The model itself\n self.loss = self.make_loss() # The loss function\n self.optm = self.make_optimizer() # The optimizer\n self.train_loader = train_loader # The train data loader\n self.test_loader = test_loader # The test data loader\n self.log = SummaryWriter(self.ckpt_dir) # Create a summary writer for keeping the summary to the tensor board\n self.best_validation_loss = float('inf') # Set the BVL to large number\n\n def create_model(self):\n \"\"\"\n Function to create the network module from provided model fn and flags\n :return: the created nn module\n \"\"\"\n model = self.model_fn(self.flags)\n #summary(model, input_size=(128, 8))\n print(model)\n return model\n\n def make_loss(self, logit=None, labels=None):\n \"\"\"\n Create a tensor that represents the loss. This is consistant both at training time \\\n and inference time for Backward model\n :param logit: The output of the network\n :return: the total loss\n \"\"\"\n if logit is None:\n return None\n MSE_loss = nn.functional.mse_loss(logit, labels) # The MSE Loss of the\n BDY_loss = 0 # Implemenation later\n return MSE_loss + BDY_loss\n\n def make_optimizer(self):\n \"\"\"\n Make the corresponding optimizer from the flags. Only below optimizers are allowed. Welcome to add more\n :return:\n \"\"\"\n if self.flags.optim == 'Adam':\n op = torch.optim.Adam(self.model.parameters(), lr=self.flags.lr, weight_decay=self.flags.reg_scale)\n elif self.flags.optim == 'RMSprop':\n op = torch.optim.RMSprop(self.model.parameters(), lr=self.flags.lr, weight_decay=self.flags.reg_scale)\n elif self.flags.optim == 'SGD':\n op = torch.optim.SGD(self.model.parameters(), lr=self.flags.lr, weight_decay=self.flags.reg_scale)\n else:\n raise Exception(\"Your Optimizer is neither Adam, RMSprop or SGD, please change in param or contact Ben\")\n return op\n\n def save(self):\n \"\"\"\n Saving the model to the current check point folder with name best_model.pt\n :return: None\n \"\"\"\n #torch.save(self.model.state_dict, os.path.join(self.ckpt_dir, 'best_model_state_dict.pt'))\n torch.save(self.model, os.path.join(self.ckpt_dir, 'best_model.pt'))\n\n def load(self):\n \"\"\"\n Loading the model from the check point folder with name best_model.pt\n :return:\n \"\"\"\n #self.model.load_state_dict(torch.load(os.path.join(self.ckpt_dir, 'best_model_state_dict.pt')))\n self.model.load(torch.load(os.path.join(self.ckpt_dir, 'best_model.pt')))\n\n def train(self):\n \"\"\"\n The major training function. This would start the training using information given in the flags\n :return: None\n \"\"\"\n cuda = True if torch.cuda.is_available() else False\n if cuda:\n self.model.cuda()\n for epoch in range(self.flags.train_step):\n # Set to Training Mode\n train_loss = 0\n self.model.train()\n for j, (geometry, spectra) in enumerate(self.train_loader):\n if cuda:\n geometry = geometry.cuda() # Put data onto GPU\n spectra = spectra.cuda() # Put data onto GPU\n self.optm.zero_grad() # Zero the gradient first\n logit = self.model(geometry) # Get the output\n loss = self.make_loss(logit, spectra) # Get the loss tensor\n loss.backward() # Calculate the backward gradients\n self.optm.step() # Move one step the optimizer\n train_loss += loss # Aggregate the loss\n\n if epoch % self.flags.eval_step: # For eval steps, do the evaluations and tensor board\n # Record the training loss to the tensorboard\n train_avg_loss = train_loss.data.numpy() / (j+1)\n self.log.add_scalar('Loss/train', train_avg_loss, epoch)\n\n # Set to Evaluation Mode\n self.model.eval()\n print(\"Doing Evaluation on the model now\")\n test_loss = 0\n for j, (geometry, spectra) in enumerate(self.test_loader): # Loop through the eval set\n if cuda:\n geometry = geometry.cuda()\n spectra = spectra.cuda()\n logit = self.model(geometry)\n loss = self.make_loss(logit, spectra) # compute the loss\n test_loss += loss # Aggregate the loss\n\n # Record the testing loss to the tensorboard\n test_avg_loss = test_loss.data.numpy() / (j+1)\n self.log.add_scalar('Loss/test', test_avg_loss, epoch)\n\n print(\"This is Epoch %d, training loss %.5f, validation loss %.5f\" \\\n % (epoch, train_avg_loss, test_avg_loss ))\n\n # Model improving, save the model down\n if test_avg_loss < self.best_validation_loss:\n self.best_validation_loss = test_avg_loss\n self.save()\n print(\"Saving the model down...\")\n\n if self.best_validation_loss < self.flags.stop_threshold:\n print(\"Training finished EARLIER at epoch %d, reaching loss of %.5f\" %\\\n (epoch, self.best_validation_loss))\n return None\n\n def evaluate(self, save_dir='data/'):\n self.load()\n self.model.eval() # Evaluation mode\n\n # Get the file names\n Ypred_file = os.path.join(save_dir, 'test_Ypred_{}.csv'.format(self.saved_model))\n Xtruth_file = os.path.join(save_dir, 'test_Xtruth_{}.csv'.format(self.saved_model))\n Ytruth_file = os.path.join(save_dir, 'test_Ytruth_{}.csv'.format(self.saved_model))\n #Xpred_file = os.path.join(save_dir, 'test_Xpred_{}.csv'.format(self.saved_model)) # For pure forward model, there is no Xpred\n\n # Open those files to append\n with open(Xtruth_file,'a') as fxt,open(Ytruth_file, 'a') as fyt, open(Ypred_file,'a') as fyp:\n # Loop through the eval data and evaluate\n for ind, (geometry, spectra) in enumerate(self.test_loader):\n logits = self.model(geometry)\n np.savetxt(fxt, geometry.numpy(), fmt='%.3f')\n np.savetxt(fyt, spectra.numpy(), fmt='%.3f')\n np.savetxt(fyp, logits.numpy(), fmt='%.3f')\n\n\n", "import os\nimport time\nimport inspect #The built-in lib of Python, inspecting the live objects \nimport numpy as np\nimport tensorflow as tf\nimport struct\nimport pandas as pd\nimport model_maker\nimport time_recorder\nclass BackPropCnnNetwork(object):\n def __init__(self, features, labels, model_fn, batch_size,\n clip=0,forward_fc_filters=(5, 10, 15),tconv_Fnums=(4,4), tconv_dims=(60, 120, 240), \n tconv_filters=(1, 1, 1),n_filter=5, n_branch=3,\n reg_scale=.001, learn_rate=1e-4, decay_step=200, decay_rate=0.1,\n ckpt_dir=os.path.join(os.path.abspath(''), 'models'),\n make_folder=True, geoboundary = [30, 55, 42, 52]):\n \n \"\"\"\n Initialize a Network class\n :param features: input features\n :param labels: input labels\n :param model_fn: model definition function, can be customized by user\n :param batch_size: batch size\n :param fc_filters: #neurons in each fully connected layers\n :param tconv_dims: dimensionality of data after each transpose convolution\n :param tconv_filters: #filters at each transpose convolution\n :param learn_rate: learning rate\n :param decay_step: decay learning rate at this number of steps\n :param decay_rate: decay learn rate by multiplying this factor\n :param ckpt_dir: checkpoint directory, default to ./models\n :param make_folder: if True, create the directory if not exists\n \"\"\"\n self.features = features\n self.labels = labels\n self.model_fn = model_fn\n self.batch_size = batch_size\n self.clip = clip\n assert len(tconv_dims) == len(tconv_filters)\n assert len(tconv_Fnums) == len(tconv_filters)\n self.tconv_Fnums = tconv_Fnums\n self.tconv_dims = tconv_dims\n self.tconv_filters = tconv_filters\n self.best_validation_loss = float(\"inf\")\n self.n_filter = n_filter\n self.n_branch = n_branch\n self.forward_fc_filters = forward_fc_filters\n self.reg_scale = reg_scale\n self.geoboundary = geoboundary\n self.global_step = tf.Variable(0, dtype=tf.int64, trainable=False, name='global_step')\n self.learn_rate = tf.train.exponential_decay(learn_rate, self.global_step,\n decay_step, decay_rate, staircase=True)\n\n self.ckpt_dir = os.path.join(ckpt_dir, time.strftime('%Y%m%d_%H%M%S', time.localtime()))\n if not os.path.exists(self.ckpt_dir) and make_folder:\n os.makedirs(self.ckpt_dir)\n self.write_record()\n\n self.forward_in, self.logits, self.merged_summary_op, self.geometry_variable,\\\n self.train_Forward, self.Boundary_loss = self.create_graph()\n #self.model = tf.keras.Model(self.features, self.logits,name = 'Backward')\n if self.labels==[]:\n print('labels list is empty')\n else:\n self.loss, self.mse_loss, self.reg_loss, self.bdy_loss = self.make_loss()\n self.optm = self.make_optimizer()\n self.backprop_optm = self.make_backprop_optimizer()\n \n def create_graph(self):\n \"\"\"\n Create model graph\n :return: outputs of the last layer\n \"\"\"\n return self.model_fn(self.features, self.batch_size, \n self.clip, self.forward_fc_filters, self.tconv_Fnums,\n self.tconv_dims, self.tconv_filters,\n self.n_filter, self.n_branch, self.reg_scale, self.geoboundary)\n \n\n def write_record(self):\n \"\"\"\n Write records, including model_fn, parameters into the checkpoint folder\n These records can be used to reconstruct & repeat experiments\n :return:\n \"\"\"\n #insepect.getsource = return the text of the source code for an object\n model_fn_str = inspect.getsource(self.model_fn) #Get the text of the source code of the object\n params = inspect.getmembers(self, lambda a: not inspect.isroutine(a)) #get all the members that are not a routine (function)\n params = [a for a in params if not (a[0].startswith('__') and a[0].endswith('__'))]\n with open(os.path.join(self.ckpt_dir, 'model_meta.txt'), 'w+') as f:\n f.write('model_fn:\\n')\n f.writelines(model_fn_str)\n f.write('\\nparams:\\n')\n for key, val in params:\n f.write('{}: {}\\n'.format(key, val))\n\n def make_loss(self):\n \"\"\"\n Make cross entropy loss for forward part of the model\n :return: mean cross entropy loss of the batch\n \"\"\"\n with tf.variable_scope('loss'):\n mse_loss = tf.losses.mean_squared_error(self.labels, self.logits) #reconstruction loss\n reg_loss = tf.losses.get_regularization_loss() #regularizaiton loss\n bdy_loss = self.Boundary_loss #boundary loss\n total_loss = mse_loss + reg_loss + bdy_loss #Total loss\n return total_loss, mse_loss, reg_loss, bdy_loss\n \n def make_optimizer(self):\n \"\"\"\n Make an Adam optimizer with the learning rate defined when the class is initialized\n :return: an AdamOptimizer\n \"\"\"\n return tf.train.AdamOptimizer(learning_rate=self.learn_rate).minimize(self.loss, self.global_step)\n \n def make_backprop_optimizer(self):\n \"\"\"\n Make an Backproping optimizer with the learning rate defined when the class is initialized\n :return: an AdamOptimizer\n \"\"\"\n return tf.train.AdamOptimizer(learning_rate=self.learn_rate * 5000).minimize(self.loss, \n self.global_step,\n var_list = [self.geometry_variable])\n\n def save(self, sess):\n \"\"\"\n Save the model to the checkpoint directory\n :param sess: current running session\n :return:\n \"\"\"\n saver = tf.train.Saver(var_list=tf.global_variables(), max_to_keep=1)\n saver.save(sess, os.path.join(self.ckpt_dir, 'model.ckpt'))\n\n def load(self, sess, ckpt_dir):\n \"\"\"\n Load the model from the checkpoint directory\n :param sess: current running session\n :param ckpt_dir: checkpoint directory\n :return:\n \"\"\"\n sess.run([tf.global_variables_initializer(), tf.local_variables_initializer()])\n saver = tf.train.Saver(var_list=tf.global_variables())\n latest_check_point = tf.train.latest_checkpoint(ckpt_dir)\n saver.restore(sess, latest_check_point)\n print('loaded {}'.format(latest_check_point))\n\n def train(self, train_init_op, step_num, forward_hooks,\\\n write_summary=False,load_forward_ckpt = None):\n \"\"\"\n Train the model with step_num steps\n First train the forward model and then the tandem part\n :param train_init_op: training dataset init operation\n :param step_num: number of steps to train\n :param hooks: hooks for monitoring the training process\n :param write_summary: write summary into tensorboard or not\n :return:\n \"\"\"\n with tf.Session() as sess:\n sess.run([tf.global_variables_initializer(), tf.local_variables_initializer()])\n if load_forward_ckpt != None:\n self.load(sess, load_forward_ckpt)\n if write_summary:\n summary_writer = tf.summary.FileWriter(self.ckpt_dir, sess.graph)\n else:\n summary_writer = None\n \n print(\"Training forward model now:\")\n \n assign_true_op = self.train_Forward.assign(True)\n sess.run([train_init_op, assign_true_op])\n \n ##Train the forward model\n for i in range(int(step_num)):\n sess.run([train_init_op, assign_true_op])\n [feature, optm_out] = sess.run([self.features ,self.optm])\n if (i % 500 == 0):\n print(\"Feature now is:\", feature[0,:])\n for hook in forward_hooks:\n hook.run(sess, writer=summary_writer)\n if forward_hooks[-1].save: #If the hook tells to save the model, then save it\n self.save(sess)\n self.best_validation_loss = forward_hooks[-1].best_validation_loss\n if forward_hooks[-1].stop:\n break\n \n def evaluate_one(self, target_spectra, back_prop_epoch, sess, verb_step, stop_thres, point_index):\n \"\"\"\n The function that evaluate one single given target spectra and return the results\n :param target_spectra: The target spectra to back prop towards. Should be only 1 row\n :param back_prop_epoch: #epochs to do the gradient descend\n :param sess: The current session to do the back prop\n \"\"\"\n\n #Set up target output\n print(\"shape before repeat\",np.shape(target_spectra.values))\n target_spectra_repeat = np.repeat(np.reshape(target_spectra.values,(1,-1)), self.batch_size, axis = 0)\n print(\"Size of the target spectra repeat\", np.shape(target_spectra_repeat))\n #target_spectra_dataset = tf.data.Dataset.from_tensor_slices(target_spectra_repeat)\n #target_spectra_dataset = target_spectra_dataset.repeat()\n for i in range(back_prop_epoch):\n loss_back_prop, optm_out, inferred_spectra = sess.run([self.loss, self.backprop_optm, self.logits], \n feed_dict={self.labels: target_spectra_repeat}) \n if (i % verb_step == 0):\n print(\"Loss at inference step{} : {}\".format(i,loss_back_prop))\n if (loss_back_prop < stop_thres):\n print(\"Loss is lower than the threshold{}, inference stop\".format(stop_thres))\n break\n #Then it is time to get the best performing one\n Xpred, Ypred, loss = sess.run([self.forward_in, self.logits, self.loss], feed_dict={self.labels: target_spectra_repeat})\n loss_list = np.sum(np.square(Ypred - target_spectra_repeat), axis = 1) / self.batch_size\n best_estimate_index = np.argmin(loss_list)\n print('best error is {}, in best estimate-indx is {}, squared loss is {}'.format(min(loss_list), \n loss_list[best_estimate_index],\n loss))\n print('Best error for point {} is having absolute error of {}'.format(point_index, loss_list[best_estimate_index]))\n Xpred_best = Xpred[best_estimate_index,:]\n Ypred_best = Ypred[best_estimate_index,:]\n # print(\"Xpred_best:\", Xpred_best)\n return Xpred_best, Ypred_best\n \n\n def evaluate(self, valid_init_op, train_init_op, ckpt_dir,verb_step = 500, \n back_prop_epoch = 10000, stop_thres = 1e-3,\n save_file=os.path.join(os.path.abspath(''), 'data'),\n model_name='', write_summary=False, eval_forward = False,\n time_recorder = None):\n \"\"\"\n Evaluate the model, and save predictions to save_file\n :param valid_init_op: validation dataset init operation\n :param checkpoint directory\n :param save_file: full path to pred file\n :param model_name: name of the model\n :param eval_forward\n :return:\n \"\"\"\n assign_eval_forward_op = self.train_Forward.assign(eval_forward) #Change the graph accordingly\n \n \n with tf.Session() as sess:\n self.load(sess, ckpt_dir)\n\n if write_summary:\n writer_path = os.path.join(ckpt_dir, 'evalSummary')\n print(\"summary_writer directory is {}\".format(writer_path))\n activation_summary_writer = tf.summary.FileWriter(writer_path, sess.graph)\n else:\n activation_summary_writer = None\n \n sess.run([valid_init_op, assign_eval_forward_op])\n pred_file = os.path.join(save_file, 'test_Ypred_{}.csv'.format(model_name))\n feature_file = os.path.join(save_file, 'test_Xtruth_{}.csv'.format(model_name))\n truth_file = os.path.join(save_file, 'test_Ytruth_{}.csv'.format(model_name))\n feat_file = os.path.join(save_file, 'test_Xpred_{}.csv'.format(model_name))\n \n eval_cnt = 0\n start_pred = time.time()\n try:\n while True:\n with open(feature_file, 'a') as f0, open(truth_file, 'a') as f2: \n Xtruth, Ytruth = sess.run([self.features, self.labels])\n np.savetxt(f0, Xtruth, fmt='%.3f')\n np.savetxt(f2, Ytruth, fmt='%.3f')\n except tf.errors.OutOfRangeError:\n Ytruth = pd.read_csv(truth_file,header= None, delimiter= ' ')\n h ,w = Ytruth.values.shape\n print(h)\n \n #inference time\n with open(feat_file, 'a') as f1, open(pred_file, 'a') as f3: \n #First initialize the starting points\n RN = model_maker.initializeInBoundary(self.geometry_variable.shape, self.geoboundary) \n print(\"Random number within range\", self.geoboundary)\n assign_var_op = self.geometry_variable.assign(RN) #Assign the variable\n sess.run([assign_var_op, train_init_op])\n for i in range(h):\n sess.run([assign_var_op, train_init_op])\n Xpred, Ypred = self.evaluate_one(Ytruth.iloc[i,:], back_prop_epoch, sess, verb_step, stop_thres, i)\n Xpred = np.reshape(Xpred, (1, -1))\n Ypred = np.reshape(Ypred, (1, -1))\n #print(\"Xpred is:\", Xpred)\n np.savetxt(f1, Xpred, fmt='%.3f')\n np.savetxt(f3, Ypred, fmt='%.3f')\n if (time_recorder != None):\n time_recorder.record(write_number = i)\n return pred_file, truth_file\n\n\n \"\"\"\n def predict(self, pred_init_op, ckpt_dir, save_file=os.path.join(os.path.abspath(''), 'dataGrid'),\n model_name=''):\n \"\"\"\"\"\"\n Evaluate the model, and save predictions to save_file\n :param ckpt_dir directory\n :param save_file: full path to pred file\n :param model_name: name of the model\n :return:\n \"\"\"\"\"\"\n with tf.Session() as sess:\n self.load(sess, ckpt_dir)\n sess.run(pred_init_op)\n pred_file = os.path.join(save_file, 'test_pred_{}.csv'.format(model_name))\n feat_file = os.path.join(save_file, 'test_feat_{}'.format(model_name) + '.csv')\n with open(pred_file, 'w'):\n pass\n try:\n start = time.time()\n cnt = 1\n while True:\n with open(pred_file, 'a') as f1: #, open(feat_file, 'a') as f2\n pred_batch, features_batch = sess.run([self.logits, self.features])\n for pred, features in zip(pred_batch, features_batch):\n pred_str = [str(el) for el in pred]\n features_str = [ str(el) for el in features]\n f1.write(','.join(pred_str)+'\\n')\n # f2.write(','.join(features_str)+'\\n')\n if (cnt % 100) == 0:\n print('cnt is {}, time elapsed is {}, features are {} '.format(cnt,\n np.round(time.time()-start),\n features_batch))\n cnt += 1\n except tf.errors.OutOfRangeError:\n return pred_file, feat_file\n pass\n \"\"\"\n", "import argparse\nimport tensorflow as tf\nimport data_reader\nimport model_maker\nimport VAE_network_maker\nimport network_helper\nimport plotsAnalysis\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nimport pandas as pd\nimport flag_reader\nimport time_recorder\nimport get_pred_truth_file\n\ndef compare_truth_pred(pred_file, truth_file):\n \"\"\"\n Read truth and pred from csv files, compute their mean-absolute-error and the mean-squared-error\n :param pred_file: full path to pred file\n :param truth_file: full path to truth file\n :return: mae and mse\n \"\"\"\n pred = np.loadtxt(pred_file, delimiter=' ')\n truth = np.loadtxt(truth_file, delimiter=' ')\n\n mae = np.mean(np.abs(pred-truth), axis=1)\n mse = np.mean(np.square(pred-truth), axis=1)\n\n return mae, mse\ndef evaluatemain(flags, eval_forward):\n #Clear the default graph first for resolving potential name conflicts\n #Set the environment variable for if this is a cpu only script\n if flags.use_cpu_only:\n os.environ['CUDA_VISIBLE_DEVICES'] = '-1'\n \n print(\"Start Evaluating now...\")\n TK = time_recorder.time_keeper(time_keeping_file = \"data/time_keeper.txt\")\n\n tf.reset_default_graph()\n ckpt_dir = os.path.join(os.path.abspath(''), 'models', flags.model_name)\n \n decoder_fc_filters, encoder_fc_filters, spectra_fc_filters, conv1d_filters, \\\n filter_channel_list, geoboundary, latent_dim, batch_size = network_helper.get_parameters(ckpt_dir) \n batch_size = batch_size[0] #Get rid of the list \n geometry, spectra, train_init_op, valid_init_op = data_reader.read_data(input_size=flags.input_size,\n output_size=300,\n x_range=flags.x_range,\n y_range=flags.y_range,\n\t\t\t\t\t\t\t geoboundary=flags.geoboundary,\n cross_val=flags.cross_val,\n val_fold=flags.val_fold,\n batch_size=flags.batch_size,\n shuffle_size=flags.shuffle_size,\n\t\t\t\t\t\t\t\tdata_dir = flags.data_dir,\n\t\t\t\t\t\t\t normalize_input = flags.normalize_input,\n test_ratio = 0.9999)\n #if the input is normalized\n if flags.normalize_input:\n\t\t flags.boundary = [-1, 1, -1, 1]\n print(\"Boundary read from meta_file is \", geoboundary)\n print(\"batch_size read from meta_file is \", batch_size)\n print(\"latent_dim read from meta_file is \", latent_dim)\n # make network\n ntwk = VAE_network_maker.VAENetwork(geometry, spectra, model_maker.VAE, batch_size, latent_dim,\n spectra_fc_filters=spectra_fc_filters, decoder_fc_filters=decoder_fc_filters,\n encoder_fc_filters=encoder_fc_filters,reg_scale=flags.reg_scale,\n learn_rate=flags.learn_rate, decay_step=flags.decay_step, decay_rate=flags.decay_rate,\n geoboundary = flags.geoboundary, conv1d_filters = conv1d_filters, filter_channel_list = filter_channel_list)\n \n # evaluate the results if the results do not exist or user force to re-run evaluation\n save_file = os.path.join(os.path.abspath(''), 'data', 'test_pred_{}.csv'.format(flags.model_name))\n \n if flags.force_run or (not os.path.exists(save_file)):\n print('Evaluating the model ...')\n #pred_file, truth_file = ntwk.evaluate(valid_init_op, ckpt_dir=ckpt_dir,\n Xpred_file = ntwk.evaluate(valid_init_op, train_init_op, ckpt_dir=ckpt_dir, \n model_name=flags.model_name, write_summary=True,\n eval_forward = eval_forward, time_keeper = TK)\n\n print(\"Prediction File output at:\", Xpred_file)\n unpack_Xpred(Xpred_file,batch_size)\n #pred_file, truth_file = get_spectra_from_geometry(Xpred_file)\n \"\"\"\n mae, mse = compare_truth_pred(pred_file, truth_file)\n\n plt.figure(figsize=(12, 6))\n plt.hist(mse, bins=100)\n plt.xlabel('Mean Squared Error')\n plt.ylabel('cnt')\n plt.suptitle('VAE (Avg MSE={:.4e})'.format(np.mean(mse)))\n plt.savefig(os.path.join(os.path.abspath(''), 'data',\n 'VAE_{}.png'.format(flags.model_name)))\n plt.show()\n print('VAE (Avg MSE={:.4e})'.format(np.mean(mse)))\n \"\"\"\n\ndef unpack_Xpred(Xpred_file, batch_size):\n \"\"\"\n THis is the function which unpacks the Xpred file from VAE evaluation to a long file\n Since VAE prediction gives #batch_size of Geometry each time, unpack them into a long list for Tandem inference\n \"\"\"\n Xpred = np.loadtxt(Xpred_file, delimiter=' ')\n h,w = np.shape(Xpred)\n with open(\"data/Unpackinformation.txt\",'w') as f1:\n f1.write('The number of data point is {}, each with {} predicted geometries'.format(h, w/8))\n Xpred_reshaped = np.transpose(np.reshape(Xpred, (8, -1)))\n h,w = np.shape(Xpred_reshaped)\n assert w == 8, \"Your unpack function didn't work, check again what was wrong in the evaluateion output and unpack\"\n with open(Xpred_file,'w') as f:\n np.savetxt(f, Xpred_reshaped, fmt='%.3f')\n\ndef after_Tandem_pred():\n \"\"\"\n This function handles the rest of the evaluation after the Ypred has been generated by the Tandem model (forward model)\n \"\"\"\n data_dir = 'data'\n Ypred_file = get_pred_truth_file.get_Ypred(data_dir)\n Xpred_file = get_pred_truth_file.get_Xpred(data_dir)\n Ytruth_file = get_pred_truth_file.get_Ytruth(data_dir)\n Ypred = np.loadtxt(Ypred_file, delimiter = ' ')\n Ytruth = np.loadtxt(Ytruth_file, delimiter = ' ')\n Xpred = np.loadtxt(Xpred_file, delimiter = ' ')\n \n l_Ypred = len(Ypred)\n l_Ytruth = len(Ytruth)\n k = l_Ypred / l_Ytruth\n print(\"l_Ypred\",l_Ypred)\n print(\"l_Ytruth\",l_Ytruth)\n print(\"k\",k)\n assert k - int(k) < 0.001,\"Check you length, the divide result k is not an int!!\"\n print('For each data point in your truth file, the VAE generated {} data points'.format(k))\n k = int(k) \n #best_index_list = np.zeros([1,l_Ytruth])\n Xpred_new = np.zeros([l_Ytruth,8])\n Ypred_new = np.zeros(np.shape(Ytruth))\n for i in range(l_Ytruth):\n diff_mat = Ypred[i*k:(i+1)*k,:] - Ytruth[i,:] \n distance_mat = np.linalg.norm(diff_mat, axis = 1)\n best_index = np.argmax(distance_mat)\n #best_index_list[i] = best_index\n Xpred_new[i,:] = Xpred[i*k + best_index,:]\n Ypred_new[i,:] = Ypred[i*k + best_index,:]\n with open(Xpred_file, 'w') as f1:\n np.savetxt(f1, Xpred_new, fmt='%.3f')\n with open(Ypred_file, 'w') as f2:\n np.savetxt(f2, Ypred_new, fmt='%.3f')\n \n mae, mse = compare_truth_pred(Ypred_file, Ytruth_file)\n\n plt.figure(figsize=(12, 6))\n plt.hist(mse, bins=100)\n plt.xlabel('Mean Squared Error')\n plt.ylabel('cnt')\n plt.suptitle('VAE (Avg MSE={:.4e})'.format(np.mean(mse)))\n plt.savefig(os.path.join(os.path.abspath(''), 'data',\n 'VAE.png'))\n plt.show()\n print('VAE (Avg MSE={:.4e})'.format(np.mean(mse)))\n\nif __name__ == '__main__':\n\tflags = flag_reader.read_flag()\n\tevaluatemain(flags, eval_forward = False)\n\t#plotsAnalysis.SpectrumComparisonNGeometryComparison(3,2, (13,8), flags.model_name,flags.boundary)\t\n\n\n\n\n\n" ]
[ [ "torch.nn.functional.mse_loss", "torch.utils.tensorboard.SummaryWriter", "torch.cuda.is_available" ], [ "numpy.square", "tensorflow.losses.mean_squared_error", "pandas.read_csv", "tensorflow.train.latest_checkpoint", "tensorflow.local_variables_initializer", "tensorflow.Variable", "tensorflow.summary.FileWriter", "tensorflow.losses.get_regularization_loss", "numpy.reshape", "tensorflow.global_variables", "tensorflow.train.exponential_decay", "tensorflow.global_variables_initializer", "numpy.argmin", "numpy.shape", "tensorflow.Session", "tensorflow.train.AdamOptimizer", "tensorflow.variable_scope", "numpy.savetxt" ], [ "numpy.square", "numpy.abs", "numpy.reshape", "numpy.linalg.norm", "matplotlib.pyplot.ylabel", "tensorflow.reset_default_graph", "numpy.shape", "numpy.argmax", "numpy.mean", "numpy.savetxt", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.show", "numpy.zeros", "matplotlib.pyplot.hist", "numpy.loadtxt", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [ "1.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] } ]
magic428/subjects_notes
[ "6930adbb3f445c11ca9d024abb12a53d6aca19e7", "6930adbb3f445c11ca9d024abb12a53d6aca19e7" ]
[ "computer_vision/learning-opencv-practical/image-process-100ask/Question_31_40/answers/answer_40.py", "computer_vision/learning-opencv-practical/image-process-100ask/Question_41_50/answers/answer_48.py" ]
[ "import cv2\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n# Read image\r\nimg = cv2.imread(\"imori.jpg\").astype(np.float32)\r\nH, W, C = img.shape\r\n\r\n# RGB > YCbCr\r\nY = 0.2990 * img[..., 2] + 0.5870 * img[..., 1] + 0.1140 * img[..., 0]\r\nCb = -0.1687 * img[..., 2] - 0.3313 * img[..., 1] + 0.5 * img[..., 0] + 128.\r\nCr = 0.5 * img[..., 2] - 0.4187 * img[..., 1] - 0.0813 * img[..., 0] + 128.\r\n\r\nYCC = np.zeros_like(img, dtype=np.float32)\r\nYCC[..., 0] = Y\r\nYCC[..., 1] = Cb\r\nYCC[..., 2] = Cr\r\n\r\n\r\n# DCT\r\nT = 8\r\nK = 8\r\nX = np.zeros((H, W, C), dtype=np.float64)\r\n\r\nQ1 = np.array(((16, 11, 10, 16, 24, 40, 51, 61),\r\n (12, 12, 14, 19, 26, 58, 60, 55),\r\n (14, 13, 16, 24, 40, 57, 69, 56),\r\n (14, 17, 22, 29, 51, 87, 80, 62),\r\n (18, 22, 37, 56, 68, 109, 103, 77),\r\n (24, 35, 55, 64, 81, 104, 113, 92),\r\n (49, 64, 78, 87, 103, 121, 120, 101),\r\n (72, 92, 95, 98, 112, 100, 103, 99)), dtype=np.float32)\r\n\r\nQ2 = np.array(((17, 18, 24, 47, 99, 99, 99, 99),\r\n (18, 21, 26, 66, 99, 99, 99, 99),\r\n (24, 26, 56, 99, 99, 99, 99, 99),\r\n (47, 66, 99, 99, 99, 99, 99, 99),\r\n (99, 99, 99, 99, 99, 99, 99, 99),\r\n (99, 99, 99, 99, 99, 99, 99, 99),\r\n (99, 99, 99, 99, 99, 99, 99, 99),\r\n (99, 99, 99, 99, 99, 99, 99, 99)), dtype=np.float32)\r\n\r\ndef w(x, y, u, v):\r\n cu = 1.\r\n cv = 1.\r\n if u == 0:\r\n cu /= np.sqrt(2)\r\n if v == 0:\r\n cv /= np.sqrt(2)\r\n theta = np.pi / (2 * T)\r\n return (( 2 * cu * cv / T) * np.cos((2*x+1)*u*theta) * np.cos((2*y+1)*v*theta))\r\n \r\nfor yi in range(0, H, T):\r\n for xi in range(0, W, T):\r\n for v in range(T):\r\n for u in range(T):\r\n for y in range(T):\r\n for x in range(T):\r\n for c in range(C):\r\n X[v+yi, u+xi, c] += YCC[y+yi, x+xi, c] * w(x,y,u,v)\r\n \r\n X[yi:yi+T, xi:xi+T, 0] = np.round(X[yi:yi+T, xi:xi+T, 0] / Q1) * Q1\r\n X[yi:yi+T, xi:xi+T, 1] = np.round(X[yi:yi+T, xi:xi+T, 1] / Q2) * Q2\r\n X[yi:yi+T, xi:xi+T, 2] = np.round(X[yi:yi+T, xi:xi+T, 2] / Q2) * Q2\r\n \r\n\r\n# IDCT\r\nIYCC = np.zeros((H, W, 3), dtype=np.float64)\r\n\r\nfor yi in range(0, H, T):\r\n for xi in range(0, W, T):\r\n for y in range(T):\r\n for x in range(T):\r\n for v in range(K):\r\n for u in range(K):\r\n IYCC[y+yi, x+xi] += X[v+yi, u+xi] * w(x,y,u,v)\r\n\r\n\r\n# YCbCr > RGB\r\nout = np.zeros_like(img, dtype=np.float32)\r\nout[..., 2] = IYCC[..., 0] + (IYCC[..., 2] - 128.) * 1.4020\r\nout[..., 1] = IYCC[..., 0] - (IYCC[..., 1] - 128.) * 0.3441 - (IYCC[..., 2] - 128.) * 0.7139\r\nout[..., 0] = IYCC[..., 0] + (IYCC[..., 1] - 128.) * 1.7718\r\n\r\nout[out>255] = 255\r\nout = out.astype(np.uint8)\r\n \r\n# MSE\r\nv_max = 255.\r\nmse = np.sum(np.power(np.abs(img.astype(np.float32) - out.astype(np.float32)), 2)) / (H * W * C)\r\npsnr = 10 * np.log10(v_max ** 2 / mse)\r\n\r\nprint(\"PSNR >>\", psnr)\r\n\r\nbitrate = 1. * T * K ** 2 / (T ** 2)\r\nprint(\"bitrate >>\", bitrate)\r\n\r\n# Save result\r\ncv2.imshow(\"result\", out)\r\ncv2.waitKey(0)\r\ncv2.imwrite(\"out.jpg\", out)\r\n", "import cv2\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n# Read image\r\nimg = cv2.imread(\"imori.jpg\").astype(np.float32)\r\nH, W, C = img.shape\r\n\r\n# Otsu binary\r\n## Grayscale\r\nout = 0.2126 * img[..., 2] + 0.7152 * img[..., 1] + 0.0722 * img[..., 0]\r\nout = out.astype(np.uint8)\r\n\r\n## Determine threshold of Otsu's binarization\r\nmax_sigma = 0\r\nmax_t = 0\r\n\r\nfor _t in range(1, 255):\r\n v0 = out[np.where(out < _t)]\r\n m0 = np.mean(v0) if len(v0) > 0 else 0.\r\n w0 = len(v0) / (H * W)\r\n v1 = out[np.where(out >= _t)]\r\n m1 = np.mean(v1) if len(v1) > 0 else 0.\r\n w1 = len(v1) / (H * W)\r\n sigma = w0 * w1 * ((m0 - m1) ** 2)\r\n if sigma > max_sigma:\r\n max_sigma = sigma\r\n max_t = _t\r\n\r\n## Binarization\r\n#print(\"threshold >>\", max_t)\r\nth = max_t\r\nout[out < th] = 0\r\nout[out >= th] = 255\r\n\r\n\r\n# Morphology filter\r\nMF = np.array(((0, 1, 0),\r\n (1, 0, 1),\r\n (0, 1, 0)), dtype=np.int)\r\n\r\n# Morphology - erode\r\nErode_time = 2\r\n\r\nfor i in range(Erode_time):\r\n tmp = np.pad(out, (1, 1), 'edge')\r\n for y in range(1, H+1):\r\n for x in range(1, W+1):\r\n if np.sum(MF * tmp[y-1:y+2, x-1:x+2]) < 255*4:\r\n out[y-1, x-1] = 0\r\n\r\n\r\n# Save result\r\ncv2.imwrite(\"out.jpg\", out)\r\ncv2.imshow(\"result\", out)\r\ncv2.waitKey(0)\r\ncv2.destroyAllWindows()\r\n" ]
[ [ "numpy.sqrt", "numpy.cos", "numpy.round", "numpy.log10", "numpy.zeros_like", "numpy.array", "numpy.zeros" ], [ "numpy.pad", "numpy.mean", "numpy.array", "numpy.where", "numpy.sum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
BatsiBoy/PyFrac
[ "a898f6111295fa9196c382613639fc84e73d6035" ]
[ "examples/visexp.py" ]
[ "# -*- coding: utf-8 -*-\n#Name: Fractal Example - Exponential Curves\n#Author: Sean Pope\n\n#Example use of the fractal engine and coefficient block.\n#Creates random coefficient blocks and draws frames to create a simple animation.\n#This one is optimized for the exponential variation.\n\nimport matplotlib.pyplot as plt\nimport PyFrac as pf\n\nplt.style.use('dark_background') #Mostly just used for the black background.\n\nax = plt.subplot(111,frameon=False) #Create a figure and axes for drawing.\nax.axes.get_xaxis().set_visible(False) #Hide axis\nax.axes.get_yaxis().set_visible(False)\nplt.xlim(-1,1) #This function looks best in the biunit square.\nplt.ylim(-1,1)\n\n\n\ndef quitloop(*args): #Closes the event loop when no longer needed.\n global run\n run = 0\n return\n\n\n\nfig = plt.gcf() #Get the figure that pyplot spawned.\nfig.canvas.mpl_connect('close_event', quitloop) #If the window is closed, exit loop.\nfig.canvas.mpl_connect('key_press_event', quitloop) #If a button is pressed, close.\n\nmng = plt.get_current_fig_manager() #Grab the figure window\nmng.full_screen_toggle() #Maximize the image to fill the screen.\n\n\"\"\" Runtime variables \"\"\"\n\nrun = 1 #Set to continue drawing frames, unset to terminate\nframecount = 0 #Used to set frames drawn per coefficient block\nframeclear = 0 #Starts deleting frames when set\n\ncoeffs = pf.coeffs.rand(0.9,0.2)\n\n\"\"\" Main event loop. \"\"\"\n\nwhile(run):\n framecount += 1\n if framecount == 40: #Draws a new coefficient set if the current image is done.\n frameclear = 1\n coeffs = pf.coeffs.rand(0.9,0.2)\n framecount -= 40 #Reset frame counter.\n\n fractal = pf.engine.fractpoints(coeffs, 200, pf.variations.exponential) #Run the engine to get a figure.\n plt.scatter(fractal['x'], fractal['y'], #Get the x,y coordinates for each point\n marker='.', alpha=0.8, #Use small pixel markers with low opacity\n c=fractal['color'], cmap='plasma', #Map the color row to this colormap.\n s=25, edgecolor='none'\n )\n if frameclear:\n del ax.collections[0] #Remove the oldest frame.\n\n plt.pause(.01) #This pause draws the frame before looping.\n\n\nplt.close(fig)" ]
[ [ "matplotlib.pyplot.pause", "matplotlib.pyplot.scatter", "matplotlib.pyplot.ylim", "matplotlib.pyplot.gcf", "matplotlib.pyplot.xlim", "matplotlib.pyplot.subplot", "matplotlib.pyplot.get_current_fig_manager", "matplotlib.pyplot.close", "matplotlib.pyplot.style.use" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
dengniewei/Face-Recognition-Class-Attendance-System
[ "58aa85ff3b378991da3ccebd69e6ace5ec2af93f" ]
[ "02 Main/mainRUN.py" ]
[ "# 导入必要的模块\r\nfrom PyQt5 import QtCore, QtGui\r\nfrom PyQt5.QtWidgets import QApplication, QWidget, QMessageBox, QInputDialog\r\nfrom PyQt5.QtGui import QImage, QIcon, QPixmap\r\nfrom PyQt5.QtCore import QTimer, QDateTime, QCoreApplication, QThread\r\nimport sys, os\r\nimport cv2, imutils\r\n# 导入UI主界面\r\nimport main\r\n# 导入信息采集框界面\r\nimport infoUI\r\n# 导入打印中文脚本\r\nimport ChinesePutText\r\n# 导入人脸识别检测包\r\nfrom imutils.video import VideoStream\r\nimport numpy as np\r\nimport pickle\r\n# 导入眨眼检测必要的包\r\nfrom scipy.spatial import distance as dist\r\nfrom imutils import face_utils\r\nfrom datetime import datetime\r\nimport dlib\r\n# 导入数据库操作包\r\nimport pymysql\r\n\r\n# 定义活体检测-眨眼检测类\r\nclass BlinksDetectThread(QThread):\r\n trigger = QtCore.pyqtSignal()\r\n def __init__(self):\r\n super(BlinksDetectThread, self).__init__()\r\n # 定义两个常数,一个用于眼睛纵横比以指示眨眼,第二个作为眨眼连续帧数的阈值\r\n self.EYE_AR_THRESH = 0.25\r\n self.EYE_AR_CONSEC_FRAMES = 3\r\n # 初始化帧计数器和总闪烁次数\r\n self.COUNTER = 0\r\n self.TOTAL = 0\r\n # 初始化变量\r\n self.A = 0\r\n self.B = 0\r\n self.C = 0\r\n self.leftEye = 0\r\n self.rightEye = 0\r\n self.leftEAR = 0\r\n self.rightEAR = 0\r\n self.ear = 0\r\n # 线程启动停止标识符\r\n self.BlinksFlag = 1\r\n # 初始化摄像头\r\n self.cap3 = cv2.VideoCapture()\r\n\r\n # 定义眨眼检测距离函数\r\n def eye_aspect_ratio(self, eye):\r\n # 计算两组垂直方向上的眼睛标记(x,y)坐标之间的欧氏距离\r\n self.A = dist.euclidean(eye[1], eye[5])\r\n self.B = dist.euclidean(eye[2], eye[4])\r\n # 计算水平方向上的眼睛标记(x,y)坐标之间的欧氏距离\r\n self.C = dist.euclidean(eye[0], eye[3])\r\n # 计算眼睛的纵横比\r\n ear = (self.A + self.B) / (2.0 * self.C)\r\n # 返回眼睛的纵横比\r\n return ear\r\n\r\n def run(self):\r\n if self.BlinksFlag == 1:\r\n # 初始化dlib的人脸检测器(基于HOG),然后创建面部标志预测器\r\n print(\"[INFO] loading facial landmark predictor...\")\r\n shape_predictor_path = \"shape_predictor_68_face_landmarks.dat\"\r\n detector = dlib.get_frontal_face_detector()\r\n predictor = dlib.shape_predictor(shape_predictor_path)\r\n # 分别提取左眼和右眼的面部标志的索引\r\n (lStart, lEnd) = face_utils.FACIAL_LANDMARKS_IDXS[\"left_eye\"]\r\n (rStart, rEnd) = face_utils.FACIAL_LANDMARKS_IDXS[\"right_eye\"]\r\n # 在视频流的帧中循环\r\n self.cap3.open(cv2.CAP_DSHOW)\r\n while self.BlinksFlag == 1:\r\n # 从线程视频文件流中抓取帧,调整其大小,并将其转换为灰度通道\r\n vs = VideoStream(src=cv2.CAP_DSHOW).start()\r\n frame3 = vs.read()\r\n # ret, frame3 = self.cap3.read()\r\n QApplication.processEvents()\r\n frame3 = imutils.resize(frame3, width=900)\r\n gray = cv2.cvtColor(frame3, cv2.COLOR_BGR2GRAY)\r\n # 检测灰度帧中的人脸\r\n rects = detector(gray, 0)\r\n # 循环检测人脸\r\n for rect in rects:\r\n # 确定面部区域的面部标记,然后将面部标记(x,y)坐标转换为NumPy阵列\r\n shape = predictor(gray, rect)\r\n shape = face_utils.shape_to_np(shape)\r\n # 提取左眼和右眼坐标,然后使用坐标计算双眼的眼睛纵横比\r\n self.leftEye = shape[lStart:lEnd]\r\n self.rightEye = shape[rStart:rEnd]\r\n self.leftEAR = self.eye_aspect_ratio(self.leftEye)\r\n self.rightEAR = self.eye_aspect_ratio(self.rightEye)\r\n # 两只眼睛的平均眼睛纵横比\r\n self.ear = (self.leftEAR + self.rightEAR) / 2.0\r\n # 检查眼睛纵横比是否低于闪烁阈值,如果是,则增加闪烁帧计数器;否则执行else\r\n if self.ear < self.EYE_AR_THRESH:\r\n self.COUNTER += 1\r\n else:\r\n # 如果眼睛闭合次数足够则增加眨眼总数\r\n if self.COUNTER >= self.EYE_AR_CONSEC_FRAMES:\r\n self.TOTAL += 1\r\n # 重置眼框计数器\r\n self.COUNTER = 0\r\n self.trigger.emit()\r\n if self.TOTAL == 1:\r\n print(\"活体!眨眼次数为: {}\".format(self.TOTAL))\r\n\r\n # 定义停止线程操作\r\n def terminate(self):\r\n self.BlinksFlag = 0\r\n if flag2 == 0:\r\n VideoStream(src=cv2.CAP_DSHOW).stop()\r\n\r\n#########################################################################################\r\n\r\nclass MainWindow(QWidget):\r\n # 类构造函数\r\n def __init__(self):\r\n # super()构造器方法返回父级的对象。__init__()方法是构造器的一个方法。\r\n super().__init__()\r\n self.ui = main.Ui_Form()\r\n self.ui.setupUi(self)\r\n # 设置窗口名称和图标\r\n self.setWindowTitle('人脸识别考勤系统')\r\n self.setWindowIcon(QIcon('fcblogo.jpg'))\r\n # label_time显示系统时间\r\n timer = QTimer(self)\r\n timer.timeout.connect(self.showTimeText)\r\n timer.start()\r\n # 初始化摄像头\r\n # self.url = 0 # 这样调用摄像头会报错,并且会卡死。\r\n self.url = cv2.CAP_DSHOW # 默认调用0,如果要调用摄像头1,可以这样写:cv2.CAP_DSHOW + 1\r\n self.cap = cv2.VideoCapture()\r\n # 设置单张图片背景\r\n pixmap = QPixmap('background1.png')\r\n self.ui.label_camera.setPixmap(pixmap)\r\n # 设置摄像头按键连接函数\r\n self.ui.bt_openCamera.clicked.connect(self.openCamera)\r\n # 设置开始考勤按键的回调函数\r\n self.ui.bt_startCheck.clicked.connect(self.autoControl)\r\n # 设置活体检测按键的回调函数\r\n self.ui.bt_blinks.clicked.connect(self.BlinksThread)\r\n # 设置“退出系统”按键事件, 按下之后退出主界面\r\n self.ui.bt_exit.clicked.connect(QCoreApplication.instance().quit)\r\n # 设置信息采集按键连接\r\n self.bt_gathering = self.ui.bt_gathering\r\n # 设置区分打开摄像头还是人脸识别的标识符\r\n self.switch_bt = 0\r\n global flag2\r\n flag2 = 0\r\n\r\n # 初始化需要记录的人名\r\n self.record_name1 = ([])\r\n\r\n # 设置更新人脸数据库的按键连接函数\r\n self.ui.bt_generator.clicked.connect(self.trainModel)\r\n # 设置查询班级人数按键的连接函数\r\n self.ui.bt_check.clicked.connect(self.checkNums)\r\n # 设置请假按键的连接函数\r\n self.ui.bt_leave.clicked.connect(self.leaveButton)\r\n # 设置漏签补签按键的连接函数\r\n self.ui.bt_Supplement.clicked.connect(self.supplymentButton)\r\n # 设置对输入内容的删除提示\r\n self.ui.lineEdit.setClearButtonEnabled(True)\r\n self.ui.lineEdit_2.setClearButtonEnabled(True)\r\n # 设置查看结果(显示未到和迟到)按键的连接函数\r\n self.ui.bt_view.clicked.connect(self.showLateAbsentee)\r\n\r\n self.checkTime, ok = QInputDialog.getText(self, '考勤时间设定', '请输入考勤时间(格式为00:00:00):')\r\n\r\n # 显示系统时间以及相关文字提示函数\r\n def showTimeText(self):\r\n # 设置宽度\r\n self.ui.label_time.setFixedWidth(200)\r\n # 设置显示文本格式\r\n self.ui.label_time.setStyleSheet(\r\n # \"QLabel{background:white;}\" 此处设置背景色\r\n # \"QLabel{color:rgb(300,300,300,120); font-size:14px; font-weight:bold; font-family:宋体;}\"\r\n \"QLabel{font-size:14px; font-weight:bold; font-family:宋体;}\"\r\n )\r\n datetime = QDateTime.currentDateTime().toString()\r\n self.ui.label_time.setText(\"\" + datetime)\r\n\r\n # 显示“人脸识别考勤系统”文字\r\n self.ui.label_title.setFixedWidth(400)\r\n self.ui.label_title.setStyleSheet(\r\n \"QLabel{font-size:30px; font-weight:bold; font-family:宋体;}\")\r\n self.ui.label_title.setText(\"人脸识别考勤系统\")\r\n\r\n def openCamera(self, url):\r\n # 判断摄像头是否打开,如果打开则为true,反之为false\r\n flag = self.cap.isOpened()\r\n if flag == False:\r\n self.ui.label_logo.clear()\r\n self.cap.open(self.url)\r\n self.showCamera()\r\n elif flag == True:\r\n self.cap.release()\r\n self.ui.label_logo.clear()\r\n self.ui.label_camera.clear()\r\n self.ui.bt_openCamera.setText(u'打开相机')\r\n\r\n # 进入考勤模式,通过switch_bt进行控制的函数\r\n def autoControl(self):\r\n if self.switch_bt == 0:\r\n self.switch_bt = 1\r\n flag2 = 1\r\n self.ui.bt_startCheck.setText(u'退出考勤')\r\n self.showCamera()\r\n elif self.switch_bt == 1:\r\n self.switch_bt = 0\r\n flag2 = 0\r\n self.ui.bt_startCheck.setText(u'开始考勤')\r\n self.showCamera()\r\n\r\n def BlinksThread(self):\r\n bt_text = self.ui.bt_blinks.text()\r\n if bt_text == '活体检测':\r\n # 初始化眨眼检测线程\r\n self.startThread = BlinksDetectThread()\r\n self.startThread.start() # 启动线程\r\n self.ui.bt_blinks.setText('停止检测')\r\n else:\r\n self.ui.bt_blinks.setText('活体检测')\r\n # self.startThread.terminate() # 停止线程\r\n\r\n def showCamera(self):\r\n # 如果按键按下\r\n if self.switch_bt == 0:\r\n self.ui.label_logo.clear()\r\n self.ui.bt_openCamera.setText(u'关闭相机')\r\n while (self.cap.isOpened()):\r\n # 以BGR格式读取图像\r\n ret, self.image = self.cap.read(cv2.CAP_DSHOW)\r\n QApplication.processEvents() # 这句代码告诉QT处理来处理任何没有被处理的事件,并且将控制权返回给调用者,让代码变的没有那么卡\r\n # 将图像转换为RGB格式\r\n show = cv2.cvtColor(self.image, cv2.COLOR_BGR2RGB) # 这里指的是显示原图\r\n # opencv 读取图片的样式,不能通过Qlabel进行显示,需要转换为Qimage QImage(uchar * data, int width,\r\n self.showImage = QImage(show.data, show.shape[1], show.shape[0], QImage.Format_RGB888)\r\n self.ui.label_camera.setPixmap(QPixmap.fromImage(self.showImage))\r\n # 因为最后会存留一张图像在lable上,需要对lable进行清理\r\n self.ui.label_camera.clear()\r\n self.ui.bt_openCamera.setText(u'打开相机')\r\n\r\n elif self.switch_bt == 1:\r\n self.ui.label_logo.clear()\r\n self.ui.bt_startCheck.setText(u'退出考勤')\r\n # OpenCV深度学习人脸检测器的路径\r\n detector = \"face_detection_model\"\r\n # OpenCV深度学习面部嵌入模型的路径\r\n embedding_model = \"face_detection_model/openface_nn4.small2.v1.t7\"\r\n # 训练模型以识别面部的路径\r\n recognizer_path = \"output/recognizer.pickle\"\r\n # 标签编码器的路径\r\n le_path = \"output/le.pickle\"\r\n # 置信度\r\n confidence_default = 0.5\r\n # 从磁盘加载序列化面部检测器\r\n protoPath = os.path.sep.join([detector, \"deploy.prototxt\"])\r\n modelPath = os.path.sep.join([detector, \"res10_300x300_ssd_iter_140000.caffemodel\"])\r\n detector = cv2.dnn.readNetFromCaffe(protoPath, modelPath)\r\n # 从磁盘加载我们的序列化面嵌入模型\r\n print(\"[INFO] loading face recognizer...\")\r\n embedder = cv2.dnn.readNetFromTorch(embedding_model)\r\n # 加载实际的人脸识别模型和标签\r\n recognizer = pickle.loads(open(recognizer_path, \"rb\").read())\r\n le = pickle.loads(open(le_path, \"rb\").read())\r\n # 循环来自视频文件流的帧\r\n while (self.cap.isOpened()):\r\n # 从线程视频流中抓取帧\r\n ret, frame = self.cap.read()\r\n QApplication.processEvents()\r\n # 调整框架的大小以使其宽度为900像素(同时保持纵横比),然后抓取图像尺寸\r\n frame = imutils.resize(frame, width=900)\r\n (h, w) = frame.shape[:2]\r\n # 从图像构造一个blob\r\n imageBlob = cv2.dnn.blobFromImage(\r\n cv2.resize(frame, (300, 300)), 1.0, (300, 300),\r\n (104.0, 177.0, 123.0), swapRB=False, crop=False)\r\n # 应用OpenCV的基于深度学习的人脸检测器来定位输入图像中的人脸\r\n detector.setInput(imageBlob)\r\n detections = detector.forward()\r\n # 保存识别到的人脸\r\n face_names = []\r\n # 循环检测\r\n for i in np.arange(0, detections.shape[2]):\r\n # 提取与预测相关的置信度(即概率)\r\n confidence = detections[0, 0, i, 2]\r\n\r\n # 用于更新相机开关按键信息\r\n flag = self.cap.isOpened()\r\n if flag == False:\r\n self.ui.bt_openCamera.setText(u'打开相机')\r\n elif flag == True:\r\n self.ui.bt_openCamera.setText(u'关闭相机')\r\n\r\n # 过滤弱检测\r\n if confidence > confidence_default:\r\n # 计算面部边界框的(x,y)坐标\r\n box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])\r\n (startX, startY, endX, endY) = box.astype(\"int\")\r\n\r\n # 提取面部ROI\r\n face = frame[startY:endY, startX:endX]\r\n (fH, fW) = face.shape[:2]\r\n\r\n # 确保面部宽度和高度足够大\r\n if fW < 20 or fH < 20:\r\n continue\r\n\r\n # 为面部ROI构造一个blob,然后通过我们的面部嵌入模型传递blob以获得面部的128-d量化\r\n faceBlob = cv2.dnn.blobFromImage(face, 1.0 / 255, (96, 96), (0, 0, 0), swapRB=True, crop=False)\r\n embedder.setInput(faceBlob)\r\n vec = embedder.forward()\r\n # 执行分类识别面部\r\n preds = recognizer.predict_proba(vec)[0]\r\n j = np.argmax(preds)\r\n proba = preds[j]\r\n name = le.classes_[j]\r\n # 绘制面部的边界框以及相关的概率\r\n text = \"{}: {:.2f}%\".format(name, proba * 100)\r\n y = startY - 10 if startY - 10 > 10 else startY + 10\r\n cv2.rectangle(frame, (startX, startY), (endX, endY), (0, 0, 255), 2)\r\n frame = cv2.putText(frame, text, (startX, y), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 255), 2)\r\n face_names.append(name)\r\n\r\n bt_liveness = self.ui.bt_blinks.text()\r\n if bt_liveness == '停止检测':\r\n ChineseText = ChinesePutText.put_chinese_text('microsoft.ttf')\r\n frame = ChineseText.draw_text(frame, (330, 80), ' 请眨眨眼睛 ', 25, (55, 255, 55))\r\n # 显示输出框架\r\n show_video = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # 这里指的是显示原图\r\n # opencv读取图片的样式,不能通过Qlabel进行显示,需要转换为Qimage。\r\n # QImage(uchar * data, int width, int height, int bytesPerLine, Format format)\r\n self.showImage = QImage(show_video.data, show_video.shape[1], show_video.shape[0], QImage.Format_RGB888)\r\n self.ui.label_camera.setPixmap(QPixmap.fromImage(self.showImage))\r\n self.set_name = set(face_names)\r\n self.set_names = tuple(self.set_name)\r\n self.recordNames()\r\n\r\n # 因为最后一张画面会显示在GUI中,此处实现清除。\r\n self.ui.label_camera.clear()\r\n\r\n def recordNames(self):\r\n if self.set_name.issubset(self.record_name1): # 如果self.set_names是self.record_names 的子集返回ture\r\n pass # record_name1是要写进数据库中的名字信息 set_name是从摄像头中读出人脸的tuple形式\r\n else:\r\n self.different_name1 = self.set_name.difference(self.record_name1) # 获取到self.set_name有而self.record_name无的名字\r\n self.record_name1 = self.set_name.union(self.record_name1) # 把self.record_name变成两个集合的并集\r\n # different_name是为了获取到之前没有捕捉到的人脸,并再次将record_name1进行更新\r\n # 将集合变成tuple,并统计人数\r\n self.write_data = tuple(self.different_name1)\r\n names_num = len(self.write_data)\r\n # 显示签到人数\r\n self.ui.lcd_2.display(len(self.record_name1))\r\n\r\n if names_num > 0:\r\n # 将签到信息写入数据库\r\n self.lineTextInfo2 = []\r\n # 打开数据库连接\r\n db2 = pymysql.connect(\"localhost\", \"root\", \"mysql105\", \"facerecognition\")\r\n # 使用cursor()方法获取操作游标\r\n cursor2 = db2.cursor()\r\n # 获取系统时间,保存到秒\r\n import datetime\r\n currentTime2 = str(datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\"))\r\n results2 = self.useIDGetInfo(self.write_data[0])\r\n # 判断是否迟到\r\n import datetime\r\n self.ymd = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\r\n self.ymd2 = datetime.datetime.now().strftime(\"%H:%M:%S\")\r\n compareResult2 = self.compare_time('{}'.format(self.ymd2), '{}'.format(self.checkTime))\r\n\r\n # 82800表示23个小时,在compare_time()函数中,如果第一个时间小于第二个时间,则为第一个时间加24h后再减去第二时间;\r\n # 而正常的结果应该为'正常'.\r\n if compareResult2 <= 82800:\r\n self.description2 = '迟到'\r\n else:\r\n self.description2 = '正常'\r\n self.lineTextInfo2.append((results2[0], results2[1], results2[2], currentTime2, self.description2))\r\n print(self.lineTextInfo2)\r\n\r\n # 写入数据库\r\n try:\r\n # 如果存在数据,先删除再写入。前提是设置唯一索引字段或者主键。\r\n insert_sql2 = \"replace into checkin(Name, ID, Class, Time, Description) values(%s, %s, %s, %s, %s)\"\r\n users2 = self.lineTextInfo2\r\n cursor2.executemany(insert_sql2, users2)\r\n except Exception as e:\r\n print(e)\r\n print(\"SQL execute failed!\")\r\n else:\r\n print(\"SQL execute success!\")\r\n QMessageBox.information(self, \"Tips\", \"签到成功,请勿重复操作!\", QMessageBox.Yes | QMessageBox.No)\r\n # 提交到数据库执行\r\n db2.commit()\r\n cursor2.close()\r\n db2.close()\r\n\r\n # 比较时间大小,判断是否迟到\r\n def compare_time(self, time1, time2):\r\n import datetime\r\n s_time = datetime.datetime.strptime(time1, '%H:%M:%S')\r\n e_time = datetime.datetime.strptime(time2, '%H:%M:%S')\r\n delta = s_time - e_time\r\n return delta.seconds\r\n\r\n # 查询班级人数\r\n def checkNums(self):\r\n # 选择的班级\r\n input_Class = self.ui.comboBox.currentText()\r\n # 打开数据库连接\r\n db = pymysql.connect(\"localhost\", \"root\", \"mysql105\", \"facerecognition\")\r\n # 使用cursor()方法获取操作游标\r\n cursor = db.cursor()\r\n\r\n # 查询语句,实现通过ID关键字检索个人信息的功能\r\n sql = \"select * from studentnums where class = {}\".format(input_Class)\r\n # 执行查询\r\n if input_Class != '':\r\n try:\r\n cursor.execute(sql)\r\n # 获取所有记录列表\r\n results = cursor.fetchall()\r\n self.nums = []\r\n for i in results:\r\n self.nums.append(i[1])\r\n except:\r\n print(\"Error: unable to fetch data\")\r\n\r\n # 用于查询每班的实到人数\r\n sql2 = \"select * from checkin where class = {}\".format(input_Class)\r\n # 执行查询\r\n if input_Class != '':\r\n try:\r\n cursor.execute(sql2)\r\n # 获取所有记录列表\r\n results2 = cursor.fetchall()\r\n self.nums2 = []\r\n for i in results2:\r\n self.nums2.append(i[2])\r\n except:\r\n print(\"Error: unable to fetch data\")\r\n\r\n # lcd控件显示人数\r\n self.ui.lcd_1.display(self.nums[0])\r\n self.ui.lcd_2.display(len(self.nums2))\r\n # 关闭数据库连接\r\n db.close()\r\n\r\n # 请假/补签登记\r\n def leaveButton(self):\r\n self.leaveStudents(1)\r\n def supplymentButton(self):\r\n self.leaveStudents(2)\r\n def leaveStudents(self, button):\r\n self.lineTextInfo = []\r\n # 为防止输入为空卡死,先进行是否输入数据的判断\r\n if self.ui.lineEdit.isModified() or self.ui.lineEdit_2.isModified():\r\n # 打开数据库连接\r\n db = pymysql.connect(\"localhost\", \"root\", \"mysql105\", \"facerecognition\")\r\n # 使用cursor()方法获取操作游标\r\n cursor = db.cursor()\r\n # 获取系统时间,保存到秒\r\n currentTime = str(datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\"))\r\n if button == 1:\r\n self.description = '请假'\r\n self.lineTextID = self.ui.lineEdit.text()\r\n results = self.useIDGetInfo(self.lineTextID)\r\n elif button == 2:\r\n self.description = '漏签补签'\r\n self.lineTextID = self.ui.lineEdit_2.text()\r\n results = self.useIDGetInfo(self.lineTextID)\r\n self.lineTextInfo.append((results[0], results[1], results[2], currentTime, self.description))\r\n # 写入数据库\r\n try:\r\n # 如果存在数据,先删除再写入。前提是设置唯一索引字段或者主键。\r\n insert_sql = \"replace into checkin(Name, ID, Class, Time, Description) values(%s, %s, %s, %s, %s)\"\r\n users = self.lineTextInfo\r\n cursor.executemany(insert_sql, users)\r\n except Exception as e:\r\n print(e)\r\n print(\"sql execute failed\")\r\n else:\r\n print(\"sql execute success\")\r\n QMessageBox.warning(self, \"warning\", \"{} 登记成功,请勿重复操作!\".format(self.description), QMessageBox.Yes | QMessageBox.No)\r\n # 提交到数据库执行\r\n db.commit()\r\n cursor.close()\r\n db.close()\r\n else:\r\n QMessageBox.warning(self, \"warning\", \"学号不能为空,请输入后重试!\", QMessageBox.Yes | QMessageBox.No)\r\n # 输入框清零\r\n self.ui.lineEdit.clear()\r\n self.ui.lineEdit_2.clear()\r\n\r\n # 使用ID当索引找到其它信息\r\n def useIDGetInfo(self, ID):\r\n # 打开数据库连接\r\n db = pymysql.connect(\"localhost\", \"root\", \"mysql105\", \"facerecognition\")\r\n # 使用cursor()方法获取操作游标\r\n cursor = db.cursor()\r\n # 查询语句,实现通过ID关键字检索个人信息的功能\r\n sql = \"select * from students where ID = {}\".format(ID)\r\n # 执行查询\r\n if ID != '':\r\n try:\r\n cursor.execute(sql)\r\n # 获取所有记录列表\r\n results = cursor.fetchall()\r\n self.checkInfo = []\r\n for i in results:\r\n self.checkInfo.append(i[1])\r\n self.checkInfo.append(i[0])\r\n self.checkInfo.append(i[2])\r\n return self.checkInfo\r\n except:\r\n print(\"Error: unable to fetch data\")\r\n\r\n # 显示迟到和未到\r\n def showLateAbsentee(self):\r\n db = pymysql.connect(\"localhost\", \"root\", \"mysql105\", \"facerecognition\")\r\n cursor = db.cursor()\r\n # 一定要注意字符串在检索时要加''!\r\n sql1 = \"select name from checkin where Description = '{}'\".format('迟到')\r\n sql2 = \"select name from students\"\r\n try:\r\n cursor.execute(sql1)\r\n results = cursor.fetchall()\r\n self.lateNums = []\r\n for x in results:\r\n self.lateNums.append(x[0])\r\n self.lateNums.sort()\r\n # print(self.lateNums)\r\n except:\r\n print(\"Error: unable to fetch latedata\")\r\n try:\r\n cursor.execute(sql2)\r\n results2 = cursor.fetchall()\r\n self.allNums = []\r\n for i in results2:\r\n self.allNums.append(i[0])\r\n self.allNums.sort()\r\n print(self.allNums)\r\n except:\r\n print(\"Error: unable to fetch absenteedata\")\r\n\r\n db.commit()\r\n cursor.close()\r\n db.close()\r\n\r\n # 集合运算,算出未到的和迟到的\r\n self.AbsenteeNums = set(set(self.allNums) - set(self.lateNums))\r\n self.AbsenteeNums = list(self.AbsenteeNums)\r\n self.AbsenteeNums.sort()\r\n\r\n # 在控件中显示未到的同学\r\n rowLate = len(self.lateNums)\r\n rowAbsentee = len(self.AbsenteeNums)\r\n model1 = QtGui.QStandardItemModel(rowLate, 0)\r\n # 设置数据行、列标题\r\n model1.setHorizontalHeaderLabels(['姓名'])\r\n # 设置填入数据内容\r\n for row in range(rowLate):\r\n item = QtGui.QStandardItem(self.lateNums[row])\r\n # 设置每个位置的文本值\r\n model1.setItem(row, 0, item)\r\n # 指定显示的tableView控件,实例化表格视图\r\n View1 = self.ui.tableView_escape\r\n View1.setModel(model1)\r\n\r\n # 迟到显示\r\n model2 = QtGui.QStandardItemModel(rowAbsentee, 0)\r\n # 设置数据行、列标题\r\n model2.setHorizontalHeaderLabels(['姓名'])\r\n # 设置填入数据内容\r\n for row in range(rowAbsentee):\r\n item = QtGui.QStandardItem(self.AbsenteeNums[row])\r\n # 设置每个位置的文本值\r\n model2.setItem(row, 0, item)\r\n # 指定显示的tableView控件,实例化表格视图\r\n View2 = self.ui.tableView_late\r\n View2.setModel(model2)\r\n\r\n # 训练人脸识别模型\r\n def trainModel(self):\r\n import GeneratorModel\r\n GeneratorModel.Generator()\r\n GeneratorModel.TrainModel()\r\n print('Model have been trained!')\r\n\r\n##########################################################################################\r\n\r\nclass infoDialog(QWidget):\r\n def __init__(self):\r\n # super()构造器方法返回父级的对象。__init__()方法是构造器的一个方法。\r\n super().__init__()\r\n self.Dialog = infoUI.Ui_Form()\r\n self.Dialog.setupUi(self)\r\n\r\n # 设置窗口名称和图标\r\n self.setWindowTitle('个人信息采集')\r\n self.setWindowIcon(QIcon('fcblogo.jpg'))\r\n\r\n # 设置单张图片背景\r\n pixmap = QPixmap('background2.png')\r\n self.Dialog.label_capture.setPixmap(pixmap)\r\n\r\n # 设置信息采集按键连接函数\r\n self.Dialog.bt_collectInfo.clicked.connect(self.openCam)\r\n # 设置拍照按键连接函数\r\n self.Dialog.bt_takephoto.clicked.connect(self.takePhoto)\r\n # 设置查询信息按键连接函数\r\n self.Dialog.bt_checkInfo.clicked.connect(self.checkInfo)\r\n # 设置写入信息按键连接函数\r\n self.Dialog.bt_changeInfo.clicked.connect(self.changeInfo)\r\n # 初始化信息导入列表\r\n self.users = []\r\n # 初始化摄像头\r\n self.url2 = cv2.CAP_DSHOW\r\n self.cap2 = cv2.VideoCapture()\r\n # 初始化保存人脸数目\r\n self.photos = 0\r\n\r\n def handle_click(self):\r\n if not self.isVisible():\r\n self.show()\r\n def handle_close(self):\r\n self.close()\r\n\r\n def openCam(self):\r\n # 判断摄像头是否打开,如果打开则为true,反之为false\r\n flagCam = self.cap2.isOpened()\r\n if flagCam == False:\r\n # 通过对话框设置被采集人学号\r\n self.text, self.ok = QInputDialog.getText(self, '创建个人图像数据库', '请输入学号:')\r\n if self.ok and self.text != '':\r\n self.Dialog.label_capture.clear()\r\n self.cap2.open(self.url2)\r\n self.showCapture()\r\n elif flagCam == True:\r\n self.cap2.release()\r\n self.Dialog.label_capture.clear()\r\n self.Dialog.bt_collectInfo.setText(u'采集人像')\r\n\r\n def showCapture(self):\r\n self.Dialog.bt_collectInfo.setText(u'停止采集')\r\n self.Dialog.label_capture.clear()\r\n # 导入opencv人脸检测xml文件\r\n cascade = 'haarcascades_cuda/haarcascade_frontalface_default.xml'\r\n # 加载 Haar级联人脸检测库\r\n detector = cv2.CascadeClassifier(cascade)\r\n print(\"[INFO] starting video stream...\")\r\n # 循环来自视频文件流的帧\r\n while self.cap2.isOpened():\r\n ret, frame2 = self.cap2.read()\r\n QApplication.processEvents()\r\n self.orig = frame2.copy()\r\n frame2 = imutils.resize(frame2, width=500)\r\n rects = detector.detectMultiScale(cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY), scaleFactor=1.1,\r\n minNeighbors=5, minSize=(30, 30))\r\n for (x, y, w, h) in rects:\r\n cv2.rectangle(frame2, (x, y), (x + w, y + h), (0, 255, 0), 2)\r\n frame2 = cv2.putText(frame2, \"Have token {}/20 faces\".format(self.photos), (50, 60), cv2.FONT_HERSHEY_SIMPLEX, 0.7,\r\n (200, 100, 50), 2)\r\n # 显示输出框架\r\n show_video2 = cv2.cvtColor(frame2, cv2.COLOR_BGR2RGB) # 这里指的是显示原图\r\n # opencv读取图片的样式,不能通过Qlabel进行显示,需要转换为Qimage。\r\n # QImage(uchar * data, int width, int height, int bytesPerLine, Format format)\r\n self.showImage2 = QImage(show_video2.data, show_video2.shape[1], show_video2.shape[0], QImage.Format_RGB888)\r\n self.Dialog.label_capture.setPixmap(QPixmap.fromImage(self.showImage2))\r\n # 因为最后一张画面会显示在GUI中,此处实现清除。\r\n self.Dialog.label_capture.clear()\r\n\r\n # 创建文件夹\r\n def mkdir(self, path):\r\n # 去除首位空格\r\n path = path.strip()\r\n # 去除尾部 \\ 符号\r\n path = path.rstrip(\"\\\\\")\r\n # 判断路径是否存在, 存在=True; 不存在=False\r\n isExists = os.path.exists(path)\r\n # 判断结果\r\n if not isExists:\r\n # 如果不存在则创建目录\r\n os.makedirs(path)\r\n return True\r\n\r\n def takePhoto(self):\r\n self.photos += 1\r\n self.filename = \"D:\\\\Github\\\\class-attendance-system-based-on-face-recognition\\\\02 Main\\\\dataset\\\\{}\\\\\".format(self.text)\r\n self.mkdir(self.filename)\r\n photo_save_path = os.path.join(os.path.dirname(os.path.abspath('__file__')), '{}'.format(self.filename))\r\n self.showImage2.save(photo_save_path + datetime.now().strftime(\"%Y%m%d%H%M%S\") + \".png\")\r\n # p = os.path.sep.join([output, \"{}.png\".format(str(total).zfill(5))])\r\n # cv2.imwrite(p, self.showImage2)\r\n if self.photos == 20:\r\n QMessageBox.information(self, \"Information\", self.tr(\"采集成功!\"), QMessageBox.Yes | QMessageBox.No)\r\n\r\n # 数据库查询\r\n def checkInfo(self):\r\n # 键入ID\r\n self.input_ID = self.Dialog.lineEdit_ID.text()\r\n # 打开数据库连接\r\n db = pymysql.connect(\"localhost\", \"root\", \"mysql105\", \"facerecognition\")\r\n # 使用cursor()方法获取操作游标\r\n cursor = db.cursor()\r\n # 查询语句,实现通过ID关键字检索个人信息的功能\r\n sql = \"SELECT * FROM STUDENTS WHERE ID = {}\".format(self.input_ID)\r\n # 执行查询\r\n if self.input_ID != '':\r\n try:\r\n cursor.execute(sql)\r\n # 获取所有记录列表\r\n results = cursor.fetchall()\r\n self.lists = []\r\n for i in results:\r\n self.lists.append(i[0])\r\n self.lists.append(i[1])\r\n self.lists.append(i[2])\r\n self.lists.append(i[3])\r\n self.lists.append(i[4])\r\n except:\r\n print(\"Error: unable to fetch data\")\r\n\r\n # 设置显示数据层次结构,5行2列(包含行表头)\r\n self.model = QtGui.QStandardItemModel(5, 0)\r\n # 设置数据行、列标题\r\n self.model.setHorizontalHeaderLabels(['值'])\r\n self.model.setVerticalHeaderLabels(['学号', '姓名', '班级', '性别', '生日'])\r\n # 设置填入数据内容\r\n nums = len(self.lists)\r\n if nums == 0:\r\n QMessageBox.warning(self, \"warning\", \"人脸数据库中无此人信息,请马上录入!\", QMessageBox.Yes | QMessageBox.No)\r\n\r\n for row in range(nums):\r\n item = QtGui.QStandardItem(self.lists[row])\r\n # 设置每个位置的文本值\r\n self.model.setItem(row, 0, item)\r\n # 指定显示的tableView控件,实例化表格视图\r\n self.View = self.Dialog.tableView\r\n self.View.setModel(self.model)\r\n # 关闭数据库连接\r\n db.close()\r\n\r\n # 将采集信息写入数据库\r\n def userInfo(self):\r\n ID = self.Dialog.lineEdit_ID.text()\r\n Name = self.Dialog.lineEdit_Name.text()\r\n Class = self.Dialog.lineEdit_Class.text()\r\n Sex = self.Dialog.lineEdit_Sex.text()\r\n Birth = self.Dialog.lineEdit_Birth.text()\r\n self.users.append((ID, Name, Class, Sex, Birth))\r\n return self.users\r\n\r\n def changeInfo(self):\r\n # 打开数据库连接\r\n db = pymysql.connect(\"localhost\", \"root\", \"mysql105\", \"facerecognition\")\r\n # 使用cursor()方法获取操作游标\r\n cursor = db.cursor()\r\n # 写入数据库\r\n try:\r\n # 如果存在数据,先删除再写入。前提是设置唯一索引字段或者主键。\r\n insert_sql = \"replace into students(ID, Name, Class, Sex, Birthday) values(%s, %s, %s, %s, %s)\"\r\n users = self.userInfo()\r\n cursor.executemany(insert_sql, users)\r\n except Exception as e:\r\n print(e)\r\n print(\"sql execute failed\")\r\n else:\r\n print(\"sql execute success\")\r\n QMessageBox.warning(self, \"warning\", \"录入成功,请勿重复操作!\", QMessageBox.Yes | QMessageBox.No)\r\n # 提交到数据库执行\r\n db.commit()\r\n # 关闭数据库\r\n cursor.close()\r\n # 关闭数据库连接\r\n db.close()\r\n\r\nif __name__ == '__main__':\r\n app = QApplication(sys.argv)\r\n # 创建并显示窗口\r\n mainWindow = MainWindow()\r\n infoWindow = infoDialog()\r\n mainWindow.ui.bt_gathering.clicked.connect(infoWindow.handle_click)\r\n mainWindow.show()\r\n sys.exit(app.exec_())" ]
[ [ "numpy.arange", "numpy.array", "numpy.argmax", "scipy.spatial.distance.euclidean" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "1.6", "0.14", "1.10", "0.15", "1.4", "0.16", "1.9", "0.19", "1.5", "0.18", "1.2", "1.7", "0.12", "1.0", "0.17", "1.3", "1.8" ], "tensorflow": [] } ]
AVsolutionsai/YOLOv3_custom
[ "d974e8305310cef31621b20128ba29c3b09ce2af" ]
[ "yolov3_tf2/models.py" ]
[ "from absl import flags\nfrom absl.flags import FLAGS\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras import Model\nfrom tensorflow.keras.layers import (\n Add,\n Concatenate,\n Conv2D,\n Input,\n Lambda,\n LeakyReLU,\n MaxPool2D,\n UpSampling2D,\n ZeroPadding2D,\n)\nfrom tensorflow.keras.regularizers import l2\nfrom tensorflow.keras.losses import (\n binary_crossentropy,\n sparse_categorical_crossentropy\n)\nfrom .batch_norm import BatchNormalization\nfrom .utils import broadcast_iou\n\nyolo_max_boxes = 100\nyolo_iou_threshold = 0.1\nyolo_score_threshold = 0.1\n# customize your model through the following parameters\nflags.DEFINE_integer('yolo_max_boxes', 100, 'maximum number of detections at one time')\nflags.DEFINE_float('yolo_iou_threshold', 0.5, 'iou threshold')\nflags.DEFINE_float('yolo_score_threshold', 0.5, 'score threshold')\n\nyolo_anchors = np.array([(10, 13), (16, 30), (33, 23), (30, 61), (62, 45),\n (59, 119), (116, 90), (156, 198), (373, 326)],\n np.float32) / 416\nyolo_anchor_masks = np.array([[6, 7, 8], [3, 4, 5], [0, 1, 2]])\n\nyolo_tiny_anchors = np.array([(10, 14), (23, 27), (37, 58),\n (81, 82), (135, 169), (344, 319)],\n np.float32) / 416\nyolo_tiny_anchor_masks = np.array([[3, 4, 5], [0, 1, 2]])\n\n\ndef DarknetConv(x, filters, size, strides=1, batch_norm=True):\n if strides == 1:\n padding = 'same'\n else:\n x = ZeroPadding2D(((1, 0), (1, 0)))(x) # top left half-padding\n padding = 'valid'\n x = Conv2D(filters=filters, kernel_size=size,\n strides=strides, padding=padding,\n use_bias=not batch_norm, kernel_regularizer=l2(0.0005))(x)\n if batch_norm:\n x = BatchNormalization()(x)\n x = LeakyReLU(alpha=0.1)(x)\n return x\n\n\ndef DarknetResidual(x, filters):\n prev = x\n x = DarknetConv(x, filters // 2, 1)\n x = DarknetConv(x, filters, 3)\n x = Add()([prev, x])\n return x\n\n\ndef DarknetBlock(x, filters, blocks):\n x = DarknetConv(x, filters, 3, strides=2)\n for _ in range(blocks):\n x = DarknetResidual(x, filters)\n return x\n\n\ndef Darknet(name=None):\n x = inputs = Input([None, None, 3])\n x = DarknetConv(x, 32, 3)\n x = DarknetBlock(x, 64, 1)\n x = DarknetBlock(x, 128, 2) # skip connection\n x = x_36 = DarknetBlock(x, 256, 8) # skip connection\n x = x_61 = DarknetBlock(x, 512, 8)\n x = DarknetBlock(x, 1024, 4)\n return tf.keras.Model(inputs, (x_36, x_61, x), name=name)\n\n\ndef DarknetTiny(name=None):\n x = inputs = Input([None, None, 3])\n x = DarknetConv(x, 16, 3)\n x = MaxPool2D(2, 2, 'same')(x)\n x = DarknetConv(x, 32, 3)\n x = MaxPool2D(2, 2, 'same')(x)\n x = DarknetConv(x, 64, 3)\n x = MaxPool2D(2, 2, 'same')(x)\n x = DarknetConv(x, 128, 3)\n x = MaxPool2D(2, 2, 'same')(x)\n x = x_8 = DarknetConv(x, 256, 3) # skip connection\n x = MaxPool2D(2, 2, 'same')(x)\n x = DarknetConv(x, 512, 3)\n x = MaxPool2D(2, 1, 'same')(x)\n x = DarknetConv(x, 1024, 3)\n return tf.keras.Model(inputs, (x_8, x), name=name)\n\n\ndef YoloConv(filters, name=None):\n def yolo_conv(x_in):\n if isinstance(x_in, tuple):\n inputs = Input(x_in[0].shape[1:]), Input(x_in[1].shape[1:])\n x, x_skip = inputs\n\n # concat with skip connection\n x = DarknetConv(x, filters, 1)\n x = UpSampling2D(2)(x)\n x = Concatenate()([x, x_skip])\n else:\n x = inputs = Input(x_in.shape[1:])\n\n x = DarknetConv(x, filters, 1)\n x = DarknetConv(x, filters * 2, 3)\n x = DarknetConv(x, filters, 1)\n x = DarknetConv(x, filters * 2, 3)\n x = DarknetConv(x, filters, 1)\n return Model(inputs, x, name=name)(x_in)\n return yolo_conv\n\n\ndef YoloConvTiny(filters, name=None):\n def yolo_conv(x_in):\n if isinstance(x_in, tuple):\n inputs = Input(x_in[0].shape[1:]), Input(x_in[1].shape[1:])\n x, x_skip = inputs\n\n # concat with skip connection\n x = DarknetConv(x, filters, 1)\n x = UpSampling2D(2)(x)\n x = Concatenate()([x, x_skip])\n else:\n x = inputs = Input(x_in.shape[1:])\n x = DarknetConv(x, filters, 1)\n\n return Model(inputs, x, name=name)(x_in)\n return yolo_conv\n\n\ndef YoloOutput(filters, anchors, classes, name=None):\n def yolo_output(x_in):\n x = inputs = Input(x_in.shape[1:])\n x = DarknetConv(x, filters * 2, 3)\n x = DarknetConv(x, anchors * (classes + 5), 1, batch_norm=False)\n x = Lambda(lambda x: tf.reshape(x, (-1, tf.shape(x)[1], tf.shape(x)[2],\n anchors, classes + 5)))(x)\n return tf.keras.Model(inputs, x, name=name)(x_in)\n return yolo_output\n\n\ndef yolo_boxes(pred, anchors, classes):\n # pred: (batch_size, grid, grid, anchors, (x, y, w, h, obj, ...classes))\n grid_size = tf.shape(pred)[1]\n box_xy, box_wh, objectness, class_probs = tf.split(\n pred, (2, 2, 1, classes), axis=-1)\n\n box_xy = tf.sigmoid(box_xy)\n objectness = tf.sigmoid(objectness)\n class_probs = tf.sigmoid(class_probs)\n pred_box = tf.concat((box_xy, box_wh), axis=-1) # original xywh for loss\n\n # !!! grid[x][y] == (y, x)\n grid = tf.meshgrid(tf.range(grid_size), tf.range(grid_size))\n grid = tf.expand_dims(tf.stack(grid, axis=-1), axis=2) # [gx, gy, 1, 2]\n\n box_xy = (box_xy + tf.cast(grid, tf.float32)) / \\\n tf.cast(grid_size, tf.float32)\n box_wh = tf.exp(box_wh) * anchors\n\n box_x1y1 = box_xy - box_wh / 2\n box_x2y2 = box_xy + box_wh / 2\n bbox = tf.concat([box_x1y1, box_x2y2], axis=-1)\n\n return bbox, objectness, class_probs, pred_box\n\n\ndef yolo_nms(outputs, anchors, masks, classes):\n # boxes, conf, type\n b, c, t = [], [], []\n\n for o in outputs:\n b.append(tf.reshape(o[0], (tf.shape(o[0])[0], -1, tf.shape(o[0])[-1])))\n c.append(tf.reshape(o[1], (tf.shape(o[1])[0], -1, tf.shape(o[1])[-1])))\n t.append(tf.reshape(o[2], (tf.shape(o[2])[0], -1, tf.shape(o[2])[-1])))\n\n bbox = tf.concat(b, axis=1)\n confidence = tf.concat(c, axis=1)\n class_probs = tf.concat(t, axis=1)\n\n scores = confidence * class_probs\n boxes, scores, classes, valid_detections = tf.image.combined_non_max_suppression(\n boxes=tf.reshape(bbox, (tf.shape(bbox)[0], -1, 1, 4)),\n scores=tf.reshape(\n scores, (tf.shape(scores)[0], -1, tf.shape(scores)[-1])),\n max_output_size_per_class=yolo_max_boxes,\n max_total_size=yolo_max_boxes,\n iou_threshold=yolo_iou_threshold,\n score_threshold=yolo_score_threshold\n )\n\n return boxes, scores, classes, valid_detections\n\n\ndef YoloV3(size=None, channels=3, anchors=yolo_anchors,\n masks=yolo_anchor_masks, classes=80, training=False):\n physical_devices = tf.config.experimental.list_physical_devices('GPU')\n if len(physical_devices) > 0:\n tf.config.experimental.set_memory_growth(physical_devices[0], True)\n x = inputs = Input([size, size, channels], name='input')\n\n x_36, x_61, x = Darknet(name='yolo_darknet')(x)\n\n x = YoloConv(512, name='yolo_conv_0')(x)\n output_0 = YoloOutput(512, len(masks[0]), classes, name='yolo_output_0')(x)\n\n x = YoloConv(256, name='yolo_conv_1')((x, x_61))\n output_1 = YoloOutput(256, len(masks[1]), classes, name='yolo_output_1')(x)\n\n x = YoloConv(128, name='yolo_conv_2')((x, x_36))\n output_2 = YoloOutput(128, len(masks[2]), classes, name='yolo_output_2')(x)\n\n if training:\n return Model(inputs, (output_0, output_1, output_2), name='yolov3')\n\n boxes_0 = Lambda(lambda x: yolo_boxes(x, anchors[masks[0]], classes),\n name='yolo_boxes_0')(output_0)\n boxes_1 = Lambda(lambda x: yolo_boxes(x, anchors[masks[1]], classes),\n name='yolo_boxes_1')(output_1)\n boxes_2 = Lambda(lambda x: yolo_boxes(x, anchors[masks[2]], classes),\n name='yolo_boxes_2')(output_2)\n\n outputs = Lambda(lambda x: yolo_nms(x, anchors, masks, classes),\n name='yolo_nms')((boxes_0[:3], boxes_1[:3], boxes_2[:3]))\n\n return Model(inputs, outputs, name='yolov3')\n\n\ndef YoloV3Tiny(size=None, channels=3, anchors=yolo_tiny_anchors,\n masks=yolo_tiny_anchor_masks, classes=80, training=False):\n physical_devices = tf.config.experimental.list_physical_devices('GPU')\n if len(physical_devices) > 0:\n tf.config.experimental.set_memory_growth(physical_devices[0], True)\n x = inputs = Input([size, size, channels], name='input')\n\n x_8, x = DarknetTiny(name='yolo_darknet')(x)\n\n x = YoloConvTiny(256, name='yolo_conv_0')(x)\n output_0 = YoloOutput(256, len(masks[0]), classes, name='yolo_output_0')(x)\n\n x = YoloConvTiny(128, name='yolo_conv_1')((x, x_8))\n output_1 = YoloOutput(128, len(masks[1]), classes, name='yolo_output_1')(x)\n\n if training:\n return Model(inputs, (output_0, output_1), name='yolov3')\n\n boxes_0 = Lambda(lambda x: yolo_boxes(x, anchors[masks[0]], classes),\n name='yolo_boxes_0')(output_0)\n boxes_1 = Lambda(lambda x: yolo_boxes(x, anchors[masks[1]], classes),\n name='yolo_boxes_1')(output_1)\n outputs = Lambda(lambda x: yolo_nms(x, anchors, masks, classes),\n name='yolo_nms')((boxes_0[:3], boxes_1[:3]))\n return Model(inputs, outputs, name='yolov3_tiny')\n\n\ndef YoloLoss(anchors, classes=80, ignore_thresh=0.5):\n def yolo_loss(y_true, y_pred):\n # 1. transform all pred outputs\n # y_pred: (batch_size, grid, grid, anchors, (x, y, w, h, obj, ...cls))\n pred_box, pred_obj, pred_class, pred_xywh = yolo_boxes(\n y_pred, anchors, classes)\n pred_xy = pred_xywh[..., 0:2]\n pred_wh = pred_xywh[..., 2:4]\n\n # 2. transform all true outputs\n # y_true: (batch_size, grid, grid, anchors, (x1, y1, x2, y2, obj, cls))\n true_box, true_obj, true_class_idx = tf.split(\n y_true, (4, 1, 1), axis=-1)\n true_xy = (true_box[..., 0:2] + true_box[..., 2:4]) / 2\n true_wh = true_box[..., 2:4] - true_box[..., 0:2]\n\n # give higher weights to small boxes\n box_loss_scale = 2 - true_wh[..., 0] * true_wh[..., 1]\n\n # 3. inverting the pred box equations\n grid_size = tf.shape(y_true)[1]\n grid = tf.meshgrid(tf.range(grid_size), tf.range(grid_size))\n grid = tf.expand_dims(tf.stack(grid, axis=-1), axis=2)\n true_xy = true_xy * tf.cast(grid_size, tf.float32) - \\\n tf.cast(grid, tf.float32)\n true_wh = tf.math.log(true_wh / anchors)\n true_wh = tf.where(tf.math.is_inf(true_wh),\n tf.zeros_like(true_wh), true_wh)\n\n # 4. calculate all masks\n obj_mask = tf.squeeze(true_obj, -1)\n # ignore false positive when iou is over threshold\n best_iou = tf.map_fn(\n lambda x: tf.reduce_max(broadcast_iou(x[0], tf.boolean_mask(\n x[1], tf.cast(x[2], tf.bool))), axis=-1),\n (pred_box, true_box, obj_mask),\n tf.float32)\n ignore_mask = tf.cast(best_iou < ignore_thresh, tf.float32)\n\n # 5. calculate all losses\n xy_loss = obj_mask * box_loss_scale * \\\n tf.reduce_sum(tf.square(true_xy - pred_xy), axis=-1)\n wh_loss = obj_mask * box_loss_scale * \\\n tf.reduce_sum(tf.square(true_wh - pred_wh), axis=-1)\n obj_loss = binary_crossentropy(true_obj, pred_obj)\n obj_loss = obj_mask * obj_loss + \\\n (1 - obj_mask) * ignore_mask * obj_loss\n # TODO: use binary_crossentropy instead\n class_loss = obj_mask * sparse_categorical_crossentropy(\n true_class_idx, pred_class)\n\n # 6. sum over (batch, gridx, gridy, anchors) => (batch, 1)\n xy_loss = tf.reduce_sum(xy_loss, axis=(1, 2, 3))\n wh_loss = tf.reduce_sum(wh_loss, axis=(1, 2, 3))\n obj_loss = tf.reduce_sum(obj_loss, axis=(1, 2, 3))\n class_loss = tf.reduce_sum(class_loss, axis=(1, 2, 3))\n\n return xy_loss + wh_loss + obj_loss + class_loss\n return yolo_loss\n" ]
[ [ "tensorflow.concat", "tensorflow.stack", "tensorflow.reduce_sum", "tensorflow.cast", "tensorflow.keras.layers.ZeroPadding2D", "tensorflow.keras.layers.Concatenate", "tensorflow.keras.layers.LeakyReLU", "tensorflow.config.experimental.set_memory_growth", "tensorflow.keras.regularizers.l2", "tensorflow.keras.layers.UpSampling2D", "tensorflow.squeeze", "tensorflow.square", "tensorflow.keras.layers.Add", "tensorflow.math.is_inf", "tensorflow.shape", "tensorflow.config.experimental.list_physical_devices", "tensorflow.keras.losses.sparse_categorical_crossentropy", "tensorflow.exp", "tensorflow.keras.Model", "tensorflow.zeros_like", "tensorflow.keras.losses.binary_crossentropy", "tensorflow.split", "numpy.array", "tensorflow.range", "tensorflow.sigmoid", "tensorflow.keras.layers.MaxPool2D", "tensorflow.math.log", "tensorflow.keras.layers.Input" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
israel-cj/GAMA-GEISHA
[ "210101df0e280d5c2eb5d325fc26d551bba74ed6", "210101df0e280d5c2eb5d325fc26d551bba74ed6" ]
[ "secret/gama/genetic_programming/compilers/scikitlearn.py", "secret/gama/search_methods/pygmo_search.py" ]
[ "from datetime import datetime\nimport logging\nimport os\nimport time\nfrom typing import Callable, Tuple, Optional, Sequence\n\nimport stopit\nfrom sklearn.base import TransformerMixin, is_classifier\nfrom sklearn.model_selection import ShuffleSplit, cross_validate, check_cv\nfrom sklearn.pipeline import Pipeline\n\nfrom gama.utilities.evaluation_library import Evaluation\nfrom gama.utilities.generic.stopwatch import Stopwatch\nimport numpy as np\nfrom gama.utilities.metrics import Metric\nfrom gama.genetic_programming.components import Individual, PrimitiveNode, Fitness\n\nlog = logging.getLogger(__name__)\n\n\ndef primitive_node_to_sklearn(primitive_node: PrimitiveNode) -> object:\n hyperparameters = {\n terminal.output: terminal.value for terminal in primitive_node._terminals\n }\n return primitive_node._primitive.identifier(**hyperparameters)\n\n\ndef compile_individual(\n individual: Individual,\n parameter_checks=None,\n preprocessing_steps: Sequence[Tuple[str, TransformerMixin]] = None,\n) -> Pipeline:\n steps = [\n (str(i), primitive_node_to_sklearn(primitive))\n for i, primitive in enumerate(individual.primitives)\n ]\n if preprocessing_steps:\n steps = steps + list(reversed(preprocessing_steps))\n return Pipeline(list(reversed(steps)))\n\n\ndef object_is_valid_pipeline(o):\n \"\"\" Determines if object behaves like a scikit-learn pipeline. \"\"\"\n return (\n o is not None\n and hasattr(o, \"fit\")\n and hasattr(o, \"predict\")\n and hasattr(o, \"steps\")\n )\n\n\ndef evaluate_pipeline(\n pipeline, x, y_train, timeout: float, metrics: Tuple[Metric], cv=5, subsample=None,\n) -> Tuple:\n \"\"\" Score `pipeline` with k-fold CV according to `metrics` on (a subsample of) X, y\n Returns\n -------\n Tuple:\n prediction: np.ndarray if successful, None if not\n scores: tuple with one float per metric, each value is -inf on fail.\n estimators: list of fitted pipelines if successful, None if not\n error: None if successful, otherwise an Exception\n \"\"\"\n if not object_is_valid_pipeline(pipeline):\n raise TypeError(f\"Pipeline must not be None and requires fit, predict, steps.\")\n if not timeout > 0:\n raise ValueError(f\"`timeout` must be greater than 0, is {timeout}.\")\n\n prediction, estimators = None, None\n # default score for e.g. timeout or failure\n scores = tuple([float(\"-inf\")] * len(metrics))\n\n with stopit.ThreadingTimeout(timeout) as c_mgr:\n try:\n if isinstance(subsample, int) and subsample < len(y_train):\n sampler = ShuffleSplit(n_splits=1, train_size=subsample, random_state=0)\n idx, _ = next(sampler.split(x))\n x, y_train = x.iloc[idx, :], y_train[idx]\n\n splitter = check_cv(cv, y_train, is_classifier(pipeline))\n result = cross_validate(\n pipeline,\n x,\n y_train,\n cv=splitter,\n return_estimator=True,\n scoring=[m.name for m in metrics],\n error_score=\"raise\",\n )\n scores = tuple([np.mean(result[f\"test_{m.name}\"]) for m in metrics])\n estimators = result[\"estimator\"]\n\n for (estimator, (_, test)) in zip(estimators, splitter.split(x, y_train)):\n if any([m.requires_probabilities for m in metrics]):\n fold_pred = estimator.predict_proba(x.iloc[test, :])\n else:\n fold_pred = estimator.predict(x.iloc[test, :])\n\n if prediction is None:\n if fold_pred.ndim == 2:\n prediction = np.empty(shape=(len(y_train), fold_pred.shape[1]))\n else:\n prediction = np.empty(shape=(len(y_train),))\n prediction[test] = fold_pred\n\n # prediction, scores, estimators = cross_val_predict_score(\n # pipeline, x, y_train, cv=cv, metrics=metrics\n # )\n except stopit.TimeoutException:\n # This exception is handled by the ThreadingTimeout context manager.\n raise\n except KeyboardInterrupt:\n raise\n except Exception as e:\n return prediction, scores, estimators, e\n\n if c_mgr.state == c_mgr.INTERRUPTED:\n # A TimeoutException was raised, but not by the context manager.\n # This indicates that the outer context manager (the ea) timed out.\n raise stopit.utils.TimeoutException()\n\n if not c_mgr:\n # For now we treat an eval timeout the same way as\n # e.g. NaN exceptions and use the default score.\n return prediction, scores, estimators, stopit.TimeoutException()\n\n return prediction, tuple(scores), estimators, None\n\n\ndef evaluate_individual(\n individual: Individual,\n evaluate_pipeline: Callable,\n timeout: float = 1e6,\n deadline: Optional[float] = None,\n add_length_to_score: bool = True,\n **kwargs,\n) -> Evaluation:\n \"\"\" Evaluate the pipeline specified by individual, and record\n Parameters\n ----------\n individual: Individual\n Blueprint for the pipeline to evaluate.\n evaluate_pipeline: Callable\n Function which takes the pipeline and produces validation predictions,\n scores, estimators and errors.\n timeout: float (default=1e6)\n Maximum time in seconds that the evaluation is allowed to take.\n Don't depend on high accuracy.\n A shorter timeout is imposed if `deadline` is in less than `timeout` seconds.\n deadline: float, optional\n A time in seconds since epoch.\n Cut off evaluation at `deadline` even if `timeout` seconds have not yet elapsed.\n add_length_to_score: bool (default=True)\n Add the length of the individual to the score result of the evaluation.\n **kwargs: Dict, optional (default=None)\n Passed to `evaluate_pipeline` function.\n Returns\n -------\n Evaluation\n \"\"\"\n result = Evaluation(individual, pid=os.getpid())\n result.start_time = datetime.now()\n\n if deadline is not None:\n time_to_deadline = deadline - time.time()\n timeout = min(timeout, time_to_deadline)\n\n with Stopwatch() as wall_time, Stopwatch(time.process_time) as process_time:\n evaluation = evaluate_pipeline(individual.pipeline, timeout=timeout, **kwargs)\n result._predictions, result.score, result._estimators, error = evaluation\n if error is not None:\n result.error = f\"{type(error)} {str(error)}\"\n result.duration = wall_time.elapsed_time\n\n if add_length_to_score:\n result.score = result.score + (-len(individual.primitives),)\n individual.fitness = Fitness(\n result.score,\n result.start_time,\n wall_time.elapsed_time,\n process_time.elapsed_time,\n )\n\n return result", "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 15 17:28:28 2021\n\n@author: 20210595\n\"\"\"\nfrom gama.genetic_programming.components.individual import Individual\nfrom gama.genetic_programming.compilers.scikitlearn import compile_individual\nfrom gama.genetic_programming.components.primitive_node import PrimitiveNode\nfrom gama.genetic_programming.components.primitive import Primitive\nfrom gama.genetic_programming.components.terminal import Terminal\n\n# Packages for pygmo\nimport os\nimport pickle\nimport uuid\nfrom shutil import rmtree\nfrom numpy import genfromtxt\nimport numpy as np\nimport pygmo as pg\nfrom pygmo import *\nfrom gama.configuration.bounds_pygmo import (\n upperBound, \n lowerBound, \n vector_support,\n count_aux\n ) \nfrom gama.configuration.create_individuals import ValuesSearchSpace, IndividuoVector\n\nimport logging\nfrom functools import partial\nfrom typing import Optional, Any, Tuple, Dict, List, Callable\n\nimport pandas as pd\n\nfrom gama.genetic_programming.components import Individual\nfrom gama.genetic_programming.operator_set import OperatorSet\nfrom gama.logging.evaluation_logger import EvaluationLogger\nfrom gama.search_methods.base_search import BaseSearch\nfrom gama.utilities.generic.async_evaluator import AsyncEvaluator\n\nlog = logging.getLogger(__name__)\n \nclass SearchPygmo(BaseSearch):\n \"\"\" Perform asynchronous evolutionary optimization.\n Parameters\n ----------\n population_size: int, optional (default=50)\n Maximum number of individuals in the population at any time.\n max_n_evaluations: int, optional (default=None)\n If specified, only a maximum of `max_n_evaluations` individuals are evaluated.\n If None, the algorithm will be run until interrupted by the user or a timeout.\n restart_callback: Callable[[], bool], optional (default=None)\n Function which takes no arguments and returns True if search restart.\n \"\"\"\n\n def __init__(\n self,\n population_size: Optional[int] = None,\n max_n_evaluations: Optional[int] = None,\n restart_callback: Optional[Callable[[], bool]] = None,\n ):\n super().__init__()\n # maps hyperparameter -> (set value, default)\n self._hyperparameters: Dict[str, Tuple[Any, Any]] = dict(\n population_size=(population_size, 50),\n restart_callback=(restart_callback, None),\n max_n_evaluations=(max_n_evaluations, None),\n )\n self.output = []\n\n def get_parent(evaluation, n) -> str:\n \"\"\" retrieves the nth parent if it exists, '' otherwise. \"\"\"\n if len(evaluation.individual.meta.get(\"parents\", [])) > n:\n return evaluation.individual.meta[\"parents\"][n]\n return \"\"\n\n self.logger = partial(\n EvaluationLogger,\n extra_fields=dict(\n parent0=partial(get_parent, n=0),\n parent1=partial(get_parent, n=1),\n origin=lambda e: e.individual.meta.get(\"origin\", \"unknown\"),\n ),\n )\n\n def dynamic_defaults(self, x: pd.DataFrame, y: pd.DataFrame, time_limit: float):\n pass\n\n def search(self, operations: OperatorSet, start_candidates: List[Individual]):\n self.output = pygmo_serach(\n operations, self.output, start_candidates, **self.hyperparameters\n ) \n\n \ndef top(elementos = 10):\n lista_top = []\n path_use = os.getcwd()\n path = path_use.replace(os.sep, '/')\n path = path + \"/pickle_gama/\"\n for root, dirs, files, in os.walk(path):\n for file in files:\n if file.endswith(\".pkl\"):\n if (file==\"list_successive_halving.pkl\") or (file==\"archipelago_champions.pkl\"):\n print(file)\n else:\n new_f_path = path + file \n try:\n new_lista = pickle.load(open(new_f_path, \"rb\"))\n except:\n new_lista = []\n lista_top = lista_top + new_lista\n print(\"len lista_top\", len(lista_top))\n f_vectors = [new_individual.fitness.values[0] for new_individual in lista_top] \n for i in range(len(f_vectors)):\n if f_vectors[i] == -np.inf:\n f_vectors[i] = -10000\n f_vectors = np.array(f_vectors)\n print(\"Valores para ordenar del fitness\", f_vectors)\n if len(f_vectors) > elementos:\n #indices_best = f_vectors.argsort()[:10]\n indices_best = f_vectors.argsort()[-elementos:][::-1]\n indices_best = indices_best.tolist()\n print(\"indices_best\", indices_best)\n lista_ind_numpy = np.array(lista_top)\n lista_to_return = lista_ind_numpy[indices_best]\n lista_to_return = lista_to_return.tolist()\n print(\"lista_to_return\", lista_to_return)\n print(\"type lista_to_return\", type(lista_to_return))\n return lista_to_return\n else:\n lista_to_return =[]\n return lista_to_return\n\nclass AutoMLProblem(object):\n #save_whiout_evaluation = []\n contador = 0\n def __init__(self, ops, name=\"individual\"):\n self.operator = ops\n self.output = []\n self.name = name\n self.name_previous = name\n self.old_loss = 1000\n self.new_loss = None\n \n # Define objectives\n def fitness(self, x):\n #path = path + '/individual10.pkl'\n #os.path.isfile(path)\n AutoMLProblem.contador += 1\n path_use = os.getcwd()\n path = path_use.replace(os.sep, '/')\n path = path + \"/pickle_gama/\" + self.name + \".pkl\"\n instance_individual = ValuesSearchSpace(x)\n individual_from_x = instance_individual.get_individuals()\n if individual_from_x == None:\n print(\"El individuo era None\")\n f1 = -1000\n else:\n try:\n if individual_from_x != None:\n individual_to_use = self._loss_function(self.operator, individual_from_x)\n print(\"Individual evaluated with PyGMO Search Multi-Archipelago 50 generations\", individual_to_use)\n f1 = individual_to_use.fitness.values[0]\n if f1 == -np.inf:\n f1 = -1000\n if -f1 < self.old_loss:\n self.old_loss = -f1\n print(\"The loss is lower than the previous one\", self.old_loss)\n self.output.append(individual_to_use)\n \n print(\"El camino es: \", path)\n self.name = self.name_previous + str(uuid.uuid4())\n path_use = os.getcwd()\n path = path_use.replace(os.sep, '/')\n path = path + \"/pickle_gama/\" + self.name + \".pkl\"\n print(\"Nuevo camino es: \", path)\n \n with open(path, 'wb') as f:\n pickle.dump(self.output, f)\n else:\n print(\"Voy a imprimir el individuo\", individual_to_use)\n f1 = -1000\n except:\n f1 = -1000\n return [-f1]\n \n\n \n # Define bounds\n def get_bounds(self):\n lower = lowerBound\n upper = upperBound\n return (lower, upper)\n \n def _loss_function(self, ops: OperatorSet, ind1: Individual) -> Individual:\n #individual = ops.evaluate(ind1).individual\n print(\"Hi Pieter\", **AsyncEvaluator.defaults)\n #help(ops.evaluate)\n result = ops.evaluate(ind1)\n #result = ops.evaluate(ind1, **AsyncEvaluator.defaults)\n return result.individual\n \n # Return function name\n def get_name(self):\n return \"AutoMLProblem\"\n \n \ndef pygmo_serach(\n ops: OperatorSet,\n output: List[Individual],\n start_candidates: List[Individual],\n restart_callback: Optional[Callable[[], bool]] = None,\n max_n_evaluations: Optional[int] = None,\n population_size: int = 50,\n islands: int = 8,\n iters: int = 5,\n #iters: int = 10,\n) -> List[Individual]:\n #print(AsyncEvaluator.defaults) \n #current_population = output\n print(\"Iterations succesive after para AutoMLBenchmark, exceptions\", iters)\n successive = False\n #Create a folder to save the invididuals\n path_use = os.getcwd()\n path = path_use.replace(os.sep, '/')\n path = path + \"/pickle_gama\"\n\n try: \n #os.mkdir(path) \n os.makedirs(path, exist_ok=True)\n except: \n path = path + \"/list_successive_halving.pkl\"\n list_successive_halving = pickle.load(open(path, \"rb\"))\n print(\"len list_successive_halving\", len(list_successive_halving))\n if len(list_successive_halving)==5:\n eliminar = True\n \n # if eliminar:\n # path_use = os.getcwd()\n # path = path_use.replace(os.sep, '/')\n # path = path + \"/pickle_gama/\"\n # for root, dirs, files, in os.walk(path):\n # for file in files:\n # if file.endswith(\".pkl\"):\n # name_file = path + file\n # os.remove(name_file)\n # # if file == \"buscar.pkl\":\n # # os.remove(file)\n \n \n # if eliminar:\n # path_use = os.getcwd()\n # path = path_use.replace(os.sep, '/')\n # path = path + \"/pickle_gama\"\n # rmtree(path)\n # os.mkdir(path)\n try:\n if eliminar:\n path_use = os.getcwd()\n path = path_use.replace(os.sep, '/')\n path = path + \"/pickle_gama\"\n rmtree(path)\n os.mkdir(path)\n except:\n print(\"Eliminar no ha sido definida\")\n \n path_use = os.getcwd()\n path = path_use.replace(os.sep, '/')\n path = path + \"/pickle_gama/\" + \"list_successive_halving.pkl\"\n if os.path.isfile(path):\n list_successive_halving = pickle.load(open(path, \"rb\"))\n if len(list_successive_halving)<5:\n successive = True\n elif len(list_successive_halving)==5:\n eliminar = True\n \n \n if not successive:\n print(\"Fist step\")\n lista_successive = [1]\n path_use = os.getcwd()\n path = path_use.replace(os.sep, '/')\n path = path + \"/pickle_gama/\" + \"list_successive_halving.pkl\"\n with open(path, 'wb') as f:\n pickle.dump(lista_successive, f)\n \n # lista_aux = []\n f_vectors = []\n path_use = os.getcwd()\n path = path_use.replace(os.sep, '/')\n path = path + \"/pickle_gama/\" + \"warm_start\" + \".pkl\"\n for individual in start_candidates:\n result = ops.evaluate(individual)\n new_ind = result.individual\n loss = new_ind.fitness.values[0]\n f_vectors.append(loss)\n output.append(new_ind)\n with open(path, 'wb') as f:\n pickle.dump(output, f)\n \n x_vectors = []\n for i in output:\n instance_individual_to_vectors = IndividuoVector()\n new_vector = instance_individual_to_vectors(i)\n x_vectors.append(new_vector)\n \n print(\"Ya convertí el warm-start en vectores, new method\")\n \n print(\"START with pygmo\") \n algo = pg.algorithm(pg.de(gen = iters))\n prob = pg.problem(AutoMLProblem(ops)) \n # The initial population\n pop = pg.population(prob)\n for i in range(len(x_vectors)):\n if f_vectors[i] == -np.inf:\n f_vectors[i] = -10000\n pop.push_back(x = x_vectors[i], f = [-f_vectors[i]])\n \n # Changes from here\n r_policy = pg.r_policy(pg.fair_replace(rate=0.5)) # Share 50% of the individulas en each island\n s_policy = pg.s_policy(udsp=pg.select_best())\n archi = pg.archipelago(r_pol=r_policy, s_pol=s_policy, t=pg.topology(pg.fully_connected()))\n broadcast = pg.migration_type(1) # 1 = Broadcast type\n archi.set_migration_type(broadcast)\n # To here\n \n # archi = pg.archipelago(t=pg.topology(pg.ring()))\n # archi = pg.archipelago(t=pg.topology(pg.fully_connected()))\n # archi = pg.archipelago(t=pg.topology(pg.free_form()))\n # archi = pg.archipelago() # unconnected topology\n # archi = pg.archipelago(t=pg.topology(pg.base_bgl_topology())) # this doesn't work, is only the base of a topology\n isl1 = pg.island(algo = pg.algorithm(pg.de(gen = iters)), pop=pop)\n isl2 = pg.island(algo = pg.algorithm(pg.sade(gen = iters)), pop=pop)\n isl3 = pg.island(algo = pg.algorithm(pg.de1220(gen = iters)), pop=pop)\n isl4 = pg.island(algo = pg.algorithm(pg.gwo(gen = iters)), pop=pop)\n isl5 = pg.island(algo = pg.algorithm(pg.pso(gen = iters)), pop=pop)\n isl6 = pg.island(algo = pg.algorithm(pg.pso_gen(gen = iters)), pop=pop)\n isl7 = pg.island(algo = pg.algorithm(pg.sea(gen = iters)), pop=pop)\n isl8 = pg.island(algo = pg.algorithm(pg.bee_colony(gen = iters)), pop=pop)\n isls = [isl1, isl2, isl3, isl4, isl5, isl6, isl7, isl8]\n\n for isl in isls:\n archi.push_back(isl)\n print(\"Acabo de CREAR EL ARCHIPELAGO, EMPEZARÉ A EVOLUCIONAR EN PARALELO\")\n \n #archi = pg.archipelago(n=islands, algo=algo, pop=pop, t=pg.topology(pg.ring()))\n print(\"CREATION OF THE ARCHIPELAGO, IT WILL START THE EVOLUTION IN PARALLEL\")\n print(archi) \n archi.get_champions_f() \n print(archi.get_champions_f()) \n archi.evolve()\n archi.wait()\n archi.wait_check()\n archi.get_champions_f() \n print(archi.get_champions_f()) \n print(\"IT JUST FINISH\")\n print(archi)\n print(\"Let's start with the iterative process\")\n print(\"len archi.get_champions_f()\", len(archi.get_champions_f()))\n print(\"len archi.get_champions_x()[0]\", len(archi.get_champions_x()[0]))\n print(\"len archi.get_champions_x()\", len(archi.get_champions_x()))\n \n \n # final_lista = []\n path_use = os.getcwd()\n path = path_use.replace(os.sep, '/')\n path = path + \"/pickle_gama/\"\n for root, dirs, files, in os.walk(path):\n for file in files:\n if file.endswith(\".pkl\"):\n if (file==\"list_successive_halving.pkl\") or (file==\"archipelago_champions.pkl\"):\n print(file)\n else:\n new_f_path = path + file \n try:\n new_lista = pickle.load(open(new_f_path, \"rb\"))\n except:\n new_lista = []\n output = output + new_lista \n \n # final_output = []\n x_of_island_champion = archi.get_champions_x()\n print(\"El archipelago tiene \", len(x_of_island_champion), \" nuevos individuos\")\n for k in x_of_island_champion:\n final_instance = ValuesSearchSpace(k)\n individual_from_x = final_instance.get_individuals()\n result = ops.evaluate(individual_from_x)\n new_ind = result.individual\n output.append(new_ind)\n path_use = os.getcwd()\n path = path_use.replace(os.sep, '/')\n path = path + \"/pickle_gama/\" + \"archipelago_champions.pkl\"\n with open(path, 'wb') as f:\n pickle.dump(output, f)\n \n # final_lista = final_lista + final_output\n \n # current_population=final_lista + lista_aux\n print(\"Longitud final\", len(output))\n else:\n print(\"Successive step\")\n path_use = os.getcwd()\n path = path_use.replace(os.sep, '/')\n path = path + \"/pickle_gama/\" + \"list_successive_halving.pkl\"\n list_successive_halving = pickle.load(open(path, \"rb\"))\n list_successive_halving.append(1)\n\n \n #New warm_start\n # lista_aux = []\n # f_vectors = []\n path_use = os.getcwd()\n path = path_use.replace(os.sep, '/')\n path = path + \"/pickle_gama/\" + \"archipelago_champions.pkl\"\n new_warm_start=[]\n if os.path.isfile(path):\n print(\"Voy a usar el archipelago anterior\")\n support_to_successive = top()\n new_warm_start = pickle.load(open(path, \"rb\"))\n output = new_warm_start + support_to_successive\n else:\n print(\"Usaré los individuos\")\n \n print(\"Usaré los individuos\")\n # warm starting only 10 individuals\n \n # lista_aux = []\n \n f_vectors = []\n path_use = os.getcwd()\n path = path_use.replace(os.sep, '/')\n path = path + \"/pickle_gama/\" + \"warm_start\" + \".pkl\"\n # for individual in start_candidates:\n for i in range(10):\n result = ops.evaluate(start_candidates[i])\n new_ind = result.start_candidates[i]\n loss = new_ind.fitness.values[0]\n f_vectors.append(loss)\n output.append(new_ind)\n with open(path, 'wb') as f:\n pickle.dump(output, f)\n \n print(\"############################################\")\n \n for por in output:\n print(por)\n \n print(\"############################################\")\n \n print(\"Ya convertí el warm-start en vectores successive, new method\")\n \n output = output + top(elementos=10)\n if len(output) == 0:\n path_use = os.getcwd()\n path = path_use.replace(os.sep, '/')\n path = path + \"/pickle_gama/\"\n for root, dirs, files, in os.walk(path):\n for file in files:\n print(file)\n if file.endswith(\".pkl\"):\n new_f_path = path + file\n if (file==\"list_successive_halving.pkl\"):\n print(\"This won't be take in consideration\")\n #new_lista = pickle.load(open(new_f_path, \"rb\"))\n else:\n try:\n new_lista = pickle.load(open(new_f_path, \"rb\"))\n #print(\"imprimiento new_lista gama.py\", new_lista)\n except:\n print(\"Exception\", file)\n new_lista = []\n output = output + new_lista\n \n #Remove all the .pkl files\n path_use = os.getcwd()\n path = path_use.replace(os.sep, '/')\n path = path + \"/pickle_gama/\"\n for root, dirs, files, in os.walk(path):\n for file in files:\n if file.endswith(\".pkl\"):\n name_file = path + file\n os.remove(name_file)\n # # if file == \"buscar.pkl\":\n # # os.remove(file)\n \n path_use = os.getcwd()\n path = path_use.replace(os.sep, '/')\n path = path + \"/pickle_gama/\" + \"list_successive_halving.pkl\"\n with open(path, 'wb') as f:\n pickle.dump(list_successive_halving, f)\n \n #Now use the previous individuals as new war_start in the archipelago\n f_vectors = [new_individual.fitness.values[0] for new_individual in output] \n x_vectors = []\n for i in output:\n instance_individual_to_vectors = IndividuoVector()\n new_vector = instance_individual_to_vectors(i)\n x_vectors.append(new_vector)\n \n print(\"Ya convertí el warm-start en vectores, new method\")\n \n print(\"START with pygmo\") \n #new_iters=iters\n new_iters = int(iters*len(list_successive_halving))\n print(\"new_iters\", new_iters)\n print(\"len list_successive_halving\", len(list_successive_halving))\n print(\"new_iters\", new_iters)\n algo = pg.algorithm(pg.de(gen = new_iters))\n prob = pg.problem(AutoMLProblem(ops)) \n # The initial population\n pop = pg.population(prob)\n for i in range(len(x_vectors)):\n if f_vectors[i] == -np.inf:\n f_vectors[i] = -10000\n pop.push_back(x = x_vectors[i], f = [-f_vectors[i]])\n \n # # Changes from here\n r_policy = pg.r_policy(pg.fair_replace(rate=0.5)) # Share 50% of the individulas en each island\n s_policy = pg.s_policy(udsp=pg.select_best())\n archi = pg.archipelago(r_pol=r_policy, s_pol=s_policy, t=pg.topology(pg.fully_connected()))\n broadcast = pg.migration_type(1) # 1 = Broadcast type\n archi.set_migration_type(broadcast)\n # To here\n \n # archi = pg.archipelago(t=pg.topology(pg.ring()))\n # archi = pg.archipelago(t=pg.topology(pg.fully_connected()))\n # archi = pg.archipelago(t=pg.topology(pg.free_form()))\n # archi = pg.archipelago() # unconnected topology\n # archi = pg.archipelago(t=pg.topology(pg.base_bgl_topology())) # this doesn't work, is only the base of a topology\n isl1 = pg.island(algo = pg.algorithm(pg.de(gen = iters)), pop=pop)\n isl2 = pg.island(algo = pg.algorithm(pg.sade(gen = iters)), pop=pop)\n isl3 = pg.island(algo = pg.algorithm(pg.de1220(gen = iters)), pop=pop)\n isl4 = pg.island(algo = pg.algorithm(pg.gwo(gen = iters)), pop=pop)\n isl5 = pg.island(algo = pg.algorithm(pg.pso(gen = iters)), pop=pop)\n isl6 = pg.island(algo = pg.algorithm(pg.pso_gen(gen = iters)), pop=pop)\n isl7 = pg.island(algo = pg.algorithm(pg.sea(gen = iters)), pop=pop)\n isl8 = pg.island(algo = pg.algorithm(pg.bee_colony(gen = iters)), pop=pop)\n isls = [isl1, isl2, isl3, isl4, isl5, isl6, isl7, isl8]\n\n for isl in isls:\n archi.push_back(isl)\n print(\"Acabo de CREAR EL ARCHIPELAGO, EMPEZARÉ A EVOLUCIONAR EN PARALELO\")\n \n #archi = pg.archipelago(n=islands, algo=algo, pop=pop, t=pg.topology(pg.ring()))\n print(\"CREATION OF THE ARCHIPELAGO, IT WILL START THE EVOLUTION IN PARALLEL\")\n print(archi) \n archi.get_champions_f() \n print(archi.get_champions_f()) \n archi.evolve()\n archi.wait()\n archi.wait_check()\n archi.get_champions_f() \n print(archi.get_champions_f()) \n print(\"IT JUST FINISH\")\n print(archi)\n print(\"Let's start with the iterative process\")\n print(\"len archi.get_champions_f()\", len(archi.get_champions_f()))\n print(\"len archi.get_champions_x()[0]\", len(archi.get_champions_x()[0]))\n print(\"len archi.get_champions_x()\", len(archi.get_champions_x()))\n \n \n # final_lista = []\n path_use = os.getcwd()\n path = path_use.replace(os.sep, '/')\n path = path + \"/pickle_gama/\"\n for root, dirs, files, in os.walk(path):\n for file in files:\n if file.endswith(\".pkl\"):\n if (file==\"list_successive_halving.pkl\") or (file==\"archipelago_champions.pkl\"):\n print(file)\n else:\n new_f_path = path + file \n try:\n new_lista = pickle.load(open(new_f_path, \"rb\"))\n except:\n new_lista = []\n output = output + new_lista \n \n final_output = []\n x_of_island_champion = archi.get_champions_x()\n print(\"El archipelago tiene \", len(x_of_island_champion), \" nuevos individuos\")\n for k in x_of_island_champion:\n final_instance = ValuesSearchSpace(k)\n individual_from_x = final_instance.get_individuals()\n result = ops.evaluate(individual_from_x)\n new_ind = result.individual\n final_output.append(new_ind)\n path_use = os.getcwd()\n path = path_use.replace(os.sep, '/')\n path = path + \"/pickle_gama/\" + \"archipelago_champions.pkl\"\n with open(path, 'wb') as f:\n pickle.dump(final_output, f)\n \n output = output + final_output\n # current_population=final_lista + new_warm_start\n print(\"Longitud final\", len(output))\n \n return output\n\n\n # import os\n # import pickle\n # path_use = os.getcwd()\n # path = path_use.replace(os.sep, '/')\n # path = path + \"/list_successive_halving.pkl\" \n # lista = [1,1,1,1,1]\n # with open(path, 'wb') as f:\n # pickle.dump(lista, f) \n # # for root, dirs, files, in os.walk(path):\n # # for file in files:\n # # if file.endswith(\".pkl\"):\n # # print(file)\n # # # if file == \"buscar.pkl\":\n # # # os.remove(file)\n \n # # path = path + \"/\"+ \"list_successive_halving.pkl\"\n # # list_successive_halving = pickle.load(open(path, \"rb\"))" ]
[ [ "sklearn.model_selection.cross_validate", "numpy.mean", "sklearn.model_selection.ShuffleSplit", "sklearn.base.is_classifier" ], [ "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
rhong3/GBM
[ "088b1e99f4fe02395b62d324ec4f9e8402417651" ]
[ "Scripts/Slicer.py" ]
[ "\"\"\"\nTile real scn/svs files; used by Cutter.py\n\nCreated on 11/19/2018\n\n*** Removed imlist storage to minimize memory usage 01/24/2019 ***\n\n@author: RH\n\"\"\"\nfrom openslide import OpenSlide\nimport numpy as np\nimport pandas as pd\nimport multiprocessing as mp\nimport staintools\nfrom PIL import Image\n\n\n# check if a tile is background or not; return a blank pixel percentage score\ndef bgcheck(img, ts):\n the_imagea = np.array(img)[:, :, :3]\n the_imagea = np.nan_to_num(the_imagea)\n mask = (the_imagea[:, :, :3] > 200).astype(np.uint8)\n maskb = (the_imagea[:, :, :3] < 50).astype(np.uint8)\n greya = ((np.ptp(the_imagea[0])) < 100).astype(np.uint8)\n greyb = ((np.ptp(the_imagea[1])) < 100).astype(np.uint8)\n greyc = ((np.ptp(the_imagea[2])) < 100).astype(np.uint8)\n grey = greya * greyb * greyc\n mask = mask[:, :, 0] * mask[:, :, 1] * mask[:, :, 2]\n maskb = maskb[:, :, 0] * maskb[:, :, 1] * maskb[:, :, 2]\n white = (np.sum(mask) + np.sum(maskb)) / (ts * ts) + grey\n return white\n\n\n# Tile color normalization\ndef normalization(img, sttd):\n img = np.array(img)[:, :, :3]\n img = staintools.LuminosityStandardizer.standardize(img)\n normalizer = staintools.StainNormalizer(method='vahadane')\n normalizer.fit(sttd)\n img = normalizer.transform(img)\n img = Image.fromarray(img.astype('uint8'), 'RGB')\n return img\n\n\n# tile method; slp is the scn/svs image; n_y is the number of tiles can be cut on y column to be cut;\n# x and y are the upper left position of each tile; tile_size is tile size; stepsize of each step; x0 is the row to cut.\n# outdir is the output directory for images;\n# imloc record each tile's relative and absolute coordinates; imlist is a list of cut tiles (Removed 01/24/2019).\ndef v_slide(slp, n_y, x, y, tile_size, stepsize, x0, outdir, level, dp, std):\n # pid = os.getpid()\n # print('{}: start working'.format(pid))\n slide = OpenSlide(slp)\n imloc = []\n y0 = 0\n target_x = x0 * stepsize\n image_x = (target_x + x)*(4**level)\n while y0 < n_y:\n target_y = y0 * stepsize\n image_y = (target_y + y)*(4**level)\n img = slide.read_region((image_x, image_y), level, (tile_size, tile_size))\n wscore = bgcheck(img, tile_size)\n if 0.01 < wscore < 0.4:\n img = img.resize((299, 299))\n img = normalization(img, std)\n if dp:\n img.save(outdir + \"/region_x-{}-y-{}_{}.png\".format(image_x, image_y, str(dp)))\n strr = outdir + \"/region_x-{}-y-{}_{}.png\".format(image_x, image_y, str(dp))\n else:\n img.save(outdir + \"/region_x-{}-y-{}.png\".format(image_x, image_y))\n strr = outdir + \"/region_x-{}-y-{}.png\".format(image_x, image_y)\n imloc.append([x0, y0, image_x, image_y, strr])\n y0 += 1\n slide.close()\n return imloc\n\n\n# image_file is the scn/svs name; outdir is the output directory; path_to_slide is where the scn/svs stored.\n# First open the slide, determine how many tiles can be cut, record the residue edges width,\n# and calculate the final output prediction heat map size should be. Then, using multithread to cut tiles, and stack up\n# tiles and their position dictionaries.\ndef tile(image_file, outdir, level, std_img, path_to_slide=\"../images/\", dp=None, ft=1):\n slide = OpenSlide(path_to_slide+image_file)\n slp = str(path_to_slide+image_file)\n print(slp)\n print(slide.level_dimensions)\n\n bounds_width = slide.level_dimensions[level][0]\n bounds_height = slide.level_dimensions[level][1]\n x = 0\n y = 0\n half_width_region = 49*ft\n full_width_region = 299*ft\n stepsize = (full_width_region - half_width_region)\n\n n_x = int((bounds_width - 1) / stepsize)\n n_y = int((bounds_height - 1) / stepsize)\n\n residue_x = int((bounds_width - n_x * stepsize)/50)\n residue_y = int((bounds_height - n_y * stepsize)/50)\n lowres = slide.read_region((x, y), 2, (int(n_x*stepsize/16), int(n_y*stepsize/16)))\n lowres = np.array(lowres)[:,:,:3]\n\n x0 = 0\n # create multiporcessing pool\n print(mp.cpu_count())\n pool = mp.Pool(processes=mp.cpu_count())\n tasks = []\n while x0 < n_x:\n task = tuple((slp, n_y, x, y, full_width_region, stepsize, x0, outdir, level, dp, std_img))\n tasks.append(task)\n x0 += 1\n # slice images with multiprocessing\n temp = pool.starmap(v_slide, tasks)\n tempdict = list(temp)\n temp = None\n pool.close()\n pool.join()\n\n tempdict = list(filter(None, tempdict))\n imloc = []\n list(map(imloc.extend, tempdict))\n imlocpd = pd.DataFrame(imloc, columns = [\"X_pos\", \"Y_pos\", \"X\", \"Y\", \"Loc\"])\n imlocpd = imlocpd.sort_values([\"X_pos\", \"Y_pos\"], ascending=[True, True])\n imlocpd = imlocpd.reset_index(drop=True)\n imlocpd = imlocpd.reset_index(drop=False)\n imlocpd.columns = [\"Num\", \"X_pos\", \"Y_pos\", \"X\", \"Y\", \"Loc\"]\n if dp:\n imlocpd.to_csv(outdir + \"/{}_dict.csv\".format(dp), index=False)\n else:\n imlocpd.to_csv(outdir + \"/dict.csv\", index=False)\n tempdict = None\n ct = len(imloc)\n print(ct)\n\n return n_x, n_y, lowres, residue_x, residue_y, ct\n\n\n" ]
[ [ "numpy.ptp", "numpy.nan_to_num", "pandas.DataFrame", "numpy.array", "numpy.sum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
MarkWuNLP/StreamingTransformer
[ "df9bfe348608b7e55ef1ff70464070c0055ea799" ]
[ "espnet/asr/pytorch_backend/asr_recog.py" ]
[ "#!/usr/bin/env python3\n# encoding: utf-8\n\n# Copyright 2017 Johns Hopkins University (Shinji Watanabe)\n# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)\n\n\"\"\"Training/decoding definition for the speech recognition task.\"\"\"\n\nimport json\nimport logging\nimport os\n\nimport numpy as np\nimport torch\n\nfrom espnet.asr.asr_utils import add_results_to_json, add_single_results\nfrom espnet.asr.asr_utils import get_model_conf\nfrom espnet.asr.asr_utils import torch_load\nfrom espnet.asr.pytorch_backend.asr_init import load_trained_model\nimport espnet.nets.pytorch_backend.lm.default as lm_pytorch\nfrom espnet.utils.deterministic_utils import set_deterministic_pytorch\nfrom espnet.utils.dynamic_import import dynamic_import\nfrom espnet.utils.io_utils import LoadInputsAndTargets\n\n\ndef _recursive_to(xs, device):\n if torch.is_tensor(xs):\n return xs.to(device)\n if isinstance(xs, tuple):\n return tuple(_recursive_to(x, device) for x in xs)\n return xs\n\n\ndef recog(args):\n \"\"\"Decode with the given args.\n\n Args:\n args (namespace): The program arguments.\n\n \"\"\"\n set_deterministic_pytorch(args)\n model, train_args = load_trained_model(args.model)\n model.recog_args = args\n\n\n # read rnnlm\n if args.rnnlm:\n rnnlm_args = get_model_conf(args.rnnlm, args.rnnlm_conf)\n if getattr(rnnlm_args, \"model_module\", \"default\") != \"default\":\n raise ValueError(\n \"use '--api v2' option to decode with non-default language model\"\n )\n rnnlm = lm_pytorch.ClassifierWithState(\n lm_pytorch.RNNLM(\n len(train_args.char_list),\n rnnlm_args.layer,\n rnnlm_args.unit,\n getattr(rnnlm_args, \"embed_unit\", None), # for backward compatibility\n )\n )\n torch_load(args.rnnlm, rnnlm)\n rnnlm.eval()\n else:\n rnnlm = None\n\n\n # gpu\n if args.ngpu == 1:\n gpu_id = list(range(args.ngpu))\n logging.info(\"gpu id: \" + str(gpu_id))\n model.cuda()\n if rnnlm:\n rnnlm.cuda()\n\n # read json data\n with open(args.recog_json, \"rb\") as f:\n js = json.load(f)[\"utts\"]\n new_js = {}\n\n load_inputs_and_targets = LoadInputsAndTargets(\n mode=\"asr\",\n load_output=False,\n sort_in_input_length=False,\n preprocess_conf=train_args.preprocess_conf\n if args.preprocess_conf is None\n else args.preprocess_conf,\n preprocess_args={\"train\": False},\n )\n\n with torch.no_grad():\n for idx, name in enumerate(js.keys(), 1):\n logging.info(\"(%d/%d) decoding \" + name, idx, len(js.keys()))\n batch = [(name, js[name])]\n feat = load_inputs_and_targets(batch)\n feat = feat[0][0]\n if args.prefix_decode:\n best, ids, score = model.prefix_recognize(feat, args, train_args, train_args.char_list, rnnlm)\n new_js[name] = add_single_results(js[name], best, ids, score)\n else:\n nbest_hyps = model.recognize(\n feat, args, train_args.char_list, rnnlm\n )\n new_js[name] = add_results_to_json(\n js[name], nbest_hyps, train_args.char_list\n )\n\n\n with open(args.result_label, \"wb\") as f:\n f.write(\n json.dumps(\n {\"utts\": new_js}, indent=4, ensure_ascii=False, sort_keys=True\n ).encode(\"utf_8\")\n )\n\ndef viterbi_decode(args):\n set_deterministic_pytorch(args)\n idim, odim, train_args = get_model_conf(\n args.model, os.path.join(os.path.dirname(args.model), 'model.json'))\n model_class = dynamic_import(train_args.model_module)\n model = model_class(idim, odim, train_args)\n if args.model is not None:\n load_params = dict(torch.load(args.model))\n if 'model' in load_params:\n load_params = dict(load_params['model'])\n if 'state_dict' in load_params:\n load_params = dict(load_params['state_dict'])\n model_params = dict(model.named_parameters())\n for k, v in load_params.items():\n k = k.replace('module.', '')\n if k in model_params and v.size() == model_params[k].size():\n model_params[k].data = v.data\n logging.warning('load parameters {}'.format(k))\n model.recog_args = args\n\n if args.ngpu == 1:\n gpu_id = list(range(args.ngpu))\n logging.info('gpu id: ' + str(gpu_id))\n model.cuda()\n\n with open(args.recog_json, 'rb') as f:\n js = json.load(f)['utts']\n new_js = {}\n\n\n load_inputs_and_targets = LoadInputsAndTargets(\n mode='asr', load_output=False, sort_in_input_length=False,\n preprocess_conf=train_args.preprocess_conf\n if args.preprocess_conf is None else args.preprocess_conf,\n preprocess_args={'train': False})\n\n\n with torch.no_grad():\n for idx, name in enumerate(js.keys(), 1):\n logging.info('(%d/%d) decoding ' + name, idx, len(js.keys()))\n batch = [(name, js[name])]\n feat = load_inputs_and_targets(batch)\n y = np.fromiter(map(int, batch[0][1]['output'][0]['tokenid'].split()), dtype=np.int64)\n align = model.viterbi_decode(feat[0][0], y)\n assert len(align) == len(y)\n new_js[name] = js[name]\n new_js[name]['output'][0]['align'] = ' '.join([str(i) for i in list(align)])\n\n with open(args.result_label, 'wb') as f:\n f.write(json.dumps({'utts': new_js}, indent=4, ensure_ascii=False, sort_keys=True).encode('utf_8'))\n" ]
[ [ "torch.no_grad", "torch.is_tensor", "torch.load" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jiyauppal/face-mask-detector.github.io
[ "210ce81fa37c441a076fbb8db28376268e634412" ]
[ "draw_tracking_line.py" ]
[ "import cv2\r\nimport datetime\r\nimport imutils\r\nimport numpy as np\r\nfrom centroidtracker import CentroidTracker\r\nfrom collections import defaultdict\r\n\r\nprotopath = \"MobileNetSSD_deploy.prototxt\"\r\nmodelpath = \"MobileNetSSD_deploy.caffemodel\"\r\ndetector = cv2.dnn.readNetFromCaffe(prototxt=protopath, caffeModel=modelpath)\r\n\r\n# Only enable it if you are using OpenVino environment\r\n# detector.setPreferableBackend(cv2.dnn.DNN_BACKEND_INFERENCE_ENGINE)\r\n# detector.setPreferableTarget(cv2.dnn.DNN_TARGET_CPU)\r\n\r\n\r\nCLASSES = [\"background\", \"aeroplane\", \"bicycle\", \"bird\", \"boat\",\r\n \"bottle\", \"bus\", \"car\", \"cat\", \"chair\", \"cow\", \"diningtable\",\r\n \"dog\", \"horse\", \"motorbike\", \"person\", \"pottedplant\", \"sheep\",\r\n \"sofa\", \"train\", \"tvmonitor\"]\r\n\r\ntracker = CentroidTracker(maxDisappeared=80, maxDistance=90)\r\n\r\n\r\ndef non_max_suppression_fast(boxes, overlapThresh):\r\n try:\r\n if len(boxes) == 0:\r\n return []\r\n\r\n if boxes.dtype.kind == \"i\":\r\n boxes = boxes.astype(\"float\")\r\n\r\n pick = []\r\n\r\n x1 = boxes[:, 0]\r\n y1 = boxes[:, 1]\r\n x2 = boxes[:, 2]\r\n y2 = boxes[:, 3]\r\n\r\n area = (x2 - x1 + 1) * (y2 - y1 + 1)\r\n idxs = np.argsort(y2)\r\n\r\n while len(idxs) > 0:\r\n last = len(idxs) - 1\r\n i = idxs[last]\r\n pick.append(i)\r\n\r\n xx1 = np.maximum(x1[i], x1[idxs[:last]])\r\n yy1 = np.maximum(y1[i], y1[idxs[:last]])\r\n xx2 = np.minimum(x2[i], x2[idxs[:last]])\r\n yy2 = np.minimum(y2[i], y2[idxs[:last]])\r\n\r\n w = np.maximum(0, xx2 - xx1 + 1)\r\n h = np.maximum(0, yy2 - yy1 + 1)\r\n\r\n overlap = (w * h) / area[idxs[:last]]\r\n\r\n idxs = np.delete(idxs, np.concatenate(([last],\r\n np.where(overlap > overlapThresh)[0])))\r\n\r\n return boxes[pick].astype(\"int\")\r\n except Exception as e:\r\n print(\"Exception occurred in non_max_suppression : {}\".format(e))\r\n\r\n\r\ndef main():\r\n cap = cv2.VideoCapture('test_video.mp4')\r\n\r\n fps_start_time = datetime.datetime.now()\r\n fps = 0\r\n total_frames = 0\r\n centroid_dict = defaultdict(list)\r\n object_id_list = []\r\n\r\n while True:\r\n ret, frame = cap.read()\r\n frame = imutils.resize(frame, width=600)\r\n total_frames = total_frames + 1\r\n\r\n (H, W) = frame.shape[:2]\r\n\r\n blob = cv2.dnn.blobFromImage(frame, 0.007843, (W, H), 127.5)\r\n\r\n detector.setInput(blob)\r\n person_detections = detector.forward()\r\n rects = []\r\n for i in np.arange(0, person_detections.shape[2]):\r\n confidence = person_detections[0, 0, i, 2]\r\n if confidence > 0.5:\r\n idx = int(person_detections[0, 0, i, 1])\r\n\r\n if CLASSES[idx] != \"person\":\r\n continue\r\n\r\n person_box = person_detections[0, 0, i, 3:7] * np.array([W, H, W, H])\r\n (startX, startY, endX, endY) = person_box.astype(\"int\")\r\n rects.append(person_box)\r\n\r\n boundingboxes = np.array(rects)\r\n boundingboxes = boundingboxes.astype(int)\r\n rects = non_max_suppression_fast(boundingboxes, 0.3)\r\n\r\n objects = tracker.update(rects)\r\n for (objectId, bbox) in objects.items():\r\n x1, y1, x2, y2 = bbox\r\n x1 = int(x1)\r\n y1 = int(y1)\r\n x2 = int(x2)\r\n y2 = int(y2)\r\n\r\n cX = int((x1 + x2) / 2.0)\r\n cY = int((y1 + y2) / 2.0)\r\n cv2.circle(frame, (cX, cY), 4, (0, 255, 0), -1)\r\n\r\n centroid_dict[objectId].append((cX, cY))\r\n if objectId not in object_id_list:\r\n object_id_list.append(objectId)\r\n start_pt = (cX, cY)\r\n end_pt = (cX, cY)\r\n cv2.line(frame, start_pt, end_pt, (0, 255, 0), 2)\r\n else:\r\n l = len(centroid_dict[objectId])\r\n for pt in range(len(centroid_dict[objectId])):\r\n if not pt + 1 == l:\r\n start_pt = (centroid_dict[objectId][pt][0], centroid_dict[objectId][pt][1])\r\n end_pt = (centroid_dict[objectId][pt + 1][0], centroid_dict[objectId][pt + 1][1])\r\n cv2.line(frame, start_pt, end_pt, (0, 255, 0), 2)\r\n\r\n cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 0, 255), 2)\r\n text = \"ID: {}\".format(objectId)\r\n cv2.putText(frame, text, (x1, y1 - 5), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 0, 255), 1)\r\n\r\n fps_end_time = datetime.datetime.now()\r\n time_diff = fps_end_time - fps_start_time\r\n if time_diff.seconds == 0:\r\n fps = 0.0\r\n else:\r\n fps = (total_frames / time_diff.seconds)\r\n\r\n fps_text = \"FPS: {:.2f}\".format(fps)\r\n\r\n cv2.putText(frame, fps_text, (5, 30), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 0, 255), 1)\r\n\r\n cv2.imshow(\"Application\", frame)\r\n key = cv2.waitKey(1)\r\n if key == ord('q'):\r\n break\r\n\r\n cv2.destroyAllWindows()\r\n\r\n\r\nmain()\r\n" ]
[ [ "numpy.maximum", "numpy.minimum", "numpy.arange", "numpy.argsort", "numpy.array", "numpy.where" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Elenadisa/PhenCo
[ "f320fc286b90ec566afb5edfe3d6d1e3dcc28497" ]
[ "scripts/py_scripts/calculate_cluster_average.py" ]
[ "#! /usr/bin/env python\n##############################################################################################################################################\n#\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tMETHODS\n##############################################################################################################################################\nimport functions as fn\n\n\n##############################################################################################################################################\n#\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOPTPARSE\n##############################################################################################################################################\nimport optparse\nparser = optparse.OptionParser()\nparser.add_option(\"-c\", \"--cluster file\", dest=\"dictionary\",\n help=\"Input file with the clusters of a network\", metavar=\"FILE\")\nparser.add_option(\"-A\", \"--cluster_id\", dest=\"cluster_id\", \n help=\"column which have clusters identificators\", type='int')\nparser.add_option(\"-B\", \"--item_id\", dest=\"item_id\", \n help=\"column which have HPO o disease identificators\", type='int')\nparser.add_option(\"-m\", \"--model\", dest=\"model_type\",\n help=\"network_type\", metavar=\"str\")\nparser.add_option(\"-n\", \"--model_name\", dest=\"model_name\",\n help=\"network_name\", metavar=\"str\")\nparser.add_option(\"-e\", \"--enrichment_type\", dest=\"enrichment\",\n help=\"type of enrichment\", metavar=\"str\")\nparser.add_option(\"-p\", \"--p_value\", dest=\"pvalue\",\n help=\"pvalue\", metavar=\"float\")\n\n\n(options, args) = parser.parse_args()\n\n###############################################################################################################################################\n# \t\t\t\t\t\t\t\t\t\t\t\t\t\t\tMAIN\n###############################################################################################################################################\nimport numpy as np\nimport os.path as path\n\n#If the principal file exits it makes a dictionary cluster HPO\nif path.exists(options.dictionary): #if the dictionary has a length different to 0 append the length of every cluster in the empty list, esle append 0.\n\tdictionary = fn.build_dictionary(options.dictionary, options.cluster_id, options.item_id)\n\n\tsize = []\t\t#empty list\n\tif int(len(dictionary)) != 0:\t\t\n\t\tfor cluster_id in dictionary:\n\t\t\tsize.append(len(dictionary[cluster_id]))\n\telse:\n\t\tsize.append(0)\n\t \n\tmean = np.mean(size) #Calculate the mean of the clusters length\n\nelse :\t\t\t\t\t#If the dictionary has length 0 the mean of clusters size is 0\n\tmean = 0\n\nprint(options.model_name + \"\\t\" + options.model_type + \"\\t\" + \"Average_Cluster_size_\" + options.enrichment + \"_\" + options.pvalue + \"\\t\" + str(mean))\n\n" ]
[ [ "numpy.mean" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
sntgl/scipy
[ "6660830eb7d7590d56f1377d27bf7ee97bb3adec", "6660830eb7d7590d56f1377d27bf7ee97bb3adec" ]
[ "scipy/stats/_distn_infrastructure.py", "scipy/signal/_fir_filter_design.py" ]
[ "#\n# Author: Travis Oliphant 2002-2011 with contributions from\n# SciPy Developers 2004-2011\n#\nfrom scipy._lib._util import getfullargspec_no_self as _getfullargspec\n\nimport sys\nimport keyword\nimport re\nimport types\nimport warnings\nimport inspect\nfrom itertools import zip_longest\nfrom collections import namedtuple\n\nfrom scipy._lib import doccer\nfrom scipy._lib._util import _lazywhere\nfrom ._distr_params import distcont, distdiscrete\nfrom scipy._lib._util import check_random_state\n\nfrom scipy.special import (comb, chndtr, entr, xlogy, ive)\n\n# for root finding for continuous distribution ppf, and max likelihood\n# estimation\nfrom scipy import optimize\n\n# for functions of continuous distributions (e.g. moments, entropy, cdf)\nfrom scipy import integrate\n\n# to approximate the pdf of a continuous distribution given its cdf\nfrom scipy.misc import derivative\n\n# for scipy.stats.entropy. Attempts to import just that function or file\n# have cause import problems\nfrom scipy import stats\n\nfrom numpy import (arange, putmask, ravel, ones, shape, ndarray, zeros, floor,\n logical_and, log, sqrt, place, argmax, vectorize, asarray,\n nan, inf, isinf, NINF, empty)\n\nimport numpy as np\nfrom ._constants import _XMAX\n\n# These are the docstring parts used for substitution in specific\n# distribution docstrings\n\ndocheaders = {'methods': \"\"\"\\nMethods\\n-------\\n\"\"\",\n 'notes': \"\"\"\\nNotes\\n-----\\n\"\"\",\n 'examples': \"\"\"\\nExamples\\n--------\\n\"\"\"}\n\n_doc_rvs = \"\"\"\\\nrvs(%(shapes)s, loc=0, scale=1, size=1, random_state=None)\n Random variates.\n\"\"\"\n_doc_pdf = \"\"\"\\\npdf(x, %(shapes)s, loc=0, scale=1)\n Probability density function.\n\"\"\"\n_doc_logpdf = \"\"\"\\\nlogpdf(x, %(shapes)s, loc=0, scale=1)\n Log of the probability density function.\n\"\"\"\n_doc_pmf = \"\"\"\\\npmf(k, %(shapes)s, loc=0, scale=1)\n Probability mass function.\n\"\"\"\n_doc_logpmf = \"\"\"\\\nlogpmf(k, %(shapes)s, loc=0, scale=1)\n Log of the probability mass function.\n\"\"\"\n_doc_cdf = \"\"\"\\\ncdf(x, %(shapes)s, loc=0, scale=1)\n Cumulative distribution function.\n\"\"\"\n_doc_logcdf = \"\"\"\\\nlogcdf(x, %(shapes)s, loc=0, scale=1)\n Log of the cumulative distribution function.\n\"\"\"\n_doc_sf = \"\"\"\\\nsf(x, %(shapes)s, loc=0, scale=1)\n Survival function (also defined as ``1 - cdf``, but `sf` is sometimes more accurate).\n\"\"\"\n_doc_logsf = \"\"\"\\\nlogsf(x, %(shapes)s, loc=0, scale=1)\n Log of the survival function.\n\"\"\"\n_doc_ppf = \"\"\"\\\nppf(q, %(shapes)s, loc=0, scale=1)\n Percent point function (inverse of ``cdf`` --- percentiles).\n\"\"\"\n_doc_isf = \"\"\"\\\nisf(q, %(shapes)s, loc=0, scale=1)\n Inverse survival function (inverse of ``sf``).\n\"\"\"\n_doc_moment = \"\"\"\\\nmoment(order, %(shapes)s, loc=0, scale=1)\n Non-central moment of the specified order.\n\"\"\"\n_doc_stats = \"\"\"\\\nstats(%(shapes)s, loc=0, scale=1, moments='mv')\n Mean('m'), variance('v'), skew('s'), and/or kurtosis('k').\n\"\"\"\n_doc_entropy = \"\"\"\\\nentropy(%(shapes)s, loc=0, scale=1)\n (Differential) entropy of the RV.\n\"\"\"\n_doc_fit = \"\"\"\\\nfit(data)\n Parameter estimates for generic data.\n See `scipy.stats.rv_continuous.fit <https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.rv_continuous.fit.html#scipy.stats.rv_continuous.fit>`__ for detailed documentation of the\n keyword arguments.\n\"\"\"\n_doc_expect = \"\"\"\\\nexpect(func, args=(%(shapes_)s), loc=0, scale=1, lb=None, ub=None, conditional=False, **kwds)\n Expected value of a function (of one argument) with respect to the distribution.\n\"\"\"\n_doc_expect_discrete = \"\"\"\\\nexpect(func, args=(%(shapes_)s), loc=0, lb=None, ub=None, conditional=False)\n Expected value of a function (of one argument) with respect to the distribution.\n\"\"\"\n_doc_median = \"\"\"\\\nmedian(%(shapes)s, loc=0, scale=1)\n Median of the distribution.\n\"\"\"\n_doc_mean = \"\"\"\\\nmean(%(shapes)s, loc=0, scale=1)\n Mean of the distribution.\n\"\"\"\n_doc_var = \"\"\"\\\nvar(%(shapes)s, loc=0, scale=1)\n Variance of the distribution.\n\"\"\"\n_doc_std = \"\"\"\\\nstd(%(shapes)s, loc=0, scale=1)\n Standard deviation of the distribution.\n\"\"\"\n_doc_interval = \"\"\"\\\ninterval(confidence, %(shapes)s, loc=0, scale=1)\n Confidence interval with equal areas around the median.\n\"\"\"\n_doc_allmethods = ''.join([docheaders['methods'], _doc_rvs, _doc_pdf,\n _doc_logpdf, _doc_cdf, _doc_logcdf, _doc_sf,\n _doc_logsf, _doc_ppf, _doc_isf, _doc_moment,\n _doc_stats, _doc_entropy, _doc_fit,\n _doc_expect, _doc_median,\n _doc_mean, _doc_var, _doc_std, _doc_interval])\n\n_doc_default_longsummary = \"\"\"\\\nAs an instance of the `rv_continuous` class, `%(name)s` object inherits from it\na collection of generic methods (see below for the full list),\nand completes them with details specific for this particular distribution.\n\"\"\"\n\n_doc_default_frozen_note = \"\"\"\nAlternatively, the object may be called (as a function) to fix the shape,\nlocation, and scale parameters returning a \"frozen\" continuous RV object:\n\nrv = %(name)s(%(shapes)s, loc=0, scale=1)\n - Frozen RV object with the same methods but holding the given shape,\n location, and scale fixed.\n\"\"\"\n_doc_default_example = \"\"\"\\\nExamples\n--------\n>>> from scipy.stats import %(name)s\n>>> import matplotlib.pyplot as plt\n>>> fig, ax = plt.subplots(1, 1)\n\nCalculate the first four moments:\n\n%(set_vals_stmt)s\n>>> mean, var, skew, kurt = %(name)s.stats(%(shapes)s, moments='mvsk')\n\nDisplay the probability density function (``pdf``):\n\n>>> x = np.linspace(%(name)s.ppf(0.01, %(shapes)s),\n... %(name)s.ppf(0.99, %(shapes)s), 100)\n>>> ax.plot(x, %(name)s.pdf(x, %(shapes)s),\n... 'r-', lw=5, alpha=0.6, label='%(name)s pdf')\n\nAlternatively, the distribution object can be called (as a function)\nto fix the shape, location and scale parameters. This returns a \"frozen\"\nRV object holding the given parameters fixed.\n\nFreeze the distribution and display the frozen ``pdf``:\n\n>>> rv = %(name)s(%(shapes)s)\n>>> ax.plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf')\n\nCheck accuracy of ``cdf`` and ``ppf``:\n\n>>> vals = %(name)s.ppf([0.001, 0.5, 0.999], %(shapes)s)\n>>> np.allclose([0.001, 0.5, 0.999], %(name)s.cdf(vals, %(shapes)s))\nTrue\n\nGenerate random numbers:\n\n>>> r = %(name)s.rvs(%(shapes)s, size=1000)\n\nAnd compare the histogram:\n\n>>> ax.hist(r, density=True, histtype='stepfilled', alpha=0.2)\n>>> ax.legend(loc='best', frameon=False)\n>>> plt.show()\n\n\"\"\"\n\n_doc_default_locscale = \"\"\"\\\nThe probability density above is defined in the \"standardized\" form. To shift\nand/or scale the distribution use the ``loc`` and ``scale`` parameters.\nSpecifically, ``%(name)s.pdf(x, %(shapes)s, loc, scale)`` is identically\nequivalent to ``%(name)s.pdf(y, %(shapes)s) / scale`` with\n``y = (x - loc) / scale``. Note that shifting the location of a distribution\ndoes not make it a \"noncentral\" distribution; noncentral generalizations of\nsome distributions are available in separate classes.\n\"\"\"\n\n_doc_default = ''.join([_doc_default_longsummary,\n _doc_allmethods,\n '\\n',\n _doc_default_example])\n\n_doc_default_before_notes = ''.join([_doc_default_longsummary,\n _doc_allmethods])\n\ndocdict = {\n 'rvs': _doc_rvs,\n 'pdf': _doc_pdf,\n 'logpdf': _doc_logpdf,\n 'cdf': _doc_cdf,\n 'logcdf': _doc_logcdf,\n 'sf': _doc_sf,\n 'logsf': _doc_logsf,\n 'ppf': _doc_ppf,\n 'isf': _doc_isf,\n 'stats': _doc_stats,\n 'entropy': _doc_entropy,\n 'fit': _doc_fit,\n 'moment': _doc_moment,\n 'expect': _doc_expect,\n 'interval': _doc_interval,\n 'mean': _doc_mean,\n 'std': _doc_std,\n 'var': _doc_var,\n 'median': _doc_median,\n 'allmethods': _doc_allmethods,\n 'longsummary': _doc_default_longsummary,\n 'frozennote': _doc_default_frozen_note,\n 'example': _doc_default_example,\n 'default': _doc_default,\n 'before_notes': _doc_default_before_notes,\n 'after_notes': _doc_default_locscale\n}\n\n# Reuse common content between continuous and discrete docs, change some\n# minor bits.\ndocdict_discrete = docdict.copy()\n\ndocdict_discrete['pmf'] = _doc_pmf\ndocdict_discrete['logpmf'] = _doc_logpmf\ndocdict_discrete['expect'] = _doc_expect_discrete\n_doc_disc_methods = ['rvs', 'pmf', 'logpmf', 'cdf', 'logcdf', 'sf', 'logsf',\n 'ppf', 'isf', 'stats', 'entropy', 'expect', 'median',\n 'mean', 'var', 'std', 'interval']\nfor obj in _doc_disc_methods:\n docdict_discrete[obj] = docdict_discrete[obj].replace(', scale=1', '')\n\n_doc_disc_methods_err_varname = ['cdf', 'logcdf', 'sf', 'logsf']\nfor obj in _doc_disc_methods_err_varname:\n docdict_discrete[obj] = docdict_discrete[obj].replace('(x, ', '(k, ')\n\ndocdict_discrete.pop('pdf')\ndocdict_discrete.pop('logpdf')\n\n_doc_allmethods = ''.join([docdict_discrete[obj] for obj in _doc_disc_methods])\ndocdict_discrete['allmethods'] = docheaders['methods'] + _doc_allmethods\n\ndocdict_discrete['longsummary'] = _doc_default_longsummary.replace(\n 'rv_continuous', 'rv_discrete')\n\n_doc_default_frozen_note = \"\"\"\nAlternatively, the object may be called (as a function) to fix the shape and\nlocation parameters returning a \"frozen\" discrete RV object:\n\nrv = %(name)s(%(shapes)s, loc=0)\n - Frozen RV object with the same methods but holding the given shape and\n location fixed.\n\"\"\"\ndocdict_discrete['frozennote'] = _doc_default_frozen_note\n\n_doc_default_discrete_example = \"\"\"\\\nExamples\n--------\n>>> from scipy.stats import %(name)s\n>>> import matplotlib.pyplot as plt\n>>> fig, ax = plt.subplots(1, 1)\n\nCalculate the first four moments:\n\n%(set_vals_stmt)s\n>>> mean, var, skew, kurt = %(name)s.stats(%(shapes)s, moments='mvsk')\n\nDisplay the probability mass function (``pmf``):\n\n>>> x = np.arange(%(name)s.ppf(0.01, %(shapes)s),\n... %(name)s.ppf(0.99, %(shapes)s))\n>>> ax.plot(x, %(name)s.pmf(x, %(shapes)s), 'bo', ms=8, label='%(name)s pmf')\n>>> ax.vlines(x, 0, %(name)s.pmf(x, %(shapes)s), colors='b', lw=5, alpha=0.5)\n\nAlternatively, the distribution object can be called (as a function)\nto fix the shape and location. This returns a \"frozen\" RV object holding\nthe given parameters fixed.\n\nFreeze the distribution and display the frozen ``pmf``:\n\n>>> rv = %(name)s(%(shapes)s)\n>>> ax.vlines(x, 0, rv.pmf(x), colors='k', linestyles='-', lw=1,\n... label='frozen pmf')\n>>> ax.legend(loc='best', frameon=False)\n>>> plt.show()\n\nCheck accuracy of ``cdf`` and ``ppf``:\n\n>>> prob = %(name)s.cdf(x, %(shapes)s)\n>>> np.allclose(x, %(name)s.ppf(prob, %(shapes)s))\nTrue\n\nGenerate random numbers:\n\n>>> r = %(name)s.rvs(%(shapes)s, size=1000)\n\"\"\"\n\n\n_doc_default_discrete_locscale = \"\"\"\\\nThe probability mass function above is defined in the \"standardized\" form.\nTo shift distribution use the ``loc`` parameter.\nSpecifically, ``%(name)s.pmf(k, %(shapes)s, loc)`` is identically\nequivalent to ``%(name)s.pmf(k - loc, %(shapes)s)``.\n\"\"\"\n\ndocdict_discrete['example'] = _doc_default_discrete_example\ndocdict_discrete['after_notes'] = _doc_default_discrete_locscale\n\n_doc_default_before_notes = ''.join([docdict_discrete['longsummary'],\n docdict_discrete['allmethods']])\ndocdict_discrete['before_notes'] = _doc_default_before_notes\n\n_doc_default_disc = ''.join([docdict_discrete['longsummary'],\n docdict_discrete['allmethods'],\n docdict_discrete['frozennote'],\n docdict_discrete['example']])\ndocdict_discrete['default'] = _doc_default_disc\n\n# clean up all the separate docstring elements, we do not need them anymore\nfor obj in [s for s in dir() if s.startswith('_doc_')]:\n exec('del ' + obj)\ndel obj\n\n\ndef _moment(data, n, mu=None):\n if mu is None:\n mu = data.mean()\n return ((data - mu)**n).mean()\n\n\ndef _moment_from_stats(n, mu, mu2, g1, g2, moment_func, args):\n if (n == 0):\n return 1.0\n elif (n == 1):\n if mu is None:\n val = moment_func(1, *args)\n else:\n val = mu\n elif (n == 2):\n if mu2 is None or mu is None:\n val = moment_func(2, *args)\n else:\n val = mu2 + mu*mu\n elif (n == 3):\n if g1 is None or mu2 is None or mu is None:\n val = moment_func(3, *args)\n else:\n mu3 = g1 * np.power(mu2, 1.5) # 3rd central moment\n val = mu3+3*mu*mu2+mu*mu*mu # 3rd non-central moment\n elif (n == 4):\n if g1 is None or g2 is None or mu2 is None or mu is None:\n val = moment_func(4, *args)\n else:\n mu4 = (g2+3.0)*(mu2**2.0) # 4th central moment\n mu3 = g1*np.power(mu2, 1.5) # 3rd central moment\n val = mu4+4*mu*mu3+6*mu*mu*mu2+mu*mu*mu*mu\n else:\n val = moment_func(n, *args)\n\n return val\n\n\ndef _skew(data):\n \"\"\"\n skew is third central moment / variance**(1.5)\n \"\"\"\n data = np.ravel(data)\n mu = data.mean()\n m2 = ((data - mu)**2).mean()\n m3 = ((data - mu)**3).mean()\n return m3 / np.power(m2, 1.5)\n\n\ndef _kurtosis(data):\n \"\"\"kurtosis is fourth central moment / variance**2 - 3.\"\"\"\n data = np.ravel(data)\n mu = data.mean()\n m2 = ((data - mu)**2).mean()\n m4 = ((data - mu)**4).mean()\n return m4 / m2**2 - 3\n\n\ndef _fit_determine_optimizer(optimizer):\n if not callable(optimizer) and isinstance(optimizer, str):\n if not optimizer.startswith('fmin_'):\n optimizer = \"fmin_\"+optimizer\n if optimizer == 'fmin_':\n optimizer = 'fmin'\n try:\n optimizer = getattr(optimize, optimizer)\n except AttributeError as e:\n raise ValueError(\"%s is not a valid optimizer\" % optimizer) from e\n return optimizer\n\n\n# Frozen RV class\nclass rv_frozen:\n\n def __init__(self, dist, *args, **kwds):\n self.args = args\n self.kwds = kwds\n\n # create a new instance\n self.dist = dist.__class__(**dist._updated_ctor_param())\n\n shapes, _, _ = self.dist._parse_args(*args, **kwds)\n self.a, self.b = self.dist._get_support(*shapes)\n\n @property\n def random_state(self):\n return self.dist._random_state\n\n @random_state.setter\n def random_state(self, seed):\n self.dist._random_state = check_random_state(seed)\n\n def cdf(self, x):\n return self.dist.cdf(x, *self.args, **self.kwds)\n\n def logcdf(self, x):\n return self.dist.logcdf(x, *self.args, **self.kwds)\n\n def ppf(self, q):\n return self.dist.ppf(q, *self.args, **self.kwds)\n\n def isf(self, q):\n return self.dist.isf(q, *self.args, **self.kwds)\n\n def rvs(self, size=None, random_state=None):\n kwds = self.kwds.copy()\n kwds.update({'size': size, 'random_state': random_state})\n return self.dist.rvs(*self.args, **kwds)\n\n def sf(self, x):\n return self.dist.sf(x, *self.args, **self.kwds)\n\n def logsf(self, x):\n return self.dist.logsf(x, *self.args, **self.kwds)\n\n def stats(self, moments='mv'):\n kwds = self.kwds.copy()\n kwds.update({'moments': moments})\n return self.dist.stats(*self.args, **kwds)\n\n def median(self):\n return self.dist.median(*self.args, **self.kwds)\n\n def mean(self):\n return self.dist.mean(*self.args, **self.kwds)\n\n def var(self):\n return self.dist.var(*self.args, **self.kwds)\n\n def std(self):\n return self.dist.std(*self.args, **self.kwds)\n\n def moment(self, order=None, **kwds):\n return self.dist.moment(order, *self.args, **self.kwds, **kwds)\n\n def entropy(self):\n return self.dist.entropy(*self.args, **self.kwds)\n\n def interval(self, confidence=None, **kwds):\n return self.dist.interval(confidence, *self.args, **self.kwds, **kwds)\n\n def expect(self, func=None, lb=None, ub=None, conditional=False, **kwds):\n # expect method only accepts shape parameters as positional args\n # hence convert self.args, self.kwds, also loc/scale\n # See the .expect method docstrings for the meaning of\n # other parameters.\n a, loc, scale = self.dist._parse_args(*self.args, **self.kwds)\n if isinstance(self.dist, rv_discrete):\n return self.dist.expect(func, a, loc, lb, ub, conditional, **kwds)\n else:\n return self.dist.expect(func, a, loc, scale, lb, ub,\n conditional, **kwds)\n\n def support(self):\n return self.dist.support(*self.args, **self.kwds)\n\n\nclass rv_discrete_frozen(rv_frozen):\n\n def pmf(self, k):\n return self.dist.pmf(k, *self.args, **self.kwds)\n\n def logpmf(self, k): # No error\n return self.dist.logpmf(k, *self.args, **self.kwds)\n\n\nclass rv_continuous_frozen(rv_frozen):\n\n def pdf(self, x):\n return self.dist.pdf(x, *self.args, **self.kwds)\n\n def logpdf(self, x):\n return self.dist.logpdf(x, *self.args, **self.kwds)\n\n\ndef argsreduce(cond, *args):\n \"\"\"Clean arguments to:\n\n 1. Ensure all arguments are iterable (arrays of dimension at least one\n 2. If cond != True and size > 1, ravel(args[i]) where ravel(condition) is\n True, in 1D.\n\n Return list of processed arguments.\n\n Examples\n --------\n >>> rng = np.random.default_rng()\n >>> A = rng.random((4, 5))\n >>> B = 2\n >>> C = rng.random((1, 5))\n >>> cond = np.ones(A.shape)\n >>> [A1, B1, C1] = argsreduce(cond, A, B, C)\n >>> A1.shape\n (4, 5)\n >>> B1.shape\n (1,)\n >>> C1.shape\n (1, 5)\n >>> cond[2,:] = 0\n >>> [A1, B1, C1] = argsreduce(cond, A, B, C)\n >>> A1.shape\n (15,)\n >>> B1.shape\n (1,)\n >>> C1.shape\n (15,)\n\n \"\"\"\n # some distributions assume arguments are iterable.\n newargs = np.atleast_1d(*args)\n\n # np.atleast_1d returns an array if only one argument, or a list of arrays\n # if more than one argument.\n if not isinstance(newargs, list):\n newargs = [newargs, ]\n\n if np.all(cond):\n # broadcast arrays with cond\n *newargs, cond = np.broadcast_arrays(*newargs, cond)\n return [arg.ravel() for arg in newargs]\n\n s = cond.shape\n # np.extract returns flattened arrays, which are not broadcastable together\n # unless they are either the same size or size == 1.\n return [(arg if np.size(arg) == 1\n else np.extract(cond, np.broadcast_to(arg, s)))\n for arg in newargs]\n\n\nparse_arg_template = \"\"\"\ndef _parse_args(self, %(shape_arg_str)s %(locscale_in)s):\n return (%(shape_arg_str)s), %(locscale_out)s\n\ndef _parse_args_rvs(self, %(shape_arg_str)s %(locscale_in)s, size=None):\n return self._argcheck_rvs(%(shape_arg_str)s %(locscale_out)s, size=size)\n\ndef _parse_args_stats(self, %(shape_arg_str)s %(locscale_in)s, moments='mv'):\n return (%(shape_arg_str)s), %(locscale_out)s, moments\n\"\"\"\n\n\n# Both the continuous and discrete distributions depend on ncx2.\n# The function name ncx2 is an abbreviation for noncentral chi squared.\n\ndef _ncx2_log_pdf(x, df, nc):\n # We use (xs**2 + ns**2)/2 = (xs - ns)**2/2 + xs*ns, and include the\n # factor of exp(-xs*ns) into the ive function to improve numerical\n # stability at large values of xs. See also `rice.pdf`.\n df2 = df/2.0 - 1.0\n xs, ns = np.sqrt(x), np.sqrt(nc)\n res = xlogy(df2/2.0, x/nc) - 0.5*(xs - ns)**2\n corr = ive(df2, xs*ns) / 2.0\n # Return res + np.log(corr) avoiding np.log(0)\n return _lazywhere(\n corr > 0,\n (res, corr),\n f=lambda r, c: r + np.log(c),\n fillvalue=-np.inf)\n\n\ndef _ncx2_pdf(x, df, nc):\n # Copy of _ncx2_log_pdf avoiding np.log(0) when corr = 0\n df2 = df/2.0 - 1.0\n xs, ns = np.sqrt(x), np.sqrt(nc)\n res = xlogy(df2/2.0, x/nc) - 0.5*(xs - ns)**2\n corr = ive(df2, xs*ns) / 2.0\n return np.exp(res) * corr\n\n\ndef _ncx2_cdf(x, df, nc):\n return chndtr(x, df, nc)\n\n\nclass rv_generic:\n \"\"\"Class which encapsulates common functionality between rv_discrete\n and rv_continuous.\n\n \"\"\"\n def __init__(self, seed=None):\n super().__init__()\n\n # figure out if _stats signature has 'moments' keyword\n sig = _getfullargspec(self._stats)\n self._stats_has_moments = ((sig.varkw is not None) or\n ('moments' in sig.args) or\n ('moments' in sig.kwonlyargs))\n self._random_state = check_random_state(seed)\n\n # For historical reasons, `size` was made an attribute that was read\n # inside _rvs(). The code is being changed so that 'size'\n # is an argument\n # to self._rvs(). However some external (non-SciPy) distributions\n # have not\n # been updated. Maintain backwards compatibility by checking if\n # the self._rvs() signature has the 'size' keyword, or a **kwarg,\n # and if not set self._size inside self.rvs()\n # before calling self._rvs().\n argspec = inspect.getfullargspec(self._rvs)\n self._rvs_uses_size_attribute = (argspec.varkw is None and\n 'size' not in argspec.args and\n 'size' not in argspec.kwonlyargs)\n # Warn on first use only\n self._rvs_size_warned = False\n\n @property\n def random_state(self):\n \"\"\"Get or set the generator object for generating random variates.\n\n If `seed` is None (or `np.random`), the `numpy.random.RandomState`\n singleton is used.\n If `seed` is an int, a new ``RandomState`` instance is used,\n seeded with `seed`.\n If `seed` is already a ``Generator`` or ``RandomState`` instance then\n that instance is used.\n\n \"\"\"\n return self._random_state\n\n @random_state.setter\n def random_state(self, seed):\n self._random_state = check_random_state(seed)\n\n def __setstate__(self, state):\n try:\n self.__dict__.update(state)\n # attaches the dynamically created methods on each instance.\n # if a subclass overrides rv_generic.__setstate__, or implements\n # it's own _attach_methods, then it must make sure that\n # _attach_argparser_methods is called.\n self._attach_methods()\n except ValueError:\n # reconstitute an old pickle scipy<1.6, that contains\n # (_ctor_param, random_state) as state\n self._ctor_param = state[0]\n self._random_state = state[1]\n self.__init__()\n\n def _attach_methods(self):\n \"\"\"Attaches dynamically created methods to the rv_* instance.\n\n This method must be overridden by subclasses, and must itself call\n _attach_argparser_methods. This method is called in __init__ in\n subclasses, and in __setstate__\n \"\"\"\n raise NotImplementedError\n\n def _attach_argparser_methods(self):\n \"\"\"\n Generates the argument-parsing functions dynamically and attaches\n them to the instance.\n\n Should be called from `_attach_methods`, typically in __init__ and\n during unpickling (__setstate__)\n \"\"\"\n ns = {}\n exec(self._parse_arg_template, ns)\n # NB: attach to the instance, not class\n for name in ['_parse_args', '_parse_args_stats', '_parse_args_rvs']:\n setattr(self, name, types.MethodType(ns[name], self))\n\n def _construct_argparser(\n self, meths_to_inspect, locscale_in, locscale_out):\n \"\"\"Construct the parser string for the shape arguments.\n\n This method should be called in __init__ of a class for each\n distribution. It creates the `_parse_arg_template` attribute that is\n then used by `_attach_argparser_methods` to dynamically create and\n attach the `_parse_args`, `_parse_args_stats`, `_parse_args_rvs`\n methods to the instance.\n\n If self.shapes is a non-empty string, interprets it as a\n comma-separated list of shape parameters.\n\n Otherwise inspects the call signatures of `meths_to_inspect`\n and constructs the argument-parsing functions from these.\n In this case also sets `shapes` and `numargs`.\n \"\"\"\n\n if self.shapes:\n # sanitize the user-supplied shapes\n if not isinstance(self.shapes, str):\n raise TypeError('shapes must be a string.')\n\n shapes = self.shapes.replace(',', ' ').split()\n\n for field in shapes:\n if keyword.iskeyword(field):\n raise SyntaxError('keywords cannot be used as shapes.')\n if not re.match('^[_a-zA-Z][_a-zA-Z0-9]*$', field):\n raise SyntaxError(\n 'shapes must be valid python identifiers')\n else:\n # find out the call signatures (_pdf, _cdf etc), deduce shape\n # arguments. Generic methods only have 'self, x', any further args\n # are shapes.\n shapes_list = []\n for meth in meths_to_inspect:\n shapes_args = _getfullargspec(meth) # NB does not contain self\n args = shapes_args.args[1:] # peel off 'x', too\n\n if args:\n shapes_list.append(args)\n\n # *args or **kwargs are not allowed w/automatic shapes\n if shapes_args.varargs is not None:\n raise TypeError(\n '*args are not allowed w/out explicit shapes')\n if shapes_args.varkw is not None:\n raise TypeError(\n '**kwds are not allowed w/out explicit shapes')\n if shapes_args.kwonlyargs:\n raise TypeError(\n 'kwonly args are not allowed w/out explicit shapes')\n if shapes_args.defaults is not None:\n raise TypeError('defaults are not allowed for shapes')\n\n if shapes_list:\n shapes = shapes_list[0]\n\n # make sure the signatures are consistent\n for item in shapes_list:\n if item != shapes:\n raise TypeError('Shape arguments are inconsistent.')\n else:\n shapes = []\n\n # have the arguments, construct the method from template\n shapes_str = ', '.join(shapes) + ', ' if shapes else '' # NB: not None\n dct = dict(shape_arg_str=shapes_str,\n locscale_in=locscale_in,\n locscale_out=locscale_out,\n )\n\n # this string is used by _attach_argparser_methods\n self._parse_arg_template = parse_arg_template % dct\n\n self.shapes = ', '.join(shapes) if shapes else None\n if not hasattr(self, 'numargs'):\n # allows more general subclassing with *args\n self.numargs = len(shapes)\n\n def _construct_doc(self, docdict, shapes_vals=None):\n \"\"\"Construct the instance docstring with string substitutions.\"\"\"\n tempdict = docdict.copy()\n tempdict['name'] = self.name or 'distname'\n tempdict['shapes'] = self.shapes or ''\n\n if shapes_vals is None:\n shapes_vals = ()\n vals = ', '.join('%.3g' % val for val in shapes_vals)\n tempdict['vals'] = vals\n\n tempdict['shapes_'] = self.shapes or ''\n if self.shapes and self.numargs == 1:\n tempdict['shapes_'] += ','\n\n if self.shapes:\n tempdict['set_vals_stmt'] = '>>> %s = %s' % (self.shapes, vals)\n else:\n tempdict['set_vals_stmt'] = ''\n\n if self.shapes is None:\n # remove shapes from call parameters if there are none\n for item in ['default', 'before_notes']:\n tempdict[item] = tempdict[item].replace(\n \"\\n%(shapes)s : array_like\\n shape parameters\", \"\")\n for i in range(2):\n if self.shapes is None:\n # necessary because we use %(shapes)s in two forms (w w/o \", \")\n self.__doc__ = self.__doc__.replace(\"%(shapes)s, \", \"\")\n try:\n self.__doc__ = doccer.docformat(self.__doc__, tempdict)\n except TypeError as e:\n raise Exception(\"Unable to construct docstring for \"\n \"distribution \\\"%s\\\": %s\" %\n (self.name, repr(e))) from e\n\n # correct for empty shapes\n self.__doc__ = self.__doc__.replace('(, ', '(').replace(', )', ')')\n\n def _construct_default_doc(self, longname=None, extradoc=None,\n docdict=None, discrete='continuous'):\n \"\"\"Construct instance docstring from the default template.\"\"\"\n if longname is None:\n longname = 'A'\n if extradoc is None:\n extradoc = ''\n if extradoc.startswith('\\n\\n'):\n extradoc = extradoc[2:]\n self.__doc__ = ''.join(['%s %s random variable.' % (longname, discrete),\n '\\n\\n%(before_notes)s\\n', docheaders['notes'],\n extradoc, '\\n%(example)s'])\n self._construct_doc(docdict)\n\n def freeze(self, *args, **kwds):\n \"\"\"Freeze the distribution for the given arguments.\n\n Parameters\n ----------\n arg1, arg2, arg3,... : array_like\n The shape parameter(s) for the distribution. Should include all\n the non-optional arguments, may include ``loc`` and ``scale``.\n\n Returns\n -------\n rv_frozen : rv_frozen instance\n The frozen distribution.\n\n \"\"\"\n if isinstance(self, rv_continuous):\n return rv_continuous_frozen(self, *args, **kwds)\n else:\n return rv_discrete_frozen(self, *args, **kwds)\n\n def __call__(self, *args, **kwds):\n return self.freeze(*args, **kwds)\n __call__.__doc__ = freeze.__doc__\n\n # The actual calculation functions (no basic checking need be done)\n # If these are defined, the others won't be looked at.\n # Otherwise, the other set can be defined.\n def _stats(self, *args, **kwds):\n return None, None, None, None\n\n # Noncentral moments (also known as the moment about the origin).\n # Expressed in LaTeX, munp would be $\\mu'_{n}$, i.e. \"mu-sub-n-prime\".\n # The primed mu is a widely used notation for the noncentral moment.\n def _munp(self, n, *args):\n # Silence floating point warnings from integration.\n with np.errstate(all='ignore'):\n vals = self.generic_moment(n, *args)\n return vals\n\n def _argcheck_rvs(self, *args, **kwargs):\n # Handle broadcasting and size validation of the rvs method.\n # Subclasses should not have to override this method.\n # The rule is that if `size` is not None, then `size` gives the\n # shape of the result (integer values of `size` are treated as\n # tuples with length 1; i.e. `size=3` is the same as `size=(3,)`.)\n #\n # `args` is expected to contain the shape parameters (if any), the\n # location and the scale in a flat tuple (e.g. if there are two\n # shape parameters `a` and `b`, `args` will be `(a, b, loc, scale)`).\n # The only keyword argument expected is 'size'.\n size = kwargs.get('size', None)\n all_bcast = np.broadcast_arrays(*args)\n\n def squeeze_left(a):\n while a.ndim > 0 and a.shape[0] == 1:\n a = a[0]\n return a\n\n # Eliminate trivial leading dimensions. In the convention\n # used by numpy's random variate generators, trivial leading\n # dimensions are effectively ignored. In other words, when `size`\n # is given, trivial leading dimensions of the broadcast parameters\n # in excess of the number of dimensions in size are ignored, e.g.\n # >>> np.random.normal([[1, 3, 5]], [[[[0.01]]]], size=3)\n # array([ 1.00104267, 3.00422496, 4.99799278])\n # If `size` is not given, the exact broadcast shape is preserved:\n # >>> np.random.normal([[1, 3, 5]], [[[[0.01]]]])\n # array([[[[ 1.00862899, 3.00061431, 4.99867122]]]])\n #\n all_bcast = [squeeze_left(a) for a in all_bcast]\n bcast_shape = all_bcast[0].shape\n bcast_ndim = all_bcast[0].ndim\n\n if size is None:\n size_ = bcast_shape\n else:\n size_ = tuple(np.atleast_1d(size))\n\n # Check compatibility of size_ with the broadcast shape of all\n # the parameters. This check is intended to be consistent with\n # how the numpy random variate generators (e.g. np.random.normal,\n # np.random.beta) handle their arguments. The rule is that, if size\n # is given, it determines the shape of the output. Broadcasting\n # can't change the output size.\n\n # This is the standard broadcasting convention of extending the\n # shape with fewer dimensions with enough dimensions of length 1\n # so that the two shapes have the same number of dimensions.\n ndiff = bcast_ndim - len(size_)\n if ndiff < 0:\n bcast_shape = (1,)*(-ndiff) + bcast_shape\n elif ndiff > 0:\n size_ = (1,)*ndiff + size_\n\n # This compatibility test is not standard. In \"regular\" broadcasting,\n # two shapes are compatible if for each dimension, the lengths are the\n # same or one of the lengths is 1. Here, the length of a dimension in\n # size_ must not be less than the corresponding length in bcast_shape.\n ok = all([bcdim == 1 or bcdim == szdim\n for (bcdim, szdim) in zip(bcast_shape, size_)])\n if not ok:\n raise ValueError(\"size does not match the broadcast shape of \"\n \"the parameters. %s, %s, %s\" % (size, size_,\n bcast_shape))\n\n param_bcast = all_bcast[:-2]\n loc_bcast = all_bcast[-2]\n scale_bcast = all_bcast[-1]\n\n return param_bcast, loc_bcast, scale_bcast, size_\n\n # These are the methods you must define (standard form functions)\n # NB: generic _pdf, _logpdf, _cdf are different for\n # rv_continuous and rv_discrete hence are defined in there\n def _argcheck(self, *args):\n \"\"\"Default check for correct values on args and keywords.\n\n Returns condition array of 1's where arguments are correct and\n 0's where they are not.\n\n \"\"\"\n cond = 1\n for arg in args:\n cond = logical_and(cond, (asarray(arg) > 0))\n return cond\n\n def _get_support(self, *args, **kwargs):\n \"\"\"Return the support of the (unscaled, unshifted) distribution.\n\n *Must* be overridden by distributions which have support dependent\n upon the shape parameters of the distribution. Any such override\n *must not* set or change any of the class members, as these members\n are shared amongst all instances of the distribution.\n\n Parameters\n ----------\n arg1, arg2, ... : array_like\n The shape parameter(s) for the distribution (see docstring of the\n instance object for more information).\n\n Returns\n -------\n a, b : numeric (float, or int or +/-np.inf)\n end-points of the distribution's support for the specified\n shape parameters.\n \"\"\"\n return self.a, self.b\n\n def _support_mask(self, x, *args):\n a, b = self._get_support(*args)\n with np.errstate(invalid='ignore'):\n return (a <= x) & (x <= b)\n\n def _open_support_mask(self, x, *args):\n a, b = self._get_support(*args)\n with np.errstate(invalid='ignore'):\n return (a < x) & (x < b)\n\n def _rvs(self, *args, size=None, random_state=None):\n # This method must handle size being a tuple, and it must\n # properly broadcast *args and size. size might be\n # an empty tuple, which means a scalar random variate is to be\n # generated.\n\n # Use basic inverse cdf algorithm for RV generation as default.\n U = random_state.uniform(size=size)\n Y = self._ppf(U, *args)\n return Y\n\n def _logcdf(self, x, *args):\n with np.errstate(divide='ignore'):\n return log(self._cdf(x, *args))\n\n def _sf(self, x, *args):\n return 1.0-self._cdf(x, *args)\n\n def _logsf(self, x, *args):\n with np.errstate(divide='ignore'):\n return log(self._sf(x, *args))\n\n def _ppf(self, q, *args):\n return self._ppfvec(q, *args)\n\n def _isf(self, q, *args):\n return self._ppf(1.0-q, *args) # use correct _ppf for subclasses\n\n # These are actually called, and should not be overwritten if you\n # want to keep error checking.\n def rvs(self, *args, **kwds):\n \"\"\"Random variates of given type.\n\n Parameters\n ----------\n arg1, arg2, arg3,... : array_like\n The shape parameter(s) for the distribution (see docstring of the\n instance object for more information).\n loc : array_like, optional\n Location parameter (default=0).\n scale : array_like, optional\n Scale parameter (default=1).\n size : int or tuple of ints, optional\n Defining number of random variates (default is 1).\n random_state : {None, int, `numpy.random.Generator`,\n `numpy.random.RandomState`}, optional\n\n If `seed` is None (or `np.random`), the `numpy.random.RandomState`\n singleton is used.\n If `seed` is an int, a new ``RandomState`` instance is used,\n seeded with `seed`.\n If `seed` is already a ``Generator`` or ``RandomState`` instance\n then that instance is used.\n\n Returns\n -------\n rvs : ndarray or scalar\n Random variates of given `size`.\n\n \"\"\"\n discrete = kwds.pop('discrete', None)\n rndm = kwds.pop('random_state', None)\n args, loc, scale, size = self._parse_args_rvs(*args, **kwds)\n cond = logical_and(self._argcheck(*args), (scale >= 0))\n if not np.all(cond):\n message = (\"Domain error in arguments. The `scale` parameter must \"\n \"be positive for all distributions; see the \"\n \"distribution documentation for other restrictions.\")\n raise ValueError(message)\n\n if np.all(scale == 0):\n return loc*ones(size, 'd')\n\n # extra gymnastics needed for a custom random_state\n if rndm is not None:\n random_state_saved = self._random_state\n random_state = check_random_state(rndm)\n else:\n random_state = self._random_state\n\n # Maintain backwards compatibility by setting self._size\n # for distributions that still need it.\n if self._rvs_uses_size_attribute:\n if not self._rvs_size_warned:\n warnings.warn(\n f'The signature of {self._rvs} does not contain '\n f'a \"size\" keyword. Such signatures are deprecated.',\n np.VisibleDeprecationWarning)\n self._rvs_size_warned = True\n self._size = size\n self._random_state = random_state\n vals = self._rvs(*args)\n else:\n vals = self._rvs(*args, size=size, random_state=random_state)\n\n vals = vals * scale + loc\n\n # do not forget to restore the _random_state\n if rndm is not None:\n self._random_state = random_state_saved\n\n # Cast to int if discrete\n if discrete:\n if size == ():\n vals = int(vals)\n else:\n vals = vals.astype(np.int64)\n\n return vals\n\n def stats(self, *args, **kwds):\n \"\"\"Some statistics of the given RV.\n\n Parameters\n ----------\n arg1, arg2, arg3,... : array_like\n The shape parameter(s) for the distribution (see docstring of the\n instance object for more information)\n loc : array_like, optional\n location parameter (default=0)\n scale : array_like, optional (continuous RVs only)\n scale parameter (default=1)\n moments : str, optional\n composed of letters ['mvsk'] defining which moments to compute:\n 'm' = mean,\n 'v' = variance,\n 's' = (Fisher's) skew,\n 'k' = (Fisher's) kurtosis.\n (default is 'mv')\n\n Returns\n -------\n stats : sequence\n of requested moments.\n\n \"\"\"\n args, loc, scale, moments = self._parse_args_stats(*args, **kwds)\n # scale = 1 by construction for discrete RVs\n loc, scale = map(asarray, (loc, scale))\n args = tuple(map(asarray, args))\n cond = self._argcheck(*args) & (scale > 0) & (loc == loc)\n output = []\n default = np.full(shape(cond), fill_value=self.badvalue)\n\n # Use only entries that are valid in calculation\n if np.any(cond):\n goodargs = argsreduce(cond, *(args+(scale, loc)))\n scale, loc, goodargs = goodargs[-2], goodargs[-1], goodargs[:-2]\n\n if self._stats_has_moments:\n mu, mu2, g1, g2 = self._stats(*goodargs,\n **{'moments': moments})\n else:\n mu, mu2, g1, g2 = self._stats(*goodargs)\n\n if 'm' in moments:\n if mu is None:\n mu = self._munp(1, *goodargs)\n out0 = default.copy()\n place(out0, cond, mu * scale + loc)\n output.append(out0)\n\n if 'v' in moments:\n if mu2 is None:\n mu2p = self._munp(2, *goodargs)\n if mu is None:\n mu = self._munp(1, *goodargs)\n # if mean is inf then var is also inf\n with np.errstate(invalid='ignore'):\n mu2 = np.where(~np.isinf(mu), mu2p - mu**2, np.inf)\n out0 = default.copy()\n place(out0, cond, mu2 * scale * scale)\n output.append(out0)\n\n if 's' in moments:\n if g1 is None:\n mu3p = self._munp(3, *goodargs)\n if mu is None:\n mu = self._munp(1, *goodargs)\n if mu2 is None:\n mu2p = self._munp(2, *goodargs)\n mu2 = mu2p - mu * mu\n with np.errstate(invalid='ignore'):\n mu3 = (-mu*mu - 3*mu2)*mu + mu3p\n g1 = mu3 / np.power(mu2, 1.5)\n out0 = default.copy()\n place(out0, cond, g1)\n output.append(out0)\n\n if 'k' in moments:\n if g2 is None:\n mu4p = self._munp(4, *goodargs)\n if mu is None:\n mu = self._munp(1, *goodargs)\n if mu2 is None:\n mu2p = self._munp(2, *goodargs)\n mu2 = mu2p - mu * mu\n if g1 is None:\n mu3 = None\n else:\n # (mu2**1.5) breaks down for nan and inf\n mu3 = g1 * np.power(mu2, 1.5)\n if mu3 is None:\n mu3p = self._munp(3, *goodargs)\n with np.errstate(invalid='ignore'):\n mu3 = (-mu * mu - 3 * mu2) * mu + mu3p\n with np.errstate(invalid='ignore'):\n mu4 = ((-mu**2 - 6*mu2) * mu - 4*mu3)*mu + mu4p\n g2 = mu4 / mu2**2.0 - 3.0\n out0 = default.copy()\n place(out0, cond, g2)\n output.append(out0)\n else: # no valid args\n output = [default.copy() for _ in moments]\n\n if len(output) == 1:\n return output[0]\n else:\n return tuple(output)\n\n def entropy(self, *args, **kwds):\n \"\"\"Differential entropy of the RV.\n\n Parameters\n ----------\n arg1, arg2, arg3,... : array_like\n The shape parameter(s) for the distribution (see docstring of the\n instance object for more information).\n loc : array_like, optional\n Location parameter (default=0).\n scale : array_like, optional (continuous distributions only).\n Scale parameter (default=1).\n\n Notes\n -----\n Entropy is defined base `e`:\n\n >>> drv = rv_discrete(values=((0, 1), (0.5, 0.5)))\n >>> np.allclose(drv.entropy(), np.log(2.0))\n True\n\n \"\"\"\n args, loc, scale = self._parse_args(*args, **kwds)\n # NB: for discrete distributions scale=1 by construction in _parse_args\n loc, scale = map(asarray, (loc, scale))\n args = tuple(map(asarray, args))\n cond0 = self._argcheck(*args) & (scale > 0) & (loc == loc)\n output = zeros(shape(cond0), 'd')\n place(output, (1-cond0), self.badvalue)\n goodargs = argsreduce(cond0, scale, *args)\n goodscale = goodargs[0]\n goodargs = goodargs[1:]\n place(output, cond0, self.vecentropy(*goodargs) + log(goodscale))\n return output\n\n def moment(self, order=None, *args, **kwds):\n \"\"\"non-central moment of distribution of specified order.\n\n .. deprecated:: 1.9.0\n Parameter `n` is replaced by parameter `order` to avoid name\n collisions with the shape parameter `n` of several distributions.\n Parameter `n` will be removed in SciPy 1.11.0.\n\n Parameters\n ----------\n order : int, order >= 1\n Order of moment.\n arg1, arg2, arg3,... : float\n The shape parameter(s) for the distribution (see docstring of the\n instance object for more information).\n loc : array_like, optional\n location parameter (default=0)\n scale : array_like, optional\n scale parameter (default=1)\n\n \"\"\"\n # This function was originally written with parameter `n`, but `n`\n # is also the name of many distribution shape parameters.\n # This block allows the function to accept both `n` and its\n # replacement `order` during a deprecation period; it can be removed\n # in the second release after 1.9.0.\n # The logic to provide a DeprecationWarning only when `n` is passed\n # as a keyword, accept the new keyword `order`, and otherwise be\n # backward-compatible deserves explanation. We need to look out for\n # the following:\n # * Does the distribution have a shape named `n`?\n # * Is `order` provided? It doesn't matter whether it is provided as a\n # positional or keyword argument; it will be used as the order of the\n # moment rather than a distribution shape parameter because:\n # - The first positional argument of `moment` has always been the\n # order of the moment.\n # - The keyword `order` is new, so it's unambiguous that it refers to\n # the order of the moment.\n # * Is `n` provided as a keyword argument? It _does_ matter whether it\n # is provided as a positional or keyword argument.\n # - The first positional argument of `moment` has always been the\n # order of moment, but\n # - if `n` is provided as a keyword argument, its meaning depends\n # on whether the distribution accepts `n` as a shape parameter.\n has_shape_n = (self.shapes is not None\n and \"n\" in (self.shapes.split(\", \")))\n got_order = order is not None\n got_keyword_n = kwds.get(\"n\", None) is not None\n\n # These lead to the following cases.\n # Case A: If the distribution _does_ accept `n` as a shape\n # 1. If both `order` and `n` are provided, this is now OK:\n # it is unambiguous that `order` is the order of the moment and `n`\n # is the shape parameter. Previously, this would have caused an\n # error because `n` was provided both as a keyword argument and\n # as the first positional argument. I don't think it is credible for\n # users to rely on this error in their code, though, so I don't see\n # this as a backward compatibility break.\n # 2. If only `n` is provided (as a keyword argument), this would have\n # been an error in the past because `n` would have been treated as\n # the order of the moment while the shape parameter would be\n # missing. It is still the same type of error, but for a different\n # reason: now, `n` is treated as the shape parameter while the\n # order of the moment is missing.\n # 3. If only `order` is provided, no special treament is needed.\n # Clearly this value is intended to be the order of the moment,\n # and the rest of the function will determine whether `n` is\n # available as a shape parameter in `args`.\n # 4. If neither `n` nor `order` is provided, this would have been an\n # error (order of the moment is not provided) and it is still an\n # error for the same reason.\n\n # Case B: the distribution does _not_ accept `n` as a shape\n # 1. If both `order` and `n` are provided, this was an error, and it\n # still is an error: two values for same parameter.\n # 2. If only `n` is provided (as a keyword argument), this was OK and\n # is still OK, but there shold now be a `DeprecationWarning`. The\n # value of `n` should be removed from `kwds` and stored in `order`.\n # 3. If only `order` is provided, there was no problem before providing\n # only the first argument of `moment`, and there is no problem with\n # that now.\n # 4. If neither `n` nor `order` is provided, this would have been an\n # error (order of the moment is not provided), and it is still an\n # error for the same reason.\n if not got_order and ((not got_keyword_n) # A4 and B4\n or (got_keyword_n and has_shape_n)): # A2\n message = (\"moment() missing 1 required \"\n \"positional argument: `order`\")\n raise TypeError(message)\n\n if got_keyword_n and not has_shape_n:\n if got_order: # B1\n # this will change to \"moment got unexpected argument n\"\n message = \"moment() got multiple values for first argument\"\n raise TypeError(message)\n else: # B2\n message = (\"Use of keyword argument `n` for method \"\n \"`moment` is deprecated. Use first positional \"\n \"argument or keyword argument `order` instead.\")\n order = kwds.pop(\"n\")\n warnings.warn(message, DeprecationWarning, stacklevel=2)\n n = order\n # No special treatment of A1, A3, or B3 is needed because the order\n # of the moment is now in variable `n` and the shape parameter, if\n # needed, will be fished out of `args` or `kwds` by _parse_args\n # A3 might still cause an error if the shape parameter called `n`\n # is not found in `args`.\n\n shapes, loc, scale = self._parse_args(*args, **kwds)\n args = np.broadcast_arrays(*(*shapes, loc, scale))\n *shapes, loc, scale = args\n\n i0 = np.logical_and(self._argcheck(*shapes), scale > 0)\n i1 = np.logical_and(i0, loc == 0)\n i2 = np.logical_and(i0, loc != 0)\n\n args = argsreduce(i0, *shapes, loc, scale)\n *shapes, loc, scale = args\n\n if (floor(n) != n):\n raise ValueError(\"Moment must be an integer.\")\n if (n < 0):\n raise ValueError(\"Moment must be positive.\")\n mu, mu2, g1, g2 = None, None, None, None\n if (n > 0) and (n < 5):\n if self._stats_has_moments:\n mdict = {'moments': {1: 'm', 2: 'v', 3: 'vs', 4: 'vk'}[n]}\n else:\n mdict = {}\n mu, mu2, g1, g2 = self._stats(*shapes, **mdict)\n val = np.empty(loc.shape) # val needs to be indexed by loc\n val[...] = _moment_from_stats(n, mu, mu2, g1, g2, self._munp, shapes)\n\n # Convert to transformed X = L + S*Y\n # E[X^n] = E[(L+S*Y)^n] = L^n sum(comb(n, k)*(S/L)^k E[Y^k], k=0...n)\n result = zeros(i0.shape)\n place(result, ~i0, self.badvalue)\n\n if i1.any():\n res1 = scale[loc == 0]**n * val[loc == 0]\n place(result, i1, res1)\n\n if i2.any():\n mom = [mu, mu2, g1, g2]\n arrs = [i for i in mom if i is not None]\n idx = [i for i in range(4) if mom[i] is not None]\n if any(idx):\n arrs = argsreduce(loc != 0, *arrs)\n j = 0\n for i in idx:\n mom[i] = arrs[j]\n j += 1\n mu, mu2, g1, g2 = mom\n args = argsreduce(loc != 0, *shapes, loc, scale, val)\n *shapes, loc, scale, val = args\n\n res2 = zeros(loc.shape, dtype='d')\n fac = scale / loc\n for k in range(n):\n valk = _moment_from_stats(k, mu, mu2, g1, g2, self._munp,\n shapes)\n res2 += comb(n, k, exact=True)*fac**k * valk\n res2 += fac**n * val\n res2 *= loc**n\n place(result, i2, res2)\n\n if result.ndim == 0:\n return result.item()\n return result\n\n def median(self, *args, **kwds):\n \"\"\"Median of the distribution.\n\n Parameters\n ----------\n arg1, arg2, arg3,... : array_like\n The shape parameter(s) for the distribution (see docstring of the\n instance object for more information)\n loc : array_like, optional\n Location parameter, Default is 0.\n scale : array_like, optional\n Scale parameter, Default is 1.\n\n Returns\n -------\n median : float\n The median of the distribution.\n\n See Also\n --------\n rv_discrete.ppf\n Inverse of the CDF\n\n \"\"\"\n return self.ppf(0.5, *args, **kwds)\n\n def mean(self, *args, **kwds):\n \"\"\"Mean of the distribution.\n\n Parameters\n ----------\n arg1, arg2, arg3,... : array_like\n The shape parameter(s) for the distribution (see docstring of the\n instance object for more information)\n loc : array_like, optional\n location parameter (default=0)\n scale : array_like, optional\n scale parameter (default=1)\n\n Returns\n -------\n mean : float\n the mean of the distribution\n\n \"\"\"\n kwds['moments'] = 'm'\n res = self.stats(*args, **kwds)\n if isinstance(res, ndarray) and res.ndim == 0:\n return res[()]\n return res\n\n def var(self, *args, **kwds):\n \"\"\"Variance of the distribution.\n\n Parameters\n ----------\n arg1, arg2, arg3,... : array_like\n The shape parameter(s) for the distribution (see docstring of the\n instance object for more information)\n loc : array_like, optional\n location parameter (default=0)\n scale : array_like, optional\n scale parameter (default=1)\n\n Returns\n -------\n var : float\n the variance of the distribution\n\n \"\"\"\n kwds['moments'] = 'v'\n res = self.stats(*args, **kwds)\n if isinstance(res, ndarray) and res.ndim == 0:\n return res[()]\n return res\n\n def std(self, *args, **kwds):\n \"\"\"Standard deviation of the distribution.\n\n Parameters\n ----------\n arg1, arg2, arg3,... : array_like\n The shape parameter(s) for the distribution (see docstring of the\n instance object for more information)\n loc : array_like, optional\n location parameter (default=0)\n scale : array_like, optional\n scale parameter (default=1)\n\n Returns\n -------\n std : float\n standard deviation of the distribution\n\n \"\"\"\n kwds['moments'] = 'v'\n res = sqrt(self.stats(*args, **kwds))\n return res\n\n def interval(self, confidence=None, *args, **kwds):\n \"\"\"Confidence interval with equal areas around the median.\n\n .. deprecated:: 1.9.0\n Parameter `alpha` is replaced by parameter `confidence` to avoid\n name collisions with the shape parameter `alpha` of some\n distributions. Parameter `alpha` will be removed in SciPy 1.11.0.\n\n Parameters\n ----------\n confidence : array_like of float\n Probability that an rv will be drawn from the returned range.\n Each value should be in the range [0, 1].\n arg1, arg2, ... : array_like\n The shape parameter(s) for the distribution (see docstring of the\n instance object for more information).\n loc : array_like, optional\n location parameter, Default is 0.\n scale : array_like, optional\n scale parameter, Default is 1.\n\n Returns\n -------\n a, b : ndarray of float\n end-points of range that contain ``100 * alpha %`` of the rv's\n possible values.\n\n \"\"\"\n # This function was originally written with parameter `alpha`, but\n # `alpha` is also the name of a shape parameter of two distributions.\n # This block allows the function to accept both `alpha` and its\n # replacement `confidence` during a deprecation period; it can be\n # removed in the second release after 1.9.0.\n # See description of logic in `moment` method.\n has_shape_alpha = (self.shapes is not None\n and \"alpha\" in (self.shapes.split(\", \")))\n got_confidence = confidence is not None\n got_keyword_alpha = kwds.get(\"alpha\", None) is not None\n\n if not got_confidence and ((not got_keyword_alpha)\n or (got_keyword_alpha and has_shape_alpha)):\n message = (\"interval() missing 1 required positional argument: \"\n \"`confidence`\")\n raise TypeError(message)\n\n if got_keyword_alpha and not has_shape_alpha:\n if got_confidence:\n # this will change to \"interval got unexpected argument alpha\"\n message = \"interval() got multiple values for first argument\"\n raise TypeError(message)\n else:\n message = (\"Use of keyword argument `alpha` for method \"\n \"`interval` is deprecated. Use first positional \"\n \"argument or keyword argument `confidence` \"\n \"instead.\")\n confidence = kwds.pop(\"alpha\")\n warnings.warn(message, DeprecationWarning, stacklevel=2)\n alpha = confidence\n\n alpha = asarray(alpha)\n if np.any((alpha > 1) | (alpha < 0)):\n raise ValueError(\"alpha must be between 0 and 1 inclusive\")\n q1 = (1.0-alpha)/2\n q2 = (1.0+alpha)/2\n a = self.ppf(q1, *args, **kwds)\n b = self.ppf(q2, *args, **kwds)\n return a, b\n\n def support(self, *args, **kwargs):\n \"\"\"Support of the distribution.\n\n Parameters\n ----------\n arg1, arg2, ... : array_like\n The shape parameter(s) for the distribution (see docstring of the\n instance object for more information).\n loc : array_like, optional\n location parameter, Default is 0.\n scale : array_like, optional\n scale parameter, Default is 1.\n\n Returns\n -------\n a, b : array_like\n end-points of the distribution's support.\n\n \"\"\"\n args, loc, scale = self._parse_args(*args, **kwargs)\n arrs = np.broadcast_arrays(*args, loc, scale)\n args, loc, scale = arrs[:-2], arrs[-2], arrs[-1]\n cond = self._argcheck(*args) & (scale > 0)\n _a, _b = self._get_support(*args)\n if cond.all():\n return _a * scale + loc, _b * scale + loc\n elif cond.ndim == 0:\n return self.badvalue, self.badvalue\n # promote bounds to at least float to fill in the badvalue\n _a, _b = np.asarray(_a).astype('d'), np.asarray(_b).astype('d')\n out_a, out_b = _a * scale + loc, _b * scale + loc\n place(out_a, 1-cond, self.badvalue)\n place(out_b, 1-cond, self.badvalue)\n return out_a, out_b\n\n def nnlf(self, theta, x):\n \"\"\"Negative loglikelihood function.\n Notes\n -----\n This is ``-sum(log pdf(x, theta), axis=0)`` where `theta` are the\n parameters (including loc and scale).\n \"\"\"\n loc, scale, args = self._unpack_loc_scale(theta)\n if not self._argcheck(*args) or scale <= 0:\n return inf\n x = asarray((x-loc) / scale)\n n_log_scale = len(x) * log(scale)\n if np.any(~self._support_mask(x, *args)):\n return inf\n return self._nnlf(x, *args) + n_log_scale\n\n def _nnlf(self, x, *args):\n return -np.sum(self._logpxf(x, *args), axis=0)\n\n def _nnlf_and_penalty(self, x, args):\n cond0 = ~self._support_mask(x, *args)\n n_bad = np.count_nonzero(cond0, axis=0)\n if n_bad > 0:\n x = argsreduce(~cond0, x)[0]\n logpxf = self._logpxf(x, *args)\n finite_logpxf = np.isfinite(logpxf)\n n_bad += np.sum(~finite_logpxf, axis=0)\n if n_bad > 0:\n penalty = n_bad * log(_XMAX) * 100\n return -np.sum(logpxf[finite_logpxf], axis=0) + penalty\n return -np.sum(logpxf, axis=0)\n\n def _penalized_nnlf(self, theta, x):\n \"\"\"Penalized negative loglikelihood function.\n i.e., - sum (log pdf(x, theta), axis=0) + penalty\n where theta are the parameters (including loc and scale)\n \"\"\"\n loc, scale, args = self._unpack_loc_scale(theta)\n if not self._argcheck(*args) or scale <= 0:\n return inf\n x = asarray((x-loc) / scale)\n n_log_scale = len(x) * log(scale)\n return self._nnlf_and_penalty(x, args) + n_log_scale\n\n\nclass _ShapeInfo:\n def __init__(self, name, integrality=False, domain=(-np.inf, np.inf),\n inclusive=(True, True)):\n self.name = name\n self.integrality = integrality\n\n domain = list(domain)\n if np.isfinite(domain[0]) and not inclusive[0]:\n domain[0] = np.nextafter(domain[0], np.inf)\n if np.isfinite(domain[1]) and not inclusive[1]:\n domain[1] = np.nextafter(domain[1], -np.inf)\n self.domain = domain\n\n\ndef _get_fixed_fit_value(kwds, names):\n \"\"\"\n Given names such as `['f0', 'fa', 'fix_a']`, check that there is\n at most one non-None value in `kwds` associaed with those names.\n Return that value, or None if none of the names occur in `kwds`.\n As a side effect, all occurrences of those names in `kwds` are\n removed.\n \"\"\"\n vals = [(name, kwds.pop(name)) for name in names if name in kwds]\n if len(vals) > 1:\n repeated = [name for name, val in vals]\n raise ValueError(\"fit method got multiple keyword arguments to \"\n \"specify the same fixed parameter: \" +\n ', '.join(repeated))\n return vals[0][1] if vals else None\n\n# continuous random variables: implement maybe later\n#\n# hf --- Hazard Function (PDF / SF)\n# chf --- Cumulative hazard function (-log(SF))\n# psf --- Probability sparsity function (reciprocal of the pdf) in\n# units of percent-point-function (as a function of q).\n# Also, the derivative of the percent-point function.\n\n\nclass rv_continuous(rv_generic):\n \"\"\"A generic continuous random variable class meant for subclassing.\n\n `rv_continuous` is a base class to construct specific distribution classes\n and instances for continuous random variables. It cannot be used\n directly as a distribution.\n\n Parameters\n ----------\n momtype : int, optional\n The type of generic moment calculation to use: 0 for pdf, 1 (default)\n for ppf.\n a : float, optional\n Lower bound of the support of the distribution, default is minus\n infinity.\n b : float, optional\n Upper bound of the support of the distribution, default is plus\n infinity.\n xtol : float, optional\n The tolerance for fixed point calculation for generic ppf.\n badvalue : float, optional\n The value in a result arrays that indicates a value that for which\n some argument restriction is violated, default is np.nan.\n name : str, optional\n The name of the instance. This string is used to construct the default\n example for distributions.\n longname : str, optional\n This string is used as part of the first line of the docstring returned\n when a subclass has no docstring of its own. Note: `longname` exists\n for backwards compatibility, do not use for new subclasses.\n shapes : str, optional\n The shape of the distribution. For example ``\"m, n\"`` for a\n distribution that takes two integers as the two shape arguments for all\n its methods. If not provided, shape parameters will be inferred from\n the signature of the private methods, ``_pdf`` and ``_cdf`` of the\n instance.\n extradoc : str, optional, deprecated\n This string is used as the last part of the docstring returned when a\n subclass has no docstring of its own. Note: `extradoc` exists for\n backwards compatibility, do not use for new subclasses.\n seed : {None, int, `numpy.random.Generator`,\n `numpy.random.RandomState`}, optional\n\n If `seed` is None (or `np.random`), the `numpy.random.RandomState`\n singleton is used.\n If `seed` is an int, a new ``RandomState`` instance is used,\n seeded with `seed`.\n If `seed` is already a ``Generator`` or ``RandomState`` instance then\n that instance is used.\n\n Methods\n -------\n rvs\n pdf\n logpdf\n cdf\n logcdf\n sf\n logsf\n ppf\n isf\n moment\n stats\n entropy\n expect\n median\n mean\n std\n var\n interval\n __call__\n fit\n fit_loc_scale\n nnlf\n support\n\n Notes\n -----\n Public methods of an instance of a distribution class (e.g., ``pdf``,\n ``cdf``) check their arguments and pass valid arguments to private,\n computational methods (``_pdf``, ``_cdf``). For ``pdf(x)``, ``x`` is valid\n if it is within the support of the distribution.\n Whether a shape parameter is valid is decided by an ``_argcheck`` method\n (which defaults to checking that its arguments are strictly positive.)\n\n **Subclassing**\n\n New random variables can be defined by subclassing the `rv_continuous` class\n and re-defining at least the ``_pdf`` or the ``_cdf`` method (normalized\n to location 0 and scale 1).\n\n If positive argument checking is not correct for your RV\n then you will also need to re-define the ``_argcheck`` method.\n\n For most of the scipy.stats distributions, the support interval doesn't\n depend on the shape parameters. ``x`` being in the support interval is\n equivalent to ``self.a <= x <= self.b``. If either of the endpoints of\n the support do depend on the shape parameters, then\n i) the distribution must implement the ``_get_support`` method; and\n ii) those dependent endpoints must be omitted from the distribution's\n call to the ``rv_continuous`` initializer.\n\n Correct, but potentially slow defaults exist for the remaining\n methods but for speed and/or accuracy you can over-ride::\n\n _logpdf, _cdf, _logcdf, _ppf, _rvs, _isf, _sf, _logsf\n\n The default method ``_rvs`` relies on the inverse of the cdf, ``_ppf``,\n applied to a uniform random variate. In order to generate random variates\n efficiently, either the default ``_ppf`` needs to be overwritten (e.g.\n if the inverse cdf can expressed in an explicit form) or a sampling\n method needs to be implemented in a custom ``_rvs`` method.\n\n If possible, you should override ``_isf``, ``_sf`` or ``_logsf``.\n The main reason would be to improve numerical accuracy: for example,\n the survival function ``_sf`` is computed as ``1 - _cdf`` which can\n result in loss of precision if ``_cdf(x)`` is close to one.\n\n **Methods that can be overwritten by subclasses**\n ::\n\n _rvs\n _pdf\n _cdf\n _sf\n _ppf\n _isf\n _stats\n _munp\n _entropy\n _argcheck\n _get_support\n\n There are additional (internal and private) generic methods that can\n be useful for cross-checking and for debugging, but might work in all\n cases when directly called.\n\n A note on ``shapes``: subclasses need not specify them explicitly. In this\n case, `shapes` will be automatically deduced from the signatures of the\n overridden methods (`pdf`, `cdf` etc).\n If, for some reason, you prefer to avoid relying on introspection, you can\n specify ``shapes`` explicitly as an argument to the instance constructor.\n\n\n **Frozen Distributions**\n\n Normally, you must provide shape parameters (and, optionally, location and\n scale parameters to each call of a method of a distribution.\n\n Alternatively, the object may be called (as a function) to fix the shape,\n location, and scale parameters returning a \"frozen\" continuous RV object:\n\n rv = generic(<shape(s)>, loc=0, scale=1)\n `rv_frozen` object with the same methods but holding the given shape,\n location, and scale fixed\n\n **Statistics**\n\n Statistics are computed using numerical integration by default.\n For speed you can redefine this using ``_stats``:\n\n - take shape parameters and return mu, mu2, g1, g2\n - If you can't compute one of these, return it as None\n - Can also be defined with a keyword argument ``moments``, which is a\n string composed of \"m\", \"v\", \"s\", and/or \"k\".\n Only the components appearing in string should be computed and\n returned in the order \"m\", \"v\", \"s\", or \"k\" with missing values\n returned as None.\n\n Alternatively, you can override ``_munp``, which takes ``n`` and shape\n parameters and returns the n-th non-central moment of the distribution.\n\n Examples\n --------\n To create a new Gaussian distribution, we would do the following:\n\n >>> from scipy.stats import rv_continuous\n >>> class gaussian_gen(rv_continuous):\n ... \"Gaussian distribution\"\n ... def _pdf(self, x):\n ... return np.exp(-x**2 / 2.) / np.sqrt(2.0 * np.pi)\n >>> gaussian = gaussian_gen(name='gaussian')\n\n ``scipy.stats`` distributions are *instances*, so here we subclass\n `rv_continuous` and create an instance. With this, we now have\n a fully functional distribution with all relevant methods automagically\n generated by the framework.\n\n Note that above we defined a standard normal distribution, with zero mean\n and unit variance. Shifting and scaling of the distribution can be done\n by using ``loc`` and ``scale`` parameters: ``gaussian.pdf(x, loc, scale)``\n essentially computes ``y = (x - loc) / scale`` and\n ``gaussian._pdf(y) / scale``.\n\n \"\"\"\n def __init__(self, momtype=1, a=None, b=None, xtol=1e-14,\n badvalue=None, name=None, longname=None,\n shapes=None, extradoc=None, seed=None):\n\n super().__init__(seed)\n\n if extradoc is not None:\n warnings.warn(\"extradoc is deprecated and will be removed in \"\n \"SciPy 1.11.0\", DeprecationWarning)\n\n # save the ctor parameters, cf generic freeze\n self._ctor_param = dict(\n momtype=momtype, a=a, b=b, xtol=xtol,\n badvalue=badvalue, name=name, longname=longname,\n shapes=shapes, extradoc=extradoc, seed=seed)\n\n if badvalue is None:\n badvalue = nan\n if name is None:\n name = 'Distribution'\n self.badvalue = badvalue\n self.name = name\n self.a = a\n self.b = b\n if a is None:\n self.a = -inf\n if b is None:\n self.b = inf\n self.xtol = xtol\n self.moment_type = momtype\n self.shapes = shapes\n self.extradoc = extradoc\n\n self._construct_argparser(meths_to_inspect=[self._pdf, self._cdf],\n locscale_in='loc=0, scale=1',\n locscale_out='loc, scale')\n self._attach_methods()\n\n if longname is None:\n if name[0] in ['aeiouAEIOU']:\n hstr = \"An \"\n else:\n hstr = \"A \"\n longname = hstr + name\n\n if sys.flags.optimize < 2:\n # Skip adding docstrings if interpreter is run with -OO\n if self.__doc__ is None:\n self._construct_default_doc(longname=longname,\n extradoc=extradoc,\n docdict=docdict,\n discrete='continuous')\n else:\n dct = dict(distcont)\n self._construct_doc(docdict, dct.get(self.name))\n\n def __getstate__(self):\n dct = self.__dict__.copy()\n\n # these methods will be remade in __setstate__\n # _random_state attribute is taken care of by rv_generic\n attrs = [\"_parse_args\", \"_parse_args_stats\", \"_parse_args_rvs\",\n \"_cdfvec\", \"_ppfvec\", \"vecentropy\", \"generic_moment\"]\n [dct.pop(attr, None) for attr in attrs]\n return dct\n\n def _attach_methods(self):\n \"\"\"\n Attaches dynamically created methods to the rv_continuous instance.\n \"\"\"\n # _attach_methods is responsible for calling _attach_argparser_methods\n self._attach_argparser_methods()\n\n # nin correction\n self._ppfvec = vectorize(self._ppf_single, otypes='d')\n self._ppfvec.nin = self.numargs + 1\n self.vecentropy = vectorize(self._entropy, otypes='d')\n self._cdfvec = vectorize(self._cdf_single, otypes='d')\n self._cdfvec.nin = self.numargs + 1\n\n if self.moment_type == 0:\n self.generic_moment = vectorize(self._mom0_sc, otypes='d')\n else:\n self.generic_moment = vectorize(self._mom1_sc, otypes='d')\n # Because of the *args argument of _mom0_sc, vectorize cannot count the\n # number of arguments correctly.\n self.generic_moment.nin = self.numargs + 1\n\n def _updated_ctor_param(self):\n \"\"\"Return the current version of _ctor_param, possibly updated by user.\n\n Used by freezing.\n Keep this in sync with the signature of __init__.\n \"\"\"\n dct = self._ctor_param.copy()\n dct['a'] = self.a\n dct['b'] = self.b\n dct['xtol'] = self.xtol\n dct['badvalue'] = self.badvalue\n dct['name'] = self.name\n dct['shapes'] = self.shapes\n dct['extradoc'] = self.extradoc\n return dct\n\n def _ppf_to_solve(self, x, q, *args):\n return self.cdf(*(x, )+args)-q\n\n def _ppf_single(self, q, *args):\n factor = 10.\n left, right = self._get_support(*args)\n\n if np.isinf(left):\n left = min(-factor, right)\n while self._ppf_to_solve(left, q, *args) > 0.:\n left, right = left * factor, left\n # left is now such that cdf(left) <= q\n # if right has changed, then cdf(right) > q\n\n if np.isinf(right):\n right = max(factor, left)\n while self._ppf_to_solve(right, q, *args) < 0.:\n left, right = right, right * factor\n # right is now such that cdf(right) >= q\n\n return optimize.brentq(self._ppf_to_solve,\n left, right, args=(q,)+args, xtol=self.xtol)\n\n # moment from definition\n def _mom_integ0(self, x, m, *args):\n return x**m * self.pdf(x, *args)\n\n def _mom0_sc(self, m, *args):\n _a, _b = self._get_support(*args)\n return integrate.quad(self._mom_integ0, _a, _b,\n args=(m,)+args)[0]\n\n # moment calculated using ppf\n def _mom_integ1(self, q, m, *args):\n return (self.ppf(q, *args))**m\n\n def _mom1_sc(self, m, *args):\n return integrate.quad(self._mom_integ1, 0, 1, args=(m,)+args)[0]\n\n def _pdf(self, x, *args):\n return derivative(self._cdf, x, dx=1e-5, args=args, order=5)\n\n # Could also define any of these\n def _logpdf(self, x, *args):\n p = self._pdf(x, *args)\n with np.errstate(divide='ignore'):\n return log(p)\n\n def _logpxf(self, x, *args):\n # continuous distributions have PDF, discrete have PMF, but sometimes\n # the distinction doesn't matter. This lets us use `_logpxf` for both\n # discrete and continuous distributions.\n return self._logpdf(x, *args)\n\n def _cdf_single(self, x, *args):\n _a, _b = self._get_support(*args)\n return integrate.quad(self._pdf, _a, x, args=args)[0]\n\n def _cdf(self, x, *args):\n return self._cdfvec(x, *args)\n\n # generic _argcheck, _logcdf, _sf, _logsf, _ppf, _isf, _rvs are defined\n # in rv_generic\n\n def pdf(self, x, *args, **kwds):\n \"\"\"Probability density function at x of the given RV.\n\n Parameters\n ----------\n x : array_like\n quantiles\n arg1, arg2, arg3,... : array_like\n The shape parameter(s) for the distribution (see docstring of the\n instance object for more information)\n loc : array_like, optional\n location parameter (default=0)\n scale : array_like, optional\n scale parameter (default=1)\n\n Returns\n -------\n pdf : ndarray\n Probability density function evaluated at x\n\n \"\"\"\n args, loc, scale = self._parse_args(*args, **kwds)\n x, loc, scale = map(asarray, (x, loc, scale))\n args = tuple(map(asarray, args))\n dtyp = np.find_common_type([x.dtype, np.float64], [])\n x = np.asarray((x - loc)/scale, dtype=dtyp)\n cond0 = self._argcheck(*args) & (scale > 0)\n cond1 = self._support_mask(x, *args) & (scale > 0)\n cond = cond0 & cond1\n output = zeros(shape(cond), dtyp)\n putmask(output, (1-cond0)+np.isnan(x), self.badvalue)\n if np.any(cond):\n goodargs = argsreduce(cond, *((x,)+args+(scale,)))\n scale, goodargs = goodargs[-1], goodargs[:-1]\n place(output, cond, self._pdf(*goodargs) / scale)\n if output.ndim == 0:\n return output[()]\n return output\n\n def logpdf(self, x, *args, **kwds):\n \"\"\"Log of the probability density function at x of the given RV.\n\n This uses a more numerically accurate calculation if available.\n\n Parameters\n ----------\n x : array_like\n quantiles\n arg1, arg2, arg3,... : array_like\n The shape parameter(s) for the distribution (see docstring of the\n instance object for more information)\n loc : array_like, optional\n location parameter (default=0)\n scale : array_like, optional\n scale parameter (default=1)\n\n Returns\n -------\n logpdf : array_like\n Log of the probability density function evaluated at x\n\n \"\"\"\n args, loc, scale = self._parse_args(*args, **kwds)\n x, loc, scale = map(asarray, (x, loc, scale))\n args = tuple(map(asarray, args))\n dtyp = np.find_common_type([x.dtype, np.float64], [])\n x = np.asarray((x - loc)/scale, dtype=dtyp)\n cond0 = self._argcheck(*args) & (scale > 0)\n cond1 = self._support_mask(x, *args) & (scale > 0)\n cond = cond0 & cond1\n output = empty(shape(cond), dtyp)\n output.fill(NINF)\n putmask(output, (1-cond0)+np.isnan(x), self.badvalue)\n if np.any(cond):\n goodargs = argsreduce(cond, *((x,)+args+(scale,)))\n scale, goodargs = goodargs[-1], goodargs[:-1]\n place(output, cond, self._logpdf(*goodargs) - log(scale))\n if output.ndim == 0:\n return output[()]\n return output\n\n def cdf(self, x, *args, **kwds):\n \"\"\"\n Cumulative distribution function of the given RV.\n\n Parameters\n ----------\n x : array_like\n quantiles\n arg1, arg2, arg3,... : array_like\n The shape parameter(s) for the distribution (see docstring of the\n instance object for more information)\n loc : array_like, optional\n location parameter (default=0)\n scale : array_like, optional\n scale parameter (default=1)\n\n Returns\n -------\n cdf : ndarray\n Cumulative distribution function evaluated at `x`\n\n \"\"\"\n args, loc, scale = self._parse_args(*args, **kwds)\n x, loc, scale = map(asarray, (x, loc, scale))\n args = tuple(map(asarray, args))\n _a, _b = self._get_support(*args)\n dtyp = np.find_common_type([x.dtype, np.float64], [])\n x = np.asarray((x - loc)/scale, dtype=dtyp)\n cond0 = self._argcheck(*args) & (scale > 0)\n cond1 = self._open_support_mask(x, *args) & (scale > 0)\n cond2 = (x >= np.asarray(_b)) & cond0\n cond = cond0 & cond1\n output = zeros(shape(cond), dtyp)\n place(output, (1-cond0)+np.isnan(x), self.badvalue)\n place(output, cond2, 1.0)\n if np.any(cond): # call only if at least 1 entry\n goodargs = argsreduce(cond, *((x,)+args))\n place(output, cond, self._cdf(*goodargs))\n if output.ndim == 0:\n return output[()]\n return output\n\n def logcdf(self, x, *args, **kwds):\n \"\"\"Log of the cumulative distribution function at x of the given RV.\n\n Parameters\n ----------\n x : array_like\n quantiles\n arg1, arg2, arg3,... : array_like\n The shape parameter(s) for the distribution (see docstring of the\n instance object for more information)\n loc : array_like, optional\n location parameter (default=0)\n scale : array_like, optional\n scale parameter (default=1)\n\n Returns\n -------\n logcdf : array_like\n Log of the cumulative distribution function evaluated at x\n\n \"\"\"\n args, loc, scale = self._parse_args(*args, **kwds)\n x, loc, scale = map(asarray, (x, loc, scale))\n args = tuple(map(asarray, args))\n _a, _b = self._get_support(*args)\n dtyp = np.find_common_type([x.dtype, np.float64], [])\n x = np.asarray((x - loc)/scale, dtype=dtyp)\n cond0 = self._argcheck(*args) & (scale > 0)\n cond1 = self._open_support_mask(x, *args) & (scale > 0)\n cond2 = (x >= _b) & cond0\n cond = cond0 & cond1\n output = empty(shape(cond), dtyp)\n output.fill(NINF)\n place(output, (1-cond0)*(cond1 == cond1)+np.isnan(x), self.badvalue)\n place(output, cond2, 0.0)\n if np.any(cond): # call only if at least 1 entry\n goodargs = argsreduce(cond, *((x,)+args))\n place(output, cond, self._logcdf(*goodargs))\n if output.ndim == 0:\n return output[()]\n return output\n\n def sf(self, x, *args, **kwds):\n \"\"\"Survival function (1 - `cdf`) at x of the given RV.\n\n Parameters\n ----------\n x : array_like\n quantiles\n arg1, arg2, arg3,... : array_like\n The shape parameter(s) for the distribution (see docstring of the\n instance object for more information)\n loc : array_like, optional\n location parameter (default=0)\n scale : array_like, optional\n scale parameter (default=1)\n\n Returns\n -------\n sf : array_like\n Survival function evaluated at x\n\n \"\"\"\n args, loc, scale = self._parse_args(*args, **kwds)\n x, loc, scale = map(asarray, (x, loc, scale))\n args = tuple(map(asarray, args))\n _a, _b = self._get_support(*args)\n dtyp = np.find_common_type([x.dtype, np.float64], [])\n x = np.asarray((x - loc)/scale, dtype=dtyp)\n cond0 = self._argcheck(*args) & (scale > 0)\n cond1 = self._open_support_mask(x, *args) & (scale > 0)\n cond2 = cond0 & (x <= _a)\n cond = cond0 & cond1\n output = zeros(shape(cond), dtyp)\n place(output, (1-cond0)+np.isnan(x), self.badvalue)\n place(output, cond2, 1.0)\n if np.any(cond):\n goodargs = argsreduce(cond, *((x,)+args))\n place(output, cond, self._sf(*goodargs))\n if output.ndim == 0:\n return output[()]\n return output\n\n def logsf(self, x, *args, **kwds):\n \"\"\"Log of the survival function of the given RV.\n\n Returns the log of the \"survival function,\" defined as (1 - `cdf`),\n evaluated at `x`.\n\n Parameters\n ----------\n x : array_like\n quantiles\n arg1, arg2, arg3,... : array_like\n The shape parameter(s) for the distribution (see docstring of the\n instance object for more information)\n loc : array_like, optional\n location parameter (default=0)\n scale : array_like, optional\n scale parameter (default=1)\n\n Returns\n -------\n logsf : ndarray\n Log of the survival function evaluated at `x`.\n\n \"\"\"\n args, loc, scale = self._parse_args(*args, **kwds)\n x, loc, scale = map(asarray, (x, loc, scale))\n args = tuple(map(asarray, args))\n _a, _b = self._get_support(*args)\n dtyp = np.find_common_type([x.dtype, np.float64], [])\n x = np.asarray((x - loc)/scale, dtype=dtyp)\n cond0 = self._argcheck(*args) & (scale > 0)\n cond1 = self._open_support_mask(x, *args) & (scale > 0)\n cond2 = cond0 & (x <= _a)\n cond = cond0 & cond1\n output = empty(shape(cond), dtyp)\n output.fill(NINF)\n place(output, (1-cond0)+np.isnan(x), self.badvalue)\n place(output, cond2, 0.0)\n if np.any(cond):\n goodargs = argsreduce(cond, *((x,)+args))\n place(output, cond, self._logsf(*goodargs))\n if output.ndim == 0:\n return output[()]\n return output\n\n def ppf(self, q, *args, **kwds):\n \"\"\"Percent point function (inverse of `cdf`) at q of the given RV.\n\n Parameters\n ----------\n q : array_like\n lower tail probability\n arg1, arg2, arg3,... : array_like\n The shape parameter(s) for the distribution (see docstring of the\n instance object for more information)\n loc : array_like, optional\n location parameter (default=0)\n scale : array_like, optional\n scale parameter (default=1)\n\n Returns\n -------\n x : array_like\n quantile corresponding to the lower tail probability q.\n\n \"\"\"\n args, loc, scale = self._parse_args(*args, **kwds)\n q, loc, scale = map(asarray, (q, loc, scale))\n args = tuple(map(asarray, args))\n _a, _b = self._get_support(*args)\n cond0 = self._argcheck(*args) & (scale > 0) & (loc == loc)\n cond1 = (0 < q) & (q < 1)\n cond2 = cond0 & (q == 0)\n cond3 = cond0 & (q == 1)\n cond = cond0 & cond1\n output = np.full(shape(cond), fill_value=self.badvalue)\n\n lower_bound = _a * scale + loc\n upper_bound = _b * scale + loc\n place(output, cond2, argsreduce(cond2, lower_bound)[0])\n place(output, cond3, argsreduce(cond3, upper_bound)[0])\n\n if np.any(cond): # call only if at least 1 entry\n goodargs = argsreduce(cond, *((q,)+args+(scale, loc)))\n scale, loc, goodargs = goodargs[-2], goodargs[-1], goodargs[:-2]\n place(output, cond, self._ppf(*goodargs) * scale + loc)\n if output.ndim == 0:\n return output[()]\n return output\n\n def isf(self, q, *args, **kwds):\n \"\"\"Inverse survival function (inverse of `sf`) at q of the given RV.\n\n Parameters\n ----------\n q : array_like\n upper tail probability\n arg1, arg2, arg3,... : array_like\n The shape parameter(s) for the distribution (see docstring of the\n instance object for more information)\n loc : array_like, optional\n location parameter (default=0)\n scale : array_like, optional\n scale parameter (default=1)\n\n Returns\n -------\n x : ndarray or scalar\n Quantile corresponding to the upper tail probability q.\n\n \"\"\"\n args, loc, scale = self._parse_args(*args, **kwds)\n q, loc, scale = map(asarray, (q, loc, scale))\n args = tuple(map(asarray, args))\n _a, _b = self._get_support(*args)\n cond0 = self._argcheck(*args) & (scale > 0) & (loc == loc)\n cond1 = (0 < q) & (q < 1)\n cond2 = cond0 & (q == 1)\n cond3 = cond0 & (q == 0)\n cond = cond0 & cond1\n output = np.full(shape(cond), fill_value=self.badvalue)\n\n lower_bound = _a * scale + loc\n upper_bound = _b * scale + loc\n place(output, cond2, argsreduce(cond2, lower_bound)[0])\n place(output, cond3, argsreduce(cond3, upper_bound)[0])\n\n if np.any(cond):\n goodargs = argsreduce(cond, *((q,)+args+(scale, loc)))\n scale, loc, goodargs = goodargs[-2], goodargs[-1], goodargs[:-2]\n place(output, cond, self._isf(*goodargs) * scale + loc)\n if output.ndim == 0:\n return output[()]\n return output\n\n def _unpack_loc_scale(self, theta):\n try:\n loc = theta[-2]\n scale = theta[-1]\n args = tuple(theta[:-2])\n except IndexError as e:\n raise ValueError(\"Not enough input arguments.\") from e\n return loc, scale, args\n\n def _fitstart(self, data, args=None):\n \"\"\"Starting point for fit (shape arguments + loc + scale).\"\"\"\n if args is None:\n args = (1.0,)*self.numargs\n loc, scale = self._fit_loc_scale_support(data, *args)\n return args + (loc, scale)\n\n def _reduce_func(self, args, kwds, data=None):\n \"\"\"\n Return the (possibly reduced) function to optimize in order to find MLE\n estimates for the .fit method.\n \"\"\"\n # Convert fixed shape parameters to the standard numeric form: e.g. for\n # stats.beta, shapes='a, b'. To fix `a`, the caller can give a value\n # for `f0`, `fa` or 'fix_a'. The following converts the latter two\n # into the first (numeric) form.\n shapes = []\n if self.shapes:\n shapes = self.shapes.replace(',', ' ').split()\n for j, s in enumerate(shapes):\n key = 'f' + str(j)\n names = [key, 'f' + s, 'fix_' + s]\n val = _get_fixed_fit_value(kwds, names)\n if val is not None:\n kwds[key] = val\n\n args = list(args)\n Nargs = len(args)\n fixedn = []\n names = ['f%d' % n for n in range(Nargs - 2)] + ['floc', 'fscale']\n x0 = []\n for n, key in enumerate(names):\n if key in kwds:\n fixedn.append(n)\n args[n] = kwds.pop(key)\n else:\n x0.append(args[n])\n\n methods = {\"mle\", \"mm\"}\n method = kwds.pop('method', \"mle\").lower()\n if method == \"mm\":\n n_params = len(shapes) + 2 - len(fixedn)\n exponents = (np.arange(1, n_params+1))[:, np.newaxis]\n data_moments = np.sum(data[None, :]**exponents/len(data), axis=1)\n\n def objective(theta, x):\n return self._moment_error(theta, x, data_moments)\n elif method == \"mle\":\n objective = self._penalized_nnlf\n else:\n raise ValueError(\"Method '{0}' not available; must be one of {1}\"\n .format(method, methods))\n\n if len(fixedn) == 0:\n func = objective\n restore = None\n else:\n if len(fixedn) == Nargs:\n raise ValueError(\n \"All parameters fixed. There is nothing to optimize.\")\n\n def restore(args, theta):\n # Replace with theta for all numbers not in fixedn\n # This allows the non-fixed values to vary, but\n # we still call self.nnlf with all parameters.\n i = 0\n for n in range(Nargs):\n if n not in fixedn:\n args[n] = theta[i]\n i += 1\n return args\n\n def func(theta, x):\n newtheta = restore(args[:], theta)\n return objective(newtheta, x)\n\n return x0, func, restore, args\n\n def _moment_error(self, theta, x, data_moments):\n loc, scale, args = self._unpack_loc_scale(theta)\n if not self._argcheck(*args) or scale <= 0:\n return inf\n\n dist_moments = np.array([self.moment(i+1, *args, loc=loc, scale=scale)\n for i in range(len(data_moments))])\n if np.any(np.isnan(dist_moments)):\n raise ValueError(\"Method of moments encountered a non-finite \"\n \"distribution moment and cannot continue. \"\n \"Consider trying method='MLE'.\")\n\n return (((data_moments - dist_moments) /\n np.maximum(np.abs(data_moments), 1e-8))**2).sum()\n\n def fit(self, data, *args, **kwds):\n \"\"\"\n Return estimates of shape (if applicable), location, and scale\n parameters from data. The default estimation method is Maximum\n Likelihood Estimation (MLE), but Method of Moments (MM)\n is also available.\n\n Starting estimates for\n the fit are given by input arguments; for any arguments not provided\n with starting estimates, ``self._fitstart(data)`` is called to generate\n such.\n\n One can hold some parameters fixed to specific values by passing in\n keyword arguments ``f0``, ``f1``, ..., ``fn`` (for shape parameters)\n and ``floc`` and ``fscale`` (for location and scale parameters,\n respectively).\n\n Parameters\n ----------\n data : array_like\n Data to use in estimating the distribution parameters.\n arg1, arg2, arg3,... : floats, optional\n Starting value(s) for any shape-characterizing arguments (those not\n provided will be determined by a call to ``_fitstart(data)``).\n No default value.\n **kwds : floats, optional\n - `loc`: initial guess of the distribution's location parameter.\n - `scale`: initial guess of the distribution's scale parameter.\n\n Special keyword arguments are recognized as holding certain\n parameters fixed:\n\n - f0...fn : hold respective shape parameters fixed.\n Alternatively, shape parameters to fix can be specified by name.\n For example, if ``self.shapes == \"a, b\"``, ``fa`` and ``fix_a``\n are equivalent to ``f0``, and ``fb`` and ``fix_b`` are\n equivalent to ``f1``.\n\n - floc : hold location parameter fixed to specified value.\n\n - fscale : hold scale parameter fixed to specified value.\n\n - optimizer : The optimizer to use.\n The optimizer must take ``func``,\n and starting position as the first two arguments,\n plus ``args`` (for extra arguments to pass to the\n function to be optimized) and ``disp=0`` to suppress\n output as keyword arguments.\n\n - method : The method to use. The default is \"MLE\" (Maximum\n Likelihood Estimate); \"MM\" (Method of Moments)\n is also available.\n\n\n Returns\n -------\n parameter_tuple : tuple of floats\n Estimates for any shape parameters (if applicable),\n followed by those for location and scale.\n For most random variables, shape statistics\n will be returned, but there are exceptions (e.g. ``norm``).\n\n Notes\n -----\n With ``method=\"MLE\"`` (default), the fit is computed by minimizing\n the negative log-likelihood function. A large, finite penalty\n (rather than infinite negative log-likelihood) is applied for\n observations beyond the support of the distribution.\n\n With ``method=\"MM\"``, the fit is computed by minimizing the L2 norm\n of the relative errors between the first *k* raw (about zero) data\n moments and the corresponding distribution moments, where *k* is the\n number of non-fixed parameters.\n More precisely, the objective function is::\n\n (((data_moments - dist_moments)\n / np.maximum(np.abs(data_moments), 1e-8))**2).sum()\n\n where the constant ``1e-8`` avoids division by zero in case of\n vanishing data moments. Typically, this error norm can be reduced to\n zero.\n Note that the standard method of moments can produce parameters for\n which some data are outside the support of the fitted distribution;\n this implementation does nothing to prevent this.\n\n For either method,\n the returned answer is not guaranteed to be globally optimal; it\n may only be locally optimal, or the optimization may fail altogether.\n If the data contain any of ``np.nan``, ``np.inf``, or ``-np.inf``,\n the `fit` method will raise a ``RuntimeError``.\n\n Examples\n --------\n\n Generate some data to fit: draw random variates from the `beta`\n distribution\n\n >>> from scipy.stats import beta\n >>> a, b = 1., 2.\n >>> x = beta.rvs(a, b, size=1000)\n\n Now we can fit all four parameters (``a``, ``b``, ``loc``\n and ``scale``):\n\n >>> a1, b1, loc1, scale1 = beta.fit(x)\n\n We can also use some prior knowledge about the dataset: let's keep\n ``loc`` and ``scale`` fixed:\n\n >>> a1, b1, loc1, scale1 = beta.fit(x, floc=0, fscale=1)\n >>> loc1, scale1\n (0, 1)\n\n We can also keep shape parameters fixed by using ``f``-keywords. To\n keep the zero-th shape parameter ``a`` equal 1, use ``f0=1`` or,\n equivalently, ``fa=1``:\n\n >>> a1, b1, loc1, scale1 = beta.fit(x, fa=1, floc=0, fscale=1)\n >>> a1\n 1\n\n Not all distributions return estimates for the shape parameters.\n ``norm`` for example just returns estimates for location and scale:\n\n >>> from scipy.stats import norm\n >>> x = norm.rvs(a, b, size=1000, random_state=123)\n >>> loc1, scale1 = norm.fit(x)\n >>> loc1, scale1\n (0.92087172783841631, 2.0015750750324668)\n \"\"\"\n data = np.asarray(data)\n method = kwds.get('method', \"mle\").lower()\n\n # memory for method of moments\n Narg = len(args)\n if Narg > self.numargs:\n raise TypeError(\"Too many input arguments.\")\n\n if not np.isfinite(data).all():\n raise RuntimeError(\"The data contains non-finite values.\")\n\n start = [None]*2\n if (Narg < self.numargs) or not ('loc' in kwds and\n 'scale' in kwds):\n # get distribution specific starting locations\n start = self._fitstart(data)\n args += start[Narg:-2]\n loc = kwds.pop('loc', start[-2])\n scale = kwds.pop('scale', start[-1])\n args += (loc, scale)\n x0, func, restore, args = self._reduce_func(args, kwds, data=data)\n optimizer = kwds.pop('optimizer', optimize.fmin)\n # convert string to function in scipy.optimize\n optimizer = _fit_determine_optimizer(optimizer)\n # by now kwds must be empty, since everybody took what they needed\n if kwds:\n raise TypeError(\"Unknown arguments: %s.\" % kwds)\n\n # In some cases, method of moments can be done with fsolve/root\n # instead of an optimizer, but sometimes no solution exists,\n # especially when the user fixes parameters. Minimizing the sum\n # of squares of the error generalizes to these cases.\n vals = optimizer(func, x0, args=(ravel(data),), disp=0)\n obj = func(vals, data)\n\n if restore is not None:\n vals = restore(args, vals)\n vals = tuple(vals)\n\n loc, scale, shapes = self._unpack_loc_scale(vals)\n if not (np.all(self._argcheck(*shapes)) and scale > 0):\n raise Exception(\"Optimization converged to parameters that are \"\n \"outside the range allowed by the distribution.\")\n\n if method == 'mm':\n if not np.isfinite(obj):\n raise Exception(\"Optimization failed: either a data moment \"\n \"or fitted distribution moment is \"\n \"non-finite.\")\n\n return vals\n\n def _fit_loc_scale_support(self, data, *args):\n \"\"\"Estimate loc and scale parameters from data accounting for support.\n\n Parameters\n ----------\n data : array_like\n Data to fit.\n arg1, arg2, arg3,... : array_like\n The shape parameter(s) for the distribution (see docstring of the\n instance object for more information).\n\n Returns\n -------\n Lhat : float\n Estimated location parameter for the data.\n Shat : float\n Estimated scale parameter for the data.\n\n \"\"\"\n data = np.asarray(data)\n\n # Estimate location and scale according to the method of moments.\n loc_hat, scale_hat = self.fit_loc_scale(data, *args)\n\n # Compute the support according to the shape parameters.\n self._argcheck(*args)\n _a, _b = self._get_support(*args)\n a, b = _a, _b\n support_width = b - a\n\n # If the support is empty then return the moment-based estimates.\n if support_width <= 0:\n return loc_hat, scale_hat\n\n # Compute the proposed support according to the loc and scale\n # estimates.\n a_hat = loc_hat + a * scale_hat\n b_hat = loc_hat + b * scale_hat\n\n # Use the moment-based estimates if they are compatible with the data.\n data_a = np.min(data)\n data_b = np.max(data)\n if a_hat < data_a and data_b < b_hat:\n return loc_hat, scale_hat\n\n # Otherwise find other estimates that are compatible with the data.\n data_width = data_b - data_a\n rel_margin = 0.1\n margin = data_width * rel_margin\n\n # For a finite interval, both the location and scale\n # should have interesting values.\n if support_width < np.inf:\n loc_hat = (data_a - a) - margin\n scale_hat = (data_width + 2 * margin) / support_width\n return loc_hat, scale_hat\n\n # For a one-sided interval, use only an interesting location parameter.\n if a > -np.inf:\n return (data_a - a) - margin, 1\n elif b < np.inf:\n return (data_b - b) + margin, 1\n else:\n raise RuntimeError\n\n def fit_loc_scale(self, data, *args):\n \"\"\"\n Estimate loc and scale parameters from data using 1st and 2nd moments.\n\n Parameters\n ----------\n data : array_like\n Data to fit.\n arg1, arg2, arg3,... : array_like\n The shape parameter(s) for the distribution (see docstring of the\n instance object for more information).\n\n Returns\n -------\n Lhat : float\n Estimated location parameter for the data.\n Shat : float\n Estimated scale parameter for the data.\n\n \"\"\"\n mu, mu2 = self.stats(*args, **{'moments': 'mv'})\n tmp = asarray(data)\n muhat = tmp.mean()\n mu2hat = tmp.var()\n Shat = sqrt(mu2hat / mu2)\n Lhat = muhat - Shat*mu\n if not np.isfinite(Lhat):\n Lhat = 0\n if not (np.isfinite(Shat) and (0 < Shat)):\n Shat = 1\n return Lhat, Shat\n\n def _entropy(self, *args):\n def integ(x):\n val = self._pdf(x, *args)\n return entr(val)\n\n # upper limit is often inf, so suppress warnings when integrating\n _a, _b = self._get_support(*args)\n with np.errstate(over='ignore'):\n h = integrate.quad(integ, _a, _b)[0]\n\n if not np.isnan(h):\n return h\n else:\n # try with different limits if integration problems\n low, upp = self.ppf([1e-10, 1. - 1e-10], *args)\n if np.isinf(_b):\n upper = upp\n else:\n upper = _b\n if np.isinf(_a):\n lower = low\n else:\n lower = _a\n return integrate.quad(integ, lower, upper)[0]\n\n def expect(self, func=None, args=(), loc=0, scale=1, lb=None, ub=None,\n conditional=False, **kwds):\n \"\"\"Calculate expected value of a function with respect to the\n distribution by numerical integration.\n\n The expected value of a function ``f(x)`` with respect to a\n distribution ``dist`` is defined as::\n\n ub\n E[f(x)] = Integral(f(x) * dist.pdf(x)),\n lb\n\n where ``ub`` and ``lb`` are arguments and ``x`` has the ``dist.pdf(x)``\n distribution. If the bounds ``lb`` and ``ub`` correspond to the\n support of the distribution, e.g. ``[-inf, inf]`` in the default\n case, then the integral is the unrestricted expectation of ``f(x)``.\n Also, the function ``f(x)`` may be defined such that ``f(x)`` is ``0``\n outside a finite interval in which case the expectation is\n calculated within the finite range ``[lb, ub]``.\n\n Parameters\n ----------\n func : callable, optional\n Function for which integral is calculated. Takes only one argument.\n The default is the identity mapping f(x) = x.\n args : tuple, optional\n Shape parameters of the distribution.\n loc : float, optional\n Location parameter (default=0).\n scale : float, optional\n Scale parameter (default=1).\n lb, ub : scalar, optional\n Lower and upper bound for integration. Default is set to the\n support of the distribution.\n conditional : bool, optional\n If True, the integral is corrected by the conditional probability\n of the integration interval. The return value is the expectation\n of the function, conditional on being in the given interval.\n Default is False.\n\n Additional keyword arguments are passed to the integration routine.\n\n Returns\n -------\n expect : float\n The calculated expected value.\n\n Notes\n -----\n The integration behavior of this function is inherited from\n `scipy.integrate.quad`. Neither this function nor\n `scipy.integrate.quad` can verify whether the integral exists or is\n finite. For example ``cauchy(0).mean()`` returns ``np.nan`` and\n ``cauchy(0).expect()`` returns ``0.0``.\n\n The function is not vectorized.\n\n Examples\n --------\n\n To understand the effect of the bounds of integration consider\n\n >>> from scipy.stats import expon\n >>> expon(1).expect(lambda x: 1, lb=0.0, ub=2.0)\n 0.6321205588285578\n\n This is close to\n\n >>> expon(1).cdf(2.0) - expon(1).cdf(0.0)\n 0.6321205588285577\n\n If ``conditional=True``\n\n >>> expon(1).expect(lambda x: 1, lb=0.0, ub=2.0, conditional=True)\n 1.0000000000000002\n\n The slight deviation from 1 is due to numerical integration.\n \"\"\"\n lockwds = {'loc': loc,\n 'scale': scale}\n self._argcheck(*args)\n _a, _b = self._get_support(*args)\n if func is None:\n def fun(x, *args):\n return x * self.pdf(x, *args, **lockwds)\n else:\n def fun(x, *args):\n return func(x) * self.pdf(x, *args, **lockwds)\n if lb is None:\n lb = loc + _a * scale\n if ub is None:\n ub = loc + _b * scale\n if conditional:\n invfac = (self.sf(lb, *args, **lockwds)\n - self.sf(ub, *args, **lockwds))\n else:\n invfac = 1.0\n kwds['args'] = args\n # Silence floating point warnings from integration.\n with np.errstate(all='ignore'):\n vals = integrate.quad(fun, lb, ub, **kwds)[0] / invfac\n return vals\n\n def _param_info(self):\n shape_info = self._shape_info()\n loc_info = _ShapeInfo(\"loc\", False, (-np.inf, np.inf), (False, False))\n scale_info = _ShapeInfo(\"scale\", False, (0, np.inf), (False, False))\n param_info = shape_info + [loc_info, scale_info]\n return param_info\n\n# Helpers for the discrete distributions\ndef _drv2_moment(self, n, *args):\n \"\"\"Non-central moment of discrete distribution.\"\"\"\n def fun(x):\n return np.power(x, n) * self._pmf(x, *args)\n\n _a, _b = self._get_support(*args)\n return _expect(fun, _a, _b, self.ppf(0.5, *args), self.inc)\n\n\ndef _drv2_ppfsingle(self, q, *args): # Use basic bisection algorithm\n _a, _b = self._get_support(*args)\n b = _b\n a = _a\n if isinf(b): # Be sure ending point is > q\n b = int(max(100*q, 10))\n while 1:\n if b >= _b:\n qb = 1.0\n break\n qb = self._cdf(b, *args)\n if (qb < q):\n b += 10\n else:\n break\n else:\n qb = 1.0\n if isinf(a): # be sure starting point < q\n a = int(min(-100*q, -10))\n while 1:\n if a <= _a:\n qb = 0.0\n break\n qa = self._cdf(a, *args)\n if (qa > q):\n a -= 10\n else:\n break\n else:\n qa = self._cdf(a, *args)\n\n while 1:\n if (qa == q):\n return a\n if (qb == q):\n return b\n if b <= a+1:\n if qa > q:\n return a\n else:\n return b\n c = int((a+b)/2.0)\n qc = self._cdf(c, *args)\n if (qc < q):\n if a != c:\n a = c\n else:\n raise RuntimeError('updating stopped, endless loop')\n qa = qc\n elif (qc > q):\n if b != c:\n b = c\n else:\n raise RuntimeError('updating stopped, endless loop')\n qb = qc\n else:\n return c\n\n\n# Must over-ride one of _pmf or _cdf or pass in\n# x_k, p(x_k) lists in initialization\n\n\nclass rv_discrete(rv_generic):\n \"\"\"A generic discrete random variable class meant for subclassing.\n\n `rv_discrete` is a base class to construct specific distribution classes\n and instances for discrete random variables. It can also be used\n to construct an arbitrary distribution defined by a list of support\n points and corresponding probabilities.\n\n Parameters\n ----------\n a : float, optional\n Lower bound of the support of the distribution, default: 0\n b : float, optional\n Upper bound of the support of the distribution, default: plus infinity\n moment_tol : float, optional\n The tolerance for the generic calculation of moments.\n values : tuple of two array_like, optional\n ``(xk, pk)`` where ``xk`` are integers and ``pk`` are the non-zero\n probabilities between 0 and 1 with ``sum(pk) = 1``. ``xk``\n and ``pk`` must have the same shape.\n inc : integer, optional\n Increment for the support of the distribution.\n Default is 1. (other values have not been tested)\n badvalue : float, optional\n The value in a result arrays that indicates a value that for which\n some argument restriction is violated, default is np.nan.\n name : str, optional\n The name of the instance. This string is used to construct the default\n example for distributions.\n longname : str, optional\n This string is used as part of the first line of the docstring returned\n when a subclass has no docstring of its own. Note: `longname` exists\n for backwards compatibility, do not use for new subclasses.\n shapes : str, optional\n The shape of the distribution. For example \"m, n\" for a distribution\n that takes two integers as the two shape arguments for all its methods\n If not provided, shape parameters will be inferred from\n the signatures of the private methods, ``_pmf`` and ``_cdf`` of\n the instance.\n extradoc : str, optional, deprecated\n This string is used as the last part of the docstring returned when a\n subclass has no docstring of its own. Note: `extradoc` exists for\n backwards compatibility, do not use for new subclasses.\n seed : {None, int, `numpy.random.Generator`,\n `numpy.random.RandomState`}, optional\n\n If `seed` is None (or `np.random`), the `numpy.random.RandomState`\n singleton is used.\n If `seed` is an int, a new ``RandomState`` instance is used,\n seeded with `seed`.\n If `seed` is already a ``Generator`` or ``RandomState`` instance then\n that instance is used.\n\n Methods\n -------\n rvs\n pmf\n logpmf\n cdf\n logcdf\n sf\n logsf\n ppf\n isf\n moment\n stats\n entropy\n expect\n median\n mean\n std\n var\n interval\n __call__\n support\n\n Notes\n -----\n This class is similar to `rv_continuous`. Whether a shape parameter is\n valid is decided by an ``_argcheck`` method (which defaults to checking\n that its arguments are strictly positive.)\n The main differences are:\n\n - the support of the distribution is a set of integers\n - instead of the probability density function, ``pdf`` (and the\n corresponding private ``_pdf``), this class defines the\n *probability mass function*, `pmf` (and the corresponding\n private ``_pmf``.)\n - scale parameter is not defined.\n\n To create a new discrete distribution, we would do the following:\n\n >>> from scipy.stats import rv_discrete\n >>> class poisson_gen(rv_discrete):\n ... \"Poisson distribution\"\n ... def _pmf(self, k, mu):\n ... return exp(-mu) * mu**k / factorial(k)\n\n and create an instance::\n\n >>> poisson = poisson_gen(name=\"poisson\")\n\n Note that above we defined the Poisson distribution in the standard form.\n Shifting the distribution can be done by providing the ``loc`` parameter\n to the methods of the instance. For example, ``poisson.pmf(x, mu, loc)``\n delegates the work to ``poisson._pmf(x-loc, mu)``.\n\n **Discrete distributions from a list of probabilities**\n\n Alternatively, you can construct an arbitrary discrete rv defined\n on a finite set of values ``xk`` with ``Prob{X=xk} = pk`` by using the\n ``values`` keyword argument to the `rv_discrete` constructor.\n\n Examples\n --------\n Custom made discrete distribution:\n\n >>> from scipy import stats\n >>> xk = np.arange(7)\n >>> pk = (0.1, 0.2, 0.3, 0.1, 0.1, 0.0, 0.2)\n >>> custm = stats.rv_discrete(name='custm', values=(xk, pk))\n >>>\n >>> import matplotlib.pyplot as plt\n >>> fig, ax = plt.subplots(1, 1)\n >>> ax.plot(xk, custm.pmf(xk), 'ro', ms=12, mec='r')\n >>> ax.vlines(xk, 0, custm.pmf(xk), colors='r', lw=4)\n >>> plt.show()\n\n Random number generation:\n\n >>> R = custm.rvs(size=100)\n\n \"\"\"\n def __new__(cls, a=0, b=inf, name=None, badvalue=None,\n moment_tol=1e-8, values=None, inc=1, longname=None,\n shapes=None, extradoc=None, seed=None):\n\n if values is not None:\n # dispatch to a subclass\n return super(rv_discrete, cls).__new__(rv_sample)\n else:\n # business as usual\n return super(rv_discrete, cls).__new__(cls)\n\n def __init__(self, a=0, b=inf, name=None, badvalue=None,\n moment_tol=1e-8, values=None, inc=1, longname=None,\n shapes=None, extradoc=None, seed=None):\n\n super().__init__(seed)\n\n if extradoc is not None:\n warnings.warn(\"extradoc is deprecated and will be removed in \"\n \"SciPy 1.11.0\", DeprecationWarning)\n\n # cf generic freeze\n self._ctor_param = dict(\n a=a, b=b, name=name, badvalue=badvalue,\n moment_tol=moment_tol, values=values, inc=inc,\n longname=longname, shapes=shapes, extradoc=extradoc, seed=seed)\n\n if badvalue is None:\n badvalue = nan\n self.badvalue = badvalue\n self.a = a\n self.b = b\n self.moment_tol = moment_tol\n self.inc = inc\n self.shapes = shapes\n\n if values is not None:\n raise ValueError(\"rv_discrete.__init__(..., values != None, ...)\")\n\n self._construct_argparser(meths_to_inspect=[self._pmf, self._cdf],\n locscale_in='loc=0',\n # scale=1 for discrete RVs\n locscale_out='loc, 1')\n self._attach_methods()\n self._construct_docstrings(name, longname, extradoc)\n\n def __getstate__(self):\n dct = self.__dict__.copy()\n # these methods will be remade in __setstate__\n attrs = [\"_parse_args\", \"_parse_args_stats\", \"_parse_args_rvs\",\n \"_cdfvec\", \"_ppfvec\", \"generic_moment\"]\n [dct.pop(attr, None) for attr in attrs]\n return dct\n\n def _attach_methods(self):\n \"\"\"Attaches dynamically created methods to the rv_discrete instance.\"\"\"\n self._cdfvec = vectorize(self._cdf_single, otypes='d')\n self.vecentropy = vectorize(self._entropy)\n\n # _attach_methods is responsible for calling _attach_argparser_methods\n self._attach_argparser_methods()\n\n # nin correction needs to be after we know numargs\n # correct nin for generic moment vectorization\n _vec_generic_moment = vectorize(_drv2_moment, otypes='d')\n _vec_generic_moment.nin = self.numargs + 2\n self.generic_moment = types.MethodType(_vec_generic_moment, self)\n\n # correct nin for ppf vectorization\n _vppf = vectorize(_drv2_ppfsingle, otypes='d')\n _vppf.nin = self.numargs + 2\n self._ppfvec = types.MethodType(_vppf, self)\n\n # now that self.numargs is defined, we can adjust nin\n self._cdfvec.nin = self.numargs + 1\n\n def _construct_docstrings(self, name, longname, extradoc):\n if name is None:\n name = 'Distribution'\n self.name = name\n self.extradoc = extradoc\n\n # generate docstring for subclass instances\n if longname is None:\n if name[0] in ['aeiouAEIOU']:\n hstr = \"An \"\n else:\n hstr = \"A \"\n longname = hstr + name\n\n if sys.flags.optimize < 2:\n # Skip adding docstrings if interpreter is run with -OO\n if self.__doc__ is None:\n self._construct_default_doc(longname=longname,\n extradoc=extradoc,\n docdict=docdict_discrete,\n discrete='discrete')\n else:\n dct = dict(distdiscrete)\n self._construct_doc(docdict_discrete, dct.get(self.name))\n\n # discrete RV do not have the scale parameter, remove it\n self.__doc__ = self.__doc__.replace(\n '\\n scale : array_like, '\n 'optional\\n scale parameter (default=1)', '')\n\n def _updated_ctor_param(self):\n \"\"\"Return the current version of _ctor_param, possibly updated by user.\n\n Used by freezing.\n Keep this in sync with the signature of __init__.\n \"\"\"\n dct = self._ctor_param.copy()\n dct['a'] = self.a\n dct['b'] = self.b\n dct['badvalue'] = self.badvalue\n dct['moment_tol'] = self.moment_tol\n dct['inc'] = self.inc\n dct['name'] = self.name\n dct['shapes'] = self.shapes\n dct['extradoc'] = self.extradoc\n return dct\n\n def _nonzero(self, k, *args):\n return floor(k) == k\n\n def _pmf(self, k, *args):\n return self._cdf(k, *args) - self._cdf(k-1, *args)\n\n def _logpmf(self, k, *args):\n return log(self._pmf(k, *args))\n\n def _logpxf(self, k, *args):\n # continuous distributions have PDF, discrete have PMF, but sometimes\n # the distinction doesn't matter. This lets us use `_logpxf` for both\n # discrete and continuous distributions.\n return self._logpmf(k, *args)\n\n def _unpack_loc_scale(self, theta):\n try:\n loc = theta[-1]\n scale = 1\n args = tuple(theta[:-1])\n except IndexError as e:\n raise ValueError(\"Not enough input arguments.\") from e\n return loc, scale, args\n\n def _cdf_single(self, k, *args):\n _a, _b = self._get_support(*args)\n m = arange(int(_a), k+1)\n return np.sum(self._pmf(m, *args), axis=0)\n\n def _cdf(self, x, *args):\n k = floor(x)\n return self._cdfvec(k, *args)\n\n # generic _logcdf, _sf, _logsf, _ppf, _isf, _rvs defined in rv_generic\n\n def rvs(self, *args, **kwargs):\n \"\"\"Random variates of given type.\n\n Parameters\n ----------\n arg1, arg2, arg3,... : array_like\n The shape parameter(s) for the distribution (see docstring of the\n instance object for more information).\n loc : array_like, optional\n Location parameter (default=0).\n size : int or tuple of ints, optional\n Defining number of random variates (Default is 1). Note that `size`\n has to be given as keyword, not as positional argument.\n random_state : {None, int, `numpy.random.Generator`,\n `numpy.random.RandomState`}, optional\n\n If `seed` is None (or `np.random`), the `numpy.random.RandomState`\n singleton is used.\n If `seed` is an int, a new ``RandomState`` instance is used,\n seeded with `seed`.\n If `seed` is already a ``Generator`` or ``RandomState`` instance\n then that instance is used.\n\n Returns\n -------\n rvs : ndarray or scalar\n Random variates of given `size`.\n\n \"\"\"\n kwargs['discrete'] = True\n return super().rvs(*args, **kwargs)\n\n def pmf(self, k, *args, **kwds):\n \"\"\"Probability mass function at k of the given RV.\n\n Parameters\n ----------\n k : array_like\n Quantiles.\n arg1, arg2, arg3,... : array_like\n The shape parameter(s) for the distribution (see docstring of the\n instance object for more information)\n loc : array_like, optional\n Location parameter (default=0).\n\n Returns\n -------\n pmf : array_like\n Probability mass function evaluated at k\n\n \"\"\"\n args, loc, _ = self._parse_args(*args, **kwds)\n k, loc = map(asarray, (k, loc))\n args = tuple(map(asarray, args))\n _a, _b = self._get_support(*args)\n k = asarray((k-loc))\n cond0 = self._argcheck(*args)\n cond1 = (k >= _a) & (k <= _b) & self._nonzero(k, *args)\n cond = cond0 & cond1\n output = zeros(shape(cond), 'd')\n place(output, (1-cond0) + np.isnan(k), self.badvalue)\n if np.any(cond):\n goodargs = argsreduce(cond, *((k,)+args))\n place(output, cond, np.clip(self._pmf(*goodargs), 0, 1))\n if output.ndim == 0:\n return output[()]\n return output\n\n def logpmf(self, k, *args, **kwds):\n \"\"\"Log of the probability mass function at k of the given RV.\n\n Parameters\n ----------\n k : array_like\n Quantiles.\n arg1, arg2, arg3,... : array_like\n The shape parameter(s) for the distribution (see docstring of the\n instance object for more information).\n loc : array_like, optional\n Location parameter. Default is 0.\n\n Returns\n -------\n logpmf : array_like\n Log of the probability mass function evaluated at k.\n\n \"\"\"\n args, loc, _ = self._parse_args(*args, **kwds)\n k, loc = map(asarray, (k, loc))\n args = tuple(map(asarray, args))\n _a, _b = self._get_support(*args)\n k = asarray((k-loc))\n cond0 = self._argcheck(*args)\n cond1 = (k >= _a) & (k <= _b) & self._nonzero(k, *args)\n cond = cond0 & cond1\n output = empty(shape(cond), 'd')\n output.fill(NINF)\n place(output, (1-cond0) + np.isnan(k), self.badvalue)\n if np.any(cond):\n goodargs = argsreduce(cond, *((k,)+args))\n place(output, cond, self._logpmf(*goodargs))\n if output.ndim == 0:\n return output[()]\n return output\n\n def cdf(self, k, *args, **kwds):\n \"\"\"Cumulative distribution function of the given RV.\n\n Parameters\n ----------\n k : array_like, int\n Quantiles.\n arg1, arg2, arg3,... : array_like\n The shape parameter(s) for the distribution (see docstring of the\n instance object for more information).\n loc : array_like, optional\n Location parameter (default=0).\n\n Returns\n -------\n cdf : ndarray\n Cumulative distribution function evaluated at `k`.\n\n \"\"\"\n args, loc, _ = self._parse_args(*args, **kwds)\n k, loc = map(asarray, (k, loc))\n args = tuple(map(asarray, args))\n _a, _b = self._get_support(*args)\n k = asarray((k-loc))\n cond0 = self._argcheck(*args)\n cond1 = (k >= _a) & (k < _b)\n cond2 = (k >= _b)\n cond = cond0 & cond1\n output = zeros(shape(cond), 'd')\n place(output, cond2*(cond0 == cond0), 1.0)\n place(output, (1-cond0) + np.isnan(k), self.badvalue)\n\n if np.any(cond):\n goodargs = argsreduce(cond, *((k,)+args))\n place(output, cond, np.clip(self._cdf(*goodargs), 0, 1))\n if output.ndim == 0:\n return output[()]\n return output\n\n def logcdf(self, k, *args, **kwds):\n \"\"\"Log of the cumulative distribution function at k of the given RV.\n\n Parameters\n ----------\n k : array_like, int\n Quantiles.\n arg1, arg2, arg3,... : array_like\n The shape parameter(s) for the distribution (see docstring of the\n instance object for more information).\n loc : array_like, optional\n Location parameter (default=0).\n\n Returns\n -------\n logcdf : array_like\n Log of the cumulative distribution function evaluated at k.\n\n \"\"\"\n args, loc, _ = self._parse_args(*args, **kwds)\n k, loc = map(asarray, (k, loc))\n args = tuple(map(asarray, args))\n _a, _b = self._get_support(*args)\n k = asarray((k-loc))\n cond0 = self._argcheck(*args)\n cond1 = (k >= _a) & (k < _b)\n cond2 = (k >= _b)\n cond = cond0 & cond1\n output = empty(shape(cond), 'd')\n output.fill(NINF)\n place(output, (1-cond0) + np.isnan(k), self.badvalue)\n place(output, cond2*(cond0 == cond0), 0.0)\n\n if np.any(cond):\n goodargs = argsreduce(cond, *((k,)+args))\n place(output, cond, self._logcdf(*goodargs))\n if output.ndim == 0:\n return output[()]\n return output\n\n def sf(self, k, *args, **kwds):\n \"\"\"Survival function (1 - `cdf`) at k of the given RV.\n\n Parameters\n ----------\n k : array_like\n Quantiles.\n arg1, arg2, arg3,... : array_like\n The shape parameter(s) for the distribution (see docstring of the\n instance object for more information).\n loc : array_like, optional\n Location parameter (default=0).\n\n Returns\n -------\n sf : array_like\n Survival function evaluated at k.\n\n \"\"\"\n args, loc, _ = self._parse_args(*args, **kwds)\n k, loc = map(asarray, (k, loc))\n args = tuple(map(asarray, args))\n _a, _b = self._get_support(*args)\n k = asarray(k-loc)\n cond0 = self._argcheck(*args)\n cond1 = (k >= _a) & (k < _b)\n cond2 = (k < _a) & cond0\n cond = cond0 & cond1\n output = zeros(shape(cond), 'd')\n place(output, (1-cond0) + np.isnan(k), self.badvalue)\n place(output, cond2, 1.0)\n if np.any(cond):\n goodargs = argsreduce(cond, *((k,)+args))\n place(output, cond, np.clip(self._sf(*goodargs), 0, 1))\n if output.ndim == 0:\n return output[()]\n return output\n\n def logsf(self, k, *args, **kwds):\n \"\"\"Log of the survival function of the given RV.\n\n Returns the log of the \"survival function,\" defined as 1 - `cdf`,\n evaluated at `k`.\n\n Parameters\n ----------\n k : array_like\n Quantiles.\n arg1, arg2, arg3,... : array_like\n The shape parameter(s) for the distribution (see docstring of the\n instance object for more information).\n loc : array_like, optional\n Location parameter (default=0).\n\n Returns\n -------\n logsf : ndarray\n Log of the survival function evaluated at `k`.\n\n \"\"\"\n args, loc, _ = self._parse_args(*args, **kwds)\n k, loc = map(asarray, (k, loc))\n args = tuple(map(asarray, args))\n _a, _b = self._get_support(*args)\n k = asarray(k-loc)\n cond0 = self._argcheck(*args)\n cond1 = (k >= _a) & (k < _b)\n cond2 = (k < _a) & cond0\n cond = cond0 & cond1\n output = empty(shape(cond), 'd')\n output.fill(NINF)\n place(output, (1-cond0) + np.isnan(k), self.badvalue)\n place(output, cond2, 0.0)\n if np.any(cond):\n goodargs = argsreduce(cond, *((k,)+args))\n place(output, cond, self._logsf(*goodargs))\n if output.ndim == 0:\n return output[()]\n return output\n\n def ppf(self, q, *args, **kwds):\n \"\"\"Percent point function (inverse of `cdf`) at q of the given RV.\n\n Parameters\n ----------\n q : array_like\n Lower tail probability.\n arg1, arg2, arg3,... : array_like\n The shape parameter(s) for the distribution (see docstring of the\n instance object for more information).\n loc : array_like, optional\n Location parameter (default=0).\n\n Returns\n -------\n k : array_like\n Quantile corresponding to the lower tail probability, q.\n\n \"\"\"\n args, loc, _ = self._parse_args(*args, **kwds)\n q, loc = map(asarray, (q, loc))\n args = tuple(map(asarray, args))\n _a, _b = self._get_support(*args)\n cond0 = self._argcheck(*args) & (loc == loc)\n cond1 = (q > 0) & (q < 1)\n cond2 = (q == 1) & cond0\n cond = cond0 & cond1\n output = np.full(shape(cond), fill_value=self.badvalue, dtype='d')\n # output type 'd' to handle nin and inf\n place(output, (q == 0)*(cond == cond), _a-1 + loc)\n place(output, cond2, _b + loc)\n if np.any(cond):\n goodargs = argsreduce(cond, *((q,)+args+(loc,)))\n loc, goodargs = goodargs[-1], goodargs[:-1]\n place(output, cond, self._ppf(*goodargs) + loc)\n\n if output.ndim == 0:\n return output[()]\n return output\n\n def isf(self, q, *args, **kwds):\n \"\"\"Inverse survival function (inverse of `sf`) at q of the given RV.\n\n Parameters\n ----------\n q : array_like\n Upper tail probability.\n arg1, arg2, arg3,... : array_like\n The shape parameter(s) for the distribution (see docstring of the\n instance object for more information).\n loc : array_like, optional\n Location parameter (default=0).\n\n Returns\n -------\n k : ndarray or scalar\n Quantile corresponding to the upper tail probability, q.\n\n \"\"\"\n args, loc, _ = self._parse_args(*args, **kwds)\n q, loc = map(asarray, (q, loc))\n args = tuple(map(asarray, args))\n _a, _b = self._get_support(*args)\n cond0 = self._argcheck(*args) & (loc == loc)\n cond1 = (q > 0) & (q < 1)\n cond2 = (q == 1) & cond0\n cond3 = (q == 0) & cond0\n cond = cond0 & cond1\n\n # same problem as with ppf; copied from ppf and changed\n output = np.full(shape(cond), fill_value=self.badvalue, dtype='d')\n # output type 'd' to handle nin and inf\n lower_bound = _a - 1 + loc\n upper_bound = _b + loc\n place(output, cond2*(cond == cond), lower_bound)\n place(output, cond3*(cond == cond), upper_bound)\n\n # call place only if at least 1 valid argument\n if np.any(cond):\n goodargs = argsreduce(cond, *((q,)+args+(loc,)))\n loc, goodargs = goodargs[-1], goodargs[:-1]\n # PB same as ticket 766\n place(output, cond, self._isf(*goodargs) + loc)\n\n if output.ndim == 0:\n return output[()]\n return output\n\n def _entropy(self, *args):\n if hasattr(self, 'pk'):\n return stats.entropy(self.pk)\n else:\n _a, _b = self._get_support(*args)\n return _expect(lambda x: entr(self.pmf(x, *args)),\n _a, _b, self.ppf(0.5, *args), self.inc)\n\n def expect(self, func=None, args=(), loc=0, lb=None, ub=None,\n conditional=False, maxcount=1000, tolerance=1e-10, chunksize=32):\n \"\"\"\n Calculate expected value of a function with respect to the distribution\n for discrete distribution by numerical summation.\n\n Parameters\n ----------\n func : callable, optional\n Function for which the expectation value is calculated.\n Takes only one argument.\n The default is the identity mapping f(k) = k.\n args : tuple, optional\n Shape parameters of the distribution.\n loc : float, optional\n Location parameter.\n Default is 0.\n lb, ub : int, optional\n Lower and upper bound for the summation, default is set to the\n support of the distribution, inclusive (``lb <= k <= ub``).\n conditional : bool, optional\n If true then the expectation is corrected by the conditional\n probability of the summation interval. The return value is the\n expectation of the function, `func`, conditional on being in\n the given interval (k such that ``lb <= k <= ub``).\n Default is False.\n maxcount : int, optional\n Maximal number of terms to evaluate (to avoid an endless loop for\n an infinite sum). Default is 1000.\n tolerance : float, optional\n Absolute tolerance for the summation. Default is 1e-10.\n chunksize : int, optional\n Iterate over the support of a distributions in chunks of this size.\n Default is 32.\n\n Returns\n -------\n expect : float\n Expected value.\n\n Notes\n -----\n For heavy-tailed distributions, the expected value may or\n may not exist,\n depending on the function, `func`. If it does exist, but the\n sum converges\n slowly, the accuracy of the result may be rather low. For instance, for\n ``zipf(4)``, accuracy for mean, variance in example is only 1e-5.\n increasing `maxcount` and/or `chunksize` may improve the result,\n but may also make zipf very slow.\n\n The function is not vectorized.\n\n \"\"\"\n if func is None:\n def fun(x):\n # loc and args from outer scope\n return (x+loc)*self._pmf(x, *args)\n else:\n def fun(x):\n # loc and args from outer scope\n return func(x+loc)*self._pmf(x, *args)\n # used pmf because _pmf does not check support in randint and there\n # might be problems(?) with correct self.a, self.b at this stage maybe\n # not anymore, seems to work now with _pmf\n\n _a, _b = self._get_support(*args)\n if lb is None:\n lb = _a\n else:\n lb = lb - loc # convert bound for standardized distribution\n if ub is None:\n ub = _b\n else:\n ub = ub - loc # convert bound for standardized distribution\n if conditional:\n invfac = self.sf(lb-1, *args) - self.sf(ub, *args)\n else:\n invfac = 1.0\n\n if isinstance(self, rv_sample):\n res = self._expect(fun, lb, ub)\n return res / invfac\n\n # iterate over the support, starting from the median\n x0 = self.ppf(0.5, *args)\n res = _expect(fun, lb, ub, x0, self.inc, maxcount, tolerance, chunksize)\n return res / invfac\n\n def _param_info(self):\n shape_info = self._shape_info()\n loc_info = _ShapeInfo(\"loc\", True, (-np.inf, np.inf), (False, False))\n param_info = shape_info + [loc_info]\n return param_info\n\n\ndef _expect(fun, lb, ub, x0, inc, maxcount=1000, tolerance=1e-10,\n chunksize=32):\n \"\"\"Helper for computing the expectation value of `fun`.\"\"\"\n # short-circuit if the support size is small enough\n if (ub - lb) <= chunksize:\n supp = np.arange(lb, ub+1, inc)\n vals = fun(supp)\n return np.sum(vals)\n\n # otherwise, iterate starting from x0\n if x0 < lb:\n x0 = lb\n if x0 > ub:\n x0 = ub\n\n count, tot = 0, 0.\n # iterate over [x0, ub] inclusive\n for x in _iter_chunked(x0, ub+1, chunksize=chunksize, inc=inc):\n count += x.size\n delta = np.sum(fun(x))\n tot += delta\n if abs(delta) < tolerance * x.size:\n break\n if count > maxcount:\n warnings.warn('expect(): sum did not converge', RuntimeWarning)\n return tot\n\n # iterate over [lb, x0)\n for x in _iter_chunked(x0-1, lb-1, chunksize=chunksize, inc=-inc):\n count += x.size\n delta = np.sum(fun(x))\n tot += delta\n if abs(delta) < tolerance * x.size:\n break\n if count > maxcount:\n warnings.warn('expect(): sum did not converge', RuntimeWarning)\n break\n\n return tot\n\n\ndef _iter_chunked(x0, x1, chunksize=4, inc=1):\n \"\"\"Iterate from x0 to x1 in chunks of chunksize and steps inc.\n\n x0 must be finite, x1 need not be. In the latter case, the iterator is\n infinite.\n Handles both x0 < x1 and x0 > x1. In the latter case, iterates downwards\n (make sure to set inc < 0.)\n\n >>> [x for x in _iter_chunked(2, 5, inc=2)]\n [array([2, 4])]\n >>> [x for x in _iter_chunked(2, 11, inc=2)]\n [array([2, 4, 6, 8]), array([10])]\n >>> [x for x in _iter_chunked(2, -5, inc=-2)]\n [array([ 2, 0, -2, -4])]\n >>> [x for x in _iter_chunked(2, -9, inc=-2)]\n [array([ 2, 0, -2, -4]), array([-6, -8])]\n\n \"\"\"\n if inc == 0:\n raise ValueError('Cannot increment by zero.')\n if chunksize <= 0:\n raise ValueError('Chunk size must be positive; got %s.' % chunksize)\n\n s = 1 if inc > 0 else -1\n stepsize = abs(chunksize * inc)\n\n x = x0\n while (x - x1) * inc < 0:\n delta = min(stepsize, abs(x - x1))\n step = delta * s\n supp = np.arange(x, x + step, inc)\n x += step\n yield supp\n\n\nclass rv_sample(rv_discrete):\n \"\"\"A 'sample' discrete distribution defined by the support and values.\n\n The ctor ignores most of the arguments, only needs the `values` argument.\n \"\"\"\n def __init__(self, a=0, b=inf, name=None, badvalue=None,\n moment_tol=1e-8, values=None, inc=1, longname=None,\n shapes=None, extradoc=None, seed=None):\n\n super(rv_discrete, self).__init__(seed)\n\n if extradoc is not None:\n warnings.warn(\"extradoc is deprecated and will be removed in \"\n \"SciPy 1.11.0\", DeprecationWarning)\n\n if values is None:\n raise ValueError(\"rv_sample.__init__(..., values=None,...)\")\n\n # cf generic freeze\n self._ctor_param = dict(\n a=a, b=b, name=name, badvalue=badvalue,\n moment_tol=moment_tol, values=values, inc=inc,\n longname=longname, shapes=shapes, extradoc=extradoc, seed=seed)\n\n if badvalue is None:\n badvalue = nan\n self.badvalue = badvalue\n self.moment_tol = moment_tol\n self.inc = inc\n self.shapes = shapes\n self.vecentropy = self._entropy\n\n xk, pk = values\n\n if np.shape(xk) != np.shape(pk):\n raise ValueError(\"xk and pk must have the same shape.\")\n if np.less(pk, 0.0).any():\n raise ValueError(\"All elements of pk must be non-negative.\")\n if not np.allclose(np.sum(pk), 1):\n raise ValueError(\"The sum of provided pk is not 1.\")\n\n indx = np.argsort(np.ravel(xk))\n self.xk = np.take(np.ravel(xk), indx, 0)\n self.pk = np.take(np.ravel(pk), indx, 0)\n self.a = self.xk[0]\n self.b = self.xk[-1]\n\n self.qvals = np.cumsum(self.pk, axis=0)\n\n self.shapes = ' ' # bypass inspection\n\n self._construct_argparser(meths_to_inspect=[self._pmf],\n locscale_in='loc=0',\n # scale=1 for discrete RVs\n locscale_out='loc, 1')\n\n self._attach_methods()\n\n self._construct_docstrings(name, longname, extradoc)\n\n def __getstate__(self):\n dct = self.__dict__.copy()\n\n # these methods will be remade in rv_generic.__setstate__,\n # which calls rv_generic._attach_methods\n attrs = [\"_parse_args\", \"_parse_args_stats\", \"_parse_args_rvs\"]\n [dct.pop(attr, None) for attr in attrs]\n\n return dct\n\n def _attach_methods(self):\n \"\"\"Attaches dynamically created argparser methods.\"\"\"\n self._attach_argparser_methods()\n\n def _get_support(self, *args):\n \"\"\"Return the support of the (unscaled, unshifted) distribution.\n\n Parameters\n ----------\n arg1, arg2, ... : array_like\n The shape parameter(s) for the distribution (see docstring of the\n instance object for more information).\n\n Returns\n -------\n a, b : numeric (float, or int or +/-np.inf)\n end-points of the distribution's support.\n \"\"\"\n return self.a, self.b\n\n def _pmf(self, x):\n return np.select([x == k for k in self.xk],\n [np.broadcast_arrays(p, x)[0] for p in self.pk], 0)\n\n def _cdf(self, x):\n xx, xxk = np.broadcast_arrays(x[:, None], self.xk)\n indx = np.argmax(xxk > xx, axis=-1) - 1\n return self.qvals[indx]\n\n def _ppf(self, q):\n qq, sqq = np.broadcast_arrays(q[..., None], self.qvals)\n indx = argmax(sqq >= qq, axis=-1)\n return self.xk[indx]\n\n def _rvs(self, size=None, random_state=None):\n # Need to define it explicitly, otherwise .rvs() with size=None\n # fails due to explicit broadcasting in _ppf\n U = random_state.uniform(size=size)\n if size is None:\n U = np.array(U, ndmin=1)\n Y = self._ppf(U)[0]\n else:\n Y = self._ppf(U)\n return Y\n\n def _entropy(self):\n return stats.entropy(self.pk)\n\n def generic_moment(self, n):\n n = asarray(n)\n return np.sum(self.xk**n[np.newaxis, ...] * self.pk, axis=0)\n\n def _expect(self, fun, lb, ub, *args, **kwds):\n # ignore all args, just do a brute force summation\n supp = self.xk[(lb <= self.xk) & (self.xk <= ub)]\n vals = fun(supp)\n return np.sum(vals)\n\n\ndef _check_shape(argshape, size):\n \"\"\"\n This is a utility function used by `_rvs()` in the class geninvgauss_gen.\n It compares the tuple argshape to the tuple size.\n\n Parameters\n ----------\n argshape : tuple of integers\n Shape of the arguments.\n size : tuple of integers or integer\n Size argument of rvs().\n\n Returns\n -------\n The function returns two tuples, scalar_shape and bc.\n\n scalar_shape : tuple\n Shape to which the 1-d array of random variates returned by\n _rvs_scalar() is converted when it is copied into the\n output array of _rvs().\n\n bc : tuple of booleans\n bc is an tuple the same length as size. bc[j] is True if the data\n associated with that index is generated in one call of _rvs_scalar().\n\n \"\"\"\n scalar_shape = []\n bc = []\n for argdim, sizedim in zip_longest(argshape[::-1], size[::-1],\n fillvalue=1):\n if sizedim > argdim or (argdim == sizedim == 1):\n scalar_shape.append(sizedim)\n bc.append(True)\n else:\n bc.append(False)\n return tuple(scalar_shape[::-1]), tuple(bc[::-1])\n\n\ndef get_distribution_names(namespace_pairs, rv_base_class):\n \"\"\"Collect names of statistical distributions and their generators.\n\n Parameters\n ----------\n namespace_pairs : sequence\n A snapshot of (name, value) pairs in the namespace of a module.\n rv_base_class : class\n The base class of random variable generator classes in a module.\n\n Returns\n -------\n distn_names : list of strings\n Names of the statistical distributions.\n distn_gen_names : list of strings\n Names of the generators of the statistical distributions.\n Note that these are not simply the names of the statistical\n distributions, with a _gen suffix added.\n\n \"\"\"\n distn_names = []\n distn_gen_names = []\n for name, value in namespace_pairs:\n if name.startswith('_'):\n continue\n if name.endswith('_gen') and issubclass(value, rv_base_class):\n distn_gen_names.append(name)\n if isinstance(value, rv_base_class):\n distn_names.append(name)\n return distn_names, distn_gen_names\n", "# -*- coding: utf-8 -*-\n\"\"\"Functions for FIR filter design.\"\"\"\n\nfrom math import ceil, log\nimport operator\nimport warnings\n\nimport numpy as np\nfrom numpy.fft import irfft, fft, ifft\nfrom scipy.special import sinc\nfrom scipy.linalg import (toeplitz, hankel, solve, LinAlgError, LinAlgWarning,\n lstsq)\n\nfrom . import _sigtools\n\n__all__ = ['kaiser_beta', 'kaiser_atten', 'kaiserord',\n 'firwin', 'firwin2', 'remez', 'firls', 'minimum_phase']\n\n\ndef _get_fs(fs, nyq):\n \"\"\"\n Utility for replacing the argument 'nyq' (with default 1) with 'fs'.\n \"\"\"\n if nyq is None and fs is None:\n fs = 2\n elif nyq is not None:\n if fs is not None:\n raise ValueError(\"Values cannot be given for both 'nyq' and 'fs'.\")\n fs = 2*nyq\n return fs\n\n\n# Some notes on function parameters:\n#\n# `cutoff` and `width` are given as numbers between 0 and 1. These are\n# relative frequencies, expressed as a fraction of the Nyquist frequency.\n# For example, if the Nyquist frequency is 2 KHz, then width=0.15 is a width\n# of 300 Hz.\n#\n# The `order` of a FIR filter is one less than the number of taps.\n# This is a potential source of confusion, so in the following code,\n# we will always use the number of taps as the parameterization of\n# the 'size' of the filter. The \"number of taps\" means the number\n# of coefficients, which is the same as the length of the impulse\n# response of the filter.\n\n\ndef kaiser_beta(a):\n \"\"\"Compute the Kaiser parameter `beta`, given the attenuation `a`.\n\n Parameters\n ----------\n a : float\n The desired attenuation in the stopband and maximum ripple in\n the passband, in dB. This should be a *positive* number.\n\n Returns\n -------\n beta : float\n The `beta` parameter to be used in the formula for a Kaiser window.\n\n References\n ----------\n Oppenheim, Schafer, \"Discrete-Time Signal Processing\", p.475-476.\n\n Examples\n --------\n Suppose we want to design a lowpass filter, with 65 dB attenuation\n in the stop band. The Kaiser window parameter to be used in the\n window method is computed by ``kaiser_beta(65)``:\n\n >>> from scipy.signal import kaiser_beta\n >>> kaiser_beta(65)\n 6.20426\n\n \"\"\"\n if a > 50:\n beta = 0.1102 * (a - 8.7)\n elif a > 21:\n beta = 0.5842 * (a - 21) ** 0.4 + 0.07886 * (a - 21)\n else:\n beta = 0.0\n return beta\n\n\ndef kaiser_atten(numtaps, width):\n \"\"\"Compute the attenuation of a Kaiser FIR filter.\n\n Given the number of taps `N` and the transition width `width`, compute the\n attenuation `a` in dB, given by Kaiser's formula:\n\n a = 2.285 * (N - 1) * pi * width + 7.95\n\n Parameters\n ----------\n numtaps : int\n The number of taps in the FIR filter.\n width : float\n The desired width of the transition region between passband and\n stopband (or, in general, at any discontinuity) for the filter,\n expressed as a fraction of the Nyquist frequency.\n\n Returns\n -------\n a : float\n The attenuation of the ripple, in dB.\n\n See Also\n --------\n kaiserord, kaiser_beta\n\n Examples\n --------\n Suppose we want to design a FIR filter using the Kaiser window method\n that will have 211 taps and a transition width of 9 Hz for a signal that\n is sampled at 480 Hz. Expressed as a fraction of the Nyquist frequency,\n the width is 9/(0.5*480) = 0.0375. The approximate attenuation (in dB)\n is computed as follows:\n\n >>> from scipy.signal import kaiser_atten\n >>> kaiser_atten(211, 0.0375)\n 64.48099630593983\n\n \"\"\"\n a = 2.285 * (numtaps - 1) * np.pi * width + 7.95\n return a\n\n\ndef kaiserord(ripple, width):\n \"\"\"\n Determine the filter window parameters for the Kaiser window method.\n\n The parameters returned by this function are generally used to create\n a finite impulse response filter using the window method, with either\n `firwin` or `firwin2`.\n\n Parameters\n ----------\n ripple : float\n Upper bound for the deviation (in dB) of the magnitude of the\n filter's frequency response from that of the desired filter (not\n including frequencies in any transition intervals). That is, if w\n is the frequency expressed as a fraction of the Nyquist frequency,\n A(w) is the actual frequency response of the filter and D(w) is the\n desired frequency response, the design requirement is that::\n\n abs(A(w) - D(w))) < 10**(-ripple/20)\n\n for 0 <= w <= 1 and w not in a transition interval.\n width : float\n Width of transition region, normalized so that 1 corresponds to pi\n radians / sample. That is, the frequency is expressed as a fraction\n of the Nyquist frequency.\n\n Returns\n -------\n numtaps : int\n The length of the Kaiser window.\n beta : float\n The beta parameter for the Kaiser window.\n\n See Also\n --------\n kaiser_beta, kaiser_atten\n\n Notes\n -----\n There are several ways to obtain the Kaiser window:\n\n - ``signal.windows.kaiser(numtaps, beta, sym=True)``\n - ``signal.get_window(beta, numtaps)``\n - ``signal.get_window(('kaiser', beta), numtaps)``\n\n The empirical equations discovered by Kaiser are used.\n\n References\n ----------\n Oppenheim, Schafer, \"Discrete-Time Signal Processing\", pp.475-476.\n\n Examples\n --------\n We will use the Kaiser window method to design a lowpass FIR filter\n for a signal that is sampled at 1000 Hz.\n\n We want at least 65 dB rejection in the stop band, and in the pass\n band the gain should vary no more than 0.5%.\n\n We want a cutoff frequency of 175 Hz, with a transition between the\n pass band and the stop band of 24 Hz. That is, in the band [0, 163],\n the gain varies no more than 0.5%, and in the band [187, 500], the\n signal is attenuated by at least 65 dB.\n\n >>> from scipy.signal import kaiserord, firwin, freqz\n >>> import matplotlib.pyplot as plt\n >>> fs = 1000.0\n >>> cutoff = 175\n >>> width = 24\n\n The Kaiser method accepts just a single parameter to control the pass\n band ripple and the stop band rejection, so we use the more restrictive\n of the two. In this case, the pass band ripple is 0.005, or 46.02 dB,\n so we will use 65 dB as the design parameter.\n\n Use `kaiserord` to determine the length of the filter and the\n parameter for the Kaiser window.\n\n >>> numtaps, beta = kaiserord(65, width/(0.5*fs))\n >>> numtaps\n 167\n >>> beta\n 6.20426\n\n Use `firwin` to create the FIR filter.\n\n >>> taps = firwin(numtaps, cutoff, window=('kaiser', beta),\n ... scale=False, nyq=0.5*fs)\n\n Compute the frequency response of the filter. ``w`` is the array of\n frequencies, and ``h`` is the corresponding complex array of frequency\n responses.\n\n >>> w, h = freqz(taps, worN=8000)\n >>> w *= 0.5*fs/np.pi # Convert w to Hz.\n\n Compute the deviation of the magnitude of the filter's response from\n that of the ideal lowpass filter. Values in the transition region are\n set to ``nan``, so they won't appear in the plot.\n\n >>> ideal = w < cutoff # The \"ideal\" frequency response.\n >>> deviation = np.abs(np.abs(h) - ideal)\n >>> deviation[(w > cutoff - 0.5*width) & (w < cutoff + 0.5*width)] = np.nan\n\n Plot the deviation. A close look at the left end of the stop band shows\n that the requirement for 65 dB attenuation is violated in the first lobe\n by about 0.125 dB. This is not unusual for the Kaiser window method.\n\n >>> plt.plot(w, 20*np.log10(np.abs(deviation)))\n >>> plt.xlim(0, 0.5*fs)\n >>> plt.ylim(-90, -60)\n >>> plt.grid(alpha=0.25)\n >>> plt.axhline(-65, color='r', ls='--', alpha=0.3)\n >>> plt.xlabel('Frequency (Hz)')\n >>> plt.ylabel('Deviation from ideal (dB)')\n >>> plt.title('Lowpass Filter Frequency Response')\n >>> plt.show()\n\n \"\"\"\n A = abs(ripple) # in case somebody is confused as to what's meant\n if A < 8:\n # Formula for N is not valid in this range.\n raise ValueError(\"Requested maximum ripple attentuation %f is too \"\n \"small for the Kaiser formula.\" % A)\n beta = kaiser_beta(A)\n\n # Kaiser's formula (as given in Oppenheim and Schafer) is for the filter\n # order, so we have to add 1 to get the number of taps.\n numtaps = (A - 7.95) / 2.285 / (np.pi * width) + 1\n\n return int(ceil(numtaps)), beta\n\n\ndef firwin(numtaps, cutoff, width=None, window='hamming', pass_zero=True,\n scale=True, nyq=None, fs=None):\n \"\"\"\n FIR filter design using the window method.\n\n This function computes the coefficients of a finite impulse response\n filter. The filter will have linear phase; it will be Type I if\n `numtaps` is odd and Type II if `numtaps` is even.\n\n Type II filters always have zero response at the Nyquist frequency, so a\n ValueError exception is raised if firwin is called with `numtaps` even and\n having a passband whose right end is at the Nyquist frequency.\n\n Parameters\n ----------\n numtaps : int\n Length of the filter (number of coefficients, i.e. the filter\n order + 1). `numtaps` must be odd if a passband includes the\n Nyquist frequency.\n cutoff : float or 1-D array_like\n Cutoff frequency of filter (expressed in the same units as `fs`)\n OR an array of cutoff frequencies (that is, band edges). In the\n latter case, the frequencies in `cutoff` should be positive and\n monotonically increasing between 0 and `fs/2`. The values 0 and\n `fs/2` must not be included in `cutoff`.\n width : float or None, optional\n If `width` is not None, then assume it is the approximate width\n of the transition region (expressed in the same units as `fs`)\n for use in Kaiser FIR filter design. In this case, the `window`\n argument is ignored.\n window : string or tuple of string and parameter values, optional\n Desired window to use. See `scipy.signal.get_window` for a list\n of windows and required parameters.\n pass_zero : {True, False, 'bandpass', 'lowpass', 'highpass', 'bandstop'}, optional\n If True, the gain at the frequency 0 (i.e., the \"DC gain\") is 1.\n If False, the DC gain is 0. Can also be a string argument for the\n desired filter type (equivalent to ``btype`` in IIR design functions).\n\n .. versionadded:: 1.3.0\n Support for string arguments.\n scale : bool, optional\n Set to True to scale the coefficients so that the frequency\n response is exactly unity at a certain frequency.\n That frequency is either:\n\n - 0 (DC) if the first passband starts at 0 (i.e. pass_zero\n is True)\n - `fs/2` (the Nyquist frequency) if the first passband ends at\n `fs/2` (i.e the filter is a single band highpass filter);\n center of first passband otherwise\n\n nyq : float, optional\n *Deprecated. Use `fs` instead.* This is the Nyquist frequency.\n Each frequency in `cutoff` must be between 0 and `nyq`. Default\n is 1.\n fs : float, optional\n The sampling frequency of the signal. Each frequency in `cutoff`\n must be between 0 and ``fs/2``. Default is 2.\n\n Returns\n -------\n h : (numtaps,) ndarray\n Coefficients of length `numtaps` FIR filter.\n\n Raises\n ------\n ValueError\n If any value in `cutoff` is less than or equal to 0 or greater\n than or equal to ``fs/2``, if the values in `cutoff` are not strictly\n monotonically increasing, or if `numtaps` is even but a passband\n includes the Nyquist frequency.\n\n See Also\n --------\n firwin2\n firls\n minimum_phase\n remez\n\n Examples\n --------\n Low-pass from 0 to f:\n\n >>> from scipy import signal\n >>> numtaps = 3\n >>> f = 0.1\n >>> signal.firwin(numtaps, f)\n array([ 0.06799017, 0.86401967, 0.06799017])\n\n Use a specific window function:\n\n >>> signal.firwin(numtaps, f, window='nuttall')\n array([ 3.56607041e-04, 9.99286786e-01, 3.56607041e-04])\n\n High-pass ('stop' from 0 to f):\n\n >>> signal.firwin(numtaps, f, pass_zero=False)\n array([-0.00859313, 0.98281375, -0.00859313])\n\n Band-pass:\n\n >>> f1, f2 = 0.1, 0.2\n >>> signal.firwin(numtaps, [f1, f2], pass_zero=False)\n array([ 0.06301614, 0.88770441, 0.06301614])\n\n Band-stop:\n\n >>> signal.firwin(numtaps, [f1, f2])\n array([-0.00801395, 1.0160279 , -0.00801395])\n\n Multi-band (passbands are [0, f1], [f2, f3] and [f4, 1]):\n\n >>> f3, f4 = 0.3, 0.4\n >>> signal.firwin(numtaps, [f1, f2, f3, f4])\n array([-0.01376344, 1.02752689, -0.01376344])\n\n Multi-band (passbands are [f1, f2] and [f3,f4]):\n\n >>> signal.firwin(numtaps, [f1, f2, f3, f4], pass_zero=False)\n array([ 0.04890915, 0.91284326, 0.04890915])\n\n \"\"\" # noqa: E501\n # The major enhancements to this function added in November 2010 were\n # developed by Tom Krauss (see ticket #902).\n\n nyq = 0.5 * _get_fs(fs, nyq)\n\n cutoff = np.atleast_1d(cutoff) / float(nyq)\n\n # Check for invalid input.\n if cutoff.ndim > 1:\n raise ValueError(\"The cutoff argument must be at most \"\n \"one-dimensional.\")\n if cutoff.size == 0:\n raise ValueError(\"At least one cutoff frequency must be given.\")\n if cutoff.min() <= 0 or cutoff.max() >= 1:\n raise ValueError(\"Invalid cutoff frequency: frequencies must be \"\n \"greater than 0 and less than fs/2.\")\n if np.any(np.diff(cutoff) <= 0):\n raise ValueError(\"Invalid cutoff frequencies: the frequencies \"\n \"must be strictly increasing.\")\n\n if width is not None:\n # A width was given. Find the beta parameter of the Kaiser window\n # and set `window`. This overrides the value of `window` passed in.\n atten = kaiser_atten(numtaps, float(width) / nyq)\n beta = kaiser_beta(atten)\n window = ('kaiser', beta)\n\n if isinstance(pass_zero, str):\n if pass_zero in ('bandstop', 'lowpass'):\n if pass_zero == 'lowpass':\n if cutoff.size != 1:\n raise ValueError('cutoff must have one element if '\n 'pass_zero==\"lowpass\", got %s'\n % (cutoff.shape,))\n elif cutoff.size <= 1:\n raise ValueError('cutoff must have at least two elements if '\n 'pass_zero==\"bandstop\", got %s'\n % (cutoff.shape,))\n pass_zero = True\n elif pass_zero in ('bandpass', 'highpass'):\n if pass_zero == 'highpass':\n if cutoff.size != 1:\n raise ValueError('cutoff must have one element if '\n 'pass_zero==\"highpass\", got %s'\n % (cutoff.shape,))\n elif cutoff.size <= 1:\n raise ValueError('cutoff must have at least two elements if '\n 'pass_zero==\"bandpass\", got %s'\n % (cutoff.shape,))\n pass_zero = False\n else:\n raise ValueError('pass_zero must be True, False, \"bandpass\", '\n '\"lowpass\", \"highpass\", or \"bandstop\", got '\n '%s' % (pass_zero,))\n pass_zero = bool(operator.index(pass_zero)) # ensure bool-like\n\n pass_nyquist = bool(cutoff.size & 1) ^ pass_zero\n if pass_nyquist and numtaps % 2 == 0:\n raise ValueError(\"A filter with an even number of coefficients must \"\n \"have zero response at the Nyquist frequency.\")\n\n # Insert 0 and/or 1 at the ends of cutoff so that the length of cutoff\n # is even, and each pair in cutoff corresponds to passband.\n cutoff = np.hstack(([0.0] * pass_zero, cutoff, [1.0] * pass_nyquist))\n\n # `bands` is a 2-D array; each row gives the left and right edges of\n # a passband.\n bands = cutoff.reshape(-1, 2)\n\n # Build up the coefficients.\n alpha = 0.5 * (numtaps - 1)\n m = np.arange(0, numtaps) - alpha\n h = 0\n for left, right in bands:\n h += right * sinc(right * m)\n h -= left * sinc(left * m)\n\n # Get and apply the window function.\n from .windows import get_window\n win = get_window(window, numtaps, fftbins=False)\n h *= win\n\n # Now handle scaling if desired.\n if scale:\n # Get the first passband.\n left, right = bands[0]\n if left == 0:\n scale_frequency = 0.0\n elif right == 1:\n scale_frequency = 1.0\n else:\n scale_frequency = 0.5 * (left + right)\n c = np.cos(np.pi * m * scale_frequency)\n s = np.sum(h * c)\n h /= s\n\n return h\n\n\n# Original version of firwin2 from scipy ticket #457, submitted by \"tash\".\n#\n# Rewritten by Warren Weckesser, 2010.\n\ndef firwin2(numtaps, freq, gain, nfreqs=None, window='hamming', nyq=None,\n antisymmetric=False, fs=None):\n \"\"\"\n FIR filter design using the window method.\n\n From the given frequencies `freq` and corresponding gains `gain`,\n this function constructs an FIR filter with linear phase and\n (approximately) the given frequency response.\n\n Parameters\n ----------\n numtaps : int\n The number of taps in the FIR filter. `numtaps` must be less than\n `nfreqs`.\n freq : array_like, 1-D\n The frequency sampling points. Typically 0.0 to 1.0 with 1.0 being\n Nyquist. The Nyquist frequency is half `fs`.\n The values in `freq` must be nondecreasing. A value can be repeated\n once to implement a discontinuity. The first value in `freq` must\n be 0, and the last value must be ``fs/2``. Values 0 and ``fs/2`` must\n not be repeated.\n gain : array_like\n The filter gains at the frequency sampling points. Certain\n constraints to gain values, depending on the filter type, are applied,\n see Notes for details.\n nfreqs : int, optional\n The size of the interpolation mesh used to construct the filter.\n For most efficient behavior, this should be a power of 2 plus 1\n (e.g, 129, 257, etc). The default is one more than the smallest\n power of 2 that is not less than `numtaps`. `nfreqs` must be greater\n than `numtaps`.\n window : string or (string, float) or float, or None, optional\n Window function to use. Default is \"hamming\". See\n `scipy.signal.get_window` for the complete list of possible values.\n If None, no window function is applied.\n nyq : float, optional\n *Deprecated. Use `fs` instead.* This is the Nyquist frequency.\n Each frequency in `freq` must be between 0 and `nyq`. Default is 1.\n antisymmetric : bool, optional\n Whether resulting impulse response is symmetric/antisymmetric.\n See Notes for more details.\n fs : float, optional\n The sampling frequency of the signal. Each frequency in `cutoff`\n must be between 0 and ``fs/2``. Default is 2.\n\n Returns\n -------\n taps : ndarray\n The filter coefficients of the FIR filter, as a 1-D array of length\n `numtaps`.\n\n See also\n --------\n firls\n firwin\n minimum_phase\n remez\n\n Notes\n -----\n From the given set of frequencies and gains, the desired response is\n constructed in the frequency domain. The inverse FFT is applied to the\n desired response to create the associated convolution kernel, and the\n first `numtaps` coefficients of this kernel, scaled by `window`, are\n returned.\n\n The FIR filter will have linear phase. The type of filter is determined by\n the value of 'numtaps` and `antisymmetric` flag.\n There are four possible combinations:\n\n - odd `numtaps`, `antisymmetric` is False, type I filter is produced\n - even `numtaps`, `antisymmetric` is False, type II filter is produced\n - odd `numtaps`, `antisymmetric` is True, type III filter is produced\n - even `numtaps`, `antisymmetric` is True, type IV filter is produced\n\n Magnitude response of all but type I filters are subjects to following\n constraints:\n\n - type II -- zero at the Nyquist frequency\n - type III -- zero at zero and Nyquist frequencies\n - type IV -- zero at zero frequency\n\n .. versionadded:: 0.9.0\n\n References\n ----------\n .. [1] Oppenheim, A. V. and Schafer, R. W., \"Discrete-Time Signal\n Processing\", Prentice-Hall, Englewood Cliffs, New Jersey (1989).\n (See, for example, Section 7.4.)\n\n .. [2] Smith, Steven W., \"The Scientist and Engineer's Guide to Digital\n Signal Processing\", Ch. 17. http://www.dspguide.com/ch17/1.htm\n\n Examples\n --------\n A lowpass FIR filter with a response that is 1 on [0.0, 0.5], and\n that decreases linearly on [0.5, 1.0] from 1 to 0:\n\n >>> from scipy import signal\n >>> taps = signal.firwin2(150, [0.0, 0.5, 1.0], [1.0, 1.0, 0.0])\n >>> print(taps[72:78])\n [-0.02286961 -0.06362756 0.57310236 0.57310236 -0.06362756 -0.02286961]\n\n \"\"\"\n nyq = 0.5 * _get_fs(fs, nyq)\n\n if len(freq) != len(gain):\n raise ValueError('freq and gain must be of same length.')\n\n if nfreqs is not None and numtaps >= nfreqs:\n raise ValueError(('ntaps must be less than nfreqs, but firwin2 was '\n 'called with ntaps=%d and nfreqs=%s') %\n (numtaps, nfreqs))\n\n if freq[0] != 0 or freq[-1] != nyq:\n raise ValueError('freq must start with 0 and end with fs/2.')\n d = np.diff(freq)\n if (d < 0).any():\n raise ValueError('The values in freq must be nondecreasing.')\n d2 = d[:-1] + d[1:]\n if (d2 == 0).any():\n raise ValueError('A value in freq must not occur more than twice.')\n if freq[1] == 0:\n raise ValueError('Value 0 must not be repeated in freq')\n if freq[-2] == nyq:\n raise ValueError('Value fs/2 must not be repeated in freq')\n\n if antisymmetric:\n if numtaps % 2 == 0:\n ftype = 4\n else:\n ftype = 3\n else:\n if numtaps % 2 == 0:\n ftype = 2\n else:\n ftype = 1\n\n if ftype == 2 and gain[-1] != 0.0:\n raise ValueError(\"A Type II filter must have zero gain at the \"\n \"Nyquist frequency.\")\n elif ftype == 3 and (gain[0] != 0.0 or gain[-1] != 0.0):\n raise ValueError(\"A Type III filter must have zero gain at zero \"\n \"and Nyquist frequencies.\")\n elif ftype == 4 and gain[0] != 0.0:\n raise ValueError(\"A Type IV filter must have zero gain at zero \"\n \"frequency.\")\n\n if nfreqs is None:\n nfreqs = 1 + 2 ** int(ceil(log(numtaps, 2)))\n\n if (d == 0).any():\n # Tweak any repeated values in freq so that interp works.\n freq = np.array(freq, copy=True)\n eps = np.finfo(float).eps * nyq\n for k in range(len(freq) - 1):\n if freq[k] == freq[k + 1]:\n freq[k] = freq[k] - eps\n freq[k + 1] = freq[k + 1] + eps\n # Check if freq is strictly increasing after tweak\n d = np.diff(freq)\n if (d <= 0).any():\n raise ValueError(\"freq cannot contain numbers that are too close \"\n \"(within eps * (fs/2): \"\n \"{}) to a repeated value\".format(eps))\n\n # Linearly interpolate the desired response on a uniform mesh `x`.\n x = np.linspace(0.0, nyq, nfreqs)\n fx = np.interp(x, freq, gain)\n\n # Adjust the phases of the coefficients so that the first `ntaps` of the\n # inverse FFT are the desired filter coefficients.\n shift = np.exp(-(numtaps - 1) / 2. * 1.j * np.pi * x / nyq)\n if ftype > 2:\n shift *= 1j\n\n fx2 = fx * shift\n\n # Use irfft to compute the inverse FFT.\n out_full = irfft(fx2)\n\n if window is not None:\n # Create the window to apply to the filter coefficients.\n from .windows import get_window\n wind = get_window(window, numtaps, fftbins=False)\n else:\n wind = 1\n\n # Keep only the first `numtaps` coefficients in `out`, and multiply by\n # the window.\n out = out_full[:numtaps] * wind\n\n if ftype == 3:\n out[out.size // 2] = 0.0\n\n return out\n\n\ndef remez(numtaps, bands, desired, weight=None, Hz=None, type='bandpass',\n maxiter=25, grid_density=16, fs=None):\n \"\"\"\n Calculate the minimax optimal filter using the Remez exchange algorithm.\n\n Calculate the filter-coefficients for the finite impulse response\n (FIR) filter whose transfer function minimizes the maximum error\n between the desired gain and the realized gain in the specified\n frequency bands using the Remez exchange algorithm.\n\n Parameters\n ----------\n numtaps : int\n The desired number of taps in the filter. The number of taps is\n the number of terms in the filter, or the filter order plus one.\n bands : array_like\n A monotonic sequence containing the band edges.\n All elements must be non-negative and less than half the sampling\n frequency as given by `fs`.\n desired : array_like\n A sequence half the size of bands containing the desired gain\n in each of the specified bands.\n weight : array_like, optional\n A relative weighting to give to each band region. The length of\n `weight` has to be half the length of `bands`.\n Hz : scalar, optional\n *Deprecated. Use `fs` instead.*\n The sampling frequency in Hz. Default is 1.\n type : {'bandpass', 'differentiator', 'hilbert'}, optional\n The type of filter:\n\n * 'bandpass' : flat response in bands. This is the default.\n\n * 'differentiator' : frequency proportional response in bands.\n\n * 'hilbert' : filter with odd symmetry, that is, type III\n (for even order) or type IV (for odd order)\n linear phase filters.\n\n maxiter : int, optional\n Maximum number of iterations of the algorithm. Default is 25.\n grid_density : int, optional\n Grid density. The dense grid used in `remez` is of size\n ``(numtaps + 1) * grid_density``. Default is 16.\n fs : float, optional\n The sampling frequency of the signal. Default is 1.\n\n Returns\n -------\n out : ndarray\n A rank-1 array containing the coefficients of the optimal\n (in a minimax sense) filter.\n\n See Also\n --------\n firls\n firwin\n firwin2\n minimum_phase\n\n References\n ----------\n .. [1] J. H. McClellan and T. W. Parks, \"A unified approach to the\n design of optimum FIR linear phase digital filters\",\n IEEE Trans. Circuit Theory, vol. CT-20, pp. 697-701, 1973.\n .. [2] J. H. McClellan, T. W. Parks and L. R. Rabiner, \"A Computer\n Program for Designing Optimum FIR Linear Phase Digital\n Filters\", IEEE Trans. Audio Electroacoust., vol. AU-21,\n pp. 506-525, 1973.\n\n Examples\n --------\n In these examples `remez` gets used creating a bandpass, bandstop, lowpass\n and highpass filter. The used parameters are the filter order, an array\n with according frequency boundaries, the desired attenuation values and the\n sampling frequency. Using `freqz` the corresponding frequency response\n gets calculated and plotted.\n\n >>> from scipy import signal\n >>> import matplotlib.pyplot as plt\n\n >>> def plot_response(fs, w, h, title):\n ... \"Utility function to plot response functions\"\n ... fig = plt.figure()\n ... ax = fig.add_subplot(111)\n ... ax.plot(0.5*fs*w/np.pi, 20*np.log10(np.abs(h)))\n ... ax.set_ylim(-40, 5)\n ... ax.set_xlim(0, 0.5*fs)\n ... ax.grid(True)\n ... ax.set_xlabel('Frequency (Hz)')\n ... ax.set_ylabel('Gain (dB)')\n ... ax.set_title(title)\n\n This example shows a steep low pass transition according to the small\n transition width and high filter order:\n\n >>> fs = 22050.0 # Sample rate, Hz\n >>> cutoff = 8000.0 # Desired cutoff frequency, Hz\n >>> trans_width = 100 # Width of transition from pass band to stop band, Hz\n >>> numtaps = 400 # Size of the FIR filter.\n >>> taps = signal.remez(numtaps, [0, cutoff, cutoff + trans_width, 0.5*fs], [1, 0], Hz=fs)\n >>> w, h = signal.freqz(taps, [1], worN=2000)\n >>> plot_response(fs, w, h, \"Low-pass Filter\")\n\n This example shows a high pass filter:\n\n >>> fs = 22050.0 # Sample rate, Hz\n >>> cutoff = 2000.0 # Desired cutoff frequency, Hz\n >>> trans_width = 250 # Width of transition from pass band to stop band, Hz\n >>> numtaps = 125 # Size of the FIR filter.\n >>> taps = signal.remez(numtaps, [0, cutoff - trans_width, cutoff, 0.5*fs],\n ... [0, 1], Hz=fs)\n >>> w, h = signal.freqz(taps, [1], worN=2000)\n >>> plot_response(fs, w, h, \"High-pass Filter\")\n\n For a signal sampled with 22 kHz a bandpass filter with a pass band of 2-5\n kHz gets calculated using the Remez algorithm. The transition width is 260\n Hz and the filter order 10:\n\n >>> fs = 22000.0 # Sample rate, Hz\n >>> band = [2000, 5000] # Desired pass band, Hz\n >>> trans_width = 260 # Width of transition from pass band to stop band, Hz\n >>> numtaps = 10 # Size of the FIR filter.\n >>> edges = [0, band[0] - trans_width, band[0], band[1],\n ... band[1] + trans_width, 0.5*fs]\n >>> taps = signal.remez(numtaps, edges, [0, 1, 0], Hz=fs)\n >>> w, h = signal.freqz(taps, [1], worN=2000)\n >>> plot_response(fs, w, h, \"Band-pass Filter\")\n\n It can be seen that for this bandpass filter, the low order leads to higher\n ripple and less steep transitions. There is very low attenuation in the\n stop band and little overshoot in the pass band. Of course the desired\n gain can be better approximated with a higher filter order.\n\n The next example shows a bandstop filter. Because of the high filter order\n the transition is quite steep:\n\n >>> fs = 20000.0 # Sample rate, Hz\n >>> band = [6000, 8000] # Desired stop band, Hz\n >>> trans_width = 200 # Width of transition from pass band to stop band, Hz\n >>> numtaps = 175 # Size of the FIR filter.\n >>> edges = [0, band[0] - trans_width, band[0], band[1], band[1] + trans_width, 0.5*fs]\n >>> taps = signal.remez(numtaps, edges, [1, 0, 1], Hz=fs)\n >>> w, h = signal.freqz(taps, [1], worN=2000)\n >>> plot_response(fs, w, h, \"Band-stop Filter\")\n\n >>> plt.show()\n\n \"\"\"\n if Hz is None and fs is None:\n fs = 1.0\n elif Hz is not None:\n if fs is not None:\n raise ValueError(\"Values cannot be given for both 'Hz' and 'fs'.\")\n fs = Hz\n\n # Convert type\n try:\n tnum = {'bandpass': 1, 'differentiator': 2, 'hilbert': 3}[type]\n except KeyError as e:\n raise ValueError(\"Type must be 'bandpass', 'differentiator', \"\n \"or 'hilbert'\") from e\n\n # Convert weight\n if weight is None:\n weight = [1] * len(desired)\n\n bands = np.asarray(bands).copy()\n return _sigtools._remez(numtaps, bands, desired, weight, tnum, fs,\n maxiter, grid_density)\n\n\ndef firls(numtaps, bands, desired, weight=None, nyq=None, fs=None):\n \"\"\"\n FIR filter design using least-squares error minimization.\n\n Calculate the filter coefficients for the linear-phase finite\n impulse response (FIR) filter which has the best approximation\n to the desired frequency response described by `bands` and\n `desired` in the least squares sense (i.e., the integral of the\n weighted mean-squared error within the specified bands is\n minimized).\n\n Parameters\n ----------\n numtaps : int\n The number of taps in the FIR filter. `numtaps` must be odd.\n bands : array_like\n A monotonic nondecreasing sequence containing the band edges in\n Hz. All elements must be non-negative and less than or equal to\n the Nyquist frequency given by `nyq`.\n desired : array_like\n A sequence the same size as `bands` containing the desired gain\n at the start and end point of each band.\n weight : array_like, optional\n A relative weighting to give to each band region when solving\n the least squares problem. `weight` has to be half the size of\n `bands`.\n nyq : float, optional\n *Deprecated. Use `fs` instead.*\n Nyquist frequency. Each frequency in `bands` must be between 0\n and `nyq` (inclusive). Default is 1.\n fs : float, optional\n The sampling frequency of the signal. Each frequency in `bands`\n must be between 0 and ``fs/2`` (inclusive). Default is 2.\n\n Returns\n -------\n coeffs : ndarray\n Coefficients of the optimal (in a least squares sense) FIR filter.\n\n See also\n --------\n firwin\n firwin2\n minimum_phase\n remez\n\n Notes\n -----\n This implementation follows the algorithm given in [1]_.\n As noted there, least squares design has multiple advantages:\n\n 1. Optimal in a least-squares sense.\n 2. Simple, non-iterative method.\n 3. The general solution can obtained by solving a linear\n system of equations.\n 4. Allows the use of a frequency dependent weighting function.\n\n This function constructs a Type I linear phase FIR filter, which\n contains an odd number of `coeffs` satisfying for :math:`n < numtaps`:\n\n .. math:: coeffs(n) = coeffs(numtaps - 1 - n)\n\n The odd number of coefficients and filter symmetry avoid boundary\n conditions that could otherwise occur at the Nyquist and 0 frequencies\n (e.g., for Type II, III, or IV variants).\n\n .. versionadded:: 0.18\n\n References\n ----------\n .. [1] Ivan Selesnick, Linear-Phase Fir Filter Design By Least Squares.\n OpenStax CNX. Aug 9, 2005.\n http://cnx.org/contents/eb1ecb35-03a9-4610-ba87-41cd771c95f2@7\n\n Examples\n --------\n We want to construct a band-pass filter. Note that the behavior in the\n frequency ranges between our stop bands and pass bands is unspecified,\n and thus may overshoot depending on the parameters of our filter:\n\n >>> from scipy import signal\n >>> import matplotlib.pyplot as plt\n >>> fig, axs = plt.subplots(2)\n >>> fs = 10.0 # Hz\n >>> desired = (0, 0, 1, 1, 0, 0)\n >>> for bi, bands in enumerate(((0, 1, 2, 3, 4, 5), (0, 1, 2, 4, 4.5, 5))):\n ... fir_firls = signal.firls(73, bands, desired, fs=fs)\n ... fir_remez = signal.remez(73, bands, desired[::2], fs=fs)\n ... fir_firwin2 = signal.firwin2(73, bands, desired, fs=fs)\n ... hs = list()\n ... ax = axs[bi]\n ... for fir in (fir_firls, fir_remez, fir_firwin2):\n ... freq, response = signal.freqz(fir)\n ... hs.append(ax.semilogy(0.5*fs*freq/np.pi, np.abs(response))[0])\n ... for band, gains in zip(zip(bands[::2], bands[1::2]),\n ... zip(desired[::2], desired[1::2])):\n ... ax.semilogy(band, np.maximum(gains, 1e-7), 'k--', linewidth=2)\n ... if bi == 0:\n ... ax.legend(hs, ('firls', 'remez', 'firwin2'),\n ... loc='lower center', frameon=False)\n ... else:\n ... ax.set_xlabel('Frequency (Hz)')\n ... ax.grid(True)\n ... ax.set(title='Band-pass %d-%d Hz' % bands[2:4], ylabel='Magnitude')\n ...\n >>> fig.tight_layout()\n >>> plt.show()\n\n \"\"\" # noqa\n nyq = 0.5 * _get_fs(fs, nyq)\n\n numtaps = int(numtaps)\n if numtaps % 2 == 0 or numtaps < 1:\n raise ValueError(\"numtaps must be odd and >= 1\")\n M = (numtaps-1) // 2\n\n # normalize bands 0->1 and make it 2 columns\n nyq = float(nyq)\n if nyq <= 0:\n raise ValueError('nyq must be positive, got %s <= 0.' % nyq)\n bands = np.asarray(bands).flatten() / nyq\n if len(bands) % 2 != 0:\n raise ValueError(\"bands must contain frequency pairs.\")\n if (bands < 0).any() or (bands > 1).any():\n raise ValueError(\"bands must be between 0 and 1 relative to Nyquist\")\n bands.shape = (-1, 2)\n\n # check remaining params\n desired = np.asarray(desired).flatten()\n if bands.size != desired.size:\n raise ValueError(\"desired must have one entry per frequency, got %s \"\n \"gains for %s frequencies.\"\n % (desired.size, bands.size))\n desired.shape = (-1, 2)\n if (np.diff(bands) <= 0).any() or (np.diff(bands[:, 0]) < 0).any():\n raise ValueError(\"bands must be monotonically nondecreasing and have \"\n \"width > 0.\")\n if (bands[:-1, 1] > bands[1:, 0]).any():\n raise ValueError(\"bands must not overlap.\")\n if (desired < 0).any():\n raise ValueError(\"desired must be non-negative.\")\n if weight is None:\n weight = np.ones(len(desired))\n weight = np.asarray(weight).flatten()\n if len(weight) != len(desired):\n raise ValueError(\"weight must be the same size as the number of \"\n \"band pairs (%s).\" % (len(bands),))\n if (weight < 0).any():\n raise ValueError(\"weight must be non-negative.\")\n\n # Set up the linear matrix equation to be solved, Qa = b\n\n # We can express Q(k,n) = 0.5 Q1(k,n) + 0.5 Q2(k,n)\n # where Q1(k,n)=q(k-n) and Q2(k,n)=q(k+n), i.e. a Toeplitz plus Hankel.\n\n # We omit the factor of 0.5 above, instead adding it during coefficient\n # calculation.\n\n # We also omit the 1/π from both Q and b equations, as they cancel\n # during solving.\n\n # We have that:\n # q(n) = 1/π ∫W(ω)cos(nω)dω (over 0->π)\n # Using our nomalization ω=πf and with a constant weight W over each\n # interval f1->f2 we get:\n # q(n) = W∫cos(πnf)df (0->1) = Wf sin(πnf)/πnf\n # integrated over each f1->f2 pair (i.e., value at f2 - value at f1).\n n = np.arange(numtaps)[:, np.newaxis, np.newaxis]\n q = np.dot(np.diff(np.sinc(bands * n) * bands, axis=2)[:, :, 0], weight)\n\n # Now we assemble our sum of Toeplitz and Hankel\n Q1 = toeplitz(q[:M+1])\n Q2 = hankel(q[:M+1], q[M:])\n Q = Q1 + Q2\n\n # Now for b(n) we have that:\n # b(n) = 1/π ∫ W(ω)D(ω)cos(nω)dω (over 0->π)\n # Using our normalization ω=πf and with a constant weight W over each\n # interval and a linear term for D(ω) we get (over each f1->f2 interval):\n # b(n) = W ∫ (mf+c)cos(πnf)df\n # = f(mf+c)sin(πnf)/πnf + mf**2 cos(nπf)/(πnf)**2\n # integrated over each f1->f2 pair (i.e., value at f2 - value at f1).\n n = n[:M + 1] # only need this many coefficients here\n # Choose m and c such that we are at the start and end weights\n m = (np.diff(desired, axis=1) / np.diff(bands, axis=1))\n c = desired[:, [0]] - bands[:, [0]] * m\n b = bands * (m*bands + c) * np.sinc(bands * n)\n # Use L'Hospital's rule here for cos(nπf)/(πnf)**2 @ n=0\n b[0] -= m * bands * bands / 2.\n b[1:] += m * np.cos(n[1:] * np.pi * bands) / (np.pi * n[1:]) ** 2\n b = np.dot(np.diff(b, axis=2)[:, :, 0], weight)\n\n # Now we can solve the equation\n try: # try the fast way\n with warnings.catch_warnings(record=True) as w:\n warnings.simplefilter('always')\n a = solve(Q, b, sym_pos=True, check_finite=False)\n for ww in w:\n if (ww.category == LinAlgWarning and\n str(ww.message).startswith('Ill-conditioned matrix')):\n raise LinAlgError(str(ww.message))\n except LinAlgError: # in case Q is rank deficient\n # This is faster than pinvh, even though we don't explicitly use\n # the symmetry here. gelsy was faster than gelsd and gelss in\n # some non-exhaustive tests.\n a = lstsq(Q, b, lapack_driver='gelsy')[0]\n\n # make coefficients symmetric (linear phase)\n coeffs = np.hstack((a[:0:-1], 2 * a[0], a[1:]))\n return coeffs\n\n\ndef _dhtm(mag):\n \"\"\"Compute the modified 1-D discrete Hilbert transform\n\n Parameters\n ----------\n mag : ndarray\n The magnitude spectrum. Should be 1-D with an even length, and\n preferably a fast length for FFT/IFFT.\n \"\"\"\n # Adapted based on code by Niranjan Damera-Venkata,\n # Brian L. Evans and Shawn R. McCaslin (see refs for `minimum_phase`)\n sig = np.zeros(len(mag))\n # Leave Nyquist and DC at 0, knowing np.abs(fftfreq(N)[midpt]) == 0.5\n midpt = len(mag) // 2\n sig[1:midpt] = 1\n sig[midpt+1:] = -1\n # eventually if we want to support complex filters, we will need a\n # np.abs() on the mag inside the log, and should remove the .real\n recon = ifft(mag * np.exp(fft(sig * ifft(np.log(mag))))).real\n return recon\n\n\ndef minimum_phase(h, method='homomorphic', n_fft=None):\n \"\"\"Convert a linear-phase FIR filter to minimum phase\n\n Parameters\n ----------\n h : array\n Linear-phase FIR filter coefficients.\n method : {'hilbert', 'homomorphic'}\n The method to use:\n\n 'homomorphic' (default)\n This method [4]_ [5]_ works best with filters with an\n odd number of taps, and the resulting minimum phase filter\n will have a magnitude response that approximates the square\n root of the the original filter's magnitude response.\n\n 'hilbert'\n This method [1]_ is designed to be used with equiripple\n filters (e.g., from `remez`) with unity or zero gain\n regions.\n\n n_fft : int\n The number of points to use for the FFT. Should be at least a\n few times larger than the signal length (see Notes).\n\n Returns\n -------\n h_minimum : array\n The minimum-phase version of the filter, with length\n ``(length(h) + 1) // 2``.\n\n See Also\n --------\n firwin\n firwin2\n remez\n\n Notes\n -----\n Both the Hilbert [1]_ or homomorphic [4]_ [5]_ methods require selection\n of an FFT length to estimate the complex cepstrum of the filter.\n\n In the case of the Hilbert method, the deviation from the ideal\n spectrum ``epsilon`` is related to the number of stopband zeros\n ``n_stop`` and FFT length ``n_fft`` as::\n\n epsilon = 2. * n_stop / n_fft\n\n For example, with 100 stopband zeros and a FFT length of 2048,\n ``epsilon = 0.0976``. If we conservatively assume that the number of\n stopband zeros is one less than the filter length, we can take the FFT\n length to be the next power of 2 that satisfies ``epsilon=0.01`` as::\n\n n_fft = 2 ** int(np.ceil(np.log2(2 * (len(h) - 1) / 0.01)))\n\n This gives reasonable results for both the Hilbert and homomorphic\n methods, and gives the value used when ``n_fft=None``.\n\n Alternative implementations exist for creating minimum-phase filters,\n including zero inversion [2]_ and spectral factorization [3]_ [4]_.\n For more information, see:\n\n http://dspguru.com/dsp/howtos/how-to-design-minimum-phase-fir-filters\n\n Examples\n --------\n Create an optimal linear-phase filter, then convert it to minimum phase:\n\n >>> from scipy.signal import remez, minimum_phase, freqz, group_delay\n >>> import matplotlib.pyplot as plt\n >>> freq = [0, 0.2, 0.3, 1.0]\n >>> desired = [1, 0]\n >>> h_linear = remez(151, freq, desired, Hz=2.)\n\n Convert it to minimum phase:\n\n >>> h_min_hom = minimum_phase(h_linear, method='homomorphic')\n >>> h_min_hil = minimum_phase(h_linear, method='hilbert')\n\n Compare the three filters:\n\n >>> fig, axs = plt.subplots(4, figsize=(4, 8))\n >>> for h, style, color in zip((h_linear, h_min_hom, h_min_hil),\n ... ('-', '-', '--'), ('k', 'r', 'c')):\n ... w, H = freqz(h)\n ... w, gd = group_delay((h, 1))\n ... w /= np.pi\n ... axs[0].plot(h, color=color, linestyle=style)\n ... axs[1].plot(w, np.abs(H), color=color, linestyle=style)\n ... axs[2].plot(w, 20 * np.log10(np.abs(H)), color=color, linestyle=style)\n ... axs[3].plot(w, gd, color=color, linestyle=style)\n >>> for ax in axs:\n ... ax.grid(True, color='0.5')\n ... ax.fill_between(freq[1:3], *ax.get_ylim(), color='#ffeeaa', zorder=1)\n >>> axs[0].set(xlim=[0, len(h_linear) - 1], ylabel='Amplitude', xlabel='Samples')\n >>> axs[1].legend(['Linear', 'Min-Hom', 'Min-Hil'], title='Phase')\n >>> for ax, ylim in zip(axs[1:], ([0, 1.1], [-150, 10], [-60, 60])):\n ... ax.set(xlim=[0, 1], ylim=ylim, xlabel='Frequency')\n >>> axs[1].set(ylabel='Magnitude')\n >>> axs[2].set(ylabel='Magnitude (dB)')\n >>> axs[3].set(ylabel='Group delay')\n >>> plt.tight_layout()\n\n References\n ----------\n .. [1] N. Damera-Venkata and B. L. Evans, \"Optimal design of real and\n complex minimum phase digital FIR filters,\" Acoustics, Speech,\n and Signal Processing, 1999. Proceedings., 1999 IEEE International\n Conference on, Phoenix, AZ, 1999, pp. 1145-1148 vol.3.\n :doi:`10.1109/ICASSP.1999.756179`\n .. [2] X. Chen and T. W. Parks, \"Design of optimal minimum phase FIR\n filters by direct factorization,\" Signal Processing,\n vol. 10, no. 4, pp. 369-383, Jun. 1986.\n .. [3] T. Saramaki, \"Finite Impulse Response Filter Design,\" in\n Handbook for Digital Signal Processing, chapter 4,\n New York: Wiley-Interscience, 1993.\n .. [4] J. S. Lim, Advanced Topics in Signal Processing.\n Englewood Cliffs, N.J.: Prentice Hall, 1988.\n .. [5] A. V. Oppenheim, R. W. Schafer, and J. R. Buck,\n \"Discrete-Time Signal Processing,\" 2nd edition.\n Upper Saddle River, N.J.: Prentice Hall, 1999.\n \"\"\" # noqa\n h = np.asarray(h)\n if np.iscomplexobj(h):\n raise ValueError('Complex filters not supported')\n if h.ndim != 1 or h.size <= 2:\n raise ValueError('h must be 1-D and at least 2 samples long')\n n_half = len(h) // 2\n if not np.allclose(h[-n_half:][::-1], h[:n_half]):\n warnings.warn('h does not appear to by symmetric, conversion may '\n 'fail', RuntimeWarning)\n if not isinstance(method, str) or method not in \\\n ('homomorphic', 'hilbert',):\n raise ValueError('method must be \"homomorphic\" or \"hilbert\", got %r'\n % (method,))\n if n_fft is None:\n n_fft = 2 ** int(np.ceil(np.log2(2 * (len(h) - 1) / 0.01)))\n n_fft = int(n_fft)\n if n_fft < len(h):\n raise ValueError('n_fft must be at least len(h)==%s' % len(h))\n if method == 'hilbert':\n w = np.arange(n_fft) * (2 * np.pi / n_fft * n_half)\n H = np.real(fft(h, n_fft) * np.exp(1j * w))\n dp = max(H) - 1\n ds = 0 - min(H)\n S = 4. / (np.sqrt(1+dp+ds) + np.sqrt(1-dp+ds)) ** 2\n H += ds\n H *= S\n H = np.sqrt(H, out=H)\n H += 1e-10 # ensure that the log does not explode\n h_minimum = _dhtm(H)\n else: # method == 'homomorphic'\n # zero-pad; calculate the DFT\n h_temp = np.abs(fft(h, n_fft))\n # take 0.25*log(|H|**2) = 0.5*log(|H|)\n h_temp += 1e-7 * h_temp[h_temp > 0].min() # don't let log blow up\n np.log(h_temp, out=h_temp)\n h_temp *= 0.5\n # IDFT\n h_temp = ifft(h_temp).real\n # multiply pointwise by the homomorphic filter\n # lmin[n] = 2u[n] - d[n]\n win = np.zeros(n_fft)\n win[0] = 1\n stop = (len(h) + 1) // 2\n win[1:stop] = 2\n if len(h) % 2:\n win[stop] = 1\n h_temp *= win\n h_temp = ifft(np.exp(fft(h_temp)))\n h_minimum = h_temp.real\n n_out = n_half + len(h) % 2\n return h_minimum[:n_out]\n" ]
[ [ "numpy.sqrt", "scipy.special.ive", "numpy.asarray", "numpy.cumsum", "numpy.all", "numpy.max", "scipy._lib.doccer.docformat", "numpy.any", "numpy.exp", "numpy.place", "scipy.misc.derivative", "numpy.nextafter", "scipy.special.entr", "scipy.special.chndtr", "numpy.arange", "numpy.less", "numpy.atleast_1d", "scipy._lib._util.check_random_state", "numpy.argmax", "numpy.size", "numpy.count_nonzero", "numpy.ravel", "numpy.zeros", "numpy.log", "numpy.power", "numpy.min", "numpy.isnan", "numpy.floor", "numpy.broadcast_arrays", "numpy.errstate", "scipy.integrate.quad", "numpy.find_common_type", "numpy.logical_and", "scipy.special.xlogy", "scipy._lib._util.getfullargspec_no_self", "numpy.sum", "numpy.array", "numpy.abs", "numpy.isfinite", "numpy.ones", "scipy.special.comb", "numpy.vectorize", "scipy.stats.entropy", "numpy.shape", "numpy.broadcast_to", "scipy.optimize.brentq", "numpy.isinf", "numpy.empty" ], [ "numpy.sqrt", "numpy.linspace", "numpy.asarray", "numpy.iscomplexobj", "numpy.exp", "numpy.hstack", "numpy.sinc", "numpy.allclose", "numpy.arange", "scipy.linalg.lstsq", "numpy.finfo", "numpy.atleast_1d", "numpy.diff", "numpy.interp", "scipy.linalg.hankel", "numpy.zeros", "scipy.linalg.solve", "numpy.log", "numpy.fft.irfft", "numpy.fft.ifft", "numpy.array", "numpy.sum", "scipy.special.sinc", "scipy.linalg.toeplitz", "numpy.fft.fft", "numpy.cos" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.14", "1.6", "1.10", "0.15", "1.4", "0.16", "1.9", "0.19", "1.5", "0.18", "1.2", "1.7", "1.0", "0.17", "1.3", "1.8" ], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "0.12" ], "tensorflow": [] } ]
sperlingxx/cudf
[ "c681211df6253e1ceee9203658108980e7e93e3c", "c681211df6253e1ceee9203658108980e7e93e3c", "c681211df6253e1ceee9203658108980e7e93e3c", "c681211df6253e1ceee9203658108980e7e93e3c", "c681211df6253e1ceee9203658108980e7e93e3c", "c681211df6253e1ceee9203658108980e7e93e3c", "c681211df6253e1ceee9203658108980e7e93e3c" ]
[ "python/cudf/cudf/tests/test_duplicates.py", "python/cudf_kafka/setup.py", "python/cudf/cudf/tests/test_onehot.py", "python/cudf/cudf/tests/test_scan.py", "python/dask_cudf/dask_cudf/tests/test_reductions.py", "python/cudf/cudf/tests/test_array_function.py", "python/dask_cudf/dask_cudf/core.py" ]
[ "# Copyright (c) 2020-2021, NVIDIA CORPORATION.\n\nimport itertools as it\nimport random\n\nimport numpy as np\nimport pytest\nfrom pandas import DataFrame, MultiIndex, Series, date_range\n\nimport cudf\nfrom cudf import concat\nfrom cudf.tests.utils import assert_eq, assert_exceptions_equal\n\n# TODO: PANDAS 1.0 support\n# Revisit drop_duplicates() tests to update parameters like ignore_index.\n\n\ndef assert_df(g, p):\n # assert_eq() with sorted index of dataframes\n g = g.sort_index()\n p = p.sort_index()\n return assert_eq(g, p)\n\n\ndef assert_df2(g, p):\n assert g.index.dtype == p.index.dtype\n np.testing.assert_equal(g.index.to_array(), p.index)\n assert tuple(g.columns) == tuple(p.columns)\n for k in g.columns:\n assert g[k].dtype == p[k].dtype\n np.testing.assert_equal(g[k].to_array(), p[k])\n\n\n# most tests are similar to pandas drop_duplicates\n\n\[email protected](\"subset\", [\"a\", [\"a\"], [\"a\", \"B\"]])\ndef test_duplicated_with_misspelled_column_name(subset):\n df = DataFrame({\"A\": [0, 0, 1], \"B\": [0, 0, 1], \"C\": [0, 0, 1]})\n gdf = cudf.DataFrame.from_pandas(df)\n\n assert_exceptions_equal(\n lfunc=df.drop_duplicates,\n rfunc=gdf.drop_duplicates,\n lfunc_args_and_kwargs=([subset],),\n rfunc_args_and_kwargs=([subset],),\n compare_error_message=False,\n )\n\n\[email protected](\"keep\", [\"first\", \"last\", False])\[email protected](\n \"data\",\n [\n [1, 2, 4, 5, 6, 6],\n [],\n [\"a\", \"b\", \"s\", \"sd\", \"a\", \"b\"],\n Series([\"aaa\"] * 10, dtype=\"object\"),\n ],\n)\ndef test_drop_duplicates_series(data, keep):\n pds = cudf.utils.utils._create_pandas_series(data)\n gds = cudf.from_pandas(pds)\n\n assert_df(pds.drop_duplicates(keep=keep), gds.drop_duplicates(keep=keep))\n pds.drop_duplicates(keep=keep, inplace=True)\n gds.drop_duplicates(keep=keep, inplace=True)\n assert_df(pds, gds)\n\n\ndef test_drop_duplicates():\n pdf = DataFrame(\n {\n \"AAA\": [\"foo\", \"bar\", \"foo\", \"bar\", \"foo\", \"bar\", \"bar\", \"foo\"],\n \"B\": [\"one\", \"one\", \"two\", \"two\", \"two\", \"two\", \"one\", \"two\"],\n \"C\": [1, 1, 2, 2, 2, 2, 1, 2],\n \"D\": range(8),\n }\n )\n gdf = cudf.DataFrame.from_pandas(pdf)\n # single column\n result = gdf.copy()\n result.drop_duplicates(\"AAA\", inplace=True)\n expected = pdf.copy()\n expected.drop_duplicates(\"AAA\", inplace=True)\n assert_df(result, expected)\n\n result = gdf.drop_duplicates(\"AAA\", keep=\"last\")\n expected = pdf.drop_duplicates(\"AAA\", keep=\"last\")\n assert_df(result, expected)\n\n result = gdf.drop_duplicates(\"AAA\", keep=False)\n expected = pdf.drop_duplicates(\"AAA\", keep=False)\n assert_df(result, expected)\n assert len(result) == 0\n\n # multi column\n expected = pdf.loc[[0, 1, 2, 3]]\n result = gdf.drop_duplicates(np.array([\"AAA\", \"B\"]))\n assert_df(result, expected)\n result = pdf.drop_duplicates(np.array([\"AAA\", \"B\"]))\n assert_df(result, expected)\n\n result = gdf.drop_duplicates((\"AAA\", \"B\"), keep=\"last\")\n expected = pdf.drop_duplicates((\"AAA\", \"B\"), keep=\"last\")\n assert_df(result, expected)\n\n result = gdf.drop_duplicates((\"AAA\", \"B\"), keep=False)\n expected = pdf.drop_duplicates((\"AAA\", \"B\"), keep=False)\n assert_df(result, expected)\n\n # consider everything\n df2 = gdf.loc[:, [\"AAA\", \"B\", \"C\"]]\n\n result = df2.drop_duplicates()\n # in this case only\n expected = df2.drop_duplicates([\"AAA\", \"B\"])\n assert_df(result, expected)\n\n result = df2.drop_duplicates(keep=\"last\")\n expected = df2.drop_duplicates([\"AAA\", \"B\"], keep=\"last\")\n assert_df(result, expected)\n\n result = df2.drop_duplicates(keep=False)\n expected = df2.drop_duplicates([\"AAA\", \"B\"], keep=False)\n assert_df(result, expected)\n\n # integers\n result = gdf.drop_duplicates(\"C\")\n expected = pdf.drop_duplicates(\"C\")\n assert_df(result, expected)\n result = gdf.drop_duplicates(\"C\", keep=\"last\")\n expected = pdf.drop_duplicates(\"C\", keep=\"last\")\n assert_df(result, expected)\n\n gdf[\"E\"] = gdf[\"C\"].astype(\"int8\")\n result = gdf.drop_duplicates(\"E\")\n pdf[\"E\"] = pdf[\"C\"].astype(\"int8\")\n expected = pdf.drop_duplicates(\"E\")\n assert_df(result, expected)\n result = gdf.drop_duplicates(\"E\", keep=\"last\")\n expected = pdf.drop_duplicates(\"E\", keep=\"last\")\n assert_df(result, expected)\n\n pdf = DataFrame({\"x\": [7, 6, 3, 3, 4, 8, 0], \"y\": [0, 6, 5, 5, 9, 1, 2]})\n gdf = cudf.DataFrame.from_pandas(pdf)\n assert_df(gdf.drop_duplicates(), pdf.drop_duplicates())\n\n pdf = DataFrame([[1, 0], [0, 2]])\n gdf = cudf.DataFrame.from_pandas(pdf)\n assert_df(gdf.drop_duplicates(), pdf.drop_duplicates())\n\n pdf = DataFrame([[-2, 0], [0, -4]])\n gdf = cudf.DataFrame.from_pandas(pdf)\n assert_df(gdf.drop_duplicates(), pdf.drop_duplicates())\n\n x = np.iinfo(np.int64).max / 3 * 2\n pdf = DataFrame([[-x, x], [0, x + 4]])\n gdf = cudf.DataFrame.from_pandas(pdf)\n assert_df(gdf.drop_duplicates(), pdf.drop_duplicates())\n\n pdf = DataFrame([[-x, x], [x, x + 4]])\n gdf = cudf.DataFrame.from_pandas(pdf)\n assert_df(gdf.drop_duplicates(), pdf.drop_duplicates())\n\n pdf = DataFrame([i] * 9 for i in range(16))\n pdf = pdf.append([[1] + [0] * 8], ignore_index=True)\n gdf = cudf.DataFrame.from_pandas(pdf)\n assert_df(gdf.drop_duplicates(), pdf.drop_duplicates())\n\n\[email protected](reason=\"cudf does not support duplicate column names yet\")\ndef test_drop_duplicates_with_duplicate_column_names():\n df = DataFrame([[1, 2, 5], [3, 4, 6], [3, 4, 7]], columns=[\"a\", \"a\", \"b\"])\n df = cudf.DataFrame.from_pandas(df)\n\n result0 = df.drop_duplicates()\n assert_df(result0, df)\n\n result1 = df.drop_duplicates(\"a\")\n expected1 = df[:2]\n assert_df(result1, expected1)\n\n\ndef test_drop_duplicates_for_take_all():\n pdf = DataFrame(\n {\n \"AAA\": [\"foo\", \"bar\", \"baz\", \"bar\", \"foo\", \"bar\", \"qux\", \"foo\"],\n \"B\": [\"one\", \"one\", \"two\", \"two\", \"two\", \"two\", \"one\", \"two\"],\n \"C\": [1, 1, 2, 2, 2, 2, 1, 2],\n \"D\": range(8),\n }\n )\n gdf = cudf.DataFrame.from_pandas(pdf)\n # single column\n result = gdf.drop_duplicates(\"AAA\")\n expected = pdf.drop_duplicates(\"AAA\")\n assert_df(result, expected)\n\n result = gdf.drop_duplicates(\"AAA\", keep=\"last\")\n expected = pdf.drop_duplicates(\"AAA\", keep=\"last\")\n assert_df(result, expected)\n\n result = gdf.drop_duplicates(\"AAA\", keep=False)\n expected = pdf.drop_duplicates(\"AAA\", keep=False)\n assert_df(result, expected)\n\n # multiple columns\n result = gdf.drop_duplicates([\"AAA\", \"B\"])\n expected = pdf.drop_duplicates([\"AAA\", \"B\"])\n assert_df(result, expected)\n\n result = gdf.drop_duplicates([\"AAA\", \"B\"], keep=\"last\")\n expected = pdf.drop_duplicates([\"AAA\", \"B\"], keep=\"last\")\n assert_df(result, expected)\n\n result = gdf.drop_duplicates([\"AAA\", \"B\"], keep=False)\n expected = pdf.drop_duplicates([\"AAA\", \"B\"], keep=False)\n assert_df(result, expected)\n\n\ndef test_drop_duplicates_tuple():\n pdf = DataFrame(\n {\n (\"AA\", \"AB\"): [\n \"foo\",\n \"bar\",\n \"foo\",\n \"bar\",\n \"foo\",\n \"bar\",\n \"bar\",\n \"foo\",\n ],\n \"B\": [\"one\", \"one\", \"two\", \"two\", \"two\", \"two\", \"one\", \"two\"],\n \"C\": [1, 1, 2, 2, 2, 2, 1, 2],\n \"D\": range(8),\n }\n )\n gdf = cudf.DataFrame.from_pandas(pdf)\n # single column\n result = gdf.drop_duplicates((\"AA\", \"AB\"))\n expected = pdf.drop_duplicates((\"AA\", \"AB\"))\n assert_df(result, expected)\n\n result = gdf.drop_duplicates((\"AA\", \"AB\"), keep=\"last\")\n expected = pdf.drop_duplicates((\"AA\", \"AB\"), keep=\"last\")\n assert_df(result, expected)\n\n result = gdf.drop_duplicates((\"AA\", \"AB\"), keep=False)\n expected = pdf.drop_duplicates((\"AA\", \"AB\"), keep=False) # empty df\n assert len(result) == 0\n assert_df(result, expected)\n\n # multi column\n expected = pdf.drop_duplicates(((\"AA\", \"AB\"), \"B\"))\n result = gdf.drop_duplicates(((\"AA\", \"AB\"), \"B\"))\n assert_df(result, expected)\n\n\[email protected](\n \"df\",\n [\n DataFrame(),\n DataFrame(columns=[]),\n DataFrame(columns=[\"A\", \"B\", \"C\"]),\n DataFrame(index=[]),\n DataFrame(index=[\"A\", \"B\", \"C\"]),\n ],\n)\ndef test_drop_duplicates_empty(df):\n df = cudf.DataFrame.from_pandas(df)\n result = df.drop_duplicates()\n assert_df(result, df)\n\n result = df.copy()\n result.drop_duplicates(inplace=True)\n assert_df(result, df)\n\n\[email protected](\"num_columns\", [3, 4, 5])\ndef test_dataframe_drop_duplicates_numeric_method(num_columns):\n comb = list(it.permutations(range(num_columns), num_columns))\n shuf = list(comb)\n random.Random(num_columns).shuffle(shuf)\n\n def get_pdf(n_dup):\n # create dataframe with n_dup duplicate rows\n rows = comb + shuf[:n_dup]\n random.Random(n_dup).shuffle(rows)\n return DataFrame(rows)\n\n for i in range(5):\n pdf = get_pdf(i)\n gdf = cudf.DataFrame.from_pandas(pdf)\n assert_df(gdf.drop_duplicates(), pdf.drop_duplicates())\n\n # subset columns, single columns\n assert_df(\n gdf.drop_duplicates(pdf.columns[:-1]),\n pdf.drop_duplicates(pdf.columns[:-1]),\n )\n assert_df(\n gdf.drop_duplicates(pdf.columns[-1]),\n pdf.drop_duplicates(pdf.columns[-1]),\n )\n assert_df(\n gdf.drop_duplicates(pdf.columns[0]),\n pdf.drop_duplicates(pdf.columns[0]),\n )\n\n # subset columns shuffled\n cols = list(pdf.columns)\n random.Random(3).shuffle(cols)\n assert_df(gdf.drop_duplicates(cols), pdf.drop_duplicates(cols))\n random.Random(3).shuffle(cols)\n assert_df(gdf.drop_duplicates(cols[:-1]), pdf.drop_duplicates(cols[:-1]))\n random.Random(3).shuffle(cols)\n assert_df(gdf.drop_duplicates(cols[-1]), pdf.drop_duplicates(cols[-1]))\n assert_df(\n gdf.drop_duplicates(cols, keep=\"last\"),\n pdf.drop_duplicates(cols, keep=\"last\"),\n )\n\n\ndef test_dataframe_drop_duplicates_method():\n pdf = DataFrame(\n [(1, 2, \"a\"), (2, 3, \"b\"), (3, 4, \"c\"), (2, 3, \"d\"), (3, 5, \"c\")],\n columns=[\"n1\", \"n2\", \"s1\"],\n )\n gdf = cudf.DataFrame.from_pandas(pdf)\n assert_df(gdf.drop_duplicates(), pdf.drop_duplicates())\n\n assert_eq(\n gdf.drop_duplicates(\"n1\")[\"n1\"].reset_index(drop=True),\n pdf.drop_duplicates(\"n1\")[\"n1\"].reset_index(drop=True),\n )\n assert_eq(\n gdf.drop_duplicates(\"n2\")[\"n2\"].reset_index(drop=True),\n pdf.drop_duplicates(\"n2\")[\"n2\"].reset_index(drop=True),\n )\n assert_eq(\n gdf.drop_duplicates(\"s1\")[\"s1\"].reset_index(drop=True),\n pdf.drop_duplicates(\"s1\")[\"s1\"].reset_index(drop=True),\n )\n assert_eq(\n gdf.drop_duplicates(\"s1\", keep=\"last\")[\"s1\"]\n .sort_index()\n .reset_index(drop=True),\n pdf.drop_duplicates(\"s1\", keep=\"last\")[\"s1\"].reset_index(drop=True),\n )\n assert gdf.drop_duplicates(\"s1\", inplace=True) is None\n\n gdf = cudf.DataFrame.from_pandas(pdf)\n assert_df(gdf.drop_duplicates(\"n1\"), pdf.drop_duplicates(\"n1\"))\n assert_df(gdf.drop_duplicates(\"n2\"), pdf.drop_duplicates(\"n2\"))\n assert_df(gdf.drop_duplicates(\"s1\"), pdf.drop_duplicates(\"s1\"))\n assert_df(\n gdf.drop_duplicates([\"n1\", \"n2\"]), pdf.drop_duplicates([\"n1\", \"n2\"])\n )\n assert_df(\n gdf.drop_duplicates([\"n1\", \"s1\"]), pdf.drop_duplicates([\"n1\", \"s1\"])\n )\n\n # Test drop error\n assert_exceptions_equal(\n lfunc=pdf.drop_duplicates,\n rfunc=gdf.drop_duplicates,\n lfunc_args_and_kwargs=([\"n3\"],),\n rfunc_args_and_kwargs=([\"n3\"],),\n expected_error_message=\"columns {'n3'} do not exist\",\n )\n\n assert_exceptions_equal(\n lfunc=pdf.drop_duplicates,\n rfunc=gdf.drop_duplicates,\n lfunc_args_and_kwargs=([[\"n1\", \"n4\", \"n3\"]],),\n rfunc_args_and_kwargs=([[\"n1\", \"n4\", \"n3\"]],),\n expected_error_message=\"columns {'n[34]', 'n[34]'} do not exist\",\n )\n\n\ndef test_datetime_drop_duplicates():\n\n date_df = cudf.DataFrame()\n date_df[\"date\"] = date_range(\"11/20/2018\", periods=6, freq=\"D\")\n date_df[\"value\"] = np.random.sample(len(date_df))\n\n df = concat([date_df, date_df[:4]])\n assert_df(df[:-4], df.drop_duplicates())\n\n df2 = df.reset_index()\n assert_df(df2[:-4], df2.drop_duplicates())\n\n df3 = df.set_index(\"date\")\n assert_df(df3[:-4], df3.drop_duplicates())\n\n\ndef test_drop_duplicates_NA():\n # none\n df = DataFrame(\n {\n \"A\": [None, None, \"foo\", \"bar\", \"foo\", \"bar\", \"bar\", \"foo\"],\n \"B\": [\"one\", \"one\", \"two\", \"two\", \"two\", \"two\", \"one\", \"two\"],\n \"C\": [1.0, np.nan, np.nan, np.nan, 1.0, 1.0, 1, 1.0],\n \"D\": range(8),\n }\n )\n df = cudf.DataFrame.from_pandas(df)\n # single column\n result = df.drop_duplicates(\"A\")\n expected = df.to_pandas().loc[[0, 2, 3]]\n assert_df(result, expected)\n\n result = df.drop_duplicates(\"A\", keep=\"last\")\n expected = df.to_pandas().loc[[1, 6, 7]]\n assert_df(result, expected)\n\n result = df.drop_duplicates(\"A\", keep=False)\n expected = df.to_pandas().loc[[]] # empty df\n assert_df(result, expected)\n assert len(result) == 0\n\n # multi column\n result = df.drop_duplicates([\"A\", \"B\"])\n expected = df.to_pandas().loc[[0, 2, 3, 6]]\n assert_df(result, expected)\n\n result = df.drop_duplicates([\"A\", \"B\"], keep=\"last\")\n expected = df.to_pandas().loc[[1, 5, 6, 7]]\n assert_df(result, expected)\n\n result = df.drop_duplicates([\"A\", \"B\"], keep=False)\n expected = df.to_pandas().loc[[6]]\n assert_df(result, expected)\n\n # nan\n df = DataFrame(\n {\n \"A\": [\"foo\", \"bar\", \"foo\", \"bar\", \"foo\", \"bar\", \"bar\", \"foo\"],\n \"B\": [\"one\", \"one\", \"two\", \"two\", \"two\", \"two\", \"one\", \"two\"],\n \"C\": [1.0, np.nan, np.nan, np.nan, 1.0, 1.0, 1, 1.0],\n \"D\": range(8),\n }\n )\n df = cudf.DataFrame.from_pandas(df)\n # single column\n result = df.drop_duplicates(\"C\")\n expected = df[:2]\n assert_df(result, expected)\n\n result = df.drop_duplicates(\"C\", keep=\"last\")\n expected = df.to_pandas().loc[[3, 7]]\n assert_df(result, expected)\n\n result = df.drop_duplicates(\"C\", keep=False)\n expected = df.to_pandas().loc[[]] # empty df\n assert_df(result, expected)\n assert len(result) == 0\n\n # multi column\n result = df.drop_duplicates([\"C\", \"B\"])\n expected = df.to_pandas().loc[[0, 1, 2, 4]]\n assert_df(result, expected)\n\n result = df.drop_duplicates([\"C\", \"B\"], keep=\"last\")\n expected = df.to_pandas().loc[[1, 3, 6, 7]]\n assert_df(result, expected)\n\n result = df.drop_duplicates([\"C\", \"B\"], keep=False)\n expected = df.to_pandas().loc[[1]]\n assert_df(result, expected)\n\n\ndef test_drop_duplicates_NA_for_take_all():\n # TODO: PANDAS 1.0 support - add ignore_index for\n # pandas drop_duplicates calls in this function.\n\n # none\n pdf = DataFrame(\n {\n \"A\": [None, None, \"foo\", \"bar\", \"foo\", \"baz\", \"bar\", \"qux\"],\n \"C\": [1.0, np.nan, np.nan, np.nan, 1.0, 2.0, 3, 1.0],\n }\n )\n\n df = cudf.DataFrame.from_pandas(pdf)\n # single column\n result = df.drop_duplicates(\"A\")\n expected = pdf.iloc[[0, 2, 3, 5, 7]]\n assert_df(result, expected)\n assert_df(\n df.drop_duplicates(\"A\", ignore_index=True),\n result.reset_index(drop=True),\n )\n\n result = df.drop_duplicates(\"A\", keep=\"last\")\n expected = pdf.iloc[[1, 4, 5, 6, 7]]\n assert_df(result, expected)\n assert_df(\n df.drop_duplicates(\"A\", ignore_index=True, keep=\"last\"),\n result.reset_index(drop=True),\n )\n\n result = df.drop_duplicates(\"A\", keep=False)\n expected = pdf.iloc[[5, 7]]\n assert_df(result, expected)\n assert_df(\n df.drop_duplicates(\"A\", ignore_index=True, keep=False),\n result.reset_index(drop=True),\n )\n\n # nan\n\n # single column\n result = df.drop_duplicates(\"C\")\n expected = pdf.iloc[[0, 1, 5, 6]]\n assert_df(result, expected)\n\n result = df.drop_duplicates(\"C\", keep=\"last\")\n expected = pdf.iloc[[3, 5, 6, 7]]\n assert_df(result, expected)\n\n result = df.drop_duplicates(\"C\", keep=False)\n expected = pdf.iloc[[5, 6]]\n assert_df(result, expected)\n\n\ndef test_drop_duplicates_inplace():\n orig = DataFrame(\n {\n \"A\": [\"foo\", \"bar\", \"foo\", \"bar\", \"foo\", \"bar\", \"bar\", \"foo\"],\n \"B\": [\"one\", \"one\", \"two\", \"two\", \"two\", \"two\", \"one\", \"two\"],\n \"C\": [1, 1, 2, 2, 2, 2, 1, 2],\n \"D\": range(8),\n }\n )\n orig = cudf.DataFrame.from_pandas(orig)\n # single column\n df = orig.copy()\n df.drop_duplicates(\"A\", inplace=True)\n expected = orig[:2]\n result = df\n assert_df(result, expected)\n\n df = orig.copy()\n df.drop_duplicates(\"A\", keep=\"last\", inplace=True)\n expected = orig.loc[[6, 7]]\n result = df\n assert_df(result, expected)\n\n df = orig.copy()\n df.drop_duplicates(\"A\", keep=False, inplace=True)\n expected = orig.loc[[]]\n result = df\n assert_df(result, expected)\n assert len(df) == 0\n\n # multi column\n df = orig.copy()\n df.drop_duplicates([\"A\", \"B\"], inplace=True)\n expected = orig.loc[[0, 1, 2, 3]]\n result = df\n assert_df(result, expected)\n\n df = orig.copy()\n df.drop_duplicates([\"A\", \"B\"], keep=\"last\", inplace=True)\n expected = orig.loc[[0, 5, 6, 7]]\n result = df\n assert_df(result, expected)\n\n df = orig.copy()\n df.drop_duplicates([\"A\", \"B\"], keep=False, inplace=True)\n expected = orig.loc[[0]]\n result = df\n assert_df(result, expected)\n\n # consider everything\n orig2 = orig.loc[:, [\"A\", \"B\", \"C\"]].copy()\n\n df2 = orig2.copy()\n df2.drop_duplicates(inplace=True)\n # in this case only\n expected = orig2.drop_duplicates([\"A\", \"B\"])\n result = df2\n assert_df(result, expected)\n\n df2 = orig2.copy()\n df2.drop_duplicates(keep=\"last\", inplace=True)\n expected = orig2.drop_duplicates([\"A\", \"B\"], keep=\"last\")\n result = df2\n assert_df(result, expected)\n\n df2 = orig2.copy()\n df2.drop_duplicates(keep=False, inplace=True)\n expected = orig2.drop_duplicates([\"A\", \"B\"], keep=False)\n result = df2\n assert_df(result, expected)\n\n\ndef test_drop_duplicates_multi_index():\n arrays = [\n [\"bar\", \"bar\", \"baz\", \"baz\", \"foo\", \"foo\", \"qux\", \"qux\"],\n [\"one\", \"two\", \"one\", \"two\", \"one\", \"two\", \"one\", \"two\"],\n ]\n\n idx = MultiIndex.from_tuples(list(zip(*arrays)), names=[\"a\", \"b\"])\n pdf = DataFrame(np.random.randint(0, 2, (8, 4)), index=idx)\n gdf = cudf.DataFrame.from_pandas(pdf)\n\n expected = pdf.drop_duplicates()\n result = gdf.drop_duplicates()\n assert_df(result.to_pandas(), expected)\n # FIXME: to_pandas needed until sort_index support for MultiIndex\n\n for col in gdf.columns:\n assert_df(\n gdf[col].drop_duplicates().to_pandas(), pdf[col].drop_duplicates(),\n )\n", "# Copyright (c) 2020, NVIDIA CORPORATION.\nimport os\nimport shutil\nimport sysconfig\nfrom distutils.sysconfig import get_python_lib\n\nimport numpy as np\nfrom Cython.Build import cythonize\nfrom setuptools import find_packages, setup\nfrom setuptools.extension import Extension\n\nimport versioneer\n\ninstall_requires = [\"cudf\", \"cython\"]\n\ncython_files = [\"cudf_kafka/_lib/*.pyx\"]\n\nCUDA_HOME = os.environ.get(\"CUDA_HOME\", False)\nif not CUDA_HOME:\n path_to_cuda_gdb = shutil.which(\"cuda-gdb\")\n if path_to_cuda_gdb is None:\n raise OSError(\n \"Could not locate CUDA. \"\n \"Please set the environment variable \"\n \"CUDA_HOME to the path to the CUDA installation \"\n \"and try again.\"\n )\n CUDA_HOME = os.path.dirname(os.path.dirname(path_to_cuda_gdb))\n\nif not os.path.isdir(CUDA_HOME):\n raise OSError(f\"Invalid CUDA_HOME: directory does not exist: {CUDA_HOME}\")\n\ncuda_include_dir = os.path.join(CUDA_HOME, \"include\")\n\nCUDF_ROOT = os.environ.get(\n \"CUDF_ROOT\",\n os.path.abspath(\n os.path.join(\n os.path.dirname(os.path.abspath(__file__)), \"../../cpp/build/\"\n )\n ),\n)\nCUDF_KAFKA_ROOT = os.environ.get(\n \"CUDF_KAFKA_ROOT\", \"../../libcudf_kafka/build\"\n)\n\ntry:\n nthreads = int(os.environ.get(\"PARALLEL_LEVEL\", \"0\") or \"0\")\nexcept Exception:\n nthreads = 0\n\nextensions = [\n Extension(\n \"*\",\n sources=cython_files,\n include_dirs=[\n os.path.abspath(os.path.join(CUDF_ROOT, \"../include/cudf\")),\n os.path.abspath(os.path.join(CUDF_ROOT, \"../include\")),\n os.path.abspath(\n os.path.join(CUDF_ROOT, \"../libcudf_kafka/include/cudf_kafka\")\n ),\n os.path.join(CUDF_ROOT, \"include\"),\n os.path.join(CUDF_ROOT, \"_deps/libcudacxx-src/include\"),\n os.path.join(\n os.path.dirname(sysconfig.get_path(\"include\")),\n \"libcudf/libcudacxx\",\n ),\n os.path.dirname(sysconfig.get_path(\"include\")),\n np.get_include(),\n cuda_include_dir,\n ],\n library_dirs=([get_python_lib(), os.path.join(os.sys.prefix, \"lib\")]),\n libraries=[\"cudf\", \"cudf_kafka\"],\n language=\"c++\",\n extra_compile_args=[\"-std=c++14\"],\n )\n]\n\nsetup(\n name=\"cudf_kafka\",\n version=versioneer.get_version(),\n description=\"cuDF Kafka Datasource\",\n url=\"https://github.com/rapidsai/cudf\",\n author=\"NVIDIA Corporation\",\n license=\"Apache 2.0\",\n classifiers=[\n \"Intended Audience :: Developers\",\n \"Topic :: Streaming\",\n \"Topic :: Scientific/Engineering\",\n \"Topic :: Apache Kafka\",\n \"License :: OSI Approved :: Apache Software License\",\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: 3.8\",\n ],\n # Include the separately-compiled shared library\n setup_requires=[\"Cython>=0.29,<0.30\"],\n ext_modules=cythonize(\n extensions,\n nthreads=nthreads,\n compiler_directives=dict(\n profile=False, language_level=3, embedsignature=True\n ),\n ),\n packages=find_packages(include=[\"cudf_kafka\", \"cudf_kafka.*\"]),\n package_data=dict.fromkeys(\n find_packages(include=[\"cudf_kafka._lib*\"]), [\"*.pxd\"],\n ),\n cmdclass=versioneer.get_cmdclass(),\n install_requires=install_requires,\n extras_require={\"test\": [\"pytest\", \"pytest-xdist\"]},\n zip_safe=False,\n)\n", "# Copyright (c) 2018, NVIDIA CORPORATION.\n\nfrom string import ascii_lowercase\n\nimport numpy as np\nimport pandas as pd\nimport pytest\n\nimport cudf\nfrom cudf.core import DataFrame, GenericIndex, Series\nfrom cudf.tests import utils\n\n\ndef test_onehot_simple():\n np.random.seed(0)\n df = DataFrame()\n # Populate with data [0, 10)\n df[\"vals\"] = np.arange(10, dtype=np.int32)\n # One Hot (Series)\n for i, col in enumerate(df[\"vals\"].one_hot_encoding(list(range(10)))):\n arr = col.to_array()\n # Verify 1 in the right position\n np.testing.assert_equal(arr[i], 1)\n # Every other slots are 0s\n np.testing.assert_equal(arr[:i], 0)\n np.testing.assert_equal(arr[i + 1 :], 0)\n # One Hot (DataFrame)\n df2 = df.one_hot_encoding(\n column=\"vals\", prefix=\"vals\", cats=list(range(10))\n )\n assert df2.columns[0] == \"vals\"\n for i in range(1, len(df2.columns)):\n assert df2.columns[i] == \"vals_%s\" % (i - 1)\n got = df2.as_matrix(columns=df2.columns[1:])\n expect = np.identity(got.shape[0])\n np.testing.assert_equal(got, expect)\n\n\ndef test_onehot_random():\n df = DataFrame()\n low = 10\n high = 17\n size = 10\n df[\"src\"] = src = np.random.randint(low=low, high=high, size=size)\n df2 = df.one_hot_encoding(\n column=\"src\", prefix=\"out_\", cats=tuple(range(10, 17))\n )\n mat = df2.as_matrix(columns=df2.columns[1:])\n\n for val in range(low, high):\n colidx = val - low\n arr = mat[:, colidx]\n mask = src == val\n np.testing.assert_equal(arr, mask)\n\n\ndef test_onehot_masked():\n np.random.seed(0)\n high = 5\n size = 100\n arr = np.random.randint(low=0, high=high, size=size)\n bitmask = utils.random_bitmask(size)\n bytemask = np.asarray(\n utils.expand_bits_to_bytes(bitmask)[:size], dtype=np.bool_\n )\n arr[~bytemask] = -1\n\n df = DataFrame()\n df[\"a\"] = Series(arr).set_mask(bitmask)\n\n out = df.one_hot_encoding(\n \"a\", cats=list(range(high)), prefix=\"a\", dtype=np.int32\n )\n\n assert tuple(out.columns) == (\"a\", \"a_0\", \"a_1\", \"a_2\", \"a_3\", \"a_4\")\n np.testing.assert_array_equal((out[\"a_0\"] == 1).to_array(), arr == 0)\n np.testing.assert_array_equal((out[\"a_1\"] == 1).to_array(), arr == 1)\n np.testing.assert_array_equal((out[\"a_2\"] == 1).to_array(), arr == 2)\n np.testing.assert_array_equal((out[\"a_3\"] == 1).to_array(), arr == 3)\n np.testing.assert_array_equal((out[\"a_4\"] == 1).to_array(), arr == 4)\n\n\ndef test_onehot_generic_index():\n np.random.seed(0)\n size = 33\n indices = np.random.randint(low=0, high=100, size=size)\n df = DataFrame()\n values = np.random.randint(low=0, high=4, size=size)\n df[\"fo\"] = Series(values, index=GenericIndex(indices))\n out = df.one_hot_encoding(\n \"fo\", cats=df.fo.unique(), prefix=\"fo\", dtype=np.int32\n )\n assert set(out.columns) == {\"fo\", \"fo_0\", \"fo_1\", \"fo_2\", \"fo_3\"}\n np.testing.assert_array_equal(values == 0, out.fo_0.to_array())\n np.testing.assert_array_equal(values == 1, out.fo_1.to_array())\n np.testing.assert_array_equal(values == 2, out.fo_2.to_array())\n np.testing.assert_array_equal(values == 3, out.fo_3.to_array())\n\n\[email protected](\n \"data\",\n [\n np.arange(10),\n [\"abc\", \"zyx\", \"pppp\"],\n [],\n pd.Series([\"cudf\", \"hello\", \"pandas\"] * 10, dtype=\"category\"),\n ],\n)\ndef test_get_dummies(data):\n gdf = DataFrame({\"x\": data})\n pdf = pd.DataFrame({\"x\": data})\n\n encoded_expected = pd.get_dummies(pdf, prefix=\"test\")\n encoded_actual = cudf.get_dummies(gdf, prefix=\"test\")\n\n utils.assert_eq(encoded_expected, encoded_actual)\n encoded_actual = cudf.get_dummies(gdf, prefix=\"test\", dtype=np.uint8)\n\n utils.assert_eq(encoded_expected, encoded_actual)\n\n\[email protected](\"n_cols\", [5, 10, 20])\ndef test_onehot_get_dummies_multicol(n_cols):\n n_categories = 5\n data = dict(\n zip(ascii_lowercase, (np.arange(n_categories) for _ in range(n_cols)))\n )\n\n gdf = cudf.DataFrame(data)\n pdf = pd.DataFrame(data)\n\n encoded_expected = pd.get_dummies(pdf, prefix=\"test\")\n encoded_actual = cudf.get_dummies(gdf, prefix=\"test\")\n\n utils.assert_eq(encoded_expected, encoded_actual)\n\n\[email protected](\"nan_as_null\", [True, False])\[email protected](\"dummy_na\", [True, False])\ndef test_onehost_get_dummies_dummy_na(nan_as_null, dummy_na):\n pdf = pd.DataFrame({\"a\": [0, 1, np.nan]})\n df = DataFrame.from_pandas(pdf, nan_as_null=nan_as_null)\n\n expected = pd.get_dummies(pdf, dummy_na=dummy_na, columns=[\"a\"])\n got = cudf.get_dummies(df, dummy_na=dummy_na, columns=[\"a\"])\n\n if dummy_na and nan_as_null:\n got = got.rename(columns={\"a_null\": \"a_nan\"})[expected.columns]\n\n utils.assert_eq(expected, got)\n\n\[email protected](\n \"prefix\",\n [\n [\"a\", \"b\", \"c\"],\n \"\",\n None,\n {\"first\": \"one\", \"second\": \"two\", \"third\": \"three\"},\n \"--\",\n ],\n)\[email protected](\n \"prefix_sep\",\n [\n [\"a\", \"b\", \"c\"],\n \"\",\n \"++\",\n {\"first\": \"*******\", \"second\": \"__________\", \"third\": \"#########\"},\n ],\n)\ndef test_get_dummies_prefix_sep(prefix, prefix_sep):\n data = {\n \"first\": [\"1\", \"2\", \"3\"],\n \"second\": [\"abc\", \"def\", \"ghi\"],\n \"third\": [\"ji\", \"ji\", \"ji\"],\n }\n\n gdf = DataFrame(data)\n pdf = pd.DataFrame(data)\n\n encoded_expected = pd.get_dummies(\n pdf, prefix=prefix, prefix_sep=prefix_sep\n )\n encoded_actual = cudf.get_dummies(\n gdf, prefix=prefix, prefix_sep=prefix_sep\n )\n\n utils.assert_eq(encoded_expected, encoded_actual)\n\n\ndef test_get_dummies_with_nan():\n df = cudf.DataFrame(\n {\"a\": cudf.Series([1, 2, np.nan, None], nan_as_null=False)}\n )\n expected = cudf.DataFrame(\n {\n \"a_1.0\": [1, 0, 0, 0],\n \"a_2.0\": [0, 1, 0, 0],\n \"a_nan\": [0, 0, 1, 0],\n \"a_null\": [0, 0, 0, 1],\n },\n dtype=\"uint8\",\n )\n actual = cudf.get_dummies(df, dummy_na=True, columns=[\"a\"])\n\n utils.assert_eq(expected, actual)\n\n\[email protected](\n \"data\",\n [\n cudf.Series([\"abc\", \"l\", \"a\", \"abc\", \"z\", \"xyz\"]),\n cudf.Index([None, 1, 2, 3.3, None, 0.2]),\n cudf.Series([0.1, 2, 3, None, np.nan]),\n cudf.Series([23678, 324, 1, 324], name=\"abc\"),\n ],\n)\[email protected](\"prefix_sep\", [\"-\", \"#\"])\[email protected](\"prefix\", [None, \"hi\"])\[email protected](\"dtype\", [\"uint8\", \"int16\"])\ndef test_get_dummies_array_like(data, prefix_sep, prefix, dtype):\n expected = cudf.get_dummies(\n data, prefix=prefix, prefix_sep=prefix_sep, dtype=dtype\n )\n if isinstance(data, (cudf.Series, cudf.Index)):\n pd_data = data.to_pandas()\n else:\n pd_data = data\n\n actual = pd.get_dummies(\n pd_data, prefix=prefix, prefix_sep=prefix_sep, dtype=dtype\n )\n utils.assert_eq(expected, actual)\n\n\ndef test_get_dummies_array_like_with_nan():\n ser = cudf.Series([0.1, 2, 3, None, np.nan], nan_as_null=False)\n expected = cudf.DataFrame(\n {\n \"a_null\": [0, 0, 0, 1, 0],\n \"a_0.1\": [1, 0, 0, 0, 0],\n \"a_2.0\": [0, 1, 0, 0, 0],\n \"a_3.0\": [0, 0, 1, 0, 0],\n \"a_nan\": [0, 0, 0, 0, 1],\n },\n dtype=\"uint8\",\n )\n actual = cudf.get_dummies(ser, dummy_na=True, prefix=\"a\", prefix_sep=\"_\")\n\n utils.assert_eq(expected, actual)\n", "from itertools import product\n\nimport numpy as np\nimport pandas as pd\nimport pytest\n\nimport cudf\nfrom cudf.tests.utils import INTEGER_TYPES, NUMERIC_TYPES, assert_eq, gen_rand\nfrom cudf.core.dtypes import Decimal64Dtype\n\nparams_sizes = [0, 1, 2, 5]\n\n\ndef _gen_params():\n for t, n in product(NUMERIC_TYPES, params_sizes):\n if (t == np.int8 or t == np.int16) and n > 20:\n # to keep data in range\n continue\n yield t, n\n\n\[email protected](\"dtype,nelem\", list(_gen_params()))\ndef test_cumsum(dtype, nelem):\n if dtype == np.int8:\n # to keep data in range\n data = gen_rand(dtype, nelem, low=-2, high=2)\n else:\n data = gen_rand(dtype, nelem)\n\n decimal = 4 if dtype == np.float32 else 6\n\n # series\n gs = cudf.Series(data)\n ps = pd.Series(data)\n np.testing.assert_array_almost_equal(\n gs.cumsum().to_array(), ps.cumsum(), decimal=decimal\n )\n\n # dataframe series (named series)\n gdf = cudf.DataFrame()\n gdf[\"a\"] = cudf.Series(data)\n pdf = pd.DataFrame()\n pdf[\"a\"] = pd.Series(data)\n np.testing.assert_array_almost_equal(\n gdf.a.cumsum().to_array(), pdf.a.cumsum(), decimal=decimal\n )\n\n\ndef test_cumsum_masked():\n data = [1, 2, None, 4, 5]\n float_types = [\"float32\", \"float64\"]\n\n for type_ in float_types:\n gs = cudf.Series(data).astype(type_)\n ps = pd.Series(data).astype(type_)\n assert_eq(gs.cumsum(), ps.cumsum())\n\n for type_ in INTEGER_TYPES:\n gs = cudf.Series(data).astype(type_)\n got = gs.cumsum()\n expected = pd.Series([1, 3, np.nan, 7, 12], dtype=\"float64\")\n assert_eq(got, expected)\n\n\[email protected](\n \"dtype\",\n [Decimal64Dtype(8, 4), Decimal64Dtype(10, 5), Decimal64Dtype(12, 7)],\n)\ndef test_cumsum_decimal(dtype):\n data = [\"243.32\", \"48.245\", \"-7234.298\", np.nan, \"-467.2\"]\n gser = cudf.Series(data).astype(dtype)\n pser = pd.Series(data, dtype=\"float64\")\n\n got = gser.cumsum()\n expected = cudf.Series.from_pandas(pser.cumsum()).astype(dtype)\n\n assert_eq(got, expected)\n\n\[email protected](\"dtype,nelem\", list(_gen_params()))\ndef test_cummin(dtype, nelem):\n if dtype == np.int8:\n # to keep data in range\n data = gen_rand(dtype, nelem, low=-2, high=2)\n else:\n data = gen_rand(dtype, nelem)\n\n decimal = 4 if dtype == np.float32 else 6\n\n # series\n gs = cudf.Series(data)\n ps = pd.Series(data)\n np.testing.assert_array_almost_equal(\n gs.cummin().to_array(), ps.cummin(), decimal=decimal\n )\n\n # dataframe series (named series)\n gdf = cudf.DataFrame()\n gdf[\"a\"] = cudf.Series(data)\n pdf = pd.DataFrame()\n pdf[\"a\"] = pd.Series(data)\n np.testing.assert_array_almost_equal(\n gdf.a.cummin().to_array(), pdf.a.cummin(), decimal=decimal\n )\n\n\ndef test_cummin_masked():\n data = [1, 2, None, 4, 5]\n float_types = [\"float32\", \"float64\"]\n\n for type_ in float_types:\n gs = cudf.Series(data).astype(type_)\n ps = pd.Series(data).astype(type_)\n assert_eq(gs.cummin(), ps.cummin())\n\n for type_ in INTEGER_TYPES:\n gs = cudf.Series(data).astype(type_)\n expected = pd.Series([1, 1, np.nan, 1, 1]).astype(\"float64\")\n assert_eq(gs.cummin(), expected)\n\n\[email protected](\n \"dtype\",\n [Decimal64Dtype(8, 4), Decimal64Dtype(11, 6), Decimal64Dtype(14, 7)],\n)\ndef test_cummin_decimal(dtype):\n data = [\"8394.294\", np.nan, \"-9940.444\", np.nan, \"-23.928\"]\n gser = cudf.Series(data).astype(dtype)\n pser = pd.Series(data, dtype=\"float64\")\n\n got = gser.cummin()\n expected = cudf.Series.from_pandas(pser.cummin()).astype(dtype)\n\n assert_eq(got, expected)\n\n\[email protected](\"dtype,nelem\", list(_gen_params()))\ndef test_cummax(dtype, nelem):\n if dtype == np.int8:\n # to keep data in range\n data = gen_rand(dtype, nelem, low=-2, high=2)\n else:\n data = gen_rand(dtype, nelem)\n\n decimal = 4 if dtype == np.float32 else 6\n\n # series\n gs = cudf.Series(data)\n ps = pd.Series(data)\n np.testing.assert_array_almost_equal(\n gs.cummax().to_array(), ps.cummax(), decimal=decimal\n )\n\n # dataframe series (named series)\n gdf = cudf.DataFrame()\n gdf[\"a\"] = cudf.Series(data)\n pdf = pd.DataFrame()\n pdf[\"a\"] = pd.Series(data)\n np.testing.assert_array_almost_equal(\n gdf.a.cummax().to_array(), pdf.a.cummax(), decimal=decimal\n )\n\n\ndef test_cummax_masked():\n data = [1, 2, None, 4, 5]\n float_types = [\"float32\", \"float64\"]\n\n for type_ in float_types:\n gs = cudf.Series(data).astype(type_)\n ps = pd.Series(data).astype(type_)\n assert_eq(gs.cummax(), ps.cummax())\n\n for type_ in INTEGER_TYPES:\n gs = cudf.Series(data).astype(type_)\n expected = pd.Series([1, 2, np.nan, 4, 5]).astype(\"float64\")\n assert_eq(gs.cummax(), expected)\n\n\[email protected](\n \"dtype\",\n [Decimal64Dtype(8, 4), Decimal64Dtype(11, 6), Decimal64Dtype(14, 7)],\n)\ndef test_cummax_decimal(dtype):\n data = [np.nan, \"54.203\", \"8.222\", \"644.32\", \"-562.272\"]\n gser = cudf.Series(data).astype(dtype)\n pser = pd.Series(data, dtype=\"float64\")\n\n got = gser.cummax()\n expected = cudf.Series.from_pandas(pser.cummax()).astype(dtype)\n\n assert_eq(got, expected)\n\n\[email protected](\"dtype,nelem\", list(_gen_params()))\ndef test_cumprod(dtype, nelem):\n if dtype == np.int8:\n # to keep data in range\n data = gen_rand(dtype, nelem, low=-2, high=2)\n else:\n data = gen_rand(dtype, nelem)\n\n decimal = 4 if dtype == np.float32 else 6\n\n # series\n gs = cudf.Series(data)\n ps = pd.Series(data)\n np.testing.assert_array_almost_equal(\n gs.cumprod().to_array(), ps.cumprod(), decimal=decimal\n )\n\n # dataframe series (named series)\n gdf = cudf.DataFrame()\n gdf[\"a\"] = cudf.Series(data)\n pdf = pd.DataFrame()\n pdf[\"a\"] = pd.Series(data)\n np.testing.assert_array_almost_equal(\n gdf.a.cumprod().to_array(), pdf.a.cumprod(), decimal=decimal\n )\n\n\ndef test_cumprod_masked():\n data = [1, 2, None, 4, 5]\n float_types = [\"float32\", \"float64\"]\n\n for type_ in float_types:\n gs = cudf.Series(data).astype(type_)\n ps = pd.Series(data).astype(type_)\n assert_eq(gs.cumprod(), ps.cumprod())\n\n for type_ in INTEGER_TYPES:\n gs = cudf.Series(data).astype(type_)\n got = gs.cumprod()\n expected = pd.Series([1, 2, np.nan, 8, 40], dtype=\"float64\")\n assert_eq(got, expected)\n\n\ndef test_scan_boolean_cumsum():\n s = cudf.Series([0, -1, -300, 23, 4, -3, 0, 0, 100])\n\n # cumsum test\n got = (s > 0).cumsum()\n expect = (s > 0).to_pandas().cumsum()\n\n assert_eq(expect, got)\n\n\ndef test_scan_boolean_cumprod():\n s = cudf.Series([0, -1, -300, 23, 4, -3, 0, 0, 100])\n\n # cumprod test\n got = (s > 0).cumprod()\n expect = (s > 0).to_pandas().cumprod()\n\n assert_eq(expect, got)\n", "# Copyright (c) 2021, NVIDIA CORPORATION.\n\nimport numpy as np\nimport pandas as pd\nimport pytest\n\nfrom dask import dataframe as dd\n\nimport dask_cudf as dgd\n\nimport cudf\n\n\ndef _make_random_frame(nelem, npartitions=2):\n df = pd.DataFrame(\n {\n \"x\": np.random.randint(0, 5, size=nelem),\n \"y\": np.random.normal(size=nelem) + 1,\n }\n )\n gdf = cudf.DataFrame.from_pandas(df)\n dgf = dgd.from_cudf(gdf, npartitions=npartitions)\n return df, dgf\n\n\n_reducers = [\"sum\", \"count\", \"mean\", \"var\", \"std\", \"min\", \"max\"]\n\n\ndef _get_reduce_fn(name):\n def wrapped(series):\n fn = getattr(series, name)\n return fn()\n\n return wrapped\n\n\[email protected](\"reducer\", _reducers)\ndef test_series_reduce(reducer):\n reducer = _get_reduce_fn(reducer)\n np.random.seed(0)\n size = 10\n df, gdf = _make_random_frame(size)\n\n got = reducer(gdf.x)\n exp = reducer(df.x)\n dd.assert_eq(got, exp)\n\n\[email protected](\n \"data\",\n [\n cudf.datasets.randomdata(\n nrows=10000,\n dtypes={\"a\": \"category\", \"b\": int, \"c\": float, \"d\": int},\n ),\n cudf.datasets.randomdata(\n nrows=10000,\n dtypes={\"a\": \"category\", \"b\": int, \"c\": float, \"d\": str},\n ),\n cudf.datasets.randomdata(\n nrows=10000, dtypes={\"a\": bool, \"b\": int, \"c\": float, \"d\": str}\n ),\n ],\n)\[email protected](\n \"op\", [\"max\", \"min\", \"sum\", \"prod\", \"mean\", \"var\", \"std\"]\n)\ndef test_rowwise_reductions(data, op):\n\n gddf = dgd.from_cudf(data, npartitions=10)\n pddf = gddf.to_dask_dataframe()\n\n if op in (\"var\", \"std\"):\n expected = getattr(pddf, op)(axis=1, ddof=0)\n got = getattr(gddf, op)(axis=1, ddof=0)\n else:\n expected = getattr(pddf, op)(axis=1)\n got = getattr(pddf, op)(axis=1)\n\n dd.assert_eq(expected.compute(), got.compute(), check_exact=False)\n", "# Copyright (c) 2018, NVIDIA CORPORATION.\nimport numpy as np\nimport pandas as pd\nimport pytest\n\nimport cudf\nfrom cudf.tests.utils import assert_eq\nfrom cudf.utils.utils import IS_NEP18_ACTIVE\n\nmissing_arrfunc_cond = not IS_NEP18_ACTIVE\nmissing_arrfunc_reason = \"NEP-18 support is not available in NumPy\"\n\n# Test implementation based on dask array test\n# https://github.com/dask/dask/blob/master/dask/array/tests/test_array_function.py\n\n\[email protected](missing_arrfunc_cond, reason=missing_arrfunc_reason)\[email protected](\"np_ar\", [np.random.random(100)])\[email protected](\n \"func\",\n [\n lambda x: np.mean(x),\n lambda x: np.sum(x),\n lambda x: np.var(x, ddof=1),\n lambda x: np.unique(x),\n lambda x: np.dot(x, x),\n lambda x: np.linalg.norm(x),\n ],\n)\ndef test_array_func_cudf_series(np_ar, func):\n cudf_ser = cudf.Series(np_ar)\n expect = func(np_ar)\n got = func(cudf_ser)\n if np.isscalar(expect):\n assert_eq(expect, got)\n else:\n assert_eq(expect, got.to_array())\n\n\[email protected](missing_arrfunc_cond, reason=missing_arrfunc_reason)\[email protected](\n \"pd_df\", [pd.DataFrame(np.random.uniform(size=(100, 10)))]\n)\[email protected](\n \"func\",\n [lambda x: np.mean(x), lambda x: np.sum(x), lambda x: np.var(x, ddof=1)],\n)\ndef test_array_func_cudf_dataframe(pd_df, func):\n cudf_df = cudf.from_pandas(pd_df)\n expect = func(pd_df)\n got = func(cudf_df)\n assert_eq(expect, got)\n\n\[email protected](missing_arrfunc_cond, reason=missing_arrfunc_reason)\[email protected](\n \"pd_df\", [pd.DataFrame(np.random.uniform(size=(100, 10)))]\n)\[email protected](\n \"func\",\n [\n lambda x: np.cov(x, x),\n lambda x: np.dot(x, x),\n lambda x: np.linalg.norm(x),\n lambda x: np.linalg.det(x),\n ],\n)\ndef test_array_func_missing_cudf_dataframe(pd_df, func):\n cudf_df = cudf.from_pandas(pd_df)\n with pytest.raises(TypeError):\n func(cudf_df)\n\n\n# we only implement sum among all numpy non-ufuncs\[email protected](missing_arrfunc_cond, reason=missing_arrfunc_reason)\[email protected](\"np_ar\", [np.random.random(100)])\[email protected](\"func\", [lambda x: np.sum(x)])\ndef test_array_func_cudf_index(np_ar, func):\n cudf_index = cudf.core.index.as_index(cudf.Series(np_ar))\n expect = func(np_ar)\n got = func(cudf_index)\n assert_eq(expect, got)\n\n\[email protected](missing_arrfunc_cond, reason=missing_arrfunc_reason)\[email protected](\"np_ar\", [np.random.random(100)])\[email protected](\n \"func\",\n [\n lambda x: np.cov(x, x),\n lambda x: np.dot(x, x),\n lambda x: np.linalg.norm(x),\n lambda x: np.linalg.det(x),\n ],\n)\ndef test_array_func_missing_cudf_index(np_ar, func):\n cudf_index = cudf.core.index.as_index(cudf.Series(np_ar))\n with pytest.raises(TypeError):\n func(cudf_index)\n\n\[email protected](missing_arrfunc_cond, reason=missing_arrfunc_reason)\[email protected](\n \"func\",\n [\n lambda x: np.cov(x, x),\n lambda x: np.dot(x, x),\n lambda x: np.linalg.norm(x),\n lambda x: np.linalg.det(x),\n ],\n)\ndef test_array_func_missing_cudf_multi_index(func):\n levels = [[\"a\", \"b\"], [\"c\", \"d\"]]\n codes = [[0, 1], [1, 0]]\n\n cudf_multi_index = cudf.MultiIndex(levels, codes)\n with pytest.raises(TypeError):\n func(cudf_multi_index)\n\n\[email protected](missing_arrfunc_cond, reason=missing_arrfunc_reason)\ndef test_list_input_array_func():\n ar = np.array([1, 2, 3])\n\n s = cudf.Series(ar)\n with pytest.raises(TypeError):\n np.concatenate([s, s, s])\n\n s = cudf.Series(ar, index=[1, 2, 3])\n with pytest.raises(TypeError):\n np.concatenate([s, s, s])\n", "# Copyright (c) 2018-2020, NVIDIA CORPORATION.\nimport math\nimport warnings\nfrom distutils.version import LooseVersion\n\nimport numpy as np\nimport pandas as pd\nfrom tlz import partition_all\n\nimport dask\nfrom dask import dataframe as dd\nfrom dask.base import normalize_token, tokenize\nfrom dask.compatibility import apply\nfrom dask.context import _globals\nfrom dask.core import flatten\nfrom dask.dataframe.core import Scalar, finalize, handle_out, map_partitions\nfrom dask.dataframe.utils import raise_on_meta_error\nfrom dask.highlevelgraph import HighLevelGraph\nfrom dask.optimization import cull, fuse\nfrom dask.utils import M, OperatorMethodMixin, derived_from, funcname\n\nimport cudf\nfrom cudf import _lib as libcudf\n\nfrom dask_cudf import sorting\nfrom dask_cudf.accessors import ListMethods\n\nDASK_VERSION = LooseVersion(dask.__version__)\n\n\ndef optimize(dsk, keys, **kwargs):\n flatkeys = list(flatten(keys)) if isinstance(keys, list) else [keys]\n dsk, dependencies = cull(dsk, flatkeys)\n dsk, dependencies = fuse(\n dsk,\n keys,\n dependencies=dependencies,\n ave_width=_globals.get(\"fuse_ave_width\", 1),\n )\n dsk, _ = cull(dsk, keys)\n return dsk\n\n\nclass _Frame(dd.core._Frame, OperatorMethodMixin):\n \"\"\" Superclass for DataFrame and Series\n\n Parameters\n ----------\n dsk : dict\n The dask graph to compute this DataFrame\n name : str\n The key prefix that specifies which keys in the dask comprise this\n particular DataFrame / Series\n meta : cudf.DataFrame, cudf.Series, or cudf.Index\n An empty cudf object with names, dtypes, and indices matching the\n expected output.\n divisions : tuple of index values\n Values along which we partition our blocks on the index\n \"\"\"\n\n __dask_scheduler__ = staticmethod(dask.get)\n __dask_optimize__ = staticmethod(optimize)\n\n def __dask_postcompute__(self):\n return finalize, ()\n\n def __dask_postpersist__(self):\n return type(self), (self._name, self._meta, self.divisions)\n\n def __init__(self, dsk, name, meta, divisions):\n if not isinstance(dsk, HighLevelGraph):\n dsk = HighLevelGraph.from_collections(name, dsk, dependencies=[])\n self.dask = dsk\n self._name = name\n meta = dd.core.make_meta(meta)\n if not isinstance(meta, self._partition_type):\n raise TypeError(\n f\"Expected meta to specify type \"\n f\"{self._partition_type.__name__}, got type \"\n f\"{type(meta).__name__}\"\n )\n self._meta = meta\n self.divisions = tuple(divisions)\n\n def __getstate__(self):\n return (self.dask, self._name, self._meta, self.divisions)\n\n def __setstate__(self, state):\n self.dask, self._name, self._meta, self.divisions = state\n\n def __repr__(self):\n s = \"<dask_cudf.%s | %d tasks | %d npartitions>\"\n return s % (type(self).__name__, len(self.dask), self.npartitions)\n\n def to_dask_dataframe(self, **kwargs):\n \"\"\"Create a dask.dataframe object from a dask_cudf object\"\"\"\n nullable_pd_dtype = kwargs.get(\"nullable_pd_dtype\", False)\n return self.map_partitions(\n M.to_pandas, nullable_pd_dtype=nullable_pd_dtype\n )\n\n\nconcat = dd.concat\n\n\nnormalize_token.register(_Frame, lambda a: a._name)\n\n\nclass DataFrame(_Frame, dd.core.DataFrame):\n _partition_type = cudf.DataFrame\n\n def _assign_column(self, k, v):\n def assigner(df, k, v):\n out = df.copy()\n out[k] = v\n return out\n\n meta = assigner(self._meta, k, dd.core.make_meta(v))\n return self.map_partitions(assigner, k, v, meta=meta)\n\n def apply_rows(self, func, incols, outcols, kwargs=None, cache_key=None):\n import uuid\n\n if kwargs is None:\n kwargs = {}\n\n if cache_key is None:\n cache_key = uuid.uuid4()\n\n def do_apply_rows(df, func, incols, outcols, kwargs):\n return df.apply_rows(\n func, incols, outcols, kwargs, cache_key=cache_key\n )\n\n meta = do_apply_rows(self._meta, func, incols, outcols, kwargs)\n return self.map_partitions(\n do_apply_rows, func, incols, outcols, kwargs, meta=meta\n )\n\n def merge(self, other, **kwargs):\n if kwargs.pop(\"shuffle\", \"tasks\") != \"tasks\":\n raise ValueError(\n \"Dask-cudf only supports task based shuffling, got %s\"\n % kwargs[\"shuffle\"]\n )\n on = kwargs.pop(\"on\", None)\n if isinstance(on, tuple):\n on = list(on)\n return super().merge(other, on=on, shuffle=\"tasks\", **kwargs)\n\n def join(self, other, **kwargs):\n if kwargs.pop(\"shuffle\", \"tasks\") != \"tasks\":\n raise ValueError(\n \"Dask-cudf only supports task based shuffling, got %s\"\n % kwargs[\"shuffle\"]\n )\n\n # CuDF doesn't support \"right\" join yet\n how = kwargs.pop(\"how\", \"left\")\n if how == \"right\":\n return other.join(other=self, how=\"left\", **kwargs)\n\n on = kwargs.pop(\"on\", None)\n if isinstance(on, tuple):\n on = list(on)\n return super().join(other, how=how, on=on, shuffle=\"tasks\", **kwargs)\n\n def set_index(self, other, sorted=False, divisions=None, **kwargs):\n if kwargs.pop(\"shuffle\", \"tasks\") != \"tasks\":\n raise ValueError(\n \"Dask-cudf only supports task based shuffling, got %s\"\n % kwargs[\"shuffle\"]\n )\n pre_sorted = sorted\n del sorted\n\n if (\n divisions == \"quantile\"\n or isinstance(divisions, (cudf.DataFrame, cudf.Series))\n or (\n isinstance(other, str)\n and cudf.utils.dtypes.is_string_dtype(self[other].dtype)\n )\n ):\n\n # Let upstream-dask handle \"pre-sorted\" case\n if pre_sorted:\n return dd.shuffle.set_sorted_index(\n self, other, divisions=divisions, **kwargs\n )\n\n by = other\n if not isinstance(other, list):\n by = [by]\n if len(by) > 1:\n raise ValueError(\"Dask does not support MultiIndex (yet).\")\n if divisions == \"quantile\":\n divisions = None\n\n # Use dask_cudf's sort_values\n # TODO: Handle `sorted=True`\n df = self.sort_values(\n by,\n max_branch=kwargs.get(\"max_branch\", None),\n divisions=divisions,\n set_divisions=True,\n ignore_index=True,\n )\n\n # Ignore divisions if its a dataframe\n if isinstance(divisions, cudf.DataFrame):\n divisions = None\n\n # Set index and repartition\n df2 = df.map_partitions(\n sorting.set_index_post,\n index_name=other,\n drop=kwargs.get(\"drop\", True),\n column_dtype=df.columns.dtype,\n )\n npartitions = kwargs.get(\"npartitions\", self.npartitions)\n partition_size = kwargs.get(\"partition_size\", None)\n if partition_size:\n return df2.repartition(partition_size=partition_size)\n if not divisions and df2.npartitions != npartitions:\n return df2.repartition(npartitions=npartitions)\n if divisions and df2.npartitions != len(divisions) - 1:\n return df2.repartition(divisions=divisions)\n return df2\n\n return super().set_index(\n other,\n sorted=pre_sorted,\n shuffle=\"tasks\",\n divisions=divisions,\n **kwargs,\n )\n\n def sort_values(\n self,\n by,\n ignore_index=False,\n max_branch=None,\n divisions=None,\n set_divisions=False,\n **kwargs,\n ):\n if self.npartitions == 1:\n df = self.map_partitions(M.sort_values, by)\n else:\n df = sorting.sort_values(\n self,\n by,\n max_branch=max_branch,\n divisions=divisions,\n set_divisions=set_divisions,\n ignore_index=ignore_index,\n )\n\n if ignore_index:\n return df.reset_index(drop=True)\n return df\n\n def to_parquet(self, path, *args, **kwargs):\n \"\"\" Calls dask.dataframe.io.to_parquet with CudfEngine backend \"\"\"\n from dask_cudf.io import to_parquet\n\n return to_parquet(self, path, *args, **kwargs)\n\n def to_orc(self, path, **kwargs):\n \"\"\" Calls dask_cudf.io.to_orc \"\"\"\n from dask_cudf.io import to_orc\n\n return to_orc(self, path, **kwargs)\n\n @derived_from(pd.DataFrame)\n def var(\n self,\n axis=None,\n skipna=True,\n ddof=1,\n split_every=False,\n dtype=None,\n out=None,\n naive=False,\n ):\n axis = self._validate_axis(axis)\n meta = self._meta_nonempty.var(axis=axis, skipna=skipna)\n if axis == 1:\n result = map_partitions(\n M.var,\n self,\n meta=meta,\n token=self._token_prefix + \"var\",\n axis=axis,\n skipna=skipna,\n ddof=ddof,\n )\n return handle_out(out, result)\n elif naive:\n return _naive_var(self, meta, skipna, ddof, split_every, out)\n else:\n return _parallel_var(self, meta, skipna, split_every, out)\n\n def repartition(self, *args, **kwargs):\n \"\"\" Wraps dask.dataframe DataFrame.repartition method.\n Uses DataFrame.shuffle if `columns=` is specified.\n \"\"\"\n # TODO: Remove this function in future(0.17 release)\n columns = kwargs.pop(\"columns\", None)\n if columns:\n warnings.warn(\n \"The column argument will be removed from repartition in \"\n \" future versions of dask_cudf. Use DataFrame.shuffle().\",\n DeprecationWarning,\n )\n warnings.warn(\n \"Rearranging data by column hash. Divisions will lost. \"\n \"Set ignore_index=False to preserve Index values.\"\n )\n ignore_index = kwargs.pop(\"ignore_index\", True)\n return self.shuffle(\n on=columns, ignore_index=ignore_index, **kwargs\n )\n return super().repartition(*args, **kwargs)\n\n def shuffle(self, *args, **kwargs):\n \"\"\" Wraps dask.dataframe DataFrame.shuffle method\n \"\"\"\n shuffle_arg = kwargs.pop(\"shuffle\", None)\n if shuffle_arg and shuffle_arg != \"tasks\":\n raise ValueError(\"dask_cudf does not support disk-based shuffle.\")\n return super().shuffle(*args, shuffle=\"tasks\", **kwargs)\n\n def groupby(self, by=None, **kwargs):\n from .groupby import CudfDataFrameGroupBy\n\n return CudfDataFrameGroupBy(self, by=by, **kwargs)\n\n\ndef sum_of_squares(x):\n x = x.astype(\"f8\")._column\n outcol = libcudf.reduce.reduce(\"sum_of_squares\", x)\n return cudf.Series(outcol)\n\n\ndef var_aggregate(x2, x, n, ddof):\n try:\n with warnings.catch_warnings(record=True):\n warnings.simplefilter(\"always\")\n result = (x2 / n) - (x / n) ** 2\n if ddof != 0:\n result = result * n / (n - ddof)\n return result\n except ZeroDivisionError:\n return np.float64(np.nan)\n\n\ndef nlargest_agg(x, **kwargs):\n return cudf.concat(x).nlargest(**kwargs)\n\n\ndef nsmallest_agg(x, **kwargs):\n return cudf.concat(x).nsmallest(**kwargs)\n\n\nclass Series(_Frame, dd.core.Series):\n _partition_type = cudf.Series\n\n def count(self, split_every=False):\n return reduction(\n [self],\n chunk=M.count,\n aggregate=np.sum,\n split_every=split_every,\n meta=\"i8\",\n )\n\n def mean(self, split_every=False):\n sum = self.sum(split_every=split_every)\n n = self.count(split_every=split_every)\n return sum / n\n\n @derived_from(pd.DataFrame)\n def var(\n self,\n axis=None,\n skipna=True,\n ddof=1,\n split_every=False,\n dtype=None,\n out=None,\n naive=False,\n ):\n axis = self._validate_axis(axis)\n meta = self._meta_nonempty.var(axis=axis, skipna=skipna)\n if axis == 1:\n result = map_partitions(\n M.var,\n self,\n meta=meta,\n token=self._token_prefix + \"var\",\n axis=axis,\n skipna=skipna,\n ddof=ddof,\n )\n return handle_out(out, result)\n elif naive:\n return _naive_var(self, meta, skipna, ddof, split_every, out)\n else:\n return _parallel_var(self, meta, skipna, split_every, out)\n\n def groupby(self, *args, **kwargs):\n from .groupby import CudfSeriesGroupBy\n\n return CudfSeriesGroupBy(self, *args, **kwargs)\n\n @property\n def list(self):\n return ListMethods(self)\n\n\nclass Index(Series, dd.core.Index):\n _partition_type = cudf.Index\n\n\ndef _naive_var(ddf, meta, skipna, ddof, split_every, out):\n num = ddf._get_numeric_data()\n x = 1.0 * num.sum(skipna=skipna, split_every=split_every)\n x2 = 1.0 * (num ** 2).sum(skipna=skipna, split_every=split_every)\n n = num.count(split_every=split_every)\n name = ddf._token_prefix + \"var\"\n result = map_partitions(\n var_aggregate, x2, x, n, token=name, meta=meta, ddof=ddof\n )\n if isinstance(ddf, DataFrame):\n result.divisions = (min(ddf.columns), max(ddf.columns))\n return handle_out(out, result)\n\n\ndef _parallel_var(ddf, meta, skipna, split_every, out):\n def _local_var(x, skipna):\n if skipna:\n n = x.count(skipna=skipna)\n avg = x.mean(skipna=skipna)\n else:\n # Not skipping nulls, so might as well\n # avoid the full `count` operation\n n = len(x)\n avg = x.sum(skipna=skipna) / n\n m2 = ((x - avg) ** 2).sum(skipna=skipna)\n return n, avg, m2\n\n def _aggregate_var(parts):\n n, avg, m2 = parts[0]\n for i in range(1, len(parts)):\n n_a, avg_a, m2_a = n, avg, m2\n n_b, avg_b, m2_b = parts[i]\n n = n_a + n_b\n avg = (n_a * avg_a + n_b * avg_b) / n\n delta = avg_b - avg_a\n m2 = m2_a + m2_b + delta ** 2 * n_a * n_b / n\n return n, avg, m2\n\n def _finalize_var(vals):\n n, _, m2 = vals\n return m2 / (n - 1)\n\n # Build graph\n nparts = ddf.npartitions\n if not split_every:\n split_every = nparts\n name = \"var-\" + tokenize(skipna, split_every, out)\n local_name = \"local-\" + name\n num = ddf._get_numeric_data()\n dsk = {\n (local_name, n, 0): (_local_var, (num._name, n), skipna)\n for n in range(nparts)\n }\n\n # Use reduction tree\n widths = [nparts]\n while nparts > 1:\n nparts = math.ceil(nparts / split_every)\n widths.append(nparts)\n height = len(widths)\n for depth in range(1, height):\n for group in range(widths[depth]):\n p_max = widths[depth - 1]\n lstart = split_every * group\n lstop = min(lstart + split_every, p_max)\n node_list = [\n (local_name, p, depth - 1) for p in range(lstart, lstop)\n ]\n dsk[(local_name, group, depth)] = (_aggregate_var, node_list)\n if height == 1:\n group = depth = 0\n dsk[(name, 0)] = (_finalize_var, (local_name, group, depth))\n\n graph = HighLevelGraph.from_collections(name, dsk, dependencies=[num, ddf])\n result = dd.core.new_dd_object(graph, name, meta, (None, None))\n if isinstance(ddf, DataFrame):\n result.divisions = (min(ddf.columns), max(ddf.columns))\n return handle_out(out, result)\n\n\ndef _extract_meta(x):\n \"\"\"\n Extract internal cache data (``_meta``) from dask_cudf objects\n \"\"\"\n if isinstance(x, (Scalar, _Frame)):\n return x._meta\n elif isinstance(x, list):\n return [_extract_meta(_x) for _x in x]\n elif isinstance(x, tuple):\n return tuple([_extract_meta(_x) for _x in x])\n elif isinstance(x, dict):\n return {k: _extract_meta(v) for k, v in x.items()}\n return x\n\n\ndef _emulate(func, *args, **kwargs):\n \"\"\"\n Apply a function using args / kwargs. If arguments contain dd.DataFrame /\n dd.Series, using internal cache (``_meta``) for calculation\n \"\"\"\n with raise_on_meta_error(funcname(func)):\n return func(*_extract_meta(args), **_extract_meta(kwargs))\n\n\ndef align_partitions(args):\n \"\"\"Align partitions between dask_cudf objects.\n\n Note that if all divisions are unknown, but have equal npartitions, then\n they will be passed through unchanged.\"\"\"\n dfs = [df for df in args if isinstance(df, _Frame)]\n if not dfs:\n return args\n\n divisions = dfs[0].divisions\n if not all(df.divisions == divisions for df in dfs):\n raise NotImplementedError(\"Aligning mismatched partitions\")\n return args\n\n\ndef reduction(\n args,\n chunk=None,\n aggregate=None,\n combine=None,\n meta=None,\n token=None,\n chunk_kwargs=None,\n aggregate_kwargs=None,\n combine_kwargs=None,\n split_every=None,\n **kwargs,\n):\n \"\"\"Generic tree reduction operation.\n\n Parameters\n ----------\n args :\n Positional arguments for the `chunk` function. All `dask.dataframe`\n objects should be partitioned and indexed equivalently.\n chunk : function [block-per-arg] -> block\n Function to operate on each block of data\n aggregate : function list-of-blocks -> block\n Function to operate on the list of results of chunk\n combine : function list-of-blocks -> block, optional\n Function to operate on intermediate lists of results of chunk\n in a tree-reduction. If not provided, defaults to aggregate.\n $META\n token : str, optional\n The name to use for the output keys.\n chunk_kwargs : dict, optional\n Keywords for the chunk function only.\n aggregate_kwargs : dict, optional\n Keywords for the aggregate function only.\n combine_kwargs : dict, optional\n Keywords for the combine function only.\n split_every : int, optional\n Group partitions into groups of this size while performing a\n tree-reduction. If set to False, no tree-reduction will be used,\n and all intermediates will be concatenated and passed to ``aggregate``.\n Default is 8.\n kwargs :\n All remaining keywords will be passed to ``chunk``, ``aggregate``, and\n ``combine``.\n \"\"\"\n if chunk_kwargs is None:\n chunk_kwargs = dict()\n if aggregate_kwargs is None:\n aggregate_kwargs = dict()\n chunk_kwargs.update(kwargs)\n aggregate_kwargs.update(kwargs)\n\n if combine is None:\n if combine_kwargs:\n raise ValueError(\"`combine_kwargs` provided with no `combine`\")\n combine = aggregate\n combine_kwargs = aggregate_kwargs\n else:\n if combine_kwargs is None:\n combine_kwargs = dict()\n combine_kwargs.update(kwargs)\n\n if not isinstance(args, (tuple, list)):\n args = [args]\n\n npartitions = set(\n arg.npartitions for arg in args if isinstance(arg, _Frame)\n )\n if len(npartitions) > 1:\n raise ValueError(\"All arguments must have same number of partitions\")\n npartitions = npartitions.pop()\n\n if split_every is None:\n split_every = 8\n elif split_every is False:\n split_every = npartitions\n elif split_every < 2 or not isinstance(split_every, int):\n raise ValueError(\"split_every must be an integer >= 2\")\n\n token_key = tokenize(\n token or (chunk, aggregate),\n meta,\n args,\n chunk_kwargs,\n aggregate_kwargs,\n combine_kwargs,\n split_every,\n )\n\n # Chunk\n a = \"{0}-chunk-{1}\".format(token or funcname(chunk), token_key)\n if len(args) == 1 and isinstance(args[0], _Frame) and not chunk_kwargs:\n dsk = {\n (a, 0, i): (chunk, key)\n for i, key in enumerate(args[0].__dask_keys__())\n }\n else:\n dsk = {\n (a, 0, i): (\n apply,\n chunk,\n [(x._name, i) if isinstance(x, _Frame) else x for x in args],\n chunk_kwargs,\n )\n for i in range(args[0].npartitions)\n }\n\n # Combine\n b = \"{0}-combine-{1}\".format(token or funcname(combine), token_key)\n k = npartitions\n depth = 0\n while k > split_every:\n for part_i, inds in enumerate(partition_all(split_every, range(k))):\n conc = (list, [(a, depth, i) for i in inds])\n dsk[(b, depth + 1, part_i)] = (\n (apply, combine, [conc], combine_kwargs)\n if combine_kwargs\n else (combine, conc)\n )\n k = part_i + 1\n a = b\n depth += 1\n\n # Aggregate\n b = \"{0}-agg-{1}\".format(token or funcname(aggregate), token_key)\n conc = (list, [(a, depth, i) for i in range(k)])\n if aggregate_kwargs:\n dsk[(b, 0)] = (apply, aggregate, [conc], aggregate_kwargs)\n else:\n dsk[(b, 0)] = (aggregate, conc)\n\n if meta is None:\n meta_chunk = _emulate(apply, chunk, args, chunk_kwargs)\n meta = _emulate(apply, aggregate, [[meta_chunk]], aggregate_kwargs)\n meta = dd.core.make_meta(meta)\n\n graph = HighLevelGraph.from_collections(b, dsk, dependencies=args)\n return dd.core.new_dd_object(graph, b, meta, (None, None))\n\n\ndef from_cudf(data, npartitions=None, chunksize=None, sort=True, name=None):\n if isinstance(getattr(data, \"index\", None), cudf.MultiIndex):\n raise NotImplementedError(\n \"dask_cudf does not support MultiIndex Dataframes.\"\n )\n\n name = name or (\"from_cudf-\" + tokenize(data, npartitions or chunksize))\n return dd.from_pandas(\n data,\n npartitions=npartitions,\n chunksize=chunksize,\n sort=sort,\n name=name,\n )\n\n\nfrom_cudf.__doc__ = (\n \"Wraps main-line Dask from_pandas...\\n\" + dd.from_pandas.__doc__\n)\n\n\ndef from_dask_dataframe(df):\n return df.map_partitions(cudf.from_pandas)\n\n\nfor name in [\n \"add\",\n \"sub\",\n \"mul\",\n \"truediv\",\n \"floordiv\",\n \"mod\",\n \"pow\",\n \"radd\",\n \"rsub\",\n \"rmul\",\n \"rtruediv\",\n \"rfloordiv\",\n \"rmod\",\n \"rpow\",\n]:\n meth = getattr(cudf.DataFrame, name)\n kwargs = {\"original\": cudf.DataFrame} if DASK_VERSION >= \"2.11.1\" else {}\n DataFrame._bind_operator_method(name, meth, **kwargs)\n\n meth = getattr(cudf.Series, name)\n kwargs = {\"original\": cudf.Series} if DASK_VERSION >= \"2.11.1\" else {}\n Series._bind_operator_method(name, meth, **kwargs)\n\nfor name in [\"lt\", \"gt\", \"le\", \"ge\", \"ne\", \"eq\"]:\n meth = getattr(cudf.Series, name)\n kwargs = {\"original\": cudf.Series} if DASK_VERSION >= \"2.11.1\" else {}\n Series._bind_comparison_method(name, meth, **kwargs)\n" ]
[ [ "pandas.Series", "pandas.DataFrame", "numpy.iinfo", "pandas.date_range", "numpy.array", "numpy.random.randint" ], [ "numpy.get_include" ], [ "numpy.testing.assert_equal", "pandas.Series", "numpy.random.seed", "numpy.arange", "pandas.DataFrame", "numpy.identity", "pandas.get_dummies", "numpy.random.randint" ], [ "pandas.Series", "pandas.DataFrame" ], [ "numpy.random.normal", "numpy.random.seed", "numpy.random.randint" ], [ "numpy.dot", "numpy.random.random", "numpy.unique", "numpy.linalg.norm", "numpy.concatenate", "numpy.linalg.det", "numpy.cov", "numpy.mean", "numpy.isscalar", "numpy.var", "numpy.random.uniform", "numpy.array", "numpy.sum" ], [ "numpy.float64" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.3", "0.19", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.3", "0.19", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.3", "0.19", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
stasbel/Meme-Machinery-VKHack2018
[ "5e15198d6bc8d350f2dc0158a34467f3415da0bc" ]
[ "experiments/download.py" ]
[ "\"\"\"Downloads prescribed data from the Internet, embed and store it.\"\"\"\n\nimport logging\n\nimport numpy as np\nimport torch\n\nfrom experiments.scrap import META_PATH\nfrom mem.gen.stages import Extractor\n\nlogger = logging.getLogger(__name__)\n\nMATRIX_PATH = 'matrix.npy'\nNEW_META_PATH = 'processed_reddit_data.pth'\n\n\ndef main(_):\n meta = torch.load(META_PATH)\n\n extractor = Extractor()\n meta, matrix = extractor.extract(meta)\n\n torch.save(meta, NEW_META_PATH)\n logger.info(f'Obtain matrix of shape {matrix.shape}.')\n np.save(MATRIX_PATH, matrix)\n\n\ndef _parse_config():\n logging.basicConfig(\n format='%(asctime)s | %(message)s',\n handlers=[\n logging.StreamHandler()\n ],\n level=logging.INFO\n )\n\n\nif __name__ == '__main__':\n main(_parse_config())\n" ]
[ [ "torch.save", "numpy.save", "torch.load" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jiangyangby/DRDSC
[ "4b53e18626b9839578bea6c84bba47d15bc8d3d6" ]
[ "models.py" ]
[ "from __future__ import print_function, absolute_import, division\n\nimport tensorflow as tf\nfrom tensorflow.contrib import layers\n\nmu = 1.0e-6\n\n\[email protected]_gradient\ndef f_norm(x):\n f2 = tf.square(tf.norm(x, ord='fro', axis=[-2, -1]))\n f = tf.sqrt(f2 + mu ** 2) - mu\n def grad(dy):\n return dy * (x / tf.sqrt(f2 + mu ** 2))\n return f, grad\n\n\[email protected]_gradient\ndef l2_norm(x):\n f2 = tf.square(tf.norm(x, ord=2))\n f = tf.sqrt(f2 + mu ** 2) - mu\n def grad(dy):\n return dy * (x / tf.sqrt(f2 + mu ** 2))\n return f, grad\n\n\nclass RSCConvAE:\n '''\n Duet Robust Deep Subspace Clustering\n '''\n\n def __init__(self, n_input, kernel_size, n_hidden, z_dim, lamda1=1.0,\n lamda2=1.0, eta1=1.0, eta2=1.0, batch_size=200, reg=None,\n denoise=False, save_path=None, restore_path=None,\n normalize_input=False, logs_path='./logs'):\n self.n_input = n_input\n self.kernel_size = kernel_size\n self.n_hidden = n_hidden\n self.batch_size = batch_size\n self.z_dim = z_dim\n self.reg = reg\n self.save_path = save_path\n self.restore_path = restore_path\n self.iter = 0\n\n # input required to be fed\n self.x = tf.placeholder(tf.float32, [None, n_input[0], n_input[1], 1])\n self.learning_rate = tf.placeholder(tf.float32, [])\n\n weights = self._initialize_weights()\n self.x_noise = weights['x_noise']\n self.z_noise = weights['z_noise']\n\n self.z, self.Coef, self.x_r, self.x_diff, self.z_diff = \\\n self._forward(denoise, normalize_input, weights)\n\n # l_2 reconstruction loss\n self.reconst_cost = self._get_reconstruction_loss(eta1)\n tf.summary.scalar(\"recons_loss\", self.reconst_cost)\n\n self.reg_loss = self._get_coef_reg_loss(reg_type='l2') # l2 reg\n tf.summary.scalar(\"reg_loss\", lamda2 * self.reg_loss)\n\n selfexpress_cost = tf.square(self.z_diff - self.z_noise)\n z_noise_reg = tf.map_fn(lambda frame: l2_norm(frame), self.z_noise)\n self.selfexpress_loss = 0.5 * \\\n tf.reduce_sum(selfexpress_cost) + eta2 * tf.reduce_sum(z_noise_reg)\n tf.summary.scalar(\"selfexpress_loss\", lamda1 *\n self.selfexpress_loss)\n\n self.loss = self.reconst_cost + lamda1 * \\\n self.selfexpress_loss + lamda2 * self.reg_loss\n\n self.merged_summary_op = tf.summary.merge_all()\n self.optimizer = tf.train.AdamOptimizer(\n # self.optimizer = tf.train.GradientDescentOptimizer(\n learning_rate=self.learning_rate).minimize(self.loss)\n\n self.init = tf.global_variables_initializer()\n self.sess = tf.InteractiveSession()\n self.sess.run(self.init)\n self.saver = tf.train.Saver(\n [v for v in tf.trainable_variables() if not (v.name.startswith(\"Coef\"))])\n self.summary_writer = tf.summary.FileWriter(\n logs_path, graph=tf.get_default_graph())\n\n def _build_input(self, denoise, normalize_input):\n if not normalize_input:\n x_input = self.x\n else:\n x_input = tf.map_fn(\n lambda frame: tf.image.per_image_standardization(frame), self.x)\n if denoise:\n x_input = tf.add(self.x, tf.random_normal(shape=tf.shape(self.x),\n mean=0,\n stddev=0.2,\n dtype=tf.float32))\n return x_input\n\n def _forward(self, denoise, normalize_input, weights):\n x_input = self._build_input(denoise, normalize_input)\n latent, shape = self.encoder(x_input, weights)\n\n z = tf.reshape(latent, [self.batch_size, -1])\n Coef = weights['Coef']\n Coef = Coef - tf.diag(tf.diag_part(Coef))\n z_c = tf.matmul(Coef, z)\n latent_c = tf.reshape(z_c, tf.shape(latent))\n x_r = self.decoder(latent_c, weights, shape)\n z_diff = z - z_c\n x_diff = x_input - x_r\n return z, Coef, x_r, x_diff, z_diff\n\n def _get_reconstruction_loss(self, eta1):\n reconst_cost = tf.square(self.x_diff - self.x_noise) # l2\n x_noise_3dim = tf.squeeze(self.x_noise)\n x_noise_group_reg = tf.map_fn(\n lambda frame: f_norm(frame), x_noise_3dim)\n reconst_cost = 0.5 * tf.reduce_sum(reconst_cost) + \\\n eta1 * tf.reduce_sum(x_noise_group_reg)\n return reconst_cost\n\n def _get_coef_reg_loss(self, reg_type='l2'):\n if reg_type is 'l2':\n loss = tf.reduce_sum(tf.square(self.Coef))\n elif reg_type is 'l1':\n loss = tf.reduce_sum(tf.abs(self.Coef))\n return loss\n\n def _initialize_weights(self):\n all_weights = dict()\n n_layers = len(self.n_hidden)\n # all_weights['Coef'] = tf.Variable(\n # tf.random_normal([self.batch_size, self.batch_size],\n # mean=0.0, stddev=0.1, dtype=tf.float32,\n # seed=None), name='Coef')\n all_weights['Coef'] = tf.Variable(\n 0 * tf.ones([self.batch_size, self.batch_size], tf.float32), name='Coef')\n all_weights['x_noise'] = tf.Variable(\n tf.zeros([self.batch_size, self.n_input[0],\n self.n_input[1], 1], tf.float32), name='Coef')\n all_weights['z_noise'] = tf.Variable(\n tf.zeros([self.batch_size, self.z_dim], tf.float32), name='Coef')\n\n all_weights['enc_w0'] = tf.get_variable(\"enc_w0\", shape=[self.kernel_size[0], self.kernel_size[0], 1, self.n_hidden[0]],\n initializer=layers.xavier_initializer_conv2d(), regularizer=self.reg)\n all_weights['enc_b0'] = tf.Variable(\n tf.zeros([self.n_hidden[0]], dtype=tf.float32))\n\n for iter_i in range(1, n_layers):\n enc_name_wi = 'enc_w' + str(iter_i)\n all_weights[enc_name_wi] = tf.get_variable(enc_name_wi, shape=[self.kernel_size[iter_i], self.kernel_size[iter_i], self.n_hidden[iter_i - 1],\n self.n_hidden[iter_i]], initializer=layers.xavier_initializer_conv2d(), regularizer=self.reg)\n enc_name_bi = 'enc_b' + str(iter_i)\n all_weights[enc_name_bi] = tf.Variable(\n tf.zeros([self.n_hidden[iter_i]], dtype=tf.float32))\n\n for iter_i in range(1, n_layers):\n dec_name_wi = 'dec_w' + str(iter_i - 1)\n all_weights[dec_name_wi] = tf.get_variable(dec_name_wi, shape=[self.kernel_size[n_layers - iter_i], self.kernel_size[n_layers - iter_i],\n self.n_hidden[n_layers - iter_i - 1], self.n_hidden[n_layers - iter_i]],\n initializer=layers.xavier_initializer_conv2d(), regularizer=self.reg)\n dec_name_bi = 'dec_b' + str(iter_i - 1)\n all_weights[dec_name_bi] = tf.Variable(tf.zeros(\n [self.n_hidden[n_layers - iter_i - 1]], dtype=tf.float32))\n\n dec_name_wi = 'dec_w' + str(n_layers - 1)\n all_weights[dec_name_wi] = tf.get_variable(dec_name_wi, shape=[self.kernel_size[0], self.kernel_size[0], 1, self.n_hidden[0]],\n initializer=layers.xavier_initializer_conv2d(), regularizer=self.reg)\n dec_name_bi = 'dec_b' + str(n_layers - 1)\n all_weights[dec_name_bi] = tf.Variable(\n tf.zeros([1], dtype=tf.float32))\n\n return all_weights\n\n # Building the encoder\n def encoder(self, x, weights):\n shapes = []\n shapes.append(x.get_shape().as_list())\n layeri = tf.nn.bias_add(tf.nn.conv2d(x, weights['enc_w0'], strides=[\n 1, 2, 2, 1], padding='SAME'), weights['enc_b0'])\n layeri = tf.nn.relu(layeri)\n shapes.append(layeri.get_shape().as_list())\n\n for iter_i in range(1, len(self.n_hidden)):\n layeri = tf.nn.bias_add(tf.nn.conv2d(layeri, weights['enc_w' + str(iter_i)], strides=[\n 1, 2, 2, 1], padding='SAME'), weights['enc_b' + str(iter_i)])\n layeri = tf.nn.relu(layeri)\n shapes.append(layeri.get_shape().as_list())\n\n layer3 = layeri\n return layer3, shapes\n\n # Building the decoder\n def decoder(self, z, weights, shapes):\n n_layers = len(self.n_hidden)\n layer3 = z\n for iter_i in range(n_layers):\n shape_de = shapes[n_layers - iter_i - 1]\n layer3 = tf.add(tf.nn.conv2d_transpose(layer3, weights['dec_w' + str(iter_i)], tf.stack([tf.shape(self.x)[0], shape_de[1], shape_de[2], shape_de[3]]),\n strides=[1, 2, 2, 1], padding='SAME'), weights['dec_b' + str(iter_i)])\n layer3 = tf.nn.relu(layer3)\n return layer3\n\n def partial_fit(self, X, lr):\n cost, summary, _, Coef, z_diff, x_diff = self.sess.run(\n (self.loss, self.merged_summary_op, self.optimizer, self.Coef,\n self.z_diff, self.x_diff),\n feed_dict={self.x: X, self.learning_rate: lr})\n self.summary_writer.add_summary(summary, self.iter)\n self.iter = self.iter + 1\n return cost, Coef, z_diff, x_diff\n\n def initlization(self):\n self.sess.run(self.init)\n\n def reconstruct(self, X):\n return self.sess.run(self.x_r, feed_dict={self.x: X})\n\n def transform(self, X):\n return self.sess.run(self.z, feed_dict={self.x: X})\n\n def save_model(self):\n save_path = self.saver.save(self.sess, self.save_path)\n print(\"model saved in file: %s\" % save_path)\n\n def restore(self):\n self.saver.restore(self.sess, self.restore_path)\n print(\"model restored\")\n" ]
[ [ "tensorflow.zeros", "tensorflow.reduce_sum", "tensorflow.train.AdamOptimizer", "tensorflow.get_default_graph", "tensorflow.summary.scalar", "tensorflow.nn.conv2d", "tensorflow.diag_part", "tensorflow.squeeze", "tensorflow.square", "tensorflow.trainable_variables", "tensorflow.norm", "tensorflow.matmul", "tensorflow.InteractiveSession", "tensorflow.shape", "tensorflow.placeholder", "tensorflow.global_variables_initializer", "tensorflow.summary.merge_all", "tensorflow.image.per_image_standardization", "tensorflow.contrib.layers.xavier_initializer_conv2d", "tensorflow.nn.relu", "tensorflow.reshape", "tensorflow.ones", "tensorflow.sqrt", "tensorflow.abs" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
raijin0704/models
[ "6906bfbdbf2ad628bb6aeca9989dc04f605b6a60" ]
[ "research/object_detection/metrics/coco_evaluation.py" ]
[ "# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Class for evaluating object detections with COCO metrics.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nfrom six.moves import zip\nimport tensorflow.compat.v1 as tf\n\nfrom object_detection.core import standard_fields\nfrom object_detection.metrics import coco_tools\nfrom object_detection.utils import json_utils\nfrom object_detection.utils import np_mask_ops\nfrom object_detection.utils import object_detection_evaluation\n\n\nclass CocoDetectionEvaluator(object_detection_evaluation.DetectionEvaluator):\n \"\"\"Class to evaluate COCO detection metrics.\"\"\"\n\n def __init__(self,\n categories,\n include_metrics_per_category=False,\n all_metrics_per_category=False):\n \"\"\"Constructor.\n\n Args:\n categories: A list of dicts, each of which has the following keys -\n 'id': (required) an integer id uniquely identifying this category.\n 'name': (required) string representing category name e.g., 'cat', 'dog'.\n include_metrics_per_category: If True, include metrics for each category.\n all_metrics_per_category: Whether to include all the summary metrics for\n each category in per_category_ap. Be careful with setting it to true if\n you have more than handful of categories, because it will pollute\n your mldash.\n \"\"\"\n super(CocoDetectionEvaluator, self).__init__(categories)\n # _image_ids is a dictionary that maps unique image ids to Booleans which\n # indicate whether a corresponding detection has been added.\n self._image_ids = {}\n self._groundtruth_list = []\n self._detection_boxes_list = []\n self._category_id_set = set([cat['id'] for cat in self._categories])\n self._annotation_id = 1\n self._metrics = None\n self._include_metrics_per_category = include_metrics_per_category\n self._all_metrics_per_category = all_metrics_per_category\n\n def clear(self):\n \"\"\"Clears the state to prepare for a fresh evaluation.\"\"\"\n self._image_ids.clear()\n self._groundtruth_list = []\n self._detection_boxes_list = []\n\n def add_single_ground_truth_image_info(self,\n image_id,\n groundtruth_dict):\n \"\"\"Adds groundtruth for a single image to be used for evaluation.\n\n If the image has already been added, a warning is logged, and groundtruth is\n ignored.\n\n Args:\n image_id: A unique string/integer identifier for the image.\n groundtruth_dict: A dictionary containing -\n InputDataFields.groundtruth_boxes: float32 numpy array of shape\n [num_boxes, 4] containing `num_boxes` groundtruth boxes of the format\n [ymin, xmin, ymax, xmax] in absolute image coordinates.\n InputDataFields.groundtruth_classes: integer numpy array of shape\n [num_boxes] containing 1-indexed groundtruth classes for the boxes.\n InputDataFields.groundtruth_is_crowd (optional): integer numpy array of\n shape [num_boxes] containing iscrowd flag for groundtruth boxes.\n InputDataFields.groundtruth_area (optional): float numpy array of\n shape [num_boxes] containing the area (in the original absolute\n coordinates) of the annotated object.\n InputDataFields.groundtruth_keypoints (optional): float numpy array of\n keypoints with shape [num_boxes, num_keypoints, 2].\n InputDataFields.groundtruth_keypoint_visibilities (optional): integer\n numpy array of keypoint visibilities with shape [num_gt_boxes,\n num_keypoints]. Integer is treated as an enum with 0=not labeled,\n 1=labeled but not visible and 2=labeled and visible.\n \"\"\"\n if image_id in self._image_ids:\n tf.logging.warning('Ignoring ground truth with image id %s since it was '\n 'previously added', image_id)\n return\n\n # Drop optional fields if empty tensor.\n groundtruth_is_crowd = groundtruth_dict.get(\n standard_fields.InputDataFields.groundtruth_is_crowd)\n groundtruth_area = groundtruth_dict.get(\n standard_fields.InputDataFields.groundtruth_area)\n groundtruth_keypoints = groundtruth_dict.get(\n standard_fields.InputDataFields.groundtruth_keypoints)\n groundtruth_keypoint_visibilities = groundtruth_dict.get(\n standard_fields.InputDataFields.groundtruth_keypoint_visibilities)\n if groundtruth_is_crowd is not None and not groundtruth_is_crowd.shape[0]:\n groundtruth_is_crowd = None\n if groundtruth_area is not None and not groundtruth_area.shape[0]:\n groundtruth_area = None\n if groundtruth_keypoints is not None and not groundtruth_keypoints.shape[0]:\n groundtruth_keypoints = None\n if groundtruth_keypoint_visibilities is not None and not groundtruth_keypoint_visibilities.shape[\n 0]:\n groundtruth_keypoint_visibilities = None\n\n self._groundtruth_list.extend(\n coco_tools.ExportSingleImageGroundtruthToCoco(\n image_id=image_id,\n next_annotation_id=self._annotation_id,\n category_id_set=self._category_id_set,\n groundtruth_boxes=groundtruth_dict[\n standard_fields.InputDataFields.groundtruth_boxes],\n groundtruth_classes=groundtruth_dict[\n standard_fields.InputDataFields.groundtruth_classes],\n groundtruth_is_crowd=groundtruth_is_crowd,\n groundtruth_area=groundtruth_area,\n groundtruth_keypoints=groundtruth_keypoints,\n groundtruth_keypoint_visibilities=groundtruth_keypoint_visibilities)\n )\n\n self._annotation_id += groundtruth_dict[standard_fields.InputDataFields.\n groundtruth_boxes].shape[0]\n # Boolean to indicate whether a detection has been added for this image.\n self._image_ids[image_id] = False\n\n def add_single_detected_image_info(self,\n image_id,\n detections_dict):\n \"\"\"Adds detections for a single image to be used for evaluation.\n\n If a detection has already been added for this image id, a warning is\n logged, and the detection is skipped.\n\n Args:\n image_id: A unique string/integer identifier for the image.\n detections_dict: A dictionary containing -\n DetectionResultFields.detection_boxes: float32 numpy array of shape\n [num_boxes, 4] containing `num_boxes` detection boxes of the format\n [ymin, xmin, ymax, xmax] in absolute image coordinates.\n DetectionResultFields.detection_scores: float32 numpy array of shape\n [num_boxes] containing detection scores for the boxes.\n DetectionResultFields.detection_classes: integer numpy array of shape\n [num_boxes] containing 1-indexed detection classes for the boxes.\n DetectionResultFields.detection_keypoints (optional): float numpy array\n of keypoints with shape [num_boxes, num_keypoints, 2].\n Raises:\n ValueError: If groundtruth for the image_id is not available.\n \"\"\"\n if image_id not in self._image_ids:\n raise ValueError('Missing groundtruth for image id: {}'.format(image_id))\n\n if self._image_ids[image_id]:\n tf.logging.warning('Ignoring detection with image id %s since it was '\n 'previously added', image_id)\n return\n\n # Drop optional fields if empty tensor.\n detection_keypoints = detections_dict.get(\n standard_fields.DetectionResultFields.detection_keypoints)\n if detection_keypoints is not None and not detection_keypoints.shape[0]:\n detection_keypoints = None\n self._detection_boxes_list.extend(\n coco_tools.ExportSingleImageDetectionBoxesToCoco(\n image_id=image_id,\n category_id_set=self._category_id_set,\n detection_boxes=detections_dict[\n standard_fields.DetectionResultFields.detection_boxes],\n detection_scores=detections_dict[\n standard_fields.DetectionResultFields.detection_scores],\n detection_classes=detections_dict[\n standard_fields.DetectionResultFields.detection_classes],\n detection_keypoints=detection_keypoints))\n self._image_ids[image_id] = True\n\n def dump_detections_to_json_file(self, json_output_path):\n \"\"\"Saves the detections into json_output_path in the format used by MS COCO.\n\n Args:\n json_output_path: String containing the output file's path. It can be also\n None. In that case nothing will be written to the output file.\n \"\"\"\n if json_output_path and json_output_path is not None:\n with tf.gfile.GFile(json_output_path, 'w') as fid:\n tf.logging.info('Dumping detections to output json file.')\n json_utils.Dump(\n obj=self._detection_boxes_list, fid=fid, float_digits=4, indent=2)\n\n def evaluate(self):\n \"\"\"Evaluates the detection boxes and returns a dictionary of coco metrics.\n\n Returns:\n A dictionary holding -\n\n 1. summary_metrics:\n 'DetectionBoxes_Precision/mAP': mean average precision over classes\n averaged over IOU thresholds ranging from .5 to .95 with .05\n increments.\n 'DetectionBoxes_Precision/[email protected]': mean average precision at 50% IOU\n 'DetectionBoxes_Precision/[email protected]': mean average precision at 75% IOU\n 'DetectionBoxes_Precision/mAP (small)': mean average precision for small\n objects (area < 32^2 pixels).\n 'DetectionBoxes_Precision/mAP (medium)': mean average precision for\n medium sized objects (32^2 pixels < area < 96^2 pixels).\n 'DetectionBoxes_Precision/mAP (large)': mean average precision for large\n objects (96^2 pixels < area < 10000^2 pixels).\n 'DetectionBoxes_Recall/AR@1': average recall with 1 detection.\n 'DetectionBoxes_Recall/AR@10': average recall with 10 detections.\n 'DetectionBoxes_Recall/AR@100': average recall with 100 detections.\n 'DetectionBoxes_Recall/AR@100 (small)': average recall for small objects\n with 100.\n 'DetectionBoxes_Recall/AR@100 (medium)': average recall for medium objects\n with 100.\n 'DetectionBoxes_Recall/AR@100 (large)': average recall for large objects\n with 100 detections.\n\n 2. per_category_ap: if include_metrics_per_category is True, category\n specific results with keys of the form:\n 'Precision mAP ByCategory/category' (without the supercategory part if\n no supercategories exist). For backward compatibility\n 'PerformanceByCategory' is included in the output regardless of\n all_metrics_per_category.\n \"\"\"\n tf.logging.info('Performing evaluation on %d images.', len(self._image_ids))\n groundtruth_dict = {\n 'annotations': self._groundtruth_list,\n 'images': [{'id': image_id} for image_id in self._image_ids],\n 'categories': self._categories\n }\n coco_wrapped_groundtruth = coco_tools.COCOWrapper(groundtruth_dict)\n coco_wrapped_detections = coco_wrapped_groundtruth.LoadAnnotations(\n self._detection_boxes_list)\n box_evaluator = coco_tools.COCOEvalWrapper(\n coco_wrapped_groundtruth, coco_wrapped_detections, agnostic_mode=False)\n box_metrics, box_per_category_ap = box_evaluator.ComputeMetrics(\n include_metrics_per_category=self._include_metrics_per_category,\n all_metrics_per_category=self._all_metrics_per_category)\n box_metrics.update(box_per_category_ap)\n box_metrics = {'DetectionBoxes_'+ key: value\n for key, value in iter(box_metrics.items())}\n return box_metrics\n\n def add_eval_dict(self, eval_dict):\n \"\"\"Observes an evaluation result dict for a single example.\n\n When executing eagerly, once all observations have been observed by this\n method you can use `.evaluate()` to get the final metrics.\n\n When using `tf.estimator.Estimator` for evaluation this function is used by\n `get_estimator_eval_metric_ops()` to construct the metric update op.\n\n Args:\n eval_dict: A dictionary that holds tensors for evaluating an object\n detection model, returned from\n eval_util.result_dict_for_single_example().\n\n Returns:\n None when executing eagerly, or an update_op that can be used to update\n the eval metrics in `tf.estimator.EstimatorSpec`.\n \"\"\"\n def update_op(\n image_id_batched,\n groundtruth_boxes_batched,\n groundtruth_classes_batched,\n groundtruth_is_crowd_batched,\n num_gt_boxes_per_image,\n detection_boxes_batched,\n detection_scores_batched,\n detection_classes_batched,\n num_det_boxes_per_image,\n is_annotated_batched):\n \"\"\"Update operation for adding batch of images to Coco evaluator.\"\"\"\n\n for (image_id, gt_box, gt_class, gt_is_crowd, num_gt_box, det_box,\n det_score, det_class, num_det_box, is_annotated) in zip(\n image_id_batched, groundtruth_boxes_batched,\n groundtruth_classes_batched, groundtruth_is_crowd_batched,\n num_gt_boxes_per_image,\n detection_boxes_batched, detection_scores_batched,\n detection_classes_batched, num_det_boxes_per_image,\n is_annotated_batched):\n if is_annotated:\n self.add_single_ground_truth_image_info(\n image_id, {\n 'groundtruth_boxes': gt_box[:num_gt_box],\n 'groundtruth_classes': gt_class[:num_gt_box],\n 'groundtruth_is_crowd': gt_is_crowd[:num_gt_box]\n })\n self.add_single_detected_image_info(\n image_id,\n {'detection_boxes': det_box[:num_det_box],\n 'detection_scores': det_score[:num_det_box],\n 'detection_classes': det_class[:num_det_box]})\n\n # Unpack items from the evaluation dictionary.\n input_data_fields = standard_fields.InputDataFields\n detection_fields = standard_fields.DetectionResultFields\n image_id = eval_dict[input_data_fields.key]\n groundtruth_boxes = eval_dict[input_data_fields.groundtruth_boxes]\n groundtruth_classes = eval_dict[input_data_fields.groundtruth_classes]\n groundtruth_is_crowd = eval_dict.get(\n input_data_fields.groundtruth_is_crowd, None)\n detection_boxes = eval_dict[detection_fields.detection_boxes]\n detection_scores = eval_dict[detection_fields.detection_scores]\n detection_classes = eval_dict[detection_fields.detection_classes]\n num_gt_boxes_per_image = eval_dict.get(\n 'num_groundtruth_boxes_per_image', None)\n num_det_boxes_per_image = eval_dict.get('num_det_boxes_per_image', None)\n is_annotated = eval_dict.get('is_annotated', None)\n\n if groundtruth_is_crowd is None:\n groundtruth_is_crowd = tf.zeros_like(groundtruth_classes, dtype=tf.bool)\n if not image_id.shape.as_list():\n # Apply a batch dimension to all tensors.\n image_id = tf.expand_dims(image_id, 0)\n groundtruth_boxes = tf.expand_dims(groundtruth_boxes, 0)\n groundtruth_classes = tf.expand_dims(groundtruth_classes, 0)\n groundtruth_is_crowd = tf.expand_dims(groundtruth_is_crowd, 0)\n detection_boxes = tf.expand_dims(detection_boxes, 0)\n detection_scores = tf.expand_dims(detection_scores, 0)\n detection_classes = tf.expand_dims(detection_classes, 0)\n\n if num_gt_boxes_per_image is None:\n num_gt_boxes_per_image = tf.shape(groundtruth_boxes)[1:2]\n else:\n num_gt_boxes_per_image = tf.expand_dims(num_gt_boxes_per_image, 0)\n\n if num_det_boxes_per_image is None:\n num_det_boxes_per_image = tf.shape(detection_boxes)[1:2]\n else:\n num_det_boxes_per_image = tf.expand_dims(num_det_boxes_per_image, 0)\n\n if is_annotated is None:\n is_annotated = tf.constant([True])\n else:\n is_annotated = tf.expand_dims(is_annotated, 0)\n else:\n if num_gt_boxes_per_image is None:\n num_gt_boxes_per_image = tf.tile(\n tf.shape(groundtruth_boxes)[1:2],\n multiples=tf.shape(groundtruth_boxes)[0:1])\n if num_det_boxes_per_image is None:\n num_det_boxes_per_image = tf.tile(\n tf.shape(detection_boxes)[1:2],\n multiples=tf.shape(detection_boxes)[0:1])\n if is_annotated is None:\n is_annotated = tf.ones_like(image_id, dtype=tf.bool)\n\n return tf.py_func(update_op, [image_id,\n groundtruth_boxes,\n groundtruth_classes,\n groundtruth_is_crowd,\n num_gt_boxes_per_image,\n detection_boxes,\n detection_scores,\n detection_classes,\n num_det_boxes_per_image,\n is_annotated], [])\n\n def get_estimator_eval_metric_ops(self, eval_dict):\n \"\"\"Returns a dictionary of eval metric ops.\n\n Note that once value_op is called, the detections and groundtruth added via\n update_op are cleared.\n\n This function can take in groundtruth and detections for a batch of images,\n or for a single image. For the latter case, the batch dimension for input\n tensors need not be present.\n\n Args:\n eval_dict: A dictionary that holds tensors for evaluating object detection\n performance. For single-image evaluation, this dictionary may be\n produced from eval_util.result_dict_for_single_example(). If multi-image\n evaluation, `eval_dict` should contain the fields\n 'num_groundtruth_boxes_per_image' and 'num_det_boxes_per_image' to\n properly unpad the tensors from the batch.\n\n Returns:\n a dictionary of metric names to tuple of value_op and update_op that can\n be used as eval metric ops in tf.estimator.EstimatorSpec. Note that all\n update ops must be run together and similarly all value ops must be run\n together to guarantee correct behaviour.\n \"\"\"\n update_op = self.add_eval_dict(eval_dict)\n metric_names = ['DetectionBoxes_Precision/mAP',\n 'DetectionBoxes_Precision/[email protected]',\n 'DetectionBoxes_Precision/[email protected]',\n 'DetectionBoxes_Precision/mAP (large)',\n 'DetectionBoxes_Precision/mAP (medium)',\n 'DetectionBoxes_Precision/mAP (small)',\n 'DetectionBoxes_Recall/AR@1',\n 'DetectionBoxes_Recall/AR@10',\n 'DetectionBoxes_Recall/AR@100',\n 'DetectionBoxes_Recall/AR@100 (large)',\n 'DetectionBoxes_Recall/AR@100 (medium)',\n 'DetectionBoxes_Recall/AR@100 (small)']\n if self._include_metrics_per_category:\n for category_dict in self._categories:\n metric_names.append('DetectionBoxes_PerformanceByCategory/mAP/' +\n category_dict['name'])\n\n def first_value_func():\n self._metrics = self.evaluate()\n self.clear()\n return np.float32(self._metrics[metric_names[0]])\n\n def value_func_factory(metric_name):\n def value_func():\n return np.float32(self._metrics[metric_name])\n return value_func\n\n # Ensure that the metrics are only evaluated once.\n first_value_op = tf.py_func(first_value_func, [], tf.float32)\n eval_metric_ops = {metric_names[0]: (first_value_op, update_op)}\n with tf.control_dependencies([first_value_op]):\n for metric_name in metric_names[1:]:\n eval_metric_ops[metric_name] = (tf.py_func(\n value_func_factory(metric_name), [], np.float32), update_op)\n return eval_metric_ops\n\n\ndef convert_masks_to_binary(masks):\n \"\"\"Converts masks to 0 or 1 and uint8 type.\"\"\"\n return (masks > 0).astype(np.uint8)\n\n\nclass CocoKeypointEvaluator(CocoDetectionEvaluator):\n \"\"\"Class to evaluate COCO keypoint metrics.\"\"\"\n\n def __init__(self,\n category_id,\n category_keypoints,\n class_text,\n oks_sigmas=None):\n \"\"\"Constructor.\n\n Args:\n category_id: An integer id uniquely identifying this category.\n category_keypoints: A list specifying keypoint mappings, with items:\n 'id': (required) an integer id identifying the keypoint.\n 'name': (required) a string representing the keypoint name.\n class_text: A string representing the category name for which keypoint\n metrics are to be computed.\n oks_sigmas: A dict of keypoint name to standard deviation values for OKS\n metrics. If not provided, default value of 0.05 will be used.\n \"\"\"\n self._category_id = category_id\n self._category_name = class_text\n self._keypoint_ids = sorted(\n [keypoint['id'] for keypoint in category_keypoints])\n kpt_id_to_name = {kpt['id']: kpt['name'] for kpt in category_keypoints}\n if oks_sigmas:\n self._oks_sigmas = np.array([\n oks_sigmas[kpt_id_to_name[idx]] for idx in self._keypoint_ids\n ])\n else:\n # Default all per-keypoint sigmas to 0.\n self._oks_sigmas = np.full((len(self._keypoint_ids)), 0.05)\n tf.logging.warning('No default keypoint OKS sigmas provided. Will use '\n '0.05')\n tf.logging.info('Using the following keypoint OKS sigmas: {}'.format(\n self._oks_sigmas))\n self._metrics = None\n super(CocoKeypointEvaluator, self).__init__([{\n 'id': self._category_id,\n 'name': class_text\n }])\n\n def add_single_ground_truth_image_info(self, image_id, groundtruth_dict):\n \"\"\"Adds groundtruth for a single image with keypoints.\n\n If the image has already been added, a warning is logged, and groundtruth\n is ignored.\n\n Args:\n image_id: A unique string/integer identifier for the image.\n groundtruth_dict: A dictionary containing -\n InputDataFields.groundtruth_boxes: float32 numpy array of shape\n [num_boxes, 4] containing `num_boxes` groundtruth boxes of the format\n [ymin, xmin, ymax, xmax] in absolute image coordinates.\n InputDataFields.groundtruth_classes: integer numpy array of shape\n [num_boxes] containing 1-indexed groundtruth classes for the boxes.\n InputDataFields.groundtruth_is_crowd (optional): integer numpy array of\n shape [num_boxes] containing iscrowd flag for groundtruth boxes.\n InputDataFields.groundtruth_area (optional): float numpy array of\n shape [num_boxes] containing the area (in the original absolute\n coordinates) of the annotated object.\n InputDataFields.groundtruth_keypoints: float numpy array of\n keypoints with shape [num_boxes, num_keypoints, 2].\n InputDataFields.groundtruth_keypoint_visibilities (optional): integer\n numpy array of keypoint visibilities with shape [num_gt_boxes,\n num_keypoints]. Integer is treated as an enum with 0=not labels,\n 1=labeled but not visible and 2=labeled and visible.\n \"\"\"\n\n # Keep only the groundtruth for our category and its keypoints.\n groundtruth_classes = groundtruth_dict[\n standard_fields.InputDataFields.groundtruth_classes]\n groundtruth_boxes = groundtruth_dict[\n standard_fields.InputDataFields.groundtruth_boxes]\n groundtruth_keypoints = groundtruth_dict[\n standard_fields.InputDataFields.groundtruth_keypoints]\n class_indices = [\n idx for idx, gt_class_id in enumerate(groundtruth_classes)\n if gt_class_id == self._category_id\n ]\n filtered_groundtruth_classes = np.take(\n groundtruth_classes, class_indices, axis=0)\n filtered_groundtruth_boxes = np.take(\n groundtruth_boxes, class_indices, axis=0)\n filtered_groundtruth_keypoints = np.take(\n groundtruth_keypoints, class_indices, axis=0)\n filtered_groundtruth_keypoints = np.take(\n filtered_groundtruth_keypoints, self._keypoint_ids, axis=1)\n\n filtered_groundtruth_dict = {}\n filtered_groundtruth_dict[\n standard_fields.InputDataFields\n .groundtruth_classes] = filtered_groundtruth_classes\n filtered_groundtruth_dict[standard_fields.InputDataFields\n .groundtruth_boxes] = filtered_groundtruth_boxes\n filtered_groundtruth_dict[\n standard_fields.InputDataFields\n .groundtruth_keypoints] = filtered_groundtruth_keypoints\n\n if (standard_fields.InputDataFields.groundtruth_is_crowd in\n groundtruth_dict.keys()):\n groundtruth_is_crowd = groundtruth_dict[\n standard_fields.InputDataFields.groundtruth_is_crowd]\n filtered_groundtruth_is_crowd = np.take(groundtruth_is_crowd,\n class_indices, 0)\n filtered_groundtruth_dict[\n standard_fields.InputDataFields\n .groundtruth_is_crowd] = filtered_groundtruth_is_crowd\n if (standard_fields.InputDataFields.groundtruth_area in\n groundtruth_dict.keys()):\n groundtruth_area = groundtruth_dict[\n standard_fields.InputDataFields.groundtruth_area]\n filtered_groundtruth_area = np.take(groundtruth_area, class_indices, 0)\n filtered_groundtruth_dict[\n standard_fields.InputDataFields\n .groundtruth_area] = filtered_groundtruth_area\n if (standard_fields.InputDataFields.groundtruth_keypoint_visibilities in\n groundtruth_dict.keys()):\n groundtruth_keypoint_visibilities = groundtruth_dict[\n standard_fields.InputDataFields.groundtruth_keypoint_visibilities]\n filtered_groundtruth_keypoint_visibilities = np.take(\n groundtruth_keypoint_visibilities, class_indices, axis=0)\n filtered_groundtruth_keypoint_visibilities = np.take(\n filtered_groundtruth_keypoint_visibilities,\n self._keypoint_ids,\n axis=1)\n filtered_groundtruth_dict[\n standard_fields.InputDataFields.\n groundtruth_keypoint_visibilities] = filtered_groundtruth_keypoint_visibilities\n\n super(CocoKeypointEvaluator,\n self).add_single_ground_truth_image_info(image_id,\n filtered_groundtruth_dict)\n\n def add_single_detected_image_info(self, image_id, detections_dict):\n \"\"\"Adds detections for a single image and the specific category for which keypoints are evaluated.\n\n If a detection has already been added for this image id, a warning is\n logged, and the detection is skipped.\n\n Args:\n image_id: A unique string/integer identifier for the image.\n detections_dict: A dictionary containing -\n DetectionResultFields.detection_boxes: float32 numpy array of shape\n [num_boxes, 4] containing `num_boxes` detection boxes of the format\n [ymin, xmin, ymax, xmax] in absolute image coordinates.\n DetectionResultFields.detection_scores: float32 numpy array of shape\n [num_boxes] containing detection scores for the boxes.\n DetectionResultFields.detection_classes: integer numpy array of shape\n [num_boxes] containing 1-indexed detection classes for the boxes.\n DetectionResultFields.detection_keypoints: float numpy array of\n keypoints with shape [num_boxes, num_keypoints, 2].\n\n Raises:\n ValueError: If groundtruth for the image_id is not available.\n \"\"\"\n\n # Keep only the detections for our category and its keypoints.\n detection_classes = detections_dict[\n standard_fields.DetectionResultFields.detection_classes]\n detection_boxes = detections_dict[\n standard_fields.DetectionResultFields.detection_boxes]\n detection_scores = detections_dict[\n standard_fields.DetectionResultFields.detection_scores]\n detection_keypoints = detections_dict[\n standard_fields.DetectionResultFields.detection_keypoints]\n class_indices = [\n idx for idx, class_id in enumerate(detection_classes)\n if class_id == self._category_id\n ]\n filtered_detection_classes = np.take(\n detection_classes, class_indices, axis=0)\n filtered_detection_boxes = np.take(detection_boxes, class_indices, axis=0)\n filtered_detection_scores = np.take(detection_scores, class_indices, axis=0)\n filtered_detection_keypoints = np.take(\n detection_keypoints, class_indices, axis=0)\n filtered_detection_keypoints = np.take(\n filtered_detection_keypoints, self._keypoint_ids, axis=1)\n\n filtered_detections_dict = {}\n filtered_detections_dict[standard_fields.DetectionResultFields\n .detection_classes] = filtered_detection_classes\n filtered_detections_dict[standard_fields.DetectionResultFields\n .detection_boxes] = filtered_detection_boxes\n filtered_detections_dict[standard_fields.DetectionResultFields\n .detection_scores] = filtered_detection_scores\n filtered_detections_dict[standard_fields.DetectionResultFields.\n detection_keypoints] = filtered_detection_keypoints\n\n super(CocoKeypointEvaluator,\n self).add_single_detected_image_info(image_id,\n filtered_detections_dict)\n\n def evaluate(self):\n \"\"\"Evaluates the keypoints and returns a dictionary of coco metrics.\n\n Returns:\n A dictionary holding -\n\n 1. summary_metrics:\n 'Keypoints_Precision/mAP': mean average precision over classes\n averaged over OKS thresholds ranging from .5 to .95 with .05\n increments.\n 'Keypoints_Precision/[email protected]': mean average precision at 50% OKS\n 'Keypoints_Precision/[email protected]': mean average precision at 75% OKS\n 'Keypoints_Precision/mAP (medium)': mean average precision for medium\n sized objects (32^2 pixels < area < 96^2 pixels).\n 'Keypoints_Precision/mAP (large)': mean average precision for large\n objects (96^2 pixels < area < 10000^2 pixels).\n 'Keypoints_Recall/AR@1': average recall with 1 detection.\n 'Keypoints_Recall/AR@10': average recall with 10 detections.\n 'Keypoints_Recall/AR@100': average recall with 100 detections.\n 'Keypoints_Recall/AR@100 (medium)': average recall for medium objects with\n 100.\n 'Keypoints_Recall/AR@100 (large)': average recall for large objects with\n 100 detections.\n \"\"\"\n tf.logging.info('Performing evaluation on %d images.', len(self._image_ids))\n groundtruth_dict = {\n 'annotations': self._groundtruth_list,\n 'images': [{'id': image_id} for image_id in self._image_ids],\n 'categories': self._categories\n }\n coco_wrapped_groundtruth = coco_tools.COCOWrapper(\n groundtruth_dict, detection_type='bbox')\n coco_wrapped_detections = coco_wrapped_groundtruth.LoadAnnotations(\n self._detection_boxes_list)\n keypoint_evaluator = coco_tools.COCOEvalWrapper(\n coco_wrapped_groundtruth,\n coco_wrapped_detections,\n agnostic_mode=False,\n iou_type='keypoints',\n oks_sigmas=self._oks_sigmas)\n keypoint_metrics, _ = keypoint_evaluator.ComputeMetrics(\n include_metrics_per_category=False, all_metrics_per_category=False)\n keypoint_metrics = {\n 'Keypoints_' + key: value\n for key, value in iter(keypoint_metrics.items())\n }\n return keypoint_metrics\n\n def add_eval_dict(self, eval_dict):\n \"\"\"Observes an evaluation result dict for a single example.\n\n When executing eagerly, once all observations have been observed by this\n method you can use `.evaluate()` to get the final metrics.\n\n When using `tf.estimator.Estimator` for evaluation this function is used by\n `get_estimator_eval_metric_ops()` to construct the metric update op.\n\n Args:\n eval_dict: A dictionary that holds tensors for evaluating an object\n detection model, returned from\n eval_util.result_dict_for_single_example().\n\n Returns:\n None when executing eagerly, or an update_op that can be used to update\n the eval metrics in `tf.estimator.EstimatorSpec`.\n \"\"\"\n def update_op(\n image_id_batched,\n groundtruth_boxes_batched,\n groundtruth_classes_batched,\n groundtruth_is_crowd_batched,\n groundtruth_area_batched,\n groundtruth_keypoints_batched,\n groundtruth_keypoint_visibilities_batched,\n num_gt_boxes_per_image,\n detection_boxes_batched,\n detection_scores_batched,\n detection_classes_batched,\n detection_keypoints_batched,\n num_det_boxes_per_image,\n is_annotated_batched):\n \"\"\"Update operation for adding batch of images to Coco evaluator.\"\"\"\n\n for (image_id, gt_box, gt_class, gt_is_crowd, gt_area, gt_keyp,\n gt_keyp_vis, num_gt_box, det_box, det_score, det_class, det_keyp,\n num_det_box, is_annotated) in zip(\n image_id_batched, groundtruth_boxes_batched,\n groundtruth_classes_batched, groundtruth_is_crowd_batched,\n groundtruth_area_batched, groundtruth_keypoints_batched,\n groundtruth_keypoint_visibilities_batched,\n num_gt_boxes_per_image, detection_boxes_batched,\n detection_scores_batched, detection_classes_batched,\n detection_keypoints_batched, num_det_boxes_per_image,\n is_annotated_batched):\n if is_annotated:\n self.add_single_ground_truth_image_info(\n image_id, {\n 'groundtruth_boxes': gt_box[:num_gt_box],\n 'groundtruth_classes': gt_class[:num_gt_box],\n 'groundtruth_is_crowd': gt_is_crowd[:num_gt_box],\n 'groundtruth_area': gt_area[:num_gt_box],\n 'groundtruth_keypoints': gt_keyp[:num_gt_box],\n 'groundtruth_keypoint_visibilities': gt_keyp_vis[:num_gt_box]\n })\n self.add_single_detected_image_info(\n image_id, {\n 'detection_boxes': det_box[:num_det_box],\n 'detection_scores': det_score[:num_det_box],\n 'detection_classes': det_class[:num_det_box],\n 'detection_keypoints': det_keyp[:num_det_box],\n })\n\n # Unpack items from the evaluation dictionary.\n input_data_fields = standard_fields.InputDataFields\n detection_fields = standard_fields.DetectionResultFields\n image_id = eval_dict[input_data_fields.key]\n groundtruth_boxes = eval_dict[input_data_fields.groundtruth_boxes]\n groundtruth_classes = eval_dict[input_data_fields.groundtruth_classes]\n groundtruth_is_crowd = eval_dict.get(input_data_fields.groundtruth_is_crowd,\n None)\n groundtruth_area = eval_dict.get(input_data_fields.groundtruth_area, None)\n groundtruth_keypoints = eval_dict[input_data_fields.groundtruth_keypoints]\n groundtruth_keypoint_visibilities = eval_dict.get(\n input_data_fields.groundtruth_keypoint_visibilities, None)\n detection_boxes = eval_dict[detection_fields.detection_boxes]\n detection_scores = eval_dict[detection_fields.detection_scores]\n detection_classes = eval_dict[detection_fields.detection_classes]\n detection_keypoints = eval_dict[detection_fields.detection_keypoints]\n num_gt_boxes_per_image = eval_dict.get(\n 'num_groundtruth_boxes_per_image', None)\n num_det_boxes_per_image = eval_dict.get('num_det_boxes_per_image', None)\n is_annotated = eval_dict.get('is_annotated', None)\n\n if groundtruth_is_crowd is None:\n groundtruth_is_crowd = tf.zeros_like(groundtruth_classes, dtype=tf.bool)\n\n if groundtruth_area is None:\n groundtruth_area = tf.zeros_like(groundtruth_classes, dtype=tf.float32)\n\n if not image_id.shape.as_list():\n # Apply a batch dimension to all tensors.\n image_id = tf.expand_dims(image_id, 0)\n groundtruth_boxes = tf.expand_dims(groundtruth_boxes, 0)\n groundtruth_classes = tf.expand_dims(groundtruth_classes, 0)\n groundtruth_is_crowd = tf.expand_dims(groundtruth_is_crowd, 0)\n groundtruth_area = tf.expand_dims(groundtruth_area, 0)\n groundtruth_keypoints = tf.expand_dims(groundtruth_keypoints, 0)\n detection_boxes = tf.expand_dims(detection_boxes, 0)\n detection_scores = tf.expand_dims(detection_scores, 0)\n detection_classes = tf.expand_dims(detection_classes, 0)\n detection_keypoints = tf.expand_dims(detection_keypoints, 0)\n\n if num_gt_boxes_per_image is None:\n num_gt_boxes_per_image = tf.shape(groundtruth_boxes)[1:2]\n else:\n num_gt_boxes_per_image = tf.expand_dims(num_gt_boxes_per_image, 0)\n\n if num_det_boxes_per_image is None:\n num_det_boxes_per_image = tf.shape(detection_boxes)[1:2]\n else:\n num_det_boxes_per_image = tf.expand_dims(num_det_boxes_per_image, 0)\n\n if is_annotated is None:\n is_annotated = tf.constant([True])\n else:\n is_annotated = tf.expand_dims(is_annotated, 0)\n\n if groundtruth_keypoint_visibilities is None:\n groundtruth_keypoint_visibilities = tf.fill([\n tf.shape(groundtruth_boxes)[1],\n tf.shape(groundtruth_keypoints)[2]\n ], tf.constant(2, dtype=tf.int32))\n groundtruth_keypoint_visibilities = tf.expand_dims(\n groundtruth_keypoint_visibilities, 0)\n else:\n if num_gt_boxes_per_image is None:\n num_gt_boxes_per_image = tf.tile(\n tf.shape(groundtruth_boxes)[1:2],\n multiples=tf.shape(groundtruth_boxes)[0:1])\n if num_det_boxes_per_image is None:\n num_det_boxes_per_image = tf.tile(\n tf.shape(detection_boxes)[1:2],\n multiples=tf.shape(detection_boxes)[0:1])\n if is_annotated is None:\n is_annotated = tf.ones_like(image_id, dtype=tf.bool)\n if groundtruth_keypoint_visibilities is None:\n groundtruth_keypoint_visibilities = tf.fill([\n tf.shape(groundtruth_keypoints)[1],\n tf.shape(groundtruth_keypoints)[2]\n ], tf.constant(2, dtype=tf.int32))\n groundtruth_keypoint_visibilities = tf.tile(\n tf.expand_dims(groundtruth_keypoint_visibilities, 0),\n multiples=[tf.shape(groundtruth_keypoints)[0], 1, 1])\n\n return tf.py_func(update_op, [\n image_id, groundtruth_boxes, groundtruth_classes, groundtruth_is_crowd,\n groundtruth_area, groundtruth_keypoints,\n groundtruth_keypoint_visibilities, num_gt_boxes_per_image,\n detection_boxes, detection_scores, detection_classes,\n detection_keypoints, num_det_boxes_per_image, is_annotated\n ], [])\n\n def get_estimator_eval_metric_ops(self, eval_dict):\n \"\"\"Returns a dictionary of eval metric ops.\n\n Note that once value_op is called, the detections and groundtruth added via\n update_op are cleared.\n\n This function can take in groundtruth and detections for a batch of images,\n or for a single image. For the latter case, the batch dimension for input\n tensors need not be present.\n\n Args:\n eval_dict: A dictionary that holds tensors for evaluating object detection\n performance. For single-image evaluation, this dictionary may be\n produced from eval_util.result_dict_for_single_example(). If multi-image\n evaluation, `eval_dict` should contain the fields\n 'num_groundtruth_boxes_per_image' and 'num_det_boxes_per_image' to\n properly unpad the tensors from the batch.\n\n Returns:\n a dictionary of metric names to tuple of value_op and update_op that can\n be used as eval metric ops in tf.estimator.EstimatorSpec. Note that all\n update ops must be run together and similarly all value ops must be run\n together to guarantee correct behaviour.\n \"\"\"\n update_op = self.add_eval_dict(eval_dict)\n category = self._category_name\n metric_names = [\n 'Keypoints_Precision/mAP ByCategory/{}'.format(category),\n 'Keypoints_Precision/[email protected] ByCategory/{}'.format(category),\n 'Keypoints_Precision/[email protected] ByCategory/{}'.format(category),\n 'Keypoints_Precision/mAP (large) ByCategory/{}'.format(category),\n 'Keypoints_Precision/mAP (medium) ByCategory/{}'.format(category),\n 'Keypoints_Recall/AR@1 ByCategory/{}'.format(category),\n 'Keypoints_Recall/AR@10 ByCategory/{}'.format(category),\n 'Keypoints_Recall/AR@100 ByCategory/{}'.format(category),\n 'Keypoints_Recall/AR@100 (large) ByCategory/{}'.format(category),\n 'Keypoints_Recall/AR@100 (medium) ByCategory/{}'.format(category)\n ]\n\n def first_value_func():\n self._metrics = self.evaluate()\n self.clear()\n return np.float32(self._metrics[metric_names[0]])\n\n def value_func_factory(metric_name):\n def value_func():\n return np.float32(self._metrics[metric_name])\n return value_func\n\n # Ensure that the metrics are only evaluated once.\n first_value_op = tf.py_func(first_value_func, [], tf.float32)\n eval_metric_ops = {metric_names[0]: (first_value_op, update_op)}\n with tf.control_dependencies([first_value_op]):\n for metric_name in metric_names[1:]:\n eval_metric_ops[metric_name] = (tf.py_func(\n value_func_factory(metric_name), [], np.float32), update_op)\n return eval_metric_ops\n\n\nclass CocoMaskEvaluator(object_detection_evaluation.DetectionEvaluator):\n \"\"\"Class to evaluate COCO detection metrics.\"\"\"\n\n def __init__(self, categories, include_metrics_per_category=False):\n \"\"\"Constructor.\n\n Args:\n categories: A list of dicts, each of which has the following keys -\n 'id': (required) an integer id uniquely identifying this category.\n 'name': (required) string representing category name e.g., 'cat', 'dog'.\n include_metrics_per_category: If True, include metrics for each category.\n \"\"\"\n super(CocoMaskEvaluator, self).__init__(categories)\n self._image_id_to_mask_shape_map = {}\n self._image_ids_with_detections = set([])\n self._groundtruth_list = []\n self._detection_masks_list = []\n self._category_id_set = set([cat['id'] for cat in self._categories])\n self._annotation_id = 1\n self._include_metrics_per_category = include_metrics_per_category\n\n def clear(self):\n \"\"\"Clears the state to prepare for a fresh evaluation.\"\"\"\n self._image_id_to_mask_shape_map.clear()\n self._image_ids_with_detections.clear()\n self._groundtruth_list = []\n self._detection_masks_list = []\n\n def add_single_ground_truth_image_info(self,\n image_id,\n groundtruth_dict):\n \"\"\"Adds groundtruth for a single image to be used for evaluation.\n\n If the image has already been added, a warning is logged, and groundtruth is\n ignored.\n\n Args:\n image_id: A unique string/integer identifier for the image.\n groundtruth_dict: A dictionary containing -\n InputDataFields.groundtruth_boxes: float32 numpy array of shape\n [num_boxes, 4] containing `num_boxes` groundtruth boxes of the format\n [ymin, xmin, ymax, xmax] in absolute image coordinates.\n InputDataFields.groundtruth_classes: integer numpy array of shape\n [num_boxes] containing 1-indexed groundtruth classes for the boxes.\n InputDataFields.groundtruth_instance_masks: uint8 numpy array of shape\n [num_boxes, image_height, image_width] containing groundtruth masks\n corresponding to the boxes. The elements of the array must be in\n {0, 1}.\n \"\"\"\n if image_id in self._image_id_to_mask_shape_map:\n tf.logging.warning('Ignoring ground truth with image id %s since it was '\n 'previously added', image_id)\n return\n\n groundtruth_instance_masks = groundtruth_dict[\n standard_fields.InputDataFields.groundtruth_instance_masks]\n groundtruth_instance_masks = convert_masks_to_binary(\n groundtruth_instance_masks)\n self._groundtruth_list.extend(\n coco_tools.\n ExportSingleImageGroundtruthToCoco(\n image_id=image_id,\n next_annotation_id=self._annotation_id,\n category_id_set=self._category_id_set,\n groundtruth_boxes=groundtruth_dict[standard_fields.InputDataFields.\n groundtruth_boxes],\n groundtruth_classes=groundtruth_dict[standard_fields.\n InputDataFields.\n groundtruth_classes],\n groundtruth_masks=groundtruth_instance_masks))\n self._annotation_id += groundtruth_dict[standard_fields.InputDataFields.\n groundtruth_boxes].shape[0]\n self._image_id_to_mask_shape_map[image_id] = groundtruth_dict[\n standard_fields.InputDataFields.groundtruth_instance_masks].shape\n\n def add_single_detected_image_info(self,\n image_id,\n detections_dict):\n \"\"\"Adds detections for a single image to be used for evaluation.\n\n If a detection has already been added for this image id, a warning is\n logged, and the detection is skipped.\n\n Args:\n image_id: A unique string/integer identifier for the image.\n detections_dict: A dictionary containing -\n DetectionResultFields.detection_scores: float32 numpy array of shape\n [num_boxes] containing detection scores for the boxes.\n DetectionResultFields.detection_classes: integer numpy array of shape\n [num_boxes] containing 1-indexed detection classes for the boxes.\n DetectionResultFields.detection_masks: optional uint8 numpy array of\n shape [num_boxes, image_height, image_width] containing instance\n masks corresponding to the boxes. The elements of the array must be\n in {0, 1}.\n\n Raises:\n ValueError: If groundtruth for the image_id is not available or if\n spatial shapes of groundtruth_instance_masks and detection_masks are\n incompatible.\n \"\"\"\n if image_id not in self._image_id_to_mask_shape_map:\n raise ValueError('Missing groundtruth for image id: {}'.format(image_id))\n\n if image_id in self._image_ids_with_detections:\n tf.logging.warning('Ignoring detection with image id %s since it was '\n 'previously added', image_id)\n return\n\n groundtruth_masks_shape = self._image_id_to_mask_shape_map[image_id]\n detection_masks = detections_dict[standard_fields.DetectionResultFields.\n detection_masks]\n if groundtruth_masks_shape[1:] != detection_masks.shape[1:]:\n raise ValueError('Spatial shape of groundtruth masks and detection masks '\n 'are incompatible: {} vs {}'.format(\n groundtruth_masks_shape,\n detection_masks.shape))\n detection_masks = convert_masks_to_binary(detection_masks)\n self._detection_masks_list.extend(\n coco_tools.ExportSingleImageDetectionMasksToCoco(\n image_id=image_id,\n category_id_set=self._category_id_set,\n detection_masks=detection_masks,\n detection_scores=detections_dict[standard_fields.\n DetectionResultFields.\n detection_scores],\n detection_classes=detections_dict[standard_fields.\n DetectionResultFields.\n detection_classes]))\n self._image_ids_with_detections.update([image_id])\n\n def dump_detections_to_json_file(self, json_output_path):\n \"\"\"Saves the detections into json_output_path in the format used by MS COCO.\n\n Args:\n json_output_path: String containing the output file's path. It can be also\n None. In that case nothing will be written to the output file.\n \"\"\"\n if json_output_path and json_output_path is not None:\n tf.logging.info('Dumping detections to output json file.')\n with tf.gfile.GFile(json_output_path, 'w') as fid:\n json_utils.Dump(\n obj=self._detection_masks_list, fid=fid, float_digits=4, indent=2)\n\n def evaluate(self):\n \"\"\"Evaluates the detection masks and returns a dictionary of coco metrics.\n\n Returns:\n A dictionary holding -\n\n 1. summary_metrics:\n 'DetectionMasks_Precision/mAP': mean average precision over classes\n averaged over IOU thresholds ranging from .5 to .95 with .05 increments.\n 'DetectionMasks_Precision/[email protected]': mean average precision at 50% IOU.\n 'DetectionMasks_Precision/[email protected]': mean average precision at 75% IOU.\n 'DetectionMasks_Precision/mAP (small)': mean average precision for small\n objects (area < 32^2 pixels).\n 'DetectionMasks_Precision/mAP (medium)': mean average precision for medium\n sized objects (32^2 pixels < area < 96^2 pixels).\n 'DetectionMasks_Precision/mAP (large)': mean average precision for large\n objects (96^2 pixels < area < 10000^2 pixels).\n 'DetectionMasks_Recall/AR@1': average recall with 1 detection.\n 'DetectionMasks_Recall/AR@10': average recall with 10 detections.\n 'DetectionMasks_Recall/AR@100': average recall with 100 detections.\n 'DetectionMasks_Recall/AR@100 (small)': average recall for small objects\n with 100 detections.\n 'DetectionMasks_Recall/AR@100 (medium)': average recall for medium objects\n with 100 detections.\n 'DetectionMasks_Recall/AR@100 (large)': average recall for large objects\n with 100 detections.\n\n 2. per_category_ap: if include_metrics_per_category is True, category\n specific results with keys of the form:\n 'Precision mAP ByCategory/category' (without the supercategory part if\n no supercategories exist). For backward compatibility\n 'PerformanceByCategory' is included in the output regardless of\n all_metrics_per_category.\n \"\"\"\n groundtruth_dict = {\n 'annotations': self._groundtruth_list,\n 'images': [{'id': image_id, 'height': shape[1], 'width': shape[2]}\n for image_id, shape in self._image_id_to_mask_shape_map.\n items()],\n 'categories': self._categories\n }\n coco_wrapped_groundtruth = coco_tools.COCOWrapper(\n groundtruth_dict, detection_type='segmentation')\n coco_wrapped_detection_masks = coco_wrapped_groundtruth.LoadAnnotations(\n self._detection_masks_list)\n mask_evaluator = coco_tools.COCOEvalWrapper(\n coco_wrapped_groundtruth, coco_wrapped_detection_masks,\n agnostic_mode=False, iou_type='segm')\n mask_metrics, mask_per_category_ap = mask_evaluator.ComputeMetrics(\n include_metrics_per_category=self._include_metrics_per_category)\n mask_metrics.update(mask_per_category_ap)\n mask_metrics = {'DetectionMasks_'+ key: value\n for key, value in mask_metrics.items()}\n return mask_metrics\n\n def add_eval_dict(self, eval_dict):\n \"\"\"Observes an evaluation result dict for a single example.\n\n When executing eagerly, once all observations have been observed by this\n method you can use `.evaluate()` to get the final metrics.\n\n When using `tf.estimator.Estimator` for evaluation this function is used by\n `get_estimator_eval_metric_ops()` to construct the metric update op.\n\n Args:\n eval_dict: A dictionary that holds tensors for evaluating an object\n detection model, returned from\n eval_util.result_dict_for_single_example().\n\n Returns:\n None when executing eagerly, or an update_op that can be used to update\n the eval metrics in `tf.estimator.EstimatorSpec`.\n \"\"\"\n def update_op(image_id_batched, groundtruth_boxes_batched,\n groundtruth_classes_batched,\n groundtruth_instance_masks_batched,\n groundtruth_is_crowd_batched, num_gt_boxes_per_image,\n detection_scores_batched, detection_classes_batched,\n detection_masks_batched, num_det_boxes_per_image):\n \"\"\"Update op for metrics.\"\"\"\n\n for (image_id, groundtruth_boxes, groundtruth_classes,\n groundtruth_instance_masks, groundtruth_is_crowd, num_gt_box,\n detection_scores, detection_classes,\n detection_masks, num_det_box) in zip(\n image_id_batched, groundtruth_boxes_batched,\n groundtruth_classes_batched, groundtruth_instance_masks_batched,\n groundtruth_is_crowd_batched, num_gt_boxes_per_image,\n detection_scores_batched, detection_classes_batched,\n detection_masks_batched, num_det_boxes_per_image):\n self.add_single_ground_truth_image_info(\n image_id, {\n 'groundtruth_boxes':\n groundtruth_boxes[:num_gt_box],\n 'groundtruth_classes':\n groundtruth_classes[:num_gt_box],\n 'groundtruth_instance_masks':\n groundtruth_instance_masks[:num_gt_box],\n 'groundtruth_is_crowd':\n groundtruth_is_crowd[:num_gt_box]\n })\n self.add_single_detected_image_info(\n image_id, {\n 'detection_scores': detection_scores[:num_det_box],\n 'detection_classes': detection_classes[:num_det_box],\n 'detection_masks': detection_masks[:num_det_box]\n })\n\n # Unpack items from the evaluation dictionary.\n input_data_fields = standard_fields.InputDataFields\n detection_fields = standard_fields.DetectionResultFields\n image_id = eval_dict[input_data_fields.key]\n groundtruth_boxes = eval_dict[input_data_fields.groundtruth_boxes]\n groundtruth_classes = eval_dict[input_data_fields.groundtruth_classes]\n groundtruth_instance_masks = eval_dict[\n input_data_fields.groundtruth_instance_masks]\n groundtruth_is_crowd = eval_dict.get(\n input_data_fields.groundtruth_is_crowd, None)\n num_gt_boxes_per_image = eval_dict.get(\n input_data_fields.num_groundtruth_boxes, None)\n detection_scores = eval_dict[detection_fields.detection_scores]\n detection_classes = eval_dict[detection_fields.detection_classes]\n detection_masks = eval_dict[detection_fields.detection_masks]\n num_det_boxes_per_image = eval_dict.get(detection_fields.num_detections,\n None)\n\n if groundtruth_is_crowd is None:\n groundtruth_is_crowd = tf.zeros_like(groundtruth_classes, dtype=tf.bool)\n\n if not image_id.shape.as_list():\n # Apply a batch dimension to all tensors.\n image_id = tf.expand_dims(image_id, 0)\n groundtruth_boxes = tf.expand_dims(groundtruth_boxes, 0)\n groundtruth_classes = tf.expand_dims(groundtruth_classes, 0)\n groundtruth_instance_masks = tf.expand_dims(groundtruth_instance_masks, 0)\n groundtruth_is_crowd = tf.expand_dims(groundtruth_is_crowd, 0)\n detection_scores = tf.expand_dims(detection_scores, 0)\n detection_classes = tf.expand_dims(detection_classes, 0)\n detection_masks = tf.expand_dims(detection_masks, 0)\n\n if num_gt_boxes_per_image is None:\n num_gt_boxes_per_image = tf.shape(groundtruth_boxes)[1:2]\n else:\n num_gt_boxes_per_image = tf.expand_dims(num_gt_boxes_per_image, 0)\n\n if num_det_boxes_per_image is None:\n num_det_boxes_per_image = tf.shape(detection_scores)[1:2]\n else:\n num_det_boxes_per_image = tf.expand_dims(num_det_boxes_per_image, 0)\n else:\n if num_gt_boxes_per_image is None:\n num_gt_boxes_per_image = tf.tile(\n tf.shape(groundtruth_boxes)[1:2],\n multiples=tf.shape(groundtruth_boxes)[0:1])\n if num_det_boxes_per_image is None:\n num_det_boxes_per_image = tf.tile(\n tf.shape(detection_scores)[1:2],\n multiples=tf.shape(detection_scores)[0:1])\n\n return tf.py_func(update_op, [\n image_id, groundtruth_boxes, groundtruth_classes,\n groundtruth_instance_masks, groundtruth_is_crowd,\n num_gt_boxes_per_image, detection_scores, detection_classes,\n detection_masks, num_det_boxes_per_image\n ], [])\n\n def get_estimator_eval_metric_ops(self, eval_dict):\n \"\"\"Returns a dictionary of eval metric ops.\n\n Note that once value_op is called, the detections and groundtruth added via\n update_op are cleared.\n\n Args:\n eval_dict: A dictionary that holds tensors for evaluating object detection\n performance. For single-image evaluation, this dictionary may be\n produced from eval_util.result_dict_for_single_example(). If multi-image\n evaluation, `eval_dict` should contain the fields\n 'num_groundtruth_boxes_per_image' and 'num_det_boxes_per_image' to\n properly unpad the tensors from the batch.\n\n Returns:\n a dictionary of metric names to tuple of value_op and update_op that can\n be used as eval metric ops in tf.estimator.EstimatorSpec. Note that all\n update ops must be run together and similarly all value ops must be run\n together to guarantee correct behaviour.\n \"\"\"\n update_op = self.add_eval_dict(eval_dict)\n metric_names = ['DetectionMasks_Precision/mAP',\n 'DetectionMasks_Precision/[email protected]',\n 'DetectionMasks_Precision/[email protected]',\n 'DetectionMasks_Precision/mAP (large)',\n 'DetectionMasks_Precision/mAP (medium)',\n 'DetectionMasks_Precision/mAP (small)',\n 'DetectionMasks_Recall/AR@1',\n 'DetectionMasks_Recall/AR@10',\n 'DetectionMasks_Recall/AR@100',\n 'DetectionMasks_Recall/AR@100 (large)',\n 'DetectionMasks_Recall/AR@100 (medium)',\n 'DetectionMasks_Recall/AR@100 (small)']\n if self._include_metrics_per_category:\n for category_dict in self._categories:\n metric_names.append('DetectionMasks_PerformanceByCategory/mAP/' +\n category_dict['name'])\n\n def first_value_func():\n self._metrics = self.evaluate()\n self.clear()\n return np.float32(self._metrics[metric_names[0]])\n\n def value_func_factory(metric_name):\n def value_func():\n return np.float32(self._metrics[metric_name])\n return value_func\n\n # Ensure that the metrics are only evaluated once.\n first_value_op = tf.py_func(first_value_func, [], tf.float32)\n eval_metric_ops = {metric_names[0]: (first_value_op, update_op)}\n with tf.control_dependencies([first_value_op]):\n for metric_name in metric_names[1:]:\n eval_metric_ops[metric_name] = (tf.py_func(\n value_func_factory(metric_name), [], np.float32), update_op)\n return eval_metric_ops\n\n\nclass CocoPanopticSegmentationEvaluator(\n object_detection_evaluation.DetectionEvaluator):\n \"\"\"Class to evaluate PQ (panoptic quality) metric on COCO dataset.\n\n More details about this metric: https://arxiv.org/pdf/1801.00868.pdf.\n \"\"\"\n\n def __init__(self,\n categories,\n include_metrics_per_category=False,\n iou_threshold=0.5,\n ioa_threshold=0.5):\n \"\"\"Constructor.\n\n Args:\n categories: A list of dicts, each of which has the following keys -\n 'id': (required) an integer id uniquely identifying this category.\n 'name': (required) string representing category name e.g., 'cat', 'dog'.\n include_metrics_per_category: If True, include metrics for each category.\n iou_threshold: intersection-over-union threshold for mask matching (with\n normal groundtruths).\n ioa_threshold: intersection-over-area threshold for mask matching with\n \"is_crowd\" groundtruths.\n \"\"\"\n super(CocoPanopticSegmentationEvaluator, self).__init__(categories)\n self._groundtruth_masks = {}\n self._groundtruth_class_labels = {}\n self._groundtruth_is_crowd = {}\n self._predicted_masks = {}\n self._predicted_class_labels = {}\n self._include_metrics_per_category = include_metrics_per_category\n self._iou_threshold = iou_threshold\n self._ioa_threshold = ioa_threshold\n\n def clear(self):\n \"\"\"Clears the state to prepare for a fresh evaluation.\"\"\"\n self._groundtruth_masks.clear()\n self._groundtruth_class_labels.clear()\n self._groundtruth_is_crowd.clear()\n self._predicted_masks.clear()\n self._predicted_class_labels.clear()\n\n def add_single_ground_truth_image_info(self, image_id, groundtruth_dict):\n \"\"\"Adds groundtruth for a single image to be used for evaluation.\n\n If the image has already been added, a warning is logged, and groundtruth is\n ignored.\n\n Args:\n image_id: A unique string/integer identifier for the image.\n groundtruth_dict: A dictionary containing -\n InputDataFields.groundtruth_classes: integer numpy array of shape\n [num_masks] containing 1-indexed groundtruth classes for the mask.\n InputDataFields.groundtruth_instance_masks: uint8 numpy array of shape\n [num_masks, image_height, image_width] containing groundtruth masks.\n The elements of the array must be in {0, 1}.\n InputDataFields.groundtruth_is_crowd (optional): integer numpy array of\n shape [num_boxes] containing iscrowd flag for groundtruth boxes.\n \"\"\"\n\n if image_id in self._groundtruth_masks:\n tf.logging.warning(\n 'Ignoring groundtruth with image %s, since it has already been '\n 'added to the ground truth database.', image_id)\n return\n\n self._groundtruth_masks[image_id] = groundtruth_dict[\n standard_fields.InputDataFields.groundtruth_instance_masks]\n self._groundtruth_class_labels[image_id] = groundtruth_dict[\n standard_fields.InputDataFields.groundtruth_classes]\n groundtruth_is_crowd = groundtruth_dict.get(\n standard_fields.InputDataFields.groundtruth_is_crowd)\n # Drop groundtruth_is_crowd if empty tensor.\n if groundtruth_is_crowd is not None and not groundtruth_is_crowd.size > 0:\n groundtruth_is_crowd = None\n if groundtruth_is_crowd is not None:\n self._groundtruth_is_crowd[image_id] = groundtruth_is_crowd\n\n def add_single_detected_image_info(self, image_id, detections_dict):\n \"\"\"Adds detections for a single image to be used for evaluation.\n\n If a detection has already been added for this image id, a warning is\n logged, and the detection is skipped.\n\n Args:\n image_id: A unique string/integer identifier for the image.\n detections_dict: A dictionary containing -\n DetectionResultFields.detection_classes: integer numpy array of shape\n [num_masks] containing 1-indexed detection classes for the masks.\n DetectionResultFields.detection_masks: optional uint8 numpy array of\n shape [num_masks, image_height, image_width] containing instance\n masks. The elements of the array must be in {0, 1}.\n\n Raises:\n ValueError: If results and groundtruth shape don't match.\n \"\"\"\n\n if image_id not in self._groundtruth_masks:\n raise ValueError('Missing groundtruth for image id: {}'.format(image_id))\n\n detection_masks = detections_dict[\n standard_fields.DetectionResultFields.detection_masks]\n self._predicted_masks[image_id] = detection_masks\n self._predicted_class_labels[image_id] = detections_dict[\n standard_fields.DetectionResultFields.detection_classes]\n groundtruth_mask_shape = self._groundtruth_masks[image_id].shape\n if groundtruth_mask_shape[1:] != detection_masks.shape[1:]:\n raise ValueError(\"The shape of results doesn't match groundtruth.\")\n\n def evaluate(self):\n \"\"\"Evaluates the detection masks and returns a dictionary of coco metrics.\n\n Returns:\n A dictionary holding -\n\n 1. summary_metric:\n 'PanopticQuality@%.2fIOU': mean panoptic quality averaged over classes at\n the required IOU.\n 'SegmentationQuality@%.2fIOU': mean segmentation quality averaged over\n classes at the required IOU.\n 'RecognitionQuality@%.2fIOU': mean recognition quality averaged over\n classes at the required IOU.\n 'NumValidClasses': number of valid classes. A valid class should have at\n least one normal (is_crowd=0) groundtruth mask or one predicted mask.\n 'NumTotalClasses': number of total classes.\n\n 2. per_category_pq: if include_metrics_per_category is True, category\n specific results with keys of the form:\n 'PanopticQuality@%.2fIOU_ByCategory/category'.\n \"\"\"\n # Evaluate and accumulate the iou/tp/fp/fn.\n sum_tp_iou, sum_num_tp, sum_num_fp, sum_num_fn = self._evaluate_all_masks()\n # Compute PQ metric for each category and average over all classes.\n mask_metrics = self._compute_panoptic_metrics(sum_tp_iou, sum_num_tp,\n sum_num_fp, sum_num_fn)\n return mask_metrics\n\n def get_estimator_eval_metric_ops(self, eval_dict):\n \"\"\"Returns a dictionary of eval metric ops.\n\n Note that once value_op is called, the detections and groundtruth added via\n update_op are cleared.\n\n Args:\n eval_dict: A dictionary that holds tensors for evaluating object detection\n performance. For single-image evaluation, this dictionary may be\n produced from eval_util.result_dict_for_single_example(). If multi-image\n evaluation, `eval_dict` should contain the fields\n 'num_gt_masks_per_image' and 'num_det_masks_per_image' to properly unpad\n the tensors from the batch.\n\n Returns:\n a dictionary of metric names to tuple of value_op and update_op that can\n be used as eval metric ops in tf.estimator.EstimatorSpec. Note that all\n update ops must be run together and similarly all value ops must be run\n together to guarantee correct behaviour.\n \"\"\"\n\n def update_op(image_id_batched, groundtruth_classes_batched,\n groundtruth_instance_masks_batched,\n groundtruth_is_crowd_batched, num_gt_masks_per_image,\n detection_classes_batched, detection_masks_batched,\n num_det_masks_per_image):\n \"\"\"Update op for metrics.\"\"\"\n for (image_id, groundtruth_classes, groundtruth_instance_masks,\n groundtruth_is_crowd, num_gt_mask, detection_classes,\n detection_masks, num_det_mask) in zip(\n image_id_batched, groundtruth_classes_batched,\n groundtruth_instance_masks_batched, groundtruth_is_crowd_batched,\n num_gt_masks_per_image, detection_classes_batched,\n detection_masks_batched, num_det_masks_per_image):\n\n self.add_single_ground_truth_image_info(\n image_id, {\n 'groundtruth_classes':\n groundtruth_classes[:num_gt_mask],\n 'groundtruth_instance_masks':\n groundtruth_instance_masks[:num_gt_mask],\n 'groundtruth_is_crowd':\n groundtruth_is_crowd[:num_gt_mask]\n })\n self.add_single_detected_image_info(\n image_id, {\n 'detection_classes': detection_classes[:num_det_mask],\n 'detection_masks': detection_masks[:num_det_mask]\n })\n\n # Unpack items from the evaluation dictionary.\n (image_id, groundtruth_classes, groundtruth_instance_masks,\n groundtruth_is_crowd, num_gt_masks_per_image, detection_classes,\n detection_masks, num_det_masks_per_image\n ) = self._unpack_evaluation_dictionary_items(eval_dict)\n\n update_op = tf.py_func(update_op, [\n image_id, groundtruth_classes, groundtruth_instance_masks,\n groundtruth_is_crowd, num_gt_masks_per_image, detection_classes,\n detection_masks, num_det_masks_per_image\n ], [])\n\n metric_names = [\n 'PanopticQuality@%.2fIOU' % self._iou_threshold,\n 'SegmentationQuality@%.2fIOU' % self._iou_threshold,\n 'RecognitionQuality@%.2fIOU' % self._iou_threshold\n ]\n if self._include_metrics_per_category:\n for category_dict in self._categories:\n metric_names.append('PanopticQuality@%.2fIOU_ByCategory/%s' %\n (self._iou_threshold, category_dict['name']))\n\n def first_value_func():\n self._metrics = self.evaluate()\n self.clear()\n return np.float32(self._metrics[metric_names[0]])\n\n def value_func_factory(metric_name):\n\n def value_func():\n return np.float32(self._metrics[metric_name])\n\n return value_func\n\n # Ensure that the metrics are only evaluated once.\n first_value_op = tf.py_func(first_value_func, [], tf.float32)\n eval_metric_ops = {metric_names[0]: (first_value_op, update_op)}\n with tf.control_dependencies([first_value_op]):\n for metric_name in metric_names[1:]:\n eval_metric_ops[metric_name] = (tf.py_func(\n value_func_factory(metric_name), [], np.float32), update_op)\n return eval_metric_ops\n\n def _evaluate_all_masks(self):\n \"\"\"Evaluate all masks and compute sum iou/TP/FP/FN.\"\"\"\n\n sum_num_tp = {category['id']: 0 for category in self._categories}\n sum_num_fp = sum_num_tp.copy()\n sum_num_fn = sum_num_tp.copy()\n sum_tp_iou = sum_num_tp.copy()\n\n for image_id in self._groundtruth_class_labels:\n # Separate normal and is_crowd groundtruth\n crowd_gt_indices = self._groundtruth_is_crowd.get(image_id)\n (normal_gt_masks, normal_gt_classes, crowd_gt_masks,\n crowd_gt_classes) = self._separate_normal_and_crowd_labels(\n crowd_gt_indices, self._groundtruth_masks[image_id],\n self._groundtruth_class_labels[image_id])\n\n # Mask matching to normal GT.\n predicted_masks = self._predicted_masks[image_id]\n predicted_class_labels = self._predicted_class_labels[image_id]\n (overlaps, pred_matched,\n gt_matched) = self._match_predictions_to_groundtruths(\n predicted_masks,\n predicted_class_labels,\n normal_gt_masks,\n normal_gt_classes,\n self._iou_threshold,\n is_crowd=False,\n with_replacement=False)\n\n # Accumulate true positives.\n for (class_id, is_matched, overlap) in zip(predicted_class_labels,\n pred_matched, overlaps):\n if is_matched:\n sum_num_tp[class_id] += 1\n sum_tp_iou[class_id] += overlap\n\n # Accumulate false negatives.\n for (class_id, is_matched) in zip(normal_gt_classes, gt_matched):\n if not is_matched:\n sum_num_fn[class_id] += 1\n\n # Match remaining predictions to crowd gt.\n remained_pred_indices = np.logical_not(pred_matched)\n remained_pred_masks = predicted_masks[remained_pred_indices, :, :]\n remained_pred_classes = predicted_class_labels[remained_pred_indices]\n _, pred_matched, _ = self._match_predictions_to_groundtruths(\n remained_pred_masks,\n remained_pred_classes,\n crowd_gt_masks,\n crowd_gt_classes,\n self._ioa_threshold,\n is_crowd=True,\n with_replacement=True)\n\n # Accumulate false positives\n for (class_id, is_matched) in zip(remained_pred_classes, pred_matched):\n if not is_matched:\n sum_num_fp[class_id] += 1\n return sum_tp_iou, sum_num_tp, sum_num_fp, sum_num_fn\n\n def _compute_panoptic_metrics(self, sum_tp_iou, sum_num_tp, sum_num_fp,\n sum_num_fn):\n \"\"\"Compute PQ metric for each category and average over all classes.\n\n Args:\n sum_tp_iou: dict, summed true positive intersection-over-union (IoU) for\n each class, keyed by class_id.\n sum_num_tp: the total number of true positives for each class, keyed by\n class_id.\n sum_num_fp: the total number of false positives for each class, keyed by\n class_id.\n sum_num_fn: the total number of false negatives for each class, keyed by\n class_id.\n\n Returns:\n mask_metrics: a dictionary containing averaged metrics over all classes,\n and per-category metrics if required.\n \"\"\"\n mask_metrics = {}\n sum_pq = 0\n sum_sq = 0\n sum_rq = 0\n num_valid_classes = 0\n for category in self._categories:\n class_id = category['id']\n (panoptic_quality, segmentation_quality,\n recognition_quality) = self._compute_panoptic_metrics_single_class(\n sum_tp_iou[class_id], sum_num_tp[class_id], sum_num_fp[class_id],\n sum_num_fn[class_id])\n if panoptic_quality is not None:\n sum_pq += panoptic_quality\n sum_sq += segmentation_quality\n sum_rq += recognition_quality\n num_valid_classes += 1\n if self._include_metrics_per_category:\n mask_metrics['PanopticQuality@%.2fIOU_ByCategory/%s' %\n (self._iou_threshold,\n category['name'])] = panoptic_quality\n mask_metrics['PanopticQuality@%.2fIOU' %\n self._iou_threshold] = sum_pq / num_valid_classes\n mask_metrics['SegmentationQuality@%.2fIOU' %\n self._iou_threshold] = sum_sq / num_valid_classes\n mask_metrics['RecognitionQuality@%.2fIOU' %\n self._iou_threshold] = sum_rq / num_valid_classes\n mask_metrics['NumValidClasses'] = num_valid_classes\n mask_metrics['NumTotalClasses'] = len(self._categories)\n return mask_metrics\n\n def _compute_panoptic_metrics_single_class(self, sum_tp_iou, num_tp, num_fp,\n num_fn):\n \"\"\"Compute panoptic metrics: panoptic/segmentation/recognition quality.\n\n More computation details in https://arxiv.org/pdf/1801.00868.pdf.\n Args:\n sum_tp_iou: summed true positive intersection-over-union (IoU) for a\n specific class.\n num_tp: the total number of true positives for a specific class.\n num_fp: the total number of false positives for a specific class.\n num_fn: the total number of false negatives for a specific class.\n\n Returns:\n panoptic_quality: sum_tp_iou / (num_tp + 0.5*num_fp + 0.5*num_fn).\n segmentation_quality: sum_tp_iou / num_tp.\n recognition_quality: num_tp / (num_tp + 0.5*num_fp + 0.5*num_fn).\n \"\"\"\n denominator = num_tp + 0.5 * num_fp + 0.5 * num_fn\n # Calculate metric only if there is at least one GT or one prediction.\n if denominator > 0:\n recognition_quality = num_tp / denominator\n if num_tp > 0:\n segmentation_quality = sum_tp_iou / num_tp\n else:\n # If there is no TP for this category.\n segmentation_quality = 0\n panoptic_quality = segmentation_quality * recognition_quality\n return panoptic_quality, segmentation_quality, recognition_quality\n else:\n return None, None, None\n\n def _separate_normal_and_crowd_labels(self, crowd_gt_indices,\n groundtruth_masks, groundtruth_classes):\n \"\"\"Separate normal and crowd groundtruth class_labels and masks.\n\n Args:\n crowd_gt_indices: None or array of shape [num_groundtruths]. If None, all\n groundtruths are treated as normal ones.\n groundtruth_masks: array of shape [num_groundtruths, height, width].\n groundtruth_classes: array of shape [num_groundtruths].\n\n Returns:\n normal_gt_masks: array of shape [num_normal_groundtruths, height, width].\n normal_gt_classes: array of shape [num_normal_groundtruths].\n crowd_gt_masks: array of shape [num_crowd_groundtruths, height, width].\n crowd_gt_classes: array of shape [num_crowd_groundtruths].\n Raises:\n ValueError: if the shape of groundtruth classes doesn't match groundtruth\n masks or if the shape of crowd_gt_indices.\n \"\"\"\n if groundtruth_masks.shape[0] != groundtruth_classes.shape[0]:\n raise ValueError(\n \"The number of masks doesn't match the number of labels.\")\n if crowd_gt_indices is None:\n # All gts are treated as normal\n crowd_gt_indices = np.zeros(groundtruth_masks.shape, dtype=np.bool)\n else:\n if groundtruth_masks.shape[0] != crowd_gt_indices.shape[0]:\n raise ValueError(\n \"The number of masks doesn't match the number of is_crowd labels.\")\n crowd_gt_indices = crowd_gt_indices.astype(np.bool)\n normal_gt_indices = np.logical_not(crowd_gt_indices)\n if normal_gt_indices.size:\n normal_gt_masks = groundtruth_masks[normal_gt_indices, :, :]\n normal_gt_classes = groundtruth_classes[normal_gt_indices]\n crowd_gt_masks = groundtruth_masks[crowd_gt_indices, :, :]\n crowd_gt_classes = groundtruth_classes[crowd_gt_indices]\n else:\n # No groundtruths available, groundtruth_masks.shape = (0, h, w)\n normal_gt_masks = groundtruth_masks\n normal_gt_classes = groundtruth_classes\n crowd_gt_masks = groundtruth_masks\n crowd_gt_classes = groundtruth_classes\n return normal_gt_masks, normal_gt_classes, crowd_gt_masks, crowd_gt_classes\n\n def _match_predictions_to_groundtruths(self,\n predicted_masks,\n predicted_classes,\n groundtruth_masks,\n groundtruth_classes,\n matching_threshold,\n is_crowd=False,\n with_replacement=False):\n \"\"\"Match the predicted masks to groundtruths.\n\n Args:\n predicted_masks: array of shape [num_predictions, height, width].\n predicted_classes: array of shape [num_predictions].\n groundtruth_masks: array of shape [num_groundtruths, height, width].\n groundtruth_classes: array of shape [num_groundtruths].\n matching_threshold: if the overlap between a prediction and a groundtruth\n is larger than this threshold, the prediction is true positive.\n is_crowd: whether the groundtruths are crowd annotation or not. If True,\n use intersection over area (IoA) as the overlapping metric; otherwise\n use intersection over union (IoU).\n with_replacement: whether a groundtruth can be matched to multiple\n predictions. By default, for normal groundtruths, only 1-1 matching is\n allowed for normal groundtruths; for crowd groundtruths, 1-to-many must\n be allowed.\n\n Returns:\n best_overlaps: array of shape [num_predictions]. Values representing the\n IoU\n or IoA with best matched groundtruth.\n pred_matched: array of shape [num_predictions]. Boolean value representing\n whether the ith prediction is matched to a groundtruth.\n gt_matched: array of shape [num_groundtruth]. Boolean value representing\n whether the ith groundtruth is matched to a prediction.\n Raises:\n ValueError: if the shape of groundtruth/predicted masks doesn't match\n groundtruth/predicted classes.\n \"\"\"\n if groundtruth_masks.shape[0] != groundtruth_classes.shape[0]:\n raise ValueError(\n \"The number of GT masks doesn't match the number of labels.\")\n if predicted_masks.shape[0] != predicted_classes.shape[0]:\n raise ValueError(\n \"The number of predicted masks doesn't match the number of labels.\")\n gt_matched = np.zeros(groundtruth_classes.shape, dtype=np.bool)\n pred_matched = np.zeros(predicted_classes.shape, dtype=np.bool)\n best_overlaps = np.zeros(predicted_classes.shape)\n for pid in range(predicted_classes.shape[0]):\n best_overlap = 0\n matched_gt_id = -1\n for gid in range(groundtruth_classes.shape[0]):\n if predicted_classes[pid] == groundtruth_classes[gid]:\n if (not with_replacement) and gt_matched[gid]:\n continue\n if not is_crowd:\n overlap = np_mask_ops.iou(predicted_masks[pid:pid + 1],\n groundtruth_masks[gid:gid + 1])[0, 0]\n else:\n overlap = np_mask_ops.ioa(groundtruth_masks[gid:gid + 1],\n predicted_masks[pid:pid + 1])[0, 0]\n if overlap >= matching_threshold and overlap > best_overlap:\n matched_gt_id = gid\n best_overlap = overlap\n if matched_gt_id >= 0:\n gt_matched[matched_gt_id] = True\n pred_matched[pid] = True\n best_overlaps[pid] = best_overlap\n return best_overlaps, pred_matched, gt_matched\n\n def _unpack_evaluation_dictionary_items(self, eval_dict):\n \"\"\"Unpack items from the evaluation dictionary.\"\"\"\n input_data_fields = standard_fields.InputDataFields\n detection_fields = standard_fields.DetectionResultFields\n image_id = eval_dict[input_data_fields.key]\n groundtruth_classes = eval_dict[input_data_fields.groundtruth_classes]\n groundtruth_instance_masks = eval_dict[\n input_data_fields.groundtruth_instance_masks]\n groundtruth_is_crowd = eval_dict.get(input_data_fields.groundtruth_is_crowd,\n None)\n num_gt_masks_per_image = eval_dict.get(\n input_data_fields.num_groundtruth_boxes, None)\n detection_classes = eval_dict[detection_fields.detection_classes]\n detection_masks = eval_dict[detection_fields.detection_masks]\n num_det_masks_per_image = eval_dict.get(detection_fields.num_detections,\n None)\n if groundtruth_is_crowd is None:\n groundtruth_is_crowd = tf.zeros_like(groundtruth_classes, dtype=tf.bool)\n\n if not image_id.shape.as_list():\n # Apply a batch dimension to all tensors.\n image_id = tf.expand_dims(image_id, 0)\n groundtruth_classes = tf.expand_dims(groundtruth_classes, 0)\n groundtruth_instance_masks = tf.expand_dims(groundtruth_instance_masks, 0)\n groundtruth_is_crowd = tf.expand_dims(groundtruth_is_crowd, 0)\n detection_classes = tf.expand_dims(detection_classes, 0)\n detection_masks = tf.expand_dims(detection_masks, 0)\n\n if num_gt_masks_per_image is None:\n num_gt_masks_per_image = tf.shape(groundtruth_classes)[1:2]\n else:\n num_gt_masks_per_image = tf.expand_dims(num_gt_masks_per_image, 0)\n\n if num_det_masks_per_image is None:\n num_det_masks_per_image = tf.shape(detection_classes)[1:2]\n else:\n num_det_masks_per_image = tf.expand_dims(num_det_masks_per_image, 0)\n else:\n if num_gt_masks_per_image is None:\n num_gt_masks_per_image = tf.tile(\n tf.shape(groundtruth_classes)[1:2],\n multiples=tf.shape(groundtruth_classes)[0:1])\n if num_det_masks_per_image is None:\n num_det_masks_per_image = tf.tile(\n tf.shape(detection_classes)[1:2],\n multiples=tf.shape(detection_classes)[0:1])\n return (image_id, groundtruth_classes, groundtruth_instance_masks,\n groundtruth_is_crowd, num_gt_masks_per_image, detection_classes,\n detection_masks, num_det_masks_per_image)\n" ]
[ [ "numpy.logical_not", "tensorflow.compat.v1.ones_like", "numpy.take", "tensorflow.compat.v1.expand_dims", "tensorflow.compat.v1.control_dependencies", "tensorflow.compat.v1.py_func", "tensorflow.compat.v1.logging.warning", "tensorflow.compat.v1.shape", "tensorflow.compat.v1.logging.info", "tensorflow.compat.v1.zeros_like", "numpy.float32", "tensorflow.compat.v1.gfile.GFile", "numpy.array", "numpy.zeros", "tensorflow.compat.v1.constant" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
yutiansut/menpo
[ "62af28606bc55985ab764f8ad38d239d1572bf1e" ]
[ "menpo/math/linalg.py" ]
[ "from itertools import islice\nimport numpy as np\nfrom menpo.visualize import print_progress, bytes_str, print_dynamic\n\n\ndef dot_inplace_left(a, b, block_size=1000):\n r\"\"\"\n Inplace dot product for memory efficiency. It computes ``a * b = c``, where\n ``a`` will be replaced inplace with ``c``.\n\n Parameters\n ----------\n a : ``(n_big, k)`` `ndarray`\n First array to dot - assumed to be large. Will be damaged by this\n function call as it is used to store the output inplace.\n b : ``(k, n_small)`` `ndarray`, ``n_small <= k``\n The second array to dot - assumed to be small. ``n_small`` must be\n smaller than ``k`` so the result can be stored within the memory space\n of ``a``.\n block_size : `int`, optional\n The size of the block of ``a`` that will be dotted against ``b`` in\n each iteration. larger block sizes increase the time performance of the\n dot product at the cost of a higher memory overhead for the operation.\n\n Returns\n -------\n c : ``(n_big, n_small)`` `ndarray`\n The output of the operation. Exactly the same as a memory view onto\n ``a`` (``a[:, :n_small]``) as ``a`` is modified inplace to store the\n result.\n \"\"\"\n (n_big, k_a), (k_b, n_small) = a.shape, b.shape\n if k_a != k_b:\n raise ValueError('Cannot dot {} * {}'.format(a.shape, b.shape))\n if n_small > k_a:\n raise ValueError('Cannot dot inplace left - '\n 'b.shape[1] ({}) > a.shape[1] '\n '({})'.format(n_small, k_a))\n for i in range(0, n_big, block_size):\n j = i + block_size\n a[i:j, :n_small] = a[i:j].dot(b)\n return a[:, :n_small]\n\n\ndef dot_inplace_right(a, b, block_size=1000):\n r\"\"\"\n Inplace dot product for memory efficiency. It computes ``a * b = c`` where\n ``b`` will be replaced inplace with ``c``.\n\n Parameters\n ----------\n a : ``(n_small, k)`` `ndarray`, n_small <= k\n The first array to dot - assumed to be small. ``n_small`` must be\n smaller than ``k`` so the result can be stored within the memory space\n of ``b``.\n b : ``(k, n_big)`` `ndarray`\n Second array to dot - assumed to be large. Will be damaged by this\n function call as it is used to store the output inplace.\n block_size : `int`, optional\n The size of the block of ``b`` that ``a`` will be dotted against\n in each iteration. larger block sizes increase the time performance of\n the dot product at the cost of a higher memory overhead for the\n operation.\n\n Returns\n -------\n c : ``(n_small, n_big)`` `ndarray`\n The output of the operation. Exactly the same as a memory view onto\n ``b`` (``b[:n_small]``) as ``b`` is modified inplace to store the\n result.\n \"\"\"\n (n_small, k_a), (k_b, n_big) = a.shape, b.shape\n if k_a != k_b:\n raise ValueError('Cannot dot {} * {}'.format(a.shape, b.shape))\n if n_small > k_b:\n raise ValueError('Cannot dot inplace right - '\n 'a.shape[1] ({}) > b.shape[0] '\n '({})'.format(n_small, k_b))\n for i in range(0, n_big, block_size):\n j = i + block_size\n b[:n_small, i:j] = a.dot(b[:, i:j])\n return b[:n_small]\n\n\ndef as_matrix(vectorizables, length=None, return_template=False, verbose=False):\n r\"\"\"\n Create a matrix from a list/generator of :map:`Vectorizable` objects.\n All the objects in the list **must** be the same size when vectorized.\n\n Consider using a generator if the matrix you are creating is large and\n passing the length of the generator explicitly.\n\n Parameters\n ----------\n vectorizables : `list` or generator if :map:`Vectorizable` objects\n A list or generator of objects that supports the vectorizable interface\n length : `int`, optional\n Length of the vectorizable list. Useful if you are passing a generator\n with a known length.\n verbose : `bool`, optional\n If ``True``, will print the progress of building the matrix.\n return_template : `bool`, optional\n If ``True``, will return the first element of the list/generator, which\n was used as the template. Useful if you need to map back from the\n matrix to a list of vectorizable objects.\n\n Returns\n -------\n M : (length, n_features) `ndarray`\n Every row is an element of the list.\n template : :map:`Vectorizable`, optional\n If ``return_template == True``, will return the template used to\n build the matrix `M`.\n\n Raises\n ------\n ValueError\n ``vectorizables`` terminates in fewer than ``length`` iterations\n \"\"\"\n # get the first element as the template and use it to configure the\n # data matrix\n if length is None:\n # samples is a list\n length = len(vectorizables)\n template = vectorizables[0]\n vectorizables = vectorizables[1:]\n else:\n # samples is an iterator\n template = next(vectorizables)\n n_features = template.n_parameters\n template_vector = template.as_vector()\n\n data = np.zeros((length, n_features), dtype=template_vector.dtype)\n if verbose:\n print('Allocated data matrix of size {} '\n '({} samples)'.format(bytes_str(data.nbytes), length))\n\n # now we can fill in the first element from the template\n data[0] = template_vector\n del template_vector\n\n # ensure we take at most the remaining length - 1 elements\n vectorizables = islice(vectorizables, length - 1)\n\n if verbose:\n vectorizables = print_progress(vectorizables, n_items=length, offset=1,\n prefix='Building data matrix',\n end_with_newline=False)\n\n # 1-based as we have the template vector set already\n i = 0\n for i, sample in enumerate(vectorizables, 1):\n data[i] = sample.as_vector()\n\n # we have exhausted the iterable, but did we get enough items?\n if i != length - 1: # -1\n raise ValueError('Incomplete data matrix due to early iterator '\n 'termination (expected {} items, got {})'.format(\n length, i + 1))\n\n if return_template:\n return data, template\n else:\n return data\n\n\ndef from_matrix(matrix, template):\n r\"\"\"\n Create a generator from a matrix given a template :map:`Vectorizable`\n objects as a template. The ``from_vector`` method will be used to\n reconstruct each object.\n\n If you want a list, warp the returned value in ``list()``.\n\n Parameters\n ----------\n matrix : (n_items, n_features) `ndarray`\n A matrix whereby every *row* represents the data of a vectorizable\n object.\n template : :map:`Vectorizable`\n The template object to use to reconstruct each row of the matrix with.\n\n Returns\n -------\n vectorizables : generator of :map:`Vectorizable`\n Every row of the matrix becomes an element of the list.\n \"\"\"\n return (template.from_vector(row) for row in matrix)\n" ]
[ [ "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jdebacker/taxdata
[ "c32d401a10a6c8f6e889d87c6cc72fd4338017b2" ]
[ "taxdata/puf/preppuf.py" ]
[ "\"\"\"\nScripts to clean up the raw PUF before matching\n\"\"\"\nimport numpy as np\n\n# RECIDs for aggregate variables by PUF year\nAGG_VARS = {\n 2009: [999999],\n 2010: [999998, 999999],\n 2011: [999996, 999997, 999998, 999999],\n}\n\n\ndef preppuf(puf, year):\n \"\"\"Prepares the PUF for mathcing\n\n Args:\n puf (DataFrame): the raw PUF file\n \"\"\"\n puf.columns = map(str.lower, puf.columns)\n # drop aggregate variables\n puf = puf[~puf[\"recid\"].isin(AGG_VARS[year])].copy()\n puf[\"filer\"] = 1\n puf[\"depne\"] = puf[[\"xocah\", \"xocawh\", \"xoodep\", \"xopar\"]].sum(axis=1)\n\n adjust = (\n puf[\"e03150\"]\n + puf[\"e03210\"]\n + puf[\"e03220\"]\n + puf[\"e03230\"]\n + puf[\"e03260\"]\n + puf[\"e03270\"]\n + puf[\"e03240\"]\n + puf[\"e03290\"]\n + puf[\"e03300\"]\n + puf[\"e03400\"]\n + puf[\"e03500\"]\n )\n puf[\"totincx\"] = puf[\"e00100\"] + adjust\n\n puf[\"sequence\"] = puf.index + 1\n puf[\"soiseq\"] = puf.index + 1\n puf[\"s006\"] /= 100\n puf[\"s006\"] *= 1.03\n\n puf[\"dep_stat\"] = puf[\"dsi\"]\n puf[\"agede\"] = np.where(puf[\"e02400\"] > 0, 1, 0)\n\n return puf\n" ]
[ [ "numpy.where" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
nbonacchi/ibllib
[ "9066c00a8e9a65a1d209144a2ac54d0b87bec0b3", "9066c00a8e9a65a1d209144a2ac54d0b87bec0b3", "9066c00a8e9a65a1d209144a2ac54d0b87bec0b3", "9066c00a8e9a65a1d209144a2ac54d0b87bec0b3" ]
[ "ibllib/tests/extractors/test_ephys_passive.py", "brainbox/examples/docs_scatter_raster_plot.py", "brainbox/tests/test_processing.py", "examples/archive/ibllib/qc_behaviour_bpod.py" ]
[ "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# @Author: Niccolò Bonacchi\n# @Date: Friday, October 30th 2020, 10:42:49 am\nimport unittest\n\nimport ibllib.io.extractors.ephys_passive as passive\nimport numpy as np\n\n\nclass TestsPassiveExtractor(unittest.TestCase):\n def setUp(self):\n pass\n\n def test_load_passive_stim_meta(self):\n meta = passive._load_passive_stim_meta()\n self.assertTrue(isinstance(meta, dict))\n\n def test_interpolate_rf_mapping_stimulus(self):\n idxs_up = np.array([0, 4, 8])\n idxs_dn = np.array([1, 5, 9])\n times = np.array([0, 1, 4, 5, 8, 9])\n Xq = np.arange(15)\n t_bin = 1 # Use 1 so can compare directly Xq and Tq\n Tq = passive._interpolate_rf_mapping_stimulus(\n idxs_up=idxs_up, idxs_dn=idxs_dn, times=times, Xq=Xq, t_bin=t_bin\n )\n self.assertTrue(np.array_equal(Tq, Xq))\n\n def tearDown(self):\n pass\n", "\"\"\"\r\nPlot raster across session\r\n==========================\r\nExample of how to plot scatter plot of spike depths vs spike times with colour and size of scatter\r\npoints scaled by spike amplitude\r\n\"\"\"\r\n\r\nimport numpy as np\r\nfrom brainbox.ephys_plots import scatter_raster_plot\r\nfrom brainbox.plot_base import plot_scatter\r\nfrom oneibl.one import ONE\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib\r\n\r\none = ONE()\r\n\r\neid = '671c7ea7-6726-4fbe-adeb-f89c2c8e489b'\r\nprobe = 'probe00'\r\n\r\nspikes = one.load_object(eid, obj='spikes', collection=f'alf/{probe}')\r\nmetrics = one.load_dataset(eid, dataset='clusters.metrics', collection=f'alf/{probe}')\r\n\r\n# Find the clusters that have been labelled as good and their corresponding spike indices\r\ngood_clusters = np.where(metrics.label == 1)\r\nspike_idx = np.where(np.isin(spikes['clusters'], good_clusters))[0]\r\n\r\n# Also filter for nans in amplitude and depth\r\nkp_idx = spike_idx[np.where(~np.isnan(spikes['depths'][spike_idx])\r\n & ~np.isnan(spikes['amps'][spike_idx]))[0]]\r\n\r\n# Get ScatterPlot object\r\ndata = scatter_raster_plot(spikes['amps'][kp_idx], spikes['depths'][kp_idx],\r\n spikes['times'][kp_idx])\r\n\r\n# Add v lines 10s after start and 10s before end or recording\r\nx1 = np.min(spikes['times'][kp_idx] + 100)\r\nx2 = np.max(spikes['times'][kp_idx] - 100)\r\ndata.add_lines(pos=x1, orientation='v', style='dashed', width=3, color='k')\r\ndata.add_lines(pos=x2, orientation='v', style='dashed', width=3, color='k')\r\n\r\n\r\nplot_dict = data.convert2dict()\r\n\r\nfig, ax = plot_scatter(plot_dict)\r\n\r\n", "from brainbox import processing, core\nimport unittest\nimport numpy as np\n\n\nclass TestProcessing(unittest.TestCase):\n\n def test_sync(self):\n # Test casting non-uniformly-sampled data to a evenly-sampled TimeSeries.\n # Begin by defining sampling intervals of random half-normally distributed length\n times = np.cumsum(np.abs(np.random.normal(loc=4., scale=6., size=100)))\n # take sample values as though the value was increasing as a cube of sample time\n samples = times**3\n # Use cubic interpolation to resample to uniform interval\n cubes = core.TimeSeries(times=times, values=samples, columns=('cubic',))\n resamp = processing.sync(0.1, timeseries=cubes, interp='cubic', fillval='extrapolate')\n # Check that the sync function is returning a new time series object\n self.assertTrue(isinstance(resamp, core.TimeSeries))\n # Test that all returned sample times are uniformly spaced\n # We need to use np.isclose because of floating point arithematic problems instead of ==0.1\n # Since the actual diff returns 0.09999999999999964\n self.assertTrue(np.all(np.isclose(np.diff(resamp.times), 0.1)))\n # Check that we're within a margin of error on the interpolation\n err_margin = 1e-3 # Maximum percent error allowed\n err_percs = np.abs(resamp.times**3 - resamp.values.T) / (resamp.times**3)\n self.assertTrue(np.all(err_percs < err_margin))\n # Make a second timeseries of square-law increasing samples\n times2 = np.cumsum(np.abs(np.random.normal(loc=2., scale=1., size=200)))\n samples2 = times2**2\n squares = core.TimeSeries(times=times2, values=samples2, columns=('square',))\n # Use cubic interpolation again, this time on both timeseries\n resamp2 = processing.sync(0.1, timeseries=[squares, cubes], interp='cubic',\n fillval='extrapolate')\n # Check that the new TS has both squares and cubes as keys and attribs\n self.assertTrue(hasattr(resamp2, 'cubic'))\n self.assertTrue(hasattr(resamp2, 'square'))\n # Check that both timeseries are fully contained in the resampled TS\n self.assertTrue(cubes.times.min() >= resamp2.times.min())\n self.assertTrue(cubes.times.max() <= resamp2.times.max())\n self.assertTrue(squares.times.min() >= resamp2.times.min())\n self.assertTrue(squares.times.max() <= resamp2.times.max())\n # Check that all interpolated values are within the margin of error against the known func\n sq_errperc = np.abs(resamp2.times**2 - resamp2.square) / resamp2.times**2\n cu_errperc = np.abs(resamp2.times**3 - resamp2.cubic) / resamp2.times**3\n self.assertTrue(np.all(sq_errperc < err_margin) & np.all(cu_errperc < err_margin))\n\n # Now check the numpy array behavior of sync.\n # Try running sync on the cubic times and values only.\n resamp = processing.sync(0.1, times=times, values=samples, interp='cubic',\n fillval='extrapolate')\n # Do all the tests we did for the instance created using TimeSeries objects\n self.assertTrue(isinstance(resamp, core.TimeSeries))\n self.assertTrue(np.all(np.isclose(np.diff(resamp.times), 0.1)))\n err_margin = 1e-3 # Maximum percent error allowed\n err_percs = np.abs(resamp.times**3 - resamp.values.T) / (resamp.times**3)\n self.assertTrue(np.all(err_percs < err_margin))\n # Try the multiple-arrays case in which we pass two times and two values\n resamp2 = processing.sync(0.1, times=(times, times2), values=(samples, samples2),\n interp='cubic', fillval='extrapolate')\n self.assertTrue(times.min() >= resamp2.times.min())\n self.assertTrue(times.max() <= resamp2.times.max())\n self.assertTrue(times2.min() >= resamp2.times.min())\n self.assertTrue(times2.max() <= resamp2.times.max())\n\n def test_bincount_2d(self):\n # first test simple with indices\n x = np.array([0, 1, 1, 2, 2, 3, 3, 3])\n y = np.array([3, 2, 2, 1, 1, 0, 0, 0])\n r, xscale, yscale = processing.bincount2D(x, y, xbin=1, ybin=1)\n r_ = np.zeros_like(r)\n # sometimes life would have been simpler in c:\n for ix, iy in zip(x, y):\n r_[iy, ix] += 1\n self.assertTrue(np.all(np.equal(r_, r)))\n # test with negative values\n y = np.array([3, 2, 2, 1, 1, 0, 0, 0]) - 5\n r, xscale, yscale = processing.bincount2D(x, y, xbin=1, ybin=1)\n self.assertTrue(np.all(np.equal(r_, r)))\n # test unequal bins\n r, xscale, yscale = processing.bincount2D(x / 2, y / 2, xbin=1, ybin=2)\n r_ = np.zeros_like(r)\n for ix, iy in zip(np.floor(x / 2), np.floor((y / 2 + 2.5) / 2)):\n r_[int(iy), int(ix)] += 1\n self.assertTrue(np.all(r_ == r))\n # test with weights\n w = np.ones_like(x) * 2\n r, xscale, yscale = processing.bincount2D(x / 2, y / 2, xbin=1, ybin=2, weights=w)\n self.assertTrue(np.all(r_ * 2 == r))\n # test aggregation instead of binning\n x = np.array([0, 1, 1, 2, 2, 4, 4, 4])\n y = np.array([4, 2, 2, 1, 1, 0, 0, 0])\n r, xscale, yscale = processing.bincount2D(x, y)\n self.assertTrue(np.all(xscale == yscale) and np.all(xscale == np.array([0, 1, 2, 4])))\n # test aggregation on a fixed scale\n r, xscale, yscale = processing.bincount2D(x + 10, y + 10, xbin=np.arange(5) + 10,\n ybin=np.arange(3) + 10)\n self.assertTrue(np.all(xscale == np.arange(5) + 10))\n self.assertTrue(np.all(yscale == np.arange(3) + 10))\n self.assertTrue(np.all(r.shape == (3, 5)))\n\n def test_compute_cluster_averag(self):\n # Create fake data for 3 clusters\n clust1 = np.ones(40)\n clust1_vals = np.ones(40) * 200\n clust2 = 2 * np.ones(40)\n clust2_vals = np.r_[np.ones(20) * 300, np.ones(20) * 500]\n clust100 = 100 * np.ones(50)\n clust100_vals = np.r_[np.ones(25) * 0.5, np.ones(25) * 1.0]\n\n # Concatenate data for 3 clusters together\n spike_clust = np.r_[clust1, clust2, clust100]\n spike_val = np.r_[clust1_vals, clust2_vals, clust100_vals]\n\n # Shuffle the data to make order random\n ind = np.arange(len(spike_clust))\n np.random.shuffle(ind)\n spike_clust = spike_clust[ind]\n spike_val = spike_val[ind]\n # Make sure the data you have created is correct dimension\n assert(len(spike_clust) == len(spike_val))\n\n # Compute the average value across clusters\n clust, avg_val, count = processing.compute_cluster_average(spike_clust, spike_val)\n\n # Check output is as expected\n assert(np.all(clust == (1, 2, 100)))\n assert(avg_val[0] == 200)\n assert(avg_val[1] == 400)\n assert (avg_val[2] == 0.75)\n assert(np.all(count == (40, 40, 50)))\n\n\ndef test_get_unit_bunches():\n pass\n\n\nif __name__ == \"__main__\":\n np.random.seed(0)\n unittest.main(exit=False)\n", "from pathlib import Path\n\nimport numpy as np\n\nfrom brainbox.core import Bunch\nfrom ibllib.io.raw_data_loaders import load_data, load_settings\n\n\"\"\"\ncf. extractors to get the trigger times from bpod\n- In version 5 and above, stim_trigger < stim_onset ~= cue_trigger < cue_onset ~= close_loop\n- stim_trigger - stim_onset : should max at 100ms. NaN if not detected. Cap number of Nans\nfor a session.\n- gocue_trigger - gocue_onset: get delay and count Nans\n- there should be exactly 1 step audio for a good trial, 2 steps. We know it can double up.\nHaving less is even more problematic\n\n- External data: Camera: count frames: video, timestamps and bpod\n- External data: wheel: check closed loop\n\"\"\"\n\n\ndef qc_behaviour_bpod_session(ses_path):\n ses_path = Path(ses_path)\n raw_trials = load_data(ses_path)\n settings = load_settings(ses_path)\n if not raw_trials:\n return\n n_trials = len(raw_trials)\n # getting the task protocol will be useful at some point\n settings['IBLRIG_VERSION_TAG']\n settings['PYBPOD_PROTOCOL']\n\n # important stuff is the relationship between GoCue Audio and the stim onset\n\n # init the QC dictionary: one row per trial\n qc_trials = Bunch({\n 'xor': np.zeros(n_trials, bool), # a trial is either an error, correct or a no-go\n 'correct_rewarded': np.zeros(n_trials) * np.nan, # a correct trial needs to be rewarded\n 'n_bnc1_high': np.zeros(n_trials) * np.nan, # number of bnc1 fronts\n 'n_bnc2_high': np.zeros(n_trials) * np.nan, # number of bnc2 fronts\n 'n_bnc1_low': np.zeros(n_trials) * np.nan, # number of bnc1 fronts\n 'n_bnc2_low': np.zeros(n_trials) * np.nan, # number of bnc2 fronts\n 'stim2cue': np.zeros(n_trials) * np.nan, # time elapsed between stim onset and audio cue\n\n })\n\n for m, raw_trial in enumerate(raw_trials):\n states = raw_trial['behavior_data']['States timestamps']\n # a trial is either an error, correct or a no-go. No in-between\n qc_trials.xor[m] = np.sum(int(np.all(np.isnan(states['error'][0]))) +\n int(np.all(np.isnan(states['correct'][0]))) +\n int(np.all(np.isnan(states['no_go'][0])))) == 2\n\n qc_trials.correct_rewarded[m] = (int(np.all(np.isnan(states['correct'][0]))) ==\n int(np.all(np.isnan(states['reward'][0]))))\n\n timestamps = raw_trial['behavior_data']['Events timestamps']\n qc_trials.n_bnc1_high[m] = len(timestamps['BNC1High'])\n qc_trials.n_bnc2_high[m] = len(timestamps['BNC2High'])\n qc_trials.n_bnc1_low[m] = len(timestamps['BNC1Low'])\n qc_trials.n_bnc2_low[m] = len(timestamps['BNC2Low'])\n\n qc_trials.stim2cue[m] = timestamps['BNC2High'][0] - states['stim_on'][0][0] # first BNC1\n\n\ndef get_session_flatiron():\n from oneibl.one import ONE\n one = ONE()\n ses = one.search(subjects='CSHL_003', date_range=['2019-04-17']) # session ok\n ses = one.search(subjects='CSHL_003', date_range=['2019-04-18']) # session has wrong reaction\n one.load(ses, dataset_types=['_iblrig_taskData.raw', '_iblrig_taskSettings.raw'],\n download_only=True)\n\n\nif __name__ == \"__main__\":\n ses_path = '/datadisk/Data/Subjects/ZM_1374/2019-03-24/001'\n ses_path = '/datadisk/FlatIron/churchlandlab/Subjects/CSHL_003/2019-04-17/001/'\n ses_path = '/datadisk/FlatIron/churchlandlab/Subjects/CSHL_003/2019-04-18/001/'\n qc_behaviour_bpod_session(ses_path)\n" ]
[ [ "numpy.arange", "numpy.array", "numpy.array_equal" ], [ "numpy.min", "numpy.isnan", "numpy.max", "numpy.where", "numpy.isin" ], [ "numpy.ones_like", "numpy.abs", "numpy.random.seed", "numpy.arange", "numpy.random.shuffle", "numpy.ones", "numpy.all", "numpy.random.normal", "numpy.zeros_like", "numpy.equal", "numpy.floor", "numpy.diff", "numpy.array" ], [ "numpy.isnan", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
lilyminium/openff-evaluator
[ "21da54363009d83110b54d57e4416ae31df3868b", "21da54363009d83110b54d57e4416ae31df3868b", "21da54363009d83110b54d57e4416ae31df3868b" ]
[ "openff/evaluator/datasets/curation/components/filtering.py", "openff/evaluator/tests/test_utils/test_serialization.py", "openff/evaluator/tests/test_protocols/test_gradient_protocols.py" ]
[ "import functools\nimport itertools\nimport logging\nfrom collections import defaultdict\nfrom typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union\n\nimport numpy\nimport pandas\nfrom pydantic import Field, root_validator, validator\nfrom scipy.optimize import linear_sum_assignment\nfrom typing_extensions import Literal\n\nfrom openff.evaluator.datasets.curation.components import (\n CurationComponent,\n CurationComponentSchema,\n)\nfrom openff.evaluator.datasets.utilities import (\n data_frame_to_substances,\n reorder_data_frame,\n)\nfrom openff.evaluator.utils.checkmol import (\n ChemicalEnvironment,\n analyse_functional_groups,\n)\n\nif TYPE_CHECKING:\n\n conint = int\n confloat = float\n PositiveInt = int\n PositiveFloat = float\n\nelse:\n\n from pydantic import PositiveFloat, PositiveInt, confloat, conint, constr\n\nlogger = logging.getLogger(__name__)\n\nComponentEnvironments = List[List[ChemicalEnvironment]]\nMoleFractionRange = Tuple[confloat(ge=0.0, le=1.0), confloat(ge=0.0, le=1.0)]\n\n\nclass FilterDuplicatesSchema(CurationComponentSchema):\n\n type: Literal[\"FilterDuplicates\"] = \"FilterDuplicates\"\n\n temperature_precision: conint(ge=0) = Field(\n 2,\n description=\"The number of decimal places to compare temperatures (K) to \"\n \"within.\",\n )\n pressure_precision: conint(ge=0) = Field(\n 3,\n description=\"The number of decimal places to compare pressures (kPa) to \"\n \"within.\",\n )\n mole_fraction_precision: conint(ge=0) = Field(\n 6,\n description=\"The number of decimal places to compare mole fractions to within.\",\n )\n\n\nclass FilterDuplicates(CurationComponent):\n \"\"\"A component to remove duplicate data points (within a specified precision)\n from a data set.\n \"\"\"\n\n @classmethod\n def _apply(\n cls, data_frame: pandas.DataFrame, schema: FilterDuplicatesSchema, n_processes\n ) -> pandas.DataFrame:\n\n if len(data_frame) == 0:\n return data_frame\n\n data_frame = data_frame.copy()\n data_frame = reorder_data_frame(data_frame)\n\n minimum_n_components = data_frame[\"N Components\"].min()\n maximum_n_components = data_frame[\"N Components\"].max()\n\n filtered_data = []\n\n for n_components in range(minimum_n_components, maximum_n_components + 1):\n\n component_data = data_frame[\n data_frame[\"N Components\"] == n_components\n ].copy()\n\n component_data[\"Temperature (K)\"] = component_data[\"Temperature (K)\"].round(\n schema.temperature_precision\n )\n component_data[\"Pressure (kPa)\"] = component_data[\"Pressure (kPa)\"].round(\n schema.pressure_precision\n )\n\n subset_columns = [\"Temperature (K)\", \"Pressure (kPa)\", \"Phase\"]\n\n for index in range(n_components):\n\n component_data[f\"Mole Fraction {index + 1}\"] = component_data[\n f\"Mole Fraction {index + 1}\"\n ].round(schema.mole_fraction_precision)\n\n subset_columns.extend(\n [\n f\"Component {index + 1}\",\n f\"Role {index + 1}\",\n f\"Mole Fraction {index + 1}\",\n f\"Exact Amount {index + 1}\",\n ]\n )\n\n subset_columns = [x for x in subset_columns if x in component_data]\n value_headers = [x for x in component_data if x.find(\" Value \") >= 0]\n\n sorted_filtered_data = []\n\n for value_header in value_headers:\n\n uncertainty_header = value_header.replace(\"Value\", \"Uncertainty\")\n\n property_data = component_data[component_data[value_header].notna()]\n\n if uncertainty_header in component_data:\n property_data = property_data.sort_values(uncertainty_header)\n\n property_data = property_data.drop_duplicates(\n subset=subset_columns, keep=\"last\"\n )\n\n sorted_filtered_data.append(property_data)\n\n sorted_filtered_data = pandas.concat(\n sorted_filtered_data, ignore_index=True, sort=False\n )\n\n filtered_data.append(sorted_filtered_data)\n\n filtered_data = pandas.concat(filtered_data, ignore_index=True, sort=False)\n return filtered_data\n\n\nclass FilterByTemperatureSchema(CurationComponentSchema):\n\n type: Literal[\"FilterByTemperature\"] = \"FilterByTemperature\"\n\n minimum_temperature: Optional[PositiveFloat] = Field(\n ...,\n description=\"Retain data points measured for temperatures above this value (K)\",\n )\n maximum_temperature: Optional[PositiveFloat] = Field(\n ...,\n description=\"Retain data points measured for temperatures below this value (K)\",\n )\n\n @root_validator\n def _min_max(cls, values):\n minimum_temperature = values.get(\"minimum_temperature\")\n maximum_temperature = values.get(\"maximum_temperature\")\n\n if minimum_temperature is not None and maximum_temperature is not None:\n assert maximum_temperature > minimum_temperature\n\n return values\n\n\nclass FilterByTemperature(CurationComponent):\n \"\"\"A component which will filter out data points which were measured outside of a\n specified temperature range\n \"\"\"\n\n @classmethod\n def _apply(\n cls,\n data_frame: pandas.DataFrame,\n schema: FilterByTemperatureSchema,\n n_processes,\n ) -> pandas.DataFrame:\n\n filtered_frame = data_frame\n\n if schema.minimum_temperature is not None:\n filtered_frame = filtered_frame[\n schema.minimum_temperature < filtered_frame[\"Temperature (K)\"]\n ]\n\n if schema.maximum_temperature is not None:\n filtered_frame = filtered_frame[\n filtered_frame[\"Temperature (K)\"] < schema.maximum_temperature\n ]\n\n return filtered_frame\n\n\nclass FilterByPressureSchema(CurationComponentSchema):\n\n type: Literal[\"FilterByPressure\"] = \"FilterByPressure\"\n\n minimum_pressure: Optional[PositiveFloat] = Field(\n ...,\n description=\"Retain data points measured for pressures above this value (kPa)\",\n )\n maximum_pressure: Optional[PositiveFloat] = Field(\n ...,\n description=\"Retain data points measured for pressures below this value (kPa)\",\n )\n\n @root_validator\n def _min_max(cls, values):\n minimum_pressure = values.get(\"minimum_pressure\")\n maximum_pressure = values.get(\"maximum_pressure\")\n\n if minimum_pressure is not None and maximum_pressure is not None:\n assert maximum_pressure > minimum_pressure\n\n return values\n\n\nclass FilterByPressure(CurationComponent):\n \"\"\"A component which will filter out data points which were measured outside of a\n specified pressure range.\n \"\"\"\n\n @classmethod\n def _apply(\n cls, data_frame: pandas.DataFrame, schema: FilterByPressureSchema, n_processes\n ) -> pandas.DataFrame:\n\n filtered_frame = data_frame\n\n if schema.minimum_pressure is not None:\n filtered_frame = filtered_frame[\n schema.minimum_pressure < filtered_frame[\"Pressure (kPa)\"]\n ]\n\n if schema.maximum_pressure is not None:\n filtered_frame = filtered_frame[\n filtered_frame[\"Pressure (kPa)\"] < schema.maximum_pressure\n ]\n\n return filtered_frame\n\n\nclass FilterByMoleFractionSchema(CurationComponentSchema):\n\n type: Literal[\"FilterByMoleFraction\"] = \"FilterByMoleFraction\"\n\n mole_fraction_ranges: Dict[conint(gt=1), List[List[MoleFractionRange]]] = Field(\n ...,\n description=\"The ranges of mole fractions to retain. Each key in the \"\n \"dictionary corresponds to a number of components in the system. Each value \"\n \"is a list of the allowed mole fraction ranges for all but one of the \"\n \"components, i.e for a binary system, the allowed mole fraction for only the \"\n \"first component must be specified.\",\n )\n\n @validator(\"mole_fraction_ranges\")\n def _validate_ranges(cls, value: Dict[int, List[List[MoleFractionRange]]]):\n\n for n_components, ranges in value.items():\n\n assert len(ranges) == n_components - 1\n\n assert all(\n mole_fraction_range[0] < mole_fraction_range[1]\n for component_ranges in ranges\n for mole_fraction_range in component_ranges\n )\n\n return value\n\n\nclass FilterByMoleFraction(CurationComponent):\n \"\"\"A component which will filter out data points which were measured outside of a\n specified mole fraction range.\n \"\"\"\n\n @classmethod\n def _apply(\n cls,\n data_frame: pandas.DataFrame,\n schema: FilterByMoleFractionSchema,\n n_processes,\n ) -> pandas.DataFrame:\n\n filtered_frame = data_frame\n\n full_query = ~filtered_frame[\"N Components\"].isin(schema.mole_fraction_ranges)\n\n for n_components, ranges in schema.mole_fraction_ranges.items():\n\n # Build the query to apply\n n_component_query = filtered_frame[\"N Components\"] == n_components\n\n for index, component_ranges in enumerate(ranges):\n\n component_query = None\n\n for mole_fraction_range in component_ranges:\n\n fraction_query = (\n filtered_frame[f\"Mole Fraction {index + 1}\"]\n > mole_fraction_range[0]\n ) & (\n filtered_frame[f\"Mole Fraction {index + 1}\"]\n < mole_fraction_range[1]\n )\n\n if component_query is None:\n component_query = fraction_query\n else:\n component_query |= fraction_query\n\n n_component_query &= component_query\n\n full_query |= n_component_query\n\n filtered_frame = filtered_frame[full_query]\n return filtered_frame\n\n\nclass FilterByRacemicSchema(CurationComponentSchema):\n\n type: Literal[\"FilterByRacemic\"] = \"FilterByRacemic\"\n\n\nclass FilterByRacemic(CurationComponent):\n \"\"\"A component which will filter out data points which were measured for racemic\n mixtures.\n \"\"\"\n\n @classmethod\n def _apply(\n cls,\n data_frame: pandas.DataFrame,\n schema: FilterByMoleFractionSchema,\n n_processes,\n ) -> pandas.DataFrame:\n\n # Begin building the query. All pure substances should be\n # retained by default.\n query = data_frame[\"N Components\"] < 2\n\n for n_components in range(2, data_frame[\"N Components\"].max() + 1):\n\n component_data = data_frame[data_frame[\"N Components\"] == n_components]\n\n if len(component_data) == 0:\n continue\n\n component_combinations = itertools.combinations(range(n_components), 2)\n\n is_racemic = None\n\n for index_0, index_1 in component_combinations:\n\n components_racemic = component_data[\n f\"Component {index_0 + 1}\"\n ].str.replace(\"@\", \"\") == component_data[\n f\"Component {index_1 + 1}\"\n ].str.replace(\n \"@\", \"\"\n )\n\n is_racemic = (\n components_racemic\n if is_racemic is None\n else (is_racemic | components_racemic)\n )\n\n not_racemic = ~is_racemic\n query |= not_racemic\n\n filtered_frame = data_frame[query]\n return filtered_frame\n\n\nclass FilterByElementsSchema(CurationComponentSchema):\n\n type: Literal[\"FilterByElements\"] = \"FilterByElements\"\n\n allowed_elements: Optional[List[constr(min_length=1)]] = Field(\n None,\n description=\"The only elements which must be present in the measured system \"\n \"for the data point to be retained. This option is mutually exclusive with \"\n \"`forbidden_elements`\",\n )\n forbidden_elements: Optional[List[constr(min_length=1)]] = Field(\n None,\n description=\"The elements which must not be present in the measured system for \"\n \"the data point to be retained. This option is mutually exclusive with \"\n \"`allowed_elements`\",\n )\n\n @root_validator\n def _validate_mutually_exclusive(cls, values):\n\n allowed_elements = values.get(\"allowed_elements\")\n forbidden_elements = values.get(\"forbidden_elements\")\n\n assert allowed_elements is not None or forbidden_elements is not None\n assert allowed_elements is None or forbidden_elements is None\n\n return values\n\n\nclass FilterByElements(CurationComponent):\n \"\"\"A component which will filter out data points which were measured for systems\n which contain specific elements.\"\"\"\n\n @classmethod\n def _apply(\n cls, data_frame: pandas.DataFrame, schema: FilterByElementsSchema, n_processes\n ) -> pandas.DataFrame:\n\n from openff.toolkit.topology import Molecule\n\n def filter_function(data_row):\n\n n_components = data_row[\"N Components\"]\n\n for index in range(n_components):\n\n smiles = data_row[f\"Component {index + 1}\"]\n molecule = Molecule.from_smiles(smiles, allow_undefined_stereo=True)\n\n if schema.allowed_elements is not None and not all(\n [\n x.element.symbol in schema.allowed_elements\n for x in molecule.atoms\n ]\n ):\n return False\n\n if schema.forbidden_elements is not None and any(\n [\n x.element.symbol in schema.forbidden_elements\n for x in molecule.atoms\n ]\n ):\n return False\n\n return True\n\n # noinspection PyTypeChecker\n return data_frame[data_frame.apply(filter_function, axis=1)]\n\n\nclass FilterByPropertyTypesSchema(CurationComponentSchema):\n\n type: Literal[\"FilterByPropertyTypes\"] = \"FilterByPropertyTypes\"\n\n property_types: List[constr(min_length=1)] = Field(\n ...,\n description=\"The types of property to retain.\",\n )\n n_components: Dict[constr(min_length=1), List[PositiveInt]] = Field(\n default_factory=dict,\n description=\"Optionally specify the number of components that a property \"\n \"should have been measured for (e.g. pure, binary) in order for that data \"\n \"point to be retained.\",\n )\n\n strict: bool = Field(\n False,\n description=\"If true, only substances (defined without consideration for their \"\n \"mole fractions or exact amount) which have data available for all of the \"\n \"specified property types will be retained. Note that the data points aren't \"\n \"required to have been measured at the same state.\",\n )\n\n @root_validator\n def _validate_n_components(cls, values):\n\n property_types = values.get(\"property_types\")\n n_components = values.get(\"n_components\")\n\n assert all(x in property_types for x in n_components)\n\n return values\n\n\nclass FilterByPropertyTypes(CurationComponent):\n \"\"\"A component which will apply a filter which only retains properties of specified\n types.\"\"\"\n\n @classmethod\n def _apply(\n cls,\n data_frame: pandas.DataFrame,\n schema: FilterByPropertyTypesSchema,\n n_processes,\n ) -> pandas.DataFrame:\n\n property_headers = [\n header for header in data_frame if header.find(\" Value \") >= 0\n ]\n\n # Removes the columns for properties which are not of interest.\n for header in property_headers:\n\n property_type = header.split(\" \")[0]\n\n if property_type in schema.property_types:\n continue\n\n data_frame = data_frame.drop(header, axis=1)\n\n uncertainty_header = header.replace(\" Value \", \" Uncertainty \")\n\n if uncertainty_header in data_frame:\n data_frame = data_frame.drop(uncertainty_header, axis=1)\n\n # Drop any rows which do not contain any values for the property types of\n # interest.\n property_headers = [\n header\n for header in property_headers\n if header.split(\" \")[0] in schema.property_types\n ]\n\n data_frame = data_frame.dropna(subset=property_headers, how=\"all\")\n\n # Apply a more specific filter which only retain which contain values\n # for the specific property types, and which were measured for the\n # specified number of components.\n for property_type, n_components in schema.n_components.items():\n\n property_header = next(\n iter(x for x in property_headers if x.find(f\"{property_type} \") == 0),\n None,\n )\n\n if property_header is None:\n continue\n\n data_frame = data_frame[\n data_frame[property_header].isna()\n | data_frame[\"N Components\"].isin(n_components)\n ]\n\n # Apply the strict filter if requested\n if schema.strict:\n\n reordered_data_frame = reorder_data_frame(data_frame)\n\n # Build a dictionary of which properties should be present partitioned\n # by the number of components they should have been be measured for.\n property_types = defaultdict(list)\n\n if len(schema.n_components) > 0:\n\n for property_type, n_components in schema.n_components.items():\n\n for n_component in n_components:\n property_types[n_component].append(property_type)\n\n min_n_components = min(property_types)\n max_n_components = max(property_types)\n\n else:\n\n min_n_components = reordered_data_frame[\"N Components\"].min()\n max_n_components = reordered_data_frame[\"N Components\"].max()\n\n for n_components in range(min_n_components, max_n_components + 1):\n property_types[n_components].extend(schema.property_types)\n\n substances_with_data = set()\n components_with_data = {}\n\n # For each N component find substances which have data points for\n # all of the specified property types.\n for n_components in range(min_n_components, max_n_components + 1):\n\n component_data = reordered_data_frame[\n reordered_data_frame[\"N Components\"] == n_components\n ]\n\n if n_components not in property_types or len(component_data) == 0:\n continue\n\n n_component_headers = [\n header\n for header in property_headers\n if header.split(\" \")[0] in property_types[n_components]\n and header in component_data\n ]\n\n if len(n_component_headers) != len(property_types[n_components]):\n continue\n\n n_component_substances = set.intersection(\n *[\n data_frame_to_substances(\n component_data[component_data[header].notna()]\n )\n for header in n_component_headers\n ]\n )\n substances_with_data.update(n_component_substances)\n components_with_data[n_components] = {\n component\n for substance in n_component_substances\n for component in substance\n }\n\n if len(schema.n_components) > 0:\n components_with_all_data = set.intersection(\n *components_with_data.values()\n )\n\n # Filter out any smiles for don't appear in all of the N component\n # substances.\n data_frame = FilterBySmiles.apply(\n data_frame,\n FilterBySmilesSchema(smiles_to_include=[*components_with_all_data]),\n )\n\n # Filter out any substances which (within each N component) don't have\n # all of the specified data types.\n data_frame = FilterBySubstances.apply(\n data_frame,\n FilterBySubstancesSchema(substances_to_include=[*substances_with_data]),\n )\n\n data_frame = data_frame.dropna(axis=1, how=\"all\")\n return data_frame\n\n\nclass FilterByStereochemistrySchema(CurationComponentSchema):\n\n type: Literal[\"FilterByStereochemistry\"] = \"FilterByStereochemistry\"\n\n\nclass FilterByStereochemistry(CurationComponent):\n \"\"\"A component which filters out data points measured for systems whereby the\n stereochemistry of a number of components is undefined.\"\"\"\n\n @classmethod\n def _apply(\n cls,\n data_frame: pandas.DataFrame,\n schema: FilterByStereochemistrySchema,\n n_processes,\n ) -> pandas.DataFrame:\n\n from openff.toolkit.topology import Molecule\n from openff.toolkit.utils import UndefinedStereochemistryError\n\n def filter_function(data_row):\n\n n_components = data_row[\"N Components\"]\n\n for index in range(n_components):\n\n smiles = data_row[f\"Component {index + 1}\"]\n\n try:\n Molecule.from_smiles(smiles)\n except UndefinedStereochemistryError:\n return False\n\n return True\n\n # noinspection PyTypeChecker\n return data_frame[data_frame.apply(filter_function, axis=1)]\n\n\nclass FilterByChargedSchema(CurationComponentSchema):\n\n type: Literal[\"FilterByCharged\"] = \"FilterByCharged\"\n\n\nclass FilterByCharged(CurationComponent):\n \"\"\"A component which filters out data points measured for substances where any of\n the constituent components have a net non-zero charge.\n \"\"\"\n\n @classmethod\n def _apply(\n cls, data_frame: pandas.DataFrame, schema: FilterByChargedSchema, n_processes\n ) -> pandas.DataFrame:\n\n from openff.toolkit.topology import Molecule\n from simtk import unit as simtk_unit\n\n def filter_function(data_row):\n\n n_components = data_row[\"N Components\"]\n\n for index in range(n_components):\n\n smiles = data_row[f\"Component {index + 1}\"]\n molecule = Molecule.from_smiles(smiles, allow_undefined_stereo=True)\n\n # noinspection PyUnresolvedReferences\n atom_charges = [\n atom.formal_charge\n if isinstance(atom.formal_charge, int)\n else atom.formal_charge.value_in_unit(simtk_unit.elementary_charge)\n for atom in molecule.atoms\n ]\n\n if numpy.isclose(sum(atom_charges), 0.0):\n continue\n\n return False\n\n return True\n\n # noinspection PyTypeChecker\n return data_frame[data_frame.apply(filter_function, axis=1)]\n\n\nclass FilterByIonicLiquidSchema(CurationComponentSchema):\n type: Literal[\"FilterByIonicLiquid\"] = \"FilterByIonicLiquid\"\n\n\nclass FilterByIonicLiquid(CurationComponent):\n \"\"\"A component which filters out data points measured for substances which\n contain or are classed as an ionic liquids.\n \"\"\"\n\n @classmethod\n def _apply(\n cls,\n data_frame: pandas.DataFrame,\n schema: FilterByIonicLiquidSchema,\n n_processes,\n ) -> pandas.DataFrame:\n def filter_function(data_row):\n\n n_components = data_row[\"N Components\"]\n\n for index in range(n_components):\n\n smiles = data_row[f\"Component {index + 1}\"]\n\n if \".\" in smiles:\n return False\n\n return True\n\n # noinspection PyTypeChecker\n return data_frame[data_frame.apply(filter_function, axis=1)]\n\n\nclass FilterBySmilesSchema(CurationComponentSchema):\n type: Literal[\"FilterBySmiles\"] = \"FilterBySmiles\"\n\n smiles_to_include: Optional[List[str]] = Field(\n None,\n description=\"The smiles patterns to retain. This option is mutually \"\n \"exclusive with `smiles_to_exclude`\",\n )\n smiles_to_exclude: Optional[List[str]] = Field(\n None,\n description=\"The smiles patterns to exclude. This option is mutually \"\n \"exclusive with `smiles_to_include`\",\n )\n allow_partial_inclusion: bool = Field(\n False,\n description=\"If False, all the components in a substance must appear in \"\n \"the `smiles_to_include` list, otherwise, only some must appear. \"\n \"This option only applies when `smiles_to_include` is set.\",\n )\n\n @root_validator\n def _validate_mutually_exclusive(cls, values):\n\n smiles_to_include = values.get(\"smiles_to_include\")\n smiles_to_exclude = values.get(\"smiles_to_exclude\")\n\n assert smiles_to_include is not None or smiles_to_exclude is not None\n assert smiles_to_include is None or smiles_to_exclude is None\n\n return values\n\n\nclass FilterBySmiles(CurationComponent):\n \"\"\"A component which filters the data set so that it only contains either a\n specific set of smiles, or does not contain any of a set of specifically excluded\n smiles.\n \"\"\"\n\n @classmethod\n def _apply(\n cls, data_frame: pandas.DataFrame, schema: FilterBySmilesSchema, n_processes\n ) -> pandas.DataFrame:\n\n smiles_to_include = schema.smiles_to_include\n smiles_to_exclude = schema.smiles_to_exclude\n\n if smiles_to_include is not None:\n smiles_to_exclude = []\n elif smiles_to_exclude is not None:\n smiles_to_include = []\n\n def filter_function(data_row):\n\n n_components = data_row[\"N Components\"]\n\n component_smiles = [\n data_row[f\"Component {index + 1}\"] for index in range(n_components)\n ]\n\n if any(x in smiles_to_exclude for x in component_smiles):\n return False\n elif len(smiles_to_exclude) > 0:\n return True\n\n if not schema.allow_partial_inclusion and not all(\n x in smiles_to_include for x in component_smiles\n ):\n return False\n\n if schema.allow_partial_inclusion and not any(\n x in smiles_to_include for x in component_smiles\n ):\n return False\n\n return True\n\n # noinspection PyTypeChecker\n return data_frame[data_frame.apply(filter_function, axis=1)]\n\n\nclass FilterBySmirksSchema(CurationComponentSchema):\n\n type: Literal[\"FilterBySmirks\"] = \"FilterBySmirks\"\n\n smirks_to_include: Optional[List[str]] = Field(\n None,\n description=\"The smirks patterns which must be matched by a substance in \"\n \"order to retain a measurement. This option is mutually exclusive with \"\n \"`smirks_to_exclude`\",\n )\n smirks_to_exclude: Optional[List[str]] = Field(\n None,\n description=\"The smirks patterns which must not be matched by a substance in \"\n \"order to retain a measurement. This option is mutually exclusive with \"\n \"`smirks_to_include`\",\n )\n allow_partial_inclusion: bool = Field(\n False,\n description=\"If False, all the components in a substance must match at least \"\n \"one pattern in `smirks_to_include` in order to retain a measurement, \"\n \"otherwise, only a least one component must match. This option only applies \"\n \"when `smirks_to_include` is set.\",\n )\n\n @root_validator\n def _validate_mutually_exclusive(cls, values):\n\n smirks_to_include = values.get(\"smirks_to_include\")\n smirks_to_exclude = values.get(\"smirks_to_exclude\")\n\n assert smirks_to_include is not None or smirks_to_exclude is not None\n assert smirks_to_include is None or smirks_to_exclude is None\n\n return values\n\n\nclass FilterBySmirks(CurationComponent):\n \"\"\"A component which filters a data set so that it only contains measurements made\n for molecules which contain (or don't) a set of chemical environments\n represented by SMIRKS patterns.\n \"\"\"\n\n @staticmethod\n @functools.lru_cache(1000)\n def _find_smirks_matches(smiles_pattern, *smirks_patterns):\n \"\"\"Determines which (if any) of the specified smirks match the specified\n molecule.\n\n Parameters\n ----------\n smiles_pattern: str\n The SMILES representation to try and match against.\n smirks_patterns: str\n The smirks patterns to try and match.\n\n Returns\n -------\n list of str\n The matched smirks patterns.\n \"\"\"\n\n from openff.toolkit.topology import Molecule\n\n if len(smirks_patterns) == 0:\n return []\n\n molecule = Molecule.from_smiles(smiles_pattern, allow_undefined_stereo=True)\n\n matches = [\n smirks\n for smirks in smirks_patterns\n if len(molecule.chemical_environment_matches(smirks)) > 0\n ]\n\n return matches\n\n @classmethod\n def _apply(\n cls, data_frame: pandas.DataFrame, schema: FilterBySmirksSchema, n_processes\n ) -> pandas.DataFrame:\n\n smirks_to_match = (\n schema.smirks_to_include\n if schema.smirks_to_include\n else schema.smirks_to_exclude\n )\n\n def filter_function(data_row):\n\n n_components = data_row[\"N Components\"]\n\n component_smiles = [\n data_row[f\"Component {index + 1}\"] for index in range(n_components)\n ]\n\n smirks_matches = {\n smiles: cls._find_smirks_matches(smiles, *smirks_to_match)\n for smiles in component_smiles\n }\n\n if schema.smirks_to_exclude is not None:\n return not any(len(x) > 0 for x in smirks_matches.values())\n\n if schema.allow_partial_inclusion:\n return any(len(x) > 0 for x in smirks_matches.values())\n\n return all(len(x) > 0 for x in smirks_matches.values())\n\n # noinspection PyTypeChecker\n return data_frame[data_frame.apply(filter_function, axis=1)]\n\n\nclass FilterByNComponentsSchema(CurationComponentSchema):\n\n type: Literal[\"FilterByNComponents\"] = \"FilterByNComponents\"\n\n n_components: List[PositiveInt] = Field(\n ...,\n description=\"The number of components that measurements should have been \"\n \"measured for in order to be retained.\",\n )\n\n\nclass FilterByNComponents(CurationComponent):\n \"\"\"A component which filters out data points measured for systems with specified\n number of components.\n \"\"\"\n\n @classmethod\n def _apply(\n cls,\n data_frame: pandas.DataFrame,\n schema: FilterByNComponentsSchema,\n n_processes,\n ) -> pandas.DataFrame:\n\n return data_frame[data_frame[\"N Components\"].isin(schema.n_components)]\n\n\nclass FilterBySubstancesSchema(CurationComponentSchema):\n\n type: Literal[\"FilterBySubstances\"] = \"FilterBySubstances\"\n\n substances_to_include: Optional[List[Tuple[str, ...]]] = Field(\n None,\n description=\"The substances compositions to retain, where each tuple in the \"\n \"list contains the smiles patterns which make up the substance to include. \"\n \"This option is mutually exclusive with `substances_to_exclude`.\",\n )\n substances_to_exclude: Optional[List[Tuple[str, ...]]] = Field(\n None,\n description=\"The substances compositions to retain, where each tuple in the \"\n \"list contains the smiles patterns which make up the substance to exclude. \"\n \"This option is mutually exclusive with `substances_to_include`.\",\n )\n\n @root_validator\n def _validate_mutually_exclusive(cls, values):\n\n substances_to_include = values.get(\"substances_to_include\")\n substances_to_exclude = values.get(\"substances_to_exclude\")\n\n assert substances_to_include is not None or substances_to_exclude is not None\n assert substances_to_include is None or substances_to_exclude is None\n\n return values\n\n\nclass FilterBySubstances(CurationComponent):\n \"\"\"A component which filters the data set so that it only contains properties\n measured for particular substances.\n\n This method is similar to `filter_by_smiles`, however here we explicitly define\n the full substances compositions, rather than individual smiles which should\n either be included or excluded.\n\n Examples\n --------\n To filter the data set to only include measurements for pure methanol, pure\n benzene or an aqueous ethanol mix:\n\n >>> schema = FilterBySubstancesSchema(\n >>> substances_to_include=[\n >>> ('CO',),\n >>> ('C1=CC=CC=C1',),\n >>> ('CCO', 'O')\n >>> ]\n >>> )\n\n To filter out measurements made for an aqueous mix of benzene:\n\n >>> schema = FilterBySubstancesSchema(\n >>> substances_to_exclude=[('O', 'C1=CC=CC=C1')]\n >>> )\n \"\"\"\n\n @classmethod\n def _apply(\n cls, data_frame: pandas.DataFrame, schema: FilterBySubstancesSchema, n_processes\n ) -> pandas.DataFrame:\n def filter_function(data_row):\n\n n_components = data_row[\"N Components\"]\n\n substances_to_include = schema.substances_to_include\n substances_to_exclude = schema.substances_to_exclude\n\n if substances_to_include is not None:\n substances_to_include = [\n tuple(sorted(x)) for x in substances_to_include\n ]\n if substances_to_exclude is not None:\n substances_to_exclude = [\n tuple(sorted(x)) for x in substances_to_exclude\n ]\n\n substance = tuple(\n sorted(\n [\n data_row[f\"Component {index + 1}\"]\n for index in range(n_components)\n ]\n )\n )\n\n return (\n substances_to_exclude is not None\n and substance not in substances_to_exclude\n ) or (\n substances_to_include is not None and substance in substances_to_include\n )\n\n # noinspection PyTypeChecker\n return data_frame[data_frame.apply(filter_function, axis=1)]\n\n\nclass FilterByEnvironmentsSchema(CurationComponentSchema):\n\n type: Literal[\"FilterByEnvironments\"] = \"FilterByEnvironments\"\n\n per_component_environments: Optional[Dict[int, ComponentEnvironments]] = Field(\n None,\n description=\"The environments which should be present in the components of \"\n \"the substance for which the measurements were made. Each dictionary \"\n \"key corresponds to a number of components in the system, and each \"\n \"value the environments which should be matched by those n components. \"\n \"This option is mutually exclusive with `environments`.\",\n )\n environments: Optional[List[ChemicalEnvironment]] = Field(\n None,\n description=\"The environments which should be present in the substances for \"\n \"which measurements were made. This option is mutually exclusive with \"\n \"`per_component_environments`.\",\n )\n\n at_least_one_environment: bool = Field(\n True,\n description=\"If true, data points will only be retained if all of the \"\n \"components in the measured system contain at least one of the specified \"\n \"environments. This option is mutually exclusive with \"\n \"`strictly_specified_environments`.\",\n )\n strictly_specified_environments: bool = Field(\n False,\n description=\"If true, data points will only be retained if all of the \"\n \"components in the measured system strictly contain only the specified \"\n \"environments and no others. This option is mutually exclusive with \"\n \"`at_least_one_environment`.\",\n )\n\n @validator(\"per_component_environments\")\n def _validate_per_component_environments(cls, value):\n\n if value is None:\n return value\n\n assert all(len(y) == x for x, y in value.items())\n return value\n\n @root_validator\n def _validate_mutually_exclusive(cls, values):\n\n at_least_one_environment = values.get(\"at_least_one_environment\")\n strictly_specified_environments = values.get(\"strictly_specified_environments\")\n\n assert (\n at_least_one_environment is True or strictly_specified_environments is True\n )\n assert (\n at_least_one_environment is False\n or strictly_specified_environments is False\n )\n\n per_component_environments = values.get(\"per_component_environments\")\n environments = values.get(\"environments\")\n\n assert per_component_environments is not None or environments is not None\n assert per_component_environments is None or environments is None\n\n return values\n\n\nclass FilterByEnvironments(CurationComponent):\n \"\"\"A component which filters a data set so that it only contains measurements made\n for substances which contain specific chemical environments.\n \"\"\"\n\n @classmethod\n def _find_environments_per_component(cls, data_row: pandas.Series):\n\n n_components = data_row[\"N Components\"]\n\n component_smiles = [\n data_row[f\"Component {index + 1}\"] for index in range(n_components)\n ]\n component_moieties = [analyse_functional_groups(x) for x in component_smiles]\n\n if any(x is None for x in component_moieties):\n\n logger.info(\n f\"Checkmol was unable to parse the system with components=\"\n f\"{component_smiles} and so this data point was discarded.\"\n )\n\n return None\n\n return component_moieties\n\n @classmethod\n def _is_match(cls, component_environments, environments_to_match, schema):\n\n operator = all if schema.strictly_specified_environments else any\n\n return operator(\n environment in environments_to_match\n for environment in component_environments\n )\n\n @classmethod\n def _filter_by_environments(cls, data_row, schema: FilterByEnvironmentsSchema):\n\n environments_per_component = cls._find_environments_per_component(data_row)\n\n if environments_per_component is None:\n return False\n\n return all(\n cls._is_match(component_environments, schema.environments, schema)\n for component_environments in environments_per_component\n )\n\n @classmethod\n def _filter_by_per_component(cls, data_row, schema: FilterByEnvironmentsSchema):\n\n n_components = data_row[\"N Components\"]\n\n if (\n schema.per_component_environments is not None\n and n_components not in schema.per_component_environments\n ):\n # No filter was specified for this number of components.\n return True\n\n environments_per_component = cls._find_environments_per_component(data_row)\n\n if environments_per_component is None:\n return False\n\n match_matrix = numpy.zeros((n_components, n_components))\n\n for component_index, component_environments in enumerate(\n environments_per_component\n ):\n\n # noinspection PyUnresolvedReferences\n for environments_index, environments_to_match in enumerate(\n schema.per_component_environments[n_components]\n ):\n\n match_matrix[component_index, environments_index] = cls._is_match(\n component_environments, environments_to_match, schema\n )\n\n x_indices, y_indices = linear_sum_assignment(match_matrix, maximize=True)\n\n return numpy.all(match_matrix[x_indices, y_indices] > 0)\n\n @classmethod\n def _apply(\n cls,\n data_frame: pandas.DataFrame,\n schema: FilterByEnvironmentsSchema,\n n_processes,\n ) -> pandas.DataFrame:\n\n if schema.environments is not None:\n filter_function = functools.partial(\n cls._filter_by_environments, schema=schema\n )\n else:\n filter_function = functools.partial(\n cls._filter_by_per_component, schema=schema\n )\n\n # noinspection PyTypeChecker\n return data_frame[data_frame.apply(filter_function, axis=1)]\n\n\nFilterComponentSchema = Union[\n FilterDuplicatesSchema,\n FilterByTemperatureSchema,\n FilterByPressureSchema,\n FilterByMoleFractionSchema,\n FilterByRacemicSchema,\n FilterByElementsSchema,\n FilterByPropertyTypesSchema,\n FilterByStereochemistrySchema,\n FilterByChargedSchema,\n FilterByIonicLiquidSchema,\n FilterBySmilesSchema,\n FilterBySmirksSchema,\n FilterByNComponentsSchema,\n FilterBySubstancesSchema,\n FilterByEnvironmentsSchema,\n]\n", "\"\"\"\nUnits tests for openff.evaluator.utils.serialization\n\"\"\"\nimport json\nfrom datetime import datetime\nfrom enum import Enum, IntEnum\n\nimport numpy as np\nimport pytest\n\nfrom openff.evaluator import unit\nfrom openff.evaluator.client import EvaluatorClient\nfrom openff.evaluator.utils.serialization import (\n TypedBaseModel,\n TypedJSONDecoder,\n TypedJSONEncoder,\n _type_string_to_object,\n _type_to_type_string,\n deserialize_quantity,\n serialize_quantity,\n)\n\n\nclass Foo:\n def __init__(self):\n\n self.field1 = \"field1\"\n self.field2 = 2\n\n def __getstate__(self):\n\n return {\"field1\": self.field1, \"field2\": self.field2}\n\n def __setstate__(self, state):\n\n self.field1 = state[\"field1\"]\n self.field2 = state[\"field2\"]\n\n\nclass FooInherited(Foo):\n def __init__(self):\n\n super().__init__()\n self.field3 = 100\n\n def __getstate__(self):\n\n self_state = {\"field3\": self.field3}\n parent_state = super(FooInherited, self).__getstate__()\n\n self_state.update(parent_state)\n\n return self_state\n\n def __setstate__(self, state):\n\n self.field3 = state[\"field3\"]\n super(FooInherited, self).__setstate__(state)\n\n\nclass Bar(TypedBaseModel):\n def __init__(self):\n\n self.field1 = \"field1\"\n self.field2 = 2\n\n def __getstate__(self):\n\n return {\n \"field1\": self.field1,\n \"field2\": self.field2,\n }\n\n def __setstate__(self, state):\n\n self.field1 = state[\"field1\"]\n self.field2 = state[\"field2\"]\n\n\nclass BarInherited(Bar):\n\n field3: str = 1000\n\n\nclass Baz(Enum):\n\n Option1 = \"Option1\"\n Option2 = \"Option2\"\n\n\nclass Qux(IntEnum):\n\n Option1 = 1\n Option2 = 2\n\n\nclass NestedParent:\n class NestedChild(Enum):\n\n Option1 = \"Option1\"\n Option2 = \"Option2\"\n\n\nclass ComplexObject:\n class NestedClass1:\n def __init__(self):\n\n self.field1 = 5 * unit.kelvin\n\n def __getstate__(self):\n return {\n \"field1\": self.field1,\n }\n\n def __setstate__(self, state):\n self.field1 = state[\"field1\"]\n\n class NestedClass2:\n def __init__(self):\n self.field1 = Qux.Option1\n\n def __getstate__(self):\n return {\n \"field1\": self.field1,\n }\n\n def __setstate__(self, state):\n self.field1 = state[\"field1\"]\n\n def __init__(self):\n\n self.field1 = ComplexObject.NestedClass1()\n self.field2 = ComplexObject.NestedClass2()\n\n def __getstate__(self):\n\n return {\"field1\": self.field1, \"field2\": self.field2}\n\n def __setstate__(self, state):\n\n self.field1 = state[\"field1\"]\n self.field2 = state[\"field2\"]\n\n\nclass TestClass(TypedBaseModel):\n def __init__(self, inputs=None):\n self.inputs = inputs\n\n self.foo = Foo()\n self.bar = Bar()\n\n self.foo_inherited = FooInherited()\n self.bar_inherited = BarInherited()\n\n self.complex = ComplexObject()\n\n def __getstate__(self):\n\n return {\n \"inputs\": self.inputs,\n \"foo\": self.foo,\n \"bar\": self.bar,\n \"foo_inherited\": self.foo_inherited,\n \"bar_inherited\": self.bar_inherited,\n \"complex\": self.complex,\n }\n\n def __setstate__(self, state):\n\n self.inputs = state[\"inputs\"]\n\n self.foo = state[\"foo\"]\n self.bar = state[\"bar\"]\n\n self.foo_inherited = state[\"foo_inherited\"]\n self.bar_inherited = state[\"bar_inherited\"]\n\n self.complex = state[\"complex\"]\n\n\ndef test_polymorphic_dictionary():\n \"\"\"Test the polymorphic dictionary helper class.\"\"\"\n\n test_dictionary = {\n \"test_str\": \"test1\",\n \"test_int\": 1,\n \"test_bool\": True,\n \"test_None\": None,\n \"test_Foo\": Foo(),\n \"test_FooInherited\": FooInherited(),\n \"test_Bar\": Bar(),\n \"test_BarInherited\": BarInherited(),\n \"test_Baz\": Baz.Option1,\n \"test_Qux\": Qux.Option1,\n \"test_Nested\": NestedParent.NestedChild.Option1,\n \"test_List\": [Foo(), Bar(), 1, \"Hello World\"],\n \"test_Complex\": ComplexObject(),\n }\n\n test_object = TestClass(inputs=test_dictionary)\n test_json = test_object.json()\n\n test_recreated = TestClass.parse_json(test_json)\n test_recreated_json = test_recreated.json()\n\n assert test_json == test_recreated_json\n\n\ndef test_dimensionless_quantity_serialization():\n\n test_value = 1.0 * unit.dimensionless\n\n serialized_value = serialize_quantity(test_value)\n deserialized_value = deserialize_quantity(serialized_value)\n\n assert test_value == deserialized_value\n\n test_value = 1.0 * unit.dimensionless\n\n serialized_value = serialize_quantity(test_value)\n deserialized_value = deserialize_quantity(serialized_value)\n\n assert test_value == deserialized_value\n\n\[email protected](\"float_type\", [np.float16, np.float32, np.float64])\ndef test_numpy_float_serialization(float_type):\n\n original_value = float_type(0.987654321)\n\n serialized_value = json.dumps(original_value, cls=TypedJSONEncoder)\n deserialized_value = json.loads(serialized_value, cls=TypedJSONDecoder)\n\n assert original_value == deserialized_value\n\n\[email protected](\"int_type\", [np.int32, np.int64])\ndef test_numpy_int_serialization(int_type):\n\n original_value = int_type(987654321)\n\n serialized_value = json.dumps(original_value, cls=TypedJSONEncoder)\n deserialized_value = json.loads(serialized_value, cls=TypedJSONDecoder)\n\n assert original_value == deserialized_value\n\n\ndef test_numpy_array_serialization():\n\n one_dimensional_array = np.array([1, 2, 3, 4, 5])\n\n serialized_value = json.dumps(one_dimensional_array, cls=TypedJSONEncoder)\n deserialized_value = json.loads(serialized_value, cls=TypedJSONDecoder)\n\n assert np.allclose(one_dimensional_array, deserialized_value)\n\n two_dimensional_array = np.array([[1, 9], [2, 8], [3, 7], [4, 6], [5, 5]])\n\n serialized_value = json.dumps(two_dimensional_array, cls=TypedJSONEncoder)\n deserialized_value = json.loads(serialized_value, cls=TypedJSONDecoder)\n\n assert np.allclose(two_dimensional_array, deserialized_value)\n\n one_dimensional_quantity_array = one_dimensional_array * unit.kelvin\n\n serialized_value = json.dumps(one_dimensional_quantity_array, cls=TypedJSONEncoder)\n deserialized_value = json.loads(serialized_value, cls=TypedJSONDecoder)\n\n assert np.allclose(\n one_dimensional_quantity_array.magnitude, deserialized_value.magnitude\n )\n\n two_dimensional_quantity_array = two_dimensional_array * unit.kelvin\n\n serialized_value = json.dumps(two_dimensional_quantity_array, cls=TypedJSONEncoder)\n deserialized_value = json.loads(serialized_value, cls=TypedJSONDecoder)\n\n assert np.allclose(\n two_dimensional_quantity_array.magnitude, deserialized_value.magnitude\n )\n\n\ndef test_pint_serialization():\n\n test_value = 1.0 * unit.kelvin\n\n serialized_value = json.dumps(test_value, cls=TypedJSONEncoder)\n deserialized_value = json.loads(serialized_value, cls=TypedJSONDecoder)\n\n assert test_value == deserialized_value\n\n test_value = test_value.plus_minus(1.0 * unit.kelvin)\n\n serialized_value = json.dumps(test_value, cls=TypedJSONEncoder)\n deserialized_value = json.loads(serialized_value, cls=TypedJSONDecoder)\n\n assert test_value.value == deserialized_value.value\n assert test_value.error == deserialized_value.error\n\n\ndef test_datetime_serialization():\n\n test_value = datetime.now()\n\n serialized_value = json.dumps(test_value, cls=TypedJSONEncoder)\n deserialized_value = json.loads(serialized_value, cls=TypedJSONDecoder)\n\n assert test_value == deserialized_value\n\n\ndef test_type_string_to_object():\n\n client_class = _type_string_to_object(\"openff.evaluator.client.EvaluatorClient\")\n assert client_class == EvaluatorClient\n\n nested_class = _type_string_to_object(\n \"openff.evaluator.client.EvaluatorClient._Submission\"\n )\n assert nested_class == EvaluatorClient._Submission\n\n\ndef test_type_to_type_string():\n\n client_string = _type_to_type_string(EvaluatorClient)\n assert client_string == \"openff.evaluator.client.client.EvaluatorClient\"\n\n nested_string = _type_to_type_string(EvaluatorClient._Submission)\n assert nested_string == \"openff.evaluator.client.client.EvaluatorClient._Submission\"\n\n\ndef test_backwards_compatibility():\n\n old_json = '{\"value\": 298.15, \"unit\": \"K\", \"@type\": \"evaluator.unit.Quantity\"}'\n\n value = json.loads(old_json, cls=TypedJSONDecoder)\n assert isinstance(value, unit.Quantity)\n", "import os\nimport tempfile\n\nimport numpy as np\n\nfrom openff.evaluator import unit\nfrom openff.evaluator.forcefield import ParameterGradientKey\nfrom openff.evaluator.protocols.gradients import ZeroGradients\nfrom openff.evaluator.tests.utils import build_tip3p_smirnoff_force_field\nfrom openff.evaluator.utils.observables import ObservableArray\n\n\ndef test_zero_gradient():\n\n with tempfile.TemporaryDirectory() as directory:\n\n force_field_path = os.path.join(directory, \"ff.json\")\n\n with open(force_field_path, \"w\") as file:\n file.write(build_tip3p_smirnoff_force_field().json())\n\n gradient_key = ParameterGradientKey(\"vdW\", \"[#1]-[#8X2H2+0:1]-[#1]\", \"epsilon\")\n\n zero_gradients = ZeroGradients(\"\")\n zero_gradients.input_observables = ObservableArray(value=0.0 * unit.kelvin)\n zero_gradients.gradient_parameters = [gradient_key]\n zero_gradients.force_field_path = force_field_path\n zero_gradients.execute()\n\n assert len(zero_gradients.output_observables.gradients) == 1\n assert zero_gradients.output_observables.gradients[0].key == gradient_key\n assert np.allclose(zero_gradients.output_observables.gradients[0].value, 0.0)\n" ]
[ [ "numpy.all", "pandas.concat", "numpy.zeros", "scipy.optimize.linear_sum_assignment" ], [ "numpy.array", "numpy.allclose" ], [ "numpy.allclose" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [ "1.6", "1.4", "0.19", "1.5", "0.18", "1.2", "1.7", "1.0", "0.17", "1.3", "1.8" ], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
s2812135/Data_Challenges_WiSe2122
[ "a55372f444e7344af4e2e1f04e4244fb8cefeefe", "a55372f444e7344af4e2e1f04e4244fb8cefeefe" ]
[ "otherCodeTaskSnippets/14.01.2022.py", "examples/vizualizationComponentGesichtert.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jan 14 16:03:32 2022\n\n@author: dariu\n\"\"\"\n\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Dec 7 12:43:25 2021\n\n@author: dariu\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport os\nfrom tqdm import tqdm\nimport pacmap\nimport matplotlib.pyplot as plt\nfrom sklearn.manifold import TSNE\nimport umap\nfrom sklearn.cluster import KMeans\nfrom sklearn.cluster import DBSCAN\n#import sklearn.cluster\nfrom sklearn.decomposition import PCA\nfrom sklearn import metrics\nfrom sklearn.cluster import OPTICS, cluster_optics_dbscan\nimport matplotlib.gridspec as gridspec\nfrom sklearn.cluster import SpectralCoclustering\nfrom sklearn.metrics import consensus_score\nfrom sklearn.cluster import SpectralBiclustering\nfrom sklearn import svm\nfrom sklearn.model_selection import train_test_split\nfrom imblearn.under_sampling import NearMiss\nfrom imblearn.pipeline import make_pipeline\nfrom imblearn.metrics import classification_report_imbalanced\n\n\n\n\npath = \"C:\\\\Users\\dariu\\\\Documents\\\\Master Wirtschaftsinformatik\\\\Data Challenges\\Data\\\\\"\n\ndirectorys = [\n ['training_setA/training/', 'p0'],\n ['training_setB/training_setB/', 'p1']\n]\n#%%\ndfs = []\n\nfor z, (directory, file_head) in enumerate(directorys):\n for i, filename in enumerate(tqdm(os.listdir(path + directory))):\n df_temp = pd.read_csv(path + directory + filename, skiprows=0, sep='|')\n# patient_gender = df_temp[\"Gender\"][1]\n# if df_temp[\"Age\"][1] >= 40:\n dfs.append(df_temp)\n\ndf = pd.concat(dfs)\nlabels_true = df[\"SepsisLabel\"].tolist()\n\n#%%\n\n'''\n\n#df = df[[\"HR\", \"O2Sat\", \"Temp\", \"SBP\", \"MAP\", \"DBP\", \"Resp\", \"EtCO2\"]]\n\ndf = df[[\"Age\", \"Gender\", \"Unit1\", \"Unit2\", \"HospAdmTime\", \"ICULOS\"]]\n\n\nlabels_gender = df[\"Gender\"].tolist()\nlabels_unit1 = df[\"Unit1\"].tolist()\nlabels_unit2 = df[\"Unit2\"].tolist()\n#############################################\n\n\n\n'''\n\n#%%\n'''\n\ndf = df[[\n \"BaseExcess\",\n \"HCO3\",\n \"FiO2\",\n \"pH\",\n \"PaCO2\",\n \"SaO2\",\n \"AST\",\n \"BUN\",\n \"Alkalinephos\",\n \"Calcium\",\n \"Chloride\",\n \"Creatinine\",\n \"Bilirubin_direct\",\n \"Glucose\",\n \"Lactate\",\n \"Magnesium\",\n \"Phosphate\",\n \"Potassium\",\n \"Bilirubin_total\",\n \"TroponinI\",\n \"Hct\",\n \"Hgb\",\n \"PTT\",\n \"WBC\",\n \"Fibrinogen\",\n \"Platelets\"\n ]]\n\n#%%\n'''\n\n#############################################\n\n\n\nimputation_dims = [\n 'DBP',\n 'HR',\n 'O2Sat',\n 'Temp',\n 'SBP',\n 'MAP',\n 'Resp',\n]\n\nfor d in imputation_dims:\n mean = round(df[d].sum()/df.shape[0], 2)\n df.loc[df[d].isna(), d] = mean\n \n \n\n#################################################### \n \ndf = df.drop(columns=[\"SepsisLabel\"])\n\ndf_current = df.fillna(df.mean())\n\n#df_current = df.fillna(2)\n\n###########################################################\n\n#df_current = df \n##############################\n\n#85 labels_pred?\n\n#%%\n\n'''\n\ndef calc_scores(X, labels_true, labels_pred):\n rand_score = metrics.rand_score(labels_true, labels_pred)\n adjusted_rand_score = metrics.adjusted_rand_score(labels_true, labels_pred)\n adjusted_mutual_info_score = metrics.cluster.adjusted_mutual_info_score(labels_true, labels_pred)\n silhouette_score = metrics.silhouette_score(X, labels_pred, metric='euclidean', sample_size=None, random_state=None)\n print(\"Rand Score: \" , str(rand_score) + \"\\n\" + \n \"Adjusted Rand Score: \" , str(adjusted_rand_score) + \"\\n\" \n \"Adjusted Mutual Information Score: \" + str(adjusted_mutual_info_score) + \"\\n\" \n \"Silhouette Score: \" , str(silhouette_score) + \"\\n\" \n )\n\n'''\n\n#%%\n\n\n'''\n############################################################\n# initializing the pacmap instance\n# Setting n_neighbors to \"None\" leads to a default choice shown below in \"parameter\" section\n\nembedding = pacmap.PaCMAP(n_dims=5, n_neighbors=None, MN_ratio=0.5, FP_ratio=2.0) \n\n# fit the data (The index of transformed data corresponds to the index of the original data)\n\nX_transformed = embedding.fit_transform(df_current.values, init=\"pca\")\n\n####################################################################\n'''\n\n\n#%%\n\n'''\nmodel = SpectralCoclustering(n_clusters=9, random_state=0)\n#model.fit(df_current.values)\nmodel.fit(X_transformed)\n#score = consensus_score(model.biclusters_, (rows[:, row_idx], columns[:, col_idx]))\n\n#print(\"consensus score: {:.3f}\".format(score))\n\n#fit_data = df_current.values[np.argsort(model.row_labels_)]\nfit_data = X_transformed[np.argsort(model.row_labels_)]\nfit_data = fit_data[:, np.argsort(model.column_labels_)]\n\nfit_data = fit_data[0:len(labels_true), 0:41]\n\n\n\n#plt.matshow(fit_data, cmap=plt.cm.Blues)\nplt.matshow(fit_data, cmap='Spectral')\n\n\n#plt.matshow(fit_data, cmap=plt.cm.RdYlGn)\n#plt.matshow(fit_data, cmap=plt.cm.YlOrRd)\n#plt.matshow(fit_data)\n#plt.matshow(fit_data, cmap='rainbow')\n#plt.matshow(fit_data, cmap='Set1')\n#plt.matshow(fit_data, cmap='tab20')\n#plt.matshow(fit_data, cmap='gist_rainbow')\n\n\nplt.gca().set_aspect('auto')\n#plt.gca().set_aspect('equal', adjustable='box')\n#plt.axis('scaled')\n#plt.title(\"After biclustering; rearranged to show biclusters\")\n\nplt.show()\n\n\n#%%\n\n'''\n\n#\n\n\n#%%\n\n'''\n\nmodel = SpectralBiclustering(n_clusters=(10, 5), method=\"log\", random_state=0)\n#model = SpectralBiclustering(n_clusters=(10, 5), method=\"bistochastic\", random_state=0)\nmodel.fit(df_current.values)\n#model.fit(X_transformed)\n\n\n#fit_data = df_current.values[np.argsort(model.row_labels_)]\nfit_data = df_current.values[np.argsort(model.row_labels_)]\n#fit_data = X_transformed[:, np.argsort(model.column_labels_)]\n\n#plt.matshow(fit_data, cmap=plt.cm.Blues)\nplt.matshow(fit_data, cmap='Spectral')\n\nplt.gca().set_aspect('auto')\n\n#plt.title(\"After biclustering; rearranged to show biclusters\")\n\n\n\n\n\n#plt.matshow(\n# np.outer(np.sort(model.row_labels_) + 1, np.sort(model.column_labels_) + 1),\n# cmap=plt.cm.Blues,\n#)\n\n\nplt.matshow(\n np.outer(np.sort(model.row_labels_) + 1, np.sort(model.column_labels_) + 1),\n cmap='Spectral',\n)\n\n\n\n\n\nplt.gca().set_aspect('auto')\n\n#plt.title(\"Checkerboard structure of rearranged data\")\n\nplt.show()\n\n\n\n'''\n\n#%%\n\n\nX_train, X_test, y_train, y_test = train_test_split(df_current, labels_true, test_size=0.2)\n\n#%%\n\n\n\nX_train_ss = X_train[0:int(0.1*len(X_train))]\ny_train_ss = y_train[0:int(0.1*len(y_train))]\n\n\n# Create a pipeline\npipeline = make_pipeline(\n NearMiss(version=2), svm.SVC())\n\npipeline.fit(X_train_ss, y_train_ss)\n\n# Classify and report the results\nprint(classification_report_imbalanced(y_test, pipeline.predict(X_test)))\n\n", "import numpy as np\nimport pandas as pd\nimport os\nfrom tqdm import tqdm\nimport dataframe_image as dfi\nimport streamlit as st\nimport altair as alt\nimport streamlit as st\n\n\npersonWerte = []\n\[email protected](suppress_st_warning=True)\ndef getPeople(numberDirectory, gender, sepsis, age, featurelist, chooseperson):\n #sepsis = str(sepsis) + \"\\n\"\n print(sepsis)\n directorys = []\n\n\n if(numberDirectory == 0):\n directorys = [\n ['training_setA/training/', 'p0']\n ]\n\n if(numberDirectory == 1):\n directorys = [\n ['training_setB/training/', 'p1']\n ]\n if(numberDirectory == 2):\n directorys = [\n ['training_setA/training/', 'p0'],\n ['training_setB/training/', 'p1']\n ]\n \n #Werte der Timeseries f�r y Achse\n timeseries_werte = []\n #columns sind die features\n\n #Liste with persons with specific age\n personWerte = []\n for z, (directory, file_head) in enumerate(directorys):\n for i, filename in enumerate(tqdm(os.listdir(directory))):\n #�ffnen der Datei und lesen\n df_temp = pd.read_csv(directory + filename, skiprows=0, sep='|')\n\n #j f�r dateienzeile appende ins Array\n #row ersetzen mit \n for j, row in df_temp.iterrows():\n #schauen, ob richtige file\n #if(df_temp.at[j,'Gender'] == gender and df_temp.at[j,'SepsisLabel'] == sepsis and round(df_temp.at[j,'Age']) == age):\n #if(df_temp.at[j,'Gender'] == gender and df_temp.at[j,'SepsisLabel'] == sepsis and round(df_temp.at[j,'Age']) == age):\n # personWerte.append(filename)\n \n if(filename == chooseperson):\n #print(\"Das ist filename: \", filename)\n #für jedes feature\n rows = []\n for f in featurelist:\n if(np.isnan(df_temp.at[j, f])):\n #Schauen, was f�r ein Wert man hier eingibt\n rows.append(0)\n \n #if(df_temp.at[j,'HR'] != \"nan\"):\n if(np.isnan(df_temp.at[j, f])!= True):\n rows.append(df_temp.at[j,f])\n timeseries_werte.append(rows)\n #TODO: Noch ein Break reinbauen\n if(filename == chooseperson):\n break\n #if(i == 0):\n #break\n\n #print(timeseries_werte)\n #print(\"Liste der Personen\", list(dict.fromkeys(personWerte)))\n #return personWerte\n #print(\"timeseries type\", type(timeseries_werte))\n #print(\"Das ist timeseries_werte\")\n #print(timeseries_werte)\n st.header('Visualization Result on a chosen Person')\n\n st.write(\"This diagram gives you values about the selected person as well as about the selected features. The figure represents the Time Series data of a person in a hospital stay. The x-axis describes the time every hour. the y-axis describes the values of the previously selected features.\")\n chart_data = pd.DataFrame(\n #np.random.randn(20, 3),\n np.array(timeseries_werte, dtype=\"object\"),\n columns=featurelist)\n\n st.line_chart(chart_data)\n # open file and do first a \n #for z, (directory, file_head) in enumerate(directorys):\n # for i, filename in enumerate(tqdm(os.listdir(directory))):\n # if()\n # print(\"Das ist i\",i)\n # print(\"Das ist z\",z)\n\n \n\n\n" ]
[ [ "pandas.concat", "pandas.read_csv", "sklearn.model_selection.train_test_split", "sklearn.svm.SVC" ], [ "numpy.isnan", "numpy.array", "pandas.read_csv" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
arroqc/pandacancer_kaggle
[ "a6945dcac041dac744570d61ee630ee6f32e7117" ]
[ "archive/maketiles_old.py" ]
[ "import skimage.io\nimport numpy as np\nimport pandas as pd\nimport sys\nfrom pathlib import Path\nimport pickle\nimport argparse\nimport cv2\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--base_dir\", default='G:/Datasets/panda', required=False)\nparser.add_argument(\"--out_dir\", default='D:/Datasets/panda', required=False)\nargs = parser.parse_args()\n\nBASE_PATH = Path(args.base_dir)\nOUTPUT_BASE = Path(args.out_dir)\n\nSIZE = 128\nNUM = 16\nLEVEL = 1\nSTRIDE = False\nTRAIN_PATH = BASE_PATH/'train_images/'\nMASKS_TRAIN_PATH = BASE_PATH/'train_label_masks/'\nOUTPUT_IMG_PATH = OUTPUT_BASE/f'train_tiles_{SIZE}_{LEVEL}/imgs/'\nOUTPUT_MASK_PATH = OUTPUT_BASE/f'train_tiles_{SIZE}_{LEVEL}/masks/'\nPICKLE_NAME = OUTPUT_BASE/f'stats_{SIZE}_{LEVEL}.pkl'\nCSV_PATH = BASE_PATH/'train.csv'\n\n\npen_marked_images = [\n 'fd6fe1a3985b17d067f2cb4d5bc1e6e1',\n 'ebb6a080d72e09f6481721ef9f88c472',\n 'ebb6d5ca45942536f78beb451ee43cc4',\n 'ea9d52d65500acc9b9d89eb6b82cdcdf',\n 'e726a8eac36c3d91c3c4f9edba8ba713',\n 'e90abe191f61b6fed6d6781c8305fe4b',\n 'fd0bb45eba479a7f7d953f41d574bf9f',\n 'ff10f937c3d52eff6ad4dd733f2bc3ac',\n 'feee2e895355a921f2b75b54debad328',\n 'feac91652a1c5accff08217d19116f1c',\n 'fb01a0a69517bb47d7f4699b6217f69d',\n 'f00ec753b5618cfb30519db0947fe724',\n 'e9a4f528b33479412ee019e155e1a197',\n 'f062f6c1128e0e9d51a76747d9018849',\n 'f39bf22d9a2f313425ee201932bac91a',\n]\n\n\ndef remove_pen_marks(img):\n # Define elliptic kernel\n kernel5x5 = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))\n\n # use cv2.inRange to mask pen marks (hardcoded for now)\n lower = np.array([0, 0, 0])\n upper = np.array([200, 255, 255])\n img_mask1 = cv2.inRange(img, lower, upper)\n\n # Use erosion and findContours to remove masked tissue (side effect of above)\n img_mask1 = cv2.erode(img_mask1, kernel5x5, iterations=4)\n img_mask2 = np.zeros(img_mask1.shape, dtype=np.uint8)\n contours, _ = cv2.findContours(img_mask1, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)\n for contour in contours:\n x, y = contour[:, 0, 0], contour[:, 0, 1]\n w, h = x.max() - x.min(), y.max() - y.min()\n if w > 100 and h > 100:\n cv2.drawContours(img_mask2, [contour], 0, 1, -1)\n # expand the area of the pen marks\n img_mask2 = cv2.dilate(img_mask2, kernel5x5, iterations=3)\n img_mask2 = (1 - img_mask2)\n\n # Mask out pen marks from original image\n img = cv2.bitwise_and(img, img, mask=img_mask2)\n\n img[img == 0] = 255\n\n return img, img_mask1, img_mask2\n\n\nclass TileMaker:\n\n def __init__(self, size, number):\n self.size = size\n self.number = number\n\n def make_multistride(self, image, mask):\n # Pad only once\n image, mask = self.__pad(image, mask)\n s0, _ = self.__get_tiles(image, mask)\n\n # For strided grids, need to also remove on the right/bottom\n s1, _ = self.__get_tiles(image[self.size // 2:-self.size // 2, :],\n mask[self.size // 2:-self.size // 2, :])\n s2, _ = self.__get_tiles(image[:, self.size // 2:-self.size // 2],\n image[:, self.size // 2:-self.size // 2])\n s3, _ = self.__get_tiles(image[self.size // 2:-self.size // 2, self.size // 2:-self.size // 2],\n image[self.size // 2:-self.size // 2, self.size // 2:-self.size // 2])\n\n all_tiles = np.concatenate([s0, s1, s2, s3], axis=0)\n # Find the images with the most stuff (the most red):\n red_channel = all_tiles[:, :, :, 0]\n tissue = np.where((red_channel < 230) & (red_channel > 200), red_channel, 0)\n sorted_tiles = np.argsort(np.sum(tissue, axis=(1, 2)))[::-1]\n sorted_tiles = sorted_tiles[:self.number * 4]\n\n return all_tiles[sorted_tiles], _\n\n def __pad(self, image, mask):\n h, w, c = image.shape\n horizontal_pad = 0 if (w % self.size) == 0 else self.size - (w % self.size)\n vertical_pad = 0 if (h % self.size) == 0 else self.size - (h % self.size)\n\n image = np.pad(image, pad_width=((vertical_pad // 2, vertical_pad - vertical_pad // 2),\n (horizontal_pad // 2, horizontal_pad - horizontal_pad // 2),\n (0, 0)),\n mode='constant', constant_values=255) # Empty is white in this data\n\n mask = np.pad(mask, pad_width=((vertical_pad // 2, vertical_pad - vertical_pad // 2),\n (horizontal_pad // 2, horizontal_pad - horizontal_pad // 2),\n (0, 0)),\n mode='constant', constant_values=0) # Empty is black in this data\n return image, mask\n\n def __get_tiles(self, image, mask):\n h, w, c = image.shape\n image = image.reshape(h // self.size, self.size, w // self.size, self.size, c)\n image = image.swapaxes(1, 2).reshape(-1, self.size, self.size, c)\n mask = mask.reshape(h // self.size, self.size, w // self.size, self.size, c)\n mask = mask.swapaxes(1, 2).reshape(-1, self.size, self.size, c)\n\n if image.shape[0] < self.number:\n image = np.pad(image, pad_width=((0, self.number - image.shape[0]), (0, 0), (0, 0), (0, 0)),\n mode='constant', constant_values=255)\n mask = np.pad(mask, pad_width=((0, self.number - mask.shape[0]), (0, 0), (0, 0), (0, 0)),\n mode='constant', constant_values=0)\n\n return image, mask\n\n def make(self, image, mask):\n image, mask = self.__pad(image, mask)\n image, mask = self.__get_tiles(image, mask)\n # Find the images with the most dark (epithelium) stuff\n red_channel = image[:, :, :, 0]\n tissue = np.where((red_channel < 230) & (red_channel > 200), red_channel, 0)\n sorted_tiles = np.argsort(np.sum(tissue, axis=(1, 2)))[::-1]\n sorted_tiles = sorted_tiles[:self.number]\n\n return image[sorted_tiles], mask[sorted_tiles]\n\n\nif __name__ == \"__main__\":\n\n OUTPUT_IMG_PATH.mkdir(exist_ok=True, parents=True)\n OUTPUT_MASK_PATH.mkdir(exist_ok=True, parents=True)\n\n tile_maker = TileMaker(SIZE, NUM)\n\n img_list = list(TRAIN_PATH.glob('**/*.tiff'))\n # img_list.pop(5765)\n bad_images = []\n bad_masks = []\n image_stats = []\n files = []\n for i, img_fn in enumerate(img_list):\n\n img_id = img_fn.stem\n mask_fn = MASKS_TRAIN_PATH / (img_id + '_mask.tiff')\n\n try:\n col = skimage.io.MultiImage(str(img_fn))\n image = col[-LEVEL]\n except:\n bad_images.append(img_id)\n continue\n\n if img_id in pen_marked_images:\n image, _, _ = remove_pen_marks(image)\n\n if mask_fn.exists():\n\n try:\n mask = skimage.io.MultiImage(str(mask_fn))[-LEVEL]\n except:\n bad_masks.append(img_id)\n mask = np.zeros_like(image)\n\n else:\n mask = np.zeros_like(image)\n\n if STRIDE:\n image, mask = tile_maker.make_multistride(image, mask)\n else:\n image, mask = tile_maker.make(image, mask)\n sys.stdout.write(f'\\r{i + 1}/{len(img_list)}')\n\n image_stats.append({'image_id': img_id, 'mean': image.mean(axis=(0, 1, 2)) / 255,\n 'mean_square': ((image / 255) ** 2).mean(axis=(0, 1, 2)),\n 'img_mean': (255 - image).mean()})\n\n for i, (tile_image, tile_mask) in enumerate(zip(image, mask)):\n a = (img_id + '_' + str(i) + '.png')\n b = (img_id + '_' + str(i) + '.png')\n files.append({'image_id': img_id, 'num': i, 'filename': a, 'maskname': b,\n 'value': (255-tile_image[:, :, 0]).mean()})\n skimage.io.imsave(OUTPUT_IMG_PATH / a, tile_image, check_contrast=False)\n skimage.io.imsave(OUTPUT_MASK_PATH / b, tile_mask, check_contrast=False)\n\n image_stats = pd.DataFrame(image_stats)\n df = pd.read_csv(CSV_PATH)\n df = pd.merge(df, image_stats, on='image_id', how='left')\n df[['image_id', 'img_mean']].to_csv(OUTPUT_BASE/f'img_mean_{SIZE}_{LEVEL}.csv', index=False)\n\n provider_stats = {}\n for provider in df['data_provider'].unique():\n mean = (df[df['data_provider'] == provider]['mean']).mean(0)\n std = np.sqrt((df[df['data_provider'] == provider]['mean_square']).mean(0) - mean ** 2)\n provider_stats[provider] = (mean, std)\n\n mean = (df['mean']).mean()\n std = np.sqrt((df['mean_square']).mean() - mean ** 2)\n provider_stats['all'] = (mean, std)\n\n with open(PICKLE_NAME, 'wb') as file:\n pickle.dump(provider_stats, file)\n\n pd.DataFrame(files).to_csv(OUTPUT_BASE/f'files_{SIZE}_{LEVEL}.csv', index=False)\n\n print(bad_images)\n print(bad_masks)\n print(provider_stats)\n" ]
[ [ "pandas.merge", "pandas.read_csv", "numpy.sum", "numpy.pad", "pandas.DataFrame", "numpy.concatenate", "numpy.zeros_like", "numpy.array", "numpy.zeros", "numpy.where" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
grantseiter/Biden-Tax-Proposals
[ "c215ff845264f3fce9281c7fbb343ed10758a4b6", "c215ff845264f3fce9281c7fbb343ed10758a4b6", "c215ff845264f3fce9281c7fbb343ed10758a4b6" ]
[ "Tax-Calculator-3.0.0/taxcalc/calcfunctions.py", "OG-USA-0.6.2/ogusa/tests/test_get_micro_data.py", "Tax-Calculator-2.9.0/taxcalc/tests/test_consumption.py" ]
[ "\"\"\"\nTax-Calculator functions that calculate payroll and individual income taxes.\n\nThese functions are imported into the Calculator class.\n\nNote: the parameter_indexing_CPI_offset policy parameter is the only\npolicy parameter that does not appear here; it is used in the policy.py\nfile to possibly adjust the price inflation rate used to index policy\nparameters (as would be done in a reform that introduces chained-CPI\nindexing).\n\"\"\"\n# CODING-STYLE CHECKS:\n# pycodestyle calcfunctions.py\n# pylint --disable=locally-disabled calcfunctions.py\n#\n# pylint: disable=too-many-lines\n# pylint: disable=invalid-name\n# pylint: disable=too-many-arguments\n# pylint: disable=too-many-locals\n\nimport math\nimport copy\nimport numpy as np\nfrom taxcalc.decorators import iterate_jit, JIT\n\n\ndef BenefitPrograms(calc):\n \"\"\"\n Calculate total government cost and consumption value of benefits\n delivered by non-repealed benefit programs.\n \"\"\"\n # zero out benefits delivered by repealed programs\n zero = np.zeros(calc.array_len)\n if calc.policy_param('BEN_housing_repeal'):\n calc.array('housing_ben', zero)\n if calc.policy_param('BEN_ssi_repeal'):\n calc.array('ssi_ben', zero)\n if calc.policy_param('BEN_snap_repeal'):\n calc.array('snap_ben', zero)\n if calc.policy_param('BEN_tanf_repeal'):\n calc.array('tanf_ben', zero)\n if calc.policy_param('BEN_vet_repeal'):\n calc.array('vet_ben', zero)\n if calc.policy_param('BEN_wic_repeal'):\n calc.array('wic_ben', zero)\n if calc.policy_param('BEN_mcare_repeal'):\n calc.array('mcare_ben', zero)\n if calc.policy_param('BEN_mcaid_repeal'):\n calc.array('mcaid_ben', zero)\n if calc.policy_param('BEN_oasdi_repeal'):\n calc.array('e02400', zero)\n if calc.policy_param('BEN_ui_repeal'):\n calc.array('e02300', zero)\n if calc.policy_param('BEN_other_repeal'):\n calc.array('other_ben', zero)\n # calculate government cost of all benefits\n cost = np.array(\n calc.array('housing_ben') +\n calc.array('ssi_ben') +\n calc.array('snap_ben') +\n calc.array('tanf_ben') +\n calc.array('vet_ben') +\n calc.array('wic_ben') +\n calc.array('mcare_ben') +\n calc.array('mcaid_ben') +\n calc.array('e02400') +\n calc.array('e02300') +\n calc.array('ubi') +\n calc.array('other_ben')\n )\n calc.array('benefit_cost_total', cost)\n # calculate consumption value of all benefits\n # (assuming that cash benefits have full value)\n value = np.array(\n calc.array('housing_ben') * calc.consump_param('BEN_housing_value') +\n calc.array('ssi_ben') +\n calc.array('snap_ben') * calc.consump_param('BEN_snap_value') +\n calc.array('tanf_ben') * calc.consump_param('BEN_tanf_value') +\n calc.array('vet_ben') * calc.consump_param('BEN_vet_value') +\n calc.array('wic_ben') * calc.consump_param('BEN_wic_value') +\n calc.array('mcare_ben') * calc.consump_param('BEN_mcare_value') +\n calc.array('mcaid_ben') * calc.consump_param('BEN_mcaid_value') +\n calc.array('e02400') +\n calc.array('e02300') +\n calc.array('ubi') +\n calc.array('other_ben') * calc.consump_param('BEN_other_value')\n )\n calc.array('benefit_value_total', value)\n\n\n@iterate_jit(nopython=True)\ndef EI_PayrollTax(SS_Earnings_c, e00200p, e00200s, pencon_p, pencon_s,\n FICA_ss_trt, FICA_mc_trt, ALD_SelfEmploymentTax_hc,\n SS_Earnings_thd, e00900p, e00900s, e02100p, e02100s, k1bx14p,\n k1bx14s, payrolltax, ptax_was, setax, c03260, ptax_oasdi,\n sey, earned, earned_p, earned_s,\n was_plus_sey_p, was_plus_sey_s):\n \"\"\"\n Compute part of total OASDI+HI payroll taxes and earned income variables.\n \"\"\"\n # compute sey and its individual components\n sey_p = e00900p + e02100p + k1bx14p\n sey_s = e00900s + e02100s + k1bx14s\n sey = sey_p + sey_s # total self-employment income for filing unit\n\n # compute gross wage and salary income ('was' denotes 'wage and salary')\n gross_was_p = e00200p + pencon_p\n gross_was_s = e00200s + pencon_s\n\n # compute taxable gross earnings for OASDI FICA\n txearn_was_p = min(SS_Earnings_c, gross_was_p)\n txearn_was_s = min(SS_Earnings_c, gross_was_s)\n\n # compute OASDI and HI payroll taxes on wage-and-salary income, FICA\n ptax_ss_was_p = FICA_ss_trt * txearn_was_p\n ptax_ss_was_s = FICA_ss_trt * txearn_was_s\n ptax_mc_was_p = FICA_mc_trt * gross_was_p\n ptax_mc_was_s = FICA_mc_trt * gross_was_s\n ptax_was = ptax_ss_was_p + ptax_ss_was_s + ptax_mc_was_p + ptax_mc_was_s\n\n # compute taxable self-employment income for OASDI SECA\n sey_frac = 1.0 - 0.5 * (FICA_ss_trt + FICA_mc_trt)\n txearn_sey_p = min(max(0., sey_p * sey_frac), SS_Earnings_c - txearn_was_p)\n txearn_sey_s = min(max(0., sey_s * sey_frac), SS_Earnings_c - txearn_was_s)\n\n # compute self-employment tax on taxable self-employment income, SECA\n setax_ss_p = FICA_ss_trt * txearn_sey_p\n setax_ss_s = FICA_ss_trt * txearn_sey_s\n setax_mc_p = FICA_mc_trt * max(0., sey_p * sey_frac)\n setax_mc_s = FICA_mc_trt * max(0., sey_s * sey_frac)\n setax_p = setax_ss_p + setax_mc_p\n setax_s = setax_ss_s + setax_mc_s\n setax = setax_p + setax_s\n\n # compute extra OASDI payroll taxes on the portion of the sum\n # of wage-and-salary income and taxable self employment income\n # that exceeds SS_Earnings_thd\n sey_frac = 1.0 - 0.5 * FICA_ss_trt\n was_plus_sey_p = gross_was_p + max(0., sey_p * sey_frac)\n was_plus_sey_s = gross_was_s + max(0., sey_s * sey_frac)\n extra_ss_income_p = max(0., was_plus_sey_p - SS_Earnings_thd)\n extra_ss_income_s = max(0., was_plus_sey_s - SS_Earnings_thd)\n extra_payrolltax = (extra_ss_income_p * FICA_ss_trt +\n extra_ss_income_s * FICA_ss_trt)\n\n # compute part of total payroll taxes for filing unit\n # (the ptax_amc part of total payroll taxes for the filing unit is\n # computed in the AdditionalMedicareTax function below)\n payrolltax = ptax_was + setax + extra_payrolltax\n\n # compute OASDI part of payroll taxes\n ptax_oasdi = (ptax_ss_was_p + ptax_ss_was_s +\n setax_ss_p + setax_ss_s +\n extra_payrolltax)\n\n # compute earned* variables and AGI deduction for\n # \"employer share\" of self-employment tax, c03260\n # Note: c03260 is the amount on 2015 Form 1040, line 27\n c03260 = (1. - ALD_SelfEmploymentTax_hc) * 0.5 * setax\n earned = max(0., e00200p + e00200s + sey - c03260)\n earned_p = max(0., (e00200p + sey_p -\n (1. - ALD_SelfEmploymentTax_hc) * 0.5 * setax_p))\n earned_s = max(0., (e00200s + sey_s -\n (1. - ALD_SelfEmploymentTax_hc) * 0.5 * setax_s))\n return (sey, payrolltax, ptax_was, setax, c03260, ptax_oasdi,\n earned, earned_p, earned_s, was_plus_sey_p, was_plus_sey_s)\n\n\n@iterate_jit(nopython=True)\ndef DependentCare(nu13, elderly_dependents, earned,\n MARS, ALD_Dependents_thd, ALD_Dependents_hc,\n ALD_Dependents_Child_c, ALD_Dependents_Elder_c,\n care_deduction):\n \"\"\"\n Computes dependent-care above-the-line deduction.\n\n Parameters\n ----------\n nu13: Number of dependents under 13 years old\n elderly_dependents: number of elderly dependents\n earned: Form 2441 earned income amount\n MARS: Marital Status\n ALD_Dependents_thd: Maximum income to qualify for deduction\n ALD_Dependents_hc: Deduction for dependent care haircut\n ALD_Dependents_Child_c: National weighted average cost of childcare\n ALD_Dependents_Elder_c: Eldercare deduction ceiling\n\n Returns\n -------\n care_deduction: Total above the line deductions for dependent care.\n \"\"\"\n\n if earned <= ALD_Dependents_thd[MARS - 1]:\n care_deduction = (((1. - ALD_Dependents_hc) * nu13 *\n ALD_Dependents_Child_c) +\n ((1. - ALD_Dependents_hc) * elderly_dependents *\n ALD_Dependents_Elder_c))\n else:\n care_deduction = 0.\n return care_deduction\n\n\n@iterate_jit(nopython=True)\ndef Adj(e03150, e03210, c03260,\n e03270, e03300, e03400, e03500, e00800,\n e03220, e03230, e03240, e03290, care_deduction,\n ALD_StudentLoan_hc, ALD_SelfEmp_HealthIns_hc, ALD_KEOGH_SEP_hc,\n ALD_EarlyWithdraw_hc, ALD_AlimonyPaid_hc, ALD_AlimonyReceived_hc,\n ALD_EducatorExpenses_hc, ALD_HSADeduction_hc, ALD_IRAContributions_hc,\n ALD_DomesticProduction_hc, ALD_Tuition_hc,\n c02900):\n \"\"\"\n Adj calculates Form 1040 AGI adjustments (i.e., Above-the-Line Deductions).\n\n Notes\n -----\n Taxpayer characteristics:\n\n e03210 : Student loan interest paid\n\n e03220 : Educator expenses\n\n e03150 : Total deductible IRA plan contributions\n\n e03230 : Tuition and fees (Form 8917)\n\n e03240 : Domestic production activity deduction (Form 8903)\n\n c03260 : Self-employment tax deduction (after haircut)\n\n e03270 : Self-employed health insurance premiums\n\n e03290 : HSA deduction (Form 8889)\n\n e03300 : Total deductible KEOGH/SEP/SIMPLE/etc. plan contributions\n\n e03400 : Penalty on early withdrawal of savings deduction\n\n e03500 : Alimony paid\n\n e00800 : Alimony received\n\n care_deduction : Dependent care expense deduction\n\n Tax law parameters:\n\n ALD_StudentLoan_hc : Student loan interest deduction haircut\n\n ALD_SelfEmp_HealthIns_hc : Self-employed h.i. deduction haircut\n\n ALD_KEOGH_SEP_hc : KEOGH/etc. plan contribution deduction haircut\n\n ALD_EarlyWithdraw_hc : Penalty on early withdrawal deduction haricut\n\n ALD_AlimonyPaid_hc : Alimony paid deduction haircut\n\n ALD_AlimonyReceived_hc : Alimony received deduction haircut\n\n ALD_EducatorExpenses_hc: Eductor expenses haircut\n\n ALD_HSADeduction_hc: HSA Deduction haircut\n\n ALD_IRAContributions_hc: IRA Contribution haircut\n\n ALD_DomesticProduction_hc: Domestic production haircut\n\n ALD_Tuition_hc: Tuition and fees haircut\n\n Returns\n -------\n c02900 : total Form 1040 adjustments, which are not included in AGI\n \"\"\"\n # Form 2555 foreign earned income exclusion is assumed to be zero\n # Form 1040 adjustments that are included in expanded income:\n c02900 = ((1. - ALD_StudentLoan_hc) * e03210 +\n c03260 +\n (1. - ALD_EarlyWithdraw_hc) * e03400 +\n (1. - ALD_AlimonyPaid_hc) * e03500 +\n (1. - ALD_AlimonyReceived_hc) * e00800 +\n (1. - ALD_EducatorExpenses_hc) * e03220 +\n (1. - ALD_Tuition_hc) * e03230 +\n (1. - ALD_DomesticProduction_hc) * e03240 +\n (1. - ALD_HSADeduction_hc) * e03290 +\n (1. - ALD_SelfEmp_HealthIns_hc) * e03270 +\n (1. - ALD_IRAContributions_hc) * e03150 +\n (1. - ALD_KEOGH_SEP_hc) * e03300 +\n care_deduction)\n return c02900\n\n\n@iterate_jit(nopython=True)\ndef ALD_InvInc_ec_base(p22250, p23250, sep,\n e00300, e00600, e01100, e01200,\n invinc_ec_base):\n \"\"\"\n Computes invinc_ec_base.\n \"\"\"\n # limitation on net short-term and long-term capital losses\n cgain = max((-3000. / sep), p22250 + p23250)\n # compute exclusion of investment income from AGI\n invinc_ec_base = e00300 + e00600 + cgain + e01100 + e01200\n return invinc_ec_base\n\n\n@iterate_jit(nopython=True)\ndef CapGains(p23250, p22250, sep, ALD_StudentLoan_hc,\n ALD_InvInc_ec_rt, invinc_ec_base,\n e00200, e00300, e00600, e00650, e00700, e00800,\n CG_nodiff, CG_ec, CG_reinvest_ec_rt,\n ALD_BusinessLosses_c, MARS,\n e00900, e01100, e01200, e01400, e01700, e02000, e02100,\n e02300, e00400, e02400, c02900, e03210, e03230, e03240,\n c01000, c23650, ymod, ymod1, invinc_agi_ec,\n gains_at_death, CG_death, CG_death_ec):\n \"\"\"\n CapGains function: ...\n \"\"\"\n # compute taxable portion of capital gains at death (gains_at_death - CG_death_ec)\n if CG_death is True:\n taxable_gains_at_death = max(0., gains_at_death - CG_death_ec[MARS-1])\n else:\n taxable_gains_at_death = 0.\n # net capital gain (long term + short term + gains at death) before exclusion\n c23650 = p23250 + p22250 + taxable_gains_at_death\n # limitation on capital losses\n c01000 = max((-3000. / sep), c23650)\n # compute total investment income\n invinc = e00300 + e00600 + c01000 + e01100 + e01200\n # compute exclusion of investment income from AGI\n invinc_agi_ec = ALD_InvInc_ec_rt * max(0., invinc_ec_base)\n # compute ymod1 variable that is included in AGI\n ymod1 = (e00200 + e00700 + e00800 + e01400 + e01700 +\n invinc - invinc_agi_ec + e02100 + e02300 +\n max(e00900 + e02000, -ALD_BusinessLosses_c[MARS - 1]))\n if CG_nodiff:\n # apply QDIV+CG exclusion if QDIV+LTCG receive no special tax treatment\n qdcg_pos = max(0., e00650 + c01000)\n qdcg_exclusion = (min(CG_ec, qdcg_pos) +\n CG_reinvest_ec_rt * max(0., qdcg_pos - CG_ec))\n ymod1 = max(0., ymod1 - qdcg_exclusion)\n invinc_agi_ec += qdcg_exclusion\n # compute ymod variable that is used in OASDI benefit taxation logic\n ymod2 = e00400 + (0.50 * e02400) - c02900\n ymod3 = (1. - ALD_StudentLoan_hc) * e03210 + e03230 + e03240\n ymod = ymod1 + ymod2 + ymod3\n return (c01000, c23650, ymod, ymod1, invinc_agi_ec,\n gains_at_death, taxable_gains_at_death)\n\n\n@iterate_jit(nopython=True)\ndef SSBenefits(MARS, ymod, e02400, SS_thd50, SS_thd85,\n SS_percentage1, SS_percentage2, c02500):\n \"\"\"\n Calculates OASDI benefits included in AGI, c02500.\n \"\"\"\n if ymod < SS_thd50[MARS - 1]:\n c02500 = 0.\n elif ymod < SS_thd85[MARS - 1]:\n c02500 = SS_percentage1 * min(ymod - SS_thd50[MARS - 1], e02400)\n else:\n c02500 = min(SS_percentage2 * (ymod - SS_thd85[MARS - 1]) +\n SS_percentage1 *\n min(e02400, SS_thd85[MARS - 1] -\n SS_thd50[MARS - 1]), SS_percentage2 * e02400)\n return c02500\n\n\n@iterate_jit(nopython=True)\ndef UBI(nu18, n1820, n21, UBI_u18, UBI_1820, UBI_21, UBI_ecrt,\n ubi, taxable_ubi, nontaxable_ubi):\n \"\"\"\n Calculates total and taxable Universal Basic Income (UBI) amount.\n\n Parameters\n ----------\n nu18: Number of people in the tax unit under 18\n\n n1820: Number of people in the tax unit age 18-20\n\n n21: Number of people in the tax unit age 21+\n\n UBI_u18: UBI benefit for those under 18\n\n UBI_1820: UBI benefit for those between 18 to 20\n\n UBI_21: UBI benefit for those 21 or more\n\n UBI_ecrt: Fraction of UBI benefits that are not included in AGI\n\n Returns\n -------\n ubi: total UBI received by the tax unit (is included in expanded_income)\n\n taxable_ubi: amount of UBI that is taxable (is added to AGI)\n\n nontaxable_ubi: amount of UBI that is nontaxable\n \"\"\"\n ubi = nu18 * UBI_u18 + n1820 * UBI_1820 + n21 * UBI_21\n taxable_ubi = ubi * (1. - UBI_ecrt)\n nontaxable_ubi = ubi - taxable_ubi\n return ubi, taxable_ubi, nontaxable_ubi\n\n\n@iterate_jit(nopython=True)\ndef AGI(ymod1, c02500, c02900, XTOT, MARS, sep, DSI, exact, nu18, taxable_ubi,\n II_em, II_em_ps, II_prt, II_no_em_nu18,\n c00100, pre_c04600, c04600):\n \"\"\"\n Computes Adjusted Gross Income (AGI), c00100, and\n compute personal exemption amount, c04600.\n \"\"\"\n # calculate AGI assuming no foreign earned income exclusion\n c00100 = ymod1 + c02500 - c02900 + taxable_ubi\n # calculate personal exemption amount\n if II_no_em_nu18: # repeal of personal exemptions for deps. under 18\n pre_c04600 = max(0, XTOT - nu18) * II_em\n else:\n pre_c04600 = XTOT * II_em\n if DSI:\n pre_c04600 = 0.\n # phase-out personal exemption amount\n if exact == 1: # exact calculation as on tax forms\n line5 = max(0., c00100 - II_em_ps[MARS - 1])\n line6 = math.ceil(line5 / (2500. / sep))\n line7 = II_prt * line6\n c04600 = max(0., pre_c04600 * (1. - line7))\n else: # smoothed calculation needed for sensible mtr calculation\n dispc_numer = II_prt * (c00100 - II_em_ps[MARS - 1])\n dispc_denom = 2500. / sep\n dispc = min(1., max(0., dispc_numer / dispc_denom))\n c04600 = pre_c04600 * (1. - dispc)\n return (c00100, pre_c04600, c04600)\n\n\n@iterate_jit(nopython=True)\ndef ItemDedCap(e17500, e18400, e18500, e19200, e19800, e20100, e20400, g20500,\n c00100, ID_AmountCap_rt, ID_AmountCap_Switch, e17500_capped,\n e18400_capped, e18500_capped, e19200_capped, e19800_capped,\n e20100_capped, e20400_capped, g20500_capped):\n \"\"\"\n Applies a cap to gross itemized deductions.\n\n Notes\n -----\n Tax Law Parameters:\n ID_AmountCap_Switch : Indicator for which itemized deductions are\n capped\n ID_AmountCap_rt : Cap on itemized deductions; decimal fraction of AGI\n\n Taxpayer Characteristics:\n e17500 : Medical expenses\n\n e18400 : State and local taxes\n\n e18500 : Real-estate taxes\n\n e19200 : Interest paid\n\n e19800 : Charity cash contributions\n\n e20100 : Charity noncash contributions\n\n e20400 : Total miscellaneous expenses\n\n g20500 : Gross casualty or theft loss (before disregard)\n\n c00100: Adjusted Gross Income\n\n Returns\n -------\n e17500_capped: Medical expenses, capped by ItemDedCap\n\n e18400_capped: State and local taxes, capped by ItemDedCap\n\n e18500_capped : Real-estate taxes, capped by ItemDedCap\n\n e19200_capped : Interest paid, capped by ItemDedCap\n\n e19800_capped : Charity cash contributions, capped by ItemDedCap\n\n e20100_capped : Charity noncash contributions, capped by ItemDedCap\n\n e20400_capped : Total miscellaneous expenses, capped by ItemDedCap\n\n g20500_capped : Gross casualty or theft loss (before disregard),\n capped by ItemDedCap\n \"\"\"\n # pylint: disable=too-many-branches\n\n cap = max(0., ID_AmountCap_rt * c00100)\n\n gross_ded_amt = 0\n if ID_AmountCap_Switch[0]: # medical\n gross_ded_amt += e17500\n if ID_AmountCap_Switch[1]: # statelocal\n gross_ded_amt += e18400\n if ID_AmountCap_Switch[2]: # realestate\n gross_ded_amt += e18500\n if ID_AmountCap_Switch[3]: # casualty\n gross_ded_amt += g20500\n if ID_AmountCap_Switch[4]: # misc\n gross_ded_amt += e20400\n if ID_AmountCap_Switch[5]: # interest\n gross_ded_amt += e19200\n if ID_AmountCap_Switch[6]: # charity\n gross_ded_amt += e19800 + e20100\n\n overage = max(0., gross_ded_amt - cap)\n\n e17500_capped = e17500\n e18400_capped = e18400\n e18500_capped = e18500\n g20500_capped = g20500\n e20400_capped = e20400\n e19200_capped = e19200\n e19800_capped = e19800\n e20100_capped = e20100\n\n if overage > 0. and c00100 > 0.:\n if ID_AmountCap_Switch[0]: # medical\n e17500_capped -= (e17500 / gross_ded_amt) * overage\n if ID_AmountCap_Switch[1]: # statelocal\n e18400_capped -= (e18400 / (gross_ded_amt) * overage)\n if ID_AmountCap_Switch[2]: # realestate\n e18500_capped -= (e18500 / gross_ded_amt) * overage\n if ID_AmountCap_Switch[3]: # casualty\n g20500_capped -= (g20500 / gross_ded_amt) * overage\n if ID_AmountCap_Switch[4]: # misc\n e20400_capped -= (e20400 / gross_ded_amt) * overage\n if ID_AmountCap_Switch[5]: # interest\n e19200_capped -= (e19200 / gross_ded_amt) * overage\n if ID_AmountCap_Switch[6]: # charity\n e19800_capped -= (e19800 / gross_ded_amt) * overage\n e20100_capped -= (e20100 / gross_ded_amt) * overage\n\n return (e17500_capped, e18400_capped, e18500_capped, g20500_capped,\n e20400_capped, e19200_capped, e19800_capped, e20100_capped)\n\n\n@iterate_jit(nopython=True)\ndef ItemDed(e17500_capped, e18400_capped, e18500_capped, e19200_capped,\n e19800_capped, e20100_capped, e20400_capped, g20500_capped,\n MARS, age_head, age_spouse, c00100, c04470, c21040, c21060,\n c17000, c18300, c19200, c19700, c20500, c20800,\n ID_ps, ID_Medical_frt, ID_Medical_frt_add4aged, ID_Medical_hc,\n ID_Casualty_frt, ID_Casualty_hc, ID_Miscellaneous_frt,\n ID_Miscellaneous_hc, ID_Charity_crt_all, ID_Charity_crt_noncash,\n ID_prt, ID_crt, ID_c, ID_StateLocalTax_hc, ID_Charity_frt,\n ID_Charity_hc, ID_InterestPaid_hc, ID_RealEstate_hc,\n ID_Medical_c, ID_StateLocalTax_c, ID_RealEstate_c,\n ID_InterestPaid_c, ID_Charity_c, ID_Casualty_c,\n ID_Miscellaneous_c, ID_AllTaxes_c, ID_AllTaxes_hc,\n ID_StateLocalTax_crt, ID_RealEstate_crt, ID_Charity_f):\n \"\"\"\n Calculates itemized deductions, Form 1040, Schedule A.\n\n Notes\n -----\n Tax Law Parameters:\n ID_ps : Itemized deduction phaseout AGI start (Pease)\n\n ID_crt : Itemized deduction maximum phaseout\n as a decimal fraction of total itemized deduction (Pease)\n\n ID_prt : Itemized deduction phaseout rate (Pease)\n\n ID_c: Dollar limit on itemized deductions\n\n ID_Medical_frt : Deduction for medical expenses;\n floor as a decimal fraction of AGI\n\n ID_Medical_frt_add4aged : Addon for medical expenses deduction for\n elderly; addon as a decimal fraction of AGI\n\n ID_Casualty_frt : Deduction for casualty loss;\n floor as a decimal fraction of AGI\n\n ID_Miscellaneous_frt : Deduction for miscellaneous expenses;\n floor as a decimal fraction of AGI\n\n ID_Charity_crt_all : Deduction for all charitable contributions;\n ceiling as a decimal fraction of AGI\n\n ID_Charity_crt_noncash : Deduction for noncash charitable\n contributions; ceiling as a decimal\n fraction of AGI\n\n ID_Charity_frt : Disregard for charitable contributions;\n floor as a decimal fraction of AGI\n\n ID_Medical_c : Ceiling on medical expense deduction\n\n ID_StateLocalTax_c : Ceiling on state and local tax deduction\n\n ID_RealEstate_c : Ceiling on real estate tax deduction\n\n ID_AllTaxes_c: Ceiling combined state and local income/sales and\n real estate tax deductions\n\n ID_InterestPaid_c : Ceiling on interest paid deduction\n\n ID_Charity_c : Ceiling on charity expense deduction\n\n ID_Charity_f: Floor on charity expense deduction\n\n ID_Casualty_c : Ceiling on casuality expense deduction\n\n ID_Miscellaneous_c : Ceiling on miscellaneous expense deduction\n\n ID_StateLocalTax_crt : Deduction for state and local taxes;\n ceiling as a decimal fraction of AGI\n\n ID_RealEstate_crt : Deduction for real estate taxes;\n ceiling as a decimal fraction of AGI\n\n Taxpayer Characteristics:\n e17500_capped : Medical expenses, capped by ItemDedCap\n\n e18400_capped : State and local taxes, capped by ItemDedCap\n\n e18500_capped : Real-estate taxes, capped by ItemDedCap\n\n e19200_capped : Interest paid, capped by ItemDedCap\n\n e19800_capped : Charity cash contributions, capped by ItemDedCap\n\n e20100_capped : Charity noncash contributions, capped by ItemDedCap\n\n e20400_capped : Total miscellaneous expenses, capped by ItemDedCap\n\n g20500_capped : Gross casualty or theft loss (before disregard),\n capped by ItemDedCap\n\n Returns\n -------\n c04470 : total itemized deduction amount (and other intermediate variables)\n \"\"\"\n posagi = max(c00100, 0.)\n # Medical\n medical_frt = ID_Medical_frt\n if age_head >= 65 or (MARS == 2 and age_spouse >= 65):\n medical_frt += ID_Medical_frt_add4aged\n c17750 = medical_frt * posagi\n c17000 = max(0., e17500_capped - c17750) * (1. - ID_Medical_hc)\n c17000 = min(c17000, ID_Medical_c[MARS - 1])\n # State and local taxes\n c18400 = min((1. - ID_StateLocalTax_hc) * max(e18400_capped, 0.),\n ID_StateLocalTax_c[MARS - 1])\n c18500 = min((1. - ID_RealEstate_hc) * e18500_capped,\n ID_RealEstate_c[MARS - 1])\n # following two statements implement a cap on c18400 and c18500 in a way\n # that those with negative AGI, c00100, are not capped under current law,\n # hence the 0.0001 rather than zero\n c18400 = min(c18400, ID_StateLocalTax_crt * max(c00100, 0.0001))\n c18500 = min(c18500, ID_RealEstate_crt * max(c00100, 0.0001))\n c18300 = (c18400 + c18500) * (1. - ID_AllTaxes_hc)\n c18300 = min(c18300, ID_AllTaxes_c[MARS - 1])\n # Interest paid\n c19200 = e19200_capped * (1. - ID_InterestPaid_hc)\n c19200 = min(c19200, ID_InterestPaid_c[MARS - 1])\n # Charity\n lim30 = min(ID_Charity_crt_noncash * posagi, e20100_capped)\n c19700 = min(ID_Charity_crt_all * posagi, lim30 + e19800_capped)\n # charity floor is zero in present law\n charity_floor = max(ID_Charity_frt * posagi, ID_Charity_f[MARS - 1])\n c19700 = max(0., c19700 - charity_floor) * (1. - ID_Charity_hc)\n c19700 = min(c19700, ID_Charity_c[MARS - 1])\n # Casualty\n c20500 = (max(0., g20500_capped - ID_Casualty_frt * posagi) *\n (1. - ID_Casualty_hc))\n c20500 = min(c20500, ID_Casualty_c[MARS - 1])\n # Miscellaneous\n c20400 = e20400_capped\n c20750 = ID_Miscellaneous_frt * posagi\n c20800 = max(0., c20400 - c20750) * (1. - ID_Miscellaneous_hc)\n c20800 = min(c20800, ID_Miscellaneous_c[MARS - 1])\n # Gross total itemized deductions\n c21060 = c17000 + c18300 + c19200 + c19700 + c20500 + c20800\n # Limitations on total itemized deductions\n # (no attempt to adjust c04470 components for limitations)\n nonlimited = c17000 + c20500\n limitstart = ID_ps[MARS - 1]\n if c21060 > nonlimited and c00100 > limitstart:\n dedmin = ID_crt * (c21060 - nonlimited)\n dedpho = ID_prt * max(0., posagi - limitstart)\n c21040 = min(dedmin, dedpho)\n c04470 = c21060 - c21040\n else:\n c21040 = 0.\n c04470 = c21060\n c04470 = min(c04470, ID_c[MARS - 1])\n # Return total itemized deduction amounts and components\n return (c17000, c18300, c19200, c19700, c20500, c20800,\n c21040, c21060, c04470)\n\n\n@iterate_jit(nopython=True)\ndef AdditionalMedicareTax(e00200, MARS,\n AMEDT_ec, sey, AMEDT_rt,\n FICA_mc_trt, FICA_ss_trt,\n ptax_amc, payrolltax):\n \"\"\"\n Computes Additional Medicare Tax (Form 8959) included in payroll taxes.\n\n Notes\n -----\n Tax Law Parameters:\n AMEDT_ec : Additional Medicare Tax earnings exclusion\n\n AMEDT_rt : Additional Medicare Tax rate\n\n FICA_ss_trt : FICA Social Security tax rate\n\n FICA_mc_trt : FICA Medicare tax rate\n\n Taxpayer Charateristics:\n e00200 : Wages and salaries\n\n sey : Self-employment income\n\n Returns\n -------\n ptax_amc : Additional Medicare Tax\n\n payrolltax : payroll tax augmented by Additional Medicare Tax\n \"\"\"\n line8 = max(0., sey) * (1. - 0.5 * (FICA_mc_trt + FICA_ss_trt))\n line11 = max(0., AMEDT_ec[MARS - 1] - e00200)\n ptax_amc = AMEDT_rt * (max(0., e00200 - AMEDT_ec[MARS - 1]) +\n max(0., line8 - line11))\n payrolltax += ptax_amc\n return (ptax_amc, payrolltax)\n\n\n@iterate_jit(nopython=True)\ndef StdDed(DSI, earned, STD, age_head, age_spouse, STD_Aged, STD_Dep,\n MARS, MIDR, blind_head, blind_spouse, standard, c19700,\n STD_allow_charity_ded_nonitemizers):\n \"\"\"\n Calculates standard deduction, including standard deduction for\n dependents, aged and bind.\n\n Notes\n -----\n Tax Law Parameters:\n STD : Standard deduction amount, filing status dependent\n\n STD_Dep : Standard deduction for dependents\n\n STD_Aged : Additional standard deduction for blind and aged\n\n Taxpayer Characteristics:\n earned : Form 2441 earned income amount\n\n e02400 : Gross Social Security Benefit\n\n DSI : Dependent Status Indicator:\n 0 - not being claimed as a dependent\n 1 - claimed as a dependent\n\n MIDR : Married filing separately itemized deductions\n requirement indicator:\n 0 - not necessary to itemize because of filing status\n 1 - necessary to itemize when filing separately\n\n Returns\n -------\n standard : the standard deduction amount for filing unit\n \"\"\"\n # calculate deduction for dependents\n if DSI == 1:\n c15100 = max(350. + earned, STD_Dep)\n basic_stded = min(STD[MARS - 1], c15100)\n else:\n c15100 = 0.\n if MIDR == 1:\n basic_stded = 0.\n else:\n basic_stded = STD[MARS - 1]\n # calculate extra standard deduction for aged and blind\n num_extra_stded = blind_head + blind_spouse\n if age_head >= 65:\n num_extra_stded += 1\n if MARS == 2 and age_spouse >= 65:\n num_extra_stded += 1\n extra_stded = num_extra_stded * STD_Aged[MARS - 1]\n # calculate the total standard deduction\n standard = basic_stded + extra_stded\n if MARS == 3 and MIDR == 1:\n standard = 0.\n if STD_allow_charity_ded_nonitemizers:\n standard += c19700\n return standard\n\n\n@iterate_jit(nopython=True)\ndef TaxInc(c00100, standard, c04470, c04600, MARS, e00900, e26270,\n e02100, e27200, e00650, c01000,\n PT_SSTB_income, PT_binc_w2_wages, PT_ubia_property,\n PT_qbid_rt, PT_qbid_taxinc_thd, PT_qbid_taxinc_gap,\n PT_qbid_w2_wages_rt,\n PT_qbid_alt_w2_wages_rt, PT_qbid_alt_property_rt,\n c04800, qbided, StudentLoan_em, studloan_debt, sldf):\n \"\"\"\n Calculates taxable income, c04800, and\n qualified business income deduction, qbided.\n \"\"\"\n # calculate taxable income before qualified business income deduction\n pre_qbid_taxinc = max(0., c00100 - max(c04470, standard) - c04600)\n # calculate qualified business income deduction\n qbided = 0.\n qbinc = max(0., e00900 + e26270 + e02100 + e27200)\n qbided_full = qbinc * PT_qbid_rt\n if PT_qbid_taxinc_thd[MARS-1] > 0:\n if pre_qbid_taxinc < PT_qbid_taxinc_thd[MARS-1]:\n qbided = qbided_full\n else:\n qbided = max(0., qbided_full * (1 - (pre_qbid_taxinc - PT_qbid_taxinc_thd[MARS-1])/ PT_qbid_taxinc_gap[MARS-1]))\n else:\n qbided = qbided_full\n \"\"\"\n if qbinc > 0. and PT_qbid_rt > 0.:\n qbid_before_limits = qbinc * PT_qbid_rt\n lower_thd = PT_qbid_taxinc_thd[MARS - 1]\n if pre_qbid_taxinc <= lower_thd:\n qbided = qbid_before_limits\n else:\n pre_qbid_taxinc_gap = PT_qbid_taxinc_gap[MARS - 1]\n upper_thd = lower_thd + pre_qbid_taxinc_gap\n if PT_SSTB_income == 1 and pre_qbid_taxinc >= upper_thd:\n qbided = 0.\n else:\n wage_cap = PT_binc_w2_wages * PT_qbid_w2_wages_rt\n alt_cap = (PT_binc_w2_wages * PT_qbid_alt_w2_wages_rt +\n PT_ubia_property * PT_qbid_alt_property_rt)\n full_cap = max(wage_cap, alt_cap)\n if PT_SSTB_income == 0 and pre_qbid_taxinc >= upper_thd:\n # apply full cap\n qbided = min(full_cap, qbid_before_limits)\n elif PT_SSTB_income == 0 and pre_qbid_taxinc < upper_thd:\n # apply adjusted cap as in Part III of Worksheet 12-A\n # in 2018 IRS Publication 535 (Chapter 12)\n prt = (pre_qbid_taxinc - lower_thd) / pre_qbid_taxinc_gap\n adj = prt * (qbid_before_limits - full_cap)\n qbided = qbid_before_limits - adj\n else: # PT_SSTB_income == 1 and pre_qbid_taxinc < upper_thd\n prti = (upper_thd - pre_qbid_taxinc) / pre_qbid_taxinc_gap\n qbid_adjusted = prti * qbid_before_limits\n cap_adjusted = prti * full_cap\n prt = (pre_qbid_taxinc - lower_thd) / pre_qbid_taxinc_gap\n adj = prt * (qbid_adjusted - cap_adjusted)\n qbided = qbid_adjusted - adj\n \"\"\"\n # apply taxinc cap (assuning cap rate is equal to PT_qbid_rt)\n net_cg = e00650 + c01000 # per line 34 in 2018 Pub 535 Worksheet 12-A\n taxinc_cap = PT_qbid_rt * max(0., pre_qbid_taxinc - net_cg)\n qbided = min(qbided, taxinc_cap)\n # exclude forgiven student loan debt from taxable income\n if StudentLoan_em is True:\n base_sldf = max(0., studloan_debt)\n else:\n base_sldf = 0.\n # exclusion is limited to tax inc\n sldf = max(0., min(pre_qbid_taxinc - qbided, base_sldf))\n # calculate taxable income after qualified business income deduction\n c04800 = max(0., pre_qbid_taxinc - qbided - sldf)\n return (c04800, qbided, sldf)\n\n\n@JIT(nopython=True)\ndef SchXYZ(taxable_income, MARS, e00900, e26270, e02000, e00200,\n PT_rt1, PT_rt2, PT_rt3, PT_rt4, PT_rt5,\n PT_rt6, PT_rt7, PT_rt8,\n PT_brk1, PT_brk2, PT_brk3, PT_brk4, PT_brk5,\n PT_brk6, PT_brk7,\n II_rt1, II_rt2, II_rt3, II_rt4, II_rt5,\n II_rt6, II_rt7, II_rt8,\n II_brk1, II_brk2, II_brk3, II_brk4, II_brk5,\n II_brk6, II_brk7, PT_EligibleRate_active,\n PT_EligibleRate_passive, PT_wages_active_income,\n PT_top_stacking):\n \"\"\"\n Returns Schedule X, Y, Z tax amount for specified taxable_income.\n \"\"\"\n # separate non-negative taxable income into two non-negative components,\n # doing this in a way so that the components add up to taxable income\n # define pass-through income eligible for PT schedule\n pt_passive = PT_EligibleRate_passive * (e02000 - e26270)\n pt_active_gross = e00900 + e26270\n if (pt_active_gross > 0) and PT_wages_active_income:\n pt_active_gross = pt_active_gross + e00200\n pt_active = PT_EligibleRate_active * pt_active_gross\n pt_active = min(pt_active, e00900 + e26270)\n pt_taxinc = max(0., pt_passive + pt_active)\n if pt_taxinc >= taxable_income:\n pt_taxinc = taxable_income\n reg_taxinc = 0.\n else:\n # pt_taxinc is unchanged\n reg_taxinc = taxable_income - pt_taxinc\n # determine stacking order\n if PT_top_stacking:\n reg_tbase = 0.\n pt_tbase = reg_taxinc\n else:\n reg_tbase = pt_taxinc\n pt_tbase = 0.\n # compute Schedule X,Y,Z tax using the two components of taxable income\n if reg_taxinc > 0.:\n reg_tax = Taxes(reg_taxinc, MARS, reg_tbase,\n II_rt1, II_rt2, II_rt3, II_rt4,\n II_rt5, II_rt6, II_rt7, II_rt8, II_brk1, II_brk2,\n II_brk3, II_brk4, II_brk5, II_brk6, II_brk7)\n else:\n reg_tax = 0.\n if pt_taxinc > 0.:\n pt_tax = Taxes(pt_taxinc, MARS, pt_tbase,\n PT_rt1, PT_rt2, PT_rt3, PT_rt4,\n PT_rt5, PT_rt6, PT_rt7, PT_rt8, PT_brk1, PT_brk2,\n PT_brk3, PT_brk4, PT_brk5, PT_brk6, PT_brk7)\n else:\n pt_tax = 0.\n return reg_tax + pt_tax\n\n\n@iterate_jit(nopython=True)\ndef SchXYZTax(c04800, MARS, e00900, e26270, e02000, e00200,\n PT_rt1, PT_rt2, PT_rt3, PT_rt4, PT_rt5,\n PT_rt6, PT_rt7, PT_rt8,\n PT_brk1, PT_brk2, PT_brk3, PT_brk4, PT_brk5,\n PT_brk6, PT_brk7,\n II_rt1, II_rt2, II_rt3, II_rt4, II_rt5,\n II_rt6, II_rt7, II_rt8,\n II_brk1, II_brk2, II_brk3, II_brk4, II_brk5,\n II_brk6, II_brk7, PT_EligibleRate_active,\n PT_EligibleRate_passive, PT_wages_active_income,\n PT_top_stacking, c05200):\n \"\"\"\n SchXYZTax calls SchXYZ function and sets c05200 to returned amount.\n \"\"\"\n c05200 = SchXYZ(c04800, MARS, e00900, e26270, e02000, e00200,\n PT_rt1, PT_rt2, PT_rt3, PT_rt4, PT_rt5,\n PT_rt6, PT_rt7, PT_rt8,\n PT_brk1, PT_brk2, PT_brk3, PT_brk4, PT_brk5,\n PT_brk6, PT_brk7,\n II_rt1, II_rt2, II_rt3, II_rt4, II_rt5,\n II_rt6, II_rt7, II_rt8,\n II_brk1, II_brk2, II_brk3, II_brk4, II_brk5,\n II_brk6, II_brk7, PT_EligibleRate_active,\n PT_EligibleRate_passive, PT_wages_active_income,\n PT_top_stacking)\n return c05200\n\n\n@iterate_jit(nopython=True)\ndef GainsTax(e00650, c01000, c23650, p23250, e01100, e58990, e00200,\n e24515, e24518, MARS, c04800, c05200, e00900, e26270, e02000,\n II_rt1, II_rt2, II_rt3, II_rt4, II_rt5, II_rt6, II_rt7, II_rt8,\n II_brk1, II_brk2, II_brk3, II_brk4, II_brk5, II_brk6, II_brk7,\n PT_rt1, PT_rt2, PT_rt3, PT_rt4, PT_rt5, PT_rt6, PT_rt7, PT_rt8,\n PT_brk1, PT_brk2, PT_brk3, PT_brk4, PT_brk5, PT_brk6, PT_brk7,\n CG_nodiff, PT_EligibleRate_active, PT_EligibleRate_passive,\n PT_wages_active_income, PT_top_stacking,\n CG_rt1, CG_rt2, CG_rt3, CG_rt4, CG_brk1, CG_brk2, CG_brk3,\n dwks10, dwks13, dwks14, dwks19, c05700, taxbc):\n \"\"\"\n GainsTax function implements (2015) Schedule D Tax Worksheet logic for\n the special taxation of long-term capital gains and qualified dividends\n if CG_nodiff is false.\n \"\"\"\n # pylint: disable=too-many-statements\n if c01000 > 0. or c23650 > 0. or p23250 > 0. or e01100 > 0. or e00650 > 0.:\n hasqdivltcg = 1 # has qualified dividends or long-term capital gains\n else:\n hasqdivltcg = 0 # no qualified dividends or long-term capital gains\n\n if CG_nodiff:\n hasqdivltcg = 0 # no special taxation of qual divids and l-t cap gains\n\n if hasqdivltcg == 1:\n\n dwks1 = c04800\n dwks2 = e00650\n dwks3 = e58990\n dwks4 = 0. # always assumed to be zero\n dwks5 = max(0., dwks3 - dwks4)\n dwks6 = max(0., dwks2 - dwks5)\n dwks7 = min(p23250, c23650) # SchD lines 15 and 16, respectively\n # dwks8 = min(dwks3, dwks4)\n # dwks9 = max(0., dwks7 - dwks8)\n # BELOW TWO STATEMENTS ARE UNCLEAR IN LIGHT OF dwks9=... COMMENT\n if e01100 > 0.:\n c24510 = e01100\n else:\n c24510 = max(0., dwks7) + e01100\n dwks9 = max(0., c24510 - min(0., e58990))\n # ABOVE TWO STATEMENTS ARE UNCLEAR IN LIGHT OF dwks9=... COMMENT\n dwks10 = dwks6 + dwks9\n dwks11 = e24515 + e24518 # SchD lines 18 and 19, respectively\n dwks12 = min(dwks9, dwks11)\n dwks13 = dwks10 - dwks12\n dwks14 = max(0., dwks1 - dwks13)\n dwks16 = min(CG_brk1[MARS - 1], dwks1)\n dwks17 = min(dwks14, dwks16)\n dwks18 = max(0., dwks1 - dwks10)\n dwks19 = max(dwks17, dwks18)\n dwks20 = dwks16 - dwks17\n lowest_rate_tax = CG_rt1 * dwks20\n # break in worksheet lines\n dwks21 = min(dwks1, dwks13)\n dwks22 = dwks20\n dwks23 = max(0., dwks21 - dwks22)\n dwks25 = min(CG_brk2[MARS - 1], dwks1)\n dwks26 = dwks19 + dwks20\n dwks27 = max(0., dwks25 - dwks26)\n dwks28 = min(dwks23, dwks27)\n dwks29 = CG_rt2 * dwks28\n dwks30 = dwks22 + dwks28\n dwks31 = dwks21 - dwks30\n dwks32 = CG_rt3 * dwks31\n hi_base = max(0., dwks31 - CG_brk3[MARS - 1])\n hi_incremental_rate = CG_rt4 - CG_rt3\n highest_rate_incremental_tax = hi_incremental_rate * hi_base\n # break in worksheet lines\n dwks33 = min(dwks9, e24518)\n dwks34 = dwks10 + dwks19\n dwks36 = max(0., dwks34 - dwks1)\n dwks37 = max(0., dwks33 - dwks36)\n dwks38 = 0.25 * dwks37\n # break in worksheet lines\n dwks39 = dwks19 + dwks20 + dwks28 + dwks31 + dwks37\n dwks40 = dwks1 - dwks39\n dwks41 = 0.28 * dwks40\n dwks42 = SchXYZ(dwks19, MARS, e00900, e26270, e02000, e00200,\n PT_rt1, PT_rt2, PT_rt3, PT_rt4, PT_rt5,\n PT_rt6, PT_rt7, PT_rt8,\n PT_brk1, PT_brk2, PT_brk3, PT_brk4, PT_brk5,\n PT_brk6, PT_brk7,\n II_rt1, II_rt2, II_rt3, II_rt4, II_rt5,\n II_rt6, II_rt7, II_rt8,\n II_brk1, II_brk2, II_brk3, II_brk4, II_brk5,\n II_brk6, II_brk7, PT_EligibleRate_active,\n PT_EligibleRate_passive, PT_wages_active_income,\n PT_top_stacking)\n dwks43 = (dwks29 + dwks32 + dwks38 + dwks41 + dwks42 +\n lowest_rate_tax + highest_rate_incremental_tax)\n dwks44 = c05200\n dwks45 = min(dwks43, dwks44)\n c24580 = dwks45\n\n else: # if hasqdivltcg is zero\n\n c24580 = c05200\n dwks10 = max(0., min(p23250, c23650)) + e01100\n dwks13 = 0.\n dwks14 = 0.\n dwks19 = 0.\n\n # final calculations done no matter what the value of hasqdivltcg\n c05100 = c24580 # because foreign earned income exclusion is assumed zero\n c05700 = 0. # no Form 4972, Lump Sum Distributions\n taxbc = c05700 + c05100\n return (dwks10, dwks13, dwks14, dwks19, c05700, taxbc)\n\n\n@iterate_jit(nopython=True)\ndef AGIsurtax(c00100, MARS, AGI_surtax_trt, AGI_surtax_thd, taxbc, surtax):\n \"\"\"\n Computes surtax on AGI above some threshold.\n \"\"\"\n if AGI_surtax_trt > 0.:\n hiAGItax = AGI_surtax_trt * max(c00100 - AGI_surtax_thd[MARS - 1], 0.)\n taxbc += hiAGItax\n surtax += hiAGItax\n return (taxbc, surtax)\n\n\n@iterate_jit(nopython=True)\ndef AMT(e07300, dwks13, standard, f6251, c00100, c18300, taxbc,\n c04470, c17000, c20800, c21040, e24515, MARS, sep, dwks19,\n dwks14, c05700, e62900, e00700, dwks10, age_head, age_spouse,\n earned, cmbtp,\n AMT_child_em_c_age, AMT_brk1,\n AMT_em, AMT_prt, AMT_rt1, AMT_rt2,\n AMT_child_em, AMT_em_ps, AMT_em_pe,\n AMT_CG_brk1, AMT_CG_brk2, AMT_CG_brk3, AMT_CG_rt1, AMT_CG_rt2,\n AMT_CG_rt3, AMT_CG_rt4, c05800, c09600, c62100):\n \"\"\"\n Computes Alternative Minimum Tax (AMT) taxable income and liability, where\n c62100 is AMT taxable income,\n c09600 is AMT tax liability, and\n c05800 is total (regular + AMT) income tax liability before credits.\n\n Note that line-number variable names refer to 2015 Form 6251.\n \"\"\"\n # pylint: disable=too-many-statements,too-many-branches\n # Form 6251, Part I\n if standard == 0.0:\n c62100 = (c00100 - e00700 - c04470 +\n max(0., min(c17000, 0.025 * c00100)) +\n c18300 + c20800 - c21040)\n if standard > 0.0:\n c62100 = c00100 - e00700\n c62100 += cmbtp # add income not in AGI but considered income for AMT\n if MARS == 3:\n amtsepadd = max(0.,\n min(AMT_em[MARS - 1], AMT_prt * (c62100 - AMT_em_pe)))\n else:\n amtsepadd = 0.\n c62100 = c62100 + amtsepadd # AMT taxable income, which is line28\n # Form 6251, Part II top\n line29 = max(0., AMT_em[MARS - 1] - AMT_prt *\n max(0., c62100 - AMT_em_ps[MARS - 1]))\n young_head = age_head != 0 and age_head < AMT_child_em_c_age\n no_or_young_spouse = age_spouse < AMT_child_em_c_age\n if young_head and no_or_young_spouse:\n line29 = min(line29, earned + AMT_child_em)\n line30 = max(0., c62100 - line29)\n line3163 = (AMT_rt1 * line30 +\n AMT_rt2 * max(0., (line30 - (AMT_brk1 / sep))))\n if dwks10 > 0. or dwks13 > 0. or dwks14 > 0. or dwks19 > 0. or e24515 > 0.:\n # complete Form 6251, Part III (line36 is equal to line30)\n line37 = dwks13\n line38 = e24515\n line39 = min(line37 + line38, dwks10)\n line40 = min(line30, line39)\n line41 = max(0., line30 - line40)\n line42 = (AMT_rt1 * line41 +\n AMT_rt2 * max(0., (line41 - (AMT_brk1 / sep))))\n line44 = dwks14\n line45 = max(0., AMT_CG_brk1[MARS - 1] - line44)\n line46 = min(line30, line37)\n line47 = min(line45, line46) # line47 is amount taxed at AMT_CG_rt1\n cgtax1 = line47 * AMT_CG_rt1\n line48 = line46 - line47\n line51 = dwks19\n line52 = line45 + line51\n line53 = max(0., AMT_CG_brk2[MARS - 1] - line52)\n line54 = min(line48, line53) # line54 is amount taxed at AMT_CG_rt2\n cgtax2 = line54 * AMT_CG_rt2\n line56 = line47 + line54 # total amount in lower two brackets\n if line41 == line56:\n line57 = 0. # line57 is amount taxed at AMT_CG_rt3\n linex2 = 0. # linex2 is amount taxed at AMT_CG_rt4\n else:\n line57 = line46 - line56\n linex1 = min(line48,\n max(0., AMT_CG_brk3[MARS - 1] - line44 - line45))\n linex2 = max(0., line54 - linex1)\n cgtax3 = line57 * AMT_CG_rt3\n cgtax4 = linex2 * AMT_CG_rt4\n if line38 == 0.:\n line61 = 0.\n else:\n line61 = 0.25 * max(0., line30 - line41 - line56 - line57 - linex2)\n line62 = line42 + cgtax1 + cgtax2 + cgtax3 + cgtax4 + line61\n line64 = min(line3163, line62)\n line31 = line64\n else: # if not completing Form 6251, Part III\n line31 = line3163\n # Form 6251, Part II bottom\n if f6251 == 1:\n line32 = e62900\n else:\n line32 = e07300\n line33 = line31 - line32\n c09600 = max(0., line33 - max(0., taxbc - e07300 - c05700))\n c05800 = taxbc + c09600\n return (c62100, c09600, c05800)\n\n\n@iterate_jit(nopython=True)\ndef NetInvIncTax(e00300, e00600, e02000, e26270, c01000,\n c00100, NIIT_thd, MARS, NIIT_PT_taxed, NIIT_rt, niit):\n \"\"\"\n Computes Net Investment Income Tax (NIIT) amount assuming that\n all annuity income is excluded from net investment income.\n \"\"\"\n modAGI = c00100 # no foreign earned income exclusion to add\n if not NIIT_PT_taxed:\n NII = max(0., e00300 + e00600 + c01000 + e02000 - e26270)\n else: # do not subtract e26270 from e02000\n NII = max(0., e00300 + e00600 + c01000 + e02000)\n niit = NIIT_rt * min(NII, max(0., modAGI - NIIT_thd[MARS - 1]))\n return niit\n\n\n@iterate_jit(nopython=True)\ndef F2441(MARS, earned_p, earned_s, f2441, CDCC_c, e32800,\n exact, c00100, CDCC_ps, CDCC_crt, c05800, e07300, c07180):\n \"\"\"\n Calculates Form 2441 child and dependent care expense credit, c07180.\n \"\"\"\n # credit for at most two cared-for individuals and for actual expenses\n max_credit = min(f2441, 2) * CDCC_c\n c32800 = max(0., min(e32800, max_credit))\n # credit is limited to minimum of individuals' earned income\n c32880 = earned_p # earned income of taxpayer\n if MARS == 2:\n c32890 = earned_s # earned income of spouse when present\n else:\n c32890 = earned_p\n c33000 = max(0., min(c32800, min(c32880, c32890)))\n # credit is limited by AGI-related fraction\n if exact == 1: # exact calculation as on tax forms\n tratio = math.ceil(max(((c00100 - CDCC_ps) / 2000.), 0.))\n c33200 = c33000 * 0.01 * max(20., CDCC_crt - min(15., tratio))\n else:\n c33200 = c33000 * 0.01 * max(20., CDCC_crt -\n max(((c00100 - CDCC_ps) / 2000.), 0.))\n # credit is limited by tax liability\n c07180 = min(max(0., c05800 - e07300), c33200)\n return c07180\n\n\n@JIT(nopython=True)\ndef EITCamount(basic_frac, phasein_rate, earnings, max_amount,\n phaseout_start, agi, phaseout_rate):\n \"\"\"\n Returns EITC amount given specified parameters.\n English parameter names are used in this function because the\n EITC formula is not available on IRS forms or in IRS instructions;\n the extensive IRS EITC look-up table does not reveal the formula.\n \"\"\"\n eitc = min((basic_frac * max_amount +\n (1.0 - basic_frac) * phasein_rate * earnings), max_amount)\n if earnings > phaseout_start or agi > phaseout_start:\n eitcx = max(0., (max_amount - phaseout_rate *\n max(0., max(earnings, agi) - phaseout_start)))\n eitc = min(eitc, eitcx)\n return eitc\n\n\n@iterate_jit(nopython=True)\ndef EITC(MARS, DSI, EIC, c00100, e00300, e00400, e00600, c01000,\n e02000, e26270, age_head, age_spouse, earned, earned_p, earned_s,\n EITC_ps, EITC_MinEligAge, EITC_MaxEligAge, EITC_ps_MarriedJ,\n EITC_rt, EITC_c, EITC_prt, EITC_basic_frac,\n EITC_InvestIncome_c, EITC_excess_InvestIncome_rt,\n EITC_indiv, EITC_sep_filers_elig,\n c59660):\n \"\"\"\n Computes EITC amount, c59660.\n \"\"\"\n # pylint: disable=too-many-branches\n if MARS != 2:\n eitc = EITCamount(EITC_basic_frac,\n EITC_rt[EIC], earned, EITC_c[EIC],\n EITC_ps[EIC], c00100, EITC_prt[EIC])\n if EIC == 0:\n # enforce age eligibility rule for those with no EITC-eligible\n # kids assuming that an unknown age_* value implies EITC age\n # eligibility\n h_age_elig = EITC_MinEligAge <= age_head <= EITC_MaxEligAge\n if (age_head == 0 or h_age_elig):\n c59660 = eitc\n else:\n c59660 = 0.\n else: # if EIC != 0\n c59660 = eitc\n\n if MARS == 2:\n po_start = EITC_ps[EIC] + EITC_ps_MarriedJ[EIC]\n if not EITC_indiv:\n # filing unit EITC rather than individual EITC\n eitc = EITCamount(EITC_basic_frac,\n EITC_rt[EIC], earned, EITC_c[EIC],\n po_start, c00100, EITC_prt[EIC])\n if EITC_indiv:\n # individual EITC rather than a filing-unit EITC\n eitc_p = EITCamount(EITC_basic_frac,\n EITC_rt[EIC], earned_p, EITC_c[EIC],\n po_start, earned_p, EITC_prt[EIC])\n eitc_s = EITCamount(EITC_basic_frac,\n EITC_rt[EIC], earned_s, EITC_c[EIC],\n po_start, earned_s, EITC_prt[EIC])\n eitc = eitc_p + eitc_s\n\n if EIC == 0:\n h_age_elig = EITC_MinEligAge <= age_head <= EITC_MaxEligAge\n s_age_elig = EITC_MinEligAge <= age_spouse <= EITC_MaxEligAge\n if (age_head == 0 or age_spouse == 0 or h_age_elig or s_age_elig):\n c59660 = eitc\n else:\n c59660 = 0.\n else:\n c59660 = eitc\n\n if (MARS == 3 and not EITC_sep_filers_elig) or DSI == 1:\n c59660 = 0.\n\n # reduce positive EITC if investment income exceeds ceiling\n if c59660 > 0.:\n invinc = (e00400 + e00300 + e00600 +\n max(0., c01000) + max(0., (e02000 - e26270)))\n if invinc > EITC_InvestIncome_c:\n eitc = (c59660 - EITC_excess_InvestIncome_rt *\n (invinc - EITC_InvestIncome_c))\n c59660 = max(0., eitc)\n return c59660\n\n\n@iterate_jit(nopython=True)\ndef RefundablePayrollTaxCredit(was_plus_sey_p, was_plus_sey_s,\n RPTC_c, RPTC_rt,\n rptc_p, rptc_s, rptc):\n \"\"\"\n Computes refundable payroll tax credit amounts.\n \"\"\"\n rptc_p = min(was_plus_sey_p * RPTC_rt, RPTC_c)\n rptc_s = min(was_plus_sey_s * RPTC_rt, RPTC_c)\n rptc = rptc_p + rptc_s\n return (rptc_p, rptc_s, rptc)\n\n\n@iterate_jit(nopython=True)\ndef ChildDepTaxCredit(n24, MARS, c00100, XTOT, num, c05800,\n e07260, CR_ResidentialEnergy_hc,\n e07300, CR_ForeignTax_hc,\n c07180,\n c07230,\n e07240, CR_RetirementSavings_hc,\n c07200,\n CTC_c, CTC_ps, CTC_prt, exact, ODC_c,\n CTC_c_under6_bonus, nu06,\n c07220, odc, codtc_limited):\n \"\"\"\n Computes amounts on \"Child Tax Credit and Credit for Other Dependents\n Worksheet\" in 2018 Publication 972, which pertain to these two\n nonrefundable tax credits.\n \"\"\"\n # Worksheet Part 1\n line1 = CTC_c * n24 + CTC_c_under6_bonus * nu06\n line2 = ODC_c * max(0, XTOT - n24 - num)\n line3 = line1 + line2\n modAGI = c00100 # no foreign earned income exclusion to add to AGI (line6)\n if line3 > 0. and modAGI > CTC_ps[MARS - 1]:\n excess = modAGI - CTC_ps[MARS - 1]\n if exact == 1: # exact calculation as on tax forms\n excess = 1000. * math.ceil(excess / 1000.)\n line10 = max(0., line3 - CTC_prt * excess)\n else:\n line10 = line3\n if line10 > 0.:\n # Worksheet Part 2\n line11 = c05800\n line12 = (e07260 * (1. - CR_ResidentialEnergy_hc) +\n e07300 * (1. - CR_ForeignTax_hc) +\n c07180 + # child & dependent care expense credit\n c07230 + # education credit\n e07240 * (1. - CR_RetirementSavings_hc) +\n c07200) # Schedule R credit\n line13 = line11 - line12\n line14 = 0.\n line15 = max(0., line13 - line14)\n line16 = min(line10, line15) # credit is capped by tax liability\n else:\n line16 = 0.\n # separate the CTC and ODTC amounts\n c07220 = 0. # nonrefundable CTC amount\n odc = 0. # nonrefundable ODTC amount\n if line16 > 0.:\n if line1 > 0.:\n c07220 = line16 * line1 / line3\n odc = max(0., line16 - c07220)\n # compute codtc_limited for use in AdditionalCTC function\n codtc_limited = max(0., line10 - line16)\n return (c07220, odc, codtc_limited)\n\n\n@iterate_jit(nopython=True)\ndef PersonalTaxCredit(MARS, c00100,\n II_credit, II_credit_ps, II_credit_prt,\n II_credit_nr, II_credit_nr_ps, II_credit_nr_prt,\n personal_refundable_credit,\n personal_nonrefundable_credit):\n \"\"\"\n Computes personal_refundable_credit and personal_nonrefundable_credit,\n neither of which are part of current-law policy.\n \"\"\"\n # calculate personal refundable credit amount with phase-out\n personal_refundable_credit = II_credit[MARS - 1]\n if II_credit_prt > 0. and c00100 > II_credit_ps[MARS - 1]:\n pout = II_credit_prt * (c00100 - II_credit_ps[MARS - 1])\n fully_phasedout = personal_refundable_credit - pout\n personal_refundable_credit = max(0., fully_phasedout)\n # calculate personal nonrefundable credit amount with phase-out\n personal_nonrefundable_credit = II_credit_nr[MARS - 1]\n if II_credit_nr_prt > 0. and c00100 > II_credit_nr_ps[MARS - 1]:\n pout = II_credit_nr_prt * (c00100 - II_credit_nr_ps[MARS - 1])\n fully_phasedout = personal_nonrefundable_credit - pout\n personal_nonrefundable_credit = max(0., fully_phasedout)\n return (personal_refundable_credit, personal_nonrefundable_credit)\n\n@iterate_jit(nopython=True)\ndef IRADCTaxCredit(e03150, e03300, IRADC_credit_c, IRADC_credit_rt, iradctc):\n \"\"\"\n Computes refundable retirement savings tax credit amount.\n \"\"\"\n # calculate refundable credit amount \n tot_retirement_contributions = e03150 + e03300\n if IRADC_credit_rt > 0.:\n iradctc = min(tot_retirement_contributions * IRADC_credit_rt, IRADC_credit_c)\n else:\n iradctc = 0.\n return (iradctc)\n\n@iterate_jit(nopython=True)\ndef FTHBTaxCredit(MARS, FTHB_credit, FTHB_credit_c, c00100,\n FTHB_credit_e, fthbc, fthb_credit_amt):\n \"\"\"\n Computes refundable first time homebuyers' tax credit amount.\n \"\"\"\n if FTHB_credit is True:\n # max credit\n fthbc = max(0., min(FTHB_credit_c, fthb_credit_amt))\n # eliminated based on agi\n positiveagiamt = max(c00100, 0.)\n fthb_max_agi = FTHB_credit_e[MARS - 1]\n if positiveagiamt <= fthb_max_agi:\n fthbc = fthbc\n else:\n fthbc = 0.\n return (fthbc)\n\n@iterate_jit(nopython=True)\ndef ICGTaxCredit(earned_p, earned_s, MARS, ICG_credit_c, ICG_credit_em,\n ICG_credit_rt, ICG_credit_thd, icg_expense, c05800, e07300,\n icgtc):\n \"\"\"\n Computes nonrefundable informal care giver tax credit.\n \"\"\"\n # not reflected in current law and records modified with imputation\n # earned income of taxpayer\n icg32880 = earned_p # earned income of taxpayer\n if MARS == 2:\n icg32890 = earned_s # earned income of spouse when present\n else:\n icg32890 = earned_p\n icg33000 = min(icg32880, icg32890)\n if icg33000 > ICG_credit_thd:\n # credit for actual expenses\n icg_max_credit = (icg_expense - ICG_credit_em) * ICG_credit_rt\n icg_credit = max(0., min(icg_max_credit, ICG_credit_c))\n # credit is limited to minimum of individuals' earned income\n icg_credit = max(0., min(icg_credit, icg33000))\n # credit is limited by tax liability\n icgtc = min(max(0., c05800 - e07300), icg_credit)\n else:\n icgtc = 0.\n return icgtc\n\n@iterate_jit(nopython=True)\ndef IRATaxCredit(earned_p, earned_s, MARS, AutoIRA_credit, ira_credit,\n c05800, e07300, iratc):\n \"\"\"\n Computes nonrefundable automatic enrollment in IRA tax credit.\n \"\"\"\n # not reflected in current law and records modified with imputation\n if AutoIRA_credit is True:\n iratc = max(0., ira_credit)\n else:\n iratc = 0.\n return iratc\n\n@iterate_jit(nopython=True)\ndef EVTaxCredit(EV_credit, ev_credit_amt, EV_credit_c, c00100, EV_credit_ps, MARS,\n EV_credit_prt, evtc):\n \"\"\"\n Computes nonrefundable full-electric vehicle tax credit.\n \"\"\"\n if EV_credit is True:\n # not reflected in current law and records modified with imputation\n elecv_credit = max(0., min(ev_credit_amt, EV_credit_c))\n # phaseout based on agi\n posevagi = max(c00100, 0.)\n ev_max = EV_credit_ps[MARS - 1]\n if posevagi < ev_max:\n evtc = elecv_credit\n else:\n evtc_reduced = max(0., evtc - EV_credit_prt * (posevagi - ev_max))\n evtc = min(evtc, evtc_reduced)\n return evtc\n\n@iterate_jit(nopython=True)\ndef AmOppCreditParts(exact, e87521, num, c00100, CR_AmOppRefundable_hc,\n CR_AmOppNonRefundable_hc, c10960, c87668):\n \"\"\"\n Applies a phaseout to the Form 8863, line 1, American Opportunity Credit\n amount, e87521, and then applies the 0.4 refundable rate.\n Logic corresponds to Form 8863, Part I.\n\n Notes\n -----\n Tax Law Parameters that are not parameterized:\n\n 90000 : American Opportunity Credit phaseout income base\n\n 10000 : American Opportunity Credit phaseout income range length\n\n 1/1000 : American Opportunity Credit phaseout rate\n\n 0.4 : American Opportunity Credit refundable rate\n\n Parameters\n ----------\n exact : whether or not to do rounding of phaseout fraction\n\n e87521 : total tentative American Opportunity Credit for all students,\n Form 8863, line 1\n\n num : number of people filing jointly\n\n c00100 : AGI\n\n CR_AmOppRefundable_hc: haircut for the refundable portion of the\n American Opportunity Credit\n\n CR_AmOppNonRefundable_hc: haircut for the nonrefundable portion of the\n American Opportunity Credit\n\n Returns\n -------\n c10960 : Refundable part of American Opportunity Credit\n\n c87668 : Tentative nonrefundable part of American Opportunity Credit\n \"\"\"\n if e87521 > 0.:\n c87658 = max(0., 90000. * num - c00100)\n c87660 = 10000. * num\n if exact == 1: # exact calculation as on tax forms\n c87662 = 1000. * min(1., round(c87658 / c87660, 3))\n else:\n c87662 = 1000. * min(1., c87658 / c87660)\n c87664 = c87662 * e87521 / 1000.\n c10960 = 0.4 * c87664 * (1. - CR_AmOppRefundable_hc)\n c87668 = c87664 - c10960 * (1. - CR_AmOppNonRefundable_hc)\n else:\n c10960 = 0.\n c87668 = 0.\n return (c10960, c87668)\n\n\n@iterate_jit(nopython=True)\ndef SchR(age_head, age_spouse, MARS, c00100,\n c05800, e07300, c07180, e02400, c02500, e01500, e01700, CR_SchR_hc,\n c07200):\n \"\"\"\n Calculates Schedule R credit for the elderly and the disabled, c07200.\n\n Note that no Schedule R policy parameters are inflation indexed.\n\n Note that all Schedule R policy parameters are hard-coded, and therefore,\n are not able to be changed using Policy class parameters.\n\n Note that the CR_SchR_hc policy parameter allows the user to eliminate\n or reduce total Schedule R credits.\n \"\"\"\n if age_head >= 65 or (MARS == 2 and age_spouse >= 65):\n # calculate credit assuming nobody is disabled (so line12 = line10)\n if MARS == 2:\n if age_head >= 65 and age_spouse >= 65:\n schr12 = 7500.\n else:\n schr12 = 5000.\n schr15 = 10000.\n elif MARS == 3:\n schr12 = 3750.\n schr15 = 5000.\n elif MARS in (1, 4):\n schr12 = 5000.\n schr15 = 7500.\n else:\n schr12 = 0.\n schr15 = 0.\n # nontaxable portion of OASDI benefits, line 13a\n schr13a = max(0., e02400 - c02500)\n # nontaxable portion of pension benefits, line 13b\n # NOTE: the following approximation (required because of inadequate IRS\n # data) will be accurate if all pensions are partially taxable\n # or if all pensions are fully taxable. But if a filing unit\n # receives at least one partially taxable pension and at least\n # one fully taxable pension, then the approximation in the\n # following line is not exactly correct.\n schr13b = max(0., e01500 - e01700)\n schr13c = schr13a + schr13b\n schr16 = max(0., c00100 - schr15)\n schr17 = 0.5 * schr16\n schr18 = schr13c + schr17\n schr19 = max(0., schr12 - schr18)\n schr20 = 0.15 * schr19\n schr21 = max(0., (c05800 - e07300 - c07180))\n c07200 = min(schr20, schr21) * (1. - CR_SchR_hc)\n else: # if not calculating Schedule R credit\n c07200 = 0.\n return c07200\n\n\n@iterate_jit(nopython=True)\ndef EducationTaxCredit(exact, e87530, MARS, c00100, num, c05800,\n e07300, c07180, c07200, c87668,\n LLC_Expense_c, ETC_pe_Single, ETC_pe_Married,\n CR_Education_hc,\n c07230):\n \"\"\"\n Computes Education Tax Credits (Form 8863) nonrefundable amount, c07230.\n Logic corresponds to Form 8863, Part II.\n\n Notes\n -----\n Tax Law Parameters that are not parameterized:\n\n 0.2 : Lifetime Learning Credit ratio against expense\n\n Tax Law Parameters that are parameterized:\n\n LLC_Expense_c : Lifetime Learning Credit expense limit\n\n ETC_pe_Married : Education Tax Credit phaseout end for married\n\n ETC_pe_Single : Education Tax Credit phaseout end for single\n\n Taxpayer Charateristics:\n\n exact : whether or not to do rounding of phaseout fraction\n\n e87530 : Lifetime Learning Credit total qualified expenses,\n Form 8863, line 10\n\n e07300 : Foreign tax credit - Form 1116\n\n c07180 : Child/dependent care expense credit - Form 2441\n\n c07200 : Schedule R credit\n\n Returns\n -------\n c07230 : Education Tax Credits (Form 8863) nonrefundable amount\n \"\"\"\n c87560 = 0.2 * min(e87530, LLC_Expense_c)\n if MARS == 2:\n c87570 = ETC_pe_Married * 1000.\n else:\n c87570 = ETC_pe_Single * 1000.\n c87590 = max(0., c87570 - c00100)\n c87600 = 10000. * num\n if exact == 1: # exact calculation as on tax forms\n c87610 = min(1., round(c87590 / c87600, 3))\n else:\n c87610 = min(1., c87590 / c87600)\n c87620 = c87560 * c87610\n xline4 = max(0., c05800 - (e07300 + c07180 + c07200))\n xline5 = min(c87620, xline4)\n xline9 = max(0., c05800 - (e07300 + c07180 + c07200 + xline5))\n xline10 = min(c87668, xline9)\n c87680 = xline5 + xline10\n c07230 = c87680 * (1. - CR_Education_hc)\n return c07230\n\n\n@iterate_jit(nopython=True)\ndef CharityCredit(e19800, e20100, c00100, CR_Charity_rt, CR_Charity_f,\n CR_Charity_frt, MARS, charity_credit):\n \"\"\"\n Computes nonrefundable charity credit, charity_credit.\n This credit is not part of current-law policy.\n \"\"\"\n total_charity = e19800 + e20100\n floor = max(CR_Charity_frt * c00100, CR_Charity_f[MARS - 1])\n charity_cr_floored = max(total_charity - floor, 0)\n charity_credit = CR_Charity_rt * (charity_cr_floored)\n return charity_credit\n\n\n@iterate_jit(nopython=True)\ndef NonrefundableCredits(c05800, e07240, e07260, e07300, e07400,\n e07600, p08000, odc,\n personal_nonrefundable_credit, icgtc, iratc, evtc,\n CR_RetirementSavings_hc, CR_ForeignTax_hc,\n CR_ResidentialEnergy_hc, CR_GeneralBusiness_hc,\n CR_MinimumTax_hc, CR_OtherCredits_hc, charity_credit,\n c07180, c07200, c07220, c07230, c07240,\n c07260, c07300, c07400, c07600, c08000):\n \"\"\"\n NonRefundableCredits function sequentially limits credits to tax liability.\n\n Parameters\n ----------\n CR_RetirementSavings_hc: Retirement savings credit haircut\n CR_ForeignTax_hc: Foreign tax credit haircut\n CR_ResidentialEnergy_hc: Residential energy credit haircut\n CR_GeneralBusiness_hc: General business credit haircut\n CR_MinimumTax_hc: Minimum tax credit haircut\n CR_OtherCredits_hc: Other credits haircut\n \"\"\"\n # limit tax credits to tax liability in order they are on 2015 1040 form\n avail = c05800\n # Foreign tax credit - Form 1116\n c07300 = min(e07300 * (1. - CR_ForeignTax_hc), avail)\n avail = avail - c07300\n # Child & dependent care expense credit\n c07180 = min(c07180, avail)\n avail = avail - c07180\n # Education tax credit\n c07230 = min(c07230, avail)\n avail = avail - c07230\n # Retirement savings credit - Form 8880\n c07240 = min(e07240 * (1. - CR_RetirementSavings_hc), avail)\n avail = avail - c07240\n # Child tax credit\n c07220 = min(c07220, avail)\n avail = avail - c07220\n # Other dependent credit\n odc = min(odc, avail)\n avail = avail - odc\n # Residential energy credit - Form 5695\n c07260 = min(e07260 * (1. - CR_ResidentialEnergy_hc), avail)\n avail = avail - c07260\n # General business credit - Form 3800\n c07400 = min(e07400 * (1. - CR_GeneralBusiness_hc), avail)\n avail = avail - c07400\n # Prior year minimum tax credit - Form 8801\n c07600 = min(e07600 * (1. - CR_MinimumTax_hc), avail)\n avail = avail - c07600\n # Schedule R credit\n c07200 = min(c07200, avail)\n avail = avail - c07200\n # Other credits\n c08000 = min(p08000 * (1. - CR_OtherCredits_hc), avail)\n avail = avail - c08000\n # Charity credit\n charity_credit = min(charity_credit, avail)\n avail = avail - charity_credit\n # Personal nonrefundable credit\n personal_nonrefundable_credit = min(personal_nonrefundable_credit, avail)\n avail = avail - personal_nonrefundable_credit\n # ICG credit\n icgtc = min(icgtc, avail)\n avail = avail - icgtc\n # IRA credit\n iratc = min(iratc, avail)\n avail = avail - iratc\n # EV credit\n evtc = min(evtc, avail)\n avail = avail - evtc \n return (c07180, c07200, c07220, c07230, c07240, odc,\n c07260, c07300, c07400, c07600, c08000, charity_credit,\n personal_nonrefundable_credit, icgtc, iratc, evtc)\n\n\n@iterate_jit(nopython=True)\ndef AdditionalCTC(codtc_limited, ACTC_c, n24, earned, ACTC_Income_thd,\n ACTC_rt, nu06, ACTC_rt_bonus_under6family, ACTC_ChildNum,\n ptax_was, c03260, e09800, c59660, e11200,\n c11070):\n \"\"\"\n Calculates refundable Additional Child Tax Credit (ACTC), c11070,\n following 2018 Form 8812 logic.\n \"\"\"\n # Part I\n line3 = codtc_limited\n line4 = ACTC_c * n24\n c11070 = 0. # line15\n if line3 > 0. and line4 > 0.:\n line5 = min(line3, line4)\n line7 = max(0., earned - ACTC_Income_thd)\n # accommodate ACTC rate bonus for families with children under 5\n if nu06 == 0:\n ACTC_rate = ACTC_rt\n else:\n ACTC_rate = ACTC_rt + ACTC_rt_bonus_under6family\n line8 = ACTC_rate * line7\n if n24 < ACTC_ChildNum:\n if line8 > 0.:\n c11070 = min(line5, line8)\n else: # if n24 >= ACTC_ChildNum\n if line8 >= line5:\n c11070 = line5\n else: # complete Part II\n line9 = 0.5 * ptax_was\n line10 = c03260 + e09800\n line11 = line9 + line10\n line12 = c59660 + e11200\n line13 = max(0., line11 - line12)\n line14 = max(line8, line13)\n c11070 = min(line5, line14)\n return c11070\n\n\n@iterate_jit(nopython=True)\ndef C1040(c05800, c07180, c07200, c07220, c07230, c07240, c07260, c07300,\n c07400, c07600, c08000, e09700, e09800, e09900, niit, othertaxes,\n c07100, c09200, odc, charity_credit,\n personal_nonrefundable_credit, icgtc, iratc, evtc):\n \"\"\"\n Computes total used nonrefundable credits, c07100, othertaxes, and\n income tax before refundable credits, c09200.\n \"\"\"\n # total used nonrefundable credits (as computed in NonrefundableCredits)\n c07100 = (c07180 + c07200 + c07600 + c07300 + c07400 + c07220 + c08000 +\n c07230 + c07240 + c07260 + odc + charity_credit +\n personal_nonrefundable_credit + icgtc + iratc + evtc)\n # tax after credits (2016 Form 1040, line 56)\n tax_net_nonrefundable_credits = max(0., c05800 - c07100)\n # tax (including othertaxes) before refundable credits\n othertaxes = e09700 + e09800 + e09900 + niit\n c09200 = othertaxes + tax_net_nonrefundable_credits\n return (c07100, othertaxes, c09200)\n\n\n@iterate_jit(nopython=True)\ndef CTC_new(CTC_new_c, CTC_new_rt, CTC_new_c_under6_bonus,\n CTC_new_ps, CTC_new_prt, CTC_new_for_all,\n CTC_new_refund_limited, CTC_new_refund_limit_payroll_rt,\n CTC_new_refund_limited_all_payroll, payrolltax,\n n24, nu06, c00100, MARS, ptax_oasdi, c09200,\n ctc_new):\n \"\"\"\n Computes new refundable child tax credit using specified parameters.\n \"\"\"\n if n24 > 0:\n posagi = max(c00100, 0.)\n ctc_new = CTC_new_c * n24 + CTC_new_c_under6_bonus * nu06\n if not CTC_new_for_all:\n ctc_new = min(CTC_new_rt * posagi, ctc_new)\n ymax = CTC_new_ps[MARS - 1]\n if posagi > ymax:\n ctc_new_reduced = max(0.,\n ctc_new - CTC_new_prt * (posagi - ymax))\n ctc_new = min(ctc_new, ctc_new_reduced)\n if ctc_new > 0. and CTC_new_refund_limited:\n refund_new = max(0., ctc_new - c09200)\n if not CTC_new_refund_limited_all_payroll:\n limit_new = CTC_new_refund_limit_payroll_rt * ptax_oasdi\n if CTC_new_refund_limited_all_payroll:\n limit_new = CTC_new_refund_limit_payroll_rt * payrolltax\n limited_new = max(0., refund_new - limit_new)\n ctc_new = max(0., ctc_new - limited_new)\n else:\n ctc_new = 0.\n return ctc_new\n\n@iterate_jit(nopython=True)\ndef CDCC_new(CDCC_new_c, CDCC_new_rt, CDCC_new_ps, CDCC_new_pe, CDCC_new_prt, cdcc_new,\n MARS, f2441, e32800, earned_s, earned_p, c05800, e07300, c00100):\n \"\"\"\n Calculates new refundable child and dependent care expense credit, cdcc_new.\n \"\"\"\n # credit for at most two cared-for individuals and for actual expenses\n cdcc_new_max_credit = min(f2441, 2) * CDCC_new_c\n cdcc_new_32800 = max(0., min(e32800 * CDCC_new_rt, cdcc_new_max_credit))\n # credit is limited to minimum of individuals' earned income\n cdcc_new_32880 = earned_p # earned income of taxpayer\n if MARS == 2:\n cdcc_new_32890 = earned_s # earned income of spouse when present\n else:\n cdcc_new_32890 = earned_p\n cdcc_new_33000 = max(0., min(cdcc_new_32800, min(cdcc_new_32880, cdcc_new_32890)))\n # credit is limited by tax liability\n cdcc_new = min(max(0., c05800 - e07300), cdcc_new_33000)\n # phaseout based on agi\n positiveagi = max(c00100, 0.)\n cdcc_min = CDCC_new_ps[MARS - 1]\n cdcc_max = CDCC_new_pe[MARS - 1]\n if positiveagi < cdcc_min:\n cdcc_new = cdcc_new\n elif positiveagi < cdcc_max:\n cdcc_new_reduced = max(0., cdcc_new - CDCC_new_prt * (positiveagi - cdcc_min))\n cdcc_new = min(cdcc_new, cdcc_new_reduced)\n else:\n cdcc_new = 0.\n return cdcc_new\n\n@iterate_jit(nopython=True)\ndef IITAX(c59660, c11070, c10960, personal_refundable_credit, ctc_new, rptc,\n c09200, payrolltax,\n eitc, refund, iitax, combined, iradctc, fthbc, cdcc_new,\n business_burden, estate_burden, Business_tax_combined):\n \"\"\"\n Computes final taxes.\n \"\"\"\n eitc = c59660\n refund = (eitc + c11070 + c10960 +\n personal_refundable_credit + ctc_new + rptc + iradctc + fthbc + cdcc_new)\n iitax = c09200 - refund\n if Business_tax_combined is True:\n combined = iitax + payrolltax + business_burden + estate_burden\n else:\n combined = iitax + payrolltax\n return (eitc, refund, iitax, combined)\n\n\n@JIT(nopython=True)\ndef Taxes(income, MARS, tbrk_base,\n rate1, rate2, rate3, rate4, rate5, rate6, rate7, rate8,\n tbrk1, tbrk2, tbrk3, tbrk4, tbrk5, tbrk6, tbrk7):\n \"\"\"\n Taxes function returns tax amount given the progressive tax rate\n schedule specified by the rate* and (upper) tbrk* parameters and\n given income, filing status (MARS), and tax bracket base (tbrk_base).\n \"\"\"\n if tbrk_base > 0.:\n brk1 = max(tbrk1[MARS - 1] - tbrk_base, 0.)\n brk2 = max(tbrk2[MARS - 1] - tbrk_base, 0.)\n brk3 = max(tbrk3[MARS - 1] - tbrk_base, 0.)\n brk4 = max(tbrk4[MARS - 1] - tbrk_base, 0.)\n brk5 = max(tbrk5[MARS - 1] - tbrk_base, 0.)\n brk6 = max(tbrk6[MARS - 1] - tbrk_base, 0.)\n brk7 = max(tbrk7[MARS - 1] - tbrk_base, 0.)\n else:\n brk1 = tbrk1[MARS - 1]\n brk2 = tbrk2[MARS - 1]\n brk3 = tbrk3[MARS - 1]\n brk4 = tbrk4[MARS - 1]\n brk5 = tbrk5[MARS - 1]\n brk6 = tbrk6[MARS - 1]\n brk7 = tbrk7[MARS - 1]\n return (rate1 * min(income, brk1) +\n rate2 * min(brk2 - brk1, max(0., income - brk1)) +\n rate3 * min(brk3 - brk2, max(0., income - brk2)) +\n rate4 * min(brk4 - brk3, max(0., income - brk3)) +\n rate5 * min(brk5 - brk4, max(0., income - brk4)) +\n rate6 * min(brk6 - brk5, max(0., income - brk5)) +\n rate7 * min(brk7 - brk6, max(0., income - brk6)) +\n rate8 * max(0., income - brk7))\n\n\ndef ComputeBenefit(calc, ID_switch):\n \"\"\"\n Calculates the value of the benefits accrued from itemizing.\n \"\"\"\n # compute income tax liability with no itemized deductions allowed for\n # the types of itemized deductions covered under the BenefitSurtax\n no_ID_calc = copy.deepcopy(calc)\n if ID_switch[0]:\n no_ID_calc.policy_param('ID_Medical_hc', [1.])\n if ID_switch[1]:\n no_ID_calc.policy_param('ID_StateLocalTax_hc', [1.])\n if ID_switch[2]:\n no_ID_calc.policy_param('ID_RealEstate_hc', [1.])\n if ID_switch[3]:\n no_ID_calc.policy_param('ID_Casualty_hc', [1.])\n if ID_switch[4]:\n no_ID_calc.policy_param('ID_Miscellaneous_hc', [1.])\n if ID_switch[5]:\n no_ID_calc.policy_param('ID_InterestPaid_hc', [1.])\n if ID_switch[6]:\n no_ID_calc.policy_param('ID_Charity_hc', [1.])\n no_ID_calc._calc_one_year() # pylint: disable=protected-access\n diff_iitax = no_ID_calc.array('iitax') - calc.array('iitax')\n benefit = np.where(diff_iitax > 0., diff_iitax, 0.)\n return benefit\n\n\ndef BenefitSurtax(calc):\n \"\"\"\n Computes itemized-deduction-benefit surtax and adds the surtax amount\n to income tax, combined tax, and surtax liabilities.\n \"\"\"\n if calc.policy_param('ID_BenefitSurtax_crt') != 1.:\n ben = ComputeBenefit(calc,\n calc.policy_param('ID_BenefitSurtax_Switch'))\n agi = calc.array('c00100')\n ben_deduct = calc.policy_param('ID_BenefitSurtax_crt') * agi\n ben_exempt_array = calc.policy_param('ID_BenefitSurtax_em')\n ben_exempt = ben_exempt_array[calc.array('MARS') - 1]\n ben_dedem = ben_deduct + ben_exempt\n ben_surtax = (calc.policy_param('ID_BenefitSurtax_trt') *\n np.where(ben > ben_dedem, ben - ben_dedem, 0.))\n # add ben_surtax to income & combined taxes and to surtax subtotal\n calc.incarray('iitax', ben_surtax)\n calc.incarray('combined', ben_surtax)\n calc.incarray('surtax', ben_surtax)\n\n\ndef BenefitLimitation(calc):\n \"\"\"\n Limits the benefits of select itemized deductions to a fraction of\n deductible expenses.\n \"\"\"\n if calc.policy_param('ID_BenefitCap_rt') != 1.:\n benefit = ComputeBenefit(calc,\n calc.policy_param('ID_BenefitCap_Switch'))\n # Calculate total deductible expenses under the cap\n deduct_exps = 0.\n if calc.policy_param('ID_BenefitCap_Switch')[0]: # medical\n deduct_exps += calc.array('c17000')\n if calc.policy_param('ID_BenefitCap_Switch')[1]: # statelocal\n one_minus_hc = 1. - calc.policy_param('ID_StateLocalTax_hc')\n deduct_exps += (one_minus_hc *\n np.maximum(calc.array('e18400_capped'), 0.))\n if calc.policy_param('ID_BenefitCap_Switch')[2]: # realestate\n one_minus_hc = 1. - calc.policy_param('ID_RealEstate_hc')\n deduct_exps += one_minus_hc * calc.array('e18500_capped')\n if calc.policy_param('ID_BenefitCap_Switch')[3]: # casualty\n deduct_exps += calc.array('c20500')\n if calc.policy_param('ID_BenefitCap_Switch')[4]: # misc\n deduct_exps += calc.array('c20800')\n if calc.policy_param('ID_BenefitCap_Switch')[5]: # interest\n deduct_exps += calc.array('c19200')\n if calc.policy_param('ID_BenefitCap_Switch')[6]: # charity\n deduct_exps += calc.array('c19700')\n # Calculate cap value for itemized deductions\n benefit_limit = deduct_exps * calc.policy_param('ID_BenefitCap_rt')\n # Add the difference between the actual benefit and capped benefit\n # to income tax and combined tax liabilities.\n excess_benefit = np.maximum(benefit - benefit_limit, 0)\n calc.incarray('iitax', excess_benefit)\n calc.incarray('surtax', excess_benefit)\n calc.incarray('combined', excess_benefit)\n\n\n@iterate_jit(nopython=True)\ndef FairShareTax(c00100, MARS, ptax_was, setax, ptax_amc,\n FST_AGI_trt, FST_AGI_thd_lo, FST_AGI_thd_hi,\n fstax, iitax, combined, surtax):\n \"\"\"\n Computes Fair Share Tax, or \"Buffet Rule\", types of reforms.\n\n Taxpayer Characteristics\n ------------------------\n\n c00100 : AGI\n\n MARS : filing (marital) status\n\n ptax_was : payroll tax on wages and salaries\n\n setax : self-employment tax\n\n ptax_amc : Additional Medicare Tax on high earnings\n\n Returns\n -------\n\n fstax : Fair Share Tax amount\n\n iitax : individual income tax augmented by fstax\n\n combined : individual income tax plus payroll taxes augmented by fstax\n\n surtax : individual income tax subtotal augmented by fstax\n \"\"\"\n if FST_AGI_trt > 0. and c00100 >= FST_AGI_thd_lo[MARS - 1]:\n employee_share = 0.5 * ptax_was + 0.5 * setax + ptax_amc\n fstax = max(c00100 * FST_AGI_trt - iitax - employee_share, 0.)\n thd_gap = max(FST_AGI_thd_hi[MARS - 1] - FST_AGI_thd_lo[MARS - 1], 0.)\n if thd_gap > 0. and c00100 < FST_AGI_thd_hi[MARS - 1]:\n fstax *= (c00100 - FST_AGI_thd_lo[MARS - 1]) / thd_gap\n iitax += fstax\n combined += fstax\n surtax += fstax\n else:\n fstax = 0.\n return (fstax, iitax, combined, surtax)\n\n\n@iterate_jit(nopython=True)\ndef LumpSumTax(DSI, num, XTOT,\n LST,\n lumpsum_tax, combined):\n \"\"\"\n Computes lump-sum tax and add it to combined taxes.\n \"\"\"\n if LST == 0.0 or DSI == 1:\n lumpsum_tax = 0.\n else:\n lumpsum_tax = LST * max(num, XTOT)\n combined += lumpsum_tax\n return (lumpsum_tax, combined)\n\n\n@iterate_jit(nopython=True)\ndef ExpandIncome(e00200, pencon_p, pencon_s, e00300, e00400, e00600,\n e00700, e00800, e00900, e01100, e01200, e01400, e01500,\n e02000, e02100, p22250, p23250, cmbtp, ptax_was,\n benefit_value_total, expanded_income):\n \"\"\"\n Calculates expanded_income from component income types.\n \"\"\"\n expanded_income = (\n e00200 + # wage and salary income net of DC pension contributions\n pencon_p + # tax-advantaged DC pension contributions for taxpayer\n pencon_s + # tax-advantaged DC pension contributions for spouse\n e00300 + # taxable interest income\n e00400 + # non-taxable interest income\n e00600 + # dividends\n e00700 + # state and local income tax refunds\n e00800 + # alimony received\n e00900 + # Sch C business net income/loss\n e01100 + # capital gain distributions not reported on Sch D\n e01200 + # Form 4797 other net gain/loss\n e01400 + # taxable IRA distributions\n e01500 + # total pension & annuity income (including DB-plan benefits)\n e02000 + # Sch E total rental, ..., partnership, S-corp income/loss\n e02100 + # Sch F farm net income/loss\n p22250 + # Sch D: net short-term capital gain/loss\n p23250 + # Sch D: net long-term capital gain/loss\n cmbtp + # other AMT taxable income items from Form 6251\n 0.5 * ptax_was + # employer share of FICA taxes on wages/salaries\n benefit_value_total # consumption value of all benefits received;\n # see the BenefitPrograms function in this file for details on\n # exactly how the benefit_value_total variable is computed\n )\n return expanded_income\n\n\n@iterate_jit(nopython=True)\ndef AfterTaxIncome(combined, expanded_income, aftertax_income,\n Business_tax_expinc, corp_taxliab):\n \"\"\"\n Calculates after-tax expanded income.\n\n Parameters\n ----------\n combined: combined tax liability\n expanded_income: expanded income\n corp_taxliab: imputed corporate tax liability\n\n Returns\n -------\n aftertax_income: expanded_income minus combined\n \"\"\"\n if Business_tax_expinc is True:\n expanded_income = expanded_income + corp_taxliab\n else:\n expanded_income = expanded_income\n aftertax_income = expanded_income - combined\n return aftertax_income\n", "import multiprocessing\nfrom distributed import Client, LocalCluster\nimport pytest\nfrom pandas.util.testing import assert_frame_equal\nimport numpy as np\nimport os\nfrom ogusa.constants import CPS_START_YEAR, PUF_START_YEAR, TC_LAST_YEAR\nfrom ogusa import get_micro_data, utils\nfrom taxcalc import GrowFactors\nNUM_WORKERS = min(multiprocessing.cpu_count(), 7)\n# get path to puf if puf.csv in ogusa/ directory\nCUR_PATH = os.path.abspath(os.path.dirname(__file__))\nPUF_PATH = os.path.join(CUR_PATH, '..', 'puf.csv')\n\n\[email protected](scope=\"module\")\ndef dask_client():\n cluster = LocalCluster(n_workers=NUM_WORKERS, threads_per_worker=2)\n client = Client(cluster)\n yield client\n # teardown\n client.close()\n cluster.close()\n\n\ndef test_cps():\n \"\"\"\n Check that setting `data` to 'cps' uses cps data\n \"\"\"\n baseline = False\n start_year = 2016\n reform = {\"II_em\": {2017: 10000}}\n\n calc = get_micro_data.get_calculator(\n baseline, start_year, reform=reform,\n records_start_year=CPS_START_YEAR, data=\"cps\")\n # blind_head is only in the CPS file and e00700 is only in the PUF.\n # See taxcalc/records_variables.json\n assert (calc.array(\"blind_head\").sum() > 0 and\n calc.array(\"e00700\").sum() == 0)\n\n\ndef test_set_path():\n \"\"\"\n Check that 'notapath.csv' is passed to taxcalc. An error\n containing 'notapath.csv' is sufficient proof for this\n \"\"\"\n baseline = False\n start_year = 2016\n reform = {\"II_em\": {2017: 10000}}\n\n # In theory this path doesn't exist so there should be an IOError\n # But taxcalc checks if the path exists and if it doesn't, it tries\n # to read from an egg file. This raises a ValueError. At some point,\n # this could change. So I think it's best to catch both errors\n with pytest.raises((IOError, ValueError), match=\"notapath.csv\"):\n get_micro_data.get_calculator(\n baseline, start_year, reform=reform,\n records_start_year=CPS_START_YEAR, data=\"notapath.csv\")\n\n\ndef test_puf_path():\n \"\"\"\n Check that setting `data` to None uses the puf file\n \"\"\"\n baseline = False\n start_year = 2016\n reform = {\"II_em\": {2017: 10000}}\n\n # puf.csv in ogusa/\n if os.path.exists(PUF_PATH):\n calc = get_micro_data.get_calculator(\n baseline, start_year, reform=reform, data=PUF_PATH)\n # blind_head is only in the CPS file and e00700 is only in the\n # PUF. See taxcalc/records_variables.json\n assert (calc.array('blind_head').sum() == 0 and\n calc.array('e00700').sum() > 0)\n # we do not have puf.csv\n else:\n # make sure TC is looking for puf.csv\n with pytest.raises((IOError, ValueError), match=\"puf.csv\"):\n get_micro_data.get_calculator(\n baseline, start_year, reform=reform,\n records_start_year=CPS_START_YEAR, data=None)\n\n\niit_reform_1 = {\n 'II_rt1': {2017: 0.09},\n 'II_rt2': {2017: 0.135},\n 'II_rt3': {2017: 0.225},\n 'II_rt4': {2017: 0.252},\n 'II_rt5': {2017: 0.297},\n 'II_rt6': {2017: 0.315},\n 'II_rt7': {2017: 0.3564}\n }\n\n\[email protected](\n 'baseline,iit_reform',\n [(False, iit_reform_1), (False, {}), (True, iit_reform_1),\n (True, {})],\n ids=['Reform, Policy change given',\n 'Reform, No policy change given',\n 'Baseline, Policy change given',\n 'Baseline, No policy change given'])\ndef test_get_calculator_cps(baseline, iit_reform):\n calc = get_micro_data.get_calculator(\n baseline=baseline, calculator_start_year=2017,\n reform=iit_reform, data='cps', gfactors=GrowFactors(),\n records_start_year=CPS_START_YEAR)\n assert calc.current_year == CPS_START_YEAR\n\n\ndef test_get_calculator_exception():\n iit_reform = {\n 'II_rt1': {2017: 0.09},\n 'II_rt2': {2017: 0.135},\n 'II_rt3': {2017: 0.225},\n 'II_rt4': {2017: 0.252},\n 'II_rt5': {2017: 0.297},\n 'II_rt6': {2017: 0.315},\n 'II_rt7': {2017: 0.3564}\n }\n with pytest.raises(Exception):\n assert get_micro_data.get_calculator(\n baseline=False, calculator_start_year=TC_LAST_YEAR + 1,\n reform=iit_reform, data='cps', gfactors=GrowFactors(),\n records_start_year=CPS_START_YEAR)\n\n\[email protected]_run\ndef test_get_calculator_puf():\n iit_reform = {\n 'II_rt1': {2017: 0.09},\n 'II_rt2': {2017: 0.135},\n 'II_rt3': {2017: 0.225},\n 'II_rt4': {2017: 0.252},\n 'II_rt5': {2017: 0.297},\n 'II_rt6': {2017: 0.315},\n 'II_rt7': {2017: 0.3564}\n }\n calc = get_micro_data.get_calculator(\n baseline=False, calculator_start_year=2017, reform=iit_reform,\n data=None,\n records_start_year=PUF_START_YEAR)\n assert calc.current_year == 2013\n\n\[email protected]_run\ndef test_get_calculator_puf_from_file():\n iit_reform = {\n 'II_rt1': {2017: 0.09},\n 'II_rt2': {2017: 0.135},\n 'II_rt3': {2017: 0.225},\n 'II_rt4': {2017: 0.252},\n 'II_rt5': {2017: 0.297},\n 'II_rt6': {2017: 0.315},\n 'II_rt7': {2017: 0.3564}\n }\n calc = get_micro_data.get_calculator(\n baseline=False, calculator_start_year=2017, reform=iit_reform,\n data=PUF_PATH,\n records_start_year=PUF_START_YEAR)\n assert calc.current_year == 2013\n\n\[email protected](\n 'baseline', [True, False], ids=['Baseline', 'Reform'])\ndef test_get_data(baseline, dask_client):\n '''\n Test of get_micro_data.get_data() function\n '''\n expected_data = utils.safe_read_pickle(\n os.path.join(CUR_PATH, 'test_io_data',\n 'micro_data_dict_for_tests.pkl'))\n test_data, _ = get_micro_data.get_data(\n baseline=baseline, start_year=2029, reform={}, data='cps',\n client=dask_client, num_workers=NUM_WORKERS)\n for k, v in test_data.items():\n try:\n assert_frame_equal(\n expected_data[k], v)\n except KeyError:\n pass\n\n\ndef test_taxcalc_advance():\n '''\n Test of the get_micro_data.taxcalc_advance() function\n\n Note that this test may fail if the Tax-Calculator is not v 2.4.0\n In that case, you can use the pickeld calculator object, however\n this is too large for GitHub, so it won't be available there.\n '''\n expected_dict = utils.safe_read_pickle(os.path.join(\n CUR_PATH, 'test_io_data', 'tax_dict_for_tests.pkl'))\n test_dict = get_micro_data.taxcalc_advance(True, 2028, {}, 'cps', 2028)\n del test_dict['payroll_tax_liab']\n for k, v in test_dict.items():\n assert np.allclose(expected_dict[k], v, equal_nan=True)\n\n\[email protected]_run\ndef test_cap_inc_mtr():\n '''\n Test of the get_micro_data.cap_inc_mtr() function\n\n Note that this test may fail if the Tax-Calculator is not v 2.4.0\n In that case, you can use the pickeld caculator object, however\n this is too large for GitHub, so it won't be available there.\n '''\n # calc1 = utils.safe_read_pickle(os.path.join(\n # CUR_PATH, 'test_io_data', 'calc_object_for_tests.pkl'))\n calc1 = get_micro_data.get_calculator(\n baseline=True, calculator_start_year=2028, reform={},\n data='cps')\n calc1.advance_to_year(2028)\n expected = np.genfromtxt(os.path.join(\n CUR_PATH, 'test_io_data',\n 'mtr_combined_capinc_for_tests.csv'), delimiter=',')\n test_data = get_micro_data.cap_inc_mtr(calc1)\n\n assert np.allclose(expected, test_data, equal_nan=True)\n", "# CODING-STYLE CHECKS:\n# pycodestyle test_consumption.py\n\nimport numpy as np\nimport pytest\nimport copy\nfrom taxcalc import Policy, Records, Calculator, Consumption\n\n\ndef test_year_consistency():\n assert Consumption.JSON_START_YEAR == Policy.JSON_START_YEAR\n assert Consumption.DEFAULT_NUM_YEARS == Policy.DEFAULT_NUM_YEARS\n\n\ndef test_validity_of_consumption_vars_set():\n records_varinfo = Records(data=None)\n assert Consumption.RESPONSE_VARS.issubset(records_varinfo.USABLE_READ_VARS)\n useable_vars = set(['housing', 'snap', 'tanf', 'vet', 'wic',\n 'mcare', 'mcaid', 'other'])\n assert Consumption.BENEFIT_VARS.issubset(useable_vars)\n\n\ndef test_update_consumption():\n consump = Consumption()\n consump.update_consumption({})\n revision = {\n 'MPC_e20400': {2014: 0.05,\n 2015: 0.06},\n 'BEN_mcare_value': {2014: 0.75,\n 2015: 0.80}\n }\n consump.update_consumption(revision)\n expected_mpc_e20400 = np.full((Consumption.DEFAULT_NUM_YEARS,), 0.06)\n expected_mpc_e20400[0] = 0.0\n expected_mpc_e20400[1] = 0.05\n assert np.allclose(consump._MPC_e20400,\n expected_mpc_e20400,\n rtol=0.0)\n assert np.allclose(consump._MPC_e17500,\n np.zeros((Consumption.DEFAULT_NUM_YEARS,)),\n rtol=0.0)\n expected_ben_mcare_value = np.full((Consumption.DEFAULT_NUM_YEARS,), 0.80)\n expected_ben_mcare_value[0] = 1.0\n expected_ben_mcare_value[1] = 0.75\n assert np.allclose(consump._BEN_mcare_value,\n expected_ben_mcare_value,\n rtol=0.0)\n assert np.allclose(consump._BEN_snap_value,\n np.ones((Consumption.DEFAULT_NUM_YEARS,)),\n rtol=0.0)\n consump.set_year(2015)\n assert consump.current_year == 2015\n assert consump.MPC_e20400 == 0.06\n assert consump.MPC_e17500 == 0.0\n assert consump.BEN_mcare_value == 0.80\n assert consump.BEN_snap_value == 1.0\n\n\ndef test_incorrect_update_consumption():\n with pytest.raises(ValueError):\n Consumption().update_consumption([])\n with pytest.raises(ValueError):\n Consumption().update_consumption({'MPC_e17500': {'xyz': 0.2}})\n with pytest.raises(ValueError):\n Consumption().update_consumption({'MPC_e17500': {2012: 0.2}})\n with pytest.raises(ValueError):\n Consumption().update_consumption({'MPC_e17500': {2052: 0.2}})\n with pytest.raises(ValueError):\n Consumption().update_consumption({'MPC_exxxxx': {2014: 0.2}})\n with pytest.raises(ValueError):\n Consumption().update_consumption({'MPC_e17500': {2014: -0.1}})\n with pytest.raises(ValueError):\n Consumption().update_consumption({'MPC_e17500-indexed': {2014: 0.1}})\n\n\ndef test_future_update_consumption():\n consump = Consumption()\n assert consump.current_year == consump.start_year\n assert consump.has_response() is False\n cyr = 2020\n consump.set_year(cyr)\n consump.update_consumption({'MPC_e20400': {cyr: 0.01}})\n assert consump.current_year == cyr\n assert consump.has_response() is True\n consump.set_year(cyr - 1)\n assert consump.has_response() is False\n # test future updates for benefits\n consump_ben = Consumption()\n assert consump_ben.current_year == consump_ben.start_year\n assert consump_ben.has_response() is False\n consump_ben.set_year(cyr)\n consump_ben.update_consumption({'BEN_vet_value': {cyr: 0.95}})\n assert consump_ben.current_year == cyr\n assert consump_ben.has_response() is True\n consump_ben.set_year(cyr - 1)\n assert consump_ben.has_response() is False\n\n\ndef test_consumption_default_data():\n consump = Consumption()\n pdata = consump._vals\n for pname in pdata.keys():\n if pname.startswith('MPC'):\n assert pdata[pname]['value'] == [0.0]\n elif pname.startswith('BEN'):\n assert pdata[pname]['value'] == [1.0]\n\n\ndef test_consumption_response(cps_subsample):\n consump = Consumption()\n mpc = 0.5\n consumption_response = {'MPC_e20400': {2013: mpc}}\n consump.update_consumption(consumption_response)\n # test incorrect call to response method\n with pytest.raises(ValueError):\n consump.response(list(), 1)\n # test correct call to response method\n rec = Records.cps_constructor(data=cps_subsample)\n pre = copy.deepcopy(rec.e20400)\n consump.response(rec, 1.0)\n post = rec.e20400\n actual_diff = post - pre\n expected_diff = np.ones(rec.array_length) * mpc\n assert np.allclose(actual_diff, expected_diff)\n # compute earnings mtr with no consumption response\n rec = Records.cps_constructor(data=cps_subsample)\n ided0 = copy.deepcopy(rec.e20400)\n calc0 = Calculator(policy=Policy(), records=rec, consumption=None)\n (mtr0_ptax, mtr0_itax, _) = calc0.mtr(variable_str='e00200p',\n wrt_full_compensation=False)\n assert np.allclose(calc0.array('e20400'), ided0)\n # compute earnings mtr with consumption response\n calc1 = Calculator(policy=Policy(), records=rec, consumption=consump)\n mtr1_ptax, mtr1_itax, _ = calc1.mtr(variable_str='e00200p',\n wrt_full_compensation=False)\n assert np.allclose(calc1.array('e20400'), ided0)\n # confirm that payroll mtr values are no different\n assert np.allclose(mtr1_ptax, mtr0_ptax)\n # confirm that all mtr with cons-resp are no greater than without cons-resp\n assert np.all(np.less_equal(np.around(mtr1_itax, decimals=5),\n np.around(mtr0_itax, decimals=5)))\n # confirm that some mtr with cons-resp are less than without cons-resp\n assert np.any(np.less(mtr1_itax, mtr0_itax))\n" ]
[ [ "numpy.maximum", "numpy.zeros", "numpy.where" ], [ "pandas.util.testing.assert_frame_equal", "numpy.allclose" ], [ "numpy.allclose", "numpy.less", "numpy.around", "numpy.ones", "numpy.full", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
mpwiesner/sims_GCRCatSimInterface
[ "831e78ec8eb610983768d4657fbff9744cb17249" ]
[ "bin.src/generate_lensed_hosts_agn.py" ]
[ "import numpy as np\r\nimport os\r\nimport argparse\r\nimport pylab as pl\r\nimport subprocess as sp\r\nimport astropy.io.fits as pyfits\r\nimport pandas as pd\r\nimport scipy.special as ss\r\nimport om10_lensing_equations as ole\r\n\r\ndata_dir = os.path.join(os.environ['SIMS_GCRCATSIMINTERFACE_DIR'], 'data')\r\ntwinkles_data_dir = os.path.join(os.environ['TWINKLES_DIR'], 'data')\r\noutdefault = os.path.join(data_dir,'outputs')\r\n\r\nparser = argparse.ArgumentParser(description='The location of the desired output directory')\r\nparser.add_argument(\"--outdir\", dest='outdir1', type=str, default = outdefault,\r\n help='Output location for FITS stamps')\r\nargs = parser.parse_args()\r\noutdir = args.outdir1\r\n\r\ndef load_in_data_agn():\r\n\r\n \"\"\"\r\n Reads in catalogs of host galaxy bulge and disk as well as om10 lenses\r\n \"\"\"\r\n agn_host_bulge = pd.read_csv(os.path.join(data_dir,'agn_host_bulge.csv.gz'))\r\n agn_host_disk = pd.read_csv(os.path.join(data_dir, 'agn_host_disk.csv.gz'))\r\n\r\n idx = agn_host_bulge['image_number'] == 0\r\n ahb_purged = agn_host_bulge[:][idx]\r\n ahd_purged = agn_host_disk[:][idx]\r\n\r\n lens_list = pyfits.open(os.path.join(twinkles_data_dir,\r\n 'twinkles_lenses_v2.fits'))\r\n\r\n return lens_list, ahb_purged, ahd_purged\r\n\r\n\r\ndef create_cats_agns(index, hdu_list, ahb_list, ahd_list):\r\n \"\"\"\r\n Takes input catalogs and isolates lensing parameters as well as ra and dec of lens \r\n\r\n Parameters:\r\n -----------\r\n index: int\r\n Index for pandas data frame\r\n hdu_list:\r\n row of data frame that contains lens parameters\r\n ahb_list:\r\n row of data frame that contains lens galaxy parameters for the galactic bulge\r\n ahd_list:\r\n row of data frame that contains lens galaxy parameters for the galactic disk \"\"\"\r\n\r\n twinkles_ID = ahd['twinkles_system'][index]\r\n UID_lens = ahd['uniqueId_lens'][index]\r\n Ra_lens = ahd['raPhoSim_lens'][index]\r\n Dec_lens = ahd['decPhoSim_lens'][index]\r\n\r\n idx = hdu_list[1].data['twinklesId'] == twinkles_ID\r\n lid = hdu_list[1].data['LENSID'][idx][0]\r\n xl1 = 0.0\r\n xl2 = 0.0\r\n vd = hdu_list[1].data['VELDISP'][idx][0]\r\n zd = hdu_list[1].data['ZLENS'][idx][0]\r\n ql = 1.0 - hdu_list[1].data['ELLIP'][idx][0]\r\n phi= hdu_list[1].data['PHIE'][idx][0]\r\n\r\n ys1 = hdu_list[1].data['XSRC'][idx][0]\r\n ys2 = hdu_list[1].data['YSRC'][idx][0]\r\n\r\n ext_shr = hdu_list[1].data['GAMMA'][idx][0]\r\n ext_phi = hdu_list[1].data['PHIG'][idx][0]\r\n\r\n ximg = hdu_list[1].data['XIMG'][idx][0]\r\n yimg = hdu_list[1].data['YIMG'][idx][0]\r\n \r\n\r\n #----------------------------------------------------------------------------\r\n lens_cat = {'xl1' : xl1,\r\n 'xl2' : xl2,\r\n 'ql' : ql,\r\n 'vd' : vd,\r\n 'phl' : phi,\r\n 'gamma' : ext_shr,\r\n 'phg' : ext_phi,\r\n 'zl' : zd,\r\n 'ximg' : ximg,\r\n 'yimg' : yimg,\r\n 'twinklesid' : twinkles_ID,\r\n 'lensid' : lid,\r\n 'index' : index,\r\n 'UID_lens' : UID_lens,\r\n 'Ra_lens' : Ra_lens,\r\n 'Dec_lens' : Dec_lens}\r\n \r\n #----------------------------------------------------------------------------\r\n mag_src_b = ahb_list['phosimMagNorm'][index]\r\n qs_b = ahb_list['minorAxis'][index]/ahb_list['majorAxis'][index]\r\n Reff_src_b = np.sqrt(ahb_list['minorAxis'][index]*ahb_list['majorAxis'][index])\r\n phs_b = ahb_list['positionAngle'][index]\r\n ns_b = ahb_list['sindex'][index]\r\n zs_b = ahb_list['redshift'][index]\r\n sed_src_b = ahb_list['sedFilepath'][index]\r\n \r\n srcsP_bulge = {'ys1' : ys1,\r\n 'ys2' : ys2,\r\n 'mag_src' : mag_src_b,\r\n 'Reff_src' : Reff_src_b,\r\n 'qs' : qs_b,\r\n 'phs' : phs_b,\r\n 'ns' : ns_b,\r\n 'zs' : zs_b,\r\n 'sed_src' : sed_src_b, \r\n 'components' : 'bulge'}\r\n \r\n #----------------------------------------------------------------------------\r\n mag_src_d = ahd_list['phosimMagNorm'][index]\r\n qs_d = ahd_list['minorAxis'][index]/ahd_list['majorAxis'][index]\r\n Reff_src_d = np.sqrt(ahd_list['minorAxis'][index]*ahd_list['majorAxis'][index])\r\n phs_d = ahd_list['positionAngle'][index]\r\n ns_d = ahd_list['sindex'][index]\r\n zs_d = ahd_list['redshift'][index]\r\n sed_src_d = ahd_list['sedFilepath'][index]\r\n\r\n srcsP_disk = {'ys1' : ys1,\r\n 'ys2' : ys2,\r\n 'mag_src' : mag_src_d,\r\n 'Reff_src' : Reff_src_d,\r\n 'qs' : qs_d,\r\n 'phs' : phs_d,\r\n 'ns' : ns_d,\r\n 'zs' : zs_d,\r\n 'sed_src' : sed_src_d,\r\n 'components' : 'disk'}\r\n \r\n #----------------------------------------------------------------------------\r\n\r\n return lens_cat, srcsP_bulge, srcsP_disk\r\n\r\n\r\ndef lensed_sersic_2d(xi1, xi2, yi1, yi2, source_cat, lens_cat):\r\n #Defines a magnitude of lensed host galaxy using 2d Sersic profile\t\r\n #----------------------------------------------------------------------\r\n ysc1 = source_cat['ys1'] # x position of the source, arcseconds\r\n ysc2 = source_cat['ys2'] # y position of the source, arcseconds\r\n mag_tot = source_cat['mag_src'] # total magnitude of the source\r\n Reff_arc = source_cat['Reff_src'] # Effective Radius of the source, arcseconds\r\n qs = source_cat['qs'] # axis ratio of the source, b/a\r\n phs = source_cat['phs'] # orientation of the source, degree\r\n ns = source_cat['ns'] # index of the source\r\n\r\n #----------------------------------------------------------------------\r\n g_limage = ole.sersic_2d(yi1,yi2,ysc1,ysc2,Reff_arc,qs,phs,ns)\r\n g_source = ole.sersic_2d(xi1,xi2,ysc1,ysc2,Reff_arc,qs,phs,ns)\r\n\r\n mag_lensed = mag_tot - 2.5*np.log(np.sum(g_limage)/np.sum(g_source))\r\n\r\n return mag_lensed, g_limage\r\n\r\n\r\ndef generate_lensed_host(xi1, xi2, lens_P, srcP_b, srcP_d):\r\n \"\"\"Does ray tracing of light from host galaxies using\r\n a non-singular isothermal ellipsoid profile. \r\n Ultimately writes out a FITS image of the result of the ray tracing.\t\"\"\"\r\n dsx = 0.01\r\n xlc1 = lens_P['xl1'] # x position of the lens, arcseconds\r\n xlc2 = lens_P['xl2'] # y position of the lens, arcseconds\r\n rlc = 0.0 # core size of Non-singular Isothermal Ellipsoid\r\n vd = lens_P['vd'] # velocity dispersion of the lens\r\n zl = lens_P['zl'] # redshift of the lens\r\n zs = srcP_b['zs'] # redshift of the source\r\n rle = ole.re_sv(vd, zl, zs) # Einstein radius of lens, arcseconds.\r\n ql = lens_P['ql'] # axis ratio b/a\r\n le = ole.e2le(1.0 - ql) # scale factor due to projection of ellpsoid\r\n phl = lens_P['phl'] # position angle of the lens, degree\r\n eshr = lens_P['gamma'] # external shear\r\n eang = lens_P['phg'] # position angle of external shear\r\n ekpa = 0.0 # external convergence\r\n\r\n #----------------------------------------------------------------------\r\n ai1, ai2 = ole.alphas_sie(xlc1, xlc2, phl, ql, rle, le,\r\n eshr, eang, ekpa, xi1, xi2)\r\n\r\n yi1 = xi1 - ai1\r\n yi2 = xi2 - ai2\r\n #----------------------------------------------------------------------------\r\n\r\n lensed_mag_b, lensed_image_b = lensed_sersic_2d(xi1,xi2,yi1,yi2,srcP_b,lens_P)\r\n\r\n os.makedirs(os.path.join(outdir,'agn_lensed_bulges'), exist_ok=True)\r\n\r\n fits_limg_b = os.path.join(outdir,'agn_lensed_bulges/') + str(lens_P['UID_lens']) + \"_\" + str(lensed_mag_b) + \"_bulge.fits\" \r\n \r\n pyfits.writeto(fits_limg_b, lensed_image_b.astype(\"float32\"), overwrite=True)\r\n\r\n #----------------------------------------------------------------------------\r\n\r\n lensed_mag_d, lensed_image_d = lensed_sersic_2d(xi1,xi2,yi1,yi2,srcP_d,lens_P)\r\n\r\n os.makedirs(os.path.join(outdir,'agn_lensed_disks'), exist_ok=True)\r\n\r\n fits_limg_d = os.path.join(outdir,'agn_lensed_disks/') + str(lens_P['UID_lens']) + \"_\" + str(lensed_mag_d) + \"_disk.fits\"\r\n \r\n pyfits.writeto(fits_limg_d, lensed_image_d.astype(\"float32\"), overwrite=True)\r\n\r\n return 0\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n dsx = 0.01 # pixel size per side, arcseconds\r\n nnn = 1000 # number of pixels per side\r\n xi1, xi2 = ole.make_r_coor(nnn, dsx)\r\n\r\n hdulist, ahb, ahd = load_in_data_agn()\r\n\r\n message_row = 0\r\n message_freq = 50\r\n for i, row in ahb.iterrows():\r\n if i >= message_row:\r\n print (\"working on system \", i , \"of\", max(ahb.index))\r\n message_row += message_freq\r\n lensP, srcPb, srcPd = create_cats_agns(i, hdulist, ahb, ahd)\r\n generate_lensed_host(xi1, xi2, lensP, srcPb, srcPd) \r\n" ]
[ [ "numpy.sum", "numpy.sqrt" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
thomasgibson/tabula-rasa
[ "85abf26d6604b5a9a4d356f07aeb90d5b6453f33", "85abf26d6604b5a9a4d356f07aeb90d5b6453f33" ]
[ "verification/HMM/rtcf-h-table.py", "gravity_waves/profile_problem.py" ]
[ "import os\nimport sys\nimport pandas as pd\n\n\ndata_set = [\"results/H-RTCF-degree-0.csv\",\n \"results/H-RTCF-degree-1.csv\",\n \"results/H-RTCF-degree-2.csv\",\n \"results/H-RTCF-degree-3.csv\"]\n\nfor data in data_set:\n if not os.path.exists(data):\n print(\"Cannot find data file '%s'\" % data)\n sys.exit(1)\n\ntable = r\"\"\"\\resizebox{\\textwidth}{!}{%\n\\begin{tabular}{| l | c| c | c | c | c | c | c |}\n\\hline\n\\multicolumn{8}{|c|}{RTCF-H method} \\\\\n\\hline\n\\multirow{2}{*}{$k$} & mesh &\n\\multicolumn{2}{|c|}{$\\norm{p-p_h}_{L^2(\\Omega)} \\leq \\mathcal{O}(h^{k+1})$} &\n\\multicolumn{2}{|c|}{\n$\\norm{\\boldsymbol{u}-\\boldsymbol{u}_h}_{\\boldsymbol{L}^2(\\Omega)} \\leq \\mathcal{O}(h^{k+1})$} &\n\\multicolumn{2}{|c|}{$\\norm{p-p_h^{\\star}}_{L^2(\\Omega)} \\leq \\mathcal{O}(h^{k+2})$} \\\\\n\\cline{2-8}\n& $r$ & $L^2$-error & rate & $L^2$-error & rate & $L^2$-error & rate \\\\\n\"\"\"\n\nlformat = r\"\"\"& {mesh: d} & {ScalarErrors:.3e} & {ScalarRates} & {FluxErrors:.3e} & {FluxRates} & {PPScalarErrors:.3e} & {PPScalarRates} \\\\\n\"\"\"\n\n\ndef rate(s):\n if s == '---':\n return s\n else:\n return \"{s:.3f}\".format(s=float(s))\n\n\nfor data in data_set:\n df = pd.read_csv(data)\n df = df.sort_values(\"Mesh\")\n degree = df.Degree.values[0]\n table += r\"\"\"\n \\hline\n \\multirow{5}{*}{%d}\n \"\"\" % degree\n for k in df.Mesh:\n sliced = df.loc[lambda x: x.Mesh == k]\n table += lformat.format(mesh=k,\n ScalarErrors=sliced.ScalarErrors.values[0],\n ScalarRates=rate(sliced.ScalarConvRates.values[0]),\n FluxErrors=sliced.FluxErrors.values[0],\n FluxRates=rate(sliced.FluxConvRates.values[0]),\n PPScalarErrors=sliced.PostProcessedScalarErrors.values[0],\n PPScalarRates=rate(sliced.PostProcessedScalarRates.values[0]))\n\ntable += r\"\"\"\\hline\n\\end{tabular}}\n\"\"\"\nprint(table)\n", "from firedrake import *\nfrom firedrake.utils import cached_property\nfrom pyop2.profiling import timed_stage\nimport numpy as np\nfrom solver import GravityWaveSolver\n\n\ndef fmax(f):\n fmax = op2.Global(1, np.finfo(float).min, dtype=float)\n op2.par_loop(op2.Kernel(\"\"\"\nvoid maxify(double *a, double *b) {\n a[0] = a[0] < fabs(b[0]) ? fabs(b[0]) : a[0];\n}\n\"\"\", \"maxify\"), f.dof_dset.set, fmax(op2.MAX), f.dat(op2.READ))\n return fmax.data[0]\n\n\nclass ProfileGravityWaveSolver(object):\n\n def __init__(self, refinement_level, nlayers, model_degree,\n method=\"RTCF\", X=1.0,\n H=1E4, rtol=1.0E-5, hybridization=False, cfl=1,\n monitor=False):\n\n super(ProfileGravityWaveSolver, self).__init__()\n\n self.refinement_level = refinement_level\n self.nlayers = nlayers\n self.H = H\n self.model_degree = model_degree\n self.method = method\n self.hybridization = hybridization\n self.rtol = rtol\n self.monitor = monitor\n self._X = X\n self._R = 6.371E6 / self._X\n self.R = Constant(self._R)\n self._c = 343.0\n self._N = 0.01\n self._Omega = 7.292E-5\n self.Omega = Constant(self._Omega)\n\n self.mesh_degree = 1\n if self.method == \"RT\" or self.method == \"BDFM\":\n base = IcosahedralSphereMesh(self._R,\n refinement_level=self.refinement_level,\n degree=self.mesh_degree)\n elif self.method == \"RTCF\":\n base = CubedSphereMesh(self._R,\n refinement_level=self.refinement_level,\n degree=self.mesh_degree)\n else:\n raise ValueError(\"Unknown method %s\" % self.method)\n\n global_normal = as_vector(SpatialCoordinate(base))\n base.init_cell_orientations(global_normal)\n\n mesh = ExtrudedMesh(base, extrusion_type=\"radial\",\n layers=self.nlayers,\n layer_height=self.H / self.nlayers)\n self.mesh = mesh\n\n # Get Dx information (this is approximate).\n # We compute the area (m^2) of each cell in the mesh,\n # then take the square root to get the right units.\n cell_vs = interpolate(CellVolume(base),\n FunctionSpace(base, \"DG\", 0))\n\n a_max = fmax(cell_vs)\n dx_max = sqrt(a_max)\n self.dx_max = dx_max\n self.dz = self.H / self.nlayers\n self.courant = cfl\n Dt = self.courant * dx_max / self._c\n self.Dt = Dt\n self.dt = Constant(self.Dt)\n\n # Create tensor product complex:\n if self.method == \"RT\":\n U1 = FiniteElement('RT', triangle, self.model_degree)\n U2 = FiniteElement('DG', triangle, self.model_degree - 1)\n\n elif self.method == \"BDFM\":\n U1 = FiniteElement('BDFM', triangle, 2)\n U2 = FiniteElement('DG', triangle, 1)\n # BDFM only supported for degree 2, so overwrite here\n self.model_degree = 2\n else:\n assert self.method == \"RTCF\"\n U1 = FiniteElement('RTCF', quadrilateral, self.model_degree)\n U2 = FiniteElement('DQ', quadrilateral, self.model_degree - 1)\n\n V0 = FiniteElement('CG', interval, self.model_degree)\n V1 = FiniteElement('DG', interval, self.model_degree - 1)\n\n # HDiv element\n W2_ele_h = HDiv(TensorProductElement(U1, V1))\n W2_ele_v = HDiv(TensorProductElement(U2, V0))\n W2_ele = W2_ele_h + W2_ele_v\n\n # L2 element\n W3_ele = TensorProductElement(U2, V1)\n\n # Charney-Phillips element\n Wb_ele = TensorProductElement(U2, V0)\n\n # Resulting function spaces\n self.W2 = FunctionSpace(mesh, W2_ele)\n self.W3 = FunctionSpace(mesh, W3_ele)\n self.Wb = FunctionSpace(mesh, Wb_ele)\n\n self.Wup = self.W2 * self.W3\n self.Wupb = self.W2 * self.W3 * self.Wb\n\n # Functions for the state and residual\n self.state = Function(self.Wupb)\n self.state0 = Function(self.Wupb)\n\n x = SpatialCoordinate(mesh)\n fexpr = 2*self.Omega*x[2]/self.R\n self._fexpr = fexpr\n\n xnorm = sqrt(inner(x, x))\n self.khat = interpolate(x/xnorm, mesh.coordinates.function_space())\n\n self._build_initial_conditions()\n\n solver = GravityWaveSolver(W2=self.W2,\n W3=self.W3,\n Wb=self.Wb,\n dt=self.Dt,\n c=self._c,\n N=self._N,\n khat=self.khat,\n maxiter=1000,\n tolerance=self.rtol,\n coriolis=self._fexpr,\n hybridization=self.hybridization,\n monitor=self.monitor)\n\n self.gravity_wave_solver = solver\n self.ksp_inner_its = []\n self.ksp_outer_its = []\n self.hybrid_dofs_up = []\n self.hybrid_dofs_trace = []\n\n def _build_initial_conditions(self):\n\n W2 = self.W2\n W3 = self.W3\n Wb = self.Wb\n\n u0 = Function(W2)\n urand = Function(VectorFunctionSpace(self.mesh, \"CG\", 2))\n urand.dat.data[:] += np.random.randn(*urand.dat.data.shape)\n u0.project(urand)\n\n p0 = Function(W3)\n p0.dat.data[:] += np.random.randn(len(p0.dat.data))\n\n b0 = Function(Wb)\n b0.dat.data[:] += np.random.randn(len(b0.dat.data))\n\n self.u0 = u0\n self.p0 = p0\n self.b0 = b0\n\n @cached_property\n def num_cells(self):\n return self.mesh.cell_set.size\n\n @cached_property\n def comm(self):\n return self.mesh.comm\n\n def warmup(self):\n\n state = self.state\n\n un, pn, bn = state.split()\n un.assign(self.u0)\n pn.assign(self.p0)\n bn.assign(self.b0)\n\n with timed_stage(\"Warm up: Solver\"):\n un1, pn1, bn1 = self.gravity_wave_solver.solve(un, pn, bn)\n\n def run_profile(self):\n\n state = self.state\n\n un, pn, bn = state.split()\n un.assign(self.u0)\n pn.assign(self.p0)\n bn.assign(self.b0)\n\n self.gravity_wave_solver._up_solver.snes.setConvergenceHistory()\n self.gravity_wave_solver._up_solver.snes.ksp.setConvergenceHistory()\n self.gravity_wave_solver._b_solver.snes.setConvergenceHistory()\n self.gravity_wave_solver._b_solver.snes.ksp.setConvergenceHistory()\n\n un1, pn1, bn1 = self.gravity_wave_solver.solve(un, pn, bn)\n\n outer_ksp = self.gravity_wave_solver._up_solver.snes.ksp\n if self.hybridization:\n ctx = outer_ksp.getPC().getPythonContext()\n inner_ksp = ctx.trace_ksp\n broken_solution = ctx.broken_solution\n trace_solution = ctx.trace_solution\n self.hybrid_dofs_up.append(broken_solution.dof_dset.layout_vec.getSize())\n self.hybrid_dofs_trace.append(trace_solution.dof_dset.layout_vec.getSize())\n else:\n ksps = outer_ksp.getPC().getFieldSplitSubKSP()\n _, inner_ksp = ksps\n\n # Collect ksp iterations\n self.ksp_outer_its.append(outer_ksp.getIterationNumber())\n self.ksp_inner_its.append(inner_ksp.getIterationNumber())\n" ]
[ [ "pandas.read_csv" ], [ "numpy.random.randn", "numpy.finfo" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
morteham/thermopack
[ "67deaf74a2ae974e880be25026738cc32e3a6c1e" ]
[ "addon/pycThermopack/pyctp/thermo.py" ]
[ "# Support for python2\nfrom __future__ import print_function\n\nimport sys\nfrom ctypes import *\nfrom os import path\nimport numpy as np\nfrom . import plotutils, utils, platform_specifics\n\nif utils.gcc_major_version_greater_than(7):\n c_len_type = c_size_t # c_size_t on GCC > 7\nelse:\n c_len_type = c_int\n\n\nclass thermopack(object):\n \"\"\"\n Interface to thermopack\n \"\"\"\n def __init__(self):\n \"\"\"\n Load libthermopack.(so/dll) and initialize function pointers\n \"\"\"\n pf_specifics = platform_specifics.get_platform_specifics()\n self.prefix = pf_specifics[\"prefix\"]\n self.module = pf_specifics[\"module\"]\n self.postfix = pf_specifics[\"postfix\"]\n self.postfix_nm = pf_specifics[\"postfix_no_module\"]\n dyn_lib_path = path.join(path.dirname(__file__), pf_specifics[\"dyn_lib\"])\n self.tp = cdll.LoadLibrary(dyn_lib_path)\n\n # Set phase flags\n self.s_get_phase_flags = self.tp.get_phase_flags_c\n self.get_phase_flags()\n\n # Model control\n self.s_add_eos = getattr(self.tp, self.get_export_name(\"thermopack_var\", \"add_eos\"))\n self.s_delete_eos = getattr(self.tp, self.get_export_name(\"thermopack_var\", \"delete_eos\"))\n self.s_activate_model = getattr(self.tp, self.get_export_name(\"thermopack_var\", \"activate_model\"))\n\n # Information\n self.s_get_model_id = getattr(self.tp, self.get_export_name(\"thermopack_var\", \"get_eos_identification\"))\n\n # Init methods\n self.eoslibinit_init_thermo = getattr(self.tp, self.get_export_name(\"eoslibinit\", \"init_thermo\"))\n self.Rgas = c_double.in_dll(self.tp, self.get_export_name(\"thermopack_constants\", \"rgas\")).value\n self.nc = None\n self.minimum_temperature_c = c_double.in_dll(self.tp, self.get_export_name(\"thermopack_constants\", \"tptmin\"))\n self.minimum_pressure_c = c_double.in_dll(self.tp, self.get_export_name(\"thermopack_constants\", \"tppmin\"))\n self.solideos_solid_init = getattr(self.tp, self.get_export_name(\"solideos\", \"solid_init\"))\n self.eoslibinit_init_volume_translation = getattr(self.tp, self.get_export_name(\"eoslibinit\", \"init_volume_translation\"))\n self.eoslibinit_redefine_critical_parameters = getattr(self.tp, self.get_export_name(\"eoslibinit\", \"redefine_critical_parameters\"))\n\n # Eos interface\n self.s_eos_specificvolume = getattr(self.tp, self.get_export_name(\"eos\", \"specificvolume\"))\n self.s_eos_zfac = getattr(self.tp, self.get_export_name(\"eos\", \"zfac\"))\n self.s_eos_thermo = getattr(self.tp, self.get_export_name(\"eos\", \"thermo\"))\n self.s_eos_entropy = getattr(self.tp, self.get_export_name(\"eos\", \"entropy\"))\n self.s_eos_enthalpy = getattr(self.tp, self.get_export_name(\"eos\", \"enthalpy\"))\n self.s_eos_compmoleweight = getattr(self.tp, self.get_export_name(\"eos\", \"compmoleweight\"))\n self.s_eos_idealenthalpysingle = getattr(self.tp, self.get_export_name(\"eos\", \"idealenthalpysingle\"))\n\n # Speed of sound\n #self.sos_singlePhaseSpeedOfSound = getattr(self.tp, '__speed_of_sound_MOD_singlephasespeedofsound')\n self.s_sos_sound_velocity_2ph = getattr(self.tp, self.get_export_name(\"speed_of_sound\", \"sound_velocity_2ph\"))\n\n # Component info\n self.s_compdata_compindex = getattr(self.tp, self.get_export_name(\"compdata\", \"comp_index_active\"))\n self.s_compdata_compname = getattr(self.tp, self.get_export_name(\"compdata\", \"comp_name_active\"))\n\n # Flashes\n self.s_set_ph_tolerance = getattr(self.tp, self.get_export_name(\"ph_solver\", \"setphtolerance\"))\n self.s_twophasetpflash = getattr(self.tp, self.get_export_name(\"tp_solver\", \"twophasetpflash\"))\n self.s_psflash_twophase = getattr(self.tp, self.get_export_name(\"ps_solver\", \"twophasepsflash\"))\n #self.tpflash_multiphase = getattr(self.tp, '__mp_tp_solver_MOD_mp_flash_tp')\n self.s_uvflash_twophase = getattr(self.tp, self.get_export_name(\"uv_solver\", \"twophaseuvflash\"))\n self.s_phflash_twophase = getattr(self.tp, self.get_export_name(\"ph_solver\", \"twophasephflash\"))\n #self.s_svflash_twophase = getattr(self.tp, self.get_export_name(\"sv_solver\", \"twophasesvflash\"))\n self.s_guess_phase = getattr(self.tp, self.get_export_name(\"thermo_utils\", \"guessphase\"))\n\n # TV interfaces\n self.s_internal_energy_tv = getattr(self.tp, self.get_export_name(\"eostv\", \"internal_energy\"))\n self.s_entropy_tv = getattr(self.tp, self.get_export_name(\"eostv\", \"entropytv\"))\n self.s_pressure_tv = getattr(self.tp, self.get_export_name(\"eostv\", \"pressure\"))\n self.s_lnphi_tv = getattr(self.tp, self.get_export_name(\"eostv\", \"thermotv\"))\n self.s_enthalpy_tv = getattr(self.tp, self.get_export_name(\"eostv\", \"enthalpytv\"))\n self.s_helmholtz_energy = getattr(self.tp, self.get_export_name(\"eostv\", \"free_energy\"))\n self.s_chempot = getattr(self.tp, self.get_export_name(\"eostv\", \"chemical_potential\"))\n\n # Saturation properties\n self.s_bubble_t = getattr(self.tp, self.get_export_name(\"saturation\", \"safe_bubt\"))\n self.s_bubble_p = getattr(self.tp, self.get_export_name(\"saturation\", \"safe_bubp\"))\n self.s_dew_t = getattr(self.tp, self.get_export_name(\"saturation\", \"safe_dewt\"))\n self.s_dew_p = getattr(self.tp, self.get_export_name(\"saturation\", \"safe_dewp\"))\n self.s_envelope_plot = getattr(self.tp, self.get_export_name(\"saturation_curve\", \"envelopeplot\"))\n self.s_binary_plot = getattr(self.tp, self.get_export_name(\"binaryplot\", \"vllebinaryxy\"))\n self.s_global_binary_plot = getattr(self.tp, self.get_export_name(\"binaryplot\", \"global_binary_plot\"))\n self.s_get_bp_term = getattr(self.tp, self.get_export_name(\"binaryplot\", \"get_bp_term\"))\n self.s_solid_envelope_plot = getattr(self.tp, self.get_export_name(\"solid_saturation\", \"solidenvelopeplot\"))\n self.s_isotherm = getattr(self.tp, self.get_export_name(\"isolines\", \"isotherm\"))\n self.s_isobar = getattr(self.tp, self.get_export_name(\"isolines\", \"isobar\"))\n self.s_isenthalp = getattr(self.tp, self.get_export_name(\"isolines\", \"isenthalp\"))\n self.s_isentrope = getattr(self.tp, self.get_export_name(\"isolines\", \"isentrope\"))\n # Stability\n self.s_crit_tv = getattr(self.tp, self.get_export_name(\"critical\", \"calccriticaltv\"))\n\n # Virials\n self.s_virial_coeffcients = getattr(self.tp, self.get_export_name(\"eostv\", \"virial_coefficients\"))\n self.s_second_virial_matrix = getattr(self.tp, self.get_export_name(\"eostv\", \"secondvirialcoeffmatrix\"))\n self.s_binary_third_virial_matrix = getattr(self.tp, self.get_export_name(\"eostv\", \"binarythirdvirialcoeffmatrix\"))\n\n self.add_eos()\n\n def __del__(self):\n \"\"\"Delete FORTRAN memory allocated for this instance\"\"\"\n self.delete_eos()\n\n def activate(self):\n \"\"\"Activate this instance of thermopack parameters for calculation\"\"\"\n self.s_activate_model.argtypes = [POINTER( c_int )]\n self.s_activate_model.restype = None\n self.s_activate_model(self.model_index_c)\n\n def add_eos(self):\n \"\"\"Allocate FORTRAN memory for this class instance\"\"\"\n self.s_add_eos.argtypes = None\n self.s_add_eos.restype = c_int\n self.model_index_c = c_int(self.s_add_eos())\n\n def delete_eos(self):\n \"\"\"de-allocate FORTRAN memory for this class instance\"\"\"\n self.activate()\n self.s_delete_eos.argtypes = [POINTER( c_int )]\n self.s_delete_eos.restype = None\n self.s_delete_eos(self.model_index_c)\n\n def get_model_id(self):\n \"\"\"Get model identification\n\n Returns:\n str: Eos name\n \"\"\"\n self.activate()\n\n eosid_len = 40\n eosid_c = c_char_p(b\" \" * eosid_len)\n eosid_len_c = c_len_type(eosid_len)\n self.s_get_model_id.argtypes = [c_char_p, c_len_type]\n self.s_get_model_id.restype = None\n self.s_get_model_id(eosid_c, eosid_len_c)\n\n eosid = eosid_c.value.decode('ascii').strip()\n return eosid\n\n def get_export_name(self, module, method):\n \"\"\"Generate library export name based on module and method name\n\n Args:\n module (str): Name of module\n method (str): Name of method\n\n Returns:\n str: Library export name\n \"\"\"\n if len(module) > 0:\n export_name = self.prefix + module + self.module + method + self.postfix\n else:\n export_name = method + self.postfix_nm\n return export_name\n\n #################################\n # Init\n #################################\n\n def init_thermo(self, eos, mixing, alpha, comps, nphases,\n liq_vap_discr_method=None, csp_eos=None, csp_ref_comp=None,\n kij_ref=\"Default\", alpha_ref=\"Default\", saft_ref=\"Default\",\n b_exponent=None, TrendEosForCp=None, cptype=None,\n silent=None):\n \"\"\"Initialize thermopack\n\n Args:\n eos (str): Equation of state\n mixing (str): Mixture model for cubic eos\n alpha (str): Alpha formulations for cubic EOS\n comps (string): Comma separated list of components\n nphases (int): Maximum number of phases considered during multi-phase flash calculations\n liq_vap_discr_method (int, optional): Method to discriminate between liquid and vapor in case of an undefined single phase. Defaults to None.\n csp_eos (str, optional): Corrensponding state equation. Defaults to None.\n csp_ref_comp (str, optional): CSP reference component. Defaults to None.\n kij_ref (str, optional): Data set identifiers. Defaults to \"Default\".\n alpha_ref (str, optional): Data set identifiers. Defaults to \"Default\".\n saft_ref (str, optional): Data set identifiers. Defaults to \"Default\".\n b_exponent (float, optional): Exponent used in co-volume mixing. Defaults to None.\n TrendEosForCp (str, optional): Option to init trend for ideal gas properties. Defaults to None.\n cptype (int array, optional): Equation type number for Cp. Defaults to None.\n silent (bool, optional): Supress messages during init?. Defaults to None.\n \"\"\"\n self.activate()\n self.nc = max(len(comps.split(\" \")), len(comps.split(\",\")))\n\n null_pointer = POINTER(c_int)()\n eos_c = c_char_p(eos.encode('ascii'))\n eos_len = c_len_type(len(eos))\n mixing_c = c_char_p(mixing.encode('ascii'))\n mixing_len = c_len_type(len(mixing))\n alpha_c = c_char_p(alpha.encode('ascii'))\n alpha_len = c_len_type(len(alpha))\n comp_string_c = c_char_p(comps.encode('ascii'))\n comp_string_len = c_len_type(len(comps))\n nphases_c = c_int(nphases)\n if liq_vap_discr_method is None:\n liq_vap_discr_method_c = null_pointer\n else:\n liq_vap_discr_method_c = POINTER(c_int)(c_int(liq_vap_discr_method))\n if csp_eos is None:\n csp_eos_c = c_char_p()\n csp_eos_len = c_len_type(0)\n else:\n csp_eos_c = c_char_p(csp_eos.encode('ascii'))\n csp_eos_len = c_len_type(len(csp_eos))\n if csp_ref_comp is None:\n csp_ref_comp_c = c_char_p()\n csp_ref_comp_len = c_len_type(0)\n else:\n csp_ref_comp_c = c_char_p(csp_ref_comp.encode('ascii'))\n csp_ref_comp_len = c_len_type(len(csp_ref_comp))\n kij_ref_len = c_len_type(len(kij_ref))\n kij_ref_c = c_char_p(kij_ref.encode('ascii'))\n alpha_ref_len = c_len_type(len(alpha_ref))\n alpha_ref_c = c_char_p(alpha_ref.encode('ascii'))\n saft_ref_len = c_len_type(len(saft_ref))\n saft_ref_c = c_char_p(saft_ref.encode('ascii'))\n if b_exponent is None:\n b_exponent_c = POINTER(c_double)()\n else:\n b_exponent_c = POINTER(c_double)(c_double(b_exponent))\n if TrendEosForCp is None:\n TrendEosForCp_c = c_char_p()\n TrendEosForCp_len = c_len_type(0)\n else:\n TrendEosForCp_c = c_char_p(TrendEosForCp.encode('ascii'))\n TrendEosForCp_len = c_len_type(len(TrendEosForCp))\n if cptype is None:\n cptype_c = null_pointer\n else:\n cptype_c = (c_int * self.nc)(*cptype)\n\n if silent is None:\n silent_c = null_pointer\n else:\n if silent:\n silent_int = 1\n else:\n silent_int = 0\n silent_c = POINTER(c_int)(c_int(silent_int))\n\n self.eoslibinit_init_thermo.argtypes = [c_char_p,\n c_char_p,\n c_char_p,\n c_char_p,\n POINTER( c_int ),\n POINTER( c_int ),\n c_char_p,\n c_char_p,\n c_char_p,\n c_char_p,\n c_char_p,\n POINTER( c_double ),\n c_char_p,\n POINTER( c_int ),\n POINTER( c_int ),\n c_len_type, c_len_type,\n c_len_type, c_len_type,\n c_len_type, c_len_type,\n c_len_type, c_len_type,\n c_len_type, c_len_type]\n\n\n self.eoslibinit_init_thermo.restype = None\n\n self.eoslibinit_init_thermo(eos_c,\n mixing_c,\n alpha_c,\n comp_string_c,\n byref(nphases_c),\n liq_vap_discr_method_c,\n csp_eos_c,\n csp_ref_comp_c,\n kij_ref_c,\n alpha_ref_c,\n saft_ref_c,\n b_exponent_c,\n TrendEosForCp_c,\n cptype_c,\n silent_c,\n eos_len,\n mixing_len,\n alpha_len,\n comp_string_len,\n csp_eos_len,\n csp_ref_comp_len,\n kij_ref_len,\n alpha_ref_len,\n saft_ref_len,\n TrendEosForCp_len)\n\n def init_peneloux_volume_translation(self, parameter_reference=\"Default\"):\n \"\"\"Initialialize Peneloux volume translations\n\n Args:\n parameter_reference (str): String defining parameter set, Defaults to \"Default\"\n \"\"\"\n self.activate()\n volume_trans_model = \"PENELOUX\"\n volume_trans_model_c = c_char_p(volume_trans_model.encode('ascii'))\n volume_trans_model_len = c_len_type(len(volume_trans_model))\n ref_string_c = c_char_p(parameter_reference.encode('ascii'))\n ref_string_len = c_len_type(len(parameter_reference))\n self.eoslibinit_init_volume_translation.argtypes = [c_char_p,\n c_char_p,\n c_len_type,\n c_len_type]\n\n self.eoslibinit_init_volume_translation.restype = None\n\n self.eoslibinit_init_volume_translation(volume_trans_model_c,\n ref_string_c,\n volume_trans_model_len,\n ref_string_len)\n\n def redefine_critical_parameters(self, silent=True):\n \"\"\"Recalculate critical properties of pure fluids\n\n Args:\n silent (bool): Ignore warnings? Defaults to True\n \"\"\"\n self.activate()\n if silent:\n silent_c = c_int(1)\n else:\n silent_c = c_int(0)\n\n self.eoslibinit_redefine_critical_parameters.argtypes = [ POINTER( c_int ) ]\n\n self.eoslibinit_redefine_critical_parameters.restype = None\n\n self.eoslibinit_redefine_critical_parameters(byref(silent_c))\n\n\n #################################\n # Solids\n #################################\n\n def init_solid(self, scomp):\n \"\"\"Initialize pure solid\n\n Args:\n scomp (str): Component name\n \"\"\"\n self.activate()\n scomp_c = c_char_p(scomp.encode('ascii'))\n scomp_len = c_len_type(len(scomp))\n self.solideos_solid_init.argtypes = [c_char_p, c_len_type]\n self.solideos_solid_init.restype = None\n self.solideos_solid_init(scomp_c, scomp_len)\n\n #################################\n # Utility\n #################################\n\n def getcompindex(self, comp):\n \"\"\"Get component index\n\n Args:\n comp (str): Component name\n\n Returns:\n int: Component FORTRAN index\n \"\"\"\n self.activate()\n comp_c = c_char_p(comp.encode('ascii'))\n comp_len = c_len_type(len(comp))\n self.s_compdata_compindex.argtypes = [c_char_p, c_len_type]\n self.s_compdata_compindex.restype = c_int\n idx = self.s_compdata_compindex(comp_c, comp_len)\n return idx\n\n def get_comp_name(self, index):\n \"\"\"Get component name\n\n Args:\n int: Component FORTRAN index\n\n Returns:\n comp (str): Component name\n \"\"\"\n self.activate()\n comp_len = 40\n comp_c = c_char_p(b\" \" * comp_len)\n comp_len_c = c_len_type(comp_len)\n index_c = c_int(index)\n self.s_compdata_compname.argtypes = [POINTER(c_int), c_char_p, c_len_type]\n self.s_compdata_compname.restype = None\n self.s_compdata_compname(byref(index_c), comp_c, comp_len_c)\n compname = comp_c.value.decode('ascii').strip()\n return compname\n\n def compmoleweight(self, comp):\n \"\"\"Get component mole weight (g/mol)\n\n Args:\n comp (int): Component FORTRAN index\n\n Returns:\n float: Component mole weight (g/mol)\n \"\"\"\n self.activate()\n comp_c = c_int(comp)\n self.s_eos_compmoleweight.argtypes = [POINTER( c_int )]\n self.s_eos_compmoleweight.restype = c_double\n mw_i = self.s_eos_compmoleweight(byref(comp_c))\n return mw_i\n\n def get_phase_flags(self):\n \"\"\"Get phase identifiers used by thermopack\n\n Returns:\n int: Phase int identifiers\n \"\"\"\n iTWOPH = c_int()\n iLIQPH = c_int()\n iVAPPH = c_int()\n iMINGIBBSPH = c_int()\n iSINGLEPH = c_int()\n iSOLIDPH = c_int()\n iFAKEPH = c_int()\n\n self.s_get_phase_flags.argtypes = [POINTER( c_int ),\n POINTER( c_int ),\n POINTER( c_int ),\n POINTER( c_int ),\n POINTER( c_int ),\n POINTER( c_int ),\n POINTER( c_int )]\n self.s_get_phase_flags.restype = None\n self.s_get_phase_flags(byref(iTWOPH),\n byref(iLIQPH),\n byref(iVAPPH),\n byref(iMINGIBBSPH),\n byref(iSINGLEPH),\n byref(iSOLIDPH),\n byref(iFAKEPH))\n self.TWOPH = iTWOPH.value\n self.LIQPH = iLIQPH.value\n self.VAPPH = iVAPPH.value\n self.MINGIBBSPH = iMINGIBBSPH.value\n self.SINGLEPH = iSINGLEPH.value\n self.SOLIDPH = iSOLIDPH.value\n self.FAKEPH = iFAKEPH.value\n\n def get_phase_type(self, i_phase):\n \"\"\"Get phase type\n\n Args:\n i_phase (int): Phase flag returned by thermopack\n\n Returns:\n str: Phase type\n \"\"\"\n phase_string_list = [\"TWO_PHASE\", \"LIQUID\", \"VAPOR\", \"MINIMUM_GIBBS\", \"SINGLE\", \"SOLID\", \"FAKE\"]\n return phase_string_list[i_phase]\n\n def set_tmin(self, temp):\n \"\"\"Set minimum temperature in Thermopack. Used to limit search\n domain for numerical solvers.\n\n Args:\n temp (float): Temperature (K)\n \"\"\"\n self.minimum_temperature_c.value = temp\n\n def get_tmin(self):\n \"\"\"Get minimum temperature in Thermopack. Used to limit search\n domain for numerical solvers.\n\n Returns:\n float: Temperature (K)\n \"\"\"\n temp = self.minimum_temperature_c.value\n return temp\n\n def set_pmin(self, press):\n \"\"\"Get minimum pressure in Thermopack. Used to limit search\n domain for numerical solvers.\n\n Args:\n press (float): Pressure (Pa)\n \"\"\"\n self.minimum_pressure_c.value = press\n\n #################################\n # Phase properties\n #################################\n\n def specific_volume(self, temp, press, x, phase, dvdt=None, dvdp=None, dvdn=None):\n \"\"\" Calculate single-phase specific volume\n Note that the order of the output match the default order of input for the differentials.\n Note further that dvdt, dvdp and dvdn only are flags to enable calculation.\n\n Args:\n temp (float): Temperature (K)\n press (float): Pressure (Pa)\n x (array_like): Molar composition\n phase (int): Calcualte root for specified phase\n dvdt (logical, optional): Calculate volume differentials with respect to temperature while pressure and composition are held constant. Defaults to None.\n dvdp (logical, optional): Calculate volume differentials with respect to pressure while temperature and composition are held constant. Defaults to None.\n dvdn (logical, optional): Calculate volume differentials with respect to mol numbers while pressure and temperature are held constant. Defaults to None.\n\n Returns:\n float: Specific volume (m3/mol), and optionally differentials\n \"\"\"\n self.activate()\n null_pointer = POINTER(c_double)()\n\n temp_c = c_double(temp)\n press_c = c_double(press)\n x_c = (c_double * len(x))(*x)\n phase_c = c_int(phase)\n v_c = c_double(0.0)\n\n if dvdt is None:\n dvdt_c = null_pointer\n else:\n dvdt_c = POINTER(c_double)(c_double(0.0))\n if dvdp is None:\n dvdp_c = null_pointer\n else:\n dvdp_c = POINTER(c_double)(c_double(0.0))\n if dvdn is None:\n dvdn_c = null_pointer\n else:\n dvdn_c = (c_double * len(x))(0.0)\n\n self.s_eos_specificvolume.argtypes = [POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_int ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double )]\n\n self.s_eos_specificvolume.restype = None\n\n self.s_eos_specificvolume(byref(temp_c),\n byref(press_c),\n x_c,\n byref(phase_c),\n byref(v_c),\n dvdt_c,\n dvdp_c,\n dvdn_c)\n return_tuple = (v_c.value, )\n if not dvdt is None:\n return_tuple += (dvdt_c[0], )\n if not dvdp is None:\n return_tuple += (dvdp_c[0], )\n if not dvdn is None:\n return_tuple += (np.array(dvdn_c), )\n\n return return_tuple\n\n def zfac(self,temp,press,x,phase,dzdt=None,dzdp=None,dzdn=None):\n \"\"\" Calculate single-phase compressibility\n Note that the order of the output match the default order of input for the differentials.\n Note further that dzdt, dzdp and dzdn only are flags to enable calculation.\n\n Args:\n temp (float): Temperature (K)\n press (float): Pressure (Pa)\n x (array_like): Molar composition\n phase (int): Calcualte root for specified phase\n dzdt (logical, optional): Calculate compressibility differentials with respect to temperature while pressure and composition are held constant. Defaults to None.\n dzdp (logical, optional): Calculate compressibility differentials with respect to pressure while temperature and composition are held constant. Defaults to None.\n dzdn (logical, optional): Calculate compressibility differentials with respect to mol numbers while pressure and temperature are held constant. Defaults to None.\n\n Returns:\n float: Compressibility (-), and optionally differentials\n \"\"\"\n self.activate()\n null_pointer = POINTER(c_double)()\n\n temp_c = c_double(temp)\n press_c = c_double(press)\n x_c = (c_double * len(x))(*x)\n phase_c = c_int(phase)\n z_c = c_double(0.0)\n\n if dzdt is None:\n dzdt_c = null_pointer\n else:\n dzdt_c = POINTER(c_double)(c_double(0.0))\n if dzdp is None:\n dzdp_c = null_pointer\n else:\n dzdp_c = POINTER(c_double)(c_double(0.0))\n if dzdn is None:\n dzdn_c = null_pointer\n else:\n dzdn_c = (c_double * len(x))(0.0)\n\n self.s_eos_zfac.argtypes = [POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_int ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double )]\n\n self.s_eos_zfac.restype = None\n\n self.s_eos_zfac(byref(temp_c),\n byref(press_c),\n x_c,\n byref(phase_c),\n byref(z_c),\n dzdt_c,\n dzdp_c,\n dzdn_c)\n return_tuple = (z_c.value, )\n if not dzdt is None:\n return_tuple += (dzdt_c[0], )\n if not dzdp is None:\n return_tuple += (dzdp_c[0], )\n if not dzdn is None:\n return_tuple += (np.array(dzdn_c), )\n\n return return_tuple\n\n def thermo(self,temp,press,x,phase,dlnfugdt=None,dlnfugdp=None,\n dlnfugdn=None,ophase=None,v=None):\n \"\"\" Calculate logarithm of fugacity coefficient given composition,\n temperature and pressure.\n Note that the order of the output match the default order of input for the differentials.\n Note further that dlnfugdt, dlnfugdp, dlnfugdn and ophase only are flags to enable calculation.\n\n Args:\n temp (float): Temperature (K)\n press (float): Pressure (Pa)\n x (array_like): Molar composition (.)\n phase (int): Calcualte root for specified phase\n dlnfugdt (logical, optional): Calculate fugacity coefficient differentials with respect to temperature while pressure and composition are held constant. Defaults to None.\n dlnfugdp (logical, optional): Calculate fugacity coefficient differentials with respect to pressure while temperature and composition are held constant. Defaults to None.\n dlnfugdn (logical, optional): Calculate fugacity coefficient differentials with respect to mol numbers while pressure and temperature are held constant. Defaults to None.\n ophase (int, optional): Phase flag. Only set when phase=MINGIBBSPH.\n v (float, optional): Specific volume (m3/mol)\n Returns:\n ndarray: fugacity coefficient (-), and optionally differentials\n \"\"\"\n self.activate()\n null_pointer = POINTER(c_double)()\n temp_c = c_double(temp)\n press_c = c_double(press)\n x_c = (c_double * len(x))(*x)\n phase_c = c_int(phase)\n lnfug_c = (c_double * len(x))(0.0)\n\n if dlnfugdt is None:\n dlnfugdt_c = null_pointer\n else:\n dlnfugdt_c = (c_double * len(x))(0.0)\n if dlnfugdp is None:\n dlnfugdp_c = null_pointer\n else:\n dlnfugdp_c = (c_double * len(x))(0.0)\n if dlnfugdn is None:\n dlnfugdn_c = null_pointer\n else:\n dlnfugdn_c = (c_double * len(x)**2)(0.0)\n if ophase is None:\n ophase_c = POINTER(c_int)()\n else:\n ophase_c = POINTER(c_int)(c_int(0))\n metaExtremum_c = POINTER(c_int)()\n\n if v is None:\n v_c = null_pointer\n else:\n v_c = POINTER(c_double)(c_double(0.0))\n\n self.s_eos_thermo.argtypes = [POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_int ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_int ),\n POINTER( c_int ),\n POINTER( c_double )]\n\n self.s_eos_thermo.restype = None\n\n self.s_eos_thermo(byref(temp_c),\n byref(press_c),\n x_c,\n byref(phase_c),\n lnfug_c,\n dlnfugdt_c,\n dlnfugdp_c,\n dlnfugdn_c,\n ophase_c,\n metaExtremum_c,\n v_c)\n\n return_tuple = (np.array(lnfug_c), )\n if not dlnfugdt is None:\n return_tuple += (np.array(dlnfugdt_c), )\n if not dlnfugdp is None:\n return_tuple += (np.array(dlnfugdp_c), )\n if not dlnfugdn is None:\n dlnfugdn_r = np.zeros((len(x),len(x)))\n for i in range(len(x)):\n for j in range(len(x)):\n dlnfugdn_r[i][j] = dlnfugdn_c[i+j*len(x)]\n return_tuple += (dlnfugdn_r, )\n if not ophase is None:\n return_tuple += (ophase_c[0], )\n if not v is None:\n return_tuple += (v_c[0], )\n\n return return_tuple\n\n def enthalpy(self,temp,press,x,phase,dhdt=None,dhdp=None,dhdn=None):\n \"\"\" Calculate specific single-phase enthalpy\n Note that the order of the output match the default order of input for the differentials.\n Note further that dhdt, dhdp and dhdn only are flags to enable calculation.\n\n Args:\n temp (float): Temperature (K)\n press (float): Pressure (Pa)\n x (array_like): Molar composition\n phase (int): Calcualte root for specified phase\n dhdt (logical, optional): Calculate enthalpy differentials with respect to temperature while pressure and composition are held constant. Defaults to None.\n dhdp (logical, optional): Calculate enthalpy differentials with respect to pressure while temperature and composition are held constant. Defaults to None.\n dhdn (logical, optional): Calculate enthalpy differentials with respect to mol numbers while pressure and temperature are held constant. Defaults to None.\n\n Returns:\n float: Specific enthalpy (J/mol), and optionally differentials\n \"\"\"\n self.activate()\n null_pointer = POINTER(c_double)()\n\n temp_c = c_double(temp)\n press_c = c_double(press)\n x_c = (c_double * len(x))(*x)\n phase_c = c_int(phase)\n h_c = c_double(0.0)\n\n if dhdt is None:\n dhdt_c = null_pointer\n else:\n dhdt_c = POINTER(c_double)(c_double(0.0))\n if dhdp is None:\n dhdp_c = null_pointer\n else:\n dhdp_c = POINTER(c_double)(c_double(0.0))\n if dhdn is None:\n dhdn_c = null_pointer\n else:\n dhdn_c = (c_double * len(x))(0.0)\n\n residual_c = POINTER(c_int)()\n self.s_eos_enthalpy.argtypes = [POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_int ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_int )]\n\n self.s_eos_enthalpy.restype = None\n\n self.s_eos_enthalpy(byref(temp_c),\n byref(press_c),\n x_c,\n byref(phase_c),\n byref(h_c),\n dhdt_c,\n dhdp_c,\n dhdn_c,\n residual_c)\n\n return_tuple = (h_c.value, )\n if not dhdt is None:\n return_tuple += (dhdt_c[0], )\n if not dhdp is None:\n return_tuple += (dhdp_c[0], )\n if not dhdn is None:\n return_tuple += (np.array(dhdn_c), )\n\n return return_tuple\n\n def entropy(self,temp,press,x,phase,dsdt=None,dsdp=None,dsdn=None):\n \"\"\" Calculate specific single-phase entropy\n Note that the order of the output match the default order of input for the differentials.\n Note further that dsdt, dhsp and dsdn only are flags to enable calculation.\n\n Args:\n temp (float): Temperature (K)\n press (float): Pressure (Pa)\n x (array_like): Molar composition\n phase (int): Calcualte root for specified phase\n dsdt (logical, optional): Calculate entropy differentials with respect to temperature while pressure and composition are held constant. Defaults to None.\n dsdp (logical, optional): Calculate entropy differentials with respect to pressure while temperature and composition are held constant. Defaults to None.\n dsdn (logical, optional): Calculate entropy differentials with respect to mol numbers while pressure and temperature are held constant. Defaults to None.\n\n Returns:\n float: Specific entropy (J/mol/K), and optionally differentials\n \"\"\"\n self.activate()\n null_pointer = POINTER(c_double)()\n\n temp_c = c_double(temp)\n press_c = c_double(press)\n x_c = (c_double * len(x))(*x)\n phase_c = c_int(phase)\n s_c = c_double(0.0)\n\n if dsdt is None:\n dsdt_c = null_pointer\n else:\n dsdt_c = POINTER(c_double)(c_double(0.0))\n if dsdp is None:\n dsdp_c = null_pointer\n else:\n dsdp_c = POINTER(c_double)(c_double(0.0))\n if dsdn is None:\n dsdn_c = null_pointer\n else:\n dsdn_c = (c_double * len(x))(0.0)\n residual_c = POINTER(c_int)()\n\n self.s_eos_entropy.argtypes = [POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_int ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_int )]\n\n self.s_eos_entropy.restype = None\n\n self.s_eos_entropy(byref(temp_c),\n byref(press_c),\n x_c,\n byref(phase_c),\n byref(s_c),\n dsdt_c,\n dsdp_c,\n dsdn_c,\n residual_c)\n return_tuple = (s_c.value, )\n if not dsdt is None:\n return_tuple += (dsdt_c[0], )\n if not dsdp is None:\n return_tuple += (dsdp_c[0], )\n if not dsdn is None:\n return_tuple += (np.array(dsdn_c), )\n\n return return_tuple\n\n def idealenthalpysingle(self,temp,press,j,dhdt=None,dhdp=None):\n \"\"\" Calculate specific ideal enthalpy\n Note that the order of the output match the default order of input for the differentials.\n Note further that dhdt, and dhdp only are flags to enable calculation.\n\n Args:\n temp (float): Temperature (K)\n press (float): Pressure (Pa)\n x (array_like): Molar composition\n phase (int): Calcualte root for specified phase\n dhdt (logical, optional): Calculate ideal enthalpy differentials with respect to temperature while pressure and composition are held constant. Defaults to None.\n dhdp (logical, optional): Calculate ideal enthalpy differentials with respect to pressure while temperature and composition are held constant. Defaults to None.\n\n Returns:\n float: Specific ideal enthalpy (J/mol), and optionally differentials\n \"\"\"\n self.activate()\n null_pointer = POINTER(c_double)()\n\n temp_c = c_double(temp)\n press_c = c_double(press)\n j_c = c_int(j)\n h_c = c_double(0.0)\n\n if dhdt is None:\n dhdt_c = null_pointer\n else:\n dhdt_c = POINTER(c_double)(c_double(0.0))\n if dhdp is None:\n dhdp_c = null_pointer\n else:\n dhdp_c = POINTER(c_double)(c_double(0.0))\n\n self.s_eos_idealenthalpysingle.argtypes = [POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_int ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double )]\n\n self.s_eos_idealenthalpysingle.restype = None\n\n self.s_eos_idealenthalpysingle(byref(temp_c),\n byref(press_c),\n byref(j_c),\n byref(h_c),\n dhdt_c,\n dhdp_c)\n return_tuple = (h_c.value, )\n if not dhdt is None:\n return_tuple += (dhdt_c[0], )\n if not dhdp is None:\n return_tuple += (dhdp_c[0], )\n\n return return_tuple\n\n def speed_of_sound(self,temp,press,x,y,z,betaV,betaL,phase):\n \"\"\"Calculate speed of sound for single phase or two phase mixture assuming\n mechanical, thermal and chemical equilibrium.\n\n Args:\n temp (float): Temperature (K)\n press (float): Pressure (Pa)\n x (array_like): Liquid molar composition\n y (array_like): Gas molar composition\n z (array_like): Overall molar composition\n betaV (float): Molar gas phase fraction\n betaL (float): Molar liquid phase fraction\n phase (int): Calcualte root for specified phase\n\n Returns:\n float: Speed of sound (m/s)\n \"\"\"\n self.activate()\n temp_c = c_double(temp)\n press_c = c_double(press)\n x_c = (c_double * len(x))(*x)\n y_c = (c_double * len(y))(*y)\n z_c = (c_double * len(z))(*z)\n betaV_c = c_double(betaV)\n betaL_c = c_double(betaL)\n phase_c = c_int(phase)\n ph_c = POINTER(c_int)()\n\n self.s_sos_sound_velocity_2ph.argtypes = [POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_int ),\n POINTER( c_int )]\n\n self.s_sos_sound_velocity_2ph.restype = c_double\n\n sos = self.s_sos_sound_velocity_2ph(byref(temp_c),\n byref(press_c),\n x_c,\n y_c,\n z_c,\n byref(betaV_c),\n byref(betaL_c),\n byref(phase_c),\n ph_c)\n\n return sos\n\n #################################\n # Flash interfaces\n #################################\n\n def set_ph_tolerance(self, tol):\n \"\"\"Set tolerance of isobaric-isentalpic (PH) flash\n\n Args:\n tol (float): Tolerance\n \"\"\"\n tol_c = c_double(tol)\n self.s_set_ph_tolerance.argtypes = [POINTER( c_double )]\n self.s_set_ph_tolerance.restype = None\n self.s_set_ph_tolerance(byref(tol_c))\n\n def two_phase_tpflash(self,temp,press,z):\n \"\"\"Do isothermal-isobaric (TP) flash\n\n Args:\n temp (float): Temperature (K)\n press (float): Pressure (Pa)\n z (array_like): Overall molar composition\n\n Returns:\n x (ndarray): Liquid molar composition\n y (ndarray): Gas molar composition\n betaV (float): Molar gas phase fraction\n betaL (float): Molar liquid phase fraction\n phase (int): Phase identifier (iTWOPH/iLIQPH/iVAPPH)\n \"\"\"\n self.activate()\n temp_c = c_double(temp)\n press_c = c_double(press)\n z_c = (c_double * len(z))(*z)\n\n x_c = (c_double * len(z))(0.0)\n y_c = (c_double * len(z))(0.0)\n betaV_c = c_double(0.0)\n betaL_c = c_double(0.0)\n phase_c = c_int(0)\n\n self.s_twophasetpflash.argtypes = [POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_int ),\n POINTER( c_double ),\n POINTER( c_double )]\n\n self.s_twophasetpflash.restype = None\n\n self.s_twophasetpflash(byref(temp_c),\n byref(press_c),\n z_c,\n byref(betaV_c),\n byref(betaL_c),\n byref(phase_c),\n x_c,\n y_c)\n\n x = np.array(x_c)\n y = np.array(y_c)\n\n return x, y, betaV_c.value, betaL_c.value, phase_c.value\n\n\n def two_phase_psflash(self,press,z,entropy,temp=None):\n \"\"\"Do isentropic-isobaric (SP) flash\n\n Args:\n press (float): Pressure (Pa)\n z (array_like): Overall molar composition\n entropy (float): Specific entropy (J/mol/K)\n temp (float, optional): Initial guess for temperature (K)\n\n Returns:\n temp (float): Temperature (K)\n x (ndarray): Liquid molar composition\n y (ndarray): Gas molar composition\n betaV (float): Molar gas phase fraction\n betaL (float): Molar liquid phase fraction\n phase (int): Phase identifier (iTWOPH/iLIQPH/iVAPPH)\n \"\"\"\n self.activate()\n press_c = c_double(press)\n z_c = (c_double * len(z))(*z)\n s_c = c_double(entropy)\n\n if not temp is None:\n temp_c = POINTER( c_double )(c_double(temp))\n else:\n temp_c = POINTER( c_double )(c_double(0.0))\n\n x_c = (c_double * len(z))(0.0)\n y_c = (c_double * len(z))(0.0)\n betaV_c = c_double(0.0)\n betaL_c = c_double(0.0)\n phase_c = c_int(0)\n ierr_c = c_int(0)\n self.s_psflash_twophase.argtypes = [POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_int ),\n POINTER( c_int )]\n\n self.s_psflash_twophase.restype = None\n\n self.s_psflash_twophase(temp_c,\n byref(press_c),\n z_c,\n byref(betaV_c),\n byref(betaL_c),\n x_c,\n y_c,\n byref(s_c),\n byref(phase_c),\n byref(ierr_c))\n\n if ierr_c.value != 0:\n raise Exception(\"PS flash calclualtion failed\")\n\n x = np.array(x_c)\n y = np.array(y_c)\n\n return temp_c[0], x, y, betaV_c.value, betaL_c.value, phase_c.value\n\n def two_phase_phflash(self,press,z,enthalpy,temp=None):\n \"\"\"Do isenthalpic-isobaric (HP) flash\n\n Args:\n press (float): Pressure (Pa)\n z (array_like): Overall molar composition\n enthalpy (float): Specific enthalpy (J/mol)\n temp (float, optional): Initial guess for temperature (K)\n\n Returns:\n temp (float): Temperature (K)\n x (ndarray): Liquid molar composition\n y (ndarray): Gas molar composition\n betaV (float): Molar gas phase fraction\n betaL (float): Molar liquid phase fraction\n phase (int): Phase identifier (iTWOPH/iLIQPH/iVAPPH)\n \"\"\"\n self.activate()\n press_c = c_double(press)\n z_c = (c_double * len(z))(*z)\n h_c = c_double(enthalpy)\n\n if not temp is None:\n temp_c = POINTER( c_double )(c_double(temp))\n else:\n temp_c = POINTER( c_double )(c_double(0.0))\n\n x_c = (c_double * len(z))(0.0)\n y_c = (c_double * len(z))(0.0)\n betaV_c = c_double(0.0)\n betaL_c = c_double(0.0)\n phase_c = c_int(0)\n ierr_c = c_int(0)\n\n self.s_phflash_twophase.argtypes = [POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_int ),\n POINTER( c_int )]\n\n self.s_phflash_twophase.restype = None\n\n self.s_phflash_twophase(temp_c,\n byref(press_c),\n z_c,\n byref(betaV_c),\n byref(betaL_c),\n x_c,\n y_c,\n byref(h_c),\n byref(phase_c),\n byref(ierr_c))\n\n if ierr_c.value != 0:\n raise Exception(\"PH flash calclualtion failed\")\n\n x = np.array(x_c)\n y = np.array(y_c)\n\n return temp_c[0], x, y, betaV_c.value, betaL_c.value, phase_c.value\n\n def two_phase_uvflash(self,z,specific_energy,specific_volume,temp=None,press=None):\n \"\"\"Do isoenergetic-isochoric (UV) flash\n\n Args:\n press (float): Pressure (Pa)\n z (array_like): Overall molar composition\n specific_energy (float): Specific energy (J/mol)\n specific_volume (float): Specific volume (m3/mol)\n temp (float, optional): Initial guess for temperature (K)\n press (float, optional): Initial guess for pressure (Pa)\n\n Returns:\n temp (float): Temperature (K)\n press (float): Pressure (Pa)\n x (ndarray): Liquid molar composition\n y (ndarray): Gas molar composition\n betaV (float): Molar gas phase fraction\n betaL (float): Molar liquid phase fraction\n phase (int): Phase identifier (iTWOPH/iLIQPH/iVAPPH)\n \"\"\"\n self.activate()\n z_c = (c_double * len(z))(*z)\n e_c = c_double(specific_energy)\n v_c = c_double(specific_volume)\n\n if not temp is None:\n temp_c = POINTER( c_double )(c_double(temp))\n else:\n temp_c = POINTER( c_double )(c_double(0.0))\n\n if not press is None:\n press_c = POINTER( c_double )(c_double(press))\n else:\n press_c = POINTER( c_double )(c_double(0.0))\n\n x_c = (c_double * len(z))(0.0)\n y_c = (c_double * len(z))(0.0)\n betaV_c = c_double(0.0)\n betaL_c = c_double(0.0)\n phase_c = c_int(0)\n\n self.s_uvflash_twophase.argtypes = [POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_int )]\n\n self.s_uvflash_twophase(temp_c,\n press_c,\n z_c,\n byref(betaV_c),\n byref(betaL_c),\n x_c,\n y_c,\n byref(e_c),\n byref(v_c),\n byref(phase_c))\n\n x = np.array(x_c)\n y = np.array(y_c)\n\n return temp_c[0], press_c[0], x, y, betaV_c.value, betaL_c.value, phase_c.value\n\n def guess_phase(self, temp, press, z):\n \"\"\"If only one root exsist for the equation of state the phase type can be\n determined from either the psedo-critical volume or a volume ratio to the co-volume\n\n Args:\n temp (float): Temperature (K)\n press (float): Pressure (Pa)\n\n Returns:\n int: Phase int (VAPPH or LIQPH)\n \"\"\"\n self.activate()\n temp_c = c_double(temp)\n press_c = c_double(press)\n z_c = (c_double * len(z))(*z)\n null_pointer = POINTER(c_double)()\n temp_comp_c = null_pointer\n press_comp_c = null_pointer\n vb_ratio_c = null_pointer\n\n self.s_guess_phase.argtypes = [POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double )]\n\n self.s_guess_phase.restype = c_int\n\n phase = self.s_guess_phase(byref(temp_c),\n byref(press_c),\n z_c,\n temp_comp_c,\n press_comp_c,\n vb_ratio_c)\n\n return phase\n\n #################################\n # Temperature-volume property interfaces\n #################################\n\n def pressure_tv(self, temp, volume, n, dpdt=None, dpdv=None, dpdn=None):\n \"\"\"Calculate pressure given temperature, volume and mol numbers.\n\n Args:\n temp (float): Temperature (K)\n volume (float): Volume (m3)\n n (array_like): Mol numbers (mol)\n dpdt (No type, optional): Flag to activate calculation. Defaults to None.\n dpdv (No type, optional): Flag to activate calculation. Defaults to None.\n dpdn (No type, optional): Flag to activate calculation. Defaults to None.\n\n Returns:\n float: Pressure (Pa)\n Optionally pressure differentials\n \"\"\"\n self.activate()\n temp_c = c_double(temp)\n v_c = c_double(volume)\n n_c = (c_double * len(n))(*n)\n\n null_pointer = POINTER(c_double)()\n if dpdt is None:\n dpdt_c = null_pointer\n else:\n dpdt_c = POINTER(c_double)(c_double(0.0))\n if dpdv is None:\n dpdv_c = null_pointer\n else:\n dpdv_c = POINTER(c_double)(c_double(0.0))\n d2pdv2_c = null_pointer\n if dpdn is None:\n dpdn_c = null_pointer\n else:\n dpdn_c = (c_double * len(n))(0.0)\n\n recalculate_c = POINTER(c_int)(c_int(1))\n\n self.s_pressure_tv.argtypes = [POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_int )]\n\n self.s_pressure_tv.restype = c_double\n\n P = self.s_pressure_tv(byref(temp_c),\n byref(v_c),\n n_c,\n dpdv_c,\n dpdt_c,\n d2pdv2_c,\n dpdn_c,\n recalculate_c)\n\n return_tuple = (P, )\n if not dpdt is None:\n return_tuple += (dpdt_c[0], )\n if not dpdv is None:\n return_tuple += (dpdv_c[0], )\n if not dpdn is None:\n return_tuple += (np.array(dpdn_c), )\n\n return return_tuple\n\n def internal_energy_tv(self, temp, volume, n, dedt=None, dedv=None):\n \"\"\"Calculate internal energy given temperature, volume and mol numbers.\n\n Args:\n temp (float): Temperature (K)\n volume (float): Volume (m3)\n n (array_like): Mol numbers (mol)\n dedt (No type, optional): Flag to activate calculation. Defaults to None.\n dedv (No type, optional): Flag to activate calculation. Defaults to None.\n\n Returns:\n float: Energy (J)\n Optionally energy differentials\n \"\"\"\n self.activate()\n temp_c = c_double(temp)\n v_c = c_double(volume)\n e_c = c_double(0.0)\n n_c = (c_double * len(n))(*n)\n\n null_pointer = POINTER(c_double)()\n if dedt is None:\n dedt_c = null_pointer\n else:\n dedt_c = POINTER(c_double)(c_double(0.0))\n if dedv is None:\n dedv_c = null_pointer\n else:\n dedv_c = POINTER(c_double)(c_double(0.0))\n\n recalculate_c = POINTER(c_int)(c_int(1))\n\n self.s_internal_energy_tv.argtypes = [POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_int )]\n\n self.s_internal_energy_tv.restype = None\n\n self.s_internal_energy_tv(byref(temp_c),\n byref(v_c),\n n_c,\n byref(e_c),\n dedt_c,\n dedv_c,\n recalculate_c)\n\n return_tuple = (e_c.value, )\n if not dedt is None:\n return_tuple += (dedt_c[0], )\n if not dedv is None:\n return_tuple += (dedv_c[0], )\n\n return return_tuple\n\n def entropy_tv(self, temp, volume, n, dsdt=None, dsdv=None, dsdn=None):\n \"\"\"Calculate entropy given temperature, volume and mol numbers.\n\n Args:\n temp (float): Temperature (K)\n volume (float): Volume (m3)\n n (array_like): Mol numbers (mol)\n dsdt (No type, optional): Flag to activate calculation. Defaults to None.\n dsdv (No type, optional): Flag to activate calculation. Defaults to None.\n dsdn (No type, optional): Flag to activate calculation. Defaults to None.\n\n Returns:\n float: Entropy (J/K)\n Optionally entropy differentials\n \"\"\"\n self.activate()\n temp_c = c_double(temp)\n v_c = c_double(volume)\n s_c = c_double(0.0)\n n_c = (c_double * len(n))(*n)\n\n null_pointer = POINTER(c_double)()\n if dsdt is None:\n dsdt_c = null_pointer\n else:\n dsdt_c = POINTER(c_double)(c_double(0.0))\n if dsdv is None:\n dsdv_c = null_pointer\n else:\n dsdv_c = POINTER(c_double)(c_double(0.0))\n if dsdn is None:\n dsdn_c = null_pointer\n else:\n dsdn_c = (c_double * len(n))(0.0)\n\n residual_c = POINTER(c_int)(c_int(0))\n\n self.s_entropy_tv.argtypes = [POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_int )]\n\n self.s_entropy_tv.restype = None\n\n self.s_entropy_tv(byref(temp_c),\n byref(v_c),\n n_c,\n byref(s_c),\n dsdt_c,\n dsdv_c,\n dsdn_c,\n residual_c)\n\n return_tuple = (s_c.value, )\n if not dsdt is None:\n return_tuple += (dsdt_c[0], )\n if not dsdv is None:\n return_tuple += (dsdv_c[0], )\n if not dsdn is None:\n return_tuple += (np.array(dsdn_c), )\n\n return return_tuple\n\n def enthalpy_tv(self, temp, volume, n, dhdt=None, dhdv=None, dhdn=None):\n \"\"\"Calculate enthalpy given temperature, volume and mol numbers.\n\n Args:\n temp (float): Temperature (K)\n volume (float): Volume (m3)\n n (array_like): Mol numbers (mol)\n dhdt (No type, optional): Flag to activate calculation. Defaults to None.\n dhdv (No type, optional): Flag to activate calculation. Defaults to None.\n dhdn (No type, optional): Flag to activate calculation. Defaults to None.\n\n Returns:\n float: Enthalpy (J)\n Optionally enthalpy differentials\n \"\"\"\n self.activate()\n temp_c = c_double(temp)\n v_c = c_double(volume)\n h_c = c_double(0.0)\n n_c = (c_double * len(n))(*n)\n\n null_pointer = POINTER(c_double)()\n if dhdt is None:\n dhdt_c = null_pointer\n else:\n dhdt_c = POINTER(c_double)(c_double(0.0))\n if dhdv is None:\n dhdv_c = null_pointer\n else:\n dhdv_c = POINTER(c_double)(c_double(0.0))\n if dhdn is None:\n dhdn_c = null_pointer\n else:\n dhdn_c = (c_double * len(n))(0.0)\n\n residual_c = POINTER(c_int)(c_int(0))\n\n self.s_enthalpy_tv.argtypes = [POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_int )]\n\n self.s_enthalpy_tv.restype = None\n\n self.s_enthalpy_tv(byref(temp_c),\n byref(v_c),\n n_c,\n byref(h_c),\n dhdt_c,\n dhdv_c,\n dhdn_c,\n residual_c)\n\n return_tuple = (h_c.value, )\n if not dhdt is None:\n return_tuple += (dhdt_c[0], )\n if not dhdv is None:\n return_tuple += (dhdv_c[0], )\n if not dhdn is None:\n return_tuple += (np.array(dhdn_c), )\n\n return return_tuple\n\n def helmholtz_tv(self, temp, volume, n, dadt=None, dadv=None):\n \"\"\"Calculate Helmholtz energy given temperature, volume and mol numbers.\n\n Args:\n temp (float): Temperature (K)\n volume (float): Volume (m3)\n n (array_like): Mol numbers (mol)\n dadt (No type, optional): Flag to activate calculation. Defaults to None.\n dadv (No type, optional): Flag to activate calculation. Defaults to None.\n\n Returns:\n float: Helmholtz energy (J)\n Optionally energy differentials\n \"\"\"\n self.activate()\n temp_c = c_double(temp)\n v_c = c_double(volume)\n a_c = c_double(0.0)\n n_c = (c_double * len(n))(*n)\n\n null_pointer = POINTER(c_double)()\n if dadt is None:\n dadt_c = null_pointer\n else:\n dadt_c = POINTER(c_double)(c_double(0.0))\n if dadv is None:\n dadv_c = null_pointer\n else:\n dadv_c = POINTER(c_double)(c_double(0.0))\n d2adt2_c = null_pointer\n d2adv2_c = null_pointer\n d2advdt_c = null_pointer\n recalculate_c = POINTER(c_int)(c_int(1))\n\n self.s_helmholtz_energy.argtypes = [POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_int )]\n\n self.s_helmholtz_energy.restype = None\n\n self.s_helmholtz_energy(byref(temp_c),\n byref(v_c),\n n_c,\n byref(a_c),\n dadt_c,\n dadv_c,\n d2adt2_c,\n d2adv2_c,\n d2advdt_c,\n recalculate_c)\n\n return_tuple = (a_c.value, )\n if not dadt is None:\n return_tuple += (dadt_c[0], )\n if not dadv is None:\n return_tuple += (dadv_c[0], )\n\n return return_tuple\n\n def chemical_potential_tv(self, temp, volume, n, dmudt=None, dmudv=None, dmudn=None):\n \"\"\"Calculate chemical potential given temperature, volume and mol numbers.\n\n Args:\n temp (float): Temperature (K)\n volume (float): Volume (m3)\n n (array_like): Mol numbers (mol)\n dmudt (No type, optional): Flag to activate calculation. Defaults to None.\n dmudv (No type, optional): Flag to activate calculation. Defaults to None.\n dmudn (No type, optional): Flag to activate calculation. Defaults to None.\n\n Returns:\n float: Chemical potential (J/mol)\n Optionally chemical potential differentials\n \"\"\"\n self.activate()\n temp_c = c_double(temp)\n v_c = c_double(volume)\n mu_c = (c_double * len(n))(0.0)\n n_c = (c_double * len(n))(*n)\n\n null_pointer = POINTER(c_double)()\n if dmudt is None:\n dmudt_c = null_pointer\n else:\n dmudt_c = (c_double * len(n))(0.0)\n if dmudv is None:\n dmudv_c = null_pointer\n else:\n dmudv_c = (c_double * len(n))(0.0)\n if dmudn is None:\n dmudn_c = null_pointer\n else:\n dmudn_c = (c_double * len(n)**2)(0.0)\n\n recalculate_c = POINTER(c_int)(c_int(1))\n\n self.s_chempot.argtypes = [POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_int )]\n\n self.s_chempot.restype = None\n\n self.s_chempot(byref(temp_c),\n byref(v_c),\n n_c,\n mu_c,\n dmudv_c,\n dmudt_c,\n dmudn_c,\n recalculate_c)\n\n return_tuple = (np.array(mu_c), )\n if not dmudt is None:\n return_tuple += (np.array(dmudt_c), )\n if not dmudv is None:\n return_tuple += (np.array(dmudv_c), )\n if not dmudn is None:\n dmudn = np.zeros((len(n), len(n)))\n for i in range(len(n)):\n for j in range(len(n)):\n dmudn[i][j] = dmudn_c[i + j*len(n)]\n return_tuple += (np.array(dmudn), )\n\n return return_tuple\n\n def fugacity_tv(self, temp, volume, n, dlnphidt=None, dlnphidv=None, dlnphidn=None):\n \"\"\"Calculate natural logarithm of fugacity given temperature, volume and mol numbers.\n\n Args:\n temp (float): Temperature (K)\n volume (float): Volume (m3)\n n (array_like): Mol numbers (mol)\n dlnphidt (No type, optional): Flag to activate calculation. Defaults to None.\n dlnphidv (No type, optional): Flag to activate calculation. Defaults to None.\n dlnphidn (No type, optional): Flag to activate calculation. Defaults to None.\n\n Returns:\n ndarry: Natural logarithm of fugacity\n Optionally differentials\n \"\"\"\n self.activate()\n temp_c = c_double(temp)\n v_c = c_double(volume)\n lnphi_c = (c_double * len(n))(0.0)\n n_c = (c_double * len(n))(*n)\n\n null_pointer = POINTER(c_double)()\n if dlnphidt is None:\n dlnphidt_c = null_pointer\n else:\n dlnphidt_c = (c_double * len(n))(0.0)\n if dlnphidv is None:\n dlnphidv_c = null_pointer\n else:\n dlnphidv_c = (c_double * len(n))(0.0)\n if dlnphidn is None:\n dlnphidn_c = null_pointer\n else:\n dlnphidn_c = (c_double * len(n)**2)(0.0)\n\n self.s_lnphi_tv.argtypes = [POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double )]\n\n self.s_lnphi_tv.restype = None\n\n self.s_lnphi_tv(byref(temp_c),\n byref(v_c),\n n_c,\n lnphi_c,\n dlnphidt_c,\n dlnphidv_c,\n dlnphidn_c)\n\n return_tuple = (np.array(lnphi_c), )\n if not dlnphidt is None:\n return_tuple += (np.array(dlnphidt_c), )\n if not dlnphidv is None:\n return_tuple += (np.array(dlnphidv_c), )\n if not dlnphidn is None:\n dlnphidn = np.zeros((len(n),len(n)))\n for i in range(len(n)):\n for j in range(len(n)):\n dlnphidn[i][j] = dlnphidn_c[i + j*len(n)]\n return_tuple += (dlnphidn, )\n\n return return_tuple\n\n #################################\n # Saturation interfaces\n #################################\n\n def bubble_temperature(self, press, z):\n \"\"\"Calculate bubble temperature given pressure and composition\n\n Args:\n press (float): Pressure (Pa)\n z (array_like): Composition (-)\n\n Raises:\n Exception: Faild to calculate\n\n Returns:\n float: Temperature (K)\n ndarray: Incipient phase composition\n \"\"\"\n self.activate()\n press_c = c_double(press)\n y_c = (c_double * len(z))(0.0)\n z_c = (c_double * len(z))(*z)\n ierr_c = c_int(0)\n\n self.s_bubble_t.argtypes = [POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_int )]\n\n self.s_bubble_t.restype = c_double\n\n temp = self.s_bubble_t(byref(press_c),\n z_c,\n y_c,\n byref(ierr_c))\n\n y = np.array(y_c)\n if ierr_c.value != 0:\n raise Exception(\"bubble_temperature calclualtion failed\")\n return temp, y\n\n def bubble_pressure(self, temp, z):\n \"\"\"Calculate bubble pressure given temperature and composition\n\n Args:\n temp (float): Temperature (K)\n z (array_like): Composition (-)\n\n Raises:\n Exception: Faild to calculate\n\n Returns:\n float: Pressure (Pa)\n ndarray: Incipient phase composition\n \"\"\"\n self.activate()\n temp_c = c_double(temp)\n y_c = (c_double * len(z))(0.0)\n z_c = (c_double * len(z))(*z)\n ierr_c = c_int(0)\n\n self.s_bubble_p.argtypes = [POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_int )]\n\n self.s_bubble_p.restype = c_double\n\n press = self.s_bubble_p(byref(temp_c),\n z_c,\n y_c,\n byref(ierr_c))\n\n y = np.array(y_c)\n if ierr_c.value != 0:\n raise Exception(\"bubble_pressure calclualtion failed\")\n return press, y\n\n def dew_temperature(self,press,z):\n \"\"\"Calculate dew temperature given pressure and composition\n\n Args:\n temp (float): Pressure (Pa)\n z (float): Compositon (-)\n\n Raises:\n Exception: Not able to solve for dew point\n\n Returns:\n float : Temperature (K)\n ndarray : Incipient phase composition (-)\n \"\"\"\n self.activate()\n press_c = c_double(press)\n x_c = (c_double * len(z))(0.0)\n z_c = (c_double * len(z))(*z)\n ierr_c = c_int(0)\n\n self.s_dew_t.argtypes = [POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_int )]\n\n self.s_dew_t.restype = c_double\n\n temp = self.s_dew_t(byref(press_c),\n x_c,\n z_c,\n byref(ierr_c))\n\n x = np.array(x_c)\n if ierr_c.value != 0:\n raise Exception(\"dew_temperature calclualtion failed\")\n return temp, x\n\n def dew_pressure(self,temp,z):\n \"\"\"Calculate dew pressure given temperature and composition\n\n Args:\n temp (float): Temperature (K)\n z (float): Compositon (-)\n\n Raises:\n Exception: Not able to solve for dew point\n\n Returns:\n float : Pressure (Pa)\n ndarray : Incipient phase composition (-)\n \"\"\"\n self.activate()\n temp_c = c_double(temp)\n x_c = (c_double * len(z))(0.0)\n z_c = (c_double * len(z))(*z)\n ierr_c = c_int(0)\n\n self.s_dew_p.argtypes = [POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_int )]\n\n self.s_dew_p.restype = c_double\n\n press = self.s_dew_p(byref(temp_c),\n x_c,\n z_c,\n byref(ierr_c))\n\n x = np.array(x_c)\n if ierr_c.value != 0:\n raise Exception(\"bubble_pressure calclualtion failed\")\n return press, x\n\n def get_envelope_twophase(self, initial_pressure, z, maximum_pressure=1.5e7,\n minimum_temperature=None, step_size=None,\n calc_v=False):\n \"\"\"Get the phase-envelope\n\n Args:\n initial_pressure (float): Start mapping form dew point at initial pressure (Pa).\n z (array_like): Composition (-)\n maximum_pressure (float , optional): Exit on maximum pressure (Pa). Defaults to 1.5e7.\n minimum_temperature (float , optional): Exit on minimum pressure (Pa). Defaults to None.\n step_size (float , optional): Tune step size of envelope trace. Defaults to None.\n calc_v (bool, optional): Calculate specifc volume of saturated phase? Defaults to False\n Returns:\n ndarray: Temperature values (K)\n ndarray: Pressure values (Pa)\n ndarray (optional): Specific volume (m3/mol)\n \"\"\"\n self.activate()\n nmax = 1000\n z_c = (c_double * len(z))(*z)\n temp_c = c_double(0.0)\n press_c = c_double(initial_pressure)\n spec_c = c_int(1)\n beta_in_c = c_double(1.0)\n max_press_c = c_double(maximum_pressure)\n nmax_c = c_int(nmax)\n Ta_c = (c_double * nmax)(0.0)\n Pa_c = (c_double * nmax)(0.0)\n Ki_c = (c_double * (nmax*len(z)))(0.0)\n beta_c = (c_double * nmax)(0.0)\n n_c = c_int(0)\n null_pointer = POINTER(c_double)()\n criconden_c = null_pointer\n crit_c = null_pointer\n if step_size is None:\n ds_c = null_pointer\n else:\n ds_c = POINTER(c_double)(c_double(step_size))\n exitOnTriplePoint_c = POINTER(c_int)()\n if minimum_temperature is None:\n tme_c = null_pointer\n else:\n tme_c = POINTER(c_double)(c_double(minimum_temperature))\n\n self.s_envelope_plot.argtypes = [POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_int ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_int ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_int ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_int ),\n POINTER( c_double )]\n\n self.s_envelope_plot.restype = None\n\n self.s_envelope_plot(z_c,\n byref(temp_c),\n byref(press_c),\n byref(spec_c),\n byref(beta_in_c),\n byref(max_press_c),\n byref(nmax_c),\n Ta_c,\n Pa_c,\n Ki_c,\n beta_c,\n byref(n_c),\n criconden_c,\n crit_c,\n ds_c,\n exitOnTriplePoint_c,\n tme_c)\n\n t_vals = np.array(Ta_c[0:n_c.value])\n p_vals = np.array(Pa_c[0:n_c.value])\n\n return_tuple = (t_vals, p_vals)\n\n if calc_v:\n # Special treatment for single phase\n if np.amax(z) == 1:\n t_vals_single = np.zeros(2*n_c.value)\n p_vals_single = np.zeros(2*n_c.value)\n v_vals_single = np.zeros_like(t_vals_single)\n for i in range(n_c.value):\n t_vals_single[i] = t_vals[i]\n t_vals_single[-i-1] = t_vals[i]\n p_vals_single[i] = p_vals[i]\n p_vals_single[-i-1] = p_vals[i]\n v_vals_single[i], = self.specific_volume(t_vals[i], p_vals[i], z, self.VAPPH)\n v_vals_single[-i-1], = self.specific_volume(t_vals[i], p_vals[i], z, self.LIQPH)\n return_tuple = (t_vals_single, p_vals_single, v_vals_single)\n else:\n v_vals = np.zeros_like(t_vals)\n for i in range(n_c.value):\n if beta_c[i] > 0.5:\n phase = self.VAPPH\n else:\n phase = self.LIQPH\n v_vals[i], = self.specific_volume(t_vals[i], p_vals[i], z, phase)\n return_tuple += (v_vals, )\n\n return return_tuple\n\n def get_binary_pxy(self,\n temp,\n maximum_pressure=1.5e7,\n minimum_pressure=1.0e5,\n maximum_dz = 0.003,\n maximum_dlns=0.01):\n \"\"\"Calculate binary three phase envelope\n\n Args:\n temp (float): Temperature (K)\n maximum_pressure (float, optional): Exit on maximum pressure (Pa). Defaults to 1.5e7.\n minimum_pressure (float, optional): Exit on minimum pressure (Pa). Defaults to 1.0e5.\n maximum_dz (float, optional): [description]. Defaults to 0.003.\n maximum_dlns (float, optional): [description]. Defaults to 0.01.\n\n Returns:\n tuple of arrays: LLE, L1VE, L2VE\n \"\"\"\n # Redefinition of module parameter:\n self.activate()\n nmax = 10000\n #c_int.in_dll(self.tp, self.get_export_name(\"binaryplot\", \"maxpoints\")).value\n\n temp_c = c_double(temp)\n min_temp_c = c_double(0.0)\n ispec_c = c_int(1)\n press_c = c_double(0.0)\n max_press_c = c_double(maximum_pressure)\n min_press_c = c_double(minimum_pressure)\n dz_max_c = c_double(maximum_dz)\n dlns_max_c = c_double(maximum_dlns)\n filename = \"binaryVLLE.dat\"\n filename_c = c_char_p(filename.encode('ascii'))\n filename_len = c_len_type(len(filename))\n res_c = (c_double * (nmax*9))(0.0)\n nres_c = (c_int * 3)(0)\n wsf_c = c_int(1)\n\n self.s_binary_plot.argtypes = [POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_int ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_char_p ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_int ),\n POINTER( c_int ),\n POINTER( c_double ),\n c_len_type]\n\n self.s_binary_plot.restype = None\n\n self.s_binary_plot(byref(temp_c),\n byref(press_c),\n byref(ispec_c),\n byref(min_temp_c),\n byref(max_press_c),\n byref(dz_max_c),\n filename_c,\n byref(dlns_max_c),\n res_c,\n nres_c,\n byref(wsf_c),\n byref(min_press_c),\n filename_len)\n\n nLLE = nres_c[0]\n nL1VE = nres_c[1]\n nL2VE = nres_c[2]\n\n if nLLE > 0:\n xLLE = np.zeros(nLLE)\n wLLE = np.zeros(nLLE)\n pLLE = np.zeros(nLLE)\n for i in range(nLLE):\n xLLE[i] = res_c[i*9]\n wLLE[i] = res_c[i*9+1]\n pLLE[i] = res_c[i*9+2]\n LLE = (xLLE, wLLE, pLLE)\n else:\n LLE = (None, None, None)\n\n if nL1VE > 0:\n xL1VE = np.zeros(nL1VE)\n wL1VE = np.zeros(nL1VE)\n pL1VE = np.zeros(nL1VE)\n for i in range(nL1VE):\n xL1VE[i] = res_c[i*9+3]\n wL1VE[i] = res_c[i*9+4]\n pL1VE[i] = res_c[i*9+5]\n L1VE = (xL1VE, wL1VE, pL1VE)\n else:\n L1VE = (None, None, None)\n\n if nL2VE > 0:\n xL2VE = np.zeros(nL2VE)\n wL2VE = np.zeros(nL2VE)\n pL2VE = np.zeros(nL2VE)\n for i in range(nL2VE):\n xL2VE[i] = res_c[i*9+6]\n wL2VE[i] = res_c[i*9+7]\n pL2VE[i] = res_c[i*9+8]\n L2VE = (xL2VE, wL2VE, pL2VE)\n else:\n L2VE = (None, None, None)\n\n return LLE, L1VE, L2VE\n\n def get_bp_term(self,\n i_term):\n \"\"\"Get error description for binary plot error\n\n Args:\n i_term (int): binary plot error identifyer\n\n Returns:\n str: Error message\n \"\"\"\n message_len = 50\n message_c = c_char_p(b\" \" * message_len)\n message_len = c_len_type(message_len)\n i_term_c = c_int(i_term)\n\n self.s_get_bp_term.argtypes = [POINTER( c_int ),\n c_char_p,\n c_len_type]\n\n self.s_get_bp_term.restype = None\n\n self.s_get_bp_term(byref(i_term_c),\n message_c,\n message_len)\n message = message_c.value.decode('ascii')\n return message\n\n def global_binary_plot(self,\n maximum_pressure=1.5e7,\n minimum_pressure=1.0e5,\n minimum_temperature=150.0,\n maximum_temperature=500.0,\n include_azeotropes=False):\n \"\"\"Calculate global binary phase envelope\n\n Args:\n maximum_pressure (float, optional): Exit on maximum pressure (Pa). Defaults to 1.5e7.\n minimum_pressure (float, optional): Exit on minimum pressure (Pa). Defaults to 1.0e5.\n minimum_temperature (float, optional): Terminate phase line traceing at minimum temperature. Defaults to 150.0 K.\n maximum_temperature (float, optional): Terminate phase line traceing at maximum temperature. Defaults to 500.0 K.\n include_azeotropes (bool, optional): Include azeotropic lines. Defaults to False.\n\n Returns:\n tuple of arrays\n \"\"\"\n self.activate()\n max_press_c = c_double(maximum_pressure)\n min_press_c = c_double(minimum_pressure)\n max_temp_c = c_double(maximum_temperature)\n min_temp_c = c_double(minimum_temperature)\n az_bool_c = c_int(1 if include_azeotropes else 0)\n filename = \"global_binary.dat\"\n filename_c = c_char_p(filename.encode('ascii'))\n filename_len = c_len_type(len(filename))\n i_term_c = c_int(0)\n\n self.s_global_binary_plot.argtypes = [POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n c_char_p,\n POINTER( c_int ),\n POINTER( c_double ),\n POINTER( c_int ),\n c_len_type]\n\n self.s_global_binary_plot.restype = None\n\n self.s_global_binary_plot(byref(min_press_c),\n byref(max_press_c),\n byref(min_temp_c),\n filename_c,\n byref(i_term_c),\n byref(max_temp_c),\n byref(az_bool_c),\n filename_len)\n\n if not i_term_c.value == 0:\n message = self.get_bp_term(i_term_c.value)\n print(message)\n\n # Load file with filename and read into arrays\n return plotutils.get_globa_binary_data(filename)\n\n def solid_envelope_plot(self, initial_pressure, z, maximum_pressure=1.5e7,\n minimum_temperature=170.0, calc_esv=False):\n \"\"\"Calculate phase envelope including solid lines\n\n Args:\n initial_pressure (float): Start mapping from initial pressure (Pa).\n z (array_like): Composition (-)\n maximum_pressure (float , optional): Exit on maximum pressure (Pa). Defaults to 1.5e7.\n calc_esv (bool, optional): Calculate specifc volume of saturated phase? Defaults to False\n\n Returns:\n tuple of arrays\n \"\"\"\n self.activate()\n z_c = (c_double * len(z))(*z)\n temp_c = c_double(0.0)\n press_c = c_double(initial_pressure)\n max_press_c = c_double(maximum_pressure)\n filename = \"solid_envelope.dat\"\n filename_c = c_char_p(filename.encode('ascii'))\n filename_len = c_len_type(len(filename))\n i_spec_c = c_int(1)\n esv_bool_c = c_int(1 if calc_esv else 0)\n\n min_t = self.get_tmin()\n self.set_tmin(minimum_temperature)\n\n self.s_solid_envelope_plot.argtypes = [POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_int ),\n POINTER( c_double ),\n c_char_p,\n POINTER( c_int ),\n c_len_type]\n\n self.s_solid_envelope_plot.restype = None\n\n self.s_solid_envelope_plot(z_c,\n byref(temp_c),\n byref(press_c),\n byref(i_spec_c),\n byref(max_press_c),\n filename_c,\n byref(esv_bool_c),\n filename_len)\n\n self.set_tmin(min_t)\n\n #if .not. i_term_c.value == 0:\n # message = self.get_bp_term(iTerm)\n # print(message)\n\n # Load file with filename and read into lists....\n return plotutils.get_solid_envelope_data(filename)\n\n def get_isotherm(self,\n temp,\n z,\n minimum_pressure=1.0e5,\n maximum_pressure=1.5e7,\n nmax=100):\n \"\"\"Get iso-therm at specified temperature\n\n Args:\n temp (float): Temperature (K)\n z (array_like): Composition (-)\n minimum_pressure (float, optional): Map to minimum pressure. Defaults to 1.0e5. (Pa)\n maximum_pressure (float, optional): Map to maximum pressure. Defaults to 1.5e7. (Pa)\n nmax (int, optional): Maximum number of points on iso-therm. Defaults to 100.\n\n Returns:\n Multiple numpy arrays.\n \"\"\"\n self.activate()\n temp_c = c_double(temp)\n minimum_pressure_c = c_double(minimum_pressure)\n maximum_pressure_c = c_double(maximum_pressure)\n z_c = (c_double * len(z))(*z)\n va_c = (c_double * nmax)(0.0)\n pa_c = (c_double * nmax)(0.0)\n sa_c = (c_double * nmax)(0.0)\n ha_c = (c_double * nmax)(0.0)\n nmax_c = c_int(nmax)\n na_c = c_int(0)\n\n self.s_isotherm.argtypes = [POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_int ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_int )]\n\n self.s_isotherm.restype = None\n\n self.s_isotherm(byref(temp_c),\n byref(minimum_pressure_c),\n byref(maximum_pressure_c),\n z_c,\n byref(nmax_c),\n pa_c,\n va_c,\n sa_c,\n ha_c,\n byref(na_c))\n\n p_vals = np.array(pa_c[0:na_c.value])\n v_vals = np.array(va_c[0:na_c.value])\n s_vals = np.array(sa_c[0:na_c.value])\n h_vals = np.array(ha_c[0:na_c.value])\n\n return p_vals, v_vals, s_vals, h_vals\n\n def get_isobar(self,\n press,\n z,\n minimum_temperature=200.0,\n maximum_temperature=500.0,\n nmax=100):\n \"\"\"Get isobar at specified pressure.\n\n Args:\n press (float): Pressure (Pa)\n z (array_like): Composition (-)\n minimum_temperature (float, optional): Minimum temperature. Defaults to 200.0. (K)\n maximum_temperature (float, optional): Maximum temperature. Defaults to 500.0. (K)\n nmax (int, optional): Maximum number of points on iso-bar. Defaults to 100.\n\n Returns:\n Multiple numpy arrays.\n \"\"\"\n self.activate()\n press_c = c_double(press)\n minimum_temperature_c = c_double(minimum_temperature)\n maximum_temperature_c = c_double(maximum_temperature)\n z_c = (c_double * len(z))(*z)\n va_c = (c_double * nmax)(0.0)\n ta_c = (c_double * nmax)(0.0)\n sa_c = (c_double * nmax)(0.0)\n ha_c = (c_double * nmax)(0.0)\n nmax_c = c_int(nmax)\n na_c = c_int(0)\n\n self.s_isobar.argtypes = [POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_int ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_int )]\n\n self.s_isobar.restype = None\n\n self.s_isobar(byref(press_c),\n byref(minimum_temperature_c),\n byref(maximum_temperature_c),\n z_c,\n byref(nmax_c),\n ta_c,\n va_c,\n sa_c,\n ha_c,\n byref(na_c))\n\n t_vals = np.array(ta_c[0:na_c.value])\n v_vals = np.array(va_c[0:na_c.value])\n s_vals = np.array(sa_c[0:na_c.value])\n h_vals = np.array(ha_c[0:na_c.value])\n\n return t_vals, v_vals, s_vals, h_vals\n\n def get_isenthalp(self,\n enthalpy,\n z,\n minimum_pressure=1.0e5,\n maximum_pressure=1.5e7,\n minimum_temperature=200.0,\n maximum_temperature=500.0,\n nmax=100):\n \"\"\"Get isenthalpy given specified enthalpy.\n\n Args:\n enthalpy (float): Enthalpy (J/mol)\n z (array_like): Composition (-)\n minimum_pressure (float, optional): Minimum pressure. Defaults to 1.0e5. (Pa)\n maximum_pressure (float, optional): Maximum pressure. Defaults to 1.5e7. (Pa)\n minimum_temperature (float, optional): Minimum temperature. Defaults to 200.0. (K)\n maximum_temperature (float, optional): Maximum temperature. Defaults to 500.0. (K)\n nmax (int, optional): Maximum number of points on isenthalp. Defaults to 100.\n\n Returns:\n Multiple numpy arrays.\n \"\"\"\n self.activate()\n enthalpy_c = c_double(enthalpy)\n minimum_pressure_c = c_double(minimum_pressure)\n maximum_pressure_c = c_double(maximum_pressure)\n minimum_temperature_c = c_double(minimum_temperature)\n maximum_temperature_c = c_double(maximum_temperature)\n z_c = (c_double * len(z))(*z)\n va_c = (c_double * nmax)(0.0)\n ta_c = (c_double * nmax)(0.0)\n sa_c = (c_double * nmax)(0.0)\n pa_c = (c_double * nmax)(0.0)\n nmax_c = c_int(nmax)\n na_c = c_int(0)\n\n self.s_isenthalp.argtypes = [POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_int ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_int )]\n\n self.s_isenthalp.restype = None\n\n self.s_isenthalp(byref(enthalpy_c),\n byref(minimum_pressure_c),\n byref(maximum_pressure_c),\n byref(minimum_temperature_c),\n byref(maximum_temperature_c),\n z_c,\n byref(nmax_c),\n pa_c,\n va_c,\n sa_c,\n ta_c,\n byref(na_c))\n\n t_vals = np.array(ta_c[0:na_c.value])\n v_vals = np.array(va_c[0:na_c.value])\n s_vals = np.array(sa_c[0:na_c.value])\n p_vals = np.array(pa_c[0:na_c.value])\n\n return t_vals, p_vals, v_vals, s_vals\n\n def get_isentrope(self,\n entropy,\n z,\n minimum_pressure=1.0e5,\n maximum_pressure=1.5e7,\n minimum_temperature=200.0,\n maximum_temperature=500.0,\n nmax=100):\n \"\"\"Get isentrope at specified entropy.\n\n Args:\n entropy (float): Entropy (J/mol/K)\n z (array_like): Composition (-)\n minimum_pressure (float, optional): Minimum pressure. Defaults to 1.0e5. (Pa)\n maximum_pressure (float, optional): Maximum pressure. Defaults to 1.5e7. (Pa)\n minimum_temperature (float, optional): Minimum temperature. Defaults to 200.0. (K)\n maximum_temperature (float, optional): Maximum temperature. Defaults to 500.0. (K)\n nmax (int, optional): Maximum number of points on isentrope. Defaults to 100.\n\n Returns:\n Multiple numpy arrays.\n \"\"\"\n self.activate()\n entropy_c = c_double(entropy)\n minimum_pressure_c = c_double(minimum_pressure)\n maximum_pressure_c = c_double(maximum_pressure)\n minimum_temperature_c = c_double(minimum_temperature)\n maximum_temperature_c = c_double(maximum_temperature)\n z_c = (c_double * len(z))(*z)\n va_c = (c_double * nmax)(0.0)\n ta_c = (c_double * nmax)(0.0)\n ha_c = (c_double * nmax)(0.0)\n pa_c = (c_double * nmax)(0.0)\n nmax_c = c_int(nmax)\n na_c = c_int(0)\n\n self.s_isentrope.argtypes = [POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_int ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_int )]\n\n self.s_isentrope.restype = None\n\n self.s_isentrope(byref(entropy_c),\n byref(minimum_pressure_c),\n byref(maximum_pressure_c),\n byref(minimum_temperature_c),\n byref(maximum_temperature_c),\n z_c,\n byref(nmax_c),\n pa_c,\n va_c,\n ha_c,\n ta_c,\n byref(na_c))\n\n t_vals = np.array(ta_c[0:na_c.value])\n v_vals = np.array(va_c[0:na_c.value])\n h_vals = np.array(ha_c[0:na_c.value])\n p_vals = np.array(pa_c[0:na_c.value])\n\n return t_vals, p_vals, v_vals, h_vals\n\n #################################\n # Stability interfaces\n #################################\n\n def critical(self, n, temp=0.0, v=0.0, tol=1.0e-7):\n \"\"\"Calculate critical point in variables T and V\n\n Args:\n n (array_like): Mol numbers (mol)\n temp (float, optional): Initial guess for temperature (K). Defaults to 0.0.\n v (float, optional): Initial guess for volume (m3). Defaults to 0.0.\n tol (float, optional): Error tolerance (-). Defaults to 1.0e-8.\n\n Raises:\n Exception: Failure to solve for critcal point\n\n Returns:\n float: Temperature (K)\n float: Volume (m3)\n float: Pressure (Pa)\n \"\"\"\n self.activate()\n temp_c = c_double(temp)\n v_c = c_double(v)\n n_c = (c_double * len(n))(*n)\n ierr_c = c_int(0)\n P_c = c_double(0.0)\n tol_c = c_double(tol)\n self.s_crit_tv.argtypes = [POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_int ),\n POINTER( c_double ),\n POINTER( c_double )]\n\n self.s_crit_tv.restype = None\n\n self.s_crit_tv(byref(temp_c),\n byref(v_c),\n n_c,\n byref(ierr_c),\n byref(tol_c),\n byref(P_c))\n\n if ierr_c.value != 0:\n raise Exception(\"critical calclualtion failed\")\n\n return temp_c.value, v_c.value, P_c.value\n\n #################################\n # Virial interfaces\n #################################\n\n def virial_coeffcients(self, temp, n):\n \"\"\"Calculate (composition-dependent) virial coefficients B and C,\n defined as P/RT = rho + B*rho**2 + C*rho**3 + O(rho**4) as rho->0.\n\n Args:\n temp (float): Temperature\n n (array_like): Mol numbers (mol)\n\n Returns:\n float: B (m3/mol)\n float: C (m6/mol2)\n \"\"\"\n self.activate()\n temp_c = POINTER( c_double )(c_double(temp))\n n_c = (c_double * len(n))(*n)\n B_c = c_double(0.0)\n C_c = c_double(0.0)\n self.s_virial_coeffcients.argtypes = [POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double ),\n POINTER( c_double )]\n\n self.s_virial_coeffcients.restype = None\n\n self.s_virial_coeffcients(temp_c,\n n_c,\n byref(B_c),\n byref(C_c))\n\n return B_c.value, C_c.value\n\n def second_virial_matrix(self, temp):\n \"\"\"Calculate composition-independent virial coefficients B,\n defined as P = RT*rho + B*rho**2 + C*rho**3 + O(rho**4) as rho->0.\n Including cross coefficients.\n\n Args:\n temp (float): Temperature (K)\n\n Returns:\n ndarray: B - Second virial coefficient matrix (m3/mol)\n \"\"\"\n self.activate()\n temp_c = POINTER( c_double )(c_double(temp))\n bmat_c = (c_double * self.nc**2)(0.0)\n\n self.s_second_virial_matrix.argtypes = [POINTER( c_double ),\n POINTER( c_double )]\n\n self.s_second_virial_matrix.restype = None\n\n self.s_second_virial_matrix(temp_c, bmat_c)\n\n bmat = np.zeros((self.nc,self.nc))\n for i in range(self.nc):\n for j in range(self.nc):\n bmat[i][j] = bmat_c[i+j*self.nc]\n\n return bmat\n\n def binary_third_virial_matrix(self, temp):\n \"\"\"Calculate composition-independent virial coefficients C,\n defined as P = RT*rho + B*rho**2 + C*rho**3 + O(rho**4) as rho->0.\n Including cross coefficients\n Currently the code only support binary mixtures\n\n Args:\n temp (float): Temperature (K)\n\n Returns:\n ndarray: C - Third virial coefficient matrix (m6/mol2)\n \"\"\"\n self.activate()\n assert self.nc == 2\n temp_c = POINTER( c_double )(c_double(temp))\n cmat_c = (c_double * self.nc**2)(0.0)\n\n self.s_binary_third_virial_matrix.argtypes = [POINTER( c_double ),\n POINTER( c_double )]\n\n self.s_binary_third_virial_matrix.restype = None\n\n self.s_binary_third_virial_matrix(temp_c, cmat_c)\n\n cmat = np.zeros((self.nc,self.nc))\n for i in range(self.nc):\n for j in range(self.nc):\n cmat[i][j] = cmat_c[i+j*self.nc]\n\n return cmat\n" ]
[ [ "numpy.amax", "numpy.array", "numpy.zeros", "numpy.zeros_like" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
shubham-goel/pytorch3d
[ "e5e6e90af6f81b3eccb35bbdfdc7e64ec6a4df21", "e5e6e90af6f81b3eccb35bbdfdc7e64ec6a4df21", "e5e6e90af6f81b3eccb35bbdfdc7e64ec6a4df21", "e5e6e90af6f81b3eccb35bbdfdc7e64ec6a4df21", "e5e6e90af6f81b3eccb35bbdfdc7e64ec6a4df21", "e5e6e90af6f81b3eccb35bbdfdc7e64ec6a4df21", "e5e6e90af6f81b3eccb35bbdfdc7e64ec6a4df21" ]
[ "tests/bm_interpolate_face_attributes.py", "projects/nerf/train_nerf.py", "pytorch3d/io/mtl_io.py", "docs/examples/pulsar_cam.py", "tests/test_points_alignment.py", "tests/test_render_implicit.py", "docs/examples/pulsar_basic.py" ]
[ "# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.\n\nfrom itertools import product\n\nimport torch\nfrom fvcore.common.benchmark import benchmark\nfrom pytorch3d.ops.interp_face_attrs import (\n interpolate_face_attributes,\n interpolate_face_attributes_python,\n)\n\n\ndef _generate_data(N, S, K, F, D, device, requires_grad=False):\n pix_to_face = torch.randint(-10, F, (N, S, S, K), device=device)\n barycentric_coords = torch.randn(\n N, S, S, K, 3, device=device, requires_grad=requires_grad\n )\n face_attrs = torch.randn(F, 3, D, device=device, requires_grad=requires_grad)\n grad_pix_attrs = torch.randn(N, S, S, K, D, device=device)\n return pix_to_face, barycentric_coords, face_attrs, grad_pix_attrs\n\n\ndef _bm_forward(N, S, F, K, D, impl):\n # The runtime depends on the values of pix_to_face. So for proper\n # benchmarking we should probably take the average of multiple\n # values of pix to face. But this doesn't easily fit into fvcore\n # benchmarking, so instead we'll just set a manual seed to make sure\n # that different impls will use the same data.\n torch.manual_seed(0)\n device = torch.device(\"cuda\")\n data = _generate_data(N, S, K, F, D, device, requires_grad=False)\n args = data[:3]\n torch.cuda.synchronize()\n if impl == \"cuda\":\n fun = interpolate_face_attributes\n elif impl == \"python\":\n fun = interpolate_face_attributes_python\n return lambda: fun(*args)\n\n\ndef _bm_forward_backward(N, S, F, K, D, impl):\n torch.manual_seed(0)\n device = torch.device(\"cuda\")\n data = _generate_data(N, S, K, F, D, device, requires_grad=True)\n args, grad = data[:3], data[3]\n torch.cuda.synchronize()\n if impl == \"cuda\":\n fun = interpolate_face_attributes\n elif impl == \"python\":\n fun = interpolate_face_attributes_python\n\n def run():\n out = fun(*args)\n out.backward(gradient=grad)\n\n return run\n\n\ndef bm_interpolate_face_attribues() -> None:\n # For now only benchmark on GPU\n if not torch.cuda.is_available():\n return\n\n Ns = [1, 4]\n Ss = [128]\n Ks = [1, 10, 40]\n Fs = [5000]\n Ds = [1, 3, 16]\n impls = [\"python\", \"cuda\"]\n test_cases = product(Ns, Ss, Ks, Fs, Ds, impls)\n kwargs_list = []\n for case in test_cases:\n N, S, K, F, D, impl = case\n kwargs_list.append({\"N\": N, \"S\": S, \"K\": K, \"F\": F, \"D\": D, \"impl\": impl})\n benchmark(_bm_forward, \"FORWARD\", kwargs_list, warmup_iters=3)\n benchmark(_bm_forward_backward, \"FORWARD+BACKWARD\", kwargs_list, warmup_iters=3)\n\n\nif __name__ == \"__main__\":\n bm_interpolate_face_attribues()\n", "#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.\nimport collections\nimport os\nimport pickle\nimport warnings\n\nimport hydra\nimport numpy as np\nimport torch\nfrom nerf.dataset import get_nerf_datasets, trivial_collate\nfrom nerf.nerf_renderer import RadianceFieldRenderer, visualize_nerf_outputs\nfrom nerf.stats import Stats\nfrom omegaconf import DictConfig\nfrom visdom import Visdom\n\n\nCONFIG_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"configs\")\n\n\[email protected](config_path=CONFIG_DIR, config_name=\"lego\")\ndef main(cfg: DictConfig):\n\n # Set the relevant seeds for reproducibility.\n np.random.seed(cfg.seed)\n torch.manual_seed(cfg.seed)\n\n # Device on which to run.\n if torch.cuda.is_available():\n device = \"cuda\"\n else:\n warnings.warn(\n \"Please note that although executing on CPU is supported,\"\n + \"the training is unlikely to finish in resonable time.\"\n )\n device = \"cpu\"\n\n # Initialize the Radiance Field model.\n model = RadianceFieldRenderer(\n image_size=cfg.data.image_size,\n n_pts_per_ray=cfg.raysampler.n_pts_per_ray,\n n_pts_per_ray_fine=cfg.raysampler.n_pts_per_ray,\n n_rays_per_image=cfg.raysampler.n_rays_per_image,\n min_depth=cfg.raysampler.min_depth,\n max_depth=cfg.raysampler.max_depth,\n stratified=cfg.raysampler.stratified,\n stratified_test=cfg.raysampler.stratified_test,\n chunk_size_test=cfg.raysampler.chunk_size_test,\n n_harmonic_functions_xyz=cfg.implicit_function.n_harmonic_functions_xyz,\n n_harmonic_functions_dir=cfg.implicit_function.n_harmonic_functions_dir,\n n_hidden_neurons_xyz=cfg.implicit_function.n_hidden_neurons_xyz,\n n_hidden_neurons_dir=cfg.implicit_function.n_hidden_neurons_dir,\n n_layers_xyz=cfg.implicit_function.n_layers_xyz,\n density_noise_std=cfg.implicit_function.density_noise_std,\n )\n\n # Move the model to the relevant device.\n model.to(device)\n\n # Init stats to None before loading.\n stats = None\n optimizer_state_dict = None\n start_epoch = 0\n\n checkpoint_path = os.path.join(hydra.utils.get_original_cwd(), cfg.checkpoint_path)\n if len(cfg.checkpoint_path) > 0:\n # Make the root of the experiment directory.\n checkpoint_dir = os.path.split(checkpoint_path)[0]\n os.makedirs(checkpoint_dir, exist_ok=True)\n\n # Resume training if requested.\n if cfg.resume and os.path.isfile(checkpoint_path):\n print(f\"Resuming from checkpoint {checkpoint_path}.\")\n loaded_data = torch.load(checkpoint_path)\n model.load_state_dict(loaded_data[\"model\"])\n stats = pickle.loads(loaded_data[\"stats\"])\n print(f\" => resuming from epoch {stats.epoch}.\")\n optimizer_state_dict = loaded_data[\"optimizer\"]\n start_epoch = stats.epoch\n\n # Initialize the optimizer.\n optimizer = torch.optim.Adam(\n model.parameters(),\n lr=cfg.optimizer.lr,\n )\n\n # Load the optimizer state dict in case we are resuming.\n if optimizer_state_dict is not None:\n optimizer.load_state_dict(optimizer_state_dict)\n optimizer.last_epoch = start_epoch\n\n # Init the stats object.\n if stats is None:\n stats = Stats(\n [\"loss\", \"mse_coarse\", \"mse_fine\", \"psnr_coarse\", \"psnr_fine\", \"sec/it\"],\n )\n\n # Learning rate scheduler setup.\n\n # Following the original code, we use exponential decay of the\n # learning rate: current_lr = base_lr * gamma ** (epoch / step_size)\n def lr_lambda(epoch):\n return cfg.optimizer.lr_scheduler_gamma ** (\n epoch / cfg.optimizer.lr_scheduler_step_size\n )\n\n # The learning rate scheduling is implemented with LambdaLR PyTorch scheduler.\n lr_scheduler = torch.optim.lr_scheduler.LambdaLR(\n optimizer, lr_lambda, last_epoch=start_epoch - 1, verbose=False\n )\n\n # Initialize the cache for storing variables needed for visulization.\n visuals_cache = collections.deque(maxlen=cfg.visualization.history_size)\n\n # Init the visualization visdom env.\n if cfg.visualization.visdom:\n viz = Visdom(\n server=cfg.visualization.visdom_server,\n port=cfg.visualization.visdom_port,\n use_incoming_socket=False,\n )\n else:\n viz = None\n\n # Load the training/validation data.\n train_dataset, val_dataset, _ = get_nerf_datasets(\n dataset_name=cfg.data.dataset_name,\n image_size=cfg.data.image_size,\n )\n\n if cfg.data.precache_rays:\n # Precache the projection rays.\n model.eval()\n with torch.no_grad():\n for dataset in (train_dataset, val_dataset):\n cache_cameras = [e[\"camera\"].to(device) for e in dataset]\n cache_camera_hashes = [e[\"camera_idx\"] for e in dataset]\n model.precache_rays(cache_cameras, cache_camera_hashes)\n\n train_dataloader = torch.utils.data.DataLoader(\n train_dataset,\n batch_size=1,\n shuffle=True,\n num_workers=0,\n collate_fn=trivial_collate,\n )\n\n # The validation dataloader is just an endless stream of random samples.\n val_dataloader = torch.utils.data.DataLoader(\n val_dataset,\n batch_size=1,\n num_workers=0,\n collate_fn=trivial_collate,\n sampler=torch.utils.data.RandomSampler(\n val_dataset,\n replacement=True,\n num_samples=cfg.optimizer.max_epochs,\n ),\n )\n\n # Set the model to the training mode.\n model.train()\n\n # Run the main training loop.\n for epoch in range(start_epoch, cfg.optimizer.max_epochs):\n stats.new_epoch() # Init a new epoch.\n for iteration, batch in enumerate(train_dataloader):\n image, camera, camera_idx = batch[0].values()\n image = image.to(device)\n camera = camera.to(device)\n\n optimizer.zero_grad()\n\n # Run the forward pass of the model.\n nerf_out, metrics = model(\n camera_idx if cfg.data.precache_rays else None,\n camera,\n image,\n )\n\n # The loss is a sum of coarse and fine MSEs\n loss = metrics[\"mse_coarse\"] + metrics[\"mse_fine\"]\n\n # Take the training step.\n loss.backward()\n optimizer.step()\n\n # Update stats with the current metrics.\n stats.update(\n {\"loss\": float(loss), **metrics},\n stat_set=\"train\",\n )\n\n if iteration % cfg.stats_print_interval == 0:\n stats.print(stat_set=\"train\")\n\n # Update the visualisatioon cache.\n visuals_cache.append(\n {\n \"camera\": camera.cpu(),\n \"camera_idx\": camera_idx,\n \"image\": image.cpu().detach(),\n \"rgb_fine\": nerf_out[\"rgb_fine\"].cpu().detach(),\n \"rgb_coarse\": nerf_out[\"rgb_coarse\"].cpu().detach(),\n \"rgb_gt\": nerf_out[\"rgb_gt\"].cpu().detach(),\n \"coarse_ray_bundle\": nerf_out[\"coarse_ray_bundle\"],\n }\n )\n\n # Adjust the learning rate.\n lr_scheduler.step()\n\n # Validation\n if epoch % cfg.validation_epoch_interval == 0 and epoch > 0:\n\n # Sample a validation camera/image.\n val_batch = next(val_dataloader.__iter__())\n val_image, val_camera, camera_idx = val_batch[0].values()\n val_image = val_image.to(device)\n val_camera = val_camera.to(device)\n\n # Activate eval mode of the model (allows to do a full rendering pass).\n model.eval()\n with torch.no_grad():\n val_nerf_out, val_metrics = model(\n camera_idx if cfg.data.precache_rays else None,\n val_camera,\n val_image,\n )\n\n # Update stats with the validation metrics.\n stats.update(val_metrics, stat_set=\"val\")\n stats.print(stat_set=\"val\")\n\n if viz is not None:\n # Plot that loss curves into visdom.\n stats.plot_stats(\n viz=viz,\n visdom_env=cfg.visualization.visdom_env,\n plot_file=None,\n )\n # Visualize the intermediate results.\n visualize_nerf_outputs(\n val_nerf_out, visuals_cache, viz, cfg.visualization.visdom_env\n )\n\n # Set the model back to train mode.\n model.train()\n\n # Checkpoint.\n if (\n epoch % cfg.checkpoint_epoch_interval == 0\n and len(cfg.checkpoint_path) > 0\n and epoch > 0\n ):\n print(f\"Storing checkpoint {checkpoint_path}.\")\n data_to_store = {\n \"model\": model.state_dict(),\n \"optimizer\": optimizer.state_dict(),\n \"stats\": pickle.dumps(stats),\n }\n torch.save(data_to_store, checkpoint_path)\n\n\nif __name__ == \"__main__\":\n main()\n", "# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.\n\n\"\"\"This module implements utility functions for loading .mtl files and textures.\"\"\"\nimport os\nimport warnings\nfrom typing import Dict, List, Optional, Tuple\n\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nfrom iopath.common.file_io import PathManager\nfrom pytorch3d.io.utils import _open_file, _read_image\n\n\ndef make_mesh_texture_atlas(\n material_properties: Dict,\n texture_images: Dict,\n face_material_names,\n faces_uvs: torch.Tensor,\n verts_uvs: torch.Tensor,\n texture_size: int,\n texture_wrap: Optional[str],\n) -> torch.Tensor:\n \"\"\"\n Given properties for materials defined in the .mtl file, and the face texture uv\n coordinates, construct an (F, R, R, 3) texture atlas where R is the texture_size\n and F is the number of faces in the mesh.\n\n Args:\n material_properties: dict of properties for each material. If a material\n does not have any properties it will have an emtpy dict.\n texture_images: dict of material names and texture images\n face_material_names: numpy array of the material name corresponding to each\n face. Faces which don't have an associated material will be an empty string.\n For these faces, a uniform white texture is assigned.\n faces_uvs: LongTensor of shape (F, 3,) giving the index into the verts_uvs for\n each face in the mesh.\n verts_uvs: FloatTensor of shape (V, 2) giving the uv coordinates for each vertex.\n texture_size: the resolution of the per face texture map returned by this function.\n Each face will have a texture map of shape (texture_size, texture_size, 3).\n texture_wrap: string, one of [\"repeat\", \"clamp\", None]\n If `texture_wrap=\"repeat\"` for uv values outside the range [0, 1] the integer part\n is ignored and a repeating pattern is formed.\n If `texture_wrap=\"clamp\"` the values are clamped to the range [0, 1].\n If None, do nothing.\n\n Returns:\n atlas: FloatTensor of shape (F, texture_size, texture_size, 3) giving the per\n face texture map.\n \"\"\"\n # Create an R x R texture map per face in the mesh\n R = texture_size\n F = faces_uvs.shape[0]\n\n # Initialize the per face texture map to a white color.\n # TODO: allow customization of this base color?\n atlas = torch.ones(size=(F, R, R, 3), dtype=torch.float32, device=faces_uvs.device)\n\n # Check for empty materials.\n if not material_properties and not texture_images:\n return atlas\n\n # Iterate through the material properties - not\n # all materials have texture images so this is\n # done first separately to the texture interpolation.\n for material_name, props in material_properties.items():\n # Bool to indicate which faces use this texture map.\n faces_material_ind = torch.from_numpy(face_material_names == material_name).to(\n faces_uvs.device\n )\n if faces_material_ind.sum() > 0:\n # For these faces, update the base color to the\n # diffuse material color.\n if \"diffuse_color\" not in props:\n continue\n atlas[faces_material_ind, ...] = props[\"diffuse_color\"][None, :]\n\n # If there are vertex texture coordinates, create an (F, 3, 2)\n # tensor of the vertex textures per face.\n faces_verts_uvs = verts_uvs[faces_uvs] if len(verts_uvs) > 0 else None\n\n # Some meshes only have material properties and no texture image.\n # In this case, return the atlas here.\n if faces_verts_uvs is None:\n return atlas\n\n if texture_wrap == \"repeat\":\n # If texture uv coordinates are outside the range [0, 1] follow\n # the convention GL_REPEAT in OpenGL i.e the integer part of the coordinate\n # will be ignored and a repeating pattern is formed.\n # Shapenet data uses this format see:\n # https://shapenet.org/qaforum/index.php?qa=15&qa_1=why-is-the-texture-coordinate-in-the-obj-file-not-in-the-range # noqa: B950\n if (faces_verts_uvs > 1).any() or (faces_verts_uvs < 0).any():\n msg = \"Texture UV coordinates outside the range [0, 1]. \\\n The integer part will be ignored to form a repeating pattern.\"\n warnings.warn(msg)\n faces_verts_uvs = faces_verts_uvs % 1\n elif texture_wrap == \"clamp\":\n # Clamp uv coordinates to the [0, 1] range.\n faces_verts_uvs = faces_verts_uvs.clamp(0.0, 1.0)\n\n # Iterate through the materials used in this mesh. Update the\n # texture atlas for the faces which use this material.\n # Faces without texture are white.\n for material_name, image in list(texture_images.items()):\n # Only use the RGB colors\n if image.shape[2] == 4:\n image = image[:, :, :3]\n\n # Reverse the image y direction\n image = torch.flip(image, [0]).type_as(faces_verts_uvs)\n\n # Bool to indicate which faces use this texture map.\n faces_material_ind = torch.from_numpy(face_material_names == material_name).to(\n faces_verts_uvs.device\n )\n\n # Find the subset of faces which use this texture with this texture image\n uvs_subset = faces_verts_uvs[faces_material_ind, :, :]\n\n # Update the texture atlas for the faces which use this texture.\n # TODO: should the texture map values be multiplied\n # by the diffuse material color (i.e. use *= as the atlas has\n # been initialized to the diffuse color)?. This is\n # not being done in SoftRas.\n atlas[faces_material_ind, :, :] = make_material_atlas(image, uvs_subset, R)\n\n return atlas\n\n\ndef make_material_atlas(\n image: torch.Tensor, faces_verts_uvs: torch.Tensor, texture_size: int\n) -> torch.Tensor:\n r\"\"\"\n Given a single texture image and the uv coordinates for all the\n face vertices, create a square texture map per face using\n the formulation from [1].\n\n For a triangle with vertices (v0, v1, v2) we can create a barycentric coordinate system\n with the x axis being the vector (v0 - v2) and the y axis being the vector (v1 - v2).\n The barycentric coordinates range from [0, 1] in the +x and +y direction so this creates\n a triangular texture space with vertices at (0, 1), (0, 0) and (1, 0).\n\n The per face texture map is of shape (texture_size, texture_size, 3)\n which is a square. To map a triangular texture to a square grid, each\n triangle is parametrized as follows (e.g. R = texture_size = 3):\n\n The triangle texture is first divided into RxR = 9 subtriangles which each\n map to one grid cell. The numbers in the grid cells and triangles show the mapping.\n\n ..code-block::python\n\n Triangular Texture Space:\n\n 1\n |\\\n |6 \\\n |____\\\n |\\ 7 |\\\n |3 \\ |4 \\\n |____\\|____\\\n |\\ 8 |\\ 5 |\\\n |0 \\ |1 \\ |2 \\\n |____\\|____\\|____\\\n 0 1\n\n Square per face texture map:\n\n R ____________________\n | | | |\n | 6 | 7 | 8 |\n |______|______|______|\n | | | |\n | 3 | 4 | 5 |\n |______|______|______|\n | | | |\n | 0 | 1 | 2 |\n |______|______|______|\n 0 R\n\n\n The barycentric coordinates of each grid cell are calculated using the\n xy coordinates:\n\n ..code-block::python\n\n The cartesian coordinates are:\n\n Grid 1:\n\n R ____________________\n | | | |\n | 20 | 21 | 22 |\n |______|______|______|\n | | | |\n | 10 | 11 | 12 |\n |______|______|______|\n | | | |\n | 00 | 01 | 02 |\n |______|______|______|\n 0 R\n\n where 02 means y = 0, x = 2\n\n Now consider this subset of the triangle which corresponds to\n grid cells 0 and 8:\n\n ..code-block::python\n\n 1/R ________\n |\\ 8 |\n | \\ |\n | 0 \\ |\n |_______\\|\n 0 1/R\n\n The centroids of the triangles are:\n 0: (1/3, 1/3) * 1/R\n 8: (2/3, 2/3) * 1/R\n\n For each grid cell we can now calculate the centroid `(c_y, c_x)`\n of the corresponding texture triangle:\n - if `(x + y) < R`, then offsett the centroid of\n triangle 0 by `(y, x) * (1/R)`\n - if `(x + y) > R`, then offset the centroid of\n triangle 8 by `((R-1-y), (R-1-x)) * (1/R)`.\n\n This is equivalent to updating the portion of Grid 1\n above the diagnonal, replacing `(y, x)` with `((R-1-y), (R-1-x))`:\n\n ..code-block::python\n\n R _____________________\n | | | |\n | 20 | 01 | 00 |\n |______|______|______|\n | | | |\n | 10 | 11 | 10 |\n |______|______|______|\n | | | |\n | 00 | 01 | 02 |\n |______|______|______|\n 0 R\n\n The barycentric coordinates (w0, w1, w2) are then given by:\n\n ..code-block::python\n\n w0 = c_x\n w1 = c_y\n w2 = 1- w0 - w1\n\n Args:\n image: FloatTensor of shape (H, W, 3)\n faces_verts_uvs: uv coordinates for each vertex in each face (F, 3, 2)\n texture_size: int\n\n Returns:\n atlas: a FloatTensor of shape (F, texture_size, texture_size, 3) giving a\n per face texture map.\n\n [1] Liu et al, 'Soft Rasterizer: A Differentiable Renderer for Image-based\n 3D Reasoning', ICCV 2019\n \"\"\"\n R = texture_size\n device = faces_verts_uvs.device\n rng = torch.arange(R, device=device)\n\n # Meshgrid returns (row, column) i.e (Y, X)\n # Change order to (X, Y) to make the grid.\n Y, X = torch.meshgrid(rng, rng)\n # pyre-fixme[28]: Unexpected keyword argument `axis`.\n grid = torch.stack([X, Y], axis=-1) # (R, R, 2)\n\n # Grid cells below the diagonal: x + y < R.\n below_diag = grid.sum(-1) < R\n\n # map a [0, R] grid -> to a [0, 1] barycentric coordinates of\n # the texture triangle centroids.\n bary = torch.zeros((R, R, 3), device=device) # (R, R, 3)\n slc = torch.arange(2, device=device)[:, None]\n # w0, w1\n bary[below_diag, slc] = ((grid[below_diag] + 1.0 / 3.0) / R).T\n # w0, w1 for above diagonal grid cells.\n # pyre-fixme[16]: `float` has no attribute `T`.\n bary[~below_diag, slc] = (((R - 1.0 - grid[~below_diag]) + 2.0 / 3.0) / R).T\n # w2 = 1. - w0 - w1\n bary[..., -1] = 1 - bary[..., :2].sum(dim=-1)\n\n # Calculate the uv position in the image for each pixel\n # in the per face texture map\n # (F, 1, 1, 3, 2) * (R, R, 3, 1) -> (F, R, R, 3, 2) -> (F, R, R, 2)\n uv_pos = (faces_verts_uvs[:, None, None] * bary[..., None]).sum(-2)\n\n # bi-linearly interpolate the textures from the images\n # using the uv coordinates given by uv_pos.\n textures = _bilinear_interpolation_vectorized(image, uv_pos)\n\n return textures\n\n\ndef _bilinear_interpolation_vectorized(\n image: torch.Tensor, grid: torch.Tensor\n) -> torch.Tensor:\n \"\"\"\n Bi linearly interpolate the image using the uv positions in the flow-field\n grid (following the naming conventions for torch.nn.functional.grid_sample).\n\n This implementation uses the same steps as in the SoftRas cuda kernel\n to make it easy to compare. This vectorized version requires less memory than\n _bilinear_interpolation_grid_sample but is slightly slower.\n If speed is an issue and the number of faces in the mesh and texture image sizes\n are small, consider using _bilinear_interpolation_grid_sample instead.\n\n Args:\n image: FloatTensor of shape (H, W, D) a single image/input tensor with D\n channels.\n grid: FloatTensor of shape (N, R, R, 2) giving the pixel locations of the\n points at which to sample a value in the image. The grid values must\n be in the range [0, 1]. u is the x direction and v is the y direction.\n\n Returns:\n out: FloatTensor of shape (N, H, W, D) giving the interpolated\n D dimensional value from image at each of the pixel locations in grid.\n\n \"\"\"\n H, W, _ = image.shape\n # Convert [0, 1] to the range [0, W-1] and [0, H-1]\n grid = grid * torch.tensor([W - 1, H - 1]).type_as(grid)\n weight_1 = grid - grid.int()\n weight_0 = 1.0 - weight_1\n\n grid_x, grid_y = grid.unbind(-1)\n y0 = grid_y.to(torch.int64)\n y1 = (grid_y + 1).to(torch.int64)\n x0 = grid_x.to(torch.int64)\n x1 = x0 + 1\n\n weight_x0, weight_y0 = weight_0.unbind(-1)\n weight_x1, weight_y1 = weight_1.unbind(-1)\n\n # Bi-linear interpolation\n # griditions = [[y, x], [(y+1), x]\n # [y, (x+1)], [(y+1), (x+1)]]\n # weights = [[wx0*wy0, wx0*wy1],\n # [wx1*wy0, wx1*wy1]]\n out = (\n image[y0, x0] * (weight_x0 * weight_y0)[..., None]\n + image[y1, x0] * (weight_x0 * weight_y1)[..., None]\n + image[y0, x1] * (weight_x1 * weight_y0)[..., None]\n + image[y1, x1] * (weight_x1 * weight_y1)[..., None]\n )\n\n return out\n\n\ndef _bilinear_interpolation_grid_sample(\n image: torch.Tensor, grid: torch.Tensor\n) -> torch.Tensor:\n \"\"\"\n Bi linearly interpolate the image using the uv positions in the flow-field\n grid (following the conventions for torch.nn.functional.grid_sample).\n\n This implementation is faster than _bilinear_interpolation_vectorized but\n requires more memory so can cause OOMs. If speed is an issue try this function\n instead.\n\n Args:\n image: FloatTensor of shape (H, W, D) a single image/input tensor with D\n channels.\n grid: FloatTensor of shape (N, R, R, 2) giving the pixel locations of the\n points at which to sample a value in the image. The grid values must\n be in the range [0, 1]. u is the x direction and v is the y direction.\n\n Returns:\n out: FloatTensor of shape (N, H, W, D) giving the interpolated\n D dimensional value from image at each of the pixel locations in grid.\n \"\"\"\n\n N = grid.shape[0]\n # convert [0, 1] to the range [-1, 1] expected by grid_sample.\n grid = grid * 2.0 - 1.0\n image = image.permute(2, 0, 1)[None, ...].expand(N, -1, -1, -1) # (N, 3, H, W)\n # Align_corners has to be set to True to match the output of the SoftRas\n # cuda kernel for bilinear sampling.\n out = F.grid_sample(image, grid, mode=\"bilinear\", align_corners=True)\n return out.permute(0, 2, 3, 1)\n\n\nMaterialProperties = Dict[str, Dict[str, torch.Tensor]]\nTextureFiles = Dict[str, str]\nTextureImages = Dict[str, torch.Tensor]\n\n\ndef _parse_mtl(\n f, path_manager: PathManager, device=\"cpu\"\n) -> Tuple[MaterialProperties, TextureFiles]:\n material_properties = {}\n texture_files = {}\n material_name = \"\"\n\n with _open_file(f, path_manager, \"r\") as f:\n for line in f:\n tokens = line.strip().split()\n if not tokens:\n continue\n if tokens[0] == \"newmtl\":\n material_name = tokens[1]\n material_properties[material_name] = {}\n elif tokens[0] == \"map_Kd\":\n # Diffuse texture map\n # Account for the case where filenames might have spaces\n filename = line.strip()[7:]\n texture_files[material_name] = filename\n elif tokens[0] == \"Kd\":\n # RGB diffuse reflectivity\n kd = np.array(tokens[1:4]).astype(np.float32)\n kd = torch.from_numpy(kd).to(device)\n material_properties[material_name][\"diffuse_color\"] = kd\n elif tokens[0] == \"Ka\":\n # RGB ambient reflectivity\n ka = np.array(tokens[1:4]).astype(np.float32)\n ka = torch.from_numpy(ka).to(device)\n material_properties[material_name][\"ambient_color\"] = ka\n elif tokens[0] == \"Ks\":\n # RGB specular reflectivity\n ks = np.array(tokens[1:4]).astype(np.float32)\n ks = torch.from_numpy(ks).to(device)\n material_properties[material_name][\"specular_color\"] = ks\n elif tokens[0] == \"Ns\":\n # Specular exponent\n ns = np.array(tokens[1:4]).astype(np.float32)\n ns = torch.from_numpy(ns).to(device)\n material_properties[material_name][\"shininess\"] = ns\n\n return material_properties, texture_files\n\n\ndef _load_texture_images(\n material_names: List[str],\n data_dir: str,\n material_properties: MaterialProperties,\n texture_files: TextureFiles,\n path_manager: PathManager,\n) -> Tuple[MaterialProperties, TextureImages]:\n final_material_properties = {}\n texture_images = {}\n\n # Only keep the materials referenced in the obj.\n for material_name in material_names:\n if material_name in texture_files:\n # Load the texture image.\n path = os.path.join(data_dir, texture_files[material_name])\n if os.path.isfile(path):\n image = (\n _read_image(path, path_manager=path_manager, format=\"RGB\") / 255.0\n )\n image = torch.from_numpy(image)\n texture_images[material_name] = image\n else:\n msg = f\"Texture file does not exist: {path}\"\n warnings.warn(msg)\n\n if material_name in material_properties:\n final_material_properties[material_name] = material_properties[\n material_name\n ]\n\n return final_material_properties, texture_images\n\n\ndef load_mtl(\n f,\n *,\n material_names: List[str],\n data_dir: str,\n device=\"cpu\",\n path_manager: PathManager,\n) -> Tuple[MaterialProperties, TextureImages]:\n \"\"\"\n Load texture images and material reflectivity values for ambient, diffuse\n and specular light (Ka, Kd, Ks, Ns).\n\n Args:\n f: a file-like object of the material information.\n material_names: a list of the material names found in the .obj file.\n data_dir: the directory where the material texture files are located.\n path_manager: PathManager for interpreting both f and material_names.\n\n Returns:\n material_properties: dict of properties for each material. If a material\n does not have any properties it will have an empty dict.\n {\n material_name_1: {\n \"ambient_color\": tensor of shape (1, 3),\n \"diffuse_color\": tensor of shape (1, 3),\n \"specular_color\": tensor of shape (1, 3),\n \"shininess\": tensor of shape (1)\n },\n material_name_2: {},\n ...\n }\n texture_images: dict of material names and texture images\n {\n material_name_1: (H, W, 3) image,\n ...\n }\n \"\"\"\n material_properties, texture_files = _parse_mtl(f, path_manager, device)\n return _load_texture_images(\n material_names,\n data_dir,\n material_properties,\n texture_files,\n path_manager=path_manager,\n )\n", "#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.\n\"\"\"\nThis example demonstrates camera parameter optimization with the plain\npulsar interface. For this, a reference image has been pre-generated\n(you can find it at `../../tests/pulsar/reference/examples_TestRenderer_test_cam.png`).\nThe same scene parameterization is loaded and the camera parameters\ndistorted. Gradient-based optimization is used to converge towards the\noriginal camera parameters.\nOutput: cam.gif.\n\"\"\"\nimport logging\nimport math\nfrom os import path\n\nimport cv2\nimport imageio\nimport numpy as np\nimport torch\nfrom pytorch3d.renderer.points.pulsar import Renderer\nfrom pytorch3d.transforms import axis_angle_to_matrix, matrix_to_rotation_6d\nfrom torch import nn, optim\n\n\nLOGGER = logging.getLogger(__name__)\nN_POINTS = 20\nWIDTH = 1_000\nHEIGHT = 1_000\nDEVICE = torch.device(\"cuda\")\n\n\nclass SceneModel(nn.Module):\n \"\"\"\n A simple scene model to demonstrate use of pulsar in PyTorch modules.\n\n The scene model is parameterized with sphere locations (vert_pos),\n channel content (vert_col), radiuses (vert_rad), camera position (cam_pos),\n camera rotation (cam_rot) and sensor focal length and width (cam_sensor).\n\n The forward method of the model renders this scene description. Any\n of these parameters could instead be passed as inputs to the forward\n method and come from a different model.\n \"\"\"\n\n def __init__(self):\n super(SceneModel, self).__init__()\n self.gamma = 0.1\n # Points.\n torch.manual_seed(1)\n vert_pos = torch.rand(N_POINTS, 3, dtype=torch.float32) * 10.0\n vert_pos[:, 2] += 25.0\n vert_pos[:, :2] -= 5.0\n self.register_parameter(\"vert_pos\", nn.Parameter(vert_pos, requires_grad=False))\n self.register_parameter(\n \"vert_col\",\n nn.Parameter(\n torch.rand(N_POINTS, 3, dtype=torch.float32), requires_grad=False\n ),\n )\n self.register_parameter(\n \"vert_rad\",\n nn.Parameter(\n torch.rand(N_POINTS, dtype=torch.float32), requires_grad=False\n ),\n )\n self.register_parameter(\n \"cam_pos\",\n nn.Parameter(\n torch.tensor([0.1, 0.1, 0.0], dtype=torch.float32), requires_grad=True\n ),\n )\n self.register_parameter(\n \"cam_rot\",\n # We're using the 6D rot. representation for better gradients.\n nn.Parameter(\n matrix_to_rotation_6d(\n axis_angle_to_matrix(\n torch.tensor(\n [\n [0.02, math.pi + 0.02, 0.01],\n ],\n dtype=torch.float32,\n )\n )\n )[0],\n requires_grad=True,\n ),\n )\n self.register_parameter(\n \"cam_sensor\",\n nn.Parameter(\n torch.tensor([4.8, 1.8], dtype=torch.float32), requires_grad=True\n ),\n )\n self.renderer = Renderer(WIDTH, HEIGHT, N_POINTS, right_handed_system=True)\n\n def forward(self):\n return self.renderer.forward(\n self.vert_pos,\n self.vert_col,\n self.vert_rad,\n torch.cat([self.cam_pos, self.cam_rot, self.cam_sensor]),\n self.gamma,\n 45.0,\n )\n\n\ndef cli():\n \"\"\"\n Camera optimization example using pulsar.\n\n Writes to `cam.gif`.\n \"\"\"\n LOGGER.info(\"Loading reference...\")\n # Load reference.\n ref = (\n torch.from_numpy(\n imageio.imread(\n \"../../tests/pulsar/reference/examples_TestRenderer_test_cam.png\"\n )[:, ::-1, :].copy()\n ).to(torch.float32)\n / 255.0\n ).to(DEVICE)\n # Set up model.\n model = SceneModel().to(DEVICE)\n # Optimizer.\n optimizer = optim.SGD(\n [\n {\"params\": [model.cam_pos], \"lr\": 1e-4}, # 1e-3\n {\"params\": [model.cam_rot], \"lr\": 5e-6},\n {\"params\": [model.cam_sensor], \"lr\": 1e-4},\n ]\n )\n\n LOGGER.info(\"Writing video to `%s`.\", path.abspath(\"cam.gif\"))\n writer = imageio.get_writer(\"cam.gif\", format=\"gif\", fps=25)\n\n # Optimize.\n for i in range(300):\n optimizer.zero_grad()\n result = model()\n # Visualize.\n result_im = (result.cpu().detach().numpy() * 255).astype(np.uint8)\n cv2.imshow(\"opt\", result_im[:, :, ::-1])\n writer.append_data(result_im)\n overlay_img = np.ascontiguousarray(\n ((result * 0.5 + ref * 0.5).cpu().detach().numpy() * 255).astype(np.uint8)[\n :, :, ::-1\n ]\n )\n overlay_img = cv2.putText(\n overlay_img,\n \"Step %d\" % (i),\n (10, 40),\n cv2.FONT_HERSHEY_SIMPLEX,\n 1,\n (0, 0, 0),\n 2,\n cv2.LINE_AA,\n False,\n )\n cv2.imshow(\"overlay\", overlay_img)\n cv2.waitKey(1)\n # Update.\n loss = ((result - ref) ** 2).sum()\n LOGGER.info(\"loss %d: %f\", i, loss.item())\n loss.backward()\n optimizer.step()\n writer.close()\n LOGGER.info(\"Done.\")\n\n\nif __name__ == \"__main__\":\n logging.basicConfig(level=logging.INFO)\n cli()\n", "# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.\n\nimport unittest\nfrom pathlib import Path\n\nimport numpy as np\nimport torch\nfrom common_testing import TestCaseMixin\nfrom pytorch3d.ops import points_alignment\nfrom pytorch3d.structures.pointclouds import Pointclouds\nfrom pytorch3d.transforms import rotation_conversions\n\n\ndef _apply_pcl_transformation(X, R, T, s=None):\n \"\"\"\n Apply a batch of similarity/rigid transformations, parametrized with\n rotation `R`, translation `T` and scale `s`, to an input batch of\n point clouds `X`.\n \"\"\"\n if isinstance(X, Pointclouds):\n num_points = X.num_points_per_cloud()\n X_t = X.points_padded()\n else:\n X_t = X\n\n if s is not None:\n X_t = s[:, None, None] * X_t\n\n X_t = torch.bmm(X_t, R) + T[:, None, :]\n\n if isinstance(X, Pointclouds):\n X_list = [x[:n_p] for x, n_p in zip(X_t, num_points)]\n X_t = Pointclouds(X_list)\n\n return X_t\n\n\nclass TestICP(TestCaseMixin, unittest.TestCase):\n def setUp(self) -> None:\n super().setUp()\n torch.manual_seed(42)\n np.random.seed(42)\n trimesh_results_path = Path(__file__).resolve().parent / \"data/icp_data.pth\"\n self.trimesh_results = torch.load(trimesh_results_path)\n\n @staticmethod\n def iterative_closest_point(\n batch_size=10,\n n_points_X=100,\n n_points_Y=100,\n dim=3,\n use_pointclouds=False,\n estimate_scale=False,\n ):\n\n device = torch.device(\"cuda:0\")\n\n # initialize a ground truth point cloud\n X, Y = [\n TestCorrespondingPointsAlignment.init_point_cloud(\n batch_size=batch_size,\n n_points=n_points,\n dim=dim,\n device=device,\n use_pointclouds=use_pointclouds,\n random_pcl_size=True,\n fix_seed=i,\n )\n for i, n_points in enumerate((n_points_X, n_points_Y))\n ]\n\n torch.cuda.synchronize()\n\n def run_iterative_closest_point():\n points_alignment.iterative_closest_point(\n X,\n Y,\n estimate_scale=estimate_scale,\n allow_reflection=False,\n verbose=False,\n max_iterations=100,\n relative_rmse_thr=1e-4,\n )\n torch.cuda.synchronize()\n\n return run_iterative_closest_point\n\n def test_init_transformation(self, batch_size=10):\n \"\"\"\n First runs a full ICP on a random problem. Then takes a given point\n in the history of ICP iteration transformations, initializes\n a second run of ICP with this transformation and checks whether\n both runs ended with the same solution.\n \"\"\"\n\n device = torch.device(\"cuda:0\")\n\n for dim in (2, 3, 11):\n for n_points_X in (30, 100):\n for n_points_Y in (30, 100):\n # initialize ground truth point clouds\n X, Y = [\n TestCorrespondingPointsAlignment.init_point_cloud(\n batch_size=batch_size,\n n_points=n_points,\n dim=dim,\n device=device,\n use_pointclouds=False,\n random_pcl_size=True,\n )\n for n_points in (n_points_X, n_points_Y)\n ]\n\n # run full icp\n (\n converged,\n _,\n Xt,\n (R, T, s),\n t_hist,\n ) = points_alignment.iterative_closest_point(\n X,\n Y,\n estimate_scale=False,\n allow_reflection=False,\n verbose=False,\n max_iterations=100,\n )\n\n # start from the solution after the third\n # iteration of the previous ICP\n t_init = t_hist[min(2, len(t_hist) - 1)]\n\n # rerun the ICP\n (\n converged_init,\n _,\n Xt_init,\n (R_init, T_init, s_init),\n t_hist_init,\n ) = points_alignment.iterative_closest_point(\n X,\n Y,\n init_transform=t_init,\n estimate_scale=False,\n allow_reflection=False,\n verbose=False,\n max_iterations=100,\n )\n\n # compare transformations and obtained clouds\n # check that both sets of transforms are the same\n atol = 3e-5\n self.assertClose(R_init, R, atol=atol)\n self.assertClose(T_init, T, atol=atol)\n self.assertClose(s_init, s, atol=atol)\n self.assertClose(Xt_init, Xt, atol=atol)\n\n def test_heterogenous_inputs(self, batch_size=10):\n \"\"\"\n Tests whether we get the same result when running ICP on\n a set of randomly-sized Pointclouds and on their padded versions.\n \"\"\"\n\n device = torch.device(\"cuda:0\")\n\n for estimate_scale in (True, False):\n for max_n_points in (10, 30, 100):\n # initialize ground truth point clouds\n X_pcl, Y_pcl = [\n TestCorrespondingPointsAlignment.init_point_cloud(\n batch_size=batch_size,\n n_points=max_n_points,\n dim=3,\n device=device,\n use_pointclouds=True,\n random_pcl_size=True,\n )\n for _ in range(2)\n ]\n\n # get the padded versions and their num of points\n X_padded = X_pcl.points_padded()\n Y_padded = Y_pcl.points_padded()\n n_points_X = X_pcl.num_points_per_cloud()\n n_points_Y = Y_pcl.num_points_per_cloud()\n\n # run icp with Pointlouds inputs\n (\n _,\n _,\n Xt_pcl,\n (R_pcl, T_pcl, s_pcl),\n _,\n ) = points_alignment.iterative_closest_point(\n X_pcl,\n Y_pcl,\n estimate_scale=estimate_scale,\n allow_reflection=False,\n verbose=False,\n max_iterations=100,\n )\n Xt_pcl = Xt_pcl.points_padded()\n\n # run icp with tensor inputs on each element\n # of the batch separately\n icp_results = [\n points_alignment.iterative_closest_point(\n X_[None, :n_X, :],\n Y_[None, :n_Y, :],\n estimate_scale=estimate_scale,\n allow_reflection=False,\n verbose=False,\n max_iterations=100,\n )\n for X_, Y_, n_X, n_Y in zip(\n X_padded, Y_padded, n_points_X, n_points_Y\n )\n ]\n\n # parse out the transformation results\n R, T, s = [\n torch.cat([x.RTs[i] for x in icp_results], dim=0) for i in range(3)\n ]\n\n # check that both sets of transforms are the same\n atol = 1e-5\n self.assertClose(R_pcl, R, atol=atol)\n self.assertClose(T_pcl, T, atol=atol)\n self.assertClose(s_pcl, s, atol=atol)\n\n # compare the transformed point clouds\n for pcli in range(batch_size):\n nX = n_points_X[pcli]\n Xt_ = icp_results[pcli].Xt[0, :nX]\n Xt_pcl_ = Xt_pcl[pcli][:nX]\n self.assertClose(Xt_pcl_, Xt_, atol=atol)\n\n def test_compare_with_trimesh(self):\n \"\"\"\n Compares the outputs of `iterative_closest_point` with the results\n of `trimesh.registration.icp` from the `trimesh` python package:\n https://github.com/mikedh/trimesh\n\n We have run `trimesh.registration.icp` on several random problems\n with different point cloud sizes. The results of trimesh, together with\n the randomly generated input clouds are loaded in the constructor of\n this class and this test compares the loaded results to our runs.\n \"\"\"\n for n_points_X in (10, 20, 50, 100):\n for n_points_Y in (10, 20, 50, 100):\n self._compare_with_trimesh(n_points_X=n_points_X, n_points_Y=n_points_Y)\n\n def _compare_with_trimesh(\n self, n_points_X=100, n_points_Y=100, estimate_scale=False\n ):\n \"\"\"\n Executes a single test for `iterative_closest_point` for a\n specific setting of the inputs / outputs. Compares the result with\n the result of the trimesh package on the same input data.\n \"\"\"\n\n device = torch.device(\"cuda:0\")\n\n # load the trimesh results and the initial point clouds for icp\n key = (int(n_points_X), int(n_points_Y), int(estimate_scale))\n X, Y, R_trimesh, T_trimesh, s_trimesh = [\n x.to(device) for x in self.trimesh_results[key]\n ]\n\n # run the icp algorithm\n (\n converged,\n _,\n _,\n (R_ours, T_ours, s_ours),\n _,\n ) = points_alignment.iterative_closest_point(\n X,\n Y,\n estimate_scale=estimate_scale,\n allow_reflection=False,\n verbose=False,\n max_iterations=100,\n )\n\n # check that we have the same transformation\n # and that the icp converged\n atol = 1e-5\n self.assertClose(R_ours, R_trimesh, atol=atol)\n self.assertClose(T_ours, T_trimesh, atol=atol)\n self.assertClose(s_ours, s_trimesh, atol=atol)\n self.assertTrue(converged)\n\n\nclass TestCorrespondingPointsAlignment(TestCaseMixin, unittest.TestCase):\n def setUp(self) -> None:\n super().setUp()\n torch.manual_seed(42)\n np.random.seed(42)\n\n @staticmethod\n def random_rotation(batch_size, dim, device=None):\n \"\"\"\n Generates a batch of random `dim`-dimensional rotation matrices.\n \"\"\"\n if dim == 3:\n R = rotation_conversions.random_rotations(batch_size, device=device)\n else:\n # generate random rotation matrices with orthogonalization of\n # random normal square matrices, followed by a transformation\n # that ensures determinant(R)==1\n H = torch.randn(batch_size, dim, dim, dtype=torch.float32, device=device)\n U, _, V = torch.svd(H)\n E = torch.eye(dim, dtype=torch.float32, device=device)[None].repeat(\n batch_size, 1, 1\n )\n E[:, -1, -1] = torch.det(torch.bmm(U, V.transpose(2, 1)))\n R = torch.bmm(torch.bmm(U, E), V.transpose(2, 1))\n assert torch.allclose(torch.det(R), R.new_ones(batch_size), atol=1e-4)\n\n return R\n\n @staticmethod\n def init_point_cloud(\n batch_size=10,\n n_points=1000,\n dim=3,\n device=None,\n use_pointclouds=False,\n random_pcl_size=True,\n fix_seed=None,\n ):\n \"\"\"\n Generate a batch of normally distributed point clouds.\n \"\"\"\n\n if fix_seed is not None:\n # make sure we always generate the same pointcloud\n seed = torch.random.get_rng_state()\n torch.manual_seed(fix_seed)\n\n if use_pointclouds:\n assert dim == 3, \"Pointclouds support only 3-dim points.\"\n # generate a `batch_size` point clouds with number of points\n # between 4 and `n_points`\n if random_pcl_size:\n n_points_per_batch = torch.randint(\n low=4,\n high=n_points,\n size=(batch_size,),\n device=device,\n dtype=torch.int64,\n )\n X_list = [\n torch.randn(int(n_pt), dim, device=device, dtype=torch.float32)\n for n_pt in n_points_per_batch\n ]\n X = Pointclouds(X_list)\n else:\n X = torch.randn(\n batch_size, n_points, dim, device=device, dtype=torch.float32\n )\n X = Pointclouds(list(X))\n else:\n X = torch.randn(\n batch_size, n_points, dim, device=device, dtype=torch.float32\n )\n\n if fix_seed:\n torch.random.set_rng_state(seed)\n\n return X\n\n @staticmethod\n def generate_pcl_transformation(\n batch_size=10, scale=False, reflect=False, dim=3, device=None\n ):\n \"\"\"\n Generate a batch of random rigid/similarity transformations.\n \"\"\"\n R = TestCorrespondingPointsAlignment.random_rotation(\n batch_size, dim, device=device\n )\n T = torch.randn(batch_size, dim, dtype=torch.float32, device=device)\n if scale:\n s = torch.rand(batch_size, dtype=torch.float32, device=device) + 0.1\n else:\n s = torch.ones(batch_size, dtype=torch.float32, device=device)\n\n return R, T, s\n\n @staticmethod\n def generate_random_reflection(batch_size=10, dim=3, device=None):\n \"\"\"\n Generate a batch of reflection matrices of shape (batch_size, dim, dim),\n where M_i is an identity matrix with one random entry on the\n diagonal equal to -1.\n \"\"\"\n # randomly select one of the dimensions to reflect for each\n # element in the batch\n dim_to_reflect = torch.randint(\n low=0, high=dim, size=(batch_size,), device=device, dtype=torch.int64\n )\n\n # convert dim_to_reflect to a batch of reflection matrices M\n M = torch.diag_embed(\n (\n dim_to_reflect[:, None]\n != torch.arange(dim, device=device, dtype=torch.float32)\n ).float()\n * 2\n - 1,\n dim1=1,\n dim2=2,\n )\n\n return M\n\n @staticmethod\n def corresponding_points_alignment(\n batch_size=10,\n n_points=100,\n dim=3,\n use_pointclouds=False,\n estimate_scale=False,\n allow_reflection=False,\n reflect=False,\n random_weights=False,\n ):\n\n device = torch.device(\"cuda:0\")\n\n # initialize a ground truth point cloud\n X = TestCorrespondingPointsAlignment.init_point_cloud(\n batch_size=batch_size,\n n_points=n_points,\n dim=dim,\n device=device,\n use_pointclouds=use_pointclouds,\n random_pcl_size=True,\n )\n\n # generate the true transformation\n R, T, s = TestCorrespondingPointsAlignment.generate_pcl_transformation(\n batch_size=batch_size,\n scale=estimate_scale,\n reflect=reflect,\n dim=dim,\n device=device,\n )\n\n # apply the generated transformation to the generated\n # point cloud X\n X_t = _apply_pcl_transformation(X, R, T, s=s)\n\n weights = None\n if random_weights:\n template = X.points_padded() if use_pointclouds else X\n weights = torch.rand_like(template[:, :, 0])\n weights = weights / weights.sum(dim=1, keepdim=True)\n # zero out some weights as zero weights are a common use case\n # this guarantees there are no zero weight\n weights *= (weights * template.size()[1] > 0.3).to(weights)\n if use_pointclouds: # convert to List[Tensor]\n weights = [\n w[:npts] for w, npts in zip(weights, X.num_points_per_cloud())\n ]\n\n torch.cuda.synchronize()\n\n def run_corresponding_points_alignment():\n points_alignment.corresponding_points_alignment(\n X,\n X_t,\n weights,\n allow_reflection=allow_reflection,\n estimate_scale=estimate_scale,\n )\n torch.cuda.synchronize()\n\n return run_corresponding_points_alignment\n\n def test_corresponding_points_alignment(self, batch_size=10):\n \"\"\"\n Tests whether we can estimate a rigid/similarity motion between\n a randomly initialized point cloud and its randomly transformed version.\n\n The tests are done for all possible combinations\n of the following boolean flags:\n - estimate_scale ... Estimate also a scaling component of\n the transformation.\n - reflect ... The ground truth orthonormal part of the generated\n transformation is a reflection (det==-1).\n - allow_reflection ... If True, the orthonormal matrix of the\n estimated transformation is allowed to be\n a reflection (det==-1).\n - use_pointclouds ... If True, passes the Pointclouds objects\n to corresponding_points_alignment.\n \"\"\"\n self.skipTest(\"Temporarily disabled pending investigation\")\n # run this for several different point cloud sizes\n for n_points in (100, 3, 2, 1):\n # run this for several different dimensionalities\n for dim in range(2, 10):\n # switches whether we should use the Pointclouds inputs\n use_point_clouds_cases = (\n (True, False) if dim == 3 and n_points > 3 else (False,)\n )\n for random_weights in (False, True):\n for use_pointclouds in use_point_clouds_cases:\n for estimate_scale in (False, True):\n for reflect in (False, True):\n for allow_reflection in (False, True):\n self._test_single_corresponding_points_alignment(\n batch_size=10,\n n_points=n_points,\n dim=dim,\n use_pointclouds=use_pointclouds,\n estimate_scale=estimate_scale,\n reflect=reflect,\n allow_reflection=allow_reflection,\n random_weights=random_weights,\n )\n\n def _test_single_corresponding_points_alignment(\n self,\n batch_size=10,\n n_points=100,\n dim=3,\n use_pointclouds=False,\n estimate_scale=False,\n reflect=False,\n allow_reflection=False,\n random_weights=False,\n ):\n \"\"\"\n Executes a single test for `corresponding_points_alignment` for a\n specific setting of the inputs / outputs.\n \"\"\"\n\n device = torch.device(\"cuda:0\")\n\n # initialize the a ground truth point cloud\n X = TestCorrespondingPointsAlignment.init_point_cloud(\n batch_size=batch_size,\n n_points=n_points,\n dim=dim,\n device=device,\n use_pointclouds=use_pointclouds,\n random_pcl_size=True,\n )\n\n # generate the true transformation\n R, T, s = TestCorrespondingPointsAlignment.generate_pcl_transformation(\n batch_size=batch_size,\n scale=estimate_scale,\n reflect=reflect,\n dim=dim,\n device=device,\n )\n\n if reflect:\n # generate random reflection M and apply to the rotations\n M = TestCorrespondingPointsAlignment.generate_random_reflection(\n batch_size=batch_size, dim=dim, device=device\n )\n R = torch.bmm(M, R)\n\n weights = None\n if random_weights:\n template = X.points_padded() if use_pointclouds else X\n weights = torch.rand_like(template[:, :, 0])\n weights = weights / weights.sum(dim=1, keepdim=True)\n # zero out some weights as zero weights are a common use case\n # this guarantees there are no zero weight\n weights *= (weights * template.size()[1] > 0.3).to(weights)\n if use_pointclouds: # convert to List[Tensor]\n weights = [\n w[:npts] for w, npts in zip(weights, X.num_points_per_cloud())\n ]\n\n # apply the generated transformation to the generated\n # point cloud X\n X_t = _apply_pcl_transformation(X, R, T, s=s)\n\n # run the CorrespondingPointsAlignment algorithm\n R_est, T_est, s_est = points_alignment.corresponding_points_alignment(\n X,\n X_t,\n weights,\n allow_reflection=allow_reflection,\n estimate_scale=estimate_scale,\n )\n\n assert_error_message = (\n f\"Corresponding_points_alignment assertion failure for \"\n f\"n_points={n_points}, \"\n f\"dim={dim}, \"\n f\"use_pointclouds={use_pointclouds}, \"\n f\"estimate_scale={estimate_scale}, \"\n f\"reflect={reflect}, \"\n f\"allow_reflection={allow_reflection},\"\n f\"random_weights={random_weights}.\"\n )\n\n # if we test the weighted case, check that weights help with noise\n if random_weights and not use_pointclouds and n_points >= (dim + 10):\n # add noise to 20% points with smallest weight\n X_noisy = X_t.clone()\n _, mink_idx = torch.topk(-weights, int(n_points * 0.2), dim=1)\n mink_idx = mink_idx[:, :, None].expand(-1, -1, X_t.shape[-1])\n X_noisy.scatter_add_(\n 1, mink_idx, 0.3 * torch.randn_like(mink_idx, dtype=X_t.dtype)\n )\n\n def align_and_get_mse(weights_):\n R_n, T_n, s_n = points_alignment.corresponding_points_alignment(\n X_noisy,\n X_t,\n weights_,\n allow_reflection=allow_reflection,\n estimate_scale=estimate_scale,\n )\n\n X_t_est = _apply_pcl_transformation(X_noisy, R_n, T_n, s=s_n)\n\n return (((X_t_est - X_t) * weights[..., None]) ** 2).sum(\n dim=(1, 2)\n ) / weights.sum(dim=-1)\n\n # check that using weights leads to lower weighted_MSE(X_noisy, X_t)\n self.assertTrue(\n torch.all(align_and_get_mse(weights) <= align_and_get_mse(None))\n )\n\n if reflect and not allow_reflection:\n # check that all rotations have det=1\n self._assert_all_close(\n torch.det(R_est), R_est.new_ones(batch_size), assert_error_message\n )\n\n else:\n # mask out inputs with too few non-degenerate points for assertions\n w = (\n torch.ones_like(R_est[:, 0, 0])\n if weights is None or n_points >= dim + 10\n else (weights > 0.0).all(dim=1).to(R_est)\n )\n # check that the estimated tranformation is the same\n # as the ground truth\n if n_points >= (dim + 1):\n # the checks on transforms apply only when\n # the problem setup is unambiguous\n msg = assert_error_message\n self._assert_all_close(R_est, R, msg, w[:, None, None], atol=1e-5)\n self._assert_all_close(T_est, T, msg, w[:, None])\n self._assert_all_close(s_est, s, msg, w)\n\n # check that the orthonormal part of the\n # transformation has a correct determinant (+1/-1)\n desired_det = R_est.new_ones(batch_size)\n if reflect:\n desired_det *= -1.0\n self._assert_all_close(torch.det(R_est), desired_det, msg, w)\n\n # check that the transformed point cloud\n # X matches X_t\n X_t_est = _apply_pcl_transformation(X, R_est, T_est, s=s_est)\n self._assert_all_close(\n X_t, X_t_est, assert_error_message, w[:, None, None], atol=1e-5\n )\n\n def _assert_all_close(self, a_, b_, err_message, weights=None, atol=1e-6):\n if isinstance(a_, Pointclouds):\n a_ = a_.points_packed()\n if isinstance(b_, Pointclouds):\n b_ = b_.points_packed()\n if weights is None:\n self.assertClose(a_, b_, atol=atol, msg=err_message)\n else:\n self.assertClose(a_ * weights, b_ * weights, atol=atol, msg=err_message)\n", "# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.\nimport unittest\n\nimport numpy as np\nimport torch\nfrom common_testing import TestCaseMixin\nfrom pytorch3d.renderer import (\n BlendParams,\n EmissionAbsorptionRaymarcher,\n GridRaysampler,\n ImplicitRenderer,\n Materials,\n MeshRasterizer,\n MeshRenderer,\n MonteCarloRaysampler,\n NDCGridRaysampler,\n PointLights,\n RasterizationSettings,\n RayBundle,\n SoftPhongShader,\n TexturesVertex,\n ray_bundle_to_ray_points,\n)\nfrom pytorch3d.structures import Meshes\nfrom pytorch3d.utils import ico_sphere\nfrom test_render_volumes import init_cameras\n\n\nDEBUG = False\nif DEBUG:\n import os\n import tempfile\n\n from PIL import Image\n\n\ndef spherical_volumetric_function(\n ray_bundle: RayBundle,\n sphere_centroid: torch.Tensor,\n sphere_diameter: float,\n **kwargs,\n):\n \"\"\"\n Volumetric function of a simple RGB sphere with diameter `sphere_diameter`\n and centroid `sphere_centroid`.\n \"\"\"\n # convert the ray bundle to world points\n rays_points_world = ray_bundle_to_ray_points(ray_bundle)\n batch_size = rays_points_world.shape[0]\n\n # surface_vectors = vectors from world coords towards the sphere centroid\n surface_vectors = (\n rays_points_world.view(batch_size, -1, 3) - sphere_centroid[:, None]\n )\n\n # the squared distance of each ray point to the centroid of the sphere\n surface_dist = (\n (surface_vectors ** 2)\n .sum(-1, keepdim=True)\n .view(*rays_points_world.shape[:-1], 1)\n )\n\n # set all ray densities within the sphere_diameter distance from the centroid to 1\n rays_densities = torch.sigmoid(-100.0 * (surface_dist - sphere_diameter ** 2))\n\n # ray colors are proportional to the normalized surface_vectors\n rays_features = (\n torch.nn.functional.normalize(\n surface_vectors.view(rays_points_world.shape), dim=-1\n )\n * 0.5\n + 0.5\n )\n\n return rays_densities, rays_features\n\n\nclass TestRenderImplicit(TestCaseMixin, unittest.TestCase):\n def setUp(self) -> None:\n super().setUp()\n torch.manual_seed(42)\n np.random.seed(42)\n\n @staticmethod\n def renderer(\n batch_size=10,\n raymarcher_type=EmissionAbsorptionRaymarcher,\n n_rays_per_image=10,\n n_pts_per_ray=10,\n sphere_diameter=0.75,\n ):\n # generate NDC camera extrinsics and intrinsics\n cameras = init_cameras(batch_size, image_size=None, ndc=True)\n\n # get rand offset of the volume\n sphere_centroid = torch.randn(batch_size, 3, device=cameras.device) * 0.1\n\n # init the mc raysampler\n raysampler = MonteCarloRaysampler(\n min_x=-1.0,\n max_x=1.0,\n min_y=-1.0,\n max_y=1.0,\n n_rays_per_image=n_rays_per_image,\n n_pts_per_ray=n_pts_per_ray,\n min_depth=0.1,\n max_depth=2.0,\n ).to(cameras.device)\n\n # get the raymarcher\n raymarcher = raymarcher_type()\n\n # get the implicit renderer\n renderer = ImplicitRenderer(raysampler=raysampler, raymarcher=raymarcher)\n\n def run_renderer():\n renderer(\n cameras=cameras,\n volumetric_function=spherical_volumetric_function,\n sphere_centroid=sphere_centroid,\n sphere_diameter=sphere_diameter,\n )\n\n return run_renderer\n\n def test_input_types(self):\n \"\"\"\n Check that ValueErrors are thrown where expected.\n \"\"\"\n # check the constructor\n for bad_raysampler in (None, 5, []):\n for bad_raymarcher in (None, 5, []):\n with self.assertRaises(ValueError):\n ImplicitRenderer(\n raysampler=bad_raysampler, raymarcher=bad_raymarcher\n )\n\n # init a trivial renderer\n renderer = ImplicitRenderer(\n raysampler=NDCGridRaysampler(\n image_width=100,\n image_height=100,\n n_pts_per_ray=10,\n min_depth=0.1,\n max_depth=1.0,\n ),\n raymarcher=EmissionAbsorptionRaymarcher(),\n )\n\n # get default cameras\n cameras = init_cameras()\n\n for bad_volumetric_function in (None, 5, []):\n with self.assertRaises(ValueError):\n renderer(cameras=cameras, volumetric_function=bad_volumetric_function)\n\n def test_compare_with_meshes_renderer(\n self, batch_size=11, image_size=100, sphere_diameter=0.6\n ):\n \"\"\"\n Generate a spherical RGB volumetric function and its corresponding mesh\n and check whether MeshesRenderer returns the same images as the\n corresponding ImplicitRenderer.\n \"\"\"\n\n # generate NDC camera extrinsics and intrinsics\n cameras = init_cameras(\n batch_size, image_size=[image_size, image_size], ndc=True\n )\n\n # get rand offset of the volume\n sphere_centroid = torch.randn(batch_size, 3, device=cameras.device) * 0.1\n sphere_centroid.requires_grad = True\n\n # init the grid raysampler with the ndc grid\n raysampler = NDCGridRaysampler(\n image_width=image_size,\n image_height=image_size,\n n_pts_per_ray=256,\n min_depth=0.1,\n max_depth=2.0,\n )\n\n # get the EA raymarcher\n raymarcher = EmissionAbsorptionRaymarcher()\n\n # jitter the camera intrinsics a bit for each render\n cameras_randomized = cameras.clone()\n cameras_randomized.principal_point = (\n torch.randn_like(cameras.principal_point) * 0.3\n )\n cameras_randomized.focal_length = (\n cameras.focal_length + torch.randn_like(cameras.focal_length) * 0.2\n )\n\n # the list of differentiable camera vars\n cam_vars = (\"R\", \"T\", \"focal_length\", \"principal_point\")\n # enable the gradient caching for the camera variables\n for cam_var in cam_vars:\n getattr(cameras_randomized, cam_var).requires_grad = True\n\n # get the implicit renderer\n images_opacities = ImplicitRenderer(\n raysampler=raysampler, raymarcher=raymarcher\n )(\n cameras=cameras_randomized,\n volumetric_function=spherical_volumetric_function,\n sphere_centroid=sphere_centroid,\n sphere_diameter=sphere_diameter,\n )[\n 0\n ]\n\n # check that the renderer does not erase gradients\n loss = images_opacities.sum()\n loss.backward()\n for check_var in (\n *[getattr(cameras_randomized, cam_var) for cam_var in cam_vars],\n sphere_centroid,\n ):\n self.assertIsNotNone(check_var.grad)\n\n # instantiate the corresponding spherical mesh\n ico = ico_sphere(level=4, device=cameras.device).extend(batch_size)\n verts = (\n torch.nn.functional.normalize(ico.verts_padded(), dim=-1) * sphere_diameter\n + sphere_centroid[:, None]\n )\n meshes = Meshes(\n verts=verts,\n faces=ico.faces_padded(),\n textures=TexturesVertex(\n verts_features=(\n torch.nn.functional.normalize(verts, dim=-1) * 0.5 + 0.5\n )\n ),\n )\n\n # instantiate the corresponding mesh renderer\n lights = PointLights(device=cameras.device, location=[[0.0, 0.0, 0.0]])\n renderer_textured = MeshRenderer(\n rasterizer=MeshRasterizer(\n cameras=cameras_randomized,\n raster_settings=RasterizationSettings(\n image_size=image_size, blur_radius=1e-3, faces_per_pixel=10\n ),\n ),\n shader=SoftPhongShader(\n device=cameras.device,\n cameras=cameras_randomized,\n lights=lights,\n materials=Materials(\n ambient_color=((2.0, 2.0, 2.0),),\n diffuse_color=((0.0, 0.0, 0.0),),\n specular_color=((0.0, 0.0, 0.0),),\n shininess=64,\n device=cameras.device,\n ),\n blend_params=BlendParams(\n sigma=1e-3, gamma=1e-4, background_color=(0.0, 0.0, 0.0)\n ),\n ),\n )\n\n # get the mesh render\n images_opacities_meshes = renderer_textured(\n meshes, cameras=cameras_randomized, lights=lights\n )\n\n if DEBUG:\n outdir = tempfile.gettempdir() + \"/test_implicit_vs_mesh_renderer\"\n os.makedirs(outdir, exist_ok=True)\n\n frames = []\n for (image_opacity, image_opacity_mesh) in zip(\n images_opacities, images_opacities_meshes\n ):\n image, opacity = image_opacity.split([3, 1], dim=-1)\n image_mesh, opacity_mesh = image_opacity_mesh.split([3, 1], dim=-1)\n diff_image = (\n ((image - image_mesh) * 0.5 + 0.5)\n .mean(dim=2, keepdim=True)\n .repeat(1, 1, 3)\n )\n image_pil = Image.fromarray(\n (\n torch.cat(\n (\n image,\n image_mesh,\n diff_image,\n opacity.repeat(1, 1, 3),\n opacity_mesh.repeat(1, 1, 3),\n ),\n dim=1,\n )\n .detach()\n .cpu()\n .numpy()\n * 255.0\n ).astype(np.uint8)\n )\n frames.append(image_pil)\n\n # export gif\n outfile = os.path.join(outdir, \"implicit_vs_mesh_render.gif\")\n frames[0].save(\n outfile,\n save_all=True,\n append_images=frames[1:],\n duration=batch_size // 15,\n loop=0,\n )\n print(f\"exported {outfile}\")\n\n # export concatenated frames\n outfile_cat = os.path.join(outdir, \"implicit_vs_mesh_render.png\")\n Image.fromarray(np.concatenate([np.array(f) for f in frames], axis=0)).save(\n outfile_cat\n )\n print(f\"exported {outfile_cat}\")\n\n # compare the renders\n diff = (images_opacities - images_opacities_meshes).abs().mean(dim=-1)\n mu_diff = diff.mean(dim=(1, 2))\n std_diff = diff.std(dim=(1, 2))\n self.assertClose(mu_diff, torch.zeros_like(mu_diff), atol=5e-2)\n self.assertClose(std_diff, torch.zeros_like(std_diff), atol=6e-2)\n\n def test_rotating_gif(\n self, n_frames=50, fps=15, image_size=(100, 100), sphere_diameter=0.5\n ):\n \"\"\"\n Render a gif animation of a rotating sphere (runs only if `DEBUG==True`).\n \"\"\"\n\n if not DEBUG:\n # do not run this if debug is False\n return\n\n # generate camera extrinsics and intrinsics\n cameras = init_cameras(n_frames, image_size=image_size)\n\n # init the grid raysampler\n raysampler = GridRaysampler(\n min_x=0.5,\n max_x=image_size[1] - 0.5,\n min_y=0.5,\n max_y=image_size[0] - 0.5,\n image_width=image_size[1],\n image_height=image_size[0],\n n_pts_per_ray=256,\n min_depth=0.1,\n max_depth=2.0,\n )\n\n # get the EA raymarcher\n raymarcher = EmissionAbsorptionRaymarcher()\n\n # get the implicit render\n renderer = ImplicitRenderer(raysampler=raysampler, raymarcher=raymarcher)\n\n # get the (0) centroid of the sphere\n sphere_centroid = torch.zeros(n_frames, 3, device=cameras.device) * 0.1\n\n # run the renderer\n images_opacities = renderer(\n cameras=cameras,\n volumetric_function=spherical_volumetric_function,\n sphere_centroid=sphere_centroid,\n sphere_diameter=sphere_diameter,\n )[0]\n\n # split output to the alpha channel and rendered images\n images, opacities = images_opacities[..., :3], images_opacities[..., 3]\n\n # export the gif\n outdir = tempfile.gettempdir() + \"/test_implicit_renderer_gifs\"\n os.makedirs(outdir, exist_ok=True)\n frames = []\n for image, opacity in zip(images, opacities):\n image_pil = Image.fromarray(\n (\n torch.cat(\n (image, opacity[..., None].clamp(0.0, 1.0).repeat(1, 1, 3)),\n dim=1,\n )\n .detach()\n .cpu()\n .numpy()\n * 255.0\n ).astype(np.uint8)\n )\n frames.append(image_pil)\n outfile = os.path.join(outdir, \"rotating_sphere.gif\")\n frames[0].save(\n outfile,\n save_all=True,\n append_images=frames[1:],\n duration=n_frames // fps,\n loop=0,\n )\n print(f\"exported {outfile}\")\n", "#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.\n\"\"\"\nThis example demonstrates the most trivial, direct interface of the pulsar\nsphere renderer. It renders and saves an image with 10 random spheres.\nOutput: basic.png.\n\"\"\"\nimport logging\nimport math\nfrom os import path\n\nimport imageio\nimport torch\nfrom pytorch3d.renderer.points.pulsar import Renderer\n\n\nLOGGER = logging.getLogger(__name__)\n\n\ndef cli():\n \"\"\"\n Basic example for the pulsar sphere renderer.\n\n Writes to `basic.png`.\n \"\"\"\n LOGGER.info(\"Rendering on GPU...\")\n torch.manual_seed(1)\n n_points = 10\n width = 1_000\n height = 1_000\n device = torch.device(\"cuda\")\n # The PyTorch3D system is right handed; in pulsar you can choose the handedness.\n # For easy reproducibility we use a right handed coordinate system here.\n renderer = Renderer(width, height, n_points, right_handed_system=True).to(device)\n # Generate sample data.\n vert_pos = torch.rand(n_points, 3, dtype=torch.float32, device=device) * 10.0\n vert_pos[:, 2] += 25.0\n vert_pos[:, :2] -= 5.0\n vert_col = torch.rand(n_points, 3, dtype=torch.float32, device=device)\n vert_rad = torch.rand(n_points, dtype=torch.float32, device=device)\n cam_params = torch.tensor(\n [\n 0.0,\n 0.0,\n 0.0, # Position 0, 0, 0 (x, y, z).\n 0.0,\n math.pi, # Because of the right handed system, the camera must look 'back'.\n 0.0, # Rotation 0, 0, 0 (in axis-angle format).\n 5.0, # Focal length in world size.\n 2.0, # Sensor size in world size.\n ],\n dtype=torch.float32,\n device=device,\n )\n # Render.\n image = renderer(\n vert_pos,\n vert_col,\n vert_rad,\n cam_params,\n 1.0e-1, # Renderer blending parameter gamma, in [1., 1e-5].\n 45.0, # Maximum depth.\n )\n LOGGER.info(\"Writing image to `%s`.\", path.abspath(\"basic.png\"))\n imageio.imsave(\"basic.png\", (image.cpu().detach() * 255.0).to(torch.uint8).numpy())\n LOGGER.info(\"Done.\")\n\n\nif __name__ == \"__main__\":\n logging.basicConfig(level=logging.INFO)\n cli()\n" ]
[ [ "torch.cuda.synchronize", "torch.randint", "torch.randn", "torch.manual_seed", "torch.cuda.is_available", "torch.device" ], [ "torch.optim.lr_scheduler.LambdaLR", "numpy.random.seed", "torch.load", "torch.manual_seed", "torch.utils.data.DataLoader", "torch.utils.data.RandomSampler", "torch.no_grad", "torch.cuda.is_available", "torch.save" ], [ "numpy.array", "torch.ones", "torch.zeros", "torch.from_numpy", "torch.tensor", "torch.nn.functional.grid_sample", "torch.arange", "torch.stack", "torch.flip", "torch.meshgrid" ], [ "torch.nn.Parameter", "torch.cat", "torch.manual_seed", "torch.tensor", "torch.rand", "torch.optim.SGD", "torch.device" ], [ "torch.randn_like", "torch.svd", "torch.randint", "torch.rand_like", "torch.load", "torch.cat", "torch.device", "torch.cuda.synchronize", "torch.ones", "torch.randn", "torch.eye", "torch.bmm", "torch.rand", "torch.arange", "torch.ones_like", "torch.random.set_rng_state", "numpy.random.seed", "torch.random.get_rng_state", "torch.manual_seed", "torch.det" ], [ "torch.randn_like", "torch.nn.functional.normalize", "torch.sigmoid", "numpy.random.seed", "torch.zeros", "torch.manual_seed", "torch.randn", "torch.zeros_like", "numpy.array" ], [ "torch.device", "torch.manual_seed", "torch.rand", "torch.tensor" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
minminfly68/Song-recommendation-Project-CAPP-30122-
[ "9f97d6accdfd33c5bac267980b6c10d6d5b93bc7" ]
[ "ui/sentiment.py" ]
[ "'''\nConduct Sentiment Analysis\nChun Hu, Yimin Li, Tianyue Niu\n'''\n\nimport os\nimport json\nimport re\nimport pandas as pd\nimport nltk\nnltk.download('punkt')\nnltk.download('wordnet')\nnltk.download('stopwords')\nfrom nltk import word_tokenize, sent_tokenize\nfrom nltk.corpus import stopwords\nfrom nltk.stem import WordNetLemmatizer\nfrom textblob import TextBlob\n\n# turn off warnings\npd.set_option('mode.chained_assignment', None)\n\ncwd = os.path.dirname(__file__)\ntop_10s_path = os.path.join(cwd, 'top10s.csv')\n\n\ndef merge_two_df(top_songs, lyrics):\n '''\n Input:\n top_songs (pandas data frame): kaggle data\n lyrics (json file): lyrics scraped\n Output:\n a merged data containing lyrics (pandas data frame)\n '''\n\n # merge two df\n top_songs['lyrics'] = ''\n for index, row in top_songs.iterrows():\n tit = top_songs.title[index]\n if tit in lyrics:\n top_songs['lyrics'][index] = lyrics[tit]\n\n return top_songs\n\n\ndef process_words(words, stop):\n '''\n Input:\n words (list): a list of words\n stop (list): extra stop words we want to remove\n Output:\n new_words (list): a list of normalized words\n '''\n lemmatizer = WordNetLemmatizer()\n new_words = []\n for word in words:\n new_word = re.sub(r'[^\\w\\s]', '', word)\n if new_word != '':\n new_word = new_word.lower()\n if new_word not in stop and new_word not in stopwords.words('english'):\n new_word = lemmatizer.lemmatize(new_word, pos='v')\n new_words.append(new_word)\n return new_words\n\n\ndef add_sentiment(top_songs):\n '''\n Input:\n top_songs (pandas df): raw version\n Output:\n top_songs (pandas df): with sentiment analysis result\n '''\n\n # tokenize words\n top_songs['tokenized'] = top_songs['lyrics'].apply(\\\n lambda x: [word_tokenize(s) for s in sent_tokenize(x)])\n\n # normalize words\n top_songs['normalized'] = top_songs['tokenized']\n stop = ['chorus', 'verse', 'intro', 'pre', 'outro', 'interlude']\n for index, row in top_songs['tokenized'].items():\n new_sent = []\n for sent in row:\n new_sent += process_words(sent, stop)\n top_songs['normalized'][index] = new_sent\n\n # calculate sentiment\n top_songs['sentiment'] = ''\n for index, row in top_songs.iterrows():\n obj = TextBlob(' '.join(top_songs['normalized'][index]))\n sentiment = obj.sentiment.polarity\n top_songs['sentiment'][index] = sentiment\n\n return top_songs\n\n\ndef create_final_top_songs ():\n '''\n Input:\n None\n Output:\n top_songs (pandas df): final cleaned & processed data frame\n '''\n\n top_songs = pd.read_csv(top_10s_path)\n\n with open('lyrics_file.json') as f:\n lyrics = json.load(f)\n\n top_songs = merge_two_df(top_songs, lyrics)\n df = add_sentiment(top_songs)\n\n df.to_csv('top_songs.csv')\n\n return\n\n\nif __name__ == \"__main__\":\n create_final_top_songs()\n" ]
[ [ "pandas.set_option", "pandas.read_csv" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
OleguerCanal/transplanter
[ "854fa727747a484dedde9092eeee6884d7d1b44b" ]
[ "test_models/data.py" ]
[ "from typing import Optional\nimport pytorch_lightning as pl\nimport torchvision\nimport torchvision.transforms as transforms\nfrom torchvision.datasets import CIFAR10\nfrom torch.utils.data import DataLoader, random_split\n\n\nclass CIFARDataModule(pl.LightningDataModule):\n def __init__(self, data_dir: str = \"./data\", batch_size: int = 32):\n super().__init__()\n self.data_dir = data_dir\n self.batch_size = batch_size\n\n def setup(self, stage: Optional[str] = None):\n transform = transforms.Compose(\n [transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\n\n # Train/val\n cifar_full = CIFAR10(root=self.data_dir, train=True, download=True, transform=transform)\n n_train, n_val = int(len(cifar_full)*0.9), int(len(cifar_full)*0.1)\n self.cifar_train, self.cifar_val = random_split(cifar_full, [n_train, n_val])\n \n # Test\n self.cifar_test = CIFAR10(self.data_dir, train=False)\n\n def train_dataloader(self):\n return DataLoader(self.cifar_train, batch_size=self.batch_size)\n\n def val_dataloader(self):\n return DataLoader(self.cifar_val, batch_size=self.batch_size)\n\n def test_dataloader(self):\n return DataLoader(self.cifar_test, batch_size=self.batch_size)\n" ]
[ [ "torch.utils.data.random_split", "torch.utils.data.DataLoader" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
mlline00/pandas
[ "4071dde86e33434e1bee8304fa62074949f813cc", "4071dde86e33434e1bee8304fa62074949f813cc", "4071dde86e33434e1bee8304fa62074949f813cc", "fd7db9819b8c7dba86b2887bee33f670b2715afc" ]
[ "pandas/tests/series/test_cumulative.py", "pandas/core/indexers.py", "pandas/tests/series/methods/test_cov_corr.py", "pandas/core/generic.py" ]
[ "\"\"\"\nTests for Series cumulative operations.\n\nSee also\n--------\ntests.frame.test_cumulative\n\"\"\"\nfrom itertools import product\n\nimport numpy as np\nimport pytest\n\nimport pandas as pd\nimport pandas.util.testing as tm\n\n\ndef _check_accum_op(name, series, check_dtype=True):\n func = getattr(np, name)\n tm.assert_numpy_array_equal(\n func(series).values, func(np.array(series)), check_dtype=check_dtype,\n )\n\n # with missing values\n ts = series.copy()\n ts[::2] = np.NaN\n\n result = func(ts)[1::2]\n expected = func(np.array(ts.dropna()))\n\n tm.assert_numpy_array_equal(result.values, expected, check_dtype=False)\n\n\nclass TestSeriesCumulativeOps:\n def test_cumsum(self, datetime_series):\n _check_accum_op(\"cumsum\", datetime_series)\n\n def test_cumprod(self, datetime_series):\n _check_accum_op(\"cumprod\", datetime_series)\n\n def test_cummin(self, datetime_series):\n tm.assert_numpy_array_equal(\n datetime_series.cummin().values,\n np.minimum.accumulate(np.array(datetime_series)),\n )\n ts = datetime_series.copy()\n ts[::2] = np.NaN\n result = ts.cummin()[1::2]\n expected = np.minimum.accumulate(ts.dropna())\n\n tm.assert_series_equal(result, expected)\n\n def test_cummax(self, datetime_series):\n tm.assert_numpy_array_equal(\n datetime_series.cummax().values,\n np.maximum.accumulate(np.array(datetime_series)),\n )\n ts = datetime_series.copy()\n ts[::2] = np.NaN\n result = ts.cummax()[1::2]\n expected = np.maximum.accumulate(ts.dropna())\n\n tm.assert_series_equal(result, expected)\n\n @pytest.mark.parametrize(\"tz\", [None, \"US/Pacific\"])\n def test_cummin_datetime64(self, tz):\n s = pd.Series(\n pd.to_datetime(\n [\"NaT\", \"2000-1-2\", \"NaT\", \"2000-1-1\", \"NaT\", \"2000-1-3\"]\n ).tz_localize(tz)\n )\n\n expected = pd.Series(\n pd.to_datetime(\n [\"NaT\", \"2000-1-2\", \"NaT\", \"2000-1-1\", \"NaT\", \"2000-1-1\"]\n ).tz_localize(tz)\n )\n result = s.cummin(skipna=True)\n tm.assert_series_equal(expected, result)\n\n expected = pd.Series(\n pd.to_datetime(\n [\"NaT\", \"2000-1-2\", \"2000-1-2\", \"2000-1-1\", \"2000-1-1\", \"2000-1-1\"]\n ).tz_localize(tz)\n )\n result = s.cummin(skipna=False)\n tm.assert_series_equal(expected, result)\n\n @pytest.mark.parametrize(\"tz\", [None, \"US/Pacific\"])\n def test_cummax_datetime64(self, tz):\n s = pd.Series(\n pd.to_datetime(\n [\"NaT\", \"2000-1-2\", \"NaT\", \"2000-1-1\", \"NaT\", \"2000-1-3\"]\n ).tz_localize(tz)\n )\n\n expected = pd.Series(\n pd.to_datetime(\n [\"NaT\", \"2000-1-2\", \"NaT\", \"2000-1-2\", \"NaT\", \"2000-1-3\"]\n ).tz_localize(tz)\n )\n result = s.cummax(skipna=True)\n tm.assert_series_equal(expected, result)\n\n expected = pd.Series(\n pd.to_datetime(\n [\"NaT\", \"2000-1-2\", \"2000-1-2\", \"2000-1-2\", \"2000-1-2\", \"2000-1-3\"]\n ).tz_localize(tz)\n )\n result = s.cummax(skipna=False)\n tm.assert_series_equal(expected, result)\n\n def test_cummin_timedelta64(self):\n s = pd.Series(pd.to_timedelta([\"NaT\", \"2 min\", \"NaT\", \"1 min\", \"NaT\", \"3 min\"]))\n\n expected = pd.Series(\n pd.to_timedelta([\"NaT\", \"2 min\", \"NaT\", \"1 min\", \"NaT\", \"1 min\"])\n )\n result = s.cummin(skipna=True)\n tm.assert_series_equal(expected, result)\n\n expected = pd.Series(\n pd.to_timedelta([\"NaT\", \"2 min\", \"2 min\", \"1 min\", \"1 min\", \"1 min\"])\n )\n result = s.cummin(skipna=False)\n tm.assert_series_equal(expected, result)\n\n def test_cummax_timedelta64(self):\n s = pd.Series(pd.to_timedelta([\"NaT\", \"2 min\", \"NaT\", \"1 min\", \"NaT\", \"3 min\"]))\n\n expected = pd.Series(\n pd.to_timedelta([\"NaT\", \"2 min\", \"NaT\", \"2 min\", \"NaT\", \"3 min\"])\n )\n result = s.cummax(skipna=True)\n tm.assert_series_equal(expected, result)\n\n expected = pd.Series(\n pd.to_timedelta([\"NaT\", \"2 min\", \"2 min\", \"2 min\", \"2 min\", \"3 min\"])\n )\n result = s.cummax(skipna=False)\n tm.assert_series_equal(expected, result)\n\n def test_cummethods_bool(self):\n # GH#6270\n\n a = pd.Series([False, False, False, True, True, False, False])\n b = ~a\n c = pd.Series([False] * len(b))\n d = ~c\n methods = {\n \"cumsum\": np.cumsum,\n \"cumprod\": np.cumprod,\n \"cummin\": np.minimum.accumulate,\n \"cummax\": np.maximum.accumulate,\n }\n args = product((a, b, c, d), methods)\n for s, method in args:\n expected = pd.Series(methods[method](s.values))\n result = getattr(s, method)()\n tm.assert_series_equal(result, expected)\n\n e = pd.Series([False, True, np.nan, False])\n cse = pd.Series([0, 1, np.nan, 1], dtype=object)\n cpe = pd.Series([False, 0, np.nan, 0])\n cmin = pd.Series([False, False, np.nan, False])\n cmax = pd.Series([False, True, np.nan, True])\n expecteds = {\"cumsum\": cse, \"cumprod\": cpe, \"cummin\": cmin, \"cummax\": cmax}\n\n for method in methods:\n res = getattr(e, method)()\n tm.assert_series_equal(res, expecteds[method])\n", "\"\"\"\nLow-dependency indexing utilities.\n\"\"\"\nimport numpy as np\n\nfrom pandas.core.dtypes.common import is_list_like\nfrom pandas.core.dtypes.generic import ABCIndexClass, ABCSeries\n\n# -----------------------------------------------------------\n# Indexer Identification\n\n\ndef is_list_like_indexer(key) -> bool:\n \"\"\"\n Check if we have a list-like indexer that is *not* a NamedTuple.\n\n Parameters\n ----------\n key : object\n\n Returns\n -------\n bool\n \"\"\"\n # allow a list_like, but exclude NamedTuples which can be indexers\n return is_list_like(key) and not (isinstance(key, tuple) and type(key) is not tuple)\n\n\ndef is_scalar_indexer(indexer, arr_value) -> bool:\n \"\"\"\n Return True if we are all scalar indexers.\n\n Returns\n -------\n bool\n \"\"\"\n if arr_value.ndim == 1:\n if not isinstance(indexer, tuple):\n indexer = tuple([indexer])\n return any(isinstance(idx, np.ndarray) and len(idx) == 0 for idx in indexer)\n return False\n\n\ndef is_empty_indexer(indexer, arr_value: np.ndarray) -> bool:\n \"\"\"\n Check if we have an empty indexer.\n\n Parameters\n ----------\n indexer : object\n arr_value : np.ndarray\n\n Returns\n -------\n bool\n \"\"\"\n if is_list_like(indexer) and not len(indexer):\n return True\n if arr_value.ndim == 1:\n if not isinstance(indexer, tuple):\n indexer = tuple([indexer])\n return any(isinstance(idx, np.ndarray) and len(idx) == 0 for idx in indexer)\n return False\n\n\n# -----------------------------------------------------------\n# Indexer Validation\n\n\ndef check_setitem_lengths(indexer, value, values) -> None:\n \"\"\"\n Validate that value and indexer are the same length.\n\n An special-case is allowed for when the indexer is a boolean array\n and the number of true values equals the length of ``value``. In\n this case, no exception is raised.\n\n Parameters\n ----------\n indexer : sequence\n Key for the setitem.\n value : array-like\n Value for the setitem.\n values : array-like\n Values being set into.\n\n Returns\n -------\n None\n\n Raises\n ------\n ValueError\n When the indexer is an ndarray or list and the lengths don't match.\n \"\"\"\n # boolean with truth values == len of the value is ok too\n if isinstance(indexer, (np.ndarray, list)):\n if is_list_like(value) and len(indexer) != len(value):\n if not (\n isinstance(indexer, np.ndarray)\n and indexer.dtype == np.bool_\n and len(indexer[indexer]) == len(value)\n ):\n raise ValueError(\n \"cannot set using a list-like indexer \"\n \"with a different length than the value\"\n )\n\n elif isinstance(indexer, slice):\n # slice\n if is_list_like(value) and len(values):\n if len(value) != length_of_indexer(indexer, values):\n raise ValueError(\n \"cannot set using a slice indexer with a \"\n \"different length than the value\"\n )\n\n\ndef validate_indices(indices: np.ndarray, n: int) -> None:\n \"\"\"\n Perform bounds-checking for an indexer.\n\n -1 is allowed for indicating missing values.\n\n Parameters\n ----------\n indices : ndarray\n n : int\n Length of the array being indexed.\n\n Raises\n ------\n ValueError\n\n Examples\n --------\n >>> validate_indices([1, 2], 3)\n # OK\n >>> validate_indices([1, -2], 3)\n ValueError\n >>> validate_indices([1, 2, 3], 3)\n IndexError\n >>> validate_indices([-1, -1], 0)\n # OK\n >>> validate_indices([0, 1], 0)\n IndexError\n \"\"\"\n if len(indices):\n min_idx = indices.min()\n if min_idx < -1:\n msg = f\"'indices' contains values less than allowed ({min_idx} < -1)\"\n raise ValueError(msg)\n\n max_idx = indices.max()\n if max_idx >= n:\n raise IndexError(\"indices are out-of-bounds\")\n\n\n# -----------------------------------------------------------\n# Indexer Conversion\n\n\ndef maybe_convert_indices(indices, n: int):\n \"\"\"\n Attempt to convert indices into valid, positive indices.\n\n If we have negative indices, translate to positive here.\n If we have indices that are out-of-bounds, raise an IndexError.\n\n Parameters\n ----------\n indices : array-like\n Array of indices that we are to convert.\n n : int\n Number of elements in the array that we are indexing.\n\n Returns\n -------\n array-like\n An array-like of positive indices that correspond to the ones\n that were passed in initially to this function.\n\n Raises\n ------\n IndexError\n One of the converted indices either exceeded the number of,\n elements (specified by `n`), or was still negative.\n \"\"\"\n if isinstance(indices, list):\n indices = np.array(indices)\n if len(indices) == 0:\n # If `indices` is empty, np.array will return a float,\n # and will cause indexing errors.\n return np.empty(0, dtype=np.intp)\n\n mask = indices < 0\n if mask.any():\n indices = indices.copy()\n indices[mask] += n\n\n mask = (indices >= n) | (indices < 0)\n if mask.any():\n raise IndexError(\"indices are out-of-bounds\")\n return indices\n\n\n# -----------------------------------------------------------\n# Unsorted\n\n\ndef length_of_indexer(indexer, target=None) -> int:\n \"\"\"\n Return the length of a single non-tuple indexer which could be a slice.\n\n Returns\n -------\n int\n \"\"\"\n if target is not None and isinstance(indexer, slice):\n target_len = len(target)\n start = indexer.start\n stop = indexer.stop\n step = indexer.step\n if start is None:\n start = 0\n elif start < 0:\n start += target_len\n if stop is None or stop > target_len:\n stop = target_len\n elif stop < 0:\n stop += target_len\n if step is None:\n step = 1\n elif step < 0:\n start, stop = stop + 1, start + 1\n step = -step\n return (stop - start + step - 1) // step\n elif isinstance(indexer, (ABCSeries, ABCIndexClass, np.ndarray, list)):\n return len(indexer)\n elif not is_list_like_indexer(indexer):\n return 1\n raise AssertionError(\"cannot find the length of the indexer\")\n", "import numpy as np\nimport pytest\n\nimport pandas.util._test_decorators as td\n\nimport pandas as pd\nfrom pandas import Series, isna\nimport pandas.util.testing as tm\n\n\nclass TestSeriesCov:\n def test_cov(self, datetime_series):\n # full overlap\n tm.assert_almost_equal(\n datetime_series.cov(datetime_series), datetime_series.std() ** 2\n )\n\n # partial overlap\n tm.assert_almost_equal(\n datetime_series[:15].cov(datetime_series[5:]),\n datetime_series[5:15].std() ** 2,\n )\n\n # No overlap\n assert np.isnan(datetime_series[::2].cov(datetime_series[1::2]))\n\n # all NA\n cp = datetime_series[:10].copy()\n cp[:] = np.nan\n assert isna(cp.cov(cp))\n\n # min_periods\n assert isna(datetime_series[:15].cov(datetime_series[5:], min_periods=12))\n\n ts1 = datetime_series[:15].reindex(datetime_series.index)\n ts2 = datetime_series[5:].reindex(datetime_series.index)\n assert isna(ts1.cov(ts2, min_periods=12))\n\n\nclass TestSeriesCorr:\n @td.skip_if_no_scipy\n def test_corr(self, datetime_series):\n import scipy.stats as stats\n\n # full overlap\n tm.assert_almost_equal(datetime_series.corr(datetime_series), 1)\n\n # partial overlap\n tm.assert_almost_equal(datetime_series[:15].corr(datetime_series[5:]), 1)\n\n assert isna(datetime_series[:15].corr(datetime_series[5:], min_periods=12))\n\n ts1 = datetime_series[:15].reindex(datetime_series.index)\n ts2 = datetime_series[5:].reindex(datetime_series.index)\n assert isna(ts1.corr(ts2, min_periods=12))\n\n # No overlap\n assert np.isnan(datetime_series[::2].corr(datetime_series[1::2]))\n\n # all NA\n cp = datetime_series[:10].copy()\n cp[:] = np.nan\n assert isna(cp.corr(cp))\n\n A = tm.makeTimeSeries()\n B = tm.makeTimeSeries()\n result = A.corr(B)\n expected, _ = stats.pearsonr(A, B)\n tm.assert_almost_equal(result, expected)\n\n @td.skip_if_no_scipy\n def test_corr_rank(self):\n import scipy.stats as stats\n\n # kendall and spearman\n A = tm.makeTimeSeries()\n B = tm.makeTimeSeries()\n A[-5:] = A[:5]\n result = A.corr(B, method=\"kendall\")\n expected = stats.kendalltau(A, B)[0]\n tm.assert_almost_equal(result, expected)\n\n result = A.corr(B, method=\"spearman\")\n expected = stats.spearmanr(A, B)[0]\n tm.assert_almost_equal(result, expected)\n\n # results from R\n A = Series(\n [\n -0.89926396,\n 0.94209606,\n -1.03289164,\n -0.95445587,\n 0.76910310,\n -0.06430576,\n -2.09704447,\n 0.40660407,\n -0.89926396,\n 0.94209606,\n ]\n )\n B = Series(\n [\n -1.01270225,\n -0.62210117,\n -1.56895827,\n 0.59592943,\n -0.01680292,\n 1.17258718,\n -1.06009347,\n -0.10222060,\n -0.89076239,\n 0.89372375,\n ]\n )\n kexp = 0.4319297\n sexp = 0.5853767\n tm.assert_almost_equal(A.corr(B, method=\"kendall\"), kexp)\n tm.assert_almost_equal(A.corr(B, method=\"spearman\"), sexp)\n\n def test_corr_invalid_method(self):\n # GH PR #22298\n s1 = pd.Series(np.random.randn(10))\n s2 = pd.Series(np.random.randn(10))\n msg = \"method must be either 'pearson', 'spearman', 'kendall', or a callable, \"\n with pytest.raises(ValueError, match=msg):\n s1.corr(s2, method=\"____\")\n\n def test_corr_callable_method(self, datetime_series):\n # simple correlation example\n # returns 1 if exact equality, 0 otherwise\n my_corr = lambda a, b: 1.0 if (a == b).all() else 0.0\n\n # simple example\n s1 = Series([1, 2, 3, 4, 5])\n s2 = Series([5, 4, 3, 2, 1])\n expected = 0\n tm.assert_almost_equal(s1.corr(s2, method=my_corr), expected)\n\n # full overlap\n tm.assert_almost_equal(\n datetime_series.corr(datetime_series, method=my_corr), 1.0\n )\n\n # partial overlap\n tm.assert_almost_equal(\n datetime_series[:15].corr(datetime_series[5:], method=my_corr), 1.0\n )\n\n # No overlap\n assert np.isnan(\n datetime_series[::2].corr(datetime_series[1::2], method=my_corr)\n )\n\n # dataframe example\n df = pd.DataFrame([s1, s2])\n expected = pd.DataFrame([{0: 1.0, 1: 0}, {0: 0, 1: 1.0}])\n tm.assert_almost_equal(df.transpose().corr(method=my_corr), expected)\n", "import collections\nfrom datetime import timedelta\nimport functools\nimport gc\nimport json\nimport operator\nimport pickle\nimport re\nfrom textwrap import dedent\nfrom typing import (\n Any,\n Callable,\n Dict,\n FrozenSet,\n Hashable,\n List,\n Mapping,\n Optional,\n Sequence,\n Set,\n Tuple,\n Union,\n)\nimport warnings\nimport weakref\n\nimport numpy as np\n\nfrom pandas._config import config\n\nfrom pandas._libs import Timestamp, iNaT, lib, properties\nfrom pandas._typing import Dtype, FilePathOrBuffer, FrameOrSeries, JSONSerializable\nfrom pandas.compat import set_function_name\nfrom pandas.compat._optional import import_optional_dependency\nfrom pandas.compat.numpy import function as nv\nfrom pandas.errors import AbstractMethodError\nfrom pandas.util._decorators import Appender, Substitution, rewrite_axis_style_signature\nfrom pandas.util._validators import (\n validate_bool_kwarg,\n validate_fillna_kwargs,\n validate_percentile,\n)\n\nfrom pandas.core.dtypes.common import (\n ensure_int64,\n ensure_object,\n ensure_str,\n is_bool,\n is_bool_dtype,\n is_datetime64_any_dtype,\n is_datetime64tz_dtype,\n is_dict_like,\n is_extension_array_dtype,\n is_float,\n is_integer,\n is_list_like,\n is_number,\n is_numeric_dtype,\n is_object_dtype,\n is_period_arraylike,\n is_re_compilable,\n is_scalar,\n is_timedelta64_dtype,\n pandas_dtype,\n)\nfrom pandas.core.dtypes.generic import ABCDataFrame, ABCSeries\nfrom pandas.core.dtypes.inference import is_hashable\nfrom pandas.core.dtypes.missing import isna, notna\n\nimport pandas as pd\nfrom pandas.core import missing, nanops\nimport pandas.core.algorithms as algos\nfrom pandas.core.base import PandasObject, SelectionMixin\nimport pandas.core.common as com\nfrom pandas.core.construction import create_series_with_explicit_dtype\nfrom pandas.core.indexes.api import (\n Index,\n InvalidIndexError,\n MultiIndex,\n RangeIndex,\n ensure_index,\n)\nfrom pandas.core.indexes.datetimes import DatetimeIndex\nfrom pandas.core.indexes.period import Period, PeriodIndex\nimport pandas.core.indexing as indexing\nfrom pandas.core.internals import BlockManager\nfrom pandas.core.missing import find_valid_index\nfrom pandas.core.ops import _align_method_FRAME\n\nfrom pandas.io.formats import format as fmt\nfrom pandas.io.formats.format import DataFrameFormatter, format_percentiles\nfrom pandas.io.formats.printing import pprint_thing\nfrom pandas.tseries.frequencies import to_offset\n\n# goal is to be able to define the docs close to function, while still being\n# able to share\n_shared_docs: Dict[str, str] = dict()\n_shared_doc_kwargs = dict(\n axes=\"keywords for axes\",\n klass=\"Series/DataFrame\",\n axes_single_arg=\"int or labels for object\",\n args_transpose=\"axes to permute (int or label for object)\",\n optional_by=\"\"\"\n by : str or list of str\n Name or list of names to sort by\"\"\",\n)\n\n# sentinel value to use as kwarg in place of None when None has special meaning\n# and needs to be distinguished from a user explicitly passing None.\nsentinel = object()\n\n\ndef _single_replace(self, to_replace, method, inplace, limit):\n \"\"\"\n Replaces values in a Series using the fill method specified when no\n replacement value is given in the replace method\n \"\"\"\n if self.ndim != 1:\n raise TypeError(\n f\"cannot replace {to_replace} with method {method} on a \"\n f\"{type(self).__name__}\"\n )\n\n orig_dtype = self.dtype\n result = self if inplace else self.copy()\n fill_f = missing.get_fill_func(method)\n\n mask = missing.mask_missing(result.values, to_replace)\n values = fill_f(result.values, limit=limit, mask=mask)\n\n if values.dtype == orig_dtype and inplace:\n return\n\n result = pd.Series(values, index=self.index, dtype=self.dtype).__finalize__(self)\n\n if inplace:\n self._update_inplace(result._data)\n return\n\n return result\n\n\nbool_t = bool # Need alias because NDFrame has def bool:\n\n\nclass NDFrame(PandasObject, SelectionMixin):\n \"\"\"\n N-dimensional analogue of DataFrame. Store multi-dimensional in a\n size-mutable, labeled data structure\n\n Parameters\n ----------\n data : BlockManager\n axes : list\n copy : bool, default False\n \"\"\"\n\n _internal_names: List[str] = [\n \"_data\",\n \"_cacher\",\n \"_item_cache\",\n \"_cache\",\n \"_is_copy\",\n \"_subtyp\",\n \"_name\",\n \"_index\",\n \"_default_kind\",\n \"_default_fill_value\",\n \"_metadata\",\n \"__array_struct__\",\n \"__array_interface__\",\n ]\n _internal_names_set: Set[str] = set(_internal_names)\n _accessors: Set[str] = set()\n _deprecations: FrozenSet[str] = frozenset([\"get_values\", \"ix\"])\n _metadata: List[str] = []\n _is_copy = None\n _data: BlockManager\n _attrs: Dict[Optional[Hashable], Any]\n _typ: str\n\n # ----------------------------------------------------------------------\n # Constructors\n\n def __init__(\n self,\n data: BlockManager,\n axes: Optional[List[Index]] = None,\n copy: bool = False,\n dtype: Optional[Dtype] = None,\n attrs: Optional[Mapping[Optional[Hashable], Any]] = None,\n fastpath: bool = False,\n ):\n\n if not fastpath:\n if dtype is not None:\n data = data.astype(dtype)\n elif copy:\n data = data.copy()\n\n if axes is not None:\n for i, ax in enumerate(axes):\n data = data.reindex_axis(ax, axis=i)\n\n object.__setattr__(self, \"_is_copy\", None)\n object.__setattr__(self, \"_data\", data)\n object.__setattr__(self, \"_item_cache\", {})\n if attrs is None:\n attrs = {}\n else:\n attrs = dict(attrs)\n object.__setattr__(self, \"_attrs\", attrs)\n\n def _init_mgr(self, mgr, axes=None, dtype=None, copy=False):\n \"\"\" passed a manager and a axes dict \"\"\"\n for a, axe in axes.items():\n if axe is not None:\n mgr = mgr.reindex_axis(\n axe, axis=self._get_block_manager_axis(a), copy=False\n )\n\n # make a copy if explicitly requested\n if copy:\n mgr = mgr.copy()\n if dtype is not None:\n # avoid further copies if we can\n if len(mgr.blocks) > 1 or mgr.blocks[0].values.dtype != dtype:\n mgr = mgr.astype(dtype=dtype)\n return mgr\n\n # ----------------------------------------------------------------------\n\n @property\n def attrs(self) -> Dict[Optional[Hashable], Any]:\n \"\"\"\n Dictionary of global attributes on this object.\n \"\"\"\n if self._attrs is None:\n self._attrs = {}\n return self._attrs\n\n @attrs.setter\n def attrs(self, value: Mapping[Optional[Hashable], Any]) -> None:\n self._attrs = dict(value)\n\n def _validate_dtype(self, dtype):\n \"\"\" validate the passed dtype \"\"\"\n\n if dtype is not None:\n dtype = pandas_dtype(dtype)\n\n # a compound dtype\n if dtype.kind == \"V\":\n raise NotImplementedError(\n \"compound dtypes are not implemented\"\n f\" in the {type(self).__name__} constructor\"\n )\n\n return dtype\n\n # ----------------------------------------------------------------------\n # Construction\n\n @property\n def _constructor(self):\n \"\"\"Used when a manipulation result has the same dimensions as the\n original.\n \"\"\"\n raise AbstractMethodError(self)\n\n @property\n def _constructor_sliced(self):\n \"\"\"Used when a manipulation result has one lower dimension(s) as the\n original, such as DataFrame single columns slicing.\n \"\"\"\n raise AbstractMethodError(self)\n\n @property\n def _constructor_expanddim(self):\n \"\"\"Used when a manipulation result has one higher dimension as the\n original, such as Series.to_frame()\n \"\"\"\n raise NotImplementedError\n\n # ----------------------------------------------------------------------\n # Axis\n _AXIS_ALIASES = {\"rows\": 0}\n _AXIS_IALIASES = {0: \"rows\"}\n _stat_axis_number = 0\n _stat_axis_name = \"index\"\n _ix = None\n _AXIS_ORDERS: List[str]\n _AXIS_NUMBERS: Dict[str, int]\n _AXIS_NAMES: Dict[int, str]\n _AXIS_REVERSED: bool\n _info_axis_number: int\n _info_axis_name: str\n _AXIS_LEN: int\n\n @classmethod\n def _setup_axes(cls, axes: List[str], docs: Dict[str, str]):\n \"\"\"\n Provide axes setup for the major PandasObjects.\n\n Parameters\n ----------\n axes : the names of the axes in order (lowest to highest)\n docs : docstrings for the axis properties\n \"\"\"\n info_axis = len(axes) - 1\n axes_are_reversed = len(axes) > 1\n\n cls._AXIS_ORDERS = axes\n cls._AXIS_NUMBERS = {a: i for i, a in enumerate(axes)}\n cls._AXIS_LEN = len(axes)\n cls._AXIS_NAMES = dict(enumerate(axes))\n cls._AXIS_REVERSED = axes_are_reversed\n\n cls._info_axis_number = info_axis\n cls._info_axis_name = axes[info_axis]\n\n # setup the actual axis\n def set_axis(a, i):\n setattr(cls, a, properties.AxisProperty(i, docs.get(a, a)))\n cls._internal_names_set.add(a)\n\n if axes_are_reversed:\n for i, a in cls._AXIS_NAMES.items():\n set_axis(a, 1 - i)\n else:\n for i, a in cls._AXIS_NAMES.items():\n set_axis(a, i)\n\n def _construct_axes_dict(self, axes=None, **kwargs):\n \"\"\"Return an axes dictionary for myself.\"\"\"\n d = {a: self._get_axis(a) for a in (axes or self._AXIS_ORDERS)}\n d.update(kwargs)\n return d\n\n @staticmethod\n def _construct_axes_dict_from(self, axes, **kwargs):\n \"\"\"Return an axes dictionary for the passed axes.\"\"\"\n d = {a: ax for a, ax in zip(self._AXIS_ORDERS, axes)}\n d.update(kwargs)\n return d\n\n def _construct_axes_from_arguments(\n self, args, kwargs, require_all: bool = False, sentinel=None\n ):\n \"\"\"Construct and returns axes if supplied in args/kwargs.\n\n If require_all, raise if all axis arguments are not supplied\n return a tuple of (axes, kwargs).\n\n sentinel specifies the default parameter when an axis is not\n supplied; useful to distinguish when a user explicitly passes None\n in scenarios where None has special meaning.\n \"\"\"\n\n # construct the args\n args = list(args)\n for a in self._AXIS_ORDERS:\n\n # look for a argument by position\n if a not in kwargs:\n try:\n kwargs[a] = args.pop(0)\n except IndexError:\n if require_all:\n raise TypeError(\"not enough/duplicate arguments specified!\")\n\n axes = {a: kwargs.pop(a, sentinel) for a in self._AXIS_ORDERS}\n return axes, kwargs\n\n @classmethod\n def _from_axes(cls, data, axes, **kwargs):\n # for construction from BlockManager\n if isinstance(data, BlockManager):\n return cls(data, **kwargs)\n else:\n if cls._AXIS_REVERSED:\n axes = axes[::-1]\n d = cls._construct_axes_dict_from(cls, axes, copy=False)\n d.update(kwargs)\n return cls(data, **d)\n\n @classmethod\n def _get_axis_number(cls, axis):\n axis = cls._AXIS_ALIASES.get(axis, axis)\n if is_integer(axis):\n if axis in cls._AXIS_NAMES:\n return axis\n else:\n try:\n return cls._AXIS_NUMBERS[axis]\n except KeyError:\n pass\n raise ValueError(f\"No axis named {axis} for object type {cls}\")\n\n @classmethod\n def _get_axis_name(cls, axis):\n axis = cls._AXIS_ALIASES.get(axis, axis)\n if isinstance(axis, str):\n if axis in cls._AXIS_NUMBERS:\n return axis\n else:\n try:\n return cls._AXIS_NAMES[axis]\n except KeyError:\n pass\n raise ValueError(f\"No axis named {axis} for object type {cls}\")\n\n def _get_axis(self, axis):\n name = self._get_axis_name(axis)\n return getattr(self, name)\n\n @classmethod\n def _get_block_manager_axis(cls, axis):\n \"\"\"Map the axis to the block_manager axis.\"\"\"\n axis = cls._get_axis_number(axis)\n if cls._AXIS_REVERSED:\n m = cls._AXIS_LEN - 1\n return m - axis\n return axis\n\n def _get_axis_resolvers(self, axis):\n # index or columns\n axis_index = getattr(self, axis)\n d = dict()\n prefix = axis[0]\n\n for i, name in enumerate(axis_index.names):\n if name is not None:\n key = level = name\n else:\n # prefix with 'i' or 'c' depending on the input axis\n # e.g., you must do ilevel_0 for the 0th level of an unnamed\n # multiiindex\n key = f\"{prefix}level_{i}\"\n level = i\n\n level_values = axis_index.get_level_values(level)\n s = level_values.to_series()\n s.index = axis_index\n d[key] = s\n\n # put the index/columns itself in the dict\n if isinstance(axis_index, MultiIndex):\n dindex = axis_index\n else:\n dindex = axis_index.to_series()\n\n d[axis] = dindex\n return d\n\n def _get_index_resolvers(self):\n d = {}\n for axis_name in self._AXIS_ORDERS:\n d.update(self._get_axis_resolvers(axis_name))\n return d\n\n def _get_space_character_free_column_resolvers(self):\n \"\"\"Return the space character free column resolvers of a dataframe.\n\n Column names with spaces are 'cleaned up' so that they can be referred\n to by backtick quoting.\n Used in :meth:`DataFrame.eval`.\n \"\"\"\n from pandas.core.computation.common import _remove_spaces_column_name\n\n return {_remove_spaces_column_name(k): v for k, v in self.items()}\n\n @property\n def _info_axis(self):\n return getattr(self, self._info_axis_name)\n\n @property\n def _stat_axis(self):\n return getattr(self, self._stat_axis_name)\n\n @property\n def shape(self) -> Tuple[int, ...]:\n \"\"\"\n Return a tuple of axis dimensions\n \"\"\"\n return tuple(len(self._get_axis(a)) for a in self._AXIS_ORDERS)\n\n @property\n def axes(self):\n \"\"\"\n Return index label(s) of the internal NDFrame\n \"\"\"\n # we do it this way because if we have reversed axes, then\n # the block manager shows then reversed\n return [self._get_axis(a) for a in self._AXIS_ORDERS]\n\n @property\n def ndim(self) -> int:\n \"\"\"\n Return an int representing the number of axes / array dimensions.\n\n Return 1 if Series. Otherwise return 2 if DataFrame.\n\n See Also\n --------\n ndarray.ndim : Number of array dimensions.\n\n Examples\n --------\n >>> s = pd.Series({'a': 1, 'b': 2, 'c': 3})\n >>> s.ndim\n 1\n\n >>> df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})\n >>> df.ndim\n 2\n \"\"\"\n return self._data.ndim\n\n @property\n def size(self):\n \"\"\"\n Return an int representing the number of elements in this object.\n\n Return the number of rows if Series. Otherwise return the number of\n rows times number of columns if DataFrame.\n\n See Also\n --------\n ndarray.size : Number of elements in the array.\n\n Examples\n --------\n >>> s = pd.Series({'a': 1, 'b': 2, 'c': 3})\n >>> s.size\n 3\n\n >>> df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})\n >>> df.size\n 4\n \"\"\"\n return np.prod(self.shape)\n\n @property\n def _selected_obj(self: FrameOrSeries) -> FrameOrSeries:\n \"\"\" internal compat with SelectionMixin \"\"\"\n return self\n\n @property\n def _obj_with_exclusions(self: FrameOrSeries) -> FrameOrSeries:\n \"\"\" internal compat with SelectionMixin \"\"\"\n return self\n\n def set_axis(self, labels, axis=0, inplace=False):\n \"\"\"\n Assign desired index to given axis.\n\n Indexes for column or row labels can be changed by assigning\n a list-like or Index.\n\n .. versionchanged:: 0.21.0\n\n The signature is now `labels` and `axis`, consistent with\n the rest of pandas API. Previously, the `axis` and `labels`\n arguments were respectively the first and second positional\n arguments.\n\n Parameters\n ----------\n labels : list-like, Index\n The values for the new index.\n\n axis : {0 or 'index', 1 or 'columns'}, default 0\n The axis to update. The value 0 identifies the rows, and 1\n identifies the columns.\n\n inplace : bool, default False\n Whether to return a new %(klass)s instance.\n\n Returns\n -------\n renamed : %(klass)s or None\n An object of same type as caller if inplace=False, None otherwise.\n\n See Also\n --------\n DataFrame.rename_axis : Alter the name of the index or columns.\n\n Examples\n --------\n **Series**\n\n >>> s = pd.Series([1, 2, 3])\n >>> s\n 0 1\n 1 2\n 2 3\n dtype: int64\n\n >>> s.set_axis(['a', 'b', 'c'], axis=0)\n a 1\n b 2\n c 3\n dtype: int64\n\n **DataFrame**\n\n >>> df = pd.DataFrame({\"A\": [1, 2, 3], \"B\": [4, 5, 6]})\n\n Change the row labels.\n\n >>> df.set_axis(['a', 'b', 'c'], axis='index')\n A B\n a 1 4\n b 2 5\n c 3 6\n\n Change the column labels.\n\n >>> df.set_axis(['I', 'II'], axis='columns')\n I II\n 0 1 4\n 1 2 5\n 2 3 6\n\n Now, update the labels inplace.\n\n >>> df.set_axis(['i', 'ii'], axis='columns', inplace=True)\n >>> df\n i ii\n 0 1 4\n 1 2 5\n 2 3 6\n \"\"\"\n if inplace:\n setattr(self, self._get_axis_name(axis), labels)\n else:\n obj = self.copy()\n obj.set_axis(labels, axis=axis, inplace=True)\n return obj\n\n def _set_axis(self, axis, labels):\n self._data.set_axis(axis, labels)\n self._clear_item_cache()\n\n def swapaxes(self, axis1, axis2, copy=True):\n \"\"\"\n Interchange axes and swap values axes appropriately.\n\n Returns\n -------\n y : same as input\n \"\"\"\n i = self._get_axis_number(axis1)\n j = self._get_axis_number(axis2)\n\n if i == j:\n if copy:\n return self.copy()\n return self\n\n mapping = {i: j, j: i}\n\n new_axes = (self._get_axis(mapping.get(k, k)) for k in range(self._AXIS_LEN))\n new_values = self.values.swapaxes(i, j)\n if copy:\n new_values = new_values.copy()\n\n return self._constructor(new_values, *new_axes).__finalize__(self)\n\n def droplevel(self, level, axis=0):\n \"\"\"\n Return DataFrame with requested index / column level(s) removed.\n\n .. versionadded:: 0.24.0\n\n Parameters\n ----------\n level : int, str, or list-like\n If a string is given, must be the name of a level\n If list-like, elements must be names or positional indexes\n of levels.\n\n axis : {0 or 'index', 1 or 'columns'}, default 0\n\n Returns\n -------\n DataFrame\n DataFrame with requested index / column level(s) removed.\n\n Examples\n --------\n >>> df = pd.DataFrame([\n ... [1, 2, 3, 4],\n ... [5, 6, 7, 8],\n ... [9, 10, 11, 12]\n ... ]).set_index([0, 1]).rename_axis(['a', 'b'])\n\n >>> df.columns = pd.MultiIndex.from_tuples([\n ... ('c', 'e'), ('d', 'f')\n ... ], names=['level_1', 'level_2'])\n\n >>> df\n level_1 c d\n level_2 e f\n a b\n 1 2 3 4\n 5 6 7 8\n 9 10 11 12\n\n >>> df.droplevel('a')\n level_1 c d\n level_2 e f\n b\n 2 3 4\n 6 7 8\n 10 11 12\n\n >>> df.droplevel('level2', axis=1)\n level_1 c d\n a b\n 1 2 3 4\n 5 6 7 8\n 9 10 11 12\n \"\"\"\n labels = self._get_axis(axis)\n new_labels = labels.droplevel(level)\n result = self.set_axis(new_labels, axis=axis, inplace=False)\n return result\n\n def pop(self, item):\n \"\"\"\n Return item and drop from frame. Raise KeyError if not found.\n\n Parameters\n ----------\n item : str\n Label of column to be popped.\n\n Returns\n -------\n Series\n\n Examples\n --------\n >>> df = pd.DataFrame([('falcon', 'bird', 389.0),\n ... ('parrot', 'bird', 24.0),\n ... ('lion', 'mammal', 80.5),\n ... ('monkey', 'mammal', np.nan)],\n ... columns=('name', 'class', 'max_speed'))\n >>> df\n name class max_speed\n 0 falcon bird 389.0\n 1 parrot bird 24.0\n 2 lion mammal 80.5\n 3 monkey mammal NaN\n\n >>> df.pop('class')\n 0 bird\n 1 bird\n 2 mammal\n 3 mammal\n Name: class, dtype: object\n\n >>> df\n name max_speed\n 0 falcon 389.0\n 1 parrot 24.0\n 2 lion 80.5\n 3 monkey NaN\n \"\"\"\n result = self[item]\n del self[item]\n try:\n result._reset_cacher()\n except AttributeError:\n pass\n\n return result\n\n def squeeze(self, axis=None):\n \"\"\"\n Squeeze 1 dimensional axis objects into scalars.\n\n Series or DataFrames with a single element are squeezed to a scalar.\n DataFrames with a single column or a single row are squeezed to a\n Series. Otherwise the object is unchanged.\n\n This method is most useful when you don't know if your\n object is a Series or DataFrame, but you do know it has just a single\n column. In that case you can safely call `squeeze` to ensure you have a\n Series.\n\n Parameters\n ----------\n axis : {0 or 'index', 1 or 'columns', None}, default None\n A specific axis to squeeze. By default, all length-1 axes are\n squeezed.\n\n Returns\n -------\n DataFrame, Series, or scalar\n The projection after squeezing `axis` or all the axes.\n\n See Also\n --------\n Series.iloc : Integer-location based indexing for selecting scalars.\n DataFrame.iloc : Integer-location based indexing for selecting Series.\n Series.to_frame : Inverse of DataFrame.squeeze for a\n single-column DataFrame.\n\n Examples\n --------\n >>> primes = pd.Series([2, 3, 5, 7])\n\n Slicing might produce a Series with a single value:\n\n >>> even_primes = primes[primes % 2 == 0]\n >>> even_primes\n 0 2\n dtype: int64\n\n >>> even_primes.squeeze()\n 2\n\n Squeezing objects with more than one value in every axis does nothing:\n\n >>> odd_primes = primes[primes % 2 == 1]\n >>> odd_primes\n 1 3\n 2 5\n 3 7\n dtype: int64\n\n >>> odd_primes.squeeze()\n 1 3\n 2 5\n 3 7\n dtype: int64\n\n Squeezing is even more effective when used with DataFrames.\n\n >>> df = pd.DataFrame([[1, 2], [3, 4]], columns=['a', 'b'])\n >>> df\n a b\n 0 1 2\n 1 3 4\n\n Slicing a single column will produce a DataFrame with the columns\n having only one value:\n\n >>> df_a = df[['a']]\n >>> df_a\n a\n 0 1\n 1 3\n\n So the columns can be squeezed down, resulting in a Series:\n\n >>> df_a.squeeze('columns')\n 0 1\n 1 3\n Name: a, dtype: int64\n\n Slicing a single row from a single column will produce a single\n scalar DataFrame:\n\n >>> df_0a = df.loc[df.index < 1, ['a']]\n >>> df_0a\n a\n 0 1\n\n Squeezing the rows produces a single scalar Series:\n\n >>> df_0a.squeeze('rows')\n a 1\n Name: 0, dtype: int64\n\n Squeezing all axes will project directly into a scalar:\n\n >>> df_0a.squeeze()\n 1\n \"\"\"\n axis = self._AXIS_NAMES if axis is None else (self._get_axis_number(axis),)\n return self.iloc[\n tuple(\n 0 if i in axis and len(a) == 1 else slice(None)\n for i, a in enumerate(self.axes)\n )\n ]\n\n def swaplevel(self, i=-2, j=-1, axis=0):\n \"\"\"\n Swap levels i and j in a MultiIndex on a particular axis\n\n Parameters\n ----------\n i, j : int, str (can be mixed)\n Level of index to be swapped. Can pass level name as string.\n\n Returns\n -------\n swapped : same type as caller (new object)\n \"\"\"\n axis = self._get_axis_number(axis)\n result = self.copy()\n labels = result._data.axes[axis]\n result._data.set_axis(axis, labels.swaplevel(i, j))\n return result\n\n # ----------------------------------------------------------------------\n # Rename\n\n def rename(self, *args, **kwargs):\n \"\"\"\n Alter axes input function or functions. Function / dict values must be\n unique (1-to-1). Labels not contained in a dict / Series will be left\n as-is. Extra labels listed don't throw an error. Alternatively, change\n ``Series.name`` with a scalar value (Series only).\n\n Parameters\n ----------\n %(axes)s : scalar, list-like, dict-like or function, optional\n Scalar or list-like will alter the ``Series.name`` attribute,\n and raise on DataFrame.\n dict-like or functions are transformations to apply to\n that axis' values\n copy : bool, default True\n Also copy underlying data.\n inplace : bool, default False\n Whether to return a new %(klass)s. If True then value of copy is\n ignored.\n level : int or level name, default None\n In case of a MultiIndex, only rename labels in the specified\n level.\n errors : {'ignore', 'raise'}, default 'ignore'\n If 'raise', raise a `KeyError` when a dict-like `mapper`, `index`,\n or `columns` contains labels that are not present in the Index\n being transformed.\n If 'ignore', existing keys will be renamed and extra keys will be\n ignored.\n\n Returns\n -------\n renamed : %(klass)s (new object)\n\n Raises\n ------\n KeyError\n If any of the labels is not found in the selected axis and\n \"errors='raise'\".\n\n See Also\n --------\n NDFrame.rename_axis\n\n Examples\n --------\n\n >>> s = pd.Series([1, 2, 3])\n >>> s\n 0 1\n 1 2\n 2 3\n dtype: int64\n >>> s.rename(\"my_name\") # scalar, changes Series.name\n 0 1\n 1 2\n 2 3\n Name: my_name, dtype: int64\n >>> s.rename(lambda x: x ** 2) # function, changes labels\n 0 1\n 1 2\n 4 3\n dtype: int64\n >>> s.rename({1: 3, 2: 5}) # mapping, changes labels\n 0 1\n 3 2\n 5 3\n dtype: int64\n\n Since ``DataFrame`` doesn't have a ``.name`` attribute,\n only mapping-type arguments are allowed.\n\n >>> df = pd.DataFrame({\"A\": [1, 2, 3], \"B\": [4, 5, 6]})\n >>> df.rename(2)\n Traceback (most recent call last):\n ...\n TypeError: 'int' object is not callable\n\n ``DataFrame.rename`` supports two calling conventions\n\n * ``(index=index_mapper, columns=columns_mapper, ...)``\n * ``(mapper, axis={'index', 'columns'}, ...)``\n\n We *highly* recommend using keyword arguments to clarify your\n intent.\n\n >>> df.rename(index=str, columns={\"A\": \"a\", \"B\": \"c\"})\n a c\n 0 1 4\n 1 2 5\n 2 3 6\n\n >>> df.rename(index=str, columns={\"A\": \"a\", \"C\": \"c\"})\n a B\n 0 1 4\n 1 2 5\n 2 3 6\n\n Using axis-style parameters\n\n >>> df.rename(str.lower, axis='columns')\n a b\n 0 1 4\n 1 2 5\n 2 3 6\n\n >>> df.rename({1: 2, 2: 4}, axis='index')\n A B\n 0 1 4\n 2 2 5\n 4 3 6\n\n See the :ref:`user guide <basics.rename>` for more.\n \"\"\"\n axes, kwargs = self._construct_axes_from_arguments(args, kwargs)\n copy = kwargs.pop(\"copy\", True)\n inplace = kwargs.pop(\"inplace\", False)\n level = kwargs.pop(\"level\", None)\n axis = kwargs.pop(\"axis\", None)\n errors = kwargs.pop(\"errors\", \"ignore\")\n if axis is not None:\n # Validate the axis\n self._get_axis_number(axis)\n\n if kwargs:\n raise TypeError(\n \"rename() got an unexpected keyword \"\n f'argument \"{list(kwargs.keys())[0]}\"'\n )\n\n if com.count_not_none(*axes.values()) == 0:\n raise TypeError(\"must pass an index to rename\")\n\n self._consolidate_inplace()\n result = self if inplace else self.copy(deep=copy)\n\n # start in the axis order to eliminate too many copies\n for axis in range(self._AXIS_LEN):\n v = axes.get(self._AXIS_NAMES[axis])\n if v is None:\n continue\n f = com.get_rename_function(v)\n baxis = self._get_block_manager_axis(axis)\n if level is not None:\n level = self.axes[axis]._get_level_number(level)\n\n # GH 13473\n if not callable(v):\n indexer = self.axes[axis].get_indexer_for(v)\n if errors == \"raise\" and len(indexer[indexer == -1]):\n missing_labels = [\n label for index, label in enumerate(v) if indexer[index] == -1\n ]\n raise KeyError(f\"{missing_labels} not found in axis\")\n\n result._data = result._data.rename_axis(\n f, axis=baxis, copy=copy, level=level\n )\n result._clear_item_cache()\n\n if inplace:\n self._update_inplace(result._data)\n else:\n return result.__finalize__(self)\n\n @rewrite_axis_style_signature(\"mapper\", [(\"copy\", True), (\"inplace\", False)])\n def rename_axis(self, mapper=sentinel, **kwargs):\n \"\"\"\n Set the name of the axis for the index or columns.\n\n Parameters\n ----------\n mapper : scalar, list-like, optional\n Value to set the axis name attribute.\n index, columns : scalar, list-like, dict-like or function, optional\n A scalar, list-like, dict-like or functions transformations to\n apply to that axis' values.\n\n Use either ``mapper`` and ``axis`` to\n specify the axis to target with ``mapper``, or ``index``\n and/or ``columns``.\n\n .. versionchanged:: 0.24.0\n\n axis : {0 or 'index', 1 or 'columns'}, default 0\n The axis to rename.\n copy : bool, default True\n Also copy underlying data.\n inplace : bool, default False\n Modifies the object directly, instead of creating a new Series\n or DataFrame.\n\n Returns\n -------\n Series, DataFrame, or None\n The same type as the caller or None if `inplace` is True.\n\n See Also\n --------\n Series.rename : Alter Series index labels or name.\n DataFrame.rename : Alter DataFrame index labels or name.\n Index.rename : Set new names on index.\n\n Notes\n -----\n ``DataFrame.rename_axis`` supports two calling conventions\n\n * ``(index=index_mapper, columns=columns_mapper, ...)``\n * ``(mapper, axis={'index', 'columns'}, ...)``\n\n The first calling convention will only modify the names of\n the index and/or the names of the Index object that is the columns.\n In this case, the parameter ``copy`` is ignored.\n\n The second calling convention will modify the names of the\n the corresponding index if mapper is a list or a scalar.\n However, if mapper is dict-like or a function, it will use the\n deprecated behavior of modifying the axis *labels*.\n\n We *highly* recommend using keyword arguments to clarify your\n intent.\n\n Examples\n --------\n **Series**\n\n >>> s = pd.Series([\"dog\", \"cat\", \"monkey\"])\n >>> s\n 0 dog\n 1 cat\n 2 monkey\n dtype: object\n >>> s.rename_axis(\"animal\")\n animal\n 0 dog\n 1 cat\n 2 monkey\n dtype: object\n\n **DataFrame**\n\n >>> df = pd.DataFrame({\"num_legs\": [4, 4, 2],\n ... \"num_arms\": [0, 0, 2]},\n ... [\"dog\", \"cat\", \"monkey\"])\n >>> df\n num_legs num_arms\n dog 4 0\n cat 4 0\n monkey 2 2\n >>> df = df.rename_axis(\"animal\")\n >>> df\n num_legs num_arms\n animal\n dog 4 0\n cat 4 0\n monkey 2 2\n >>> df = df.rename_axis(\"limbs\", axis=\"columns\")\n >>> df\n limbs num_legs num_arms\n animal\n dog 4 0\n cat 4 0\n monkey 2 2\n\n **MultiIndex**\n\n >>> df.index = pd.MultiIndex.from_product([['mammal'],\n ... ['dog', 'cat', 'monkey']],\n ... names=['type', 'name'])\n >>> df\n limbs num_legs num_arms\n type name\n mammal dog 4 0\n cat 4 0\n monkey 2 2\n\n >>> df.rename_axis(index={'type': 'class'})\n limbs num_legs num_arms\n class name\n mammal dog 4 0\n cat 4 0\n monkey 2 2\n\n >>> df.rename_axis(columns=str.upper)\n LIMBS num_legs num_arms\n type name\n mammal dog 4 0\n cat 4 0\n monkey 2 2\n \"\"\"\n axes, kwargs = self._construct_axes_from_arguments(\n (), kwargs, sentinel=sentinel\n )\n copy = kwargs.pop(\"copy\", True)\n inplace = kwargs.pop(\"inplace\", False)\n axis = kwargs.pop(\"axis\", 0)\n if axis is not None:\n axis = self._get_axis_number(axis)\n\n if kwargs:\n raise TypeError(\n \"rename_axis() got an unexpected keyword \"\n f'argument \"{list(kwargs.keys())[0]}\"'\n )\n\n inplace = validate_bool_kwarg(inplace, \"inplace\")\n\n if mapper is not sentinel:\n # Use v0.23 behavior if a scalar or list\n non_mapper = is_scalar(mapper) or (\n is_list_like(mapper) and not is_dict_like(mapper)\n )\n if non_mapper:\n return self._set_axis_name(mapper, axis=axis, inplace=inplace)\n else:\n raise ValueError(\"Use `.rename` to alter labels with a mapper.\")\n else:\n # Use new behavior. Means that index and/or columns\n # is specified\n result = self if inplace else self.copy(deep=copy)\n\n for axis in range(self._AXIS_LEN):\n v = axes.get(self._AXIS_NAMES[axis])\n if v is sentinel:\n continue\n non_mapper = is_scalar(v) or (is_list_like(v) and not is_dict_like(v))\n if non_mapper:\n newnames = v\n else:\n f = com.get_rename_function(v)\n curnames = self._get_axis(axis).names\n newnames = [f(name) for name in curnames]\n result._set_axis_name(newnames, axis=axis, inplace=True)\n if not inplace:\n return result\n\n def _set_axis_name(self, name, axis=0, inplace=False):\n \"\"\"\n Set the name(s) of the axis.\n\n Parameters\n ----------\n name : str or list of str\n Name(s) to set.\n axis : {0 or 'index', 1 or 'columns'}, default 0\n The axis to set the label. The value 0 or 'index' specifies index,\n and the value 1 or 'columns' specifies columns.\n inplace : bool, default False\n If `True`, do operation inplace and return None.\n\n .. versionadded:: 0.21.0\n\n Returns\n -------\n Series, DataFrame, or None\n The same type as the caller or `None` if `inplace` is `True`.\n\n See Also\n --------\n DataFrame.rename : Alter the axis labels of :class:`DataFrame`.\n Series.rename : Alter the index labels or set the index name\n of :class:`Series`.\n Index.rename : Set the name of :class:`Index` or :class:`MultiIndex`.\n\n Examples\n --------\n >>> df = pd.DataFrame({\"num_legs\": [4, 4, 2]},\n ... [\"dog\", \"cat\", \"monkey\"])\n >>> df\n num_legs\n dog 4\n cat 4\n monkey 2\n >>> df._set_axis_name(\"animal\")\n num_legs\n animal\n dog 4\n cat 4\n monkey 2\n >>> df.index = pd.MultiIndex.from_product(\n ... [[\"mammal\"], ['dog', 'cat', 'monkey']])\n >>> df._set_axis_name([\"type\", \"name\"])\n legs\n type name\n mammal dog 4\n cat 4\n monkey 2\n \"\"\"\n axis = self._get_axis_number(axis)\n idx = self._get_axis(axis).set_names(name)\n\n inplace = validate_bool_kwarg(inplace, \"inplace\")\n renamed = self if inplace else self.copy()\n renamed.set_axis(idx, axis=axis, inplace=True)\n if not inplace:\n return renamed\n\n # ----------------------------------------------------------------------\n # Comparison Methods\n\n def _indexed_same(self, other) -> bool:\n return all(\n self._get_axis(a).equals(other._get_axis(a)) for a in self._AXIS_ORDERS\n )\n\n def equals(self, other):\n \"\"\"\n Test whether two objects contain the same elements.\n\n This function allows two Series or DataFrames to be compared against\n each other to see if they have the same shape and elements. NaNs in\n the same location are considered equal. The column headers do not\n need to have the same type, but the elements within the columns must\n be the same dtype.\n\n Parameters\n ----------\n other : Series or DataFrame\n The other Series or DataFrame to be compared with the first.\n\n Returns\n -------\n bool\n True if all elements are the same in both objects, False\n otherwise.\n\n See Also\n --------\n Series.eq : Compare two Series objects of the same length\n and return a Series where each element is True if the element\n in each Series is equal, False otherwise.\n DataFrame.eq : Compare two DataFrame objects of the same shape and\n return a DataFrame where each element is True if the respective\n element in each DataFrame is equal, False otherwise.\n testing.assert_series_equal : Raises an AssertionError if left and\n right are not equal. Provides an easy interface to ignore\n inequality in dtypes, indexes and precision among others.\n testing.assert_frame_equal : Like assert_series_equal, but targets\n DataFrames.\n numpy.array_equal : Return True if two arrays have the same shape\n and elements, False otherwise.\n\n Notes\n -----\n This function requires that the elements have the same dtype as their\n respective elements in the other Series or DataFrame. However, the\n column labels do not need to have the same type, as long as they are\n still considered equal.\n\n Examples\n --------\n >>> df = pd.DataFrame({1: [10], 2: [20]})\n >>> df\n 1 2\n 0 10 20\n\n DataFrames df and exactly_equal have the same types and values for\n their elements and column labels, which will return True.\n\n >>> exactly_equal = pd.DataFrame({1: [10], 2: [20]})\n >>> exactly_equal\n 1 2\n 0 10 20\n >>> df.equals(exactly_equal)\n True\n\n DataFrames df and different_column_type have the same element\n types and values, but have different types for the column labels,\n which will still return True.\n\n >>> different_column_type = pd.DataFrame({1.0: [10], 2.0: [20]})\n >>> different_column_type\n 1.0 2.0\n 0 10 20\n >>> df.equals(different_column_type)\n True\n\n DataFrames df and different_data_type have different types for the\n same values for their elements, and will return False even though\n their column labels are the same values and types.\n\n >>> different_data_type = pd.DataFrame({1: [10.0], 2: [20.0]})\n >>> different_data_type\n 1 2\n 0 10.0 20.0\n >>> df.equals(different_data_type)\n False\n \"\"\"\n if not isinstance(other, self._constructor):\n return False\n return self._data.equals(other._data)\n\n # -------------------------------------------------------------------------\n # Unary Methods\n\n def __neg__(self):\n values = com.values_from_object(self)\n if is_bool_dtype(values):\n arr = operator.inv(values)\n elif (\n is_numeric_dtype(values)\n or is_timedelta64_dtype(values)\n or is_object_dtype(values)\n ):\n arr = operator.neg(values)\n else:\n raise TypeError(f\"Unary negative expects numeric dtype, not {values.dtype}\")\n return self.__array_wrap__(arr)\n\n def __pos__(self):\n values = com.values_from_object(self)\n if is_bool_dtype(values) or is_period_arraylike(values):\n arr = values\n elif (\n is_numeric_dtype(values)\n or is_timedelta64_dtype(values)\n or is_object_dtype(values)\n ):\n arr = operator.pos(values)\n else:\n raise TypeError(f\"Unary plus expects numeric dtype, not {values.dtype}\")\n return self.__array_wrap__(arr)\n\n def __invert__(self):\n if not self.size:\n # inv fails with 0 len\n return self\n\n arr = operator.inv(com.values_from_object(self))\n return self.__array_wrap__(arr)\n\n def __nonzero__(self):\n raise ValueError(\n f\"The truth value of a {type(self).__name__} is ambiguous. \"\n \"Use a.empty, a.bool(), a.item(), a.any() or a.all().\"\n )\n\n __bool__ = __nonzero__\n\n def bool(self):\n \"\"\"\n Return the bool of a single element PandasObject.\n\n This must be a boolean scalar value, either True or False. Raise a\n ValueError if the PandasObject does not have exactly 1 element, or that\n element is not boolean\n\n Returns\n -------\n bool\n Same single boolean value converted to bool type.\n \"\"\"\n v = self.squeeze()\n if isinstance(v, (bool, np.bool_)):\n return bool(v)\n elif is_scalar(v):\n raise ValueError(\n \"bool cannot act on a non-boolean single element \"\n f\"{type(self).__name__}\"\n )\n\n self.__nonzero__()\n\n def __abs__(self):\n return self.abs()\n\n def __round__(self, decimals=0):\n return self.round(decimals)\n\n # -------------------------------------------------------------------------\n # Label or Level Combination Helpers\n #\n # A collection of helper methods for DataFrame/Series operations that\n # accept a combination of column/index labels and levels. All such\n # operations should utilize/extend these methods when possible so that we\n # have consistent precedence and validation logic throughout the library.\n\n def _is_level_reference(self, key, axis=0):\n \"\"\"\n Test whether a key is a level reference for a given axis.\n\n To be considered a level reference, `key` must be a string that:\n - (axis=0): Matches the name of an index level and does NOT match\n a column label.\n - (axis=1): Matches the name of a column level and does NOT match\n an index label.\n\n Parameters\n ----------\n key : str\n Potential level name for the given axis\n axis : int, default 0\n Axis that levels are associated with (0 for index, 1 for columns)\n\n Returns\n -------\n is_level : bool\n \"\"\"\n axis = self._get_axis_number(axis)\n\n return (\n key is not None\n and is_hashable(key)\n and key in self.axes[axis].names\n and not self._is_label_reference(key, axis=axis)\n )\n\n def _is_label_reference(self, key, axis=0) -> bool_t:\n \"\"\"\n Test whether a key is a label reference for a given axis.\n\n To be considered a label reference, `key` must be a string that:\n - (axis=0): Matches a column label\n - (axis=1): Matches an index label\n\n Parameters\n ----------\n key: str\n Potential label name\n axis: int, default 0\n Axis perpendicular to the axis that labels are associated with\n (0 means search for column labels, 1 means search for index labels)\n\n Returns\n -------\n is_label: bool\n \"\"\"\n axis = self._get_axis_number(axis)\n other_axes = (ax for ax in range(self._AXIS_LEN) if ax != axis)\n\n return (\n key is not None\n and is_hashable(key)\n and any(key in self.axes[ax] for ax in other_axes)\n )\n\n def _is_label_or_level_reference(self, key: str, axis: int = 0) -> bool_t:\n \"\"\"\n Test whether a key is a label or level reference for a given axis.\n\n To be considered either a label or a level reference, `key` must be a\n string that:\n - (axis=0): Matches a column label or an index level\n - (axis=1): Matches an index label or a column level\n\n Parameters\n ----------\n key: str\n Potential label or level name\n axis: int, default 0\n Axis that levels are associated with (0 for index, 1 for columns)\n\n Returns\n -------\n is_label_or_level: bool\n \"\"\"\n return self._is_level_reference(key, axis=axis) or self._is_label_reference(\n key, axis=axis\n )\n\n def _check_label_or_level_ambiguity(self, key, axis: int = 0) -> None:\n \"\"\"\n Check whether `key` is ambiguous.\n\n By ambiguous, we mean that it matches both a level of the input\n `axis` and a label of the other axis.\n\n Parameters\n ----------\n key: str or object\n Label or level name.\n axis: int, default 0\n Axis that levels are associated with (0 for index, 1 for columns).\n\n Raises\n ------\n ValueError: `key` is ambiguous\n \"\"\"\n axis = self._get_axis_number(axis)\n other_axes = (ax for ax in range(self._AXIS_LEN) if ax != axis)\n\n if (\n key is not None\n and is_hashable(key)\n and key in self.axes[axis].names\n and any(key in self.axes[ax] for ax in other_axes)\n ):\n\n # Build an informative and grammatical warning\n level_article, level_type = (\n (\"an\", \"index\") if axis == 0 else (\"a\", \"column\")\n )\n\n label_article, label_type = (\n (\"a\", \"column\") if axis == 0 else (\"an\", \"index\")\n )\n\n msg = (\n f\"'{key}' is both {level_article} {level_type} level and \"\n f\"{label_article} {label_type} label, which is ambiguous.\"\n )\n raise ValueError(msg)\n\n def _get_label_or_level_values(self, key: str, axis: int = 0) -> np.ndarray:\n \"\"\"\n Return a 1-D array of values associated with `key`, a label or level\n from the given `axis`.\n\n Retrieval logic:\n - (axis=0): Return column values if `key` matches a column label.\n Otherwise return index level values if `key` matches an index\n level.\n - (axis=1): Return row values if `key` matches an index label.\n Otherwise return column level values if 'key' matches a column\n level\n\n Parameters\n ----------\n key: str\n Label or level name.\n axis: int, default 0\n Axis that levels are associated with (0 for index, 1 for columns)\n\n Returns\n -------\n values: np.ndarray\n\n Raises\n ------\n KeyError\n if `key` matches neither a label nor a level\n ValueError\n if `key` matches multiple labels\n FutureWarning\n if `key` is ambiguous. This will become an ambiguity error in a\n future version\n \"\"\"\n axis = self._get_axis_number(axis)\n other_axes = [ax for ax in range(self._AXIS_LEN) if ax != axis]\n\n if self._is_label_reference(key, axis=axis):\n self._check_label_or_level_ambiguity(key, axis=axis)\n values = self.xs(key, axis=other_axes[0])._values\n elif self._is_level_reference(key, axis=axis):\n values = self.axes[axis].get_level_values(key)._values\n else:\n raise KeyError(key)\n\n # Check for duplicates\n if values.ndim > 1:\n\n if other_axes and isinstance(self._get_axis(other_axes[0]), MultiIndex):\n multi_message = (\n \"\\n\"\n \"For a multi-index, the label must be a \"\n \"tuple with elements corresponding to \"\n \"each level.\"\n )\n else:\n multi_message = \"\"\n\n label_axis_name = \"column\" if axis == 0 else \"index\"\n raise ValueError(\n (\n f\"The {label_axis_name} label '{key}' \"\n f\"is not unique.{multi_message}\"\n )\n )\n\n return values\n\n def _drop_labels_or_levels(self, keys, axis: int = 0):\n \"\"\"\n Drop labels and/or levels for the given `axis`.\n\n For each key in `keys`:\n - (axis=0): If key matches a column label then drop the column.\n Otherwise if key matches an index level then drop the level.\n - (axis=1): If key matches an index label then drop the row.\n Otherwise if key matches a column level then drop the level.\n\n Parameters\n ----------\n keys: str or list of str\n labels or levels to drop\n axis: int, default 0\n Axis that levels are associated with (0 for index, 1 for columns)\n\n Returns\n -------\n dropped: DataFrame\n\n Raises\n ------\n ValueError\n if any `keys` match neither a label nor a level\n \"\"\"\n axis = self._get_axis_number(axis)\n\n # Validate keys\n keys = com.maybe_make_list(keys)\n invalid_keys = [\n k for k in keys if not self._is_label_or_level_reference(k, axis=axis)\n ]\n\n if invalid_keys:\n raise ValueError(\n (\n \"The following keys are not valid labels or \"\n f\"levels for axis {axis}: {invalid_keys}\"\n )\n )\n\n # Compute levels and labels to drop\n levels_to_drop = [k for k in keys if self._is_level_reference(k, axis=axis)]\n\n labels_to_drop = [k for k in keys if not self._is_level_reference(k, axis=axis)]\n\n # Perform copy upfront and then use inplace operations below.\n # This ensures that we always perform exactly one copy.\n # ``copy`` and/or ``inplace`` options could be added in the future.\n dropped = self.copy()\n\n if axis == 0:\n # Handle dropping index levels\n if levels_to_drop:\n dropped.reset_index(levels_to_drop, drop=True, inplace=True)\n\n # Handle dropping columns labels\n if labels_to_drop:\n dropped.drop(labels_to_drop, axis=1, inplace=True)\n else:\n # Handle dropping column levels\n if levels_to_drop:\n if isinstance(dropped.columns, MultiIndex):\n # Drop the specified levels from the MultiIndex\n dropped.columns = dropped.columns.droplevel(levels_to_drop)\n else:\n # Drop the last level of Index by replacing with\n # a RangeIndex\n dropped.columns = RangeIndex(dropped.columns.size)\n\n # Handle dropping index labels\n if labels_to_drop:\n dropped.drop(labels_to_drop, axis=0, inplace=True)\n\n return dropped\n\n # ----------------------------------------------------------------------\n # Iteration\n\n def __hash__(self):\n raise TypeError(\n f\"{repr(type(self).__name__)} objects are mutable, \"\n f\"thus they cannot be hashed\"\n )\n\n def __iter__(self):\n \"\"\"\n Iterate over info axis.\n\n Returns\n -------\n iterator\n Info axis as iterator.\n \"\"\"\n return iter(self._info_axis)\n\n # can we get a better explanation of this?\n def keys(self):\n \"\"\"\n Get the 'info axis' (see Indexing for more).\n\n This is index for Series, columns for DataFrame.\n\n Returns\n -------\n Index\n Info axis.\n \"\"\"\n return self._info_axis\n\n def items(self):\n \"\"\"Iterate over (label, values) on info axis\n\n This is index for Series and columns for DataFrame.\n\n Returns\n -------\n Generator\n \"\"\"\n for h in self._info_axis:\n yield h, self[h]\n\n @Appender(items.__doc__)\n def iteritems(self):\n return self.items()\n\n def __len__(self) -> int:\n \"\"\"Returns length of info axis\"\"\"\n return len(self._info_axis)\n\n def __contains__(self, key) -> bool_t:\n \"\"\"True if the key is in the info axis\"\"\"\n return key in self._info_axis\n\n @property\n def empty(self) -> bool_t:\n \"\"\"\n Indicator whether DataFrame is empty.\n\n True if DataFrame is entirely empty (no items), meaning any of the\n axes are of length 0.\n\n Returns\n -------\n bool\n If DataFrame is empty, return True, if not return False.\n\n See Also\n --------\n Series.dropna\n DataFrame.dropna\n\n Notes\n -----\n If DataFrame contains only NaNs, it is still not considered empty. See\n the example below.\n\n Examples\n --------\n An example of an actual empty DataFrame. Notice the index is empty:\n\n >>> df_empty = pd.DataFrame({'A' : []})\n >>> df_empty\n Empty DataFrame\n Columns: [A]\n Index: []\n >>> df_empty.empty\n True\n\n If we only have NaNs in our DataFrame, it is not considered empty! We\n will need to drop the NaNs to make the DataFrame empty:\n\n >>> df = pd.DataFrame({'A' : [np.nan]})\n >>> df\n A\n 0 NaN\n >>> df.empty\n False\n >>> df.dropna().empty\n True\n \"\"\"\n return any(len(self._get_axis(a)) == 0 for a in self._AXIS_ORDERS)\n\n # ----------------------------------------------------------------------\n # Array Interface\n\n # This is also set in IndexOpsMixin\n # GH#23114 Ensure ndarray.__op__(DataFrame) returns NotImplemented\n __array_priority__ = 1000\n\n def __array__(self, dtype=None):\n return com.values_from_object(self)\n\n def __array_wrap__(self, result, context=None):\n result = lib.item_from_zerodim(result)\n if is_scalar(result):\n # e.g. we get here with np.ptp(series)\n # ptp also requires the item_from_zerodim\n return result\n d = self._construct_axes_dict(self._AXIS_ORDERS, copy=False)\n return self._constructor(result, **d).__finalize__(self)\n\n # ideally we would define this to avoid the getattr checks, but\n # is slower\n # @property\n # def __array_interface__(self):\n # \"\"\" provide numpy array interface method \"\"\"\n # values = self.values\n # return dict(typestr=values.dtype.str,shape=values.shape,data=values)\n\n # ----------------------------------------------------------------------\n # Picklability\n\n def __getstate__(self) -> Dict[str, Any]:\n meta = {k: getattr(self, k, None) for k in self._metadata}\n return dict(\n _data=self._data,\n _typ=self._typ,\n _metadata=self._metadata,\n attrs=self.attrs,\n **meta,\n )\n\n def __setstate__(self, state):\n\n if isinstance(state, BlockManager):\n self._data = state\n elif isinstance(state, dict):\n typ = state.get(\"_typ\")\n if typ is not None:\n attrs = state.get(\"_attrs\", {})\n object.__setattr__(self, \"_attrs\", attrs)\n\n # set in the order of internal names\n # to avoid definitional recursion\n # e.g. say fill_value needing _data to be\n # defined\n meta = set(self._internal_names + self._metadata)\n for k in list(meta):\n if k in state:\n v = state[k]\n object.__setattr__(self, k, v)\n\n for k, v in state.items():\n if k not in meta:\n object.__setattr__(self, k, v)\n\n else:\n self._unpickle_series_compat(state)\n elif len(state) == 2:\n self._unpickle_series_compat(state)\n\n self._item_cache = {}\n\n # ----------------------------------------------------------------------\n # Rendering Methods\n\n def __repr__(self) -> str:\n # string representation based upon iterating over self\n # (since, by definition, `PandasContainers` are iterable)\n prepr = f\"[{','.join(map(pprint_thing, self))}]\"\n return f\"{type(self).__name__}({prepr})\"\n\n def _repr_latex_(self):\n \"\"\"\n Returns a LaTeX representation for a particular object.\n Mainly for use with nbconvert (jupyter notebook conversion to pdf).\n \"\"\"\n if config.get_option(\"display.latex.repr\"):\n return self.to_latex()\n else:\n return None\n\n def _repr_data_resource_(self):\n \"\"\"\n Not a real Jupyter special repr method, but we use the same\n naming convention.\n \"\"\"\n if config.get_option(\"display.html.table_schema\"):\n data = self.head(config.get_option(\"display.max_rows\"))\n payload = json.loads(\n data.to_json(orient=\"table\"), object_pairs_hook=collections.OrderedDict\n )\n return payload\n\n # ----------------------------------------------------------------------\n # I/O Methods\n\n _shared_docs[\n \"to_markdown\"\n ] = \"\"\"\n Print %(klass)s in Markdown-friendly format.\n\n .. versionadded:: 1.0.0\n\n Parameters\n ----------\n buf : writable buffer, defaults to sys.stdout\n Where to send the output. By default, the output is printed to\n sys.stdout. Pass a writable buffer if you need to further process\n the output.\n mode : str, optional\n Mode in which file is opened.\n **kwargs\n These parameters will be passed to `tabulate`.\n\n Returns\n -------\n str\n %(klass)s in Markdown-friendly format.\n \"\"\"\n\n _shared_docs[\n \"to_excel\"\n ] = \"\"\"\n Write %(klass)s to an Excel sheet.\n\n To write a single %(klass)s to an Excel .xlsx file it is only necessary to\n specify a target file name. To write to multiple sheets it is necessary to\n create an `ExcelWriter` object with a target file name, and specify a sheet\n in the file to write to.\n\n Multiple sheets may be written to by specifying unique `sheet_name`.\n With all data written to the file it is necessary to save the changes.\n Note that creating an `ExcelWriter` object with a file name that already\n exists will result in the contents of the existing file being erased.\n\n Parameters\n ----------\n excel_writer : str or ExcelWriter object\n File path or existing ExcelWriter.\n sheet_name : str, default 'Sheet1'\n Name of sheet which will contain DataFrame.\n na_rep : str, default ''\n Missing data representation.\n float_format : str, optional\n Format string for floating point numbers. For example\n ``float_format=\"%%.2f\"`` will format 0.1234 to 0.12.\n columns : sequence or list of str, optional\n Columns to write.\n header : bool or list of str, default True\n Write out the column names. If a list of string is given it is\n assumed to be aliases for the column names.\n index : bool, default True\n Write row names (index).\n index_label : str or sequence, optional\n Column label for index column(s) if desired. If not specified, and\n `header` and `index` are True, then the index names are used. A\n sequence should be given if the DataFrame uses MultiIndex.\n startrow : int, default 0\n Upper left cell row to dump data frame.\n startcol : int, default 0\n Upper left cell column to dump data frame.\n engine : str, optional\n Write engine to use, 'openpyxl' or 'xlsxwriter'. You can also set this\n via the options ``io.excel.xlsx.writer``, ``io.excel.xls.writer``, and\n ``io.excel.xlsm.writer``.\n merge_cells : bool, default True\n Write MultiIndex and Hierarchical Rows as merged cells.\n encoding : str, optional\n Encoding of the resulting excel file. Only necessary for xlwt,\n other writers support unicode natively.\n inf_rep : str, default 'inf'\n Representation for infinity (there is no native representation for\n infinity in Excel).\n verbose : bool, default True\n Display more information in the error logs.\n freeze_panes : tuple of int (length 2), optional\n Specifies the one-based bottommost row and rightmost column that\n is to be frozen.\n\n See Also\n --------\n to_csv : Write DataFrame to a comma-separated values (csv) file.\n ExcelWriter : Class for writing DataFrame objects into excel sheets.\n read_excel : Read an Excel file into a pandas DataFrame.\n read_csv : Read a comma-separated values (csv) file into DataFrame.\n\n Notes\n -----\n For compatibility with :meth:`~DataFrame.to_csv`,\n to_excel serializes lists and dicts to strings before writing.\n\n Once a workbook has been saved it is not possible write further data\n without rewriting the whole workbook.\n\n Examples\n --------\n\n Create, write to and save a workbook:\n\n >>> df1 = pd.DataFrame([['a', 'b'], ['c', 'd']],\n ... index=['row 1', 'row 2'],\n ... columns=['col 1', 'col 2'])\n >>> df1.to_excel(\"output.xlsx\") # doctest: +SKIP\n\n To specify the sheet name:\n\n >>> df1.to_excel(\"output.xlsx\",\n ... sheet_name='Sheet_name_1') # doctest: +SKIP\n\n If you wish to write to more than one sheet in the workbook, it is\n necessary to specify an ExcelWriter object:\n\n >>> df2 = df1.copy()\n >>> with pd.ExcelWriter('output.xlsx') as writer: # doctest: +SKIP\n ... df1.to_excel(writer, sheet_name='Sheet_name_1')\n ... df2.to_excel(writer, sheet_name='Sheet_name_2')\n\n ExcelWriter can also be used to append to an existing Excel file:\n\n >>> with pd.ExcelWriter('output.xlsx',\n ... mode='a') as writer: # doctest: +SKIP\n ... df.to_excel(writer, sheet_name='Sheet_name_3')\n\n To set the library that is used to write the Excel file,\n you can pass the `engine` keyword (the default engine is\n automatically chosen depending on the file extension):\n\n >>> df1.to_excel('output1.xlsx', engine='xlsxwriter') # doctest: +SKIP\n \"\"\"\n\n @Appender(_shared_docs[\"to_excel\"] % dict(klass=\"object\"))\n def to_excel(\n self,\n excel_writer,\n sheet_name=\"Sheet1\",\n na_rep=\"\",\n float_format=None,\n columns=None,\n header=True,\n index=True,\n index_label=None,\n startrow=0,\n startcol=0,\n engine=None,\n merge_cells=True,\n encoding=None,\n inf_rep=\"inf\",\n verbose=True,\n freeze_panes=None,\n ):\n df = self if isinstance(self, ABCDataFrame) else self.to_frame()\n\n from pandas.io.formats.excel import ExcelFormatter\n\n formatter = ExcelFormatter(\n df,\n na_rep=na_rep,\n cols=columns,\n header=header,\n float_format=float_format,\n index=index,\n index_label=index_label,\n merge_cells=merge_cells,\n inf_rep=inf_rep,\n )\n formatter.write(\n excel_writer,\n sheet_name=sheet_name,\n startrow=startrow,\n startcol=startcol,\n freeze_panes=freeze_panes,\n engine=engine,\n )\n\n def to_json(\n self,\n path_or_buf: Optional[FilePathOrBuffer] = None,\n orient: Optional[str] = None,\n date_format: Optional[str] = None,\n double_precision: int = 10,\n force_ascii: bool_t = True,\n date_unit: str = \"ms\",\n default_handler: Optional[Callable[[Any], JSONSerializable]] = None,\n lines: bool_t = False,\n compression: Optional[str] = \"infer\",\n index: bool_t = True,\n indent: Optional[int] = None,\n ) -> Optional[str]:\n \"\"\"\n Convert the object to a JSON string.\n\n Note NaN's and None will be converted to null and datetime objects\n will be converted to UNIX timestamps.\n\n Parameters\n ----------\n path_or_buf : str or file handle, optional\n File path or object. If not specified, the result is returned as\n a string.\n orient : str\n Indication of expected JSON string format.\n\n * Series:\n\n - default is 'index'\n - allowed values are: {'split','records','index','table'}.\n\n * DataFrame:\n\n - default is 'columns'\n - allowed values are: {'split', 'records', 'index', 'columns',\n 'values', 'table'}.\n\n * The format of the JSON string:\n\n - 'split' : dict like {'index' -> [index], 'columns' -> [columns],\n 'data' -> [values]}\n - 'records' : list like [{column -> value}, ... , {column -> value}]\n - 'index' : dict like {index -> {column -> value}}\n - 'columns' : dict like {column -> {index -> value}}\n - 'values' : just the values array\n - 'table' : dict like {'schema': {schema}, 'data': {data}}\n\n Describing the data, where data component is like ``orient='records'``.\n\n .. versionchanged:: 0.20.0\n\n date_format : {None, 'epoch', 'iso'}\n Type of date conversion. 'epoch' = epoch milliseconds,\n 'iso' = ISO8601. The default depends on the `orient`. For\n ``orient='table'``, the default is 'iso'. For all other orients,\n the default is 'epoch'.\n double_precision : int, default 10\n The number of decimal places to use when encoding\n floating point values.\n force_ascii : bool, default True\n Force encoded string to be ASCII.\n date_unit : str, default 'ms' (milliseconds)\n The time unit to encode to, governs timestamp and ISO8601\n precision. One of 's', 'ms', 'us', 'ns' for second, millisecond,\n microsecond, and nanosecond respectively.\n default_handler : callable, default None\n Handler to call if object cannot otherwise be converted to a\n suitable format for JSON. Should receive a single argument which is\n the object to convert and return a serialisable object.\n lines : bool, default False\n If 'orient' is 'records' write out line delimited json format. Will\n throw ValueError if incorrect 'orient' since others are not list\n like.\n\n compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None}\n\n A string representing the compression to use in the output file,\n only used when the first argument is a filename. By default, the\n compression is inferred from the filename.\n\n .. versionadded:: 0.21.0\n .. versionchanged:: 0.24.0\n 'infer' option added and set to default\n index : bool, default True\n Whether to include the index values in the JSON string. Not\n including the index (``index=False``) is only supported when\n orient is 'split' or 'table'.\n\n .. versionadded:: 0.23.0\n\n indent : int, optional\n Length of whitespace used to indent each record.\n\n .. versionadded:: 1.0.0\n\n Returns\n -------\n None or str\n If path_or_buf is None, returns the resulting json format as a\n string. Otherwise returns None.\n\n See Also\n --------\n read_json\n\n Notes\n -----\n The behavior of ``indent=0`` varies from the stdlib, which does not\n indent the output but does insert newlines. Currently, ``indent=0``\n and the default ``indent=None`` are equivalent in pandas, though this\n may change in a future release.\n\n Examples\n --------\n\n >>> df = pd.DataFrame([['a', 'b'], ['c', 'd']],\n ... index=['row 1', 'row 2'],\n ... columns=['col 1', 'col 2'])\n >>> df.to_json(orient='split')\n '{\"columns\":[\"col 1\",\"col 2\"],\n \"index\":[\"row 1\",\"row 2\"],\n \"data\":[[\"a\",\"b\"],[\"c\",\"d\"]]}'\n\n Encoding/decoding a Dataframe using ``'records'`` formatted JSON.\n Note that index labels are not preserved with this encoding.\n\n >>> df.to_json(orient='records')\n '[{\"col 1\":\"a\",\"col 2\":\"b\"},{\"col 1\":\"c\",\"col 2\":\"d\"}]'\n\n Encoding/decoding a Dataframe using ``'index'`` formatted JSON:\n\n >>> df.to_json(orient='index')\n '{\"row 1\":{\"col 1\":\"a\",\"col 2\":\"b\"},\"row 2\":{\"col 1\":\"c\",\"col 2\":\"d\"}}'\n\n Encoding/decoding a Dataframe using ``'columns'`` formatted JSON:\n\n >>> df.to_json(orient='columns')\n '{\"col 1\":{\"row 1\":\"a\",\"row 2\":\"c\"},\"col 2\":{\"row 1\":\"b\",\"row 2\":\"d\"}}'\n\n Encoding/decoding a Dataframe using ``'values'`` formatted JSON:\n\n >>> df.to_json(orient='values')\n '[[\"a\",\"b\"],[\"c\",\"d\"]]'\n\n Encoding with Table Schema\n\n >>> df.to_json(orient='table')\n '{\"schema\": {\"fields\": [{\"name\": \"index\", \"type\": \"string\"},\n {\"name\": \"col 1\", \"type\": \"string\"},\n {\"name\": \"col 2\", \"type\": \"string\"}],\n \"primaryKey\": \"index\",\n \"pandas_version\": \"0.20.0\"},\n \"data\": [{\"index\": \"row 1\", \"col 1\": \"a\", \"col 2\": \"b\"},\n {\"index\": \"row 2\", \"col 1\": \"c\", \"col 2\": \"d\"}]}'\n \"\"\"\n\n from pandas.io import json\n\n if date_format is None and orient == \"table\":\n date_format = \"iso\"\n elif date_format is None:\n date_format = \"epoch\"\n\n config.is_nonnegative_int(indent)\n indent = indent or 0\n\n return json.to_json(\n path_or_buf=path_or_buf,\n obj=self,\n orient=orient,\n date_format=date_format,\n double_precision=double_precision,\n force_ascii=force_ascii,\n date_unit=date_unit,\n default_handler=default_handler,\n lines=lines,\n compression=compression,\n index=index,\n indent=indent,\n )\n\n def to_hdf(\n self,\n path_or_buf,\n key: str,\n mode: str = \"a\",\n complevel: Optional[int] = None,\n complib: Optional[str] = None,\n append: bool_t = False,\n format: Optional[str] = None,\n index: bool_t = True,\n min_itemsize: Optional[Union[int, Dict[str, int]]] = None,\n nan_rep=None,\n dropna: Optional[bool_t] = None,\n data_columns: Optional[List[str]] = None,\n errors: str = \"strict\",\n encoding: str = \"UTF-8\",\n ):\n \"\"\"\n Write the contained data to an HDF5 file using HDFStore.\n\n Hierarchical Data Format (HDF) is self-describing, allowing an\n application to interpret the structure and contents of a file with\n no outside information. One HDF file can hold a mix of related objects\n which can be accessed as a group or as individual objects.\n\n In order to add another DataFrame or Series to an existing HDF file\n please use append mode and a different a key.\n\n For more information see the :ref:`user guide <io.hdf5>`.\n\n Parameters\n ----------\n path_or_buf : str or pandas.HDFStore\n File path or HDFStore object.\n key : str\n Identifier for the group in the store.\n mode : {'a', 'w', 'r+'}, default 'a'\n Mode to open file:\n\n - 'w': write, a new file is created (an existing file with\n the same name would be deleted).\n - 'a': append, an existing file is opened for reading and\n writing, and if the file does not exist it is created.\n - 'r+': similar to 'a', but the file must already exist.\n complevel : {0-9}, optional\n Specifies a compression level for data.\n A value of 0 disables compression.\n complib : {'zlib', 'lzo', 'bzip2', 'blosc'}, default 'zlib'\n Specifies the compression library to be used.\n As of v0.20.2 these additional compressors for Blosc are supported\n (default if no compressor specified: 'blosc:blosclz'):\n {'blosc:blosclz', 'blosc:lz4', 'blosc:lz4hc', 'blosc:snappy',\n 'blosc:zlib', 'blosc:zstd'}.\n Specifying a compression library which is not available issues\n a ValueError.\n append : bool, default False\n For Table formats, append the input data to the existing.\n format : {'fixed', 'table', None}, default 'fixed'\n Possible values:\n\n - 'fixed': Fixed format. Fast writing/reading. Not-appendable,\n nor searchable.\n - 'table': Table format. Write as a PyTables Table structure\n which may perform worse but allow more flexible operations\n like searching / selecting subsets of the data.\n - If None, pd.get_option('io.hdf.default_format') is checked,\n followed by fallback to \"fixed\"\n errors : str, default 'strict'\n Specifies how encoding and decoding errors are to be handled.\n See the errors argument for :func:`open` for a full list\n of options.\n encoding : str, default \"UTF-8\"\n min_itemsize : dict or int, optional\n Map column names to minimum string sizes for columns.\n nan_rep : Any, optional\n How to represent null values as str.\n Not allowed with append=True.\n data_columns : list of columns or True, optional\n List of columns to create as indexed data columns for on-disk\n queries, or True to use all columns. By default only the axes\n of the object are indexed. See :ref:`io.hdf5-query-data-columns`.\n Applicable only to format='table'.\n\n See Also\n --------\n DataFrame.read_hdf : Read from HDF file.\n DataFrame.to_parquet : Write a DataFrame to the binary parquet format.\n DataFrame.to_sql : Write to a sql table.\n DataFrame.to_feather : Write out feather-format for DataFrames.\n DataFrame.to_csv : Write out to a csv file.\n\n Examples\n --------\n >>> df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]},\n ... index=['a', 'b', 'c'])\n >>> df.to_hdf('data.h5', key='df', mode='w')\n\n We can add another object to the same file:\n\n >>> s = pd.Series([1, 2, 3, 4])\n >>> s.to_hdf('data.h5', key='s')\n\n Reading from HDF file:\n\n >>> pd.read_hdf('data.h5', 'df')\n A B\n a 1 4\n b 2 5\n c 3 6\n >>> pd.read_hdf('data.h5', 's')\n 0 1\n 1 2\n 2 3\n 3 4\n dtype: int64\n\n Deleting file with data:\n\n >>> import os\n >>> os.remove('data.h5')\n \"\"\"\n from pandas.io import pytables\n\n pytables.to_hdf(\n path_or_buf,\n key,\n self,\n mode=mode,\n complevel=complevel,\n complib=complib,\n append=append,\n format=format,\n index=index,\n min_itemsize=min_itemsize,\n nan_rep=nan_rep,\n dropna=dropna,\n data_columns=data_columns,\n errors=errors,\n encoding=encoding,\n )\n\n def to_sql(\n self,\n name: str,\n con,\n schema=None,\n if_exists: str = \"fail\",\n index: bool_t = True,\n index_label=None,\n chunksize=None,\n dtype=None,\n method=None,\n ) -> None:\n \"\"\"\n Write records stored in a DataFrame to a SQL database.\n\n Databases supported by SQLAlchemy [1]_ are supported. Tables can be\n newly created, appended to, or overwritten.\n\n Parameters\n ----------\n name : str\n Name of SQL table.\n con : sqlalchemy.engine.Engine or sqlite3.Connection\n Using SQLAlchemy makes it possible to use any DB supported by that\n library. Legacy support is provided for sqlite3.Connection objects. The user\n is responsible for engine disposal and connection closure for the SQLAlchemy\n connectable See `here \\\n <https://docs.sqlalchemy.org/en/13/core/connections.html>`_\n\n schema : str, optional\n Specify the schema (if database flavor supports this). If None, use\n default schema.\n if_exists : {'fail', 'replace', 'append'}, default 'fail'\n How to behave if the table already exists.\n\n * fail: Raise a ValueError.\n * replace: Drop the table before inserting new values.\n * append: Insert new values to the existing table.\n\n index : bool, default True\n Write DataFrame index as a column. Uses `index_label` as the column\n name in the table.\n index_label : str or sequence, default None\n Column label for index column(s). If None is given (default) and\n `index` is True, then the index names are used.\n A sequence should be given if the DataFrame uses MultiIndex.\n chunksize : int, optional\n Specify the number of rows in each batch to be written at a time.\n By default, all rows will be written at once.\n dtype : dict or scalar, optional\n Specifying the datatype for columns. If a dictionary is used, the\n keys should be the column names and the values should be the\n SQLAlchemy types or strings for the sqlite3 legacy mode. If a\n scalar is provided, it will be applied to all columns.\n method : {None, 'multi', callable}, optional\n Controls the SQL insertion clause used:\n\n * None : Uses standard SQL ``INSERT`` clause (one per row).\n * 'multi': Pass multiple values in a single ``INSERT`` clause.\n * callable with signature ``(pd_table, conn, keys, data_iter)``.\n\n Details and a sample callable implementation can be found in the\n section :ref:`insert method <io.sql.method>`.\n\n .. versionadded:: 0.24.0\n\n Raises\n ------\n ValueError\n When the table already exists and `if_exists` is 'fail' (the\n default).\n\n See Also\n --------\n read_sql : Read a DataFrame from a table.\n\n Notes\n -----\n Timezone aware datetime columns will be written as\n ``Timestamp with timezone`` type with SQLAlchemy if supported by the\n database. Otherwise, the datetimes will be stored as timezone unaware\n timestamps local to the original timezone.\n\n .. versionadded:: 0.24.0\n\n References\n ----------\n .. [1] http://docs.sqlalchemy.org\n .. [2] https://www.python.org/dev/peps/pep-0249/\n\n Examples\n --------\n\n Create an in-memory SQLite database.\n\n >>> from sqlalchemy import create_engine\n >>> engine = create_engine('sqlite://', echo=False)\n\n Create a table from scratch with 3 rows.\n\n >>> df = pd.DataFrame({'name' : ['User 1', 'User 2', 'User 3']})\n >>> df\n name\n 0 User 1\n 1 User 2\n 2 User 3\n\n >>> df.to_sql('users', con=engine)\n >>> engine.execute(\"SELECT * FROM users\").fetchall()\n [(0, 'User 1'), (1, 'User 2'), (2, 'User 3')]\n\n >>> df1 = pd.DataFrame({'name' : ['User 4', 'User 5']})\n >>> df1.to_sql('users', con=engine, if_exists='append')\n >>> engine.execute(\"SELECT * FROM users\").fetchall()\n [(0, 'User 1'), (1, 'User 2'), (2, 'User 3'),\n (0, 'User 4'), (1, 'User 5')]\n\n Overwrite the table with just ``df1``.\n\n >>> df1.to_sql('users', con=engine, if_exists='replace',\n ... index_label='id')\n >>> engine.execute(\"SELECT * FROM users\").fetchall()\n [(0, 'User 4'), (1, 'User 5')]\n\n Specify the dtype (especially useful for integers with missing values).\n Notice that while pandas is forced to store the data as floating point,\n the database supports nullable integers. When fetching the data with\n Python, we get back integer scalars.\n\n >>> df = pd.DataFrame({\"A\": [1, None, 2]})\n >>> df\n A\n 0 1.0\n 1 NaN\n 2 2.0\n\n >>> from sqlalchemy.types import Integer\n >>> df.to_sql('integers', con=engine, index=False,\n ... dtype={\"A\": Integer()})\n\n >>> engine.execute(\"SELECT * FROM integers\").fetchall()\n [(1,), (None,), (2,)]\n \"\"\"\n from pandas.io import sql\n\n sql.to_sql(\n self,\n name,\n con,\n schema=schema,\n if_exists=if_exists,\n index=index,\n index_label=index_label,\n chunksize=chunksize,\n dtype=dtype,\n method=method,\n )\n\n def to_pickle(\n self,\n path,\n compression: Optional[str] = \"infer\",\n protocol: int = pickle.HIGHEST_PROTOCOL,\n ) -> None:\n \"\"\"\n Pickle (serialize) object to file.\n\n Parameters\n ----------\n path : str\n File path where the pickled object will be stored.\n compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None}, \\\n default 'infer'\n A string representing the compression to use in the output file. By\n default, infers from the file extension in specified path.\n protocol : int\n Int which indicates which protocol should be used by the pickler,\n default HIGHEST_PROTOCOL (see [1]_ paragraph 12.1.2). The possible\n values are 0, 1, 2, 3, 4. A negative value for the protocol\n parameter is equivalent to setting its value to HIGHEST_PROTOCOL.\n\n .. [1] https://docs.python.org/3/library/pickle.html.\n .. versionadded:: 0.21.0.\n\n See Also\n --------\n read_pickle : Load pickled pandas object (or any object) from file.\n DataFrame.to_hdf : Write DataFrame to an HDF5 file.\n DataFrame.to_sql : Write DataFrame to a SQL database.\n DataFrame.to_parquet : Write a DataFrame to the binary parquet format.\n\n Examples\n --------\n >>> original_df = pd.DataFrame({\"foo\": range(5), \"bar\": range(5, 10)})\n >>> original_df\n foo bar\n 0 0 5\n 1 1 6\n 2 2 7\n 3 3 8\n 4 4 9\n >>> original_df.to_pickle(\"./dummy.pkl\")\n\n >>> unpickled_df = pd.read_pickle(\"./dummy.pkl\")\n >>> unpickled_df\n foo bar\n 0 0 5\n 1 1 6\n 2 2 7\n 3 3 8\n 4 4 9\n\n >>> import os\n >>> os.remove(\"./dummy.pkl\")\n \"\"\"\n from pandas.io.pickle import to_pickle\n\n to_pickle(self, path, compression=compression, protocol=protocol)\n\n def to_clipboard(self, excel: bool_t = True, sep: Optional[str] = None, **kwargs):\n r\"\"\"\n Copy object to the system clipboard.\n\n Write a text representation of object to the system clipboard.\n This can be pasted into Excel, for example.\n\n Parameters\n ----------\n excel : bool, default True\n Produce output in a csv format for easy pasting into excel.\n\n - True, use the provided separator for csv pasting.\n - False, write a string representation of the object to the clipboard.\n\n sep : str, default ``'\\t'``\n Field delimiter.\n **kwargs\n These parameters will be passed to DataFrame.to_csv.\n\n See Also\n --------\n DataFrame.to_csv : Write a DataFrame to a comma-separated values\n (csv) file.\n read_clipboard : Read text from clipboard and pass to read_table.\n\n Notes\n -----\n Requirements for your platform.\n\n - Linux : `xclip`, or `xsel` (with `PyQt4` modules)\n - Windows : none\n - OS X : none\n\n Examples\n --------\n Copy the contents of a DataFrame to the clipboard.\n\n >>> df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=['A', 'B', 'C'])\n >>> df.to_clipboard(sep=',')\n ... # Wrote the following to the system clipboard:\n ... # ,A,B,C\n ... # 0,1,2,3\n ... # 1,4,5,6\n\n We can omit the the index by passing the keyword `index` and setting\n it to false.\n\n >>> df.to_clipboard(sep=',', index=False)\n ... # Wrote the following to the system clipboard:\n ... # A,B,C\n ... # 1,2,3\n ... # 4,5,6\n \"\"\"\n from pandas.io import clipboards\n\n clipboards.to_clipboard(self, excel=excel, sep=sep, **kwargs)\n\n def to_xarray(self):\n \"\"\"\n Return an xarray object from the pandas object.\n\n Returns\n -------\n xarray.DataArray or xarray.Dataset\n Data in the pandas structure converted to Dataset if the object is\n a DataFrame, or a DataArray if the object is a Series.\n\n See Also\n --------\n DataFrame.to_hdf : Write DataFrame to an HDF5 file.\n DataFrame.to_parquet : Write a DataFrame to the binary parquet format.\n\n Notes\n -----\n See the `xarray docs <http://xarray.pydata.org/en/stable/>`__\n\n Examples\n --------\n >>> df = pd.DataFrame([('falcon', 'bird', 389.0, 2),\n ... ('parrot', 'bird', 24.0, 2),\n ... ('lion', 'mammal', 80.5, 4),\n ... ('monkey', 'mammal', np.nan, 4)],\n ... columns=['name', 'class', 'max_speed',\n ... 'num_legs'])\n >>> df\n name class max_speed num_legs\n 0 falcon bird 389.0 2\n 1 parrot bird 24.0 2\n 2 lion mammal 80.5 4\n 3 monkey mammal NaN 4\n\n >>> df.to_xarray()\n <xarray.Dataset>\n Dimensions: (index: 4)\n Coordinates:\n * index (index) int64 0 1 2 3\n Data variables:\n name (index) object 'falcon' 'parrot' 'lion' 'monkey'\n class (index) object 'bird' 'bird' 'mammal' 'mammal'\n max_speed (index) float64 389.0 24.0 80.5 nan\n num_legs (index) int64 2 2 4 4\n\n >>> df['max_speed'].to_xarray()\n <xarray.DataArray 'max_speed' (index: 4)>\n array([389. , 24. , 80.5, nan])\n Coordinates:\n * index (index) int64 0 1 2 3\n\n >>> dates = pd.to_datetime(['2018-01-01', '2018-01-01',\n ... '2018-01-02', '2018-01-02'])\n >>> df_multiindex = pd.DataFrame({'date': dates,\n ... 'animal': ['falcon', 'parrot',\n ... 'falcon', 'parrot'],\n ... 'speed': [350, 18, 361, 15]})\n >>> df_multiindex = df_multiindex.set_index(['date', 'animal'])\n\n >>> df_multiindex\n speed\n date animal\n 2018-01-01 falcon 350\n parrot 18\n 2018-01-02 falcon 361\n parrot 15\n\n >>> df_multiindex.to_xarray()\n <xarray.Dataset>\n Dimensions: (animal: 2, date: 2)\n Coordinates:\n * date (date) datetime64[ns] 2018-01-01 2018-01-02\n * animal (animal) object 'falcon' 'parrot'\n Data variables:\n speed (date, animal) int64 350 18 361 15\n \"\"\"\n xarray = import_optional_dependency(\"xarray\")\n\n if self.ndim == 1:\n return xarray.DataArray.from_series(self)\n else:\n return xarray.Dataset.from_dataframe(self)\n\n @Substitution(returns=fmt.return_docstring)\n def to_latex(\n self,\n buf=None,\n columns=None,\n col_space=None,\n header=True,\n index=True,\n na_rep=\"NaN\",\n formatters=None,\n float_format=None,\n sparsify=None,\n index_names=True,\n bold_rows=False,\n column_format=None,\n longtable=None,\n escape=None,\n encoding=None,\n decimal=\".\",\n multicolumn=None,\n multicolumn_format=None,\n multirow=None,\n caption=None,\n label=None,\n ):\n r\"\"\"\n Render object to a LaTeX tabular, longtable, or nested table/tabular.\n\n Requires ``\\usepackage{booktabs}``. The output can be copy/pasted\n into a main LaTeX document or read from an external file\n with ``\\input{table.tex}``.\n\n .. versionchanged:: 0.20.2\n Added to Series.\n\n .. versionchanged:: 1.0.0\n Added caption and label arguments.\n\n Parameters\n ----------\n buf : str, Path or StringIO-like, optional, default None\n Buffer to write to. If None, the output is returned as a string.\n columns : list of label, optional\n The subset of columns to write. Writes all columns by default.\n col_space : int, optional\n The minimum width of each column.\n header : bool or list of str, default True\n Write out the column names. If a list of strings is given,\n it is assumed to be aliases for the column names.\n index : bool, default True\n Write row names (index).\n na_rep : str, default 'NaN'\n Missing data representation.\n formatters : list of functions or dict of {str: function}, optional\n Formatter functions to apply to columns' elements by position or\n name. The result of each function must be a unicode string.\n List must be of length equal to the number of columns.\n float_format : one-parameter function or str, optional, default None\n Formatter for floating point numbers. For example\n ``float_format=\"%%.2f\"`` and ``float_format=\"{:0.2f}\".format`` will\n both result in 0.1234 being formatted as 0.12.\n sparsify : bool, optional\n Set to False for a DataFrame with a hierarchical index to print\n every multiindex key at each row. By default, the value will be\n read from the config module.\n index_names : bool, default True\n Prints the names of the indexes.\n bold_rows : bool, default False\n Make the row labels bold in the output.\n column_format : str, optional\n The columns format as specified in `LaTeX table format\n <https://en.wikibooks.org/wiki/LaTeX/Tables>`__ e.g. 'rcl' for 3\n columns. By default, 'l' will be used for all columns except\n columns of numbers, which default to 'r'.\n longtable : bool, optional\n By default, the value will be read from the pandas config\n module. Use a longtable environment instead of tabular. Requires\n adding a \\usepackage{longtable} to your LaTeX preamble.\n escape : bool, optional\n By default, the value will be read from the pandas config\n module. When set to False prevents from escaping latex special\n characters in column names.\n encoding : str, optional\n A string representing the encoding to use in the output file,\n defaults to 'utf-8'.\n decimal : str, default '.'\n Character recognized as decimal separator, e.g. ',' in Europe.\n multicolumn : bool, default True\n Use \\multicolumn to enhance MultiIndex columns.\n The default will be read from the config module.\n multicolumn_format : str, default 'l'\n The alignment for multicolumns, similar to `column_format`\n The default will be read from the config module.\n multirow : bool, default False\n Use \\multirow to enhance MultiIndex rows. Requires adding a\n \\usepackage{multirow} to your LaTeX preamble. Will print\n centered labels (instead of top-aligned) across the contained\n rows, separating groups via clines. The default will be read\n from the pandas config module.\n caption : str, optional\n The LaTeX caption to be placed inside ``\\caption{}`` in the output.\n\n .. versionadded:: 1.0.0\n\n label : str, optional\n The LaTeX label to be placed inside ``\\label{}`` in the output.\n This is used with ``\\ref{}`` in the main ``.tex`` file.\n\n .. versionadded:: 1.0.0\n %(returns)s\n See Also\n --------\n DataFrame.to_string : Render a DataFrame to a console-friendly\n tabular output.\n DataFrame.to_html : Render a DataFrame as an HTML table.\n\n Examples\n --------\n >>> df = pd.DataFrame({'name': ['Raphael', 'Donatello'],\n ... 'mask': ['red', 'purple'],\n ... 'weapon': ['sai', 'bo staff']})\n >>> print(df.to_latex(index=False)) # doctest: +NORMALIZE_WHITESPACE\n \\begin{tabular}{lll}\n \\toprule\n name & mask & weapon \\\\\n \\midrule\n Raphael & red & sai \\\\\n Donatello & purple & bo staff \\\\\n \\bottomrule\n \\end{tabular}\n \"\"\"\n # Get defaults from the pandas config\n if self.ndim == 1:\n self = self.to_frame()\n if longtable is None:\n longtable = config.get_option(\"display.latex.longtable\")\n if escape is None:\n escape = config.get_option(\"display.latex.escape\")\n if multicolumn is None:\n multicolumn = config.get_option(\"display.latex.multicolumn\")\n if multicolumn_format is None:\n multicolumn_format = config.get_option(\"display.latex.multicolumn_format\")\n if multirow is None:\n multirow = config.get_option(\"display.latex.multirow\")\n\n formatter = DataFrameFormatter(\n self,\n columns=columns,\n col_space=col_space,\n na_rep=na_rep,\n header=header,\n index=index,\n formatters=formatters,\n float_format=float_format,\n bold_rows=bold_rows,\n sparsify=sparsify,\n index_names=index_names,\n escape=escape,\n decimal=decimal,\n )\n return formatter.to_latex(\n buf=buf,\n column_format=column_format,\n longtable=longtable,\n encoding=encoding,\n multicolumn=multicolumn,\n multicolumn_format=multicolumn_format,\n multirow=multirow,\n caption=caption,\n label=label,\n )\n\n def to_csv(\n self,\n path_or_buf: Optional[FilePathOrBuffer] = None,\n sep: str = \",\",\n na_rep: str = \"\",\n float_format: Optional[str] = None,\n columns: Optional[Sequence[Optional[Hashable]]] = None,\n header: Union[bool_t, List[str]] = True,\n index: bool_t = True,\n index_label: Optional[Union[bool_t, str, Sequence[Optional[Hashable]]]] = None,\n mode: str = \"w\",\n encoding: Optional[str] = None,\n compression: Optional[Union[str, Mapping[str, str]]] = \"infer\",\n quoting: Optional[int] = None,\n quotechar: str = '\"',\n line_terminator: Optional[str] = None,\n chunksize: Optional[int] = None,\n date_format: Optional[str] = None,\n doublequote: bool_t = True,\n escapechar: Optional[str] = None,\n decimal: Optional[str] = \".\",\n ) -> Optional[str]:\n r\"\"\"\n Write object to a comma-separated values (csv) file.\n\n .. versionchanged:: 0.24.0\n The order of arguments for Series was changed.\n\n Parameters\n ----------\n path_or_buf : str or file handle, default None\n File path or object, if None is provided the result is returned as\n a string. If a file object is passed it should be opened with\n `newline=''`, disabling universal newlines.\n\n .. versionchanged:: 0.24.0\n\n Was previously named \"path\" for Series.\n\n sep : str, default ','\n String of length 1. Field delimiter for the output file.\n na_rep : str, default ''\n Missing data representation.\n float_format : str, default None\n Format string for floating point numbers.\n columns : sequence, optional\n Columns to write.\n header : bool or list of str, default True\n Write out the column names. If a list of strings is given it is\n assumed to be aliases for the column names.\n\n .. versionchanged:: 0.24.0\n\n Previously defaulted to False for Series.\n\n index : bool, default True\n Write row names (index).\n index_label : str or sequence, or False, default None\n Column label for index column(s) if desired. If None is given, and\n `header` and `index` are True, then the index names are used. A\n sequence should be given if the object uses MultiIndex. If\n False do not print fields for index names. Use index_label=False\n for easier importing in R.\n mode : str\n Python write mode, default 'w'.\n encoding : str, optional\n A string representing the encoding to use in the output file,\n defaults to 'utf-8'.\n compression : str or dict, default 'infer'\n If str, represents compression mode. If dict, value at 'method' is\n the compression mode. Compression mode may be any of the following\n possible values: {'infer', 'gzip', 'bz2', 'zip', 'xz', None}. If\n compression mode is 'infer' and `path_or_buf` is path-like, then\n detect compression mode from the following extensions: '.gz',\n '.bz2', '.zip' or '.xz'. (otherwise no compression). If dict given\n and mode is 'zip' or inferred as 'zip', other entries passed as\n additional compression options.\n\n .. versionchanged:: 1.0.0\n\n May now be a dict with key 'method' as compression mode\n and other entries as additional compression options if\n compression mode is 'zip'.\n\n quoting : optional constant from csv module\n Defaults to csv.QUOTE_MINIMAL. If you have set a `float_format`\n then floats are converted to strings and thus csv.QUOTE_NONNUMERIC\n will treat them as non-numeric.\n quotechar : str, default '\\\"'\n String of length 1. Character used to quote fields.\n line_terminator : str, optional\n The newline character or character sequence to use in the output\n file. Defaults to `os.linesep`, which depends on the OS in which\n this method is called ('\\n' for linux, '\\r\\n' for Windows, i.e.).\n\n .. versionchanged:: 0.24.0\n chunksize : int or None\n Rows to write at a time.\n date_format : str, default None\n Format string for datetime objects.\n doublequote : bool, default True\n Control quoting of `quotechar` inside a field.\n escapechar : str, default None\n String of length 1. Character used to escape `sep` and `quotechar`\n when appropriate.\n decimal : str, default '.'\n Character recognized as decimal separator. E.g. use ',' for\n European data.\n\n Returns\n -------\n None or str\n If path_or_buf is None, returns the resulting csv format as a\n string. Otherwise returns None.\n\n See Also\n --------\n read_csv : Load a CSV file into a DataFrame.\n to_excel : Write DataFrame to an Excel file.\n\n Examples\n --------\n >>> df = pd.DataFrame({'name': ['Raphael', 'Donatello'],\n ... 'mask': ['red', 'purple'],\n ... 'weapon': ['sai', 'bo staff']})\n >>> df.to_csv(index=False)\n 'name,mask,weapon\\nRaphael,red,sai\\nDonatello,purple,bo staff\\n'\n\n # create 'out.zip' containing 'out.csv'\n >>> compression_opts = dict(method='zip',\n ... archive_name='out.csv') # doctest: +SKIP\n\n >>> df.to_csv('out.zip', index=False,\n ... compression=compression_opts) # doctest: +SKIP\n \"\"\"\n\n df = self if isinstance(self, ABCDataFrame) else self.to_frame()\n\n from pandas.io.formats.csvs import CSVFormatter\n\n formatter = CSVFormatter(\n df,\n path_or_buf,\n line_terminator=line_terminator,\n sep=sep,\n encoding=encoding,\n compression=compression,\n quoting=quoting,\n na_rep=na_rep,\n float_format=float_format,\n cols=columns,\n header=header,\n index=index,\n index_label=index_label,\n mode=mode,\n chunksize=chunksize,\n quotechar=quotechar,\n date_format=date_format,\n doublequote=doublequote,\n escapechar=escapechar,\n decimal=decimal,\n )\n formatter.save()\n\n if path_or_buf is None:\n return formatter.path_or_buf.getvalue()\n\n return None\n\n # ----------------------------------------------------------------------\n # Fancy Indexing\n\n @classmethod\n def _create_indexer(cls, name: str, indexer) -> None:\n \"\"\"Create an indexer like _name in the class.\"\"\"\n if getattr(cls, name, None) is None:\n _indexer = functools.partial(indexer, name)\n setattr(cls, name, property(_indexer, doc=indexer.__doc__))\n\n # ----------------------------------------------------------------------\n # Lookup Caching\n\n def _set_as_cached(self, item, cacher) -> None:\n \"\"\"Set the _cacher attribute on the calling object with a weakref to\n cacher.\n \"\"\"\n self._cacher = (item, weakref.ref(cacher))\n\n def _reset_cacher(self) -> None:\n \"\"\"Reset the cacher.\"\"\"\n if hasattr(self, \"_cacher\"):\n del self._cacher\n\n def _maybe_cache_changed(self, item, value) -> None:\n \"\"\"The object has called back to us saying maybe it has changed.\n \"\"\"\n self._data.set(item, value)\n\n @property\n def _is_cached(self) -> bool_t:\n \"\"\"Return boolean indicating if self is cached or not.\"\"\"\n return getattr(self, \"_cacher\", None) is not None\n\n def _get_cacher(self):\n \"\"\"return my cacher or None\"\"\"\n cacher = getattr(self, \"_cacher\", None)\n if cacher is not None:\n cacher = cacher[1]()\n return cacher\n\n def _maybe_update_cacher(\n self, clear: bool_t = False, verify_is_copy: bool_t = True\n ) -> None:\n \"\"\"\n See if we need to update our parent cacher if clear, then clear our\n cache.\n\n Parameters\n ----------\n clear : bool, default False\n Clear the item cache.\n verify_is_copy : bool, default True\n Provide is_copy checks.\n \"\"\"\n\n cacher = getattr(self, \"_cacher\", None)\n if cacher is not None:\n ref = cacher[1]()\n\n # we are trying to reference a dead referant, hence\n # a copy\n if ref is None:\n del self._cacher\n else:\n # Note: we need to call ref._maybe_cache_changed even in the\n # case where it will raise. (Uh, not clear why)\n try:\n ref._maybe_cache_changed(cacher[0], self)\n except AssertionError:\n # ref._data.setitem can raise\n # AssertionError because of shape mismatch\n pass\n\n if verify_is_copy:\n self._check_setitem_copy(stacklevel=5, t=\"referant\")\n\n if clear:\n self._clear_item_cache()\n\n def _clear_item_cache(self) -> None:\n self._item_cache.clear()\n\n # ----------------------------------------------------------------------\n # Indexing Methods\n\n def take(self, indices, axis=0, is_copy: bool_t = True, **kwargs):\n \"\"\"\n Return the elements in the given *positional* indices along an axis.\n\n This means that we are not indexing according to actual values in\n the index attribute of the object. We are indexing according to the\n actual position of the element in the object.\n\n Parameters\n ----------\n indices : array-like\n An array of ints indicating which positions to take.\n axis : {0 or 'index', 1 or 'columns', None}, default 0\n The axis on which to select elements. ``0`` means that we are\n selecting rows, ``1`` means that we are selecting columns.\n is_copy : bool, default True\n Whether to return a copy of the original object or not.\n **kwargs\n For compatibility with :meth:`numpy.take`. Has no effect on the\n output.\n\n Returns\n -------\n taken : same type as caller\n An array-like containing the elements taken from the object.\n\n See Also\n --------\n DataFrame.loc : Select a subset of a DataFrame by labels.\n DataFrame.iloc : Select a subset of a DataFrame by positions.\n numpy.take : Take elements from an array along an axis.\n\n Examples\n --------\n >>> df = pd.DataFrame([('falcon', 'bird', 389.0),\n ... ('parrot', 'bird', 24.0),\n ... ('lion', 'mammal', 80.5),\n ... ('monkey', 'mammal', np.nan)],\n ... columns=['name', 'class', 'max_speed'],\n ... index=[0, 2, 3, 1])\n >>> df\n name class max_speed\n 0 falcon bird 389.0\n 2 parrot bird 24.0\n 3 lion mammal 80.5\n 1 monkey mammal NaN\n\n Take elements at positions 0 and 3 along the axis 0 (default).\n\n Note how the actual indices selected (0 and 1) do not correspond to\n our selected indices 0 and 3. That's because we are selecting the 0th\n and 3rd rows, not rows whose indices equal 0 and 3.\n\n >>> df.take([0, 3])\n name class max_speed\n 0 falcon bird 389.0\n 1 monkey mammal NaN\n\n Take elements at indices 1 and 2 along the axis 1 (column selection).\n\n >>> df.take([1, 2], axis=1)\n class max_speed\n 0 bird 389.0\n 2 bird 24.0\n 3 mammal 80.5\n 1 mammal NaN\n\n We may take elements using negative integers for positive indices,\n starting from the end of the object, just like with Python lists.\n\n >>> df.take([-1, -2])\n name class max_speed\n 1 monkey mammal NaN\n 3 lion mammal 80.5\n \"\"\"\n nv.validate_take(tuple(), kwargs)\n\n self._consolidate_inplace()\n\n new_data = self._data.take(\n indices, axis=self._get_block_manager_axis(axis), verify=True\n )\n result = self._constructor(new_data).__finalize__(self)\n\n # Maybe set copy if we didn't actually change the index.\n if is_copy:\n if not result._get_axis(axis).equals(self._get_axis(axis)):\n result._set_is_copy(self)\n\n return result\n\n def xs(self, key, axis=0, level=None, drop_level: bool_t = True):\n \"\"\"\n Return cross-section from the Series/DataFrame.\n\n This method takes a `key` argument to select data at a particular\n level of a MultiIndex.\n\n Parameters\n ----------\n key : label or tuple of label\n Label contained in the index, or partially in a MultiIndex.\n axis : {0 or 'index', 1 or 'columns'}, default 0\n Axis to retrieve cross-section on.\n level : object, defaults to first n levels (n=1 or len(key))\n In case of a key partially contained in a MultiIndex, indicate\n which levels are used. Levels can be referred by label or position.\n drop_level : bool, default True\n If False, returns object with same levels as self.\n\n Returns\n -------\n Series or DataFrame\n Cross-section from the original Series or DataFrame\n corresponding to the selected index levels.\n\n See Also\n --------\n DataFrame.loc : Access a group of rows and columns\n by label(s) or a boolean array.\n DataFrame.iloc : Purely integer-location based indexing\n for selection by position.\n\n Notes\n -----\n `xs` can not be used to set values.\n\n MultiIndex Slicers is a generic way to get/set values on\n any level or levels.\n It is a superset of `xs` functionality, see\n :ref:`MultiIndex Slicers <advanced.mi_slicers>`.\n\n Examples\n --------\n >>> d = {'num_legs': [4, 4, 2, 2],\n ... 'num_wings': [0, 0, 2, 2],\n ... 'class': ['mammal', 'mammal', 'mammal', 'bird'],\n ... 'animal': ['cat', 'dog', 'bat', 'penguin'],\n ... 'locomotion': ['walks', 'walks', 'flies', 'walks']}\n >>> df = pd.DataFrame(data=d)\n >>> df = df.set_index(['class', 'animal', 'locomotion'])\n >>> df\n num_legs num_wings\n class animal locomotion\n mammal cat walks 4 0\n dog walks 4 0\n bat flies 2 2\n bird penguin walks 2 2\n\n Get values at specified index\n\n >>> df.xs('mammal')\n num_legs num_wings\n animal locomotion\n cat walks 4 0\n dog walks 4 0\n bat flies 2 2\n\n Get values at several indexes\n\n >>> df.xs(('mammal', 'dog'))\n num_legs num_wings\n locomotion\n walks 4 0\n\n Get values at specified index and level\n\n >>> df.xs('cat', level=1)\n num_legs num_wings\n class locomotion\n mammal walks 4 0\n\n Get values at several indexes and levels\n\n >>> df.xs(('bird', 'walks'),\n ... level=[0, 'locomotion'])\n num_legs num_wings\n animal\n penguin 2 2\n\n Get values at specified column and axis\n\n >>> df.xs('num_wings', axis=1)\n class animal locomotion\n mammal cat walks 0\n dog walks 0\n bat flies 2\n bird penguin walks 2\n Name: num_wings, dtype: int64\n \"\"\"\n axis = self._get_axis_number(axis)\n labels = self._get_axis(axis)\n if level is not None:\n loc, new_ax = labels.get_loc_level(key, level=level, drop_level=drop_level)\n\n # create the tuple of the indexer\n _indexer = [slice(None)] * self.ndim\n _indexer[axis] = loc\n indexer = tuple(_indexer)\n\n result = self.iloc[indexer]\n setattr(result, result._get_axis_name(axis), new_ax)\n return result\n\n if axis == 1:\n return self[key]\n\n self._consolidate_inplace()\n\n index = self.index\n if isinstance(index, MultiIndex):\n loc, new_index = self.index.get_loc_level(key, drop_level=drop_level)\n else:\n loc = self.index.get_loc(key)\n\n if isinstance(loc, np.ndarray):\n if loc.dtype == np.bool_:\n (inds,) = loc.nonzero()\n return self.take(inds, axis=axis)\n else:\n return self.take(loc, axis=axis)\n\n if not is_scalar(loc):\n new_index = self.index[loc]\n\n if is_scalar(loc):\n new_values = self._data.fast_xs(loc)\n\n # may need to box a datelike-scalar\n #\n # if we encounter an array-like and we only have 1 dim\n # that means that their are list/ndarrays inside the Series!\n # so just return them (GH 6394)\n if not is_list_like(new_values) or self.ndim == 1:\n return com.maybe_box_datetimelike(new_values)\n\n result = self._constructor_sliced(\n new_values,\n index=self.columns,\n name=self.index[loc],\n dtype=new_values.dtype,\n )\n\n else:\n result = self.iloc[loc]\n result.index = new_index\n\n # this could be a view\n # but only in a single-dtyped view sliceable case\n result._set_is_copy(self, copy=not result._is_view)\n return result\n\n _xs: Callable = xs\n\n def __getitem__(self, item):\n raise AbstractMethodError(self)\n\n def _get_item_cache(self, item):\n \"\"\"Return the cached item, item represents a label indexer.\"\"\"\n cache = self._item_cache\n res = cache.get(item)\n if res is None:\n values = self._data.get(item)\n res = self._box_item_values(item, values)\n cache[item] = res\n res._set_as_cached(item, self)\n\n # for a chain\n res._is_copy = self._is_copy\n return res\n\n def _iget_item_cache(self, item):\n \"\"\"Return the cached item, item represents a positional indexer.\"\"\"\n ax = self._info_axis\n if ax.is_unique:\n lower = self._get_item_cache(ax[item])\n else:\n lower = self.take(item, axis=self._info_axis_number)\n return lower\n\n def _box_item_values(self, key, values):\n raise AbstractMethodError(self)\n\n def _slice(self, slobj: slice, axis=0, kind=None):\n \"\"\"\n Construct a slice of this container.\n\n kind parameter is maintained for compatibility with Series slicing.\n \"\"\"\n axis = self._get_block_manager_axis(axis)\n result = self._constructor(self._data.get_slice(slobj, axis=axis))\n result = result.__finalize__(self)\n\n # this could be a view\n # but only in a single-dtyped view sliceable case\n is_copy = axis != 0 or result._is_view\n result._set_is_copy(self, copy=is_copy)\n return result\n\n def _set_item(self, key, value) -> None:\n self._data.set(key, value)\n self._clear_item_cache()\n\n def _set_is_copy(self, ref=None, copy: bool_t = True) -> None:\n if not copy:\n self._is_copy = None\n else:\n if ref is not None:\n self._is_copy = weakref.ref(ref)\n else:\n self._is_copy = None\n\n def _check_is_chained_assignment_possible(self) -> bool_t:\n \"\"\"\n Check if we are a view, have a cacher, and are of mixed type.\n If so, then force a setitem_copy check.\n\n Should be called just near setting a value\n\n Will return a boolean if it we are a view and are cached, but a\n single-dtype meaning that the cacher should be updated following\n setting.\n \"\"\"\n if self._is_view and self._is_cached:\n ref = self._get_cacher()\n if ref is not None and ref._is_mixed_type:\n self._check_setitem_copy(stacklevel=4, t=\"referant\", force=True)\n return True\n elif self._is_copy:\n self._check_setitem_copy(stacklevel=4, t=\"referant\")\n return False\n\n def _check_setitem_copy(self, stacklevel=4, t=\"setting\", force=False):\n \"\"\"\n\n Parameters\n ----------\n stacklevel : int, default 4\n the level to show of the stack when the error is output\n t : str, the type of setting error\n force : bool, default False\n If True, then force showing an error.\n\n validate if we are doing a setitem on a chained copy.\n\n If you call this function, be sure to set the stacklevel such that the\n user will see the error *at the level of setting*\n\n It is technically possible to figure out that we are setting on\n a copy even WITH a multi-dtyped pandas object. In other words, some\n blocks may be views while other are not. Currently _is_view will ALWAYS\n return False for multi-blocks to avoid having to handle this case.\n\n df = DataFrame(np.arange(0,9), columns=['count'])\n df['group'] = 'b'\n\n # This technically need not raise SettingWithCopy if both are view\n # (which is not # generally guaranteed but is usually True. However,\n # this is in general not a good practice and we recommend using .loc.\n df.iloc[0:5]['group'] = 'a'\n\n \"\"\"\n\n # return early if the check is not needed\n if not (force or self._is_copy):\n return\n\n value = config.get_option(\"mode.chained_assignment\")\n if value is None:\n return\n\n # see if the copy is not actually referred; if so, then dissolve\n # the copy weakref\n if self._is_copy is not None and not isinstance(self._is_copy, str):\n r = self._is_copy()\n if not gc.get_referents(r) or r.shape == self.shape:\n self._is_copy = None\n return\n\n # a custom message\n if isinstance(self._is_copy, str):\n t = self._is_copy\n\n elif t == \"referant\":\n t = (\n \"\\n\"\n \"A value is trying to be set on a copy of a slice from a \"\n \"DataFrame\\n\\n\"\n \"See the caveats in the documentation: \"\n \"http://pandas.pydata.org/pandas-docs/stable/user_guide/\"\n \"indexing.html#returning-a-view-versus-a-copy\"\n )\n\n else:\n t = (\n \"\\n\"\n \"A value is trying to be set on a copy of a slice from a \"\n \"DataFrame.\\n\"\n \"Try using .loc[row_indexer,col_indexer] = value \"\n \"instead\\n\\nSee the caveats in the documentation: \"\n \"http://pandas.pydata.org/pandas-docs/stable/user_guide/\"\n \"indexing.html#returning-a-view-versus-a-copy\"\n )\n\n if value == \"raise\":\n raise com.SettingWithCopyError(t)\n elif value == \"warn\":\n warnings.warn(t, com.SettingWithCopyWarning, stacklevel=stacklevel)\n\n def __delitem__(self, key):\n \"\"\"\n Delete item\n \"\"\"\n deleted = False\n\n maybe_shortcut = False\n if self.ndim == 2 and isinstance(self.columns, MultiIndex):\n try:\n maybe_shortcut = key not in self.columns._engine\n except TypeError:\n pass\n\n if maybe_shortcut:\n # Allow shorthand to delete all columns whose first len(key)\n # elements match key:\n if not isinstance(key, tuple):\n key = (key,)\n for col in self.columns:\n if isinstance(col, tuple) and col[: len(key)] == key:\n del self[col]\n deleted = True\n if not deleted:\n # If the above loop ran and didn't delete anything because\n # there was no match, this call should raise the appropriate\n # exception:\n self._data.delete(key)\n\n # delete from the caches\n try:\n del self._item_cache[key]\n except KeyError:\n pass\n\n # ----------------------------------------------------------------------\n # Unsorted\n\n def get(self, key, default=None):\n \"\"\"\n Get item from object for given key (ex: DataFrame column).\n\n Returns default value if not found.\n\n Parameters\n ----------\n key : object\n\n Returns\n -------\n value : same type as items contained in object\n \"\"\"\n try:\n return self[key]\n except (KeyError, ValueError, IndexError):\n return default\n\n @property\n def _is_view(self):\n \"\"\"Return boolean indicating if self is view of another array \"\"\"\n return self._data.is_view\n\n def reindex_like(\n self,\n other,\n method: Optional[str] = None,\n copy: bool_t = True,\n limit=None,\n tolerance=None,\n ):\n \"\"\"\n Return an object with matching indices as other object.\n\n Conform the object to the same index on all axes. Optional\n filling logic, placing NaN in locations having no value\n in the previous index. A new object is produced unless the\n new index is equivalent to the current one and copy=False.\n\n Parameters\n ----------\n other : Object of the same data type\n Its row and column indices are used to define the new indices\n of this object.\n method : {None, 'backfill'/'bfill', 'pad'/'ffill', 'nearest'}\n Method to use for filling holes in reindexed DataFrame.\n Please note: this is only applicable to DataFrames/Series with a\n monotonically increasing/decreasing index.\n\n * None (default): don't fill gaps\n * pad / ffill: propagate last valid observation forward to next\n valid\n * backfill / bfill: use next valid observation to fill gap\n * nearest: use nearest valid observations to fill gap.\n\n copy : bool, default True\n Return a new object, even if the passed indexes are the same.\n limit : int, default None\n Maximum number of consecutive labels to fill for inexact matches.\n tolerance : optional\n Maximum distance between original and new labels for inexact\n matches. The values of the index at the matching locations most\n satisfy the equation ``abs(index[indexer] - target) <= tolerance``.\n\n Tolerance may be a scalar value, which applies the same tolerance\n to all values, or list-like, which applies variable tolerance per\n element. List-like includes list, tuple, array, Series, and must be\n the same size as the index and its dtype must exactly match the\n index's type.\n\n .. versionadded:: 0.21.0 (list-like tolerance)\n\n Returns\n -------\n Series or DataFrame\n Same type as caller, but with changed indices on each axis.\n\n See Also\n --------\n DataFrame.set_index : Set row labels.\n DataFrame.reset_index : Remove row labels or move them to new columns.\n DataFrame.reindex : Change to new indices or expand indices.\n\n Notes\n -----\n Same as calling\n ``.reindex(index=other.index, columns=other.columns,...)``.\n\n Examples\n --------\n >>> df1 = pd.DataFrame([[24.3, 75.7, 'high'],\n ... [31, 87.8, 'high'],\n ... [22, 71.6, 'medium'],\n ... [35, 95, 'medium']],\n ... columns=['temp_celsius', 'temp_fahrenheit',\n ... 'windspeed'],\n ... index=pd.date_range(start='2014-02-12',\n ... end='2014-02-15', freq='D'))\n\n >>> df1\n temp_celsius temp_fahrenheit windspeed\n 2014-02-12 24.3 75.7 high\n 2014-02-13 31.0 87.8 high\n 2014-02-14 22.0 71.6 medium\n 2014-02-15 35.0 95.0 medium\n\n >>> df2 = pd.DataFrame([[28, 'low'],\n ... [30, 'low'],\n ... [35.1, 'medium']],\n ... columns=['temp_celsius', 'windspeed'],\n ... index=pd.DatetimeIndex(['2014-02-12', '2014-02-13',\n ... '2014-02-15']))\n\n >>> df2\n temp_celsius windspeed\n 2014-02-12 28.0 low\n 2014-02-13 30.0 low\n 2014-02-15 35.1 medium\n\n >>> df2.reindex_like(df1)\n temp_celsius temp_fahrenheit windspeed\n 2014-02-12 28.0 NaN low\n 2014-02-13 30.0 NaN low\n 2014-02-14 NaN NaN NaN\n 2014-02-15 35.1 NaN medium\n \"\"\"\n d = other._construct_axes_dict(\n axes=self._AXIS_ORDERS,\n method=method,\n copy=copy,\n limit=limit,\n tolerance=tolerance,\n )\n\n return self.reindex(**d)\n\n def drop(\n self,\n labels=None,\n axis=0,\n index=None,\n columns=None,\n level=None,\n inplace: bool_t = False,\n errors: str = \"raise\",\n ):\n\n inplace = validate_bool_kwarg(inplace, \"inplace\")\n\n if labels is not None:\n if index is not None or columns is not None:\n raise ValueError(\"Cannot specify both 'labels' and 'index'/'columns'\")\n axis_name = self._get_axis_name(axis)\n axes = {axis_name: labels}\n elif index is not None or columns is not None:\n axes, _ = self._construct_axes_from_arguments((index, columns), {})\n else:\n raise ValueError(\n \"Need to specify at least one of 'labels', 'index' or 'columns'\"\n )\n\n obj = self\n\n for axis, labels in axes.items():\n if labels is not None:\n obj = obj._drop_axis(labels, axis, level=level, errors=errors)\n\n if inplace:\n self._update_inplace(obj)\n else:\n return obj\n\n def _drop_axis(self, labels, axis, level=None, errors: str = \"raise\"):\n \"\"\"\n Drop labels from specified axis. Used in the ``drop`` method\n internally.\n\n Parameters\n ----------\n labels : single label or list-like\n axis : int or axis name\n level : int or level name, default None\n For MultiIndex\n errors : {'ignore', 'raise'}, default 'raise'\n If 'ignore', suppress error and existing labels are dropped.\n\n \"\"\"\n axis = self._get_axis_number(axis)\n axis_name = self._get_axis_name(axis)\n axis = self._get_axis(axis)\n\n if axis.is_unique:\n if level is not None:\n if not isinstance(axis, MultiIndex):\n raise AssertionError(\"axis must be a MultiIndex\")\n new_axis = axis.drop(labels, level=level, errors=errors)\n else:\n new_axis = axis.drop(labels, errors=errors)\n result = self.reindex(**{axis_name: new_axis})\n\n # Case for non-unique axis\n else:\n labels = ensure_object(com.index_labels_to_array(labels))\n if level is not None:\n if not isinstance(axis, MultiIndex):\n raise AssertionError(\"axis must be a MultiIndex\")\n indexer = ~axis.get_level_values(level).isin(labels)\n\n # GH 18561 MultiIndex.drop should raise if label is absent\n if errors == \"raise\" and indexer.all():\n raise KeyError(f\"{labels} not found in axis\")\n else:\n indexer = ~axis.isin(labels)\n # Check if label doesn't exist along axis\n labels_missing = (axis.get_indexer_for(labels) == -1).any()\n if errors == \"raise\" and labels_missing:\n raise KeyError(f\"{labels} not found in axis\")\n\n slicer = [slice(None)] * self.ndim\n slicer[self._get_axis_number(axis_name)] = indexer\n\n result = self.loc[tuple(slicer)]\n\n return result\n\n def _update_inplace(self, result, verify_is_copy: bool_t = True) -> None:\n \"\"\"\n Replace self internals with result.\n\n Parameters\n ----------\n verify_is_copy : bool, default True\n Provide is_copy checks.\n \"\"\"\n # NOTE: This does *not* call __finalize__ and that's an explicit\n # decision that we may revisit in the future.\n\n self._reset_cache()\n self._clear_item_cache()\n self._data = getattr(result, \"_data\", result)\n self._maybe_update_cacher(verify_is_copy=verify_is_copy)\n\n def add_prefix(self, prefix: str):\n \"\"\"\n Prefix labels with string `prefix`.\n\n For Series, the row labels are prefixed.\n For DataFrame, the column labels are prefixed.\n\n Parameters\n ----------\n prefix : str\n The string to add before each label.\n\n Returns\n -------\n Series or DataFrame\n New Series or DataFrame with updated labels.\n\n See Also\n --------\n Series.add_suffix: Suffix row labels with string `suffix`.\n DataFrame.add_suffix: Suffix column labels with string `suffix`.\n\n Examples\n --------\n >>> s = pd.Series([1, 2, 3, 4])\n >>> s\n 0 1\n 1 2\n 2 3\n 3 4\n dtype: int64\n\n >>> s.add_prefix('item_')\n item_0 1\n item_1 2\n item_2 3\n item_3 4\n dtype: int64\n\n >>> df = pd.DataFrame({'A': [1, 2, 3, 4], 'B': [3, 4, 5, 6]})\n >>> df\n A B\n 0 1 3\n 1 2 4\n 2 3 5\n 3 4 6\n\n >>> df.add_prefix('col_')\n col_A col_B\n 0 1 3\n 1 2 4\n 2 3 5\n 3 4 6\n \"\"\"\n f = functools.partial(\"{prefix}{}\".format, prefix=prefix)\n\n mapper = {self._info_axis_name: f}\n return self.rename(**mapper)\n\n def add_suffix(self, suffix: str):\n \"\"\"\n Suffix labels with string `suffix`.\n\n For Series, the row labels are suffixed.\n For DataFrame, the column labels are suffixed.\n\n Parameters\n ----------\n suffix : str\n The string to add after each label.\n\n Returns\n -------\n Series or DataFrame\n New Series or DataFrame with updated labels.\n\n See Also\n --------\n Series.add_prefix: Prefix row labels with string `prefix`.\n DataFrame.add_prefix: Prefix column labels with string `prefix`.\n\n Examples\n --------\n >>> s = pd.Series([1, 2, 3, 4])\n >>> s\n 0 1\n 1 2\n 2 3\n 3 4\n dtype: int64\n\n >>> s.add_suffix('_item')\n 0_item 1\n 1_item 2\n 2_item 3\n 3_item 4\n dtype: int64\n\n >>> df = pd.DataFrame({'A': [1, 2, 3, 4], 'B': [3, 4, 5, 6]})\n >>> df\n A B\n 0 1 3\n 1 2 4\n 2 3 5\n 3 4 6\n\n >>> df.add_suffix('_col')\n A_col B_col\n 0 1 3\n 1 2 4\n 2 3 5\n 3 4 6\n \"\"\"\n f = functools.partial(\"{}{suffix}\".format, suffix=suffix)\n\n mapper = {self._info_axis_name: f}\n return self.rename(**mapper)\n\n def sort_values(\n self,\n by=None,\n axis=0,\n ascending=True,\n inplace: bool_t = False,\n kind: str = \"quicksort\",\n na_position: str = \"last\",\n ignore_index: bool_t = False,\n ):\n \"\"\"\n Sort by the values along either axis.\n\n Parameters\n ----------%(optional_by)s\n axis : %(axes_single_arg)s, default 0\n Axis to be sorted.\n ascending : bool or list of bool, default True\n Sort ascending vs. descending. Specify list for multiple sort\n orders. If this is a list of bools, must match the length of\n the by.\n inplace : bool, default False\n If True, perform operation in-place.\n kind : {'quicksort', 'mergesort', 'heapsort'}, default 'quicksort'\n Choice of sorting algorithm. See also ndarray.np.sort for more\n information. `mergesort` is the only stable algorithm. For\n DataFrames, this option is only applied when sorting on a single\n column or label.\n na_position : {'first', 'last'}, default 'last'\n Puts NaNs at the beginning if `first`; `last` puts NaNs at the\n end.\n ignore_index : bool, default False\n If True, the resulting axis will be labeled 0, 1, …, n - 1.\n\n .. versionadded:: 1.0.0\n\n Returns\n -------\n sorted_obj : DataFrame or None\n DataFrame with sorted values if inplace=False, None otherwise.\n\n Examples\n --------\n >>> df = pd.DataFrame({\n ... 'col1': ['A', 'A', 'B', np.nan, 'D', 'C'],\n ... 'col2': [2, 1, 9, 8, 7, 4],\n ... 'col3': [0, 1, 9, 4, 2, 3],\n ... })\n >>> df\n col1 col2 col3\n 0 A 2 0\n 1 A 1 1\n 2 B 9 9\n 3 NaN 8 4\n 4 D 7 2\n 5 C 4 3\n\n Sort by col1\n\n >>> df.sort_values(by=['col1'])\n col1 col2 col3\n 0 A 2 0\n 1 A 1 1\n 2 B 9 9\n 5 C 4 3\n 4 D 7 2\n 3 NaN 8 4\n\n Sort by multiple columns\n\n >>> df.sort_values(by=['col1', 'col2'])\n col1 col2 col3\n 1 A 1 1\n 0 A 2 0\n 2 B 9 9\n 5 C 4 3\n 4 D 7 2\n 3 NaN 8 4\n\n Sort Descending\n\n >>> df.sort_values(by='col1', ascending=False)\n col1 col2 col3\n 4 D 7 2\n 5 C 4 3\n 2 B 9 9\n 0 A 2 0\n 1 A 1 1\n 3 NaN 8 4\n\n Putting NAs first\n\n >>> df.sort_values(by='col1', ascending=False, na_position='first')\n col1 col2 col3\n 3 NaN 8 4\n 4 D 7 2\n 5 C 4 3\n 2 B 9 9\n 0 A 2 0\n 1 A 1 1\n \"\"\"\n raise AbstractMethodError(self)\n\n def sort_index(\n self,\n axis=0,\n level=None,\n ascending: bool_t = True,\n inplace: bool_t = False,\n kind: str = \"quicksort\",\n na_position: str = \"last\",\n sort_remaining: bool_t = True,\n ):\n \"\"\"\n Sort object by labels (along an axis).\n\n Parameters\n ----------\n axis : {0 or 'index', 1 or 'columns'}, default 0\n The axis along which to sort. The value 0 identifies the rows,\n and 1 identifies the columns.\n level : int or level name or list of ints or list of level names\n If not None, sort on values in specified index level(s).\n ascending : bool, default True\n Sort ascending vs. descending.\n inplace : bool, default False\n If True, perform operation in-place.\n kind : {'quicksort', 'mergesort', 'heapsort'}, default 'quicksort'\n Choice of sorting algorithm. See also ndarray.np.sort for more\n information. `mergesort` is the only stable algorithm. For\n DataFrames, this option is only applied when sorting on a single\n column or label.\n na_position : {'first', 'last'}, default 'last'\n Puts NaNs at the beginning if `first`; `last` puts NaNs at the end.\n Not implemented for MultiIndex.\n sort_remaining : bool, default True\n If True and sorting by level and index is multilevel, sort by other\n levels too (in order) after sorting by specified level.\n\n Returns\n -------\n sorted_obj : DataFrame or None\n DataFrame with sorted index if inplace=False, None otherwise.\n \"\"\"\n inplace = validate_bool_kwarg(inplace, \"inplace\")\n axis = self._get_axis_number(axis)\n axis_name = self._get_axis_name(axis)\n labels = self._get_axis(axis)\n\n if level is not None:\n raise NotImplementedError(\"level is not implemented\")\n if inplace:\n raise NotImplementedError(\"inplace is not implemented\")\n\n sort_index = labels.argsort()\n if not ascending:\n sort_index = sort_index[::-1]\n\n new_axis = labels.take(sort_index)\n return self.reindex(**{axis_name: new_axis})\n\n def reindex(self, *args, **kwargs):\n \"\"\"\n Conform %(klass)s to new index with optional filling logic.\n\n Places NA/NaN in locations having no value in the previous index. A new object\n is produced unless the new index is equivalent to the current one and\n ``copy=False``.\n\n Parameters\n ----------\n %(optional_labels)s\n %(axes)s : array-like, optional\n New labels / index to conform to, should be specified using\n keywords. Preferably an Index object to avoid duplicating data.\n %(optional_axis)s\n method : {None, 'backfill'/'bfill', 'pad'/'ffill', 'nearest'}\n Method to use for filling holes in reindexed DataFrame.\n Please note: this is only applicable to DataFrames/Series with a\n monotonically increasing/decreasing index.\n\n * None (default): don't fill gaps\n * pad / ffill: Propagate last valid observation forward to next\n valid.\n * backfill / bfill: Use next valid observation to fill gap.\n * nearest: Use nearest valid observations to fill gap.\n\n copy : bool, default True\n Return a new object, even if the passed indexes are the same.\n level : int or name\n Broadcast across a level, matching Index values on the\n passed MultiIndex level.\n fill_value : scalar, default np.NaN\n Value to use for missing values. Defaults to NaN, but can be any\n \"compatible\" value.\n limit : int, default None\n Maximum number of consecutive elements to forward or backward fill.\n tolerance : optional\n Maximum distance between original and new labels for inexact\n matches. The values of the index at the matching locations most\n satisfy the equation ``abs(index[indexer] - target) <= tolerance``.\n\n Tolerance may be a scalar value, which applies the same tolerance\n to all values, or list-like, which applies variable tolerance per\n element. List-like includes list, tuple, array, Series, and must be\n the same size as the index and its dtype must exactly match the\n index's type.\n\n .. versionadded:: 0.21.0 (list-like tolerance)\n\n Returns\n -------\n %(klass)s with changed index.\n\n See Also\n --------\n DataFrame.set_index : Set row labels.\n DataFrame.reset_index : Remove row labels or move them to new columns.\n DataFrame.reindex_like : Change to same indices as other DataFrame.\n\n Examples\n --------\n\n ``DataFrame.reindex`` supports two calling conventions\n\n * ``(index=index_labels, columns=column_labels, ...)``\n * ``(labels, axis={'index', 'columns'}, ...)``\n\n We *highly* recommend using keyword arguments to clarify your\n intent.\n\n Create a dataframe with some fictional data.\n\n >>> index = ['Firefox', 'Chrome', 'Safari', 'IE10', 'Konqueror']\n >>> df = pd.DataFrame({'http_status': [200, 200, 404, 404, 301],\n ... 'response_time': [0.04, 0.02, 0.07, 0.08, 1.0]},\n ... index=index)\n >>> df\n http_status response_time\n Firefox 200 0.04\n Chrome 200 0.02\n Safari 404 0.07\n IE10 404 0.08\n Konqueror 301 1.00\n\n Create a new index and reindex the dataframe. By default\n values in the new index that do not have corresponding\n records in the dataframe are assigned ``NaN``.\n\n >>> new_index = ['Safari', 'Iceweasel', 'Comodo Dragon', 'IE10',\n ... 'Chrome']\n >>> df.reindex(new_index)\n http_status response_time\n Safari 404.0 0.07\n Iceweasel NaN NaN\n Comodo Dragon NaN NaN\n IE10 404.0 0.08\n Chrome 200.0 0.02\n\n We can fill in the missing values by passing a value to\n the keyword ``fill_value``. Because the index is not monotonically\n increasing or decreasing, we cannot use arguments to the keyword\n ``method`` to fill the ``NaN`` values.\n\n >>> df.reindex(new_index, fill_value=0)\n http_status response_time\n Safari 404 0.07\n Iceweasel 0 0.00\n Comodo Dragon 0 0.00\n IE10 404 0.08\n Chrome 200 0.02\n\n >>> df.reindex(new_index, fill_value='missing')\n http_status response_time\n Safari 404 0.07\n Iceweasel missing missing\n Comodo Dragon missing missing\n IE10 404 0.08\n Chrome 200 0.02\n\n We can also reindex the columns.\n\n >>> df.reindex(columns=['http_status', 'user_agent'])\n http_status user_agent\n Firefox 200 NaN\n Chrome 200 NaN\n Safari 404 NaN\n IE10 404 NaN\n Konqueror 301 NaN\n\n Or we can use \"axis-style\" keyword arguments\n\n >>> df.reindex(['http_status', 'user_agent'], axis=\"columns\")\n http_status user_agent\n Firefox 200 NaN\n Chrome 200 NaN\n Safari 404 NaN\n IE10 404 NaN\n Konqueror 301 NaN\n\n To further illustrate the filling functionality in\n ``reindex``, we will create a dataframe with a\n monotonically increasing index (for example, a sequence\n of dates).\n\n >>> date_index = pd.date_range('1/1/2010', periods=6, freq='D')\n >>> df2 = pd.DataFrame({\"prices\": [100, 101, np.nan, 100, 89, 88]},\n ... index=date_index)\n >>> df2\n prices\n 2010-01-01 100.0\n 2010-01-02 101.0\n 2010-01-03 NaN\n 2010-01-04 100.0\n 2010-01-05 89.0\n 2010-01-06 88.0\n\n Suppose we decide to expand the dataframe to cover a wider\n date range.\n\n >>> date_index2 = pd.date_range('12/29/2009', periods=10, freq='D')\n >>> df2.reindex(date_index2)\n prices\n 2009-12-29 NaN\n 2009-12-30 NaN\n 2009-12-31 NaN\n 2010-01-01 100.0\n 2010-01-02 101.0\n 2010-01-03 NaN\n 2010-01-04 100.0\n 2010-01-05 89.0\n 2010-01-06 88.0\n 2010-01-07 NaN\n\n The index entries that did not have a value in the original data frame\n (for example, '2009-12-29') are by default filled with ``NaN``.\n If desired, we can fill in the missing values using one of several\n options.\n\n For example, to back-propagate the last valid value to fill the ``NaN``\n values, pass ``bfill`` as an argument to the ``method`` keyword.\n\n >>> df2.reindex(date_index2, method='bfill')\n prices\n 2009-12-29 100.0\n 2009-12-30 100.0\n 2009-12-31 100.0\n 2010-01-01 100.0\n 2010-01-02 101.0\n 2010-01-03 NaN\n 2010-01-04 100.0\n 2010-01-05 89.0\n 2010-01-06 88.0\n 2010-01-07 NaN\n\n Please note that the ``NaN`` value present in the original dataframe\n (at index value 2010-01-03) will not be filled by any of the\n value propagation schemes. This is because filling while reindexing\n does not look at dataframe values, but only compares the original and\n desired indexes. If you do want to fill in the ``NaN`` values present\n in the original dataframe, use the ``fillna()`` method.\n\n See the :ref:`user guide <basics.reindexing>` for more.\n \"\"\"\n # TODO: Decide if we care about having different examples for different\n # kinds\n\n # construct the args\n axes, kwargs = self._construct_axes_from_arguments(args, kwargs)\n method = missing.clean_reindex_fill_method(kwargs.pop(\"method\", None))\n level = kwargs.pop(\"level\", None)\n copy = kwargs.pop(\"copy\", True)\n limit = kwargs.pop(\"limit\", None)\n tolerance = kwargs.pop(\"tolerance\", None)\n fill_value = kwargs.pop(\"fill_value\", None)\n\n # Series.reindex doesn't use / need the axis kwarg\n # We pop and ignore it here, to make writing Series/Frame generic code\n # easier\n kwargs.pop(\"axis\", None)\n\n if kwargs:\n raise TypeError(\n \"reindex() got an unexpected keyword \"\n f'argument \"{list(kwargs.keys())[0]}\"'\n )\n\n self._consolidate_inplace()\n\n # if all axes that are requested to reindex are equal, then only copy\n # if indicated must have index names equal here as well as values\n if all(\n self._get_axis(axis).identical(ax)\n for axis, ax in axes.items()\n if ax is not None\n ):\n if copy:\n return self.copy()\n return self\n\n # check if we are a multi reindex\n if self._needs_reindex_multi(axes, method, level):\n return self._reindex_multi(axes, copy, fill_value)\n\n # perform the reindex on the axes\n return self._reindex_axes(\n axes, level, limit, tolerance, method, fill_value, copy\n ).__finalize__(self)\n\n def _reindex_axes(self, axes, level, limit, tolerance, method, fill_value, copy):\n \"\"\"Perform the reindex for all the axes.\"\"\"\n obj = self\n for a in self._AXIS_ORDERS:\n labels = axes[a]\n if labels is None:\n continue\n\n ax = self._get_axis(a)\n new_index, indexer = ax.reindex(\n labels, level=level, limit=limit, tolerance=tolerance, method=method\n )\n\n axis = self._get_axis_number(a)\n obj = obj._reindex_with_indexers(\n {axis: [new_index, indexer]},\n fill_value=fill_value,\n copy=copy,\n allow_dups=False,\n )\n\n return obj\n\n def _needs_reindex_multi(self, axes, method, level) -> bool_t:\n \"\"\"Check if we do need a multi reindex.\"\"\"\n return (\n (com.count_not_none(*axes.values()) == self._AXIS_LEN)\n and method is None\n and level is None\n and not self._is_mixed_type\n )\n\n def _reindex_multi(self, axes, copy, fill_value):\n raise AbstractMethodError(self)\n\n def _reindex_with_indexers(\n self,\n reindexers,\n fill_value=None,\n copy: bool_t = False,\n allow_dups: bool_t = False,\n ):\n \"\"\"allow_dups indicates an internal call here \"\"\"\n\n # reindex doing multiple operations on different axes if indicated\n new_data = self._data\n for axis in sorted(reindexers.keys()):\n index, indexer = reindexers[axis]\n baxis = self._get_block_manager_axis(axis)\n\n if index is None:\n continue\n\n index = ensure_index(index)\n if indexer is not None:\n indexer = ensure_int64(indexer)\n\n # TODO: speed up on homogeneous DataFrame objects\n new_data = new_data.reindex_indexer(\n index,\n indexer,\n axis=baxis,\n fill_value=fill_value,\n allow_dups=allow_dups,\n copy=copy,\n )\n\n if copy and new_data is self._data:\n new_data = new_data.copy()\n\n return self._constructor(new_data).__finalize__(self)\n\n def filter(\n self,\n items=None,\n like: Optional[str] = None,\n regex: Optional[str] = None,\n axis=None,\n ):\n \"\"\"\n Subset the dataframe rows or columns according to the specified index labels.\n\n Note that this routine does not filter a dataframe on its\n contents. The filter is applied to the labels of the index.\n\n Parameters\n ----------\n items : list-like\n Keep labels from axis which are in items.\n like : str\n Keep labels from axis for which \"like in label == True\".\n regex : str (regular expression)\n Keep labels from axis for which re.search(regex, label) == True.\n axis : {0 or ‘index’, 1 or ‘columns’, None}, default None\n The axis to filter on, expressed either as an index (int)\n or axis name (str). By default this is the info axis,\n 'index' for Series, 'columns' for DataFrame.\n\n Returns\n -------\n same type as input object\n\n See Also\n --------\n DataFrame.loc\n\n Notes\n -----\n The ``items``, ``like``, and ``regex`` parameters are\n enforced to be mutually exclusive.\n\n ``axis`` defaults to the info axis that is used when indexing\n with ``[]``.\n\n Examples\n --------\n >>> df = pd.DataFrame(np.array(([1, 2, 3], [4, 5, 6])),\n ... index=['mouse', 'rabbit'],\n ... columns=['one', 'two', 'three'])\n\n >>> # select columns by name\n >>> df.filter(items=['one', 'three'])\n one three\n mouse 1 3\n rabbit 4 6\n\n >>> # select columns by regular expression\n >>> df.filter(regex='e$', axis=1)\n one three\n mouse 1 3\n rabbit 4 6\n\n >>> # select rows containing 'bbi'\n >>> df.filter(like='bbi', axis=0)\n one two three\n rabbit 4 5 6\n \"\"\"\n nkw = com.count_not_none(items, like, regex)\n if nkw > 1:\n raise TypeError(\n \"Keyword arguments `items`, `like`, or `regex` \"\n \"are mutually exclusive\"\n )\n\n if axis is None:\n axis = self._info_axis_name\n labels = self._get_axis(axis)\n\n if items is not None:\n name = self._get_axis_name(axis)\n return self.reindex(**{name: [r for r in items if r in labels]})\n elif like:\n\n def f(x):\n return like in ensure_str(x)\n\n values = labels.map(f)\n return self.loc(axis=axis)[values]\n elif regex:\n\n def f(x):\n return matcher.search(ensure_str(x)) is not None\n\n matcher = re.compile(regex)\n values = labels.map(f)\n return self.loc(axis=axis)[values]\n else:\n raise TypeError(\"Must pass either `items`, `like`, or `regex`\")\n\n def head(self: FrameOrSeries, n: int = 5) -> FrameOrSeries:\n \"\"\"\n Return the first `n` rows.\n\n This function returns the first `n` rows for the object based\n on position. It is useful for quickly testing if your object\n has the right type of data in it.\n\n For negative values of `n`, this function returns all rows except\n the last `n` rows, equivalent to ``df[:-n]``.\n\n Parameters\n ----------\n n : int, default 5\n Number of rows to select.\n\n Returns\n -------\n same type as caller\n The first `n` rows of the caller object.\n\n See Also\n --------\n DataFrame.tail: Returns the last `n` rows.\n\n Examples\n --------\n >>> df = pd.DataFrame({'animal': ['alligator', 'bee', 'falcon', 'lion',\n ... 'monkey', 'parrot', 'shark', 'whale', 'zebra']})\n >>> df\n animal\n 0 alligator\n 1 bee\n 2 falcon\n 3 lion\n 4 monkey\n 5 parrot\n 6 shark\n 7 whale\n 8 zebra\n\n Viewing the first 5 lines\n\n >>> df.head()\n animal\n 0 alligator\n 1 bee\n 2 falcon\n 3 lion\n 4 monkey\n\n Viewing the first `n` lines (three in this case)\n\n >>> df.head(3)\n animal\n 0 alligator\n 1 bee\n 2 falcon\n\n For negative values of `n`\n\n >>> df.head(-3)\n animal\n 0 alligator\n 1 bee\n 2 falcon\n 3 lion\n 4 monkey\n 5 parrot\n \"\"\"\n\n return self.iloc[:n]\n\n def tail(self: FrameOrSeries, n: int = 5) -> FrameOrSeries:\n \"\"\"\n Return the last `n` rows.\n\n This function returns last `n` rows from the object based on\n position. It is useful for quickly verifying data, for example,\n after sorting or appending rows.\n\n For negative values of `n`, this function returns all rows except\n the first `n` rows, equivalent to ``df[n:]``.\n\n Parameters\n ----------\n n : int, default 5\n Number of rows to select.\n\n Returns\n -------\n type of caller\n The last `n` rows of the caller object.\n\n See Also\n --------\n DataFrame.head : The first `n` rows of the caller object.\n\n Examples\n --------\n >>> df = pd.DataFrame({'animal': ['alligator', 'bee', 'falcon', 'lion',\n ... 'monkey', 'parrot', 'shark', 'whale', 'zebra']})\n >>> df\n animal\n 0 alligator\n 1 bee\n 2 falcon\n 3 lion\n 4 monkey\n 5 parrot\n 6 shark\n 7 whale\n 8 zebra\n\n Viewing the last 5 lines\n\n >>> df.tail()\n animal\n 4 monkey\n 5 parrot\n 6 shark\n 7 whale\n 8 zebra\n\n Viewing the last `n` lines (three in this case)\n\n >>> df.tail(3)\n animal\n 6 shark\n 7 whale\n 8 zebra\n\n For negative values of `n`\n\n >>> df.tail(-3)\n animal\n 3 lion\n 4 monkey\n 5 parrot\n 6 shark\n 7 whale\n 8 zebra\n \"\"\"\n\n if n == 0:\n return self.iloc[0:0]\n return self.iloc[-n:]\n\n def sample(\n self,\n n=None,\n frac=None,\n replace=False,\n weights=None,\n random_state=None,\n axis=None,\n ):\n \"\"\"\n Return a random sample of items from an axis of object.\n\n You can use `random_state` for reproducibility.\n\n Parameters\n ----------\n n : int, optional\n Number of items from axis to return. Cannot be used with `frac`.\n Default = 1 if `frac` = None.\n frac : float, optional\n Fraction of axis items to return. Cannot be used with `n`.\n replace : bool, default False\n Allow or disallow sampling of the same row more than once.\n weights : str or ndarray-like, optional\n Default 'None' results in equal probability weighting.\n If passed a Series, will align with target object on index. Index\n values in weights not found in sampled object will be ignored and\n index values in sampled object not in weights will be assigned\n weights of zero.\n If called on a DataFrame, will accept the name of a column\n when axis = 0.\n Unless weights are a Series, weights must be same length as axis\n being sampled.\n If weights do not sum to 1, they will be normalized to sum to 1.\n Missing values in the weights column will be treated as zero.\n Infinite values not allowed.\n random_state : int or numpy.random.RandomState, optional\n Seed for the random number generator (if int), or numpy RandomState\n object.\n axis : {0 or ‘index’, 1 or ‘columns’, None}, default None\n Axis to sample. Accepts axis number or name. Default is stat axis\n for given data type (0 for Series and DataFrames).\n\n Returns\n -------\n Series or DataFrame\n A new object of same type as caller containing `n` items randomly\n sampled from the caller object.\n\n See Also\n --------\n numpy.random.choice: Generates a random sample from a given 1-D numpy\n array.\n\n Notes\n -----\n If `frac` > 1, `replacement` should be set to `True`.\n\n Examples\n --------\n >>> df = pd.DataFrame({'num_legs': [2, 4, 8, 0],\n ... 'num_wings': [2, 0, 0, 0],\n ... 'num_specimen_seen': [10, 2, 1, 8]},\n ... index=['falcon', 'dog', 'spider', 'fish'])\n >>> df\n num_legs num_wings num_specimen_seen\n falcon 2 2 10\n dog 4 0 2\n spider 8 0 1\n fish 0 0 8\n\n Extract 3 random elements from the ``Series`` ``df['num_legs']``:\n Note that we use `random_state` to ensure the reproducibility of\n the examples.\n\n >>> df['num_legs'].sample(n=3, random_state=1)\n fish 0\n spider 8\n falcon 2\n Name: num_legs, dtype: int64\n\n A random 50% sample of the ``DataFrame`` with replacement:\n\n >>> df.sample(frac=0.5, replace=True, random_state=1)\n num_legs num_wings num_specimen_seen\n dog 4 0 2\n fish 0 0 8\n\n An upsample sample of the ``DataFrame`` with replacement:\n Note that `replace` parameter has to be `True` for `frac` parameter > 1.\n\n >>> df.sample(frac=2, replace=True, random_state=1)\n num_legs num_wings num_specimen_seen\n dog 4 0 2\n fish 0 0 8\n falcon 2 2 10\n falcon 2 2 10\n fish 0 0 8\n dog 4 0 2\n fish 0 0 8\n dog 4 0 2\n\n Using a DataFrame column as weights. Rows with larger value in the\n `num_specimen_seen` column are more likely to be sampled.\n\n >>> df.sample(n=2, weights='num_specimen_seen', random_state=1)\n num_legs num_wings num_specimen_seen\n falcon 2 2 10\n fish 0 0 8\n \"\"\"\n\n if axis is None:\n axis = self._stat_axis_number\n\n axis = self._get_axis_number(axis)\n axis_length = self.shape[axis]\n\n # Process random_state argument\n rs = com.random_state(random_state)\n\n # Check weights for compliance\n if weights is not None:\n\n # If a series, align with frame\n if isinstance(weights, ABCSeries):\n weights = weights.reindex(self.axes[axis])\n\n # Strings acceptable if a dataframe and axis = 0\n if isinstance(weights, str):\n if isinstance(self, ABCDataFrame):\n if axis == 0:\n try:\n weights = self[weights]\n except KeyError:\n raise KeyError(\n \"String passed to weights not a valid column\"\n )\n else:\n raise ValueError(\n \"Strings can only be passed to \"\n \"weights when sampling from rows on \"\n \"a DataFrame\"\n )\n else:\n raise ValueError(\n \"Strings cannot be passed as weights \"\n \"when sampling from a Series.\"\n )\n\n weights = pd.Series(weights, dtype=\"float64\")\n\n if len(weights) != axis_length:\n raise ValueError(\n \"Weights and axis to be sampled must be of same length\"\n )\n\n if (weights == np.inf).any() or (weights == -np.inf).any():\n raise ValueError(\"weight vector may not include `inf` values\")\n\n if (weights < 0).any():\n raise ValueError(\"weight vector many not include negative values\")\n\n # If has nan, set to zero.\n weights = weights.fillna(0)\n\n # Renormalize if don't sum to 1\n if weights.sum() != 1:\n if weights.sum() != 0:\n weights = weights / weights.sum()\n else:\n raise ValueError(\"Invalid weights: weights sum to zero\")\n\n weights = weights.values\n\n # If no frac or n, default to n=1.\n if n is None and frac is None:\n n = 1\n elif frac is not None and frac > 1 and not replace:\n raise ValueError(\n \"Replace has to be set to `True` when \"\n \"upsampling the population `frac` > 1.\"\n )\n elif n is not None and frac is None and n % 1 != 0:\n raise ValueError(\"Only integers accepted as `n` values\")\n elif n is None and frac is not None:\n n = int(round(frac * axis_length))\n elif n is not None and frac is not None:\n raise ValueError(\"Please enter a value for `frac` OR `n`, not both\")\n\n # Check for negative sizes\n if n < 0:\n raise ValueError(\n \"A negative number of rows requested. Please provide positive value.\"\n )\n\n locs = rs.choice(axis_length, size=n, replace=replace, p=weights)\n return self.take(locs, axis=axis, is_copy=False)\n\n _shared_docs[\n \"pipe\"\n ] = r\"\"\"\n Apply func(self, \\*args, \\*\\*kwargs).\n\n Parameters\n ----------\n func : function\n Function to apply to the %(klass)s.\n ``args``, and ``kwargs`` are passed into ``func``.\n Alternatively a ``(callable, data_keyword)`` tuple where\n ``data_keyword`` is a string indicating the keyword of\n ``callable`` that expects the %(klass)s.\n args : iterable, optional\n Positional arguments passed into ``func``.\n kwargs : mapping, optional\n A dictionary of keyword arguments passed into ``func``.\n\n Returns\n -------\n object : the return type of ``func``.\n\n See Also\n --------\n DataFrame.apply\n DataFrame.applymap\n Series.map\n\n Notes\n -----\n\n Use ``.pipe`` when chaining together functions that expect\n Series, DataFrames or GroupBy objects. Instead of writing\n\n >>> f(g(h(df), arg1=a), arg2=b, arg3=c)\n\n You can write\n\n >>> (df.pipe(h)\n ... .pipe(g, arg1=a)\n ... .pipe(f, arg2=b, arg3=c)\n ... )\n\n If you have a function that takes the data as (say) the second\n argument, pass a tuple indicating which keyword expects the\n data. For example, suppose ``f`` takes its data as ``arg2``:\n\n >>> (df.pipe(h)\n ... .pipe(g, arg1=a)\n ... .pipe((f, 'arg2'), arg1=a, arg3=c)\n ... )\n \"\"\"\n\n @Appender(_shared_docs[\"pipe\"] % _shared_doc_kwargs)\n def pipe(self, func, *args, **kwargs):\n return com.pipe(self, func, *args, **kwargs)\n\n _shared_docs[\"aggregate\"] = dedent(\n \"\"\"\n Aggregate using one or more operations over the specified axis.\n %(versionadded)s\n Parameters\n ----------\n func : function, str, list or dict\n Function to use for aggregating the data. If a function, must either\n work when passed a %(klass)s or when passed to %(klass)s.apply.\n\n Accepted combinations are:\n\n - function\n - string function name\n - list of functions and/or function names, e.g. ``[np.sum, 'mean']``\n - dict of axis labels -> functions, function names or list of such.\n %(axis)s\n *args\n Positional arguments to pass to `func`.\n **kwargs\n Keyword arguments to pass to `func`.\n\n Returns\n -------\n scalar, Series or DataFrame\n\n The return can be:\n\n * scalar : when Series.agg is called with single function\n * Series : when DataFrame.agg is called with a single function\n * DataFrame : when DataFrame.agg is called with several functions\n\n Return scalar, Series or DataFrame.\n %(see_also)s\n Notes\n -----\n `agg` is an alias for `aggregate`. Use the alias.\n\n A passed user-defined-function will be passed a Series for evaluation.\n %(examples)s\"\"\"\n )\n\n _shared_docs[\n \"transform\"\n ] = \"\"\"\n Call ``func`` on self producing a %(klass)s with transformed values.\n\n Produced %(klass)s will have same axis length as self.\n\n Parameters\n ----------\n func : function, str, list or dict\n Function to use for transforming the data. If a function, must either\n work when passed a %(klass)s or when passed to %(klass)s.apply.\n\n Accepted combinations are:\n\n - function\n - string function name\n - list of functions and/or function names, e.g. ``[np.exp. 'sqrt']``\n - dict of axis labels -> functions, function names or list of such.\n %(axis)s\n *args\n Positional arguments to pass to `func`.\n **kwargs\n Keyword arguments to pass to `func`.\n\n Returns\n -------\n %(klass)s\n A %(klass)s that must have the same length as self.\n\n Raises\n ------\n ValueError : If the returned %(klass)s has a different length than self.\n\n See Also\n --------\n %(klass)s.agg : Only perform aggregating type operations.\n %(klass)s.apply : Invoke function on a %(klass)s.\n\n Examples\n --------\n >>> df = pd.DataFrame({'A': range(3), 'B': range(1, 4)})\n >>> df\n A B\n 0 0 1\n 1 1 2\n 2 2 3\n >>> df.transform(lambda x: x + 1)\n A B\n 0 1 2\n 1 2 3\n 2 3 4\n\n Even though the resulting %(klass)s must have the same length as the\n input %(klass)s, it is possible to provide several input functions:\n\n >>> s = pd.Series(range(3))\n >>> s\n 0 0\n 1 1\n 2 2\n dtype: int64\n >>> s.transform([np.sqrt, np.exp])\n sqrt exp\n 0 0.000000 1.000000\n 1 1.000000 2.718282\n 2 1.414214 7.389056\n \"\"\"\n\n # ----------------------------------------------------------------------\n # Attribute access\n\n def __finalize__(\n self: FrameOrSeries, other, method=None, **kwargs\n ) -> FrameOrSeries:\n \"\"\"\n Propagate metadata from other to self.\n\n Parameters\n ----------\n other : the object from which to get the attributes that we are going\n to propagate\n method : optional, a passed method name ; possibly to take different\n types of propagation actions based on this\n\n \"\"\"\n if isinstance(other, NDFrame):\n for name in other.attrs:\n self.attrs[name] = other.attrs[name]\n # For subclasses using _metadata.\n for name in self._metadata:\n object.__setattr__(self, name, getattr(other, name, None))\n return self\n\n def __getattr__(self, name: str):\n \"\"\"After regular attribute access, try looking up the name\n This allows simpler access to columns for interactive use.\n \"\"\"\n\n # Note: obj.x will always call obj.__getattribute__('x') prior to\n # calling obj.__getattr__('x').\n\n if (\n name in self._internal_names_set\n or name in self._metadata\n or name in self._accessors\n ):\n return object.__getattribute__(self, name)\n else:\n if self._info_axis._can_hold_identifiers_and_holds_name(name):\n return self[name]\n return object.__getattribute__(self, name)\n\n def __setattr__(self, name: str, value) -> None:\n \"\"\"After regular attribute access, try setting the name\n This allows simpler access to columns for interactive use.\n \"\"\"\n\n # first try regular attribute access via __getattribute__, so that\n # e.g. ``obj.x`` and ``obj.x = 4`` will always reference/modify\n # the same attribute.\n\n try:\n object.__getattribute__(self, name)\n return object.__setattr__(self, name, value)\n except AttributeError:\n pass\n\n # if this fails, go on to more involved attribute setting\n # (note that this matches __getattr__, above).\n if name in self._internal_names_set:\n object.__setattr__(self, name, value)\n elif name in self._metadata:\n object.__setattr__(self, name, value)\n else:\n try:\n existing = getattr(self, name)\n if isinstance(existing, Index):\n object.__setattr__(self, name, value)\n elif name in self._info_axis:\n self[name] = value\n else:\n object.__setattr__(self, name, value)\n except (AttributeError, TypeError):\n if isinstance(self, ABCDataFrame) and (is_list_like(value)):\n warnings.warn(\n \"Pandas doesn't allow columns to be \"\n \"created via a new attribute name - see \"\n \"https://pandas.pydata.org/pandas-docs/\"\n \"stable/indexing.html#attribute-access\",\n stacklevel=2,\n )\n object.__setattr__(self, name, value)\n\n def _dir_additions(self):\n \"\"\" add the string-like attributes from the info_axis.\n If info_axis is a MultiIndex, it's first level values are used.\n \"\"\"\n additions = {\n c\n for c in self._info_axis.unique(level=0)[:100]\n if isinstance(c, str) and c.isidentifier()\n }\n return super()._dir_additions().union(additions)\n\n # ----------------------------------------------------------------------\n # Consolidation of internals\n\n def _protect_consolidate(self, f):\n \"\"\"Consolidate _data -- if the blocks have changed, then clear the\n cache\n \"\"\"\n blocks_before = len(self._data.blocks)\n result = f()\n if len(self._data.blocks) != blocks_before:\n self._clear_item_cache()\n return result\n\n def _consolidate_inplace(self) -> None:\n \"\"\"Consolidate data in place and return None\"\"\"\n\n def f():\n self._data = self._data.consolidate()\n\n self._protect_consolidate(f)\n\n def _consolidate(self, inplace: bool_t = False):\n \"\"\"\n Compute NDFrame with \"consolidated\" internals (data of each dtype\n grouped together in a single ndarray).\n\n Parameters\n ----------\n inplace : bool, default False\n If False return new object, otherwise modify existing object.\n\n Returns\n -------\n consolidated : same type as caller\n \"\"\"\n inplace = validate_bool_kwarg(inplace, \"inplace\")\n if inplace:\n self._consolidate_inplace()\n else:\n f = lambda: self._data.consolidate()\n cons_data = self._protect_consolidate(f)\n return self._constructor(cons_data).__finalize__(self)\n\n @property\n def _is_mixed_type(self):\n f = lambda: self._data.is_mixed_type\n return self._protect_consolidate(f)\n\n @property\n def _is_numeric_mixed_type(self):\n f = lambda: self._data.is_numeric_mixed_type\n return self._protect_consolidate(f)\n\n @property\n def _is_datelike_mixed_type(self):\n f = lambda: self._data.is_datelike_mixed_type\n return self._protect_consolidate(f)\n\n def _check_inplace_setting(self, value) -> bool_t:\n \"\"\" check whether we allow in-place setting with this type of value \"\"\"\n\n if self._is_mixed_type:\n if not self._is_numeric_mixed_type:\n\n # allow an actual np.nan thru\n if is_float(value) and np.isnan(value):\n return True\n\n raise TypeError(\n \"Cannot do inplace boolean setting on \"\n \"mixed-types with a non np.nan value\"\n )\n\n return True\n\n def _get_numeric_data(self):\n return self._constructor(self._data.get_numeric_data()).__finalize__(self)\n\n def _get_bool_data(self):\n return self._constructor(self._data.get_bool_data()).__finalize__(self)\n\n # ----------------------------------------------------------------------\n # Internal Interface Methods\n\n @property\n def values(self):\n \"\"\"\n Return a Numpy representation of the DataFrame.\n\n .. warning::\n\n We recommend using :meth:`DataFrame.to_numpy` instead.\n\n Only the values in the DataFrame will be returned, the axes labels\n will be removed.\n\n Returns\n -------\n numpy.ndarray\n The values of the DataFrame.\n\n See Also\n --------\n DataFrame.to_numpy : Recommended alternative to this method.\n DataFrame.index : Retrieve the index labels.\n DataFrame.columns : Retrieving the column names.\n\n Notes\n -----\n The dtype will be a lower-common-denominator dtype (implicit\n upcasting); that is to say if the dtypes (even of numeric types)\n are mixed, the one that accommodates all will be chosen. Use this\n with care if you are not dealing with the blocks.\n\n e.g. If the dtypes are float16 and float32, dtype will be upcast to\n float32. If dtypes are int32 and uint8, dtype will be upcast to\n int32. By :func:`numpy.find_common_type` convention, mixing int64\n and uint64 will result in a float64 dtype.\n\n Examples\n --------\n A DataFrame where all columns are the same type (e.g., int64) results\n in an array of the same type.\n\n >>> df = pd.DataFrame({'age': [ 3, 29],\n ... 'height': [94, 170],\n ... 'weight': [31, 115]})\n >>> df\n age height weight\n 0 3 94 31\n 1 29 170 115\n >>> df.dtypes\n age int64\n height int64\n weight int64\n dtype: object\n >>> df.values\n array([[ 3, 94, 31],\n [ 29, 170, 115]], dtype=int64)\n\n A DataFrame with mixed type columns(e.g., str/object, int64, float32)\n results in an ndarray of the broadest type that accommodates these\n mixed types (e.g., object).\n\n >>> df2 = pd.DataFrame([('parrot', 24.0, 'second'),\n ... ('lion', 80.5, 1),\n ... ('monkey', np.nan, None)],\n ... columns=('name', 'max_speed', 'rank'))\n >>> df2.dtypes\n name object\n max_speed float64\n rank object\n dtype: object\n >>> df2.values\n array([['parrot', 24.0, 'second'],\n ['lion', 80.5, 1],\n ['monkey', nan, None]], dtype=object)\n \"\"\"\n self._consolidate_inplace()\n return self._data.as_array(transpose=self._AXIS_REVERSED)\n\n @property\n def _values(self):\n \"\"\"internal implementation\"\"\"\n return self.values\n\n @property\n def _get_values(self):\n # compat\n return self.values\n\n def _internal_get_values(self):\n \"\"\"\n Return an ndarray after converting sparse values to dense.\n\n This is the same as ``.values`` for non-sparse data. For sparse\n data contained in a `SparseArray`, the data are first\n converted to a dense representation.\n\n Returns\n -------\n numpy.ndarray\n Numpy representation of DataFrame.\n\n See Also\n --------\n values : Numpy representation of DataFrame.\n SparseArray : Container for sparse data.\n \"\"\"\n return self.values\n\n @property\n def dtypes(self):\n \"\"\"\n Return the dtypes in the DataFrame.\n\n This returns a Series with the data type of each column.\n The result's index is the original DataFrame's columns. Columns\n with mixed types are stored with the ``object`` dtype. See\n :ref:`the User Guide <basics.dtypes>` for more.\n\n Returns\n -------\n pandas.Series\n The data type of each column.\n\n Examples\n --------\n >>> df = pd.DataFrame({'float': [1.0],\n ... 'int': [1],\n ... 'datetime': [pd.Timestamp('20180310')],\n ... 'string': ['foo']})\n >>> df.dtypes\n float float64\n int int64\n datetime datetime64[ns]\n string object\n dtype: object\n \"\"\"\n from pandas import Series\n\n return Series(self._data.get_dtypes(), index=self._info_axis, dtype=np.object_)\n\n def _to_dict_of_blocks(self, copy: bool_t = True):\n \"\"\"\n Return a dict of dtype -> Constructor Types that\n each is a homogeneous dtype.\n\n Internal ONLY\n \"\"\"\n return {\n k: self._constructor(v).__finalize__(self)\n for k, v, in self._data.to_dict(copy=copy).items()\n }\n\n def astype(self, dtype, copy: bool_t = True, errors: str = \"raise\"):\n \"\"\"\n Cast a pandas object to a specified dtype ``dtype``.\n\n Parameters\n ----------\n dtype : data type, or dict of column name -> data type\n Use a numpy.dtype or Python type to cast entire pandas object to\n the same type. Alternatively, use {col: dtype, ...}, where col is a\n column label and dtype is a numpy.dtype or Python type to cast one\n or more of the DataFrame's columns to column-specific types.\n copy : bool, default True\n Return a copy when ``copy=True`` (be very careful setting\n ``copy=False`` as changes to values then may propagate to other\n pandas objects).\n errors : {'raise', 'ignore'}, default 'raise'\n Control raising of exceptions on invalid data for provided dtype.\n\n - ``raise`` : allow exceptions to be raised\n - ``ignore`` : suppress exceptions. On error return original object.\n\n Returns\n -------\n casted : same type as caller\n\n See Also\n --------\n to_datetime : Convert argument to datetime.\n to_timedelta : Convert argument to timedelta.\n to_numeric : Convert argument to a numeric type.\n numpy.ndarray.astype : Cast a numpy array to a specified type.\n\n Examples\n --------\n Create a DataFrame:\n\n >>> d = {'col1': [1, 2], 'col2': [3, 4]}\n >>> df = pd.DataFrame(data=d)\n >>> df.dtypes\n col1 int64\n col2 int64\n dtype: object\n\n Cast all columns to int32:\n\n >>> df.astype('int32').dtypes\n col1 int32\n col2 int32\n dtype: object\n\n Cast col1 to int32 using a dictionary:\n\n >>> df.astype({'col1': 'int32'}).dtypes\n col1 int32\n col2 int64\n dtype: object\n\n Create a series:\n\n >>> ser = pd.Series([1, 2], dtype='int32')\n >>> ser\n 0 1\n 1 2\n dtype: int32\n >>> ser.astype('int64')\n 0 1\n 1 2\n dtype: int64\n\n Convert to categorical type:\n\n >>> ser.astype('category')\n 0 1\n 1 2\n dtype: category\n Categories (2, int64): [1, 2]\n\n Convert to ordered categorical type with custom ordering:\n\n >>> cat_dtype = pd.api.types.CategoricalDtype(\n ... categories=[2, 1], ordered=True)\n >>> ser.astype(cat_dtype)\n 0 1\n 1 2\n dtype: category\n Categories (2, int64): [2 < 1]\n\n Note that using ``copy=False`` and changing data on a new\n pandas object may propagate changes:\n\n >>> s1 = pd.Series([1, 2])\n >>> s2 = s1.astype('int64', copy=False)\n >>> s2[0] = 10\n >>> s1 # note that s1[0] has changed too\n 0 10\n 1 2\n dtype: int64\n \"\"\"\n if is_dict_like(dtype):\n if self.ndim == 1: # i.e. Series\n if len(dtype) > 1 or self.name not in dtype:\n raise KeyError(\n \"Only the Series name can be used for \"\n \"the key in Series dtype mappings.\"\n )\n new_type = dtype[self.name]\n return self.astype(new_type, copy, errors)\n\n for col_name in dtype.keys():\n if col_name not in self:\n raise KeyError(\n \"Only a column name can be used for the \"\n \"key in a dtype mappings argument.\"\n )\n results = []\n for col_name, col in self.items():\n if col_name in dtype:\n results.append(\n col.astype(dtype=dtype[col_name], copy=copy, errors=errors)\n )\n else:\n results.append(col.copy() if copy else col)\n\n elif is_extension_array_dtype(dtype) and self.ndim > 1:\n # GH 18099/22869: columnwise conversion to extension dtype\n # GH 24704: use iloc to handle duplicate column names\n results = [\n self.iloc[:, i].astype(dtype, copy=copy)\n for i in range(len(self.columns))\n ]\n\n else:\n # else, only a single dtype is given\n new_data = self._data.astype(dtype=dtype, copy=copy, errors=errors)\n return self._constructor(new_data).__finalize__(self)\n\n # GH 19920: retain column metadata after concat\n result = pd.concat(results, axis=1, copy=False)\n result.columns = self.columns\n return result\n\n def copy(self: FrameOrSeries, deep: bool_t = True) -> FrameOrSeries:\n \"\"\"\n Make a copy of this object's indices and data.\n\n When ``deep=True`` (default), a new object will be created with a\n copy of the calling object's data and indices. Modifications to\n the data or indices of the copy will not be reflected in the\n original object (see notes below).\n\n When ``deep=False``, a new object will be created without copying\n the calling object's data or index (only references to the data\n and index are copied). Any changes to the data of the original\n will be reflected in the shallow copy (and vice versa).\n\n Parameters\n ----------\n deep : bool, default True\n Make a deep copy, including a copy of the data and the indices.\n With ``deep=False`` neither the indices nor the data are copied.\n\n Returns\n -------\n copy : Series or DataFrame\n Object type matches caller.\n\n Notes\n -----\n When ``deep=True``, data is copied but actual Python objects\n will not be copied recursively, only the reference to the object.\n This is in contrast to `copy.deepcopy` in the Standard Library,\n which recursively copies object data (see examples below).\n\n While ``Index`` objects are copied when ``deep=True``, the underlying\n numpy array is not copied for performance reasons. Since ``Index`` is\n immutable, the underlying data can be safely shared and a copy\n is not needed.\n\n Examples\n --------\n >>> s = pd.Series([1, 2], index=[\"a\", \"b\"])\n >>> s\n a 1\n b 2\n dtype: int64\n\n >>> s_copy = s.copy()\n >>> s_copy\n a 1\n b 2\n dtype: int64\n\n **Shallow copy versus default (deep) copy:**\n\n >>> s = pd.Series([1, 2], index=[\"a\", \"b\"])\n >>> deep = s.copy()\n >>> shallow = s.copy(deep=False)\n\n Shallow copy shares data and index with original.\n\n >>> s is shallow\n False\n >>> s.values is shallow.values and s.index is shallow.index\n True\n\n Deep copy has own copy of data and index.\n\n >>> s is deep\n False\n >>> s.values is deep.values or s.index is deep.index\n False\n\n Updates to the data shared by shallow copy and original is reflected\n in both; deep copy remains unchanged.\n\n >>> s[0] = 3\n >>> shallow[1] = 4\n >>> s\n a 3\n b 4\n dtype: int64\n >>> shallow\n a 3\n b 4\n dtype: int64\n >>> deep\n a 1\n b 2\n dtype: int64\n\n Note that when copying an object containing Python objects, a deep copy\n will copy the data, but will not do so recursively. Updating a nested\n data object will be reflected in the deep copy.\n\n >>> s = pd.Series([[1, 2], [3, 4]])\n >>> deep = s.copy()\n >>> s[0][0] = 10\n >>> s\n 0 [10, 2]\n 1 [3, 4]\n dtype: object\n >>> deep\n 0 [10, 2]\n 1 [3, 4]\n dtype: object\n \"\"\"\n data = self._data.copy(deep=deep)\n return self._constructor(data).__finalize__(self)\n\n def __copy__(self: FrameOrSeries, deep: bool_t = True) -> FrameOrSeries:\n return self.copy(deep=deep)\n\n def __deepcopy__(self: FrameOrSeries, memo=None) -> FrameOrSeries:\n \"\"\"\n Parameters\n ----------\n memo, default None\n Standard signature. Unused\n \"\"\"\n return self.copy(deep=True)\n\n def _convert(\n self: FrameOrSeries,\n datetime: bool_t = False,\n numeric: bool_t = False,\n timedelta: bool_t = False,\n coerce: bool_t = False,\n copy: bool_t = True,\n ) -> FrameOrSeries:\n \"\"\"\n Attempt to infer better dtype for object columns\n\n Parameters\n ----------\n datetime : bool, default False\n If True, convert to date where possible.\n numeric : bool, default False\n If True, attempt to convert to numbers (including strings), with\n unconvertible values becoming NaN.\n timedelta : bool, default False\n If True, convert to timedelta where possible.\n coerce : bool, default False\n If True, force conversion with unconvertible values converted to\n nulls (NaN or NaT).\n copy : bool, default True\n If True, return a copy even if no copy is necessary (e.g. no\n conversion was done). Note: This is meant for internal use, and\n should not be confused with inplace.\n\n Returns\n -------\n converted : same as input object\n \"\"\"\n validate_bool_kwarg(datetime, \"datetime\")\n validate_bool_kwarg(numeric, \"numeric\")\n validate_bool_kwarg(timedelta, \"timedelta\")\n validate_bool_kwarg(coerce, \"coerce\")\n validate_bool_kwarg(copy, \"copy\")\n return self._constructor(\n self._data.convert(\n datetime=datetime,\n numeric=numeric,\n timedelta=timedelta,\n coerce=coerce,\n copy=copy,\n )\n ).__finalize__(self)\n\n def infer_objects(self):\n \"\"\"\n Attempt to infer better dtypes for object columns.\n\n Attempts soft conversion of object-dtyped\n columns, leaving non-object and unconvertible\n columns unchanged. The inference rules are the\n same as during normal Series/DataFrame construction.\n\n .. versionadded:: 0.21.0\n\n Returns\n -------\n converted : same type as input object\n\n See Also\n --------\n to_datetime : Convert argument to datetime.\n to_timedelta : Convert argument to timedelta.\n to_numeric : Convert argument to numeric type.\n\n Examples\n --------\n >>> df = pd.DataFrame({\"A\": [\"a\", 1, 2, 3]})\n >>> df = df.iloc[1:]\n >>> df\n A\n 1 1\n 2 2\n 3 3\n\n >>> df.dtypes\n A object\n dtype: object\n\n >>> df.infer_objects().dtypes\n A int64\n dtype: object\n \"\"\"\n # numeric=False necessary to only soft convert;\n # python objects will still be converted to\n # native numpy numeric types\n return self._constructor(\n self._data.convert(\n datetime=True, numeric=False, timedelta=True, coerce=False, copy=True\n )\n ).__finalize__(self)\n\n # ----------------------------------------------------------------------\n # Filling NA's\n\n def fillna(\n self: FrameOrSeries,\n value=None,\n method=None,\n axis=None,\n inplace: bool_t = False,\n limit=None,\n downcast=None,\n ) -> Optional[FrameOrSeries]:\n \"\"\"\n Fill NA/NaN values using the specified method.\n\n Parameters\n ----------\n value : scalar, dict, Series, or DataFrame\n Value to use to fill holes (e.g. 0), alternately a\n dict/Series/DataFrame of values specifying which value to use for\n each index (for a Series) or column (for a DataFrame). Values not\n in the dict/Series/DataFrame will not be filled. This value cannot\n be a list.\n method : {'backfill', 'bfill', 'pad', 'ffill', None}, default None\n Method to use for filling holes in reindexed Series\n pad / ffill: propagate last valid observation forward to next valid\n backfill / bfill: use next valid observation to fill gap.\n axis : %(axes_single_arg)s\n Axis along which to fill missing values.\n inplace : bool, default False\n If True, fill in-place. Note: this will modify any\n other views on this object (e.g., a no-copy slice for a column in a\n DataFrame).\n limit : int, default None\n If method is specified, this is the maximum number of consecutive\n NaN values to forward/backward fill. In other words, if there is\n a gap with more than this number of consecutive NaNs, it will only\n be partially filled. If method is not specified, this is the\n maximum number of entries along the entire axis where NaNs will be\n filled. Must be greater than 0 if not None.\n downcast : dict, default is None\n A dict of item->dtype of what to downcast if possible,\n or the string 'infer' which will try to downcast to an appropriate\n equal type (e.g. float64 to int64 if possible).\n\n Returns\n -------\n %(klass)s or None\n Object with missing values filled or None if ``inplace=True``.\n\n See Also\n --------\n interpolate : Fill NaN values using interpolation.\n reindex : Conform object to new index.\n asfreq : Convert TimeSeries to specified frequency.\n\n Examples\n --------\n >>> df = pd.DataFrame([[np.nan, 2, np.nan, 0],\n ... [3, 4, np.nan, 1],\n ... [np.nan, np.nan, np.nan, 5],\n ... [np.nan, 3, np.nan, 4]],\n ... columns=list('ABCD'))\n >>> df\n A B C D\n 0 NaN 2.0 NaN 0\n 1 3.0 4.0 NaN 1\n 2 NaN NaN NaN 5\n 3 NaN 3.0 NaN 4\n\n Replace all NaN elements with 0s.\n\n >>> df.fillna(0)\n A B C D\n 0 0.0 2.0 0.0 0\n 1 3.0 4.0 0.0 1\n 2 0.0 0.0 0.0 5\n 3 0.0 3.0 0.0 4\n\n We can also propagate non-null values forward or backward.\n\n >>> df.fillna(method='ffill')\n A B C D\n 0 NaN 2.0 NaN 0\n 1 3.0 4.0 NaN 1\n 2 3.0 4.0 NaN 5\n 3 3.0 3.0 NaN 4\n\n Replace all NaN elements in column 'A', 'B', 'C', and 'D', with 0, 1,\n 2, and 3 respectively.\n\n >>> values = {'A': 0, 'B': 1, 'C': 2, 'D': 3}\n >>> df.fillna(value=values)\n A B C D\n 0 0.0 2.0 2.0 0\n 1 3.0 4.0 2.0 1\n 2 0.0 1.0 2.0 5\n 3 0.0 3.0 2.0 4\n\n Only replace the first NaN element.\n\n >>> df.fillna(value=values, limit=1)\n A B C D\n 0 0.0 2.0 2.0 0\n 1 3.0 4.0 NaN 1\n 2 NaN 1.0 NaN 5\n 3 NaN 3.0 NaN 4\n \"\"\"\n inplace = validate_bool_kwarg(inplace, \"inplace\")\n value, method = validate_fillna_kwargs(value, method)\n\n self._consolidate_inplace()\n\n # set the default here, so functions examining the signaure\n # can detect if something was set (e.g. in groupby) (GH9221)\n if axis is None:\n axis = 0\n axis = self._get_axis_number(axis)\n\n if value is None:\n\n if self._is_mixed_type and axis == 1:\n if inplace:\n raise NotImplementedError()\n result = self.T.fillna(method=method, limit=limit).T\n\n # need to downcast here because of all of the transposes\n result._data = result._data.downcast()\n\n return result\n\n new_data = self._data.interpolate(\n method=method,\n axis=axis,\n limit=limit,\n inplace=inplace,\n coerce=True,\n downcast=downcast,\n )\n else:\n if len(self._get_axis(axis)) == 0:\n return self\n\n if self.ndim == 1:\n if isinstance(value, (dict, ABCSeries)):\n value = create_series_with_explicit_dtype(\n value, dtype_if_empty=object\n )\n elif not is_list_like(value):\n pass\n else:\n raise TypeError(\n '\"value\" parameter must be a scalar, dict '\n \"or Series, but you passed a \"\n f'\"{type(value).__name__}\"'\n )\n\n new_data = self._data.fillna(\n value=value, limit=limit, inplace=inplace, downcast=downcast\n )\n\n elif isinstance(value, (dict, ABCSeries)):\n if axis == 1:\n raise NotImplementedError(\n \"Currently only can fill \"\n \"with dict/Series column \"\n \"by column\"\n )\n\n result = self if inplace else self.copy()\n for k, v in value.items():\n if k not in result:\n continue\n obj = result[k]\n obj.fillna(v, limit=limit, inplace=True, downcast=downcast)\n return result if not inplace else None\n\n elif not is_list_like(value):\n new_data = self._data.fillna(\n value=value, limit=limit, inplace=inplace, downcast=downcast\n )\n elif isinstance(value, ABCDataFrame) and self.ndim == 2:\n new_data = self.where(self.notna(), value)\n else:\n raise ValueError(f\"invalid fill value with a {type(value)}\")\n\n if inplace:\n self._update_inplace(new_data)\n return None\n else:\n return self._constructor(new_data).__finalize__(self)\n\n def ffill(\n self: FrameOrSeries,\n axis=None,\n inplace: bool_t = False,\n limit=None,\n downcast=None,\n ) -> Optional[FrameOrSeries]:\n \"\"\"\n Synonym for :meth:`DataFrame.fillna` with ``method='ffill'``.\n\n Returns\n -------\n %(klass)s or None\n Object with missing values filled or None if ``inplace=True``.\n \"\"\"\n return self.fillna(\n method=\"ffill\", axis=axis, inplace=inplace, limit=limit, downcast=downcast\n )\n\n def bfill(\n self: FrameOrSeries,\n axis=None,\n inplace: bool_t = False,\n limit=None,\n downcast=None,\n ) -> Optional[FrameOrSeries]:\n \"\"\"\n Synonym for :meth:`DataFrame.fillna` with ``method='bfill'``.\n\n Returns\n -------\n %(klass)s or None\n Object with missing values filled or None if ``inplace=True``.\n \"\"\"\n return self.fillna(\n method=\"bfill\", axis=axis, inplace=inplace, limit=limit, downcast=downcast\n )\n\n _shared_docs[\n \"replace\"\n ] = \"\"\"\n Replace values given in `to_replace` with `value`.\n\n Values of the %(klass)s are replaced with other values dynamically.\n This differs from updating with ``.loc`` or ``.iloc``, which require\n you to specify a location to update with some value.\n\n Parameters\n ----------\n to_replace : str, regex, list, dict, Series, int, float, or None\n How to find the values that will be replaced.\n\n * numeric, str or regex:\n\n - numeric: numeric values equal to `to_replace` will be\n replaced with `value`\n - str: string exactly matching `to_replace` will be replaced\n with `value`\n - regex: regexs matching `to_replace` will be replaced with\n `value`\n\n * list of str, regex, or numeric:\n\n - First, if `to_replace` and `value` are both lists, they\n **must** be the same length.\n - Second, if ``regex=True`` then all of the strings in **both**\n lists will be interpreted as regexs otherwise they will match\n directly. This doesn't matter much for `value` since there\n are only a few possible substitution regexes you can use.\n - str, regex and numeric rules apply as above.\n\n * dict:\n\n - Dicts can be used to specify different replacement values\n for different existing values. For example,\n ``{'a': 'b', 'y': 'z'}`` replaces the value 'a' with 'b' and\n 'y' with 'z'. To use a dict in this way the `value`\n parameter should be `None`.\n - For a DataFrame a dict can specify that different values\n should be replaced in different columns. For example,\n ``{'a': 1, 'b': 'z'}`` looks for the value 1 in column 'a'\n and the value 'z' in column 'b' and replaces these values\n with whatever is specified in `value`. The `value` parameter\n should not be ``None`` in this case. You can treat this as a\n special case of passing two lists except that you are\n specifying the column to search in.\n - For a DataFrame nested dictionaries, e.g.,\n ``{'a': {'b': np.nan}}``, are read as follows: look in column\n 'a' for the value 'b' and replace it with NaN. The `value`\n parameter should be ``None`` to use a nested dict in this\n way. You can nest regular expressions as well. Note that\n column names (the top-level dictionary keys in a nested\n dictionary) **cannot** be regular expressions.\n\n * None:\n\n - This means that the `regex` argument must be a string,\n compiled regular expression, or list, dict, ndarray or\n Series of such elements. If `value` is also ``None`` then\n this **must** be a nested dictionary or Series.\n\n See the examples section for examples of each of these.\n value : scalar, dict, list, str, regex, default None\n Value to replace any values matching `to_replace` with.\n For a DataFrame a dict of values can be used to specify which\n value to use for each column (columns not in the dict will not be\n filled). Regular expressions, strings and lists or dicts of such\n objects are also allowed.\n inplace : bool, default False\n If True, in place. Note: this will modify any\n other views on this object (e.g. a column from a DataFrame).\n Returns the caller if this is True.\n limit : int, default None\n Maximum size gap to forward or backward fill.\n regex : bool or same types as `to_replace`, default False\n Whether to interpret `to_replace` and/or `value` as regular\n expressions. If this is ``True`` then `to_replace` *must* be a\n string. Alternatively, this could be a regular expression or a\n list, dict, or array of regular expressions in which case\n `to_replace` must be ``None``.\n method : {'pad', 'ffill', 'bfill', `None`}\n The method to use when for replacement, when `to_replace` is a\n scalar, list or tuple and `value` is ``None``.\n\n .. versionchanged:: 0.23.0\n Added to DataFrame.\n\n Returns\n -------\n %(klass)s\n Object after replacement.\n\n Raises\n ------\n AssertionError\n * If `regex` is not a ``bool`` and `to_replace` is not\n ``None``.\n TypeError\n * If `to_replace` is a ``dict`` and `value` is not a ``list``,\n ``dict``, ``ndarray``, or ``Series``\n * If `to_replace` is ``None`` and `regex` is not compilable\n into a regular expression or is a list, dict, ndarray, or\n Series.\n * When replacing multiple ``bool`` or ``datetime64`` objects and\n the arguments to `to_replace` does not match the type of the\n value being replaced\n ValueError\n * If a ``list`` or an ``ndarray`` is passed to `to_replace` and\n `value` but they are not the same length.\n\n See Also\n --------\n %(klass)s.fillna : Fill NA values.\n %(klass)s.where : Replace values based on boolean condition.\n Series.str.replace : Simple string replacement.\n\n Notes\n -----\n * Regex substitution is performed under the hood with ``re.sub``. The\n rules for substitution for ``re.sub`` are the same.\n * Regular expressions will only substitute on strings, meaning you\n cannot provide, for example, a regular expression matching floating\n point numbers and expect the columns in your frame that have a\n numeric dtype to be matched. However, if those floating point\n numbers *are* strings, then you can do this.\n * This method has *a lot* of options. You are encouraged to experiment\n and play with this method to gain intuition about how it works.\n * When dict is used as the `to_replace` value, it is like\n key(s) in the dict are the to_replace part and\n value(s) in the dict are the value parameter.\n\n Examples\n --------\n\n **Scalar `to_replace` and `value`**\n\n >>> s = pd.Series([0, 1, 2, 3, 4])\n >>> s.replace(0, 5)\n 0 5\n 1 1\n 2 2\n 3 3\n 4 4\n dtype: int64\n\n >>> df = pd.DataFrame({'A': [0, 1, 2, 3, 4],\n ... 'B': [5, 6, 7, 8, 9],\n ... 'C': ['a', 'b', 'c', 'd', 'e']})\n >>> df.replace(0, 5)\n A B C\n 0 5 5 a\n 1 1 6 b\n 2 2 7 c\n 3 3 8 d\n 4 4 9 e\n\n **List-like `to_replace`**\n\n >>> df.replace([0, 1, 2, 3], 4)\n A B C\n 0 4 5 a\n 1 4 6 b\n 2 4 7 c\n 3 4 8 d\n 4 4 9 e\n\n >>> df.replace([0, 1, 2, 3], [4, 3, 2, 1])\n A B C\n 0 4 5 a\n 1 3 6 b\n 2 2 7 c\n 3 1 8 d\n 4 4 9 e\n\n >>> s.replace([1, 2], method='bfill')\n 0 0\n 1 3\n 2 3\n 3 3\n 4 4\n dtype: int64\n\n **dict-like `to_replace`**\n\n >>> df.replace({0: 10, 1: 100})\n A B C\n 0 10 5 a\n 1 100 6 b\n 2 2 7 c\n 3 3 8 d\n 4 4 9 e\n\n >>> df.replace({'A': 0, 'B': 5}, 100)\n A B C\n 0 100 100 a\n 1 1 6 b\n 2 2 7 c\n 3 3 8 d\n 4 4 9 e\n\n >>> df.replace({'A': {0: 100, 4: 400}})\n A B C\n 0 100 5 a\n 1 1 6 b\n 2 2 7 c\n 3 3 8 d\n 4 400 9 e\n\n **Regular expression `to_replace`**\n\n >>> df = pd.DataFrame({'A': ['bat', 'foo', 'bait'],\n ... 'B': ['abc', 'bar', 'xyz']})\n >>> df.replace(to_replace=r'^ba.$', value='new', regex=True)\n A B\n 0 new abc\n 1 foo new\n 2 bait xyz\n\n >>> df.replace({'A': r'^ba.$'}, {'A': 'new'}, regex=True)\n A B\n 0 new abc\n 1 foo bar\n 2 bait xyz\n\n >>> df.replace(regex=r'^ba.$', value='new')\n A B\n 0 new abc\n 1 foo new\n 2 bait xyz\n\n >>> df.replace(regex={r'^ba.$': 'new', 'foo': 'xyz'})\n A B\n 0 new abc\n 1 xyz new\n 2 bait xyz\n\n >>> df.replace(regex=[r'^ba.$', 'foo'], value='new')\n A B\n 0 new abc\n 1 new new\n 2 bait xyz\n\n Note that when replacing multiple ``bool`` or ``datetime64`` objects,\n the data types in the `to_replace` parameter must match the data\n type of the value being replaced:\n\n >>> df = pd.DataFrame({'A': [True, False, True],\n ... 'B': [False, True, False]})\n >>> df.replace({'a string': 'new value', True: False}) # raises\n Traceback (most recent call last):\n ...\n TypeError: Cannot compare types 'ndarray(dtype=bool)' and 'str'\n\n This raises a ``TypeError`` because one of the ``dict`` keys is not of\n the correct type for replacement.\n\n Compare the behavior of ``s.replace({'a': None})`` and\n ``s.replace('a', None)`` to understand the peculiarities\n of the `to_replace` parameter:\n\n >>> s = pd.Series([10, 'a', 'a', 'b', 'a'])\n\n When one uses a dict as the `to_replace` value, it is like the\n value(s) in the dict are equal to the `value` parameter.\n ``s.replace({'a': None})`` is equivalent to\n ``s.replace(to_replace={'a': None}, value=None, method=None)``:\n\n >>> s.replace({'a': None})\n 0 10\n 1 None\n 2 None\n 3 b\n 4 None\n dtype: object\n\n When ``value=None`` and `to_replace` is a scalar, list or\n tuple, `replace` uses the method parameter (default 'pad') to do the\n replacement. So this is why the 'a' values are being replaced by 10\n in rows 1 and 2 and 'b' in row 4 in this case.\n The command ``s.replace('a', None)`` is actually equivalent to\n ``s.replace(to_replace='a', value=None, method='pad')``:\n\n >>> s.replace('a', None)\n 0 10\n 1 10\n 2 10\n 3 b\n 4 b\n dtype: object\n \"\"\"\n\n @Appender(_shared_docs[\"replace\"] % _shared_doc_kwargs)\n def replace(\n self,\n to_replace=None,\n value=None,\n inplace=False,\n limit=None,\n regex=False,\n method=\"pad\",\n ):\n inplace = validate_bool_kwarg(inplace, \"inplace\")\n if not is_bool(regex) and to_replace is not None:\n raise AssertionError(\"'to_replace' must be 'None' if 'regex' is not a bool\")\n\n self._consolidate_inplace()\n\n if value is None:\n # passing a single value that is scalar like\n # when value is None (GH5319), for compat\n if not is_dict_like(to_replace) and not is_dict_like(regex):\n to_replace = [to_replace]\n\n if isinstance(to_replace, (tuple, list)):\n if isinstance(self, ABCDataFrame):\n return self.apply(\n _single_replace, args=(to_replace, method, inplace, limit)\n )\n return _single_replace(self, to_replace, method, inplace, limit)\n\n if not is_dict_like(to_replace):\n if not is_dict_like(regex):\n raise TypeError(\n 'If \"to_replace\" and \"value\" are both None'\n ' and \"to_replace\" is not a list, then '\n \"regex must be a mapping\"\n )\n to_replace = regex\n regex = True\n\n items = list(to_replace.items())\n keys, values = zip(*items) if items else ([], [])\n\n are_mappings = [is_dict_like(v) for v in values]\n\n if any(are_mappings):\n if not all(are_mappings):\n raise TypeError(\n \"If a nested mapping is passed, all values\"\n \" of the top level mapping must be \"\n \"mappings\"\n )\n # passed a nested dict/Series\n to_rep_dict = {}\n value_dict = {}\n\n for k, v in items:\n keys, values = list(zip(*v.items())) or ([], [])\n\n to_rep_dict[k] = list(keys)\n value_dict[k] = list(values)\n\n to_replace, value = to_rep_dict, value_dict\n else:\n to_replace, value = keys, values\n\n return self.replace(\n to_replace, value, inplace=inplace, limit=limit, regex=regex\n )\n else:\n\n # need a non-zero len on all axes\n if not self.size:\n return self\n\n new_data = self._data\n if is_dict_like(to_replace):\n if is_dict_like(value): # {'A' : NA} -> {'A' : 0}\n res = self if inplace else self.copy()\n for c, src in to_replace.items():\n if c in value and c in self:\n # object conversion is handled in\n # series.replace which is called recursively\n res[c] = res[c].replace(\n to_replace=src,\n value=value[c],\n inplace=False,\n regex=regex,\n )\n return None if inplace else res\n\n # {'A': NA} -> 0\n elif not is_list_like(value):\n keys = [(k, src) for k, src in to_replace.items() if k in self]\n keys_len = len(keys) - 1\n for i, (k, src) in enumerate(keys):\n convert = i == keys_len\n new_data = new_data.replace(\n to_replace=src,\n value=value,\n filter=[k],\n inplace=inplace,\n regex=regex,\n convert=convert,\n )\n else:\n raise TypeError(\"value argument must be scalar, dict, or Series\")\n\n elif is_list_like(to_replace): # [NA, ''] -> [0, 'missing']\n if is_list_like(value):\n if len(to_replace) != len(value):\n raise ValueError(\n f\"Replacement lists must match in length. \"\n f\"Expecting {len(to_replace)} got {len(value)} \"\n )\n\n new_data = self._data.replace_list(\n src_list=to_replace,\n dest_list=value,\n inplace=inplace,\n regex=regex,\n )\n\n else: # [NA, ''] -> 0\n new_data = self._data.replace(\n to_replace=to_replace, value=value, inplace=inplace, regex=regex\n )\n elif to_replace is None:\n if not (\n is_re_compilable(regex)\n or is_list_like(regex)\n or is_dict_like(regex)\n ):\n raise TypeError(\n f\"'regex' must be a string or a compiled regular expression \"\n f\"or a list or dict of strings or regular expressions, \"\n f\"you passed a {repr(type(regex).__name__)}\"\n )\n return self.replace(\n regex, value, inplace=inplace, limit=limit, regex=True\n )\n else:\n\n # dest iterable dict-like\n if is_dict_like(value): # NA -> {'A' : 0, 'B' : -1}\n new_data = self._data\n\n for k, v in value.items():\n if k in self:\n new_data = new_data.replace(\n to_replace=to_replace,\n value=v,\n filter=[k],\n inplace=inplace,\n regex=regex,\n )\n\n elif not is_list_like(value): # NA -> 0\n new_data = self._data.replace(\n to_replace=to_replace, value=value, inplace=inplace, regex=regex\n )\n else:\n raise TypeError(\n f'Invalid \"to_replace\" type: {repr(type(to_replace).__name__)}'\n )\n\n if inplace:\n self._update_inplace(new_data)\n else:\n return self._constructor(new_data).__finalize__(self)\n\n _shared_docs[\n \"interpolate\"\n ] = \"\"\"\n Please note that only ``method='linear'`` is supported for\n DataFrame/Series with a MultiIndex.\n\n Parameters\n ----------\n method : str, default 'linear'\n Interpolation technique to use. One of:\n\n * 'linear': Ignore the index and treat the values as equally\n spaced. This is the only method supported on MultiIndexes.\n * 'time': Works on daily and higher resolution data to interpolate\n given length of interval.\n * 'index', 'values': use the actual numerical values of the index.\n * 'pad': Fill in NaNs using existing values.\n * 'nearest', 'zero', 'slinear', 'quadratic', 'cubic', 'spline',\n 'barycentric', 'polynomial': Passed to\n `scipy.interpolate.interp1d`. These methods use the numerical\n values of the index. Both 'polynomial' and 'spline' require that\n you also specify an `order` (int), e.g.\n ``df.interpolate(method='polynomial', order=5)``.\n * 'krogh', 'piecewise_polynomial', 'spline', 'pchip', 'akima':\n Wrappers around the SciPy interpolation methods of similar\n names. See `Notes`.\n * 'from_derivatives': Refers to\n `scipy.interpolate.BPoly.from_derivatives` which\n replaces 'piecewise_polynomial' interpolation method in\n scipy 0.18.\n axis : {0 or 'index', 1 or 'columns', None}, default None\n Axis to interpolate along.\n limit : int, optional\n Maximum number of consecutive NaNs to fill. Must be greater than\n 0.\n inplace : bool, default False\n Update the data in place if possible.\n limit_direction : {'forward', 'backward', 'both'}, default 'forward'\n If limit is specified, consecutive NaNs will be filled in this\n direction.\n limit_area : {`None`, 'inside', 'outside'}, default None\n If limit is specified, consecutive NaNs will be filled with this\n restriction.\n\n * ``None``: No fill restriction.\n * 'inside': Only fill NaNs surrounded by valid values\n (interpolate).\n * 'outside': Only fill NaNs outside valid values (extrapolate).\n\n .. versionadded:: 0.23.0\n\n downcast : optional, 'infer' or None, defaults to None\n Downcast dtypes if possible.\n **kwargs\n Keyword arguments to pass on to the interpolating function.\n\n Returns\n -------\n Series or DataFrame\n Returns the same object type as the caller, interpolated at\n some or all ``NaN`` values.\n\n See Also\n --------\n fillna : Fill missing values using different methods.\n scipy.interpolate.Akima1DInterpolator : Piecewise cubic polynomials\n (Akima interpolator).\n scipy.interpolate.BPoly.from_derivatives : Piecewise polynomial in the\n Bernstein basis.\n scipy.interpolate.interp1d : Interpolate a 1-D function.\n scipy.interpolate.KroghInterpolator : Interpolate polynomial (Krogh\n interpolator).\n scipy.interpolate.PchipInterpolator : PCHIP 1-d monotonic cubic\n interpolation.\n scipy.interpolate.CubicSpline : Cubic spline data interpolator.\n\n Notes\n -----\n The 'krogh', 'piecewise_polynomial', 'spline', 'pchip' and 'akima'\n methods are wrappers around the respective SciPy implementations of\n similar names. These use the actual numerical values of the index.\n For more information on their behavior, see the\n `SciPy documentation\n <http://docs.scipy.org/doc/scipy/reference/interpolate.html#univariate-interpolation>`__\n and `SciPy tutorial\n <http://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html>`__.\n\n Examples\n --------\n Filling in ``NaN`` in a :class:`~pandas.Series` via linear\n interpolation.\n\n >>> s = pd.Series([0, 1, np.nan, 3])\n >>> s\n 0 0.0\n 1 1.0\n 2 NaN\n 3 3.0\n dtype: float64\n >>> s.interpolate()\n 0 0.0\n 1 1.0\n 2 2.0\n 3 3.0\n dtype: float64\n\n Filling in ``NaN`` in a Series by padding, but filling at most two\n consecutive ``NaN`` at a time.\n\n >>> s = pd.Series([np.nan, \"single_one\", np.nan,\n ... \"fill_two_more\", np.nan, np.nan, np.nan,\n ... 4.71, np.nan])\n >>> s\n 0 NaN\n 1 single_one\n 2 NaN\n 3 fill_two_more\n 4 NaN\n 5 NaN\n 6 NaN\n 7 4.71\n 8 NaN\n dtype: object\n >>> s.interpolate(method='pad', limit=2)\n 0 NaN\n 1 single_one\n 2 single_one\n 3 fill_two_more\n 4 fill_two_more\n 5 fill_two_more\n 6 NaN\n 7 4.71\n 8 4.71\n dtype: object\n\n Filling in ``NaN`` in a Series via polynomial interpolation or splines:\n Both 'polynomial' and 'spline' methods require that you also specify\n an ``order`` (int).\n\n >>> s = pd.Series([0, 2, np.nan, 8])\n >>> s.interpolate(method='polynomial', order=2)\n 0 0.000000\n 1 2.000000\n 2 4.666667\n 3 8.000000\n dtype: float64\n\n Fill the DataFrame forward (that is, going down) along each column\n using linear interpolation.\n\n Note how the last entry in column 'a' is interpolated differently,\n because there is no entry after it to use for interpolation.\n Note how the first entry in column 'b' remains ``NaN``, because there\n is no entry before it to use for interpolation.\n\n >>> df = pd.DataFrame([(0.0, np.nan, -1.0, 1.0),\n ... (np.nan, 2.0, np.nan, np.nan),\n ... (2.0, 3.0, np.nan, 9.0),\n ... (np.nan, 4.0, -4.0, 16.0)],\n ... columns=list('abcd'))\n >>> df\n a b c d\n 0 0.0 NaN -1.0 1.0\n 1 NaN 2.0 NaN NaN\n 2 2.0 3.0 NaN 9.0\n 3 NaN 4.0 -4.0 16.0\n >>> df.interpolate(method='linear', limit_direction='forward', axis=0)\n a b c d\n 0 0.0 NaN -1.0 1.0\n 1 1.0 2.0 -2.0 5.0\n 2 2.0 3.0 -3.0 9.0\n 3 2.0 4.0 -4.0 16.0\n\n Using polynomial interpolation.\n\n >>> df['d'].interpolate(method='polynomial', order=2)\n 0 1.0\n 1 4.0\n 2 9.0\n 3 16.0\n Name: d, dtype: float64\n \"\"\"\n\n @Appender(_shared_docs[\"interpolate\"] % _shared_doc_kwargs)\n def interpolate(\n self,\n method=\"linear\",\n axis=0,\n limit=None,\n inplace=False,\n limit_direction=\"forward\",\n limit_area=None,\n downcast=None,\n **kwargs,\n ):\n \"\"\"\n Interpolate values according to different methods.\n \"\"\"\n inplace = validate_bool_kwarg(inplace, \"inplace\")\n\n axis = self._get_axis_number(axis)\n\n if axis == 0:\n ax = self._info_axis_name\n _maybe_transposed_self = self\n elif axis == 1:\n _maybe_transposed_self = self.T\n ax = 1\n\n ax = _maybe_transposed_self._get_axis_number(ax)\n\n if _maybe_transposed_self.ndim == 2:\n alt_ax = 1 - ax\n else:\n alt_ax = ax\n\n if isinstance(_maybe_transposed_self.index, MultiIndex) and method != \"linear\":\n raise ValueError(\n \"Only `method=linear` interpolation is supported on MultiIndexes.\"\n )\n\n if _maybe_transposed_self._data.get_dtype_counts().get(\"object\") == len(\n _maybe_transposed_self.T\n ):\n raise TypeError(\n \"Cannot interpolate with all object-dtype columns \"\n \"in the DataFrame. Try setting at least one \"\n \"column to a numeric dtype.\"\n )\n\n # create/use the index\n if method == \"linear\":\n # prior default\n index = np.arange(len(_maybe_transposed_self._get_axis(alt_ax)))\n else:\n index = _maybe_transposed_self._get_axis(alt_ax)\n methods = {\"index\", \"values\", \"nearest\", \"time\"}\n is_numeric_or_datetime = (\n is_numeric_dtype(index)\n or is_datetime64_any_dtype(index)\n or is_timedelta64_dtype(index)\n )\n if method not in methods and not is_numeric_or_datetime:\n raise ValueError(\n \"Index column must be numeric or datetime type when \"\n f\"using {method} method other than linear. \"\n \"Try setting a numeric or datetime index column before \"\n \"interpolating.\"\n )\n\n if isna(index).any():\n raise NotImplementedError(\n \"Interpolation with NaNs in the index \"\n \"has not been implemented. Try filling \"\n \"those NaNs before interpolating.\"\n )\n data = _maybe_transposed_self._data\n new_data = data.interpolate(\n method=method,\n axis=ax,\n index=index,\n values=_maybe_transposed_self,\n limit=limit,\n limit_direction=limit_direction,\n limit_area=limit_area,\n inplace=inplace,\n downcast=downcast,\n **kwargs,\n )\n\n if inplace:\n if axis == 1:\n new_data = self._constructor(new_data).T._data\n self._update_inplace(new_data)\n else:\n res = self._constructor(new_data).__finalize__(self)\n if axis == 1:\n res = res.T\n return res\n\n # ----------------------------------------------------------------------\n # Timeseries methods Methods\n\n def asof(self, where, subset=None):\n \"\"\"\n Return the last row(s) without any NaNs before `where`.\n\n The last row (for each element in `where`, if list) without any\n NaN is taken.\n In case of a :class:`~pandas.DataFrame`, the last row without NaN\n considering only the subset of columns (if not `None`)\n\n If there is no good value, NaN is returned for a Series or\n a Series of NaN values for a DataFrame\n\n Parameters\n ----------\n where : date or array-like of dates\n Date(s) before which the last row(s) are returned.\n subset : str or array-like of str, default `None`\n For DataFrame, if not `None`, only use these columns to\n check for NaNs.\n\n Returns\n -------\n scalar, Series, or DataFrame\n\n The return can be:\n\n * scalar : when `self` is a Series and `where` is a scalar\n * Series: when `self` is a Series and `where` is an array-like,\n or when `self` is a DataFrame and `where` is a scalar\n * DataFrame : when `self` is a DataFrame and `where` is an\n array-like\n\n Return scalar, Series, or DataFrame.\n\n See Also\n --------\n merge_asof : Perform an asof merge. Similar to left join.\n\n Notes\n -----\n Dates are assumed to be sorted. Raises if this is not the case.\n\n Examples\n --------\n A Series and a scalar `where`.\n\n >>> s = pd.Series([1, 2, np.nan, 4], index=[10, 20, 30, 40])\n >>> s\n 10 1.0\n 20 2.0\n 30 NaN\n 40 4.0\n dtype: float64\n\n >>> s.asof(20)\n 2.0\n\n For a sequence `where`, a Series is returned. The first value is\n NaN, because the first element of `where` is before the first\n index value.\n\n >>> s.asof([5, 20])\n 5 NaN\n 20 2.0\n dtype: float64\n\n Missing values are not considered. The following is ``2.0``, not\n NaN, even though NaN is at the index location for ``30``.\n\n >>> s.asof(30)\n 2.0\n\n Take all columns into consideration\n\n >>> df = pd.DataFrame({'a': [10, 20, 30, 40, 50],\n ... 'b': [None, None, None, None, 500]},\n ... index=pd.DatetimeIndex(['2018-02-27 09:01:00',\n ... '2018-02-27 09:02:00',\n ... '2018-02-27 09:03:00',\n ... '2018-02-27 09:04:00',\n ... '2018-02-27 09:05:00']))\n >>> df.asof(pd.DatetimeIndex(['2018-02-27 09:03:30',\n ... '2018-02-27 09:04:30']))\n a b\n 2018-02-27 09:03:30 NaN NaN\n 2018-02-27 09:04:30 NaN NaN\n\n Take a single column into consideration\n\n >>> df.asof(pd.DatetimeIndex(['2018-02-27 09:03:30',\n ... '2018-02-27 09:04:30']),\n ... subset=['a'])\n a b\n 2018-02-27 09:03:30 30.0 NaN\n 2018-02-27 09:04:30 40.0 NaN\n \"\"\"\n if isinstance(where, str):\n where = Timestamp(where)\n\n if not self.index.is_monotonic:\n raise ValueError(\"asof requires a sorted index\")\n\n is_series = isinstance(self, ABCSeries)\n if is_series:\n if subset is not None:\n raise ValueError(\"subset is not valid for Series\")\n else:\n if subset is None:\n subset = self.columns\n if not is_list_like(subset):\n subset = [subset]\n\n is_list = is_list_like(where)\n if not is_list:\n start = self.index[0]\n if isinstance(self.index, PeriodIndex):\n where = Period(where, freq=self.index.freq).ordinal\n start = start.ordinal\n\n if where < start:\n if not is_series:\n from pandas import Series\n\n return Series(index=self.columns, name=where, dtype=np.float64)\n return np.nan\n\n # It's always much faster to use a *while* loop here for\n # Series than pre-computing all the NAs. However a\n # *while* loop is extremely expensive for DataFrame\n # so we later pre-compute all the NAs and use the same\n # code path whether *where* is a scalar or list.\n # See PR: https://github.com/pandas-dev/pandas/pull/14476\n if is_series:\n loc = self.index.searchsorted(where, side=\"right\")\n if loc > 0:\n loc -= 1\n\n values = self._values\n while loc > 0 and isna(values[loc]):\n loc -= 1\n return values[loc]\n\n if not isinstance(where, Index):\n where = Index(where) if is_list else Index([where])\n\n nulls = self.isna() if is_series else self[subset].isna().any(1)\n if nulls.all():\n if is_series:\n return self._constructor(np.nan, index=where, name=self.name)\n elif is_list:\n from pandas import DataFrame\n\n return DataFrame(np.nan, index=where, columns=self.columns)\n else:\n from pandas import Series\n\n return Series(np.nan, index=self.columns, name=where[0])\n\n locs = self.index.asof_locs(where, ~(nulls.values))\n\n # mask the missing\n missing = locs == -1\n data = self.take(locs, is_copy=False)\n data.index = where\n data.loc[missing] = np.nan\n return data if is_list else data.iloc[-1]\n\n # ----------------------------------------------------------------------\n # Action Methods\n\n _shared_docs[\n \"isna\"\n ] = \"\"\"\n Detect missing values.\n\n Return a boolean same-sized object indicating if the values are NA.\n NA values, such as None or :attr:`numpy.NaN`, gets mapped to True\n values.\n Everything else gets mapped to False values. Characters such as empty\n strings ``''`` or :attr:`numpy.inf` are not considered NA values\n (unless you set ``pandas.options.mode.use_inf_as_na = True``).\n\n Returns\n -------\n %(klass)s\n Mask of bool values for each element in %(klass)s that\n indicates whether an element is not an NA value.\n\n See Also\n --------\n %(klass)s.isnull : Alias of isna.\n %(klass)s.notna : Boolean inverse of isna.\n %(klass)s.dropna : Omit axes labels with missing values.\n isna : Top-level isna.\n\n Examples\n --------\n Show which entries in a DataFrame are NA.\n\n >>> df = pd.DataFrame({'age': [5, 6, np.NaN],\n ... 'born': [pd.NaT, pd.Timestamp('1939-05-27'),\n ... pd.Timestamp('1940-04-25')],\n ... 'name': ['Alfred', 'Batman', ''],\n ... 'toy': [None, 'Batmobile', 'Joker']})\n >>> df\n age born name toy\n 0 5.0 NaT Alfred None\n 1 6.0 1939-05-27 Batman Batmobile\n 2 NaN 1940-04-25 Joker\n\n >>> df.isna()\n age born name toy\n 0 False True False True\n 1 False False False False\n 2 True False False False\n\n Show which entries in a Series are NA.\n\n >>> ser = pd.Series([5, 6, np.NaN])\n >>> ser\n 0 5.0\n 1 6.0\n 2 NaN\n dtype: float64\n\n >>> ser.isna()\n 0 False\n 1 False\n 2 True\n dtype: bool\n \"\"\"\n\n @Appender(_shared_docs[\"isna\"] % _shared_doc_kwargs)\n def isna(self):\n return isna(self).__finalize__(self)\n\n @Appender(_shared_docs[\"isna\"] % _shared_doc_kwargs)\n def isnull(self):\n return isna(self).__finalize__(self)\n\n _shared_docs[\n \"notna\"\n ] = \"\"\"\n Detect existing (non-missing) values.\n\n Return a boolean same-sized object indicating if the values are not NA.\n Non-missing values get mapped to True. Characters such as empty\n strings ``''`` or :attr:`numpy.inf` are not considered NA values\n (unless you set ``pandas.options.mode.use_inf_as_na = True``).\n NA values, such as None or :attr:`numpy.NaN`, get mapped to False\n values.\n\n Returns\n -------\n %(klass)s\n Mask of bool values for each element in %(klass)s that\n indicates whether an element is not an NA value.\n\n See Also\n --------\n %(klass)s.notnull : Alias of notna.\n %(klass)s.isna : Boolean inverse of notna.\n %(klass)s.dropna : Omit axes labels with missing values.\n notna : Top-level notna.\n\n Examples\n --------\n Show which entries in a DataFrame are not NA.\n\n >>> df = pd.DataFrame({'age': [5, 6, np.NaN],\n ... 'born': [pd.NaT, pd.Timestamp('1939-05-27'),\n ... pd.Timestamp('1940-04-25')],\n ... 'name': ['Alfred', 'Batman', ''],\n ... 'toy': [None, 'Batmobile', 'Joker']})\n >>> df\n age born name toy\n 0 5.0 NaT Alfred None\n 1 6.0 1939-05-27 Batman Batmobile\n 2 NaN 1940-04-25 Joker\n\n >>> df.notna()\n age born name toy\n 0 True False True False\n 1 True True True True\n 2 False True True True\n\n Show which entries in a Series are not NA.\n\n >>> ser = pd.Series([5, 6, np.NaN])\n >>> ser\n 0 5.0\n 1 6.0\n 2 NaN\n dtype: float64\n\n >>> ser.notna()\n 0 True\n 1 True\n 2 False\n dtype: bool\n \"\"\"\n\n @Appender(_shared_docs[\"notna\"] % _shared_doc_kwargs)\n def notna(self):\n return notna(self).__finalize__(self)\n\n @Appender(_shared_docs[\"notna\"] % _shared_doc_kwargs)\n def notnull(self):\n return notna(self).__finalize__(self)\n\n def _clip_with_scalar(self, lower, upper, inplace: bool_t = False):\n if (lower is not None and np.any(isna(lower))) or (\n upper is not None and np.any(isna(upper))\n ):\n raise ValueError(\"Cannot use an NA value as a clip threshold\")\n\n result = self\n mask = isna(self.values)\n\n with np.errstate(all=\"ignore\"):\n if upper is not None:\n subset = self.to_numpy() <= upper\n result = result.where(subset, upper, axis=None, inplace=False)\n if lower is not None:\n subset = self.to_numpy() >= lower\n result = result.where(subset, lower, axis=None, inplace=False)\n\n if np.any(mask):\n result[mask] = np.nan\n\n if inplace:\n self._update_inplace(result)\n else:\n return result\n\n def _clip_with_one_bound(self, threshold, method, axis, inplace):\n\n if axis is not None:\n axis = self._get_axis_number(axis)\n\n # method is self.le for upper bound and self.ge for lower bound\n if is_scalar(threshold) and is_number(threshold):\n if method.__name__ == \"le\":\n return self._clip_with_scalar(None, threshold, inplace=inplace)\n return self._clip_with_scalar(threshold, None, inplace=inplace)\n\n subset = method(threshold, axis=axis) | isna(self)\n\n # GH #15390\n # In order for where method to work, the threshold must\n # be transformed to NDFrame from other array like structure.\n if (not isinstance(threshold, ABCSeries)) and is_list_like(threshold):\n if isinstance(self, ABCSeries):\n threshold = self._constructor(threshold, index=self.index)\n else:\n threshold = _align_method_FRAME(self, threshold, axis)\n return self.where(subset, threshold, axis=axis, inplace=inplace)\n\n def clip(\n self,\n lower=None,\n upper=None,\n axis=None,\n inplace: bool_t = False,\n *args,\n **kwargs,\n ):\n \"\"\"\n Trim values at input threshold(s).\n\n Assigns values outside boundary to boundary values. Thresholds\n can be singular values or array like, and in the latter case\n the clipping is performed element-wise in the specified axis.\n\n Parameters\n ----------\n lower : float or array_like, default None\n Minimum threshold value. All values below this\n threshold will be set to it.\n upper : float or array_like, default None\n Maximum threshold value. All values above this\n threshold will be set to it.\n axis : int or str axis name, optional\n Align object with lower and upper along the given axis.\n inplace : bool, default False\n Whether to perform the operation in place on the data.\n\n .. versionadded:: 0.21.0\n *args, **kwargs\n Additional keywords have no effect but might be accepted\n for compatibility with numpy.\n\n Returns\n -------\n Series or DataFrame\n Same type as calling object with the values outside the\n clip boundaries replaced.\n\n Examples\n --------\n >>> data = {'col_0': [9, -3, 0, -1, 5], 'col_1': [-2, -7, 6, 8, -5]}\n >>> df = pd.DataFrame(data)\n >>> df\n col_0 col_1\n 0 9 -2\n 1 -3 -7\n 2 0 6\n 3 -1 8\n 4 5 -5\n\n Clips per column using lower and upper thresholds:\n\n >>> df.clip(-4, 6)\n col_0 col_1\n 0 6 -2\n 1 -3 -4\n 2 0 6\n 3 -1 6\n 4 5 -4\n\n Clips using specific lower and upper thresholds per column element:\n\n >>> t = pd.Series([2, -4, -1, 6, 3])\n >>> t\n 0 2\n 1 -4\n 2 -1\n 3 6\n 4 3\n dtype: int64\n\n >>> df.clip(t, t + 4, axis=0)\n col_0 col_1\n 0 6 2\n 1 -3 -4\n 2 0 3\n 3 6 8\n 4 5 3\n \"\"\"\n inplace = validate_bool_kwarg(inplace, \"inplace\")\n\n axis = nv.validate_clip_with_axis(axis, args, kwargs)\n if axis is not None:\n axis = self._get_axis_number(axis)\n\n # GH 17276\n # numpy doesn't like NaN as a clip value\n # so ignore\n # GH 19992\n # numpy doesn't drop a list-like bound containing NaN\n if not is_list_like(lower) and np.any(isna(lower)):\n lower = None\n if not is_list_like(upper) and np.any(isna(upper)):\n upper = None\n\n # GH 2747 (arguments were reversed)\n if lower is not None and upper is not None:\n if is_scalar(lower) and is_scalar(upper):\n lower, upper = min(lower, upper), max(lower, upper)\n\n # fast-path for scalars\n if (lower is None or (is_scalar(lower) and is_number(lower))) and (\n upper is None or (is_scalar(upper) and is_number(upper))\n ):\n return self._clip_with_scalar(lower, upper, inplace=inplace)\n\n result = self\n if lower is not None:\n result = result._clip_with_one_bound(\n lower, method=self.ge, axis=axis, inplace=inplace\n )\n if upper is not None:\n if inplace:\n result = self\n result = result._clip_with_one_bound(\n upper, method=self.le, axis=axis, inplace=inplace\n )\n\n return result\n\n def groupby(\n self,\n by=None,\n axis=0,\n level=None,\n as_index: bool_t = True,\n sort: bool_t = True,\n group_keys: bool_t = True,\n squeeze: bool_t = False,\n observed: bool_t = False,\n ):\n \"\"\"\n Group DataFrame or Series using a mapper or by a Series of columns.\n\n A groupby operation involves some combination of splitting the\n object, applying a function, and combining the results. This can be\n used to group large amounts of data and compute operations on these\n groups.\n\n Parameters\n ----------\n by : mapping, function, label, or list of labels\n Used to determine the groups for the groupby.\n If ``by`` is a function, it's called on each value of the object's\n index. If a dict or Series is passed, the Series or dict VALUES\n will be used to determine the groups (the Series' values are first\n aligned; see ``.align()`` method). If an ndarray is passed, the\n values are used as-is determine the groups. A label or list of\n labels may be passed to group by the columns in ``self``. Notice\n that a tuple is interpreted as a (single) key.\n axis : {0 or 'index', 1 or 'columns'}, default 0\n Split along rows (0) or columns (1).\n level : int, level name, or sequence of such, default None\n If the axis is a MultiIndex (hierarchical), group by a particular\n level or levels.\n as_index : bool, default True\n For aggregated output, return object with group labels as the\n index. Only relevant for DataFrame input. as_index=False is\n effectively \"SQL-style\" grouped output.\n sort : bool, default True\n Sort group keys. Get better performance by turning this off.\n Note this does not influence the order of observations within each\n group. Groupby preserves the order of rows within each group.\n group_keys : bool, default True\n When calling apply, add group keys to index to identify pieces.\n squeeze : bool, default False\n Reduce the dimensionality of the return type if possible,\n otherwise return a consistent type.\n observed : bool, default False\n This only applies if any of the groupers are Categoricals.\n If True: only show observed values for categorical groupers.\n If False: show all values for categorical groupers.\n\n .. versionadded:: 0.23.0\n\n Returns\n -------\n DataFrameGroupBy or SeriesGroupBy\n Depends on the calling object and returns groupby object that\n contains information about the groups.\n\n See Also\n --------\n resample : Convenience method for frequency conversion and resampling\n of time series.\n\n Notes\n -----\n See the `user guide\n <http://pandas.pydata.org/pandas-docs/stable/groupby.html>`_ for more.\n\n Examples\n --------\n >>> df = pd.DataFrame({'Animal': ['Falcon', 'Falcon',\n ... 'Parrot', 'Parrot'],\n ... 'Max Speed': [380., 370., 24., 26.]})\n >>> df\n Animal Max Speed\n 0 Falcon 380.0\n 1 Falcon 370.0\n 2 Parrot 24.0\n 3 Parrot 26.0\n >>> df.groupby(['Animal']).mean()\n Max Speed\n Animal\n Falcon 375.0\n Parrot 25.0\n\n **Hierarchical Indexes**\n\n We can groupby different levels of a hierarchical index\n using the `level` parameter:\n\n >>> arrays = [['Falcon', 'Falcon', 'Parrot', 'Parrot'],\n ... ['Captive', 'Wild', 'Captive', 'Wild']]\n >>> index = pd.MultiIndex.from_arrays(arrays, names=('Animal', 'Type'))\n >>> df = pd.DataFrame({'Max Speed': [390., 350., 30., 20.]},\n ... index=index)\n >>> df\n Max Speed\n Animal Type\n Falcon Captive 390.0\n Wild 350.0\n Parrot Captive 30.0\n Wild 20.0\n >>> df.groupby(level=0).mean()\n Max Speed\n Animal\n Falcon 370.0\n Parrot 25.0\n >>> df.groupby(level=1).mean()\n Max Speed\n Type\n Captive 210.0\n Wild 185.0\n \"\"\"\n from pandas.core.groupby.groupby import get_groupby\n\n if level is None and by is None:\n raise TypeError(\"You have to supply one of 'by' and 'level'\")\n axis = self._get_axis_number(axis)\n\n return get_groupby(\n self,\n by=by,\n axis=axis,\n level=level,\n as_index=as_index,\n sort=sort,\n group_keys=group_keys,\n squeeze=squeeze,\n observed=observed,\n )\n\n def asfreq(\n self,\n freq,\n method=None,\n how: Optional[str] = None,\n normalize: bool_t = False,\n fill_value=None,\n ):\n \"\"\"\n Convert TimeSeries to specified frequency.\n\n Optionally provide filling method to pad/backfill missing values.\n\n Returns the original data conformed to a new index with the specified\n frequency. ``resample`` is more appropriate if an operation, such as\n summarization, is necessary to represent the data at the new frequency.\n\n Parameters\n ----------\n freq : DateOffset or str\n method : {'backfill'/'bfill', 'pad'/'ffill'}, default None\n Method to use for filling holes in reindexed Series (note this\n does not fill NaNs that already were present):\n\n * 'pad' / 'ffill': propagate last valid observation forward to next\n valid\n * 'backfill' / 'bfill': use NEXT valid observation to fill.\n how : {'start', 'end'}, default end\n For PeriodIndex only (see PeriodIndex.asfreq).\n normalize : bool, default False\n Whether to reset output index to midnight.\n fill_value : scalar, optional\n Value to use for missing values, applied during upsampling (note\n this does not fill NaNs that already were present).\n\n Returns\n -------\n converted : same type as caller\n\n See Also\n --------\n reindex\n\n Notes\n -----\n To learn more about the frequency strings, please see `this link\n <http://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases>`__.\n\n Examples\n --------\n\n Start by creating a series with 4 one minute timestamps.\n\n >>> index = pd.date_range('1/1/2000', periods=4, freq='T')\n >>> series = pd.Series([0.0, None, 2.0, 3.0], index=index)\n >>> df = pd.DataFrame({'s':series})\n >>> df\n s\n 2000-01-01 00:00:00 0.0\n 2000-01-01 00:01:00 NaN\n 2000-01-01 00:02:00 2.0\n 2000-01-01 00:03:00 3.0\n\n Upsample the series into 30 second bins.\n\n >>> df.asfreq(freq='30S')\n s\n 2000-01-01 00:00:00 0.0\n 2000-01-01 00:00:30 NaN\n 2000-01-01 00:01:00 NaN\n 2000-01-01 00:01:30 NaN\n 2000-01-01 00:02:00 2.0\n 2000-01-01 00:02:30 NaN\n 2000-01-01 00:03:00 3.0\n\n Upsample again, providing a ``fill value``.\n\n >>> df.asfreq(freq='30S', fill_value=9.0)\n s\n 2000-01-01 00:00:00 0.0\n 2000-01-01 00:00:30 9.0\n 2000-01-01 00:01:00 NaN\n 2000-01-01 00:01:30 9.0\n 2000-01-01 00:02:00 2.0\n 2000-01-01 00:02:30 9.0\n 2000-01-01 00:03:00 3.0\n\n Upsample again, providing a ``method``.\n\n >>> df.asfreq(freq='30S', method='bfill')\n s\n 2000-01-01 00:00:00 0.0\n 2000-01-01 00:00:30 NaN\n 2000-01-01 00:01:00 NaN\n 2000-01-01 00:01:30 2.0\n 2000-01-01 00:02:00 2.0\n 2000-01-01 00:02:30 3.0\n 2000-01-01 00:03:00 3.0\n \"\"\"\n from pandas.core.resample import asfreq\n\n return asfreq(\n self,\n freq,\n method=method,\n how=how,\n normalize=normalize,\n fill_value=fill_value,\n )\n\n def at_time(self, time, asof: bool_t = False, axis=None):\n \"\"\"\n Select values at particular time of day (e.g. 9:30AM).\n\n Parameters\n ----------\n time : datetime.time or str\n axis : {0 or 'index', 1 or 'columns'}, default 0\n\n .. versionadded:: 0.24.0\n\n Returns\n -------\n Series or DataFrame\n\n Raises\n ------\n TypeError\n If the index is not a :class:`DatetimeIndex`\n\n See Also\n --------\n between_time : Select values between particular times of the day.\n first : Select initial periods of time series based on a date offset.\n last : Select final periods of time series based on a date offset.\n DatetimeIndex.indexer_at_time : Get just the index locations for\n values at particular time of the day.\n\n Examples\n --------\n >>> i = pd.date_range('2018-04-09', periods=4, freq='12H')\n >>> ts = pd.DataFrame({'A': [1, 2, 3, 4]}, index=i)\n >>> ts\n A\n 2018-04-09 00:00:00 1\n 2018-04-09 12:00:00 2\n 2018-04-10 00:00:00 3\n 2018-04-10 12:00:00 4\n\n >>> ts.at_time('12:00')\n A\n 2018-04-09 12:00:00 2\n 2018-04-10 12:00:00 4\n \"\"\"\n if axis is None:\n axis = self._stat_axis_number\n axis = self._get_axis_number(axis)\n\n index = self._get_axis(axis)\n try:\n indexer = index.indexer_at_time(time, asof=asof)\n except AttributeError:\n raise TypeError(\"Index must be DatetimeIndex\")\n\n return self.take(indexer, axis=axis)\n\n def between_time(\n self,\n start_time,\n end_time,\n include_start: bool_t = True,\n include_end: bool_t = True,\n axis=None,\n ):\n \"\"\"\n Select values between particular times of the day (e.g., 9:00-9:30 AM).\n\n By setting ``start_time`` to be later than ``end_time``,\n you can get the times that are *not* between the two times.\n\n Parameters\n ----------\n start_time : datetime.time or str\n end_time : datetime.time or str\n include_start : bool, default True\n include_end : bool, default True\n axis : {0 or 'index', 1 or 'columns'}, default 0\n\n .. versionadded:: 0.24.0\n\n Returns\n -------\n Series or DataFrame\n\n Raises\n ------\n TypeError\n If the index is not a :class:`DatetimeIndex`\n\n See Also\n --------\n at_time : Select values at a particular time of the day.\n first : Select initial periods of time series based on a date offset.\n last : Select final periods of time series based on a date offset.\n DatetimeIndex.indexer_between_time : Get just the index locations for\n values between particular times of the day.\n\n Examples\n --------\n >>> i = pd.date_range('2018-04-09', periods=4, freq='1D20min')\n >>> ts = pd.DataFrame({'A': [1, 2, 3, 4]}, index=i)\n >>> ts\n A\n 2018-04-09 00:00:00 1\n 2018-04-10 00:20:00 2\n 2018-04-11 00:40:00 3\n 2018-04-12 01:00:00 4\n\n >>> ts.between_time('0:15', '0:45')\n A\n 2018-04-10 00:20:00 2\n 2018-04-11 00:40:00 3\n\n You get the times that are *not* between two times by setting\n ``start_time`` later than ``end_time``:\n\n >>> ts.between_time('0:45', '0:15')\n A\n 2018-04-09 00:00:00 1\n 2018-04-12 01:00:00 4\n \"\"\"\n if axis is None:\n axis = self._stat_axis_number\n axis = self._get_axis_number(axis)\n\n index = self._get_axis(axis)\n try:\n indexer = index.indexer_between_time(\n start_time,\n end_time,\n include_start=include_start,\n include_end=include_end,\n )\n except AttributeError:\n raise TypeError(\"Index must be DatetimeIndex\")\n\n return self.take(indexer, axis=axis)\n\n def resample(\n self,\n rule,\n axis=0,\n closed: Optional[str] = None,\n label: Optional[str] = None,\n convention: str = \"start\",\n kind: Optional[str] = None,\n loffset=None,\n base: int = 0,\n on=None,\n level=None,\n ):\n \"\"\"\n Resample time-series data.\n\n Convenience method for frequency conversion and resampling of time\n series. Object must have a datetime-like index (`DatetimeIndex`,\n `PeriodIndex`, or `TimedeltaIndex`), or pass datetime-like values\n to the `on` or `level` keyword.\n\n Parameters\n ----------\n rule : DateOffset, Timedelta or str\n The offset string or object representing target conversion.\n axis : {0 or 'index', 1 or 'columns'}, default 0\n Which axis to use for up- or down-sampling. For `Series` this\n will default to 0, i.e. along the rows. Must be\n `DatetimeIndex`, `TimedeltaIndex` or `PeriodIndex`.\n closed : {'right', 'left'}, default None\n Which side of bin interval is closed. The default is 'left'\n for all frequency offsets except for 'M', 'A', 'Q', 'BM',\n 'BA', 'BQ', and 'W' which all have a default of 'right'.\n label : {'right', 'left'}, default None\n Which bin edge label to label bucket with. The default is 'left'\n for all frequency offsets except for 'M', 'A', 'Q', 'BM',\n 'BA', 'BQ', and 'W' which all have a default of 'right'.\n convention : {'start', 'end', 's', 'e'}, default 'start'\n For `PeriodIndex` only, controls whether to use the start or\n end of `rule`.\n kind : {'timestamp', 'period'}, optional, default None\n Pass 'timestamp' to convert the resulting index to a\n `DateTimeIndex` or 'period' to convert it to a `PeriodIndex`.\n By default the input representation is retained.\n loffset : timedelta, default None\n Adjust the resampled time labels.\n base : int, default 0\n For frequencies that evenly subdivide 1 day, the \"origin\" of the\n aggregated intervals. For example, for '5min' frequency, base could\n range from 0 through 4. Defaults to 0.\n on : str, optional\n For a DataFrame, column to use instead of index for resampling.\n Column must be datetime-like.\n\n level : str or int, optional\n For a MultiIndex, level (name or number) to use for\n resampling. `level` must be datetime-like.\n\n Returns\n -------\n Resampler object\n\n See Also\n --------\n groupby : Group by mapping, function, label, or list of labels.\n Series.resample : Resample a Series.\n DataFrame.resample: Resample a DataFrame.\n\n Notes\n -----\n See the `user guide\n <https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#resampling>`_\n for more.\n\n To learn more about the offset strings, please see `this link\n <http://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#dateoffset-objects>`__.\n\n Examples\n --------\n\n Start by creating a series with 9 one minute timestamps.\n\n >>> index = pd.date_range('1/1/2000', periods=9, freq='T')\n >>> series = pd.Series(range(9), index=index)\n >>> series\n 2000-01-01 00:00:00 0\n 2000-01-01 00:01:00 1\n 2000-01-01 00:02:00 2\n 2000-01-01 00:03:00 3\n 2000-01-01 00:04:00 4\n 2000-01-01 00:05:00 5\n 2000-01-01 00:06:00 6\n 2000-01-01 00:07:00 7\n 2000-01-01 00:08:00 8\n Freq: T, dtype: int64\n\n Downsample the series into 3 minute bins and sum the values\n of the timestamps falling into a bin.\n\n >>> series.resample('3T').sum()\n 2000-01-01 00:00:00 3\n 2000-01-01 00:03:00 12\n 2000-01-01 00:06:00 21\n Freq: 3T, dtype: int64\n\n Downsample the series into 3 minute bins as above, but label each\n bin using the right edge instead of the left. Please note that the\n value in the bucket used as the label is not included in the bucket,\n which it labels. For example, in the original series the\n bucket ``2000-01-01 00:03:00`` contains the value 3, but the summed\n value in the resampled bucket with the label ``2000-01-01 00:03:00``\n does not include 3 (if it did, the summed value would be 6, not 3).\n To include this value close the right side of the bin interval as\n illustrated in the example below this one.\n\n >>> series.resample('3T', label='right').sum()\n 2000-01-01 00:03:00 3\n 2000-01-01 00:06:00 12\n 2000-01-01 00:09:00 21\n Freq: 3T, dtype: int64\n\n Downsample the series into 3 minute bins as above, but close the right\n side of the bin interval.\n\n >>> series.resample('3T', label='right', closed='right').sum()\n 2000-01-01 00:00:00 0\n 2000-01-01 00:03:00 6\n 2000-01-01 00:06:00 15\n 2000-01-01 00:09:00 15\n Freq: 3T, dtype: int64\n\n Upsample the series into 30 second bins.\n\n >>> series.resample('30S').asfreq()[0:5] # Select first 5 rows\n 2000-01-01 00:00:00 0.0\n 2000-01-01 00:00:30 NaN\n 2000-01-01 00:01:00 1.0\n 2000-01-01 00:01:30 NaN\n 2000-01-01 00:02:00 2.0\n Freq: 30S, dtype: float64\n\n Upsample the series into 30 second bins and fill the ``NaN``\n values using the ``pad`` method.\n\n >>> series.resample('30S').pad()[0:5]\n 2000-01-01 00:00:00 0\n 2000-01-01 00:00:30 0\n 2000-01-01 00:01:00 1\n 2000-01-01 00:01:30 1\n 2000-01-01 00:02:00 2\n Freq: 30S, dtype: int64\n\n Upsample the series into 30 second bins and fill the\n ``NaN`` values using the ``bfill`` method.\n\n >>> series.resample('30S').bfill()[0:5]\n 2000-01-01 00:00:00 0\n 2000-01-01 00:00:30 1\n 2000-01-01 00:01:00 1\n 2000-01-01 00:01:30 2\n 2000-01-01 00:02:00 2\n Freq: 30S, dtype: int64\n\n Pass a custom function via ``apply``\n\n >>> def custom_resampler(array_like):\n ... return np.sum(array_like) + 5\n ...\n >>> series.resample('3T').apply(custom_resampler)\n 2000-01-01 00:00:00 8\n 2000-01-01 00:03:00 17\n 2000-01-01 00:06:00 26\n Freq: 3T, dtype: int64\n\n For a Series with a PeriodIndex, the keyword `convention` can be\n used to control whether to use the start or end of `rule`.\n\n Resample a year by quarter using 'start' `convention`. Values are\n assigned to the first quarter of the period.\n\n >>> s = pd.Series([1, 2], index=pd.period_range('2012-01-01',\n ... freq='A',\n ... periods=2))\n >>> s\n 2012 1\n 2013 2\n Freq: A-DEC, dtype: int64\n >>> s.resample('Q', convention='start').asfreq()\n 2012Q1 1.0\n 2012Q2 NaN\n 2012Q3 NaN\n 2012Q4 NaN\n 2013Q1 2.0\n 2013Q2 NaN\n 2013Q3 NaN\n 2013Q4 NaN\n Freq: Q-DEC, dtype: float64\n\n Resample quarters by month using 'end' `convention`. Values are\n assigned to the last month of the period.\n\n >>> q = pd.Series([1, 2, 3, 4], index=pd.period_range('2018-01-01',\n ... freq='Q',\n ... periods=4))\n >>> q\n 2018Q1 1\n 2018Q2 2\n 2018Q3 3\n 2018Q4 4\n Freq: Q-DEC, dtype: int64\n >>> q.resample('M', convention='end').asfreq()\n 2018-03 1.0\n 2018-04 NaN\n 2018-05 NaN\n 2018-06 2.0\n 2018-07 NaN\n 2018-08 NaN\n 2018-09 3.0\n 2018-10 NaN\n 2018-11 NaN\n 2018-12 4.0\n Freq: M, dtype: float64\n\n For DataFrame objects, the keyword `on` can be used to specify the\n column instead of the index for resampling.\n\n >>> d = dict({'price': [10, 11, 9, 13, 14, 18, 17, 19],\n ... 'volume': [50, 60, 40, 100, 50, 100, 40, 50]})\n >>> df = pd.DataFrame(d)\n >>> df['week_starting'] = pd.date_range('01/01/2018',\n ... periods=8,\n ... freq='W')\n >>> df\n price volume week_starting\n 0 10 50 2018-01-07\n 1 11 60 2018-01-14\n 2 9 40 2018-01-21\n 3 13 100 2018-01-28\n 4 14 50 2018-02-04\n 5 18 100 2018-02-11\n 6 17 40 2018-02-18\n 7 19 50 2018-02-25\n >>> df.resample('M', on='week_starting').mean()\n price volume\n week_starting\n 2018-01-31 10.75 62.5\n 2018-02-28 17.00 60.0\n\n For a DataFrame with MultiIndex, the keyword `level` can be used to\n specify on which level the resampling needs to take place.\n\n >>> days = pd.date_range('1/1/2000', periods=4, freq='D')\n >>> d2 = dict({'price': [10, 11, 9, 13, 14, 18, 17, 19],\n ... 'volume': [50, 60, 40, 100, 50, 100, 40, 50]})\n >>> df2 = pd.DataFrame(d2,\n ... index=pd.MultiIndex.from_product([days,\n ... ['morning',\n ... 'afternoon']]\n ... ))\n >>> df2\n price volume\n 2000-01-01 morning 10 50\n afternoon 11 60\n 2000-01-02 morning 9 40\n afternoon 13 100\n 2000-01-03 morning 14 50\n afternoon 18 100\n 2000-01-04 morning 17 40\n afternoon 19 50\n >>> df2.resample('D', level=0).sum()\n price volume\n 2000-01-01 21 110\n 2000-01-02 22 140\n 2000-01-03 32 150\n 2000-01-04 36 90\n \"\"\"\n\n from pandas.core.resample import resample\n\n axis = self._get_axis_number(axis)\n return resample(\n self,\n freq=rule,\n label=label,\n closed=closed,\n axis=axis,\n kind=kind,\n loffset=loffset,\n convention=convention,\n base=base,\n key=on,\n level=level,\n )\n\n def first(self, offset):\n \"\"\"\n Method to subset initial periods of time series data based on a date offset.\n\n Parameters\n ----------\n offset : str, DateOffset, dateutil.relativedelta\n\n Returns\n -------\n subset : same type as caller\n\n Raises\n ------\n TypeError\n If the index is not a :class:`DatetimeIndex`\n\n See Also\n --------\n last : Select final periods of time series based on a date offset.\n at_time : Select values at a particular time of the day.\n between_time : Select values between particular times of the day.\n\n Examples\n --------\n >>> i = pd.date_range('2018-04-09', periods=4, freq='2D')\n >>> ts = pd.DataFrame({'A': [1,2,3,4]}, index=i)\n >>> ts\n A\n 2018-04-09 1\n 2018-04-11 2\n 2018-04-13 3\n 2018-04-15 4\n\n Get the rows for the first 3 days:\n\n >>> ts.first('3D')\n A\n 2018-04-09 1\n 2018-04-11 2\n\n Notice the data for 3 first calender days were returned, not the first\n 3 days observed in the dataset, and therefore data for 2018-04-13 was\n not returned.\n \"\"\"\n if not isinstance(self.index, DatetimeIndex):\n raise TypeError(\"'first' only supports a DatetimeIndex index\")\n\n if len(self.index) == 0:\n return self\n\n offset = to_offset(offset)\n end_date = end = self.index[0] + offset\n\n # Tick-like, e.g. 3 weeks\n if not offset.is_anchored() and hasattr(offset, \"_inc\"):\n if end_date in self.index:\n end = self.index.searchsorted(end_date, side=\"left\")\n return self.iloc[:end]\n\n return self.loc[:end]\n\n def last(self, offset):\n \"\"\"\n Method to subset final periods of time series data based on a date offset.\n\n Parameters\n ----------\n offset : str, DateOffset, dateutil.relativedelta\n\n Returns\n -------\n subset : same type as caller\n\n Raises\n ------\n TypeError\n If the index is not a :class:`DatetimeIndex`\n\n See Also\n --------\n first : Select initial periods of time series based on a date offset.\n at_time : Select values at a particular time of the day.\n between_time : Select values between particular times of the day.\n\n Examples\n --------\n >>> i = pd.date_range('2018-04-09', periods=4, freq='2D')\n >>> ts = pd.DataFrame({'A': [1, 2, 3, 4]}, index=i)\n >>> ts\n A\n 2018-04-09 1\n 2018-04-11 2\n 2018-04-13 3\n 2018-04-15 4\n\n Get the rows for the last 3 days:\n\n >>> ts.last('3D')\n A\n 2018-04-13 3\n 2018-04-15 4\n\n Notice the data for 3 last calender days were returned, not the last\n 3 observed days in the dataset, and therefore data for 2018-04-11 was\n not returned.\n \"\"\"\n if not isinstance(self.index, DatetimeIndex):\n raise TypeError(\"'last' only supports a DatetimeIndex index\")\n\n if len(self.index) == 0:\n return self\n\n offset = to_offset(offset)\n\n start_date = self.index[-1] - offset\n start = self.index.searchsorted(start_date, side=\"right\")\n return self.iloc[start:]\n\n def rank(\n self: FrameOrSeries,\n axis=0,\n method: str = \"average\",\n numeric_only: Optional[bool_t] = None,\n na_option: str = \"keep\",\n ascending: bool_t = True,\n pct: bool_t = False,\n ) -> FrameOrSeries:\n \"\"\"\n Compute numerical data ranks (1 through n) along axis.\n\n By default, equal values are assigned a rank that is the average of the\n ranks of those values.\n\n Parameters\n ----------\n axis : {0 or 'index', 1 or 'columns'}, default 0\n Index to direct ranking.\n method : {'average', 'min', 'max', 'first', 'dense'}, default 'average'\n How to rank the group of records that have the same value (i.e. ties):\n\n * average: average rank of the group\n * min: lowest rank in the group\n * max: highest rank in the group\n * first: ranks assigned in order they appear in the array\n * dense: like 'min', but rank always increases by 1 between groups.\n\n numeric_only : bool, optional\n For DataFrame objects, rank only numeric columns if set to True.\n na_option : {'keep', 'top', 'bottom'}, default 'keep'\n How to rank NaN values:\n\n * keep: assign NaN rank to NaN values\n * top: assign smallest rank to NaN values if ascending\n * bottom: assign highest rank to NaN values if ascending.\n\n ascending : bool, default True\n Whether or not the elements should be ranked in ascending order.\n pct : bool, default False\n Whether or not to display the returned rankings in percentile\n form.\n\n Returns\n -------\n same type as caller\n Return a Series or DataFrame with data ranks as values.\n\n See Also\n --------\n core.groupby.GroupBy.rank : Rank of values within each group.\n\n Examples\n --------\n\n >>> df = pd.DataFrame(data={'Animal': ['cat', 'penguin', 'dog',\n ... 'spider', 'snake'],\n ... 'Number_legs': [4, 2, 4, 8, np.nan]})\n >>> df\n Animal Number_legs\n 0 cat 4.0\n 1 penguin 2.0\n 2 dog 4.0\n 3 spider 8.0\n 4 snake NaN\n\n The following example shows how the method behaves with the above\n parameters:\n\n * default_rank: this is the default behaviour obtained without using\n any parameter.\n * max_rank: setting ``method = 'max'`` the records that have the\n same values are ranked using the highest rank (e.g.: since 'cat'\n and 'dog' are both in the 2nd and 3rd position, rank 3 is assigned.)\n * NA_bottom: choosing ``na_option = 'bottom'``, if there are records\n with NaN values they are placed at the bottom of the ranking.\n * pct_rank: when setting ``pct = True``, the ranking is expressed as\n percentile rank.\n\n >>> df['default_rank'] = df['Number_legs'].rank()\n >>> df['max_rank'] = df['Number_legs'].rank(method='max')\n >>> df['NA_bottom'] = df['Number_legs'].rank(na_option='bottom')\n >>> df['pct_rank'] = df['Number_legs'].rank(pct=True)\n >>> df\n Animal Number_legs default_rank max_rank NA_bottom pct_rank\n 0 cat 4.0 2.5 3.0 2.5 0.625\n 1 penguin 2.0 1.0 1.0 1.0 0.250\n 2 dog 4.0 2.5 3.0 2.5 0.625\n 3 spider 8.0 4.0 4.0 4.0 1.000\n 4 snake NaN NaN NaN 5.0 NaN\n \"\"\"\n axis = self._get_axis_number(axis)\n\n if na_option not in {\"keep\", \"top\", \"bottom\"}:\n msg = \"na_option must be one of 'keep', 'top', or 'bottom'\"\n raise ValueError(msg)\n\n def ranker(data):\n ranks = algos.rank(\n data.values,\n axis=axis,\n method=method,\n ascending=ascending,\n na_option=na_option,\n pct=pct,\n )\n ranks = self._constructor(ranks, **data._construct_axes_dict())\n return ranks.__finalize__(self)\n\n # if numeric_only is None, and we can't get anything, we try with\n # numeric_only=True\n if numeric_only is None:\n try:\n return ranker(self)\n except TypeError:\n numeric_only = True\n\n if numeric_only:\n data = self._get_numeric_data()\n else:\n data = self\n\n return ranker(data)\n\n _shared_docs[\n \"align\"\n ] = \"\"\"\n Align two objects on their axes with the specified join method.\n\n Join method is specified for each axis Index.\n\n Parameters\n ----------\n other : DataFrame or Series\n join : {'outer', 'inner', 'left', 'right'}, default 'outer'\n axis : allowed axis of the other object, default None\n Align on index (0), columns (1), or both (None).\n level : int or level name, default None\n Broadcast across a level, matching Index values on the\n passed MultiIndex level.\n copy : bool, default True\n Always returns new objects. If copy=False and no reindexing is\n required then original objects are returned.\n fill_value : scalar, default np.NaN\n Value to use for missing values. Defaults to NaN, but can be any\n \"compatible\" value.\n method : {'backfill', 'bfill', 'pad', 'ffill', None}, default None\n Method to use for filling holes in reindexed Series:\n\n - pad / ffill: propagate last valid observation forward to next valid.\n - backfill / bfill: use NEXT valid observation to fill gap.\n\n limit : int, default None\n If method is specified, this is the maximum number of consecutive\n NaN values to forward/backward fill. In other words, if there is\n a gap with more than this number of consecutive NaNs, it will only\n be partially filled. If method is not specified, this is the\n maximum number of entries along the entire axis where NaNs will be\n filled. Must be greater than 0 if not None.\n fill_axis : %(axes_single_arg)s, default 0\n Filling axis, method and limit.\n broadcast_axis : %(axes_single_arg)s, default None\n Broadcast values along this axis, if aligning two objects of\n different dimensions.\n\n Returns\n -------\n (left, right) : (%(klass)s, type of other)\n Aligned objects.\n \"\"\"\n\n @Appender(_shared_docs[\"align\"] % _shared_doc_kwargs)\n def align(\n self,\n other,\n join=\"outer\",\n axis=None,\n level=None,\n copy=True,\n fill_value=None,\n method=None,\n limit=None,\n fill_axis=0,\n broadcast_axis=None,\n ):\n method = missing.clean_fill_method(method)\n\n if broadcast_axis == 1 and self.ndim != other.ndim:\n if isinstance(self, ABCSeries):\n # this means other is a DataFrame, and we need to broadcast\n # self\n cons = self._constructor_expanddim\n df = cons(\n {c: self for c in other.columns}, **other._construct_axes_dict()\n )\n return df._align_frame(\n other,\n join=join,\n axis=axis,\n level=level,\n copy=copy,\n fill_value=fill_value,\n method=method,\n limit=limit,\n fill_axis=fill_axis,\n )\n elif isinstance(other, ABCSeries):\n # this means self is a DataFrame, and we need to broadcast\n # other\n cons = other._constructor_expanddim\n df = cons(\n {c: other for c in self.columns}, **self._construct_axes_dict()\n )\n return self._align_frame(\n df,\n join=join,\n axis=axis,\n level=level,\n copy=copy,\n fill_value=fill_value,\n method=method,\n limit=limit,\n fill_axis=fill_axis,\n )\n\n if axis is not None:\n axis = self._get_axis_number(axis)\n if isinstance(other, ABCDataFrame):\n return self._align_frame(\n other,\n join=join,\n axis=axis,\n level=level,\n copy=copy,\n fill_value=fill_value,\n method=method,\n limit=limit,\n fill_axis=fill_axis,\n )\n elif isinstance(other, ABCSeries):\n return self._align_series(\n other,\n join=join,\n axis=axis,\n level=level,\n copy=copy,\n fill_value=fill_value,\n method=method,\n limit=limit,\n fill_axis=fill_axis,\n )\n else: # pragma: no cover\n raise TypeError(f\"unsupported type: {type(other)}\")\n\n def _align_frame(\n self,\n other,\n join=\"outer\",\n axis=None,\n level=None,\n copy: bool_t = True,\n fill_value=None,\n method=None,\n limit=None,\n fill_axis=0,\n ):\n # defaults\n join_index, join_columns = None, None\n ilidx, iridx = None, None\n clidx, cridx = None, None\n\n is_series = isinstance(self, ABCSeries)\n\n if axis is None or axis == 0:\n if not self.index.equals(other.index):\n join_index, ilidx, iridx = self.index.join(\n other.index, how=join, level=level, return_indexers=True\n )\n\n if axis is None or axis == 1:\n if not is_series and not self.columns.equals(other.columns):\n join_columns, clidx, cridx = self.columns.join(\n other.columns, how=join, level=level, return_indexers=True\n )\n\n if is_series:\n reindexers = {0: [join_index, ilidx]}\n else:\n reindexers = {0: [join_index, ilidx], 1: [join_columns, clidx]}\n\n left = self._reindex_with_indexers(\n reindexers, copy=copy, fill_value=fill_value, allow_dups=True\n )\n # other must be always DataFrame\n right = other._reindex_with_indexers(\n {0: [join_index, iridx], 1: [join_columns, cridx]},\n copy=copy,\n fill_value=fill_value,\n allow_dups=True,\n )\n\n if method is not None:\n left = left.fillna(axis=fill_axis, method=method, limit=limit)\n right = right.fillna(axis=fill_axis, method=method, limit=limit)\n\n # if DatetimeIndex have different tz, convert to UTC\n if is_datetime64tz_dtype(left.index):\n if left.index.tz != right.index.tz:\n if join_index is not None:\n left.index = join_index\n right.index = join_index\n\n return left.__finalize__(self), right.__finalize__(other)\n\n def _align_series(\n self,\n other,\n join=\"outer\",\n axis=None,\n level=None,\n copy: bool_t = True,\n fill_value=None,\n method=None,\n limit=None,\n fill_axis=0,\n ):\n\n is_series = isinstance(self, ABCSeries)\n\n # series/series compat, other must always be a Series\n if is_series:\n if axis:\n raise ValueError(\"cannot align series to a series other than axis 0\")\n\n # equal\n if self.index.equals(other.index):\n join_index, lidx, ridx = None, None, None\n else:\n join_index, lidx, ridx = self.index.join(\n other.index, how=join, level=level, return_indexers=True\n )\n\n left = self._reindex_indexer(join_index, lidx, copy)\n right = other._reindex_indexer(join_index, ridx, copy)\n\n else:\n # one has > 1 ndim\n fdata = self._data\n if axis == 0:\n join_index = self.index\n lidx, ridx = None, None\n if not self.index.equals(other.index):\n join_index, lidx, ridx = self.index.join(\n other.index, how=join, level=level, return_indexers=True\n )\n\n if lidx is not None:\n fdata = fdata.reindex_indexer(join_index, lidx, axis=1)\n\n elif axis == 1:\n join_index = self.columns\n lidx, ridx = None, None\n if not self.columns.equals(other.index):\n join_index, lidx, ridx = self.columns.join(\n other.index, how=join, level=level, return_indexers=True\n )\n\n if lidx is not None:\n fdata = fdata.reindex_indexer(join_index, lidx, axis=0)\n else:\n raise ValueError(\"Must specify axis=0 or 1\")\n\n if copy and fdata is self._data:\n fdata = fdata.copy()\n\n left = self._constructor(fdata)\n\n if ridx is None:\n right = other\n else:\n right = other.reindex(join_index, level=level)\n\n # fill\n fill_na = notna(fill_value) or (method is not None)\n if fill_na:\n left = left.fillna(fill_value, method=method, limit=limit, axis=fill_axis)\n right = right.fillna(fill_value, method=method, limit=limit)\n\n # if DatetimeIndex have different tz, convert to UTC\n if is_series or (not is_series and axis == 0):\n if is_datetime64tz_dtype(left.index):\n if left.index.tz != right.index.tz:\n if join_index is not None:\n left.index = join_index\n right.index = join_index\n\n return left.__finalize__(self), right.__finalize__(other)\n\n def _where(\n self,\n cond,\n other=np.nan,\n inplace=False,\n axis=None,\n level=None,\n errors=\"raise\",\n try_cast=False,\n ):\n \"\"\"\n Equivalent to public method `where`, except that `other` is not\n applied as a function even if callable. Used in __setitem__.\n \"\"\"\n inplace = validate_bool_kwarg(inplace, \"inplace\")\n\n # align the cond to same shape as myself\n cond = com.apply_if_callable(cond, self)\n if isinstance(cond, NDFrame):\n cond, _ = cond.align(self, join=\"right\", broadcast_axis=1)\n else:\n if not hasattr(cond, \"shape\"):\n cond = np.asanyarray(cond)\n if cond.shape != self.shape:\n raise ValueError(\"Array conditional must be same shape as self\")\n cond = self._constructor(cond, **self._construct_axes_dict())\n\n # make sure we are boolean\n fill_value = bool(inplace)\n cond = cond.fillna(fill_value)\n\n msg = \"Boolean array expected for the condition, not {dtype}\"\n\n if not isinstance(cond, ABCDataFrame):\n # This is a single-dimensional object.\n if not is_bool_dtype(cond):\n raise ValueError(msg.format(dtype=cond.dtype))\n elif not cond.empty:\n for dt in cond.dtypes:\n if not is_bool_dtype(dt):\n raise ValueError(msg.format(dtype=dt))\n\n cond = -cond if inplace else cond\n\n # try to align with other\n try_quick = True\n if hasattr(other, \"align\"):\n\n # align with me\n if other.ndim <= self.ndim:\n\n _, other = self.align(\n other, join=\"left\", axis=axis, level=level, fill_value=np.nan\n )\n\n # if we are NOT aligned, raise as we cannot where index\n if axis is None and not all(\n other._get_axis(i).equals(ax) for i, ax in enumerate(self.axes)\n ):\n raise InvalidIndexError\n\n # slice me out of the other\n else:\n raise NotImplementedError(\n \"cannot align with a higher dimensional NDFrame\"\n )\n\n if isinstance(other, np.ndarray):\n\n if other.shape != self.shape:\n\n if self.ndim == 1:\n\n icond = cond.values\n\n # GH 2745 / GH 4192\n # treat like a scalar\n if len(other) == 1:\n other = np.array(other[0])\n\n # GH 3235\n # match True cond to other\n elif len(cond[icond]) == len(other):\n\n # try to not change dtype at first (if try_quick)\n if try_quick:\n new_other = com.values_from_object(self)\n new_other = new_other.copy()\n new_other[icond] = other\n other = new_other\n\n else:\n raise ValueError(\n \"Length of replacements must equal series length\"\n )\n\n else:\n raise ValueError(\n \"other must be the same shape as self when an ndarray\"\n )\n\n # we are the same shape, so create an actual object for alignment\n else:\n other = self._constructor(other, **self._construct_axes_dict())\n\n if axis is None:\n axis = 0\n\n if self.ndim == getattr(other, \"ndim\", 0):\n align = True\n else:\n align = self._get_axis_number(axis) == 1\n\n block_axis = self._get_block_manager_axis(axis)\n\n if inplace:\n # we may have different type blocks come out of putmask, so\n # reconstruct the block manager\n\n self._check_inplace_setting(other)\n new_data = self._data.putmask(\n mask=cond,\n new=other,\n align=align,\n inplace=True,\n axis=block_axis,\n transpose=self._AXIS_REVERSED,\n )\n self._update_inplace(new_data)\n\n else:\n new_data = self._data.where(\n other=other,\n cond=cond,\n align=align,\n errors=errors,\n try_cast=try_cast,\n axis=block_axis,\n )\n\n return self._constructor(new_data).__finalize__(self)\n\n _shared_docs[\n \"where\"\n ] = \"\"\"\n Replace values where the condition is %(cond_rev)s.\n\n Parameters\n ----------\n cond : bool %(klass)s, array-like, or callable\n Where `cond` is %(cond)s, keep the original value. Where\n %(cond_rev)s, replace with corresponding value from `other`.\n If `cond` is callable, it is computed on the %(klass)s and\n should return boolean %(klass)s or array. The callable must\n not change input %(klass)s (though pandas doesn't check it).\n other : scalar, %(klass)s, or callable\n Entries where `cond` is %(cond_rev)s are replaced with\n corresponding value from `other`.\n If other is callable, it is computed on the %(klass)s and\n should return scalar or %(klass)s. The callable must not\n change input %(klass)s (though pandas doesn't check it).\n inplace : bool, default False\n Whether to perform the operation in place on the data.\n axis : int, default None\n Alignment axis if needed.\n level : int, default None\n Alignment level if needed.\n errors : str, {'raise', 'ignore'}, default 'raise'\n Note that currently this parameter won't affect\n the results and will always coerce to a suitable dtype.\n\n - 'raise' : allow exceptions to be raised.\n - 'ignore' : suppress exceptions. On error return original object.\n\n try_cast : bool, default False\n Try to cast the result back to the input type (if possible).\n\n Returns\n -------\n Same type as caller\n\n See Also\n --------\n :func:`DataFrame.%(name_other)s` : Return an object of same shape as\n self.\n\n Notes\n -----\n The %(name)s method is an application of the if-then idiom. For each\n element in the calling DataFrame, if ``cond`` is ``%(cond)s`` the\n element is used; otherwise the corresponding element from the DataFrame\n ``other`` is used.\n\n The signature for :func:`DataFrame.where` differs from\n :func:`numpy.where`. Roughly ``df1.where(m, df2)`` is equivalent to\n ``np.where(m, df1, df2)``.\n\n For further details and examples see the ``%(name)s`` documentation in\n :ref:`indexing <indexing.where_mask>`.\n\n Examples\n --------\n >>> s = pd.Series(range(5))\n >>> s.where(s > 0)\n 0 NaN\n 1 1.0\n 2 2.0\n 3 3.0\n 4 4.0\n dtype: float64\n\n >>> s.mask(s > 0)\n 0 0.0\n 1 NaN\n 2 NaN\n 3 NaN\n 4 NaN\n dtype: float64\n\n >>> s.where(s > 1, 10)\n 0 10\n 1 10\n 2 2\n 3 3\n 4 4\n dtype: int64\n\n >>> df = pd.DataFrame(np.arange(10).reshape(-1, 2), columns=['A', 'B'])\n >>> df\n A B\n 0 0 1\n 1 2 3\n 2 4 5\n 3 6 7\n 4 8 9\n >>> m = df %% 3 == 0\n >>> df.where(m, -df)\n A B\n 0 0 -1\n 1 -2 3\n 2 -4 -5\n 3 6 -7\n 4 -8 9\n >>> df.where(m, -df) == np.where(m, df, -df)\n A B\n 0 True True\n 1 True True\n 2 True True\n 3 True True\n 4 True True\n >>> df.where(m, -df) == df.mask(~m, -df)\n A B\n 0 True True\n 1 True True\n 2 True True\n 3 True True\n 4 True True\n \"\"\"\n\n @Appender(\n _shared_docs[\"where\"]\n % dict(\n _shared_doc_kwargs,\n cond=\"True\",\n cond_rev=\"False\",\n name=\"where\",\n name_other=\"mask\",\n )\n )\n def where(\n self,\n cond,\n other=np.nan,\n inplace=False,\n axis=None,\n level=None,\n errors=\"raise\",\n try_cast=False,\n ):\n\n other = com.apply_if_callable(other, self)\n return self._where(\n cond, other, inplace, axis, level, errors=errors, try_cast=try_cast\n )\n\n @Appender(\n _shared_docs[\"where\"]\n % dict(\n _shared_doc_kwargs,\n cond=\"False\",\n cond_rev=\"True\",\n name=\"mask\",\n name_other=\"where\",\n )\n )\n def mask(\n self,\n cond,\n other=np.nan,\n inplace=False,\n axis=None,\n level=None,\n errors=\"raise\",\n try_cast=False,\n ):\n\n inplace = validate_bool_kwarg(inplace, \"inplace\")\n cond = com.apply_if_callable(cond, self)\n\n # see gh-21891\n if not hasattr(cond, \"__invert__\"):\n cond = np.array(cond)\n\n return self.where(\n ~cond,\n other=other,\n inplace=inplace,\n axis=axis,\n level=level,\n try_cast=try_cast,\n errors=errors,\n )\n\n _shared_docs[\n \"shift\"\n ] = \"\"\"\n Shift index by desired number of periods with an optional time `freq`.\n\n When `freq` is not passed, shift the index without realigning the data.\n If `freq` is passed (in this case, the index must be date or datetime,\n or it will raise a `NotImplementedError`), the index will be\n increased using the periods and the `freq`.\n\n Parameters\n ----------\n periods : int\n Number of periods to shift. Can be positive or negative.\n freq : DateOffset, tseries.offsets, timedelta, or str, optional\n Offset to use from the tseries module or time rule (e.g. 'EOM').\n If `freq` is specified then the index values are shifted but the\n data is not realigned. That is, use `freq` if you would like to\n extend the index when shifting and preserve the original data.\n axis : {0 or 'index', 1 or 'columns', None}, default None\n Shift direction.\n fill_value : object, optional\n The scalar value to use for newly introduced missing values.\n the default depends on the dtype of `self`.\n For numeric data, ``np.nan`` is used.\n For datetime, timedelta, or period data, etc. :attr:`NaT` is used.\n For extension dtypes, ``self.dtype.na_value`` is used.\n\n .. versionchanged:: 0.24.0\n\n Returns\n -------\n %(klass)s\n Copy of input object, shifted.\n\n See Also\n --------\n Index.shift : Shift values of Index.\n DatetimeIndex.shift : Shift values of DatetimeIndex.\n PeriodIndex.shift : Shift values of PeriodIndex.\n tshift : Shift the time index, using the index's frequency if\n available.\n\n Examples\n --------\n >>> df = pd.DataFrame({'Col1': [10, 20, 15, 30, 45],\n ... 'Col2': [13, 23, 18, 33, 48],\n ... 'Col3': [17, 27, 22, 37, 52]})\n\n >>> df.shift(periods=3)\n Col1 Col2 Col3\n 0 NaN NaN NaN\n 1 NaN NaN NaN\n 2 NaN NaN NaN\n 3 10.0 13.0 17.0\n 4 20.0 23.0 27.0\n\n >>> df.shift(periods=1, axis='columns')\n Col1 Col2 Col3\n 0 NaN 10.0 13.0\n 1 NaN 20.0 23.0\n 2 NaN 15.0 18.0\n 3 NaN 30.0 33.0\n 4 NaN 45.0 48.0\n\n >>> df.shift(periods=3, fill_value=0)\n Col1 Col2 Col3\n 0 0 0 0\n 1 0 0 0\n 2 0 0 0\n 3 10 13 17\n 4 20 23 27\n \"\"\"\n\n @Appender(_shared_docs[\"shift\"] % _shared_doc_kwargs)\n def shift(self, periods=1, freq=None, axis=0, fill_value=None):\n if periods == 0:\n return self.copy()\n\n block_axis = self._get_block_manager_axis(axis)\n if freq is None:\n new_data = self._data.shift(\n periods=periods, axis=block_axis, fill_value=fill_value\n )\n else:\n return self.tshift(periods, freq)\n\n return self._constructor(new_data).__finalize__(self)\n\n def slice_shift(self: FrameOrSeries, periods: int = 1, axis=0) -> FrameOrSeries:\n \"\"\"\n Equivalent to `shift` without copying data.\n\n The shifted data will not include the dropped periods and the\n shifted axis will be smaller than the original.\n\n Parameters\n ----------\n periods : int\n Number of periods to move, can be positive or negative.\n\n Returns\n -------\n shifted : same type as caller\n\n Notes\n -----\n While the `slice_shift` is faster than `shift`, you may pay for it\n later during alignment.\n \"\"\"\n if periods == 0:\n return self\n\n if periods > 0:\n vslicer = slice(None, -periods)\n islicer = slice(periods, None)\n else:\n vslicer = slice(-periods, None)\n islicer = slice(None, periods)\n\n new_obj = self._slice(vslicer, axis=axis)\n shifted_axis = self._get_axis(axis)[islicer]\n new_obj.set_axis(shifted_axis, axis=axis, inplace=True)\n\n return new_obj.__finalize__(self)\n\n def tshift(self, periods: int = 1, freq=None, axis=0):\n \"\"\"\n Shift the time index, using the index's frequency if available.\n\n Parameters\n ----------\n periods : int\n Number of periods to move, can be positive or negative.\n freq : DateOffset, timedelta, or str, default None\n Increment to use from the tseries module\n or time rule expressed as a string (e.g. 'EOM').\n axis : {0 or ‘index’, 1 or ‘columns’, None}, default 0\n Corresponds to the axis that contains the Index.\n\n Returns\n -------\n shifted : Series/DataFrame\n\n Notes\n -----\n If freq is not specified then tries to use the freq or inferred_freq\n attributes of the index. If neither of those attributes exist, a\n ValueError is thrown\n \"\"\"\n\n index = self._get_axis(axis)\n if freq is None:\n freq = getattr(index, \"freq\", None)\n\n if freq is None:\n freq = getattr(index, \"inferred_freq\", None)\n\n if freq is None:\n msg = \"Freq was not given and was not set in the index\"\n raise ValueError(msg)\n\n if periods == 0:\n return self\n\n if isinstance(freq, str):\n freq = to_offset(freq)\n\n block_axis = self._get_block_manager_axis(axis)\n if isinstance(index, PeriodIndex):\n orig_freq = to_offset(index.freq)\n if freq == orig_freq:\n new_data = self._data.copy()\n new_data.axes[block_axis] = index.shift(periods)\n elif orig_freq is not None:\n msg = (\n f\"Given freq {freq.rule_code} does not match\"\n f\" PeriodIndex freq {orig_freq.rule_code}\"\n )\n raise ValueError(msg)\n else:\n new_data = self._data.copy()\n new_data.axes[block_axis] = index.shift(periods, freq)\n\n return self._constructor(new_data).__finalize__(self)\n\n def truncate(\n self: FrameOrSeries, before=None, after=None, axis=None, copy: bool_t = True\n ) -> FrameOrSeries:\n \"\"\"\n Truncate a Series or DataFrame before and after some index value.\n\n This is a useful shorthand for boolean indexing based on index\n values above or below certain thresholds.\n\n Parameters\n ----------\n before : date, str, int\n Truncate all rows before this index value.\n after : date, str, int\n Truncate all rows after this index value.\n axis : {0 or 'index', 1 or 'columns'}, optional\n Axis to truncate. Truncates the index (rows) by default.\n copy : bool, default is True,\n Return a copy of the truncated section.\n\n Returns\n -------\n type of caller\n The truncated Series or DataFrame.\n\n See Also\n --------\n DataFrame.loc : Select a subset of a DataFrame by label.\n DataFrame.iloc : Select a subset of a DataFrame by position.\n\n Notes\n -----\n If the index being truncated contains only datetime values,\n `before` and `after` may be specified as strings instead of\n Timestamps.\n\n Examples\n --------\n >>> df = pd.DataFrame({'A': ['a', 'b', 'c', 'd', 'e'],\n ... 'B': ['f', 'g', 'h', 'i', 'j'],\n ... 'C': ['k', 'l', 'm', 'n', 'o']},\n ... index=[1, 2, 3, 4, 5])\n >>> df\n A B C\n 1 a f k\n 2 b g l\n 3 c h m\n 4 d i n\n 5 e j o\n\n >>> df.truncate(before=2, after=4)\n A B C\n 2 b g l\n 3 c h m\n 4 d i n\n\n The columns of a DataFrame can be truncated.\n\n >>> df.truncate(before=\"A\", after=\"B\", axis=\"columns\")\n A B\n 1 a f\n 2 b g\n 3 c h\n 4 d i\n 5 e j\n\n For Series, only rows can be truncated.\n\n >>> df['A'].truncate(before=2, after=4)\n 2 b\n 3 c\n 4 d\n Name: A, dtype: object\n\n The index values in ``truncate`` can be datetimes or string\n dates.\n\n >>> dates = pd.date_range('2016-01-01', '2016-02-01', freq='s')\n >>> df = pd.DataFrame(index=dates, data={'A': 1})\n >>> df.tail()\n A\n 2016-01-31 23:59:56 1\n 2016-01-31 23:59:57 1\n 2016-01-31 23:59:58 1\n 2016-01-31 23:59:59 1\n 2016-02-01 00:00:00 1\n\n >>> df.truncate(before=pd.Timestamp('2016-01-05'),\n ... after=pd.Timestamp('2016-01-10')).tail()\n A\n 2016-01-09 23:59:56 1\n 2016-01-09 23:59:57 1\n 2016-01-09 23:59:58 1\n 2016-01-09 23:59:59 1\n 2016-01-10 00:00:00 1\n\n Because the index is a DatetimeIndex containing only dates, we can\n specify `before` and `after` as strings. They will be coerced to\n Timestamps before truncation.\n\n >>> df.truncate('2016-01-05', '2016-01-10').tail()\n A\n 2016-01-09 23:59:56 1\n 2016-01-09 23:59:57 1\n 2016-01-09 23:59:58 1\n 2016-01-09 23:59:59 1\n 2016-01-10 00:00:00 1\n\n Note that ``truncate`` assumes a 0 value for any unspecified time\n component (midnight). This differs from partial string slicing, which\n returns any partially matching dates.\n\n >>> df.loc['2016-01-05':'2016-01-10', :].tail()\n A\n 2016-01-10 23:59:55 1\n 2016-01-10 23:59:56 1\n 2016-01-10 23:59:57 1\n 2016-01-10 23:59:58 1\n 2016-01-10 23:59:59 1\n \"\"\"\n if axis is None:\n axis = self._stat_axis_number\n axis = self._get_axis_number(axis)\n ax = self._get_axis(axis)\n\n # GH 17935\n # Check that index is sorted\n if not ax.is_monotonic_increasing and not ax.is_monotonic_decreasing:\n raise ValueError(\"truncate requires a sorted index\")\n\n # if we have a date index, convert to dates, otherwise\n # treat like a slice\n if ax.is_all_dates:\n from pandas.core.tools.datetimes import to_datetime\n\n before = to_datetime(before)\n after = to_datetime(after)\n\n if before is not None and after is not None:\n if before > after:\n raise ValueError(f\"Truncate: {after} must be after {before}\")\n\n slicer = [slice(None, None)] * self._AXIS_LEN\n slicer[axis] = slice(before, after)\n result = self.loc[tuple(slicer)]\n\n if isinstance(ax, MultiIndex):\n setattr(result, self._get_axis_name(axis), ax.truncate(before, after))\n\n if copy:\n result = result.copy()\n\n return result\n\n def tz_convert(\n self: FrameOrSeries, tz, axis=0, level=None, copy: bool_t = True\n ) -> FrameOrSeries:\n \"\"\"\n Convert tz-aware axis to target time zone.\n\n Parameters\n ----------\n tz : str or tzinfo object\n axis : the axis to convert\n level : int, str, default None\n If axis is a MultiIndex, convert a specific level. Otherwise\n must be None.\n copy : bool, default True\n Also make a copy of the underlying data.\n\n Returns\n -------\n %(klass)s\n Object with time zone converted axis.\n\n Raises\n ------\n TypeError\n If the axis is tz-naive.\n \"\"\"\n axis = self._get_axis_number(axis)\n ax = self._get_axis(axis)\n\n def _tz_convert(ax, tz):\n if not hasattr(ax, \"tz_convert\"):\n if len(ax) > 0:\n ax_name = self._get_axis_name(axis)\n raise TypeError(\n f\"{ax_name} is not a valid DatetimeIndex or PeriodIndex\"\n )\n else:\n ax = DatetimeIndex([], tz=tz)\n else:\n ax = ax.tz_convert(tz)\n return ax\n\n # if a level is given it must be a MultiIndex level or\n # equivalent to the axis name\n if isinstance(ax, MultiIndex):\n level = ax._get_level_number(level)\n new_level = _tz_convert(ax.levels[level], tz)\n ax = ax.set_levels(new_level, level=level)\n else:\n if level not in (None, 0, ax.name):\n raise ValueError(f\"The level {level} is not valid\")\n ax = _tz_convert(ax, tz)\n\n result = self._constructor(self._data, copy=copy)\n result = result.set_axis(ax, axis=axis, inplace=False)\n return result.__finalize__(self)\n\n def tz_localize(\n self: FrameOrSeries,\n tz,\n axis=0,\n level=None,\n copy: bool_t = True,\n ambiguous=\"raise\",\n nonexistent: str = \"raise\",\n ) -> FrameOrSeries:\n \"\"\"\n Localize tz-naive index of a Series or DataFrame to target time zone.\n\n This operation localizes the Index. To localize the values in a\n timezone-naive Series, use :meth:`Series.dt.tz_localize`.\n\n Parameters\n ----------\n tz : str or tzinfo\n axis : the axis to localize\n level : int, str, default None\n If axis ia a MultiIndex, localize a specific level. Otherwise\n must be None.\n copy : bool, default True\n Also make a copy of the underlying data.\n ambiguous : 'infer', bool-ndarray, 'NaT', default 'raise'\n When clocks moved backward due to DST, ambiguous times may arise.\n For example in Central European Time (UTC+01), when going from\n 03:00 DST to 02:00 non-DST, 02:30:00 local time occurs both at\n 00:30:00 UTC and at 01:30:00 UTC. In such a situation, the\n `ambiguous` parameter dictates how ambiguous times should be\n handled.\n\n - 'infer' will attempt to infer fall dst-transition hours based on\n order\n - bool-ndarray where True signifies a DST time, False designates\n a non-DST time (note that this flag is only applicable for\n ambiguous times)\n - 'NaT' will return NaT where there are ambiguous times\n - 'raise' will raise an AmbiguousTimeError if there are ambiguous\n times.\n nonexistent : str, default 'raise'\n A nonexistent time does not exist in a particular timezone\n where clocks moved forward due to DST. Valid values are:\n\n - 'shift_forward' will shift the nonexistent time forward to the\n closest existing time\n - 'shift_backward' will shift the nonexistent time backward to the\n closest existing time\n - 'NaT' will return NaT where there are nonexistent times\n - timedelta objects will shift nonexistent times by the timedelta\n - 'raise' will raise an NonExistentTimeError if there are\n nonexistent times.\n\n .. versionadded:: 0.24.0\n\n Returns\n -------\n Series or DataFrame\n Same type as the input.\n\n Raises\n ------\n TypeError\n If the TimeSeries is tz-aware and tz is not None.\n\n Examples\n --------\n\n Localize local times:\n\n >>> s = pd.Series([1],\n ... index=pd.DatetimeIndex(['2018-09-15 01:30:00']))\n >>> s.tz_localize('CET')\n 2018-09-15 01:30:00+02:00 1\n dtype: int64\n\n Be careful with DST changes. When there is sequential data, pandas\n can infer the DST time:\n\n >>> s = pd.Series(range(7),\n ... index=pd.DatetimeIndex(['2018-10-28 01:30:00',\n ... '2018-10-28 02:00:00',\n ... '2018-10-28 02:30:00',\n ... '2018-10-28 02:00:00',\n ... '2018-10-28 02:30:00',\n ... '2018-10-28 03:00:00',\n ... '2018-10-28 03:30:00']))\n >>> s.tz_localize('CET', ambiguous='infer')\n 2018-10-28 01:30:00+02:00 0\n 2018-10-28 02:00:00+02:00 1\n 2018-10-28 02:30:00+02:00 2\n 2018-10-28 02:00:00+01:00 3\n 2018-10-28 02:30:00+01:00 4\n 2018-10-28 03:00:00+01:00 5\n 2018-10-28 03:30:00+01:00 6\n dtype: int64\n\n In some cases, inferring the DST is impossible. In such cases, you can\n pass an ndarray to the ambiguous parameter to set the DST explicitly\n\n >>> s = pd.Series(range(3),\n ... index=pd.DatetimeIndex(['2018-10-28 01:20:00',\n ... '2018-10-28 02:36:00',\n ... '2018-10-28 03:46:00']))\n >>> s.tz_localize('CET', ambiguous=np.array([True, True, False]))\n 2018-10-28 01:20:00+02:00 0\n 2018-10-28 02:36:00+02:00 1\n 2018-10-28 03:46:00+01:00 2\n dtype: int64\n\n If the DST transition causes nonexistent times, you can shift these\n dates forward or backwards with a timedelta object or `'shift_forward'`\n or `'shift_backwards'`.\n >>> s = pd.Series(range(2),\n ... index=pd.DatetimeIndex(['2015-03-29 02:30:00',\n ... '2015-03-29 03:30:00']))\n >>> s.tz_localize('Europe/Warsaw', nonexistent='shift_forward')\n 2015-03-29 03:00:00+02:00 0\n 2015-03-29 03:30:00+02:00 1\n dtype: int64\n >>> s.tz_localize('Europe/Warsaw', nonexistent='shift_backward')\n 2015-03-29 01:59:59.999999999+01:00 0\n 2015-03-29 03:30:00+02:00 1\n dtype: int64\n >>> s.tz_localize('Europe/Warsaw', nonexistent=pd.Timedelta('1H'))\n 2015-03-29 03:30:00+02:00 0\n 2015-03-29 03:30:00+02:00 1\n dtype: int64\n \"\"\"\n nonexistent_options = (\"raise\", \"NaT\", \"shift_forward\", \"shift_backward\")\n if nonexistent not in nonexistent_options and not isinstance(\n nonexistent, timedelta\n ):\n raise ValueError(\n \"The nonexistent argument must be one of 'raise', \"\n \"'NaT', 'shift_forward', 'shift_backward' or \"\n \"a timedelta object\"\n )\n\n axis = self._get_axis_number(axis)\n ax = self._get_axis(axis)\n\n def _tz_localize(ax, tz, ambiguous, nonexistent):\n if not hasattr(ax, \"tz_localize\"):\n if len(ax) > 0:\n ax_name = self._get_axis_name(axis)\n raise TypeError(\n f\"{ax_name} is not a valid DatetimeIndex or PeriodIndex\"\n )\n else:\n ax = DatetimeIndex([], tz=tz)\n else:\n ax = ax.tz_localize(tz, ambiguous=ambiguous, nonexistent=nonexistent)\n return ax\n\n # if a level is given it must be a MultiIndex level or\n # equivalent to the axis name\n if isinstance(ax, MultiIndex):\n level = ax._get_level_number(level)\n new_level = _tz_localize(ax.levels[level], tz, ambiguous, nonexistent)\n ax = ax.set_levels(new_level, level=level)\n else:\n if level not in (None, 0, ax.name):\n raise ValueError(f\"The level {level} is not valid\")\n ax = _tz_localize(ax, tz, ambiguous, nonexistent)\n\n result = self._constructor(self._data, copy=copy)\n result = result.set_axis(ax, axis=axis, inplace=False)\n return result.__finalize__(self)\n\n # ----------------------------------------------------------------------\n # Numeric Methods\n def abs(self):\n \"\"\"\n Return a Series/DataFrame with absolute numeric value of each element.\n\n This function only applies to elements that are all numeric.\n\n Returns\n -------\n abs\n Series/DataFrame containing the absolute value of each element.\n\n See Also\n --------\n numpy.absolute : Calculate the absolute value element-wise.\n\n Notes\n -----\n For ``complex`` inputs, ``1.2 + 1j``, the absolute value is\n :math:`\\\\sqrt{ a^2 + b^2 }`.\n\n Examples\n --------\n Absolute numeric values in a Series.\n\n >>> s = pd.Series([-1.10, 2, -3.33, 4])\n >>> s.abs()\n 0 1.10\n 1 2.00\n 2 3.33\n 3 4.00\n dtype: float64\n\n Absolute numeric values in a Series with complex numbers.\n\n >>> s = pd.Series([1.2 + 1j])\n >>> s.abs()\n 0 1.56205\n dtype: float64\n\n Absolute numeric values in a Series with a Timedelta element.\n\n >>> s = pd.Series([pd.Timedelta('1 days')])\n >>> s.abs()\n 0 1 days\n dtype: timedelta64[ns]\n\n Select rows with data closest to certain value using argsort (from\n `StackOverflow <https://stackoverflow.com/a/17758115>`__).\n\n >>> df = pd.DataFrame({\n ... 'a': [4, 5, 6, 7],\n ... 'b': [10, 20, 30, 40],\n ... 'c': [100, 50, -30, -50]\n ... })\n >>> df\n a b c\n 0 4 10 100\n 1 5 20 50\n 2 6 30 -30\n 3 7 40 -50\n >>> df.loc[(df.c - 43).abs().argsort()]\n a b c\n 1 5 20 50\n 0 4 10 100\n 2 6 30 -30\n 3 7 40 -50\n \"\"\"\n return np.abs(self)\n\n def describe(self, percentiles=None, include=None, exclude=None):\n \"\"\"\n Generate descriptive statistics.\n\n Descriptive statistics include those that summarize the central\n tendency, dispersion and shape of a\n dataset's distribution, excluding ``NaN`` values.\n\n Analyzes both numeric and object series, as well\n as ``DataFrame`` column sets of mixed data types. The output\n will vary depending on what is provided. Refer to the notes\n below for more detail.\n\n Parameters\n ----------\n percentiles : list-like of numbers, optional\n The percentiles to include in the output. All should\n fall between 0 and 1. The default is\n ``[.25, .5, .75]``, which returns the 25th, 50th, and\n 75th percentiles.\n include : 'all', list-like of dtypes or None (default), optional\n A white list of data types to include in the result. Ignored\n for ``Series``. Here are the options:\n\n - 'all' : All columns of the input will be included in the output.\n - A list-like of dtypes : Limits the results to the\n provided data types.\n To limit the result to numeric types submit\n ``numpy.number``. To limit it instead to object columns submit\n the ``numpy.object`` data type. Strings\n can also be used in the style of\n ``select_dtypes`` (e.g. ``df.describe(include=['O'])``). To\n select pandas categorical columns, use ``'category'``\n - None (default) : The result will include all numeric columns.\n exclude : list-like of dtypes or None (default), optional,\n A black list of data types to omit from the result. Ignored\n for ``Series``. Here are the options:\n\n - A list-like of dtypes : Excludes the provided data types\n from the result. To exclude numeric types submit\n ``numpy.number``. To exclude object columns submit the data\n type ``numpy.object``. Strings can also be used in the style of\n ``select_dtypes`` (e.g. ``df.describe(include=['O'])``). To\n exclude pandas categorical columns, use ``'category'``\n - None (default) : The result will exclude nothing.\n\n Returns\n -------\n Series or DataFrame\n Summary statistics of the Series or Dataframe provided.\n\n See Also\n --------\n DataFrame.count: Count number of non-NA/null observations.\n DataFrame.max: Maximum of the values in the object.\n DataFrame.min: Minimum of the values in the object.\n DataFrame.mean: Mean of the values.\n DataFrame.std: Standard deviation of the observations.\n DataFrame.select_dtypes: Subset of a DataFrame including/excluding\n columns based on their dtype.\n\n Notes\n -----\n For numeric data, the result's index will include ``count``,\n ``mean``, ``std``, ``min``, ``max`` as well as lower, ``50`` and\n upper percentiles. By default the lower percentile is ``25`` and the\n upper percentile is ``75``. The ``50`` percentile is the\n same as the median.\n\n For object data (e.g. strings or timestamps), the result's index\n will include ``count``, ``unique``, ``top``, and ``freq``. The ``top``\n is the most common value. The ``freq`` is the most common value's\n frequency. Timestamps also include the ``first`` and ``last`` items.\n\n If multiple object values have the highest count, then the\n ``count`` and ``top`` results will be arbitrarily chosen from\n among those with the highest count.\n\n For mixed data types provided via a ``DataFrame``, the default is to\n return only an analysis of numeric columns. If the dataframe consists\n only of object and categorical data without any numeric columns, the\n default is to return an analysis of both the object and categorical\n columns. If ``include='all'`` is provided as an option, the result\n will include a union of attributes of each type.\n\n The `include` and `exclude` parameters can be used to limit\n which columns in a ``DataFrame`` are analyzed for the output.\n The parameters are ignored when analyzing a ``Series``.\n\n Examples\n --------\n Describing a numeric ``Series``.\n\n >>> s = pd.Series([1, 2, 3])\n >>> s.describe()\n count 3.0\n mean 2.0\n std 1.0\n min 1.0\n 25% 1.5\n 50% 2.0\n 75% 2.5\n max 3.0\n dtype: float64\n\n Describing a categorical ``Series``.\n\n >>> s = pd.Series(['a', 'a', 'b', 'c'])\n >>> s.describe()\n count 4\n unique 3\n top a\n freq 2\n dtype: object\n\n Describing a timestamp ``Series``.\n\n >>> s = pd.Series([\n ... np.datetime64(\"2000-01-01\"),\n ... np.datetime64(\"2010-01-01\"),\n ... np.datetime64(\"2010-01-01\")\n ... ])\n >>> s.describe()\n count 3\n unique 2\n top 2010-01-01 00:00:00\n freq 2\n first 2000-01-01 00:00:00\n last 2010-01-01 00:00:00\n dtype: object\n\n Describing a ``DataFrame``. By default only numeric fields\n are returned.\n\n >>> df = pd.DataFrame({'categorical': pd.Categorical(['d','e','f']),\n ... 'numeric': [1, 2, 3],\n ... 'object': ['a', 'b', 'c']\n ... })\n >>> df.describe()\n numeric\n count 3.0\n mean 2.0\n std 1.0\n min 1.0\n 25% 1.5\n 50% 2.0\n 75% 2.5\n max 3.0\n\n Describing all columns of a ``DataFrame`` regardless of data type.\n\n >>> df.describe(include='all')\n categorical numeric object\n count 3 3.0 3\n unique 3 NaN 3\n top f NaN c\n freq 1 NaN 1\n mean NaN 2.0 NaN\n std NaN 1.0 NaN\n min NaN 1.0 NaN\n 25% NaN 1.5 NaN\n 50% NaN 2.0 NaN\n 75% NaN 2.5 NaN\n max NaN 3.0 NaN\n\n Describing a column from a ``DataFrame`` by accessing it as\n an attribute.\n\n >>> df.numeric.describe()\n count 3.0\n mean 2.0\n std 1.0\n min 1.0\n 25% 1.5\n 50% 2.0\n 75% 2.5\n max 3.0\n Name: numeric, dtype: float64\n\n Including only numeric columns in a ``DataFrame`` description.\n\n >>> df.describe(include=[np.number])\n numeric\n count 3.0\n mean 2.0\n std 1.0\n min 1.0\n 25% 1.5\n 50% 2.0\n 75% 2.5\n max 3.0\n\n Including only string columns in a ``DataFrame`` description.\n\n >>> df.describe(include=[np.object])\n object\n count 3\n unique 3\n top c\n freq 1\n\n Including only categorical columns from a ``DataFrame`` description.\n\n >>> df.describe(include=['category'])\n categorical\n count 3\n unique 3\n top f\n freq 1\n\n Excluding numeric columns from a ``DataFrame`` description.\n\n >>> df.describe(exclude=[np.number])\n categorical object\n count 3 3\n unique 3 3\n top f c\n freq 1 1\n\n Excluding object columns from a ``DataFrame`` description.\n\n >>> df.describe(exclude=[np.object])\n categorical numeric\n count 3 3.0\n unique 3 NaN\n top f NaN\n freq 1 NaN\n mean NaN 2.0\n std NaN 1.0\n min NaN 1.0\n 25% NaN 1.5\n 50% NaN 2.0\n 75% NaN 2.5\n max NaN 3.0\n \"\"\"\n if self.ndim == 2 and self.columns.size == 0:\n raise ValueError(\"Cannot describe a DataFrame without columns\")\n\n if percentiles is not None:\n # explicit conversion of `percentiles` to list\n percentiles = list(percentiles)\n\n # get them all to be in [0, 1]\n validate_percentile(percentiles)\n\n # median should always be included\n if 0.5 not in percentiles:\n percentiles.append(0.5)\n percentiles = np.asarray(percentiles)\n else:\n percentiles = np.array([0.25, 0.5, 0.75])\n\n # sort and check for duplicates\n unique_pcts = np.unique(percentiles)\n if len(unique_pcts) < len(percentiles):\n raise ValueError(\"percentiles cannot contain duplicates\")\n percentiles = unique_pcts\n\n formatted_percentiles = format_percentiles(percentiles)\n\n def describe_numeric_1d(series):\n stat_index = (\n [\"count\", \"mean\", \"std\", \"min\"] + formatted_percentiles + [\"max\"]\n )\n d = (\n [series.count(), series.mean(), series.std(), series.min()]\n + series.quantile(percentiles).tolist()\n + [series.max()]\n )\n return pd.Series(d, index=stat_index, name=series.name)\n\n def describe_categorical_1d(data):\n names = [\"count\", \"unique\"]\n objcounts = data.value_counts()\n count_unique = len(objcounts[objcounts != 0])\n result = [data.count(), count_unique]\n dtype = None\n if result[1] > 0:\n top, freq = objcounts.index[0], objcounts.iloc[0]\n\n if is_datetime64_any_dtype(data):\n tz = data.dt.tz\n asint = data.dropna().values.view(\"i8\")\n top = Timestamp(top)\n if top.tzinfo is not None and tz is not None:\n # Don't tz_localize(None) if key is already tz-aware\n top = top.tz_convert(tz)\n else:\n top = top.tz_localize(tz)\n names += [\"top\", \"freq\", \"first\", \"last\"]\n result += [\n top,\n freq,\n Timestamp(asint.min(), tz=tz),\n Timestamp(asint.max(), tz=tz),\n ]\n else:\n names += [\"top\", \"freq\"]\n result += [top, freq]\n\n # If the DataFrame is empty, set 'top' and 'freq' to None\n # to maintain output shape consistency\n else:\n names += [\"top\", \"freq\"]\n result += [np.nan, np.nan]\n dtype = \"object\"\n\n return pd.Series(result, index=names, name=data.name, dtype=dtype)\n\n def describe_1d(data):\n if is_bool_dtype(data):\n return describe_categorical_1d(data)\n elif is_numeric_dtype(data):\n return describe_numeric_1d(data)\n elif is_timedelta64_dtype(data):\n return describe_numeric_1d(data)\n else:\n return describe_categorical_1d(data)\n\n if self.ndim == 1:\n return describe_1d(self)\n elif (include is None) and (exclude is None):\n # when some numerics are found, keep only numerics\n data = self.select_dtypes(include=[np.number])\n if len(data.columns) == 0:\n data = self\n elif include == \"all\":\n if exclude is not None:\n msg = \"exclude must be None when include is 'all'\"\n raise ValueError(msg)\n data = self\n else:\n data = self.select_dtypes(include=include, exclude=exclude)\n\n ldesc = [describe_1d(s) for _, s in data.items()]\n # set a convenient order for rows\n names = []\n ldesc_indexes = sorted((x.index for x in ldesc), key=len)\n for idxnames in ldesc_indexes:\n for name in idxnames:\n if name not in names:\n names.append(name)\n\n d = pd.concat([x.reindex(names, copy=False) for x in ldesc], axis=1, sort=False)\n d.columns = data.columns.copy()\n return d\n\n _shared_docs[\n \"pct_change\"\n ] = \"\"\"\n Percentage change between the current and a prior element.\n\n Computes the percentage change from the immediately previous row by\n default. This is useful in comparing the percentage of change in a time\n series of elements.\n\n Parameters\n ----------\n periods : int, default 1\n Periods to shift for forming percent change.\n fill_method : str, default 'pad'\n How to handle NAs before computing percent changes.\n limit : int, default None\n The number of consecutive NAs to fill before stopping.\n freq : DateOffset, timedelta, or str, optional\n Increment to use from time series API (e.g. 'M' or BDay()).\n **kwargs\n Additional keyword arguments are passed into\n `DataFrame.shift` or `Series.shift`.\n\n Returns\n -------\n chg : Series or DataFrame\n The same type as the calling object.\n\n See Also\n --------\n Series.diff : Compute the difference of two elements in a Series.\n DataFrame.diff : Compute the difference of two elements in a DataFrame.\n Series.shift : Shift the index by some number of periods.\n DataFrame.shift : Shift the index by some number of periods.\n\n Examples\n --------\n **Series**\n\n >>> s = pd.Series([90, 91, 85])\n >>> s\n 0 90\n 1 91\n 2 85\n dtype: int64\n\n >>> s.pct_change()\n 0 NaN\n 1 0.011111\n 2 -0.065934\n dtype: float64\n\n >>> s.pct_change(periods=2)\n 0 NaN\n 1 NaN\n 2 -0.055556\n dtype: float64\n\n See the percentage change in a Series where filling NAs with last\n valid observation forward to next valid.\n\n >>> s = pd.Series([90, 91, None, 85])\n >>> s\n 0 90.0\n 1 91.0\n 2 NaN\n 3 85.0\n dtype: float64\n\n >>> s.pct_change(fill_method='ffill')\n 0 NaN\n 1 0.011111\n 2 0.000000\n 3 -0.065934\n dtype: float64\n\n **DataFrame**\n\n Percentage change in French franc, Deutsche Mark, and Italian lira from\n 1980-01-01 to 1980-03-01.\n\n >>> df = pd.DataFrame({\n ... 'FR': [4.0405, 4.0963, 4.3149],\n ... 'GR': [1.7246, 1.7482, 1.8519],\n ... 'IT': [804.74, 810.01, 860.13]},\n ... index=['1980-01-01', '1980-02-01', '1980-03-01'])\n >>> df\n FR GR IT\n 1980-01-01 4.0405 1.7246 804.74\n 1980-02-01 4.0963 1.7482 810.01\n 1980-03-01 4.3149 1.8519 860.13\n\n >>> df.pct_change()\n FR GR IT\n 1980-01-01 NaN NaN NaN\n 1980-02-01 0.013810 0.013684 0.006549\n 1980-03-01 0.053365 0.059318 0.061876\n\n Percentage of change in GOOG and APPL stock volume. Shows computing\n the percentage change between columns.\n\n >>> df = pd.DataFrame({\n ... '2016': [1769950, 30586265],\n ... '2015': [1500923, 40912316],\n ... '2014': [1371819, 41403351]},\n ... index=['GOOG', 'APPL'])\n >>> df\n 2016 2015 2014\n GOOG 1769950 1500923 1371819\n APPL 30586265 40912316 41403351\n\n >>> df.pct_change(axis='columns')\n 2016 2015 2014\n GOOG NaN -0.151997 -0.086016\n APPL NaN 0.337604 0.012002\n \"\"\"\n\n @Appender(_shared_docs[\"pct_change\"] % _shared_doc_kwargs)\n def pct_change(self, periods=1, fill_method=\"pad\", limit=None, freq=None, **kwargs):\n # TODO: Not sure if above is correct - need someone to confirm.\n axis = self._get_axis_number(kwargs.pop(\"axis\", self._stat_axis_name))\n if fill_method is None:\n data = self\n else:\n data = self.fillna(method=fill_method, limit=limit, axis=axis)\n\n rs = data.div(data.shift(periods=periods, freq=freq, axis=axis, **kwargs)) - 1\n rs = rs.loc[~rs.index.duplicated()]\n rs = rs.reindex_like(data)\n if freq is None:\n mask = isna(com.values_from_object(data))\n np.putmask(rs.values, mask, np.nan)\n return rs\n\n def _agg_by_level(self, name, axis=0, level=0, skipna=True, **kwargs):\n if axis is None:\n raise ValueError(\"Must specify 'axis' when aggregating by level.\")\n grouped = self.groupby(level=level, axis=axis, sort=False)\n if hasattr(grouped, name) and skipna:\n return getattr(grouped, name)(**kwargs)\n axis = self._get_axis_number(axis)\n method = getattr(type(self), name)\n applyf = lambda x: method(x, axis=axis, skipna=skipna, **kwargs)\n return grouped.aggregate(applyf)\n\n @classmethod\n def _add_numeric_operations(cls):\n \"\"\"\n Add the operations to the cls; evaluate the doc strings again\n \"\"\"\n\n axis_descr, name, name2 = _doc_parms(cls)\n\n cls.any = _make_logical_function(\n cls,\n \"any\",\n name,\n name2,\n axis_descr,\n _any_desc,\n nanops.nanany,\n _any_see_also,\n _any_examples,\n empty_value=False,\n )\n cls.all = _make_logical_function(\n cls,\n \"all\",\n name,\n name2,\n axis_descr,\n _all_desc,\n nanops.nanall,\n _all_see_also,\n _all_examples,\n empty_value=True,\n )\n\n @Substitution(\n desc=\"Return the mean absolute deviation of the values \"\n \"for the requested axis.\",\n name1=name,\n name2=name2,\n axis_descr=axis_descr,\n min_count=\"\",\n see_also=\"\",\n examples=\"\",\n )\n @Appender(_num_doc)\n def mad(self, axis=None, skipna=None, level=None):\n if skipna is None:\n skipna = True\n if axis is None:\n axis = self._stat_axis_number\n if level is not None:\n return self._agg_by_level(\"mad\", axis=axis, level=level, skipna=skipna)\n\n data = self._get_numeric_data()\n if axis == 0:\n demeaned = data - data.mean(axis=0)\n else:\n demeaned = data.sub(data.mean(axis=1), axis=0)\n return np.abs(demeaned).mean(axis=axis, skipna=skipna)\n\n cls.mad = mad\n\n cls.sem = _make_stat_function_ddof(\n cls,\n \"sem\",\n name,\n name2,\n axis_descr,\n \"Return unbiased standard error of the mean over requested \"\n \"axis.\\n\\nNormalized by N-1 by default. This can be changed \"\n \"using the ddof argument\",\n nanops.nansem,\n )\n cls.var = _make_stat_function_ddof(\n cls,\n \"var\",\n name,\n name2,\n axis_descr,\n \"Return unbiased variance over requested axis.\\n\\nNormalized by \"\n \"N-1 by default. This can be changed using the ddof argument\",\n nanops.nanvar,\n )\n cls.std = _make_stat_function_ddof(\n cls,\n \"std\",\n name,\n name2,\n axis_descr,\n \"Return sample standard deviation over requested axis.\"\n \"\\n\\nNormalized by N-1 by default. This can be changed using the \"\n \"ddof argument\",\n nanops.nanstd,\n )\n\n cls.cummin = _make_cum_function(\n cls,\n \"cummin\",\n name,\n name2,\n axis_descr,\n \"minimum\",\n np.minimum.accumulate,\n \"min\",\n np.inf,\n np.nan,\n _cummin_examples,\n )\n cls.cumsum = _make_cum_function(\n cls,\n \"cumsum\",\n name,\n name2,\n axis_descr,\n \"sum\",\n np.cumsum,\n \"sum\",\n 0.0,\n np.nan,\n _cumsum_examples,\n )\n cls.cumprod = _make_cum_function(\n cls,\n \"cumprod\",\n name,\n name2,\n axis_descr,\n \"product\",\n np.cumprod,\n \"prod\",\n 1.0,\n np.nan,\n _cumprod_examples,\n )\n cls.cummax = _make_cum_function(\n cls,\n \"cummax\",\n name,\n name2,\n axis_descr,\n \"maximum\",\n np.maximum.accumulate,\n \"max\",\n -np.inf,\n np.nan,\n _cummax_examples,\n )\n\n cls.sum = _make_min_count_stat_function(\n cls,\n \"sum\",\n name,\n name2,\n axis_descr,\n \"\"\"Return the sum of the values for the requested axis.\\n\n This is equivalent to the method ``numpy.sum``.\"\"\",\n nanops.nansum,\n _stat_func_see_also,\n _sum_examples,\n )\n cls.mean = _make_stat_function(\n cls,\n \"mean\",\n name,\n name2,\n axis_descr,\n \"Return the mean of the values for the requested axis.\",\n nanops.nanmean,\n )\n cls.skew = _make_stat_function(\n cls,\n \"skew\",\n name,\n name2,\n axis_descr,\n \"Return unbiased skew over requested axis.\\n\\nNormalized by N-1.\",\n nanops.nanskew,\n )\n cls.kurt = _make_stat_function(\n cls,\n \"kurt\",\n name,\n name2,\n axis_descr,\n \"Return unbiased kurtosis over requested axis.\\n\\n\"\n \"Kurtosis obtained using Fisher's definition of\\n\"\n \"kurtosis (kurtosis of normal == 0.0). Normalized \"\n \"by N-1.\",\n nanops.nankurt,\n )\n cls.kurtosis = cls.kurt\n cls.prod = _make_min_count_stat_function(\n cls,\n \"prod\",\n name,\n name2,\n axis_descr,\n \"Return the product of the values for the requested axis.\",\n nanops.nanprod,\n examples=_prod_examples,\n )\n cls.product = cls.prod\n cls.median = _make_stat_function(\n cls,\n \"median\",\n name,\n name2,\n axis_descr,\n \"Return the median of the values for the requested axis.\",\n nanops.nanmedian,\n )\n cls.max = _make_stat_function(\n cls,\n \"max\",\n name,\n name2,\n axis_descr,\n \"\"\"Return the maximum of the values for the requested axis.\\n\n If you want the *index* of the maximum, use ``idxmax``. This is\n the equivalent of the ``numpy.ndarray`` method ``argmax``.\"\"\",\n nanops.nanmax,\n _stat_func_see_also,\n _max_examples,\n )\n cls.min = _make_stat_function(\n cls,\n \"min\",\n name,\n name2,\n axis_descr,\n \"\"\"Return the minimum of the values for the requested axis.\\n\n If you want the *index* of the minimum, use ``idxmin``. This is\n the equivalent of the ``numpy.ndarray`` method ``argmin``.\"\"\",\n nanops.nanmin,\n _stat_func_see_also,\n _min_examples,\n )\n\n @classmethod\n def _add_series_or_dataframe_operations(cls):\n \"\"\"\n Add the series or dataframe only operations to the cls; evaluate\n the doc strings again.\n \"\"\"\n\n from pandas.core.window import EWM, Expanding, Rolling, Window\n\n @Appender(Rolling.__doc__)\n def rolling(\n self,\n window,\n min_periods=None,\n center=False,\n win_type=None,\n on=None,\n axis=0,\n closed=None,\n ):\n axis = self._get_axis_number(axis)\n\n if win_type is not None:\n return Window(\n self,\n window=window,\n min_periods=min_periods,\n center=center,\n win_type=win_type,\n on=on,\n axis=axis,\n closed=closed,\n )\n\n return Rolling(\n self,\n window=window,\n min_periods=min_periods,\n center=center,\n win_type=win_type,\n on=on,\n axis=axis,\n closed=closed,\n )\n\n cls.rolling = rolling\n\n @Appender(Expanding.__doc__)\n def expanding(self, min_periods=1, center=False, axis=0):\n axis = self._get_axis_number(axis)\n return Expanding(self, min_periods=min_periods, center=center, axis=axis)\n\n cls.expanding = expanding\n\n @Appender(EWM.__doc__)\n def ewm(\n self,\n com=None,\n span=None,\n halflife=None,\n alpha=None,\n min_periods=0,\n adjust=True,\n ignore_na=False,\n axis=0,\n ):\n axis = self._get_axis_number(axis)\n return EWM(\n self,\n com=com,\n span=span,\n halflife=halflife,\n alpha=alpha,\n min_periods=min_periods,\n adjust=adjust,\n ignore_na=ignore_na,\n axis=axis,\n )\n\n cls.ewm = ewm\n\n @Appender(_shared_docs[\"transform\"] % dict(axis=\"\", **_shared_doc_kwargs))\n def transform(self, func, *args, **kwargs):\n result = self.agg(func, *args, **kwargs)\n if is_scalar(result) or len(result) != len(self):\n raise ValueError(\"transforms cannot produce aggregated results\")\n\n return result\n\n # ----------------------------------------------------------------------\n # Misc methods\n\n _shared_docs[\n \"valid_index\"\n ] = \"\"\"\n Return index for %(position)s non-NA/null value.\n\n Returns\n -------\n scalar : type of index\n\n Notes\n -----\n If all elements are non-NA/null, returns None.\n Also returns None for empty %(klass)s.\n \"\"\"\n\n def _find_valid_index(self, how: str):\n \"\"\"\n Retrieves the index of the first valid value.\n\n Parameters\n ----------\n how : {'first', 'last'}\n Use this parameter to change between the first or last valid index.\n\n Returns\n -------\n idx_first_valid : type of index\n \"\"\"\n\n idxpos = find_valid_index(self._values, how)\n if idxpos is None:\n return None\n return self.index[idxpos]\n\n @Appender(\n _shared_docs[\"valid_index\"] % {\"position\": \"first\", \"klass\": \"Series/DataFrame\"}\n )\n def first_valid_index(self):\n return self._find_valid_index(\"first\")\n\n @Appender(\n _shared_docs[\"valid_index\"] % {\"position\": \"last\", \"klass\": \"Series/DataFrame\"}\n )\n def last_valid_index(self):\n return self._find_valid_index(\"last\")\n\n\ndef _doc_parms(cls):\n \"\"\"Return a tuple of the doc parms.\"\"\"\n axis_descr = (\n f\"{{{', '.join(f'{a} ({i})' for i, a in enumerate(cls._AXIS_ORDERS))}}}\"\n )\n name = cls._constructor_sliced.__name__ if cls._AXIS_LEN > 1 else \"scalar\"\n name2 = cls.__name__\n return axis_descr, name, name2\n\n\n_num_doc = \"\"\"\n%(desc)s\n\nParameters\n----------\naxis : %(axis_descr)s\n Axis for the function to be applied on.\nskipna : bool, default True\n Exclude NA/null values when computing the result.\nlevel : int or level name, default None\n If the axis is a MultiIndex (hierarchical), count along a\n particular level, collapsing into a %(name1)s.\nnumeric_only : bool, default None\n Include only float, int, boolean columns. If None, will attempt to use\n everything, then use only numeric data. Not implemented for Series.\n%(min_count)s\\\n**kwargs\n Additional keyword arguments to be passed to the function.\n\nReturns\n-------\n%(name1)s or %(name2)s (if level specified)\\\n%(see_also)s\\\n%(examples)s\n\"\"\"\n\n_num_ddof_doc = \"\"\"\n%(desc)s\n\nParameters\n----------\naxis : %(axis_descr)s\nskipna : bool, default True\n Exclude NA/null values. If an entire row/column is NA, the result\n will be NA.\nlevel : int or level name, default None\n If the axis is a MultiIndex (hierarchical), count along a\n particular level, collapsing into a %(name1)s.\nddof : int, default 1\n Delta Degrees of Freedom. The divisor used in calculations is N - ddof,\n where N represents the number of elements.\nnumeric_only : bool, default None\n Include only float, int, boolean columns. If None, will attempt to use\n everything, then use only numeric data. Not implemented for Series.\n\nReturns\n-------\n%(name1)s or %(name2)s (if level specified)\\n\"\"\"\n\n_bool_doc = \"\"\"\n%(desc)s\n\nParameters\n----------\naxis : {0 or 'index', 1 or 'columns', None}, default 0\n Indicate which axis or axes should be reduced.\n\n * 0 / 'index' : reduce the index, return a Series whose index is the\n original column labels.\n * 1 / 'columns' : reduce the columns, return a Series whose index is the\n original index.\n * None : reduce all axes, return a scalar.\n\nbool_only : bool, default None\n Include only boolean columns. If None, will attempt to use everything,\n then use only boolean data. Not implemented for Series.\nskipna : bool, default True\n Exclude NA/null values. If the entire row/column is NA and skipna is\n True, then the result will be %(empty_value)s, as for an empty row/column.\n If skipna is False, then NA are treated as True, because these are not\n equal to zero.\nlevel : int or level name, default None\n If the axis is a MultiIndex (hierarchical), count along a\n particular level, collapsing into a %(name1)s.\n**kwargs : any, default None\n Additional keywords have no effect but might be accepted for\n compatibility with NumPy.\n\nReturns\n-------\n%(name1)s or %(name2)s\n If level is specified, then, %(name2)s is returned; otherwise, %(name1)s\n is returned.\n\n%(see_also)s\n%(examples)s\"\"\"\n\n_all_desc = \"\"\"\\\nReturn whether all elements are True, potentially over an axis.\n\nReturns True unless there at least one element within a series or\nalong a Dataframe axis that is False or equivalent (e.g. zero or\nempty).\"\"\"\n\n_all_examples = \"\"\"\\\nExamples\n--------\n**Series**\n\n>>> pd.Series([True, True]).all()\nTrue\n>>> pd.Series([True, False]).all()\nFalse\n>>> pd.Series([]).all()\nTrue\n>>> pd.Series([np.nan]).all()\nTrue\n>>> pd.Series([np.nan]).all(skipna=False)\nTrue\n\n**DataFrames**\n\nCreate a dataframe from a dictionary.\n\n>>> df = pd.DataFrame({'col1': [True, True], 'col2': [True, False]})\n>>> df\n col1 col2\n0 True True\n1 True False\n\nDefault behaviour checks if column-wise values all return True.\n\n>>> df.all()\ncol1 True\ncol2 False\ndtype: bool\n\nSpecify ``axis='columns'`` to check if row-wise values all return True.\n\n>>> df.all(axis='columns')\n0 True\n1 False\ndtype: bool\n\nOr ``axis=None`` for whether every value is True.\n\n>>> df.all(axis=None)\nFalse\n\"\"\"\n\n_all_see_also = \"\"\"\\\nSee Also\n--------\nSeries.all : Return True if all elements are True.\nDataFrame.any : Return True if one (or more) elements are True.\n\"\"\"\n\n_cnum_doc = \"\"\"\nReturn cumulative %(desc)s over a DataFrame or Series axis.\n\nReturns a DataFrame or Series of the same size containing the cumulative\n%(desc)s.\n\nParameters\n----------\naxis : {0 or 'index', 1 or 'columns'}, default 0\n The index or the name of the axis. 0 is equivalent to None or 'index'.\nskipna : bool, default True\n Exclude NA/null values. If an entire row/column is NA, the result\n will be NA.\n*args, **kwargs :\n Additional keywords have no effect but might be accepted for\n compatibility with NumPy.\n\nReturns\n-------\n%(name1)s or %(name2)s\n\nSee Also\n--------\ncore.window.Expanding.%(accum_func_name)s : Similar functionality\n but ignores ``NaN`` values.\n%(name2)s.%(accum_func_name)s : Return the %(desc)s over\n %(name2)s axis.\n%(name2)s.cummax : Return cumulative maximum over %(name2)s axis.\n%(name2)s.cummin : Return cumulative minimum over %(name2)s axis.\n%(name2)s.cumsum : Return cumulative sum over %(name2)s axis.\n%(name2)s.cumprod : Return cumulative product over %(name2)s axis.\n\n%(examples)s\"\"\"\n\n_cummin_examples = \"\"\"\\\nExamples\n--------\n**Series**\n\n>>> s = pd.Series([2, np.nan, 5, -1, 0])\n>>> s\n0 2.0\n1 NaN\n2 5.0\n3 -1.0\n4 0.0\ndtype: float64\n\nBy default, NA values are ignored.\n\n>>> s.cummin()\n0 2.0\n1 NaN\n2 2.0\n3 -1.0\n4 -1.0\ndtype: float64\n\nTo include NA values in the operation, use ``skipna=False``\n\n>>> s.cummin(skipna=False)\n0 2.0\n1 NaN\n2 NaN\n3 NaN\n4 NaN\ndtype: float64\n\n**DataFrame**\n\n>>> df = pd.DataFrame([[2.0, 1.0],\n... [3.0, np.nan],\n... [1.0, 0.0]],\n... columns=list('AB'))\n>>> df\n A B\n0 2.0 1.0\n1 3.0 NaN\n2 1.0 0.0\n\nBy default, iterates over rows and finds the minimum\nin each column. This is equivalent to ``axis=None`` or ``axis='index'``.\n\n>>> df.cummin()\n A B\n0 2.0 1.0\n1 2.0 NaN\n2 1.0 0.0\n\nTo iterate over columns and find the minimum in each row,\nuse ``axis=1``\n\n>>> df.cummin(axis=1)\n A B\n0 2.0 1.0\n1 3.0 NaN\n2 1.0 0.0\n\"\"\"\n\n_cumsum_examples = \"\"\"\\\nExamples\n--------\n**Series**\n\n>>> s = pd.Series([2, np.nan, 5, -1, 0])\n>>> s\n0 2.0\n1 NaN\n2 5.0\n3 -1.0\n4 0.0\ndtype: float64\n\nBy default, NA values are ignored.\n\n>>> s.cumsum()\n0 2.0\n1 NaN\n2 7.0\n3 6.0\n4 6.0\ndtype: float64\n\nTo include NA values in the operation, use ``skipna=False``\n\n>>> s.cumsum(skipna=False)\n0 2.0\n1 NaN\n2 NaN\n3 NaN\n4 NaN\ndtype: float64\n\n**DataFrame**\n\n>>> df = pd.DataFrame([[2.0, 1.0],\n... [3.0, np.nan],\n... [1.0, 0.0]],\n... columns=list('AB'))\n>>> df\n A B\n0 2.0 1.0\n1 3.0 NaN\n2 1.0 0.0\n\nBy default, iterates over rows and finds the sum\nin each column. This is equivalent to ``axis=None`` or ``axis='index'``.\n\n>>> df.cumsum()\n A B\n0 2.0 1.0\n1 5.0 NaN\n2 6.0 1.0\n\nTo iterate over columns and find the sum in each row,\nuse ``axis=1``\n\n>>> df.cumsum(axis=1)\n A B\n0 2.0 3.0\n1 3.0 NaN\n2 1.0 1.0\n\"\"\"\n\n_cumprod_examples = \"\"\"\\\nExamples\n--------\n**Series**\n\n>>> s = pd.Series([2, np.nan, 5, -1, 0])\n>>> s\n0 2.0\n1 NaN\n2 5.0\n3 -1.0\n4 0.0\ndtype: float64\n\nBy default, NA values are ignored.\n\n>>> s.cumprod()\n0 2.0\n1 NaN\n2 10.0\n3 -10.0\n4 -0.0\ndtype: float64\n\nTo include NA values in the operation, use ``skipna=False``\n\n>>> s.cumprod(skipna=False)\n0 2.0\n1 NaN\n2 NaN\n3 NaN\n4 NaN\ndtype: float64\n\n**DataFrame**\n\n>>> df = pd.DataFrame([[2.0, 1.0],\n... [3.0, np.nan],\n... [1.0, 0.0]],\n... columns=list('AB'))\n>>> df\n A B\n0 2.0 1.0\n1 3.0 NaN\n2 1.0 0.0\n\nBy default, iterates over rows and finds the product\nin each column. This is equivalent to ``axis=None`` or ``axis='index'``.\n\n>>> df.cumprod()\n A B\n0 2.0 1.0\n1 6.0 NaN\n2 6.0 0.0\n\nTo iterate over columns and find the product in each row,\nuse ``axis=1``\n\n>>> df.cumprod(axis=1)\n A B\n0 2.0 2.0\n1 3.0 NaN\n2 1.0 0.0\n\"\"\"\n\n_cummax_examples = \"\"\"\\\nExamples\n--------\n**Series**\n\n>>> s = pd.Series([2, np.nan, 5, -1, 0])\n>>> s\n0 2.0\n1 NaN\n2 5.0\n3 -1.0\n4 0.0\ndtype: float64\n\nBy default, NA values are ignored.\n\n>>> s.cummax()\n0 2.0\n1 NaN\n2 5.0\n3 5.0\n4 5.0\ndtype: float64\n\nTo include NA values in the operation, use ``skipna=False``\n\n>>> s.cummax(skipna=False)\n0 2.0\n1 NaN\n2 NaN\n3 NaN\n4 NaN\ndtype: float64\n\n**DataFrame**\n\n>>> df = pd.DataFrame([[2.0, 1.0],\n... [3.0, np.nan],\n... [1.0, 0.0]],\n... columns=list('AB'))\n>>> df\n A B\n0 2.0 1.0\n1 3.0 NaN\n2 1.0 0.0\n\nBy default, iterates over rows and finds the maximum\nin each column. This is equivalent to ``axis=None`` or ``axis='index'``.\n\n>>> df.cummax()\n A B\n0 2.0 1.0\n1 3.0 NaN\n2 3.0 1.0\n\nTo iterate over columns and find the maximum in each row,\nuse ``axis=1``\n\n>>> df.cummax(axis=1)\n A B\n0 2.0 2.0\n1 3.0 NaN\n2 1.0 1.0\n\"\"\"\n\n_any_see_also = \"\"\"\\\nSee Also\n--------\nnumpy.any : Numpy version of this method.\nSeries.any : Return whether any element is True.\nSeries.all : Return whether all elements are True.\nDataFrame.any : Return whether any element is True over requested axis.\nDataFrame.all : Return whether all elements are True over requested axis.\n\"\"\"\n\n_any_desc = \"\"\"\\\nReturn whether any element is True, potentially over an axis.\n\nReturns False unless there at least one element within a series or\nalong a Dataframe axis that is True or equivalent (e.g. non-zero or\nnon-empty).\"\"\"\n\n_any_examples = \"\"\"\\\nExamples\n--------\n**Series**\n\nFor Series input, the output is a scalar indicating whether any element\nis True.\n\n>>> pd.Series([False, False]).any()\nFalse\n>>> pd.Series([True, False]).any()\nTrue\n>>> pd.Series([]).any()\nFalse\n>>> pd.Series([np.nan]).any()\nFalse\n>>> pd.Series([np.nan]).any(skipna=False)\nTrue\n\n**DataFrame**\n\nWhether each column contains at least one True element (the default).\n\n>>> df = pd.DataFrame({\"A\": [1, 2], \"B\": [0, 2], \"C\": [0, 0]})\n>>> df\n A B C\n0 1 0 0\n1 2 2 0\n\n>>> df.any()\nA True\nB True\nC False\ndtype: bool\n\nAggregating over the columns.\n\n>>> df = pd.DataFrame({\"A\": [True, False], \"B\": [1, 2]})\n>>> df\n A B\n0 True 1\n1 False 2\n\n>>> df.any(axis='columns')\n0 True\n1 True\ndtype: bool\n\n>>> df = pd.DataFrame({\"A\": [True, False], \"B\": [1, 0]})\n>>> df\n A B\n0 True 1\n1 False 0\n\n>>> df.any(axis='columns')\n0 True\n1 False\ndtype: bool\n\nAggregating over the entire DataFrame with ``axis=None``.\n\n>>> df.any(axis=None)\nTrue\n\n`any` for an empty DataFrame is an empty Series.\n\n>>> pd.DataFrame([]).any()\nSeries([], dtype: bool)\n\"\"\"\n\n_shared_docs[\n \"stat_func_example\"\n] = \"\"\"\n\nExamples\n--------\n>>> idx = pd.MultiIndex.from_arrays([\n... ['warm', 'warm', 'cold', 'cold'],\n... ['dog', 'falcon', 'fish', 'spider']],\n... names=['blooded', 'animal'])\n>>> s = pd.Series([4, 2, 0, 8], name='legs', index=idx)\n>>> s\nblooded animal\nwarm dog 4\n falcon 2\ncold fish 0\n spider 8\nName: legs, dtype: int64\n\n>>> s.{stat_func}()\n{default_output}\n\n{verb} using level names, as well as indices.\n\n>>> s.{stat_func}(level='blooded')\nblooded\nwarm {level_output_0}\ncold {level_output_1}\nName: legs, dtype: int64\n\n>>> s.{stat_func}(level=0)\nblooded\nwarm {level_output_0}\ncold {level_output_1}\nName: legs, dtype: int64\"\"\"\n\n_sum_examples = _shared_docs[\"stat_func_example\"].format(\n stat_func=\"sum\", verb=\"Sum\", default_output=14, level_output_0=6, level_output_1=8\n)\n\n_sum_examples += \"\"\"\n\nBy default, the sum of an empty or all-NA Series is ``0``.\n\n>>> pd.Series([]).sum() # min_count=0 is the default\n0.0\n\nThis can be controlled with the ``min_count`` parameter. For example, if\nyou'd like the sum of an empty series to be NaN, pass ``min_count=1``.\n\n>>> pd.Series([]).sum(min_count=1)\nnan\n\nThanks to the ``skipna`` parameter, ``min_count`` handles all-NA and\nempty series identically.\n\n>>> pd.Series([np.nan]).sum()\n0.0\n\n>>> pd.Series([np.nan]).sum(min_count=1)\nnan\"\"\"\n\n_max_examples = _shared_docs[\"stat_func_example\"].format(\n stat_func=\"max\", verb=\"Max\", default_output=8, level_output_0=4, level_output_1=8\n)\n\n_min_examples = _shared_docs[\"stat_func_example\"].format(\n stat_func=\"min\", verb=\"Min\", default_output=0, level_output_0=2, level_output_1=0\n)\n\n_stat_func_see_also = \"\"\"\n\nSee Also\n--------\nSeries.sum : Return the sum.\nSeries.min : Return the minimum.\nSeries.max : Return the maximum.\nSeries.idxmin : Return the index of the minimum.\nSeries.idxmax : Return the index of the maximum.\nDataFrame.sum : Return the sum over the requested axis.\nDataFrame.min : Return the minimum over the requested axis.\nDataFrame.max : Return the maximum over the requested axis.\nDataFrame.idxmin : Return the index of the minimum over the requested axis.\nDataFrame.idxmax : Return the index of the maximum over the requested axis.\"\"\"\n\n_prod_examples = \"\"\"\n\nExamples\n--------\nBy default, the product of an empty or all-NA Series is ``1``\n\n>>> pd.Series([]).prod()\n1.0\n\nThis can be controlled with the ``min_count`` parameter\n\n>>> pd.Series([]).prod(min_count=1)\nnan\n\nThanks to the ``skipna`` parameter, ``min_count`` handles all-NA and\nempty series identically.\n\n>>> pd.Series([np.nan]).prod()\n1.0\n\n>>> pd.Series([np.nan]).prod(min_count=1)\nnan\"\"\"\n\n_min_count_stub = \"\"\"\\\nmin_count : int, default 0\n The required number of valid values to perform the operation. If fewer than\n ``min_count`` non-NA values are present the result will be NA.\n\n .. versionadded:: 0.22.0\n\n Added with the default being 0. This means the sum of an all-NA\n or empty Series is 0, and the product of an all-NA or empty\n Series is 1.\n\"\"\"\n\n\ndef _make_min_count_stat_function(\n cls, name, name1, name2, axis_descr, desc, f, see_also: str = \"\", examples: str = \"\"\n):\n @Substitution(\n desc=desc,\n name1=name1,\n name2=name2,\n axis_descr=axis_descr,\n min_count=_min_count_stub,\n see_also=see_also,\n examples=examples,\n )\n @Appender(_num_doc)\n def stat_func(\n self,\n axis=None,\n skipna=None,\n level=None,\n numeric_only=None,\n min_count=0,\n **kwargs,\n ):\n if name == \"sum\":\n nv.validate_sum(tuple(), kwargs)\n elif name == \"prod\":\n nv.validate_prod(tuple(), kwargs)\n else:\n nv.validate_stat_func(tuple(), kwargs, fname=name)\n if skipna is None:\n skipna = True\n if axis is None:\n axis = self._stat_axis_number\n if level is not None:\n return self._agg_by_level(\n name, axis=axis, level=level, skipna=skipna, min_count=min_count\n )\n return self._reduce(\n f,\n name,\n axis=axis,\n skipna=skipna,\n numeric_only=numeric_only,\n min_count=min_count,\n )\n\n return set_function_name(stat_func, name, cls)\n\n\ndef _make_stat_function(\n cls, name, name1, name2, axis_descr, desc, f, see_also: str = \"\", examples: str = \"\"\n):\n @Substitution(\n desc=desc,\n name1=name1,\n name2=name2,\n axis_descr=axis_descr,\n min_count=\"\",\n see_also=see_also,\n examples=examples,\n )\n @Appender(_num_doc)\n def stat_func(\n self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs\n ):\n if name == \"median\":\n nv.validate_median(tuple(), kwargs)\n else:\n nv.validate_stat_func(tuple(), kwargs, fname=name)\n if skipna is None:\n skipna = True\n if axis is None:\n axis = self._stat_axis_number\n if level is not None:\n return self._agg_by_level(name, axis=axis, level=level, skipna=skipna)\n return self._reduce(\n f, name, axis=axis, skipna=skipna, numeric_only=numeric_only\n )\n\n return set_function_name(stat_func, name, cls)\n\n\ndef _make_stat_function_ddof(cls, name, name1, name2, axis_descr, desc, f):\n @Substitution(desc=desc, name1=name1, name2=name2, axis_descr=axis_descr)\n @Appender(_num_ddof_doc)\n def stat_func(\n self, axis=None, skipna=None, level=None, ddof=1, numeric_only=None, **kwargs\n ):\n nv.validate_stat_ddof_func(tuple(), kwargs, fname=name)\n if skipna is None:\n skipna = True\n if axis is None:\n axis = self._stat_axis_number\n if level is not None:\n return self._agg_by_level(\n name, axis=axis, level=level, skipna=skipna, ddof=ddof\n )\n return self._reduce(\n f, name, axis=axis, numeric_only=numeric_only, skipna=skipna, ddof=ddof\n )\n\n return set_function_name(stat_func, name, cls)\n\n\ndef _make_cum_function(\n cls,\n name,\n name1,\n name2,\n axis_descr,\n desc,\n accum_func,\n accum_func_name,\n mask_a,\n mask_b,\n examples,\n):\n @Substitution(\n desc=desc,\n name1=name1,\n name2=name2,\n axis_descr=axis_descr,\n accum_func_name=accum_func_name,\n examples=examples,\n )\n @Appender(_cnum_doc)\n def cum_func(self, axis=None, skipna=True, *args, **kwargs):\n skipna = nv.validate_cum_func_with_skipna(skipna, args, kwargs, name)\n if axis is None:\n axis = self._stat_axis_number\n else:\n axis = self._get_axis_number(axis)\n\n if axis == 1:\n return cum_func(self.T, axis=0, skipna=skipna, *args, **kwargs).T\n\n def na_accum_func(blk_values):\n # We will be applying this function to block values\n if blk_values.dtype.kind in [\"m\", \"M\"]:\n # numpy 1.18 started sorting NaTs at the end instead of beginning,\n # so we need to work around to maintain backwards-consistency.\n orig_dtype = blk_values.dtype\n\n # We need to define mask before masking NaTs\n mask = isna(blk_values)\n\n if accum_func == np.minimum.accumulate:\n # Note: the accum_func comparison fails as an \"is\" comparison\n y = blk_values.view(\"i8\")\n y[mask] = np.iinfo(np.int64).max\n changed = True\n else:\n y = blk_values\n changed = False\n\n result = accum_func(y.view(\"i8\"), axis)\n if skipna:\n np.putmask(result, mask, iNaT)\n elif accum_func == np.minimum.accumulate:\n # Restore NaTs that we masked previously\n nz = (~np.asarray(mask)).nonzero()[0]\n if len(nz):\n # everything up to the first non-na entry stays NaT\n result[: nz[0]] = iNaT\n\n if changed:\n # restore NaT elements\n y[mask] = iNaT # TODO: could try/finally for this?\n\n if isinstance(blk_values, np.ndarray):\n result = result.view(orig_dtype)\n else:\n # DatetimeArray\n result = type(blk_values)._from_sequence(result, dtype=orig_dtype)\n\n elif skipna and not issubclass(\n blk_values.dtype.type, (np.integer, np.bool_)\n ):\n vals = blk_values.copy().T\n mask = isna(vals)\n np.putmask(vals, mask, mask_a)\n result = accum_func(vals, axis)\n np.putmask(result, mask, mask_b)\n else:\n result = accum_func(blk_values.T, axis)\n\n # transpose back for ndarray, not for EA\n return result.T if hasattr(result, \"T\") else result\n\n result = self._data.apply(na_accum_func)\n\n d = self._construct_axes_dict()\n d[\"copy\"] = False\n return self._constructor(result, **d).__finalize__(self)\n\n return set_function_name(cum_func, name, cls)\n\n\ndef _make_logical_function(\n cls, name, name1, name2, axis_descr, desc, f, see_also, examples, empty_value\n):\n @Substitution(\n desc=desc,\n name1=name1,\n name2=name2,\n axis_descr=axis_descr,\n see_also=see_also,\n examples=examples,\n empty_value=empty_value,\n )\n @Appender(_bool_doc)\n def logical_func(self, axis=0, bool_only=None, skipna=True, level=None, **kwargs):\n nv.validate_logical_func(tuple(), kwargs, fname=name)\n if level is not None:\n if bool_only is not None:\n raise NotImplementedError(\n \"Option bool_only is not implemented with option level.\"\n )\n return self._agg_by_level(name, axis=axis, level=level, skipna=skipna)\n return self._reduce(\n f,\n name,\n axis=axis,\n skipna=skipna,\n numeric_only=bool_only,\n filter_type=\"bool\",\n )\n\n return set_function_name(logical_func, name, cls)\n\n\n# install the indexes\nfor _name, _indexer in indexing.get_indexers_list():\n NDFrame._create_indexer(_name, _indexer)\n" ]
[ [ "pandas.util.testing.assert_numpy_array_equal", "pandas.to_datetime", "pandas.Series", "pandas.util.testing.assert_series_equal", "pandas.to_timedelta", "numpy.array" ], [ "pandas.core.dtypes.common.is_list_like", "numpy.array", "numpy.empty" ], [ "pandas.util.testing.makeTimeSeries", "pandas.Series", "scipy.stats.pearsonr", "pandas.util.testing.assert_almost_equal", "pandas.DataFrame", "numpy.random.randn", "scipy.stats.kendalltau", "scipy.stats.spearmanr" ], [ "pandas.tseries.frequencies.to_offset", "pandas.util._validators.validate_bool_kwarg", "pandas.core.dtypes.inference.is_hashable", "numpy.unique", "numpy.asanyarray", "pandas.core.dtypes.common.is_re_compilable", "pandas.concat", "pandas.core.dtypes.common.is_list_like", "pandas.compat.numpy.function.validate_cum_func_with_skipna", "pandas.io.pickle.to_pickle", "numpy.array", "pandas.core.dtypes.common.is_period_arraylike", "pandas.io.formats.format.DataFrameFormatter", "pandas.core.dtypes.common.is_bool_dtype", "pandas.core.window.Window", "pandas.core.dtypes.missing.isna", "pandas.io.sql.to_sql", "pandas.Series", "numpy.asarray", "pandas.io.json.to_json", "pandas.core.dtypes.common.is_datetime64tz_dtype", "numpy.iinfo", "pandas.core.common.SettingWithCopyError", "pandas.compat._optional.import_optional_dependency", "pandas._config.config.is_nonnegative_int", "numpy.putmask", "pandas.core.construction.create_series_with_explicit_dtype", "pandas.core.common.maybe_box_datetimelike", "pandas._libs.Timestamp", "pandas.core.dtypes.common.ensure_str", "pandas.core.indexes.api.Index", "numpy.errstate", "pandas.core.resample.resample", "pandas.core.common.random_state", "pandas.core.dtypes.common.is_integer", "pandas._libs.lib.item_from_zerodim", "pandas.core.indexes.datetimes.DatetimeIndex", "pandas.core.window.EWM", "pandas.core.dtypes.common.is_extension_array_dtype", "pandas.core.missing.find_valid_index", "pandas.core.dtypes.missing.notna", "pandas.DataFrame", "pandas.core.common.pipe", "pandas.core.indexes.api.RangeIndex", "pandas.core.common.values_from_object", "pandas.io.pytables.to_hdf", "pandas.util._decorators.Substitution", "pandas.core.dtypes.common.is_numeric_dtype", "pandas.errors.AbstractMethodError", "pandas.core.groupby.groupby.get_groupby", "pandas.core.dtypes.common.is_number", "pandas.core.dtypes.common.ensure_int64", "pandas.core.dtypes.common.is_dict_like", "pandas.core.window.Rolling", "pandas.util._decorators.Appender", "pandas.core.dtypes.common.pandas_dtype", "pandas.core.dtypes.common.is_timedelta64_dtype", "numpy.isnan", "pandas.core.algorithms.rank", "pandas.core.missing.mask_missing", "pandas.core.missing.get_fill_func", "pandas.util._decorators.rewrite_axis_style_signature", "pandas.core.missing.clean_fill_method", "pandas.core.common.get_rename_function", "pandas.core.dtypes.common.is_bool", "pandas.core.dtypes.common.is_scalar", "pandas.io.formats.csvs.CSVFormatter", "pandas.io.formats.format.format_percentiles", "pandas.util._validators.validate_fillna_kwargs", "pandas.core.resample.asfreq", "pandas.core.indexes.api.ensure_index", "pandas.compat.numpy.function.validate_clip_with_axis", "pandas.core.computation.common._remove_spaces_column_name", "pandas.util._validators.validate_percentile", "pandas.core.indexes.period.Period", "numpy.any", "pandas.core.indexing.get_indexers_list", "pandas.io.clipboards.to_clipboard", "pandas.core.window.Expanding", "pandas.compat.set_function_name", "pandas.core.dtypes.common.is_float", "pandas.core.dtypes.common.is_datetime64_any_dtype", "pandas.core.tools.datetimes.to_datetime", "pandas.core.common.maybe_make_list", "pandas._config.config.get_option", "pandas.core.common.count_not_none", "numpy.abs", "pandas.core.ops._align_method_FRAME", "pandas.io.formats.excel.ExcelFormatter", "pandas.core.dtypes.common.is_object_dtype", "pandas.core.common.apply_if_callable", "numpy.prod", "pandas.core.common.index_labels_to_array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.24" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [ "0.13", "1.6", "0.14", "1.10", "0.15", "1.4", "1.3", "1.9", "0.19", "1.5", "0.18", "1.2", "1.7", "0.12", "1.0", "0.17", "0.16", "1.8" ], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "0.24", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] } ]
Shivanisen16/vtulabs
[ "2bc41d856612840cf035b570e6256ffc5bcbab5d" ]
[ "15CSL76_Machine_Learning/lab/8-em-kmeans.py" ]
[ "import copy\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom matplotlib import pyplot as plt\r\nfrom sklearn.mixture import GaussianMixture\r\nfrom sklearn.cluster import KMeans\r\n\r\n# Importing the dataset\r\ndata = pd.read_csv(\"ex.csv\")\r\nprint(\"Input Data and Shape:\")\r\nprint(data.head(3))\r\nprint(\"Shape:\", data.shape)\r\n\r\n# Getting the values and plotting it\r\nf1 = data['V1'].values\r\nf2 = data['V2'].values\r\nX = np.array(list(zip(f1, f2)))\r\nprint('Graph for whole dataset')\r\nplt.scatter(f1, f2, c='black', s=50)\r\nplt.show()\r\n\r\n##########################################\r\nkmeans = KMeans(2, random_state=0)\r\nlabels = kmeans.fit(X).predict(X)\r\ncentroids = kmeans.cluster_centers_\r\nprint(\"Labels KMeans:\", labels)\r\n\r\nprint('Graph using Kmeans Algorithm')\r\n# plot all points, color the labels\r\nplt.scatter(X[:, 0], X[:, 1], c=labels, s=50)\r\n# mark centroids\r\nplt.scatter(centroids[:, 0], centroids[:, 1], marker='*', s=200, c='black')\r\nplt.show()\r\n\r\n\r\n# gmm demo\r\ngmm = GaussianMixture(n_components=2)\r\nlabels = gmm.fit(X).predict(X)\r\nprint(\"\\nLabels EM:\", labels)\r\nprint('Graph using EM Algorithm')\r\nplt.scatter(X[:, 0], X[:, 1], c=labels, s=40)\r\nplt.show()\r\n" ]
[ [ "pandas.read_csv", "sklearn.cluster.KMeans", "matplotlib.pyplot.scatter", "sklearn.mixture.GaussianMixture", "matplotlib.pyplot.show" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
moha31x/SESAME
[ "0956cbf081d1a033855173e989da6e21f0a13215" ]
[ "sesame/train_model.py" ]
[ "'''\nThis is a script to train a model with a variety of estimators\n'''\nimport pickle\nimport pandas as pd\nfrom sklearn.neural_network import MLPRegressor\nfrom config import Config\n\n# Creating a path to save our model\nConfig.models_path.mkdir(parents=True, exist_ok=True)\n\n# Loading the training and testing features into a pandas DataFrame\nx_train = pd.read_csv(str(Config.features_path / 'train_features.csv'))\ny_train = pd.read_csv(str(Config.features_path / 'train_target.csv'))\n\n# Instantiating and fitting the algorithm\nmodel = MLPRegressor(max_iter=800, alpha=0.4371)\nmodel = model.fit(x_train, y_train.to_numpy().ravel())\n\n# Saving the model into a pickle file\npickle.dump(model, open('model.pickle', 'wb'))\n" ]
[ [ "sklearn.neural_network.MLPRegressor" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
darynarr/CV_UKMA
[ "2d0e5fe42c539b441e45c4281f7dc5d42939dd89", "2d0e5fe42c539b441e45c4281f7dc5d42939dd89" ]
[ "ComputerVision_HW/3B-L3/match_two_strips.py", "ComputerVision_HW/2A-L4/find_template_2D.py" ]
[ "import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n# We will use the function implemented in the last quiz\n# Find best match\ndef find_best_match(patch, strip):\n # TODO: Find patch in strip and return column index (x value) of topleft corner\n best_id = None\n min_diff = np.inf\n strip_n, patch_n = strip.shape[1], patch.shape[1]\n for i in range(strip_n-patch_n):\n temp = strip[:, i: i + patch_n]\n ssd = np.sum(np.power(temp - patch, 2))\n if ssd < min_diff:\n best_id, min_diff = i, ssd\n return best_id\n\n\ndef match_strips(strip_left, strip_right, b):\n # For each non-overlapping patch/block of width b in the left strip,\n # find the best matching position (along X-axis) in the right strip.\n # Return a vector of disparities (left X-position - right X-position).\n # Note: Only consider whole blocks that fit within image bounds.\n disparities = []\n\n for x_left in range(0, strip_left.shape[1]+1, b):\n patch_left = strip_left[:, x_left: x_left + b]\n x_right = find_best_match(patch_left, strip_right)\n disparities.append(x_left - x_right)\n\n return np.array([disparities])\n\n\n# Test code:\n\n# Load images\nleft = cv2.imread('images/flowers-left.png')\nright = cv2.imread('images/flowers-right.png')\ncv2.imshow('Left', left)\ncv2.imshow('Right', right)\n\n# Convert to grayscale, double, [0, 1] range for easier computation\nleft_gray = cv2.cvtColor(left, cv2.COLOR_BGR2GRAY) / 255.\nright_gray = cv2.cvtColor(right, cv2.COLOR_BGR2GRAY) / 255.\n\n# Define strip row (y) and square block size (b)\ny = 120\nb = 100\n\n# Extract strip from left image\nstrip_left = left_gray[y: y + b, :]\ncv2.imshow('Strip Left', strip_left)\n\n# Extract strip from right image\nstrip_right = right_gray[y: y + b, :]\ncv2.imshow('Strip Right', strip_right)\n\n# Now match these two strips to compute disparity values\ndisparity = match_strips(strip_left, strip_right, b)\nprint( disparity)\n\n# Finally we plot the disparity values. Note that there may be some differences\n# in the results shown in the quiz because we had to adapt the index values.\nplt.plot(range(disparity.shape[1]), disparity[0])\nplt.show()\nplt.close('all')\n", "import cv2\nimport numpy as np\nimport scipy.signal as sp\n\n\n# Find template 2D\ndef find_template_2D(template, img):\n # TODO: Find template in img and return [y x] location. Make sure this location is the top-left corner of the match.\n corr = sp.correlate2d(img, template)\n y, x = np.unravel_index(np.argmax(corr), corr.shape)\n y += -template.shape[0]+1\n x += -template.shape[1]+1\n return y, x\n\n\ntablet = cv2.imread('images/tablet.png', cv2.IMREAD_GRAYSCALE)\ncv2.imshow('Tablet', tablet)\n\nglyph = tablet[74:165, 149:184]\ncv2.imshow('Glyph', glyph)\n\ntablet_2 = 1. * tablet - np.mean(tablet)\nglyph_2 = 1. * glyph - np.mean(glyph)\n\ny, x = find_template_2D(glyph_2, tablet_2)\nprint(\"Y: {}, X: {}\".format(y, x))\n\ntablet = cv2.cvtColor(tablet, code=cv2.COLOR_GRAY2BGR)\ncv2.rectangle(tablet, (x, y), (x+glyph.shape[1], y+glyph.shape[0]),\n (0, 0, 255), thickness=2)\ncv2.imshow('Rectangle', tablet)\ncv2.waitKey(0)\n" ]
[ [ "numpy.array", "matplotlib.pyplot.show", "matplotlib.pyplot.close", "numpy.power" ], [ "scipy.signal.correlate2d", "numpy.argmax", "numpy.mean" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "1.7", "1.0", "0.10", "1.2", "0.14", "0.19", "1.5", "0.12", "0.17", "0.13", "1.6", "1.4", "1.9", "1.3", "1.10", "0.15", "0.18", "0.16", "1.8" ], "tensorflow": [] } ]
ryought/3d-dna
[ "caa187a272c2c3d5720727d846489d628092b680" ]
[ "scaffold/infer-distribution.py" ]
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport dask.dataframe as ddf\nimport pandas as pd\nimport time\nfrom sklearn.neighbors.kde import KernelDensity\nfrom scipy.optimize import curve_fit\nimport numpy as np\n\ndef infer_distribution_from_contig(contacts, K, K0):\n \"\"\"\n \"\"\"\n longest_contig_name = contacts.loc[contacts.P1.idxmax()].N1\n inter_contacts = contacts[\n (contacts.N1 == longest_contig_name)\n & (contacts.N2 == longest_contig_name)]\n inter = np.abs(inter_contacts.P1.values - inter_contacts.P2.values)\n\n kde = KernelDensity(kernel='gaussian', bandwidth=200).fit(inter.reshape(-1, 1))\n f = lambda x: kde.score_samples(x.reshape(-1, 1))\n\n # distant\n x1 = np.logspace(np.log10(K0), np.log10(K), 500)\n p = lambda x, a, b: a + b * np.log(x)\n param1, cov = curve_fit(p, x1, f(x1))\n\n # proximal\n # degree = 30\n # x0 = np.logspace(0, np.log10(K0), 500)\n # param0 = np.polyfit(x0, f(x0), degree)\n\n # P = (lambda x: np.where(\n # x < K0,\n # np.poly1d(param0)(x),\n # np.where(\n # x < K,\n # param1[0] + param1[1] * np.log(x),\n # param1[0] + param1[1] * np.log(K))\n # ))\n return param1[0], param1[1]\n\ndef main():\n import sys\n if len(sys.argv) != 4:\n print('not enough arguments')\n print('usage: python infer-distribution.py foo.mnd K K0')\n return -1\n\n mnd_filename = sys.argv[1]\n K = int(sys.argv[2])\n K0 = int(sys.argv[3])\n\n # print('parsing mnd by dask.dataframe.read_csv', time.time())\n df = ddf.read_csv(\n mnd_filename,\n sep=' ',\n header=None,\n names=['N1', 'P1', 'N2', 'P2'],\n usecols=[1, 2, 5, 6],\n engine='c',\n ).compute()\n # reorder index\n # print('reset indexing', time.time())\n df = df.reset_index(drop=True)\n\n # print('fitting')\n p = infer_distribution_from_contig(df, K=K, K0=K0)\n print(p[0])\n print(p[1])\n\nmain()\n" ]
[ [ "numpy.log", "numpy.log10", "numpy.abs", "sklearn.neighbors.kde.KernelDensity" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
abhikbhattacharjee/Motifizer
[ "ee816690f71325e3e17a554d43a7711f08a8c3a9" ]
[ "Peak_calling_length_python_code.py" ]
[ "import pandas as pd\nimport sys\n\npeak_calling=pd.read_excel(str(sys.argv[1]), str(sys.argv[4]))\npeak_calling['Length'] = peak_calling['End'] - peak_calling['Start'] \n\npeak_calling1=pd.read_excel(str(sys.argv[1]), str(sys.argv[3]))\npeak_calling1['Length'] = peak_calling1['End'] - peak_calling1['Start'] \n\npeak_calling2=pd.read_excel(str(sys.argv[1]), str(sys.argv[2]))\npeak_calling2['Length'] = peak_calling2['End'] - peak_calling2['Start'] \n\nwith pd.ExcelWriter('Excel/Peak_calling_length.xlsx') as writer:\n peak_calling.to_excel(writer, sheet_name='not_diff')\n peak_calling1.to_excel(writer, sheet_name='down_toptags')\n peak_calling2.to_excel(writer, sheet_name='up_toptags')\n\n" ]
[ [ "pandas.ExcelWriter" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
kilinmao/sarl_star
[ "3b9b2521436ef7f364a250da71a01e915d840296", "3b9b2521436ef7f364a250da71a01e915d840296" ]
[ "navigation/arena_local_planner/model_based/crowdnav_ros/scripts/crowd_nav/utils/explorer.py", "navigation/arena_local_planner/learning_based/arena_ros/scripts/gru_dynamic.py" ]
[ "import logging\nimport copy\nimport torch\nfrom crowd_sim.envs.utils.info import *\n\n\nclass Explorer(object):\n def __init__(self, env, robot, device, memory=None, gamma=None, target_policy=None):\n self.env = env\n self.robot = robot\n self.device = device\n self.memory = memory\n self.gamma = gamma\n self.target_policy = target_policy\n self.target_model = None\n\n def update_target_model(self, target_model):\n self.target_model = copy.deepcopy(target_model)\n\n # @profile\n def run_k_episodes(self, k, phase, update_memory=False, imitation_learning=False, episode=None,\n print_failure=False):\n self.robot.policy.set_phase(phase)\n success_times = []\n collision_times = []\n timeout_times = []\n success = 0\n collision = 0\n timeout = 0\n too_close = 0\n min_dist = []\n cumulative_rewards = []\n collision_cases = []\n timeout_cases = []\n for i in range(k):\n ob = self.env.reset(phase)\n done = False\n states = []\n actions = []\n rewards = []\n while not done:\n action = self.robot.act(ob)\n ob, reward, done, info = self.env.step(action)\n states.append(self.robot.policy.last_state)\n actions.append(action)\n rewards.append(reward)\n\n if isinstance(info, Danger):\n too_close += 1\n min_dist.append(info.min_dist)\n\n if isinstance(info, ReachGoal):\n success += 1\n success_times.append(self.env.global_time)\n elif isinstance(info, Collision):\n collision += 1\n collision_cases.append(i)\n collision_times.append(self.env.global_time)\n elif isinstance(info, Timeout):\n timeout += 1\n timeout_cases.append(i)\n timeout_times.append(self.env.time_limit)\n else:\n raise ValueError('Invalid end signal from environment')\n\n if update_memory:\n if isinstance(info, ReachGoal) or isinstance(info, Collision):\n # only add positive(success) or negative(collision) experience in experience set\n self.update_memory(states, actions, rewards, imitation_learning)\n\n cumulative_rewards.append(sum([pow(self.gamma, t * self.robot.time_step * self.robot.v_pref)\n * reward for t, reward in enumerate(rewards)]))\n\n success_rate = success / k\n collision_rate = collision / k\n assert success + collision + timeout == k\n avg_nav_time = sum(success_times) / len(success_times) if success_times else self.env.time_limit\n\n extra_info = '' if episode is None else 'in episode {} '.format(episode)\n logging.info('{:<5} {}has success rate: {:.2f}, collision rate: {:.2f}, nav time: {:.2f}, total reward: {:.4f}'.\n format(phase.upper(), extra_info, success_rate, collision_rate, avg_nav_time,\n average(cumulative_rewards)))\n if phase in ['val', 'test']:\n total_time = sum(success_times + collision_times + timeout_times) * self.robot.time_step\n logging.info('Frequency of being in danger: %.2f and average min separate distance in danger: %.2f',\n too_close / total_time, average(min_dist))\n\n if print_failure:\n logging.info('Collision cases: ' + ' '.join([str(x) for x in collision_cases]))\n logging.info('Timeout cases: ' + ' '.join([str(x) for x in timeout_cases]))\n\n def update_memory(self, states, actions, rewards, imitation_learning=False):\n if self.memory is None or self.gamma is None:\n raise ValueError('Memory or gamma value is not set!')\n\n for i, state in enumerate(states):\n reward = rewards[i]\n\n # VALUE UPDATE\n if imitation_learning:\n # define the value of states in IL as cumulative discounted rewards, which is the same in RL\n state = self.target_policy.transform(state)\n # value = pow(self.gamma, (len(states) - 1 - i) * self.robot.time_step * self.robot.v_pref)\n value = sum([pow(self.gamma, max(t - i, 0) * self.robot.time_step * self.robot.v_pref) * reward\n * (1 if t >= i else 0) for t, reward in enumerate(rewards)])\n else:\n if i == len(states) - 1:\n # terminal state\n value = reward\n else:\n next_state = states[i + 1]\n gamma_bar = pow(self.gamma, self.robot.time_step * self.robot.v_pref)\n value = reward + gamma_bar * self.target_model(next_state.unsqueeze(0)).data.item()\n value = torch.Tensor([value]).to(self.device)\n\n # # transform state of different human_num into fixed-size tensor\n # if len(state.size()) == 1:\n # human_num = 1\n # feature_size = state.size()[0]\n # else:\n # human_num, feature_size = state.size()\n # if human_num != 5:\n # padding = torch.zeros((5 - human_num, feature_size))\n # state = torch.cat([state, padding])\n self.memory.push((state, value))\n\n\ndef average(input_list):\n if input_list:\n return sum(input_list) / len(input_list)\n else:\n return 0\n", "import torch\nimport torch.nn as nn\nfrom torch.nn.utils.rnn import PackedSequence\n\n###parameters of gru##########\nembedding_size_first = 128\n#embedding_size_second = 128 #number of nodes in embedding layer of the fc network\nHIDDEN_SHAPE_SECOND = 96\nhidden_dim = 96 #number of nodes in GRU \nlayer_dim = 2 #number of gru layers 1 3 5 7\n##############################\n\nclass GRUModel(nn.Module):\n def __init__(self, input_dim,n_actions, bias=True):\n super(GRUModel, self).__init__()\n # Hidden dimensions\n self.hidden_dim = hidden_dim\n # Number of hidden layers\n self.layer_dim = layer_dim\n self.embedding = nn.Sequential(\n nn.Linear(input_dim, embedding_size_first),\n nn.LeakyReLU(0.01), \n nn.Linear(embedding_size_first, HIDDEN_SHAPE_SECOND))\n #self.embedding = nn.Linear(input_dim,embedding_size)\t\n self.gru = nn.GRU(HIDDEN_SHAPE_SECOND, hidden_dim, layer_dim, dropout=0.1) #GRUCell(input_dim, hidden_dim, layer_dim) , dropout=0.1\n self.fc = nn.Sequential(\n nn.LeakyReLU(0.01),\n nn.Linear(hidden_dim, n_actions)) #nn.Linear(hidden_dim, HIDDEN_SHAPE), nn.ReLU(),\n\t \n def forward(self, x:PackedSequence, h):\n embedding=self.embedding(x.data)\n embedding = PackedSequence(embedding, x.batch_sizes, x.sorted_indices, x.unsorted_indices)\n out, h = self.gru(embedding,h) \n out = self.fc(h[-1,:,:])\t\n return out,h.data\n\n def init_hidden(self, batch_size):\n weight = next(self.parameters()).data\n hidden = weight.new(self.layer_dim, batch_size, self.hidden_dim).zero_().cuda()\n return hidden\n\n\n" ]
[ [ "torch.Tensor" ], [ "torch.nn.Linear", "torch.nn.utils.rnn.PackedSequence", "torch.nn.GRU", "torch.nn.LeakyReLU" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
shreyaspotnis/rampage
[ "e2565aef7ee16ee06523de975e8aa41aca14e3b2" ]
[ "rampage/daq/gpib.py" ]
[ "import visa\nimport numpy as np\nimport logging\nfrom datetime import datetime\n\nresource_manager = visa.ResourceManager()\n\n\nclass Aglient33250A(object):\n\n def __init__(self):\n self.instr = self.open_instrument()\n\n def open_instrument(self):\n resource_list = resource_manager.list_resources()\n gpib_address_list = filter(lambda x: x[:4] == 'GPIB', resource_list)\n\n for addr in gpib_address_list:\n instr = resource_manager.open_resource(addr)\n idn = instr.query('*IDN?')\n if 'Agilent Technologies,33250A' in idn:\n return instr\n else:\n raise GPIBError('Aglient33250A function generator not in GPIB device list')\n # device not round raise exception\n\n def set_output(self, state):\n \"\"\"Sets whether the function generator is outputting a voltage.\"\"\"\n if state:\n self.instr.write('OUTP ON')\n else:\n self.instr.write('OUTP OFF')\n\n def set_fm_ext(self, freq, amplitude, peak_freq_dev=None,\n output_state=True):\n \"\"\"Sets the func generator to frequency modulation with external modulation.\n freq is the carrier frequency in Hz.\"\"\"\n\n if peak_freq_dev is None:\n peak_freq_dev = freq\n commands = ['FUNC SIN', # set to output sine functions\n 'FM:STAT ON',\n 'FREQ {0}'.format(freq),\n 'FM:SOUR EXT',\n # 'FM:FREQ {0}'.format(freq),\n 'FM:DEV {0}'.format(peak_freq_dev),\n 'VOLT {0}'.format(amplitude),\n 'VOLT:OFFS 0'] # set to frequency modulation\n if output_state is True:\n commands.append('OUTP ON')\n else:\n commands.append('OUTP OFF')\n command_string = '\\n'.join(commands)\n print_string = '\\n\\t' + command_string.replace('\\n', '\\n\\t')\n logging.info(print_string)\n self.instr.write(command_string)\n # self.read_all_errors()\n\n def set_burst(self, freq, amplitude, period, output_state=True):\n \"\"\"Sets the func generator to burst mode with external trigerring.\"\"\"\n\n ncyc = int(period*freq)\n commands = ['FUNC SIN',\n 'BURS:STAT ON',\n 'BURS:MODE TRIG', # external trigger\n 'TRIG:SOUR EXT',\n 'TRIG:SLOP POS',\n 'FREQ {0}'.format(freq),\n 'VOLT {0}'.format(amplitude),\n 'VOLT:OFFS 0',\n 'BURS:NCYC {0}'.format(ncyc)]\n if output_state is True:\n commands.append('OUTP ON')\n else:\n commands.append('OUTP OFF')\n\n command_string = '\\n'.join(commands)\n print_string = '\\n\\t' + command_string.replace('\\n', '\\n\\t')\n logging.info(print_string)\n self.instr.write(command_string)\n\n # self.read_all_errors()\n\n def set_continuous(self, freq, amplitude, offset, output_state=True):\n \"\"\"Programs the function generator to output a continuous sine wave.\"\"\"\n commands = ['FUNC SIN',\n 'BURS:STAT OFF',\n 'SWE:STAT OFF',\n 'FM:STAT OFF',\n 'FREQ {0}'.format(freq),\n 'VOLT {0}'.format(amplitude),\n 'VOLT:OFFS {0}'.format(offset),\n ]\n if output_state is True:\n commands.append('OUTP ON')\n else:\n commands.append('OUTP OFF')\n\n command_string = '\\n'.join(commands)\n print_string = '\\n\\t' + command_string.replace('\\n', '\\n\\t')\n logging.info(print_string)\n self.instr.write(command_string)\n\n # self.read_all_errors()\n\n def set_freq_sweep(self, start_freq, stop_freq, sweep_time, amplitude,\n output_state=True):\n commands = ['FUNC SIN',\n 'TRIG:SOUR EXT',\n 'TRIG:SLOP POS',\n 'SWE:STAT ON',\n 'FREQ:STAR {0}'.format(start_freq),\n 'FREQ:STOP {0}'.format(stop_freq),\n 'SWE:TIME {0}'.format(sweep_time),\n 'VOLT {0}'.format(amplitude),\n 'VOLT:OFFS 0',\n 'SWE:STAT ON']\n if output_state is True:\n commands.append('OUTP ON')\n else:\n commands.append('OUTP OFF')\n\n command_string = '\\n'.join(commands)\n print_string = '\\n\\t' + command_string.replace('\\n', '\\n\\t')\n logging.info(print_string)\n self.instr.write(command_string)\n\n def set_arbitrary(self, freq, low_volt, high_volt, output_state=True):\n \"\"\"Programs the function generator to output the arbitrary waveform.\"\"\"\n commands = ['FUNC USER',\n 'BURS:STAT OFF',\n 'SWE:STAT OFF',\n 'FM:STAT OFF',\n 'FREQ {0}'.format(freq),\n 'VOLT:HIGH {0}'.format(high_volt),\n 'VOLT:LOW {0}'.format(low_volt),\n ]\n if output_state is True:\n commands.append('OUTP ON')\n else:\n commands.append('OUTP OFF')\n\n command_string = '\\n'.join(commands)\n print_string = '\\n\\t' + command_string.replace('\\n', '\\n\\t')\n logging.info(print_string)\n self.instr.write(command_string)\n\n def read_all_errors(self):\n done = False\n while not done:\n err = self.instr.query('SYST:ERR?')\n print(err)\n if err[:2] == '+0':\n done = True\n\nclass TektronixTDS1002(object):\n\n def __init__(self):\n self.instr = self.open_instrument()\n\n def open_instrument(self):\n resource_list = resource_manager.list_resources()\n gpib_address_list = filter(lambda x: x[:4] == 'GPIB', resource_list)\n\n for addr in gpib_address_list:\n instr = resource_manager.open_resource(addr)\n idn = instr.query('*IDN?')\n if 'TEKTRONIX,TDS 1002' in idn:\n return instr\n else:\n raise GPIBError('TektronicsTDS1002 oscilloscope not in GPIB device list')\n # device not round raise exception\n\n def get_data(self, channel=1):\n hor_pos = float(self.instr.query('HOR:MAI:POS?'))\n hor_scale = float(self.instr.query('HOR:MAI:SCA?'))\n ch1_pos = float(self.instr.query('CH{0}:POS?'.format(channel)))\n ch1_sca = float(self.instr.query('CH{0}:SCA?'.format(channel)))\n commands = ['DATA:WIDTH 1',\n 'DATA:STAR 1',\n 'DATA:STOP 2500',\n 'DATA:SOU CH{0}'.format(channel),\n 'CURV?']\n command_string = '\\r\\n'.join(commands)\n self.instr.write(command_string)\n # the first 6 bytes are #42500 and the last byte is \\n\n # ignore those\n data = self.instr.read_raw()[6:-1]\n data = np.fromstring(data, dtype=np.int8)\n data_scaled = (np.array(data, dtype='float')*(10.0/2**8) - ch1_pos)*ch1_sca\n time_array = np.arange(len(data_scaled), dtype='float')*10.0*hor_scale/len(data_scaled)\n return time_array, data_scaled\n\n def get_save_data(self, file_path, channel=1):\n hor_pos = float(self.instr.query('HOR:MAI:POS?'))\n hor_scale = float(self.instr.query('HOR:MAI:SCA?'))\n ch1_pos = float(self.instr.query('CH{0}:POS?'.format(channel)))\n ch1_sca = float(self.instr.query('CH{0}:SCA?'.format(channel)))\n commands = ['DATA:WIDTH 1',\n 'DATA:STAR 1',\n 'DATA:STOP 2500',\n 'DATA:SOU CH{0}'.format(channel),\n 'CURV?']\n command_string = '\\r\\n'.join(commands)\n self.instr.write(command_string)\n # the first 6 bytes are #42500 and the last byte is \\n\n # ignore those\n data = self.instr.read_raw()[6:-1]\n data = np.fromstring(data, dtype=np.int8)\n data_scaled = (np.array(data, dtype='float')*(10.0/2**8) - ch1_pos)*ch1_sca\n time_array = np.arange(len(data_scaled), dtype='float')*10.0*hor_scale/len(data_scaled)\n np.savetxt(file_path + '\\\\' + datetime.now().strftime('%Y_%m_%d_%H_%M_%S') + '.txt', (time_array, data_scaled), fmt='%1.4e')\n #return time_array, data_scaled\n\nclass TektronixTDS2012C(TektronixTDS1002):\n\n def __init__(self):\n self.instr = self.open_instrument()\n super(TektronixTDS2012C, self).__init__()\n\n def open_instrument(self):\n resource_list = resource_manager.list_resources()\n gpib_address_list = filter(lambda x: x[:3] == 'USB', resource_list)\n\n for addr in gpib_address_list:\n instr = resource_manager.open_resource(addr)\n idn = instr.query('*IDN?')\n if 'TEKTRONIX,TDS 2012C' in idn:\n return instr\n else:\n raise GPIBError('TektronixTDS2012C oscilloscope not in USB device list')\n # device not round raise exception\n\nclass NewportESP300(object):\n\n def __init__(self):\n self.instr = self.open_instrument()\n\n def open_instrument(self):\n resource_list = resource_manager.list_resources()\n gpib_address_list = filter(lambda x: x[:4] == 'GPIB', resource_list)\n\n for addr in gpib_address_list:\n instr = resource_manager.open_resource(addr)\n idn = instr.query('*IDN?')\n if 'ESP300 Version' in idn:\n return instr\n else:\n raise GPIBError('ESP300 Motion Controller not in GPIB device list')\n # device not round raise exception\n\n def read_position(self, num_axes=2):\n for i in range(num_axes-1):\n pos = self.instr.query(str(i+1)+'TP?')\n print('Pos' + str(i+1) + ' ' + pos[:8])\n\n def move_absposition(self, abs_pos, axis):\n self.instr.write(str(int(axis))+'PA'+str(np.around(abs_pos, decimals=3)))\n print('Set Axis ' + str(axis) + ' to ' + str(np.around(abs_pos, decimals=3)))\n\n def read_all_errors(self):\n done = False\n while not done:\n err = self.instr.query('TB?')\n print(err)\n if 'NO ERROR DETECTED' in err:\n done = True\n\nclass AgilentN900A(object):\n\n def __init__(self):\n self.instr = self.open_instrument()\n\n def open_instrument(self):\n\n IP = '192.168.0.109'\n instr = resource_manager.get_instrument('TCPIP::' + IP + '::INSTR')\n return instr\n\n def get_n_save_marker_pos(self, file_path, channel=1):\n self.instr.write(':CALC:MARK1:X?')\n freq = np.float(self.instr.read())\n self.instr.write(':CALC:MARK1:Y?')\n amp = np.float(self.instr.read())\n self.instr.write(':AVER:STAT OFF')\n arr_write = np.array([freq, amp])\n f_handle = open(file_path + '\\\\' + datetime.now().strftime('%Y_%m_%d_%H_%M_%S') + '.txt', 'ab')\n np.savetxt(f_handle, arr_write.reshape(1, arr_write.shape[0]))\n f_handle.close()\n\n def trigger_marker_avg(self,num_avg=100,freq=6.83468,span=25,ref_lev=15):\n commands = [':FREQ:CENT {0}'.format(freq) + ' GHz',\n ':FREQ:SPAN {0}'.format(span) + ' MHz',\n ':DISP:WIND:TRAC:Y:RLEV {0}'.format(ref_lev) + ' dBm',\n ':CALC:MARK:MODE POS',\n ':CALC:MARK:CPS ON',\n ':TRIG:SOUR EXT1',\n ':TRIG:EXT1:LEV 1.0V',\n ':AVER:STAT ON',\n ':AVER:COUNT {0}'.format(num_avg)\n ]\n command_string = '\\n'.join(commands)\n print_string = '\\n\\t' + command_string.replace('\\n', '\\n\\t')\n logging.info(print_string)\n self.instr.write(command_string)\n\nclass SRSSG384(object):\n\n def __init__(self):\n self.instr = self.open_instrument()\n\n def open_instrument(self):\n resource_list = resource_manager.list_resources()\n gpib_address_list = filter(lambda x: x[:4] == 'GPIB', resource_list)\n\n for addr in gpib_address_list:\n instr = resource_manager.open_resource(addr)\n idn = instr.query('*IDN?')\n if 'Stanford Research Systems,SG384' in idn:\n return instr\n else:\n raise GPIBError('SRS SG384 function generator not in GPIB device list')\n # device not found raise exception\n\n def read_all_errors(self):\n done = False\n while not done:\n err = self.instr.query('LERR?')\n print(err)\n if err[:1] == '0':\n done = True\n\n def set_continuous(self, freq, amplitude, offset, output_state=True):\n \"\"\"Programs the Stanford MW function generator to output a continuous sine wave.\n External 'triggering' is accomplished using the MW switch.\"\"\"\n commands = ['MODL 0', #disable any modulation\n 'FREQ {0}'.format(freq)\n ]\n\n if freq > 4.05e9:\n commands.append('AMPH {0}'.format(amplitude)) #set rear RF doubler amplitude\n if offset > 0.0:\n print('HIGH FREQUENCY OUTPUT IS AC ONLY')\n if output_state is True:\n commands.append('ENBH 1') #enable output\n else:\n commands.append('ENBH 0')\n elif freq < 62.5e6:\n commands.extend(['AMPL {0}'.format(amplitude), 'OFSL {0}'.format(offset)]) #set front BNC amplitude\n if output_state is True:\n commands.append('ENBL 1') #enable output\n else:\n commands.append('ENBL 0')\n\n command_string = '\\n'.join(commands)\n print_string = '\\n\\t' + command_string.replace('\\n', '\\n\\t')\n logging.info(print_string)\n self.instr.write(command_string)\n\n # print(print_string)\n # self.read_all_errors()\n\n def set_continuous_Vpp(self, freq, amplitude, offset, output_state=True):\n \"\"\"Programs the Stanford MW function generator to output a continuous sine wave.\n External 'triggering' is accomplished using the MW switch.\"\"\"\n commands = ['MODL 0', #disable any modulation\n 'FREQ {0}'.format(freq)\n ]\n\n if freq > 4.05e9:\n commands.append('AMPH {0} VPP'.format(amplitude)) #set rear RF doubler amplitude\n if offset > 0.0:\n print('HIGH FREQUENCY OUTPUT IS AC ONLY')\n if output_state is True:\n commands.append('ENBH 1') #enable output\n else:\n commands.append('ENBH 0')\n elif freq < 62.5e6:\n commands.extend(['AMPL {0} VPP'.format(amplitude), 'OFSL {0}'.format(offset)]) #set front BNC amplitude\n if output_state is True:\n commands.append('ENBL 1') #enable output\n else:\n commands.append('ENBL 0')\n\n command_string = '\\n'.join(commands)\n print_string = '\\n\\t' + command_string.replace('\\n', '\\n\\t')\n logging.info(print_string)\n self.instr.write(command_string)\n\n def set_fm_ext(self, freq, amplitude, offset=0.0, peak_fm_deviation=None, output_state=True):\n \"\"\"Sets the Stanford MW function generator to freq modulation with external modulation.\n freq is the carrier frequency in Hz.\"\"\"\n if peak_fm_deviation is None:\n peak_fm_deviation = freq\n commands = ['TYPE 1', #set to FM\n 'MFNC 5', #external modulation\n 'FREQ {0}'.format(freq),\n 'FDEV {0}'.format(peak_fm_deviation),\n 'MODL 1' #enable modulation\n ]\n if freq > 4.05e9:\n commands.append('AMPH {0}'.format(amplitude)) #set rear RF doubler amplitude\n if offset > 0.0:\n print('HIGH FREQUENCY OUTPUT IS AC ONLY')\n if output_state is True:\n commands.append('ENBH 1') #enable output\n else:\n commands.append('ENBH 0')\n elif freq < 62.5e6:\n commands.extend(['AMPL {0}'.format(amplitude), 'OFSL {0}'.format(offset)]) #set front BNC amplitude\n if output_state is True:\n commands.append('ENBL 1') #enable output\n else:\n commands.append('ENBL 0')\n\n command_string = '\\n'.join(commands)\n print_string = '\\n\\t' + command_string.replace('\\n', '\\n\\t')\n logging.info(print_string)\n self.instr.write(command_string)\n\n #print(print_string)\n #self.read_all_errors()\n\n def set_freqsweep_ext(self, amplitude, sweep_low_end, sweep_high_end, offset=0.0, output_state=True):\n \"\"\"Sets the Stanford MW function generator to freq modulation with external modulation.\n freq is the carrier frequency in Hz.\"\"\"\n\n sweep_deviation = round(abs(sweep_low_end - sweep_high_end)/2.0,6)\n freq = sweep_low_end + sweep_deviation\n commands = ['TYPE 3', #set to sweep\n 'SFNC 5', #external modulation\n 'FREQ {0}'.format(freq),\n 'SDEV {0}'.format(sweep_deviation),\n 'MODL 1' #enable modulation\n ]\n if freq > 4.05e9:\n commands.append('AMPH {0}'.format(amplitude)) #set rear RF doubler amplitude\n if offset > 0.0:\n print('HIGH FREQUENCY OUTPUT IS AC ONLY')\n if output_state is True:\n commands.append('ENBH 1') #enable output\n else:\n commands.append('ENBH 0')\n elif freq < 62.5e6:\n commands.extend(['AMPL {0}'.format(amplitude), 'OFSL {0}'.format(offset)]) #set front BNC amplitude\n if output_state is True:\n commands.append('ENBL 1') #enable output\n else:\n commands.append('ENBL 0')\n\n command_string = '\\n'.join(commands)\n print_string = '\\n\\t' + command_string.replace('\\n', '\\n\\t')\n logging.info(print_string)\n self.instr.write(command_string)\n\n #print(print_string)\n #self.read_all_errors()\n\n def set_output(self, state):\n \"\"\"Sets whether the function generator is outputting a voltage.\"\"\"\n freq = float(self.instr.query('FREQ?'))\n if freq > 4.05e9:\n if state:\n self.instr.write('ENBH 1') #enable output\n else:\n self.instr.write('ENBH 0')\n elif freq < 62.5e6:\n if state:\n self.instr.write('ENBL 1') #enable output\n else:\n self.instr.write('ENBL 0')\n\n def trigger_ListMode(self):\n \"\"\"Iterates the function generator to the next state in ListMode\n NOTE: ListMode does not enable outputs, but only writes the function\n generator state. Output must be enabled separately\"\"\"\n self.instr.write('*TRG')\n\n def disable_all(self, disable):\n \"\"\"Disables all modulation and outputs of the Standford MW func. generator\"\"\"\n commands = ['ENBH 0', #disable high freq. rear output\n 'ENBL 0', #disable low freq. front bnc\n 'MODL 0' #disable modulation\n ]\n command_string = '\\n'.join(commands)\n print_string = '\\n\\t' + command_string.replace('\\n', '\\n\\t')\n logging.info(print_string)\n if disable:\n self.instr.write(command_string)\n\n # self.read_all_errors()\n\n\n # def set_MWinstr_freq_sweep(self, mod_type, freq, amplitude, mod_rate, mod_deviation, list_size=2, list_enable=True):\n # \"\"\"Sets the Stanford MW device to an instrument to be triggered later.\"\"\"\n # #create list of instrument states\n # self.instr.query('LSTC? {0}'.format(list_size))\n\n # for j in range(list_size):\n\n\n # #enable to list for triggering\n # cur_enable_state = self.instr.query('LSTE?')\n # if cur_enable_state == False:\n # self.instr.write('LSTE 1')\n\nclass RigolDG1022Z(object):\n\n def __init__(self):\n self.instr = self.open_instrument()\n\n def open_instrument(self):\n resource_list = resource_manager.list_resources()\n gpib_address_list = filter(lambda x: x[:3] == 'USB', resource_list)\n\n for addr in gpib_address_list:\n instr = resource_manager.open_resource(addr)\n idn = instr.query('*IDN?')\n if 'Rigol Technologies,DG1022Z,DG1ZA184750979' in idn:\n return instr\n else:\n raise GPIBError('Rigol DG1022Z function generator not in USB device list')\n # device not round raise exception\n\n def set_output(self, state, channel=2):\n \"\"\"Sets whether the function generator is outputting a voltage.\"\"\"\n if state:\n self.instr.write(':OUTP{0} ON'.format(channel))\n else:\n self.instr.write(':OUTP{0} OFF'.format(channel))\n\n def set_continuous(self, freq, amplitude, offset, phase, channel=2):\n \"\"\"Programs the function generator to output a continuous sine wave.\"\"\"\n commands = [':SOUR{0}:APPL:SIN '.format(channel),\n '{0},'.format(freq),\n '{0},'.format(amplitude),\n '{0},'.format(offset),\n '{0}'.format(phase),\n ]\n\n command_string = ''.join(commands)\n logging.info(command_string)\n self.instr.write(command_string)\n\n def read_all_errors(self):\n done = False\n while not done:\n err = self.instr.query('SYST:ERR?')\n print(err)\n if err[:2] == '+0':\n done = True\n\n\nclass GPIBError(Exception):\n def __init__(self, value):\n self.value = value\n\n def __str__(self):\n return repr(self.value)\n\n#globals\nagilent_33250a = Aglient33250A()\ntektronixTDS1002 = TektronixTDS1002()\n# agilentN900A = AgilentN900A()\n#tektronixTDS2012C = TektronixTDS2012C()\nstanfordSG384 = SRSSG384()\n# newportesp300 = NewportESP300()\nrigolDG1022Z = RigolDG1022Z()" ]
[ [ "numpy.around", "numpy.array", "numpy.fromstring" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
heydude1337/pyshield
[ "8f103ccc160e6208c8a6754264168416f62373cb", "8f103ccc160e6208c8a6754264168416f62373cb" ]
[ "pyshield/io.py", "pyshield/calculations/dose_rates.py" ]
[ "\"\"\" Functions to read resource files (.yml, .xls/.xlsx and images) \"\"\"\n\n# -*- coding: utf-8 -*-\n\n\nfrom os import path\nimport pandas as pd\nimport matplotlib.image as mpimg\nimport numpy as np\nimport yaml\n\n\n\nimport pyshield as ps\n\n\ndef load_item(item):\n \"\"\" Load yaml, image or excel or return value as is. \"\"\"\n if isinstance(item, str):\n if is_yaml(item):\n try:\n item = read_yaml(item)\n except FileNotFoundError:\n item = {}\n if is_img(item):\n item = read_img(item)\n if is_excel(item):\n item = read_excel(item)\n \n if isinstance(item, dict):\n return dict(zip(item.keys(), map(load_item, item.values())))\n else:\n return item\n \ndef _file_ext(file):\n return path.splitext(file)[1].lower()\n\ndef is_yaml(file):\n YAML = ('.yml','.yaml')\n return isinstance(file, str) and _file_ext(file) in YAML\n\ndef is_img(file):\n IMG = ('.png', '.jpeg', '.jpg', '.bmp')\n return isinstance(file, str) and _file_ext(file) in IMG\n\ndef is_excel(file):\n XLS = ('.csv', '.xls', '.xlsx')\n return isinstance(file, str) and _file_ext(file) in XLS\n\ndef read_excel(file):\n return pd.read_excel(file, sheet_name=None)\n\ndef read_img(file):\n return np.flipud(mpimg.imread(file))\n\ndef read_yaml(file):\n \"\"\" \n Read yaml file and include files that are defined with the INCLUDE tag\n \"\"\"\n if not is_yaml(file):\n raise IOError('File {0} is not a yaml file'.format(file))\n\n folder = path.dirname(path.abspath(file))\n\n stream = open(file, 'r')\n yaml_dict = yaml.load(stream)\n\n if yaml_dict is None: yaml_dict = {}\n\n # append include files to dict\n files = yaml_dict.pop('INCLUDE', [])\n\n # read all included files and add items to dict\n for file in files:\n\n # take care of relative path\n if not(path.isabs(file)):\n file = path.join(folder, file)\n\n append_dict = read_yaml(file) # recursive call\n\n # check if key already existed warn if key will be overwritten\n for key in append_dict.keys():\n if key in yaml_dict.keys():\n ps.logger.warning('Duplicate data found in file' + \\\n\t\t\t\t '{0} for key {1}'.format(file, key))\n\n # append data (append_dict keys overwrite yaml_dict keys if duplicates)\n yaml_dict = {**yaml_dict, **append_dict}\n\n return yaml_dict\n\ndef write_yaml(file_name, dict_obj):\n stream = open(file_name, 'w')\n yaml.dump(dict_obj, stream=stream, default_flow_style=False)\n\n\n\n\n\n", "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Oct 10 11:35:41 2016\n\n@author: Marcel\n\"\"\"\nimport numpy as np\n\n\ndef ratio_H10_air_kerma(energy_keV):\n # source http://www.nucleonica.net/wiki/index.php?title=Help%3ADose_Rate_CONSTants%2B%2B#Air_kerma_rate_CONSTant.2C_.CE.93Kair\n E0 = 10\n xi = np.log(energy_keV / E0)\n\n r = xi / (1.465 * xi**2 - 4.414 * xi + 4.789) \\\n + 0.7006 * np.arctan(0.6519 * xi)\n return r\n\n\n\n\ndef H10(energy_keV, abundance = 1, add = True):\n \"\"\"\n Calculates the h10 in uSv/h per MBq/m^2 for given photon energy or\n multiple energies.\n Args:\n energy_keV: photon energy(ies)\n abundance: abundance for each photon energy\n add: sum dose rates for all energies (default = True)\n Returns:\n dose rate in uSv/h per MBq/m^2\n \"\"\"\n # convert tuple and list to numpy\n energy_keV = np.array(energy_keV)\n abundance = np.array(abundance)\n\n #ratio = np.interp(energy_keV, energies_keV, Hp10_ka)\n ratio = ratio_H10_air_kerma(energy_keV)\n\n h10 = ratio * kerma_air_rate(energy_keV, abundance, add = False)\n\n if add:\n h10 = np.sum(h10)\n return h10\n\ndef kerma_air_rate(energy_keV, abundance=1, add = True):\n \"\"\"\n Calculates the air kerma in uGy/h per MBq/m^2 for given photon energy or\n multiple energies.\n Args:\n energy_keV: photon energy(ies)\n abundance: abundance for each photon energy\n add: sum dose rates for all energies (default = True)\n Returns:\n kerma in uGy/h per MBq/m^2\n \"\"\"\n # air kerma : dKair/dt = A/(4*pi*l^2) * uk/p * E\n energy_keV = np.array(energy_keV)\n abundance = np.array(abundance)\n\n # kerma rate at 1m for 1 Bq (A=1, l=1)\n Joule_per_eV = 1.60217662e-19\n\n energy_J = Joule_per_eV * energy_keV * 1000\n\n energy_absorption_coeff = linear_energy_absorption_coeff_air(energy_keV)\n\n # s^-1 --> h^-1 Gy--> uGy Bq --> MBq\n energy_absorption_coeff *= 3600 * 1e12\n\n # kerma in uGy/h per MBq/m^2\n kerma = abundance * energy_absorption_coeff * energy_J / (4 * np.pi)\n\n if add:\n kerma = np.sum(kerma)\n return kerma\n\n\n\ndef linear_energy_absorption_coeff_air(energy_keV):\n \"\"\"\n Calculates the linear energy transfer coefficients by interpolation.\n Source data is obtained from the NIST XCOM database.\n\n Args:\n energy_keV: photon energy(ies) in keV\n Returns:\n linear energy tranfer rate(s)\n \"\"\"\n\n energy_keV = np.array(energy_keV)\n # source data\n Energy_MeV = [ 1.00000000e-03, 1.50000000e-03, 2.00000000e-03,\n 3.00000000e-03, 3.20000000e-03, 3.20000000e-03,\n 4.00000000e-03, 5.00000000e-03, 6.00000000e-03,\n 8.00000000e-03, 1.00000000e-02, 1.50000000e-02,\n 2.00000000e-02, 3.00000000e-02, 4.00000000e-02,\n 5.00000000e-02, 6.00000000e-02, 8.00000000e-02,\n 1.00000000e-01, 1.50000000e-01, 2.00000000e-01,\n 3.00000000e-01, 4.00000000e-01, 5.00000000e-01,\n 6.00000000e-01, 8.00000000e-01, 1.00000000e+00,\n 1.25000000e+00, 1.50000000e+00, 2.00000000e+00,\n 3.00000000e+00, 4.00000000e+00, 5.00000000e+00,\n 6.00000000e+00, 8.00000000e+00, 1.00000000e+01,\n 1.50000000e+01, 2.00000000e+01]\n\n\n u_en_p = [ 3.60000000e+03, 1.19000000e+03, 5.26000000e+02,\n 1.61000000e+02, 1.33000000e+02, 1.46000000e+02,\n 7.64000000e+01, 3.93000000e+01, 2.27000000e+01,\n 9.45000000e+00, 4.74000000e+00, 1.33000000e+00,\n 5.39000000e-01, 1.54000000e-01, 6.83000000e-02,\n 4.10000000e-02, 3.04000000e-02, 2.41000000e-02,\n 2.33000000e-02, 2.50000000e-02, 2.67000000e-02,\n 2.87000000e-02, 2.95000000e-02, 2.97000000e-02,\n 2.95000000e-02, 2.88000000e-02, 2.79000000e-02,\n 2.67000000e-02, 2.55000000e-02, 2.35000000e-02,\n 2.06000000e-02, 1.87000000e-02, 1.74000000e-02,\n 1.65000000e-02, 1.53000000e-02, 1.45000000e-02,\n 1.35000000e-02, 1.31000000e-02]\n coeff = np.interp(energy_keV/1e3, Energy_MeV, u_en_p) # Units cm^2 per g\n coeff /= 10 # cm^2/g --> m^2/g\n return coeff\n\nif __name__ == \"__main__\":\n #http://cdn.intechopen.com/pdfs-wm/32834.pdf\n import pyshield as ps\n isotopes = ps.RESOURCES[ps.ISOTOPES]\n dose_rates = {}\n for isotope in isotopes.keys():\n try:\n dose_rates[isotope] = H10(isotopes[isotope][ps.ENERGY_keV],\n isotopes[isotope][ps.ABUNDANCE])\n\n print(str(dose_rates[isotope]/isotopes[isotope][ps.H10] * 100) + \\\n '% ' 'accurate for {0}'.format(isotope))\n except KeyError:\n pass\n\n\n" ]
[ [ "matplotlib.image.imread", "pandas.read_excel" ], [ "numpy.log", "numpy.arctan", "numpy.interp", "numpy.array", "numpy.sum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
EricElmoznino/OrthogonalLowrankEmbedding
[ "cce12ca5cb34f7cb888b04739724bdbbd18b1e2d" ]
[ "stl10/utee/misc.py" ]
[ "from __future__ import print_function\nimport cv2\nimport os\nimport shutil\nimport pickle as pkl\nimport time\nimport numpy as np\nimport hashlib\n\nfrom IPython import embed\n\nclass Logger(object):\n def __init__(self):\n self._logger = None\n\n def init(self, logdir, name='log'):\n if self._logger is None:\n import logging\n if not os.path.exists(logdir):\n os.makedirs(logdir)\n log_file = os.path.join(logdir, name)\n if os.path.exists(log_file):\n os.remove(log_file)\n self._logger = logging.getLogger()\n self._logger.setLevel('INFO')\n fh = logging.FileHandler(log_file)\n ch = logging.StreamHandler()\n self._logger.addHandler(fh)\n self._logger.addHandler(ch)\n\n def info(self, str_info):\n self.init('/tmp', 'tmp.log')\n self._logger.info(str_info)\nlogger = Logger()\n\nprint = logger.info\ndef ensure_dir(path, erase=False):\n if os.path.exists(path) and erase:\n print(\"Removing old folder {}\".format(path))\n shutil.rmtree(path)\n if not os.path.exists(path):\n print(\"Creating folder {}\".format(path))\n os.makedirs(path)\n\ndef load_pickle(path):\n begin_st = time.time()\n with open(path, 'rb') as f:\n print(\"Loading pickle object from {}\".format(path))\n v = pkl.load(f)\n print(\"=> Done ({:.4f} s)\".format(time.time() - begin_st))\n return v\n\ndef dump_pickle(obj, path):\n with open(path, 'wb') as f:\n print(\"Dumping pickle object to {}\".format(path))\n pkl.dump(obj, f, protocol=pkl.HIGHEST_PROTOCOL)\n\ndef auto_select_gpu(mem_bound=500, utility_bound=0, gpus=(0, 1, 2, 3, 4, 5, 6, 7), num_gpu=1, selected_gpus=None):\n import sys\n import os\n import subprocess\n import re\n import time\n import numpy as np\n if 'CUDA_VISIBLE_DEVCIES' in os.environ:\n sys.exit(0)\n if selected_gpus is None:\n mem_trace = []\n utility_trace = []\n for i in range(5): # sample 5 times\n info = subprocess.check_output('nvidia-smi', shell=True).decode('utf-8')\n mem = [int(s[:-5]) for s in re.compile('\\d+MiB\\s/').findall(info)]\n utility = [int(re.compile('\\d+').findall(s)[0]) for s in re.compile('\\d+%\\s+Default').findall(info)]\n mem_trace.append(mem)\n utility_trace.append(utility)\n time.sleep(0.1)\n mem = np.mean(mem_trace, axis=0)\n utility = np.mean(utility_trace, axis=0)\n assert(len(mem) == len(utility))\n nGPU = len(utility)\n ideal_gpus = [i for i in range(nGPU) if mem[i] <= mem_bound and utility[i] <= utility_bound and i in gpus]\n\n if len(ideal_gpus) < num_gpu:\n print(\"No sufficient resource, available: {}, require {} gpu\".format(ideal_gpus, num_gpu))\n sys.exit(0)\n else:\n selected_gpus = list(map(str, ideal_gpus[:num_gpu]))\n else:\n selected_gpus = selected_gpus.split(',')\n\n print(\"Setting GPU: {}\".format(selected_gpus))\n os.environ['CUDA_VISIBLE_DEVICES'] = ','.join(selected_gpus)\n return selected_gpus\n\ndef expand_user(path):\n return os.path.abspath(os.path.expanduser(path))\n\ndef model_snapshot(model, new_file, old_file=None, verbose=False):\n from collections import OrderedDict\n import torch\n if isinstance(model, torch.nn.DataParallel):\n model = model.module\n if old_file and os.path.exists(expand_user(old_file)):\n if verbose:\n print(\"Removing old model {}\".format(expand_user(old_file)))\n os.remove(expand_user(old_file))\n if verbose:\n print(\"Saving model to {}\".format(expand_user(new_file)))\n\n state_dict = OrderedDict()\n for k, v in model.state_dict().items():\n if v.is_cuda:\n v = v.cpu()\n state_dict[k] = v\n torch.save(state_dict, expand_user(new_file))\n\n\ndef load_lmdb(lmdb_file, n_records=None):\n import lmdb\n import numpy as np\n lmdb_file = expand_user(lmdb_file)\n if os.path.exists(lmdb_file):\n data = []\n env = lmdb.open(lmdb_file, readonly=True, max_readers=512)\n with env.begin() as txn:\n cursor = txn.cursor()\n begin_st = time.time()\n print(\"Loading lmdb file {} into memory\".format(lmdb_file))\n for key, value in cursor:\n _, target, _ = key.decode('ascii').split(':')\n target = int(target)\n img = cv2.imdecode(np.fromstring(value, np.uint8), cv2.IMREAD_COLOR)\n data.append((img, target))\n if n_records is not None and len(data) >= n_records:\n break\n env.close()\n print(\"=> Done ({:.4f} s)\".format(time.time() - begin_st))\n return data\n else:\n print(\"Not found lmdb file\".format(lmdb_file))\n\ndef str2img(str_b):\n return cv2.imdecode(np.fromstring(str_b, np.uint8), cv2.IMREAD_COLOR)\n\ndef img2str(img):\n return cv2.imencode('.jpg', img)[1].tostring()\n\ndef md5(s):\n m = hashlib.md5()\n m.update(s)\n return m.hexdigest()\n\ndef eval_model(model, ds, n_sample=None, ngpu=1, is_imagenet=False):\n import tqdm\n import torch\n from torch import nn\n from torch.autograd import Variable\n\n class ModelWrapper(nn.Module):\n def __init__(self, model):\n super(ModelWrapper, self).__init__()\n self.model = model\n self.mean = [0.485, 0.456, 0.406]\n self.std = [0.229, 0.224, 0.225]\n\n def forward(self, input):\n input.data.div_(255.)\n input.data[:, 0, :, :].sub_(self.mean[0]).div_(self.std[0])\n input.data[:, 1, :, :].sub_(self.mean[1]).div_(self.std[1])\n input.data[:, 2, :, :].sub_(self.mean[2]).div_(self.std[2])\n return self.model(input)\n\n correct1, correct5 = 0, 0\n n_passed = 0\n if is_imagenet:\n model = ModelWrapper(model)\n model = model.eval()\n model = torch.nn.DataParallel(model, device_ids=range(ngpu)).cuda()\n\n n_sample = len(ds) if n_sample is None else n_sample\n for idx, (data, target) in enumerate(tqdm.tqdm(ds, total=n_sample)):\n n_passed += len(data)\n data = Variable(torch.FloatTensor(data)).cuda()\n indx_target = torch.LongTensor(target)\n output = model(data)\n bs = output.size(0)\n idx_pred = output.data.sort(1, descending=True)[1]\n\n idx_gt1 = indx_target.expand(1, bs).transpose_(0, 1)\n idx_gt5 = idx_gt1.expand(bs, 5)\n\n correct1 += idx_pred[:, :1].cpu().eq(idx_gt1).sum()\n correct5 += idx_pred[:, :5].cpu().eq(idx_gt5).sum()\n\n if idx >= n_sample - 1:\n break\n\n acc1 = correct1 * 1.0 / n_passed\n acc5 = correct5 * 1.0 / n_passed\n return acc1, acc5\n\ndef load_state_dict(model, model_urls, model_root):\n from torch.utils import model_zoo\n from torch import nn\n import re\n from collections import OrderedDict\n own_state_old = model.state_dict()\n own_state = OrderedDict() # remove all 'group' string\n for k, v in own_state_old.items():\n k = re.sub('group\\d+\\.', '', k)\n own_state[k] = v\n\n state_dict = model_zoo.load_url(model_urls, model_root)\n\n for name, param in state_dict.items():\n if name not in own_state:\n print(own_state.keys())\n raise KeyError('unexpected key \"{}\" in state_dict'\n .format(name))\n if isinstance(param, nn.Parameter):\n # backwards compatibility for serialized parameters\n param = param.data\n own_state[name].copy_(param)\n\n missing = set(own_state.keys()) - set(state_dict.keys())\n if len(missing) > 0:\n raise KeyError('missing keys in state_dict: \"{}\"'.format(missing))\n\n" ]
[ [ "torch.LongTensor", "numpy.fromstring", "torch.FloatTensor", "numpy.mean", "torch.utils.model_zoo.load_url" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
TraceOnBrainOff/pytorch-dc-tts
[ "993a0fbace561729b04df2179b41a0a7ea502e93" ]
[ "train-text2mel.py" ]
[ "#!/usr/bin/env python\n\"\"\"Train the Text2Mel network. See: https://arxiv.org/abs/1710.08969\"\"\"\n__author__ = 'Erdene-Ochir Tuguldur'\n\nimport sys\nimport time\nimport argparse\nfrom tqdm import *\n\nimport numpy as np\n\nimport torch\nimport torch.nn.functional as F\n\n# project imports\nfrom models import Text2Mel\nfrom hyperparams import HParams as hp\nfrom logger import Logger\nfrom utils import get_last_checkpoint_file_name, load_checkpoint, save_checkpoint, load_checkpoint_test\nfrom datasets.data_loader import Text2MelDataLoader\n\nparser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter)\nparser.add_argument(\"--dataset\", required=True, choices=['ljspeech', 'mbspeech','emovdb'], help='dataset name')\nargs = parser.parse_args()\n\nif args.dataset == 'ljspeech':\n from datasets.lj_speech import vocab, LJSpeech as SpeechDataset\nelif args.dataset == 'emovdb':\n from datasets.emovdb import vocab, Emovdb as SpeechDataset\nelse:\n from datasets.mb_speech import vocab, MBSpeech as SpeechDataset\n\nuse_gpu = torch.cuda.is_available()\nprint('use_gpu', use_gpu)\nif use_gpu:\n torch.backends.cudnn.benchmark = True\n\ntrain_data_loader = Text2MelDataLoader(text2mel_dataset=SpeechDataset(['texts', 'mels', 'mel_gates']), batch_size=64,\n mode='train')\nvalid_data_loader = Text2MelDataLoader(text2mel_dataset=SpeechDataset(['texts', 'mels', 'mel_gates']), batch_size=64,\n mode='valid')\n\ntext2mel = Text2Mel(vocab).cpu()\n\n\nstart_timestamp = int(time.time() * 1000)\nstart_epoch = 0\nglobal_step = 0\n\nlogger = Logger(args.dataset, 'text2mel')\n\n# load the last checkpoint if exists\nlast_checkpoint_file_name = get_last_checkpoint_file_name(logger.logdir)\nif last_checkpoint_file_name:\n print(\"loading the last checkpoint: %s\" % last_checkpoint_file_name)\n start_epoch, global_step = load_checkpoint(last_checkpoint_file_name, text2mel, None)\n\noptimizer = torch.optim.Adam(text2mel.parameters(), lr=hp.text2mel_lr)\n\ndef get_lr():\n return optimizer.param_groups[0]['lr']\n\n\ndef lr_decay(step, warmup_steps=4000):\n new_lr = hp.text2mel_lr * warmup_steps ** 0.5 * min((step + 1) * warmup_steps ** -1.5, (step + 1) ** -0.5)\n optimizer.param_groups[0]['lr'] = new_lr\n\n\ndef train(train_epoch, phase='train'):\n global global_step\n\n lr_decay(global_step)\n print(\"epoch %3d with lr=%.02e\" % (train_epoch, get_lr()))\n\n text2mel.train() if phase == 'train' else text2mel.eval()\n torch.set_grad_enabled(True) if phase == 'train' else torch.set_grad_enabled(False)\n data_loader = train_data_loader if phase == 'train' else valid_data_loader\n\n it = 0\n running_loss = 0.0\n running_l1_loss = 0.0\n running_att_loss = 0.0\n\n pbar = tqdm(data_loader, unit=\"audios\", unit_scale=data_loader.batch_size, disable=hp.disable_progress_bar)\n for batch in pbar:\n L, S, gates = batch['texts'], batch['mels'], batch['mel_gates']\n S = S.permute(0, 2, 1) # TODO: because of pre processing\n\n B, N = L.size() # batch size and text count\n _, n_mels, T = S.size() # number of melspectrogram bins and time\n\n assert gates.size(0) == B # TODO: later remove\n assert gates.size(1) == T\n\n S_shifted = torch.cat((S[:, :, 1:], torch.zeros(B, n_mels, 1)), 2)\n\n S.requires_grad = False\n S_shifted.requires_grad = False\n gates.requires_grad = False\n\n def W_nt(_, n, t, g=0.2):\n return 1.0 - np.exp(-((n / float(N) - t / float(T)) ** 2) / (2 * g ** 2))\n\n W = np.fromfunction(W_nt, (B, N, T), dtype=np.float32)\n W = torch.from_numpy(W)\n\n L = L.cpu()\n S = S.cpu()\n S_shifted = S_shifted.cpu()\n W = W.cpu()\n gates = gates.cpu()\n\n Y_logit, Y, A = text2mel(L, S, monotonic_attention=True)\n\n l1_loss = F.l1_loss(Y, S_shifted)\n masks = gates.reshape(B, 1, T).float()\n att_loss = (A * W * masks).mean()\n\n loss = l1_loss + att_loss\n\n if phase == 'train':\n lr_decay(global_step)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n global_step += 1\n\n it += 1\n\n loss, l1_loss, att_loss = loss.item(), l1_loss.item(), att_loss.item()\n running_loss += loss\n running_l1_loss += l1_loss\n running_att_loss += att_loss\n\n if phase == 'train':\n # update the progress bar\n pbar.set_postfix({\n 'l1': \"%.05f\" % (running_l1_loss / it),\n 'att': \"%.05f\" % (running_att_loss / it)\n })\n logger.log_step(phase, global_step, {'loss_l1': l1_loss, 'loss_att': att_loss},\n {'mels-true': S[:1, :, :], 'mels-pred': Y[:1, :, :], 'attention': A[:1, :, :]})\n if global_step % 1000 == 0:\n # checkpoint at every 1000th step\n save_checkpoint(logger.logdir, train_epoch, global_step, text2mel, optimizer)\n\n epoch_loss = running_loss / it\n epoch_l1_loss = running_l1_loss / it\n epoch_att_loss = running_att_loss / it\n\n logger.log_epoch(phase, global_step, {'loss_l1': epoch_l1_loss, 'loss_att': epoch_att_loss})\n\n return epoch_loss\n\n\nsince = time.time()\nepoch = start_epoch\nwhile True:\n train_epoch_loss = train(epoch, phase='train')\n time_elapsed = time.time() - since\n time_str = 'total time elapsed: {:.0f}h {:.0f}m {:.0f}s '.format(time_elapsed // 3600, time_elapsed % 3600 // 60,\n time_elapsed % 60)\n print(\"train epoch loss %f, step=%d, %s\" % (train_epoch_loss, global_step, time_str))\n\n valid_epoch_loss = train(epoch, phase='valid')\n print(\"valid epoch loss %f\" % valid_epoch_loss)\n\n epoch += 1\n if global_step >= hp.text2mel_max_iteration:\n print(\"max step %d (current step %d) reached, exiting...\" % (hp.text2mel_max_iteration, global_step))\n sys.exit(0)\n\n" ]
[ [ "torch.nn.functional.l1_loss", "torch.zeros", "torch.from_numpy", "torch.set_grad_enabled", "numpy.fromfunction", "torch.cuda.is_available" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Koen-AI/world-model-as-a-graph
[ "cafde59ef7159d1b62ca508568c85c6498c1342c", "cafde59ef7159d1b62ca508568c85c6498c1342c", "cafde59ef7159d1b62ca508568c85c6498c1342c", "cafde59ef7159d1b62ca508568c85c6498c1342c" ]
[ "rl/replay/planner.py", "rl/logger.py", "rl/launcher_latent_robot.py", "rl/search/latent_planner.py" ]
[ "import threading\nimport numpy as np\nimport torch\nimport os.path as osp\n\nfrom rl.utils import mpi_utils\n\n#Replay buffer!!!\n\ndef sample_her_transitions(buffer, reward_func, batch_size, future_step, future_p=1.0):\n assert all(k in buffer for k in ['ob', 'ag', 'bg', 'a'])\n buffer['o2'] = buffer['ob'][:, 1:, :]\n buffer['ag2'] = buffer['ag'][:, 1:, :]\n \n n_trajs = buffer['a'].shape[0]\n horizon = buffer['a'].shape[1]\n ep_idxes = np.random.randint(0, n_trajs, size=batch_size)\n t_samples = np.random.randint(0, horizon, size=batch_size)\n batch = {key: buffer[key][ep_idxes, t_samples].copy() for key in buffer.keys()}\n \n her_indexes = np.where(np.random.uniform(size=batch_size) < future_p)\n \n future_offset = (np.random.uniform(size=batch_size) * np.minimum(horizon - t_samples, future_step)).astype(int)\n future_t = (t_samples + 1 + future_offset)\n \n batch['bg'][her_indexes] = buffer['ag'][ep_idxes[her_indexes], future_t[her_indexes]]\n batch['future_ag'] = buffer['ag'][ep_idxes, future_t].copy()\n batch['offset'] = future_offset.copy()\n batch['r'] = reward_func(batch['ag2'], batch['bg'], None)\n \n assert all(batch[k].shape[0] == batch_size for k in batch.keys())\n assert all(k in batch for k in ['ob', 'ag', 'bg', 'a', 'o2', 'ag2', 'r', 'future_ag', 'offset'])\n return batch\n\n\ndef sample_transitions(buffer, batch_size):\n n_trajs = buffer['a'].shape[0]\n horizon = buffer['a'].shape[1]\n ep_idxes = np.random.randint(0, n_trajs, size=batch_size)\n t_samples = np.random.randint(0, horizon, size=batch_size)\n batch = {key: buffer[key][ep_idxes, t_samples].copy() for key in buffer.keys()}\n assert all(batch[k].shape[0] == batch_size for k in batch.keys())\n return batch\n\n\nclass Replay:\n def __init__(self, env_params, args, reward_func, name='replay'):\n self.env_params = env_params\n self.args = args\n self.reward_func = reward_func\n \n self.horizon = env_params['max_timesteps']\n self.size = args.buffer_size // self.horizon\n \n self.current_size = 0\n self.n_transitions_stored = 0\n \n self.buffers = dict(ob=np.zeros((self.size, self.horizon + 1, self.env_params['obs'])),\n ag=np.zeros((self.size, self.horizon + 1, self.env_params['goal'])),\n bg=np.zeros((self.size, self.horizon, self.env_params['goal'])),\n a=np.zeros((self.size, self.horizon, self.env_params['action'])))\n \n self.lock = threading.Lock()\n self._save_file = str(name) + '_' + str(mpi_utils.get_rank()) + '.pt'\n \n def store(self, episodes):\n ob_list, ag_list, bg_list, a_list = episodes['ob'], episodes['ag'], episodes['bg'], episodes['a']\n batch_size = ob_list.shape[0]\n with self.lock:\n idxs = self._get_storage_idx(batch_size=batch_size)\n self.buffers['ob'][idxs] = ob_list.copy() # State\n self.buffers['ag'][idxs] = ag_list.copy() # Achieved state after N steps\n self.buffers['bg'][idxs] = bg_list.copy() # Desired goal\n self.buffers['a'][idxs] = a_list.copy() # Action taken from state\n self.n_transitions_stored += self.horizon * batch_size\n \n def sample(self, batch_size):\n temp_buffers = {}\n with self.lock:\n for key in self.buffers.keys():\n temp_buffers[key] = self.buffers[key][:self.current_size]\n transitions = sample_her_transitions(temp_buffers, self.reward_func, batch_size,\n future_step=self.args.future_step,\n future_p=self.args.future_p)\n return transitions\n \n def _get_storage_idx(self, batch_size):\n if self.current_size + batch_size <= self.size:\n idx = np.arange(self.current_size, self.current_size + batch_size)\n elif self.current_size < self.size:\n idx_a = np.arange(self.current_size, self.size)\n idx_b = np.random.randint(0, self.current_size, batch_size - len(idx_a))\n idx = np.concatenate([idx_a, idx_b])\n else:\n idx = np.random.randint(0, self.size, batch_size)\n self.current_size = min(self.size, self.current_size + batch_size)\n if batch_size == 1:\n idx = idx[0]\n return idx\n \n def get_all_data(self):\n temp_buffers = {}\n with self.lock:\n for key in self.buffers.keys():\n temp_buffers[key] = self.buffers[key][:self.current_size]\n return temp_buffers\n \n def sample_regular_batch(self, batch_size):\n temp_buffers = {}\n with self.lock:\n for key in self.buffers.keys():\n temp_buffers[key] = self.buffers[key][:self.current_size]\n transitions = sample_transitions(temp_buffers, batch_size)\n return transitions\n \n def state_dict(self):\n return dict(\n current_size=self.current_size,\n n_transitions_stored=self.n_transitions_stored,\n buffers=self.buffers,\n )\n \n def load_state_dict(self, state_dict):\n self.current_size = state_dict['current_size']\n self.n_transitions_stored = state_dict['n_transitions_stored']\n self.buffers = state_dict['buffers']\n \n def save(self, path):\n state_dict = self.state_dict()\n save_path = osp.join(path, self._save_file)\n torch.save(state_dict, save_path)\n \n def load(self, path):\n load_path = osp.join(path, self._save_file)\n try:\n state_dict = torch.load(load_path)\n except RuntimeError:\n state_dict = torch.load(load_path, map_location=torch.device('cpu'))\n self.load_state_dict(state_dict)\n", "import os\nimport sys\nimport shutil\nimport os.path as osp\nimport json\nimport time\nimport datetime\nimport tempfile\nimport warnings\nfrom collections import defaultdict\nfrom contextlib import contextmanager\n\nDEBUG = 10\nINFO = 20\nWARN = 30\nERROR = 40\n\nDISABLED = 50\n\n\ndef mpi_weighted_mean(comm, local_name2valcount):\n \"\"\"\n Perform a weighted average over dicts that are each on a different node\n Input: local_name2valcount: dict mapping key -> (value, count)\n Returns: key -> mean\n \"\"\"\n all_name2valcount = comm.gather(local_name2valcount)\n if comm.rank == 0:\n name2sum = defaultdict(float)\n name2count = defaultdict(float)\n for n2vc in all_name2valcount:\n for (name, (val, count)) in n2vc.items():\n try:\n val = float(val)\n except ValueError:\n if comm.rank == 0:\n warnings.warn('WARNING: tried to compute mean on non-float {}={}'.format(name, val))\n else:\n name2sum[name] += val * count\n name2count[name] += count\n return {name: name2sum[name] / name2count[name] for name in name2sum}\n else:\n return {}\n\n\nclass KVWriter(object):\n def writekvs(self, kvs):\n raise NotImplementedError\n\n\nclass SeqWriter(object):\n def writeseq(self, seq):\n raise NotImplementedError\n\n\nclass HumanOutputFormat(KVWriter, SeqWriter):\n def __init__(self, filename_or_file):\n if isinstance(filename_or_file, str):\n self.file = open(filename_or_file, 'wt')\n self.own_file = True\n else:\n assert hasattr(filename_or_file, 'read'), 'expected file or str, got %s' % filename_or_file\n self.file = filename_or_file\n self.own_file = False\n \n def writekvs(self, kvs):\n # Create strings for printing\n key2str = {}\n for (key, val) in sorted(kvs.items()):\n if hasattr(val, '__float__'):\n valstr = '%-8.3g' % val\n else:\n valstr = str(val)\n key2str[self._truncate(key)] = self._truncate(valstr)\n \n # Find max widths\n if len(key2str) == 0:\n print('WARNING: tried to write empty key-value dict')\n return\n else:\n keywidth = max(map(len, key2str.keys()))\n valwidth = max(map(len, key2str.values()))\n \n # Write out the data\n dashes = '-' * (keywidth + valwidth + 7)\n lines = [dashes]\n for (key, val) in sorted(key2str.items(), key=lambda kv: kv[0].lower()):\n lines.append('| %s%s | %s%s |' % (\n key,\n ' ' * (keywidth - len(key)),\n val,\n ' ' * (valwidth - len(val)),\n ))\n lines.append(dashes)\n self.file.write('\\n'.join(lines) + '\\n')\n \n # Flush the output to the file\n self.file.flush()\n \n def _truncate(self, s):\n maxlen = 30\n return s[:maxlen - 3] + '...' if len(s) > maxlen else s\n \n def writeseq(self, seq):\n seq = list(seq)\n for (i, elem) in enumerate(seq):\n self.file.write(elem)\n if i < len(seq) - 1: # add space unless this is the last one\n self.file.write(' ')\n self.file.write('\\n')\n self.file.flush()\n \n def close(self):\n if self.own_file:\n self.file.close()\n\n\nclass JSONOutputFormat(KVWriter):\n def __init__(self, filename):\n self.file = open(filename, 'wt')\n \n def writekvs(self, kvs):\n for k, v in sorted(kvs.items()):\n if hasattr(v, 'dtype'):\n kvs[k] = float(v)\n self.file.write(json.dumps(kvs) + '\\n')\n self.file.flush()\n \n def close(self):\n self.file.close()\n\n\nclass CSVOutputFormat(KVWriter):\n def __init__(self, filename):\n self.file = open(filename, 'w+t')\n self.keys = []\n self.sep = ','\n \n def writekvs(self, kvs):\n # Add our current row to the history\n extra_keys = list(kvs.keys() - self.keys)\n extra_keys.sort()\n if extra_keys:\n self.keys.extend(extra_keys)\n self.file.seek(0)\n lines = self.file.readlines()\n self.file.seek(0)\n for (i, k) in enumerate(self.keys):\n if i > 0:\n self.file.write(',')\n self.file.write(k)\n self.file.write('\\n')\n for line in lines[1:]:\n self.file.write(line[:-1])\n self.file.write(self.sep * len(extra_keys))\n self.file.write('\\n')\n for (i, k) in enumerate(self.keys):\n if i > 0:\n self.file.write(',')\n v = kvs.get(k)\n if v is not None:\n self.file.write(str(v))\n self.file.write('\\n')\n self.file.flush()\n \n def close(self):\n self.file.close()\n\n\nclass TensorBoardOutputFormat(KVWriter):\n \"\"\"\n Dumps key/value pairs into TensorBoard's numeric format.\n \"\"\"\n \n def __init__(self, dir):\n os.makedirs(dir, exist_ok=True)\n self.dir = dir\n self.step = 1\n prefix = 'events'\n path = osp.join(osp.abspath(dir), prefix)\n import warnings\n warnings.filterwarnings('ignore', category=FutureWarning)\n import tensorflow as tf\n from tensorflow.python import pywrap_tensorflow\n from tensorflow.core.util import event_pb2\n from tensorflow.python.util import compat\n self.tf = tf\n self.event_pb2 = event_pb2\n self.pywrap_tensorflow = pywrap_tensorflow\n self.writer = pywrap_tensorflow.EventsWriter(compat.as_bytes(path))\n \n def writekvs(self, kvs):\n def summary_val(k, v):\n kwargs = {'tag': k, 'simple_value': float(v)}\n return self.tf.Summary.Value(**kwargs)\n \n summary = self.tf.Summary(value=[summary_val(k, v) for k, v in kvs.items()])\n event = self.event_pb2.Event(wall_time=time.time(), summary=summary)\n event.step = self.step # is there any reason why you'd want to specify the step?\n self.writer.WriteEvent(event)\n self.writer.Flush()\n self.step += 1\n \n def close(self):\n if self.writer:\n self.writer.Close()\n self.writer = None\n\n\ndef make_output_format(format, ev_dir, log_suffix=''):\n os.makedirs(ev_dir, exist_ok=True)\n if format == 'stdout':\n return HumanOutputFormat(sys.stdout)\n elif format == 'log':\n return HumanOutputFormat(osp.join(ev_dir, 'log%s.txt' % log_suffix))\n elif format == 'json':\n return JSONOutputFormat(osp.join(ev_dir, 'progress%s.json' % log_suffix))\n elif format == 'csv':\n return CSVOutputFormat(osp.join(ev_dir, 'progress%s.csv' % log_suffix))\n elif format == 'tensorboard':\n return TensorBoardOutputFormat(osp.join(ev_dir, 'tb%s' % log_suffix))\n else:\n raise ValueError('Unknown format specified: %s' % (format,))\n\n\n# ================================================================\n# API\n# ================================================================\n\ndef logkv(key, val):\n \"\"\"\n Log a value of some diagnostic\n Call this once for each diagnostic quantity, each iteration\n If called many times, last value will be used.\n \"\"\"\n get_current().logkv(key, val)\n\n\ndef logkv_mean(key, val):\n \"\"\"\n The same as logkv(), but if called many times, values averaged.\n \"\"\"\n get_current().logkv_mean(key, val)\n\n\ndef logkvs(d):\n \"\"\"\n Log a dictionary of key-value pairs\n \"\"\"\n for (k, v) in d.items():\n logkv(k, v)\n\n\ndef dumpkvs():\n \"\"\"\n Write all of the diagnostics from the current iteration\n \"\"\"\n return get_current().dumpkvs()\n\n\ndef getkvs():\n return get_current().name2val\n\n\ndef log(*args, level=INFO):\n \"\"\"\n Write the sequence of args, with no separators, to the console and output files (if you've configured an output file).\n \"\"\"\n get_current().log(*args, level=level)\n\n\ndef debug(*args):\n log(*args, level=DEBUG)\n\n\ndef info(*args):\n log(*args, level=INFO)\n\n\ndef warn(*args):\n log(*args, level=WARN)\n\n\ndef error(*args):\n log(*args, level=ERROR)\n\n\ndef set_level(level):\n \"\"\"\n Set logging threshold on current logger.\n \"\"\"\n get_current().set_level(level)\n\n\ndef set_comm(comm):\n get_current().set_comm(comm)\n\n\ndef get_dir():\n \"\"\"\n Get directory that log files are being written to.\n will be None if there is no output directory (i.e., if you didn't call start)\n \"\"\"\n return get_current().get_dir()\n\n\nrecord_tabular = logkv\ndump_tabular = dumpkvs\n\n\n@contextmanager\ndef profile_kv(scopename):\n logkey = 'wait_' + scopename\n tstart = time.time()\n try:\n yield\n finally:\n get_current().name2val[logkey] += time.time() - tstart\n\n\ndef profile(n):\n \"\"\"\n Usage:\n @profile(\"my_func\")\n def my_func(): code\n \"\"\"\n \n def decorator_with_name(func):\n def func_wrapper(*args, **kwargs):\n with profile_kv(n):\n return func(*args, **kwargs)\n \n return func_wrapper\n \n return decorator_with_name\n\n\n# ================================================================\n# Backend\n# ================================================================\n\ndef get_current():\n if Logger.CURRENT is None:\n _configure_default_logger()\n \n return Logger.CURRENT\n\n\nclass Logger(object):\n DEFAULT = None # A logger with no output files. (See right below class definition)\n # So that you can still log to the terminal without setting up any output files\n CURRENT = None # Current logger being used by the free functions above\n \n def __init__(self, dir, output_formats, comm=None):\n self.name2val = defaultdict(float) # values this iteration\n self.name2cnt = defaultdict(int)\n self.level = INFO\n self.dir = dir\n self.output_formats = output_formats\n self.comm = comm\n \n # Logging API, forwarded\n # ----------------------------------------\n def logkv(self, key, val):\n self.name2val[key] = val\n \n def logkv_mean(self, key, val):\n oldval, cnt = self.name2val[key], self.name2cnt[key]\n self.name2val[key] = oldval * cnt / (cnt + 1) + val / (cnt + 1)\n self.name2cnt[key] = cnt + 1\n \n def dumpkvs(self):\n if self.comm is None:\n d = self.name2val\n else:\n d = mpi_weighted_mean(self.comm,\n {name: (val, self.name2cnt.get(name, 1))\n for (name, val) in self.name2val.items()})\n if self.comm.rank != 0:\n d['dummy'] = 1 # so we don't get a warning about empty dict\n out = d.copy() # Return the dict for unit testing purposes\n for fmt in self.output_formats:\n if isinstance(fmt, KVWriter):\n fmt.writekvs(d)\n self.name2val.clear()\n self.name2cnt.clear()\n return out\n \n def log(self, *args, level=INFO):\n if self.level <= level:\n self._do_log(args)\n \n # Configuration\n # ----------------------------------------\n def set_level(self, level):\n self.level = level\n \n def set_comm(self, comm):\n self.comm = comm\n \n def get_dir(self):\n return self.dir\n \n def close(self):\n for fmt in self.output_formats:\n fmt.close()\n \n # Misc\n # ----------------------------------------\n def _do_log(self, args):\n for fmt in self.output_formats:\n if isinstance(fmt, SeqWriter):\n fmt.writeseq(map(str, args))\n\n\ndef get_rank_without_mpi_import():\n # check environment variables here instead of importing mpi4py\n # to avoid calling MPI_Init() when this module is imported\n for varname in ['PMI_RANK', 'OMPI_COMM_WORLD_RANK']:\n if varname in os.environ:\n return int(os.environ[varname])\n return 0\n\n\ndef configure(dir=None, format_strs=None, comm=None, log_suffix=''):\n \"\"\"\n If comm is provided, average all numerical stats across that comm\n \"\"\"\n if dir is None:\n dir = os.getenv('OPENAI_LOGDIR')\n if dir is None:\n dir = osp.join(tempfile.gettempdir(),\n datetime.datetime.now().strftime(\"openai-%Y-%m-%d-%H-%M-%S-%f\"))\n assert isinstance(dir, str)\n dir = os.path.expanduser(dir)\n os.makedirs(os.path.expanduser(dir), exist_ok=True)\n \n rank = get_rank_without_mpi_import()\n if rank > 0:\n log_suffix = log_suffix + \"-rank%03i\" % rank\n \n if format_strs is None:\n if rank == 0:\n format_strs = os.getenv('OPENAI_LOG_FORMAT', 'stdout,log,csv').split(',')\n else:\n format_strs = os.getenv('OPENAI_LOG_FORMAT_MPI', 'log').split(',')\n format_strs = filter(None, format_strs)\n output_formats = [make_output_format(f, dir, log_suffix) for f in format_strs]\n \n Logger.CURRENT = Logger(dir=dir, output_formats=output_formats, comm=comm)\n if output_formats:\n log('Logging to %s' % dir)\n\n\ndef _configure_default_logger():\n configure()\n Logger.DEFAULT = Logger.CURRENT\n\n\ndef reset():\n if Logger.CURRENT is not Logger.DEFAULT:\n Logger.CURRENT.close()\n Logger.CURRENT = Logger.DEFAULT\n log('Reset logger')\n\n\n@contextmanager\ndef scoped_configure(dir=None, format_strs=None, comm=None):\n prevlogger = Logger.CURRENT\n configure(dir=dir, format_strs=format_strs, comm=comm)\n try:\n yield\n finally:\n Logger.CURRENT.close()\n Logger.CURRENT = prevlogger\n\n\n# ================================================================\n\ndef _demo():\n info(\"hi\")\n debug(\"shouldn't appear\")\n set_level(DEBUG)\n debug(\"should appear\")\n dir = \"/tmp/testlogging\"\n if os.path.exists(dir):\n shutil.rmtree(dir)\n configure(dir=dir)\n logkv(\"a\", 3)\n logkv(\"b\", 2.5)\n dumpkvs()\n logkv(\"b\", -2.5)\n logkv(\"a\", 5.5)\n dumpkvs()\n info(\"^^^ should see a = 5.5\")\n logkv_mean(\"b\", -22.5)\n logkv_mean(\"b\", -44.4)\n logkv(\"a\", 5.5)\n dumpkvs()\n info(\"^^^ should see b = -33.3\")\n \n logkv(\"b\", -2.5)\n dumpkvs()\n \n logkv(\"a\", \"longasslongasslongasslongasslongasslongassvalue\")\n dumpkvs()\n\n\n# ================================================================\n# Readers\n# ================================================================\n\ndef read_json(fname):\n import pandas\n ds = []\n with open(fname, 'rt') as fh:\n for line in fh:\n ds.append(json.loads(line))\n return pandas.DataFrame(ds)\n\n\ndef read_csv(fname):\n import pandas\n return pandas.read_csv(fname, index_col=None, comment='#')\n\n\ndef read_tb(path):\n \"\"\"\n path : a tensorboard file OR a directory, where we will find all TB files\n of the form events.*\n \"\"\"\n import pandas\n import numpy as np\n from glob import glob\n import tensorflow as tf\n if osp.isdir(path):\n fnames = glob(osp.join(path, \"events.*\"))\n elif osp.basename(path).startswith(\"events.\"):\n fnames = [path]\n else:\n raise NotImplementedError(\"Expected tensorboard file or directory containing them. Got %s\" % path)\n tag2pairs = defaultdict(list)\n maxstep = 0\n for fname in fnames:\n for summary in tf.train.summary_iterator(fname):\n if summary.step > 0:\n for v in summary.summary.value:\n pair = (summary.step, v.simple_value)\n tag2pairs[v.tag].append(pair)\n maxstep = max(summary.step, maxstep)\n data = np.empty((maxstep, len(tag2pairs)))\n data[:] = np.nan\n tags = sorted(tag2pairs.keys())\n for (colidx, tag) in enumerate(tags):\n pairs = tag2pairs[tag]\n for (step, value) in pairs:\n data[step - 1, colidx] = value\n return pandas.DataFrame(data, columns=tags)\n\n\nif __name__ == \"__main__\":\n _demo()\n", "import time\nimport gym\nimport random\nimport numpy as np\nimport torch\n\nfrom rl.utils import mpi_utils\nfrom rl.utils import vec_env\nfrom rl.utils.run_utils import Monitor\n\nfrom rl.agent.latent_fetch import Agent\nfrom rl.algo.latent_planner import Algo\nfrom rl.learn.latent_planner import Learner\nfrom rl.replay.planner import Replay\n\nimport fetch\n\n\ndef get_env_params(env):\n obs = env.reset()\n params = {'obs': obs['observation'].shape[0], 'goal': obs['desired_goal'].shape[0],\n 'action': env.action_space.shape[0],\n 'action_max': env.action_space.high[0],\n 'max_timesteps': env._max_episode_steps}\n return params\n\n\ndef get_env_with_id(num_envs, env_id):\n vec_fn = vec_env.SubprocVecEnv\n return vec_fn([lambda: gym.make(env_id) for _ in range(num_envs)])\n\n\ndef get_env_with_fn(num_envs, env_fn, *args, **kwargs):\n vec_fn = vec_env.SubprocVecEnv\n return vec_fn([lambda: env_fn(*args, **kwargs) for _ in range(num_envs)])\n\n\ndef launch(args):\n env = gym.make(args.env_name)\n test_env = gym.make(args.test_env_name)\n \n rank = mpi_utils.get_rank()\n seed = args.seed + rank * args.n_workers\n \n env.seed(seed)\n test_env.seed(seed)\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n if args.cuda:\n torch.cuda.manual_seed(seed)\n \n assert np.all(env.action_space.high == -env.action_space.low)\n env_params = get_env_params(env)\n \n reward_func = env.compute_reward\n monitor = Monitor()\n \n if args.n_workers > 1:\n env = get_env_with_id(num_envs=args.n_workers, env_id=args.env_name)\n env.seed(seed)\n \n test_env = get_env_with_id(num_envs=args.n_workers, env_id=args.test_env_name)\n test_env.seed(seed)\n \n ckpt_name = args.ckpt_name\n if len(ckpt_name) == 0:\n data_time = time.ctime().split()[1:4]\n ckpt_name = data_time[0] + '-' + data_time[1]\n time_list = np.array([float(i) for i in data_time[2].split(':')], dtype=np.float32)\n if mpi_utils.use_mpi():\n time_list = mpi_utils.bcast(time_list)\n for time_ in time_list:\n ckpt_name += '-' + str(int(time_))\n args.ckpt_name = ckpt_name\n \n agent = Agent(env_params, args)\n replay = Replay(env_params, args, reward_func)\n learner = Learner(agent, monitor, args)\n algo = Algo(\n env=env, env_params=env_params, args=args,\n test_env=test_env,\n agent=agent, replay=replay, monitor=monitor, learner=learner,\n reward_func=reward_func,\n )\n return algo\n", "import numpy as np\nimport torch\n\nfrom torch.distributions import Categorical\nfrom rl.search.scheduler import Scheduler\n\ndef matrix_iter(\n matrix: torch.Tensor,\n temp=1.0,\n):\n if matrix.max() > 0.0:\n import pdb; pdb.set_trace()\n dist_tensor = matrix[:, :, None] + matrix[None, :, :] # [i, j, new] + [new, i, j] => [i, i+j, j]\n attend = torch.softmax(dist_tensor / temp, dim=1)\n return (dist_tensor * attend).sum(dim=1)\n\n\ndef value_iter(\n matrix: torch.Tensor,\n temp=1.0,\n n_iter=20,\n):\n n_states = matrix.size(0)\n assert matrix.ndim == 2 and matrix.size(0) == matrix.size(1)\n value_matrix = matrix * (torch.ones_like(matrix).to(matrix.device) - torch.eye(n_states).to(matrix.device))\n for _ in range(n_iter):\n value_matrix = matrix_iter(value_matrix, temp=temp)\n return value_matrix\n\n\ndef pairwise_dists(\n states: torch.Tensor,\n goals: torch.Tensor,\n agent,\n):\n with torch.no_grad():\n dists = []\n for goal in goals:\n goal_repeat = goal[None, :].repeat(states.size(0), 1)\n dists.append(\n agent.pairwise_value(states, goal_repeat)\n )\n dists = torch.stack(dists, dim=1) # [states, goals]\n assert dists.size(0) == states.size(0) and dists.size(1) == goals.size(0)\n return dists\n\n\ndef v_pairwise_dists(\n start_g: torch.Tensor,\n goals: torch.Tensor,\n agent,\n):\n with torch.no_grad():\n dists = []\n for goal in goals:\n goal_repeat = goal[None, :].repeat(start_g.size(0), 1)\n dists.append(\n -1. * agent.get_vf_value(start_g, goal_repeat)\n )\n dists = torch.stack(dists, dim=1) # [start_g, goals]\n assert dists.size(0) == start_g.size(0) and dists.size(1) == goals.size(0)\n return dists\n\n\ndef max_clip_dist(dists: torch.Tensor, clip=-5.0, inf_value=1e6, square=False):\n if square:\n dists = -1.0*dists*dists\n else:\n dists = dists - (dists < clip).float() * inf_value\n return dists\n\n\ndef min_clip_dist(dists: torch.Tensor, clip=-15.0, inf_value=1e6):\n dists = dists - (dists > clip).float() * inf_value\n return dists\n\n\ndef adaptive_max_clip_dist(dists: torch.Tensor, clip=-5.0, inf_value=1e6, square=False):\n assert dists.ndim == 2 and dists.size(0) == dists.size(1)\n n_states = dists.size(0)\n clip_values = clip * torch.ones(n_states).to(dists.device)\n min_dists = (dists - np.sqrt(inf_value) * torch.eye(n_states).to(dists.device)).max(dim=0)[0]\n clip_values = torch.min(min_dists, clip_values)\n \n if square:\n dists = -1.0*dists*dists\n else:\n dists = dists - (dists < clip_values[None, :]).float() * inf_value\n return dists\n\n\ndef adaptive_min_clip_dist(dists: torch.Tensor, clip=-15.0, inf_value=1e6):\n assert dists.ndim == 2 and dists.size(0) == dists.size(1)\n n_states = dists.size(0)\n clip_values = clip * torch.ones(n_states).to(dists.device)\n min_dists = (dists + np.sqrt(inf_value) * torch.eye(n_states).to(dists.device)).min(dim=0)[0]\n clip_values = torch.max(min_dists, clip_values)\n \n dists = dists - (dists > clip_values[None, :]).float() * inf_value\n return dists\n\n\ndef fps_selection(\n goals_embed: torch.Tensor,\n n_select: int,\n inf_value=1e6,\n embed_epsilon=1e-3, early_stop=True,\n embed_op='mean',\n):\n assert goals_embed.ndim == 2\n n_states = goals_embed.size(0)\n dists = torch.zeros(n_states).to(goals_embed.device) + inf_value\n chosen = []\n while len(chosen) < n_select:\n if dists.max() < embed_epsilon and early_stop:\n break\n idx = dists.argmax() # farthest point idx\n idx_embed = goals_embed[idx]\n chosen.append(idx)\n # distance from the chosen point to all other pts\n diff_embed = (goals_embed - idx_embed[None, :]).pow(2)\n if embed_op == 'mean':\n new_dists = diff_embed.mean(dim=1)\n elif embed_op == 'sum':\n new_dists = diff_embed.sum(dim=1)\n elif embed_op == 'max':\n new_dists = diff_embed.max(dim=1)[0]\n else:\n raise NotImplementedError\n dists = torch.stack((dists, new_dists.float())).min(dim=0)[0]\n chosen = torch.stack(chosen)\n chosen = chosen.detach().cpu().numpy()\n return chosen\n\n\nclass Planner:\n def __init__(\n self,\n agent, replay_buffer,\n monitor,\n args):\n self.agent = agent\n self.replay_buffer = replay_buffer\n self.monitor = monitor\n self.args = args\n self.n_goals = None\n self.n_landmarks = None\n self.past_goal = dict()\n self.past_goal_cnt = dict()\n self.subgoal_cnt = dict()\n \n self.landmarks = None\n self.dists_to_goals = None\n self._dists_to_landmarks = None\n self._dists = None\n self._g_list = []\n \n if not args.d_scheduler == None:\n self.scheduler = Scheduler(args)\n else:\n self.scheduler = None\n \n @staticmethod\n def to_2d_array(x):\n return x.reshape(-1, x.shape[-1])\n \n def to_tensor(self, x):\n return torch.as_tensor(x).float().to(self.agent.device)\n \n @staticmethod\n def assert_compatible(x, y):\n assert x.size(0) == y.size(0) and x.size(1) == y.size(1)\n \n def reset(self):\n pass\n \n def fps_sample_batch(self, initial_sample=1000, batch_size=200):\n replay_data = self.replay_buffer.sample_regular_batch(batch_size=initial_sample)\n landmarks = replay_data['ag']\n states = replay_data['ob']\n assert landmarks.ndim == 2 and states.ndim == 2\n \n landmarks = self.to_tensor(landmarks)\n states = self.to_tensor(states)\n with torch.no_grad():\n goals_embed = self.agent.ae.encoder(landmarks)\n idx = fps_selection(\n goals_embed=goals_embed, n_select=batch_size,\n inf_value=self.args.inf_value, embed_epsilon=self.args.embed_epsilon, early_stop=False,\n embed_op=self.args.embed_op, # 'mean' or 'sum'\n )\n landmarks = landmarks[idx]\n states = states[idx]\n return landmarks, states\n \n def update(\n self,\n goals: np.ndarray,\n test_time=False,\n ):\n if goals.ndim == 1:\n goals = self.to_2d_array(goals)\n \n with torch.no_grad():\n embeds = self.agent.cluster.centroids()\n landmarks = self.agent.ae.decoder(embeds)\n if self.args.n_extra_landmark > 0 and not test_time:\n extra_landmarks, _ = self.fps_sample_batch(\n initial_sample=self.args.initial_sample, batch_size=self.args.n_extra_landmark)\n landmarks = torch.cat([landmarks, extra_landmarks], dim=0)\n \n goals = self.to_tensor(goals)\n assert goals.size(1) == landmarks.size(1)\n n_goals = goals.size(0) # K\n self.n_goals = n_goals\n self.past_goal = {env_id: -1 for env_id in range(self.n_goals)}\n self.past_goal_cnt = {env_id: dict() for env_id in range(self.n_goals)}\n self.subgoal_cnt = {env_id: 0 for env_id in range(self.n_goals)}\n \n n_landmarks = landmarks.size(0)\n self.n_landmarks = n_landmarks\n assert n_landmarks <= self.args.n_latent_landmarks + self.args.n_extra_landmark\n \n landmarks_only = landmarks.clone().detach()\n landmarks = torch.cat([landmarks, goals], dim=0)\n dists = v_pairwise_dists(landmarks_only, landmarks, agent=self.agent) # n_landmark * (n_landmark + K)\n self.monitor.store(Graph_dist_raw=dists.mean().item())\n \n dists = torch.min(dists, dists * 0.)\n if dists.max() > 0.0:\n import pdb; pdb.set_trace()\n self.monitor.store(Graph_dist_min_0=dists.mean().item())\n \n # pad the last K rows in dists by -inf because nothing starts from the goal\n goals_dist_ph = torch.zeros(n_goals, n_landmarks + n_goals).to(dists.device)\n dists = torch.cat([dists, goals_dist_ph - self.args.inf_value], dim=0)\n # (n_landmark + K) * (n_landmark + K)\n \n if self.args.d_scheduler == None:\n clip_max = self.args.dist_clip\n dists = adaptive_max_clip_dist(\n dists, clip=clip_max, inf_value=self.args.inf_value, square=self.args.square)\n else:\n if self.args.scheduler_min:\n clip_min = self.scheduler.get_d_min()\n dists = adaptive_min_clip_dist(\n dists, clip=clip_min, inf_value=self.args.inf_value)\n #reset the distance to the final goal after min-clipping:\n k_l = list(dists.size())[1] - n_goals #-1 here because the final one needn't be checked since it is 0 anyways\n for k in range(k_l): #start #goal\n dists[k][k_l] = -1. * self.agent.get_vf_value(landmarks[k], landmarks[k_l])\n dists = torch.min(dists, dists * 0.)\n if self.args.scheduler_max:\n clip_max = self.scheduler.get_d_max()\n dists = adaptive_max_clip_dist(\n dists, clip=clip_max, inf_value=self.args.inf_value, square=self.args.square)\n \n dists = value_iter(dists, temp=self.args.temp, n_iter=self.args.vi_iter, )\n self.monitor.store(Graph_dist_vi=dists.mean().item())\n \n # from all the landmarks to goal\n dists_to_goals = dists[:, -n_goals:] # shape: (n_landmark + K) * K\n dists_to_goals = dists_to_goals.permute(1, 0) # K * (n_landmark + K)\n self.monitor.store(Graph_dist_to_goal=dists_to_goals.mean().item())\n \n self.landmarks = landmarks\n self.dists_to_goals = dists_to_goals\n \n def goal_repeated(self, env_id, goal_idx):\n return goal_idx in self.past_goal_cnt[env_id] and self.past_goal_cnt[env_id][goal_idx] >= 5\n \n def get_subgoals(\n self,\n obs: np.ndarray,\n goals: np.ndarray,\n ):\n obs = self.to_2d_array(obs) # (K, obs_dim)\n goals = self.to_2d_array(goals).copy() # (K, goal_dim)\n \n landmarks = self.landmarks\n assert landmarks.ndim == 2\n # (K, n_landmark + K, dim)\n obs = self.to_tensor(obs)[:, None, :].repeat(1, self.landmarks.size(0), 1)\n landmarks = landmarks[None, :, :].repeat(obs.size(0), 1, 1)\n self.assert_compatible(obs, landmarks)\n \n # remember, obs is batched, and thus different across the batch\n with torch.no_grad():\n dists_to_landmarks = self.agent.pairwise_value(obs, landmarks) # (K, n_landmark + K)\n n_goals = goals.shape[0]\n dists_to_landmarks = dists_to_landmarks.reshape(n_goals, -1)\n self.monitor.store(Dist_to_landmarks=dists_to_landmarks.mean().item())\n \n if self.args.d_scheduler == None:\n clip_max = self.args.dist_clip\n dists_to_landmarks = max_clip_dist(\n dists_to_landmarks, clip=clip_max, inf_value=self.args.inf_value, square=self.args.square)\n else:\n if self.args.scheduler_min:\n copy_dists = torch.clone(dists_to_landmarks)\n clip_min = self.scheduler.get_d_min()\n dists_to_landmarks = min_clip_dist(\n dists_to_landmarks, clip=clip_min, inf_value=self.args.inf_value)\n #reset the distance to the final goal after min-clipping:\n k_l = list(dists_to_landmarks.size())[1] - n_goals #-1 here because the final one needn't be checked since it is 0 anyways\n #print(k_l)\n #print(n_goals)\n for w in range(n_goals): #start #goal\n dists_to_landmarks[w][k_l] = copy_dists[w][k_l]#-1. * self.agent.get_vf_value(landmarks[k], landmarks[k_l])\n if self.args.scheduler_max:\n clip_max = self.scheduler.get_d_max()\n dists_to_landmarks = max_clip_dist(\n dists_to_landmarks, clip=clip_max, inf_value=self.args.inf_value, square=self.args.square)\n\n self._dists_to_landmarks = dists_to_landmarks.clone()\n \n self.assert_compatible(dists_to_landmarks, self.dists_to_goals)\n dists = dists_to_landmarks + self.dists_to_goals # (K, n_landmark + K) \n self.monitor.store(Dist_min_path=torch.min(dists).item())\n self.monitor.store(Shortest_Path=torch.min(dists, dim=-1)[0].mean().item())\n \n for env_id in range(obs.size(0)):\n for i in range(len(dists[0]) - obs.size(0), len(dists[0])):\n if i == env_id:\n continue\n dists[env_id, i] -= self.args.inf_value\n \n self._dists = dists\n \n extra_steps = 1.0\n self._g_list = []\n for env_id in range(obs.size(0)):\n env_goal_idx = self.n_landmarks + env_id\n prev_idx = self.past_goal[env_id]\n if self.subgoal_cnt[env_id] > 1.0:\n goals[env_id] = self.landmarks[prev_idx].detach().cpu().numpy()\n self.subgoal_cnt[env_id] -= 1.0\n self._g_list.append(prev_idx)\n continue\n if dists_to_landmarks[env_id, env_goal_idx] < - self.args.local_horizon:\n if prev_idx != -1:\n dists[env_id, prev_idx] -= self.args.inf_value\n try:\n out_probs = torch.softmax(dists[env_id] / self.args.temp, dim=-1)\n idx = Categorical(out_probs).sample()\n except:\n idx = torch.max(dists[env_id].cpu(), dim=-1)[1]\n idx = int(idx.cpu().numpy())\n steps_to_landmark = - dists_to_landmarks[env_id, idx].cpu().numpy()\n goals[env_id] = self.landmarks[idx].detach().cpu().numpy()\n env_goal_idx = idx\n self.past_goal[env_id] = env_goal_idx\n self.subgoal_cnt[env_id] = steps_to_landmark + extra_steps\n self._g_list.append(env_goal_idx)\n \n assert goals.ndim == 2\n return goals\n \n def forward_empty_step(self):\n if self.args.use_forward_empty_step:\n for env_id in self.subgoal_cnt:\n if self.subgoal_cnt[env_id] > 1.0:\n self.subgoal_cnt[env_id] -= 1.0\n" ]
[ [ "numpy.minimum", "torch.load", "numpy.arange", "numpy.concatenate", "numpy.random.randint", "torch.device", "numpy.random.uniform", "numpy.zeros", "torch.save" ], [ "tensorflow.python.util.compat.as_bytes", "pandas.read_csv", "tensorflow.train.summary_iterator", "pandas.DataFrame" ], [ "numpy.all", "torch.manual_seed", "torch.cuda.manual_seed", "numpy.random.seed" ], [ "torch.softmax", "torch.ones", "torch.max", "numpy.sqrt", "torch.cat", "torch.zeros", "torch.min", "torch.clone", "torch.eye", "torch.distributions.Categorical", "torch.no_grad", "torch.stack", "torch.ones_like", "torch.as_tensor" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [ "1.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
pnsafari/speechbrain
[ "3a6956a838f3796ff6d041ee6a20bcdea55794cb" ]
[ "recipes/VoxCeleb/SpeakerRec/speaker_verification_plda.py" ]
[ "#!/usr/bin/python3\n\"\"\"Recipe for training a speaker verification system based on PLDA using the voxceleb dataset.\nThe system employs a pre-trained model followed by a PLDA transformation.\nThe pre-trained model is automatically downloaded from the web if not specified.\n\nTo run this recipe, run the following command:\n > python speaker_verification_plda.py hyperparams/verification_plda_xvector.yaml\n\nAuthors\n * Nauman Dawalatabad 2020\n * Mirco Ravanelli 2020\n\"\"\"\n\nimport os\nimport sys\nimport torch\nimport torchaudio\nimport logging\nimport speechbrain as sb\nimport numpy\nimport pickle\nfrom tqdm.contrib import tqdm\nfrom hyperpyyaml import load_hyperpyyaml\nfrom speechbrain.utils.metric_stats import EER, minDCF\nfrom speechbrain.processing.PLDA_LDA import StatObject_SB\nfrom speechbrain.processing.PLDA_LDA import Ndx\nfrom speechbrain.processing.PLDA_LDA import fast_PLDA_scoring\nfrom speechbrain.utils.data_utils import download_file\nfrom speechbrain.utils.distributed import run_on_main\n\n\n# Compute embeddings from the waveforms\ndef compute_embeddings(wavs, wav_lens):\n \"\"\"Compute speaker embeddings.\n\n Arguments\n ---------\n wavs : Torch.Tensor\n Tensor containing the speech waveform (batch, time).\n Make sure the sample rate is fs=16000 Hz.\n wav_lens: Torch.Tensor\n Tensor containing the relative length for each sentence\n in the length (e.g., [0.8 0.6 1.0])\n \"\"\"\n wavs = wavs.to(params[\"device\"])\n wav_lens = wav_lens.to(params[\"device\"])\n with torch.no_grad():\n feats = params[\"compute_features\"](wavs)\n feats = params[\"mean_var_norm\"](feats, wav_lens)\n embeddings = params[\"embedding_model\"](feats, wav_lens)\n embeddings = params[\"mean_var_norm_emb\"](\n embeddings, torch.ones(embeddings.shape[0]).to(embeddings.device)\n )\n return embeddings.squeeze(1)\n\n\ndef emb_computation_loop(split, set_loader, stat_file):\n \"\"\"Computes the embeddings and saves the in a stat file\"\"\"\n # Extract embeddings (skip if already done)\n if not os.path.isfile(stat_file):\n embeddings = numpy.empty(\n shape=[0, params[\"emb_dim\"]], dtype=numpy.float64\n )\n modelset = []\n segset = []\n with tqdm(set_loader, dynamic_ncols=True) as t:\n for batch in t:\n ids = batch.id\n wavs, lens = batch.sig\n mod = [x for x in ids]\n seg = [x for x in ids]\n modelset = modelset + mod\n segset = segset + seg\n\n # Enrollment and test embeddings\n embs = compute_embeddings(wavs, lens)\n xv = embs.squeeze().cpu().numpy()\n embeddings = numpy.concatenate((embeddings, xv), axis=0)\n\n modelset = numpy.array(modelset, dtype=\"|O\")\n segset = numpy.array(segset, dtype=\"|O\")\n\n # Intialize variables for start, stop and stat0\n s = numpy.array([None] * embeddings.shape[0])\n b = numpy.array([[1.0]] * embeddings.shape[0])\n\n # Stat object (used to collect embeddings)\n stat_obj = StatObject_SB(\n modelset=modelset,\n segset=segset,\n start=s,\n stop=s,\n stat0=b,\n stat1=embeddings,\n )\n logger.info(f\"Saving stat obj for {split}\")\n stat_obj.save_stat_object(stat_file)\n\n else:\n logger.info(f\"Skipping embedding Extraction for {split}\")\n logger.info(f\"Loading previously saved stat_object for {split}\")\n\n with open(stat_file, \"rb\") as input:\n stat_obj = pickle.load(input)\n\n return stat_obj\n\n\ndef verification_performance(scores_plda):\n \"\"\"Computes the Equal Error Rate give the PLDA scores\"\"\"\n\n # Create ids, labels, and scoring list for EER evaluation\n ids = []\n labels = []\n positive_scores = []\n negative_scores = []\n for line in open(veri_file_path):\n lab = int(line.split(\" \")[0].rstrip().split(\".\")[0].strip())\n enrol_id = line.split(\" \")[1].rstrip().split(\".\")[0].strip()\n test_id = line.split(\" \")[2].rstrip().split(\".\")[0].strip()\n\n # Assuming enrol_id and test_id are unique\n i = int(numpy.where(scores_plda.modelset == enrol_id)[0][0])\n j = int(numpy.where(scores_plda.segset == test_id)[0][0])\n\n s = float(scores_plda.scoremat[i, j])\n labels.append(lab)\n ids.append(enrol_id + \"<>\" + test_id)\n if lab == 1:\n positive_scores.append(s)\n else:\n negative_scores.append(s)\n\n # Clean variable\n del scores_plda\n\n # Final EER computation\n eer, th = EER(torch.tensor(positive_scores), torch.tensor(negative_scores))\n min_dcf, th = minDCF(\n torch.tensor(positive_scores), torch.tensor(negative_scores)\n )\n return eer, min_dcf\n\n\n# Function to get mod and seg\ndef get_utt_ids_for_test(ids, data_dict):\n mod = [data_dict[x][\"wav1\"][\"data\"] for x in ids]\n seg = [data_dict[x][\"wav2\"][\"data\"] for x in ids]\n\n return mod, seg\n\n\ndef dataio_prep(params):\n \"Creates the dataloaders and their data processing pipelines.\"\n\n data_folder = params[\"data_folder\"]\n\n # 1. Declarations:\n\n # Train data (used for normalization)\n train_data = sb.dataio.dataset.DynamicItemDataset.from_csv(\n csv_path=params[\"train_data\"], replacements={\"data_root\": data_folder},\n )\n train_data = train_data.filtered_sorted(\n sort_key=\"duration\", select_n=params[\"n_train_snts\"]\n )\n\n # Enrol data\n enrol_data = sb.dataio.dataset.DynamicItemDataset.from_csv(\n csv_path=params[\"enrol_data\"], replacements={\"data_root\": data_folder},\n )\n enrol_data = enrol_data.filtered_sorted(sort_key=\"duration\")\n\n # Test data\n test_data = sb.dataio.dataset.DynamicItemDataset.from_csv(\n csv_path=params[\"test_data\"], replacements={\"data_root\": data_folder},\n )\n test_data = test_data.filtered_sorted(sort_key=\"duration\")\n\n datasets = [train_data, enrol_data, test_data]\n\n # 2. Define audio pipeline:\n @sb.utils.data_pipeline.takes(\"wav\", \"start\", \"stop\")\n @sb.utils.data_pipeline.provides(\"sig\")\n def audio_pipeline(wav, start, stop):\n start = int(start)\n stop = int(stop)\n num_frames = stop - start\n sig, fs = torchaudio.load(\n wav, num_frames=num_frames, frame_offset=start\n )\n sig = sig.transpose(0, 1).squeeze(1)\n return sig\n\n sb.dataio.dataset.add_dynamic_item(datasets, audio_pipeline)\n\n # 3. Set output:\n sb.dataio.dataset.set_output_keys(datasets, [\"id\", \"sig\", \"spk_id\"])\n\n # 4 Create dataloaders\n train_dataloader = sb.dataio.dataloader.make_dataloader(\n train_data, **params[\"train_dataloader_opts\"]\n )\n enrol_dataloader = sb.dataio.dataloader.make_dataloader(\n enrol_data, **params[\"enrol_dataloader_opts\"]\n )\n test_dataloader = sb.dataio.dataloader.make_dataloader(\n test_data, **params[\"test_dataloader_opts\"]\n )\n\n return train_dataloader, enrol_dataloader, test_dataloader\n\n\nif __name__ == \"__main__\":\n\n # Logger setup\n logger = logging.getLogger(__name__)\n current_dir = os.path.dirname(os.path.abspath(__file__))\n sys.path.append(os.path.dirname(current_dir))\n\n # Load hyperparameters file with command-line overrides\n params_file, run_opts, overrides = sb.core.parse_arguments(sys.argv[1:])\n with open(params_file) as fin:\n params = load_hyperpyyaml(fin, overrides)\n \n # Download verification list (to exlude verification sentences from train)\n veri_file_path = os.path.join(\n params[\"save_folder\"], os.path.basename(params[\"verification_file\"])\n )\n download_file(params[\"verification_file\"], veri_file_path)\n\n from voxceleb_prepare import prepare_voxceleb # noqa E402\n\n # Create experiment directory\n sb.core.create_experiment_directory(\n experiment_directory=params[\"output_folder\"],\n hyperparams_to_save=params_file,\n overrides=overrides,\n )\n\n # Prepare data from dev of Voxceleb1\n logger.info(\"Data preparation\")\n prepare_voxceleb(\n data_folder=params[\"data_folder\"],\n save_folder=params[\"save_folder\"],\n verification_pairs_file=veri_file_path,\n splits=[\"train\", \"test\"],\n split_ratio=[90, 10],\n seg_dur=3,\n )\n\n # here we create the datasets objects as well as tokenization and encoding\n train_dataloader, enrol_dataloader, test_dataloader = dataio_prep(params)\n\n # Initialize PLDA vars\n modelset, segset = [], []\n embeddings = numpy.empty(shape=[0, params[\"emb_dim\"]], dtype=numpy.float64)\n\n # Embedding file for train data\n xv_file = os.path.join(\n params[\"save_folder\"], \"VoxCeleb1_train_embeddings_stat_obj.pkl\"\n )\n \n # We download the pretrained LM from HuggingFace (or elsewhere depending on\n # the path given in the YAML file). The tokenizer is loaded at the same time.\n run_on_main(params[\"pretrainer\"].collect_files)\n params[\"pretrainer\"].load_collected()\n\n params[\"embedding_model\"].eval()\n params[\"embedding_model\"].to(params[\"device\"])\n \n # Computing training embeddings (skip it of if already extracted)\n if not os.path.exists(xv_file):\n logger.info(\"Extracting embeddings from Training set..\")\n with tqdm(train_dataloader, dynamic_ncols=True) as t:\n for batch in t:\n snt_id = batch.id\n wav, lens = batch.sig\n spk_ids = batch.spk_id\n\n # Flattening speaker ids\n modelset = modelset + spk_ids\n\n # For segset\n segset = segset + snt_id\n # Compute embeddings\n emb = compute_embeddings(wav, lens)\n xv = emb.squeeze(1).cpu().numpy()\n embeddings = numpy.concatenate((embeddings, xv), axis=0)\n\n # Speaker IDs and utterance IDs\n modelset = numpy.array(modelset, dtype=\"|O\")\n segset = numpy.array(segset, dtype=\"|O\")\n\n # Intialize variables for start, stop and stat0\n s = numpy.array([None] * embeddings.shape[0])\n b = numpy.array([[1.0]] * embeddings.shape[0])\n\n embeddings_stat = StatObject_SB(\n modelset=modelset,\n segset=segset,\n start=s,\n stop=s,\n stat0=b,\n stat1=embeddings,\n )\n\n del embeddings\n\n # Save TRAINING embeddings in StatObject_SB object\n embeddings_stat.save_stat_object(xv_file)\n\n else:\n # Load the saved stat object for train embedding\n logger.info(\"Skipping embedding Extraction for training set\")\n logger.info(\n \"Loading previously saved stat_object for train embeddings..\"\n )\n with open(xv_file, \"rb\") as input:\n embeddings_stat = pickle.load(input)\n\n # Training Gaussian PLDA model\n logger.info(\"Training PLDA model\")\n params[\"compute_plda\"].plda(embeddings_stat)\n logger.info(\"PLDA training completed\")\n\n # Set paths for enrol/test embeddings\n enrol_stat_file = os.path.join(params[\"save_folder\"], \"stat_enrol.pkl\")\n test_stat_file = os.path.join(params[\"save_folder\"], \"stat_test.pkl\")\n ndx_file = os.path.join(params[\"save_folder\"], \"ndx.pkl\")\n\n # Compute enrol and Test embeddings\n enrol_obj = emb_computation_loop(\"enrol\", enrol_dataloader, enrol_stat_file)\n test_obj = emb_computation_loop(\"test\", test_dataloader, test_stat_file)\n\n # Prepare Ndx Object\n if not os.path.isfile(ndx_file):\n models = enrol_obj.modelset\n testsegs = test_obj.modelset\n\n logger.info(\"Preparing Ndx\")\n ndx_obj = Ndx(models=models, testsegs=testsegs)\n logger.info(\"Saving ndx obj...\")\n ndx_obj.save_ndx_object(ndx_file)\n else:\n logger.info(\"Skipping Ndx preparation\")\n logger.info(\"Loading Ndx from disk\")\n with open(ndx_file, \"rb\") as input:\n ndx_obj = pickle.load(input)\n\n # PLDA scoring\n logger.info(\"PLDA scoring...\")\n scores_plda = fast_PLDA_scoring(\n enrol_obj,\n test_obj,\n ndx_obj,\n params[\"compute_plda\"].mean,\n params[\"compute_plda\"].F,\n params[\"compute_plda\"].Sigma,\n )\n\n logger.info(\"Computing EER... \")\n\n # Cleaning variable\n del enrol_dataloader\n del test_dataloader\n del enrol_obj\n del test_obj\n del embeddings_stat\n\n # Final EER computation\n eer, min_dcf = verification_performance(scores_plda)\n logger.info(\"EER(%%)=%f\", eer * 100)\n logger.info(\"min_dcf=%f\", min_dcf * 100)\n" ]
[ [ "torch.ones", "torch.tensor", "numpy.concatenate", "torch.no_grad", "numpy.array", "numpy.where", "numpy.empty" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
aforren1/ratcave
[ "e3862cdaba100ac2c6c78c08c4b09638e0c88fd4", "e3862cdaba100ac2c6c78c08c4b09638e0c88fd4", "e3862cdaba100ac2c6c78c08c4b09638e0c88fd4" ]
[ "ratcave/utils/vertices.py", "ratcave/coordinates.py", "ratcave/mesh.py" ]
[ "import itertools\nimport numpy as np\n\ndef pairwise(iterable):\n \"s -> (s0,s1), (s1,s2), (s2, s3), ...\"\n a, b = itertools.tee(iterable)\n next(b, None)\n return zip(a, b)\n\n\ndef struct_to_ndarray(array):\n \"\"\"Turns returns a view of a structured array as a regular ndarray.\"\"\"\n return array.view(array.dtype[0]).reshape((array.shape[0], -1))\n\n\ndef reindex_vertices(arrays=None):\n\n all_arrays = np.hstack(arrays)\n array_ncols = tuple(array.shape[1] for array in arrays)\n\n # Build a new array list, composed of only the unique combinations (no redundant data)\n row_searchable_array = all_arrays.view(all_arrays.dtype.descr * all_arrays.shape[1])\n unique_combs = np.sort(np.unique(row_searchable_array))\n\n new_indices = np.array([np.searchsorted(unique_combs, vert) for vert in row_searchable_array]).flatten().astype(np.uint32)\n\n ucombs = struct_to_ndarray(unique_combs)\n new_arrays = tuple(ucombs[:, start:end] for start, end in pairwise(np.append(0, np.cumsum(array_ncols))))\n new_arrays = tuple(np.array(array, dtype=np.float32) for array in new_arrays)\n return new_arrays, new_indices\n\n\ndef calculate_normals(vertices):\n \"\"\"Return Nx3 normal array from Nx3 vertex array.\"\"\"\n verts = np.array(vertices, dtype=float)\n normals = np.zeros_like(verts)\n for start, end in pairwise(np.arange(0, verts.shape[0] + 1, 3)):\n vecs = np.vstack((verts[start + 1] - verts[start], verts[start + 2] - verts[start])) # Get triangle of vertices and calculate 2-1 and 3-1\n vecs /= np.linalg.norm(vecs, axis=1, keepdims=True) # normalize vectors\n normal = np.cross(*vecs) # normal is the cross products of vectors.\n normals[start:end, :] = normal / np.linalg.norm(normal)\n return normals\n", "import numpy as np\nimport _transformations as trans\nfrom abc import ABCMeta, abstractmethod\nfrom ratcave.utils.observers import IterObservable\nimport itertools\nfrom operator import setitem\n\nclass Coordinates(IterObservable):\n\n coords = {'x': 0, 'y': 1, 'z': 2}\n\n def __init__(self, *args, **kwargs):\n \" Returns a Coordinates object\"\n super(Coordinates, self).__init__(**kwargs)\n self._array = np.array(args, dtype=np.float32)\n self._init_coord_properties()\n\n def __repr__(self):\n arg_str = ', '.join(['{}={}'.format(*el) for el in zip('xyz', self._array)])\n return \"{cls}({coords})\".format(cls=self.__class__.__name__, coords=arg_str)\n\n def _init_coord_properties(self):\n \"\"\"\n Generates combinations of named coordinate values, mapping them to the internal array.\n For Example: x, xy, xyz, y, yy, zyx, etc\n \"\"\"\n def gen_getter_setter_funs(*args):\n indices = [self.coords[coord] for coord in args]\n\n def getter(self):\n return tuple(self._array[indices]) if len(args) > 1 else self._array[indices[0]]\n\n def setter(self, value):\n setitem(self._array, indices, value)\n self.notify_observers()\n\n return getter, setter\n\n for n_repeats in range(1, len(self.coords)+1):\n for args in itertools.product(self.coords.keys(), repeat=n_repeats):\n getter, setter = gen_getter_setter_funs(*args)\n setattr(self.__class__, ''.join(args), property(fget=getter, fset=setter))\n\n def __getitem__(self, item):\n if type(item) == slice:\n return tuple(self._array[item])\n else:\n return self._array[item]\n\n def __setitem__(self, idx, value):\n self._array[idx] = value\n super(Coordinates, self).__setitem__(idx, value)\n\n\nclass RotationBase(object):\n __metaclass__ = ABCMeta\n\n @abstractmethod\n def to_quaternion(self): pass\n\n @abstractmethod\n def to_euler(self, units='rad'): pass\n\n @abstractmethod\n def to_matrix(self): pass\n\n @classmethod\n def from_matrix(cls, matrix): pass\n\n def rotate(self, vector):\n \"\"\"Takes a vector and returns it rotated by self.\"\"\"\n return np.dot(self.to_matrix()[:3, :3], vector).flatten()\n\n\nclass RotationEuler(RotationBase, Coordinates):\n\n def __init__(self, x, y, z, axes='rxyz', **kwargs):\n super(RotationEuler, self).__init__(x, y, z, **kwargs)\n self.axes = axes\n\n\nclass RotationEulerRadians(RotationEuler):\n\n def to_radians(self):\n return self\n\n def to_degrees(self):\n return RotationEulerDegrees(*np.degrees(self._array), axes=self.axes)\n\n def to_quaternion(self):\n return RotationQuaternion(*trans.quaternion_from_euler(*self._array, axes=self.axes))\n\n def to_matrix(self):\n return trans.euler_matrix(*self._array, axes=self.axes)\n\n def to_euler(self, units='rad'):\n assert units.lower() in ['rad', 'deg']\n if units.lower() == 'rad':\n return RotationEulerRadians(*self._array, axes=self.axes)\n else:\n return RotationEulerDegrees(*np.degrees(self._array), axes=self.axes)\n\n @classmethod\n def from_matrix(cls, matrix, axes='rxyz'):\n # Change to 4x4 if 3x3 rotation matrix is given\n if matrix.shape[0] == 3:\n mat = np.identity(4)\n mat[:3, :3] = matrix\n matrix = mat\n coords = trans.euler_from_matrix(matrix, axes=axes)\n return cls(*coords)\n\n\n\nclass RotationEulerDegrees(RotationEuler):\n def to_radians(self):\n return RotationEulerRadians(*np.radians(self._array), axes=self.axes)\n\n def to_degrees(self):\n return self\n\n def to_quaternion(self):\n return self.to_radians().to_quaternion()\n\n def to_euler(self, units='rad'):\n return self.to_radians().to_euler(units=units)\n\n def to_matrix(self):\n return self.to_radians().to_matrix()\n\n @classmethod\n def from_matrix(cls, matrix, axes='rxyz'):\n # Change to 4x4 if 3x3 rotation matrix is given\n if matrix.shape[0] == 3:\n mat = np.identity(4)\n mat[:3, :3] = matrix\n matrix = mat\n coords = trans.euler_from_matrix(matrix, axes=axes)\n return cls(*np.degrees(coords))\n\n\nclass RotationQuaternion(RotationBase, Coordinates):\n\n coords = {'w': 0, 'x': 1, 'y': 2, 'z': 3}\n\n def __init__(self, w, x, y, z, **kwargs):\n super(RotationQuaternion, self).__init__(w, x, y, z)\n\n def __repr__(self):\n arg_str = ', '.join(['{}={}'.format(*el) for el in zip('wxyz', self._array)])\n return \"{cls}({coords})\".format(cls=self.__class__.__name__, coords=arg_str)\n\n def to_quaternion(self):\n return self\n\n def to_matrix(self):\n return trans.quaternion_matrix(self._array)\n\n def to_euler(self, units='rad'):\n euler_data = trans.euler_from_matrix(self.to_matrix(), axes='rxyz')\n assert units.lower() in ['rad', 'deg']\n if units.lower() == 'rad':\n return RotationEulerRadians(*euler_data)\n else:\n return RotationEulerDegrees(*np.degrees(euler_data))\n\n @classmethod\n def from_matrix(cls, matrix):\n # Change to 4x4 if 3x3 rotation matrix is given\n if matrix.shape[0] == 3:\n mat = np.identity(4)\n mat[:3, :3] = matrix\n matrix = mat\n coords = trans.quaternion_from_matrix(matrix)\n return cls(*coords)\n\n\nclass Translation(Coordinates):\n\n def __init__(self, *args, **kwargs):\n assert len(args) == 3, \"Must be xyz coordinates\"\n super(Translation, self).__init__(*args, **kwargs)\n\n def __add__(self, other):\n oth = other.xyz if isinstance(other, Translation) else other\n if len(oth) != 3:\n raise ValueError(\"Other must have length of 3\")\n return Translation(*tuple(a + b for (a, b) in zip(self.xyz, oth)))\n\n def __sub__(self, other):\n oth = other.xyz if isinstance(other, Translation) else other\n if len(oth) != 3:\n raise ValueError(\"Other must have length of 3\")\n return Translation(*tuple(a - b for (a, b) in zip(self.xyz, other.xyz)))\n\n def to_matrix(self):\n return trans.translation_matrix(self._array)\n\n\nclass Scale(Coordinates):\n\n def __init__(self, *args, **kwargs):\n vals = args * 3 if len(args) == 1 else args\n assert len(vals) == 3, \"Must be xyz coordinates\"\n super(self.__class__, self).__init__(*vals, **kwargs)\n\n def to_matrix(self):\n return np.diag((self._array[0], self._array[1], self._array[2], 1.))\n\n\n\ndef cross_product_matrix(vec):\n \"\"\"Returns a 3x3 cross-product matrix from a 3-element vector.\"\"\"\n return np.array([[0, -vec[2], vec[1]],\n [vec[2], 0, -vec[0]],\n [-vec[1], vec[0], 0]])\n\n\ndef rotation_matrix_between_vectors(from_vec, to_vec):\n \"\"\"\n Returns a rotation matrix to rotate from 3d vector \"from_vec\" to 3d vector \"to_vec\".\n Equation from https://math.stackexchange.com/questions/180418/calculate-rotation-matrix-to-align-vector-a-to-vector-b-in-3d\n \"\"\"\n a, b = (trans.unit_vector(vec) for vec in (from_vec, to_vec))\n\n v = np.cross(a, b)\n cos = np.dot(a, b)\n if cos == -1.:\n raise ValueError(\"Orientation in complete opposite direction\")\n v_cpm = cross_product_matrix(v)\n rot_mat = np.identity(3) + v_cpm + np.dot(v_cpm, v_cpm) * (1. / 1. + cos)\n return rot_mat\n", "\"\"\"\nThis module contains the Mesh and EmptyEntity classes.\n\"\"\"\n\nimport pickle\nimport numpy as np\nfrom .utils import vertices as vertutils\nfrom .utils import NameLabelMixin\nfrom . import physical, shader\nfrom .texture import Texture\nfrom .vertex import VAO, VBO\nimport pyglet.gl as gl\nfrom copy import deepcopy\nfrom warnings import warn\n\n\ndef gen_fullscreen_quad(name='FullScreenQuad'):\n verts = np.array([[-1, -1, -.5], [-1, 1, -.5], [1, 1, -.5], [-1, -1, -.5], [1, 1, -.5], [1, -1, -.5]], dtype=np.float32)\n normals=np.array([[0, 0, 1]] * 6, dtype=np.float32)\n texcoords=np.array([[0, 0], [0, 1], [1, 1], [0, 0], [1, 1], [1, 0]], dtype=np.float32)\n return Mesh(name=name, arrays=(verts, normals, texcoords), mean_center=False)\n\n\nclass EmptyEntity(shader.HasUniformsUpdater, physical.PhysicalGraph, NameLabelMixin):\n \"\"\"Returns an EmptyEntity object that occupies physical space and uniforms, but doesn't draw anything when draw() is called.\"\"\"\n\n def draw(self, *args, **kwargs):\n \"\"\"Passes all given arguments\"\"\"\n pass\n\n def reset_uniforms(self):\n \"\"\"Passes alll given arguments\"\"\"\n pass\n\n\nclass Mesh(shader.HasUniformsUpdater, physical.PhysicalGraph, NameLabelMixin):\n\n triangles = gl.GL_TRIANGLES\n points = gl.GL_POINTS\n\n\n def __init__(self, arrays, textures=(), mean_center=True,\n gl_states=(), drawmode=gl.GL_TRIANGLES, point_size=15, dynamic=False, visible=True, **kwargs):\n \"\"\"\n Returns a Mesh object, containing the position, rotation, and color info of an OpenGL Mesh.\n\n Meshes have two coordinate system, the \"local\" and \"world\" systems, on which the transforms are performed\n sequentially. This allows them to be placed in the scene while maintaining a relative position to one another.\n\n .. note:: Meshes are not usually instantiated directly, but from a 3D file, like the WavefrontReader .obj and .mtl files.\n\n Args:\n arrays (tuple): a list of 2D arrays to be rendered. All arrays should have same number of rows. Arrays will be accessible in shader in same attrib location order.\n mean_center (bool):\n texture (Texture): a Texture instance, which is linked when the Mesh is rendered.\n gl_states:\n drawmode: specifies the OpenGL draw mode\n point_size (int): \n dynamic (bool): enables dynamic manipulation of vertices\n visible (bool): whether the Mesh is available to be rendered. To make hidden (invisible), set to False.\n\n Returns:\n Mesh instance\n \"\"\"\n\n super(Mesh, self).__init__(**kwargs)\n self.reset_uniforms()\n\n arrays = tuple(np.array(array, dtype=np.float32) for array in arrays)\n self.arrays, self.array_indices = vertutils.reindex_vertices(arrays)\n\n # Mean-center vertices and move position to vertex mean.\n vertex_mean = self.arrays[0][self.array_indices, :].mean(axis=0)\n\n if mean_center:\n self.arrays[0][:] -= vertex_mean\n if 'position' in kwargs:\n self.position.xyz = kwargs['position']\n elif mean_center:\n self.position.xyz = vertex_mean\n self._mean_center = mean_center\n # self.position.xyz = vertex_mean if not 'position' in kwargs else kwargs['position']\n\n # Change vertices from an Nx3 to an Nx4 array by appending ones. This makes some calculations more efficient.\n arrays = list(self.arrays)\n arrays[0] = np.append(self.arrays[0], np.ones((self.arrays[0].shape[0], 1), dtype=np.float32), axis=1)\n self.arrays = tuple(arrays)\n\n self.textures = list(textures)\n self.vao = None # Will be created upon first draw, when OpenGL context is available.\n self.gl_states = gl_states\n self.drawmode = drawmode\n self.point_size = point_size\n self.dynamic = dynamic\n self.visible = visible\n self.vbos = []\n\n\n def __repr__(self):\n return \"<Mesh(name='{self.name}', position_rel={self.position}, position_glob={self.position_global}, rotation={self.rotation})\".format(self=self)\n\n def copy(self):\n \"\"\"Returns a copy of the Mesh.\"\"\"\n return Mesh(arrays=deepcopy([arr.copy() for arr in [self.vertices, self.normals, self.texcoords]]), texture=self.textures, mean_center=deepcopy(self._mean_center),\n position=self.position.xyz, rotation=self.rotation.__class__(*self.rotation[:]), scale=self.scale.xyz,\n drawmode=self.drawmode, point_size=self.point_size, dynamic=self.dynamic, visible=self.visible,\n gl_states=deepcopy(self.gl_states))\n\n def to_pickle(self, filename):\n \"\"\"Save Mesh to a pickle file, given a filename.\"\"\"\n with open(filename, 'wb') as f:\n pickle.dump(self, f)\n\n @classmethod\n def from_pickle(cls, filename):\n \"\"\"Loads and Returns a Mesh from a pickle file, given a filename.\"\"\"\n with open(filename, 'rb') as f:\n mesh = pickle.load(f).copy()\n return mesh\n\n def reset_uniforms(self):\n \"\"\" Resets the uniforms to the Mesh object to the \"\"global\"\" coordinate system\"\"\"\n self.uniforms['model_matrix'] = self.model_matrix_global.view()\n self.uniforms['normal_matrix'] = self.normal_matrix_global.view()\n\n\n @property\n def dynamic(self):\n \"\"\"dynamic property of the mesh. If set to True, enables the user to modify vertices dynamically.\"\"\"\n return self._dynamic\n\n @dynamic.setter\n def dynamic(self, value):\n for array in self.arrays:\n array.setflags(write=True if value else False)\n self._dynamic = value\n\n\n @property\n def vertices(self):\n \"\"\"Mesh vertices, centered around 0,0,0.\"\"\"\n return self.arrays[0][:, :3].view()\n\n @vertices.setter\n def vertices(self, value):\n self.arrays[0][:, :3] = value\n\n @property\n def normals(self):\n \"\"\"Mesh normals array.\"\"\"\n return self.arrays[1][:, :3].view()\n\n @normals.setter\n def normals(self, value):\n self.arrays[1][:, :3] = value\n\n @property\n def texcoords(self):\n \"\"\"UV coordinates\"\"\"\n return self.arrays[2][:, :2].view()\n\n @texcoords.setter\n def texcoords(self, value):\n self.arrays[2][:, :2] = value\n\n @property\n def vertices_local(self):\n \"\"\"Vertex position, in local coordinate space (modified by model_matrix)\"\"\"\n return np.dot(self.model_matrix, self.vertices)\n\n @property\n def vertices_global(self):\n \"\"\"Vertex position, in world coordinate space (modified by model_matrix)\"\"\"\n return np.dot(self.model_matrix_global, self.vertices)\n\n @property\n def texture(self):\n raise DeprecationWarning(\"Mesh.texture no longer exists. Instead, please append textures to the Mesh.textures list.\")\n\n @texture.setter\n def texture(self, value):\n raise DeprecationWarning(\"Mesh.texture no longer exists. Instead, please append textures to the Mesh.textures list.\")\n\n @classmethod\n def from_incomplete_data(cls, vertices, normals=(), texcoords=(), **kwargs):\n \"\"\"Return a Mesh with (vertices, normals, texcoords) as arrays, in that order.\n Useful for when you want a standardized array location format across different amounts of info in each mesh.\"\"\"\n normals = normals if hasattr(texcoords, '__iter__') and len(normals) else vertutils.calculate_normals(vertices)\n texcoords = texcoords if hasattr(texcoords, '__iter__') and len(texcoords) else np.zeros((vertices.shape[0], 2), dtype=np.float32)\n return cls(arrays=(vertices, normals, texcoords), **kwargs)\n\n def _fill_vao(self):\n \"\"\"Put array location in VAO for shader in same order as arrays given to Mesh.\"\"\"\n with self.vao:\n self.vbos = []\n for loc, verts in enumerate(self.arrays):\n vbo = VBO(verts)\n self.vbos.append(vbo)\n self.vao.assign_vertex_attrib_location(vbo, loc)\n\n def draw(self):\n \"\"\" Draw the Mesh if it's visible, from the perspective of the camera and lit by the light. The function sends the uniforms\"\"\"\n if not self.vao:\n self.vao = VAO(indices=self.array_indices)\n self._fill_vao()\n\n if self.visible:\n if self.dynamic:\n for vbo in self.vbos:\n vbo._buffer_subdata()\n\n if self.drawmode == gl.GL_POINTS:\n gl.glPointSize(self.point_size)\n\n for texture in self.textures:\n texture.bind()\n\n with self.vao as vao:\n self.uniforms.send()\n vao.draw(mode=self.drawmode)\n\n for texture in self.textures:\n texture.unbind()\n" ]
[ [ "numpy.hstack", "numpy.unique", "numpy.arange", "numpy.linalg.norm", "numpy.cumsum", "numpy.zeros_like", "numpy.searchsorted", "numpy.cross", "numpy.array", "numpy.vstack" ], [ "numpy.diag", "numpy.dot", "numpy.radians", "numpy.degrees", "numpy.identity", "numpy.cross", "numpy.array" ], [ "numpy.dot", "numpy.array", "numpy.zeros", "numpy.ones" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
sungcheolkim78/py_kbible
[ "3a576c20e5e49f5e85be6ddede20accb6df14663" ]
[ "py_kbible/kbible.py" ]
[ "\"\"\"\nkbible.py - base bible object and commands\n\"\"\"\n\nimport pandas as pd\nimport yaml\nimport os\nimport subprocess\n\n__author__ = \"Sungcheol Kim <[email protected]>\"\n__docformat__ = \"restructuredtext en\"\n\nclass KBible(object):\n \"\"\" Bible text object \"\"\"\n\n def __init__(self, version=\"개역한글판성경\", debug=False, **kwargs):\n \"\"\" read or parse bible text \"\"\"\n\n self._biblelist = []\n self._versionlist = {}\n\n this_dir, this_filename = os.path.split(__file__)\n listname = os.path.join(this_dir, \"data\", u\"book_names.csv\")\n self._table = pd.read_csv(listname, index_col=0)\n\n self.add(version, **kwargs)\n\n def add(self, version, **kwargs):\n \"\"\" add different version \"\"\"\n b = read_full_bible(version_name=version, **kwargs)\n self._biblelist.append(b)\n self._versionlist[version] = len(self._biblelist) - 1\n\n def delete(self, version):\n \"\"\" remove version \"\"\"\n if (version in self._versionlist) and (len(self._versionlist) > 1):\n i = self._versionlist[version]\n del self._versionlist[version]\n del self._biblelist[i]\n else:\n print('... not found or only have one bible version: {}'.format(version))\n\n def save(self, version=\"개역한글판성경\"):\n \"\"\" save bible text as compressed csv \"\"\"\n\n if version in self._versionlist:\n this_dir, this_filename = os.path.split(__file__)\n filename = os.path.join(this_dir, \"data\", version + \".csv.gz\")\n\n b = self._biblelist[self._versionlist[version]]\n b.to_csv(filename, compression='gzip')\n print('... save file: {}'.format(filename))\n\n def get(self, version=\"\"):\n \"\"\" return bible as pandas \"\"\"\n\n if version == \"\":\n return self._biblelist[0]\n\n try:\n return self._biblelist[self._versionlist[version]]\n except:\n print('... no bible version: {}'.format(version))\n return []\n\n def bystr(self, sstr, form=\"md\"):\n \"\"\" extract bible verse \"\"\"\n\n if form == \"pd\":\n res = pd.DataFrame()\n for b in self._biblelist:\n res = pd.concat([res, extract_bystr(b, sstr, form=\"pd\")], axis=0)\n return res\n else:\n msg = \"\"\n for b in self._biblelist:\n msg = msg + extract_bystr(b, sstr, form=form) + '\\n'\n return msg\n\n def search(self, sstr, form=\"md\", regex=False):\n \"\"\" search string in bible \"\"\"\n\n res = pd.DataFrame()\n for b in self._biblelist:\n b_res_idx = b.text.str.contains(sstr, regex=regex)\n if sum(b_res_idx) > 0:\n res = pd.concat([res, b[b_res_idx]], axis=0)\n\n if len(res) > 0:\n return get_texts(res, form=form)\n else:\n print('... no matched results')\n return []\n\n def read(self, sstr, form='mdlines'):\n \"\"\" search by short index string and show in markdown file \"\"\"\n\n msg = self.bystr(sstr, form=form)\n\n with open('.temp.md', 'w') as f:\n f.writelines(msg)\n\n cmd = ['open', '.temp.md']\n subprocess.call(cmd)\n\n\ndef bible_parser(version_name=\"개역한글판성경\"):\n \"\"\" read bible text and return panda database\n inputs:\n version_name : available versions 개역한글판성경, 개역개정판성경\n output:\n bible panda dataframe as short version\n \"\"\"\n\n # read bible txt file\n this_dir, this_filename = os.path.split(__file__)\n filename = os.path.join(this_dir, \"data\", version_name + \".txt\")\n with open(filename, \"r\") as f:\n lines = f.readlines()\n\n # prepare data container\n books = []\n chapters = []\n verses = []\n texts = []\n\n for i, line in enumerate(lines):\n line = line.strip('\\n\\r')\n\n # check comment line\n if len(line) == 0:\n continue\n if line[0] == \"#\":\n continue\n if line.find(':') == -1:\n continue\n\n # find header\n hp = line.find(' ')\n if hp > 1 and hp < 25:\n header = line[:hp]\n text = line[hp+1:]\n\n # find book, chapter, verse, text\n try:\n tmp = header.split(':')[0]\n if tmp.find('.') > 0: # english bible short name\n book = tmp.split('.')[0]\n chapter = tmp.split('.')[1]\n elif tmp[:2] in [\"1_\", \"2_\", \"3_\"]: # english bible long name\n book = tmp[:2] + ''.join(filter(str.isalpha, tmp[2:]))\n chapter = ''.join(filter(str.isdigit, tmp[2:]))\n else: # korean bible\n book = ''.join(filter(str.isalpha, tmp))\n chapter = ''.join(filter(str.isdigit, tmp))\n verse = header.split(':')[1]\n except:\n print('... header error: ({}) {}'.format(i, header))\n continue\n\n # convert data\n try:\n verse = int(verse)\n chapter = int(chapter)\n except:\n print(\"... conversion error: ({}) {} {}\".format(i, verse, chapter))\n continue\n\n # collect\n books.append(book)\n chapters.append(chapter)\n verses.append(verse)\n texts.append(text)\n else:\n print(\"... unrecognized line: ({}) {}\".format(i, line))\n\n df_bible = {'book':books, 'chapter':chapters, 'verse':verses, 'text':texts}\n idx = range(len(books))\n bible = pd.DataFrame(data=df_bible, index=idx)\n\n return bible\n\n\ndef read_full_bible(version_name=\"개역한글판성경\", save=False):\n \"\"\" read bible version and combine book data\n inputs:\n version_name: bible version\n save: [True|False]\n output:\n bible panda dataframe\n \"\"\"\n\n try:\n this_dir, this_filename = os.path.split(__file__)\n filename = os.path.join(this_dir, \"data\", version_name + \".csv.gz\")\n full_bible = pd.read_csv(filename, index_col=0, compression = \"gzip\")\n return full_bible\n except FileNotFoundError:\n print('... generate bible database: {}'.format(filename))\n\n bible = bible_parser(version_name=version_name)\n\n listname = os.path.join(this_dir, \"data\", u\"book_names.csv\")\n table = pd.read_csv(listname, index_col=0)\n\n if bible['book'][0] == 'Gen':\n table['book'] = table['eng_short']\n elif bible['book'][0] == 'Genesis':\n table['book'] = table['eng']\n else:\n table['book'] = table['kor_short']\n\n full_bible = pd.merge(bible, table, on='book', how='left')\n\n if save:\n full_bible.to_csv(filename, compression='gzip')\n\n return full_bible\n\n\ndef find_id(bible, book=[], chapter=[], verse=[], verb=False):\n \"\"\" find index on full bible database\n inputs:\n bible: bible panda database\n book: book names as list\n chapter: chapters as list\n verse: verses as list\n verb: [True|False] show details\n output:\n panda dataframe filtered by all combination of book, chapter, verses\n \"\"\"\n\n isfullbible = False\n\n # check books\n books = set(bible['book'])\n if \"code\" in bible.columns:\n isfullbible = True\n\n if len(book) == 0:\n book = books[0]\n if isinstance(book, str):\n book = [book]\n\n if verb: print('... search book:{}'.format(book))\n if isfullbible:\n result = bible.loc[bible.kor.isin(book) | bible.kor_short.isin(book) | bible.eng.isin(book) | bible.eng_short.isin(book) | bible.book.isin(book)]\n else:\n result = bible.loc[bible.book.isin(book)]\n\n # check chapter\n if isinstance(chapter, int):\n chapter = [chapter]\n if len(chapter) == 0:\n return result\n\n if verb: print('... search chapter: {}'.format(chapter))\n result = result.loc[bible.chapter.isin(chapter)]\n\n # check verse\n if isinstance(verse, int):\n verse = [verse]\n if len(verse) == 0:\n return result\n\n if verb: print('... search verse: {}'.format(verse))\n result = result.loc[bible.verse.isin(verse)]\n\n if len(result) > 0:\n return result\n else:\n print(\"... not found: {}, {}, {}\".format(book, chapter, verse))\n return []\n\n\ndef extract_bystr(bible, sstr, form=\"pd\"):\n \"\"\" extract verse by short search string\n inputs:\n bible: panda database of bible version\n sstr: search pattern\n - example \"창3:16\", \"고후5:3\", '요일1:1', \"창세기1:1\"\n - no spaces\n - one separator :\n - ',' and '-' is possible (창3:16,17) (창1:1-5)\n form: output format\n - \"md\" one line sentence with markdowm\n - \"string\" text string\n - \"pd\" panda dataframe\n output:\n object determined by form variable\n \"\"\"\n\n # remove all spaces\n sstr = sstr.replace(\" \", \"\")\n\n # find components\n if sstr.find(\":\") > 0:\n head = sstr.split(':')[0]\n verses = sstr.split(':')[1]\n else:\n head = sstr\n verses = []\n\n book = ''.join(filter(str.isalpha, head))\n chapter = ''.join(filter(str.isdigit, head))\n\n # if there is no chapter\n if len(chapter) == 0:\n chapter = []\n else:\n chapter = int(chapter)\n\n # check , in verse\n if len(verses) > 0:\n if verses.find(',') > 0:\n verses = verses.split(',')\n # check - in verse\n elif verses.find('-') > 0:\n start = verses.split('-')[0]\n end = verses.split('-')[1]\n try:\n verses = list(range(int(start), int(end)+1))\n except:\n print('... wrong format: {}'.format(sstr))\n return 0\n else:\n verses = [int(verses)]\n\n verses = [int(v) for v in verses]\n\n #print(book, chapter, verses)\n\n # return verses\n res = find_id(bible, book=book, chapter=chapter, verse=verses)\n if len(res) == 0:\n return []\n\n return get_texts(res, form=form, sstr=sstr)\n\n\ndef get_texts(bible_pd, form=\"md\", sstr=\"\", sep=\"\", text_width=0):\n \"\"\" print verses using different format \"\"\"\n\n if form == \"pd\":\n return bible_pd\n\n if len(bible_pd[\"book\"]) == 0:\n return \"\"\n\n # show id as kor_short\n bible_pd.loc[:, \"id\"] = bible_pd.loc[:, \"kor_short\"] + sep + bible_pd[\"chapter\"].astype(str) + \":\" + bible_pd[\"verse\"].astype(str)\n bible_pd = tidy_footnote(bible_pd)\n\n if (len(set(bible_pd[\"book\"])) == 1) and (sstr.find(\":\") == -1):\n min_v = bible_pd[\"verse\"].min()\n max_v = bible_pd[\"verse\"].max()\n sstr = \"{}:{}-{}\".format(sstr, min_v, max_v)\n\n if form == \"string\":\n if sstr == \"\":\n bible_pd[form] = bible_pd[\"id\"] + \" - \" + bible_pd[form].astype(str)\n msg = '\\n'.join(bible_pd[form].values)\n else:\n msg = sstr + ' ' + ' '.join(bible_pd[form].values)\n return msg\n\n if form == \"md\":\n if sstr == \"\":\n bible_pd[form] = \"`\" + bible_pd[\"id\"] + \"` \" + bible_pd[form].astype(str)\n msg = '\\n'.join(bible_pd[form].values)\n else:\n verse_string_list = [ '<sup>{}</sup> {}'.format(v, l) for v,l in zip(bible_pd['verse'], bible_pd[form]) ]\n msg = '`{}` '.format(sstr) + ' '.join(verse_string_list)\n\n if sum(bible_pd[\"footnote\"] != \"\") > 0:\n return msg + '\\n' + ''.join(bible_pd[\"footnote\"].values)\n else:\n return msg\n\n if form == \"mdlines\":\n bible_pd[\"md\"] = \"`\" + bible_pd[\"id\"] + \"` \" + bible_pd[\"md\"].astype(str)\n msg = '\\n'.join(bible_pd[\"md\"].values)\n\n if sum(bible_pd[\"footnote\"] != \"\") > 0:\n return msg + '\\n' + ''.join(bible_pd[\"footnote\"].values)\n else:\n return msg\n\n print('... {} format is not implemented: [\"pd\", \"md\", \"string\"]'.format(form))\n return []\n\n\ndef tidy_footnote(bible_pd, keyword=\"FOOTNOTE\"):\n \"\"\" remove footnote \"\"\"\n\n bible_pd[\"md\"] = bible_pd[\"text\"]\n bible_pd[\"string\"] = bible_pd[\"text\"]\n bible_pd[\"footnote\"] = \"\"\n\n start_word = \"__a__{}__a__\".format(keyword)\n end_word = \"__b__{}__b__\".format(keyword)\n fn_idx = [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\"]\n\n # search different verses\n for i in bible_pd.index[bible_pd.text.str.contains(start_word)]:\n # search in one verse\n text = bible_pd.at[i, \"text\"]\n tmp = text.replace(\"_b_\", \"_a_\").split(start_word)\n\n bible_pd.at[i, \"string\"] = tmp[0] + ''.join(tmp[2::2])\n\n # check multiple footnotes\n md = tmp[0]\n fn = \"\"\n for j in range(int(len(tmp)/2)):\n md = md + \"[^{}{}]\".format(bible_pd.at[i, \"id\"], fn_idx[j]) + tmp[j*2 + 2]\n fn = fn + \"[^{}{}]:\".format(bible_pd.at[i, \"id\"], fn_idx[j]) + tmp[j*2 + 1].replace(\"TR\",\"\") + '\\n'\n\n bible_pd.at[i, \"md\"] = md\n bible_pd.at[i, \"footnote\"] = fn\n\n return bible_pd\n\n\ndef make_mdpage(bible, day_info, save_dir=None):\n \"\"\" print all verses in list using markdown format\n inputs:\n bible: name of version or panda dataframe\n day_info: name of day information file or yaml data\n save: [True|False]\n output:\n text strings of markdown page\n \"\"\"\n\n # check day_info.yml file\n if isinstance(day_info, str):\n try:\n with open(day_info, \"r\") as f:\n day_info = yaml.load(f, yaml.BaseLoader)\n except:\n print(\"... file: {} parser error!\".format(day_info))\n return 0\n\n bible_version = \"\"\n # check bible version\n if isinstance(bible, str):\n try:\n bible_version = \"-\" + bible\n bible = read_full_bible(bible)\n except:\n print(\"... read bible error: {}\".format(bible_version[1:]))\n return 0\n\n msg = \"# {}일차 - {}\\n\\n\".format(day_info[\"day\"],day_info[\"title\"])\n msg = msg + \"찬양 : {}\\n\\n\".format(day_info[\"song\"])\n msg = msg + \"기도 : {}\\n\\n\".format(day_info[\"prayer\"])\n msg = msg + \"요약 : {}\\n\\n\".format(day_info[\"summary\"])\n msg = msg + \"성경 버전 : {}\\n\\n\".format(bible_version[1:])\n\n for v in day_info[\"verses\"]:\n msg = msg + '- {}\\n\\n'.format(extract_bystr(bible, v, form=\"md\"))\n\n msg = msg + \"### info\\n\\n\"\n msg = msg + \"- 성경 구절 갯수 : {}\".format(len(day_info[\"verses\"]))\n\n if save_dir is not None:\n filename = '{}/day{}-{}{}.md'.format(save_dir, day_info[\"day\"], day_info[\"title\"].replace(\" \", \"\"), bible_version)\n with open(filename, \"w\") as f:\n f.write(msg)\n print('... save to {}'.format(filename))\n\n return msg\n" ]
[ [ "pandas.merge", "pandas.read_csv", "pandas.concat", "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] } ]
imaroger/sot-talos-balance
[ "5e56700b4e105273ecf6feb3474789beac469a77" ]
[ "src/sot_talos_balance/test/test_zmpEstimator.py" ]
[ "from time import sleep\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom sot_talos_balance.utils.run_test_utils import evalCommandClient, run_ft_calibration, run_test, runCommandClient\n\ntry:\n # Python 2\n input = raw_input # noqa\nexcept NameError:\n pass\n\nrun_test('appli_zmpEstimator.py')\n\nrun_ft_calibration('robot.ftc')\ninput(\"Wait before running the test\")\n\n# plug ZMP emergency signal\nrunCommandClient('plug(robot.zmp_estimator.emergencyStop,robot.cm.emergencyStop_zmp)')\nsleep(2.0)\nrunCommandClient('robot.comTrajGen.move(1,-0.025,1.0)')\nsleep(20.0)\nrunCommandClient('robot.comTrajGen.startSinusoid(1,0.05,2.0)')\nsleep(20.0)\n\nrunCommandClient('dump_tracer(robot.tracer)')\n\n# --- DISPLAY\nzmpEst_data = np.loadtxt('/tmp/dg_' + evalCommandClient('robot.zmp_estimator.name') + '-zmp.dat')\nzmpDyn_data = np.loadtxt('/tmp/dg_' + evalCommandClient('robot.dynamic.name') + '-zmp.dat')\ncom_data = np.loadtxt('/tmp/dg_' + evalCommandClient('robot.dynamic.name') + '-com.dat')\nforceRLEG_data = np.loadtxt('/tmp/dg_' + evalCommandClient('robot.device.name') + '-forceRLEG.dat')\nforceLLEG_data = np.loadtxt('/tmp/dg_' + evalCommandClient('robot.device.name') + '-forceLLEG.dat')\n\nplt.ion()\n\nplt.figure()\nplt.plot(zmpEst_data[:, 1], 'b-')\nplt.plot(zmpDyn_data[:, 1], 'b--')\nplt.plot(com_data[:, 1], 'b:')\nplt.plot(zmpEst_data[:, 2], 'r-')\nplt.plot(zmpDyn_data[:, 2], 'r--')\nplt.plot(com_data[:, 2], 'r:')\nplt.title('ZMP estimate vs dynamic vs CoM (planar)')\nplt.legend(['x estimate', 'x dynamic', 'x CoM', 'y estimate', 'y dynamic', 'y CoM'])\n\nplt.figure()\nplt.plot(com_data[:, 1], 'b-')\nplt.plot(com_data[:, 2], 'r-')\nplt.plot(com_data[:, 3], 'g-')\nplt.title('COM')\nplt.legend(['x', 'y', 'z'])\n\nplt.figure()\nplt.plot(zmpDyn_data[:, 1], 'b-')\nplt.plot(zmpDyn_data[:, 2], 'r-')\nplt.plot(zmpDyn_data[:, 3], 'g-')\nplt.title('ZMP dynamic')\nplt.legend(['x', 'y', 'z'])\n\nplt.figure()\nplt.plot(zmpEst_data[:, 1], 'b-')\nplt.plot(zmpEst_data[:, 2], 'r-')\nplt.plot(zmpEst_data[:, 3], 'g-')\nplt.title('ZMP estimate')\nplt.legend(['x', 'y', 'z'])\n\nplt.figure()\nplt.plot(forceLLEG_data[:, 1], 'b-')\nplt.plot(forceLLEG_data[:, 2], 'r-')\nplt.plot(forceLLEG_data[:, 3], 'g-')\nplt.plot(forceLLEG_data[:, 4], 'b--')\nplt.plot(forceLLEG_data[:, 5], 'r--')\nplt.plot(forceLLEG_data[:, 6], 'g--')\nplt.title('forceLLEG')\nplt.legend(['fx', 'fy', 'fz', 'tx', 'ty', 'tz'])\n\nplt.figure()\nplt.plot(forceRLEG_data[:, 1], 'b-')\nplt.plot(forceRLEG_data[:, 2], 'r-')\nplt.plot(forceRLEG_data[:, 3], 'g-')\nplt.plot(forceRLEG_data[:, 4], 'b--')\nplt.plot(forceRLEG_data[:, 5], 'r--')\nplt.plot(forceRLEG_data[:, 6], 'g--')\nplt.title('forceRLEG')\nplt.legend(['fx', 'fy', 'fz', 'tx', 'ty', 'tz'])\n\ninput(\"Wait before leaving the simulation\")\n" ]
[ [ "matplotlib.pyplot.legend", "matplotlib.pyplot.title", "matplotlib.pyplot.plot", "matplotlib.pyplot.ion", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jonathan-sung/Hexapod-GA-Gait
[ "5e82c2f141f6bd88d8b6c0a7b658c8ce0c5be8f4" ]
[ "hexapodengine2.py" ]
[ "import pybullet as p\nimport math\nimport pybullet_data\nimport time\nimport random\nimport numpy as np\nimport serial\n\n\ndef radToPwm(angle):\n return ((2000 * angle) / math.pi) + 1500\n\n\n# t in ms; the closer t is to 0, more accuracy but less smooth motion\ndef updateRealServos(ser, t):\n # right legs\n ser.write(\n f'#0P{radToPwm(-p.getJointState(hexapod_ID, 8)[0])}T{t}#1P{radToPwm(p.getJointState(hexapod_ID, 9)[0])}T{t}#2P{radToPwm(-p.getJointState(hexapod_ID, 10)[0])-100}T{t}\\r'.encode(\n 'utf-8'))\n ser.write(\n f'#4P{radToPwm(-p.getJointState(hexapod_ID, 4)[0])}T{t}#5P{radToPwm(p.getJointState(hexapod_ID, 5)[0])}T{t}#6P{radToPwm(-p.getJointState(hexapod_ID, 6)[0])+100}T{t}\\r'.encode(\n 'utf-8'))\n ser.write(\n f'#8P{radToPwm(-p.getJointState(hexapod_ID, 0)[0])}T{t}#9P{radToPwm(p.getJointState(hexapod_ID, 1)[0])}T{t}#10P{radToPwm(-p.getJointState(hexapod_ID, 2)[0])}T{t}\\r'.encode(\n 'utf-8'))\n\n # left legs\n ser.write(\n f'#24P{radToPwm(-p.getJointState(hexapod_ID, 12)[0])}T{t}#25P{radToPwm(p.getJointState(hexapod_ID, 13)[0])}T{t}#26P{radToPwm(-p.getJointState(hexapod_ID, 14)[0])+100}T{t}\\r'.encode(\n 'utf-8'))\n ser.write(\n f'#20P{radToPwm(-p.getJointState(hexapod_ID, 16)[0])}T{t}#21P{radToPwm(p.getJointState(hexapod_ID, 17)[0])}T{t}#22P{radToPwm(-p.getJointState(hexapod_ID, 18)[0])}T{t}\\r'.encode(\n 'utf-8'))\n ser.write(\n f'#16P{radToPwm(-p.getJointState(hexapod_ID, 20)[0])}T{t}#17P{radToPwm(p.getJointState(hexapod_ID, 21)[0])}T{t}#18P{radToPwm(-p.getJointState(hexapod_ID, 22)[0])-50}T{t}\\r'.encode(\n 'utf-8'))\n\n\ndef init_debug_parameters():\n for j in list(range(0, 6)):\n control_IDs.append(p.addUserDebugParameter(f\"Pelvis {j}\", -servoRangeOfMotion, servoRangeOfMotion, 0))\n control_IDs.append(p.addUserDebugParameter(f\"Hip {j}\", -servoRangeOfMotion, servoRangeOfMotion, 0))\n control_IDs.append(p.addUserDebugParameter(f\"Knee {j}\", -servoRangeOfMotion, servoRangeOfMotion, 0))\n\n\ndef read_debug_parameters():\n angles = []\n for x in control_IDs:\n angles.append(p.readUserDebugParameter(x))\n return angles\n\n\ndef chromosomeCreator():\n pos = []\n duration = 1\n force = 200\n # pos.extend([duration] + [0] * NUM_OF_SERVOS)\n for j in range(LENGTH_OF_SEQUENCE - 1):\n gaitState = [0] * NUM_OF_SERVOS\n gaitState[j] = servoRangeOfMotion\n pos.extend([duration] + gaitState)\n print(len(pos))\n return [duration] + [force] + pos\n\n\ndef readGait(progress, chromosome):\n global firstCycleComplete\n end_index = LENGTH_OF_SEQUENCE\n if not firstCycleComplete and progress >= sum([chromosome[x] for x in range(0, len(chromosome), LENGTH_OF_GAIT_STATE)]):\n firstCycleComplete = True\n if firstCycleComplete:\n progress = progress - sum([chromosome[x] for x in range(0, ((LENGTH_OF_START_SEQUENCE - 1) * LENGTH_OF_GAIT_STATE) + 1, LENGTH_OF_GAIT_STATE)])\n chromosome = chromosome[LENGTH_OF_START_SEQUENCE * LENGTH_OF_GAIT_STATE:]\n end_index = LENGTH_OF_CYCLE\n start_index = 0\n total_duration = sum([chromosome[x] for x in range(0, len(chromosome), LENGTH_OF_GAIT_STATE)])\n # duration_of_start_sequence = sum([chromosome[x] for x in range(0, ((LENGTH_OF_START_SEQUENCE - 1) * LENGTH_OF_GAIT_STATE) + 1, LENGTH_OF_GAIT_STATE)])\n # duration_of_cycle = total_duration - duration_of_start_sequence\n progress = progress % total_duration\n current_duration_index = 0\n next_duration_index = 0\n sum_of_durations = 0\n for j in range(start_index, end_index):\n current_position_index = j * LENGTH_OF_GAIT_STATE\n sum_of_durations = sum([chromosome[x] for x in range(start_index, current_position_index + 1, LENGTH_OF_GAIT_STATE)])\n if progress < sum_of_durations:\n current_duration_index = current_position_index\n next_duration_index = (j + 1) * LENGTH_OF_GAIT_STATE\n if (j + 1) >= end_index:\n next_duration_index = start_index * LENGTH_OF_GAIT_STATE\n break\n current_gait_state = chromosome[current_duration_index + 1: current_duration_index + LENGTH_OF_GAIT_STATE]\n next_gait_state = chromosome[next_duration_index + 1: next_duration_index + LENGTH_OF_GAIT_STATE]\n if not firstCycleComplete and current_duration_index == (LENGTH_OF_SEQUENCE - 1) * LENGTH_OF_GAIT_STATE:\n next_gait_state = chromosome[(LENGTH_OF_START_SEQUENCE * LENGTH_OF_GAIT_STATE) + 1: (LENGTH_OF_START_SEQUENCE * LENGTH_OF_GAIT_STATE) + LENGTH_OF_GAIT_STATE]\n alpha = (progress - (sum_of_durations - chromosome[current_duration_index])) / chromosome[current_duration_index]\n interpolated_gait_state = [interpolate(a, b, alpha) for a, b in zip(current_gait_state, next_gait_state)]\n # print(progress, alpha, sum_of_durations, chromosome[current_duration_index])\n return interpolated_gait_state\n\n\ndef interpolate(a, b, alpha):\n return a * (1 - alpha) + b * alpha\n\n\ndef resetLegJoints():\n p.resetJointStatesMultiDof(hexapod_ID, JOINT_INDEXES, [[0]] * 18, targetVelocities=[[0]] * 18)\n p.setJointMotorControlArray(hexapod_ID, JOINT_INDEXES, p.POSITION_CONTROL, targetPositions=([0] * 18), forces=([150] * 18))\n\n\ndef resetEnvironment():\n resetLegJoints()\n p.resetBasePositionAndOrientation(hexapod_ID, [0, STARTING_Y, STARTING_HEIGHT + random.uniform(0, 0.002)], [0, 0, 0, 1])\n p.stepSimulation()\n\n\ndef resetPyBulletSimulation():\n global plane_ID\n global hexapod_ID\n p.resetSimulation()\n p.setGravity(0, 0, -9.8)\n plane_ID = p.loadURDF(\"plane.urdf\", globalScaling=4)\n # testAngle = p.getQuaternionFromEuler([0, math.pi/2, math.pi])\n hexapod_ID = p.loadURDF(\"robot3.urdf\", [0, STARTING_Y, STARTING_HEIGHT + random.uniform(0, 0.002)], [0, 0, 0, 1])\n print(p.getEulerFromQuaternion(p.getBasePositionAndOrientation(hexapod_ID)[1]))\n\n\ndef gaitScore(bodyID):\n current_position = p.getBasePositionAndOrientation(bodyID)[0]\n distance = distanceFromOrigin(bodyID)\n angle = angleBetweenVectors(np.array([0, 1]), np.array([current_position[0], current_position[1]]))\n return distance, abs(angle)\n\n\ndef distanceFromOrigin(bodyID):\n return p.getBasePositionAndOrientation(bodyID)[0][1]\n\n\ndef angleBetweenVectors(a, b):\n unit_vector_1 = a / np.linalg.norm(a)\n unit_vector_2 = b / np.linalg.norm(b)\n dot_product = np.dot(unit_vector_1, unit_vector_2)\n angle = np.arccos(dot_product)\n return angle\n\n\ndef inverseCurve(x, a):\n # 1/e^2 = 0.135\n # a = 0.135\n # a = 1\n # (pi/2.0)^2 = 2.467\n # a = 2.467\n y = a / (a + (x * x))\n return y\n\n\ndef collidingLegs():\n # numOfCollisions = 0\n for j in range(24):\n aabb = (p.getAABB(hexapod_ID, j))\n familyOfLinks = [x for x in range(24) if math.floor(j / 4) == math.floor(x / 4)] + [-1]\n # collisionObjects = [x[1] for x in p.getOverlappingObjects(aabb[0], aabb[1]) if x[1] not in familyOfLinks and (j not in FEET_INDEXES or x[0] == hexapod_ID)]\n collisionObjects = [x[1] for x in p.getOverlappingObjects(aabb[0], aabb[1]) if (j not in FEET_INDEXES and (x[1] not in familyOfLinks or x[0] != hexapod_ID)) or (j in FEET_INDEXES and x[1] not in familyOfLinks and x[0] == hexapod_ID)]\n if len(collisionObjects) > 0:\n return True\n return False\n\n\ndef runGait(individual):\n global REAL_HEXAPOD_CONNECTED\n lastTime = time.time()\n global firstCycleComplete\n dt = 0\n firstCycleComplete = False\n initDuration = individual[0]\n force = individual[1]\n gaitChromosome = individual[2:]\n gaitChromosome = ([initDuration] + [0] * NUM_OF_SERVOS) + gaitChromosome\n resetEnvironment()\n stabilityScore = 0\n heightScore = 0\n collisionScore = 0\n sampleCounter = 0\n p.setRealTimeSimulation(1)\n while True:\n if CONFIG_MODE:\n p.setJointMotorControlArray(hexapod_ID, JOINT_INDEXES, p.POSITION_CONTROL, targetPositions=read_debug_parameters(), forces=([force] * 18))\n else:\n p.setJointMotorControlArray(hexapod_ID, JOINT_INDEXES, p.POSITION_CONTROL, targetPositions=readGait(dt, gaitChromosome), forces=([force] * 18))\n if REAL_HEXAPOD_CONNECTED:\n updateRealServos(ssc32, 100)\n\n # Evaluation Metrics\n hexapodBasePosAndOrn = p.getBasePositionAndOrientation(hexapod_ID)\n currentStability = sum([abs(angle) for angle in list(p.getEulerFromQuaternion(hexapodBasePosAndOrn[1]))])\n currentHeight = abs(1.375 - hexapodBasePosAndOrn[0][2])\n stabilityScore += currentStability\n heightScore += currentHeight\n #collisionScore += collidingLegs()\n sampleCounter += 1\n\n # timing variables\n now = time.time()\n dt += now - lastTime\n lastTime = now\n\n # Finish evaluation after 12.5 seconds\n if dt >= 12.5:\n break\n\n hexapodBasePosAndOrn = p.getBasePositionAndOrientation(hexapod_ID)\n currentPosition = hexapodBasePosAndOrn[0]\n distance = hexapodBasePosAndOrn[0][1]\n straightness = abs(angleBetweenVectors(np.array([0, 1]), np.array([currentPosition[0], currentPosition[1]])))\n avgHeight = abs(heightScore / sampleCounter)\n avgStability = stabilityScore / sampleCounter\n avgNumOfCollisions = collisionScore / sampleCounter\n fitness_distance = distance / 100.0\n fitness_straight = 1.0 - (straightness / math.pi)\n fitness_stability = inverseCurve(avgStability, 1)\n fitness_height = inverseCurve(avgHeight, 1)\n fitness_collisions = round(1 - avgNumOfCollisions, 2)\n fitness_total = (fitness_distance + fitness_straight + fitness_stability + fitness_height + fitness_collisions) / 5.0\n line = f'ID: {UNIQUE_THREAD_ID} | Time Elapsed: {dt} | Evaluation: {fitness_distance, fitness_straight, fitness_stability, fitness_height, fitness_collisions, fitness_total} | Chromosome: {individual}'\n print(line)\n with open('C:/Users/Jonathan/Desktop/results_normal_cyclic.txt', 'a') as f:\n f.write(line)\n f.write('\\n')\n return fitness_total\n\n\ndef sinusoidalTestGait(t):\n coxa0 = (math.pi / 4) * math.sin((2 * t) + math.pi)\n femur0 = 0.2 * math.sin((2 * t) + ((5 * math.pi) / 2))\n tibia0 = 1.3 * math.sin((0 * t) + ((3 * math.pi) / 2))\n coxa1 = (math.pi / 4) * math.sin((2 * t) + 0)\n femur1 = 0.2 * math.sin((2 * t) + ((3 * math.pi) / 2))\n tibia1 = 1.3 * math.sin((0 * t) + ((3 * math.pi) / 2))\n return [coxa0, femur0, tibia0, coxa1, femur1, tibia1, coxa0, femur0, tibia0] + [-coxa0, -femur0, -tibia0, -coxa1, -femur1, -tibia1, -coxa0, -femur0, -tibia0]\n\n\ndef evaluateGait(individual):\n lastTime = time.time()\n numOfPhysicsSteps = 3000\n samplesPerEval = 100\n stabilityUpdateRate = int(numOfPhysicsSteps / samplesPerEval)\n stabilityScore = 0\n heightScore = 0\n collisionScore = 0\n global firstCycleComplete\n while True:\n dt = 0\n firstCycleComplete = False\n initDuration = individual[0]\n force = individual[1]\n gaitChromosome = individual[2:]\n gaitChromosome = ([initDuration] + [0] * NUM_OF_SERVOS) + gaitChromosome\n resetEnvironment()\n for ii in range(numOfPhysicsSteps):\n if ii % stabilityUpdateRate == 0:\n hexapodBasePosAndOrn = p.getBasePositionAndOrientation(hexapod_ID)\n currentStability = sum([abs(angle) for angle in list(p.getEulerFromQuaternion(hexapodBasePosAndOrn[1]))])\n currentHeight = abs(TARGET_HEIGHT - hexapodBasePosAndOrn[0][2])\n stabilityScore += currentStability\n heightScore += currentHeight\n collisionScore += collidingLegs()\n p.setJointMotorControlArray(hexapod_ID, JOINT_INDEXES, p.POSITION_CONTROL, targetPositions=readGait(dt, gaitChromosome), forces=([force] * 18))\n p.stepSimulation()\n dt += 1. / 240.\n # time.sleep(1. / 30.)\n hexapodBasePosAndOrn = p.getBasePositionAndOrientation(hexapod_ID)\n currentPosition = hexapodBasePosAndOrn[0]\n distance = hexapodBasePosAndOrn[0][1]\n # straightness = abs(p.getEulerFromQuaternion(hexapodBasePosAndOrn[1])[2])\n straightness = abs(angleBetweenVectors(np.array([0, 1]), np.array([currentPosition[0], currentPosition[1]])))\n avgHeight = abs(heightScore / samplesPerEval)\n avgStability = stabilityScore / samplesPerEval\n avgNumOfCollisions = collisionScore / samplesPerEval\n fitness_distance = distance / 100.0\n fitness_straight = 1.0 - (straightness / math.pi)\n fitness_stability = inverseCurve(avgStability, 1)\n fitness_height = inverseCurve(avgHeight, 1)\n fitness_collisions = round(1 - avgNumOfCollisions, 2)\n fitness_total = (fitness_distance + fitness_straight + fitness_stability + fitness_height + fitness_collisions) / 5.0\n print(f'ID: {UNIQUE_THREAD_ID} | Time Elapsed: {time.time() - lastTime} | Evaluation: {fitness_distance, fitness_straight, fitness_stability, fitness_height, fitness_collisions, fitness_total} | Chromosome: {individual}')\n if not math.isnan(distance):\n break\n else:\n print(\"PyBullet Glitch\")\n resetPyBulletSimulation()\n return fitness_total,\n\n\n# start of main program\nMAX_MOTIONS_IN_SEQUENCE = 4\nNUM_OF_LEGS = 6\nNUM_OF_JOINTS_PER_LEG = 3\nNUM_OF_SERVOS = NUM_OF_LEGS * NUM_OF_JOINTS_PER_LEG\nUNIQUE_THREAD_ID = random.randint(1, 10000)\nLENGTH_OF_CYCLE = 12\nLENGTH_OF_START_SEQUENCE = 2 + 1\nLENGTH_OF_SEQUENCE = LENGTH_OF_START_SEQUENCE + LENGTH_OF_CYCLE\nLENGTH_OF_GAIT_STATE = NUM_OF_SERVOS + 1\nSTARTING_HEIGHT = 1.375\nSTARTING_Y = 0.01\nTARGET_HEIGHT = STARTING_HEIGHT\nfirstCycleComplete = False\nREAL_HEXAPOD_CONNECTED = False\nCONFIG_MODE = False\nssc32 = None\nif REAL_HEXAPOD_CONNECTED:\n ssc32 = serial.Serial('COM3', 115200, timeout=2) # open serial port\n\ncontrol_IDs = []\n\n# PyBullet Init\nphysicsClient = None\nif __name__ == \"__main__\":\n physicsClient = p.connect(p.GUI)\nelse:\n physicsClient = p.connect(p.DIRECT)\np.setAdditionalSearchPath(pybullet_data.getDataPath())\nplane_ID = None\nhexapod_ID = None\nresetPyBulletSimulation()\nprogramStartTime = time.time()\nservoRangeOfMotion = (math.pi * 3 / 8)\nJOINT_INDEXES = [x for x in range(0, 24) if (x + 1) % 4 != 0]\nFEET_INDEXES = [x for x in range(0, 24) if (x + 1) % 4 == 0]\np.setRealTimeSimulation(0)\n\nprint(f'PyBullet Instance ID: {UNIQUE_THREAD_ID}')\n\n\ndef main():\n init_debug_parameters()\n print(\"START\")\n\n # Back-flipper 400 Gen (use robot2.URDF)\n # runGait([0.18403936561894646, 300, 0.1549125676230881, -1.0737228551789968, 1.1074034854568302, -0.5075648311566827, 0.9410632472797863, -0.034075539924461766, 0.04087326062084187, 0.016970270367710892, 1.0693994730213368, 1.155687813177694, 0.8737522824643122, -0.8647752630675463, 0.34299370658943856, -1.0211653604035968, 0.9327693440640767, -1.1011770525732225, 0.9557766462321559, 0.12072049734526494, 0.6379668000414453, 0.38230918565376665, 0.38766472211677316, -0.23345728123331336, 0.42693206671590045, 0.7481283759819202, -1.0035764425332458, -0.37743247317618395, 0.09703593626443223, 0.4096524242490998, 0.5659367640154525, -0.48634980239282366, 0.9997166523571077, 0.9918650566996552, 0.3533658070404414, 1.0175827219942823, 0.18743930901921652, -0.4458899131062403, 0.4201947524885313, 0.9657458794711107, 0.44323639067960297, 0.8503041963843176, -1.1368206866652761, -0.5949936064673491, 0.8431072036023203, -0.8259446127674113, -1.0362372103175401, 0.15060262481341474, -0.9859007911949546, -0.21962601316827257, 0.09533520637849181, -0.640348357362408, -0.8041160416557014, -0.7812025840957206, 0.11151372791644286, 0.8274774721561737, -0.587046978534175, -0.32808303668861744, 0.2379704057869646, 0.18775280488712448, -0.4377264809328173, 0.5907623805366229, 0.05202338940205825, -0.2451747086887523, 0.8470984599764407, -0.7682503206243262, 0.3612923441372827, 0.6886023359929412, -0.9693524777736018, 0.304702690167437, -1.1660144413974514, -0.8249616411604217, 0.8945052164694315, 0.17544939809574825, -0.8272460898178078, 1.1407934664917578, -0.2000536217205298, 0.18640987180335764, 0.2679299333926803, 1.145665972340061, 0.9764033023740143, -1.0945467100291453, 0.521372365408202, -0.08805314721161141, -0.38934451999230035, 1.1416905493697052, 0.9003889322068577, -0.8129184705562436, 0.3440473274506305, -0.72472648064133, 0.05399471861877388, 0.5194134990647563, 0.6874785346278812, -0.8122596509146587, -0.650730661490093, -0.7272921738378133, 0.4576376839803699, 0.3904171653145497, -0.9810005319300584, -0.00285443936171912, -0.36535172159131735, 0.6144096327192144, -0.15837248303352225, -0.8994195620240998, -0.550954584675316, 0.6429230964102726, 0.8005796647490672, 0.06531222692534534, 0.34974094724817234, 1.176172791792436, -0.5252710369532949, 0.2649227929594751, 1.175606830532634, 0.9455873746485913, 1.0932290476666615, -0.5309007757921452, 0.2682629673178282, -1.019068207596018, 0.7873164405123094, 0.47109953022389206, 0.9043790189976995, -0.4554792669173991, -0.7129058230136001, 0.06376465587541758, 0.8334084349886761, 0.4891839072422823, -0.8195171322070331, 0.355909241507946, -0.45439362049140547, 0.7612376551762988, -0.05436372347589597, -0.8253395241105608, 0.5353956017148908, -1.1278223769955171, -0.2672704939182695, 0.08236845953569603, -0.3944515835531134, 1.0532839324087664, 0.2152014313163344, -0.32115401363252016, -0.4401831731301486, -0.8316311944948868, -0.8204912647642763, -0.20684288623086328, 0.656586992390969, 1.040632220799805, -0.5681960529259297, -0.8935973924071543, -0.5523442578187371, 1.019030749112957, -0.9889777010534911, -0.7813891126298407, -0.31025456229208886, 0.21737299067653276, 0.11975606760923985, 1.1489133897234511, -0.732747722798833, 0.46248225304712504, 0.8367764473513415, -1.1345064996816838, 0.8487271456519844, 0.47079084546084493, -0.3880313224602788, 0.5726640163660738, 0.3169122624606709, 0.3125375497368141, 1.0725665493127594, 0.04471119068333991, 1.1194888957575166, -0.694350406505744, -0.3409595779421505, 0.6171251620061712, 0.22135934758297232, 0.21247623650675107, 0.8669374876359844, -0.31535073366399385, 0.5538889770906046, 0.3757263311055013, -0.597927592864876, -0.6925085946018497, 0.34871269014582607, -0.7181727784647577, -0.9959175484190584, -0.3941241000777373, 0.5843467229636823, -0.1298465717484976, 1.1265371185410973, 0.10481709067861797, -0.6208804733701672, -0.23209634549660108, 0.09164363735575871, -0.5218291197106613, 0.13407195016157047, -1.0811880597442607, 0.6537001639909427, -0.9112100951312594, 1.1331704450421252, 0.09526547721035253, 1.0691734422557067, 0.28286325422558284, 0.2155840511857598, 0.34219576355889947, -0.06858382641835256, 0.6352320740995255, -0.8534759393001677, -0.30215311605080114, 0.4825461632485498, -0.7878025062942408, 1.1767649332440155, -0.36658719987216254, 0.614083134565041, 0.017395772324190255, -0.8141910253664506, -0.9789440851674488, -0.760947748240976, 0.10514245629454896, -0.012445121344935495, 0.8955364949519948, -0.9407396155918096, -0.5059512257000718, 1.0169038534816517, -0.5661662987702231, 1.0472948411801215, 0.9527469422382762, -1.0438693320196037, -1.0197514641091732, 0.5923565043667608, -1.1513518068819006, 1.1426265213356581, 0.7314115693481198, 0.035878365067006056, 1.1268253186061643, 1.1381898892090025, 0.050668047659784055, -0.3374091279069584, 0.7307081467526516, 0.026235117587053144, 0.5330659472771377, -0.03700545752962979, -0.23289865423067055, -0.03238468060810259, -0.8203158342693152, 0.5683798195792417, -1.1246799094062077, -0.758692396093738, 0.21847165129039725, 0.5696240201910205, -0.3529263485054064, 1.0260220368312303, 0.01224911889098179, -0.1809953840590205, 0.16439486454032642, -1.0079506314517355, -0.7339119466544526, -0.796638067199314, -1.0901440827406046, 0.6979503548178353, 0.7015791939518996, -0.07233693177751095, 0.5560875159234098, 1.1110141779625964, -0.15396573755282433, -1.1582494805739991, -0.12961450456604595, -0.651868837749322, -0.31774126871869124, -0.26337831137926265, 1.1722112677888488])\n\n # Experimenting with stability\n # runGait([0.29107088383373003, 156.78061666398597, 0.5353900646350714, -1.1333425119926464, 1.0829260730302332, -1.1640892198484636, -0.38152815636010307, -0.7197641554363123, -0.5865711046576539, -0.7927045883259933, 0.00438855244070635, -0.6432876760380152, 0.08594928155643794, 1.0817177784301633, -0.5378762158033574, 0.6930352009582383, 0.3152893767243987, -0.8955744085304733, -0.19691910222378564, -0.6131664945408353, 0.5512774089140886, 0.6670518195451283, -0.19309128337814246, -0.39607435850701944, 0.47480066743434857, -0.37028244976875146, -1.0989195356925148, 0.30442539638418725, -0.9337728215237907, 0.30406338012158807, 1.0455043322618425, -0.06789772225569224, 0.5806250136267157, -1.0375724064199314, -0.3543513598059251, 0.1989952263373842, 0.23561168218655393, 1.0508947475484427, -0.5301435173978837, 0.954111551885351, 0.17938815590296145, 0.12832022231695767, -0.1490689385957007, 1.0330605104523767, -1.0623171252199062, 0.8445117720781832, -0.36027189597546316, 0.5443268480270156, -0.1000204487317421, 0.8404845535139747, 0.7974970727477276, 0.7264552844874479, -0.7000730851293409, -0.759341129282885, 0.7648050158369193, -0.7522289855617343, -0.9984554385243157, 0.08999817877211987, 0.9363902863024169, 0.7202283975791759, -0.3961247258926616, -0.36531006526282306, 0.6003213302935796, 0.38400973936199784, 0.07770508777397611, -0.4360267539477962, -0.5751568134137885, 0.43883791069800354, -0.18052901071260805, -0.20490900220420233, 0.18186013658998493, 0.692889951182456, 1.1009750256518542, -0.5280637382212376, 0.9864059841841444, 0.735701606227071, 0.8506684523432434, 0.19014925787028816, 0.02734747647350761, -0.14246780172817314, -0.16363487369520202, -0.9807750892297045, -0.5974559893332009, 0.7052210645249009, -0.5722152424030353, 0.4150366036529538, 0.8451537180291235, 0.4434838540550997, -0.20824516651145206, 0.6091705295348645, -0.9590250992142602, 0.9808724317974076, 0.4183489440801338, 0.3607884449764098, 0.06383687946190619, 0.5937967791598316, 0.24274029229005406, 0.29029702682807396, -0.603878266910079, -0.08806950361411958, 0.7212683704190836, 0.6724813333613975, -0.18666038908670848, -1.103082059804687, 0.8768587952536211, 0.1404761787154466, -1.0478894200143816, -1.1437694960941056, -1.03754562219342, 0.9085399008442834, 1.1227743423279155, 0.498537990420221, -0.8371826748208432, -0.09808959558757369, -1.0626830441409378, 0.5380159945100353, 0.06381426021825665, -0.5683621599007505, -0.8656452557602182, -0.3593917993503882, -0.33715498495122065, -0.7801978053428386, 0.9153213044740255, -0.7555054418695308, 0.26788356436185146, -0.06902203453873508, 0.25274353461079657, -0.6944626972070734, -1.0430307172162676, 0.01812578724476625, 0.02313415896879832, -0.6806192043426953, 1.100081799618252, 0.827785090927609, 0.3269284020247252, 0.03206468028287163, 0.3034997439357618, -0.2990653227916562, 0.7397771966931967, -0.8780480762102226, -0.08487561447549834, -0.577616393319167, 1.0833921351724336, -0.45990422848121937, -0.6346960024499542, 0.7918294091829395, 0.027155163465394427, 0.19054579609590222, 0.21557173632598228, 0.2980525771157228, -0.7559737274895846, -0.97517502765191, 0.06865090400328322, -0.5031462207447848, 0.10497243089263641, -0.7965555365903747, -1.0373626266104656, -1.0533096615397561, 0.10728070263954059, 0.796368793127805, 0.0718344507091692, -0.9989396260631868, 0.6356575989158342, -0.6255437988888762, 0.9131334879875902, 0.45646847811471414, -1.0169463676260804, -0.3933819058755607, -0.5997997874897212, 0.17878990565350586, -1.1569178781134557, 0.10159645335836587, 0.7154971633906789, 0.17032819164387833, -0.01835367286864094, -0.9505402084183495, 0.9691636502442869, -1.0866819107494512, 0.19673356296061473, -1.0813009593788294, 0.6727946528411259, 1.177458334902635, 1.1463233157921833, 0.145360816245766, -0.7110332186361785, 1.1672615674161702, -0.3210995288856508, -0.3412206078486237, -1.1150104372864078, 0.41469339605306227, -0.2438596429359537, 0.539355647844741, 0.12085515871084321, -0.9647547341312186, 1.0521097335095957, 0.38872376706386774, 0.12699195498661892, -0.1666314031269644, -0.1452609089409052, -0.9161542968661167, -0.0576685820645067, -1.0362064288895902, -0.5438335521979928, 0.6421961281435908, -0.8782675763606693, -0.32039420495397747, 0.6517605169997935, -0.34461234725989986, 1.0265223840919862, -0.9642919006925839, 0.6343523074380544, 0.01045648767965579, 0.3839206068543592, 0.3625094480567086, 0.5988029218201046, -0.8066055092585431, 0.8291837194941895, 0.9966471145724585, -0.5512131701360924, 0.558229602974704, 0.6430208438139704, -0.36772966559972137, 0.9071931330847132, -0.30657207454292457, 0.18015360737564146, -1.1574946716164571, 0.6901959363107916, 0.786073839325254, 1.0524799852271292, -0.48261528673935933, 0.3021126071842598, 0.6780681739932523, 0.2650223276064161, -1.006069056570006, -0.37549673659808014, -0.8831740449899401, 0.6404770888288831, -0.29655423133316006, -0.30248718319006307, 0.2914366205771275, -0.26389183625692514, -1.0895101207281785, 1.0340066693226782, 0.9883010962564867, 0.13283052185185668, -1.0053930692545063, 0.9173399063162657, -1.1359574713434795, -0.9135848528331729, 0.05275828150306455, -0.8544265299335544, -0.6004625904664892, 0.7568333265679985, -0.11361613904339729, -1.0251203832530935, -1.1051123528377, 1.104096469074662, -0.4090842273664589, 0.23362094428508276, 1.122749227526524, 0.2089305257744809, -0.07565225626772398, -0.19006931939016714, 0.9450976678385695, -0.25602949043929973, 0.8979865614568747, -0.7508855781432413, -0.468020831328862])\n\n # NSGA\n # runGait([0.18229659766382353, 155.6458409097608, 0.9083504748793311, 0.14110476724188775, 1.093443926606583, 0.8999005754220708, 0.8149729234408216, -0.6359985441288066, 0.5861105866627622, 0.9646599108012346, 1.132867106787237, 0.7918013480335797, 1.146016728309355, 1.166593885399247, -1.0830432373628303, -0.9263478251771459, 1.0107748178924647, 0.4646106439794383, -1.169978052196896, 0.0749939582085001, 0.4339923743202392, 0.4579402086767843, 0.4206199667029586, 0.1397555030784438, 1.1401145649029063, 0.09302868565904275, 0.4914790880995965, -0.4651971857366567, 1.1659566230018072, 0.3706345064730484, 0.07552351079101301, -1.1232067067347673, 0.2222935344062407, 0.7748993910829708, 0.13034880610013827, -0.4806035746604289, 0.3172527997840071, 0.5068224937104546, -0.46511584843166, -0.3467931766616326, 0.3427084205149607, -0.32737952333572434, -0.90724945399064, -0.5250338620208708, 0.6880580209305295, -0.5448070713760786, -0.18858065144794406, 0.014731130802321182, 0.05906164696150665, 0.5284225601490862, 0.2234470472115875, -0.6232032858763568, -0.90751250478335, -0.9199446731694133, 0.24647114606718526, 1.1071349261385088, -0.22236693394071033, 0.49967256016722467, 0.8997056992139608, 0.2047903228421882, 0.9318238130993908, -1.1170109958568422, 0.3134441187993395, -0.7308917666312805, -1.069328123854823, -0.8079594196034741, -0.8413209463842631, 1.1062445646940164, -0.03586696528282618, 0.9654148851126274, -0.9432680014273601, 0.5234582594311347, -0.7471694311620266, -1.022219081571329, -1.0800214764917782, 0.7474112702428726, 0.20819166616338916, 0.7215699077419591, 0.38031567283758844, -0.5238628816347054, 1.0770153104321716, -0.6397760818081154, -0.22435045232641265, 1.0706893179893495, -0.5518655141151997, -0.19087636009819303, -0.3512479711738529, -0.6606861068197772, -0.8685585946822181, 0.3604633384909186, 1.0275382741711763, 0.06655444813978417, 0.9935834582186229, 0.7279386983043616, -1.0070347596788973, -0.2442584535361799, -0.3012388201961493, 0.7247939705316814, 0.6269234457029824, -0.009873626827067952, 0.482981540629763, 0.8598378851596727, 0.4741322053329257, 0.675550009524477, 0.346302537230719, -1.1243070756199751, 0.22681429162070263, -0.3097657746518692, 0.6778382742087453, 0.814184670743237, -1.010608111150304, -0.27376846268023297, -0.9948460491716468, 0.5069784751074181, -1.119671608976601, -0.9303075410380663, 0.7246078940736616, -0.6722076482955358, 0.37757103600219066, -0.313874069830721, -0.43472066633036216, -1.1278978108552458, -0.9970308936270744, -0.5565800651858721, -0.9069457748848149, 0.8230975287693061, -0.41294547922588815, 1.1712915826924468, 0.5098575610704372, -0.9343470208547747, -0.7502818925909562, 0.8572882565769667, 1.1527965107091545, -0.5985576253107086, 0.9812633011454751, 0.43198678500041227, 0.5217073857233142, 0.9761183062018322, 0.14128704712955387, -0.2776161554656262, 0.7504777433267875, 1.0294036660645036, 0.09622107476155035, 1.084571969315032, 0.5909472984707462, 0.21678827645458928, -0.20873040261437428, -0.8425470304835826, -0.5794336238166817, -0.7224193962610191, 0.7320581158158446, -0.3615401506592452, 1.1405747073218429, -0.3039589800092729, 0.2894225332294616, 0.26050649010553945, 0.681767611672782, -0.5129831573243372, -0.19268708535592294, 0.2842271081958875, -0.4316514377659478, 0.1747797126503924, 0.16177042672268072, -0.9595387421298439, -0.8913796116466794, -0.2835623569393363, -0.9021243233987757, 0.04675926339236765, 0.5877718252549794, -0.020728046886497195, 0.1960504582672131, 0.828348254755653, -0.3256674408706686, 0.6430416383221862, -0.20525504926868066, -0.8518231015695202, -1.0599288641751397, 0.6287112429011469, 0.12367108041799399, -1.0720406710260566, -0.22472210546705562, 0.8706060321838783, 0.5291724611088444, 0.10250068539672591, 0.7278411385365671, -1.1566550009574674, -0.48415340513814353, -0.14201813891013926, -0.42454015353898894, -0.5588938960807662, -0.3294006824868001, -0.804967243168935, 0.8162080012175026, 0.18496746845666612, 0.3891323361310516, -0.7744570170530798, 0.11870436656346904, 0.9500286012565656, 1.091687566807378, 0.3307255383169255, 0.7118468053052446, -0.9013453096963969, 0.1945196784104959, -0.7862302171325798, 1.0371600096585611, 0.8279744386055418, 0.5349665267082687, -1.0492245155619515, 0.24063714267361025, -0.5253103025206994, -0.6958371376482045, 0.5127663834795291, -0.5668633184192481, 0.028756495211944066, -0.8180067305130339, -0.7325151144334637, 1.0874568313948747, -0.6204051504490435, 0.16734526054734847, 0.9079945409597623, -0.1605782825625574, -0.9493435726574494, 0.9729771352267385, -1.041240909006733, 0.8207784518169133, 0.2019719768666147, -1.1386639991254925, -0.6372470497638072, -0.5284328510489867, -1.1424013728720803, 0.31553420746729177, 1.0380382961752586, -1.1411444021812454, 0.09246165325365872, 0.1706564355825929, -0.6346966931891327, -1.0909483051470628, -0.06566436851792082, -0.2776209741481568, 0.41899201957450416, -0.18759177838803043, 1.1555756485784177, -0.5822077172996798, -0.9193289683677482, -1.0371716158033841, 1.1423430653663564, 0.8779681991740422, 0.7805125432142439, -0.7721653288915576, 0.5155584453512811, 0.14486889941392897, 0.8446819611612648, 0.05327295198343703, -0.33865091333049985, -0.14899995870829524, 0.1953458127677415, 0.8939023739574229, 0.07623855879466708, 0.6130493982347537, 1.0918462763933745, -0.8759140979104185, -0.9919552795899489, 0.531399920610189, 1.035948455011811, -0.6346835942687693, -0.9522149883706655, 0.12740143026457326, 0.9609495300188751])\n\n # 3000 Pop\n # runGait([0.904983046733017, 159.59983729578843, 0.060696523522925525, -0.30971496430036916, 0.7353270535594881, -0.6505978383780697, 1.1023304598221446, -0.30768612827725195, -1.0234200031222016, 0.0034031598955847732, 0.21330511114420406, 0.9254559265553964, -0.6604354617020531, 0.15158813875789579, -0.7854467191411058, -0.9925929220629403, -0.2080119772713885, 0.9748408255452494, 0.32631902985278716, -1.1409334395171054, 1.0693652898105703, 0.12206649342856929, -0.2847542804409562, 0.4801514292150744, 1.0332765953216592, -0.7938197444031939, 0.2563131442452105, -0.14869709222993316, -0.9347675501625538, -0.524006106702254, -0.11909684998489307, 0.8400278760972555, -0.23718061034206372, -0.337660742691555, -1.1686283476437243, -1.1031105878405127, -0.7646199378803564, 0.6354804367029614, 0.8837680367321205, 0.15899423130435295, 0.6712575159053917, 0.4215958247199955, -0.3373087437071557, -0.9305356508955385, 0.9082056114784287, -0.9284716662471378, -0.04940610858174345, -0.06555931514262112, -0.09399768472542123, 1.1247909715839755, -0.48379285974626773, 0.570525480919135, -0.02569623444311407, 0.10714561439371209, -0.10783544772282928, 0.7051584770708194, -1.0406922832593428, 0.06343296206551907, -0.8505979742277806, 0.10694125521184705, 0.16935548980784373, 1.1420837333010894, 0.24204597235287523, 0.6475736003934104, 0.17055212844135192, 0.49474061804168407, -1.1398076486306385, -0.03973245191392927, -0.939386769890378, -0.402476064224687, 0.025119711897026987, -1.05440268787099, -0.2752953135618634, 1.1685995968528273, 1.1257083961904089, 0.29732029639677987, -0.17567621997968294, 0.9564892264662193, 0.751911791222228, 0.18761642526516176, -0.3232472318368491, 0.7932493092806446, -1.1052582188288498, 0.5487840041424124, -0.70316267873878, 0.5857454028700838, -0.30104018247011155, 0.3990877589811526, -0.27622278756255064, 0.5007368227279884, -0.34255158345432923, 0.7860783873697565, 0.3299290546401101, 0.4212830410670498, -0.5000823971778967, 0.20211647698962795, -0.5954542100162727, 0.7891262765370252, 0.8398523515973949, 0.04208448038937486, -0.24762466260929505, -0.18298569176248317, -0.36744847594043806, 0.11711890578959555, 0.6784909064918407, 0.043547048965568554, 0.915347385672616, 0.1943537417670627, 0.1961032921533715, 0.27380381570388196, -0.6925505753816085, 0.13409295730737364, 0.9238606281112889, 0.7232290263266692, -0.08475645900857555, 1.0918689969424247, 0.11494102395735217, 0.13564497247063464, 0.07791390649505298, 0.09101847685593711, 1.0802565634925867, 0.008017176336832414, -0.40863001168996127, -0.4349722126523693, 0.34453158076792034, -0.6910315034834699, -0.8948888951214328, 0.36598368092354766, -0.43159001817612835, -0.09136672190834433, -0.8265804981583658, -0.41569623861994176, 0.7235977966485335, -0.2699267245166663, 1.0160916486038205, 0.05956580763846824, -0.553446262414352, -0.9234155272540824, -0.5105546990572772, -0.634441156000243, -0.40216456144001933, -0.659878523232472, 0.016898776661833703, 0.04370343683036865, -1.0525099132085054, -0.1360717628812732, 0.5358560458811824, 0.052683861773873776, -0.953171635298017, -0.15148360309076792, 0.8695124128462544, -0.33150174271113014, 1.1018672681161934, 0.8122315339180584, 0.05632606046036302, 0.4062446410358813, 0.9032403720408388, -0.4898652953167396, 0.5547542361296853, 0.34407051580411596, -0.9688368827468914, 0.9051281478921898, -0.382672404368127, -1.0351659289591528, -0.28339507478975706, 0.2604244554458595, 1.141276061674245, 0.9511590958810777, 0.030865821870599747, 0.25589416378172836, -0.899230741333316, -0.6890771547052199, -0.36098686027424987, 0.2046761115043388, -0.003370011028005335, -1.0326969178585779, -0.6399760361033779, 0.2945889455809976, -0.5693772211328435, 0.5190623470719792, 0.9594447543339326, 0.6647471001461713, 0.1765304159915148, 0.43139180526620574, -0.7827997940081548, -0.3212428257056203, 1.08691662804371, 0.5724684958868459, -0.8190711895017851, -0.21893910988788873, 0.43754121343708036, 0.7761978329434286, 0.023307117981586058, -0.8196812812240051, 0.18349841454177002, -0.03275888140948699, -0.9354688626764325, -0.29752922729690606, 0.1038144707355869, 1.157887360987824, -0.012635618639992992, 1.1772296247879417, 1.0476346313277654, 0.10969465515895042, 0.9315375765707544, 0.4127446193866228, 1.027376379551766, -0.21108693714197815, -0.6492523615384952, -0.1992276005394296, 0.9471808298697213, 0.003879051139011558, -1.007300896674733, -0.8988174362275243, 0.4571936981359096, -0.3114735176334528, -1.0288979365415865, 0.21589235355521563, 1.1668173760981395, -1.0513185987779647, 0.12533634979511898, 1.0255130494459233, 0.748872451843244, 0.09667778038896534, -0.984941038411984, -0.07093582524591927, 0.5164103929817825, -0.27201410547664984, -0.3729048874293173, -1.1149579500690774, 0.8813975424355013, 0.621449531061543, -0.6997908270429463, 0.5020729261400154, 1.0064048881599486, -0.7789049856237727, 0.1128585572848923, -0.19354726814305145, -0.464830471290481, 1.093822978982704, -0.7444302566691616, 0.5228503281130006, 1.0127816296546253, -1.1495705447930669, 1.1634921469729014, 1.017059004992762, 0.6538475673570939, 0.2985847382952567, 0.44100054350476847, 0.20413700406627103, -0.7151778221967301, 0.40107695707208585, -0.7845232708359956, 1.126462565607725, -0.7541211894437213, 0.28493713718804164, -0.5111505775098296, 0.053487615522491705, -0.5972630106930484, 0.867696699744679, -0.591697544975821, 0.393417762872977, -0.36433296593800835, -0.8484271043364143, -0.7889442880625308, 0.5526505308931524, 0.36476343329950656, -0.010331075612058583])\n\n # 407 Gen\n # runGait([0.8781196143633982, 157.10313398974353, 0.33682254295973746, 0.28781781595826333, 0.1860859338114289, -0.20420881621380305, -0.12123927275926893, 0.4063033014361015, -0.20359193737052045, -0.6840192443790235, -0.28254702343692906, 0.5940254747152814, -0.29777220678601746, -0.07426962639294979, 0.9652159747014115, 0.2473752294851017, -0.6107793773528992, -0.13244976914336656, 0.5280864171637462, -0.059421386701237325, -0.07844527791237588, 0.6322545653056038, 0.4724601535718872, -0.3287282121853098, 0.5434097111921933, -0.12151448936067652, -0.06979580112172787, -0.2961931277705389, -0.4805882127012387, 0.3364130911622725, 1.0005701725869078, -0.21847954935067443, 0.1323700155317861, -0.32215689673367087, 0.14430331665049628, 0.09917150470049849, -0.5170401624287033, 0.5409236317536736, -1.02363228425136, -0.5320260643642395, 0.9218582075166826, 0.2807391864517396, -0.5941315102406781, -0.7080454310389085, -0.31585622472883196, -0.009146624918177084, -0.2012219697627285, -0.4409244609725404, 0.8768753147403492, 0.9343776617888977, -0.02141775939762952, -0.26104580922522647, -0.24705414040844845, 0.34300112955081297, -0.3356925840764099, -0.6775278951424454, 0.632154513923834, -0.5828623947214877, -0.5182796152392433, 0.606350185900368, 0.3246392910354486, 0.8302757207728939, -0.0023731755697271803, -0.16107561586683852, -0.5441686853739696, -0.8288171478401807, -0.397679027844255, 1.0145087733378917, 0.5771456856002078, 0.1928252929176832, 0.2801312178087099, -0.424024932102493, 0.028490342932658078, 0.5663828653801755, -0.2578226202044432, 0.4758103361385356, 0.11262059630304765, 0.17852984636877395, 0.7819886760768826, 0.4777904992793935, 1.1215684250587168, 0.7012165047082592, 0.08680724775780826, -0.12794232943092734, -0.02749916734935132, -0.45447494760953283, 0.39467736190532837, 0.556999354112899, -0.47790256532634695, 0.15041111386454983, 1.0555134056088191, 0.1949848324658606, -0.1334691560253397, 0.8282086290450636, 0.41689095269036547, 0.3213829957559171, -0.45920978149223457, 0.6474648195495811, 0.6759097856561475, -1.0097973227736488, 0.5730950969137286, -0.4092749722577607, -0.039674737074665734, 0.18021687378702161, -0.6615793121935327, 0.03142374866540614, -0.7336966171880697, -0.3283666283009425, -0.7807776498788782, 0.04535750599480415, 0.1704720716786568, 0.07139750224822779, -0.39506187566783524, 0.5372040246741976, -1.1473534956177283, -0.4013147582043887, 0.38703856371800294, 0.3971836501834768, 1.1715304273819858, 0.5442662829228595, -0.0980978149061639, -0.4344320237816741, 0.7384324675711982, -0.6187275059274405, -0.3575034072195102, -1.1288861687148302, -0.3261414464285166, 0.7523726891212104, -0.15988727327072425, 0.1131072052563967, 0.34829181401975273, -0.6281159632389499, 0.7689620896680501, -0.12006262327557764, 0.9842080944836419, 0.26578776890675115, 0.5127275308397158, 0.6177831879058816, 0.6136850718675044, -0.7101342612681036, 0.22667486103048795, -0.6637649111191182, -0.49116115181432607, 1.1778110294059096, 0.6536538976088225, 0.337894833822659, -0.8418763216442848, -0.11767229020786187, 0.3713509801518212, -1.062628223739996, -0.6364809135462092, 0.25314885600822956, -0.4532780204714063, -0.9156058815025188, 0.38398735762219094, 0.6504528410510488, -0.8483565675469873, -0.19248354081194868, -0.10272402672891327, -0.21538792572640295, -0.19546972821258218, -0.9483484869960997, 0.022956480787546467, 0.10722697400615173, -0.5339228101100632, -0.35402855681089174, -0.4909015301740968, -0.18175978846992896, 0.6859271886866835, -0.5159021239613567, -0.4536971124614899, 0.33596686235547757, -0.8380097153759376, 0.2564768448158085, -0.17784663515089585, 0.8848479741072743, 0.45734330263531453, -0.09873367668089586, -0.7500713258217162, -0.25406396619910043, -0.9054849581453508, -0.41576987655001807, 0.39503507766193025, -0.5857624014296016, 0.4560242643397691, 0.23900721343893294, 0.4454950080559121, -0.008251391139937114, -0.5778461849029692, 0.49439432908178516, -0.08522125551940313, 0.9544048902657116, 0.26600604145504003, 0.3367464085720411, 1.0096321755173974, 0.5254892106771129, -0.09967034763491985, -0.21229560617239768, 0.5697413449479685, -0.33752083603028504, 0.1099730086514387, 0.6135896282792587, -0.2316015516647347, 0.27698810246217326, -0.41050437696734554, 0.27114015297957794, 0.5172821702323088, -0.8557836333808082, 0.1431613671576169, 0.26614523302465865, -0.9784779658422884, 0.22069893362397217, 0.4698093606975688, -0.3444787910995501, 0.3215750648265838, -0.1275396420123813, -0.16744367567541496, -0.2865130786194499, -0.203914306582315, 0.09531066543160083, -1.0473530567418816, -0.43792746630963003, -0.8246099035388195, -0.1995013012675149, -0.05971337685132197, 0.07864737594828375, -0.7640329802075775, 0.7133374177394672, 0.3450741117987123, -0.6613122911561858, 0.2175616273524131, 0.39585440284780726, -0.6045817099745175, -1.1406619528893633, 0.06642553919379446, 0.17478825655989105, -0.48174098942017146, -0.5192782669857927, -1.1714093392113059, 0.5938325737824399, -0.482930381615228, 1.078819781022143, -0.8684695968207783, -0.15775647868438034, -0.19836857010162148, 0.12721713278404426, 0.20363848723966207, 0.11179394420943511, 0.49603448462048155, 0.3600952668625213, 0.3128222724984558, 0.404650588027724, 0.0840823881356966, 0.19944902798724976, 0.12426183303095407, -0.6113147369273974, -0.40558552009503623, 0.4393747149838387, 1.0064976254947864, 0.02535220524117529, 0.6867814865985039, -0.4423754966018487, 0.20201446246914118, -0.697738158333364, -0.9883884469952561, 0.4564284783687155, -0.9310257794603739, -0.7670742706760328])\n\n # 6000 Pop\n # runGait([0.5833710183294218, 159.94477382941363, 0.274991231117698, 0.238089263008252, -0.1417409643619611, -0.12761521449834923, -0.19289461538039873, -0.10856112933014755, 0.15968577636162862, -0.17368631551323016, 0.07203736702130702, 0.881941236232128, -0.49131125475461257, 0.41963359660824545, 1.0286266905353563, 0.08461166310190373, -0.0930092118460774, 0.6688730971003121, -0.5272671341802382, 0.3759165556754689, 1.0284225286200426, 0.281022494747565, 0.0009195019049819536, -0.0879260351696233, 0.36182544936252586, 0.1544240116221797, -0.3379165966729512, -0.07107860607401342, -0.35347372811378175, 0.24474628711192828, -0.9554210776881508, -0.2446425071911576, -0.21834542364787896, 0.02941224160898587, 0.19860309964710376, 0.32015885118565973, -0.38463037767537034, 0.2721652517032083, 0.4498871803091191, 0.2843738257583236, 0.501327523282536, 0.669013035550511, -0.37715689084783993, -0.7193636388118547, -0.2383013342521316, -0.17489396233602697, 0.06083890600102712, -0.4034525364101677, -0.24583511137643727, 0.05016350547975096, -0.5231072760701854, 0.0920601174252217, -0.3798879187489547, -0.06425162833626528, 0.1175629295006112, 0.02682125752619795, 0.5075090858782456, -0.16206766607753353, -0.9027943006438802, 0.5191380547248162, 0.1922772367714138, 0.3722573359482723, 0.27824784135917774, -0.36599087581441164, -0.06620007679763394, -0.37707864764924415, -0.3432745401212583, 0.1890972969239655, 0.9771314779636118, -0.6379190437437263, 0.5327515128308239, 1.1266802573644779, 0.4853618562003829, 0.03715655903182573, 0.07311510274068314, 0.5423300464375319, -0.0658356136420452, 0.6733211262326829, 0.5412515512543659, 0.475841545559648, -0.5369352656406974, -0.026774867624149132, -0.27366768812094183, -0.21535394823513682, 1.1272641607914005, -0.6324828192170618, 0.22992240750612652, -0.8332942275738103, -0.4448812583609043, -0.5639998583724821, -0.28504303170819406, -0.13715306369785674, 0.3349484025718961, -0.3700368781101578, 0.20300787227134326, 0.22374862961672667, 0.027970795265832554, 0.7014861172229404, -0.04926493320095343, 0.4402290874741377, 0.3860194514832391, 0.11569030596073443, -0.06036997313965854, 0.1497256975919505, -0.377481545800565, 0.08298090520892161, 0.9438244188255105, -0.48021805376469584, 0.4543715274216308, 0.8678356926851799, -0.003915278924756722, 0.10352872557178089, 0.3358865719916397, 0.4211155579389066, -0.030249314775129762, -0.5658285551195321, 0.2548939424634452, 0.5745275199121783, -0.7796534931283465, 0.3451123282022226, -0.5444761756627212, 0.12200790829540269, -0.25898916669720645, -0.6724214809633824, 0.34635133694786935, -1.0685493620290625, -0.166454962800517, -0.8051985252291386, -0.4306033386198576, 0.3621432335285329, 0.014468787338504891, 0.141080510173102, 0.13964744684544284, -0.15421615523049945, -0.4317859615807832, 0.225587551388641, 0.693207792900198, 0.5533948757767216, 0.20097437713556277, 0.23256665133179352, -0.4990635733731684, 0.37724815041759296, -0.8484710927328951, 0.052329062943848995, -0.6454186305205749, 0.01709338435440333, 0.1426615820133712, -0.7496362823830726, -0.024592492969917387, 0.07160640453502068, -0.2474844962946594, 0.5941575845367926, -0.20960304431184107, 0.6424578239764861, 0.2920273219156567, 0.7036560308915455, -0.8121144845665177, -0.2789410770162129, -0.7413476580353197, 0.08188596178827257, 0.07931227840034549, -0.7207975890283618, -0.6065813517836143, 0.3983191376566657, -0.5635381703226274, 0.4088177741187736, 0.8161358908559947, 0.6554301845419963, 0.04547395492205422, 0.08051995385752733, 0.7945827746307063, 0.11087351442670304, -0.590752837198396, 0.2065658076101474, 0.0751712923684167, 0.6709125887262557, 0.1373187383960103, -0.18183312802940133, -0.4350057499267376, -0.3766430661862623, -0.8199596582372628, -0.14153603961297806, 0.590381220135425, -0.16508543450631305, -0.20708569485397604, -0.34591459093209215, -0.16651848898298874, 0.5178287410957361, -0.03657852374819068, 0.7219509009910949, -0.22937310869060928, 1.1464596068133195, 0.21233031874020497, -0.3609307120798186, -0.41136793770748015, 0.16347336752562386, -0.04569336581669571, -0.12320285070861678, 0.08240315222323638, 0.4579164525630148, 0.10194743670878537, 0.5748048740706077, -0.38484763478500494, 0.8009525610955103, 0.7333605699869847, 0.37124845323434263, -0.03501117975518403, 0.012948485735009754, 0.29139932552493186, 0.34343670572619495, 0.8542624160112243, 0.2047939987143607, 0.3903803959743837, -0.20493239305818473, -1.1287011492813999, -0.32936672671984124, -0.36581898984821176, 0.2451494881151558, -0.5756460181132672, -0.030221322542399086, 0.16449751038968874, -0.3567999251278406, -0.1618212236300447, -0.11207687799559582, 0.05735981109003743, 0.9415542138674963, -0.3554473551841668, 0.5357750527639715, 0.21498207309781378, 0.4532008047694893, 0.21329882952215284, 0.5859846457864504, -0.16362093353740018, 0.1319546289160159, -0.2194715016448026, -0.266878066809855, 0.19007538470038587, -0.6214579041470789, 0.07758190484905561, -0.7515667963793465, 0.24700843522334995, -0.292447662725082, -0.4181253106644778, 0.19564903243421003, 0.19724000917384554, -0.2063833311816462, 0.46455125472211967, -0.0899164519697946, -0.4859666940225116, 0.2204956850628324, 0.5537344147667811, 0.3710020504693896, 0.42084808456566025, 0.22826893049722402, -0.3009973798887208, 0.3133299056345898, -0.5362470634819437, -0.07363025268708201, -0.4903844709824772, -0.4212031706808154, 0.593200663984306, 0.03428638943992187, 0.24491294188014479, 0.46221509482741235, -0.20849095803967968, 0.6337473393725238, -0.05747450930384633, 0.8875435750416844])\n\n # 0\n runGait([0.7387319894185713, 147.82355001579506, 0.6305372633499426, -0.6089588304954848, 0.8912756231059142, 0.2812261582743101, -0.5713260153151064, -0.17272091345083518, -0.011128621604706623, -0.802059235021269, -0.07153954960452258, -0.5428904527014263, -0.04381109750503209, 0.09113787494874881, 0.7723570365515549, 0.1241992107232388, 0.8337401506855846, 1.115458030805498, -0.013540807256189336, -0.5839520097163835, -0.7340746975491128, 0.5868023045338302, -0.9298983610216932, 0.5438917235683132, -0.05782837894738324, 0.4198029392031244, -1.0399101725816757, -0.06612708025138092, -0.5082125750188753, 0.9201548240864632, 0.06444257109533891, 0.3314957278066273, 0.43523252410016, 0.0101257284239189, -0.3455692282668785, -0.11991854934521307, 0.8938694635098376, -0.5612059600360004, -1.1311528570896223, -0.5932545380125831, 0.4344991139274895, 0.3428898066225319, -0.2906991777632436, 0.48606253534779564, 0.5357348004370723, 0.08998319318443504, -0.9267085738943713, -0.8937243514792317, 1.0577416788427096, -0.37068573549717954, 0.9165099103165408, -0.8428317356586791, 0.6907079780081538, -0.763945038433602, 1.0409972769402867, -0.7930695812727582, -0.45187653759465174, -0.5161324587418127, -0.7914439627122227, 0.833033591113862, 1.0408039580092332, -0.05381107166535859, 0.8438281153722502, -0.0387362598590002, 0.6164861225837377, -0.6286851880995831, 0.8640915900752995, -0.7744000726632477, -1.1733643185821832, -0.09815300085455836, -0.2477118609768313, 1.024101066375414, -1.147511226358933, 0.35649235792115364, 1.1024258715004915, -1.011618835769622, 0.5915335712528709, -0.030590833481361157, 0.21394935583673327, 0.2677965469007608, 0.5549362872301691, 0.2695802858891776, -0.8655473520001171, -0.13250526441705102, 0.17727687014444649, -1.070467039423309, 0.09651563983885625, -0.9558246154936185, 1.1511036912990131, 0.8111082334542412, -0.3165391333624401, -1.1028022950228613, -0.8702156791239426, -1.1681706777717666, -0.652290858655339, 1.003148181057313, -0.10090114268197192, 0.23187888015208769, 0.5941647728264801, -0.43999609085011204, -0.11509272070881571, -1.0798002236171276, 0.018290046530861526, -0.7279320899826196, -0.498825849932375, 0.5922026329566983, 1.1770495895717317, 1.1658461699766112, 0.5387616073370702, 0.6762210875494419, 0.564309749770725, -0.3035549596906124, -0.23885528257994526, 1.1072615720375825, 0.5666318535111361, -0.45569851974439834, 0.8338190610059566, -0.6359449813770147, 0.2596402577409722, -0.7767216770530929, -0.90418267806025, 0.113288160612949, 0.39315211887973467, 0.15879221931780196, 0.758361875600458, 0.8700712002631037, 0.306520197643136, 0.7532325435435356, -1.0353300637178853, -0.4455790005356547, 0.33046558165864237, -0.41986999994668306, 0.773773975624336, -0.5730775662391308, -0.32242207870145256, 0.5695427482221903, 0.06540060708986029, -1.1068765041634638, 0.8444999211248407, 0.04543079459398691, 0.4642442589105744, -0.6039790052127436, -0.892455957263908, 1.1129699696404938, 0.342772182719143, -1.115584864083039, 1.0625540212723195, -0.057194100238716405, -0.5879196602166177, 0.5790752639491412, 0.6440806383356259, -0.7481329504140624, 0.20534187872140564, -1.0990982256561714, 0.2791331755311888, 0.20300461353714883, -0.8197464538582441, -0.7741517445104196, 0.36122048253607164, 0.813782786457911, 0.39582928554897623, -0.02580819987456784, -1.1628778529586477, 1.0745713708553488, -0.5089798478319643, 1.0062303026439694, 0.6478357664888437, -1.1138156319365986, -0.4955658167644643, 0.01673202498902171, 0.9162968925255734, 1.1449260986124963, 0.45197676369281314, 0.4913407885919339, 0.9059066063082057, -0.6513168739283108, 0.08060475225758434, -0.8062943072398908, -0.5854814411007928, 0.8888342908698426, -0.9445568643031321, -0.7753945536759548, -0.3003503278781188, 0.6951193721206237, 1.0356586073990068, 0.8830749880175515, -1.0664223102877843, -0.609899276809712, 0.8167470737757756, 1.038925181199521, -0.5200440777902839, 0.4128415160980885, 0.8988517426568858, 0.23012308000225246, -0.981407304217973, -0.6000864286294282, -0.8302474366129275, 0.3022460425741058, -0.7232702813935017, 0.3225916050209834, 0.1690591643089261, -0.731263207027456, 1.0793778048303206, 0.6724712011076479, -0.7393802772190122, 0.52180702196962, 0.653704773120031, -0.8435500860065721, -0.503370357216786, 1.0089409411880252, 0.8239113158523748, 0.5789158304017497, 0.8017043064577623, -0.81666613981439, 0.4674783795387365, -0.44533480654686275, -0.4893466194479631, 0.9007928200059672, 0.02483073138245584, -0.5944238649035959, 0.28518215854040774, -0.24733421237552355, -0.8505607276413669, 0.5571358775523416, 0.9045395124615454, -0.6657820640979742, -0.9652597006250097, -0.4591179819423816, 0.05481742210849316, 0.28907992231884405, 0.7124381991670108, -0.6030190226588272, 0.3369808339189879, 0.3038297672106993, -0.995236450812498, 1.0777162746217996, -1.1439340008569936, -0.7047632734591232, -0.532467147310556, -0.7640334064115123, 0.9758524528369246, -0.24433882388927364, -1.019693761734842, -0.11397606855688958, -0.26140300759258983, -0.5755519362573679, 0.15416561480192903, 0.8157008073605059, -0.988078686018823, 0.7532529999268318, 0.31269649944522704, -0.34261705061474756, -0.8905985767822926, 0.6096508828791698, -1.0668100653950248, -0.379130418894862, 0.9096912331462104, -1.001701666565123, 0.6416783457901682, 0.14610426544728483, 0.7031005674547539, 0.4247842879063306, 0.4021107592425244, 0.8928714878416208, -1.089585355806771, 0.5386513324462168, 1.043195877742578, -0.9701398946532979])\n # 50\n runGait([0.6109376305551025, 147.5781875317787, 0.8620634914832349, -0.5626015076241742, 0.9150007577136691, -0.20417512686545095, 0.6544359094278946, -0.31327506130394855, 0.8452968857390276, 0.13887431059938735, 1.1771529929786608, -0.9178071433237085, 0.21286308614656976, -0.6984312985937364, 0.8250658263071654, 0.38678895878185166, -0.8386364979015601, -0.8324431895189177, -0.31964574670169177, -0.9513705765809792, 0.7833723510749697, 0.9633303649676936, -1.077086285278876, -0.5823511574760045, -0.24329005344133708, 0.36075110180937114, -0.8737875239530779, -0.7120336903431772, 0.9694421297627523, -0.681817972163381, -0.7263666665964092, 0.04202279641735396, 0.5376884588766628, 0.5528900104757648, -0.3762309750477318, -0.5347146669245599, 0.30309856425260817, 0.02701219403931735, -1.1761371301420371, -0.3097959495083542, 0.637250448114133, 0.45383108548435047, -1.0293681131385823, -0.34337946728402396, -0.20240409776563223, -0.30376152527443845, 0.18856656091055635, 0.13958997918335925, 0.14259244107987795, -0.3669671234254508, -0.1371355859726133, -0.3999333309862724, 0.08190816860672162, 0.9531999241577855, 0.4305115008592596, -0.15969404241405846, -0.10706207687230784, -0.5875234717318174, -0.8888652093021814, 0.7018823816096099, 0.0097155460541066, -0.31852823774787353, -0.7161533552571332, -0.6946183251839217, -0.44771872458142625, -0.8020418614747353, 0.08697562850763507, -0.33670122865676794, -0.016255823485752413, -0.44553776220063407, 0.7067040729755709, -0.3305529141109416, -0.12353152419246438, -0.06405724257227025, -0.4289379681288039, 1.0169932699634694, 0.9219679687362414, -0.07926430997569933, 0.8461155106368546, -0.5108459915920485, 0.01721461698106075, 0.25640166227431, -0.0012638280470829346, -0.32081211955480904, 0.965518227098844, 0.07977377006028907, 0.9914084076788008, 0.9368602392194756, 0.79622005627768, -0.12120211619815363, -0.07642712418177038, 0.15250148243132808, 0.8820133072304428, -0.15324005900457768, -0.012947970781577268, 0.5314107654179234, 0.2657806659207431, 0.21867155408318162, -0.5645131510256867, -0.16370059560939496, 0.2210581088064703, 0.39055811273202895, 0.2826802498295499, -0.4229943862011821, -0.835900738908754, 0.9612898958738532, 0.9962752356339487, -0.053303884261599155, 0.30951330649963815, 0.34386442126447203, 0.3167278260159818, 1.0850909905354877, 1.0088643013546652, 0.6148040192088533, -0.32713499022688375, 0.13265347253599408, 0.729050651796031, 0.4385817170037452, -0.8104814221892234, -0.08204642341024995, -0.429968478624448, -1.1469995240847928, 0.05053455747353239, -0.6868806082011671, -0.7681702363623998, -0.6240472813916106, 0.8999904570363008, -0.5540755976757679, -0.1395815200095187, 0.7216419755694113, 0.00341887019974102, -1.1314219417339941, 0.47079825372218626, 0.38634641962439187, -0.4969326894940178, 0.9700897618329442, 0.31738524085942643, 0.5918654468120178, 0.0649345288163781, 0.9223422749742548, -1.062672657821793, 0.30896020749191433, -0.28885102187939604, 0.5103642056497637, 1.1586385214620625, 0.47011741255653366, 0.7362591411689603, 0.695808261288789, -0.6331424834334121, -0.6156728717869878, -0.6958300056305404, -1.1223768304439534, -1.1079218078030504, 0.4832955305303133, 0.7872713684414188, 0.23742695514821588, -1.0325192716558655, -0.5035525254625557, -0.11125895540865731, -0.06707968995471164, -1.0901891398628312, -0.05185746626132734, 0.17939884745186596, -0.7629342237736646, -0.25568469662030346, -0.3436266275846107, 0.5234963038843524, 0.532265503526556, -0.6045831852953002, 0.9974128911214244, -0.17925607028201557, 0.5791020459001643, 0.6873833790287516, 0.21880371572846155, 0.11009481032702205, 0.12865186069194162, -0.3268975846759916, 0.02259596959226029, 0.5559932137864555, 0.5932843214246097, -0.3710969455539212, 0.14529725265287333, 0.7044006452814845, -0.008852974292849092, -0.6124416737681215, 0.9682131380447476, 1.1375649719691259, 0.37091879445775916, 0.9352732490378375, 0.1539095660283667, 0.777440000897248, 0.22606717389632985, 0.6069013838761509, 0.30093397706517244, 1.1442039256026204, -0.7161426712243226, 0.588887225888025, 0.6972839960175987, -0.3500160949784321, 0.5128375679350539, 0.7935689766031192, -0.19559794779993978, -0.6253604887410248, 1.0145936629813255, -0.6706586307879839, 0.003436295592896238, -0.417246076528322, 0.8556308147276876, -0.209938526431461, -1.049104873280623, -0.33207489467651996, 0.6814354585137341, 0.3417057443470919, -0.059172559496654564, -0.8715300782572717, -0.2556518530893984, -1.0671471245233821, 0.3614377209651649, -0.15680078741943126, 1.166195067305183, 0.32081449773971193, 0.18756280575004247, -0.19985672490920128, 0.7805915689741869, -1.0536988894142132, 1.0857317947415768, -0.48900363536886143, -0.425774798688516, 0.17741903723193003, -0.1303947078559029, 0.9502549942826287, 0.5361055442035286, 0.7290061426453971, 0.29795698418990374, 0.26959259813541037, -0.8620031075888178, -1.0011321698786917, -0.48116523293039026, -0.3455270947267371, 0.4655510054575944, 0.21073592473488212, -0.7393279519987309, -0.7331986835493073, -0.19722904469418162, -1.0802395643312521, 0.2934313950761999, 1.1402520649753152, -0.9086071535929683, 0.02395654499079075, 0.3684164909317418, 0.5614399969048851, 0.9946642592430968, 1.124476487906898, 0.19575442149823322, -0.24851818064192416, 0.3905054965095121, -1.0073781554239616, 0.44320833092972917, -1.167994336275549, 0.6853930357205337, 0.09224681578137976, -0.9244241472672434, 0.32327571642704045, -0.08511712913634017, -0.1417785078648055, 1.0629206015460837, 0.3359763967683185, -0.30410336954697426])\n # 100\n runGait([0.6640463205265905, 140.52675516067927, 0.8199810222722016, -0.25481952456604723, -0.3425457104430286, -0.29895559122008386, -0.03691952728541809, -0.2926749796378846, 0.32589540084946145, -0.917897553277117, -0.1788579132316635, -1.1021614115353857, 0.16879565842355682, 0.9654926553955153, -0.8262395642035657, -0.032366000748803886, -1.035706777515601, 0.421355764319076, 0.7572712816111169, 0.20885822322721553, 0.4327161270350611, 0.9459811540427878, 0.8261945712691102, -1.1252075254946101, 0.47151105047328135, -0.20370646005147414, -0.17791531392877594, -0.1951822044066674, -0.3347713397441206, -0.8437477462605121, 0.6043792513174889, 0.8135465977213642, 0.1161484116712968, 0.2520589879602344, -0.013875994605011654, 0.6015180797865725, -0.6176009285822545, 0.12004417622115887, -0.9961965091337416, -0.3125071727309118, 0.8937107026868603, 0.08912944387701997, -0.06790816311341702, 0.22325347059753536, -0.09025762128409298, -0.011920073737759995, 0.35752949513101395, -0.45906903012374745, -0.788562694194514, -1.0050198450114056, -0.0361372172292605, -0.5954885246272503, 0.26895619166201407, 0.27184604863769407, -0.37353950677917513, 0.40112354341843237, 0.6375471269499228, 0.3141153522934928, -0.9509274229231759, 0.8779304554614856, 0.04594048324209277, 0.2495420932435201, 0.08241559351660238, -0.17642988998764342, -0.4447938485357037, -0.29330972785416387, -1.1174363806073722, -0.9616482147806933, -0.11200817025193116, -0.2108973739829038, 0.7633783825024583, -0.3175711563677784, -0.055385576075883194, -0.23831266165748738, 0.08104352235723783, 0.023356401512964642, -0.24320747848452665, 0.5859836965526846, 0.5423632994485224, -0.1667373762787313, 0.28209152742387117, 0.57278826903801, -0.2032795427955932, -0.4025112301636612, -0.5183539956075682, -0.19265157313585188, 0.17583720556492372, -0.5476355988504892, -0.6627234804934719, -0.11118988812304811, -0.7805070621113364, -0.4529826769989489, 0.7097466060065737, -0.620126964770608, 0.17005073215107458, -0.310351639008707, 0.7097004232177474, 0.6271790085262221, 0.619307086397858, 0.8131713488548474, 0.1497738579998278, 0.02526583014944417, -0.20005273447658806, -0.5474277783268228, -0.9924782021468856, 0.5028217189827595, -0.19263703499936438, 0.20588243107956172, 1.1385437676064627, 0.23883082558624708, 0.004571684392304376, 0.44876050879385027, 0.12812072388391504, -0.24208052529798593, -0.11013899281343525, -1.1196512365364517, 0.9507652902470094, 0.4545046069675115, 0.011125408478537602, 0.6549444015747156, -0.9034580752892476, -0.816680671954233, 0.42267629830319997, -0.610277202583551, 0.5500134814297155, -1.0434024414406398, -0.1937217218579826, 0.5755930968565269, -0.3839059765475241, 0.5719780788906925, 1.0347321090545003, 0.44370082946255346, 0.876765248918222, 0.2923665942100978, 0.9325649935073932, 0.5916765606714397, -0.8204301829871634, 0.5375111299520478, -0.9513662298918846, -0.48330360663587535, -0.014861243621365067, -0.7494281866976655, -0.08825309305806134, -0.9149440954101552, 1.1656564955027569, -0.319007800832239, 0.24788655005464028, -0.3902252669018448, 0.37813696098203525, 1.0257086358944083, -0.22782064462614982, 1.0142953972331836, -0.09326047201660298, -0.9608786031964357, 0.7922821770960228, -0.5752078753307402, -0.8741277024150452, 0.42074556397962476, -0.17088790293716782, -0.27812595030330334, 0.16024650373276178, -0.9015926997014683, 0.16765286991610046, 1.0745410173910972, -0.6109232086797313, -0.6866105711698087, 0.9586175739077698, 0.36069963154315404, -0.8179673245547332, 0.28221064021521486, 0.07881056395367772, 0.9621841067996804, 0.32611659794735176, 0.44963057094757963, 0.07055641109546117, -1.0165648669301155, -0.03825226786436686, -0.2562167100164272, 0.7081096623524648, 1.0925864874641888, 0.7985534527556107, -0.576117648391484, 1.128905296865967, -0.6836316776207304, -0.2843403105351967, -0.2875350090436179, -0.8884226806370785, 1.0867043497721995, 0.15936102064610103, 0.7213678990932757, 0.20189075328906597, 0.21909012756117713, 0.35081305063305934, -0.5533491342604271, -0.39139018059751557, -0.6063198386438513, -0.5324644497030327, -0.9211774284351677, 0.8014720982812371, -0.5110042508153627, 0.9729234799472499, 0.6198329213846822, -0.7172777918874114, 0.71393306635313, -0.8845569787211464, 0.8037248436039608, -0.4005762723352054, -0.41068663652781295, -0.12408256332477458, 0.2156827075982222, -0.5842278773022845, 0.5993604325472786, -0.1714832792903668, -1.073883900675711, 0.5300023789111741, -0.393565753380665, -1.1077691155993767, -0.19722587955218868, -0.10417172968555885, 0.6584848022547337, -0.5329152183955796, -0.3950555151941949, -0.10882724704645816, 1.1644009182829218, 0.1641879666963921, -0.6681618516093505, -0.927583868963644, -1.132447578431215, 0.9601897942960477, -0.3719235237813504, 0.568283689266319, 0.30050241478858897, -0.40449584730595933, 0.4561858885619927, 0.2909602044742249, 0.32523163443121184, 0.42755122870221796, -0.43174561514948073, -0.6752553468030823, 0.4204116282761027, -0.33022122289804556, -0.10054716261882779, -0.4499960947229804, 0.5718195749224134, -0.7769045028417172, 1.119286880787453, 1.0339119406352926, 0.05274713166468337, -0.6460257891457617, 0.8332178051984421, 0.03159851737606184, 0.4659457011446515, -1.1466040486387152, 0.40969329358334694, -0.055850231800543215, 1.0507510732129994, -0.05830916713550008, 0.6673647072199382, -0.93841995086702, -0.5252036523060817, -0.4085500615196542, -0.04419643170246719, 0.5892251042672283, -0.07265048037271993, 0.6495073424232363, 0.41894378985827774, -0.12136863342675985, 1.0354604832131513])\n # 150\n runGait([0.9676294826559563, 150.70882987508452, 0.7774265785769597, 0.30438411789744857, -1.0457358937004009, 0.06569446508772794, -0.15498365774078185, -0.2377622141182121, -0.5523307256530675, -0.08686467446610878, -1.0526089743219282, 0.8693892350692811, -0.17802396330235765, 0.984292423423254, -0.2150566341031429, 0.06941172841331614, -0.3042670031127815, 0.9739683090160918, 0.3387525680108089, 0.16403610960584877, 0.3348632802624376, 0.726765357781341, -0.9126961896061363, -0.7229583630620422, -0.3051251400627612, -0.18571836602256658, -0.31864411222929206, -0.19706640874261128, -0.11173710313723983, 0.3565369869153394, 0.1971428113859381, -0.2763605210478526, -0.10988448914397031, 0.4865331848012372, 0.19579861099733442, 0.0985008925024958, 0.10508611443908723, -0.5180802186096138, 0.602575401604621, -0.8201174052127542, 0.9018628672824313, 0.0498784872337901, -0.521071153653444, 0.4481479231233141, -0.2524266051402479, -0.253402947342113, -0.3651587489535104, -0.04675187762525251, -0.5284469398758529, 0.2654544927821044, 0.46605508251848005, 0.04966663957014836, 0.2745167545365336, 0.4868187826011344, -0.1497691281628623, -0.19339266529087248, 0.24136863629471383, -0.43924814954512725, -0.6263279786320504, 0.8484699492362705, 0.1585129887321573, -0.2588768245023081, 0.4805335508720735, -0.23474437738054899, -0.33209420118866895, -0.8818001009909548, -0.3070185272881074, 0.32004109284523, 0.6027386544692759, -0.6121775505303508, 0.4490581540464468, 0.5642596329992625, -0.04982483368519975, 0.12126979404157245, 1.03751465671718, 0.3745312020424947, -0.047861781623897426, 0.23215652576049822, 0.48636218211863, -0.1235050817634415, -0.43294538682063655, 0.25467725985917183, -0.3065392897369155, -0.1557890602814631, -0.1535446617220671, -0.594059819196811, 0.2979599287648182, -0.47393639849675195, -0.1498269458086204, -0.5013840640153254, -0.4272045457213613, 0.41099576969282453, 0.435974275195693, -0.4947517141811753, 0.5589410579791683, 0.1652474308641266, 0.40923547743201916, 0.8096533414423498, -0.1614737073645072, 0.1666180159560079, 0.11988387794171795, -0.07807848102820575, -0.7442135781834419, -0.34406828342523743, -0.05221941010307851, 0.3010681255245467, -0.5477604345796725, -0.48790074433118147, 0.5210477108826119, 0.8054612805115671, -0.06963557072433436, -0.15839013687807313, -0.8487419175268571, 0.10322897440577106, 0.28014718041568193, -0.34631485812371793, 0.9430752549792686, 0.47027663953356336, -0.5794821932554436, 0.4692452807674205, -0.11158040045677747, 0.27992277267081245, 0.3776130667252946, -0.6369352430800613, -0.2996620853089707, 0.15891663821065996, -0.2687942812407239, -0.4471464630512332, 0.12797248611817225, 0.03778787082978413, -0.04817441866063496, -0.14364337110596323, 0.2456276684919766, -0.2193460148147342, 0.309322461049816, 0.8838971330552886, 0.9139067446448306, 0.7520794039116794, 0.3506023525822065, -0.25510377807771967, 0.16331308210797202, 0.8879935062411524, -0.5959693041241926, -0.20759495151814522, 0.2108418708456552, -0.7452310360910046, 0.12664881554927482, -0.047080807460529284, 0.4692849434023498, 0.7458543281348985, 0.8107049435101739, 0.7656829635908563, 0.2585428684080011, 0.9841469724781623, 0.8620949405960008, 0.4870555312544564, -1.122938689793093, -0.35529359973828545, -0.327327233145238, -0.3160934335831116, 0.39591363428761267, -1.0579727707301056, -0.31077112675144547, -0.7938933327626483, -0.3590902641595922, 0.19493924076014235, 0.5890886736882655, -0.009036129790468118, 0.596132945850858, -0.03994141013499769, 0.07806084523888342, 0.5692918377135482, 0.4974953937971758, 0.3775889672978954, 0.12873405457093853, 0.3895539355393124, -0.014462890465162359, -0.55425962690001, -0.6132736305766234, -0.41102081373534033, 0.10835255920191245, -0.39706623995337986, -0.05463237156533987, -0.8821361662438925, -0.4293498179030984, -0.44754327412891415, -0.1880089783045697, -0.7609470792799706, -0.3607734401106461, 0.7228114557048017, -0.32350458406045907, 0.003881601223850173, 0.4645169228853948, 0.30933674367871833, -0.5511008060190785, 0.019215497706641993, -0.1901675903409386, -0.2365943643295504, -0.8261367539601678, -0.5582895426381002, 0.8430889595735926, -0.10476902705139379, -0.7224029312799556, 0.27571772103786507, 0.0885536238095041, 0.015217124065685712, 0.3616330436036972, 0.4495807925732856, -0.25846532959546853, 0.02789168870877641, -0.30766351675851644, 0.4048762627077507, 0.27121677550071394, -0.15171546326311514, -0.7757535339112696, 0.07895603889692605, 0.3394112118661255, 0.2762139076230077, -0.8609718868797998, 0.6072119320035823, 0.5713716255007126, -0.6528469102896424, -0.10679737275320846, 0.05933745485535778, 1.0330880833994396, 0.3798427665421174, -0.05376631490501693, 0.35154721956479057, -0.2278546286708691, 1.1215415803557947, 0.37551720594302973, 0.20578900503472414, -1.101421780287494, -0.16904074302935618, -0.3137973325657055, -0.31107743259952253, -0.5054336950181983, -0.6015459471353947, -0.30583499460877933, -0.5710653400947024, -0.9093940918050203, 0.4258975120803453, -0.21935467585339385, 0.7752057901473814, 0.9048914510700778, -0.7846269882405049, 0.42094152311983585, 0.579829888624975, -0.17584369852195275, 0.3434019156849982, 0.4575688137719436, -0.14604013456644133, -0.3645678519465499, 0.369472539160814, 0.8790080502109889, -0.19650675936686374, -0.18752237139683797, 0.5586386030306622, 0.9508801265095614, 0.9411240544168558, -0.345415755136577, -0.14676816884141242, -0.6025122074152638, 1.0662310264379242, 0.18388246055206153, -0.07562722289757418, -0.6679498245650091, 0.18818487201688333])\n # 200\n runGait([0.9348218778087588, 146.91267362984482, 0.8744564653177251, -0.2311034676019011, -0.0162125073980263, 0.23441739730394234, -0.04068722081101439, -0.01314909472419457, 0.4223694738439635, -0.25574717281863013, 0.11241756397861355, 0.863412621923713, -0.5039035218187172, 0.8097751196961653, 0.5091863473931626, -0.10148835532593689, -0.28922562386776374, 0.5858340382268268, 0.43524750474759666, 0.23821865739642933, 0.46385381613992593, 0.9239038510623541, -0.4014932024069757, -0.7366198054221755, -0.26224195420212393, -0.26567675307257604, -0.6406999273924185, -0.3947291539512541, -0.13202897393736873, -0.36868075869905625, -0.05946923101403889, -0.27726495980956967, -0.5626455668474689, -0.011352949007235264, 0.229512162107839, 0.39705904834877165, -0.4006127993614362, 0.45741277302226363, -0.04872220530283761, 0.939231875796499, 0.9244874997661925, 0.421354026869032, -0.30719169912092076, -0.28374626104543155, 0.036224616108006924, -0.25044075786835196, 0.45388624765306124, -0.2717804606894174, -0.4275921887976257, -0.6646840055520035, -0.14474013946854764, 0.13888294858271502, -0.6177532030009414, 0.2746798600901093, -0.12203515742935869, -0.2628136886221271, 0.38679528157113163, -0.19822470557065894, -0.8884013180032637, 0.9228748319499014, -0.4928839251159022, 0.27037805010739346, -0.36086268564047347, -0.24969367306344575, -0.3336638120272727, -0.19129594916608794, -0.5412798207097986, -0.16378037787753816, 0.8380380076966655, -0.5602998817983854, 0.18838739261107923, 0.5039137894474521, 0.21024282762391727, 0.08436579427566918, 0.6355601001466065, 0.5267180582633789, 0.15087882211657277, 0.2588579542917172, 0.8159804644068003, -0.38735187036573715, -0.40374868821921456, 0.3176228472810542, -0.29327017193023885, -0.5501866453799408, -0.7389217625605805, -0.5615715453807273, 0.3712336142992907, -0.41428358751812816, -0.10726134390360059, -0.4099102222197733, -0.09159826087452744, 0.19893389971361133, -0.13132545262706974, -0.7570399899916764, -0.04170327254544387, 0.6914142826643184, 0.398856999424931, 0.9233641685403612, 0.3554904000885851, 0.07458506209142986, 0.21135000375679375, -0.23744305079600145, -0.013330649851585474, 0.01157025728448935, -0.7142922193662176, -0.057521311631223385, -0.6442594978866643, 0.1356536272774043, 0.9557393672331027, 0.5233808828963422, 0.11374875444427712, 0.09649391854350325, -0.4504172430652743, 0.6539212469538538, 0.1418178498877025, -1.0285250393762446, 0.8140662921364629, 0.22032729153232467, -0.3131857222772149, -0.48190358196718097, -0.6137839859402877, 0.4530943681506018, -0.24490264309157425, -0.7036205243667922, 0.22880630883881176, -0.9353768616975839, -0.22729920059617795, -0.3986687624180637, 0.3771370805444293, 0.2962185862198067, 0.2904151502090839, 0.41187261747985526, 0.5568412571554673, -0.12906786905832562, -0.29816090327711275, 0.6695654120828216, 0.6511164416374783, 0.2354423280825553, -0.2735118074560536, -0.09228336036973724, -0.8324667409784399, -0.5181961380658293, -0.29006499483710846, 0.20790847562845022, -0.5417341319611597, 0.38491216942962997, -0.26276464862820204, -0.4194681593642782, 0.18074940042710627, 0.3028577666580481, 0.7988109336459481, 0.3168960795244507, -0.06708903960865052, 1.065337334032617, 0.5121231247483485, 0.4516447688051512, -1.1319252709654564, 0.36013046523298803, -0.34875120783540486, -0.4784054810104189, -0.6383425055163587, -0.6044113298680207, 0.44898870301162985, -0.8409890804695659, -0.13518983270380686, 0.7206151228912457, 0.6402573302424278, 0.10412067706361405, 0.054761428387725804, 0.7078674741419084, 0.6835347252533357, 0.21226096258043248, -0.3590529214883623, 0.4262896753265209, -0.048765644390856705, 0.38707830574861446, 0.084150534306334, -0.3647673644633279, -0.33591157304158037, 0.543209090584881, -0.9227930221772509, 0.2793779445429621, 0.11437608190319354, -0.7320684310072323, -0.6016577518295898, -0.45131872796737754, 0.05815823303022799, 0.8858937450029887, -0.0019911283316581506, 0.9972537913440365, -0.03610523718702252, 0.7079473862344268, 0.2573924393198488, -0.04475989790206414, -0.046463632383485554, -0.5773905293012538, -0.21619326250264764, -0.18188721111452147, -0.07658954437605886, -0.7681077839396901, 0.09322698951176928, 0.1445427413363699, -0.26358485945073823, -0.35945630531652395, 0.6607553408730602, 0.5395749627096668, -0.06565247358481555, -0.13117986498165218, 0.6166842950843242, 0.4062530279955314, -0.32413286459352975, 0.3382214897259326, 0.060478191467047124, -0.30111192010527943, -0.6852023659365898, -0.6491951557870825, -0.6082929168718781, 1.0411226013092971, -0.6704184953876647, 0.2345803856056618, 0.4849343305291035, -0.18728401603681968, -0.19357983579761226, 0.6070055818353226, -0.1077936670840348, 0.7443380029642911, -0.17385870614262244, 0.4822669757853692, 0.389397991023952, -0.5111936026821581, 0.20633197759969002, 0.1718434261981503, -0.4672185062811099, -0.17236565565445167, -0.13557244311953168, 0.15571859432119767, -0.7500101603166999, -0.23515066300234422, 0.13714967863221472, -0.5267606306271126, 0.13519136956396957, 0.02524328959004487, 0.5235642763509845, 0.8384859468187118, 0.8448970827991501, 0.8107454533312748, 0.5496009157719298, -0.7861009121069743, -0.6234808705813863, 0.4696984323447554, 0.47429018972121284, 0.623971023164932, 0.19594794245176425, -0.08196145489238126, -0.44583013816552275, 0.331803658493219, -0.8110909742267071, -0.21348457194384118, -0.2793726604175222, 0.14931602985100503, 0.12574273195266228, -0.09011644679991501, 0.42322007305737674, 0.4167395715073748, -0.6212842551478526, 0.7246903575782073, -0.06965771001708732, 0.6997039268852637])\n # 300\n runGait([0.9580170156701137, 156.55023833080287, 0.8697263186451583, 0.41527680177951753, -0.3091878185605595, -0.6992501726886724, -0.3621632626756743, -0.08866639808357406, 0.04011602722874327, 0.07026709630165444, 0.08310069123845333, 0.9771964256154151, -0.400666267244531, 1.0176212186192009, 0.4686604002686661, -0.05444682325152628, -0.3446318452762033, 1.167921573447584, -0.24084550251954484, 0.11520414858809458, -0.9064091144422616, 0.6287846280182579, 0.4042274363728242, -0.17984894184261202, 1.1430310808904414, 0.12829599754811477, -0.2870163134708252, -0.18392037110494033, -0.1249514559839385, 0.40824155792459593, -1.0366104970327679, -0.21924341218226873, -0.10471741599076292, -0.039709787387529435, 0.24308506785995695, 0.5029106171652411, 0.00735981801132328, 0.46310261520766255, 0.2962573675541653, 0.5716571352437573, 0.9229307062858603, 0.4495458291143761, -0.32374844918493895, -0.5428033664800668, -0.1061657887085444, 0.09327418752618749, 0.1360933416106767, -0.05729803839333989, -0.5721972886843723, -0.7501829092993302, -0.15349800908427572, 0.18791462737535045, -0.5470482537350623, 0.0694805637919472, 0.11109949906739805, -0.05080609217009568, -0.10310782753879975, -0.11306331572492027, -0.7342942829959108, 0.5899346008666371, 0.15418825045439946, -0.02081659679571593, 0.23629696966788344, -0.20051899964600228, -0.1124416281658899, -0.2846997071631564, -0.7192552571252601, 0.37433250100587284, 0.4563424915786525, -0.6333746841090807, 0.48199161211899844, 0.7988546437125186, 0.3226337048037727, 0.08751293246797012, 0.6319836666961702, 0.5183905403464221, -0.03681080646589069, 0.32577945075501186, 0.6121356022112711, 0.3422973617966078, -0.38300865284018476, 0.3869972769037436, -0.3438931711267918, -0.2925667840718638, 0.02073915908080158, -0.6601106786744819, 0.18786226365552441, -0.4674216311409396, -0.20596050805709923, -0.6805376409410507, -0.11035629757866405, 0.128064195205727, 0.25006628117465546, -0.3911802588296395, 0.2206671476325982, 0.09977946265209521, -0.8307214146667822, 0.9171381291965639, -0.4940453191512136, 0.1984116913539024, 0.16554188896519878, -0.1928373027542588, 0.035841851144624626, 0.19266064738694355, -0.5850119457302836, 0.2215164403315185, -0.5896064710472241, -0.5102020534325775, 0.7417367519970856, 0.6225121973006423, 0.19164293014838338, -0.05737129492026963, 0.6121162351865662, 0.6866768284728066, 0.14965833690587552, -0.4193640570236367, 0.8160069586540502, 0.4684910259589942, -0.3030223187406086, -0.22660524229484055, -0.26703340415352106, 0.2211243087352533, -0.34540536962148954, -0.49431357086808453, 0.4597744966917602, -1.1664564277056044, -0.42563404464543353, -0.2676448037922594, 0.10874078586225963, 0.30510521880764874, 0.0201911678551102, 0.06799655432754058, 0.2696266035980911, -0.022093390708932178, -0.23885757257157703, 0.23240754800646202, 0.3154235780471931, 0.41222261068120575, 0.21621816215661968, -0.49383086489683936, 0.22028919935866093, 0.3085302761259844, -0.7607054242258245, -0.05524612679499659, -0.4005994571597372, -0.0005409548233603068, 0.09356401716698916, -0.28019790711798187, 0.11366960643707247, 0.11455280438074295, 0.23238882534231647, 0.38151138367739235, -0.6805858547100075, 1.0336614238387605, 0.3031048722576475, 0.3326128459698742, -0.4841094623424372, -0.14572762596592148, -0.6989095508218981, 0.08856510384007225, -0.7833815783352288, -0.6051206720201369, 0.05183879858837576, 0.8525690594373536, -0.21238052918801256, 0.3064353096452067, 0.5227279651783818, -0.26970368473406214, 0.30040315174676463, 0.8044560092955977, -0.31738694194412304, -0.03793873042044421, -0.43780967817899613, 0.44695577264660596, 0.07431440259337181, 0.30468167123379775, -0.17018353015014637, -0.3717841160485929, -0.38018867550367835, -0.8319113906639981, -0.3172654371086346, 0.19103501813376841, 0.7907537210342017, -0.9089959391273528, -0.296319135720049, -0.3417512761829329, -0.023084343039717133, 0.4040896098348129, -0.31660229354210917, 0.20977471047292015, 0.06648686941410495, 0.569876899843004, 0.21573326092963024, 0.12794663668726255, 0.13345639453704178, 0.06166211393616905, -0.03240968584900304, 0.5204613173650747, -0.054310331255427405, -0.606521604737881, 0.1468424637174045, -0.10111301306428899, -0.28436289560722927, 0.8017857089530022, 0.31257612218556174, 0.1945880804760491, -0.6089705211035303, -0.14618931754382708, 0.39343797880425146, -0.5405366749846467, -0.8955466868745385, 0.24857173830306561, -0.18623545173861095, -0.3623886194435283, -0.09699504056721092, -0.3486736104159766, -0.5453068629962625, -0.04010192714300855, -0.5306328827959214, -0.1354335299516863, 0.44670333258196254, -0.29490113171676874, -0.09463147398839705, 0.874510578425735, -0.08994591375239581, 0.9780471833760542, -0.5336783066507795, 0.44298379683008876, -0.44674080020159146, -0.31978046647941477, 0.4387881341782599, 0.5350973549899811, -0.27423388863198106, -0.39599195531628345, -0.17873234672818766, -0.3297290606571569, 0.4175261890217202, -0.41268092911177146, -0.22703685041841498, -0.274965576004083, 0.18191455558091849, -0.4939031672186963, -0.5349104573630611, 0.11079268810336479, 0.29357806459055, -0.7619449431049254, 0.712338129607013, -0.10469146069165344, -0.6452483516150597, 0.27405977939835985, 0.3831614384076198, 0.5368152956549854, 0.1178851135066101, 0.4460847058945193, -0.3883316848615107, 0.29727456716368683, -0.9048653966482885, -0.014346612174598924, -0.30126039008201877, -0.4640418178366639, 0.7986905413889673, -0.07702758460544154, 0.2259118808338296, 0.04026857681135493, -0.26928463274492503, 0.3490075592061821, -0.0973833708982666, 0.6135129639803163])\n # 500\n runGait([0.7788908289099306, 159.1275018887873, 0.3675002143633652, 0.29358082034076927, -0.15802555334813242, -0.10120259171082222, -0.30648918293561567, -0.05565177235370438, 0.3049336061735364, 0.019485785927701088, 0.07832249749716115, 0.7871716752724793, -0.11324944128855793, 0.33911735703936136, 0.5918403744719638, 0.023601544667689423, -0.28854114361833516, 0.3817510406516811, -0.7632588163737368, 0.022344201194842275, -0.9273228127530271, 0.23720909885208666, 0.15504539382606097, -0.06533263447758221, 0.6586022121665115, -0.29344233757111227, -0.6100745589428764, 0.17959646981207406, -0.2567640532742428, 0.3822693241621865, -0.7185816271396638, -0.17076272358383804, -0.19398205231627866, 0.030812971237587354, 0.13867994513962895, 0.3166621409958447, 0.22733110475404655, 0.5283963851565332, 0.3000850798497766, 0.6660952670105973, 0.78894440862353, 0.5157348667100712, -0.38489800997374557, -0.5993480088686595, -0.18953762119493234, -0.142888877844017, -0.2487995360903048, -0.2553184465203176, -0.6835072531097912, -0.08818770700477133, -0.36234611577801024, 0.1882081759188938, -0.5403677941379689, 0.12135448182929069, 0.13736905269298347, -0.19255224947663963, 0.40446549296965023, -0.12911247255617248, -0.8830555265743198, 0.5421547081545663, 0.19311176458866605, 0.32721151153007055, 0.2615659111455483, -0.3394759597454976, -0.06908691052009064, -0.4945679102133535, -0.664437236127388, 0.455900172021705, 0.9711538928263904, -0.6122014695612167, 0.5055842831599157, 1.0056138878174767, -0.12461961762482054, 0.07270199762420153, 0.1945368404538606, 0.6057165296982737, -0.036218178124653, 0.47457880179122397, 0.561082214156418, 0.5518568617850256, -0.5389721874824412, 0.018553983034344634, -0.33762141187925576, -0.2910578505162613, 0.14535357070447755, -0.5450888267216742, 0.3147936923887069, -0.8630308630441204, -0.35532598921412856, -0.6465004633853288, -0.13894664477940558, -0.05983048923837514, 0.365281504661632, -0.5068437133042195, 0.27739826556422653, 0.19813563846913917, 0.4204274997035509, 0.8205768952006834, 0.20430739373514373, 0.3485830076102606, 0.19097357428020537, 0.11039935013513971, -0.05699918798476541, 0.17873025134016074, -0.5020918329264104, 0.06913567443773855, 0.824576743344076, -0.5181143051990277, 0.5324747932677494, 0.4047169187725307, 0.17512694920182592, 0.09027062872679636, -0.020184312316256805, 0.45759775735791614, 0.3541811364432514, -0.42810856403905084, 0.34330793691017164, 0.37803887536859593, -0.6335568031247926, 0.7451449971471023, -0.422905787574568, 0.1108746870208986, -0.48281598513746043, -0.8845798783329725, 0.2848773437400216, -1.024048537916983, -0.3564009884656577, -0.12474613038765203, -0.20868110635282452, 0.34321844967647513, 0.026989145418742592, 0.0056243347284405665, 0.2157974836543368, -0.13733758298445253, -0.33659375632067434, 0.22898564273416638, 0.5087202771881477, 0.5372813556304213, 0.2763875601801632, -0.0931809119638537, -0.15966469444157633, 0.6929648835534945, -0.6910669985856048, -0.19389406110887974, -0.3902847322396408, 0.14551156290910644, 0.16618646822053293, -0.8039787804703373, 0.15428898913228964, 0.2190997039624487, 0.6297767323586855, 0.679561926817978, -0.25269142672699957, 1.073396465709869, 0.29029445313069896, 0.3205284197358836, -0.8690640106312963, -0.28879170523811604, -0.3779137324309013, 0.11936316568503534, 0.12976155632213082, -0.6265683661237571, -0.4855309257343185, -0.5955282235528421, -0.6845815418683121, 0.4737288107745596, 0.9252056200075451, 0.34567749439018725, 0.0363068008180909, 0.5036072080080863, 0.7640949628326337, 0.23505279305957724, -0.7167717818166955, 0.22850447613489278, -0.030879680605631232, 0.8293535643185203, -0.12780675301767844, -0.4412923860207338, -0.4755533837206397, -0.7447986150788337, -0.351029516667939, 0.14495494618770427, 0.4535847436338252, -0.3531591185986031, -0.3501206760556444, -0.34008350299413603, -0.1719031304459102, 0.5791280201924914, -0.1307266287188878, 0.5722057672119683, -0.15710148018631528, 0.8971534994186912, 0.2136354954365922, 0.10736052402292397, -0.09859594062374435, 0.029800704664000633, -0.036340884369813475, 0.13376827373262254, 0.06508877177327688, 0.3209725597538162, 0.25401652110289125, 0.306412096915022, -0.4062443766586342, 0.8116135654848087, 0.5038625296989976, 0.31304069230057774, 0.27907345633577596, -0.0628432232149184, 0.7488103240677573, 0.26866161782653364, -0.3422913295247829, 0.2620956604170435, 0.3869320718994709, -0.31031616120110883, -0.6430657281164895, -0.22156900833723173, -0.38501223572432874, 0.253328681493752, -0.43126896631860384, 0.13122580788583768, 0.38236533839599784, -0.41315518332835866, -0.06881562913283318, -0.06011531751913962, -0.1786891777692833, 0.5379347036881686, -0.40503481008181036, 0.5715406089598921, 0.09206279188231829, -0.06971523980576558, 0.2873942092356773, 0.5853487864435241, -0.2276481518074298, 0.024954174691643023, -0.45483892434063, -0.24065990358463835, 0.009443952578838826, -0.4484870705490043, 0.020876918478014064, -0.3827342793037868, 0.08765966633266016, -0.27582852508027256, -0.31975146101964735, 0.23584006084015846, 0.29568147715946885, -0.8673046059997449, 0.731200312180833, 0.023929423446759857, -0.573758689689352, 0.20993143702530428, 0.47001185232098075, 0.5565009861719601, 0.4404197794305241, 0.185040383009213, -0.4131600591525496, 0.16851972924086844, -0.4306339258923647, -0.08726456746018109, -0.4968797363532158, 0.11631152950365159, 0.12129503091276284, -0.2797069038719245, 0.28964257172500313, 0.30047606726857523, 0.7797290276248695, 0.6214545112158738, -0.05292732565014542, 0.7730879197180376])\n # 750\n runGait([0.5798525952403486, 159.40058262811087, 0.2565373666541486, 0.4318803359566548, -0.12670809771496028, -0.18389697331663157, -0.2107828186822762, -0.08822530542530635, 0.22285787517794267, -0.14626266057699905, -0.010708372490804578, 0.8284588168920229, -0.4722713879921887, 0.19208169499854316, 0.7411503431106623, 0.040109802039862204, -0.09388586098031043, 0.3021068442167352, -0.7632253195827811, 0.7506268013480695, 0.9817795923219715, 0.24702479164747443, 0.18619723055382778, -0.01944816101487032, 0.48047453154015674, 0.044027151050185204, -0.3811611523444315, 0.07043423693100055, -0.3519428921487882, 0.06993952938115677, -0.5223378593335369, -0.22654293849301965, -0.3119867211980983, 0.02203965621516251, 0.13948563872031947, 0.303700575374144, -0.38645242345574016, 0.28023524831943847, 0.48072548736928467, 0.23302786453056437, 0.5986122931605656, 0.6980983847283087, -0.34928346917889913, -0.7471794250508657, -0.17324487759716678, -0.17474742917438432, -0.016090144920211283, -0.3939766926275115, -0.22629036214619017, 0.16700221777337937, -0.37273771647989734, 0.09062261530742664, -0.37891402716818134, -0.06917514694333406, 0.17291180959585456, -0.04844904642867835, 0.4909898309834386, -0.12380149375214647, -0.9111999943893617, 0.5239305389825415, 0.18171587810764148, 0.38432773481912763, 0.2485646260803057, -0.34491165699137327, 0.006209690525156852, -0.37412477201907574, -0.4604269737237233, 0.18972851127462684, 0.9223517018397529, -0.6210098084521306, 0.49640907383479516, 1.0891123792650426, 0.49418162637573465, 0.06420244660188437, -0.12089596773664718, 0.550748464763964, -0.06108552913804381, 0.5552559735763302, 0.5522750091665136, 0.4683531478559523, -0.49173267096532985, -0.03517143099932757, 0.06100743363377523, -0.1902922529235461, 1.1122974946275956, -0.6276776253711288, 0.18178541719252822, -0.8132832667298763, -0.4537338576551622, -0.5808862777121856, -0.23668011060600833, 0.09569218539264038, 0.304579054169755, -0.4494551817405288, 0.15870763199473473, 0.3069755905115654, 0.3959705547451262, 0.7213258637748241, 0.3763728637422603, 0.40391108748034943, 0.37339498399229337, 0.01831140131395486, -0.07811735353228262, 0.13357830561871784, -0.3758537743243868, 0.05195547431005445, 0.9379615461508354, -0.5620520288627262, 0.4539455849665125, 0.8143570677050026, 0.004283675773725867, 0.11729610271034435, 0.25800504348420195, 0.3861845305371114, 0.041281706706534374, -0.5754739036307105, 0.25496830847083185, 0.5497065484163852, -0.6197402288256176, 0.4497922477657804, -0.4509130489838098, 0.08492188046586338, -0.3745067142483794, -0.6326481434329293, 0.35798335360645445, -1.0756026955774058, -0.1658013536974587, -0.7407148571190698, -0.4210965495924469, 0.31622190189278027, -0.037060520648369094, 0.027025421714000526, 0.12225503371751616, -0.1873821138347538, -0.39270249305607063, 0.20600245925762312, 0.6985349231049772, 0.538141419017502, 0.28367589673434807, 0.2408451341677153, -0.4857764076187511, 0.3515662648369627, -0.5970692688174171, 0.02074320821791737, -0.4780204081199166, 0.1369717613278151, 0.1389681583857107, -0.7410246577802894, -0.026563078155500804, 0.15750473450145544, -0.13448669931945875, 0.6551277580017717, -0.15601141002050287, 0.7448104569077326, 0.2902755482562471, 0.5364234542988243, -0.7792137180797938, -0.2846168758998948, -0.5839320530147617, 0.0628617276240415, 0.04002665260768596, -0.5479117597172838, -0.34196183099322613, 0.7056701204997842, -0.6647297748826204, 0.42806286178547925, 1.036676035059638, 0.642474334419992, -0.007131427190290577, 0.4639036629286082, 0.7267327436184402, 0.10043705596129168, -0.6440769086811172, 0.21343864782202604, -0.10329009445544304, 0.6425250240843889, 0.05230900542901544, -0.11251073882320739, -0.35085266645906615, -0.4199713623669293, -0.3351922780693797, -0.1672466366670506, 0.5379892464340184, -0.16330627356393349, -0.056804450777555304, -0.4017389922325012, -0.1611244393278351, 0.5367215850055974, 0.26665926782883664, 0.7219467754507272, -0.23576690967651864, 0.9079195952027548, 0.2062387616905374, -0.46534175178439574, -0.10399688011724603, 0.03668728875610021, -0.036926473584827625, -0.10113397006234737, -0.0394881387655676, 0.350606385291519, 0.13403276401659836, 0.5123948398917316, -0.35772789686003825, 0.9668024245923357, 1.027298011515463, 0.48938829842316445, -0.016483670605963077, -0.11757722414303058, 0.2537310530675592, 0.2784246188624572, 0.7695997113771061, 0.20066387160146376, 0.41486141094226053, -0.41256985585307027, -1.0477965177073278, -0.3200262420965195, -0.4739320902039974, 0.1565114856750497, -0.4241862276994479, -0.014128604687211607, 0.16050204319589437, -0.40332695432173227, -0.17516701158934914, -0.11260377701162964, -0.13167892785497093, 0.7970663227025759, -0.5351328770237976, 0.5899558689297649, 0.23041684659804587, -0.15627868369477282, 0.2137694705032495, 0.5696194997458192, -0.17336701928954443, 0.10876003399835937, -0.17072054408485435, -0.329611678752721, -0.14558125057844667, -0.5971107203993231, 0.09088625634430318, -0.9113803135864458, 0.20662562476533045, -0.1850266147294778, -0.3839648611252884, -0.06266604342717771, 0.32620231538556216, -0.4511759755602935, 0.46462930437425676, -0.19098144950012377, -0.45748534958561105, 0.21835806888483988, 0.375990472674876, 0.3152963988042483, 0.4174992880580025, 0.2417839091584328, -0.24397794422280902, 0.35917942428087724, -0.3968249675417042, -0.020614707571517774, -0.5895590906441834, -0.4121546533845332, 0.7169006234784104, 0.00017719522626339322, -0.009118568606292298, 0.43285003350721596, 0.9231244888866221, 0.6350781716028882, 0.025592267149331688, 0.8892290172542283])\n # best\n runGait([0.5833710183294218, 159.94477382941363, 0.274991231117698, 0.238089263008252, -0.1417409643619611, -0.12761521449834923, -0.19289461538039873, -0.10856112933014755, 0.15968577636162862, -0.17368631551323016, 0.07203736702130702, 0.881941236232128, -0.49131125475461257, 0.41963359660824545, 1.0286266905353563, 0.08461166310190373, -0.0930092118460774, 0.6688730971003121, -0.5272671341802382, 0.3759165556754689, 1.0284225286200426, 0.281022494747565, 0.0009195019049819536, -0.0879260351696233, 0.36182544936252586, 0.1544240116221797, -0.3379165966729512, -0.07107860607401342, -0.35347372811378175, 0.24474628711192828, -0.9554210776881508, -0.2446425071911576, -0.21834542364787896, 0.02941224160898587, 0.19860309964710376, 0.32015885118565973, -0.38463037767537034, 0.2721652517032083, 0.4498871803091191, 0.2843738257583236, 0.501327523282536, 0.669013035550511, -0.37715689084783993, -0.7193636388118547, -0.2383013342521316, -0.17489396233602697, 0.06083890600102712, -0.4034525364101677, -0.24583511137643727, 0.05016350547975096, -0.5231072760701854, 0.0920601174252217, -0.3798879187489547, -0.06425162833626528, 0.1175629295006112, 0.02682125752619795, 0.5075090858782456, -0.16206766607753353, -0.9027943006438802, 0.5191380547248162, 0.1922772367714138, 0.3722573359482723, 0.27824784135917774, -0.36599087581441164, -0.06620007679763394, -0.37707864764924415, -0.3432745401212583, 0.1890972969239655, 0.9771314779636118, -0.6379190437437263, 0.5327515128308239, 1.1266802573644779, 0.4853618562003829, 0.03715655903182573, 0.07311510274068314, 0.5423300464375319, -0.0658356136420452, 0.6733211262326829, 0.5412515512543659, 0.475841545559648, -0.5369352656406974, -0.026774867624149132, -0.27366768812094183, -0.21535394823513682, 1.1272641607914005, -0.6324828192170618, 0.22992240750612652, -0.8332942275738103, -0.4448812583609043, -0.5639998583724821, -0.28504303170819406, -0.13715306369785674, 0.3349484025718961, -0.3700368781101578, 0.20300787227134326, 0.22374862961672667, 0.027970795265832554, 0.7014861172229404, -0.04926493320095343, 0.4402290874741377, 0.3860194514832391, 0.11569030596073443, -0.06036997313965854, 0.1497256975919505, -0.377481545800565, 0.08298090520892161, 0.9438244188255105, -0.48021805376469584, 0.4543715274216308, 0.8678356926851799, -0.003915278924756722, 0.10352872557178089, 0.3358865719916397, 0.4211155579389066, -0.030249314775129762, -0.5658285551195321, 0.2548939424634452, 0.5745275199121783, -0.7796534931283465, 0.3451123282022226, -0.5444761756627212, 0.12200790829540269, -0.25898916669720645, -0.6724214809633824, 0.34635133694786935, -1.0685493620290625, -0.166454962800517, -0.8051985252291386, -0.4306033386198576, 0.3621432335285329, 0.014468787338504891, 0.141080510173102, 0.13964744684544284, -0.15421615523049945, -0.4317859615807832, 0.225587551388641, 0.693207792900198, 0.5533948757767216, 0.20097437713556277, 0.23256665133179352, -0.4990635733731684, 0.37724815041759296, -0.8484710927328951, 0.052329062943848995, -0.6454186305205749, 0.01709338435440333, 0.1426615820133712, -0.7496362823830726, -0.024592492969917387, 0.07160640453502068, -0.2474844962946594, 0.5941575845367926, -0.20960304431184107, 0.6424578239764861, 0.2920273219156567, 0.7036560308915455, -0.8121144845665177, -0.2789410770162129, -0.7413476580353197, 0.08188596178827257, 0.07931227840034549, -0.7207975890283618, -0.6065813517836143, 0.3983191376566657, -0.5635381703226274, 0.4088177741187736, 0.8161358908559947, 0.6554301845419963, 0.04547395492205422, 0.08051995385752733, 0.7945827746307063, 0.11087351442670304, -0.590752837198396, 0.2065658076101474, 0.0751712923684167, 0.6709125887262557, 0.1373187383960103, -0.18183312802940133, -0.4350057499267376, -0.3766430661862623, -0.8199596582372628, -0.14153603961297806, 0.590381220135425, -0.16508543450631305, -0.20708569485397604, -0.34591459093209215, -0.16651848898298874, 0.5178287410957361, -0.03657852374819068, 0.7219509009910949, -0.22937310869060928, 1.1464596068133195, 0.21233031874020497, -0.3609307120798186, -0.41136793770748015, 0.16347336752562386, -0.04569336581669571, -0.12320285070861678, 0.08240315222323638, 0.4579164525630148, 0.10194743670878537, 0.5748048740706077, -0.38484763478500494, 0.8009525610955103, 0.7333605699869847, 0.37124845323434263, -0.03501117975518403, 0.012948485735009754, 0.29139932552493186, 0.34343670572619495, 0.8542624160112243, 0.2047939987143607, 0.3903803959743837, -0.20493239305818473, -1.1287011492813999, -0.32936672671984124, -0.36581898984821176, 0.2451494881151558, -0.5756460181132672, -0.030221322542399086, 0.16449751038968874, -0.3567999251278406, -0.1618212236300447, -0.11207687799559582, 0.05735981109003743, 0.9415542138674963, -0.3554473551841668, 0.5357750527639715, 0.21498207309781378, 0.4532008047694893, 0.21329882952215284, 0.5859846457864504, -0.16362093353740018, 0.1319546289160159, -0.2194715016448026, -0.266878066809855, 0.19007538470038587, -0.6214579041470789, 0.07758190484905561, -0.7515667963793465, 0.24700843522334995, -0.292447662725082, -0.4181253106644778, 0.19564903243421003, 0.19724000917384554, -0.2063833311816462, 0.46455125472211967, -0.0899164519697946, -0.4859666940225116, 0.2204956850628324, 0.5537344147667811, 0.3710020504693896, 0.42084808456566025, 0.22826893049722402, -0.3009973798887208, 0.3133299056345898, -0.5362470634819437, -0.07363025268708201, -0.4903844709824772, -0.4212031706808154, 0.593200663984306, 0.03428638943992187, 0.24491294188014479, 0.46221509482741235, -0.20849095803967968, 0.6337473393725238, -0.05747450930384633, 0.8875435750416844])\n p.disconnect(physicsClient)\n\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "numpy.dot", "numpy.array", "numpy.linalg.norm", "numpy.arccos" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
didriknielsen/pixelcnn_flow
[ "9030f6a66d5ff83d7d299541ed55b20b20bb9a15", "9030f6a66d5ff83d7d299541ed55b20b20bb9a15", "9030f6a66d5ff83d7d299541ed55b20b20bb9a15" ]
[ "pixelflow/distributions/normal.py", "experiments/train/exact_pixelcnn_quad.py", "pixelflow/flows/inverse_flow.py" ]
[ "import math\nimport torch\nfrom pixelflow.distributions import Distribution\nfrom pixelflow.utils import sum_except_batch\nfrom torch.distributions import Normal\n\n\nclass StandardNormal(Distribution):\n \"\"\"A multivariate Normal with zero mean and unit covariance.\"\"\"\n\n def __init__(self, shape):\n super(StandardNormal, self).__init__()\n self.shape = torch.Size(shape)\n self.register_buffer('base_measure', - 0.5 * self.shape.numel() * torch.log(torch.tensor(2 * math.pi)))\n\n def log_prob(self, x):\n return self.base_measure - 0.5 * sum_except_batch(x**2)\n\n def sample(self, num_samples):\n return torch.randn((num_samples,) + self.shape, device=self.base_measure.device, dtype=self.base_measure.dtype)\n\n def sample_shape(self, num_samples):\n return (num_samples,) + self.shape\n", "# General\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n# Setup\nfrom setups import CategoricalImageFlowSetup\n\n# Data\nfrom pixelflow.data import CategoricalCIFAR10\n\n# Model\nfrom pixelflow.flows import AutoregressiveSubsetFlow2d\nfrom pixelflow.transforms.subset import QuadraticSplineAutoregressiveSubsetTransform2d\nfrom pixelflow.networks.autoregressive import PixelCNN\n\n# Optim\nimport torch.optim as optim\n\n###################\n## Specify setup ##\n###################\n\nsetup = CategoricalImageFlowSetup()\n\nparser = setup.get_parser()\n\n# Model params\nparser.add_argument('--num_bins', type=int, default=16)\nparser.add_argument('--filters', type=int, default=128)\nparser.add_argument('--num_blocks', type=int, default=15)\nparser.add_argument('--kernel_size', type=int, default=3)\nparser.add_argument('--kernel_size_in', type=int, default=7)\nparser.add_argument('--output_filters', type=int, default=1024)\n\n# Optim params\nparser.add_argument('--lr', type=float, default=1e-3)\nparser.add_argument('--milestones', type=eval, default=[])\nparser.add_argument('--gamma', type=float, default=0.1)\n\nargs = parser.parse_args()\nsetup.prepare_env(args)\n\n##################\n## Specify data ##\n##################\n\ndata = CategoricalCIFAR10()\n\nsetup.register_data(data.train, data.test)\n\n###################\n## Specify model ##\n###################\n\nmodel = AutoregressiveSubsetFlow2d(base_shape = (3,32,32,),\n transforms = [\n QuadraticSplineAutoregressiveSubsetTransform2d(PixelCNN(3, num_params=2*args.num_bins+1,\n num_blocks=args.num_blocks,\n filters=args.filters,\n kernel_size=args.kernel_size,\n kernel_size_in=args.kernel_size_in,\n output_filters=args.output_filters,\n init_transforms=lambda x: 2*x-1), num_bins=args.num_bins),\n ])\n\nsetup.register_model(model)\n\n#######################\n## Specify optimizer ##\n#######################\n\noptimizer = optim.Adam(model.parameters(), lr=args.lr)\nscheduler = optim.lr_scheduler.MultiStepLR(optimizer, milestones=args.milestones, gamma=args.gamma)\n\nsetup.register_optimizer(optimizer, scheduler)\n\n###############\n## Run setup ##\n###############\n\nsetup.run(args)\n", "import torch\nfrom torch import nn\nfrom collections.abc import Iterable\nfrom pixelflow.distributions import Distribution\nfrom pixelflow.transforms import Transform\n\n\nclass InverseFlow(Distribution):\n \"\"\"\n Base class for InverseFlow.\n Inverse flows use the forward transforms to transform noise to samples.\n These are typically useful as variational distributions.\n Here, we are not interested in the log probability of novel samples.\n However, using .sample_with_log_prob(), samples can be obtained together\n with their log probability.\n \"\"\"\n\n mode = 'sample_with_log_prob'\n allowed_modes = {'sample_with_log_prob', 'sample'}\n\n def __init__(self, base_dist, transforms):\n super(InverseFlow, self).__init__()\n assert isinstance(base_dist, Distribution)\n if isinstance(transforms, Transform): transforms = [transforms]\n assert isinstance(transforms, Iterable)\n assert all(isinstance(transform, Transform) for transform in transforms)\n self.base_dist = base_dist\n self.transforms = nn.ModuleList(transforms)\n\n def log_prob(self, x):\n raise RuntimeError(\"Inverse flows do not support log_prob\")\n\n def sample(self, num_samples):\n self.base_dist.set_mode('sample')\n z = self.base_dist(num_samples)\n for transform in self.transforms:\n z, _ = transform(z)\n return z\n\n def sample_with_log_prob(self, num_samples):\n self.base_dist.set_mode('sample_with_log_prob')\n z, log_prob = self.base_dist(num_samples)\n for transform in self.transforms:\n z, ldj = transform(z)\n log_prob -= ldj\n return z, log_prob\n\n def check_shapes(self, num_samples):\n assert isinstance(num_samples, int)\n print(\"Checking Shapes...\")\n with torch.no_grad():\n x = self.base_dist.sample(num_samples)\n shape = x.shape\n expected_shape = self.base_dist.sample_shape(num_samples)\n assert shape == expected_shape, 'Expected shape {}, but found shape {} in output of layer {}'.format(expected_shape, shape, n)\n for n, transform in enumerate(self.transforms):\n expected_shape = transform.z_shape(shape)\n x, _ = transform(x)\n shape = x.shape\n assert shape == expected_shape, 'Expected shape {}, but found shape {} in output of layer {}'.format(expected_shape, shape, n)\n print(\"Success!\")\n" ]
[ [ "torch.randn", "torch.Size", "torch.tensor" ], [ "torch.optim.lr_scheduler.MultiStepLR" ], [ "torch.nn.ModuleList", "torch.no_grad" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
srimanthtenneti/Deep-Learning-NanoDegree
[ "d99b09530a96f4aeca7adf3b9188e1d5fc4104d4" ]
[ "AWS_Deployment/serve/predict.py" ]
[ "import argparse\nimport json\nimport os\nimport pickle\nimport sys\nimport sagemaker_containers\nimport pandas as pd\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.utils.data\n\nfrom model import LSTMClassifier\n\nfrom utils import review_to_words, convert_and_pad\n\ndef model_fn(model_dir):\n \"\"\"Load the PyTorch model from the `model_dir` directory.\"\"\"\n print(\"Loading model.\")\n\n # First, load the parameters used to create the model.\n model_info = {}\n model_info_path = os.path.join(model_dir, 'model_info.pth')\n with open(model_info_path, 'rb') as f:\n model_info = torch.load(f)\n\n print(\"model_info: {}\".format(model_info))\n\n # Determine the device and construct the model.\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n model = LSTMClassifier(model_info['embedding_dim'], model_info['hidden_dim'], model_info['vocab_size'])\n\n # Load the store model parameters.\n model_path = os.path.join(model_dir, 'model.pth')\n with open(model_path, 'rb') as f:\n model.load_state_dict(torch.load(f))\n\n # Load the saved word_dict.\n word_dict_path = os.path.join(model_dir, 'word_dict.pkl')\n with open(word_dict_path, 'rb') as f:\n model.word_dict = pickle.load(f)\n\n model.to(device).eval()\n\n print(\"Done loading model.\")\n return model\n\ndef input_fn(serialized_input_data, content_type):\n print('Deserializing the input data.')\n if content_type == 'text/plain':\n data = serialized_input_data.decode('utf-8')\n return data\n raise Exception('Requested unsupported ContentType in content_type: ' + content_type)\n\ndef output_fn(prediction_output, accept):\n print('Serializing the generated output.')\n return str(prediction_output)\n\ndef predict_fn(input_data, model):\n print('Inferring sentiment of input data.')\n\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n \n if model.word_dict is None:\n raise Exception('Model has not been loaded properly, no word_dict.')\n \n # TODO: Process input_data so that it is ready to be sent to our model.\n # You should produce two variables:\n # data_X - A sequence of length 500 which represents the converted review\n # data_len - The length of the review\n\n data_X , data_len = convert_and_pad(model.word_dict, review_to_words(input_data))\n\n # Using data_X and data_len we construct an appropriate input tensor. Remember\n # that our model expects input data of the form 'len, review[500]'.\n data_pack = np.hstack((data_len, data_X))\n data_pack = data_pack.reshape(1, -1)\n \n data = torch.from_numpy(data_pack)\n data = data.to(device)\n\n # Make sure to put the model into evaluation mode\n model.eval()\n\n # TODO: Compute the result of applying the model to the input data. The variable `result` should\n # be a numpy array which contains a single integer which is either 1 or 0\n \n with torch.no_grad():\n y = model.forward(data)\n \n result = np.round(y.numpy())\n return result\n" ]
[ [ "numpy.hstack", "torch.load", "torch.from_numpy", "torch.no_grad", "torch.cuda.is_available" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jandremarais/TabularLearner
[ "7905b06a31fc6e0b0adf6a13a0fb445bdfe00c96" ]
[ "code/fastai_ext/fastai_ext/hyperparameter.py" ]
[ "import pandas as pd\nimport itertools\nfrom functools import partial\nfrom fastai.callbacks import CSVLogger\n\ndef get_config_df(config):\n df = pd.DataFrame(list(itertools.product(*config.values())), columns=config.keys())\n df.index = [f'model_{i+1}' for i in range(len(df))]\n return df\n\n\ndef create_experiment(nm, path, folder='results'):\n exp_path = (path/folder/nm)\n exp_path.mkdir(exist_ok=True)\n return nm, exp_path\n\ndef record_experiment(learn, fn, exp_path):\n learn.callback_fns.append(partial(CSVLogger, filename=exp_path/fn))\n\n\ndef load_results(exp_path):\n config_df = pd.read_csv(exp_path/'config.csv', index_col=0)\n param_names = config_df.columns.values\n recorder_df=[]\n for p in exp_path.ls():\n if p.name.startswith(tuple(config_df.index.values)):\n df = pd.read_csv(p)\n ind_name, fold_name = p.stem.split('-')\n df['index']=ind_name\n df['fold']=int(fold_name.split('_')[-1].split('.')[0])\n recorder_df.append(df)\n recorder_df = pd.concat(recorder_df)\n metric_names = list(set(recorder_df.columns).symmetric_difference(['index', 'epoch', 'train_loss', 'fold']))\n recorder_df = recorder_df.merge(config_df.reset_index())\n return config_df, recorder_df, param_names, metric_names\n\ndef summarise_results(recorder_df, param_names, metric_names):\n return (recorder_df.groupby(['index', *param_names, 'epoch'], as_index=False)\n .agg({k:['mean', 'std'] for k in metric_names}))" ]
[ [ "pandas.concat", "pandas.read_csv" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] } ]
ParthivNaresh/Facilyst
[ "786932b0afcf07cd300b2e6ce55ccf7f9e4c49d9" ]
[ "facilyst/mocks/mock_types/features.py" ]
[ "\"\"\"A mock type that returns features data.\"\"\"\nimport pandas as pd\nimport woodwork as ww\n\nfrom facilyst.mocks import MockBase\nfrom facilyst.mocks.mock_types.utils import mock_features_dtypes\n\n\nclass Features(MockBase):\n \"\"\"Class to manage mock data creation of features.\n\n :param num_rows: The number of observations in the final dataset. Defaults to 100.\n :type num_rows: int, optional\n :param library: The library of which the final dataset should be, options are 'pandas' and 'numpy'. Defaults to 'pandas'.\n :type library: str, optional\n :param ints: Flag that includes column with monotonically increasing incremental set of negative and positive integers. Defaults to True.\n :type ints: bool, optional\n :param rand_ints: Flag that includes column with randomly selected integers between -5 and 5. Defaults to True.\n :type rand_ints: bool, optional\n :param floats: Flag that includes column which is the float version of the 'ints' column. Defaults to True.\n :type floats: bool, optional\n :param rand_floats: Flag that includes column with randomly selected floats between -5 and 5. Defaults to True.\n :type rand_floats: bool, optional\n :param booleans: Flag that includes column with randomly selected boolean values. Defaults to False.\n :type booleans: bool, optional\n :param categoricals: Flag that includes column with four categoriesL 'First', 'Second', 'Third', and 'Fourth'. Defaults to False.\n :type categoricals: bool, optional\n :param dates: Flag that includes column with monotonically increasing dates from 01/01/2001 with a daily frequency. Defaults to False.\n :type dates: bool, optional\n :param texts: Flag that includes column with different text on each line. Defaults to False.\n :type texts: bool, optional\n :param ints_nullable: Flag that includes column which is the same as the 'ints' column with pd.NA included. Defaults to False.\n :type ints_nullable: bool, optional\n :param floats_nullable: Flag that includes column which is the same as the 'floats' column with pd.NA included. Defaults to False.\n :type floats_nullable: bool, optional\n :param booleans_nullable: Flag that includes column which is a randomly selected column with boolean values and pd.NA included. Defaults to False.\n :type booleans_nullable: bool, optional\n :param full_names: Flag that includes column with first and last names. Defaults to False.\n :type full_names: bool, optional\n :param phone_numbers: Flag that includes column with US-based phone numbers. Defaults to True.\n :type phone_numbers: bool, optional\n :param addresses: Flag that includes column with addresses. Defaults to True.\n :type addresses: bool, optional\n :param countries: Flag that includes column with country names. Defaults to False.\n :type countries: bool, optional\n :param email_addresses: Flag that includes column with email addresses. Defaults to True.\n :type email_addresses: bool, optional\n :param urls: Flag that includes column with URLs. Defaults to True.\n :type urls: bool, optional\n :param currencies: Flag that includes column with US dollar based amounts. Defaults to False.\n :type currencies: bool, optional\n :param file_paths: Flag that includes column with file paths at a depth of 3. Defaults to False.\n :type file_paths: bool, optional\n :param ipv4: Flag that includes column with different IPv4 addresses. Defaults to False.\n :type ipv4: bool, optional\n :param ipv6: Flag that includes column with different IPv6 addresses. Defaults to False.\n :type ipv6: bool, optional\n :param lat_longs: Flag that includes column with latitude and longitude values in a tuple. Defaults to False.\n :type lat_longs: bool, optional\n :param all_dtypes: Flag that includes all columns. Defaults to False.\n :type all_dtypes: bool, optional\n :return: Mock features data.\n :rtype: pd.DataFrame by default, can also return np.ndarray\n \"\"\"\n\n name = \"Features\"\n\n def __init__(\n self,\n num_rows=100,\n library=\"pandas\",\n ints=True,\n rand_ints=True,\n floats=True,\n rand_floats=True,\n booleans=False,\n categoricals=False,\n dates=False,\n texts=False,\n ints_nullable=False,\n floats_nullable=False,\n booleans_nullable=False,\n full_names=False,\n phone_numbers=False,\n addresses=False,\n countries=False,\n email_addresses=False,\n urls=False,\n currencies=False,\n file_paths=False,\n ipv4=False,\n ipv6=False,\n lat_longs=False,\n all_dtypes=False,\n ):\n kw_args = locals()\n\n if all_dtypes:\n parameters = {\n k: True\n for k, v in kw_args.items()\n if k not in [\"self\", \"library\", \"num_rows\", \"__class__\"]\n }\n else:\n parameters = {\n k: v\n for k, v in kw_args.items()\n if k not in [\"self\", \"library\", \"num_rows\", \"__class__\"] and v\n }\n if not any(\n parameters.values()\n ): # All False flags results in all dtypes being included\n parameters = {k: True for k, v in kw_args.items()}\n\n super().__init__(library, num_rows, parameters)\n\n def create_data(self):\n \"\"\"Main function to be called to create features data.\n\n :return: The final features data created.\n \"\"\"\n data, dtypes_to_keep = self.get_data_from_dict()\n data = self.handle_library(data, dtypes_to_keep)\n return data\n\n def get_data_from_dict(self):\n \"\"\"Returns the data based on the dtypes specified during class instantiation.\n\n :return: The final data created from the appropriate library as a pd.DataFrame or ndarray.\n \"\"\"\n dtypes_to_keep = list(self.parameters.keys())\n mocked = Features._refine_dtypes(dtypes_to_keep, self.num_rows)\n\n mocked_df = pd.DataFrame.from_dict(mocked)\n return mocked_df, dtypes_to_keep\n\n def handle_library(self, data, dtypes_to_keep):\n \"\"\"Handles the library that was selected to determine the format in which the data will be returned.\n\n :param data: The final data to be returned.\n :type data: pd.DataFrame\n :param dtypes_to_keep: All data format options from the class initialization. Defaults to returning the full dataset.\n :type dtypes_to_keep: list\n :return: The final data created from the appropriate library as a pd.DataFrame or ndarray.\n \"\"\"\n if self.library == \"numpy\":\n return data.to_numpy()\n else:\n if \"ints_nullable\" in dtypes_to_keep:\n data[\"ints_nullable\"] = data[\"ints_nullable\"].astype(\"Int64\")\n if \"floats_nullable\" in dtypes_to_keep:\n data[\"floats_nullable\"] = data[\"floats_nullable\"].astype(\"Float64\")\n data.ww.init()\n return data\n\n @staticmethod\n def _refine_dtypes(dtypes, num_rows=100):\n \"\"\"Internal function that selects the dtypes to be kept from the full dataset.\n\n :param dtypes: All data format options from the class initialization. Defaults to returning the full dataset.\n :type dtypes: list\n :param num_rows : The number of observations in the final dataset. Defaults to 100.\n :type num_rows: int\n :return: A refined form of the full set of columns available.\n \"\"\"\n full_mock = mock_features_dtypes(num_rows)\n return {k: v for k, v in full_mock.items() if k in dtypes}\n" ]
[ [ "pandas.DataFrame.from_dict" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
simassakenis/CausalMediationAnalysis
[ "ad46c02cdda88e13e2e891e9968c365e093ecc99" ]
[ "attention_intervention_winobias.py" ]
[ "\"\"\"Performs attention intervention on Winobias samples and saves results to JSON file.\"\"\"\n\nimport json\n\nimport fire\nfrom pandas import DataFrame\nfrom transformers import (\n GPT2Tokenizer, TransfoXLTokenizer, XLNetTokenizer,\n BertTokenizer, DistilBertTokenizer, RobertaTokenizer\n)\n\nimport winobias\nfrom attention_utils import perform_interventions, get_odds_ratio\nfrom experiment import Model\n\n\ndef get_interventions_winobias(gpt2_version, do_filter, split, model, tokenizer,\n device='cuda', filter_quantile=0.25):\n if split == 'dev':\n examples = winobias.load_dev_examples()\n elif split == 'test':\n examples = winobias.load_test_examples()\n else:\n raise ValueError(f\"Invalid split: {split}\")\n json_data = {'model_version': gpt2_version,\n 'do_filter': do_filter,\n 'split': split,\n 'num_examples_loaded': len(examples)}\n if do_filter:\n interventions = [ex.to_intervention(tokenizer) for ex in examples]\n df = DataFrame({'odds_ratio': [get_odds_ratio(intervention, model) for intervention in interventions]})\n df_expected = df[df.odds_ratio > 1]\n threshold = df_expected.odds_ratio.quantile(filter_quantile)\n filtered_examples = []\n assert len(examples) == len(df)\n for i in range(len(examples)):\n ex = examples[i]\n odds_ratio = df.iloc[i].odds_ratio\n if odds_ratio > threshold:\n filtered_examples.append(ex)\n\n print(f'Num examples with odds ratio > 1: {len(df_expected)} / {len(examples)}')\n print(\n f'Num examples with odds ratio > {threshold:.4f} ({filter_quantile} quantile): {len(filtered_examples)} / {len(examples)}')\n json_data['num_examples_aligned'] = len(df_expected)\n json_data['filter_quantile'] = filter_quantile\n json_data['threshold'] = threshold\n examples = filtered_examples\n json_data['num_examples_analyzed'] = len(examples)\n interventions = [ex.to_intervention(tokenizer) for ex in examples]\n return interventions, json_data\n\ndef intervene_attention(gpt2_version, do_filter, split, device='cuda',\n filter_quantile=0.25, random_weights=False,\n masking_approach=1):\n model = Model(output_attentions=True, gpt2_version=gpt2_version,\n device=device, random_weights=random_weights,\n masking_approach=masking_approach)\n tokenizer = (GPT2Tokenizer if model.is_gpt2 else\n TransfoXLTokenizer if model.is_txl else\n XLNetTokenizer if model.is_xlnet else\n BertTokenizer if model.is_bert else\n DistilBertTokenizer if model.is_distilbert else\n RobertaTokenizer).from_pretrained(gpt2_version)\n\n interventions, json_data = get_interventions_winobias(gpt2_version, do_filter, split, model, tokenizer,\n device, filter_quantile)\n results = perform_interventions(interventions, model)\n json_data['mean_total_effect'] = DataFrame(results).total_effect.mean()\n json_data['mean_model_indirect_effect'] = DataFrame(results).indirect_effect_model.mean()\n json_data['mean_model_direct_effect'] = DataFrame(results).direct_effect_model.mean()\n filter_name = 'filtered' if do_filter else 'unfiltered'\n if random_weights:\n gpt2_version += '_random'\n if model.is_gpt2 or model.is_txl or model.is_xlnet:\n fname = f\"winobias_data/attention_intervention_{gpt2_version}_{filter_name}_{split}.json\"\n else:\n fname = f\"winobias_data/attention_intervention_{gpt2_version}_{filter_name}_{split}_{masking_approach}.json\"\n json_data['results'] = results\n with open(fname, 'w') as f:\n json.dump(json_data, f)\n\n\nif __name__ == \"__main__\":\n fire.Fire(intervene_attention)\n" ]
[ [ "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
justinshenk/simba
[ "a58ccd0ceeda201c1452d186033ce6b25fbab564", "a58ccd0ceeda201c1452d186033ce6b25fbab564", "a58ccd0ceeda201c1452d186033ce6b25fbab564" ]
[ "simba/features_scripts/extract_features_16bp.py", "simba/process_data_log_old.py", "simba/dpk_script/detect_merge_outliers.py" ]
[ "from __future__ import division\r\nimport os, glob\r\nimport pandas as pd\r\nimport math\r\nimport numpy as np\r\nfrom scipy.spatial import ConvexHull\r\nimport scipy\r\nfrom configparser import ConfigParser, NoOptionError, NoSectionError\r\nfrom numba import jit\r\nfrom simba.rw_dfs import *\r\nimport re\r\n\r\n\r\ndef extract_features_wotarget_16(inifile):\r\n config = ConfigParser()\r\n configFile = str(inifile)\r\n config.read(configFile)\r\n projectPath = config.get('General settings', 'project_path')\r\n csv_dir_in, csv_dir_out = os.path.join(projectPath, 'csv', 'outlier_corrected_movement_location'), os.path.join(projectPath,'csv', 'features_extracted')\r\n vidInfPath = os.path.join(projectPath, 'logs', 'video_info.csv')\r\n try:\r\n wfileType = config.get('General settings', 'workflow_file_type')\r\n except NoOptionError:\r\n wfileType = 'csv'\r\n vidinfDf = pd.read_csv(vidInfPath)\r\n #change videos name to str\r\n vidinfDf.Video = vidinfDf.Video.astype('str')\r\n\r\n def count_values_in_range(series, values_in_range_min, values_in_range_max):\r\n return series.between(left=values_in_range_min, right=values_in_range_max).sum()\r\n\r\n def angle3pt(ax, ay, bx, by, cx, cy):\r\n ang = math.degrees(\r\n math.atan2(cy - by, cx - bx) - math.atan2(ay - by, ax - bx))\r\n return ang + 360 if ang < 0 else ang\r\n\r\n @jit(nopython=True, cache=True)\r\n def EuclidianDistCald(bp1xVals, bp1yVals, bp2xVals, bp2yVals, currPixPerMM):\r\n series = (np.sqrt((bp1xVals - bp2xVals) ** 2 + (bp1yVals - bp2yVals) ** 2)) / currPixPerMM\r\n return series\r\n\r\n roll_windows, loopy = [], 0\r\n roll_windows_values = [2, 5, 6, 7.5, 15]\r\n\r\n #REMOVE WINDOWS THAT ARE TOO SMALL\r\n minimum_fps = vidinfDf['fps'].min()\r\n for win in range(len(roll_windows_values)):\r\n if minimum_fps < roll_windows_values[win]:\r\n roll_windows_values[win] = minimum_fps\r\n else:\r\n pass\r\n roll_windows_values = list(set(roll_windows_values))\r\n\r\n ########### FIND CSV FILES ###########\r\n print(csv_dir_in)\r\n filesFound = glob.glob(csv_dir_in + '/*.' + wfileType)\r\n print('Extracting features from ' + str(len(filesFound)) + ' files...')\r\n\r\n ########### CREATE PD FOR RAW DATA AND PD FOR MOVEMENT BETWEEN FRAMES ###########\r\n for currentFile in filesFound:\r\n M1_hull_large_euclidean_list, M1_hull_small_euclidean_list, M1_hull_mean_euclidean_list, M1_hull_sum_euclidean_list, M2_hull_large_euclidean_list, M2_hull_small_euclidean_list, M2_hull_mean_euclidean_list, M2_hull_sum_euclidean_list = [], [], [], [], [], [], [], []\r\n currVidName = os.path.basename(currentFile).replace('.' +wfileType, '')\r\n\r\n # get current pixels/mm\r\n currVideoSettings = vidinfDf.loc[vidinfDf['Video'] == currVidName]\r\n try:\r\n currPixPerMM = float(currVideoSettings['pixels/mm'])\r\n except TypeError:\r\n print('Error: make sure all the videos that are going to be analyzed are represented in the project_folder/logs/video_info.csv file')\r\n\r\n fps = float(currVideoSettings['fps'])\r\n print('Processing ' + '\"' + str(currVidName) + '\".' + ' Fps: ' + str(fps) + \". mm/ppx: \" + str(currPixPerMM))\r\n\r\n\r\n\r\n\r\n\r\n for i in range(len(roll_windows_values)):\r\n roll_windows.append(int(fps / roll_windows_values[i]))\r\n loopy += 1\r\n columnHeaders = [\"Ear_left_1_x\", \"Ear_left_1_y\", \"Ear_left_1_p\", \"Ear_right_1_x\", \"Ear_right_1_y\",\r\n \"Ear_right_1_p\", \"Nose_1_x\", \"Nose_1_y\", \"Nose_1_p\", \"Center_1_x\", \"Center_1_y\", \"Center_1_p\",\r\n \"Lat_left_1_x\", \"Lat_left_1_y\",\r\n \"Lat_left_1_p\", \"Lat_right_1_x\", \"Lat_right_1_y\", \"Lat_right_1_p\", \"Tail_base_1_x\",\r\n \"Tail_base_1_y\", \"Tail_base_1_p\", \"Tail_end_1_x\", \"Tail_end_1_y\", \"Tail_end_1_p\",\r\n \"Ear_left_2_x\",\r\n \"Ear_left_2_y\", \"Ear_left_2_p\", \"Ear_right_2_x\", \"Ear_right_2_y\", \"Ear_right_2_p\",\r\n \"Nose_2_x\", \"Nose_2_y\", \"Nose_2_p\", \"Center_2_x\", \"Center_2_y\", \"Center_2_p\", \"Lat_left_2_x\",\r\n \"Lat_left_2_y\",\r\n \"Lat_left_2_p\", \"Lat_right_2_x\", \"Lat_right_2_y\", \"Lat_right_2_p\", \"Tail_base_2_x\",\r\n \"Tail_base_2_y\", \"Tail_base_2_p\", \"Tail_end_2_x\", \"Tail_end_2_y\", \"Tail_end_2_p\"]\r\n csv_df = read_df(currentFile, wfileType)\r\n try:\r\n csv_df = csv_df.set_index('scorer')\r\n except KeyError:\r\n pass\r\n csv_df.columns = columnHeaders\r\n csv_df = csv_df.fillna(0)\r\n #csv_df = csv_df.drop(csv_df.index[[0]])\r\n csv_df = csv_df.apply(pd.to_numeric)\r\n csv_df = csv_df.reset_index()\r\n csv_df = csv_df.reset_index(drop=True)\r\n\r\n print('Evaluating convex hulls...')\r\n ########### MOUSE AREAS ###########################################\r\n\r\n try:\r\n csv_df['Mouse_1_poly_area'] = csv_df.apply(lambda x: ConvexHull(np.array(\r\n [[x['Ear_left_1_x'], x[\"Ear_left_1_y\"]],\r\n [x['Ear_right_1_x'], x[\"Ear_right_1_y\"]],\r\n [x['Nose_1_x'], x[\"Nose_1_y\"]],\r\n [x['Lat_left_1_x'], x[\"Lat_left_1_y\"]], \\\r\n [x['Lat_right_1_x'], x[\"Lat_right_1_y\"]],\r\n [x['Tail_base_1_x'], x[\"Tail_base_1_y\"]],\r\n [x['Center_1_x'], x[\"Center_1_y\"]]])).area, axis=1)\r\n except scipy.spatial.qhull.QhullError as e:\r\n print(e)\r\n print('ERROR: For more information, go to https://github.com/sgoldenlab/simba/blob/SimBA_no_TF/docs/FAQ.md#i-get-a-qhull-eg-qh6154-or-6013-error-when-extracting-the-features')\r\n\r\n csv_df['Mouse_1_poly_area'] = csv_df.eval('Mouse_1_poly_area / @currPixPerMM')\r\n\r\n try:\r\n csv_df['Mouse_2_poly_area'] = csv_df.apply(lambda x: ConvexHull(np.array(\r\n [[x['Ear_left_2_x'], x[\"Ear_left_2_y\"]],\r\n [x['Ear_right_2_x'], x[\"Ear_right_2_y\"]],\r\n [x['Nose_2_x'], x[\"Nose_2_y\"]],\r\n [x['Lat_left_2_x'], x[\"Lat_left_2_y\"]], \\\r\n [x['Lat_right_2_x'], x[\"Lat_right_2_y\"]],\r\n [x['Tail_base_2_x'], x[\"Tail_base_2_y\"]],\r\n [x['Center_2_x'], x[\"Center_2_y\"]]])).area, axis=1)\r\n except scipy.spatial.qhull.QhullError as e:\r\n print(e)\r\n print('ERROR: For more information, check https://github.com/sgoldenlab/simba/blob/SimBA_no_TF/docs/FAQ.md#i-get-a-qhull-eg-qh6154-or-6013-error-when-extracting-the-features')\r\n\r\n ########### CREATE SHIFTED DATAFRAME FOR DISTANCE CALCULATIONS ###########################################\r\n csv_df_shifted = csv_df.shift(periods=1)\r\n csv_df_shifted = csv_df_shifted.rename(\r\n columns={'Ear_left_1_x': 'Ear_left_1_x_shifted', 'Ear_left_1_y': 'Ear_left_1_y_shifted',\r\n 'Ear_left_1_p': 'Ear_left_1_p_shifted', 'Ear_right_1_x': 'Ear_right_1_x_shifted', \\\r\n 'Ear_right_1_y': 'Ear_right_1_y_shifted', 'Ear_right_1_p': 'Ear_right_1_p_shifted',\r\n 'Nose_1_x': 'Nose_1_x_shifted', 'Nose_1_y': 'Nose_1_y_shifted', \\\r\n 'Nose_1_p': 'Nose_1_p_shifted', 'Center_1_x': 'Center_1_x_shifted',\r\n 'Center_1_y': 'Center_1_y_shifted', 'Center_1_p': 'Center_1_p_shifted', 'Lat_left_1_x': \\\r\n 'Lat_left_1_x_shifted', 'Lat_left_1_y': 'Lat_left_1_y_shifted',\r\n 'Lat_left_1_p': 'Lat_left_1_p_shifted', 'Lat_right_1_x': 'Lat_right_1_x_shifted',\r\n 'Lat_right_1_y': 'Lat_right_1_y_shifted', \\\r\n 'Lat_right_1_p': 'Lat_right_1_p_shifted', 'Tail_base_1_x': 'Tail_base_1_x_shifted',\r\n 'Tail_base_1_y': 'Tail_base_1_y_shifted', \\\r\n 'Tail_base_1_p': 'Tail_base_1_p_shifted', 'Tail_end_1_x': 'Tail_end_1_x_shifted',\r\n 'Tail_end_1_y': 'Tail_end_1_y_shifted', 'Tail_end_1_p': 'Tail_end_1_p_shifted',\r\n 'Ear_left_2_x': 'Ear_left_2_x_shifted', 'Ear_left_2_y': 'Ear_left_2_y_shifted',\r\n 'Ear_left_2_p': 'Ear_left_2_p_shifted', 'Ear_right_2_x': 'Ear_right_2_x_shifted', \\\r\n 'Ear_right_2_y': 'Ear_right_2_y_shifted', 'Ear_right_2_p': 'Ear_right_2_p_shifted',\r\n 'Nose_2_x': 'Nose_2_x_shifted', 'Nose_2_y': 'Nose_2_y_shifted', \\\r\n 'Nose_2_p': 'Nose_2_p_shifted', 'Center_2_x': 'Center_2_x_shifted',\r\n 'Center_2_y': 'Center_2_y_shifted', 'Center_2_p': 'Center_2_p_shifted', 'Lat_left_2_x': \\\r\n 'Lat_left_2_x_shifted', 'Lat_left_2_y': 'Lat_left_2_y_shifted',\r\n 'Lat_left_2_p': 'Lat_left_2_p_shifted', 'Lat_right_2_x': 'Lat_right_2_x_shifted',\r\n 'Lat_right_2_y': 'Lat_right_2_y_shifted', \\\r\n 'Lat_right_2_p': 'Lat_right_2_p_shifted', 'Tail_base_2_x': 'Tail_base_2_x_shifted',\r\n 'Tail_base_2_y': 'Tail_base_2_y_shifted', \\\r\n 'Tail_base_2_p': 'Tail_base_2_p_shifted', 'Tail_end_2_x': 'Tail_end_2_x_shifted',\r\n 'Tail_end_2_y': 'Tail_end_2_y_shifted', 'Tail_end_2_p': 'Tail_end_2_p_shifted',\r\n 'Mouse_1_poly_area': 'Mouse_1_poly_area_shifted',\r\n 'Mouse_2_poly_area': 'Mouse_2_poly_area_shifted'})\r\n csv_df_combined = pd.concat([csv_df, csv_df_shifted], axis=1, join='inner')\r\n csv_df_combined = csv_df_combined.fillna(0)\r\n csv_df_combined = csv_df_combined.reset_index(drop=True)\r\n\r\n print('Calculating euclidean distances...')\r\n ########### EUCLIDEAN DISTANCES ###########################################\r\n csv_df['Mouse_1_nose_to_tail'] = EuclidianDistCald(csv_df['Nose_1_x'].values, csv_df['Nose_1_y'].values, csv_df['Tail_base_1_x'].values, csv_df['Tail_base_1_y'].values, currPixPerMM)\r\n csv_df['Mouse_2_nose_to_tail'] = EuclidianDistCald(csv_df['Nose_2_x'].values, csv_df['Nose_2_y'].values, csv_df['Tail_base_2_x'].values, csv_df['Tail_base_2_y'].values, currPixPerMM)\r\n csv_df['Mouse_1_width'] = EuclidianDistCald(csv_df['Lat_left_1_x'].values, csv_df['Lat_left_1_y'].values, csv_df['Lat_right_1_x'].values, csv_df['Lat_right_1_y'].values, currPixPerMM)\r\n csv_df['Mouse_2_width'] = EuclidianDistCald(csv_df['Lat_left_2_x'].values, csv_df['Lat_left_2_y'].values, csv_df['Lat_right_2_x'].values, csv_df['Lat_right_2_y'].values, currPixPerMM)\r\n csv_df['Mouse_1_Ear_distance'] = EuclidianDistCald(csv_df['Ear_left_1_x'].values, csv_df['Ear_left_1_y'].values, csv_df['Ear_right_1_x'].values, csv_df['Ear_right_1_y'].values, currPixPerMM)\r\n csv_df['Mouse_2_Ear_distance'] = EuclidianDistCald(csv_df['Ear_left_2_x'].values, csv_df['Ear_left_2_y'].values, csv_df['Ear_right_2_x'].values, csv_df['Ear_right_2_y'].values, currPixPerMM)\r\n csv_df['Mouse_1_Nose_to_centroid'] = EuclidianDistCald(csv_df['Nose_1_x'].values, csv_df['Nose_1_y'].values, csv_df['Center_1_x'].values, csv_df['Center_1_y'].values, currPixPerMM)\r\n csv_df['Mouse_2_Nose_to_centroid'] = EuclidianDistCald(csv_df['Nose_2_x'].values, csv_df['Nose_2_y'].values,csv_df['Center_2_x'].values, csv_df['Center_2_y'].values, currPixPerMM)\r\n csv_df['Mouse_1_Nose_to_lateral_left'] = EuclidianDistCald(csv_df['Nose_1_x'].values, csv_df['Nose_1_y'].values,csv_df['Lat_left_1_x'].values, csv_df['Lat_left_1_y'].values, currPixPerMM)\r\n csv_df['Mouse_2_Nose_to_lateral_left'] = EuclidianDistCald(csv_df['Nose_2_x'].values, csv_df['Nose_2_y'].values,csv_df['Lat_left_2_x'].values, csv_df['Lat_left_2_y'].values, currPixPerMM)\r\n csv_df['Mouse_1_Nose_to_lateral_right'] = EuclidianDistCald(csv_df['Nose_1_x'].values, csv_df['Nose_1_y'].values,csv_df['Lat_right_1_x'].values, csv_df['Lat_right_1_y'].values, currPixPerMM)\r\n csv_df['Mouse_2_Nose_to_lateral_right'] = EuclidianDistCald(csv_df['Nose_2_x'].values, csv_df['Nose_2_y'].values,csv_df['Lat_right_2_x'].values, csv_df['Lat_right_2_y'].values, currPixPerMM)\r\n csv_df['Mouse_1_Centroid_to_lateral_left'] = EuclidianDistCald(csv_df['Center_1_x'].values, csv_df['Center_1_y'].values,csv_df['Lat_left_1_x'].values, csv_df['Lat_left_1_y'].values, currPixPerMM)\r\n csv_df['Mouse_2_Centroid_to_lateral_left'] = EuclidianDistCald(csv_df['Center_2_x'].values, csv_df['Center_2_y'].values,csv_df['Lat_left_2_x'].values, csv_df['Lat_left_2_y'].values, currPixPerMM)\r\n csv_df['Mouse_1_Centroid_to_lateral_right'] = EuclidianDistCald(csv_df['Center_1_x'].values, csv_df['Center_1_y'].values,csv_df['Lat_right_1_x'].values, csv_df['Lat_right_1_y'].values, currPixPerMM)\r\n csv_df['Mouse_2_Centroid_to_lateral_right'] = EuclidianDistCald(csv_df['Center_2_x'].values, csv_df['Center_2_y'].values,csv_df['Lat_right_2_x'].values, csv_df['Lat_right_2_y'].values, currPixPerMM)\r\n csv_df['Centroid_distance'] = EuclidianDistCald(csv_df['Center_2_x'].values, csv_df['Center_2_y'].values,csv_df['Center_1_x'].values, csv_df['Center_1_y'].values, currPixPerMM)\r\n csv_df['Nose_to_nose_distance'] = EuclidianDistCald(csv_df['Nose_1_x'].values, csv_df['Nose_1_y'].values,csv_df['Nose_2_x'].values, csv_df['Nose_2_y'].values, currPixPerMM)\r\n csv_df['M1_Nose_to_M2_lat_left'] = EuclidianDistCald(csv_df['Nose_1_x'].values, csv_df['Nose_1_y'].values,csv_df['Lat_left_2_x'].values, csv_df['Lat_left_2_y'].values, currPixPerMM)\r\n csv_df['M1_Nose_to_M2_lat_right'] = EuclidianDistCald(csv_df['Nose_1_x'].values, csv_df['Nose_1_y'].values,csv_df['Lat_right_2_x'].values, csv_df['Lat_right_2_y'].values, currPixPerMM)\r\n csv_df['M2_Nose_to_M1_lat_left'] = EuclidianDistCald(csv_df['Nose_2_x'].values, csv_df['Nose_2_y'].values,csv_df['Lat_left_1_x'].values, csv_df['Lat_left_1_y'].values, currPixPerMM)\r\n csv_df['M2_Nose_to_M1_lat_right'] = EuclidianDistCald(csv_df['Nose_2_x'].values, csv_df['Nose_2_y'].values,csv_df['Lat_right_1_x'].values, csv_df['Lat_right_1_y'].values, currPixPerMM)\r\n csv_df['M1_Nose_to_M2_tail_base'] = EuclidianDistCald(csv_df['Nose_1_x'].values, csv_df['Nose_1_y'].values,csv_df['Tail_base_2_x'].values, csv_df['Tail_base_2_y'].values, currPixPerMM)\r\n csv_df['M2_Nose_to_M1_tail_base'] = EuclidianDistCald(csv_df['Nose_2_x'].values, csv_df['Nose_2_y'].values,csv_df['Tail_base_1_x'].values, csv_df['Tail_base_1_y'].values, currPixPerMM)\r\n csv_df['Movement_mouse_1_centroid'] = EuclidianDistCald(csv_df_combined['Center_1_x_shifted'].values, csv_df_combined['Center_1_y_shifted'].values,csv_df_combined['Center_1_x'].values, csv_df_combined['Center_1_y'].values, currPixPerMM)\r\n csv_df['Movement_mouse_2_centroid'] = EuclidianDistCald(csv_df_combined['Center_2_x_shifted'].values, csv_df_combined['Center_2_y_shifted'].values,csv_df_combined['Center_2_x'].values, csv_df_combined['Center_2_y'].values, currPixPerMM)\r\n csv_df['Movement_mouse_1_nose'] = EuclidianDistCald(csv_df_combined['Nose_1_x_shifted'].values, csv_df_combined['Nose_1_y_shifted'].values,csv_df_combined['Nose_1_x'].values, csv_df_combined['Nose_1_y'].values, currPixPerMM)\r\n csv_df['Movement_mouse_2_nose'] = EuclidianDistCald(csv_df_combined['Nose_2_x_shifted'].values, csv_df_combined['Nose_2_y_shifted'].values,csv_df_combined['Nose_2_x'].values, csv_df_combined['Nose_2_y'].values, currPixPerMM)\r\n csv_df['Movement_mouse_1_tail_base'] = EuclidianDistCald(csv_df_combined['Tail_base_1_x_shifted'].values, csv_df_combined['Tail_base_1_y_shifted'].values,csv_df_combined['Tail_base_1_x'].values, csv_df_combined['Tail_base_1_y'].values, currPixPerMM)\r\n csv_df['Movement_mouse_2_tail_base'] = EuclidianDistCald(csv_df_combined['Tail_base_2_x_shifted'].values, csv_df_combined['Tail_base_2_y_shifted'].values,csv_df_combined['Tail_base_2_x'].values, csv_df_combined['Tail_base_2_y'].values, currPixPerMM)\r\n csv_df['Movement_mouse_1_tail_end'] = EuclidianDistCald(csv_df_combined['Tail_end_1_x_shifted'].values, csv_df_combined['Tail_end_1_y_shifted'].values,csv_df_combined['Tail_end_1_x'].values, csv_df_combined['Tail_end_1_y'].values, currPixPerMM)\r\n csv_df['Movement_mouse_2_tail_end'] = EuclidianDistCald(csv_df_combined['Tail_end_2_x_shifted'].values, csv_df_combined['Tail_end_2_y_shifted'].values,csv_df_combined['Tail_end_2_x'].values, csv_df_combined['Tail_end_2_y'].values, currPixPerMM)\r\n csv_df['Movement_mouse_1_left_ear'] = EuclidianDistCald(csv_df_combined['Ear_left_1_x_shifted'].values, csv_df_combined['Ear_left_1_y_shifted'].values,csv_df_combined['Ear_left_1_x'].values, csv_df_combined['Ear_left_1_y'].values, currPixPerMM)\r\n csv_df['Movement_mouse_2_left_ear'] = EuclidianDistCald(csv_df_combined['Ear_left_2_x_shifted'].values, csv_df_combined['Ear_left_2_y_shifted'].values,csv_df_combined['Ear_left_2_x'].values, csv_df_combined['Ear_left_2_y'].values, currPixPerMM)\r\n csv_df['Movement_mouse_1_right_ear'] = EuclidianDistCald(csv_df_combined['Ear_right_1_x_shifted'].values, csv_df_combined['Ear_right_1_y_shifted'].values,csv_df_combined['Ear_right_1_x'].values, csv_df_combined['Ear_right_1_y'].values, currPixPerMM)\r\n csv_df['Movement_mouse_2_right_ear'] = EuclidianDistCald(csv_df_combined['Ear_right_2_x_shifted'].values, csv_df_combined['Ear_right_2_y_shifted'].values,csv_df_combined['Ear_right_2_x'].values, csv_df_combined['Ear_right_2_y'].values, currPixPerMM)\r\n csv_df['Movement_mouse_1_lateral_left'] = EuclidianDistCald(csv_df_combined['Lat_left_1_x_shifted'].values, csv_df_combined['Lat_left_1_y_shifted'].values,csv_df_combined['Lat_left_1_x'].values, csv_df_combined['Lat_left_1_y'].values, currPixPerMM)\r\n csv_df['Movement_mouse_2_lateral_left'] = EuclidianDistCald(csv_df_combined['Lat_left_2_x_shifted'].values, csv_df_combined['Lat_left_2_y_shifted'].values,csv_df_combined['Lat_left_2_x'].values, csv_df_combined['Lat_left_2_y'].values, currPixPerMM)\r\n csv_df['Movement_mouse_1_lateral_right'] = EuclidianDistCald(csv_df_combined['Lat_right_1_x_shifted'].values, csv_df_combined['Lat_right_1_y_shifted'].values,csv_df_combined['Lat_right_1_x'].values, csv_df_combined['Lat_right_1_y'].values, currPixPerMM)\r\n csv_df['Movement_mouse_2_lateral_right'] = EuclidianDistCald(csv_df_combined['Lat_right_2_x_shifted'].values, csv_df_combined['Lat_right_2_y_shifted'].values,csv_df_combined['Lat_right_2_x'].values, csv_df_combined['Lat_right_2_y'].values, currPixPerMM)\r\n csv_df['Mouse_1_polygon_size_change'] = pd.eval(\"csv_df_combined.Mouse_1_poly_area_shifted - csv_df_combined.Mouse_1_poly_area\")\r\n csv_df['Mouse_2_polygon_size_change'] = pd.eval(\"csv_df_combined.Mouse_2_poly_area_shifted - csv_df_combined.Mouse_2_poly_area\")\r\n\r\n print('Calculating hull variables...')\r\n ########### HULL - EUCLIDEAN DISTANCES ###########################################\r\n for index, row in csv_df.iterrows():\r\n M1_np_array = np.array(\r\n [[row['Ear_left_1_x'], row[\"Ear_left_1_y\"]], [row['Ear_right_1_x'], row[\"Ear_right_1_y\"]],\r\n [row['Nose_1_x'], row[\"Nose_1_y\"]], [row['Center_1_x'], row[\"Center_1_y\"]],\r\n [row['Lat_left_1_x'], row[\"Lat_left_1_y\"]], [row['Lat_right_1_x'], row[\"Lat_right_1_y\"]],\r\n [row['Tail_base_1_x'], row[\"Tail_base_1_y\"]]]).astype(int)\r\n M2_np_array = np.array(\r\n [[row['Ear_left_2_x'], row[\"Ear_left_2_y\"]], [row['Ear_right_2_x'], row[\"Ear_right_2_y\"]],\r\n [row['Nose_2_x'], row[\"Nose_2_y\"]], [row['Center_2_x'], row[\"Center_2_y\"]],\r\n [row['Lat_left_2_x'], row[\"Lat_left_2_y\"]], [row['Lat_right_2_x'], row[\"Lat_right_2_y\"]],\r\n [row['Tail_base_2_x'], row[\"Tail_base_2_y\"]]]).astype(int)\r\n M1_dist_euclidean = scipy.spatial.distance.cdist(M1_np_array, M1_np_array, metric='euclidean')\r\n M1_dist_euclidean = M1_dist_euclidean[M1_dist_euclidean != 0]\r\n M1_hull_large_euclidean = np.amax(M1_dist_euclidean)\r\n M1_hull_small_euclidean = np.min(M1_dist_euclidean)\r\n M1_hull_mean_euclidean = np.mean(M1_dist_euclidean)\r\n M1_hull_sum_euclidean = np.sum(M1_dist_euclidean)\r\n M1_hull_large_euclidean_list.append(M1_hull_large_euclidean)\r\n M1_hull_small_euclidean_list.append(M1_hull_small_euclidean)\r\n M1_hull_mean_euclidean_list.append(M1_hull_mean_euclidean)\r\n M1_hull_sum_euclidean_list.append(M1_hull_sum_euclidean)\r\n M2_dist_euclidean = scipy.spatial.distance.cdist(M2_np_array, M2_np_array, metric='euclidean')\r\n M2_dist_euclidean = M2_dist_euclidean[M2_dist_euclidean != 0]\r\n M2_hull_large_euclidean = np.amax(M2_dist_euclidean)\r\n M2_hull_small_euclidean = np.min(M2_dist_euclidean)\r\n M2_hull_mean_euclidean = np.mean(M2_dist_euclidean)\r\n M2_hull_sum_euclidean = np.sum(M2_dist_euclidean)\r\n M2_hull_large_euclidean_list.append(M2_hull_large_euclidean)\r\n M2_hull_small_euclidean_list.append(M2_hull_small_euclidean)\r\n M2_hull_mean_euclidean_list.append(M2_hull_mean_euclidean)\r\n M2_hull_sum_euclidean_list.append(M2_hull_sum_euclidean)\r\n csv_df['M1_largest_euclidean_distance_hull'] = list(map(lambda x: x / currPixPerMM, M1_hull_large_euclidean_list))\r\n csv_df['M1_smallest_euclidean_distance_hull'] = list(map(lambda x: x / currPixPerMM, M1_hull_small_euclidean_list))\r\n csv_df['M1_mean_euclidean_distance_hull'] = list(map(lambda x: x / currPixPerMM, M1_hull_mean_euclidean_list))\r\n csv_df['M1_sum_euclidean_distance_hull'] = list(map(lambda x: x / currPixPerMM, M1_hull_sum_euclidean_list))\r\n csv_df['M2_largest_euclidean_distance_hull'] = list(map(lambda x: x / currPixPerMM, M2_hull_large_euclidean_list))\r\n csv_df['M2_smallest_euclidean_distance_hull'] = list(map(lambda x: x / currPixPerMM, M2_hull_small_euclidean_list))\r\n csv_df['M2_mean_euclidean_distance_hull'] = list(map(lambda x: x / currPixPerMM, M2_hull_mean_euclidean_list))\r\n csv_df['M2_sum_euclidean_distance_hull'] = list(map(lambda x: x / currPixPerMM, M2_hull_sum_euclidean_list))\r\n csv_df['Sum_euclidean_distance_hull_M1_M2'] = (csv_df['M1_sum_euclidean_distance_hull'] + csv_df['M2_sum_euclidean_distance_hull'])\r\n\r\n\r\n ########### COLLAPSED MEASURES ###########################################\r\n csv_df['Total_movement_centroids'] = csv_df.eval(\"Movement_mouse_1_centroid + Movement_mouse_2_centroid\")\r\n csv_df['Total_movement_tail_ends'] = csv_df.eval('Movement_mouse_1_tail_end + Movement_mouse_2_tail_end')\r\n csv_df['Total_movement_all_bodyparts_M1'] = csv_df.eval('Movement_mouse_1_nose + Movement_mouse_1_tail_end + Movement_mouse_1_tail_base + Movement_mouse_1_left_ear + Movement_mouse_1_right_ear + Movement_mouse_1_lateral_left + Movement_mouse_1_lateral_right')\r\n csv_df['Total_movement_all_bodyparts_M2'] = csv_df.eval('Movement_mouse_2_nose + Movement_mouse_2_tail_end + Movement_mouse_2_tail_base + Movement_mouse_2_left_ear + Movement_mouse_2_right_ear + Movement_mouse_2_lateral_left + Movement_mouse_2_lateral_right')\r\n csv_df['Total_movement_all_bodyparts_both_mice'] = csv_df.eval('Total_movement_all_bodyparts_M1 + Total_movement_all_bodyparts_M2')\r\n\r\n ########### CALC ROLLING WINDOWS MEDIANS AND MEANS ###########################################\r\n print('Calculating rolling windows: medians, medians, and sums...')\r\n\r\n for i in range(len(roll_windows_values)):\r\n currentColName = 'Sum_euclid_distances_hull_median_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['Sum_euclidean_distance_hull_M1_M2'].rolling(roll_windows[i],\r\n min_periods=1).median()\r\n currentColName = 'Sum_euclid_distances_hull_mean_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['Sum_euclidean_distance_hull_M1_M2'].rolling(roll_windows[i],\r\n min_periods=1).mean()\r\n currentColName = 'Sum_euclid_distances_hull_sum_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['Sum_euclidean_distance_hull_M1_M2'].rolling(roll_windows[i], min_periods=1).sum()\r\n\r\n for i in range(len(roll_windows_values)):\r\n currentColName = 'Movement_median_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['Total_movement_centroids'].rolling(roll_windows[i], min_periods=1).median()\r\n currentColName = 'Movement_mean_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['Total_movement_centroids'].rolling(roll_windows[i], min_periods=1).mean()\r\n currentColName = 'Movement_sum_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['Total_movement_centroids'].rolling(roll_windows[i], min_periods=1).sum()\r\n\r\n for i in range(len(roll_windows_values)):\r\n currentColName = 'Distance_median_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['Centroid_distance'].rolling(roll_windows[i], min_periods=1).median()\r\n currentColName = 'Distance_mean_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['Centroid_distance'].rolling(roll_windows[i], min_periods=1).mean()\r\n currentColName = 'Distance_sum_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['Centroid_distance'].rolling(roll_windows[i], min_periods=1).sum()\r\n\r\n for i in range(len(roll_windows_values)):\r\n currentColName = 'Mouse1_width_median_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['Mouse_1_width'].rolling(roll_windows[i], min_periods=1).median()\r\n currentColName = 'Mouse1_width_mean_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['Mouse_1_width'].rolling(roll_windows[i], min_periods=1).mean()\r\n currentColName = 'Mouse1_width_sum_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['Mouse_1_width'].rolling(roll_windows[i], min_periods=1).sum()\r\n\r\n for i in range(len(roll_windows_values)):\r\n currentColName = 'Mouse2_width_median_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['Mouse_2_width'].rolling(roll_windows[i], min_periods=1).median()\r\n currentColName = 'Mouse2_width_mean_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['Mouse_2_width'].rolling(roll_windows[i], min_periods=1).mean()\r\n currentColName = 'Mouse2_width_sum_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['Mouse_2_width'].rolling(roll_windows[i], min_periods=1).sum()\r\n\r\n for i in range(len(roll_windows_values)):\r\n currentColName = 'Mouse1_mean_euclid_distances_median_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['M1_mean_euclidean_distance_hull'].rolling(roll_windows[i],\r\n min_periods=1).median()\r\n currentColName = 'Mouse1_mean_euclid_distances_mean_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['M1_mean_euclidean_distance_hull'].rolling(roll_windows[i],\r\n min_periods=1).mean()\r\n currentColName = 'Mouse1_mean_euclid_distances_sum_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['M1_mean_euclidean_distance_hull'].rolling(roll_windows[i],\r\n min_periods=1).sum()\r\n\r\n for i in range(len(roll_windows_values)):\r\n currentColName = 'Mouse2_mean_euclid_distances_median_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['M2_mean_euclidean_distance_hull'].rolling(roll_windows[i],\r\n min_periods=1).median()\r\n currentColName = 'Mouse2_mean_euclid_distances_mean_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['M2_mean_euclidean_distance_hull'].rolling(roll_windows[i],\r\n min_periods=1).mean()\r\n currentColName = 'Mouse2_mean_euclid_distances_sum_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['M2_mean_euclidean_distance_hull'].rolling(roll_windows[i],\r\n min_periods=1).sum()\r\n\r\n for i in range(len(roll_windows_values)):\r\n currentColName = 'Mouse1_smallest_euclid_distances_median_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['M1_smallest_euclidean_distance_hull'].rolling(roll_windows[i],\r\n min_periods=1).median()\r\n currentColName = 'Mouse1_smallest_euclid_distances_mean_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['M1_smallest_euclidean_distance_hull'].rolling(roll_windows[i],\r\n min_periods=1).mean()\r\n currentColName = 'Mouse1_smallest_euclid_distances_sum_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['M1_smallest_euclidean_distance_hull'].rolling(roll_windows[i],\r\n min_periods=1).sum()\r\n\r\n for i in range(len(roll_windows_values)):\r\n currentColName = 'Mouse2_smallest_euclid_distances_median_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['M2_smallest_euclidean_distance_hull'].rolling(roll_windows[i],\r\n min_periods=1).median()\r\n currentColName = 'Mouse2_smallest_euclid_distances_mean_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['M2_smallest_euclidean_distance_hull'].rolling(roll_windows[i],\r\n min_periods=1).mean()\r\n currentColName = 'Mouse2_smallest_euclid_distances_sum_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['M2_smallest_euclidean_distance_hull'].rolling(roll_windows[i],\r\n min_periods=1).sum()\r\n\r\n for i in range(len(roll_windows_values)):\r\n currentColName = 'Mouse1_largest_euclid_distances_median_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['M1_largest_euclidean_distance_hull'].rolling(roll_windows[i],\r\n min_periods=1).median()\r\n currentColName = 'Mouse1_largest_euclid_distances_mean_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['M1_largest_euclidean_distance_hull'].rolling(roll_windows[i],\r\n min_periods=1).mean()\r\n currentColName = 'Mouse1_largest_euclid_distances_sum_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['M1_largest_euclidean_distance_hull'].rolling(roll_windows[i],\r\n min_periods=1).sum()\r\n\r\n for i in range(len(roll_windows_values)):\r\n currentColName = 'Mouse2_largest_euclid_distances_median_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['M2_largest_euclidean_distance_hull'].rolling(roll_windows[i],\r\n min_periods=1).median()\r\n currentColName = 'Mouse2_largest_euclid_distances_mean_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['M2_largest_euclidean_distance_hull'].rolling(roll_windows[i],\r\n min_periods=1).mean()\r\n currentColName = 'Mouse2_largest_euclid_distances_sum_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['M2_largest_euclidean_distance_hull'].rolling(roll_windows[i],\r\n min_periods=1).sum()\r\n\r\n for i in range(len(roll_windows_values)):\r\n currentColName = 'Total_movement_all_bodyparts_both_mice_median_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['Total_movement_all_bodyparts_both_mice'].rolling(roll_windows[i],\r\n min_periods=1).median()\r\n currentColName = 'Total_movement_all_bodyparts_both_mice_mean_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['Total_movement_all_bodyparts_both_mice'].rolling(roll_windows[i],\r\n min_periods=1).mean()\r\n currentColName = 'Total_movement_all_bodyparts_both_mice_sum_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['Total_movement_all_bodyparts_both_mice'].rolling(roll_windows[i],\r\n min_periods=1).sum()\r\n\r\n for i in range(len(roll_windows_values)):\r\n currentColName = 'Total_movement_centroids_median_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['Total_movement_centroids'].rolling(roll_windows[i], min_periods=1).median()\r\n currentColName = 'Total_movement_centroids_mean_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['Total_movement_centroids'].rolling(roll_windows[i], min_periods=1).mean()\r\n currentColName = 'Total_movement_centroids_sum_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['Total_movement_centroids'].rolling(roll_windows[i], min_periods=1).sum()\r\n\r\n for i in range(len(roll_windows_values)):\r\n currentColName = 'Tail_base_movement_M1_median_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['Movement_mouse_1_tail_base'].rolling(roll_windows[i],\r\n min_periods=1).median()\r\n currentColName = 'Tail_base_movement_M1_mean_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['Movement_mouse_1_tail_base'].rolling(roll_windows[i], min_periods=1).mean()\r\n currentColName = 'Tail_base_movement_M1_sum_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['Movement_mouse_1_tail_base'].rolling(roll_windows[i], min_periods=1).sum()\r\n\r\n for i in range(len(roll_windows_values)):\r\n currentColName = 'Tail_base_movement_M2_median_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['Movement_mouse_2_tail_base'].rolling(roll_windows[i],\r\n min_periods=1).median()\r\n currentColName = 'Tail_base_movement_M2_mean_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['Movement_mouse_2_tail_base'].rolling(roll_windows[i], min_periods=1).mean()\r\n currentColName = 'Tail_base_movement_M2_sum_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['Movement_mouse_2_tail_base'].rolling(roll_windows[i], min_periods=1).sum()\r\n\r\n for i in range(len(roll_windows_values)):\r\n currentColName = 'Centroid_movement_M1_median_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['Movement_mouse_1_centroid'].rolling(roll_windows[i],\r\n min_periods=1).median()\r\n currentColName = 'Centroid_movement_M1_mean_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['Movement_mouse_1_centroid'].rolling(roll_windows[i], min_periods=1).mean()\r\n currentColName = 'Centroid_movement_M1_sum_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['Movement_mouse_1_centroid'].rolling(roll_windows[i], min_periods=1).sum()\r\n\r\n for i in range(len(roll_windows_values)):\r\n currentColName = 'Centroid_movement_M2_median_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['Movement_mouse_2_centroid'].rolling(roll_windows[i],\r\n min_periods=1).median()\r\n currentColName = 'Centroid_movement_M2_mean_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['Movement_mouse_2_centroid'].rolling(roll_windows[i], min_periods=1).mean()\r\n currentColName = 'Centroid_movement_M2_sum_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['Movement_mouse_2_centroid'].rolling(roll_windows[i], min_periods=1).sum()\r\n\r\n for i in range(len(roll_windows_values)):\r\n currentColName = 'Tail_end_movement_M1_median_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['Movement_mouse_1_tail_end'].rolling(roll_windows[i],\r\n min_periods=1).median()\r\n currentColName = 'Tail_end_movement_M1_mean_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['Movement_mouse_1_tail_end'].rolling(roll_windows[i], min_periods=1).mean()\r\n currentColName = 'Tail_end_movement_M1_sum_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['Movement_mouse_1_tail_end'].rolling(roll_windows[i], min_periods=1).sum()\r\n\r\n for i in range(len(roll_windows_values)):\r\n currentColName = 'Tail_end_movement_M2_median_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['Movement_mouse_2_tail_end'].rolling(roll_windows[i],\r\n min_periods=1).median()\r\n currentColName = 'Tail_end_movement_M2_mean_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['Movement_mouse_2_tail_end'].rolling(roll_windows[i], min_periods=1).mean()\r\n currentColName = 'Tail_end_movement_M2_sum_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['Movement_mouse_2_tail_end'].rolling(roll_windows[i], min_periods=1).sum()\r\n\r\n for i in range(len(roll_windows_values)):\r\n currentColName = 'Nose_movement_M1_median_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['Movement_mouse_1_nose'].rolling(roll_windows[i], min_periods=1).median()\r\n currentColName = 'Nose_movement_M1_mean_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['Movement_mouse_1_nose'].rolling(roll_windows[i], min_periods=1).mean()\r\n currentColName = 'Nose_movement_M1_sum_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['Movement_mouse_1_nose'].rolling(roll_windows[i], min_periods=1).sum()\r\n\r\n for i in range(len(roll_windows_values)):\r\n currentColName = 'Nose_movement_M2_median_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['Movement_mouse_2_nose'].rolling(roll_windows[i], min_periods=1).median()\r\n currentColName = 'Nose_movement_M2_mean_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['Movement_mouse_2_nose'].rolling(roll_windows[i], min_periods=1).mean()\r\n currentColName = 'Nose_movement_M2_sum_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['Movement_mouse_2_nose'].rolling(roll_windows[i], min_periods=1).sum()\r\n\r\n ########### BODY PARTS RELATIVE TO EACH OTHER ##################\r\n csv_df['Tail_end_relative_to_tail_base_centroid_nose'] = csv_df['Movement_mouse_1_tail_end'] - (\r\n csv_df['Movement_mouse_1_tail_base'] + csv_df['Movement_mouse_1_centroid'] + csv_df[\r\n 'Movement_mouse_1_nose'])\r\n for i in range(len(roll_windows_values)):\r\n currentColName_M1 = 'Tail_end_relative_to_tail_base_centroid_nose_M1_' + str(roll_windows_values[i])\r\n tail_end_col_name = 'Tail_end_movement_M1_mean_' + str(roll_windows_values[i])\r\n tail_base_col_name = 'Tail_base_movement_M1_mean_' + str(roll_windows_values[i])\r\n centroid_col_name = 'Centroid_movement_M1_mean_' + str(roll_windows_values[i])\r\n nose_col_name = 'Nose_movement_M1_mean_' + str(roll_windows_values[i])\r\n currentColName_M2 = 'Tail_end_relative_to_tail_base_centroid_nose_M2_mean_' + str(roll_windows_values[i])\r\n tail_end_col_name_M2 = 'Tail_end_movement_M2_mean_' + str(roll_windows_values[i])\r\n tail_base_col_name_M2 = 'Tail_base_movement_M2_mean_' + str(roll_windows_values[i])\r\n centroid_col_name_M2 = 'Centroid_movement_M2_mean_' + str(roll_windows_values[i])\r\n nose_col_name_M2 = 'Nose_movement_M2_mean_' + str(roll_windows_values[i])\r\n csv_df[currentColName_M1] = csv_df[tail_end_col_name] - (\r\n csv_df[tail_base_col_name] + csv_df[centroid_col_name] + csv_df[nose_col_name])\r\n csv_df[currentColName_M2] = csv_df[tail_end_col_name_M2] - (\r\n csv_df[tail_base_col_name_M2] + csv_df[centroid_col_name_M2] + csv_df[nose_col_name_M2])\r\n\r\n ########### ANGLES ###########################################\r\n print('Calculating angles...')\r\n csv_df['Mouse_1_angle'] = csv_df.apply(\r\n lambda x: angle3pt(x['Nose_1_x'], x['Nose_1_y'], x['Center_1_x'], x['Center_1_y'], x['Tail_base_1_x'],\r\n x['Tail_base_1_y']), axis=1)\r\n csv_df['Mouse_2_angle'] = csv_df.apply(\r\n lambda x: angle3pt(x['Nose_2_x'], x['Nose_2_y'], x['Center_2_x'], x['Center_2_y'], x['Tail_base_2_x'],\r\n x['Tail_base_2_y']), axis=1)\r\n csv_df['Total_angle_both_mice'] = csv_df['Mouse_1_angle'] + csv_df['Mouse_2_angle']\r\n for i in range(len(roll_windows_values)):\r\n currentColName = 'Total_angle_both_mice_' + str(roll_windows_values[i])\r\n csv_df[currentColName] = csv_df['Total_angle_both_mice'].rolling(roll_windows[i], min_periods=1).sum()\r\n\r\n ########### DEVIATIONS ###########################################\r\n print('Calculating deviations...')\r\n csv_df['Total_movement_all_bodyparts_both_mice_deviation'] = csv_df.eval('Total_movement_all_bodyparts_both_mice.mean() - Total_movement_all_bodyparts_both_mice')\r\n csv_df['Sum_euclid_distances_hull_deviation'] = csv_df.eval('Sum_euclidean_distance_hull_M1_M2.mean() - Sum_euclidean_distance_hull_M1_M2')\r\n csv_df['M1_smallest_euclid_distances_hull_deviation'] = csv_df.eval('M1_smallest_euclidean_distance_hull.mean() - M1_smallest_euclidean_distance_hull')\r\n csv_df['M1_largest_euclid_distances_hull_deviation'] = csv_df.eval('M1_largest_euclidean_distance_hull.mean() - M1_largest_euclidean_distance_hull')\r\n csv_df['M1_mean_euclid_distances_hull_deviation'] = csv_df.eval('M1_mean_euclidean_distance_hull.mean() - M1_mean_euclidean_distance_hull')\r\n csv_df['Centroid_distance_deviation'] = csv_df.eval('Centroid_distance.mean() - Centroid_distance')\r\n csv_df['Total_angle_both_mice_deviation'] = csv_df.eval('Total_angle_both_mice - Total_angle_both_mice')\r\n csv_df['Movement_mouse_1_deviation_centroid'] = csv_df.eval('Movement_mouse_1_centroid.mean() - Movement_mouse_1_centroid')\r\n csv_df['Movement_mouse_2_deviation_centroid'] = csv_df.eval('Movement_mouse_2_centroid.mean() - Movement_mouse_2_centroid')\r\n csv_df['Mouse_1_polygon_deviation'] = csv_df.eval('Mouse_1_poly_area.mean() - Mouse_1_poly_area')\r\n csv_df['Mouse_2_polygon_deviation'] = csv_df.eval('Mouse_2_poly_area.mean() - Mouse_2_poly_area')\r\n\r\n for i in roll_windows_values:\r\n currentColName = 'Total_movement_all_bodyparts_both_mice_mean_' + str(i)\r\n currentDev_colName = currentColName + '_deviation'\r\n csv_df[currentDev_colName] = (csv_df[currentColName].mean() - csv_df[currentColName])\r\n\r\n for i in range(len(roll_windows_values)):\r\n currentColName = 'Sum_euclid_distances_hull_mean_' + str(roll_windows_values[i])\r\n currentDev_colName = currentColName + '_deviation'\r\n csv_df[currentDev_colName] = (csv_df[currentColName].mean() - csv_df[currentColName])\r\n\r\n for i in range(len(roll_windows_values)):\r\n currentColName = 'Mouse1_smallest_euclid_distances_mean_' + str(roll_windows_values[i])\r\n currentDev_colName = currentColName + '_deviation'\r\n csv_df[currentDev_colName] = (csv_df[currentColName].mean() - csv_df[currentColName])\r\n\r\n for i in range(len(roll_windows_values)):\r\n currentColName = 'Mouse1_largest_euclid_distances_mean_' + str(roll_windows_values[i])\r\n currentDev_colName = currentColName + '_deviation'\r\n csv_df[currentDev_colName] = (csv_df[currentColName].mean() - csv_df[currentColName])\r\n\r\n for i in range(len(roll_windows_values)):\r\n currentColName = 'Mouse1_mean_euclid_distances_mean_' + str(roll_windows_values[i])\r\n currentDev_colName = currentColName + '_deviation'\r\n csv_df[currentDev_colName] = (csv_df[currentColName].mean() - csv_df[currentColName])\r\n\r\n for i in range(len(roll_windows_values)):\r\n currentColName = 'Movement_mean_' + str(roll_windows_values[i])\r\n currentDev_colName = currentColName + '_deviation'\r\n csv_df[currentDev_colName] = (csv_df[currentColName].mean() - csv_df[currentColName])\r\n\r\n for i in range(len(roll_windows_values)):\r\n currentColName = 'Distance_mean_' + str(roll_windows_values[i])\r\n currentDev_colName = currentColName + '_deviation'\r\n csv_df[currentDev_colName] = (csv_df[currentColName].mean() - csv_df[currentColName])\r\n\r\n for i in range(len(roll_windows_values)):\r\n currentColName = 'Total_angle_both_mice_' + str(roll_windows_values[i])\r\n currentDev_colName = currentColName + '_deviation'\r\n csv_df[currentDev_colName] = (csv_df[currentColName].mean() - csv_df[currentColName])\r\n\r\n ########### PERCENTILE RANK ###########################################\r\n print('Calculating percentile ranks...')\r\n csv_df['Movement_percentile_rank'] = csv_df['Total_movement_centroids'].rank(pct=True)\r\n csv_df['Distance_percentile_rank'] = csv_df['Centroid_distance'].rank(pct=True)\r\n csv_df['Movement_mouse_1_percentile_rank'] = csv_df['Movement_mouse_1_centroid'].rank(pct=True)\r\n csv_df['Movement_mouse_2_percentile_rank'] = csv_df['Movement_mouse_1_centroid'].rank(pct=True)\r\n csv_df['Movement_mouse_1_deviation_percentile_rank'] = csv_df['Movement_mouse_1_deviation_centroid'].rank(\r\n pct=True)\r\n csv_df['Movement_mouse_2_deviation_percentile_rank'] = csv_df['Movement_mouse_2_deviation_centroid'].rank(\r\n pct=True)\r\n csv_df['Centroid_distance_percentile_rank'] = csv_df['Centroid_distance'].rank(pct=True)\r\n csv_df['Centroid_distance_deviation_percentile_rank'] = csv_df['Centroid_distance_deviation'].rank(pct=True)\r\n\r\n for i in range(len(roll_windows_values)):\r\n currentColName = 'Total_movement_all_bodyparts_both_mice_mean_' + str(roll_windows_values[i])\r\n currentDev_colName = currentColName + '_percentile_rank'\r\n csv_df[currentDev_colName] = (csv_df[currentColName].mean() - csv_df[currentColName])\r\n\r\n for i in range(len(roll_windows_values)):\r\n currentColName = 'Sum_euclid_distances_hull_mean_' + str(roll_windows_values[i])\r\n currentDev_colName = currentColName + '_percentile_rank'\r\n csv_df[currentDev_colName] = (csv_df[currentColName].mean() - csv_df[currentColName])\r\n\r\n for i in range(len(roll_windows_values)):\r\n currentColName = 'Mouse1_mean_euclid_distances_mean_' + str(roll_windows_values[i])\r\n currentDev_colName = currentColName + '_percentile_rank'\r\n csv_df[currentDev_colName] = (csv_df[currentColName].mean() - csv_df[currentColName])\r\n\r\n for i in range(len(roll_windows_values)):\r\n currentColName = 'Mouse1_smallest_euclid_distances_mean_' + str(roll_windows_values[i])\r\n currentDev_colName = currentColName + '_percentile_rank'\r\n csv_df[currentDev_colName] = (csv_df[currentColName].mean() - csv_df[currentColName])\r\n\r\n for i in range(len(roll_windows_values)):\r\n currentColName = 'Mouse1_largest_euclid_distances_mean_' + str(roll_windows_values[i])\r\n currentDev_colName = currentColName + '_percentile_rank'\r\n csv_df[currentDev_colName] = (csv_df[currentColName].mean() - csv_df[currentColName])\r\n\r\n for i in range(len(roll_windows_values)):\r\n currentColName = 'Movement_mean_' + str(roll_windows_values[i])\r\n currentDev_colName = currentColName + '_percentile_rank'\r\n csv_df[currentDev_colName] = (csv_df[currentColName].mean() - csv_df[currentColName])\r\n\r\n for i in range(len(roll_windows_values)):\r\n currentColName = 'Distance_mean_' + str(roll_windows_values[i])\r\n currentDev_colName = currentColName + '_percentile_rank'\r\n csv_df[currentDev_colName] = (csv_df[currentColName].mean() - csv_df[currentColName])\r\n\r\n ########### CALCULATE STRAIGHTNESS OF POLYLINE PATH: tortuosity ###########################################\r\n print('Calculating path tortuosities...')\r\n as_strided = np.lib.stride_tricks.as_strided\r\n win_size = 3\r\n centroidList_Mouse1_x = as_strided(csv_df.Center_1_x, (len(csv_df) - (win_size - 1), win_size),\r\n (csv_df.Center_1_x.values.strides * 2))\r\n centroidList_Mouse1_y = as_strided(csv_df.Center_1_y, (len(csv_df) - (win_size - 1), win_size),\r\n (csv_df.Center_1_y.values.strides * 2))\r\n centroidList_Mouse2_x = as_strided(csv_df.Center_2_x, (len(csv_df) - (win_size - 1), win_size),\r\n (csv_df.Center_2_x.values.strides * 2))\r\n centroidList_Mouse2_y = as_strided(csv_df.Center_2_y, (len(csv_df) - (win_size - 1), win_size),\r\n (csv_df.Center_2_y.values.strides * 2))\r\n\r\n for k in range(len(roll_windows_values)):\r\n start = 0\r\n end = start + int(roll_windows_values[k])\r\n tortuosity_M1 = []\r\n tortuosity_M2 = []\r\n for y in range(len(csv_df)):\r\n tortuosity_List_M1 = []\r\n tortuosity_List_M2 = []\r\n CurrCentroidList_Mouse1_x = centroidList_Mouse1_x[start:end]\r\n CurrCentroidList_Mouse1_y = centroidList_Mouse1_y[start:end]\r\n CurrCentroidList_Mouse2_x = centroidList_Mouse2_x[start:end]\r\n CurrCentroidList_Mouse2_y = centroidList_Mouse2_y[start:end]\r\n for i in range(len(CurrCentroidList_Mouse1_x)):\r\n currMovementAngle_mouse1 = (\r\n angle3pt(CurrCentroidList_Mouse1_x[i][0], CurrCentroidList_Mouse1_y[i][0],\r\n CurrCentroidList_Mouse1_x[i][1], CurrCentroidList_Mouse1_y[i][1],\r\n CurrCentroidList_Mouse1_x[i][2], CurrCentroidList_Mouse1_y[i][2]))\r\n currMovementAngle_mouse2 = (\r\n angle3pt(CurrCentroidList_Mouse2_x[i][0], CurrCentroidList_Mouse2_y[i][0],\r\n CurrCentroidList_Mouse2_x[i][1], CurrCentroidList_Mouse2_y[i][1],\r\n CurrCentroidList_Mouse2_x[i][2], CurrCentroidList_Mouse2_y[i][2]))\r\n tortuosity_List_M1.append(currMovementAngle_mouse1)\r\n tortuosity_List_M2.append(currMovementAngle_mouse2)\r\n tortuosity_M1.append(sum(tortuosity_List_M1) / (2 * math.pi))\r\n tortuosity_M2.append(sum(tortuosity_List_M2) / (2 * math.pi))\r\n start += 1\r\n end += 1\r\n currentColName1 = str('Tortuosity_Mouse1_') + str(roll_windows_values[k])\r\n #currentColName2 = str('Tortuosity_Mouse2_') + str(roll_windows_values[k])\r\n csv_df[currentColName1] = tortuosity_M1\r\n #csv_df[currentColName2] = tortuosity_M2\r\n\r\n ########### CALC THE NUMBER OF LOW PROBABILITY DETECTIONS & TOTAL PROBABILITY VALUE FOR ROW###########################################\r\n print('Calculating pose probability scores...')\r\n csv_df['Sum_probabilities'] = csv_df.eval('Ear_left_1_p + Ear_right_1_p + Nose_1_p + Center_1_p + Lat_left_1_p + Lat_right_1_p + Tail_base_1_p + Tail_end_1_p + Ear_left_2_p + Ear_right_2_p + Nose_2_p + Center_2_p + Lat_left_2_p + Lat_right_2_p + Tail_base_2_p + Tail_end_2_p')\r\n csv_df['Sum_probabilities_deviation'] = csv_df.eval('Sum_probabilities.mean() - Sum_probabilities')\r\n csv_df['Sum_probabilities_deviation_percentile_rank'] = csv_df['Sum_probabilities_deviation'].rank(pct=True)\r\n csv_df['Sum_probabilities_percentile_rank'] = csv_df['Sum_probabilities_deviation_percentile_rank'].rank(pct=True)\r\n csv_df_probability = csv_df.filter(\r\n ['Ear_left_1_p', 'Ear_right_1_p', 'Nose_1_p', 'Center_1_p', 'Lat_left_1_p', 'Lat_right_1_p',\r\n 'Tail_base_1_p', 'Tail_end_1_p', 'Ear_left_2_p', 'Ear_right_2_p', 'Nose_2_p', 'Center_2_p', 'Lat_left_2_p',\r\n 'Lat_right_2_p', 'Tail_base_2_p', 'Tail_end_2_p'])\r\n values_in_range_min, values_in_range_max = 0.0, 0.1\r\n csv_df[\"Low_prob_detections_0.1\"] = csv_df_probability.apply(func=lambda row: count_values_in_range(row, values_in_range_min, values_in_range_max), axis=1)\r\n values_in_range_min, values_in_range_max = 0.000000000, 0.5\r\n csv_df[\"Low_prob_detections_0.5\"] = csv_df_probability.apply(\r\n func=lambda row: count_values_in_range(row, values_in_range_min, values_in_range_max), axis=1)\r\n values_in_range_min, values_in_range_max = 0.000000000, 0.75\r\n csv_df[\"Low_prob_detections_0.75\"] = csv_df_probability.apply(\r\n func=lambda row: count_values_in_range(row, values_in_range_min, values_in_range_max), axis=1)\r\n\r\n ########### DROP COORDINATE COLUMNS ###########################################\r\n csv_df = csv_df.reset_index(drop=True)\r\n csv_df = csv_df.fillna(0)\r\n csv_df = csv_df.drop(columns=['index'], axis=1, errors='ignore')\r\n fileName = os.path.basename(currentFile)\r\n saveFN = os.path.join(csv_dir_out, fileName)\r\n save_df(csv_df, wfileType, saveFN)\r\n print('Feature extraction complete for ' + '\"' + str(currVidName) + '\".')\r\n print('All feature extraction complete.')", "import pandas as pd\r\nimport os\r\nfrom configparser import ConfigParser\r\nfrom datetime import datetime\r\nimport numpy as np\r\n\r\n\r\ndef analyze_process_data_log(configini,chosenlist):\r\n\r\n dateTime = datetime.now().strftime('%Y%m%d%H%M%S')\r\n config = ConfigParser()\r\n configFile = str(configini)\r\n config.read(configFile)\r\n csv_dir = config.get('General settings', 'csv_path')\r\n csv_dir_in = os.path.join(csv_dir, 'machine_results')\r\n no_targets = config.getint('SML settings', 'No_targets')\r\n boutEnd = 0\r\n boutEnd_list = [0]\r\n boutStart_list = []\r\n filesFound = []\r\n target_names = []\r\n vidInfPath = config.get('General settings', 'project_path')\r\n vidInfPath = os.path.join(vidInfPath, 'logs')\r\n vidInfPath = os.path.join(vidInfPath, 'video_info.csv')\r\n vidinfDf = pd.read_csv(vidInfPath)\r\n loop = 0\r\n loopy = 0\r\n\r\n ########### FIND CSV FILES ###########\r\n for i in os.listdir(csv_dir_in):\r\n if i.endswith(\".csv\"):\r\n file = os.path.join(csv_dir_in, i)\r\n filesFound.append(file)\r\n\r\n ########### GET TARGET COLUMN NAMES ###########\r\n for ff in range(no_targets):\r\n currentModelNames = 'target_name_' + str(ff+1)\r\n currentModelNames = config.get('SML settings', currentModelNames)\r\n target_names.append(currentModelNames)\r\n print('Analyzing ' + str(len(target_names)) + ' classifier result(s) in ' + str(len(filesFound)) + ' video file(s).')\r\n\r\n ########### logfile path ###########\r\n log_fn = 'sklearn_' + str(dateTime) + '.csv'\r\n log_path = config.get('General settings', 'project_path')\r\n log_path = os.path.join(log_path, 'logs')\r\n log_fn = os.path.join(log_path, log_fn)\r\n if not os.path.exists(log_path):\r\n os.makedirs(log_path)\r\n\r\n headers = ['Video']\r\n for i in target_names:\r\n head1 = str(i) + ' events'\r\n head2 = str(i) + ' sum duration (s)'\r\n head3 = str(i) + ' mean duration (s)'\r\n head4 = str(i) + ' median duration (s)'\r\n head5 = str(i) + ' first occurance (s)'\r\n head6 = str(i) + ' mean interval (s)'\r\n head7 = str(i) + ' median interval (s)'\r\n headers.extend([head1, head2, head3, head4, head5, head6, head7])\r\n log_df = pd.DataFrame(columns=headers)\r\n\r\n for i in filesFound:\r\n boutsDf = pd.DataFrame(columns=['Event', 'Start_frame', 'End_frame'])\r\n currentFile = i\r\n currVidName = os.path.basename(currentFile)\r\n currVidName = currVidName.replace('.csv', '')\r\n fps = vidinfDf.loc[vidinfDf['Video'] == currVidName]\r\n try:\r\n fps = int(fps['fps'])\r\n except TypeError:\r\n print('Error: make sure all the videos that are going to be analyzed are represented in the project_folder/logs/video_info.csv file')\r\n loopy+=1\r\n print('Analyzing video ' + str(loopy) + '/' + str(len(filesFound)) + '...')\r\n dataDf = pd.read_csv(currentFile)\r\n dataDf['frames'] = np.arange(len(dataDf))\r\n folderNm = os.path.basename(currentFile)\r\n logFolderNm = str(folderNm.split('.')[0])\r\n for bb in target_names:\r\n currTarget = bb\r\n for indexes, rows in dataDf[dataDf['frames'] >= boutEnd].iterrows():\r\n if rows[currTarget] == 1:\r\n boutStart = rows['frames']\r\n for index, row in dataDf[dataDf['frames'] >= boutStart].iterrows():\r\n if row[currTarget] == 0:\r\n boutEnd = row['frames']\r\n if boutEnd_list[-1] != boutEnd:\r\n boutStart_list.append(boutStart)\r\n boutEnd_list.append(boutEnd)\r\n values = [currTarget, boutStart, boutEnd]\r\n boutsDf.loc[(len(boutsDf))] = values\r\n break\r\n break\r\n boutStart_list = [0]\r\n boutEnd_list = [0]\r\n boutEnd = 0\r\n\r\n #Convert to time\r\n boutsDf['Start_time'] = boutsDf['Start_frame'] / fps\r\n boutsDf['End_time'] = boutsDf['End_frame'] / fps\r\n boutsDf['Bout_time'] = boutsDf['End_time'] - boutsDf['Start_time']\r\n\r\n #record logs\r\n log_list = []\r\n log_list.append(logFolderNm)\r\n for i in target_names:\r\n currDf = boutsDf.loc[boutsDf['Event'] == i]\r\n try:\r\n firstOccur = round(currDf['Start_time'].iloc[0], 4)\r\n except IndexError:\r\n firstOccur = 0\r\n eventNOs = len(currDf)\r\n TotEventDur = round(currDf['Bout_time'].sum(), 4)\r\n try:\r\n MeanEventDur = round(TotEventDur / eventNOs, 4)\r\n except ZeroDivisionError:\r\n MeanEventDur = 0\r\n try:\r\n MedianEventDur = round(currDf['Bout_time'].median(), 10)\r\n\r\n except ZeroDivisionError:\r\n MedianEventDur = 0\r\n currDf_shifted = currDf.shift(periods=-1)\r\n currDf_shifted = currDf_shifted.drop(columns=['Event', 'Start_frame', 'End_frame', 'End_time', 'Bout_time'])\r\n currDf_shifted = currDf_shifted.rename(columns={'Start_time': 'Start_time_shifted'})\r\n currDf_combined = pd.concat([currDf, currDf_shifted], axis=1, join='inner')\r\n currDf_combined['Event_interval'] = currDf_combined['Start_time_shifted'] - currDf_combined['End_time']\r\n meanEventInterval = currDf_combined[\"Event_interval\"].mean()\r\n medianEventInterval = currDf_combined['Event_interval'].median()\r\n log_list.append(eventNOs)\r\n log_list.append(TotEventDur)\r\n log_list.append(MeanEventDur)\r\n log_list.append(MedianEventDur)\r\n log_list.append(firstOccur)\r\n log_list.append(meanEventInterval)\r\n log_list.append(medianEventInterval)\r\n log_df.loc[loop] = log_list\r\n loop += 1\r\n print('File # processed for machine predictions: ' + str(loop) + '/' + str(len(filesFound)))\r\n log_df.fillna(0, inplace=True)\r\n # drop columns not chosen\r\n for i in chosenlist:\r\n log_df = log_df[log_df.columns.drop(list(log_df.filter(regex=str(i))))]\r\n\r\n\r\n log_df.to_csv(log_fn, index=False)\r\n print('All files processed for machine predictions: data file saved @' + str(log_fn))\r\n\r\n\r\n\r\n", "import numpy as np\r\nfrom scipy.signal import find_peaks\r\nimport pandas as pd\r\nimport cv2\r\nimport numpy as np\r\nfrom deepposekit.models import load_model\r\nfrom deepposekit.io import DataGenerator, VideoReader, VideoWriter\r\nimport os\r\nfrom configparser import ConfigParser\r\nimport glob\r\nimport warnings\r\nwarnings.filterwarnings('ignore',category=FutureWarning)\r\n\r\ndpkini = r\"Z:\\DeepLabCut\\DLC_extract\\Troubleshooting\\Hazel\\project_folder\\logs\\measures\\dpk\\Hazel_1\\dpk_config.ini\"\r\nvideofolder = r\"Z:\\DeepLabCut\\DLC_extract\\Troubleshooting\\Hazel\\project_folder\\logs\\measures\\dpk\\Hazel_1\\videos\\input\"\r\n\r\nconfigFile = str(dpkini)\r\nconfig = ConfigParser()\r\nconfig.read(configFile)\r\nproject_folder = config.get('general DPK settings', 'project_folder')\r\nmodelPath = config.get('predict settings', 'modelPath')\r\nvideoFolderPath = videofolder\r\nprint(videoFolderPath)\r\nbatchSize = config.getint('predict settings', 'batch_size')\r\noutputfolder = os.path.join(project_folder, 'predictions')\r\nif not os.path.exists(outputfolder):\r\n os.makedirs(outputfolder)\r\n\r\nbodyPartColumnNames = []\r\n\r\nskeletonPath = os.path.join(project_folder, 'skeleton.csv')\r\nskeletonDf = pd.read_csv(skeletonPath)\r\nskeletonList = list(skeletonDf['name'])\r\n\r\nfor i in skeletonList:\r\n x_col, y_col, p_col = (str(i) + '_x', str(i) + '_y', str(i) + '_p')\r\n bodyPartColumnNames.append(x_col)\r\n bodyPartColumnNames.append(y_col)\r\n bodyPartColumnNames.append(p_col)\r\n\r\nfilesFound = glob.glob(videoFolderPath + '/*.mp4')\r\n\r\n\r\n#Check if videos are greyscale\r\ncap = cv2.VideoCapture(filesFound[0])\r\ncap.set(1, 0)\r\nret, frame = cap.read()\r\nfileName = str(0) + str('.bmp')\r\nfilePath = os.path.join(videoFolderPath, fileName)\r\ncv2.imwrite(filePath, frame)\r\nimg = cv2.imread(filePath)\r\nimgDepth = img.shape[2]\r\nif imgDepth == 3:\r\n greyscaleStatus = False\r\nelse:\r\n greyscaleStatus = True\r\nos.remove(filePath)\r\n\r\n# This loads the trained model into memory for making predictions\r\nmodel = load_model(modelPath)\r\nfor video in filesFound:\r\n print('Analyzing file: ' + str(os.path.basename(video)))\r\n reader = VideoReader(video, batch_size=batchSize, gray=greyscaleStatus)\r\n predictions = model.predict(reader, verbose=1)\r\n reader.close()\r\n outputFilename = os.path.join(outputfolder, os.path.basename(video).replace('.mp4', '.csv'))\r\n x, y, confidence = np.split(predictions, 3, -1)\r\n\r\nconfidence_diff = np.abs(np.diff(confidence.mean(-1).mean(-1)))\r\nconfidence_outlier_peaks = find_peaks(confidence_diff, height=0.1)[0]\r\ntime_diff = np.diff(predictions[..., :2], axis=0)\r\ntime_diff = np.abs(time_diff.reshape(time_diff.shape[0], -1))\r\ntime_diff = time_diff.mean(-1)\r\n\r\ntime_diff_outlier_peaks = find_peaks(time_diff, height=10)[0]\r\noutlier_index = np.concatenate((confidence_outlier_peaks, time_diff_outlier_peaks))\r\noutlier_index = np.unique(outlier_index) # make sure there are no repeats\r\n\r\nreader = VideoReader(r\"Z:\\DeepLabCut\\DLC_extract\\Troubleshooting\\Hazel\\project_folder\\logs\\measures\\dpk\\Hazel_1\\videos\\input\\Hazel_2_fps_20_downsampled.mp4\", batch_size=1, gray=False)\r\noutlier_images = []\r\noutlier_keypoints = []\r\nfor idx in outlier_index:\r\n outlier_images.append(reader[idx])\r\n outlier_keypoints.append(predictions[idx])\r\n\r\noutlier_images = np.concatenate(outlier_images)\r\noutlier_keypoints = np.stack(outlier_keypoints)\r\n\r\nreader.close()\r\n\r\ndata_generator = DataGenerator(r\"Z:\\DeepLabCut\\DLC_extract\\Troubleshooting\\Hazel\\project_folder\\logs\\measures\\dpk\\Hazel_1\\annotation_sets\\Annotation_Hazel.h5\")\r\nfrom deepposekit.io.utils import merge_new_images\r\n\r\n\r\nmerge_new_images(\r\n datapath=r\"Z:\\DeepLabCut\\DLC_extract\\Troubleshooting\\Hazel\\project_folder\\logs\\measures\\dpk\\Hazel_1\\annotation_sets\\Annotation_Hazel.h5\",\r\n merged_datapath=r\"Z:\\DeepLabCut\\DLC_extract\\Troubleshooting\\Hazel\\project_folder\\logs\\measures\\dpk\\Hazel_1\\annotation_sets\\Annotation_Hazel_merged_2.h5\",\r\n images=outlier_images,\r\n keypoints=outlier_keypoints,\r\n # overwrite=True # This overwrites the merged dataset if it already exists\r\n)\r\n\r\n" ]
[ [ "pandas.concat", "pandas.read_csv", "pandas.eval", "numpy.sqrt", "numpy.amax", "numpy.min", "scipy.spatial.distance.cdist", "numpy.mean", "numpy.array", "numpy.sum" ], [ "pandas.concat", "pandas.read_csv", "pandas.DataFrame" ], [ "numpy.split", "pandas.read_csv", "scipy.signal.find_peaks", "numpy.unique", "numpy.stack", "numpy.concatenate", "numpy.diff" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [ "0.13", "1.6", "0.14", "1.10", "0.15", "1.4", "0.16", "1.9", "0.19", "1.5", "0.18", "1.2", "1.7", "0.12", "1.0", "0.17", "1.3", "1.8" ], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [ "1.6", "1.10", "1.4", "1.9", "1.5", "1.2", "1.7", "1.3", "1.8" ], "tensorflow": [] } ]
johannbrehmer/rl-6-nimmt
[ "8bc504e0372bb4bc99a3d69e77418991092ffdac" ]
[ "rl_6_nimmt/play.py" ]
[ "import torch\nimport numpy as np\nimport logging\nfrom .env import SechsNimmtEnv\n\nlogger = logging.getLogger(__name__)\n\n\nclass GameSession:\n def __init__(self, *agents, device=torch.device(\"cpu\"), dtype=torch.float):\n \"\"\" Initializes a game session, which consists of an arbitrary number of games between the given agents \"\"\"\n\n self.device = device\n self.dtype = dtype\n self.agents = [agent.to(self.device, self.dtype) for agent in agents]\n self.num_agents = len(agents)\n self.env = SechsNimmtEnv(self.num_agents)\n self.results = [] # List of total scores (negative Hornochsen) for each game\n self.game = 0\n\n self._set_env_player_names()\n\n def play_game(self, render=False):\n \"\"\" Play one game, i.e. until one player hits 66 Hornochsen or whatever it is \"\"\"\n\n states, all_legal_actions = self.env.reset()\n states = self._tensorize(states)\n done = False\n rewards = np.zeros(self.num_agents, dtype=np.int)\n scores = np.zeros(self.num_agents, dtype=np.int)\n\n if render:\n self.env.render()\n\n while not done:\n # Agent turns\n actions, agent_infos = [], []\n for agent, state, legal_actions in zip(self.agents, states, all_legal_actions):\n action, agent_info = agent(state, legal_actions=legal_actions)\n actions.append(int(action))\n agent_infos.append(agent_info)\n # TODO: gently enforce legality of actions by giving a negative reward and asking again\n\n # Environment steps\n (next_states, next_all_legal_actions), next_rewards, done, info = self.env.step(actions)\n next_states = self._tensorize(next_states)\n\n if render:\n self.env.render()\n\n # Learning\n for agent, action, state, next_state, reward, next_reward, agent_info, legal_actions, next_legal_actions, in zip(\n self.agents, actions, states, next_states, rewards, next_rewards, agent_infos, all_legal_actions, next_all_legal_actions\n ):\n agent.learn(\n state=state,\n legal_actions=legal_actions.copy(),\n reward=reward,\n action=action,\n done=done,\n next_state=next_state,\n next_legal_actions=next_legal_actions.copy(),\n next_reward=next_reward,\n num_episode=self.game,\n episode_end=done,\n **agent_info,\n )\n\n scores += np.array(next_rewards)\n states = next_states\n all_legal_actions = next_all_legal_actions\n rewards = next_rewards\n\n self.results.append(scores)\n self.game += 1\n\n def _tensorize(self, inputs):\n return [torch.tensor(input).to(self.device, self.dtype) for input in inputs]\n\n def _set_env_player_names(self):\n names = []\n for agent in self.agents:\n try:\n names.append(agent.__name__)\n except:\n names.append(type(agent).__name__)\n self.env._player_names = names\n" ]
[ [ "torch.device", "numpy.array", "numpy.zeros", "torch.tensor" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
mrbermell/seed_rl
[ "9562e178fb8c16d2551d9e5d59594a7f908655dd" ]
[ "agents/policy_gradient/modules/generalized_onpolicy_loss.py" ]
[ "# coding=utf-8\n# Copyright 2019 The SEED Authors\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\n\"\"\"Implements a generalized onpolicy loss.\"\"\"\n\nimport abc\nimport inspect\nimport gin\nfrom seed_rl.agents.policy_gradient.modules import logging_module\nimport tensorflow as tf\n\n\[email protected]\nclass GeneralizedOnPolicyLoss(tf.Module, logging_module.LoggingModule):\n \"\"\"TensorFlow module implementing the generalized onpolicy loss.\"\"\"\n\n def __init__(self, agent, reward_normalizer, parametric_action_distribution,\n advantage_estimator, policy_loss, discount_factor,\n regularizer=None, max_abs_reward=None,\n handle_abandoned_episodes_properly=True,\n huber_delta=None, value_ppo_style_clip_eps=None,\n baseline_cost=1., include_regularization_in_returns=False,\n frame_skip=1, reward_scaling=1.0):\n \"\"\"Creates a GeneralizedOnPolicyLoss.\"\"\"\n self._agent = agent\n self._reward_normalizer = reward_normalizer\n self._parametric_action_distribution = parametric_action_distribution\n self._advantage_estimator = advantage_estimator\n self._policy_loss = policy_loss\n self._regularizer = regularizer\n self._max_abs_reward = max_abs_reward\n self._reward_scaling = reward_scaling\n self._baseline_cost = baseline_cost\n # Provided here so that it is shared.\n self._discount_factor = discount_factor\n self._frame_skip = frame_skip\n self._handle_abandoned_episodes_properly = handle_abandoned_episodes_properly\n self._value_ppo_style_clip_eps = value_ppo_style_clip_eps\n self._include_regularization_in_returns = include_regularization_in_returns\n if huber_delta is not None:\n self.v_loss_fn = tf.keras.losses.Huber(\n delta=huber_delta, reduction=tf.keras.losses.Reduction.NONE)\n else:\n self.v_loss_fn = tf.keras.losses.MeanSquaredError(\n reduction=tf.keras.losses.Reduction.NONE)\n\n def init(self):\n for module in self.submodules:\n if hasattr(module, 'init'):\n if not inspect.signature(module.init).parameters:\n module.init()\n\n def compute_advantages(self, agent_state, prev_actions, env_outputs,\n agent_outputs, return_learner_outputs=False):\n # Extract rewards and done information.\n rewards, done, _, abandoned, _ = tf.nest.map_structure(lambda t: t[1:],\n env_outputs)\n if self._max_abs_reward is not None:\n rewards = tf.clip_by_value(rewards, -self._max_abs_reward, \n self._max_abs_reward)\n rewards *= self._reward_scaling\n\n # Compute the outputs of the neural networks on the learner.\n learner_outputs, _ = self._agent((prev_actions, env_outputs),\n agent_state,\n unroll=True,\n is_training=True)\n\n # At this point, we have unroll length + 1 steps. The last step is only used\n # as bootstrap value, so it's removed.\n agent_outputs = tf.nest.map_structure(lambda t: t[:-1], agent_outputs)\n learner_v = learner_outputs.baseline # current value function\n learner_outputs = tf.nest.map_structure(lambda t: t[:-1], learner_outputs)\n\n target_action_log_probs = self._parametric_action_distribution(\n learner_outputs.policy_logits).log_prob(agent_outputs.action)\n behaviour_action_log_probs = self._parametric_action_distribution(\n agent_outputs.policy_logits).log_prob(agent_outputs.action)\n\n # Compute the advantages.\n\n if self._reward_normalizer:\n corrected_predictions = self._reward_normalizer.correct_prediction(\n learner_v)\n unnormalized_predictions = self._reward_normalizer.unnormalize_prediction(\n corrected_predictions)\n else:\n corrected_predictions = learner_v\n unnormalized_predictions = learner_v\n if not self._handle_abandoned_episodes_properly:\n abandoned = tf.zeros_like(abandoned)\n done_terminated = tf.logical_and(done, ~abandoned)\n done_abandoned = tf.logical_and(done, abandoned)\n\n if self._include_regularization_in_returns and self._regularizer:\n additional_rewards, _ = self._regularizer(\n self._parametric_action_distribution,\n learner_outputs.policy_logits,\n agent_outputs.policy_logits,\n agent_outputs.action, with_logging=False)\n assert rewards.shape == additional_rewards.shape\n rewards += additional_rewards\n\n # tf.math.pow does not work on TPU so we compute it manually.\n adjusted_discount_factor = 1.\n for _ in range(self._frame_skip):\n adjusted_discount_factor *= self._discount_factor\n\n vs, advantages = self._advantage_estimator(\n unnormalized_predictions,\n rewards, done_terminated,\n done_abandoned,\n adjusted_discount_factor,\n target_action_log_probs,\n behaviour_action_log_probs)\n\n if self._reward_normalizer:\n normalized_targets = self._reward_normalizer.normalize_target(vs)\n normalized_advantages = self._reward_normalizer.normalize_advantage(\n advantages)\n self._reward_normalizer.update_normalization_statistics(vs)\n else:\n normalized_targets = vs\n normalized_advantages = advantages\n\n outputs = (normalized_targets, normalized_advantages)\n if return_learner_outputs:\n outputs += (learner_outputs,)\n return outputs\n\n def __call__(self, agent_state, prev_actions, env_outputs, agent_outputs,\n normalized_targets=None, normalized_advantages=None):\n \"\"\"Computes the loss.\"\"\"\n if normalized_targets is None:\n normalized_targets, normalized_advantages, learner_outputs = \\\n self.compute_advantages( \n agent_state, prev_actions, env_outputs, agent_outputs,\n return_learner_outputs=True)\n # The last timestep is only used for computing advantages so we\n # remove it here.\n agent_state, prev_actions, env_outputs, agent_outputs = \\\n tf.nest.map_structure(\n lambda t: t[:-1],\n (agent_state, prev_actions, env_outputs, agent_outputs))\n else: # Advantages are already precomputed.\n learner_outputs, _ = self._agent((prev_actions, env_outputs),\n agent_state,\n unroll=True,\n is_training=True)\n\n target_action_log_probs = self._parametric_action_distribution(\n learner_outputs.policy_logits).log_prob(agent_outputs.action)\n behaviour_action_log_probs = self._parametric_action_distribution(\n agent_outputs.policy_logits).log_prob(agent_outputs.action)\n\n # Compute the advantages.\n if self._reward_normalizer:\n corrected_predictions = self._reward_normalizer.correct_prediction(\n learner_outputs.baseline)\n old_corrected_predictions = self._reward_normalizer.correct_prediction(\n agent_outputs.baseline)\n else:\n corrected_predictions = learner_outputs.baseline\n old_corrected_predictions = agent_outputs.baseline\n\n # Compute the advantage-based loss.\n policy_loss = tf.reduce_mean(\n self._policy_loss(\n normalized_advantages,\n target_action_log_probs,\n behaviour_action_log_probs,\n actions=agent_outputs.action,\n target_logits=learner_outputs.policy_logits,\n behaviour_logits=agent_outputs.policy_logits,\n parametric_action_distribution=self._parametric_action_distribution)\n )\n\n # Value function loss\n v_error = normalized_targets - corrected_predictions\n self.log('GeneralizedOnPolicyLoss/V_error', v_error)\n self.log('GeneralizedOnPolicyLoss/abs_V_error', tf.abs(v_error))\n self.log('GeneralizedOnPolicyLoss/corrected_predictions',\n corrected_predictions)\n # Huber loss reduces the last dimension so we add a dummy one here.\n normalized_targets = normalized_targets[..., tf.newaxis]\n corrected_predictions = corrected_predictions[..., tf.newaxis]\n v_loss = self.v_loss_fn(normalized_targets, corrected_predictions)\n\n # PPO-style value loss clipping\n if self._value_ppo_style_clip_eps is not None:\n old_corrected_predictions = old_corrected_predictions[..., tf.newaxis]\n clipped_corrected_predictions = tf.clip_by_value(\n corrected_predictions,\n old_corrected_predictions - self._value_ppo_style_clip_eps,\n old_corrected_predictions + self._value_ppo_style_clip_eps)\n clipped_v_loss = self.v_loss_fn(normalized_targets,\n clipped_corrected_predictions)\n v_loss = tf.maximum(v_loss, clipped_v_loss)\n v_loss = tf.reduce_mean(v_loss)\n\n # Compute the regularization loss.\n if self._regularizer:\n per_step_regularization, regularization_loss = self._regularizer(\n self._parametric_action_distribution,\n learner_outputs.policy_logits,\n agent_outputs.policy_logits,\n agent_outputs.action)\n if not self._include_regularization_in_returns:\n regularization_loss += tf.reduce_mean(per_step_regularization)\n else:\n regularization_loss = 0.\n\n total_loss = policy_loss + self._baseline_cost*v_loss + regularization_loss\n return total_loss\n\n\nclass PolicyLoss(tf.Module, metaclass=abc.ABCMeta):\n \"\"\"Abstract base class for policy losses.\"\"\"\n\n @abc.abstractmethod\n def __call__(self, advantages, target_action_log_probs,\n behaviour_action_log_probs):\n r\"\"\"Computes policy loss.\n\n Args:\n advantages: A float32 tensor of shape [T, B] of advantages.\n target_action_log_probs: A float32 tensor of shape [T, B] with\n log-probabilities of taking the action by the current policy\n behaviour_action_log_probs: A float32 tensor of shape [T, B] with\n log-probabilities of taking the action by the behavioural policy\n\n\n Returns:\n A float32 tensor of shape [T, B] with the policy loss.\n \"\"\"\n raise NotImplementedError('`__call__()` is not implemented!')\n\n\nclass RegularizationLoss(tf.Module, metaclass=abc.ABCMeta):\n \"\"\"Abstract base class for policy losses.\"\"\"\n\n @abc.abstractmethod\n def __call__(self, parametric_action_distribution, target_action_logits,\n behaviour_action_logits, actions):\n r\"\"\"Computes regularization loss.\n\n Args:\n parametric_action_distribution: Parametric action distribution.\n target_action_logits: A float32 tensor of shape [T, B, A] with\n the logits of the target policy.\n behaviour_action_logits: A float32 tensor of shape [T, B, A] with\n the logits of the behavioural policy.\n actions: A float32 tensor of shape [T, B, A] with the actions taken by the\n behaviour policy.\n\n Returns:\n A float32 tensor of shape [T, B] with the regularization loss.\n \"\"\"\n raise NotImplementedError('`__call__()` is not implemented!')\n" ]
[ [ "tensorflow.clip_by_value", "tensorflow.reduce_mean", "tensorflow.keras.losses.MeanSquaredError", "tensorflow.maximum", "tensorflow.keras.losses.Huber", "tensorflow.zeros_like", "tensorflow.abs", "tensorflow.nest.map_structure", "tensorflow.logical_and" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "1.12", "2.6", "2.2", "1.13", "2.3", "2.4", "1.4", "2.9", "1.5", "1.7", "2.5", "0.12", "1.0", "2.8", "1.2", "2.10" ] } ]
jorgemarpa/lightkurve
[ "86320a67eabb3a93f60e9faff0447e4b235bccf2", "86320a67eabb3a93f60e9faff0447e4b235bccf2", "86320a67eabb3a93f60e9faff0447e4b235bccf2" ]
[ "tests/io/test_k2sff.py", "tests/test_targetpixelfile.py", "tests/io/test_tasoc.py" ]
[ "import pytest\n\nfrom astropy.io import fits\nimport numpy as np\nfrom numpy.testing import assert_array_equal\n\nfrom lightkurve.io.k2sff import read_k2sff_lightcurve\nfrom lightkurve import search_lightcurve\n\n\[email protected]_data\ndef test_read_k2sff():\n \"\"\"Can we read K2SFF files?\"\"\"\n url = \"http://archive.stsci.edu/hlsps/k2sff/c16/212100000/00236/hlsp_k2sff_k2_lightcurve_212100236-c16_kepler_v1_llc.fits\"\n f = fits.open(url)\n # Verify different extensions\n fluxes = []\n for ext in [\"BESTAPER\", \"CIRC_APER9\"]:\n lc = read_k2sff_lightcurve(url, ext=ext)\n assert type(lc).__name__ == \"KeplerLightCurve\"\n # Are `time` and `flux` consistent with the FITS file?\n assert_array_equal(f[ext].data[\"T\"], lc.time.value)\n assert_array_equal(f[ext].data[\"FCOR\"], lc.flux.value)\n fluxes.append(lc.flux)\n # Different extensions should show different fluxes\n assert not np.array_equal(fluxes[0], fluxes[1])\n\n\[email protected]_data\ndef test_search_k2sff():\n \"\"\"Can we search and download a K2SFF light curve?\"\"\"\n # Try an early campaign\n search = search_lightcurve(\"K2-18\", author=\"K2SFF\", campaign=1)\n assert len(search) == 1\n assert search.table[\"author\"][0] == \"K2SFF\"\n lc = search.download()\n assert type(lc).__name__ == \"KeplerLightCurve\"\n assert lc.campaign == 1\n # Try a late campaign\n lc = search_lightcurve(\"GJ 9827\", author=\"K2SFF\", campaign=19).download()\n assert type(lc).__name__ == \"KeplerLightCurve\"\n assert lc.targetid == 246389858\n assert lc.campaign == 19\n", "import os\nimport tempfile\nimport warnings\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom numpy.testing import assert_array_equal\nimport pytest\n\nfrom astropy.utils.data import get_pkg_data_filename\nfrom astropy.io.fits.verify import VerifyWarning\nfrom astropy.coordinates import SkyCoord\nfrom astropy.io import fits\nfrom astropy import wcs\nfrom astropy.io.fits.card import UNDEFINED\nimport astropy.units as u\nfrom astropy.utils.exceptions import AstropyWarning\n\nfrom lightkurve.targetpixelfile import KeplerTargetPixelFile, TargetPixelFileFactory\nfrom lightkurve.targetpixelfile import TessTargetPixelFile, TargetPixelFile\nfrom lightkurve.lightcurve import TessLightCurve\nfrom lightkurve.utils import LightkurveWarning, LightkurveDeprecationWarning\nfrom lightkurve.io import read\nfrom lightkurve.search import search_tesscut\n\nfrom .test_synthetic_data import filename_synthetic_flat\n\nfilename_tpf_all_zeros = get_pkg_data_filename(\"data/test-tpf-all-zeros.fits\")\nfilename_tpf_one_center = get_pkg_data_filename(\"data/test-tpf-non-zero-center.fits\")\nfilename_tess = get_pkg_data_filename(\"data/tess25155310-s01-first-cadences.fits.gz\")\n\nTABBY_Q8 = (\n \"https://archive.stsci.edu/missions/kepler/lightcurves\"\n \"/0084/008462852/kplr008462852-2011073133259_llc.fits\"\n)\nTABBY_TPF = (\n \"https://archive.stsci.edu/missions/kepler/target_pixel_files\"\n \"/0084/008462852/kplr008462852-2011073133259_lpd-targ.fits.gz\"\n)\nTESS_SIM = (\n \"https://archive.stsci.edu/missions/tess/ete-6/tid/00/000\"\n \"/004/176/tess2019128220341-0000000417699452-0016-s_tp.fits\"\n)\nasteroid_TPF = get_pkg_data_filename(\"data/asteroid_test.fits\")\n\n\[email protected]_data\ndef test_load_bad_file():\n \"\"\"Test if a light curve can be opened without exception.\"\"\"\n with pytest.raises(ValueError) as exc:\n KeplerTargetPixelFile(TABBY_Q8)\n assert \"is this a target pixel file?\" in exc.value.args[0]\n with pytest.raises(ValueError) as exc:\n TessTargetPixelFile(TABBY_Q8)\n assert \"is this a target pixel file?\" in exc.value.args[0]\n\n\ndef test_tpf_shapes():\n \"\"\"Are the data array shapes of the TargetPixelFile object consistent?\"\"\"\n with warnings.catch_warnings():\n # Ignore the \"TELESCOP is not equal to TESS\" warning\n warnings.simplefilter(\"ignore\", LightkurveWarning)\n tpfs = [\n KeplerTargetPixelFile(filename_tpf_all_zeros),\n TessTargetPixelFile(filename_tpf_all_zeros),\n ]\n for tpf in tpfs:\n assert tpf.quality_mask.shape == tpf.hdu[1].data[\"TIME\"].shape\n assert tpf.flux.shape == tpf.flux_err.shape\n\n\ndef test_tpf_math():\n \"\"\"Can you add, subtract, multiply and divide?\"\"\"\n with warnings.catch_warnings():\n # Ignore the \"TELESCOP is not equal to TESS\" warning\n warnings.simplefilter(\"ignore\", LightkurveWarning)\n tpfs = [\n KeplerTargetPixelFile(filename_tpf_all_zeros),\n TessTargetPixelFile(filename_tpf_all_zeros),\n ]\n\n # These should work\n for tpf in tpfs:\n for other in [1, np.ones(tpf.flux.shape[1:]), np.ones(tpf.shape)]:\n tpf + other\n tpf - other\n tpf * other\n tpf / other\n\n tpf += other\n tpf -= other\n tpf *= other\n tpf /= other\n\n # These should fail with a value error because their shape is wrong.\n for tpf in tpfs:\n for other in [\n np.asarray([1, 2]),\n np.arange(len(tpf.time) - 1),\n np.ones([100, 1]),\n np.ones([1, 2, 3]),\n ]:\n with pytest.raises(ValueError):\n tpf + other\n\n # Check the values are correct\n assert np.all(\n ((tpf.flux.value + 2) == (tpf + 2).flux.value)[np.isfinite(tpf.flux)]\n )\n assert np.all(\n ((tpf.flux.value - 2) == (tpf - 2).flux.value)[np.isfinite(tpf.flux)]\n )\n assert np.all(\n ((tpf.flux.value * 2) == (tpf * 2).flux.value)[np.isfinite(tpf.flux)]\n )\n assert np.all(\n ((tpf.flux.value / 2) == (tpf / 2).flux.value)[np.isfinite(tpf.flux)]\n )\n assert np.all(\n ((tpf.flux_err.value * 2) == (tpf * 2).flux_err.value)[\n np.isfinite(tpf.flux)\n ]\n )\n assert np.all(\n ((tpf.flux_err.value / 2) == (tpf / 2).flux_err.value)[\n np.isfinite(tpf.flux)\n ]\n )\n\n\ndef test_tpf_plot():\n \"\"\"Sanity check to verify that tpf plotting works\"\"\"\n with warnings.catch_warnings():\n # Ignore the \"TELESCOP is not equal to TESS\" warning\n warnings.simplefilter(\"ignore\", LightkurveWarning)\n tpfs = [\n KeplerTargetPixelFile(filename_tpf_one_center),\n TessTargetPixelFile(filename_tpf_one_center),\n ]\n for tpf in tpfs:\n tpf.plot()\n tpf.plot(aperture_mask=tpf.pipeline_mask)\n tpf.plot(aperture_mask=\"all\")\n tpf.plot(frame=3)\n with pytest.raises(ValueError):\n tpf.plot(frame=999999)\n tpf.plot(cadenceno=125250)\n with pytest.raises(ValueError):\n tpf.plot(cadenceno=999)\n tpf.plot(bkg=True)\n tpf.plot(scale=\"sqrt\")\n tpf.plot(scale=\"log\")\n with pytest.raises(ValueError):\n tpf.plot(scale=\"blabla\")\n tpf.plot(column=\"FLUX\")\n tpf.plot(column=\"FLUX_ERR\")\n tpf.plot(column=\"FLUX_BKG\")\n tpf.plot(column=\"FLUX_BKG_ERR\")\n tpf.plot(column=\"RAW_CNTS\")\n tpf.plot(column=\"COSMIC_RAYS\")\n with pytest.raises(ValueError):\n tpf.plot(column=\"not a column\")\n\n plt.close(\"all\")\n\n\ndef test_tpf_zeros():\n \"\"\"Does the LightCurve of a zero-flux TPF make sense?\"\"\"\n tpf = KeplerTargetPixelFile(filename_tpf_all_zeros, quality_bitmask=None)\n with warnings.catch_warnings():\n # Ignore \"LightCurve contains NaN times\" warnings triggered by the liberal mask\n warnings.simplefilter(\"ignore\", LightkurveWarning)\n lc = tpf.to_lightcurve()\n # If you don't mask out bad data, time contains NaNs\n assert np.any(\n lc.time.value != tpf.time\n ) # Using the property that NaN does not equal NaN\n # When you do mask out bad data everything should work.\n assert (tpf.time.value == 0).any()\n tpf = KeplerTargetPixelFile(filename_tpf_all_zeros, quality_bitmask=\"hard\")\n lc = tpf.to_lightcurve(aperture_mask=\"all\")\n assert len(lc.time) == len(lc.flux)\n assert np.all(lc.time == tpf.time)\n assert np.all(np.isnan(lc.flux)) # we expect all NaNs because of #874\n # The default QUALITY bitmask should have removed all NaNs in the TIME\n assert ~np.any(np.isnan(tpf.time.value))\n\n\[email protected](\"centroid_method\", [(\"moments\"), (\"quadratic\")])\ndef test_tpf_ones(centroid_method):\n \"\"\"Does the LightCurve of a one-flux TPF make sense?\"\"\"\n with warnings.catch_warnings():\n # Ignore the \"TELESCOP is not equal to TESS\" warning\n warnings.simplefilter(\"ignore\", LightkurveWarning)\n tpfs = [\n KeplerTargetPixelFile(filename_tpf_one_center),\n TessTargetPixelFile(filename_tpf_one_center),\n ]\n for tpf in tpfs:\n lc = tpf.to_lightcurve(aperture_mask=\"all\", centroid_method=centroid_method)\n assert np.all(lc.flux.value == 1)\n assert np.all(\n (lc.centroid_col.value < tpf.column + tpf.shape[1]).all()\n * (lc.centroid_col.value > tpf.column).all()\n )\n assert np.all(\n (lc.centroid_row.value < tpf.row + tpf.shape[2]).all()\n * (lc.centroid_row.value > tpf.row).all()\n )\n\n\[email protected](\n \"quality_bitmask,answer\",\n [\n (None, 1290),\n (\"none\", 1290),\n (\"default\", 1233),\n (\"hard\", 1101),\n (\"hardest\", 1101),\n (1, 1290),\n (100, 1278),\n (2096639, 1101),\n ],\n)\ndef test_bitmasking(quality_bitmask, answer):\n \"\"\"Test whether the bitmasking behaves like it should\"\"\"\n tpf = KeplerTargetPixelFile(\n filename_tpf_one_center, quality_bitmask=quality_bitmask\n )\n with warnings.catch_warnings():\n # Ignore \"LightCurve contains NaN times\" warnings triggered by liberal masks\n warnings.simplefilter(\"ignore\", LightkurveWarning)\n lc = tpf.to_lightcurve()\n assert len(lc.flux) == answer\n\n\ndef test_wcs():\n \"\"\"Test the wcs property.\"\"\"\n for tpf in [\n KeplerTargetPixelFile(filename_tpf_one_center),\n TessTargetPixelFile(filename_tess),\n ]:\n w = tpf.wcs\n ra, dec = tpf.get_coordinates()\n assert ra.shape == tpf.shape\n assert dec.shape == tpf.shape\n assert type(w).__name__ == \"WCS\"\n\n\[email protected]_data\[email protected](\"method\", [(\"moments\"), (\"quadratic\")])\ndef test_wcs_tabby(method):\n \"\"\"Test the centroids from Tabby's star against simbad values\"\"\"\n tpf = KeplerTargetPixelFile(TABBY_TPF)\n tpf.wcs\n ra, dec = tpf.get_coordinates(0)\n col, row = tpf.estimate_centroids(method=method)\n col = col.value - tpf.column\n row = row.value - tpf.row\n y, x = int(np.round(col[0])), int(np.round(row[1]))\n # Compare with RA and Dec from Simbad\n assert np.isclose(ra[x, y], 301.5643971, 1e-4)\n assert np.isclose(dec[x, y], 44.4568869, 1e-4)\n\n\ndef test_centroid_methods_consistency():\n \"\"\"Are the centroid methods consistent for a well behaved target?\"\"\"\n pixels = read(filename_synthetic_flat)\n centr_moments = pixels.estimate_centroids(method=\"moments\")\n centr_quadratic = pixels.estimate_centroids(method=\"quadratic\")\n # check that the maximum relative difference doesnt exceed 1%\n assert (\n np.max(np.abs(centr_moments[0] - centr_quadratic[0]) / centr_moments[0]) < 1e-2\n )\n assert (\n np.max(np.abs(centr_moments[1] - centr_quadratic[1]) / centr_moments[1]) < 1e-2\n )\n\n\ndef test_properties():\n \"\"\"Test the short-hand properties.\"\"\"\n tpf = KeplerTargetPixelFile(filename_tpf_all_zeros)\n assert tpf.channel == tpf.hdu[0].header[\"CHANNEL\"]\n assert tpf.module == tpf.hdu[0].header[\"MODULE\"]\n assert tpf.output == tpf.hdu[0].header[\"OUTPUT\"]\n assert tpf.ra == tpf.hdu[0].header[\"RA_OBJ\"]\n assert tpf.dec == tpf.hdu[0].header[\"DEC_OBJ\"]\n assert_array_equal(tpf.flux.value, tpf.hdu[1].data[\"FLUX\"][tpf.quality_mask])\n assert_array_equal(\n tpf.flux_err.value, tpf.hdu[1].data[\"FLUX_ERR\"][tpf.quality_mask]\n )\n assert_array_equal(\n tpf.flux_bkg.value, tpf.hdu[1].data[\"FLUX_BKG\"][tpf.quality_mask]\n )\n assert_array_equal(\n tpf.flux_bkg_err.value, tpf.hdu[1].data[\"FLUX_BKG_ERR\"][tpf.quality_mask]\n )\n assert_array_equal(tpf.quality, tpf.hdu[1].data[\"QUALITY\"][tpf.quality_mask])\n assert tpf.campaign == tpf.hdu[0].header[\"CAMPAIGN\"]\n assert tpf.quarter is None\n\n\ndef test_repr():\n \"\"\"Do __str__ and __repr__ work?\"\"\"\n for tpf in [\n KeplerTargetPixelFile(filename_tpf_all_zeros),\n TessTargetPixelFile(filename_tess),\n ]:\n str(tpf)\n repr(tpf)\n\n\ndef test_to_lightcurve():\n for tpf in [\n KeplerTargetPixelFile(filename_tpf_all_zeros),\n TessTargetPixelFile(filename_tess),\n ]:\n tpf.to_lightcurve()\n tpf.to_lightcurve(aperture_mask=None)\n tpf.to_lightcurve(aperture_mask=\"all\")\n lc = tpf.to_lightcurve(aperture_mask=\"threshold\")\n assert lc.time.scale == \"tdb\"\n assert lc.label == tpf.hdu[0].header[\"OBJECT\"]\n if np.any(tpf.pipeline_mask):\n tpf.to_lightcurve(aperture_mask=\"pipeline\")\n else:\n with pytest.raises(ValueError):\n tpf.to_lightcurve(aperture_mask=\"pipeline\")\n\n\ndef test_bkg_lightcurve():\n for tpf in [\n KeplerTargetPixelFile(filename_tpf_all_zeros),\n TessTargetPixelFile(filename_tess),\n ]:\n lc = tpf.get_bkg_lightcurve()\n lc = tpf.get_bkg_lightcurve(aperture_mask=None)\n lc = tpf.get_bkg_lightcurve(aperture_mask=\"all\")\n assert lc.time.scale == \"tdb\"\n assert lc.flux.shape == lc.flux_err.shape\n assert len(lc.time) == len(lc.flux)\n\n\ndef test_aperture_photometry():\n for tpf in [\n KeplerTargetPixelFile(filename_tpf_all_zeros),\n TessTargetPixelFile(filename_tess),\n ]:\n tpf.extract_aperture_photometry()\n for mask in [None, \"all\", \"default\", \"threshold\", \"background\"]:\n tpf.extract_aperture_photometry(aperture_mask=mask)\n if np.any(tpf.pipeline_mask):\n tpf.extract_aperture_photometry(aperture_mask=\"pipeline\")\n else:\n with pytest.raises(ValueError):\n tpf.extract_aperture_photometry(aperture_mask=\"pipeline\")\n\n\ndef test_tpf_to_fits():\n \"\"\"Can we write a TPF back to a fits file?\"\"\"\n for tpf in [\n KeplerTargetPixelFile(filename_tpf_all_zeros),\n TessTargetPixelFile(filename_tess),\n ]:\n # `delete=False` is necessary to enable writing to the file on Windows\n # but it means we have to clean up the tmp file ourselves\n tmp = tempfile.NamedTemporaryFile(delete=False)\n try:\n tpf.to_fits(tmp.name)\n finally:\n tmp.close()\n os.remove(tmp.name)\n\n\ndef test_tpf_factory():\n \"\"\"Can we create TPFs using TargetPixelFileFactory?\"\"\"\n from lightkurve.targetpixelfile import FactoryError\n\n factory = TargetPixelFileFactory(n_cadences=10, n_rows=6, n_cols=8)\n flux_0 = np.ones((6, 8))\n factory.add_cadence(frameno=0, flux=flux_0, header={\"TSTART\": 0, \"TSTOP\": 10})\n flux_9 = 3 * np.ones((6, 8))\n factory.add_cadence(frameno=9, flux=flux_9, header={\"TSTART\": 90, \"TSTOP\": 100})\n\n # You shouldn't be able to build a TPF like this...because TPFs shouldn't\n # have extensions where time stamps are duplicated (here frames 1-8 will have)\n # time stamp zero\n with pytest.warns(LightkurveWarning, match=\"identical TIME values\"):\n tpf = factory.get_tpf()\n [\n factory.add_cadence(\n frameno=i, flux=flux_0, header={\"TSTART\": i * 10, \"TSTOP\": (i * 10) + 10}\n )\n for i in np.arange(2, 9)\n ]\n\n # This should fail because the time stamps of the images are not in order...\n with pytest.warns(LightkurveWarning, match=\"chronological order\"):\n tpf = factory.get_tpf()\n\n [\n factory.add_cadence(\n frameno=i, flux=flux_0, header={\"TSTART\": i * 10, \"TSTOP\": (i * 10) + 10}\n )\n for i in np.arange(1, 9)\n ]\n\n # This should pass\n tpf = factory.get_tpf(hdu0_keywords={\"TELESCOP\": \"TESS\"})\n\n assert_array_equal(tpf.flux[0].value, flux_0)\n assert_array_equal(tpf.flux[9].value, flux_9)\n\n tpf = factory.get_tpf(hdu0_keywords={\"TELESCOP\": \"Kepler\"})\n\n assert_array_equal(tpf.flux[0].value, flux_0)\n assert_array_equal(tpf.flux[9].value, flux_9)\n assert tpf.time[0].value == 5\n assert tpf.time[9].value == 95\n\n # Can you add the WRONG sized frame?\n flux_wrong = 3 * np.ones((6, 9))\n with pytest.raises(FactoryError):\n factory.add_cadence(\n frameno=2, flux=flux_wrong, header={\"TSTART\": 90, \"TSTOP\": 100}\n )\n\n # Can you add the WRONG cadence?\n flux_wrong = 3 * np.ones((6, 8))\n with pytest.raises(FactoryError):\n factory.add_cadence(\n frameno=11, flux=flux_wrong, header={\"TSTART\": 90, \"TSTOP\": 100}\n )\n\n # Can we add our own keywords?\n tpf = factory.get_tpf(\n hdu0_keywords={\"creator\": \"Christina TargetPixelFileWriter\", \"TELESCOP\": \"TESS\"}\n )\n assert tpf.get_keyword(\"CREATOR\") == \"Christina TargetPixelFileWriter\"\n\n\ndef _create_image_array(header=None, shape=(5, 5)):\n \"\"\"Helper function for tests below.\"\"\"\n if header is None:\n header = fits.Header()\n images = []\n for i in range(5):\n header[\"TSTART\"] = i\n header[\"TSTOP\"] = i + 1\n images.append(fits.ImageHDU(data=np.ones(shape), header=header))\n return images\n\n\ndef test_tpf_from_images():\n \"\"\"Basic tests of tpf.from_fits_images()\"\"\"\n # Not without a wcs...\n with pytest.raises(Exception):\n TargetPixelFile.from_fits_images(\n _create_image_array(),\n size=(3, 3),\n position=SkyCoord(-234.75, 8.3393, unit=\"deg\"),\n )\n\n # Make a fake WCS based on astropy.docs...\n w = wcs.WCS(naxis=2)\n w.wcs.crpix = [-234.75, 8.3393]\n w.wcs.cdelt = np.array([-0.066667, 0.066667])\n w.wcs.crval = [0, -90]\n w.wcs.ctype = [\"RA---AIR\", \"DEC--AIR\"]\n w.wcs.set_pv([(2, 1, 45.0)])\n pixcrd = np.array([[0, 0], [24, 38], [45, 98]], np.float_)\n header = w.to_header()\n header[\"CRVAL1P\"] = 10\n header[\"CRVAL2P\"] = 20\n ra, dec = 268.21686048, -73.66991904\n\n # Now this should work.\n images = _create_image_array(header=header)\n with warnings.catch_warnings():\n # Ignore \"LightkurveWarning: Could not detect filetype as TESSTargetPixelFile or KeplerTargetPixelFile, returning generic TargetPixelFile instead.\"\n warnings.simplefilter(\"ignore\", LightkurveWarning)\n tpf = TargetPixelFile.from_fits_images(\n images, size=(3, 3), position=SkyCoord(ra, dec, unit=(u.deg, u.deg))\n )\n assert isinstance(tpf, TargetPixelFile)\n\n with warnings.catch_warnings():\n # Some cards are too long -- to be investigated.\n warnings.simplefilter(\"ignore\", VerifyWarning)\n # Can we write the output to disk?\n # `delete=False` is necessary below to enable writing to the file on Windows\n # but it means we have to clean up the tmp file ourselves\n tmp = tempfile.NamedTemporaryFile(delete=False)\n try:\n tpf.to_fits(tmp.name)\n finally:\n tmp.close()\n os.remove(tmp.name)\n\n # Can we read in a list of file names or a list of HDUlists?\n hdus = []\n tmpfile_names = []\n for im in images:\n tmpfile = tempfile.NamedTemporaryFile(delete=False)\n tmpfile_names.append(tmpfile.name)\n hdu = fits.HDUList([fits.PrimaryHDU(), im])\n hdu.writeto(tmpfile.name)\n hdus.append(hdu)\n\n with warnings.catch_warnings():\n # Ignore \"LightkurveWarning: Could not detect filetype as TESSTargetPixelFile or KeplerTargetPixelFile, returning generic TargetPixelFile instead.\"\n warnings.simplefilter(\"ignore\", LightkurveWarning)\n # Should be able to run with a list of file names\n tpf_tmpfiles = TargetPixelFile.from_fits_images(\n tmpfile_names,\n size=(3, 3),\n position=SkyCoord(ra, dec, unit=(u.deg, u.deg)),\n )\n\n # Should be able to run with a list of HDUlists\n tpf_hdus = TargetPixelFile.from_fits_images(\n hdus, size=(3, 3), position=SkyCoord(ra, dec, unit=(u.deg, u.deg))\n )\n\n # Clean up the temporary files we created\n for filename in tmpfile_names:\n try:\n os.remove(filename)\n except PermissionError:\n pass # This appears to happen on Windows\n\n\ndef test_tpf_wcs_from_images():\n \"\"\"Test to see if tpf.from_fits_images() output a tpf with WCS in the header\"\"\"\n # Not without a wcs...\n with pytest.raises(Exception):\n TargetPixelFile.from_fits_images(\n _create_image_array(),\n size=(3, 3),\n position=SkyCoord(-234.75, 8.3393, unit=\"deg\"),\n )\n\n # Make a fake WCS based on astropy.docs...\n w = wcs.WCS(naxis=2)\n w.wcs.crpix = [0.0, 0.0]\n w.wcs.cdelt = np.array([0.001111, 0.001111])\n w.wcs.crval = [23.2334, 45.2333]\n w.wcs.ctype = [\"RA---TAN\", \"DEC--TAN\"]\n header = w.to_header()\n header[\"CRVAL1P\"] = 10\n header[\"CRVAL2P\"] = 20\n ra, dec = 23.2336, 45.235\n\n with warnings.catch_warnings():\n # Ignore \"LightkurveWarning: Could not detect filetype as TESSTargetPixelFile or KeplerTargetPixelFile, returning generic TargetPixelFile instead.\"\n warnings.simplefilter(\"ignore\", LightkurveWarning)\n # Now this should work.\n tpf = TargetPixelFile.from_fits_images(\n _create_image_array(header=header),\n size=(3, 3),\n position=SkyCoord(ra, dec, unit=(u.deg, u.deg)),\n )\n assert tpf.hdu[1].header[\"1CRPX5\"] != UNDEFINED\n assert tpf.hdu[1].header[\"1CTYP5\"] == \"RA---TAN\"\n assert tpf.hdu[1].header[\"2CTYP5\"] == \"DEC--TAN\"\n assert tpf.hdu[1].header[\"1CRPX5\"] != UNDEFINED\n assert tpf.hdu[1].header[\"2CRPX5\"] != UNDEFINED\n assert tpf.hdu[1].header[\"1CUNI5\"] == \"deg\"\n assert tpf.hdu[1].header[\"2CUNI5\"] == \"deg\"\n with warnings.catch_warnings():\n # Ignore the warning: \"PC1_1 = a floating-point value was expected.\"\n warnings.simplefilter(\"ignore\", AstropyWarning)\n assert tpf.wcs.to_header()[\"CDELT1\"] == w.wcs.cdelt[0]\n\n\ndef test_properties2(capfd):\n \"\"\"Test if the describe function produces an output.\n The output is 1870 characters at the moment, but we might add more properties.\"\"\"\n tpf = KeplerTargetPixelFile(filename_tpf_all_zeros)\n tpf.show_properties()\n out, err = capfd.readouterr()\n assert len(out) > 1000\n\n\ndef test_interact():\n \"\"\"Test the Jupyter notebook interact() widget.\"\"\"\n for tpf in [\n KeplerTargetPixelFile(filename_tpf_one_center),\n TessTargetPixelFile(filename_tess),\n ]:\n tpf.interact()\n\n\[email protected]_data\ndef test_interact_sky():\n \"\"\"Test the Jupyter notebook interact() widget.\"\"\"\n for tpf in [\n KeplerTargetPixelFile(filename_tpf_one_center),\n TessTargetPixelFile(filename_tess),\n ]:\n tpf.interact_sky()\n\n\ndef test_get_models():\n \"\"\"Can we obtain PRF and TPF models?\"\"\"\n tpf = KeplerTargetPixelFile(filename_tpf_all_zeros, quality_bitmask=None)\n with warnings.catch_warnings():\n # Ignore \"RuntimeWarning: All-NaN slice encountered\"\n warnings.simplefilter(\"ignore\", RuntimeWarning)\n tpf.get_model()\n tpf.get_prf_model()\n\n\[email protected]_data\ndef test_tess_simulation():\n \"\"\"Can we read simulated TESS data?\"\"\"\n tpf = TessTargetPixelFile(TESS_SIM)\n assert tpf.mission == \"TESS\"\n assert tpf.time.scale == \"tdb\"\n assert tpf.flux.shape == tpf.flux_err.shape\n tpf.wcs\n col, row = tpf.estimate_centroids()\n # Regression test for https://github.com/lightkurve/lightkurve/pull/236\n assert (tpf.time.value == 0).sum() == 0\n\n\ndef test_threshold_aperture_mask():\n \"\"\"Does the threshold mask work?\"\"\"\n tpf = KeplerTargetPixelFile(filename_tpf_one_center)\n tpf.plot(aperture_mask=\"threshold\")\n lc = tpf.to_lightcurve(aperture_mask=tpf.create_threshold_mask(threshold=1))\n assert (lc.flux.value == 1).all()\n # The TESS file shows three pixel regions above a 2-sigma threshold;\n # let's make sure the `reference_pixel` argument allows them to be selected.\n tpf = TessTargetPixelFile(filename_tess)\n assert tpf.create_threshold_mask(threshold=2.0).sum() == 25\n assert (\n tpf.create_threshold_mask(threshold=2.0, reference_pixel=\"center\").sum() == 25\n )\n assert tpf.create_threshold_mask(threshold=2.0, reference_pixel=None).sum() == 28\n assert tpf.create_threshold_mask(threshold=2.0, reference_pixel=(5, 0)).sum() == 2\n # A mask which contains zero-flux pixels should work without crashing\n tpf = KeplerTargetPixelFile(filename_tpf_all_zeros)\n assert tpf.create_threshold_mask().sum() == 9\n\n\ndef test_tpf_tess():\n \"\"\"Does a TESS Sector 1 TPF work?\"\"\"\n tpf = TessTargetPixelFile(filename_tess, quality_bitmask=None)\n assert tpf.mission == \"TESS\"\n assert tpf.targetid == 25155310\n assert tpf.sector == 1\n assert tpf.camera == 4\n assert tpf.ccd == 1\n assert tpf.pipeline_mask.sum() == 9\n assert tpf.background_mask.sum() == 30\n lc = tpf.to_lightcurve()\n assert isinstance(lc, TessLightCurve)\n assert_array_equal(lc.time, tpf.time)\n assert tpf.time.scale == \"tdb\"\n assert tpf.flux.shape == tpf.flux_err.shape\n tpf.wcs\n col, row = tpf.estimate_centroids()\n\n\[email protected](\"tpf_type\", [KeplerTargetPixelFile, TessTargetPixelFile])\ndef test_tpf_slicing(tpf_type):\n \"\"\"Test indexing and slicing of TargetPixelFile objects.\"\"\"\n with warnings.catch_warnings():\n # Ignore \"LightkurveWarning: A Kepler data product is being opened using the `TessTargetPixelFile` class. Please use `KeplerTargetPixelFile` instead.\"\n warnings.simplefilter(\"ignore\", LightkurveWarning)\n tpf = tpf_type(filename_tpf_one_center)\n\n assert tpf[0].time == tpf.time[0]\n assert tpf[-1].time == tpf.time[-1]\n assert tpf[5:10].shape == tpf.flux[5:10].shape\n assert tpf[0].targetid == tpf.targetid\n assert_array_equal(tpf[tpf.time < tpf.time[5]].time, tpf.time[0:5])\n\n frame = tpf[5]\n assert frame.shape[0] == 1\n assert frame.shape[1:] == tpf.shape[1:]\n assert_array_equal(frame.time[0], tpf.time[5])\n assert_array_equal(frame.flux[0], tpf.flux[5])\n\n frames = tpf[100:200]\n assert frames.shape[0] == 100\n assert frames.shape[1:] == tpf.shape[1:]\n assert_array_equal(frames.time, tpf.time[100:200])\n assert_array_equal(frames.flux, tpf.flux[100:200])\n\n\ndef test_endianness():\n \"\"\"Regression test for https://github.com/lightkurve/lightkurve/issues/188\"\"\"\n tpf = KeplerTargetPixelFile(filename_tpf_one_center)\n tpf.to_lightcurve().to_pandas().describe()\n\n\ndef test_get_keyword():\n tpf = KeplerTargetPixelFile(filename_tpf_one_center)\n assert tpf.get_keyword(\"TELESCOP\") == \"Kepler\"\n assert tpf.get_keyword(\"TTYPE1\", hdu=1) == \"TIME\"\n assert tpf.get_keyword(\"DOESNOTEXIST\", default=5) == 5\n\n\ndef test_cutout():\n \"\"\"Test tpf.cutout() function.\"\"\"\n for tpf in [\n KeplerTargetPixelFile(filename_tpf_one_center),\n TessTargetPixelFile(filename_tess, quality_bitmask=None),\n ]:\n ntpf = tpf.cutout(size=2)\n assert ntpf.flux[0].shape == (2, 2)\n assert ntpf.flux_err[0].shape == (2, 2)\n assert ntpf.flux_bkg[0].shape == (2, 2)\n ntpf = tpf.cutout((0, 0), size=3)\n ntpf = tpf.cutout(size=(1, 2))\n assert ntpf.flux.shape[1] == 2\n assert ntpf.flux.shape[2] == 1\n ntpf = tpf.cutout(SkyCoord(tpf.ra, tpf.dec, unit=\"deg\"), size=2)\n ntpf = tpf.cutout(size=2)\n assert np.product(ntpf.flux.shape[1:]) == 4\n assert ntpf.targetid == \"{}_CUTOUT\".format(tpf.targetid)\n\n\ndef test_aperture_photometry_nan():\n \"\"\"Regression test for #648.\n\n When FLUX or FLUX_ERR is entirely NaN in a TPF, the resulting light curve\n should report NaNs in that cadence rather than zero.\"\"\"\n tpf = read(filename_tpf_one_center)\n tpf.hdu[1].data[\"FLUX\"][2] = np.nan\n tpf.hdu[1].data[\"FLUX_ERR\"][2] = np.nan\n lc = tpf.to_lightcurve(aperture_mask=\"all\")\n assert ~np.isnan(lc.flux[1])\n assert ~np.isnan(lc.flux_err[1])\n assert np.isnan(lc.flux[2])\n assert np.isnan(lc.flux_err[2])\n\n\n#@pytest.mark.remote_data\[email protected] # At time of writing, the SkyBot API yields too many intermittent HTTP Errors\ndef test_SSOs():\n # TESS test\n tpf = TessTargetPixelFile(asteroid_TPF)\n result = tpf.query_solar_system_objects() # default cadence_mask = 'outliers'\n assert (\n result is None\n ) # the TPF has only data for 1 epoch. The lone time is removed as outlier\n result = tpf.query_solar_system_objects(cadence_mask=\"all\", cache=False)\n assert len(result) == 1\n result = tpf.query_solar_system_objects(\n cadence_mask=np.asarray([True]), cache=False\n )\n assert len(result) == 1\n result = tpf.query_solar_system_objects(cadence_mask=[True], cache=False)\n assert len(result) == 1\n result = tpf.query_solar_system_objects(cadence_mask=(True), cache=False)\n assert len(result) == 1\n result, mask = tpf.query_solar_system_objects(\n cadence_mask=np.asarray([True]), cache=True, return_mask=True\n )\n assert len(mask) == len(tpf.flux)\n try:\n result = tpf.query_solar_system_objects(\n cadence_mask=\"str-not-supported\", cache=False\n )\n pytest.fail(\"Unsupported cadence_mask should have thrown Error\")\n except ValueError:\n pass\n\n\ndef test_get_header():\n \"\"\"Test the basic functionality of ``tpf.get_header()``\"\"\"\n tpf = read(filename_tpf_one_center)\n assert tpf.get_header()[\"CHANNEL\"] == tpf.get_keyword(\"CHANNEL\")\n assert tpf.get_header(0)[\"MISSION\"] == tpf.get_keyword(\"MISSION\")\n assert tpf.get_header(ext=2)[\"EXTNAME\"] == \"APERTURE\"\n # ``tpf.header`` is deprecated\n with pytest.warns(LightkurveDeprecationWarning, match=\"deprecated\"):\n tpf.header\n\n\ndef test_plot_pixels():\n tpf = KeplerTargetPixelFile(filename_tpf_one_center)\n tpf.plot_pixels()\n tpf.plot_pixels(normalize=True)\n tpf.plot_pixels(periodogram=True)\n tpf.plot_pixels(periodogram=True, nyquist_factor=0.5)\n tpf.plot_pixels(aperture_mask=\"all\")\n tpf.plot_pixels(aperture_mask=tpf.pipeline_mask)\n tpf.plot_pixels(aperture_mask=tpf.create_threshold_mask())\n tpf.plot_pixels(show_flux=True)\n tpf.plot_pixels(corrector_func=lambda x: x)\n plt.close(\"all\")\n\n\[email protected]_data\ndef test_missing_pipeline_mask():\n \"\"\"Regression test for #791.\n\n TPFs produced by TESSCut contain an empty pipeline mask. When the pipeline\n mask is missing or empty, we want `to_lightcurve()` to fall back on the\n 'threshold' mask by default, to avoid creating a light curve based on zero pixels.\"\"\"\n tpf = search_tesscut(\"Proxima Cen\", sector=12).download(cutout_size=1)\n lc = tpf.to_lightcurve()\n assert np.isfinite(lc.flux).any()\n assert lc.meta.get(\"APERTURE_MASK\", None) == \"threshold\"\n\n with pytest.raises(ValueError):\n # if aperture_mask is explicitly set as pipeline,\n # the logic will throw an error as it is missing in the TPF\n lc = tpf.to_lightcurve(aperture_mask=\"pipeline\")\n\n\ndef test_cutout_quality_masking():\n \"\"\"Regression test for #813: Does tpf.cutout() maintain the quality mask?\"\"\"\n tpf = read(filename_tpf_one_center, quality_bitmask=8192)\n tpfcut = tpf.cutout()\n assert len(tpf) == len(tpfcut)\n\n\ndef test_parse_numeric_aperture_masks():\n \"\"\"Regression test for #694: float or int aperture masks should be\n interpreted as boolean masks.\"\"\"\n tpf = read(filename_tpf_one_center)\n mask = tpf._parse_aperture_mask(np.zeros(tpf.shape[1:], dtype=float))\n assert mask.dtype == bool\n mask = tpf._parse_aperture_mask(np.zeros(tpf.shape[1:], dtype=int))\n assert mask.dtype == bool\n\n\ndef test_tpf_meta():\n \"\"\"Can we access meta data using tpf.meta?\"\"\"\n tpf = read(filename_tpf_one_center)\n assert tpf.meta.get(\"MISSION\") == \"K2\"\n assert tpf.meta[\"MISSION\"] == \"K2\"\n assert tpf.meta.get(\"mission\", None) is None # key is case in-sensitive\n assert tpf.meta.get(\"CHANNEL\") == 45\n # ensure meta is read-only view of the underlying self.hdu[0].header\n with pytest.raises(TypeError):\n tpf.meta[\"CHANNEL\"] = 44\n with pytest.raises(TypeError):\n tpf.meta[\"KEY-NEW\"] = 44\n\n\ndef test_estimate_background():\n \"\"\"Verifies tpf.estimate_background().\"\"\"\n # Create a TPF with 100 electron/second in every pixel\n tpf = read(filename_tpf_all_zeros) + 100.0\n # The resulting background should be 100 e/s/pixel\n bg = tpf.estimate_background(aperture_mask=\"all\")\n assert_array_equal(bg.flux.value, 100)\n assert bg.flux.unit == tpf.flux.unit / u.pixel\n\n\ndef test_fluxmode():\n \"\"\"This should verify the median flux use in an aperture\"\"\"\n tpf = read(filename_tpf_one_center)\n lc_n = tpf.extract_aperture_photometry(aperture_mask=\"all\")\n lc_sum = tpf.extract_aperture_photometry(aperture_mask=\"all\", flux_method=\"sum\")\n lc_med = tpf.extract_aperture_photometry(aperture_mask=\"all\", flux_method=\"median\")\n lc_mean = tpf.extract_aperture_photometry(aperture_mask=\"all\", flux_method=\"mean\")\n assert lc_n.flux.value[0] == np.nansum(tpf.flux.value[0])\n assert lc_sum.flux.value[0] == np.nansum(tpf.flux.value[0])\n assert lc_med.flux.value[0] == np.nanmedian(tpf.flux.value[0])\n assert lc_mean.flux.value[0] == np.nanmean(tpf.flux.value[0])\n\n\ndef test_animate():\n tpf = read(filename_tpf_one_center)\n tpf.animate()\n", "import pytest\n\nfrom astropy.io import fits\nimport numpy as np\nfrom numpy.testing import assert_array_equal\n\nfrom lightkurve import search_lightcurve\nfrom lightkurve.io.tasoc import read_tasoc_lightcurve\nfrom lightkurve.io.detect import detect_filetype\n\n\[email protected]_data\ndef test_detect_tasoc():\n \"\"\"Can we detect the correct format for TASOC files?\"\"\"\n url = \"https://mast.stsci.edu/api/v0.1/Download/file?uri=mast:HLSP/tasoc/s0001/ffi/0000/0004/1206/4070/hlsp_tasoc_tess_ffi_tic00412064070-s01-c1800_tess_v04_lc.fits\"\n f = fits.open(url)\n\n assert detect_filetype(f) == \"TASOC\"\n\n\[email protected]_data\ndef test_read_tasoc():\n \"\"\"Can we read TASOC files?\"\"\"\n url = \"https://mast.stsci.edu/api/v0.1/Download/file?uri=mast:HLSP/tasoc/s0001/ffi/0000/0004/1206/4070/hlsp_tasoc_tess_ffi_tic00412064070-s01-c1800_tess_v04_lc.fits\"\n with fits.open(url, mode=\"readonly\") as hdulist:\n fluxes = hdulist[1].data[\"FLUX_RAW\"]\n\n lc = read_tasoc_lightcurve(url, flux_column=\"FLUX_RAW\")\n\n flux_lc = lc.flux.value\n\n # print(flux_lc, fluxes)\n assert np.sum(fluxes) == np.sum(flux_lc)\n\n\[email protected]_data\ndef test_search_tasoc():\n \"\"\"Can we search and download a TASOC light curve?\"\"\"\n search = search_lightcurve(\"TIC 412064070\", author=\"TASOC\", sector=1)\n assert len(search) == 1\n assert search.table[\"author\"][0] == \"TASOC\"\n lc = search.download()\n assert type(lc).__name__ == \"TessLightCurve\"\n assert lc.sector == 1\n" ]
[ [ "numpy.testing.assert_array_equal", "numpy.array_equal" ], [ "numpy.nanmedian", "numpy.product", "numpy.abs", "numpy.isfinite", "numpy.isnan", "numpy.arange", "numpy.asarray", "numpy.ones", "numpy.all", "numpy.testing.assert_array_equal", "numpy.round", "numpy.nansum", "numpy.any", "matplotlib.pyplot.close", "numpy.nanmean", "numpy.array", "numpy.zeros", "numpy.isclose" ], [ "numpy.sum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
vpisarev/onnxruntime
[ "bab9b80f1f2330d3a115e0abbb4d8278c2be3f44" ]
[ "onnxruntime/python/tools/transformers/quantize_helper.py" ]
[ "# -------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n# --------------------------------------------------------------------------\n\nimport logging\nimport torch\nimport onnx\nimport os\nfrom transformers.modeling_utils import Conv1D\n\nlogger = logging.getLogger(__name__)\n\n\ndef _conv1d_to_linear(module):\n in_size, out_size = module.weight.shape\n linear = torch.nn.Linear(in_size, out_size)\n linear.weight.data = module.weight.data.T.contiguous()\n linear.bias.data = module.bias.data\n return linear\n\n\ndef conv1d_to_linear(model):\n '''in-place\n This is for Dynamic Quantization, as Conv1D is not recognized by PyTorch, convert it to nn.Linear\n '''\n logger.debug(\"replace Conv1D with Linear\")\n for name in list(model._modules):\n module = model._modules[name]\n if isinstance(module, Conv1D):\n linear = _conv1d_to_linear(module)\n model._modules[name] = linear\n else:\n conv1d_to_linear(module)\n\n\ndef _get_size_of_pytorch_model(model):\n torch.save(model.state_dict(), \"temp.p\")\n size = os.path.getsize(\"temp.p\") / (1024 * 1024)\n os.remove('temp.p')\n return size\n\n\nclass QuantizeHelper:\n @staticmethod\n def quantize_torch_model(model, dtype=torch.qint8):\n '''\n Usage: model = quantize_model(model)\n\n TODO: mix of in-place and return, but results are different\n '''\n conv1d_to_linear(model)\n quantized_model = torch.quantization.quantize_dynamic(model, {torch.nn.Linear}, dtype=dtype)\n logger.info(f'Size of full precision Torch model(MB):{_get_size_of_pytorch_model(model)}')\n logger.info(f'Size of quantized Torch model(MB):{_get_size_of_pytorch_model(quantized_model)}')\n return quantized_model\n\n @staticmethod\n def quantize_onnx_model(onnx_model_path, quantized_model_path, use_external_data_format=False):\n from onnxruntime.quantization import quantize_dynamic\n from pathlib import Path\n Path(quantized_model_path).parent.mkdir(parents=True, exist_ok=True)\n logger.info(f'Size of full precision ONNX model(MB):{os.path.getsize(onnx_model_path)/(1024*1024)}')\n quantize_dynamic(onnx_model_path,\n quantized_model_path,\n use_external_data_format = use_external_data_format)\n logger.info(f\"quantized model saved to:{quantized_model_path}\")\n #TODO: inlcude external data in total model size.\n logger.info(f'Size of quantized ONNX model(MB):{os.path.getsize(quantized_model_path)/(1024*1024)}')\n" ]
[ [ "torch.nn.Linear", "torch.quantization.quantize_dynamic" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
CryptoTheSuperDog/fds
[ "12795290f5784eb5d218a648aee4edbcfa890078", "12795290f5784eb5d218a648aee4edbcfa890078" ]
[ "assignments/assignment2/my_NB_hint.py", "assignments/assignment1/A1.py" ]
[ "import pandas as pd\nimport numpy as np\nfrom collections import Counter\n\nclass my_NB:\n\n def __init__(self, alpha=1):\n # alpha: smoothing factor\n # P(xi = t | y = c) = (N(t,c) + alpha) / (N(c) + n(i)*alpha)\n # where n(i) is the number of available categories (values) of feature i\n # Setting alpha = 1 is called Laplace smoothing\n self.alpha = alpha\n\n def fit(self, X, y):\n # X: pd.DataFrame, independent variables, str\n # y: list, np.array or pd.Series, dependent variables, int or str\n # list of classes for this model\n self.classes_ = list(set(list(y)))\n # for calculation of P(y)\n self.P_y = Counter(y)\n # self.P[yj][Xi][xi] = P(xi|yj) where Xi is the feature name and xi is the feature value, yj is a specific class label\n # make sure to use self.alpha in the __init__() function as the smoothing factor when calculating P(xi|yj)\n self.P = {}\n\n\n\n\n\n \n return\n\n def predict_proba(self, X):\n # X: pd.DataFrame, independent variables, str\n # prob is a dict of prediction probabilities belonging to each categories\n # return probs = pd.DataFrame(list of prob, columns = self.classes_)\n # P(yj|x) = P(x|yj)P(yj)/P(x)\n # P(x|yj) = P(x1|yj)P(x2|yj)...P(xk|yj) = self.P[yj][X1][x1]*self.P[yj][X2][x2]*...*self.P[yj][Xk][xk]\n probs = {}\n for label in self.classes_:\n p = self.P_y[label]\n for key in X:\n p *= X[key].apply(lambda value: self.P[label][key][value] if value in self.P[label][key] else 1)\n probs[label] = p\n probs = pd.DataFrame(probs, columns=self.classes_)\n sums = probs.sum(axis=1)\n probs = probs.apply(lambda v: v / sums)\n return probs\n\n def predict(self, X):\n # X: pd.DataFrame, independent variables, str\n # return predictions: list\n # Hint: predicted class is the class with highest prediction probability (from self.predict_proba)\n probs = self.predict_proba(X)\n predictions = \"Write your own code\"\n return predictions\n\n\n\n\n\n", "from sklearn.naive_bayes import GaussianNB\nimport pandas as pd\n\nif __name__ == \"__main__\":\n # Load training data\n data_train = pd.read_csv(\"../data/Iris_train.csv\")\n # Separate independent variables and dependent variables\n independent = [\"SepalLengthCm\",\t\"SepalWidthCm\",\t\"PetalLengthCm\",\t\"PetalWidthCm\"]\n X = data_train[independent]\n Y = data_train[\"Species\"]\n # Train model\n clf = GaussianNB()\n clf.fit(X,Y)\n # Load testing data\n data_test = pd.read_csv(\"../data/Iris_test.csv\")\n X_test = data_test[independent]\n # Predict\n predictions = clf.predict(X_test)\n # Predict probabilities\n probs = clf.predict_proba(X_test)\n # Print results\n for i,pred in enumerate(predictions):\n print(\"%s\\t%f\" %(pred,max(probs[i])))" ]
[ [ "pandas.DataFrame" ], [ "pandas.read_csv", "sklearn.naive_bayes.GaussianNB" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
laurentmackay/3d-vertex
[ "6d6e124ecfaca018d979c5ef17d0b83d1cc0f96c", "6d6e124ecfaca018d979c5ef17d0b83d1cc0f96c", "6d6e124ecfaca018d979c5ef17d0b83d1cc0f96c" ]
[ "Validation/Viscoelastic/PeriodicTimeseriesAnalysis.py", "VertexTissue/validate.py", "main_orig.py" ]
[ "import string\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom VertexTissue import globals as const\nfrom VertexTissue.Analysis import *\n\nfrom VertexTissue.funcs import euclidean_distance\n\nfrom periodic_2D import forces, omegas\n\n\nif __name__ == '__main__':\n\n square_length = lambda G, t : euclidean_distance(G.nodes[0]['pos'], G.nodes[2]['pos'])\n\n fig, axs = plt.subplots(2,int(np.ceil(len(omegas)*len(forces)/2)))\n fig.set_size_inches(12, 8)\n axs = axs.flatten()\n\n patterns=[]\n i=0\n\n ke=const.mu_apical\n kv = ke*60\n eta = const.eta\n kappa = eta + 2*kv\n\n alphabet_string = string.ascii_lowercase\n alphabet_list = list(alphabet_string)\n\n\n linewidth=3\n for f in forces:\n for omega in omegas:\n\n\n\n\n\n ax=axs[i]\n lbl = alphabet_list[i]\n i+=1\n\n arg = (kappa*ke/(omega*kv**2)+omega*eta/ke)/2\n delta = -np.arctan(arg)\n\n num = ke**2+(omega*kv)**2\n denom = (kappa*omega*ke)**2+(kv*eta*omega**2)**2\n\n\n denom2 = (kappa*ke)**3+kappa*ke*(omega*kv*eta)**2\n \n res = analyze_network_evolution(path='./data/viscoelastic/',\n pattern=f'periodic_force_{f}_freq_{omega}_*.pickle',\n func=square_length)\n\n res=np.array(res)\n t=res[:,0]\n ax.plot(t, res[:,1],linewidth=linewidth, label='numerical')\n A=f\n lam = 2*ke/eta + 1/60\n gamma = ke/eta * (2*A)\n B=(2.0/(lam*eta))*(0+gamma/lam)\n sol = (3.4+B)+gamma*(1/const.mu_apical-2.0/(const.eta*lam))*t - B*np.exp(-lam*t)\n\n \n\n num2 = -kv*2*A*omega*ke*eta*kv**2\n l_final = const.l_apical + 2*A/(2*omega*kv+omega*eta)\n l_trans = -2*np.exp(-lam*t)*(num2)/denom2\n amp = 2*A*np.sqrt(num/denom)\n sol = l_final+amp*np.sin(omega*t+delta) +l_trans\n\n\n ax.plot(t, sol, '--',linewidth=linewidth, label='theoretical')\n \n ax.set_xlabel('t (seconds)', fontsize=14)\n ax.set_ylabel('length', fontsize=14)\n ax.title.set_text(f'({lbl}) Force={f}, max error = {np.max(np.abs(sol-res[:,1])):.3e}')\n ax.title.set_fontsize(16)\n ax.legend(loc='right')\n\n \n \n \n\n\n\n\n\n\n \n plt.tight_layout()\n plt.show()", "import os\n\nimport networkx as nx\nimport numpy as np\n\n\n\n\n\n\n\ndef validate(n,attr='pos'): \n try:\n G=nx.read_gpickle(f't{n}.pickle')\n G1=nx.read_gpickle(f't_fast{n}.pickle')\n\n vals = nx.get_node_attributes(G,attr)\n vals1 = nx.get_node_attributes(G1,attr)\n\n max_diff = np.max([np.max(np.abs(v-v1)) for v,v1 in zip(vals.values(),vals1.values()) ])\n print(f'{n}: {max_diff}')\n\n\n return True\n except:\n return False\n\n\nfor i in range(300):\n cont= validate(i)\n if not cont:\n break", "import networkx as nx\nimport numpy as np\nimport itertools\nfrom scipy.spatial import distance\nimport matplotlib\nmatplotlib.use('agg')\nimport matplotlib.pyplot as plt\nimport csv\nimport pdb\nimport globals as const\nfrom funcs_orig import *\nfrom math import isclose\nfrom pyqt_viz import edge_viewer\nimport time\n\n# Constants for simulation\ndt = const.dt\n#var_dt = True\n\n# dimensions of the cell \nl_apical = const.l_apical \nl_depth = const.l_depth \n\n# Set the arcs list\ninner_arc = const.inner_arc\nouter_arc = const.outer_arc\n\n# mechanical parameters\n# rest lengths of the passively elastic apical, basal and cell walls\nl0_apical = l_apical\nl0_basal = l_apical \nl0_wall = l_depth \n\nmu_apical = const.mu_apical \nmu_basal = const.mu_basal \nmu_wall = const.mu_wall \nmyo_beta = const.myo_beta \neta = const.eta \npress_alpha = const.press_alpha \nl_mvmt = const.l_mvmt\n\n# initialize the tissue\nG, K, centers, num_api_nodes, circum_sorted, belt, triangles = tissue_3d()\npit_centers = const.pit_centers \n\n# Starting from t=0\nt = 0\nnum_inter = 0 \nblacklist = [] \ncontract = [True for counter in range(0,num_inter)]\n#inter_edges = [[301,302],[295,296],[292,293],[298,299],[45,46],[39,40],[272,273],[174,175],[180,181],[276,277],[183,184],[177,178],[112,113],[286,287],[289,290],[115,116],[109,110],[283,284],[280,281],[106,107]] \n# Starting from t=? after intercalations occur\n#t = 1640 \n#num_inter = 20 \n#blacklist = [[301,302],[295,296],[292,293],[298,299],[45,46],[39,40],[272,273],[174,175],[180,181],[276,277],[183,184],[177,178],[112,113],[286,287],[289,290],[115,116],[109,110],[283,284],[280,281],[106,107]] \n#contract = [False for counter in range(0,num_inter)]\n#G = nx.read_gpickle('/home/cdurney/3d-vertex/concentric/t1640.pickle')\n#\n#for counter in range(0,num_inter): \n# node = blacklist[counter][0]\n# neighbor = blacklist[counter][1]\n# print(node, neighbor) \n# cents = list(set(K.neighbors(node)) & set(K.neighbors(neighbor)))\n# ii = list((set(list(K.neighbors(node))) & set(list(centers))) - (set(list(K.neighbors(node))) & set(list(K.neighbors(neighbor)))))[0]\n# jj = list((set(list(K.neighbors(neighbor))) & set(list(centers))) - (set(list(K.neighbors(node))) & set(list(K.neighbors(neighbor)))))[0]\n# temp1 = list(set(K.neighbors(node)) & set(K.neighbors(cents[0])))\n# temp1.remove(neighbor)\n# temp2 = list(set(K.neighbors(neighbor)) & set(K.neighbors(cents[1])))\n# temp2.remove(node)\n# circum_sorted, triangles, K = new_topology(K,[node, neighbor], cents, temp1, temp2, ii, jj, belt, centers, num_api_nodes)\n#\n\n# t=initial nx Graph in pickled form for plotting later\nprint(t) \nfile_name = 't' + str(int(t)) \nnx.write_gpickle(G,file_name + '.pickle')\nnp.save(file_name,circum_sorted) \n\nviewer = edge_viewer(G,attr='myosin')\n\nt_plot=5\nt_last=-t_plot\nwhile t <= const.t_final:\n \n if t == const.t_1:\n for i in range(0,len(inner_arc)):\n G[inner_arc[i-1]][inner_arc[i]]['myosin'] = const.belt_strength \n print(\"Inner arc established\")\n\n # update myosin on outer arc \n if t == const.t_2:\n for i in range(0,len(outer_arc)):\n G[outer_arc[i-1]][outer_arc[i]]['myosin'] = const.belt_strength \n print(\"Outer arc established\")\n\n # update myosin on belt\n if t == const.t_belt:\n for i in range(0,len(belt)):\n G[belt[i-1]][belt[i]]['myosin'] = const.belt_strength \n print(\"Belt established\") \n\n if t-t_last>=t_plot:\n viewer(G)\n # increment t by dt\n # initialize force_dict back to zeros\n t = round(t+dt,1)\n print(dt, t) \n pos = nx.get_node_attributes(G,'pos')\n force_dict = {new_list: np.zeros(3,dtype=float) for new_list in G.nodes()} \n \n # pre-calculate magnitude of pressure\n # index of list corresponds to index of centers list\n PI = np.zeros(len(centers),dtype=float) \n # eventually move to classes?\n for n in range(0,len(centers)):\n # get nodes for volume\n pts = get_points(G,centers[n],pos) \n # calculate volume\n vol = convex_hull_volume_bis(pts) \n # calculate pressure\n PI[n] = -press_alpha*(vol-const.v_0) \n\n# # Update myosin on a fictitious pit (no resemblance to SG geometry)\n# if t < const.t_pit: \n# myo = const.pit_strength*t\n# for node in pit_centers: \n# if node == 0:\n# myo = 1.5*myo\n# for neighbor in G.neighbors(node): \n# G[node][neighbor]['myosin'] = myo\n\n# if t > const.t_intercalate:\n# if contract[0] == True:\n# G[301][302]['myosin'] = const.belt_strength*(t-const.t_intercalate) \n \n # update myosin on inner arc \n \n\n for node in G.nodes(): \n # update force on each node \n force = [0.0,0.0,0.0]\n \n # Elastic forces due to the cytoskeleton \n for neighbor in G.neighbors(node):\n a = pos[node]\n b = pos[neighbor]\n \n dist = distance.euclidean(a,b)\n direction = unit_vector(a,b)\n \n magnitude = elastic_force(dist, G[node][neighbor]['l_rest'], mu_apical) \n force = np.sum([force,magnitude*np.array(direction)],axis=0)\n \n # Force due to myosin\n magnitude = myo_beta*G[node][neighbor]['myosin']\n force = np.sum([force, magnitude*np.array(direction)],axis=0)\n\n force_dict[node] = np.add(force_dict[node], force) \n \n for center in centers:\n index = centers.index(center)\n pts = circum_sorted[index]\n centroid = np.array([pos[center], pos[center+1000]])\n centroid = np.average(centroid,axis=0)\n \n # pressure for: \n # apical nodes \n for i in range(0,len(circum_sorted[index])):\n area, extra = be_area([center,pts[i],pts[i-1]],[center,pts[i],pts[i-1]],pos) \n magnitude = PI[index]*area[0]*(1/3)\n \n direction = area[1]/np.linalg.norm(area[1]) \n force = magnitude*direction\n force_dict[center] = np.add(force_dict[center],force)\n force_dict[pts[i-1]] = np.add(force_dict[pts[i-1]],force)\n force_dict[pts[i]] = np.add(force_dict[pts[i]],force)\n \n # pressure for: \n # basal nodes\n area, extra = be_area([center+1000,pts[i-1]+1000,pts[i]+1000],[center+1000,pts[i-1]+1000,pts[i]+1000],pos) \n magnitude = PI[index]*area[0]*(1/3)\n direction = area[1]/np.linalg.norm(area[1]) \n force = magnitude*direction\n force_dict[center+1000] = np.add(force_dict[center+1000],force)\n force_dict[pts[i-1]+1000] = np.add(force_dict[pts[i-1]+1000],force)\n force_dict[pts[i]+1000] = np.add(force_dict[pts[i]+1000],force)\n\n # pressure for side panels\n # loop through each cell\n for index in range(0,len(circum_sorted)):\n cell_nodes = circum_sorted[index]\n centroid = np.array([pos[centers[index]], pos[centers[index]+1000]])\n centroid = np.average(centroid, axis=0)\n # loop through the 6 faces (or 5 or 7 after intercalation)\n for i in range(0, len(cell_nodes)):\n pts_id = np.array([cell_nodes[i-1], cell_nodes[i], cell_nodes[i]+1000, cell_nodes[i-1]+1000])\n pts_pos = np.array([pos[pts_id[ii]] for ii in range(0,4)])\n # on each face, calculate the center\n center = np.average(pts_pos,axis=0)\n # loop through the 4 triangles that make the face\n for ii in range(0,4):\n pos_side = [center, pts_pos[ii-1], pts_pos[ii]] \n area = area_side(pos_side) \n magnitude = PI[index]*area[0]*(1/2)\n \n direction = area[1]/np.linalg.norm(area[1]) \n force = magnitude*direction\n force_dict[pts_id[ii-1]] = np.add(force_dict[pts_id[ii-1]],force)\n force_dict[pts_id[ii]] = np.add(force_dict[pts_id[ii]],force)\n \n # Implement bending energy\n # Loop through all alpha, beta pairs of triangles\n for pair in triangles:\n alpha, beta = pair[0], pair[1]\n \n # Apical faces, calculate areas and cross-products \n A_alpha, A_beta = be_area(alpha, beta, pos)\n \n for node in alpha:\n inda = alpha.index(node) \n nbhrs_alpha = (alpha[(inda+1)%3], alpha[(inda-1)%3]) \n if node in beta:\n indb = beta.index(node) \n nbhrs_beta = (beta[(indb+1)%3], beta[(indb-1)%3]) \n frce = const.c_ab*bending_energy(nbhrs_alpha, nbhrs_beta, A_alpha, A_beta, pos)\n else:\n frce = const.c_ab*bending_energy(nbhrs_alpha, False, A_alpha, A_beta, pos)\n\t\t\n force_dict[node] = np.add(force_dict[node],frce)\n\n for node in beta:\n # don't double count the shared nodes\n indb = beta.index(node) \n nbhrs_beta = (beta[(indb+1)%3], beta[(indb-1)%3]) \n if node not in alpha:\n frce = const.c_ab*bending_energy(False, nbhrs_beta, A_alpha, A_beta, pos)\n else:\t\t\t\n frce = const.c_ab*np.array([0.,0.,0.])\n \n force_dict[node] = np.add(force_dict[node],frce)\n\n # Basal faces\n alpha = [alpha[0]+1000, alpha[1]+1000, alpha[2]+1000] \n beta = [beta[0]+1000, beta[1]+1000, beta[2]+1000] \n\n A_alpha, A_beta = be_area(alpha, beta, pos)\n \n for node in alpha:\n inda = alpha.index(node) \n nbhrs_alpha = (alpha[(inda+1)%3], alpha[(inda-1)%3]) \n if node in beta:\n indb = beta.index(node) \n nbhrs_beta = (beta[(indb+1)%3], beta[(indb-1)%3]) \n frce = const.c_ab*bending_energy(nbhrs_alpha, nbhrs_beta, A_alpha, A_beta, pos)\n else:\n frce = const.c_ab*bending_energy(nbhrs_alpha, False, A_alpha, A_beta, pos)\n\t\t\n force_dict[node] = np.add(force_dict[node],frce)\n\n for node in beta:\n # don't double count the shared nodes\n indb = beta.index(node) \n nbhrs_beta = (beta[(indb+1)%3], beta[(indb-1)%3]) \n if node not in alpha:\n frce = const.c_ab*bending_energy(False, nbhrs_beta, A_alpha, A_beta, pos)\n else:\t\t\t\n frce = np.array([0.,0.,0.])\n \n force_dict[node] = np.add(force_dict[node],frce)\n\n # update location of node \n pos = nx.get_node_attributes(G,'pos')\n \n for node in force_dict:\n G.node[node]['pos'] = d_pos(pos[node],force_dict[node],dt)\n\n ## Check for intercalation events\n pos = nx.get_node_attributes(G,'pos')\n for node in range(0,num_api_nodes):\n if node not in belt: \n for neighbor in G.neighbors(node):\n if (neighbor < 1000) and (neighbor not in belt) and (node not in centers) and (neighbor not in centers) and ([min(node, neighbor), max(node, neighbor)] not in blacklist): \n \n a = pos[node]\n b = pos[neighbor]\n c = pos[node+1000]\n d = pos[neighbor+1000]\n \n dist = distance.euclidean(a,b)\n \n if (dist < const.l_intercalation): \n if (np.random.rand(1)[0] < 1.):\n print(\"Intercalation event between nodes\", node, \"and\", neighbor, \"at t = \", t) \n # collapse nodes to same position \n # apical \n avg_loc = (np.array(a) + np.array(b)) / 2.0 \n a = avg_loc \n b = avg_loc \n # basal \n avg_loc = (np.array(c) + np.array(d)) / 2.0 \n c = avg_loc \n d = avg_loc \n # move nodes toward new center \n # apical \n cents = list(set(G.neighbors(node)) & set(G.neighbors(neighbor)))\n mvmt = unit_vector(a,pos[cents[1]])\n a = [a[0]+l_mvmt*mvmt[0], a[1]+l_mvmt*mvmt[1], a[2]+l_mvmt*mvmt[2]]\n G.node[node]['pos'] = a \n mvmt = unit_vector(b,pos[cents[0]])\n b = [b[0]+l_mvmt*mvmt[0], b[1]+l_mvmt*mvmt[1], b[2]+l_mvmt*mvmt[2]]\n G.node[neighbor]['pos'] = b \n # basal \n #cents = list(set(G.neighbors(node+1000)) & set(G.neighbors(neighbor+1000)))\n mvmt = unit_vector(c,pos[cents[1]+1000])\n c = [c[0]+l_mvmt*mvmt[0], c[1]+l_mvmt*mvmt[1], c[2]+l_mvmt*mvmt[2]]\n G.node[node+1000]['pos'] = c \n mvmt = unit_vector(d,pos[cents[0]+1000])\n d = [d[0]+l_mvmt*mvmt[0], d[1]+l_mvmt*mvmt[1], d[2]+l_mvmt*mvmt[2]]\n G.node[neighbor+1000]['pos'] = d \n \n ii = list((set(list(G.neighbors(node))) & set(list(centers))) - (set(list(G.neighbors(node))) & set(list(G.neighbors(neighbor)))))[0]\n jj = list((set(list(G.neighbors(neighbor))) & set(list(centers))) - (set(list(G.neighbors(node))) & set(list(G.neighbors(neighbor)))))[0]\n temp1 = list(set(G.neighbors(node)) & set(G.neighbors(cents[0])))\n temp1.remove(neighbor)\n temp2 = list(set(G.neighbors(neighbor)) & set(G.neighbors(cents[1])))\n temp2.remove(node)\n\n # sever connections\n # apical \n G.remove_edge(node,cents[0])\n G.remove_edge(node,temp1[0])\n G.remove_edge(neighbor,cents[1])\n G.remove_edge(neighbor,temp2[0])\n # basal \n G.remove_edge(node+1000,cents[0]+1000)\n G.remove_edge(node+1000,temp1[0]+1000)\n G.remove_edge(neighbor+1000,cents[1]+1000)\n G.remove_edge(neighbor+1000,temp2[0]+1000)\n\n # add new connections\n # apical \n # new edges \n G.add_edge(node,temp2[0],l_rest = const.l_apical, myosin=0,color='#808080')\n G.add_edge(neighbor,temp1[0],l_rest = const.l_apical, myosin=0,color='#808080')\n # new spokes \n G.add_edge(neighbor,ii,l_rest = const.l_apical, myosin=0)\n G.add_edge(node,jj,l_rest = const.l_apical, myosin=0)\n # basal \n # new edges \n G.add_edge(node+1000,temp2[0]+1000,l_rest = const.l_apical, myosin=0,color='#808080')\n G.add_edge(neighbor+1000,temp1[0]+1000,l_rest = const.l_apical, myosin=0,color='#808080')\n # new spokes \n G.add_edge(neighbor+1000,ii+1000,l_rest = const.l_apical, myosin=0)\n G.add_edge(node+1000,jj+1000,l_rest = const.l_apical, myosin=0)\n \n # reset myosin on contracted edge\n G[node][neighbor]['myosin'] = 0\n G[node+1000][neighbor+1000]['myosin'] = 0\n \n blacklist.append([min(node, neighbor), max(node, neighbor)])\n \n circum_sorted, triangles, K = new_topology(K,[node, neighbor], cents, temp1, temp2, ii, jj, belt, centers, num_api_nodes)\n \n if min(node,neighbor) == 301:\n contract[0] = False\n\n# #set dt for next loop \n# if var_dt == True:\n# if any(contract) == True:\n# # if any edges are still contracting, check for threshold length \n# for i in range(0,num_inter):\n# # calculate lengths of those that are still True \n# if contract[i] == True:\n# a = inter_edges[i][0]\n# b = inter_edges[i][1]\n# if distance.euclidean(pos[a],pos[b]) < 0.2:\n# dt = 0.1\n# break \n# else: \n# if isclose(t % 1, 0) == False: \n# dt = 0.1 \n# else:\n# dt = const.dt\n# var_dt = False \n# else:\n# dt = const.dt\n\n# Save nx Graph in pickled form for plotting later\n \n if t % 1 == 0: \n file_name = 't' + str(round(t)) \n nx.write_gpickle(G,file_name + '.pickle')\n np.save(file_name,circum_sorted)\n" ]
[ [ "matplotlib.pyplot.tight_layout", "numpy.sqrt", "numpy.arctan", "numpy.abs", "numpy.sin", "numpy.exp", "numpy.array", "matplotlib.pyplot.show" ], [ "numpy.abs" ], [ "matplotlib.use", "numpy.linalg.norm", "numpy.save", "scipy.spatial.distance.euclidean", "numpy.random.rand", "numpy.average", "numpy.add", "numpy.array", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "1.6", "0.14", "1.10", "0.15", "1.4", "0.16", "1.9", "0.19", "1.5", "0.18", "1.2", "1.7", "0.12", "1.0", "0.17", "1.3", "1.8" ], "tensorflow": [] } ]
harunpehlivan/tensorflow
[ "d87a9fbbc5f49ec5ae8eb52c62628f0b1a0bf67f", "d87a9fbbc5f49ec5ae8eb52c62628f0b1a0bf67f", "d87a9fbbc5f49ec5ae8eb52c62628f0b1a0bf67f", "d87a9fbbc5f49ec5ae8eb52c62628f0b1a0bf67f", "d87a9fbbc5f49ec5ae8eb52c62628f0b1a0bf67f", "376e2cfdab31f4da251ea2e50992a9bf97fd171b", "d87a9fbbc5f49ec5ae8eb52c62628f0b1a0bf67f", "376e2cfdab31f4da251ea2e50992a9bf97fd171b", "d87a9fbbc5f49ec5ae8eb52c62628f0b1a0bf67f", "d87a9fbbc5f49ec5ae8eb52c62628f0b1a0bf67f" ]
[ "tensorflow/contrib/factorization/python/ops/gmm.py", "tensorflow/contrib/py2tf/__init__.py", "tensorflow/python/keras/_impl/keras/datasets/cifar10.py", "tensorflow/contrib/tpu/profiler/pip_package/cloud_tpu_profiler/main.py", "tensorflow/python/kernel_tests/constant_op_test.py", "tensorflow/python/ops/nn_fused_batchnorm_test.py", "tensorflow/python/training/adam_test.py", "tensorflow/python/lib/core/bfloat16_test.py", "tensorflow/contrib/data/python/kernel_tests/reader_dataset_ops_test.py", "tensorflow/python/keras/_impl/keras/layers/convolutional.py" ]
[ "# Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Implementation of Gaussian mixture model (GMM) clustering using tf.Learn.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport time\nimport numpy as np\n\nfrom tensorflow.contrib import framework\nfrom tensorflow.contrib.factorization.python.ops import gmm_ops\nfrom tensorflow.contrib.framework.python.framework import checkpoint_utils\nfrom tensorflow.python.training import training_util\nfrom tensorflow.contrib.learn.python.learn.estimators import estimator\nfrom tensorflow.contrib.learn.python.learn.estimators import model_fn as model_fn_lib\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import logging_ops as logging\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import state_ops\nfrom tensorflow.python.ops.control_flow_ops import with_dependencies\nfrom tensorflow.python.training import session_run_hook\n\n\ndef _streaming_sum(scalar_tensor):\n \"\"\"Create a sum metric and update op.\"\"\"\n sum_metric = framework.local_variable(constant_op.constant(0.0))\n sum_update = sum_metric.assign_add(scalar_tensor)\n return sum_metric, sum_update\n\n\nclass _InitializeClustersHook(session_run_hook.SessionRunHook):\n \"\"\"Initializes clusters or waits for cluster initialization.\"\"\"\n\n def __init__(self, init_op, is_initialized_op, is_chief):\n self._init_op = init_op\n self._is_chief = is_chief\n self._is_initialized_op = is_initialized_op\n\n def after_create_session(self, session, _):\n assert self._init_op.graph == ops.get_default_graph()\n assert self._is_initialized_op.graph == self._init_op.graph\n while True:\n try:\n if session.run(self._is_initialized_op):\n break\n elif self._is_chief:\n session.run(self._init_op)\n else:\n time.sleep(1)\n except RuntimeError as e:\n logging.info(e)\n\n\nclass GMM(estimator.Estimator):\n \"\"\"An estimator for GMM clustering.\"\"\"\n SCORES = 'scores'\n ASSIGNMENTS = 'assignments'\n ALL_SCORES = 'all_scores'\n\n def __init__(self,\n num_clusters,\n model_dir=None,\n random_seed=0,\n params='wmc',\n initial_clusters='random',\n covariance_type='full',\n config=None):\n \"\"\"Creates a model for running GMM training and inference.\n\n Args:\n num_clusters: number of clusters to train.\n model_dir: the directory to save the model results and log files.\n random_seed: Python integer. Seed for PRNG used to initialize centers.\n params: Controls which parameters are updated in the training process.\n Can contain any combination of \"w\" for weights, \"m\" for means,\n and \"c\" for covars.\n initial_clusters: specifies how to initialize the clusters for training.\n See gmm_ops.gmm for the possible values.\n covariance_type: one of \"full\", \"diag\".\n config: See Estimator\n \"\"\"\n self._num_clusters = num_clusters\n self._params = params\n self._training_initial_clusters = initial_clusters\n self._covariance_type = covariance_type\n self._training_graph = None\n self._random_seed = random_seed\n super(GMM, self).__init__(\n model_fn=self._model_builder(), model_dir=model_dir, config=config)\n\n def predict_assignments(self, input_fn=None, batch_size=None, outputs=None):\n \"\"\"See BaseEstimator.predict.\"\"\"\n results = self.predict(input_fn=input_fn,\n batch_size=batch_size,\n outputs=outputs)\n for result in results:\n yield result[GMM.ASSIGNMENTS]\n\n def score(self, input_fn=None, batch_size=None, steps=None):\n \"\"\"Predict total sum of distances to nearest clusters.\n\n Note that this function is different from the corresponding one in sklearn\n which returns the negative of the sum of distances.\n\n Args:\n input_fn: see predict.\n batch_size: see predict.\n steps: see predict.\n\n Returns:\n Total sum of distances to nearest clusters.\n \"\"\"\n results = self.evaluate(input_fn=input_fn, batch_size=batch_size,\n steps=steps)\n return np.sum(results[GMM.SCORES])\n\n def weights(self):\n \"\"\"Returns the cluster weights.\"\"\"\n return checkpoint_utils.load_variable(\n self.model_dir, gmm_ops.GmmAlgorithm.CLUSTERS_WEIGHT)\n\n def clusters(self):\n \"\"\"Returns cluster centers.\"\"\"\n clusters = checkpoint_utils.load_variable(\n self.model_dir, gmm_ops.GmmAlgorithm.CLUSTERS_VARIABLE)\n return np.squeeze(clusters, 1)\n\n def covariances(self):\n \"\"\"Returns the covariances.\"\"\"\n return checkpoint_utils.load_variable(\n self.model_dir, gmm_ops.GmmAlgorithm.CLUSTERS_COVS_VARIABLE)\n\n def _parse_tensor_or_dict(self, features):\n if isinstance(features, dict):\n return array_ops.concat([features[k] for k in sorted(features.keys())],\n 1)\n return features\n\n def _model_builder(self):\n \"\"\"Creates a model function.\"\"\"\n\n def _model_fn(features, labels, mode, config):\n \"\"\"Model function.\"\"\"\n assert labels is None, labels\n (all_scores,\n model_predictions,\n losses, training_op,\n init_op,\n is_initialized) = gmm_ops.gmm(self._parse_tensor_or_dict(features),\n self._training_initial_clusters,\n self._num_clusters, self._random_seed,\n self._covariance_type,\n self._params)\n incr_step = state_ops.assign_add(training_util.get_global_step(), 1)\n loss = math_ops.reduce_sum(losses)\n training_op = with_dependencies([training_op, incr_step], loss)\n training_hooks = [_InitializeClustersHook(\n init_op, is_initialized, config.is_chief)]\n predictions = {\n GMM.ALL_SCORES: all_scores[0],\n GMM.ASSIGNMENTS: model_predictions[0][0],\n }\n eval_metric_ops = {\n GMM.SCORES: _streaming_sum(loss),\n }\n return model_fn_lib.ModelFnOps(mode=mode, predictions=predictions,\n eval_metric_ops=eval_metric_ops,\n loss=loss, train_op=training_op,\n training_hooks=training_hooks)\n\n return _model_fn\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\"\"\"Py2TF compiles Python code into equivalent TensorFlow code.\n\nEquivalent here means that they have the same effect when executed.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.python.util.all_util import remove_undocumented\n\n\n_allowed_symbols = []\n\nremove_undocumented(__name__, _allowed_symbols)\n", "# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"CIFAR10 small image classification dataset.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\n\nimport numpy as np\n\nfrom tensorflow.python.keras._impl.keras import backend as K\nfrom tensorflow.python.keras._impl.keras.datasets.cifar import load_batch\nfrom tensorflow.python.keras._impl.keras.utils.data_utils import get_file\n\n\ndef load_data():\n \"\"\"Loads CIFAR10 dataset.\n\n Returns:\n Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`.\n \"\"\"\n dirname = 'cifar-10-batches-py'\n origin = 'https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz'\n path = get_file(dirname, origin=origin, untar=True)\n\n num_train_samples = 50000\n\n x_train = np.empty((num_train_samples, 3, 32, 32), dtype='uint8')\n y_train = np.empty((num_train_samples,), dtype='uint8')\n\n for i in range(1, 6):\n fpath = os.path.join(path, 'data_batch_' + str(i))\n (x_train[(i - 1) * 10000:i * 10000, :, :, :],\n y_train[(i - 1) * 10000:i * 10000]) = load_batch(fpath)\n\n fpath = os.path.join(path, 'test_batch')\n x_test, y_test = load_batch(fpath)\n\n y_train = np.reshape(y_train, (len(y_train), 1))\n y_test = np.reshape(y_test, (len(y_test), 1))\n\n if K.image_data_format() == 'channels_last':\n x_train = x_train.transpose(0, 2, 3, 1)\n x_test = x_test.transpose(0, 2, 3, 1)\n\n return (x_train, y_train), (x_test, y_test)\n", "# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# =============================================================================\n\"\"\"Wraps capture_tpu_profile binary.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport subprocess\nimport sys\n\nimport tensorflow as tf\n\ntf.flags.DEFINE_string('service_addr', '',\n 'Address of TPU profiler service e.g. localhost:8466')\ntf.flags.DEFINE_string('logdir', '',\n 'Path of TensorBoard log directory e.g. /tmp/tb_log')\ntf.flags.DEFINE_integer('duration_ms', 2000, 'Duration of tracing in ms.')\n\nFLAGS = tf.flags.FLAGS\nEXECUTABLE = 'data/capture_tpu_profile'\n\n\ndef run_main():\n tf.app.run(main)\n\n\ndef main(unused_argv=None):\n if not FLAGS.service_addr or not FLAGS.logdir:\n sys.exit('service_addr and logdir must be provided.')\n executable_path = os.path.join(os.path.dirname(__file__), EXECUTABLE)\n cmd = [executable_path]\n cmd.append('--logdir='+FLAGS.logdir)\n cmd.append('--service_addr='+FLAGS.service_addr)\n cmd.append('--duration_ms='+str(FLAGS.duration_ms))\n subprocess.call(cmd)\n\n\nif __name__ == '__main__':\n run_main()\n", "# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for ConstantOp.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom google.protobuf import text_format\n\nfrom tensorflow.core.framework import graph_pb2\nfrom tensorflow.core.framework import tensor_pb2\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes as dtypes_lib\nfrom tensorflow.python.framework import errors_impl\nfrom tensorflow.python.framework import importer\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import gradient_checker\nfrom tensorflow.python.ops import logging_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.platform import test\nfrom tensorflow.python.util import compat\n\n\nclass ConstantTest(test.TestCase):\n\n def _testCpu(self, x):\n np_ans = np.array(x)\n with self.test_session(use_gpu=False):\n tf_ans = ops.convert_to_tensor(x).eval()\n dtype = dtypes_lib.as_dtype(np_ans.dtype)\n if dtype.is_floating or dtype.is_complex:\n self.assertAllClose(np_ans, tf_ans)\n else:\n self.assertAllEqual(np_ans, tf_ans)\n\n def _testGpu(self, x):\n np_ans = np.array(x)\n with self.test_session(use_gpu=True):\n tf_ans = ops.convert_to_tensor(x).eval()\n dtype = dtypes_lib.as_dtype(np_ans.dtype)\n if dtype.is_floating or dtype.is_complex:\n self.assertAllClose(np_ans, tf_ans)\n else:\n self.assertAllEqual(np_ans, tf_ans)\n\n def _testAll(self, x):\n self._testCpu(x)\n self._testGpu(x)\n\n def testBFloat16(self):\n bfloat16 = dtypes_lib.bfloat16.as_numpy_dtype\n self._testAll(np.arange(-15, 15).reshape([2, 3, 5]).astype(bfloat16))\n self._testAll(\n np.random.normal(size=30).reshape([2, 3, 5]).astype(bfloat16))\n self._testAll(np.empty((2, 0, 5)).astype(bfloat16))\n\n def testHalf(self):\n self._testAll(np.arange(-15, 15).reshape([2, 3, 5]).astype(np.float16))\n self._testAll(\n np.random.normal(size=30).reshape([2, 3, 5]).astype(np.float16))\n self._testAll(np.empty((2, 0, 5)).astype(np.float16))\n\n def testFloat(self):\n self._testAll(np.arange(-15, 15).reshape([2, 3, 5]).astype(np.float32))\n self._testAll(\n np.random.normal(size=30).reshape([2, 3, 5]).astype(np.float32))\n self._testAll(np.empty((2, 0, 5)).astype(np.float32))\n\n def testDouble(self):\n self._testAll(np.arange(-15, 15).reshape([2, 3, 5]).astype(np.float64))\n self._testAll(\n np.random.normal(size=30).reshape([2, 3, 5]).astype(np.float64))\n self._testAll(np.empty((2, 0, 5)).astype(np.float64))\n\n def testInt32(self):\n self._testAll(np.arange(-15, 15).reshape([2, 3, 5]).astype(np.int32))\n self._testAll((100 * np.random.normal(size=30)).reshape([2, 3, 5]).astype(\n np.int32))\n self._testAll(np.empty((2, 0, 5)).astype(np.int32))\n\n def testInt64(self):\n self._testAll(np.arange(-15, 15).reshape([2, 3, 5]).astype(np.int64))\n self._testAll((100 * np.random.normal(size=30)).reshape([2, 3, 5]).astype(\n np.int64))\n self._testAll(np.empty((2, 0, 5)).astype(np.int64))\n\n def testComplex64(self):\n self._testAll(\n np.complex(1, 2) *\n np.arange(-15, 15).reshape([2, 3, 5]).astype(np.complex64))\n self._testAll(\n np.complex(1, 2) *\n np.random.normal(size=30).reshape([2, 3, 5]).astype(np.complex64))\n self._testAll(np.empty((2, 0, 5)).astype(np.complex64))\n\n def testComplex128(self):\n self._testAll(\n np.complex(1, 2) *\n np.arange(-15, 15).reshape([2, 3, 5]).astype(np.complex128))\n self._testAll(\n np.complex(1, 2) *\n np.random.normal(size=30).reshape([2, 3, 5]).astype(np.complex128))\n self._testAll(np.empty((2, 0, 5)).astype(np.complex128))\n\n def testString(self):\n self._testCpu(\n np.array([compat.as_bytes(str(x)) for x in np.arange(-15, 15)]).reshape(\n [2, 3, 5]))\n self._testCpu(np.empty((2, 0, 5)).astype(np.str_))\n\n def testVariant(self):\n # TODO(ebrevdo): Re-enable use_gpu=True once non-DMA Variant\n # copying between CPU and GPU is supported.\n with self.test_session(use_gpu=False):\n variant_tensor = tensor_pb2.TensorProto(\n dtype=dtypes_lib.variant.as_datatype_enum,\n tensor_shape=tensor_shape.TensorShape([]).as_proto(),\n variant_val=[\n tensor_pb2.VariantTensorDataProto(\n # Match registration in variant_op_registry.cc\n type_name=b\"int\",\n metadata=np.array(1, dtype=np.int32).tobytes())\n ])\n const = constant_op.constant(variant_tensor)\n const_value = const.op.get_attr(\"value\")\n\n # Ensure we stored the tensor proto properly.\n self.assertProtoEquals(variant_tensor, const_value)\n\n # Smoke test -- ensure this executes without trouble.\n # Right now, non-numpy-compatible objects cannot be returned from a\n # session.run call; similarly, objects that can't be converted to\n # native numpy types cannot be passed to ops.convert_to_tensor.\n # TODO(ebrevdo): Add registration mechanism for\n # ops.convert_to_tensor and for session.run output.\n logging_const_op = logging_ops.Print(\n const, [const],\n message=\"Variant storing an int, decoded const value:\").op\n logging_const_op.run()\n\n def testStringWithNulls(self):\n with self.test_session():\n val = ops.convert_to_tensor(b\"\\0\\0\\0\\0\").eval()\n self.assertEqual(len(val), 4)\n self.assertEqual(val, b\"\\0\\0\\0\\0\")\n\n with self.test_session():\n val = ops.convert_to_tensor(b\"xx\\0xx\").eval()\n self.assertEqual(len(val), 5)\n self.assertAllEqual(val, b\"xx\\0xx\")\n nested = [[b\"\\0\\0\\0\\0\", b\"xx\\0xx\"], [b\"\\0_\\0_\\0_\\0\", b\"\\0\"]]\n\n with self.test_session():\n val = ops.convert_to_tensor(nested).eval()\n # NOTE(mrry): Do not use assertAllEqual, because it converts nested to a\n # numpy array, which loses the null terminators.\n self.assertEqual(val.tolist(), nested)\n\n def testExplicitShapeNumPy(self):\n with ops.Graph().as_default():\n c = constant_op.constant(\n np.arange(-15, 15).reshape([2, 3, 5]).astype(np.float32),\n shape=[2, 3, 5])\n self.assertEqual(c.get_shape(), [2, 3, 5])\n\n def testImplicitShapeNumPy(self):\n with ops.Graph().as_default():\n c = constant_op.constant(\n np.arange(-15, 15).reshape([2, 3, 5]).astype(np.float32))\n self.assertEqual(c.get_shape(), [2, 3, 5])\n\n def testExplicitShapeList(self):\n with ops.Graph().as_default():\n c = constant_op.constant([1, 2, 3, 4, 5, 6, 7], shape=[7])\n self.assertEqual(c.get_shape(), [7])\n\n def testImplicitShapeList(self):\n with ops.Graph().as_default():\n c = constant_op.constant([1, 2, 3, 4, 5, 6, 7])\n self.assertEqual(c.get_shape(), [7])\n\n def testExplicitShapeNumber(self):\n with ops.Graph().as_default():\n c = constant_op.constant(1, shape=[1])\n self.assertEqual(c.get_shape(), [1])\n\n def testImplicitShapeNumber(self):\n with ops.Graph().as_default():\n c = constant_op.constant(1)\n self.assertEqual(c.get_shape(), [])\n\n def testShapeInconsistent(self):\n with ops.Graph().as_default():\n c = constant_op.constant([1, 2, 3, 4, 5, 6, 7], shape=[10])\n self.assertEqual(c.get_shape(), [10])\n\n # pylint: disable=g-long-lambda\n def testShapeWrong(self):\n with ops.Graph().as_default():\n with self.assertRaisesWithPredicateMatch(\n ValueError,\n lambda e: (\"Too many elements provided. Needed at most 5, \"\n \"but received 7\" == str(e))):\n constant_op.constant([1, 2, 3, 4, 5, 6, 7], shape=[5])\n\n # pylint: enable=g-long-lambda\n # TODO(b/35396543): Temporarily disable: suspicion that\n # this is causing test timeouts.\n def _testTooLargeConstant(self):\n with ops.Graph().as_default():\n large_array = np.zeros((512, 1024, 1024), dtype=np.float32)\n with self.assertRaisesRegexp(\n ValueError,\n \"Cannot create a tensor proto whose content is larger than 2GB.\"):\n c = constant_op.constant(large_array)\n\n # TODO(b/35396543): Temporarily disable: suspicion that\n # this is causing test timeouts.\n def _testTooLargeGraph(self):\n with ops.Graph().as_default() as g:\n large_array = np.zeros((256, 1024, 1024), dtype=np.float32)\n c = constant_op.constant(large_array)\n d = constant_op.constant(large_array)\n with self.assertRaisesRegexp(ValueError,\n \"GraphDef cannot be larger than 2GB.\"):\n g.as_graph_def()\n\n def testSparseValuesRaiseErrors(self):\n with self.assertRaisesRegexp(ValueError,\n \"setting an array element with a sequence\"):\n c = constant_op.constant([[1, 2], [3]], dtype=dtypes_lib.int32)\n\n with self.assertRaisesRegexp(ValueError, \"must be a dense\"):\n c = constant_op.constant([[1, 2], [3]])\n\n with self.assertRaisesRegexp(ValueError, \"must be a dense\"):\n c = constant_op.constant([[1, 2], [3], [4, 5]])\n\n\nclass AsTensorTest(test.TestCase):\n\n def testAsTensorForTensorInput(self):\n with ops.Graph().as_default():\n t = constant_op.constant(10.0)\n x = ops.convert_to_tensor(t)\n self.assertIs(t, x)\n\n def testAsTensorForNonTensorInput(self):\n with ops.Graph().as_default():\n x = ops.convert_to_tensor(10.0)\n self.assertTrue(isinstance(x, ops.Tensor))\n\n def testAsTensorForShapeInput(self):\n with self.test_session():\n x = ops.convert_to_tensor(tensor_shape.TensorShape([]))\n self.assertEqual(dtypes_lib.int32, x.dtype)\n self.assertAllEqual([], x.eval())\n\n x = ops.convert_to_tensor(tensor_shape.TensorShape([1, 2, 3]))\n self.assertEqual(dtypes_lib.int32, x.dtype)\n self.assertAllEqual([1, 2, 3], x.eval())\n\n x = ops.convert_to_tensor(tensor_shape.TensorShape([2**31-1, 2, 3]))\n self.assertEqual(dtypes_lib.int32, x.dtype)\n self.assertAllEqual([2**31-1, 2, 3], x.eval())\n\n x = ops.convert_to_tensor(tensor_shape.TensorShape([2**31-1, 2, 3]),\n dtype=dtypes_lib.int32)\n self.assertEqual(dtypes_lib.int32, x.dtype)\n self.assertAllEqual([2**31-1, 2, 3], x.eval())\n\n x = ops.convert_to_tensor(tensor_shape.TensorShape([2**31, 2, 3]))\n self.assertEqual(dtypes_lib.int64, x.dtype)\n self.assertAllEqual([2**31, 2, 3], x.eval())\n\n x = ops.convert_to_tensor(tensor_shape.TensorShape([2**31, 2, 3]),\n dtype=dtypes_lib.int64)\n self.assertEqual(dtypes_lib.int64, x.dtype)\n self.assertAllEqual([2**31, 2, 3], x.eval())\n\n with self.assertRaisesRegexp(\n ValueError, \"a dimension is too large .2147483648.\"):\n x = ops.convert_to_tensor(tensor_shape.TensorShape([2**31, 2, 3]),\n dtype=dtypes_lib.int32)\n\n x = ops.convert_to_tensor(\n tensor_shape.TensorShape([1, 2, 3]), dtype=dtypes_lib.int64)\n self.assertEqual(dtypes_lib.int64, x.dtype)\n self.assertAllEqual([1, 2, 3], x.eval())\n\n x = array_ops.reshape(\n array_ops.zeros([6]), tensor_shape.TensorShape([2, 3]))\n self.assertAllEqual([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]], x.eval())\n\n with self.assertRaisesRegexp(ValueError, \"partially known\"):\n ops.convert_to_tensor(tensor_shape.TensorShape(None))\n\n with self.assertRaisesRegexp(ValueError, \"partially known\"):\n ops.convert_to_tensor(tensor_shape.TensorShape([1, None, 64]))\n\n with self.assertRaises(TypeError):\n ops.convert_to_tensor(\n tensor_shape.TensorShape([1, 2, 3]), dtype=dtypes_lib.float32)\n\n def testAsTensorForDimensionInput(self):\n with self.test_session():\n x = ops.convert_to_tensor(tensor_shape.TensorShape([1, 2, 3])[1])\n self.assertEqual(dtypes_lib.int32, x.dtype)\n self.assertAllEqual(2, x.eval())\n\n x = ops.convert_to_tensor(\n tensor_shape.TensorShape([1, 2, 3])[1], dtype=dtypes_lib.int64)\n self.assertEqual(dtypes_lib.int64, x.dtype)\n self.assertAllEqual(2, x.eval())\n\n with self.assertRaisesRegexp(ValueError, \"unknown Dimension\"):\n ops.convert_to_tensor(tensor_shape.TensorShape(None)[1])\n\n with self.assertRaisesRegexp(ValueError, \"unknown Dimension\"):\n ops.convert_to_tensor(tensor_shape.TensorShape([1, None, 64])[1])\n\n with self.assertRaises(TypeError):\n ops.convert_to_tensor(\n tensor_shape.TensorShape([1, 2, 3])[1], dtype=dtypes_lib.float32)\n\n\nclass IdentityOpTest(test.TestCase):\n\n def testIdTensor(self):\n with ops.Graph().as_default():\n x = constant_op.constant(2.0, shape=[6], name=\"input\")\n id_op = array_ops.identity(x, name=\"id\")\n self.assertTrue(isinstance(id_op.op.inputs[0], ops.Tensor))\n self.assertProtoEquals(\"name: 'id' op: 'Identity' input: 'input' \"\n \"attr { key: 'T' value { type: DT_FLOAT } }\",\n id_op.op.node_def)\n\n\nclass ZerosTest(test.TestCase):\n\n def _Zeros(self, shape):\n with self.test_session():\n ret = array_ops.zeros(shape)\n self.assertEqual(shape, ret.get_shape())\n return ret.eval()\n\n def testConst(self):\n self.assertTrue(\n np.array_equal(self._Zeros([2, 3]), np.array([[0] * 3] * 2)))\n\n def testScalar(self):\n self.assertEqual(0, self._Zeros([]))\n self.assertEqual(0, self._Zeros(()))\n with self.test_session():\n scalar = array_ops.zeros(constant_op.constant([], dtype=dtypes_lib.int32))\n self.assertEqual(0, scalar.eval())\n\n def testDynamicSizes(self):\n np_ans = np.array([[0] * 3] * 2)\n with self.test_session():\n # Creates a tensor of 2 x 3.\n d = array_ops.fill([2, 3], 12., name=\"fill\")\n # Constructs a tensor of zeros of the same dimensions as \"d\".\n z = array_ops.zeros(array_ops.shape(d))\n out = z.eval()\n self.assertAllEqual(np_ans, out)\n self.assertShapeEqual(np_ans, d)\n self.assertShapeEqual(np_ans, z)\n\n def testDtype(self):\n with self.test_session():\n d = array_ops.fill([2, 3], 12., name=\"fill\")\n self.assertEqual(d.get_shape(), [2, 3])\n # Test default type for both constant size and dynamic size\n z = array_ops.zeros([2, 3])\n self.assertEqual(z.dtype, dtypes_lib.float32)\n self.assertEqual([2, 3], z.get_shape())\n self.assertAllEqual(z.eval(), np.zeros([2, 3]))\n z = array_ops.zeros(array_ops.shape(d))\n self.assertEqual(z.dtype, dtypes_lib.float32)\n self.assertEqual([2, 3], z.get_shape())\n self.assertAllEqual(z.eval(), np.zeros([2, 3]))\n # Test explicit type control\n for dtype in [\n dtypes_lib.float32, dtypes_lib.float64, dtypes_lib.int32,\n dtypes_lib.uint8, dtypes_lib.int16, dtypes_lib.int8,\n dtypes_lib.complex64, dtypes_lib.complex128, dtypes_lib.int64,\n dtypes_lib.bool, dtypes_lib.string\n ]:\n z = array_ops.zeros([2, 3], dtype=dtype)\n self.assertEqual(z.dtype, dtype)\n self.assertEqual([2, 3], z.get_shape())\n z_value = z.eval()\n self.assertFalse(np.any(z_value))\n self.assertEqual((2, 3), z_value.shape)\n z = array_ops.zeros(array_ops.shape(d), dtype=dtype)\n self.assertEqual(z.dtype, dtype)\n self.assertEqual([2, 3], z.get_shape())\n z_value = z.eval()\n self.assertFalse(np.any(z_value))\n self.assertEqual((2, 3), z_value.shape)\n\n\nclass ZerosLikeTest(test.TestCase):\n\n def _compareZeros(self, dtype, fully_defined_shape, use_gpu):\n with self.test_session(use_gpu=use_gpu):\n # Creates a tensor of non-zero values with shape 2 x 3.\n # NOTE(kearnes): The default numpy dtype associated with tf.string is\n # np.object (and can't be changed without breaking a lot things), which\n # causes a TypeError in constant_op.constant below. Here we catch the\n # special case of tf.string and set the numpy dtype appropriately.\n if dtype == dtypes_lib.string:\n numpy_dtype = np.string_\n else:\n numpy_dtype = dtype.as_numpy_dtype\n if fully_defined_shape:\n d = constant_op.constant(\n np.ones((2, 3), dtype=numpy_dtype), dtype=dtype)\n else:\n d = array_ops.placeholder(dtype=dtype)\n # Constructs a tensor of zeros of the same dimensions and type as \"d\".\n z_var = array_ops.zeros_like(d)\n # Test that the type is correct\n self.assertEqual(z_var.dtype, dtype)\n # Test that the shape is correct\n if fully_defined_shape:\n self.assertEqual([2, 3], z_var.get_shape())\n\n # Test that the value is correct\n feed_dict = {}\n if not fully_defined_shape:\n feed_dict[d] = np.ones((2, 3), dtype=numpy_dtype)\n z_value = z_var.eval(feed_dict=feed_dict)\n self.assertFalse(np.any(z_value))\n self.assertEqual((2, 3), z_value.shape)\n\n def testZerosLikeCPU(self):\n for dtype in [\n dtypes_lib.float32, dtypes_lib.float64, dtypes_lib.int8,\n dtypes_lib.uint8, dtypes_lib.int16, dtypes_lib.uint16, dtypes_lib.int32,\n dtypes_lib.int64, dtypes_lib.bool, dtypes_lib.complex64,\n dtypes_lib.complex128, dtypes_lib.string\n ]:\n self._compareZeros(dtype, fully_defined_shape=False, use_gpu=False)\n self._compareZeros(dtype, fully_defined_shape=True, use_gpu=False)\n\n def testZerosLikeGPU(self):\n for dtype in [\n dtypes_lib.float32, dtypes_lib.float64, dtypes_lib.int32,\n dtypes_lib.bool, dtypes_lib.int64, dtypes_lib.string\n ]:\n self._compareZeros(dtype, fully_defined_shape=False, use_gpu=True)\n self._compareZeros(dtype, fully_defined_shape=True, use_gpu=True)\n\n def testZerosLikePartialShape(self):\n d = array_ops.placeholder(dtypes_lib.float32, shape=[None, 4, None])\n z = array_ops.zeros_like(d)\n self.assertEqual(d.get_shape().as_list(), z.get_shape().as_list())\n\n def testZerosLikeDtype(self):\n # Make sure zeros_like works even for dtypes that cannot be cast between\n with self.test_session():\n shape = (3, 5)\n dtypes = np.float32, np.complex64\n for in_type in dtypes:\n x = np.arange(15).astype(in_type).reshape(*shape)\n for out_type in dtypes:\n y = array_ops.zeros_like(x, dtype=out_type).eval()\n self.assertEqual(y.dtype, out_type)\n self.assertEqual(y.shape, shape)\n self.assertAllEqual(y, np.zeros(shape, dtype=out_type))\n\n def testZerosLikeVariant(self):\n # TODO(ebrevdo): Re-enable use_gpu=True once non-DMA Variant\n # copying between CPU and GPU is supported AND we register a\n # ZerosLike callback for GPU for Variant storing primitive types\n # in variant_op_registry.cc.\n with self.test_session(use_gpu=False):\n variant_tensor = tensor_pb2.TensorProto(\n dtype=dtypes_lib.variant.as_datatype_enum,\n tensor_shape=tensor_shape.TensorShape([]).as_proto(),\n variant_val=[\n tensor_pb2.VariantTensorDataProto(\n # Match registration in variant_op_registry.cc\n type_name=b\"int\",\n metadata=np.array(1, dtype=np.int32).tobytes())\n ])\n const_variant = constant_op.constant(variant_tensor)\n zeros_like = array_ops.zeros_like(const_variant)\n zeros_like_op = logging_ops.Print(\n zeros_like, [const_variant, zeros_like],\n message=\"Variant storing an int, input and output of zeros_like:\").op\n\n # Smoke test -- ensure this executes without trouble.\n # Right now, non-numpy-compatible objects cannot be returned from a\n # session.run call; similarly, objects that can't be converted to\n # native numpy types cannot be passed to ops.convert_to_tensor.\n # TODO(ebrevdo): Add registration mechanism for\n # ops.convert_to_tensor and for session.run output.\n zeros_like_op.run()\n\n\nclass OnesTest(test.TestCase):\n\n def _Ones(self, shape):\n with self.test_session():\n ret = array_ops.ones(shape)\n self.assertEqual(shape, ret.get_shape())\n return ret.eval()\n\n def testConst(self):\n self.assertTrue(np.array_equal(self._Ones([2, 3]), np.array([[1] * 3] * 2)))\n\n def testScalar(self):\n self.assertEqual(1, self._Ones([]))\n self.assertEqual(1, self._Ones(()))\n with self.test_session():\n scalar = array_ops.ones(constant_op.constant([], dtype=dtypes_lib.int32))\n self.assertEqual(1, scalar.eval())\n\n def testDynamicSizes(self):\n np_ans = np.array([[1] * 3] * 2)\n with self.test_session():\n # Creates a tensor of 2 x 3.\n d = array_ops.fill([2, 3], 12., name=\"fill\")\n # Constructs a tensor of ones of the same dimensions as \"d\".\n z = array_ops.ones(array_ops.shape(d))\n out = z.eval()\n self.assertAllEqual(np_ans, out)\n self.assertShapeEqual(np_ans, d)\n self.assertShapeEqual(np_ans, z)\n\n def testAutoPack(self):\n with self.test_session():\n h = array_ops.placeholder(dtypes_lib.int32, shape=[])\n w = array_ops.placeholder(dtypes_lib.int32, shape=[])\n z = array_ops.ones([h, w])\n out = z.eval(feed_dict={h: 4, w: 16})\n self.assertAllEqual(out, np.array([[1] * 16] * 4))\n\n def testDtype(self):\n with self.test_session():\n d = array_ops.fill([2, 3], 12., name=\"fill\")\n self.assertEqual(d.get_shape(), [2, 3])\n # Test default type for both constant size and dynamic size\n z = array_ops.ones([2, 3])\n self.assertEqual(z.dtype, dtypes_lib.float32)\n self.assertEqual([2, 3], z.get_shape())\n self.assertAllEqual(z.eval(), np.ones([2, 3]))\n z = array_ops.ones(array_ops.shape(d))\n self.assertEqual(z.dtype, dtypes_lib.float32)\n self.assertEqual([2, 3], z.get_shape())\n self.assertAllEqual(z.eval(), np.ones([2, 3]))\n # Test explicit type control\n for dtype in (dtypes_lib.float32, dtypes_lib.float64, dtypes_lib.int32,\n dtypes_lib.uint8, dtypes_lib.int16, dtypes_lib.int8,\n dtypes_lib.complex64, dtypes_lib.complex128,\n dtypes_lib.int64, dtypes_lib.bool):\n z = array_ops.ones([2, 3], dtype=dtype)\n self.assertEqual(z.dtype, dtype)\n self.assertEqual([2, 3], z.get_shape())\n self.assertAllEqual(z.eval(), np.ones([2, 3]))\n z = array_ops.ones(array_ops.shape(d), dtype=dtype)\n self.assertEqual(z.dtype, dtype)\n self.assertEqual([2, 3], z.get_shape())\n self.assertAllEqual(z.eval(), np.ones([2, 3]))\n\n\nclass OnesLikeTest(test.TestCase):\n\n def testOnesLike(self):\n for dtype in [\n dtypes_lib.float32, dtypes_lib.float64, dtypes_lib.int8,\n dtypes_lib.uint8, dtypes_lib.int16, dtypes_lib.uint16, dtypes_lib.int32,\n dtypes_lib.int64, dtypes_lib.bool, dtypes_lib.complex64,\n dtypes_lib.complex128\n ]:\n numpy_dtype = dtype.as_numpy_dtype\n with self.test_session():\n # Creates a tensor of non-zero values with shape 2 x 3.\n d = constant_op.constant(\n np.ones(\n (2, 3), dtype=numpy_dtype), dtype=dtype)\n # Constructs a tensor of zeros of the same dimensions and type as \"d\".\n z_var = array_ops.ones_like(d)\n # Test that the type is correct\n self.assertEqual(z_var.dtype, dtype)\n z_value = z_var.eval()\n\n # Test that the value is correct\n self.assertTrue(np.array_equal(z_value, np.array([[1] * 3] * 2)))\n self.assertEqual([2, 3], z_var.get_shape())\n\n def testOnesLikePartialShape(self):\n d = array_ops.placeholder(dtypes_lib.float32, shape=[None, 4, None])\n z = array_ops.ones_like(d)\n self.assertEqual(d.get_shape().as_list(), z.get_shape().as_list())\n\n\nclass FillTest(test.TestCase):\n\n def _compare(self, dims, val, np_ans, use_gpu):\n with self.test_session(use_gpu=use_gpu):\n tf_ans = array_ops.fill(dims, val, name=\"fill\")\n out = tf_ans.eval()\n self.assertAllClose(np_ans, out)\n # Fill does not set the shape.\n # self.assertShapeEqual(np_ans, tf_ans)\n\n def _compareAll(self, dims, val, np_ans):\n self._compare(dims, val, np_ans, False)\n self._compare(dims, val, np_ans, True)\n\n def testFillFloat(self):\n np_ans = np.array([[3.1415] * 3] * 2).astype(np.float32)\n self._compareAll([2, 3], np_ans[0][0], np_ans)\n\n def testFillDouble(self):\n np_ans = np.array([[3.1415] * 3] * 2).astype(np.float64)\n self._compareAll([2, 3], np_ans[0][0], np_ans)\n\n def testFillInt32(self):\n np_ans = np.array([[42] * 3] * 2).astype(np.int32)\n self._compareAll([2, 3], np_ans[0][0], np_ans)\n\n def testFillInt64(self):\n np_ans = np.array([[-42] * 3] * 2).astype(np.int64)\n self._compareAll([2, 3], np_ans[0][0], np_ans)\n\n def testFillComplex64(self):\n np_ans = np.array([[0.15] * 3] * 2).astype(np.complex64)\n self._compare([2, 3], np_ans[0][0], np_ans, use_gpu=False)\n\n def testFillComplex128(self):\n np_ans = np.array([[0.15] * 3] * 2).astype(np.complex128)\n self._compare([2, 3], np_ans[0][0], np_ans, use_gpu=False)\n\n def testFillString(self):\n np_ans = np.array([[b\"yolo\"] * 3] * 2)\n with self.test_session(use_gpu=False):\n tf_ans = array_ops.fill([2, 3], np_ans[0][0], name=\"fill\").eval()\n self.assertAllEqual(np_ans, tf_ans)\n\n def testFillNegative(self):\n with self.test_session():\n for shape in (-1,), (2, -1), (-1, 2), (-2), (-3):\n with self.assertRaises(ValueError):\n array_ops.fill(shape, 7)\n\n # Using a placeholder so this won't be caught in static analysis.\n dims = array_ops.placeholder(dtypes_lib.int32)\n fill_t = array_ops.fill(dims, 3.0)\n for shape in (-1,), (2, -1), (-1, 2), (-2), (-3):\n with self.assertRaises(errors_impl.InvalidArgumentError):\n fill_t.eval({dims: shape})\n\n def testShapeFunctionEdgeCases(self):\n # Non-vector dimensions.\n with self.assertRaises(ValueError):\n array_ops.fill([[0, 1], [2, 3]], 1.0)\n\n # Non-scalar value.\n with self.assertRaises(ValueError):\n array_ops.fill([3, 2], [1.0, 2.0])\n\n # Partial dimension information.\n f = array_ops.fill(array_ops.placeholder(dtypes_lib.int32, shape=(4,)), 3.0)\n self.assertEqual([None, None, None, None], f.get_shape().as_list())\n\n f = array_ops.fill(\n [array_ops.placeholder(\n dtypes_lib.int32, shape=()), 17], 1.0)\n self.assertEqual([None, 17], f.get_shape().as_list())\n\n def testGradient(self):\n with self.test_session():\n in_v = constant_op.constant(5.0)\n out_shape = [3, 2]\n out_filled = array_ops.fill(out_shape, in_v)\n err = gradient_checker.compute_gradient_error(in_v, [], out_filled,\n out_shape)\n self.assertLess(err, 1e-3)\n\n\nclass PlaceholderTest(test.TestCase):\n\n def testDtype(self):\n with self.test_session():\n p = array_ops.placeholder(dtypes_lib.float32, shape=(10, 10), name=\"p\")\n p_identity = array_ops.identity(p)\n feed_array = np.random.rand(10, 10)\n self.assertAllClose(\n p_identity.eval(feed_dict={p: feed_array}), feed_array)\n\n with self.assertRaisesOpError(\n \"must feed a value for placeholder tensor 'p' with dtype float\"):\n p_identity.eval()\n\n def testShape(self):\n with self.test_session():\n p = array_ops.placeholder(dtypes_lib.float32, shape=(10, 10), name=\"p\")\n p_identity = array_ops.identity(p)\n feed_array = np.random.rand(10, 10)\n self.assertAllClose(\n p_identity.eval(feed_dict={p: feed_array}), feed_array)\n\n with self.assertRaisesOpError(\n \"must feed a value for placeholder tensor 'p' with dtype float and \"\n r\"shape \\[10,10\\]\"):\n p_identity.eval()\n\n with self.assertRaisesWithPredicateMatch(\n ValueError, lambda e: \"Cannot feed value of shape\" in str(e)):\n p_identity.eval(feed_dict={p: feed_array[:5, :5]})\n\n def testUnknownShape(self):\n with self.test_session():\n p = array_ops.placeholder(dtypes_lib.float32, shape=None, name=\"p\")\n p_identity = array_ops.identity(p)\n # can feed anything\n feed_array = np.random.rand(10, 3)\n self.assertAllClose(\n p_identity.eval(feed_dict={p: feed_array}), feed_array)\n feed_array = np.random.rand(4, 2, 5)\n self.assertAllClose(\n p_identity.eval(feed_dict={p: feed_array}), feed_array)\n\n def testScalarShape(self):\n with self.test_session():\n p = array_ops.placeholder(dtypes_lib.float32, shape=[], name=\"p\")\n p_identity = array_ops.identity(p)\n self.assertAllClose(p_identity.eval(feed_dict={p: 5}), 5)\n\n def testPartialShape(self):\n with self.test_session():\n p = array_ops.placeholder(dtypes_lib.float32, shape=[None, 3], name=\"p\")\n p_identity = array_ops.identity(p)\n feed_array = np.random.rand(10, 3)\n self.assertAllClose(\n p_identity.eval(feed_dict={p: feed_array}), feed_array)\n\n with self.assertRaisesWithPredicateMatch(\n ValueError, lambda e: \"Cannot feed value of shape\" in str(e)):\n p_identity.eval(feed_dict={p: feed_array[:5, :2]})\n\n def testPartialShapeWhenNotFed(self):\n with self.test_session():\n p = array_ops.placeholder(dtypes_lib.float32, shape=[None, 3], name=\"p\")\n p_identity = array_ops.identity(p)\n\n # Should trigger an operator error, not a shape error.\n with self.assertRaisesOpError(\n \"must feed a value for placeholder tensor 'p' with dtype float\"):\n p_identity.eval()\n\n def testControlDependency(self):\n with self.test_session():\n p = array_ops.placeholder(dtypes_lib.int32, shape=[], name=\"p\")\n with ops.control_dependencies([p]):\n c = constant_op.constant(5, dtypes_lib.int32)\n d = math_ops.multiply(p, c)\n val = np.array(2).astype(np.int)\n self.assertEqual(10, d.eval(feed_dict={p: val}))\n\n def testBadShape(self):\n with self.assertRaises(ValueError):\n array_ops.placeholder(dtypes_lib.float32, shape=(-1, 10))\n\n def testTensorStr(self):\n a = array_ops.placeholder(dtypes_lib.float32, shape=None, name=\"a\")\n self.assertEqual(\"<tf.Tensor 'a:0' shape=<unknown> dtype=float32>\", repr(a))\n\n b = array_ops.placeholder(dtypes_lib.int32, shape=(32, 40), name=\"b\")\n self.assertEqual(\"<tf.Tensor 'b:0' shape=(32, 40) dtype=int32>\", repr(b))\n\n c = array_ops.placeholder(dtypes_lib.qint32, shape=(32, None, 2), name=\"c\")\n self.assertEqual(\"<tf.Tensor 'c:0' shape=(32, ?, 2) dtype=qint32>\", repr(c))\n\n def testOldGraph(self):\n # Load graph generated from earlier version of TF where\n # placeholder shape was not set.\n #\n # a = tf.placeholder(tf.float32)\n # b = a + 1.0\n #\n # Older graph's default shape is 'shape {}', not 'shape {\n # unknown_rank: true }'\n graph = \"\"\"\nnode {\n name: \"Placeholder\"\n op: \"Placeholder\"\n attr {\n key: \"dtype\"\n value {\n type: DT_FLOAT\n }\n }\n attr {\n key: \"shape\"\n value {\n shape {\n }\n }\n }\n}\nnode {\n name: \"add/y\"\n op: \"Const\"\n attr {\n key: \"dtype\"\n value {\n type: DT_FLOAT\n }\n }\n attr {\n key: \"value\"\n value {\n tensor {\n dtype: DT_FLOAT\n tensor_shape {\n }\n float_val: 1.0\n }\n }\n }\n}\nnode {\n name: \"add\"\n op: \"Add\"\n input: \"Placeholder\"\n input: \"add/y\"\n attr {\n key: \"T\"\n value {\n type: DT_FLOAT\n }\n }\n}\nversions {\n producer: 21\n}\n\"\"\"\n gdef = graph_pb2.GraphDef()\n text_format.Merge(graph, gdef)\n with self.test_session():\n p, ret = importer.import_graph_def(\n gdef, return_elements=[\"Placeholder:0\", \"add:0\"])\n\n # Feed in a vector of two elements. Since the producer version\n # of 21, a shape of {} is interpreted as \"any shape\". If\n # producer version were 22, then we'd get a shape mismatch\n # error.\n self.assertAllEqual([2.0, 3.0], ret.eval(feed_dict={p: [1.0, 2.0]}))\n\n\nclass PlaceholderWithDefaultTest(test.TestCase):\n\n def testFullShape(self):\n with self.test_session():\n p = array_ops.placeholder_with_default([[2, 2], [2, 2]], shape=[2, 2])\n a = array_ops.identity(p)\n self.assertAllEqual([[2, 2], [2, 2]], a.eval())\n self.assertAllEqual(\n [[3, 3], [3, 3]], a.eval(feed_dict={p: [[3, 3], [3, 3]]}))\n\n with self.assertRaises(ValueError):\n a.eval(feed_dict={p: [[6, 6, 6], [6, 6, 6]]})\n\n def testPartialShape(self):\n with self.test_session():\n p = array_ops.placeholder_with_default([1, 2, 3], shape=[None])\n a = array_ops.identity(p)\n self.assertAllEqual([1, 2, 3], a.eval())\n self.assertAllEqual([3, 37], a.eval(feed_dict={p: [3, 37]}))\n\n with self.assertRaises(ValueError):\n a.eval(feed_dict={p: [[2, 2], [2, 2]]})\n\n def testNoShape(self):\n with self.test_session():\n p = array_ops.placeholder_with_default([17], shape=None)\n a = array_ops.identity(p)\n self.assertAllEqual([17], a.eval())\n self.assertAllEqual([3, 37], a.eval(feed_dict={p: [3, 37]}))\n self.assertAllEqual(\n [[3, 3], [3, 3]], a.eval(feed_dict={p: [[3, 3], [3, 3]]}))\n\n def testGradient(self):\n with self.test_session():\n x = array_ops.placeholder(dtypes_lib.float32, [5, 7])\n y = array_ops.placeholder_with_default(x, None)\n err = gradient_checker.compute_gradient_error(x, [5, 7], y, [5, 7])\n self.assertLess(err, 1e-3)\n\nif __name__ == \"__main__\":\n test.main()\n", "# Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for fused_batch_norm related functionality in tensorflow.ops.nn.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import gradient_checker\nfrom tensorflow.python.ops import gradients_impl\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import nn_grad\nfrom tensorflow.python.ops import nn_impl\nfrom tensorflow.python.platform import test\n\n\nclass BatchNormalizationTest(test.TestCase):\n\n def _batch_norm(self, x, mean, var, offset, scale, epsilon):\n # We compute the batch norm manually in this function because\n # nn_impl.batch_normalization does not support float16 yet.\n # TODO(reedwm): Add float16 support to nn_impl.batch_normalization.\n inv = math_ops.rsqrt(var + epsilon) * scale\n y = math_ops.cast(x, scale.dtype) * inv + (offset - mean * inv)\n return math_ops.cast(y, x.dtype)\n\n def _inference_ref(self, x, scale, offset, mean, var, epsilon, data_format):\n if data_format not in ['NHWC', 'NCHW']:\n raise ValueError('data_format must be NCHW or NHWC, '\n 'got %s.' % data_format)\n if data_format == 'NCHW':\n x = array_ops.transpose(x, [0, 2, 3, 1])\n y = self._batch_norm(x, mean, var, offset, scale, epsilon)\n if data_format == 'NCHW':\n y = array_ops.transpose(y, [0, 3, 1, 2])\n return y.eval()\n\n def _test_inference(self,\n x_shape,\n x_dtype,\n scale_shape,\n scale_dtype,\n use_gpu=True,\n data_format='NHWC'):\n np.random.seed(1)\n x_val = np.random.random_sample(x_shape).astype(x_dtype)\n scale_val = np.random.random_sample(scale_shape).astype(scale_dtype)\n offset_val = np.random.random_sample(scale_shape).astype(scale_dtype)\n mean_val = np.random.random_sample(scale_shape).astype(scale_dtype)\n var_val = np.random.random_sample(scale_shape).astype(scale_dtype)\n\n with self.test_session(use_gpu=use_gpu) as sess:\n x = constant_op.constant(x_val, name='x')\n scale = constant_op.constant(scale_val, name='scale')\n offset = constant_op.constant(offset_val, name='offset')\n mean = constant_op.constant(mean_val, name='mean')\n var = constant_op.constant(var_val, name='variance')\n epsilon = 0.001\n y, _, _ = nn_impl.fused_batch_norm(\n x,\n scale,\n offset,\n mean=mean,\n variance=var,\n epsilon=epsilon,\n data_format=data_format,\n is_training=False)\n y_val = sess.run(y)\n y_ref = self._inference_ref(x, scale, offset, mean, var, epsilon,\n data_format)\n # An atol value of 1e-3 is too small for float16's, because some adjacent\n # float16 values that y_val can take are greater than 1e-3 apart, e.g.\n # 2.16602 and 2.16797.\n atol = 2e-3 if x_dtype == np.float16 else 1e-3\n self.assertAllClose(y_ref, y_val, atol=atol)\n\n def _training_ref(self, x, scale, offset, epsilon, data_format):\n if data_format not in ['NHWC', 'NCHW']:\n raise ValueError('data_format must be NCHW or NHWC, '\n 'got %s.' % data_format)\n if data_format == 'NCHW':\n x = array_ops.transpose(x, [0, 2, 3, 1])\n mean, var = nn_impl.moments(\n math_ops.cast(x, scale.dtype), [0, 1, 2], keep_dims=False)\n y = self._batch_norm(x, mean, var, offset, scale, epsilon)\n if data_format == 'NCHW':\n y = array_ops.transpose(y, [0, 3, 1, 2])\n return y.eval(), mean.eval(), var.eval()\n\n def _test_training(self,\n x_shape,\n x_dtype,\n scale_shape,\n scale_dtype,\n use_gpu=True,\n data_format='NHWC'):\n np.random.seed(1)\n x_val = np.random.random_sample(x_shape).astype(x_dtype)\n scale_val = np.random.random_sample(scale_shape).astype(scale_dtype)\n offset_val = np.random.random_sample(scale_shape).astype(scale_dtype)\n with self.test_session(use_gpu=use_gpu) as sess:\n x = constant_op.constant(x_val, name='x')\n scale = constant_op.constant(scale_val, name='scale')\n offset = constant_op.constant(offset_val, name='offset')\n epsilon = 0.001\n y, mean, var = nn_impl.fused_batch_norm(\n x,\n scale,\n offset,\n epsilon=epsilon,\n data_format=data_format,\n is_training=True)\n y_val, mean_val, var_val = sess.run([y, mean, var])\n y_ref, mean_ref, var_ref = self._training_ref(x, scale, offset, epsilon,\n data_format)\n y_atol = 2e-3 if x_dtype == np.float16 else 1e-3\n self.assertAllClose(y_ref, y_val, atol=y_atol)\n self.assertAllClose(mean_ref, mean_val, atol=1e-3)\n # This is for Bessel's correction. tf.nn.moments uses n, instead of n-1, as\n # the denominator in the formula to calculate variance, while\n # tf.nn.fused_batch_norm has Bessel's correction built in.\n sample_size = x_val.size / scale_val.size\n var_ref = var_ref * sample_size / (max(sample_size - 1.0, 1.0))\n self.assertAllClose(var_ref, var_val, atol=1e-3)\n\n def _compute_gradient_error_float16(self, x, x32, x_shape, y, y32, y_shape):\n \"\"\"Computes the gradient error for float16 inputs and/or outputs.\n\n This returns the same value as gradient_checker.compute_gradient_error. The\n difference is that gradient_checker.compute_gradient_error does not\n numerically compute the gradients in a numerically stable way for float16\n tensors. To fix this, this function requires float32 versions of x and y to\n numerically compute the gradients, to compare with the float16 symbolically\n computed gradients.\n\n Args:\n x: The input tensor.\n x32: A float32 version of x.\n x_shape: The shape of x.\n y: The output tensor.\n y32: A float32 version of y. Must be calculated based on x32, not x.\n y_shape: The shape of y.\n\n Returns:\n The maximum error in between the two Jacobians, as in\n gradient_checker.compute_gradient_error.\n \"\"\"\n x_init_val = np.random.random_sample(x_shape).astype(np.float16)\n x32_init_val = x_init_val.astype(np.float32)\n\n # TODO(reedwm): Do not perform the unnecessary computations in\n # compute_gradient, since they double the computation time of this function.\n theoretical_grad, _ = gradient_checker.compute_gradient(\n x, x_shape, y, y_shape, delta=1e-3, x_init_value=x_init_val)\n _, numerical_grad = gradient_checker.compute_gradient(\n x32, x_shape, y32, y_shape, delta=1e-3, x_init_value=x32_init_val)\n return np.fabs(theoretical_grad - numerical_grad).max()\n\n def _test_gradient(self,\n x_shape,\n x_dtype,\n scale_shape,\n scale_dtype,\n use_gpu=True,\n data_format='NHWC',\n is_training=True):\n np.random.seed(1)\n x_val = np.random.random_sample(x_shape).astype(x_dtype)\n scale_val = np.random.random_sample(scale_shape).astype(scale_dtype)\n offset_val = np.random.random_sample(scale_shape).astype(scale_dtype)\n\n with self.test_session(use_gpu=use_gpu):\n x = constant_op.constant(x_val, name='x')\n scale = constant_op.constant(scale_val, name='scale')\n offset = constant_op.constant(offset_val, name='offset')\n if is_training:\n pop_mean = None\n pop_var = None\n else:\n pop_mean = np.random.random_sample(scale_shape).astype(scale_dtype)\n pop_var = np.random.random_sample(scale_shape).astype(scale_dtype)\n y, _, _ = nn_impl.fused_batch_norm(\n x,\n scale,\n offset,\n mean=pop_mean,\n variance=pop_var,\n data_format=data_format,\n is_training=is_training)\n if x_dtype != np.float16:\n err_x = gradient_checker.compute_gradient_error(x, x_shape, y, x_shape)\n err_scale = gradient_checker.compute_gradient_error(\n scale, scale_shape, y, x_shape)\n err_offset = gradient_checker.compute_gradient_error(\n offset, scale_shape, y, x_shape)\n else:\n x32 = constant_op.constant(x_val, name='x32', dtype=dtypes.float32)\n y32, _, _ = nn_impl.fused_batch_norm(\n x32,\n scale,\n offset,\n mean=pop_mean,\n variance=pop_var,\n data_format=data_format,\n is_training=is_training)\n err_x = self._compute_gradient_error_float16(x, x32, x_shape, y, y32,\n x_shape)\n err_scale = self._compute_gradient_error_float16(\n scale, scale, scale_shape, y, y32, x_shape)\n err_offset = self._compute_gradient_error_float16(\n offset, offset, scale_shape, y, y32, x_shape)\n\n x_err_tolerance = 2e-3 if x_dtype == np.float16 else 1e-3\n scale_err_tolerance = 1e-3\n self.assertLess(err_x, x_err_tolerance)\n self.assertLess(err_scale, scale_err_tolerance)\n self.assertLess(err_offset, scale_err_tolerance)\n\n def _test_grad_grad(self,\n x_shape,\n x_dtype,\n scale_shape,\n scale_dtype,\n use_gpu=True,\n data_format='NHWC',\n is_training=True,\n err_tolerance=1e-3):\n np.random.seed(1)\n x_val = np.random.random_sample(x_shape).astype(x_dtype)\n grad_y_val = np.random.random_sample(x_shape).astype(x_dtype)\n scale_val = np.random.random_sample(scale_shape).astype(scale_dtype)\n offset_val = np.random.random_sample(scale_shape).astype(scale_dtype)\n\n with self.test_session(use_gpu=use_gpu) as sess:\n x = constant_op.constant(x_val, name='x')\n grad_y = constant_op.constant(grad_y_val, name='grad_y')\n scale = constant_op.constant(scale_val, name='scale')\n offset = constant_op.constant(offset_val, name='offset')\n if is_training:\n pop_mean = None\n pop_var = None\n else:\n pop_mean = np.random.random_sample(scale_shape).astype(scale_dtype)\n pop_var = np.random.random_sample(scale_shape).astype(scale_dtype)\n y, _, _ = nn_impl.fused_batch_norm(\n x,\n scale,\n offset,\n mean=pop_mean,\n variance=pop_var,\n data_format=data_format,\n is_training=is_training)\n grad_x, grad_scale, grad_offset = gradients_impl.gradients(\n y, [x, scale, offset], grad_y)\n\n if is_training:\n epsilon = y.op.get_attr('epsilon')\n data_format = y.op.get_attr('data_format')\n grad_vals = sess.run([grad_x, grad_scale, grad_offset])\n grad_internal = nn_grad._BatchNormGrad(grad_y, x, scale, pop_mean, pop_var, epsilon, data_format)\n grad_internal_vals = sess.run(list(grad_internal))\n for grad_val, grad_internal_val in zip(grad_vals, grad_internal_vals):\n self.assertAllClose(grad_val, grad_internal_val, atol=err_tolerance)\n\n if x_dtype != np.float16:\n err_grad_grad_y_1 = gradient_checker.compute_gradient_error(\n grad_y, x_shape, grad_x, x_shape)\n err_grad_grad_y_2 = gradient_checker.compute_gradient_error(\n grad_y, x_shape, grad_scale, scale_shape)\n err_grad_grad_y_3 = gradient_checker.compute_gradient_error(\n grad_y, x_shape, grad_offset, scale_shape)\n # In freeze mode, grad_x is not a function of x.\n if is_training:\n err_grad_x_1 = gradient_checker.compute_gradient_error(\n x, x_shape, grad_x, x_shape)\n err_grad_x_2 = gradient_checker.compute_gradient_error(\n x, x_shape, grad_scale, scale_shape)\n\n err_grad_scale = gradient_checker.compute_gradient_error(\n scale, scale_shape, grad_x, x_shape)\n else:\n x32 = constant_op.constant(x_val, dtype=dtypes.float32, name='x32')\n grad_y32 = constant_op.constant(\n grad_y_val, dtype=dtypes.float32, name='grad_y32')\n y32, _, _ = nn_impl.fused_batch_norm(\n x32,\n scale,\n offset,\n mean=pop_mean,\n variance=pop_var,\n data_format=data_format,\n is_training=is_training)\n grad_x32, grad_scale32, grad_offset32 = gradients_impl.gradients(\n y32, [x32, scale, offset], grad_y32)\n err_grad_grad_y_1 = self._compute_gradient_error_float16(\n grad_y, grad_y32, x_shape, grad_x, grad_x32, x_shape)\n err_grad_grad_y_2 = self._compute_gradient_error_float16(\n grad_y, grad_y32, x_shape, grad_scale, grad_scale32, scale_shape)\n err_grad_grad_y_3 = self._compute_gradient_error_float16(\n grad_y, grad_y32, x_shape, grad_offset, grad_offset32, scale_shape)\n # In freeze mode, grad_x is not a function of x.\n if is_training:\n err_grad_x_1 = self._compute_gradient_error_float16(\n x, x32, x_shape, grad_x, grad_x32, x_shape)\n err_grad_x_2 = self._compute_gradient_error_float16(\n x, x32, x_shape, grad_scale, grad_scale32, scale_shape)\n\n err_grad_scale = self._compute_gradient_error_float16(\n scale, scale, scale_shape, grad_x, grad_x32, x_shape)\n\n self.assertLess(err_grad_grad_y_1, err_tolerance)\n self.assertLess(err_grad_grad_y_2, err_tolerance)\n self.assertLess(err_grad_grad_y_3, err_tolerance)\n if is_training:\n self.assertLess(err_grad_x_1, err_tolerance)\n self.assertLess(err_grad_x_2, err_tolerance)\n self.assertLess(err_grad_scale, err_tolerance)\n\n def testInferenceShape1(self):\n x_shape = [1, 1, 6, 1]\n for dtype in [np.float16, np.float32]:\n if test.is_gpu_available(cuda_only=True):\n self._test_inference(\n x_shape, dtype, [1], np.float32, use_gpu=True, data_format='NHWC')\n self._test_inference(\n x_shape, dtype, [1], np.float32, use_gpu=True, data_format='NCHW')\n self._test_inference(\n x_shape, dtype, [1], np.float32, use_gpu=False, data_format='NHWC')\n\n def testInferenceShape2(self):\n x_shape = [1, 1, 6, 2]\n if test.is_gpu_available(cuda_only=True):\n for dtype in [np.float16, np.float32]:\n self._test_inference(\n x_shape, dtype, [2], np.float32, use_gpu=True, data_format='NHWC')\n self._test_inference(\n x_shape, dtype, [2], np.float32, use_gpu=False, data_format='NHWC')\n\n def testInferenceShape3(self):\n x_shape = [1, 2, 1, 6]\n if test.is_gpu_available(cuda_only=True):\n for dtype in [np.float16, np.float32]:\n self._test_inference(\n x_shape, dtype, [2], np.float32, use_gpu=True, data_format='NCHW')\n\n def testInferenceShape4(self):\n x_shape = [27, 131, 127, 6]\n for dtype in [np.float16, np.float32]:\n if test.is_gpu_available(cuda_only=True):\n self._test_inference(\n x_shape, dtype, [131], np.float32, use_gpu=True, data_format='NCHW')\n self._test_inference(\n x_shape, dtype, [6], np.float32, use_gpu=True, data_format='NHWC')\n self._test_inference(\n x_shape, dtype, [6], np.float32, use_gpu=False, data_format='NHWC')\n\n def testTrainingShape1(self):\n x_shape = [1, 1, 6, 1]\n for dtype in [np.float16, np.float32]:\n if test.is_gpu_available(cuda_only=True):\n self._test_training(\n x_shape, dtype, [1], np.float32, use_gpu=True, data_format='NHWC')\n self._test_training(\n x_shape, dtype, [1], np.float32, use_gpu=True, data_format='NCHW')\n self._test_training(\n x_shape, dtype, [1], np.float32, use_gpu=False, data_format='NHWC')\n\n def testTrainingShape2(self):\n x_shape = [1, 1, 6, 2]\n for dtype in [np.float16, np.float32]:\n if test.is_gpu_available(cuda_only=True):\n self._test_training(\n x_shape, dtype, [2], np.float32, use_gpu=True, data_format='NHWC')\n self._test_training(\n x_shape, dtype, [2], np.float32, use_gpu=False, data_format='NHWC')\n\n def testTrainingShape3(self):\n x_shape = [1, 2, 1, 6]\n if test.is_gpu_available(cuda_only=True):\n for dtype in [np.float16, np.float32]:\n self._test_training(\n x_shape, dtype, [2], np.float32, use_gpu=True, data_format='NCHW')\n\n def testTrainingShape4(self):\n x_shape = [27, 131, 127, 6]\n for dtype in [np.float16, np.float32]:\n if test.is_gpu_available(cuda_only=True):\n self._test_training(\n x_shape, dtype, [131], np.float32, use_gpu=True, data_format='NCHW')\n self._test_training(\n x_shape, dtype, [6], np.float32, use_gpu=True, data_format='NHWC')\n self._test_training(\n x_shape, dtype, [6], np.float32, use_gpu=False, data_format='NHWC')\n\n def testBatchNormGradShape1(self):\n for is_training in [True, False]:\n x_shape = [1, 1, 6, 1]\n for dtype in [np.float16, np.float32]:\n if test.is_gpu_available(cuda_only=True):\n self._test_gradient(\n x_shape,\n dtype, [1],\n np.float32,\n use_gpu=True,\n data_format='NHWC',\n is_training=is_training)\n self._test_gradient(\n x_shape,\n dtype, [1],\n np.float32,\n use_gpu=True,\n data_format='NCHW',\n is_training=is_training)\n self._test_gradient(\n x_shape,\n dtype, [1],\n np.float32,\n use_gpu=False,\n data_format='NHWC',\n is_training=is_training)\n\n def testBatchNormGradShape2(self):\n for is_training in [True, False]:\n x_shape = [1, 1, 6, 2]\n for dtype in [np.float16, np.float32]:\n if test.is_gpu_available(cuda_only=True):\n self._test_gradient(\n x_shape,\n dtype, [2],\n np.float32,\n use_gpu=True,\n data_format='NHWC',\n is_training=is_training)\n self._test_gradient(\n x_shape,\n dtype, [2],\n np.float32,\n use_gpu=False,\n data_format='NHWC',\n is_training=is_training)\n\n def testBatchNormGradShape3(self):\n for is_training in [True, False]:\n x_shape = [1, 2, 1, 6]\n if test.is_gpu_available(cuda_only=True):\n for dtype in [np.float16, np.float32]:\n self._test_gradient(\n x_shape,\n dtype, [2],\n np.float32,\n use_gpu=True,\n data_format='NCHW',\n is_training=is_training)\n\n def testBatchNormGradShape4(self):\n for is_training in [True, False]:\n x_shape = [5, 7, 11, 4]\n for dtype in [np.float16, np.float32]:\n if test.is_gpu_available(cuda_only=True):\n self._test_gradient(\n x_shape,\n dtype, [7],\n np.float32,\n use_gpu=True,\n data_format='NCHW',\n is_training=is_training)\n self._test_gradient(\n x_shape,\n dtype, [4],\n np.float32,\n use_gpu=True,\n data_format='NHWC',\n is_training=is_training)\n self._test_gradient(\n x_shape,\n dtype, [4],\n np.float32,\n use_gpu=False,\n data_format='NHWC',\n is_training=is_training)\n\n def _testBatchNormGradGrad(self, config):\n shape = config['shape']\n err_tolerance = config['err_tolerance']\n dtype = config['dtype']\n for is_training in [True, False]:\n if test.is_gpu_available(cuda_only=True):\n self._test_grad_grad(\n shape,\n dtype, [shape[3]],\n np.float32,\n use_gpu=True,\n data_format='NHWC',\n is_training=is_training,\n err_tolerance=err_tolerance)\n self._test_grad_grad(\n shape,\n dtype, [shape[1]],\n np.float32,\n use_gpu=True,\n data_format='NCHW',\n is_training=is_training,\n err_tolerance=err_tolerance)\n self._test_grad_grad(\n shape,\n dtype, [shape[3]],\n np.float32,\n use_gpu=False,\n data_format='NHWC',\n is_training=is_training,\n err_tolerance=err_tolerance)\n\n def testBatchNormGradGradConfig1(self):\n config = {\n 'shape': [2, 3, 4, 5],\n 'err_tolerance': 1e-2,\n 'dtype': np.float32,\n }\n self._testBatchNormGradGrad(config)\n\n def testBatchNormGradGradConfig2(self):\n config = {\n 'shape': [2, 3, 2, 2],\n 'err_tolerance': 1e-3,\n 'dtype': np.float32,\n }\n self._testBatchNormGradGrad(config)\n\n def testBatchNormGradGradConfig3(self):\n config = {\n 'shape': [2, 3, 4, 5],\n 'err_tolerance': 1e-2,\n 'dtype': np.float16,\n }\n self._testBatchNormGradGrad(config)\n\n def testBatchNormGradGradConfig4(self):\n config = {\n 'shape': [2, 3, 2, 2],\n 'err_tolerance': 2e-3,\n 'dtype': np.float16,\n }\n self._testBatchNormGradGrad(config)\n\n\nif __name__ == '__main__':\n test.main()\n", "# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for Adam.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom tensorflow.python.client import session\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import resource_variable_ops\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.platform import test\nfrom tensorflow.python.training import adam\n\n\ndef adam_update_numpy(param,\n g_t,\n t,\n m,\n v,\n alpha=0.001,\n beta1=0.9,\n beta2=0.999,\n epsilon=1e-8):\n alpha_t = alpha * np.sqrt(1 - beta2**t) / (1 - beta1**t)\n\n m_t = beta1 * m + (1 - beta1) * g_t\n v_t = beta2 * v + (1 - beta2) * g_t * g_t\n\n param_t = param - alpha_t * m_t / (np.sqrt(v_t) + epsilon)\n return param_t, m_t, v_t\n\n\nclass AdamOptimizerTest(test.TestCase):\n\n def doTestSparse(self, use_resource=False):\n for dtype in [dtypes.half, dtypes.float32, dtypes.float64]:\n with self.test_session():\n # Initialize variables for numpy implementation.\n m0, v0, m1, v1 = 0.0, 0.0, 0.0, 0.0\n var0_np = np.array([1.0, 2.0], dtype=dtype.as_numpy_dtype)\n grads0_np = np.array([0.1, 0.1], dtype=dtype.as_numpy_dtype)\n var1_np = np.array([3.0, 4.0], dtype=dtype.as_numpy_dtype)\n grads1_np = np.array([0.01, 0.01], dtype=dtype.as_numpy_dtype)\n\n if use_resource:\n var0 = resource_variable_ops.ResourceVariable(var0_np)\n var1 = resource_variable_ops.ResourceVariable(var1_np)\n else:\n var0 = variables.Variable(var0_np)\n var1 = variables.Variable(var1_np)\n grads0_np_indices = np.array([0, 1], dtype=np.int32)\n grads0 = ops.IndexedSlices(\n constant_op.constant(grads0_np),\n constant_op.constant(grads0_np_indices), constant_op.constant([2]))\n grads1_np_indices = np.array([0, 1], dtype=np.int32)\n grads1 = ops.IndexedSlices(\n constant_op.constant(grads1_np),\n constant_op.constant(grads1_np_indices), constant_op.constant([2]))\n opt = adam.AdamOptimizer()\n update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))\n variables.global_variables_initializer().run()\n\n # Fetch params to validate initial values\n self.assertAllClose([1.0, 2.0], var0.eval())\n self.assertAllClose([3.0, 4.0], var1.eval())\n\n beta1_power, beta2_power = opt._get_beta_accumulators()\n\n # Run 3 steps of Adam\n for t in range(1, 4):\n self.assertAllCloseAccordingToType(0.9**t, beta1_power.eval())\n self.assertAllCloseAccordingToType(0.999**t, beta2_power.eval())\n update.run()\n\n var0_np, m0, v0 = adam_update_numpy(var0_np, grads0_np, t, m0, v0)\n var1_np, m1, v1 = adam_update_numpy(var1_np, grads1_np, t, m1, v1)\n\n # Validate updated params\n self.assertAllCloseAccordingToType(var0_np, var0.eval())\n self.assertAllCloseAccordingToType(var1_np, var1.eval())\n\n def testSparse(self):\n self.doTestSparse(use_resource=False)\n\n def testResourceSparse(self):\n self.doTestSparse(use_resource=True)\n\n def testSparseDevicePlacement(self):\n for index_dtype in [dtypes.int32, dtypes.int64]:\n with self.test_session(force_gpu=test.is_gpu_available()):\n # If a GPU is available, tests that all optimizer ops can be placed on\n # it (i.e. they have GPU kernels).\n var = variables.Variable([[1.0], [2.0]])\n indices = constant_op.constant([0, 1], dtype=index_dtype)\n gathered_sum = math_ops.reduce_sum(array_ops.gather(var, indices))\n optimizer = adam.AdamOptimizer(3.0)\n minimize_op = optimizer.minimize(gathered_sum)\n variables.global_variables_initializer().run()\n minimize_op.run()\n\n def testSparseRepeatedIndices(self):\n for dtype in [dtypes.half, dtypes.float32, dtypes.float64]:\n with self.test_session():\n repeated_index_update_var = variables.Variable(\n [[1.0], [2.0]], dtype=dtype)\n aggregated_update_var = variables.Variable(\n [[1.0], [2.0]], dtype=dtype)\n grad_repeated_index = ops.IndexedSlices(\n constant_op.constant(\n [0.1, 0.1], shape=[2, 1], dtype=dtype),\n constant_op.constant([1, 1]),\n constant_op.constant([2, 1]))\n grad_aggregated = ops.IndexedSlices(\n constant_op.constant(\n [0.2], shape=[1, 1], dtype=dtype),\n constant_op.constant([1]),\n constant_op.constant([2, 1]))\n repeated_update = adam.AdamOptimizer().apply_gradients(\n [(grad_repeated_index, repeated_index_update_var)])\n aggregated_update = adam.AdamOptimizer().apply_gradients(\n [(grad_aggregated, aggregated_update_var)])\n variables.global_variables_initializer().run()\n self.assertAllClose(aggregated_update_var.eval(),\n repeated_index_update_var.eval())\n for _ in range(3):\n repeated_update.run()\n aggregated_update.run()\n self.assertAllClose(aggregated_update_var.eval(),\n repeated_index_update_var.eval())\n\n def doTestBasic(self, use_resource=False):\n for i, dtype in enumerate([dtypes.half, dtypes.float32, dtypes.float64]):\n with self.test_session(graph=ops.Graph()):\n # Initialize variables for numpy implementation.\n m0, v0, m1, v1 = 0.0, 0.0, 0.0, 0.0\n var0_np = np.array([1.0, 2.0], dtype=dtype.as_numpy_dtype)\n grads0_np = np.array([0.1, 0.1], dtype=dtype.as_numpy_dtype)\n var1_np = np.array([3.0, 4.0], dtype=dtype.as_numpy_dtype)\n grads1_np = np.array([0.01, 0.01], dtype=dtype.as_numpy_dtype)\n\n if use_resource:\n var0 = resource_variable_ops.ResourceVariable(\n var0_np, name=\"var0_%d\" % i)\n var1 = resource_variable_ops.ResourceVariable(\n var1_np, name=\"var1_%d\" % i)\n else:\n var0 = variables.Variable(var0_np)\n var1 = variables.Variable(var1_np)\n grads0 = constant_op.constant(grads0_np)\n grads1 = constant_op.constant(grads1_np)\n\n opt = adam.AdamOptimizer()\n update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))\n opt_variables = opt.variables()\n self.assertIn(opt._beta1_power, opt_variables)\n self.assertIn(opt._beta2_power, opt_variables)\n\n with ops.Graph().as_default():\n # Shouldn't return non-slot variables from other graphs.\n self.assertEqual(0, len(opt.variables()))\n\n if context.in_graph_mode():\n self.evaluate(variables.global_variables_initializer())\n # Fetch params to validate initial values\n self.assertAllClose([1.0, 2.0], self.evaluate(var0))\n self.assertAllClose([3.0, 4.0], self.evaluate(var1))\n\n beta1_power, beta2_power = opt._get_beta_accumulators()\n\n # Run 3 steps of Adam\n for t in range(1, 4):\n if context.in_graph_mode():\n self.evaluate(update)\n elif t > 1:\n opt.apply_gradients(zip([grads0, grads1], [var0, var1]))\n\n self.assertAllCloseAccordingToType(0.9**(t + 1),\n self.evaluate(beta1_power))\n self.assertAllCloseAccordingToType(0.999**(t + 1),\n self.evaluate(beta2_power))\n\n var0_np, m0, v0 = adam_update_numpy(var0_np, grads0_np, t, m0, v0)\n var1_np, m1, v1 = adam_update_numpy(var1_np, grads1_np, t, m1, v1)\n\n # Validate updated params\n self.assertAllCloseAccordingToType(var0_np, self.evaluate(var0))\n self.assertAllCloseAccordingToType(var1_np, self.evaluate(var1))\n if use_resource:\n self.assertEqual(\"var0_%d/Adam:0\" % (i,),\n opt.get_slot(var=var0, name=\"m\").name)\n\n def testBasic(self):\n with self.test_session():\n self.doTestBasic(use_resource=False)\n\n @test_util.run_in_graph_and_eager_modes(reset_test=True)\n def testResourceBasic(self):\n self.doTestBasic(use_resource=True)\n\n def testTensorLearningRate(self):\n for dtype in [dtypes.half, dtypes.float32, dtypes.float64]:\n with self.test_session():\n # Initialize variables for numpy implementation.\n m0, v0, m1, v1 = 0.0, 0.0, 0.0, 0.0\n var0_np = np.array([1.0, 2.0], dtype=dtype.as_numpy_dtype)\n grads0_np = np.array([0.1, 0.1], dtype=dtype.as_numpy_dtype)\n var1_np = np.array([3.0, 4.0], dtype=dtype.as_numpy_dtype)\n grads1_np = np.array([0.01, 0.01], dtype=dtype.as_numpy_dtype)\n\n var0 = variables.Variable(var0_np)\n var1 = variables.Variable(var1_np)\n grads0 = constant_op.constant(grads0_np)\n grads1 = constant_op.constant(grads1_np)\n opt = adam.AdamOptimizer(constant_op.constant(0.001))\n update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))\n variables.global_variables_initializer().run()\n\n # Fetch params to validate initial values\n self.assertAllClose([1.0, 2.0], var0.eval())\n self.assertAllClose([3.0, 4.0], var1.eval())\n\n beta1_power, beta2_power = opt._get_beta_accumulators()\n\n # Run 3 steps of Adam\n for t in range(1, 4):\n self.assertAllCloseAccordingToType(0.9**t, beta1_power.eval())\n self.assertAllCloseAccordingToType(0.999**t, beta2_power.eval())\n update.run()\n\n var0_np, m0, v0 = adam_update_numpy(var0_np, grads0_np, t, m0, v0)\n var1_np, m1, v1 = adam_update_numpy(var1_np, grads1_np, t, m1, v1)\n\n # Validate updated params\n self.assertAllCloseAccordingToType(var0_np, var0.eval())\n self.assertAllCloseAccordingToType(var1_np, var1.eval())\n\n def testSharing(self):\n for dtype in [dtypes.half, dtypes.float32, dtypes.float64]:\n with self.test_session():\n # Initialize variables for numpy implementation.\n m0, v0, m1, v1 = 0.0, 0.0, 0.0, 0.0\n var0_np = np.array([1.0, 2.0], dtype=dtype.as_numpy_dtype)\n grads0_np = np.array([0.1, 0.1], dtype=dtype.as_numpy_dtype)\n var1_np = np.array([3.0, 4.0], dtype=dtype.as_numpy_dtype)\n grads1_np = np.array([0.01, 0.01], dtype=dtype.as_numpy_dtype)\n\n var0 = variables.Variable(var0_np)\n var1 = variables.Variable(var1_np)\n grads0 = constant_op.constant(grads0_np)\n grads1 = constant_op.constant(grads1_np)\n opt = adam.AdamOptimizer()\n update1 = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))\n update2 = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))\n variables.global_variables_initializer().run()\n\n beta1_power, beta2_power = opt._get_beta_accumulators()\n\n # Fetch params to validate initial values\n self.assertAllClose([1.0, 2.0], var0.eval())\n self.assertAllClose([3.0, 4.0], var1.eval())\n\n # Run 3 steps of intertwined Adam1 and Adam2.\n for t in range(1, 4):\n self.assertAllCloseAccordingToType(0.9**t, beta1_power.eval())\n self.assertAllCloseAccordingToType(0.999**t, beta2_power.eval())\n if t % 2 == 0:\n update1.run()\n else:\n update2.run()\n\n var0_np, m0, v0 = adam_update_numpy(var0_np, grads0_np, t, m0, v0)\n var1_np, m1, v1 = adam_update_numpy(var1_np, grads1_np, t, m1, v1)\n\n # Validate updated params\n self.assertAllCloseAccordingToType(var0_np, var0.eval())\n self.assertAllCloseAccordingToType(var1_np, var1.eval())\n\n def testTwoSessions(self):\n optimizer = adam.AdamOptimizer()\n g = ops.Graph()\n with g.as_default():\n with session.Session():\n var0 = variables.Variable(np.array([1.0, 2.0]), name=\"v0\")\n grads0 = constant_op.constant(np.array([0.1, 0.1]))\n optimizer.apply_gradients([(grads0, var0)])\n\n gg = ops.Graph()\n with gg.as_default():\n with session.Session():\n var0 = variables.Variable(np.array([1.0, 2.0]), name=\"v0\")\n grads0 = constant_op.constant(np.array([0.1, 0.1]))\n\n # If the optimizer saves any state not keyed by graph the following line\n # fails.\n optimizer.apply_gradients([(grads0, var0)])\n\n\nif __name__ == \"__main__\":\n test.main()\n", "# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"Test cases for the bfloat16 Python type.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport math\n\nimport numpy as np\n\n# pylint: disable=unused-import,g-bad-import-order\nfrom tensorflow.python import pywrap_tensorflow\nfrom tensorflow.python.platform import test\n\n\nbfloat16 = pywrap_tensorflow.TF_bfloat16_type()\n\n\nclass Bfloat16Test(test.TestCase):\n\n def float_values(self):\n \"\"\"Returns values that should round trip exactly to float and back.\"\"\"\n epsilon = float.fromhex(\"1.0p-7\")\n return [\n 0.0, 1.0, -1, 0.5, -0.5, epsilon, 1.0 + epsilon, 1.0 - epsilon,\n -1.0 - epsilon, -1.0 + epsilon, 3.5, 42.0, 255.0, 256.0,\n float(\"inf\"), float(\"-inf\"), float(\"nan\")]\n\n def _assertFloatIdentical(self, v, w):\n if math.isnan(v):\n self.assertTrue(math.isnan(w))\n else:\n self.assertEqual(v, w)\n\n def testRoundTripToFloat(self):\n for v in self.float_values():\n self._assertFloatIdentical(v, float(bfloat16(v)))\n\n def testRoundTripToInt(self):\n for v in [-256, -255, -34, -2, -1, 0, 1, 2, 10, 47, 128, 255, 256, 512]:\n self.assertEqual(v, int(bfloat16(v)))\n\n def testStr(self):\n self.assertEqual(\"0\", str(bfloat16(0.0)))\n self.assertEqual(\"1\", str(bfloat16(1.0)))\n self.assertEqual(\"-3.5\", str(bfloat16(-3.5)))\n self.assertEqual(\"0.0078125\", str(bfloat16(float.fromhex(\"1.0p-7\"))))\n self.assertEqual(\"inf\", str(bfloat16(float(\"inf\"))))\n self.assertEqual(\"-inf\", str(bfloat16(float(\"-inf\"))))\n self.assertEqual(\"nan\", str(bfloat16(float(\"nan\"))))\n\n def testRepr(self):\n self.assertEqual(\"bfloat16(0)\", repr(bfloat16(0)))\n self.assertEqual(\"bfloat16(1)\", repr(bfloat16(1)))\n self.assertEqual(\"bfloat16(-3.5)\", repr(bfloat16(-3.5)))\n self.assertEqual(\"bfloat16(0.0078125)\",\n repr(bfloat16(float.fromhex(\"1.0p-7\"))))\n self.assertEqual(\"bfloat16(inf)\", repr(bfloat16(float(\"inf\"))))\n self.assertEqual(\"bfloat16(-inf)\", repr(bfloat16(float(\"-inf\"))))\n self.assertEqual(\"bfloat16(nan)\", repr(bfloat16(float(\"nan\"))))\n\n def testHash(self):\n self.assertEqual(0, hash(bfloat16(0.0)))\n self.assertEqual(0x3f80, hash(bfloat16(1.0)))\n self.assertEqual(0x7fc0, hash(bfloat16(float(\"nan\"))))\n\n # Tests for Python operations\n def testNegate(self):\n for v in self.float_values():\n self._assertFloatIdentical(-v, float(-bfloat16(v)))\n\n def testAdd(self):\n self._assertFloatIdentical(0, float(bfloat16(0) + bfloat16(0)))\n self._assertFloatIdentical(1, float(bfloat16(1) + bfloat16(0)))\n self._assertFloatIdentical(0, float(bfloat16(1) + bfloat16(-1)))\n self._assertFloatIdentical(5.5, float(bfloat16(2) + bfloat16(3.5)))\n self._assertFloatIdentical(1.25, float(bfloat16(3.5) + bfloat16(-2.25)))\n self._assertFloatIdentical(float(\"inf\"),\n float(bfloat16(float(\"inf\")) + bfloat16(-2.25)))\n self._assertFloatIdentical(float(\"-inf\"),\n float(bfloat16(float(\"-inf\")) + bfloat16(-2.25)))\n self.assertTrue(math.isnan(float(bfloat16(3.5) + bfloat16(float(\"nan\")))))\n\n def testSub(self):\n self._assertFloatIdentical(0, float(bfloat16(0) - bfloat16(0)))\n self._assertFloatIdentical(1, float(bfloat16(1) - bfloat16(0)))\n self._assertFloatIdentical(2, float(bfloat16(1) - bfloat16(-1)))\n self._assertFloatIdentical(-1.5, float(bfloat16(2) - bfloat16(3.5)))\n self._assertFloatIdentical(5.75, float(bfloat16(3.5) - bfloat16(-2.25)))\n self._assertFloatIdentical(float(\"-inf\"),\n float(bfloat16(-2.25) - bfloat16(float(\"inf\"))))\n self._assertFloatIdentical(float(\"inf\"),\n float(bfloat16(-2.25) - bfloat16(float(\"-inf\"))))\n self.assertTrue(math.isnan(float(bfloat16(3.5) - bfloat16(float(\"nan\")))))\n\n def testMul(self):\n self._assertFloatIdentical(0, float(bfloat16(0) * bfloat16(0)))\n self._assertFloatIdentical(0, float(bfloat16(1) * bfloat16(0)))\n self._assertFloatIdentical(-1, float(bfloat16(1) * bfloat16(-1)))\n self._assertFloatIdentical(-7.875, float(bfloat16(3.5) * bfloat16(-2.25)))\n self._assertFloatIdentical(float(\"-inf\"),\n float(bfloat16(float(\"inf\")) * bfloat16(-2.25)))\n self._assertFloatIdentical(float(\"inf\"),\n float(bfloat16(float(\"-inf\")) * bfloat16(-2.25)))\n self.assertTrue(math.isnan(float(bfloat16(3.5) * bfloat16(float(\"nan\")))))\n\n def testDiv(self):\n self.assertTrue(math.isnan(float(bfloat16(0) / bfloat16(0))))\n self._assertFloatIdentical(float(\"inf\"), float(bfloat16(1) / bfloat16(0)))\n self._assertFloatIdentical(-1, float(bfloat16(1) / bfloat16(-1)))\n self._assertFloatIdentical(-1.75, float(bfloat16(3.5) / bfloat16(-2)))\n self._assertFloatIdentical(float(\"-inf\"),\n float(bfloat16(float(\"inf\")) / bfloat16(-2.25)))\n self._assertFloatIdentical(float(\"inf\"),\n float(bfloat16(float(\"-inf\")) / bfloat16(-2.25)))\n self.assertTrue(math.isnan(float(bfloat16(3.5) / bfloat16(float(\"nan\")))))\n\n def testLess(self):\n for v in self.float_values():\n for w in self.float_values():\n self.assertEqual(v < w, bfloat16(v) < bfloat16(w))\n\n def testLessEqual(self):\n for v in self.float_values():\n for w in self.float_values():\n self.assertEqual(v <= w, bfloat16(v) <= bfloat16(w))\n\n def testGreater(self):\n for v in self.float_values():\n for w in self.float_values():\n self.assertEqual(v > w, bfloat16(v) > bfloat16(w))\n\n def testGreaterEqual(self):\n for v in self.float_values():\n for w in self.float_values():\n self.assertEqual(v >= w, bfloat16(v) >= bfloat16(w))\n\n def testEqual(self):\n for v in self.float_values():\n for w in self.float_values():\n self.assertEqual(v == w, bfloat16(v) == bfloat16(w))\n\n def testNotEqual(self):\n for v in self.float_values():\n for w in self.float_values():\n self.assertEqual(v != w, bfloat16(v) != bfloat16(w))\n\n\nclass Bfloat16NumPyTest(test.TestCase):\n\n def testDtype(self):\n self.assertEqual(bfloat16, np.dtype(bfloat16))\n\n def testArray(self):\n x = np.array([[1, 2, 3]], dtype=bfloat16)\n self.assertEqual(bfloat16, x.dtype)\n self.assertEqual(\"[[bfloat16(1) bfloat16(2) bfloat16(3)]]\", str(x))\n self.assertAllEqual(x, x)\n self.assertAllClose(x, x)\n\n def testCasts(self):\n for dtype in [\n np.float16, np.float32, np.float64, np.int32, np.int64,\n np.complex64, np.complex128]:\n x = np.array([[1, 2, 3]], dtype=dtype)\n y = x.astype(bfloat16)\n z = y.astype(dtype)\n self.assertTrue(np.all(x == y))\n self.assertEqual(bfloat16, y.dtype)\n self.assertTrue(np.all(x == z))\n self.assertEqual(dtype, z.dtype)\n\n def testConformNumpyComplex(self):\n for dtype in [np.complex64, np.complex128]:\n x = np.array([1.1, 2.2 + 2.2j, 3.3], dtype=dtype)\n y_np = x.astype(np.float32)\n y_tf = x.astype(bfloat16)\n self.assertAllClose(y_np, y_tf, atol=2e-2)\n\n z_np = y_np.astype(dtype)\n z_tf = y_tf.astype(dtype)\n self.assertAllClose(z_np, z_tf, atol=2e-2)\n\n def testAdd(self):\n x = np.array([[1, 2, 3]], dtype=bfloat16)\n y = np.array([[4, 5, 6]], dtype=bfloat16)\n self.assertAllClose(np.array([[5, 7, 9]]), x + y)\n\n def testLogSumExp(self):\n x = np.array([[1, 2, 3]], dtype=np.float32)\n y = np.array([[4, 5, 6]], dtype=np.float32)\n self.assertAllClose(np.logaddexp(x, y),\n np.logaddexp(x.astype(bfloat16), y.astype(bfloat16)),\n atol=2e-2)\n\n\nif __name__ == \"__main__\":\n test.main()\n", "# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for the experimental input pipeline ops.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport gzip\nimport os\nimport zlib\n\nfrom tensorflow.contrib.data.python.kernel_tests import dataset_serialization_test_base\nfrom tensorflow.contrib.data.python.ops import readers\nfrom tensorflow.core.example import example_pb2\nfrom tensorflow.core.example import feature_pb2\nfrom tensorflow.python.data.ops import iterator_ops\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.lib.io import python_io\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import parsing_ops\nfrom tensorflow.python.platform import test\nfrom tensorflow.python.util import compat\n\n\nclass TextLineDatasetTestBase(test.TestCase):\n\n def _lineText(self, f, l):\n return compat.as_bytes(\"%d: %d\" % (f, l))\n\n def _createFiles(self,\n num_files,\n num_lines,\n crlf=False,\n compression_type=None):\n filenames = []\n for i in range(num_files):\n fn = os.path.join(self.get_temp_dir(), \"text_line.%d.txt\" % i)\n filenames.append(fn)\n contents = []\n for j in range(num_lines):\n contents.append(self._lineText(i, j))\n # Always include a newline after the record unless it is\n # at the end of the file, in which case we include it\n if j + 1 != num_lines or i == 0:\n contents.append(b\"\\r\\n\" if crlf else b\"\\n\")\n contents = b\"\".join(contents)\n\n if not compression_type:\n with open(fn, \"wb\") as f:\n f.write(contents)\n elif compression_type == \"GZIP\":\n with gzip.GzipFile(fn, \"wb\") as f:\n f.write(contents)\n elif compression_type == \"ZLIB\":\n contents = zlib.compress(contents)\n with open(fn, \"wb\") as f:\n f.write(contents)\n else:\n raise ValueError(\"Unsupported compression_type\", compression_type)\n\n return filenames\n\n\nclass TextLineDatasetTest(TextLineDatasetTestBase):\n\n def _testTextLineDataset(self, compression_type=None):\n test_filenames = self._createFiles(\n 2, 5, crlf=True, compression_type=compression_type)\n filenames = array_ops.placeholder(dtypes.string, shape=[None])\n num_epochs = array_ops.placeholder(dtypes.int64, shape=[])\n batch_size = array_ops.placeholder(dtypes.int64, shape=[])\n\n repeat_dataset = readers.TextLineDataset(\n filenames, compression_type=compression_type).repeat(num_epochs)\n batch_dataset = repeat_dataset.batch(batch_size)\n\n iterator = iterator_ops.Iterator.from_structure(batch_dataset.output_types)\n init_op = iterator.make_initializer(repeat_dataset)\n init_batch_op = iterator.make_initializer(batch_dataset)\n get_next = iterator.get_next()\n\n with self.test_session() as sess:\n # Basic test: read from file 0.\n sess.run(\n init_op, feed_dict={filenames: [test_filenames[0]],\n num_epochs: 1})\n for i in range(5):\n self.assertEqual(self._lineText(0, i), sess.run(get_next))\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(get_next)\n\n # Basic test: read from file 1.\n sess.run(\n init_op, feed_dict={filenames: [test_filenames[1]],\n num_epochs: 1})\n for i in range(5):\n self.assertEqual(self._lineText(1, i), sess.run(get_next))\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(get_next)\n\n # Basic test: read from both files.\n sess.run(init_op, feed_dict={filenames: test_filenames, num_epochs: 1})\n for j in range(2):\n for i in range(5):\n self.assertEqual(self._lineText(j, i), sess.run(get_next))\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(get_next)\n\n # Test repeated iteration through both files.\n sess.run(init_op, feed_dict={filenames: test_filenames, num_epochs: 10})\n for _ in range(10):\n for j in range(2):\n for i in range(5):\n self.assertEqual(self._lineText(j, i), sess.run(get_next))\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(get_next)\n\n # Test batched and repeated iteration through both files.\n sess.run(\n init_batch_op,\n feed_dict={filenames: test_filenames,\n num_epochs: 10,\n batch_size: 5})\n for _ in range(10):\n self.assertAllEqual([self._lineText(0, i) for i in range(5)],\n sess.run(get_next))\n self.assertAllEqual([self._lineText(1, i) for i in range(5)],\n sess.run(get_next))\n\n def testTextLineDatasetNoCompression(self):\n self._testTextLineDataset()\n\n def testTextLineDatasetGzipCompression(self):\n self._testTextLineDataset(compression_type=\"GZIP\")\n\n def testTextLineDatasetZlibCompression(self):\n self._testTextLineDataset(compression_type=\"ZLIB\")\n\n def testTextLineDatasetBuffering(self):\n test_filenames = self._createFiles(2, 5, crlf=True)\n\n repeat_dataset = readers.TextLineDataset(test_filenames, buffer_size=10)\n iterator = repeat_dataset.make_one_shot_iterator()\n\n with self.test_session() as sess:\n for j in range(2):\n for i in range(5):\n self.assertEqual(self._lineText(j, i), sess.run(iterator.get_next()))\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(iterator.get_next())\n\n\nclass TextLineDatasetSerializationTest(\n TextLineDatasetTestBase,\n dataset_serialization_test_base.DatasetSerializationTestBase):\n\n def _build_iterator_graph(self, test_filenames, compression_type=None):\n return readers.TextLineDataset(\n test_filenames, compression_type=compression_type, buffer_size=10)\n\n def testTextLineCore(self):\n compression_types = [None, \"GZIP\", \"ZLIB\"]\n num_files = 5\n lines_per_file = 5\n num_outputs = num_files * lines_per_file\n for compression_type in compression_types:\n test_filenames = self._createFiles(\n num_files,\n lines_per_file,\n crlf=True,\n compression_type=compression_type)\n # pylint: disable=cell-var-from-loop\n self.run_core_tests(\n lambda: self._build_iterator_graph(test_filenames, compression_type),\n lambda: self._build_iterator_graph(test_filenames), num_outputs)\n # pylint: enable=cell-var-from-loop\n\n\nclass FixedLengthRecordReaderTestBase(test.TestCase):\n\n def setUp(self):\n super(FixedLengthRecordReaderTestBase, self).setUp()\n self._num_files = 2\n self._num_records = 7\n self._header_bytes = 5\n self._record_bytes = 3\n self._footer_bytes = 2\n\n def _record(self, f, r):\n return compat.as_bytes(str(f * 2 + r) * self._record_bytes)\n\n def _createFiles(self):\n filenames = []\n for i in range(self._num_files):\n fn = os.path.join(self.get_temp_dir(), \"fixed_length_record.%d.txt\" % i)\n filenames.append(fn)\n with open(fn, \"wb\") as f:\n f.write(b\"H\" * self._header_bytes)\n for j in range(self._num_records):\n f.write(self._record(i, j))\n f.write(b\"F\" * self._footer_bytes)\n return filenames\n\n\nclass FixedLengthRecordReaderTest(FixedLengthRecordReaderTestBase):\n\n def testFixedLengthRecordDataset(self):\n test_filenames = self._createFiles()\n filenames = array_ops.placeholder(dtypes.string, shape=[None])\n num_epochs = array_ops.placeholder(dtypes.int64, shape=[])\n batch_size = array_ops.placeholder(dtypes.int64, shape=[])\n\n repeat_dataset = (readers.FixedLengthRecordDataset(\n filenames, self._record_bytes, self._header_bytes, self._footer_bytes)\n .repeat(num_epochs))\n batch_dataset = repeat_dataset.batch(batch_size)\n\n iterator = iterator_ops.Iterator.from_structure(batch_dataset.output_types)\n init_op = iterator.make_initializer(repeat_dataset)\n init_batch_op = iterator.make_initializer(batch_dataset)\n get_next = iterator.get_next()\n\n with self.test_session() as sess:\n # Basic test: read from file 0.\n sess.run(\n init_op, feed_dict={filenames: [test_filenames[0]],\n num_epochs: 1})\n for i in range(self._num_records):\n self.assertEqual(self._record(0, i), sess.run(get_next))\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(get_next)\n\n # Basic test: read from file 1.\n sess.run(\n init_op, feed_dict={filenames: [test_filenames[1]],\n num_epochs: 1})\n for i in range(self._num_records):\n self.assertEqual(self._record(1, i), sess.run(get_next))\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(get_next)\n\n # Basic test: read from both files.\n sess.run(init_op, feed_dict={filenames: test_filenames, num_epochs: 1})\n for j in range(self._num_files):\n for i in range(self._num_records):\n self.assertEqual(self._record(j, i), sess.run(get_next))\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(get_next)\n\n # Test repeated iteration through both files.\n sess.run(init_op, feed_dict={filenames: test_filenames, num_epochs: 10})\n for _ in range(10):\n for j in range(self._num_files):\n for i in range(self._num_records):\n self.assertEqual(self._record(j, i), sess.run(get_next))\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(get_next)\n\n # Test batched and repeated iteration through both files.\n sess.run(\n init_batch_op,\n feed_dict={\n filenames: test_filenames,\n num_epochs: 10,\n batch_size: self._num_records\n })\n for _ in range(10):\n for j in range(self._num_files):\n self.assertAllEqual(\n [self._record(j, i) for i in range(self._num_records)],\n sess.run(get_next))\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(get_next)\n\n def testFixedLengthRecordDatasetBuffering(self):\n test_filenames = self._createFiles()\n dataset = readers.FixedLengthRecordDataset(\n test_filenames,\n self._record_bytes,\n self._header_bytes,\n self._footer_bytes,\n buffer_size=10)\n iterator = dataset.make_one_shot_iterator()\n\n with self.test_session() as sess:\n for j in range(self._num_files):\n for i in range(self._num_records):\n self.assertEqual(self._record(j, i), sess.run(iterator.get_next()))\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(iterator.get_next())\n\n\nclass FixedLengthRecordDatasetSerializationTest(\n FixedLengthRecordReaderTestBase,\n dataset_serialization_test_base.DatasetSerializationTestBase):\n\n def _build_iterator_graph(self, num_epochs, compression_type=None):\n filenames = self._createFiles()\n return readers.FixedLengthRecordDataset(\n filenames, self._record_bytes, self._header_bytes,\n self._footer_bytes).repeat(num_epochs)\n\n def testFixedLengthRecordCore(self):\n num_epochs = 5\n num_outputs = num_epochs * self._num_files * self._num_records\n self.run_core_tests(lambda: self._build_iterator_graph(num_epochs),\n lambda: self._build_iterator_graph(num_epochs * 2),\n num_outputs)\n\n\nclass TFRecordDatasetTestBase(test.TestCase):\n\n def setUp(self):\n super(TFRecordDatasetTestBase, self).setUp()\n self._num_files = 2\n self._num_records = 7\n\n self.test_filenames = self._createFiles()\n\n self.filenames = array_ops.placeholder(dtypes.string, shape=[None])\n self.num_epochs = array_ops.placeholder_with_default(\n constant_op.constant(1, dtypes.int64), shape=[])\n self.compression_type = array_ops.placeholder_with_default(\"\", shape=[])\n self.batch_size = array_ops.placeholder(dtypes.int64, shape=[])\n\n repeat_dataset = readers.TFRecordDataset(self.filenames,\n self.compression_type).repeat(\n self.num_epochs)\n batch_dataset = repeat_dataset.batch(self.batch_size)\n\n iterator = iterator_ops.Iterator.from_structure(batch_dataset.output_types)\n self.init_op = iterator.make_initializer(repeat_dataset)\n self.init_batch_op = iterator.make_initializer(batch_dataset)\n self.get_next = iterator.get_next()\n\n def _record(self, f, r):\n return compat.as_bytes(\"Record %d of file %d\" % (r, f))\n\n def _createFiles(self):\n filenames = []\n for i in range(self._num_files):\n fn = os.path.join(self.get_temp_dir(), \"tf_record.%d.txt\" % i)\n filenames.append(fn)\n writer = python_io.TFRecordWriter(fn)\n for j in range(self._num_records):\n writer.write(self._record(i, j))\n writer.close()\n return filenames\n\n\nclass TFRecordDatasetTest(TFRecordDatasetTestBase):\n\n def testReadOneEpoch(self):\n with self.test_session() as sess:\n # Basic test: read from file 0.\n sess.run(\n self.init_op,\n feed_dict={\n self.filenames: [self.test_filenames[0]],\n self.num_epochs: 1\n })\n for i in range(self._num_records):\n self.assertAllEqual(self._record(0, i), sess.run(self.get_next))\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(self.get_next)\n\n # Basic test: read from file 1.\n sess.run(\n self.init_op,\n feed_dict={\n self.filenames: [self.test_filenames[1]],\n self.num_epochs: 1\n })\n for i in range(self._num_records):\n self.assertAllEqual(self._record(1, i), sess.run(self.get_next))\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(self.get_next)\n\n # Basic test: read from both files.\n sess.run(\n self.init_op,\n feed_dict={self.filenames: self.test_filenames,\n self.num_epochs: 1})\n for j in range(self._num_files):\n for i in range(self._num_records):\n self.assertAllEqual(self._record(j, i), sess.run(self.get_next))\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(self.get_next)\n\n def testReadTenEpochs(self):\n with self.test_session() as sess:\n sess.run(\n self.init_op,\n feed_dict={self.filenames: self.test_filenames,\n self.num_epochs: 10})\n for _ in range(10):\n for j in range(self._num_files):\n for i in range(self._num_records):\n self.assertAllEqual(self._record(j, i), sess.run(self.get_next))\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(self.get_next)\n\n def testReadTenEpochsOfBatches(self):\n with self.test_session() as sess:\n sess.run(\n self.init_batch_op,\n feed_dict={\n self.filenames: self.test_filenames,\n self.num_epochs: 10,\n self.batch_size: self._num_records\n })\n for _ in range(10):\n for j in range(self._num_files):\n values = sess.run(self.get_next)\n self.assertAllEqual(\n [self._record(j, i) for i in range(self._num_records)], values)\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(self.get_next)\n\n def testReadZlibFiles(self):\n zlib_files = []\n for i, fn in enumerate(self.test_filenames):\n with open(fn, \"rb\") as f:\n cdata = zlib.compress(f.read())\n\n zfn = os.path.join(self.get_temp_dir(), \"tfrecord_%s.z\" % i)\n with open(zfn, \"wb\") as f:\n f.write(cdata)\n zlib_files.append(zfn)\n\n with self.test_session() as sess:\n sess.run(\n self.init_op,\n feed_dict={self.filenames: zlib_files,\n self.compression_type: \"ZLIB\"})\n for j in range(self._num_files):\n for i in range(self._num_records):\n self.assertAllEqual(self._record(j, i), sess.run(self.get_next))\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(self.get_next)\n\n def testReadGzipFiles(self):\n gzip_files = []\n for i, fn in enumerate(self.test_filenames):\n with open(fn, \"rb\") as f:\n gzfn = os.path.join(self.get_temp_dir(), \"tfrecord_%s.gz\" % i)\n with gzip.GzipFile(gzfn, \"wb\") as gzf:\n gzf.write(f.read())\n gzip_files.append(gzfn)\n\n with self.test_session() as sess:\n sess.run(\n self.init_op,\n feed_dict={self.filenames: gzip_files,\n self.compression_type: \"GZIP\"})\n for j in range(self._num_files):\n for i in range(self._num_records):\n self.assertAllEqual(self._record(j, i), sess.run(self.get_next))\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(self.get_next)\n\n def testReadWithBuffer(self):\n one_mebibyte = 2**20\n d = readers.TFRecordDataset(self.test_filenames, buffer_size=one_mebibyte)\n iterator = d.make_one_shot_iterator()\n with self.test_session() as sess:\n for j in range(self._num_files):\n for i in range(self._num_records):\n self.assertAllEqual(self._record(j, i), sess.run(iterator.get_next()))\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(iterator.get_next())\n\n\nclass TFRecordDatasetSerializationTest(\n TFRecordDatasetTestBase,\n dataset_serialization_test_base.DatasetSerializationTestBase):\n\n def _build_iterator_graph(self,\n num_epochs,\n batch_size=1,\n compression_type=None,\n buffer_size=None):\n filenames = self._createFiles()\n if compression_type is \"ZLIB\":\n zlib_files = []\n for i, fn in enumerate(filenames):\n with open(fn, \"rb\") as f:\n cdata = zlib.compress(f.read())\n zfn = os.path.join(self.get_temp_dir(), \"tfrecord_%s.z\" % i)\n with open(zfn, \"wb\") as f:\n f.write(cdata)\n zlib_files.append(zfn)\n filenames = zlib_files\n\n elif compression_type is \"GZIP\":\n gzip_files = []\n for i, fn in enumerate(self.test_filenames):\n with open(fn, \"rb\") as f:\n gzfn = os.path.join(self.get_temp_dir(), \"tfrecord_%s.gz\" % i)\n with gzip.GzipFile(gzfn, \"wb\") as gzf:\n gzf.write(f.read())\n gzip_files.append(gzfn)\n filenames = gzip_files\n\n return readers.TFRecordDataset(\n filenames, compression_type,\n buffer_size=buffer_size).repeat(num_epochs).batch(batch_size)\n\n def testTFRecordWithoutBufferCore(self):\n num_epochs = 5\n batch_size = num_epochs\n num_outputs = num_epochs * self._num_files * self._num_records // batch_size\n # pylint: disable=g-long-lambda\n self.run_core_tests(\n lambda: self._build_iterator_graph(num_epochs, batch_size,\n buffer_size=0),\n lambda: self._build_iterator_graph(num_epochs * 2, batch_size),\n num_outputs)\n self.run_core_tests(\n lambda: self._build_iterator_graph(num_epochs, buffer_size=0), None,\n num_outputs * batch_size)\n # pylint: enable=g-long-lambda\n\n def testTFRecordWithBufferCore(self):\n num_epochs = 5\n num_outputs = num_epochs * self._num_files * self._num_records\n self.run_core_tests(lambda: self._build_iterator_graph(num_epochs),\n lambda: self._build_iterator_graph(num_epochs * 2),\n num_outputs)\n\n def testTFRecordWithCompressionCore(self):\n num_epochs = 5\n num_outputs = num_epochs * self._num_files * self._num_records\n self.run_core_tests(\n lambda: self._build_iterator_graph(num_epochs, compression_type=\"ZLIB\"),\n lambda: self._build_iterator_graph(num_epochs * 2), num_outputs)\n self.run_core_tests(\n lambda: self._build_iterator_graph(num_epochs, compression_type=\"GZIP\"),\n lambda: self._build_iterator_graph(num_epochs * 2), num_outputs)\n\n\nclass ReadBatchFeaturesTest(test.TestCase):\n\n def setUp(self):\n super(ReadBatchFeaturesTest, self).setUp()\n self._num_files = 2\n self._num_records = 7\n self.test_filenames = self._createFiles()\n\n def _read_batch_features(self, filenames, num_epochs, batch_size):\n self.filenames = filenames\n self.num_epochs = num_epochs\n self.batch_size = batch_size\n\n return readers.read_batch_features(\n file_pattern=self.filenames,\n batch_size=self.batch_size,\n features={\n \"file\": parsing_ops.FixedLenFeature([], dtypes.int64),\n \"record\": parsing_ops.FixedLenFeature([], dtypes.int64),\n \"keywords\": parsing_ops.VarLenFeature(dtypes.string)\n },\n reader=readers.TFRecordDataset,\n randomize_input=False,\n num_epochs=self.num_epochs)\n\n def _record(self, f, r):\n example = example_pb2.Example(features=feature_pb2.Features(\n feature={\n \"file\":\n feature_pb2.Feature(int64_list=feature_pb2.Int64List(\n value=[f])),\n \"record\":\n feature_pb2.Feature(int64_list=feature_pb2.Int64List(\n value=[r])),\n \"keywords\":\n feature_pb2.Feature(bytes_list=feature_pb2.BytesList(\n value=self._get_keywords(f, r)))\n }))\n return example.SerializeToString()\n\n def _get_keywords(self, f, r):\n num_keywords = 1 + (f + r) % 2\n keywords = []\n for index in range(num_keywords):\n keywords.append(compat.as_bytes(\"keyword%d\" % index))\n return keywords\n\n def _createFiles(self):\n filenames = []\n for i in range(self._num_files):\n fn = os.path.join(self.get_temp_dir(), \"tf_record.%d.txt\" % i)\n filenames.append(fn)\n writer = python_io.TFRecordWriter(fn)\n for j in range(self._num_records):\n writer.write(self._record(i, j))\n writer.close()\n return filenames\n\n def _next_actual_batch(self, sess):\n file_op = self.outputs[\"file\"]\n keywords_indices_op = self.outputs[\"keywords\"].indices\n keywords_values_op = self.outputs[\"keywords\"].values\n keywords_dense_shape_op = self.outputs[\"keywords\"].dense_shape\n record_op = self.outputs[\"record\"]\n return sess.run([\n file_op, keywords_indices_op, keywords_values_op,\n keywords_dense_shape_op, record_op\n ])\n\n def _next_expected_batch(self, file_indices, batch_size, num_epochs):\n\n def _next_record(file_indices):\n for j in file_indices:\n for i in range(self._num_records):\n yield j, i\n\n file_batch = []\n keywords_batch_indices = []\n keywords_batch_values = []\n keywords_batch_max_len = 0\n record_batch = []\n batch_index = 0\n for _ in range(num_epochs):\n for record in _next_record(file_indices):\n f = record[0]\n r = record[1]\n file_batch.append(f)\n record_batch.append(r)\n keywords = self._get_keywords(f, r)\n keywords_batch_values.extend(keywords)\n keywords_batch_indices.extend([[batch_index, i]\n for i in range(len(keywords))])\n batch_index += 1\n keywords_batch_max_len = max(keywords_batch_max_len, len(keywords))\n if len(file_batch) == batch_size:\n yield [\n file_batch, keywords_batch_indices, keywords_batch_values,\n [batch_size, keywords_batch_max_len], record_batch\n ]\n file_batch = []\n keywords_batch_indices = []\n keywords_batch_values = []\n keywords_batch_max_len = 0\n record_batch = []\n batch_index = 0\n if file_batch:\n yield [\n file_batch, keywords_batch_indices, keywords_batch_values,\n [len(file_batch), keywords_batch_max_len], record_batch\n ]\n\n def _verify_records(self, sess, batch_size, file_index=None, num_epochs=1):\n if file_index is not None:\n file_indices = [file_index]\n else:\n file_indices = range(self._num_files)\n\n for expected_batch in self._next_expected_batch(file_indices, batch_size,\n num_epochs):\n actual_batch = self._next_actual_batch(sess)\n for i in range(len(expected_batch)):\n self.assertAllEqual(expected_batch[i], actual_batch[i])\n\n def testRead(self):\n for batch_size in [1, 2]:\n for num_epochs in [1, 10]:\n with ops.Graph().as_default() as g:\n with self.test_session(graph=g) as sess:\n # Basic test: read from file 0.\n self.outputs = self._read_batch_features(\n filenames=self.test_filenames[0],\n num_epochs=num_epochs,\n batch_size=batch_size)\n self._verify_records(sess, batch_size, 0, num_epochs=num_epochs)\n with self.assertRaises(errors.OutOfRangeError):\n self._next_actual_batch(sess)\n\n with ops.Graph().as_default() as g:\n with self.test_session(graph=g) as sess:\n # Basic test: read from file 1.\n self.outputs = self._read_batch_features(\n filenames=self.test_filenames[1],\n num_epochs=num_epochs,\n batch_size=batch_size)\n self._verify_records(sess, batch_size, 1, num_epochs=num_epochs)\n with self.assertRaises(errors.OutOfRangeError):\n self._next_actual_batch(sess)\n\n with ops.Graph().as_default() as g:\n with self.test_session(graph=g) as sess:\n # Basic test: read from both files.\n self.outputs = self._read_batch_features(\n filenames=self.test_filenames,\n num_epochs=num_epochs,\n batch_size=batch_size)\n self._verify_records(sess, batch_size, num_epochs=num_epochs)\n with self.assertRaises(errors.OutOfRangeError):\n self._next_actual_batch(sess)\n\n def testReadWithEquivalentDataset(self):\n # TODO(mrry): Add support for tf.SparseTensor as a Dataset component.\n features = {\n \"file\": parsing_ops.FixedLenFeature([], dtypes.int64),\n \"record\": parsing_ops.FixedLenFeature([], dtypes.int64),\n }\n dataset = (readers.TFRecordDataset(self.test_filenames)\n .map(lambda x: parsing_ops.parse_single_example(x, features))\n .repeat(10).batch(2))\n iterator = dataset.make_initializable_iterator()\n init_op = iterator.initializer\n next_element = iterator.get_next()\n\n with self.test_session() as sess:\n sess.run(init_op)\n for file_batch, _, _, _, record_batch in self._next_expected_batch(\n range(self._num_files), 2, 10):\n actual_batch = sess.run(next_element)\n self.assertAllEqual(file_batch, actual_batch[\"file\"])\n self.assertAllEqual(record_batch, actual_batch[\"record\"])\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(next_element)\n\n\nif __name__ == \"__main__\":\n test.main()\n", "# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Keras convolution layers and image transformation layers.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.keras._impl.keras import activations\nfrom tensorflow.python.keras._impl.keras import backend as K\nfrom tensorflow.python.keras._impl.keras import constraints\nfrom tensorflow.python.keras._impl.keras import initializers\nfrom tensorflow.python.keras._impl.keras import regularizers\nfrom tensorflow.python.keras._impl.keras.engine import InputSpec\nfrom tensorflow.python.keras._impl.keras.engine import Layer\n# imports for backwards namespace compatibility\n# pylint: disable=unused-import\nfrom tensorflow.python.keras._impl.keras.layers.pooling import AveragePooling1D\nfrom tensorflow.python.keras._impl.keras.layers.pooling import AveragePooling2D\nfrom tensorflow.python.keras._impl.keras.layers.pooling import AveragePooling3D\nfrom tensorflow.python.keras._impl.keras.layers.pooling import MaxPooling1D\nfrom tensorflow.python.keras._impl.keras.layers.pooling import MaxPooling2D\nfrom tensorflow.python.keras._impl.keras.layers.pooling import MaxPooling3D\n# pylint: enable=unused-import\nfrom tensorflow.python.keras._impl.keras.utils import conv_utils\nfrom tensorflow.python.layers import convolutional as tf_convolutional_layers\n\n\nclass Conv1D(tf_convolutional_layers.Conv1D, Layer):\n \"\"\"1D convolution layer (e.g. temporal convolution).\n\n This layer creates a convolution kernel that is convolved\n with the layer input over a single spatial (or temporal) dimension\n to produce a tensor of outputs.\n If `use_bias` is True, a bias vector is created and added to the outputs.\n Finally, if `activation` is not `None`,\n it is applied to the outputs as well.\n\n When using this layer as the first layer in a model,\n provide an `input_shape` argument\n (tuple of integers or `None`, e.g.\n `(10, 128)` for sequences of 10 vectors of 128-dimensional vectors,\n or `(None, 128)` for variable-length sequences of 128-dimensional vectors.\n\n Arguments:\n filters: Integer, the dimensionality of the output space\n (i.e. the number output of filters in the convolution).\n kernel_size: An integer or tuple/list of a single integer,\n specifying the length of the 1D convolution window.\n strides: An integer or tuple/list of a single integer,\n specifying the stride length of the convolution.\n Specifying any stride value != 1 is incompatible with specifying\n any `dilation_rate` value != 1.\n padding: One of `\"valid\"`, `\"causal\"` or `\"same\"` (case-insensitive).\n `\"causal\"` results in causal (dilated) convolutions, e.g. output[t]\n does not depend on input[t+1:]. Useful when modeling temporal data\n where the model should not violate the temporal order.\n See [WaveNet: A Generative Model for Raw Audio, section\n 2.1](https://arxiv.org/abs/1609.03499).\n dilation_rate: an integer or tuple/list of a single integer, specifying\n the dilation rate to use for dilated convolution.\n Currently, specifying any `dilation_rate` value != 1 is\n incompatible with specifying any `strides` value != 1.\n activation: Activation function to use.\n If you don't specify anything, no activation is applied\n (ie. \"linear\" activation: `a(x) = x`).\n use_bias: Boolean, whether the layer uses a bias vector.\n kernel_initializer: Initializer for the `kernel` weights matrix.\n bias_initializer: Initializer for the bias vector.\n kernel_regularizer: Regularizer function applied to\n the `kernel` weights matrix.\n bias_regularizer: Regularizer function applied to the bias vector.\n activity_regularizer: Regularizer function applied to\n the output of the layer (its \"activation\")..\n kernel_constraint: Constraint function applied to the kernel matrix.\n bias_constraint: Constraint function applied to the bias vector.\n\n Input shape:\n 3D tensor with shape: `(batch_size, steps, input_dim)`\n\n Output shape:\n 3D tensor with shape: `(batch_size, new_steps, filters)`\n `steps` value might have changed due to padding or strides.\n \"\"\"\n\n def __init__(self,\n filters,\n kernel_size,\n strides=1,\n padding='valid',\n dilation_rate=1,\n activation=None,\n use_bias=True,\n kernel_initializer='glorot_uniform',\n bias_initializer='zeros',\n kernel_regularizer=None,\n bias_regularizer=None,\n activity_regularizer=None,\n kernel_constraint=None,\n bias_constraint=None,\n **kwargs):\n super(Conv1D, self).__init__(\n filters=filters,\n kernel_size=kernel_size,\n strides=strides,\n padding=padding,\n data_format='channels_last',\n dilation_rate=dilation_rate,\n activation=activations.get(activation),\n use_bias=use_bias,\n kernel_initializer=initializers.get(kernel_initializer),\n bias_initializer=initializers.get(bias_initializer),\n kernel_regularizer=regularizers.get(kernel_regularizer),\n bias_regularizer=regularizers.get(bias_regularizer),\n activity_regularizer=regularizers.get(activity_regularizer),\n kernel_constraint=constraints.get(kernel_constraint),\n bias_constraint=constraints.get(bias_constraint),\n **kwargs)\n\n def get_config(self):\n config = {\n 'filters': self.filters,\n 'kernel_size': self.kernel_size,\n 'strides': self.strides,\n 'padding': self.padding,\n 'dilation_rate': self.dilation_rate,\n 'activation': activations.serialize(self.activation),\n 'use_bias': self.use_bias,\n 'kernel_initializer': initializers.serialize(self.kernel_initializer),\n 'bias_initializer': initializers.serialize(self.bias_initializer),\n 'kernel_regularizer': regularizers.serialize(self.kernel_regularizer),\n 'bias_regularizer': regularizers.serialize(self.bias_regularizer),\n 'activity_regularizer':\n regularizers.serialize(self.activity_regularizer),\n 'kernel_constraint': constraints.serialize(self.kernel_constraint),\n 'bias_constraint': constraints.serialize(self.bias_constraint)\n }\n base_config = super(Conv1D, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\nclass Conv2D(tf_convolutional_layers.Conv2D, Layer):\n \"\"\"2D convolution layer (e.g. spatial convolution over images).\n\n This layer creates a convolution kernel that is convolved\n with the layer input to produce a tensor of\n outputs. If `use_bias` is True,\n a bias vector is created and added to the outputs. Finally, if\n `activation` is not `None`, it is applied to the outputs as well.\n\n When using this layer as the first layer in a model,\n provide the keyword argument `input_shape`\n (tuple of integers, does not include the sample axis),\n e.g. `input_shape=(128, 128, 3)` for 128x128 RGB pictures\n in `data_format=\"channels_last\"`.\n\n Arguments:\n filters: Integer, the dimensionality of the output space\n (i.e. the number output of filters in the convolution).\n kernel_size: An integer or tuple/list of 2 integers, specifying the\n width and height of the 2D convolution window.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n strides: An integer or tuple/list of 2 integers,\n specifying the strides of the convolution along the width and height.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n Specifying any stride value != 1 is incompatible with specifying\n any `dilation_rate` value != 1.\n padding: one of `\"valid\"` or `\"same\"` (case-insensitive).\n data_format: A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, height, width, channels)` while `channels_first`\n corresponds to inputs with shape\n `(batch, channels, height, width)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".\n dilation_rate: an integer or tuple/list of 2 integers, specifying\n the dilation rate to use for dilated convolution.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n Currently, specifying any `dilation_rate` value != 1 is\n incompatible with specifying any stride value != 1.\n activation: Activation function to use.\n If you don't specify anything, no activation is applied\n (ie. \"linear\" activation: `a(x) = x`).\n use_bias: Boolean, whether the layer uses a bias vector.\n kernel_initializer: Initializer for the `kernel` weights matrix.\n bias_initializer: Initializer for the bias vector.\n kernel_regularizer: Regularizer function applied to\n the `kernel` weights matrix.\n bias_regularizer: Regularizer function applied to the bias vector.\n activity_regularizer: Regularizer function applied to\n the output of the layer (its \"activation\")..\n kernel_constraint: Constraint function applied to the kernel matrix.\n bias_constraint: Constraint function applied to the bias vector.\n\n Input shape:\n 4D tensor with shape:\n `(samples, channels, rows, cols)` if data_format='channels_first'\n or 4D tensor with shape:\n `(samples, rows, cols, channels)` if data_format='channels_last'.\n\n Output shape:\n 4D tensor with shape:\n `(samples, filters, new_rows, new_cols)` if data_format='channels_first'\n or 4D tensor with shape:\n `(samples, new_rows, new_cols, filters)` if data_format='channels_last'.\n `rows` and `cols` values might have changed due to padding.\n \"\"\"\n\n def __init__(self,\n filters,\n kernel_size,\n strides=(1, 1),\n padding='valid',\n data_format=None,\n dilation_rate=(1, 1),\n activation=None,\n use_bias=True,\n kernel_initializer='glorot_uniform',\n bias_initializer='zeros',\n kernel_regularizer=None,\n bias_regularizer=None,\n activity_regularizer=None,\n kernel_constraint=None,\n bias_constraint=None,\n **kwargs):\n if data_format is None:\n data_format = K.image_data_format()\n super(Conv2D, self).__init__(\n filters=filters,\n kernel_size=kernel_size,\n strides=strides,\n padding=padding,\n data_format=data_format,\n dilation_rate=dilation_rate,\n activation=activations.get(activation),\n use_bias=use_bias,\n kernel_initializer=initializers.get(kernel_initializer),\n bias_initializer=initializers.get(bias_initializer),\n kernel_regularizer=regularizers.get(kernel_regularizer),\n bias_regularizer=regularizers.get(bias_regularizer),\n activity_regularizer=regularizers.get(activity_regularizer),\n kernel_constraint=constraints.get(kernel_constraint),\n bias_constraint=constraints.get(bias_constraint),\n **kwargs)\n\n def get_config(self):\n config = {\n 'filters': self.filters,\n 'kernel_size': self.kernel_size,\n 'strides': self.strides,\n 'padding': self.padding,\n 'data_format': self.data_format,\n 'dilation_rate': self.dilation_rate,\n 'activation': activations.serialize(self.activation),\n 'use_bias': self.use_bias,\n 'kernel_initializer': initializers.serialize(self.kernel_initializer),\n 'bias_initializer': initializers.serialize(self.bias_initializer),\n 'kernel_regularizer': regularizers.serialize(self.kernel_regularizer),\n 'bias_regularizer': regularizers.serialize(self.bias_regularizer),\n 'activity_regularizer':\n regularizers.serialize(self.activity_regularizer),\n 'kernel_constraint': constraints.serialize(self.kernel_constraint),\n 'bias_constraint': constraints.serialize(self.bias_constraint)\n }\n base_config = super(Conv2D, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\nclass Conv3D(tf_convolutional_layers.Conv3D, Layer):\n \"\"\"3D convolution layer (e.g. spatial convolution over volumes).\n\n This layer creates a convolution kernel that is convolved\n with the layer input to produce a tensor of\n outputs. If `use_bias` is True,\n a bias vector is created and added to the outputs. Finally, if\n `activation` is not `None`, it is applied to the outputs as well.\n\n When using this layer as the first layer in a model,\n provide the keyword argument `input_shape`\n (tuple of integers, does not include the sample axis),\n e.g. `input_shape=(128, 128, 128, 1)` for 128x128x128 volumes\n with a single channel,\n in `data_format=\"channels_last\"`.\n\n Arguments:\n filters: Integer, the dimensionality of the output space\n (i.e. the number output of filters in the convolution).\n kernel_size: An integer or tuple/list of 3 integers, specifying the\n depth, height and width of the 3D convolution window.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n strides: An integer or tuple/list of 3 integers,\n specifying the strides of the convolution along each spatial\n dimension.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n Specifying any stride value != 1 is incompatible with specifying\n any `dilation_rate` value != 1.\n padding: one of `\"valid\"` or `\"same\"` (case-insensitive).\n data_format: A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, spatial_dim1, spatial_dim2, spatial_dim3, channels)`\n while `channels_first` corresponds to inputs with shape\n `(batch, channels, spatial_dim1, spatial_dim2, spatial_dim3)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".\n dilation_rate: an integer or tuple/list of 3 integers, specifying\n the dilation rate to use for dilated convolution.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n Currently, specifying any `dilation_rate` value != 1 is\n incompatible with specifying any stride value != 1.\n activation: Activation function to use.\n If you don't specify anything, no activation is applied\n (ie. \"linear\" activation: `a(x) = x`).\n use_bias: Boolean, whether the layer uses a bias vector.\n kernel_initializer: Initializer for the `kernel` weights matrix.\n bias_initializer: Initializer for the bias vector.\n kernel_regularizer: Regularizer function applied to\n the `kernel` weights matrix.\n bias_regularizer: Regularizer function applied to the bias vector.\n activity_regularizer: Regularizer function applied to\n the output of the layer (its \"activation\")..\n kernel_constraint: Constraint function applied to the kernel matrix.\n bias_constraint: Constraint function applied to the bias vector.\n\n Input shape:\n 5D tensor with shape:\n `(samples, channels, conv_dim1, conv_dim2, conv_dim3)` if\n data_format='channels_first'\n or 5D tensor with shape:\n `(samples, conv_dim1, conv_dim2, conv_dim3, channels)` if\n data_format='channels_last'.\n\n Output shape:\n 5D tensor with shape:\n `(samples, filters, new_conv_dim1, new_conv_dim2, new_conv_dim3)` if\n data_format='channels_first'\n or 5D tensor with shape:\n `(samples, new_conv_dim1, new_conv_dim2, new_conv_dim3, filters)` if\n data_format='channels_last'.\n `new_conv_dim1`, `new_conv_dim2` and `new_conv_dim3` values might have\n changed due to padding.\n \"\"\"\n\n def __init__(self,\n filters,\n kernel_size,\n strides=(1, 1, 1),\n padding='valid',\n data_format=None,\n dilation_rate=(1, 1, 1),\n activation=None,\n use_bias=True,\n kernel_initializer='glorot_uniform',\n bias_initializer='zeros',\n kernel_regularizer=None,\n bias_regularizer=None,\n activity_regularizer=None,\n kernel_constraint=None,\n bias_constraint=None,\n **kwargs):\n if data_format is None:\n data_format = K.image_data_format()\n super(Conv3D, self).__init__(\n filters=filters,\n kernel_size=kernel_size,\n strides=strides,\n padding=padding,\n data_format=data_format,\n dilation_rate=dilation_rate,\n activation=activations.get(activation),\n use_bias=use_bias,\n kernel_initializer=initializers.get(kernel_initializer),\n bias_initializer=initializers.get(bias_initializer),\n kernel_regularizer=regularizers.get(kernel_regularizer),\n bias_regularizer=regularizers.get(bias_regularizer),\n activity_regularizer=regularizers.get(activity_regularizer),\n kernel_constraint=constraints.get(kernel_constraint),\n bias_constraint=constraints.get(bias_constraint),\n **kwargs)\n\n def get_config(self):\n config = {\n 'filters': self.filters,\n 'kernel_size': self.kernel_size,\n 'strides': self.strides,\n 'padding': self.padding,\n 'data_format': self.data_format,\n 'dilation_rate': self.dilation_rate,\n 'activation': activations.serialize(self.activation),\n 'use_bias': self.use_bias,\n 'kernel_initializer': initializers.serialize(self.kernel_initializer),\n 'bias_initializer': initializers.serialize(self.bias_initializer),\n 'kernel_regularizer': regularizers.serialize(self.kernel_regularizer),\n 'bias_regularizer': regularizers.serialize(self.bias_regularizer),\n 'activity_regularizer':\n regularizers.serialize(self.activity_regularizer),\n 'kernel_constraint': constraints.serialize(self.kernel_constraint),\n 'bias_constraint': constraints.serialize(self.bias_constraint)\n }\n base_config = super(Conv3D, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\nclass Conv2DTranspose(tf_convolutional_layers.Conv2DTranspose, Layer):\n \"\"\"Transposed convolution layer (sometimes called Deconvolution).\n\n The need for transposed convolutions generally arises\n from the desire to use a transformation going in the opposite direction\n of a normal convolution, i.e., from something that has the shape of the\n output of some convolution to something that has the shape of its input\n while maintaining a connectivity pattern that is compatible with\n said convolution.\n\n When using this layer as the first layer in a model,\n provide the keyword argument `input_shape`\n (tuple of integers, does not include the sample axis),\n e.g. `input_shape=(128, 128, 3)` for 128x128 RGB pictures\n in `data_format=\"channels_last\"`.\n\n Arguments:\n filters: Integer, the dimensionality of the output space\n (i.e. the number of output filters in the convolution).\n kernel_size: An integer or tuple/list of 2 integers, specifying the\n width and height of the 2D convolution window.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n strides: An integer or tuple/list of 2 integers,\n specifying the strides of the convolution along the width and height.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n Specifying any stride value != 1 is incompatible with specifying\n any `dilation_rate` value != 1.\n padding: one of `\"valid\"` or `\"same\"` (case-insensitive).\n data_format: A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, height, width, channels)` while `channels_first`\n corresponds to inputs with shape\n `(batch, channels, height, width)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".\n dilation_rate: an integer or tuple/list of 2 integers, specifying\n the dilation rate to use for dilated convolution.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n Currently, specifying any `dilation_rate` value != 1 is\n incompatible with specifying any stride value != 1.\n activation: Activation function to use.\n If you don't specify anything, no activation is applied\n (ie. \"linear\" activation: `a(x) = x`).\n use_bias: Boolean, whether the layer uses a bias vector.\n kernel_initializer: Initializer for the `kernel` weights matrix.\n bias_initializer: Initializer for the bias vector.\n kernel_regularizer: Regularizer function applied to\n the `kernel` weights matrix.\n bias_regularizer: Regularizer function applied to the bias vector.\n activity_regularizer: Regularizer function applied to\n the output of the layer (its \"activation\")..\n kernel_constraint: Constraint function applied to the kernel matrix.\n bias_constraint: Constraint function applied to the bias vector.\n\n Input shape:\n 4D tensor with shape:\n `(batch, channels, rows, cols)` if data_format='channels_first'\n or 4D tensor with shape:\n `(batch, rows, cols, channels)` if data_format='channels_last'.\n\n Output shape:\n 4D tensor with shape:\n `(batch, filters, new_rows, new_cols)` if data_format='channels_first'\n or 4D tensor with shape:\n `(batch, new_rows, new_cols, filters)` if data_format='channels_last'.\n `rows` and `cols` values might have changed due to padding.\n\n References:\n - [A guide to convolution arithmetic for deep\n learning](https://arxiv.org/abs/1603.07285v1)\n - [Deconvolutional\n Networks](http://www.matthewzeiler.com/pubs/cvpr2010/cvpr2010.pdf)\n \"\"\"\n\n def __init__(self,\n filters,\n kernel_size,\n strides=(1, 1),\n padding='valid',\n data_format=None,\n activation=None,\n use_bias=True,\n kernel_initializer='glorot_uniform',\n bias_initializer='zeros',\n kernel_regularizer=None,\n bias_regularizer=None,\n activity_regularizer=None,\n kernel_constraint=None,\n bias_constraint=None,\n **kwargs):\n if data_format is None:\n data_format = K.image_data_format()\n super(Conv2DTranspose, self).__init__(\n filters=filters,\n kernel_size=kernel_size,\n strides=strides,\n padding=padding,\n data_format=data_format,\n activation=activations.get(activation),\n use_bias=use_bias,\n kernel_initializer=initializers.get(kernel_initializer),\n bias_initializer=initializers.get(bias_initializer),\n kernel_regularizer=regularizers.get(kernel_regularizer),\n bias_regularizer=regularizers.get(bias_regularizer),\n activity_regularizer=regularizers.get(activity_regularizer),\n kernel_constraint=constraints.get(kernel_constraint),\n bias_constraint=constraints.get(bias_constraint),\n **kwargs)\n\n def get_config(self):\n config = {\n 'filters': self.filters,\n 'kernel_size': self.kernel_size,\n 'strides': self.strides,\n 'padding': self.padding,\n 'data_format': self.data_format,\n 'activation': activations.serialize(self.activation),\n 'use_bias': self.use_bias,\n 'kernel_initializer': initializers.serialize(self.kernel_initializer),\n 'bias_initializer': initializers.serialize(self.bias_initializer),\n 'kernel_regularizer': regularizers.serialize(self.kernel_regularizer),\n 'bias_regularizer': regularizers.serialize(self.bias_regularizer),\n 'activity_regularizer':\n regularizers.serialize(self.activity_regularizer),\n 'kernel_constraint': constraints.serialize(self.kernel_constraint),\n 'bias_constraint': constraints.serialize(self.bias_constraint)\n }\n base_config = super(Conv2DTranspose, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\nclass Conv3DTranspose(tf_convolutional_layers.Conv3D, Layer):\n \"\"\"Transposed convolution layer (sometimes called Deconvolution).\n\n The need for transposed convolutions generally arises\n from the desire to use a transformation going in the opposite direction\n of a normal convolution, i.e., from something that has the shape of the\n output of some convolution to something that has the shape of its input\n while maintaining a connectivity pattern that is compatible with\n said convolution.\n\n When using this layer as the first layer in a model,\n provide the keyword argument `input_shape`\n (tuple of integers, does not include the sample axis),\n e.g. `input_shape=(128, 128, 128, 3)` for a 128x128x128 volume with 3 channels\n if `data_format=\"channels_last\"`.\n\n Arguments:\n filters: Integer, the dimensionality of the output space\n (i.e. the number of output filters in the convolution).\n kernel_size: An integer or tuple/list of 3 integers, specifying the\n depth, height and width of the 3D convolution window.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n strides: An integer or tuple/list of 3 integers,\n specifying the strides of the convolution along the depth, height\n and width.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n Specifying any stride value != 1 is incompatible with specifying\n any `dilation_rate` value != 1.\n padding: one of `\"valid\"` or `\"same\"` (case-insensitive).\n data_format: A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, depth, height, width, channels)` while `channels_first`\n corresponds to inputs with shape\n `(batch, channels, depth, height, width)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".\n dilation_rate: an integer or tuple/list of 3 integers, specifying\n the dilation rate to use for dilated convolution.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n Currently, specifying any `dilation_rate` value != 1 is\n incompatible with specifying any stride value != 1.\n activation: Activation function to use\n (see [activations](../activations.md)).\n If you don't specify anything, no activation is applied\n (ie. \"linear\" activation: `a(x) = x`).\n use_bias: Boolean, whether the layer uses a bias vector.\n kernel_initializer: Initializer for the `kernel` weights matrix\n (see [initializers](../initializers.md)).\n bias_initializer: Initializer for the bias vector\n (see [initializers](../initializers.md)).\n kernel_regularizer: Regularizer function applied to\n the `kernel` weights matrix\n (see [regularizer](../regularizers.md)).\n bias_regularizer: Regularizer function applied to the bias vector\n (see [regularizer](../regularizers.md)).\n activity_regularizer: Regularizer function applied to\n the output of the layer (its \"activation\").\n (see [regularizer](../regularizers.md)).\n kernel_constraint: Constraint function applied to the kernel matrix\n (see [constraints](../constraints.md)).\n bias_constraint: Constraint function applied to the bias vector\n (see [constraints](../constraints.md)).\n\n Input shape:\n 5D tensor with shape:\n `(batch, channels, depth, rows, cols)` if data_format='channels_first'\n or 5D tensor with shape:\n `(batch, depth, rows, cols, channels)` if data_format='channels_last'.\n\n Output shape:\n 5D tensor with shape:\n `(batch, filters, new_depth, new_rows, new_cols)` if\n data_format='channels_first'\n or 5D tensor with shape:\n `(batch, new_depth, new_rows, new_cols, filters)` if\n data_format='channels_last'.\n `depth` and `rows` and `cols` values might have changed due to padding.\n\n References:\n - [A guide to convolution arithmetic for deep\n learning](https://arxiv.org/abs/1603.07285v1)\n - [Deconvolutional\n Networks](http://www.matthewzeiler.com/pubs/cvpr2010/cvpr2010.pdf)\n \"\"\"\n\n def __init__(self,\n filters,\n kernel_size,\n strides=(1, 1, 1),\n padding='valid',\n data_format=None,\n activation=None,\n use_bias=True,\n kernel_initializer='glorot_uniform',\n bias_initializer='zeros',\n kernel_regularizer=None,\n bias_regularizer=None,\n activity_regularizer=None,\n kernel_constraint=None,\n bias_constraint=None,\n **kwargs):\n if data_format is None:\n data_format = K.image_data_format()\n super(Conv3DTranspose, self).__init__(\n filters=filters,\n kernel_size=kernel_size,\n strides=strides,\n padding=padding,\n data_format=data_format,\n activation=activations.get(activation),\n use_bias=use_bias,\n kernel_initializer=initializers.get(kernel_initializer),\n bias_initializer=initializers.get(bias_initializer),\n kernel_regularizer=regularizers.get(kernel_regularizer),\n bias_regularizer=regularizers.get(bias_regularizer),\n activity_regularizer=regularizers.get(activity_regularizer),\n kernel_constraint=constraints.get(kernel_constraint),\n bias_constraint=constraints.get(bias_constraint),\n **kwargs)\n\n def get_config(self):\n config = {\n 'filters': self.filters,\n 'kernel_size': self.kernel_size,\n 'strides': self.strides,\n 'padding': self.padding,\n 'data_format': self.data_format,\n 'activation': activations.serialize(self.activation),\n 'use_bias': self.use_bias,\n 'kernel_initializer': initializers.serialize(self.kernel_initializer),\n 'bias_initializer': initializers.serialize(self.bias_initializer),\n 'kernel_regularizer': regularizers.serialize(self.kernel_regularizer),\n 'bias_regularizer': regularizers.serialize(self.bias_regularizer),\n 'activity_regularizer':\n regularizers.serialize(self.activity_regularizer),\n 'kernel_constraint': constraints.serialize(self.kernel_constraint),\n 'bias_constraint': constraints.serialize(self.bias_constraint)\n }\n base_config = super(Conv3DTranspose, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\nclass SeparableConv2D(tf_convolutional_layers.SeparableConv2D, Layer):\n \"\"\"Depthwise separable 2D convolution.\n\n Separable convolutions consist in first performing\n a depthwise spatial convolution\n (which acts on each input channel separately)\n followed by a pointwise convolution which mixes together the resulting\n output channels. The `depth_multiplier` argument controls how many\n output channels are generated per input channel in the depthwise step.\n\n Intuitively, separable convolutions can be understood as\n a way to factorize a convolution kernel into two smaller kernels,\n or as an extreme version of an Inception block.\n\n Arguments:\n filters: Integer, the dimensionality of the output space\n (i.e. the number output of filters in the convolution).\n kernel_size: An integer or tuple/list of 2 integers, specifying the\n width and height of the 2D convolution window.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n strides: An integer or tuple/list of 2 integers,\n specifying the strides of the convolution along the width and height.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n Specifying any stride value != 1 is incompatible with specifying\n any `dilation_rate` value != 1.\n padding: one of `\"valid\"` or `\"same\"` (case-insensitive).\n data_format: A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, height, width, channels)` while `channels_first`\n corresponds to inputs with shape\n `(batch, channels, height, width)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".\n depth_multiplier: The number of depthwise convolution output channels\n for each input channel.\n The total number of depthwise convolution output\n channels will be equal to `filterss_in * depth_multiplier`.\n activation: Activation function to use.\n If you don't specify anything, no activation is applied\n (ie. \"linear\" activation: `a(x) = x`).\n use_bias: Boolean, whether the layer uses a bias vector.\n depthwise_initializer: Initializer for the depthwise kernel matrix.\n pointwise_initializer: Initializer for the pointwise kernel matrix.\n bias_initializer: Initializer for the bias vector.\n depthwise_regularizer: Regularizer function applied to\n the depthwise kernel matrix.\n pointwise_regularizer: Regularizer function applied to\n the pointwise kernel matrix.\n bias_regularizer: Regularizer function applied to the bias vector.\n activity_regularizer: Regularizer function applied to\n the output of the layer (its \"activation\")..\n depthwise_constraint: Constraint function applied to\n the depthwise kernel matrix.\n pointwise_constraint: Constraint function applied to\n the pointwise kernel matrix.\n bias_constraint: Constraint function applied to the bias vector.\n\n Input shape:\n 4D tensor with shape:\n `(batch, channels, rows, cols)` if data_format='channels_first'\n or 4D tensor with shape:\n `(batch, rows, cols, channels)` if data_format='channels_last'.\n\n Output shape:\n 4D tensor with shape:\n `(batch, filters, new_rows, new_cols)` if data_format='channels_first'\n or 4D tensor with shape:\n `(batch, new_rows, new_cols, filters)` if data_format='channels_last'.\n `rows` and `cols` values might have changed due to padding.\n \"\"\"\n\n def __init__(self,\n filters,\n kernel_size,\n strides=(1, 1),\n padding='valid',\n data_format=None,\n dilation_rate=1,\n depth_multiplier=1,\n activation=None,\n use_bias=True,\n depthwise_initializer='glorot_uniform',\n pointwise_initializer='glorot_uniform',\n bias_initializer='zeros',\n depthwise_regularizer=None,\n pointwise_regularizer=None,\n bias_regularizer=None,\n activity_regularizer=None,\n depthwise_constraint=None,\n pointwise_constraint=None,\n bias_constraint=None,\n **kwargs):\n if data_format is None:\n data_format = K.image_data_format()\n super(SeparableConv2D, self).__init__(\n filters=filters,\n kernel_size=kernel_size,\n strides=strides,\n padding=padding,\n data_format=data_format,\n dilation_rate=dilation_rate,\n activation=activations.get(activation),\n use_bias=use_bias,\n depthwise_initializer=initializers.get(depthwise_initializer),\n pointwise_initializer=initializers.get(pointwise_initializer),\n bias_initializer=initializers.get(bias_initializer),\n depthwise_regularizer=regularizers.get(depthwise_regularizer),\n pointwise_regularizer=regularizers.get(pointwise_regularizer),\n bias_regularizer=regularizers.get(bias_regularizer),\n activity_regularizer=regularizers.get(activity_regularizer),\n depthwise_constraint=constraints.get(depthwise_constraint),\n pointwise_constraint=constraints.get(pointwise_constraint),\n bias_constraint=constraints.get(bias_constraint),\n **kwargs)\n\n def get_config(self):\n config = {\n 'filters':\n self.filters,\n 'kernel_size':\n self.kernel_size,\n 'strides':\n self.strides,\n 'padding':\n self.padding,\n 'data_format':\n self.data_format,\n 'dilation_rate':\n self.dilation_rate,\n 'activation':\n activations.serialize(self.activation),\n 'use_bias':\n self.use_bias,\n 'depthwise_initializer':\n initializers.serialize(self.depthwise_initializer),\n 'pointwise_initializer':\n initializers.serialize(self.pointwise_initializer),\n 'bias_initializer':\n initializers.serialize(self.bias_initializer),\n 'depthwise_regularizer':\n regularizers.serialize(self.depthwise_regularizer),\n 'pointwise_regularizer':\n regularizers.serialize(self.pointwise_regularizer),\n 'bias_regularizer':\n regularizers.serialize(self.bias_regularizer),\n 'activity_regularizer':\n regularizers.serialize(self.activity_regularizer),\n 'depthwise_constraint':\n constraints.serialize(self.depthwise_constraint),\n 'pointwise_constraint':\n constraints.serialize(self.pointwise_constraint),\n 'bias_constraint':\n constraints.serialize(self.bias_constraint)\n }\n base_config = super(SeparableConv2D, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\nclass UpSampling1D(Layer):\n \"\"\"Upsampling layer for 1D inputs.\n\n Repeats each temporal step `size` times along the time axis.\n\n Arguments:\n size: integer. Upsampling factor.\n\n Input shape:\n 3D tensor with shape: `(batch, steps, features)`.\n\n Output shape:\n 3D tensor with shape: `(batch, upsampled_steps, features)`.\n \"\"\"\n\n def __init__(self, size=2, **kwargs):\n super(UpSampling1D, self).__init__(**kwargs)\n self.size = int(size)\n self.input_spec = InputSpec(ndim=3)\n\n def _compute_output_shape(self, input_shape):\n input_shape = tensor_shape.TensorShape(input_shape).as_list()\n size = self.size * input_shape[1] if input_shape[1] is not None else None\n return tensor_shape.TensorShape([input_shape[0], size, input_shape[2]])\n\n def call(self, inputs):\n output = K.repeat_elements(inputs, self.size, axis=1)\n return output\n\n def get_config(self):\n config = {'size': self.size}\n base_config = super(UpSampling1D, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\nclass UpSampling2D(Layer):\n \"\"\"Upsampling layer for 2D inputs.\n\n Repeats the rows and columns of the data\n by size[0] and size[1] respectively.\n\n Arguments:\n size: int, or tuple of 2 integers.\n The upsampling factors for rows and columns.\n data_format: A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, height, width, channels)` while `channels_first`\n corresponds to inputs with shape\n `(batch, channels, height, width)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".\n\n Input shape:\n 4D tensor with shape:\n - If `data_format` is `\"channels_last\"`:\n `(batch, rows, cols, channels)`\n - If `data_format` is `\"channels_first\"`:\n `(batch, channels, rows, cols)`\n\n Output shape:\n 4D tensor with shape:\n - If `data_format` is `\"channels_last\"`:\n `(batch, upsampled_rows, upsampled_cols, channels)`\n - If `data_format` is `\"channels_first\"`:\n `(batch, channels, upsampled_rows, upsampled_cols)`\n \"\"\"\n\n def __init__(self, size=(2, 2), data_format=None, **kwargs):\n super(UpSampling2D, self).__init__(**kwargs)\n self.data_format = conv_utils.normalize_data_format(data_format)\n self.size = conv_utils.normalize_tuple(size, 2, 'size')\n self.input_spec = InputSpec(ndim=4)\n\n def _compute_output_shape(self, input_shape):\n input_shape = tensor_shape.TensorShape(input_shape).as_list()\n if self.data_format == 'channels_first':\n height = self.size[0] * input_shape[\n 2] if input_shape[2] is not None else None\n width = self.size[1] * input_shape[\n 3] if input_shape[3] is not None else None\n return tensor_shape.TensorShape(\n [input_shape[0], input_shape[1], height, width])\n else:\n height = self.size[0] * input_shape[\n 1] if input_shape[1] is not None else None\n width = self.size[1] * input_shape[\n 2] if input_shape[2] is not None else None\n return tensor_shape.TensorShape(\n [input_shape[0], height, width, input_shape[3]])\n\n def call(self, inputs):\n return K.resize_images(inputs, self.size[0], self.size[1], self.data_format)\n\n def get_config(self):\n config = {'size': self.size, 'data_format': self.data_format}\n base_config = super(UpSampling2D, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\nclass UpSampling3D(Layer):\n \"\"\"Upsampling layer for 3D inputs.\n\n Repeats the 1st, 2nd and 3rd dimensions\n of the data by size[0], size[1] and size[2] respectively.\n\n Arguments:\n size: int, or tuple of 3 integers.\n The upsampling factors for dim1, dim2 and dim3.\n data_format: A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, spatial_dim1, spatial_dim2, spatial_dim3, channels)`\n while `channels_first` corresponds to inputs with shape\n `(batch, channels, spatial_dim1, spatial_dim2, spatial_dim3)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".\n\n Input shape:\n 5D tensor with shape:\n - If `data_format` is `\"channels_last\"`:\n `(batch, dim1, dim2, dim3, channels)`\n - If `data_format` is `\"channels_first\"`:\n `(batch, channels, dim1, dim2, dim3)`\n\n Output shape:\n 5D tensor with shape:\n - If `data_format` is `\"channels_last\"`:\n `(batch, upsampled_dim1, upsampled_dim2, upsampled_dim3, channels)`\n - If `data_format` is `\"channels_first\"`:\n `(batch, channels, upsampled_dim1, upsampled_dim2, upsampled_dim3)`\n \"\"\"\n\n def __init__(self, size=(2, 2, 2), data_format=None, **kwargs):\n self.data_format = conv_utils.normalize_data_format(data_format)\n self.size = conv_utils.normalize_tuple(size, 3, 'size')\n self.input_spec = InputSpec(ndim=5)\n super(UpSampling3D, self).__init__(**kwargs)\n\n def _compute_output_shape(self, input_shape):\n input_shape = tensor_shape.TensorShape(input_shape).as_list()\n if self.data_format == 'channels_first':\n dim1 = self.size[0] * input_shape[\n 2] if input_shape[2] is not None else None\n dim2 = self.size[1] * input_shape[\n 3] if input_shape[3] is not None else None\n dim3 = self.size[2] * input_shape[\n 4] if input_shape[4] is not None else None\n return tensor_shape.TensorShape(\n [input_shape[0], input_shape[1], dim1, dim2, dim3])\n else:\n dim1 = self.size[0] * input_shape[\n 1] if input_shape[1] is not None else None\n dim2 = self.size[1] * input_shape[\n 2] if input_shape[2] is not None else None\n dim3 = self.size[2] * input_shape[\n 3] if input_shape[3] is not None else None\n return tensor_shape.TensorShape(\n [input_shape[0], dim1, dim2, dim3, input_shape[4]])\n\n def call(self, inputs):\n return K.resize_volumes(inputs, self.size[0], self.size[1], self.size[2],\n self.data_format)\n\n def get_config(self):\n config = {'size': self.size, 'data_format': self.data_format}\n base_config = super(UpSampling3D, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\nclass ZeroPadding1D(Layer):\n \"\"\"Zero-padding layer for 1D input (e.g. temporal sequence).\n\n Arguments:\n padding: int, or tuple of int (length 2), or dictionary.\n - If int:\n How many zeros to add at the beginning and end of\n the padding dimension (axis 1).\n - If tuple of int (length 2):\n How many zeros to add at the beginning and at the end of\n the padding dimension (`(left_pad, right_pad)`).\n\n Input shape:\n 3D tensor with shape `(batch, axis_to_pad, features)`\n\n Output shape:\n 3D tensor with shape `(batch, padded_axis, features)`\n \"\"\"\n\n def __init__(self, padding=1, **kwargs):\n super(ZeroPadding1D, self).__init__(**kwargs)\n self.padding = conv_utils.normalize_tuple(padding, 2, 'padding')\n self.input_spec = InputSpec(ndim=3)\n\n def _compute_output_shape(self, input_shape):\n if input_shape[1] is not None:\n length = input_shape[1] + self.padding[0] + self.padding[1]\n else:\n length = None\n return tensor_shape.TensorShape([input_shape[0], length, input_shape[2]])\n\n def call(self, inputs):\n return K.temporal_padding(inputs, padding=self.padding)\n\n def get_config(self):\n config = {'padding': self.padding}\n base_config = super(ZeroPadding1D, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\nclass ZeroPadding2D(Layer):\n \"\"\"Zero-padding layer for 2D input (e.g. picture).\n\n This layer can add rows and columns of zeros\n at the top, bottom, left and right side of an image tensor.\n\n Arguments:\n padding: int, or tuple of 2 ints, or tuple of 2 tuples of 2 ints.\n - If int: the same symmetric padding\n is applied to width and height.\n - If tuple of 2 ints:\n interpreted as two different\n symmetric padding values for height and width:\n `(symmetric_height_pad, symmetric_width_pad)`.\n - If tuple of 2 tuples of 2 ints:\n interpreted as\n `((top_pad, bottom_pad), (left_pad, right_pad))`\n data_format: A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, height, width, channels)` while `channels_first`\n corresponds to inputs with shape\n `(batch, channels, height, width)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".\n\n Input shape:\n 4D tensor with shape:\n - If `data_format` is `\"channels_last\"`:\n `(batch, rows, cols, channels)`\n - If `data_format` is `\"channels_first\"`:\n `(batch, channels, rows, cols)`\n\n Output shape:\n 4D tensor with shape:\n - If `data_format` is `\"channels_last\"`:\n `(batch, padded_rows, padded_cols, channels)`\n - If `data_format` is `\"channels_first\"`:\n `(batch, channels, padded_rows, padded_cols)`\n \"\"\"\n\n def __init__(self, padding=(1, 1), data_format=None, **kwargs):\n super(ZeroPadding2D, self).__init__(**kwargs)\n self.data_format = conv_utils.normalize_data_format(data_format)\n if isinstance(padding, int):\n self.padding = ((padding, padding), (padding, padding))\n elif hasattr(padding, '__len__'):\n if len(padding) != 2:\n raise ValueError('`padding` should have two elements. '\n 'Found: ' + str(padding))\n height_padding = conv_utils.normalize_tuple(padding[0], 2,\n '1st entry of padding')\n width_padding = conv_utils.normalize_tuple(padding[1], 2,\n '2nd entry of padding')\n self.padding = (height_padding, width_padding)\n else:\n raise ValueError('`padding` should be either an int, '\n 'a tuple of 2 ints '\n '(symmetric_height_pad, symmetric_width_pad), '\n 'or a tuple of 2 tuples of 2 ints '\n '((top_pad, bottom_pad), (left_pad, right_pad)). '\n 'Found: ' + str(padding))\n self.input_spec = InputSpec(ndim=4)\n\n def _compute_output_shape(self, input_shape):\n input_shape = tensor_shape.TensorShape(input_shape).as_list()\n if self.data_format == 'channels_first':\n if input_shape[2] is not None:\n rows = input_shape[2] + self.padding[0][0] + self.padding[0][1]\n else:\n rows = None\n if input_shape[3] is not None:\n cols = input_shape[3] + self.padding[1][0] + self.padding[1][1]\n else:\n cols = None\n return tensor_shape.TensorShape(\n [input_shape[0], input_shape[1], rows, cols])\n elif self.data_format == 'channels_last':\n if input_shape[1] is not None:\n rows = input_shape[1] + self.padding[0][0] + self.padding[0][1]\n else:\n rows = None\n if input_shape[2] is not None:\n cols = input_shape[2] + self.padding[1][0] + self.padding[1][1]\n else:\n cols = None\n return tensor_shape.TensorShape(\n [input_shape[0], rows, cols, input_shape[3]])\n\n def call(self, inputs):\n return K.spatial_2d_padding(\n inputs, padding=self.padding, data_format=self.data_format)\n\n def get_config(self):\n config = {'padding': self.padding, 'data_format': self.data_format}\n base_config = super(ZeroPadding2D, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\nclass ZeroPadding3D(Layer):\n \"\"\"Zero-padding layer for 3D data (spatial or spatio-temporal).\n\n Arguments:\n padding: int, or tuple of 2 ints, or tuple of 2 tuples of 2 ints.\n - If int: the same symmetric padding\n is applied to width and height.\n - If tuple of 2 ints:\n interpreted as two different\n symmetric padding values for height and width:\n `(symmetric_dim1_pad, symmetric_dim2_pad, symmetric_dim3_pad)`.\n - If tuple of 2 tuples of 2 ints:\n interpreted as\n `((left_dim1_pad, right_dim1_pad), (left_dim2_pad,\n right_dim2_pad), (left_dim3_pad, right_dim3_pad))`\n data_format: A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, spatial_dim1, spatial_dim2, spatial_dim3, channels)`\n while `channels_first` corresponds to inputs with shape\n `(batch, channels, spatial_dim1, spatial_dim2, spatial_dim3)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".\n\n Input shape:\n 5D tensor with shape:\n - If `data_format` is `\"channels_last\"`:\n `(batch, first_axis_to_pad, second_axis_to_pad, third_axis_to_pad,\n depth)`\n - If `data_format` is `\"channels_first\"`:\n `(batch, depth, first_axis_to_pad, second_axis_to_pad,\n third_axis_to_pad)`\n\n Output shape:\n 5D tensor with shape:\n - If `data_format` is `\"channels_last\"`:\n `(batch, first_padded_axis, second_padded_axis, third_axis_to_pad,\n depth)`\n - If `data_format` is `\"channels_first\"`:\n `(batch, depth, first_padded_axis, second_padded_axis,\n third_axis_to_pad)`\n \"\"\"\n\n def __init__(self, padding=(1, 1, 1), data_format=None, **kwargs):\n super(ZeroPadding3D, self).__init__(**kwargs)\n self.data_format = conv_utils.normalize_data_format(data_format)\n if isinstance(padding, int):\n self.padding = ((padding, padding), (padding, padding), (padding,\n padding))\n elif hasattr(padding, '__len__'):\n if len(padding) != 3:\n raise ValueError('`padding` should have 3 elements. '\n 'Found: ' + str(padding))\n dim1_padding = conv_utils.normalize_tuple(padding[0], 2,\n '1st entry of padding')\n dim2_padding = conv_utils.normalize_tuple(padding[1], 2,\n '2nd entry of padding')\n dim3_padding = conv_utils.normalize_tuple(padding[2], 2,\n '3rd entry of padding')\n self.padding = (dim1_padding, dim2_padding, dim3_padding)\n else:\n raise ValueError(\n '`padding` should be either an int, '\n 'a tuple of 3 ints '\n '(symmetric_dim1_pad, symmetric_dim2_pad, symmetric_dim3_pad), '\n 'or a tuple of 3 tuples of 2 ints '\n '((left_dim1_pad, right_dim1_pad),'\n ' (left_dim2_pad, right_dim2_pad),'\n ' (left_dim3_pad, right_dim2_pad)). '\n 'Found: ' + str(padding))\n self.input_spec = InputSpec(ndim=5)\n\n def _compute_output_shape(self, input_shape):\n input_shape = tensor_shape.TensorShape(input_shape).as_list()\n if self.data_format == 'channels_first':\n if input_shape[2] is not None:\n dim1 = input_shape[2] + 2 * self.padding[0][0]\n else:\n dim1 = None\n if input_shape[3] is not None:\n dim2 = input_shape[3] + 2 * self.padding[1][0]\n else:\n dim2 = None\n if input_shape[4] is not None:\n dim3 = input_shape[4] + 2 * self.padding[2][0]\n else:\n dim3 = None\n return tensor_shape.TensorShape(\n [input_shape[0], input_shape[1], dim1, dim2, dim3])\n elif self.data_format == 'channels_last':\n if input_shape[1] is not None:\n dim1 = input_shape[1] + 2 * self.padding[0][1]\n else:\n dim1 = None\n if input_shape[2] is not None:\n dim2 = input_shape[2] + 2 * self.padding[1][1]\n else:\n dim2 = None\n if input_shape[3] is not None:\n dim3 = input_shape[3] + 2 * self.padding[2][1]\n else:\n dim3 = None\n return tensor_shape.TensorShape(\n [input_shape[0], dim1, dim2, dim3, input_shape[4]])\n\n def call(self, inputs):\n return K.spatial_3d_padding(\n inputs, padding=self.padding, data_format=self.data_format)\n\n def get_config(self):\n config = {'padding': self.padding, 'data_format': self.data_format}\n base_config = super(ZeroPadding3D, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\nclass Cropping1D(Layer):\n \"\"\"Cropping layer for 1D input (e.g. temporal sequence).\n\n It crops along the time dimension (axis 1).\n\n Arguments:\n cropping: int or tuple of int (length 2)\n How many units should be trimmed off at the beginning and end of\n the cropping dimension (axis 1).\n If a single int is provided,\n the same value will be used for both.\n\n Input shape:\n 3D tensor with shape `(batch, axis_to_crop, features)`\n\n Output shape:\n 3D tensor with shape `(batch, cropped_axis, features)`\n \"\"\"\n\n def __init__(self, cropping=(1, 1), **kwargs):\n super(Cropping1D, self).__init__(**kwargs)\n self.cropping = conv_utils.normalize_tuple(cropping, 2, 'cropping')\n self.input_spec = InputSpec(ndim=3)\n\n def _compute_output_shape(self, input_shape):\n input_shape = tensor_shape.TensorShape(input_shape).as_list()\n if input_shape[1] is not None:\n length = input_shape[1] - self.cropping[0] - self.cropping[1]\n else:\n length = None\n return tensor_shape.TensorShape([input_shape[0], length, input_shape[2]])\n\n def call(self, inputs):\n if self.cropping[1] == 0:\n return inputs[:, self.cropping[0]:, :]\n else:\n return inputs[:, self.cropping[0]:-self.cropping[1], :]\n\n def get_config(self):\n config = {'cropping': self.cropping}\n base_config = super(Cropping1D, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\nclass Cropping2D(Layer):\n \"\"\"Cropping layer for 2D input (e.g. picture).\n\n It crops along spatial dimensions, i.e. width and height.\n\n Arguments:\n cropping: int, or tuple of 2 ints, or tuple of 2 tuples of 2 ints.\n - If int: the same symmetric cropping\n is applied to width and height.\n - If tuple of 2 ints:\n interpreted as two different\n symmetric cropping values for height and width:\n `(symmetric_height_crop, symmetric_width_crop)`.\n - If tuple of 2 tuples of 2 ints:\n interpreted as\n `((top_crop, bottom_crop), (left_crop, right_crop))`\n data_format: A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, height, width, channels)` while `channels_first`\n corresponds to inputs with shape\n `(batch, channels, height, width)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".\n\n Input shape:\n 4D tensor with shape:\n - If `data_format` is `\"channels_last\"`:\n `(batch, rows, cols, channels)`\n - If `data_format` is `\"channels_first\"`:\n `(batch, channels, rows, cols)`\n\n Output shape:\n 4D tensor with shape:\n - If `data_format` is `\"channels_last\"`:\n `(batch, cropped_rows, cropped_cols, channels)`\n - If `data_format` is `\"channels_first\"`:\n `(batch, channels, cropped_rows, cropped_cols)`\n\n Examples:\n\n ```python\n # Crop the input 2D images or feature maps\n model = Sequential()\n model.add(Cropping2D(cropping=((2, 2), (4, 4)),\n input_shape=(28, 28, 3)))\n # now model.output_shape == (None, 24, 20, 3)\n model.add(Conv2D(64, (3, 3), padding='same))\n model.add(Cropping2D(cropping=((2, 2), (2, 2))))\n # now model.output_shape == (None, 20, 16. 64)\n ```\n \"\"\"\n\n def __init__(self, cropping=((0, 0), (0, 0)), data_format=None, **kwargs):\n super(Cropping2D, self).__init__(**kwargs)\n self.data_format = conv_utils.normalize_data_format(data_format)\n if isinstance(cropping, int):\n self.cropping = ((cropping, cropping), (cropping, cropping))\n elif hasattr(cropping, '__len__'):\n if len(cropping) != 2:\n raise ValueError('`cropping` should have two elements. '\n 'Found: ' + str(cropping))\n height_cropping = conv_utils.normalize_tuple(cropping[0], 2,\n '1st entry of cropping')\n width_cropping = conv_utils.normalize_tuple(cropping[1], 2,\n '2nd entry of cropping')\n self.cropping = (height_cropping, width_cropping)\n else:\n raise ValueError('`cropping` should be either an int, '\n 'a tuple of 2 ints '\n '(symmetric_height_crop, symmetric_width_crop), '\n 'or a tuple of 2 tuples of 2 ints '\n '((top_crop, bottom_crop), (left_crop, right_crop)). '\n 'Found: ' + str(cropping))\n self.input_spec = InputSpec(ndim=4)\n\n def _compute_output_shape(self, input_shape):\n input_shape = tensor_shape.TensorShape(input_shape).as_list()\n # pylint: disable=invalid-unary-operand-type\n if self.data_format == 'channels_first':\n return tensor_shape.TensorShape([\n input_shape[0], input_shape[1],\n input_shape[2] - self.cropping[0][0] - self.cropping[0][1]\n if input_shape[2] else None,\n input_shape[3] - self.cropping[1][0] - self.cropping[1][1]\n if input_shape[3] else None\n ])\n else:\n return tensor_shape.TensorShape([\n input_shape[0],\n input_shape[1] - self.cropping[0][0] - self.cropping[0][1]\n if input_shape[1] else None,\n input_shape[2] - self.cropping[1][0] - self.cropping[1][1]\n if input_shape[2] else None, input_shape[3]\n ])\n # pylint: enable=invalid-unary-operand-type\n\n def call(self, inputs):\n # pylint: disable=invalid-unary-operand-type\n if self.data_format == 'channels_first':\n if self.cropping[0][1] == self.cropping[1][1] == 0:\n return inputs[:, :, self.cropping[0][0]:, self.cropping[1][0]:]\n elif self.cropping[0][1] == 0:\n return inputs[:, :, self.cropping[0][0]:, self.cropping[1][0]:\n -self.cropping[1][1]]\n elif self.cropping[1][1] == 0:\n return inputs[:, :, self.cropping[0][0]:-self.cropping[0][1],\n self.cropping[1][0]:]\n return inputs[:, :, self.cropping[0][0]:-self.cropping[0][1],\n self.cropping[1][0]:-self.cropping[1][1]]\n else:\n if self.cropping[0][1] == self.cropping[1][1] == 0:\n return inputs[:, self.cropping[0][0]:, self.cropping[1][0]:, :]\n elif self.cropping[0][1] == 0:\n return inputs[:, self.cropping[0][0]:, self.cropping[1][0]:\n -self.cropping[1][1], :]\n elif self.cropping[1][1] == 0:\n return inputs[:, self.cropping[0][0]:-self.cropping[0][1],\n self.cropping[1][0]:, :]\n return inputs[:, self.cropping[0][0]:-self.cropping[0][1], self.cropping[\n 1][0]:-self.cropping[1][1], :] # pylint: disable=invalid-unary-operand-type\n # pylint: enable=invalid-unary-operand-type\n\n def get_config(self):\n config = {'cropping': self.cropping, 'data_format': self.data_format}\n base_config = super(Cropping2D, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\nclass Cropping3D(Layer):\n \"\"\"Cropping layer for 3D data (e.g.\n\n spatial or spatio-temporal).\n\n Arguments:\n cropping: int, or tuple of 23ints, or tuple of 3 tuples of 2 ints.\n - If int: the same symmetric cropping\n is applied to depth, height, and width.\n - If tuple of 3 ints:\n interpreted as two different\n symmetric cropping values for depth, height, and width:\n `(symmetric_dim1_crop, symmetric_dim2_crop, symmetric_dim3_crop)`.\n - If tuple of 3 tuples of 2 ints:\n interpreted as\n `((left_dim1_crop, right_dim1_crop), (left_dim2_crop,\n right_dim2_crop), (left_dim3_crop, right_dim3_crop))`\n data_format: A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, spatial_dim1, spatial_dim2, spatial_dim3, channels)`\n while `channels_first` corresponds to inputs with shape\n `(batch, channels, spatial_dim1, spatial_dim2, spatial_dim3)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".\n\n Input shape:\n 5D tensor with shape:\n - If `data_format` is `\"channels_last\"`:\n `(batch, first_axis_to_crop, second_axis_to_crop, third_axis_to_crop,\n depth)`\n - If `data_format` is `\"channels_first\"`:\n `(batch, depth, first_axis_to_crop, second_axis_to_crop,\n third_axis_to_crop)`\n\n Output shape:\n 5D tensor with shape:\n - If `data_format` is `\"channels_last\"`:\n `(batch, first_cropped_axis, second_cropped_axis, third_cropped_axis,\n depth)`\n - If `data_format` is `\"channels_first\"`:\n `(batch, depth, first_cropped_axis, second_cropped_axis,\n third_cropped_axis)`\n \"\"\"\n\n def __init__(self,\n cropping=((1, 1), (1, 1), (1, 1)),\n data_format=None,\n **kwargs):\n super(Cropping3D, self).__init__(**kwargs)\n self.data_format = conv_utils.normalize_data_format(data_format)\n if isinstance(cropping, int):\n self.cropping = ((cropping, cropping), (cropping, cropping), (cropping,\n cropping))\n elif hasattr(cropping, '__len__'):\n if len(cropping) != 3:\n raise ValueError('`cropping` should have 3 elements. '\n 'Found: ' + str(cropping))\n dim1_cropping = conv_utils.normalize_tuple(cropping[0], 2,\n '1st entry of cropping')\n dim2_cropping = conv_utils.normalize_tuple(cropping[1], 2,\n '2nd entry of cropping')\n dim3_cropping = conv_utils.normalize_tuple(cropping[2], 2,\n '3rd entry of cropping')\n self.cropping = (dim1_cropping, dim2_cropping, dim3_cropping)\n else:\n raise ValueError(\n '`cropping` should be either an int, '\n 'a tuple of 3 ints '\n '(symmetric_dim1_crop, symmetric_dim2_crop, symmetric_dim3_crop), '\n 'or a tuple of 3 tuples of 2 ints '\n '((left_dim1_crop, right_dim1_crop),'\n ' (left_dim2_crop, right_dim2_crop),'\n ' (left_dim3_crop, right_dim2_crop)). '\n 'Found: ' + str(cropping))\n self.input_spec = InputSpec(ndim=5)\n\n def _compute_output_shape(self, input_shape):\n input_shape = tensor_shape.TensorShape(input_shape).as_list()\n # pylint: disable=invalid-unary-operand-type\n if self.data_format == 'channels_first':\n if input_shape[2] is not None:\n dim1 = input_shape[2] - self.cropping[0][0] - self.cropping[0][1]\n else:\n dim1 = None\n if input_shape[3] is not None:\n dim2 = input_shape[3] - self.cropping[1][0] - self.cropping[1][1]\n else:\n dim2 = None\n if input_shape[4] is not None:\n dim3 = input_shape[4] - self.cropping[2][0] - self.cropping[2][1]\n else:\n dim3 = None\n return tensor_shape.TensorShape(\n [input_shape[0], input_shape[1], dim1, dim2, dim3])\n elif self.data_format == 'channels_last':\n if input_shape[1] is not None:\n dim1 = input_shape[1] - self.cropping[0][0] - self.cropping[0][1]\n else:\n dim1 = None\n if input_shape[2] is not None:\n dim2 = input_shape[2] - self.cropping[1][0] - self.cropping[1][1]\n else:\n dim2 = None\n if input_shape[3] is not None:\n dim3 = input_shape[3] - self.cropping[2][0] - self.cropping[2][1]\n else:\n dim3 = None\n return tensor_shape.TensorShape(\n [input_shape[0], dim1, dim2, dim3, input_shape[4]])\n # pylint: enable=invalid-unary-operand-type\n\n def call(self, inputs):\n # pylint: disable=invalid-unary-operand-type\n if self.data_format == 'channels_first':\n if self.cropping[0][1] == self.cropping[1][1] == self.cropping[2][1] == 0:\n return inputs[:, :, self.cropping[0][0]:, self.cropping[1][0]:,\n self.cropping[2][0]:]\n elif self.cropping[0][1] == self.cropping[1][1] == 0:\n return inputs[:, :, self.cropping[0][0]:, self.cropping[1][0]:,\n self.cropping[2][0]:-self.cropping[2][1]]\n elif self.cropping[1][1] == self.cropping[2][1] == 0:\n return inputs[:, :, self.cropping[0][0]:-self.cropping[0][1],\n self.cropping[1][0]:, self.cropping[2][0]:]\n elif self.cropping[0][1] == self.cropping[2][1] == 0:\n return inputs[:, :, self.cropping[0][0]:, self.cropping[1][0]:\n -self.cropping[1][1], self.cropping[2][0]:]\n elif self.cropping[0][1] == 0:\n return inputs[:, :, self.cropping[0][0]:, self.cropping[1][\n 0]:-self.cropping[1][1], self.cropping[2][0]:-self.cropping[2][1]]\n elif self.cropping[1][1] == 0:\n return inputs[:, :, self.cropping[0][0]:-self.cropping[0][1], self.\n cropping[1][0]:, self.cropping[2][0]:-self.cropping[2][1]]\n elif self.cropping[2][1] == 0:\n return inputs[:, :, self.cropping[0][0]:-self.cropping[0][1], self.\n cropping[1][0]:-self.cropping[1][1], self.cropping[2][0]:]\n return inputs[:, :, self.cropping[0][0]:-self.cropping[0][1],\n self.cropping[1][0]:-self.cropping[1][1], self.cropping[2][\n 0]:-self.cropping[2][1]]\n else:\n if self.cropping[0][1] == self.cropping[1][1] == self.cropping[2][1] == 0:\n return inputs[:, self.cropping[0][0]:, self.cropping[1][0]:,\n self.cropping[2][0]:, :]\n elif self.cropping[0][1] == self.cropping[1][1] == 0:\n return inputs[:, self.cropping[0][0]:, self.cropping[1][0]:,\n self.cropping[2][0]:-self.cropping[2][1], :]\n elif self.cropping[1][1] == self.cropping[2][1] == 0:\n return inputs[:, self.cropping[0][0]:-self.cropping[0][1],\n self.cropping[1][0]:, self.cropping[2][0]:, :]\n elif self.cropping[0][1] == self.cropping[2][1] == 0:\n return inputs[:, self.cropping[0][0]:, self.cropping[1][0]:\n -self.cropping[1][1], self.cropping[2][0]:, :]\n elif self.cropping[0][1] == 0:\n return inputs[:, self.cropping[0][0]:, self.cropping[1][\n 0]:-self.cropping[1][1], self.cropping[2][0]:\n -self.cropping[2][1], :]\n elif self.cropping[1][1] == 0:\n return inputs[:, self.cropping[0][\n 0]:-self.cropping[0][1], self.cropping[1][0]:, self.cropping[2][0]:\n -self.cropping[2][1], :]\n elif self.cropping[2][1] == 0:\n return inputs[:, self.cropping[0][0]:-self.cropping[0][1],\n self.cropping[1][0]:-self.cropping[1][1], self.cropping[\n 2][0]:, :]\n return inputs[:, self.cropping[0][0]:-self.cropping[0][1], self.cropping[\n 1][0]:-self.cropping[1][1], self.cropping[2][0]: # pylint: disable=invalid-unary-operand-type\n -self.cropping[2][1], :] # pylint: disable=invalid-unary-operand-type\n # pylint: enable=invalid-unary-operand-type\n\n def get_config(self):\n config = {'cropping': self.cropping, 'data_format': self.data_format}\n base_config = super(Cropping3D, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\n# Aliases\n\nConvolution1D = Conv1D\nConvolution2D = Conv2D\nConvolution3D = Conv3D\nSeparableConvolution2D = SeparableConv2D\nConvolution2DTranspose = Conv2DTranspose\nConvolution3DTranspose = Conv3DTranspose\nDeconvolution2D = Deconv2D = Conv2DTranspose\nDeconvolution3D = Deconv3D = Conv3DTranspose\n" ]
[ [ "tensorflow.python.ops.math_ops.reduce_sum", "tensorflow.contrib.learn.python.learn.estimators.model_fn.ModelFnOps", "tensorflow.python.ops.control_flow_ops.with_dependencies", "tensorflow.python.training.training_util.get_global_step", "numpy.squeeze", "tensorflow.python.framework.ops.get_default_graph", "tensorflow.python.ops.logging_ops.info", "tensorflow.contrib.framework.python.framework.checkpoint_utils.load_variable", "numpy.sum", "tensorflow.python.framework.constant_op.constant" ], [ "tensorflow.python.util.all_util.remove_undocumented" ], [ "numpy.empty", "tensorflow.python.keras._impl.keras.backend.image_data_format", "tensorflow.python.keras._impl.keras.datasets.cifar.load_batch", "tensorflow.python.keras._impl.keras.utils.data_utils.get_file" ], [ "tensorflow.flags.DEFINE_string", "tensorflow.flags.DEFINE_integer", "tensorflow.app.run" ], [ "tensorflow.python.framework.tensor_shape.TensorShape", "tensorflow.python.ops.array_ops.shape", "tensorflow.python.ops.logging_ops.Print", "tensorflow.python.ops.array_ops.placeholder", "tensorflow.python.ops.array_ops.zeros", "numpy.any", "tensorflow.python.ops.array_ops.identity", "tensorflow.python.ops.array_ops.fill", "numpy.arange", "tensorflow.python.platform.test.main", "tensorflow.python.ops.array_ops.ones", "tensorflow.python.framework.ops.control_dependencies", "numpy.zeros", "tensorflow.python.framework.importer.import_graph_def", "tensorflow.python.ops.gradient_checker.compute_gradient_error", "tensorflow.python.ops.array_ops.zeros_like", "tensorflow.python.framework.dtypes.as_dtype", "numpy.random.rand", "tensorflow.python.framework.ops.convert_to_tensor", "numpy.array", "tensorflow.python.ops.array_ops.ones_like", "tensorflow.python.framework.ops.Graph", "numpy.ones", "numpy.complex", "numpy.random.normal", "tensorflow.python.ops.math_ops.multiply", "tensorflow.python.ops.array_ops.placeholder_with_default", "tensorflow.core.framework.graph_pb2.GraphDef", "numpy.empty", "tensorflow.python.framework.constant_op.constant" ], [ "tensorflow.python.ops.array_ops.transpose", "tensorflow.python.ops.nn_grad._BatchNormGrad", "tensorflow.python.ops.gradient_checker.compute_gradient", "numpy.random.seed", "tensorflow.python.ops.gradient_checker.compute_gradient_error", "tensorflow.python.ops.gradients_impl.gradients", "tensorflow.python.platform.test.is_gpu_available", "tensorflow.python.ops.math_ops.rsqrt", "numpy.random.random_sample", "tensorflow.python.platform.test.main", "tensorflow.python.ops.nn_impl.fused_batch_norm", "tensorflow.python.framework.constant_op.constant", "numpy.fabs", "tensorflow.python.ops.math_ops.cast" ], [ "tensorflow.python.framework.test_util.run_in_graph_and_eager_modes", "numpy.sqrt", "tensorflow.python.eager.context.in_graph_mode", "tensorflow.python.ops.resource_variable_ops.ResourceVariable", "tensorflow.python.framework.ops.Graph", "tensorflow.python.platform.test.is_gpu_available", "tensorflow.python.ops.variables.Variable", "tensorflow.python.ops.array_ops.gather", "tensorflow.python.client.session.Session", "tensorflow.python.platform.test.main", "tensorflow.python.training.adam.AdamOptimizer", "tensorflow.python.ops.variables.global_variables_initializer", "numpy.array", "tensorflow.python.framework.constant_op.constant" ], [ "numpy.dtype", "tensorflow.python.pywrap_tensorflow.TF_bfloat16_type", "numpy.all", "tensorflow.python.platform.test.main", "numpy.array", "numpy.logaddexp" ], [ "tensorflow.python.ops.parsing_ops.FixedLenFeature", "tensorflow.contrib.data.python.ops.readers.TFRecordDataset", "tensorflow.python.ops.parsing_ops.VarLenFeature", "tensorflow.python.framework.ops.Graph", "tensorflow.python.ops.parsing_ops.parse_single_example", "tensorflow.python.util.compat.as_bytes", "tensorflow.python.ops.array_ops.placeholder", "tensorflow.contrib.data.python.ops.readers.FixedLengthRecordDataset", "tensorflow.python.platform.test.main", "tensorflow.core.example.feature_pb2.Int64List", "tensorflow.python.lib.io.python_io.TFRecordWriter", "tensorflow.python.ops.array_ops.placeholder_with_default", "tensorflow.python.data.ops.iterator_ops.Iterator.from_structure", "tensorflow.contrib.data.python.ops.readers.TextLineDataset", "tensorflow.python.framework.constant_op.constant" ], [ "tensorflow.python.framework.tensor_shape.TensorShape", "tensorflow.python.keras._impl.keras.backend.resize_volumes", "tensorflow.python.keras._impl.keras.constraints.serialize", "tensorflow.python.keras._impl.keras.regularizers.serialize", "tensorflow.python.keras._impl.keras.initializers.get", "tensorflow.python.keras._impl.keras.activations.get", "tensorflow.python.keras._impl.keras.utils.conv_utils.normalize_data_format", "tensorflow.python.keras._impl.keras.backend.image_data_format", "tensorflow.python.keras._impl.keras.initializers.serialize", "tensorflow.python.keras._impl.keras.backend.temporal_padding", "tensorflow.python.keras._impl.keras.backend.resize_images", "tensorflow.python.keras._impl.keras.backend.spatial_2d_padding", "tensorflow.python.keras._impl.keras.engine.InputSpec", "tensorflow.python.keras._impl.keras.backend.repeat_elements", "tensorflow.python.keras._impl.keras.backend.spatial_3d_padding", "tensorflow.python.keras._impl.keras.utils.conv_utils.normalize_tuple", "tensorflow.python.keras._impl.keras.regularizers.get", "tensorflow.python.keras._impl.keras.activations.serialize", "tensorflow.python.keras._impl.keras.constraints.get" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "1.12", "2.6", "2.2", "1.13", "2.3", "2.4", "1.4", "2.9", "1.5", "1.7", "2.5", "0.12", "1.0", "2.8", "1.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "1.12", "2.6", "2.2", "1.13", "2.3", "2.4", "1.4", "2.9", "1.5", "1.7", "2.5", "0.12", "1.0", "2.8", "1.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "1.10", "1.12", "1.4", "2.7", "2.2", "1.13", "2.3", "2.4", "2.9", "1.5", "1.7", "2.5", "1.0", "2.6", "1.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.5", "1.4" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.5", "1.13", "1.7", "1.12" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.5", "1.4" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
meewa1/BrukerGUI
[ "f71211557f3a61322a8a8bc9bdb1f70f3cc82969" ]
[ "MRIAssimilator/MRIAThreads.py" ]
[ "from PyQt5 import QtCore\n\nimport os, tempfile\nfrom scipy.misc import toimage\nimport brukerWriter as bw\n\nimport utils\n\nfrom FilesTreeWidget import *\n\n__all__ = [\"FilesTreeThread\", \"SaveThread\"]\n\n\nclass FilesTreeThread(QtCore.QThread):\n def __init__(self, parent = None, mode = \"create\", dirnames = \"\"):\n super().__init__()\n self.parent = parent\n self.fail = 0\n self.mode = mode\n self.dirnames = dirnames\n\n def run(self):\n if not self.dirnames:\n self.parent.tree.manageTree(self.parent.curDir, self.mode)\n else:\n #for dirname in self.dirnames:\n self.parent.tree.manageTree(self.dirnames, self.mode)\n\nclass CANCELThread(Exception):\n pass\n\nclass SaveThread(QtCore.QThread):\n \"\"\" \nCreate thread for saving experiment in the text format\nif self.trigger == \"all\" then each experiment will be saved as \n a single text file in the folder corresponding to the experiment name\nelse self.trigger == \"single\" then only one experiment will be saved without creating folder\n\n \"\"\"\n progressText = QtCore.pyqtSignal(str)\n progress = QtCore.pyqtSignal(int)\n suggestedTypes = [\"Image\", \"XML\", \"Text\"]\n def __init__(self, parent, savepath, saveType, form = \"\", filename = \"\"):\n super().__init__()\n\n self.saveType = saveType\n if self.saveType not in self.suggestedTypes:\n raise CANCELThread(\"Uncorrect function type\")\n\n self.parent = parent\n self.SaveDir = savepath\n self.form = \"xml\" if self.saveType==\"XML\" else form\n self.trigger = \"all\"\n self.cancelThread = False\n self.filename = filename\n\n def _SaveAllChecked(self):\n\n completed = 0\n data = self.parent.tree.ImageData\n\n checkedItemList = []\n self.parent.tree.findCheckedItems(self.parent.tree.invisibleRootItem(), checkedItemList)\n\n allDim = 0\n self.progressText.emit(self.tr(\"Data size counting\"))\n for expNumItem in checkedItemList:\n allDim += int(utils.num_pattern.findall(expNumItem.text(0))[1])\n\n for expNumItem in checkedItemList:\n exp_name = self.parent.tree.getExpNameItem(expNumItem).text(0)\n exp_num = utils.num_pattern.findall(expNumItem.text(0))[0]\n\n saveDir = os.path.join(self.tmp_folder.name, exp_name)\n utils.checkdir(saveDir)\n\n if self.saveType == \"Image\":\n saveDir = os.path.join(saveDir, exp_num)\n utils.checkdir(saveDir)\n\n if self.saveType != \"Image\":\n fname = '{0}{1}Experiment_{2}.{3}'.format(saveDir,\n os.sep,\n exp_num,\n self.form)\n\n img_data = data[exp_name][exp_num][\"data\"]\n for i in range(img_data.Dimension[0]):\n if self.cancelThread:\n raise CANCELThread()\n\n if self.saveType == \"Image\":\n fname = '{0}{1}Image_{2}.{3}'.format(saveDir, \n os.sep, \n i+1, \n self.form)\n self.progressText.emit(\n self.tr(\"Writting Image_{0}.{1} to the folder /{2}/{3}\").format(\n i+1,\n self.form,\n exp_name,\n exp_num))\n toimage(img_data.IntenseData[i,:,:], \n cmin=img_data.min_val, cmax=img_data.max_val).save(fname)\n\n else: \n self.progressText.emit(\n self.tr(\"Writting Image {0}\\{1} to the Experiment_{2}.{3}\").format(\n i+1,\n img_data.Dimension[0],\n exp_num,\n self.form))\n\n eval(\"bw.SingleWriteTo{}File\".format(self.saveType))(fname,\n img_data,\n i,\n i==0)\n\n completed += 100/allDim\n self.progress.emit(completed)\n\n def _SaveSingle(self):\n \"\"\"\n Saving current experiment number\n \"\"\"\n completed = 0\n allDim = self.parent.scroll.maximum()\n saveDir = self.tmp_folder.name\n img_data = self.parent.tree.ImageData[self.parent.curExpName][self.parent.curExpNum][\"data\"]\n\n # add \".xml\" postfix if it's not presented for XML files\n if self.saveType == \"XML\":\n try:\n self.filename = re.search(r\".+\\.xml$\", self.filename).group()\n except AttributeError:\n self.filename += \".xml\"\n\n fname = '{0}{1}{2}'.format(saveDir, \n os.sep, \n self.filename)\n\n for i in range(allDim):\n if self.cancelThread:\n raise CANCELThread()\n\n if self.saveType == \"Image\":\n fname = '{0}{1}{2}_{3}.{4}'.format(saveDir,\n os.sep,\n self.filename,\n i+1,\n self.form)\n self.progressText.emit(\n self.tr(\"Writting {0}_{1}.{2}\").format(self.filename, \n i+1,\n self.form))\n\n toimage(img_data.IntenseData[i,:,:], \n cmin=img_data.min_val, cmax=img_data.max_val).save(fname)\n\n else:\n self.progressText.emit(\n self.tr(\"Writting Image {0}\\{1} to the {2}\").format(i+1,\n allDim + 1, \n self.filename))\n\n eval(\"bw.SingleWriteTo{}File\".format(self.saveType))(fname, \n img_data,\n i,\n i==0)\n completed += 100/allDim\n self.progress.emit(completed)\n\n def run(self):\n\n try:\n utils.checkdir(self.SaveDir)\n\n # create a temporary folder\n self.tmp_folder = tempfile.TemporaryDirectory(suffix = \".TMP\",\n prefix=\"_MRIAssimilator_\",\n dir = self.SaveDir)\n if self.trigger == \"all\":\n self._SaveAllChecked()\n\n elif self.trigger == \"single\":\n self._SaveSingle()\n\n except CANCELThread: \n self.quit()\n" ]
[ [ "scipy.misc.toimage" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "0.14", "0.15", "1.0", "0.19", "0.18", "1.2", "0.12", "0.10", "0.17", "0.16" ], "tensorflow": [] } ]
BrunoKM/station-b-libraries
[ "ea3591837e4a33f0bef789d905467754c27913b3", "ea3591837e4a33f0bef789d905467754c27913b3", "ea3591837e4a33f0bef789d905467754c27913b3" ]
[ "PyStationB/libraries/StaticCharacterization/tests/notebooks/test_introduction.py", "PyStationB/libraries/StaticCharacterization/tests/test_integrals.py", "PyStationB/libraries/ABEX/abex/simulations/plot_convergence_multiple_runs.py" ]
[ "# # Introduction\n# In this notebook, we will load an example time series, fit a growth model\n# and plot the signals.\n#\n# ## Load example time series\n#\n# Let's start by loading example time series data.\n# -------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.\n# -------------------------------------------------------------------------------------------\n\nfrom typing import Iterable, List, Optional, cast\n\nimport matplotlib.pyplot as plt\nimport pytest\nimport seaborn as sns\nimport staticchar as ch\nfrom psbutils.filecheck import Plottable, figure_found\nfrom psbutils.misc import find_subrepo_directory\nfrom staticchar.plotting.core import AnnotationSpec\n\nSUBREPO_DIR = find_subrepo_directory()\nS_SHAPE_FOLDER = SUBREPO_DIR / \"tests/test_data/S-shape\"\n\n\ndef plot_figure(name: str, ax: Optional[Plottable] = None) -> List[str]:\n sns.despine()\n found = figure_found(ax, f\"test_introduction/{name}\")\n plt.clf()\n return [] if found else [name]\n\n\[email protected](10)\ndef test_introduction():\n dataset = ch.datasets.Dataset(S_SHAPE_FOLDER) # type: ignore # auto\n\n raw_timeseries = dataset.get_a_frame()\n rth = raw_timeseries.head()\n\n # As we can see, there is some non-zero signal at the beginning, which we attribute to\n # the media absorbance and media fluorescence (as initially we have very low cell density).\n assert sorted(rth.keys().to_list()) == sorted([ch.TIME, \"EYFP\", \"OD\", \"ECFP\", \"OD700\", \"mRFP1\"])\n\n colors = {\"EYFP\": \"yellow\", \"ECFP\": \"cyan\", \"mRFP1\": \"red\", \"OD\": \"black\"}\n\n plt.figure(figsize=(6.4, 4.8))\n ax = cast(plt.Axes, plt.subplot())\n ch.plot_signals_against_time(raw_timeseries, signals=colors.keys(), time_column=\"time\", ax=ax, colors=colors)\n ax.legend()\n figures_not_found = []\n figures_not_found += plot_figure(\"plot1_raw_timeseries\", ax)\n\n # ## Pre-processing\n # Let's assume this is the background and subtract it.\n # (A more precise, but also costly alternative is to estimate this using several blanks).\n\n # In[ ]:\n\n subtracted = ch.subtract_background(\n raw_timeseries, columns=[\"OD\", \"ECFP\", \"EYFP\", \"mRFP1\"], strategy=ch.BackgroundChoices.Minimum\n )\n ax = cast(plt.Axes, plt.subplot())\n ch.plot_signals_against_time(subtracted, signals=colors.keys(), time_column=\"time\", ax=ax, colors=colors)\n ax.legend()\n figures_not_found += plot_figure(\"plot2_subtracted_timeseries\", ax)\n\n # ## Run characterization on an example\n\n # In[ ]:\n\n yaml_path = find_subrepo_directory() / \"tests/configs/integral_basic.yml\"\n config = ch.config.load(yaml_path, ch.config.CharacterizationConfig)\n # config\n\n # ### Fitting a growth model\n #\n # Let's fit a growth model to the OD signal.\n\n model_params = ch.LogisticModel.fit(subtracted[\"time\"], subtracted[config.growth_signal]) # type: ignore # auto\n model = ch.LogisticModel(model_params)\n\n # model_params = ch.GompertzModel.fit(subtracted[\"time\"], subtracted[config.growth_signal])\n # model = ch.GompertzModel(model_params)\n\n print(f\"Inferred parameters: {model_params}\")\n print(f\"Growth phase: {model.growth_period}\")\n print(f\"Time of maximal activity: {model.time_maximal_activity}\")\n print(f\"Inferred (log of) initial density: {model.initial_density(log=True)}\")\n\n ch.plot_growth_model(subtracted[\"time\"], subtracted[config.growth_signal], model=model) # type: ignore # auto\n figures_not_found += plot_figure(\"plot3_growth_model_fit\")\n\n # ### Plotting the data\n #\n # Some time after the growth phase, we should observe a similar exponential production\n # of the proteins. Suppose that this maturation time is about 50 minutes,\n # that is about 0.85 hours.\n #\n # Then, fluorescence signals should be linear when drawn with respect to each other.\n\n # Add offset to the growth phase\n production_phase = model.growth_period + config.maturation_offset\n\n f, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4)) # type: ignore\n ch.plot_signals_against_time(subtracted, signals=colors.keys(), time_column=\"time\", ax=ax1, colors=colors)\n\n # Visualise the production phase\n ch.mark_phase(ax1, interval=production_phase, color=\"green\", alpha=0.1)\n\n ch.plot_signals_against_reference(subtracted, signals=(\"EYFP\", \"ECFP\"), reference=\"mRFP1\", colors=colors, ax=ax2)\n\n figures_not_found += plot_figure(\"plot4_fluorescence_signals\", f)\n\n # ### Truncate the time-series\n #\n # We see that this very well captures the growth phase of mRFP1 (the reference signal),\n # but is a bit too late for EYFP and ECFP -- we won't have a linear dependence between\n # the signals...\n #\n # Let's choose a more narrow interval.\n\n another_production_phase = ch.TimePeriod(reference=12, left=2, right=2)\n truncated_timeseries = ch.select_time_interval(subtracted, interval=another_production_phase)\n\n f, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4)) # type: ignore\n ch.plot_signals_against_time(subtracted, signals=colors.keys(), time_column=\"time\", ax=ax1, colors=colors)\n\n # Visualise the production phase\n ch.mark_phase(ax1, interval=another_production_phase, color=\"green\", alpha=0.1)\n\n ch.plot_signals_against_reference(\n truncated_timeseries, signals=(\"EYFP\", \"ECFP\"), reference=\"mRFP1\", colors=colors, ax=ax2 # type: ignore # auto\n )\n figures_not_found += plot_figure(\"plot5_truncated\")\n\n # Run method\n\n gradient, gradient_error = ch.transcriptional_activity_ratio(\n truncated_timeseries, # type: ignore # auto\n config.signals,\n config.reference,\n config.signal_properties,\n model_params.growth_rate,\n model.growth_period,\n maturation_offset=config.maturation_offset,\n )\n # gradient\n\n # ### Integration-based characterization\n # Now assume that we want to integrate the signals over the production period.\n\n signals = [\"EYFP\", \"ECFP\"]\n ch.integrate(data=subtracted, signals=signals, interval=config.time_window)\n\n # Now plot the output\n\n f, axs = plt.subplots(1, len(config.signals), figsize=(12, 4))\n for signal, ax in zip(config.signals, cast(Iterable, axs)):\n ch.plot_integration(\n subtracted,\n signal,\n config.time_window,\n ax,\n fillcolor=colors[signal],\n annotation_spec=AnnotationSpec(title=True),\n )\n\n figures_not_found += plot_figure(\"plot6_integration\", f)\n assert figures_not_found == [], f\"Figures not found: {', '.join(figures_not_found)}\"\n", "# -------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.\n# -------------------------------------------------------------------------------------------\nfrom pandas import DataFrame\nfrom staticchar.basic_types import TIME, TimePeriod\nfrom staticchar.integrals import integrate\n\n\ndef test_integrate():\n dct = {TIME: [0, 1, 2, 3], \"gfp\": [2.0, 3.0, 2.5, 2.0], \"rfp\": [1.0, 2.0, 1.5, 1.0]}\n df = DataFrame(dct)\n results = integrate(df, signals=[\"gfp\", \"rfp\"])\n assert results[\"gfp\"] == 7.5\n assert results[\"rfp\"] == 4.5\n results2 = integrate(df, signals=[\"gfp\", \"rfp\"], interval=TimePeriod(reference=1.5, left=0.5, right=0.5))\n assert results2[\"gfp\"] == 2.75\n assert results2[\"rfp\"] == 1.75\n", "# -------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.\n# -------------------------------------------------------------------------------------------\n\"\"\"\nConvergence plotting script for comparing multiple experiments that allows for aggregating over multiple randomised\nsub-runs (runs with same configurations, but a different random seed). The randomly seeded sub-runs are expected\nas sub-directories of the experiment directories.\n\nExample command:\npython plot_convergence_multiple_runs.py --experiment_dirs /path/to/experiment/one /path/to/experiment/two\n --experiment_labels \"Experiment 1\" \"Experiment 2\" --objective_column \"Output\"\n --init_data_filename \"initial_batch.csv\"\n\"\"\"\nimport argparse\nimport logging\nfrom functools import reduce\nfrom pathlib import Path\nfrom typing import List\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom abex.plotting.convergence_plotting import (\n ConvergencePlotStyles,\n plot_multirun_convergence,\n plot_multirun_convergence_per_sample,\n)\n\nBATCH_COLUMN = \"Batch Number\"\nRUN_NAME_COLUMN = \"Experiment Name\"\nSEED_COLUMN = \"Sub-run Number\"\n\n\ndef create_parser() -> argparse.ArgumentParser:\n parser = argparse.ArgumentParser(\n description=\"Plot convergence over several iterations of Bayesian Optimization, for possibly multiple runs.\"\n \"Assumes one file corresponds to one batch collected.\"\n )\n parser.add_argument(\n \"--experiment_dirs\",\n type=Path,\n nargs=\"+\",\n required=True,\n help=\"A sequence of directories corresponding to different configurations for an experiment \"\n \"(different runs). Each directory should contain multiple sub-directories with multiple sub-runs\"\n \"corresponding to different random seeds.\",\n )\n parser.add_argument(\n \"--experiment_labels\",\n type=str,\n nargs=\"+\",\n help=\"A sequence of names to give to each experiment (collection of sub-runs). These will be used to \"\n \"label the experiments on resulting plots. These should appear in the\"\n \"same order as --experiment_dirs. If not specified, folder names will be used as experiment labels.\",\n )\n parser.add_argument(\n \"--objective_column\",\n type=str,\n default=\"Crosstalk Ratio\",\n help=\"The name of the objective column in data files.\",\n )\n parser.add_argument(\n \"--init_data_filename\",\n type=Path,\n required=True,\n help=\"The filename for the initial data file (the other files in each seed-run subdirectory \"\n \"will be treated as batches).\",\n )\n parser.add_argument(\n \"--results_dir\", type=Path, default=Path(\"Results\"), help=\"The directory in which to save the resulting plot.\"\n )\n parser.add_argument(\n \"--output_path\",\n type=Path,\n default=None,\n help=\"If specified, the resulting plot will be saved at this location \"\n \"(otherwise a plot name will be generated).\",\n )\n parser.add_argument(\"--title\", type=str, default=None, help=\"The title for the plot.\")\n parser.add_argument(\n \"--no_boxplot\",\n action=\"store_true\",\n help=\"Whether to remove the boxplot for the final plot (useful if the plot gets too cluttered).\",\n )\n parser.add_argument(\n \"--no_scatter\",\n action=\"store_true\",\n help=\"Whether to remove the scatter points for the final plot (useful if the plot gets too cluttered).\",\n )\n parser.add_argument(\n \"--max_batch_number\",\n type=int,\n default=None,\n help=\"Whether to clip the x-axis to a given number of batches.\",\n )\n parser.add_argument(\n \"--make_per_sample_plot\",\n action=\"store_true\",\n help=\"Whether to make a per-sample plot as well in which x-axis is 'num. samples collected' rather than \"\n \"'num. batches collected'.\",\n )\n parser.add_argument(\n \"--output_scale\",\n type=str,\n default=None,\n choices=[\"symlog\", \"log\", \"linear\"],\n help=\"What scale to use for the objective on the plot. Default to log if all objective values are positive, \"\n \"symlog otherwise.\",\n )\n parser.add_argument(\n \"--styled_lines\",\n action=\"store_true\",\n help=\"Whether to give each line a different style (dashed, solid, double-dashed, ...) in addition to it \"\n \"being a different colour.\",\n )\n parser.add_argument(\n \"--styled_subset\",\n type=str,\n action=\"append\",\n nargs=\"+\",\n help=\"Style a subset (specified by run name) of the plotted traces to distinguish them from other traces.\",\n )\n parser.add_argument(\n \"--style_category_name\",\n type=str,\n default=\"Category\",\n help=\"Name to use on the legend for the style categories.\",\n )\n parser.add_argument(\n \"--styled_subset_names\",\n type=str,\n nargs=\"+\",\n default=None,\n help=\"Names for each consecutive subset that is differently styled.\",\n )\n parser.add_argument(\n \"--plot_style\",\n type=str,\n default=\"boxplot\",\n choices=[e.value for e in ConvergencePlotStyles], # [\"boxplot\", \"line\"],\n help=\"Type of convergence plot (line, or slightly offset point-plot with error bars).\",\n )\n return parser\n\n\ndef load_seeded_subrun_df(subrun_dir: Path, init_data_filename: str) -> pd.DataFrame: # pragma: no cover\n \"\"\"Return a DataFrame with the observations from this 'sub-run'. This funciton iterates over the files\n in this directory, and assumes they correspond to consecutive batches in a single optimization run in\n lexicographic order. Adds a column to the DataFrame to indicate batch number.\n \"\"\"\n init_data_file = subrun_dir / init_data_filename\n assert init_data_file.is_file(), f\"Initial data file not found at: {init_data_file}\"\n batch_files: List[Path] = [child for child in subrun_dir.glob(\"**/*\") if child.is_file() and child.suffix == \".csv\"]\n # Only keep csv files in folder that are not initial data files:\n batch_files.remove(init_data_file)\n # Sort in lexicographic order\n batch_files = sorted(batch_files)\n # Load into a DF\n batch_dfs = list(map(pd.read_csv, batch_files))\n batch_dfs.insert(0, pd.read_csv(init_data_file)) # Prepend initial data at index 0\n for i, batch_df in enumerate(batch_dfs):\n batch_df[BATCH_COLUMN] = i # type: ignore # auto\n if len({len(batch_df) for batch_df in batch_dfs}) != 1: # type: ignore # auto\n logging.warning(f\"Batches in subrun at {subrun_dir} have unequal sizes.\")\n return pd.concat(batch_dfs) # type: ignore # auto\n\n\ndef load_experiment_df(experiment_dir: Path, init_data_filename: str) -> pd.DataFrame: # pragma: no cover\n \"\"\"Return a DataFrame with accumulated observations from each sub-run in this directory. Each sub-directory\n in the folder experiment_dir is assumed to correspond to a single optimization run (with possibly\n different random seeds). Adds a column to the DataFrame to indicate sub-run ID (the ID is arbitrary).\n \"\"\"\n assert experiment_dir.exists(), f\"A directory at {experiment_dir} must exist.\"\n assert experiment_dir.is_dir(), f\"A directory at {experiment_dir} must exist, but is not a directory.\"\n # Get all subdirectories (ASSUME they correspond to seeded runs)\n subrun_dirs_in_folder = [child for child in experiment_dir.glob(\"**/*\") if child.is_dir()]\n experiment_dfs = []\n for subrun_id, subrun_dir in enumerate(subrun_dirs_in_folder):\n subrun_df = load_seeded_subrun_df(subrun_dir, init_data_filename)\n subrun_df[SEED_COLUMN] = subrun_id\n experiment_dfs.append(subrun_df)\n if len({len(one_seed_subrun_df) for one_seed_subrun_df in experiment_dfs}) != 1:\n logging.warning(f\"Not all subruns in {experiment_dir} have the same length.\")\n return pd.concat(experiment_dfs)\n\n\ndef load_combined_df(\n experiment_dirs: List[Path], experiment_labels: List[str], init_data_filename: str\n) -> pd.DataFrame: # pragma: no cover\n \"\"\"Return a DataFrame with observations from each run specified in run_dirs. The returned DataFrame\n will have additional columns for: run name, sub-run id and batch number. Here, a sub-run is a single optimization\n run/experiment where multiple batches are collected. A run is a collection of those sub-runs (with different\n rando initialisations) that share the same model/optimization configuration.\n \"\"\"\n dfs = []\n for run_name, run_dir in zip(experiment_labels, experiment_dirs):\n run_df = load_experiment_df(run_dir, init_data_filename)\n run_df[RUN_NAME_COLUMN] = run_name\n dfs.append(run_df)\n return pd.concat(dfs)\n\n\ndef get_experiment_labels(args) -> List[str]: # pragma: no cover\n \"\"\"Returns experiment labels, inferring them from `args.experiment_dirs`, if `args.experiment_labels` not\n explicitly provided.\n\n Raises:\n ValueError, if the labels don't match the experiment directories\n \"\"\"\n experiment_labels: List[str]\n # If experiment_labels specified, assert the length matches the number of directories given\n if args.experiment_labels:\n if len(args.experiment_dirs) != len(args.experiment_labels):\n raise ValueError(\n f\"Number of directories ({len(args.experiment_dirs)}) does not match the number of experiment \"\n f\"names ({len(args.experiment_labels)}).\\nDirectories: {args.experiment_dirs}\\n\"\n f\"Experiment names: {args.experiment_labels}\"\n )\n experiment_labels = args.experiment_labels\n else:\n # If not specified, use folder names\n experiment_labels = list(map(lambda exp_dir: exp_dir.stem, args.experiment_dirs))\n # Ensure names unique:\n if len(experiment_labels) != len(set(experiment_labels)):\n raise ValueError(\n f\"All experiment names must be unique, but are:\\n{experiment_labels}\\n\"\n \"Use the `--experiment_labels` flag if experiment directories don't have unique names.\"\n )\n\n return experiment_labels\n\n\ndef main(args): # pragma: no cover\n # - Get experiment (run) names\n experiment_labels: List[str] = get_experiment_labels(args)\n\n # Load the data\n combined_df = load_combined_df(\n experiment_dirs=args.experiment_dirs,\n experiment_labels=experiment_labels,\n init_data_filename=args.init_data_filename,\n )\n\n # Assert all entries in objective columns non-zero\n assert args.objective_column in combined_df.columns\n assert not combined_df[args.objective_column].isnull().any()\n\n # Clip the number of batches if max_batch_num specified\n combined_df_clipped = (\n combined_df[combined_df[BATCH_COLUMN] <= args.max_batch_number] if args.max_batch_number else combined_df\n )\n if args.styled_subset:\n assert args.experiment_labels, \"Experiment names must be given if style subsets specified\"\n # Assert all the styled subsets cover all of the experiments\n assert reduce(lambda a, b: a.union(b), args.styled_subset, set()) == set(args.experiment_labels)\n\n # Assert there is the right number of styled subsets (no duplicates between subsets)\n assert sum([len(subset) for subset in args.styled_subset]) == len(args.experiment_labels)\n\n if args.styled_subset_names is None:\n # If styled subset names not given, set generic default names\n args.styled_subset_names = [f\"Category {i}\" for i in range(len(args.styled_subset))]\n assert len(args.styled_subset) == len(args.styled_subset_names)\n # Construct result_subdir_name to style subset name mapping\n experiment_to_style_subset = dict()\n for styled_subset, subset_name in zip(args.styled_subset, args.styled_subset_names):\n for result_subdir_name in styled_subset:\n experiment_to_style_subset[result_subdir_name] = subset_name\n # If styling a subset, add style column\n combined_df_clipped[args.style_category_name] = combined_df_clipped[RUN_NAME_COLUMN].map( # type: ignore # auto\n lambda s: experiment_to_style_subset[s]\n )\n\n if args.styled_lines and args.styled_subset:\n raise ValueError(\"Both styled_lines and styled_subset can't be specified at the same time.\")\n if args.styled_lines:\n style_cols = [RUN_NAME_COLUMN]\n elif args.styled_subset & isinstance(args.style_category_name, str):\n assert isinstance(args.style_category_name, str)\n style_cols = [args.style_category_name]\n else:\n style_cols = None\n # Determine the output scale for the plot\n if args.output_scale is not None:\n output_scale = args.output_scale\n elif (combined_df_clipped[args.objective_column] > 0).all(): # type: ignore # auto\n output_scale = \"log\"\n else:\n output_scale = \"symlog\"\n fig, _ = plot_multirun_convergence(\n combined_df_clipped, # type: ignore # auto\n objective_col=args.objective_column,\n batch_num_col=BATCH_COLUMN,\n run_col=RUN_NAME_COLUMN,\n seed_col=SEED_COLUMN,\n add_boxplot=not args.no_boxplot,\n add_scatter=not args.no_scatter,\n style_cols=style_cols,\n plot_style=args.plot_style,\n yscale=output_scale,\n )\n assert fig is not None\n # Possibly add title\n if args.title:\n fig.suptitle(args.title)\n # Get output_path:\n if args.output_path:\n output_path = args.output_path\n else:\n filename = f\"multirun_convergence_plot_{'__'.join(experiment_labels)}.png\"\n output_path = args.results_dir / filename\n fig.savefig(output_path, bbox_inches=\"tight\")\n plt.close(fig)\n if args.make_per_sample_plot:\n fig_per_sample, _ = plot_multirun_convergence_per_sample(\n combined_df,\n objective_col=args.objective_column,\n batch_num_col=BATCH_COLUMN,\n run_col=RUN_NAME_COLUMN,\n seed_col=SEED_COLUMN,\n )\n assert fig_per_sample is not None\n # Possibly add title\n if args.title:\n fig_per_sample.suptitle(args.title)\n filename = f\"multirun_convergence_per_sample_plot_{'__'.join(experiment_labels)}.png\"\n output_path = args.results_dir / filename\n fig_per_sample.savefig(output_path, bbox_inches=\"tight\")\n plt.close(fig_per_sample)\n\n\nif __name__ == \"__main__\": # pragma: no cover\n args = create_parser().parse_args()\n main(args)\n" ]
[ [ "matplotlib.pyplot.subplot", "matplotlib.pyplot.clf", "matplotlib.pyplot.subplots", "matplotlib.pyplot.figure" ], [ "pandas.DataFrame" ], [ "pandas.concat", "pandas.read_csv", "matplotlib.pyplot.close" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] } ]
mir-group/nequip
[ "4e6a0914a289cf000da57a6b6e79678efdf3347f" ]
[ "nequip/nn/embedding/_one_hot.py" ]
[ "import torch\nimport torch.nn.functional\n\nfrom e3nn.o3 import Irreps\nfrom e3nn.util.jit import compile_mode\n\nfrom nequip.data import AtomicDataDict\nfrom .._graph_mixin import GraphModuleMixin\n\n\n@compile_mode(\"script\")\nclass OneHotAtomEncoding(GraphModuleMixin, torch.nn.Module):\n num_types: int\n set_features: bool\n\n # TODO: use torch.unique?\n # TODO: type annotation\n # Docstrings\n def __init__(\n self,\n num_types: int,\n set_features: bool = True,\n irreps_in=None,\n ):\n super().__init__()\n self.num_types = num_types\n self.set_features = set_features\n # Output irreps are num_types even (invariant) scalars\n irreps_out = {AtomicDataDict.NODE_ATTRS_KEY: Irreps([(self.num_types, (0, 1))])}\n if self.set_features:\n irreps_out[AtomicDataDict.NODE_FEATURES_KEY] = irreps_out[\n AtomicDataDict.NODE_ATTRS_KEY\n ]\n self._init_irreps(irreps_in=irreps_in, irreps_out=irreps_out)\n\n def forward(self, data: AtomicDataDict.Type):\n type_numbers = data[AtomicDataDict.ATOM_TYPE_KEY].squeeze(-1)\n one_hot = torch.nn.functional.one_hot(\n type_numbers, num_classes=self.num_types\n ).to(device=type_numbers.device, dtype=data[AtomicDataDict.POSITIONS_KEY].dtype)\n data[AtomicDataDict.NODE_ATTRS_KEY] = one_hot\n if self.set_features:\n data[AtomicDataDict.NODE_FEATURES_KEY] = one_hot\n return data\n" ]
[ [ "torch.nn.functional.one_hot" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
swami1995/SimuRLacra
[ "795e6ea45fbb722242ddb0c0ea5c62432826411e", "795e6ea45fbb722242ddb0c0ea5c62432826411e", "795e6ea45fbb722242ddb0c0ea5c62432826411e" ]
[ "Pyrado/pyrado/environments/mujoco/openai_half_cheetah.py", "Pyrado/pyrado/policies/feed_back/fnn.py", "Pyrado/pyrado/algorithms/step_based/dql.py" ]
[ "# Copyright (c) 2020, Fabio Muratore, Honda Research Institute Europe GmbH, and\n# Technical University of Darmstadt.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n# 1. Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# 2. Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n# 3. Neither the name of Fabio Muratore, Honda Research Institute Europe GmbH,\n# or Technical University of Darmstadt, nor the names of its contributors may\n# be used to endorse or promote products derived from this software without\n# specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL FABIO MURATORE, HONDA RESEARCH INSTITUTE EUROPE GMBH,\n# OR TECHNICAL UNIVERSITY OF DARMSTADT BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER\n# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\nimport os.path as osp\nfrom typing import Optional\n\nimport numpy as np\nfrom init_args_serializer import Serializable\n\nimport pyrado\nfrom pyrado.environments.mujoco.base import MujocoSimEnv\nfrom pyrado.spaces.base import Space\nfrom pyrado.spaces.box import BoxSpace\nfrom pyrado.tasks.base import Task\nfrom pyrado.tasks.goalless import GoallessTask\nfrom pyrado.tasks.reward_functions import ForwardVelocityRewFcn\n\n\nclass HalfCheetahSim(MujocoSimEnv, Serializable):\n \"\"\"\n The Half-Cheetah (v3) MuJoCo simulation environment where a planar cheetah-like robot tries to run forward.\n\n .. note::\n The OpenAI Gym variant considers this task solved at a reward over 4800\n (https://github.com/openai/gym/blob/master/gym/envs/__init__.py).\n\n .. seealso::\n https://github.com/openai/gym/blob/master/gym/envs/mujoco/half_cheetah_v3.py\n \"\"\"\n\n name: str = \"cth\"\n\n def __init__(\n self,\n frame_skip: int = 5,\n dt: Optional[float] = None,\n max_steps: int = 1000,\n task_args: Optional[dict] = None,\n ):\n \"\"\"\n Constructor\n\n :param frame_skip: number of simulation frames for which the same action is held, results in a multiplier of\n the time step size `dt`\n :param dt: by default the time step size is the one from the mujoco config file multiplied by the number of\n frame skips (legacy from OpenAI environments). By passing an explicit `dt` value, this can be\n overwritten. Possible use case if if you know that you recorded a trajectory with a specific `dt`.\n :param max_steps: max number of simulation time steps\n :param task_args: arguments for the task construction, e.g `dict(fwd_rew_weight=1.)`\n \"\"\"\n # Call MujocoSimEnv's constructor\n model_path = osp.join(osp.dirname(__file__), \"assets\", \"openai_half_cheetah.xml\")\n super().__init__(model_path, frame_skip, dt, max_steps, task_args)\n\n # Initial state\n noise_halfspan = self.domain_param[\"reset_noise_halfspan\"]\n min_init_qpos = self.init_qpos - np.full_like(self.init_qpos, noise_halfspan)\n max_init_qpos = self.init_qpos + np.full_like(self.init_qpos, noise_halfspan)\n min_init_qvel = self.init_qvel - np.full_like(self.init_qpos, noise_halfspan)\n max_init_qvel = self.init_qvel + np.full_like(self.init_qpos, noise_halfspan)\n min_init_state = np.concatenate([min_init_qpos, min_init_qvel]).ravel()\n max_init_state = np.concatenate([max_init_qpos, max_init_qvel]).ravel()\n self._init_space = BoxSpace(min_init_state, max_init_state)\n\n self.camera_config = dict(distance=5.0)\n\n @property\n def state_space(self) -> Space:\n state_shape = np.concatenate([self.sim.data.qpos, self.sim.data.qvel]).shape\n return BoxSpace(-pyrado.inf, pyrado.inf, shape=state_shape)\n\n @property\n def obs_space(self) -> Space:\n obs_shape = self.observe(self.state_space.bound_up).shape\n return BoxSpace(-pyrado.inf, pyrado.inf, shape=obs_shape)\n\n @property\n def act_space(self) -> Space:\n act_bounds = self.model.actuator_ctrlrange.copy().T\n return BoxSpace(*act_bounds, labels=[\"bthigh\", \"bshin\", \"bfoot\", \"fthigh\", \"fshin\", \"ffoot\"])\n\n @classmethod\n def get_nominal_domain_param(cls) -> dict:\n return dict(\n reset_noise_halfspan=0.0, # fixed initial state by default\n total_mass=14,\n tangential_friction_coeff=0.4,\n torsional_friction_coeff=0.1,\n rolling_friction_coeff=0.1,\n )\n\n def _create_task(self, task_args: dict) -> Task:\n if \"fwd_rew_weight\" not in task_args:\n task_args[\"fwd_rew_weight\"] = 1.0\n if \"ctrl_cost_weight\" not in task_args:\n task_args[\"ctrl_cost_weight\"] = 0.1\n\n return GoallessTask(self.spec, ForwardVelocityRewFcn(self._dt, idx_fwd=0, **task_args))\n\n def _mujoco_step(self, act: np.ndarray) -> dict:\n self.sim.data.ctrl[:] = act\n self.sim.step()\n\n pos = self.sim.data.qpos.copy()\n vel = self.sim.data.qvel.copy()\n self.state = np.concatenate([pos, vel])\n\n return dict()\n\n def observe(self, state: np.ndarray) -> np.ndarray:\n # Ignore horizontal position to maintain translational invariance\n return state[1:].copy()\n", "# Copyright (c) 2020, Fabio Muratore, Honda Research Institute Europe GmbH, and\n# Technical University of Darmstadt.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n# 1. Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# 2. Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n# 3. Neither the name of Fabio Muratore, Honda Research Institute Europe GmbH,\n# or Technical University of Darmstadt, nor the names of its contributors may\n# be used to endorse or promote products derived from this software without\n# specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL FABIO MURATORE, HONDA RESEARCH INSTITUTE EUROPE GMBH,\n# OR TECHNICAL UNIVERSITY OF DARMSTADT BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER\n# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\nfrom typing import Callable, Iterable, List, Optional, Sequence, Tuple, Union\n\nimport torch as to\nimport torch.cuda as cuda\nimport torch.nn as nn\nfrom torch.nn.utils import convert_parameters as cp\n\nimport pyrado\nfrom pyrado.policies.base import Policy\nfrom pyrado.policies.initialization import init_param\nfrom pyrado.spaces.discrete import DiscreteSpace\nfrom pyrado.utils.data_types import EnvSpec\n\n\nclass FNN(nn.Module):\n \"\"\"Feed-forward neural network\"\"\"\n\n def __init__(\n self,\n input_size: int,\n output_size: int,\n hidden_sizes: Sequence[int],\n hidden_nonlin: Union[Callable, Sequence[Callable]],\n dropout: Optional[float] = 0.0,\n output_nonlin: Optional[Callable] = None,\n init_param_kwargs: Optional[dict] = None,\n use_cuda: bool = False,\n ):\n \"\"\"\n Constructor\n\n :param input_size: number of inputs\n :param output_size: number of outputs\n :param hidden_sizes: sizes of hidden layers (every entry creates one hidden layer)\n :param hidden_nonlin: nonlinearity for hidden layers\n :param dropout: dropout probability, default = 0 deactivates dropout\n :param output_nonlin: nonlinearity for output layer\n :param init_param_kwargs: additional keyword arguments for the policy parameter initialization\n :param use_cuda: `True` to move the policy to the GPU, `False` (default) to use the CPU\n \"\"\"\n self._device = \"cuda\" if use_cuda and cuda.is_available() else \"cpu\"\n\n super().__init__() # init nn.Module\n\n self.hidden_nonlin = (\n hidden_nonlin if isinstance(hidden_nonlin, Iterable) else len(hidden_sizes) * [hidden_nonlin]\n )\n self.dropout = dropout\n self.output_nonlin = output_nonlin\n\n # Create hidden layers (stored in ModuleList so their parameters are tracked)\n self.hidden_layers = nn.ModuleList()\n last_size = input_size\n for hs in hidden_sizes:\n self.hidden_layers.append(nn.Linear(last_size, hs))\n # Current output size is next layer input size\n last_size = hs\n # Add a dropout layer after every hidden layer\n if self.dropout > 0:\n self.hidden_layers.append(nn.Dropout(p=self.dropout))\n\n # Create output layer\n self.output_layer = nn.Linear(last_size, output_size)\n\n # Initialize parameter values\n init_param_kwargs = init_param_kwargs if init_param_kwargs is not None else dict()\n self.init_param(None, **init_param_kwargs)\n self.to(self.device)\n\n @property\n def device(self) -> str:\n \"\"\"Get the device (CPU or GPU) on which the FNN is stored.\"\"\"\n return self._device\n\n @property\n def param_values(self) -> to.Tensor:\n \"\"\"\n Get the parameters of the policy as 1d array.\n The values are copied, modifying the return value does not propagate to the actual policy parameters.\n \"\"\"\n return cp.parameters_to_vector(self.parameters())\n\n @param_values.setter\n def param_values(self, param: to.Tensor):\n \"\"\"Set the policy parameters from an 1d array.\"\"\"\n cp.vector_to_parameters(param, self.parameters())\n\n def init_param(self, init_values: Optional[to.Tensor] = None, **kwargs):\n \"\"\"\n Initialize the network's parameters. By default the parameters are initialized randomly.\n\n :param init_values: Tensor of fixed initial network parameter values\n \"\"\"\n if init_values is None:\n # Initialize hidden layers\n for i, layer in enumerate(self.hidden_layers):\n if self.dropout == 0:\n # If there is no dropout, initialize weights and biases for every layer\n init_param(layer, **kwargs)\n elif self.dropout > 0 and i % 2 == 0:\n # If there is dropout, omit the initialization for the dropout layers\n init_param(layer, **kwargs)\n\n # Initialize output layer\n init_param(self.output_layer, **kwargs)\n\n else:\n self.param_values = init_values\n\n def forward(self, obs: to.Tensor) -> to.Tensor:\n obs = obs.to(device=self.device)\n\n # Pass input through hidden layers\n next_input = obs\n for i, layer in enumerate(self.hidden_layers):\n next_input = layer(next_input)\n # Apply non-linearity if any\n if self.dropout == 0:\n # If there is no dropout, apply the nonlinearity to every layer\n if self.hidden_nonlin[i] is not None:\n next_input = self.hidden_nonlin[i](next_input)\n elif self.dropout > 0 and i % 2 == 0:\n # If there is dropout, only apply the nonlinearity to every second layer\n if self.hidden_nonlin[i // 2] is not None:\n next_input = self.hidden_nonlin[i // 2](next_input)\n\n # And through the output layer\n output = self.output_layer(next_input)\n if self.output_nonlin is not None:\n output = self.output_nonlin(output)\n\n return output\n\n\nclass FNNPolicy(Policy):\n \"\"\"Feed-forward neural network policy\"\"\"\n\n name: str = \"fnn\"\n\n def __init__(\n self,\n spec: EnvSpec,\n hidden_sizes: Sequence[int],\n hidden_nonlin: Union[Callable, Sequence[Callable]],\n dropout: Optional[float] = 0.0,\n output_nonlin: Optional[Callable] = None,\n init_param_kwargs: Optional[dict] = None,\n use_cuda: bool = False,\n ):\n \"\"\"\n Constructor\n\n :param spec: environment specification\n :param hidden_sizes: sizes of hidden layer outputs. Every entry creates one hidden layer.\n :param hidden_nonlin: nonlinearity for hidden layers\n :param dropout: dropout probability, default = 0 deactivates dropout\n :param output_nonlin: nonlinearity for output layer\n :param init_param_kwargs: additional keyword arguments for the policy parameter initialization\n :param use_cuda: `True` to move the policy to the GPU, `False` (default) to use the CPU\n \"\"\"\n super().__init__(spec, use_cuda)\n\n # Create the feed-forward neural network\n self.net = FNN(\n input_size=spec.obs_space.flat_dim+1,\n output_size=spec.act_space.flat_dim,\n hidden_sizes=hidden_sizes,\n hidden_nonlin=hidden_nonlin,\n dropout=dropout,\n output_nonlin=output_nonlin,\n use_cuda=use_cuda,\n )\n\n # Call custom initialization function after PyTorch network parameter initialization\n init_param_kwargs = init_param_kwargs if init_param_kwargs is not None else dict()\n self.init_param(None, **init_param_kwargs)\n self.to(self.device)\n\n def init_param(self, init_values: to.Tensor = None, **kwargs):\n if init_values is None:\n # Forward to the FNN's custom initialization function (handles dropout)\n self.net.init_param(init_values, **kwargs)\n else:\n self.param_values = init_values\n\n def forward(self, obs: to.Tensor) -> to.Tensor:\n # Get the action from the owned FNN\n\n obs = to.cat([obs[:,0].unsqueeze(-1), to.sin(obs[:, 1]).unsqueeze(-1), to.cos(obs[:, 1]).unsqueeze(-1), obs[:, 2:]], dim=1)\n return self.net(obs)\n\n\nclass DiscreteActQValPolicy(Policy):\n \"\"\"State-action value (Q-value) feed-forward neural network policy for discrete actions\"\"\"\n\n name: str = \"discrqval\"\n\n def __init__(self, spec: EnvSpec, net: nn.Module, init_param_kwargs: Optional[dict] = None, use_cuda: bool = False):\n \"\"\"\n Constructor\n\n :param spec: environment specification\n :param net: module that approximates the Q-values given the observations and possible (discrete) actions.\n Make sure to create this object with the correct input and output sizes by using\n `DiscreteActQValPolicy.get_qfcn_input_size()` and `DiscreteActQValPolicy.get_qfcn_output_size()`.\n :param init_param_kwargs: additional keyword arguments for the policy parameter initialization\n :param use_cuda: `True` to move the policy to the GPU, `False` (default) to use the CPU\n \"\"\"\n\n if not isinstance(spec.act_space, DiscreteSpace):\n raise pyrado.TypeErr(given=spec.act_space, expected_type=DiscreteSpace)\n if not isinstance(net, nn.Module):\n raise pyrado.TypeErr(given=net, expected_type=nn.Module)\n\n # Call Policy's constructor\n super().__init__(spec, use_cuda)\n\n # Store the feed-forward neural network\n self.net = net\n\n # Call custom initialization function after PyTorch network parameter initialization\n init_param_kwargs = init_param_kwargs if init_param_kwargs is not None else dict()\n self.init_param(None, **init_param_kwargs)\n\n # Make sure the net runs on the correct device\n self.to(self.device)\n self.net._device = self.device\n\n @staticmethod\n def get_qfcn_input_size(spec: EnvSpec) -> int:\n \"\"\"Get the flat input size.\"\"\"\n return spec.obs_space.flat_dim + spec.act_space.ele_dim\n\n @staticmethod\n def get_qfcn_output_size() -> int:\n \"\"\"Get the flat output size.\"\"\"\n return 1\n\n def init_param(self, init_values: to.Tensor = None, **kwargs):\n if init_values is None:\n if isinstance(self.net, FNN):\n # Forward to the FNN's custom initialization function (handles dropout)\n self.net.init_param(init_values, **kwargs)\n else:\n # Initialize using default initialization\n init_param(self.net, **kwargs)\n else:\n self.param_values = init_values\n\n def _build_q_table(self, obs: to.Tensor) -> Tuple[to.Tensor, to.Tensor, int]:\n \"\"\"\n Compute the state-action values for the given observations and all possible actions.\n Since we operate on a discrete action space, we can construct a table (here for 3 actions)\n o_1 a_1\n o_1 a_2\n o_1 a_3\n ...\n o_N a_1\n o_N a_2\n o_N a_3\n\n :param obs: current observations\n :return: Q-values for all state-action combinations of dimension batch_size x act_space_flat_sim,\n indices, batch size\n \"\"\"\n # We assume flattened observations, if they are 2d, they're batched.\n if len(obs.shape) == 1:\n batch_size = 1\n elif len(obs.shape) == 2:\n batch_size = obs.shape[0]\n else:\n raise pyrado.ShapeErr(msg=f\"Expected 1- or 2-dim observations, but the shape is {obs.shape}!\")\n\n assert isinstance(self.env_spec.act_space, DiscreteSpace)\n\n # Create batched state-action table\n obs = to.atleast_2d(obs) # batch dim is along first axis, then transposed\n columns_obs = obs.repeat_interleave(repeats=self.env_spec.act_space.num_ele, dim=0)\n columns_act = to.from_numpy(self.env_spec.act_space.eles).to(dtype=to.get_default_dtype())\n columns_act = columns_act.repeat(batch_size, 1)\n\n # Batch process via PyTorch Module class\n table = to.cat([columns_obs.to(self.device), columns_act.to(self.device)], dim=1)\n q_vals = self.net(table)\n\n # Reshaped (different actions are over columns)\n q_vals = q_vals.reshape(-1, self.env_spec.act_space.num_ele)\n\n # Select the action that maximizes the Q-value\n argmax_act_idcs = to.argmax(q_vals, dim=1)\n\n return q_vals, argmax_act_idcs, batch_size\n\n def q_values_argmax(self, obs: to.Tensor) -> to.Tensor:\n \"\"\"\n Compute the state-action values for the given observations and the actions that maximize the estimated Q-Values.\n Since we operate on a discrete action space, we can construct a table.\n\n :param obs: current observations\n :return: Q-values for state-action combinations where the argmax actions, dimension equals flat action space dimension\n \"\"\"\n obs = obs.to(device=self.device)\n\n # Get the Q-values from the owned net\n q_vals, argmax_act_idcs, batch_size = self._build_q_table(obs)\n\n # Select the Q-values from the that the policy would have selected\n q_vals_argamx = q_vals.gather(dim=1, index=argmax_act_idcs.view(-1, 1)).squeeze(1) # select columns-wise\n\n return q_vals_argamx.squeeze(1) if batch_size == 1 else q_vals_argamx\n\n def forward(self, obs: to.Tensor) -> to.Tensor:\n obs = obs.to(device=self.device)\n\n # Get the Q-values from the owned net\n q_vals, argmax_act_idcs, batch_size = self._build_q_table(obs)\n\n # Select the actions with the highest Q-value\n assert isinstance(self.env_spec.act_space, DiscreteSpace)\n\n possible_acts = to.from_numpy(self.env_spec.act_space.eles) # could be affected by domain randomization\n possible_acts = possible_acts.view(1, -1).to(self.device)\n acts = possible_acts.repeat(batch_size, 1)\n act = acts.gather(dim=1, index=argmax_act_idcs.view(-1, 1)) # select column-wise\n\n return act.squeeze(0) if batch_size == 1 else act\n", "# Copyright (c) 2020, Fabio Muratore, Honda Research Institute Europe GmbH, and\n# Technical University of Darmstadt.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n# 1. Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# 2. Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n# 3. Neither the name of Fabio Muratore, Honda Research Institute Europe GmbH,\n# or Technical University of Darmstadt, nor the names of its contributors may\n# be used to endorse or promote products derived from this software without\n# specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL FABIO MURATORE, HONDA RESEARCH INSTITUTE EUROPE GMBH,\n# OR TECHNICAL UNIVERSITY OF DARMSTADT BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER\n# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\nimport sys\nfrom copy import deepcopy\nfrom typing import Optional, Tuple\n\nimport numpy as np\nimport torch as to\nimport torch.nn as nn\nfrom tqdm import tqdm\n\nimport pyrado\nfrom pyrado.algorithms.base import Algorithm\nfrom pyrado.algorithms.step_based.value_based import ValueBased\nfrom pyrado.environments.base import Env\nfrom pyrado.exploration.stochastic_action import EpsGreedyExplStrat\nfrom pyrado.logger.step import StepLogger\nfrom pyrado.policies.base import Policy\nfrom pyrado.policies.feed_back.fnn import DiscreteActQValPolicy\nfrom pyrado.sampling.cvar_sampler import CVaRSampler\nfrom pyrado.sampling.parallel_rollout_sampler import ParallelRolloutSampler\n\n\nclass DQL(ValueBased):\n \"\"\"\n Deep Q-Learning (without bells and whistles)\n\n .. seealso::\n [1] V. Mnih et.al., \"Human-level control through deep reinforcement learning\", Nature, 2015\n \"\"\"\n\n name: str = \"dql\"\n\n def __init__(\n self,\n save_dir: pyrado.PathLike,\n env: Env,\n policy: DiscreteActQValPolicy,\n memory_size: int,\n eps_init: float,\n eps_schedule_gamma: float,\n gamma: float,\n max_iter: int,\n num_updates_per_step: int,\n target_update_intvl: Optional[int] = 5,\n num_init_memory_steps: Optional[int] = None,\n min_rollouts: Optional[int] = None,\n min_steps: Optional[int] = None,\n batch_size: int = 256,\n eval_intvl: int = 100,\n max_grad_norm: float = 0.5,\n lr: float = 5e-4,\n lr_scheduler=None,\n lr_scheduler_hparam: Optional[dict] = None,\n num_workers: int = 4,\n logger: Optional[StepLogger] = None,\n use_trained_policy_for_refill: bool = False,\n ):\n r\"\"\"\n Constructor\n\n :param save_dir: directory to save the snapshots i.e. the results in\n :param env: the environment which the policy operates\n :param policy: (current) Q-network updated by this algorithm\n :param memory_size: number of transitions in the replay memory buffer\n :param eps_init: initial value for the probability of taking a random action, constant if `eps_schedule_gamma=1`\n :param eps_schedule_gamma: temporal discount factor for the exponential decay of epsilon\n :param gamma: temporal discount factor for the state values\n :param max_iter: maximum number of iterations (i.e. policy updates) that this algorithm runs\n :param num_updates_per_step: number of (batched) updates per algorithm steps\n :param target_update_intvl: number of iterations that pass before updating the `qfcn_targ` network\n :param num_init_memory_steps: number of samples used to initially fill the replay buffer with, pass `None` to\n fill the buffer completely\n :param min_rollouts: minimum number of rollouts sampled per policy update batch\n :param min_steps: minimum number of state transitions sampled per policy update batch\n :param batch_size: number of samples per policy update batch\n :param eval_intvl: interval in which the evaluation rollouts are collected, also the interval in which the\n logger prints the summary statistics\n :param max_grad_norm: maximum L2 norm of the gradients for clipping, set to `None` to disable gradient clipping\n :param lr: (initial) learning rate for the optimizer which can be by modified by the scheduler.\n By default, the learning rate is constant.\n :param lr_scheduler: learning rate scheduler that does one step per epoch (pass through the whole data set)\n :param lr_scheduler_hparam: hyper-parameters for the learning rate scheduler\n :param num_workers: number of environments for parallel sampling\n :param logger: logger for every step of the algorithm, if `None` the default logger will be created\n :param use_trained_policy_for_refill: whether to use the trained policy instead of a dummy policy to refill the\n replay buffer after resets\n \"\"\"\n if not isinstance(policy, DiscreteActQValPolicy):\n raise pyrado.TypeErr(given=policy, expected_type=DiscreteActQValPolicy)\n\n # Call ValueBased's constructor\n super().__init__(\n save_dir=save_dir,\n env=env,\n policy=policy,\n memory_size=memory_size,\n gamma=gamma,\n max_iter=max_iter,\n num_updates_per_step=num_updates_per_step,\n target_update_intvl=target_update_intvl,\n num_init_memory_steps=num_init_memory_steps,\n min_rollouts=min_rollouts,\n min_steps=min_steps,\n batch_size=batch_size,\n eval_intvl=eval_intvl,\n max_grad_norm=max_grad_norm,\n num_workers=num_workers,\n logger=logger,\n use_trained_policy_for_refill=use_trained_policy_for_refill,\n )\n\n self.qfcn_targ = deepcopy(self._policy).eval() # will not be trained using the optimizer\n self.eps = eps_init\n\n # Create sampler for exploration during training\n self._expl_strat = EpsGreedyExplStrat(self._policy, eps_init, eps_schedule_gamma)\n self._sampler = ParallelRolloutSampler(\n self._env,\n self._expl_strat,\n num_workers=num_workers if min_steps != 1 else 1,\n min_steps=min_steps,\n min_rollouts=min_rollouts,\n )\n\n # Q-function optimizer\n self.optim = to.optim.RMSprop([{\"params\": self._policy.parameters()}], lr=lr)\n\n # Learning rate scheduler\n self._lr_scheduler = lr_scheduler\n self._lr_scheduler_hparam = lr_scheduler_hparam\n if lr_scheduler is not None:\n self._lr_scheduler = lr_scheduler(self.optim, **lr_scheduler_hparam)\n\n @property\n def sampler(self) -> ParallelRolloutSampler:\n return self._sampler\n\n @sampler.setter\n def sampler(self, sampler: ParallelRolloutSampler):\n if not isinstance(sampler, (ParallelRolloutSampler, CVaRSampler)):\n raise pyrado.TypeErr(given=sampler, expected_type=(ParallelRolloutSampler, CVaRSampler))\n self._sampler = sampler\n\n @staticmethod\n def loss_fcn(q_vals: to.Tensor, expected_q_vals: to.Tensor) -> to.Tensor:\n r\"\"\"\n The Huber loss function on the one-step TD error $\\delta = Q(s,a) - (r + \\gamma \\max_a Q(s^\\prime, a))$.\n\n :param q_vals: state-action values $Q(s,a)$, from policy network\n :param expected_q_vals: expected state-action values $r + \\gamma \\max_a Q(s^\\prime, a)$, from target network\n :return: loss value\n \"\"\"\n return nn.functional.smooth_l1_loss(q_vals, expected_q_vals)\n\n def update(self):\n \"\"\"Update the policy's and qfcn_targ Q-function's parameters on transitions sampled from the replay memory.\"\"\"\n losses = to.zeros(self.num_batch_updates)\n policy_grad_norm = to.zeros(self.num_batch_updates)\n\n for b in tqdm(\n range(self.num_batch_updates),\n total=self.num_batch_updates,\n desc=f\"Updating\",\n unit=\"batches\",\n file=sys.stdout,\n leave=False,\n ):\n\n # Sample steps and the associated next step from the replay memory\n steps, next_steps = self._memory.sample(self.batch_size)\n steps.torch(data_type=to.get_default_dtype())\n next_steps.torch(data_type=to.get_default_dtype())\n\n # Create masks for the non-final observations\n not_done = to.from_numpy(1.0 - steps.done).to(device=self.policy.device, dtype=to.get_default_dtype())\n\n # Compute the state-action values Q(s,a) using the current DQN policy\n q_vals = self.expl_strat.policy.q_values_argmax(steps.observations)\n\n # Compute the second term of TD-error\n with to.no_grad():\n next_v_vals = self.qfcn_targ.q_values_argmax(next_steps.observations)\n expected_q_val = steps.rewards.to(self.policy.device) + not_done * self.gamma * next_v_vals\n\n # Compute the loss, clip the gradients if desired, and do one optimization step\n loss = DQL.loss_fcn(q_vals, expected_q_val)\n losses[b] = loss.data\n self.optim.zero_grad()\n loss.backward()\n policy_grad_norm[b] = Algorithm.clip_grad(self.expl_strat.policy, self.max_grad_norm)\n self.optim.step()\n\n # Update the qfcn_targ network by copying all weights and biases from the DQN policy\n if (self._curr_iter * self.num_batch_updates + b) % self.target_update_intvl == 0:\n self.qfcn_targ.load_state_dict(self.expl_strat.policy.state_dict())\n\n # Schedule the exploration parameter epsilon\n self.expl_strat.schedule_eps(self._curr_iter)\n\n # Update the learning rate if a scheduler has been specified\n if self._lr_scheduler is not None:\n self._lr_scheduler.step()\n\n # Logging\n with to.no_grad():\n self.logger.add_value(\"loss after\", to.mean(losses), 4)\n self.logger.add_value(\"expl strat eps\", self.expl_strat.eps, 4)\n self.logger.add_value(\"avg grad norm policy\", to.mean(policy_grad_norm), 4)\n if self._lr_scheduler is not None:\n self.logger.add_value(\"avg lr\", np.mean(self._lr_scheduler.get_last_lr()), 6)\n\n def reset(self, seed: Optional[int] = None):\n # Reset samplers, replay memory, exploration strategy, internal variables and the random seeds\n super().reset(seed)\n\n # Reset the learning rate scheduler\n if self._lr_scheduler is not None:\n self._lr_scheduler.last_epoch = -1\n\n def init_modules(self, warmstart: bool, suffix: str = \"\", prefix: str = \"\", **kwargs):\n # Initialize the policy\n super().init_modules(warmstart, suffix, prefix, **kwargs)\n\n if prefix == \"\":\n prefix = f\"iter_{self._curr_iter - 1}\"\n\n tpi = kwargs.get(\"target_param_init\", None)\n\n if warmstart and tpi is not None:\n self.qfcn_targ.init_param(tpi)\n elif warmstart and tpi is None and self._curr_iter > 0:\n self.qfcn_targ = pyrado.load(\n \"qfcn_target.pt\", self.save_dir, prefix=prefix, suffix=suffix, obj=self.qfcn_targ\n )\n else:\n # Reset the target Q-function\n self.qfcn_targ.init_param()\n\n def save_snapshot(self, meta_info: dict = None):\n super().save_snapshot(meta_info)\n\n if meta_info is None:\n # This algorithm instance is not a subroutine of another algorithm\n pyrado.save(self.qfcn_targ, \"qfcn_target.pt\", self.save_dir, use_state_dict=True)\n\n else:\n # This algorithm instance is a subroutine of another algorithm\n pyrado.save(\n self.qfcn_targ,\n \"qfcn_target.pt\",\n self.save_dir,\n prefix=meta_info.get(\"prefix\", \"\"),\n suffix=meta_info.get(\"suffix\", \"\"),\n use_state_dict=True,\n )\n\n def load_snapshot(self, parsed_args) -> Tuple[Env, Policy, dict]:\n env, policy, extra = super().load_snapshot(parsed_args)\n\n # Algorithm specific\n ex_dir = self._save_dir or getattr(parsed_args, \"dir\", None)\n if self.name == \"dql\":\n extra[\"qfcn_target\"] = pyrado.load(\"qfcn_target.pt\", ex_dir, obj=self.qfcn_targ, verbose=True)\n\n return env, policy, extra\n" ]
[ [ "numpy.concatenate", "numpy.full_like" ], [ "torch.atleast_2d", "torch.nn.Dropout", "torch.sin", "torch.nn.ModuleList", "torch.from_numpy", "torch.nn.Linear", "torch.cuda.is_available", "torch.get_default_dtype", "torch.cos", "torch.argmax" ], [ "torch.mean", "torch.zeros", "torch.from_numpy", "torch.no_grad", "torch.nn.functional.smooth_l1_loss", "torch.get_default_dtype" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
guidj/attx
[ "6a17ed393ab1f1723e7a9d8890da6313bb96c75f" ]
[ "py/tests/test_tensor_ops.py" ]
[ "import pytest\nimport tensorflow as tf\nimport numpy as np\n\nfrom attx import tensor_ops\n\n\ndef test_single_example_batch_single_step_sequence_with_high_dimension():\n # (?, k, dk) = (1, 1, 4)\n query_1 = [[1, 2, 3, 4]]\n key_1 = [[1, 1, 1, 1]]\n value_1 = [[10, 10, 10, 10]]\n\n query = tf.cast([query_1], tf.float32)\n key = tf.cast([key_1], tf.float32)\n value = tf.cast([value_1], tf.float32)\n\n expected_att_1 = [[1.0]]\n expected_output_1 = [[10.0, 10.0, 10.0, 10.0]]\n\n expected_attention = np.array([expected_att_1])\n expected_value = np.array([expected_output_1])\n\n output_attention, output_value = tensor_ops.attention(query, key, value)\n\n np.testing.assert_array_almost_equal(\n output_attention, expected_attention, decimal=3,\n )\n np.testing.assert_array_almost_equal(output_value, expected_value, decimal=3)\n\n\ndef test_single_example_batch_multi_step_sequence_with_high_dimension():\n # (?, k, dk) = (1, 2, 4)\n query_1 = [[1, 3, 5, 7], [2, 4, 6, 8]]\n key_1 = [[1, 1, 1, 1], [1, 1, 1, 1]]\n value_1 = [[10, 10, 10, 10], [50, 50, 50, 50]]\n\n query = tf.cast([query_1], tf.float32)\n key = tf.cast([key_1], tf.float32)\n value = tf.cast([value_1], tf.float32)\n\n expected_att_1 = [[0.5, 0.5], [0.5, 0.5]]\n expected_output_1 = [[30.0, 30.0, 30.0, 30.0], [30.0, 30.0, 30.0, 30.0]]\n\n expected_attention = np.array([expected_att_1])\n expected_value = np.array([expected_output_1])\n\n output_attention, output_value = tensor_ops.attention(query, key, value)\n\n np.testing.assert_array_almost_equal(\n output_attention, expected_attention, decimal=3,\n )\n np.testing.assert_array_almost_equal(output_value, expected_value, decimal=3)\n\n\ndef test_single_example_batch_multi_step_sequence_with_single_dimension():\n # (?, k, dk) = (1, 4, 1)\n query_1 = [[1], [2], [3], [4]]\n key_1 = [[1], [1], [1], [1]]\n value_1 = [10], [10], [10], [10]\n\n query = tf.cast([query_1], tf.float32)\n key = tf.cast([key_1], tf.float32)\n value = tf.cast([value_1], tf.float32)\n\n expected_att_1 = [\n [1 / 4, 1 / 4, 1 / 4, 1 / 4],\n [1 / 4, 1 / 4, 1 / 4, 1 / 4],\n [1 / 4, 1 / 4, 1 / 4, 1 / 4],\n [1 / 4, 1 / 4, 1 / 4, 1 / 4],\n ]\n expected_output_1 = [[10], [10], [10], [10]]\n\n expected_attention = np.array([expected_att_1])\n expected_value = np.array([expected_output_1])\n\n output_attention, output_value = tensor_ops.attention(query, key, value)\n\n np.testing.assert_array_almost_equal(\n output_attention, expected_attention, decimal=3,\n )\n np.testing.assert_array_almost_equal(output_value, expected_value, decimal=3)\n\n\ndef test_multi_example_batch_multi_step_sequence_with_high_dimension():\n # (?, k, dk) = (2, 2, 4)\n query_1 = [[1, 3, 5, 7], [2, 4, 6, 8]]\n query_2 = [[1, 3, 5, 7], [2, 4, 6, 8]]\n key_1 = [[1, 1, 1, 1], [1, 1, 1, 1]]\n key_2 = [[1, 2, 1, 2], [2, 1, 2, 1]]\n value_1 = [[10, 10, 10, 10], [50, 50, 50, 50]]\n value_2 = [[10, 10, 10, 10], [50, 50, 50, 50]]\n\n query = tf.cast([query_1, query_2], tf.float32)\n key = tf.cast([key_1, key_2], tf.float32)\n value = tf.cast([value_1, value_2], tf.float32,)\n\n expected_att_1 = [[0.5, 0.5], [0.5, 0.5]]\n expected_att_2 = [[0.881, 0.119], [0.881, 0.119]]\n expected_output_1 = [[30.0, 30.0, 30.0, 30.0], [30.0, 30.0, 30.0, 30.0]]\n expected_output_2 = [\n [369 / 25, 369 / 25, 369 / 25, 369 / 25],\n [369 / 25, 369 / 25, 369 / 25, 369 / 25],\n ]\n\n expected_attention = np.array([expected_att_1, expected_att_2])\n expected_value = np.array([expected_output_1, expected_output_2])\n\n output_attention, output_value = tensor_ops.attention(query, key, value)\n\n np.testing.assert_array_almost_equal(\n output_attention, expected_attention, decimal=3,\n )\n np.testing.assert_array_almost_equal(output_value, expected_value, decimal=2)\n\n\ndef test_single_example_batch_multi_step_sequence_with_high_dimension_and_different_value_dimension():\n # (?, k, dk) = (1, 2, 4)\n query_1 = [[1, 3, 5, 7], [2, 4, 6, 8]]\n key_1 = [[1, 1, 1, 1], [1, 1, 1, 1]]\n # (?, k, dv) = (1, 2, 5)\n value_1 = [[10, 10, 10, 10, 10], [50, 50, 50, 50, 50]]\n\n query = tf.cast([query_1], tf.float32)\n key = tf.cast([key_1], tf.float32)\n value = tf.cast([value_1], tf.float32)\n\n expected_att_1 = [[0.5, 0.5], [0.5, 0.5]]\n expected_output_1 = [[30.0, 30.0, 30.0, 30.0, 30.0], [30.0, 30.0, 30.0, 30.0, 30.0]]\n\n expected_attention = np.array([expected_att_1])\n expected_value = np.array([expected_output_1])\n\n output_attention, output_value = tensor_ops.attention(query, key, value)\n\n np.testing.assert_array_almost_equal(\n output_attention, expected_attention, decimal=3,\n )\n np.testing.assert_array_almost_equal(output_value, expected_value, decimal=3)\n" ]
[ [ "numpy.array", "tensorflow.cast", "numpy.testing.assert_array_almost_equal" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "1.12", "2.6", "2.2", "1.13", "2.3", "2.4", "1.4", "2.9", "1.5", "1.7", "2.5", "0.12", "1.0", "2.8", "1.2", "2.10" ] } ]
PolarNick239/Triangulum3D
[ "85c6a44f5c8f620bdc58164bd50ff89e1897f59d" ]
[ "tests/triangulum_test/test_support.py" ]
[ "#\n# Copyright (c) 2015, Nikolay Polyarnyi\n# All rights reserved.\n#\n\nimport yaml\nimport asyncio\nimport logging\nimport numpy as np\nimport pkg_resources\nfrom pathlib import Path\nfrom unittest import TestCase\n\nfrom triangulum.utils import support\nfrom triangulum.utils.support import str_dict, deep_merge\nfrom triangulum.rendering.gl import RenderingAsyncExecutor\n\n\nlogger = logging.getLogger(__name__)\n\n\nlogging.basicConfig(level=logging.DEBUG,\n format='%(relativeCreated)d [%(threadName)s]\\t%(name)s [%(levelname)s]:\\t %(message)s')\n\n\nresources_dir_path = Path(pkg_resources.get_provider('triangulum_test.resources').get_resource_filename(__name__, '.'))\n\n_default_test_config = {\n 'debug_output_dir': None,\n}\n\n\ndef load_config():\n config_path = str(resources_dir_path / \"test_config.yml\")\n try:\n with open(config_path) as f:\n user_config = yaml.load(f)\n config = deep_merge(_default_test_config, user_config)\n logger.debug(\"Using test config:\\n{}\".format(str_dict(config)))\n except FileNotFoundError:\n config = _default_test_config\n logger.debug(\"No config file found at '{}'.\".format(config_path))\n logger.debug(\"Using test config (default one):\\n{}\".format(str_dict(config)))\n return config\n\n\nclass TestBase(TestCase):\n\n def setUp(self):\n super().setUp()\n self.config = load_config()\n\n self.gl_executor = None\n self.releasables = []\n\n support.silent_make_dir(self.debug_dir())\n\n def get_gl_executor(self):\n if self.gl_executor is None:\n self.gl_executor = RenderingAsyncExecutor()\n return self.gl_executor\n\n def gl_executor_map(self, foo, *args):\n gl_executor = self.get_gl_executor()\n result = asyncio.get_event_loop().run_until_complete(gl_executor.map(foo, *args))\n return result\n\n def register_releasable(self, releasable):\n self.releasables.append(releasable)\n\n def with_debug_output(self):\n return self.config['debug_output_dir'] is not None\n\n def debug_dir(self):\n return Path(self.config['debug_output_dir']) / self.__class__.__name__\n\n def dump_debug_img(self, path, img):\n if self.with_debug_output():\n path = self.debug_dir() / path\n support.silent_make_dir(path.parent)\n support.save_image(path, img)\n\n def dump_debug_matrix_by_hue(self, path, mat):\n if self.with_debug_output():\n path = self.debug_dir() / path\n support.silent_make_dir(path.parent)\n img = support.array_to_rgb_by_hue(mat)[:, :, ::-1]\n img = np.uint8(img)\n support.save_image(path, img)\n\n def tearDown(self):\n super().tearDown()\n for releasable in self.releasables:\n self.gl_executor_map(releasable.release)\n" ]
[ [ "numpy.uint8" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
itsliupeng/automl
[ "a02038aa60bdf54e689758e5860e19c574d3638f" ]
[ "efficientdet/horovod_estimator/hooks.py" ]
[ "import io\nimport itertools\nimport os\nimport time\n\nimport cv2\n\ntry:\n import horovod.tensorflow as hvd\nexcept ImportError:\n hvd = None\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport tensorflow.compat.v1 as tf\nfrom PIL import Image\nfrom PIL import ImageDraw, ImageFont\nfrom sklearn.metrics import confusion_matrix\nfrom tensorflow.core.framework.summary_pb2 import Summary\nfrom tensorflow.python import pywrap_tensorflow\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.training import basic_session_run_hooks\nfrom tensorflow.python.training import checkpoint_management\nfrom tensorflow.python.training import training_util\nfrom tensorflow.python.training.session_run_hook import SessionRunArgs\nfrom collections import OrderedDict\n\nfrom horovod_estimator.utis import hvd_info_rank0, is_rank0\n\nmpl.use('Agg')\nnp.seterr(divide='ignore', invalid='ignore')\n\n\nclass BroadcastGlobalVariablesHook(tf.train.SessionRunHook):\n \"\"\"\n SessionRunHook that will broadcast all global variables from root rank\n to all other processes during initialization.\n\n This is necessary to ensure consistent initialization of all workers when\n training is started with random weights or restored from a checkpoint.\n \"\"\"\n\n def __init__(self, root_rank, pretrained_model_path=None, exclusions=[], device='', model_dir=None):\n \"\"\"Construct a new BroadcastGlobalVariablesHook that will broadcast all\n global variables from root rank to all other processes during initialization.\n\n Args:\n root_rank:\n Rank that will send data, other ranks will receive data.\n device:\n Device to be used for broadcasting. Uses GPU by default\n if Horovod was build with HOROVOD_GPU_BROADCAST.\n \"\"\"\n super(BroadcastGlobalVariablesHook, self).__init__()\n self.root_rank = root_rank\n self.bcast_op = None\n self.device = device\n self._pretrained_model_path = pretrained_model_path\n self._saver = None\n self._exclusions = set(exclusions)\n self._variables_to_restore = []\n self._model_dir = model_dir\n\n def begin(self):\n if not self.bcast_op or self.bcast_op.graph != tf.get_default_graph():\n with tf.device(self.device):\n self.bcast_op = hvd.broadcast_global_variables(self.root_rank)\n\n if self._model_dir is not None:\n checkpoint_path = checkpoint_management.latest_checkpoint(self._model_dir)\n if checkpoint_path is not None and not checkpoint_path.endswith('model.ckpt-0'):\n hvd_info_rank0('>>>>> model_dir {} has checkpoint {}, not using pretrained_model_path <<<<<'.\n format(self._model_dir, checkpoint_path))\n return\n\n if self._pretrained_model_path is not None and len(self._pretrained_model_path) > 0 and is_rank0():\n reader = pywrap_tensorflow.NewCheckpointReader(self._pretrained_model_path)\n var_to_shape_map = sorted(reader.get_variable_to_shape_map())\n\n self._exclusions.add('global_step')\n\n for var in tf.global_variables():\n if var.op.name in var_to_shape_map:\n excluded = False\n for exclusion in self._exclusions:\n if var.op.name.startswith(exclusion):\n excluded = True\n break\n if not excluded:\n self._variables_to_restore.append(var)\n\n self._saver = tf.train.Saver(var_list=self._variables_to_restore)\n\n def after_create_session(self, session, coord):\n if self._saver:\n hvd_info_rank0('>>>>> begin to load weights from {}, restore variables length {}, without variables {}'\n .format(self._pretrained_model_path, len(self._variables_to_restore), self._exclusions))\n self._saver.restore(session, self._pretrained_model_path)\n hvd_info_rank0('<<<<< end to load weights')\n\n hvd_info_rank0('>>>>> broadcast global variables begin during after_create_session')\n session.run(self.bcast_op)\n hvd_info_rank0('<<<<< broadcast global variables end during after_create_session ')\n\n\nclass LoggingTensorHook(tf.train.SessionRunHook):\n def __init__(self, named_tensor, summary_dir=None, every_n_iter=100, use_all_reduce=False):\n super(LoggingTensorHook, self).__init__()\n self._named_tensor = named_tensor\n self._every_n_iter = every_n_iter\n self._summary_dir = summary_dir\n self._step = 0\n self._use_all_reduce = use_all_reduce\n\n self._tic = time.time()\n self._avg_ops = {}\n self._global_step_tensor = None\n\n def begin(self):\n if self._use_all_reduce:\n self._avg_ops = OrderedDict({'{}'.format(tag): hvd.allreduce(basic_session_run_hooks._as_graph_element(tensor))\n for (tag, tensor) in self._named_tensor.items()})\n else:\n self._avg_ops = OrderedDict({'{}'.format(tag): basic_session_run_hooks._as_graph_element(tensor)\n for (tag, tensor) in self._named_tensor.items()})\n\n self._global_step_tensor = tf.train.get_or_create_global_step()\n self._avg_ops['step'] = self._global_step_tensor\n\n def before_run(self, run_context): # pylint: disable=unused-argument\n if self._step % self._every_n_iter == 0:\n return SessionRunArgs(fetches=self._avg_ops)\n\n self._tic = time.time()\n\n def _log_tensors(self, tensor_values):\n original = np.get_printoptions()\n np.set_printoptions(suppress=True)\n\n stats = []\n for tag, tensor in tensor_values.items():\n stats.append('%s = %s' % (tag, tensor))\n\n stats.append('%s = %s' % ('step_time', time.time() - self._tic))\n\n if self._use_all_reduce:\n logging_head = 'logging all reduce tensors'\n else:\n logging_head = 'logging tensors'\n\n hvd_info_rank0(\"{}: {}\".format(logging_head, \", \".join(stats)))\n np.set_printoptions(**original)\n\n def _summary(self, tensor_values):\n if self._summary_dir:\n writer = tf.summary.FileWriterCache.get(self._summary_dir)\n this_summary = tf.Summary()\n for tag, value in tensor_values.items():\n this_summary.value.add(tag='avg/{}'.format(tag), simple_value=value)\n writer.add_summary(this_summary, tensor_values['step'])\n\n writer.flush()\n\n def after_run(self, run_context, run_values):\n if self._step % self._every_n_iter == 0:\n if is_rank0() or not self._use_all_reduce:\n avg_values = run_values.results\n self._log_tensors(avg_values)\n self._summary(avg_values)\n\n self._step += 1\n\n\ndef make_image(tensor):\n \"\"\"Convert an numpy representation image to Image protobuf\"\"\"\n from PIL import Image\n height, width, channel = tensor.shape\n image = Image.fromarray(tensor)\n import io\n output = io.BytesIO()\n image.save(output, format='PNG')\n image_string = output.getvalue()\n output.close()\n return Summary.Image(height=height,\n width=width,\n colorspace=channel,\n encoded_image_string=image_string)\n\n\ndef to_fix_format(i):\n if isinstance(i, int) or isinstance(i, np.int32) or isinstance(i, np.int64):\n return str(i)\n else:\n return '{:.2f}'.format(i)\n\n\ndef draw_text_image(text, size=(224, 224)):\n # make a blank image for the text, initialized to transparent text color\n img = Image.new('RGB', size, (0, 0, 0))\n d = ImageDraw.Draw(img)\n\n # to-do: how to align\n # if len(text) <= 2:\n # font_size = 100\n # xy = (80, 60)\n # else:\n # font_size = 40\n # xy = (60, 90)\n\n xy = (10, 10)\n font_size = 20\n\n # get a font\n fnt = ImageFont.truetype('assets/fonts/FreeMono.ttf', size=font_size)\n # get a drawing context\n d.text(xy, text, font=fnt, fill=(255, 255, 255))\n return img\n\n\ndef scale_to_uint8(features_tensor):\n if len(features_tensor) > 0:\n min_f = np.min(features_tensor)\n max_f = np.max(features_tensor)\n features_tensor = (features_tensor - min_f) / (max_f - min_f) * 255\n features_tensor = features_tensor.astype(np.uint8)\n return features_tensor\n\n\ndef top_k_text(prob_array, k):\n sort_idx = np.argsort(prob_array)[-k:][::-1]\n top_k_prob = prob_array[sort_idx]\n top_k_idx = sort_idx\n\n result = ''\n for i in range(k):\n result += '{}: {}\\n'.format(top_k_idx[i], to_fix_format(top_k_prob[i]))\n\n return result.strip()\n\n\ndef find_xy(img, threshold=0.8, percentile=False):\n x_offset = 3\n y_offset = 3\n img = img[x_offset: -x_offset, y_offset: -y_offset]\n threshold = threshold * np.max(img)\n idx = np.argwhere(img > threshold)\n x_min = np.min(idx[:, 1]) + x_offset\n x_max = np.max(idx[:, 1]) + x_offset\n\n y_min = np.min(idx[:, 0]) + y_offset\n y_max = np.max(idx[:, 0]) + y_offset\n\n if percentile:\n h, w = img.shape\n x_min = x_min / w\n x_max = x_max / w\n y_min = y_min / h\n y_max = y_max / h\n\n x_max = min(1.0, x_max)\n y_max = min(1.0, y_max)\n\n return x_min, y_min, x_max, y_max\n\n\ndef draw_box(img_tensor, box):\n img = Image.fromarray(img_tensor)\n d = ImageDraw.Draw(img)\n x_min, y_min, x_max, y_max = box\n d.rectangle(((x_min, y_min), (x_max, y_max)), fill='white', outline=3)\n return np.asarray(img, dtype=np.uint8)\n\n\ndef show_images(filenames, images, raw_images, heat_map_features, labels, probs, global_step, max_images,\n summary_writer, prefix='train'):\n if summary_writer is not None:\n assert images is not None and labels is not None and probs is not None\n n, height, width, channel = images.shape\n padding_255 = np.ones([height, 1, channel], dtype=np.uint8) * 255\n padding_1 = np.ones([height, 1, channel], dtype=np.float32)\n\n filenames_tensor_list = []\n raw_images_tensor_list = []\n images_tensor_list = []\n heat_map_tensor_list = []\n label_tensor_list = []\n max_images = min(max_images, n)\n\n for i in range(max_images):\n images_tensor_list.append(images[i])\n images_tensor_list.append(padding_1)\n\n if raw_images is not None:\n raw_images_tensor_list.append(raw_images[i])\n raw_images_tensor_list.append(padding_1)\n\n if heat_map_features is not None:\n cam = heat_map_features[i][:, :, labels[i]]\n cam = cam - np.min(cam)\n cam_img = cam / np.max(cam)\n cam_img = np.uint8(255 * cam_img)\n heat_map = cv2.applyColorMap(cv2.resize(cam_img, (height, width)), cv2.COLORMAP_JET)\n blue_map = heat_map[:, :, -1]\n box = find_xy(blue_map)\n heat_map = draw_box(heat_map, box)\n heat_map = heat_map / 255.0\n heat_img = heat_map * 0.7 + images[i] * 0.3\n\n heat_map_tensor_list.append(heat_img)\n heat_map_tensor_list.append(padding_1)\n\n # labes & predicts\n probs_show_num = min(5, probs.shape[-1])\n text = '{}: {}\\n'.format(to_fix_format(labels[i]), to_fix_format(probs[i][labels[i]])) \\\n + top_k_text(probs[i], probs_show_num)\n label_image = draw_text_image(text, (height, width))\n label_tensor_list.append(np.asarray(label_image, dtype=np.uint8))\n label_tensor_list.append(padding_255)\n\n filename = filenames[i]\n if isinstance(filename, bytes):\n filename = filename.decode('utf-8')\n\n filename = filename.split('/')[-1]\n filename_image = draw_text_image(filename, (height, width))\n filenames_tensor_list.append(np.asarray(filename_image, dtype=np.uint8))\n filenames_tensor_list.append(padding_255)\n\n # scale float32 to unit8\n all_tensor_list = [scale_to_uint8(np.concatenate(filenames_tensor_list, axis=1))]\n if raw_images is not None:\n all_tensor_list.append(scale_to_uint8(np.concatenate(raw_images_tensor_list, axis=1)))\n\n all_tensor_list.append(scale_to_uint8(np.concatenate(images_tensor_list, axis=1)))\n\n if heat_map_features is not None:\n all_tensor_list.append(scale_to_uint8(np.concatenate(heat_map_tensor_list, axis=1)))\n\n all_tensor_list.append(np.concatenate(label_tensor_list, axis=1))\n\n feature_heatmap_label_tensor = np.concatenate(all_tensor_list, axis=0)\n summary = Summary(value=[Summary.Value(tag='{}/features_heatmap_labels'.format(prefix),\n image=make_image(feature_heatmap_label_tensor))])\n\n summary_writer.add_summary(summary, global_step)\n\n\ndef plt_to_image_summary(plt):\n buf = io.BytesIO()\n plt.savefig(buf, format='png')\n image = Image.open(buf).convert('RGB')\n tensor = np.asarray(image, dtype=np.uint8)\n image = make_image(tensor)\n return image\n\n\ndef confusion_matrix_summary(tag, cm, classes, normalize=False, recall=True, title='Confusion matrix',\n cmap=plt.cm.Blues):\n \"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n \"\"\"\n if normalize:\n if recall:\n s = cm.sum(axis=1)[:, np.newaxis] + np.finfo(np.float32).eps\n else:\n s = cm.sum(axis=0)[:, np.newaxis] + np.finfo(np.float32).eps\n\n cm = cm.astype('float') / s\n\n plt.close('all')\n\n f_size = max(5, int(0.6 * len(classes)))\n plt.figure(figsize=(f_size, f_size))\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar()\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes)\n plt.yticks(tick_marks, classes)\n\n fmt = '.2f' if normalize else 'd'\n thresh = cm.max() / 2.\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j, i, format(cm[i, j], fmt), horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n plt.tight_layout()\n\n image = plt_to_image_summary(plt)\n return Summary(value=[Summary.Value(tag=tag, image=image)])\n\n\ndef roc_summary(tag, y_true, y_pred, n_classes):\n import numpy as np\n import matplotlib.pyplot as plt\n from itertools import cycle\n from sklearn.metrics import roc_curve, auc\n from sklearn.preprocessing import label_binarize\n from scipy import interp\n\n classes = [i for i in range(n_classes)]\n y_true = label_binarize(y_true, classes=classes)\n y_pred = label_binarize(y_pred, classes=classes)\n\n fpr = dict()\n tpr = dict()\n roc_auc = dict()\n for i in range(n_classes):\n fpr[i], tpr[i], _ = roc_curve(y_true[:, i], y_pred[:, i])\n roc_auc[i] = auc(fpr[i], tpr[i])\n\n # Compute micro-average ROC curve and ROC area\n fpr[\"micro\"], tpr[\"micro\"], _ = roc_curve(y_true.ravel(), y_pred.ravel())\n roc_auc[\"micro\"] = auc(fpr[\"micro\"], tpr[\"micro\"])\n\n lw = 2\n\n # plt.figure(0)\n # plt.plot(fpr[2], tpr[2], color='darkorange',\n # lw=lw, label='ROC curve (area = %0.2f)' % roc_auc[2])\n # plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')\n # plt.xlim([0.0, 1.0])\n # plt.ylim([0.0, 1.05])\n # plt.xlabel('False Positive Rate')\n # plt.ylabel('True Positive Rate')\n # plt.title('Receiver operating characteristic example')\n # plt.legend(loc=\"lower right\")\n # plt.show()\n\n # Compute macro-average ROC curve and ROC area\n\n # First aggregate all false positive rates\n all_fpr = np.unique(np.concatenate([fpr[i] for i in range(n_classes)]))\n\n # Then interpolate all ROC curves at this points\n mean_tpr = np.zeros_like(all_fpr)\n for i in range(n_classes):\n mean_tpr += interp(all_fpr, fpr[i], tpr[i])\n\n # Finally average it and compute AUC\n mean_tpr /= n_classes\n\n fpr[\"macro\"] = all_fpr\n tpr[\"macro\"] = mean_tpr\n roc_auc[\"macro\"] = auc(fpr[\"macro\"], tpr[\"macro\"])\n\n # Plot all ROC curves\n plt.close('all')\n f_size = max(5, int(0.6 * len(classes)))\n plt.figure(figsize=(f_size, f_size))\n\n plt.plot(fpr[\"micro\"], tpr[\"micro\"],\n label='micro-average ROC curve (area = {0:0.2f})'\n ''.format(roc_auc[\"micro\"]),\n color='deeppink', linestyle=':', linewidth=4)\n\n plt.plot(fpr[\"macro\"], tpr[\"macro\"],\n label='macro-average ROC curve (area = {0:0.2f})'\n ''.format(roc_auc[\"macro\"]),\n color='navy', linestyle=':', linewidth=4)\n\n colors = cycle(['aqua', 'darkorange', 'cornflowerblue'])\n for i, color in zip(range(n_classes), colors):\n plt.plot(fpr[i], tpr[i], color=color, lw=lw,\n label='ROC curve of class {0} (area = {1:0.2f})'\n ''.format(i, roc_auc[i]))\n\n plt.plot([0, 1], [0, 1], 'k--', lw=lw)\n plt.xlim([0.0, 1.0])\n plt.ylim([0.0, 1.05])\n plt.xlabel('False Positive Rate')\n plt.ylabel('True Positive Rate')\n plt.title('Some extension of Receiver operating characteristic to multi-class')\n plt.legend(loc=\"lower right\")\n\n buf = io.BytesIO()\n plt.savefig(buf, format='png')\n image = Image.open(buf).convert('RGB')\n tensor = np.asarray(image, dtype=np.uint8)\n image = make_image(tensor)\n\n return Summary(value=[Summary.Value(tag=tag, image=image)])\n\n\nclass EvalImageVisualizationHook(tf.train.SessionRunHook):\n def __init__(self, images_name, labels_name, filenames_name, probs_name, raw_images_name=None,\n heat_map_features_name=None, every_n_steps=100, summary_dir=None, max_images=8):\n self._images_name = images_name\n self._labels_name = labels_name\n self._heat_map_features_name = heat_map_features_name\n self._probs_name = probs_name\n self._every_n_steps = every_n_steps\n self._summary_dir = summary_dir\n self._step = 0\n self._run_begin = 0\n self._run_end = 0\n self._max_images = max_images\n self._duration = 0.0\n self._raw_images_name = raw_images_name\n self._filenames_name = filenames_name\n\n def begin(self):\n self._summary_writer = tf.summary.FileWriterCache.get(self._summary_dir)\n self._global_step_tensor = training_util._get_or_create_global_step_read()\n\n def before_run(self, run_context):\n self._run_begin = time.time()\n if self._step > 0 and self._step % self._every_n_steps == 0:\n arg_map = {}\n\n for name in [self._images_name, self._labels_name, self._filenames_name, self._raw_images_name,\n self._heat_map_features_name, self._probs_name]:\n if name is not None:\n try:\n arg_map[name] = basic_session_run_hooks._as_graph_element(name)\n except Exception as e:\n if not self.is_logged:\n tf.logging.error('{} error {}'.format(name, e))\n self.is_logged = True\n\n arg_map['global_step'] = self._global_step_tensor\n return SessionRunArgs(arg_map)\n\n def _log_and_record(self, step):\n if self._summary_writer is not None:\n if self._total_batch_size:\n img_per_sec_tag = 'eval/img_per_sec'\n img_per_sec_tag_value = self._total_batch_size / (self._run_end - self._run_begin)\n sec_per_img_tag = 'eval/sec_per_img'\n sec_per_img_tag_value = 1 / img_per_sec_tag_value * 1000\n summary = Summary(value=[Summary.Value(tag=img_per_sec_tag, simple_value=img_per_sec_tag_value),\n Summary.Value(tag=sec_per_img_tag, simple_value=sec_per_img_tag_value)])\n logging.info(\"%s: %g, %s: %g ms, step: %g\",\n img_per_sec_tag, img_per_sec_tag_value, sec_per_img_tag, sec_per_img_tag_value, step)\n self._summary_writer.add_summary(summary, step)\n\n def after_run(self, run_context, run_values):\n self._run_end = time.time()\n self._duration += self._run_end - self._run_begin\n # not use step 0 to warmup\n if self._step > 0 and self._step % self._every_n_steps == 0:\n results = run_values.results\n global_step = results['global_step']\n\n images = get_key_or_none(results, self._images_name)\n labels = get_key_or_none(results, self._labels_name)\n filenames = get_key_or_none(results, self._filenames_name)\n raw_images = get_key_or_none(results, self._raw_images_name)\n heat_map_features = get_key_or_none(results, self._heat_map_features_name)\n probs = get_key_or_none(results, self._probs_name)\n\n self._total_batch_size = len(images) * hvd.size()\n\n self._log_and_record(self._step + global_step)\n show_images(filenames, images, raw_images, heat_map_features, labels, probs, self._step + global_step,\n self._max_images, self._summary_writer, prefix='eval')\n\n self._step += 1\n\n def end(self, session):\n total_image_count = self._step * self._total_batch_size\n image_per_second = total_image_count / self._duration\n second_per_image = self._duration / total_image_count * 1000\n logging.info('total {}: {}, {}: {}, {}: {}, {}: {} ms'.format('duration', self._duration, 'total_image_count',\n total_image_count, 'image_per_second',\n image_per_second, 'second_per_image',\n second_per_image))\n\n\nclass SpeedHook(basic_session_run_hooks.StepCounterHook):\n def __init__(self, summary_dir, batch_size, every_n_steps=100):\n super(SpeedHook, self).__init__(every_n_steps=every_n_steps, output_dir=summary_dir)\n self._total_batch_size = batch_size * hvd.size()\n\n def _log_and_record(self, elapsed_steps, elapsed_time, global_step):\n steps_per_sec = elapsed_steps / elapsed_time\n if self._summary_writer is not None:\n if self._total_batch_size:\n image_tag = 'images_sec'\n image_count = float(steps_per_sec) * self._total_batch_size\n summary = Summary(value=[Summary.Value(tag=self._summary_tag, simple_value=steps_per_sec),\n Summary.Value(tag=image_tag, simple_value=image_count)])\n logging.info(\"%s: %g, %s: %g, step: %g\", self._summary_tag, steps_per_sec, image_tag, image_count,\n global_step)\n else:\n summary = Summary(value=[Summary.Value(tag=self._summary_tag, simple_value=steps_per_sec)])\n logging.info(\"%s: %g, step: %g\", self._summary_tag, steps_per_sec, global_step)\n\n self._summary_writer.add_summary(summary, global_step)\n\n\ndef get_key_or_none(d, key):\n if key in d:\n return d[key]\n else:\n return None\n\nclass PrefillStagingAreasHook(tf.train.SessionRunHook):\n def after_create_session(self, session, coord):\n # TODO: This assumes TF collections are ordered; is this safe?\n enqueue_ops = tf.get_collection('STAGING_AREA_PUTS')\n for i in range(len(enqueue_ops)):\n session.run(enqueue_ops[:i + 1])\n\n\nclass OomReportingHook(tf.train.SessionRunHook):\n def before_run(self, run_context):\n return SessionRunArgs(fetches=[], # no extra fetches\n options=tf.RunOptions(report_tensor_allocations_upon_oom=True))\n" ]
[ [ "matplotlib.pyplot.legend", "matplotlib.pyplot.imshow", "numpy.get_printoptions", "numpy.asarray", "tensorflow.core.framework.summary_pb2.Summary.Value", "matplotlib.pyplot.plot", "numpy.seterr", "numpy.max", "numpy.concatenate", "numpy.zeros_like", "tensorflow.python.training.checkpoint_management.latest_checkpoint", "tensorflow.compat.v1.train.Saver", "matplotlib.pyplot.tight_layout", "tensorflow.compat.v1.global_variables", "numpy.uint8", "tensorflow.python.pywrap_tensorflow.NewCheckpointReader", "numpy.finfo", "tensorflow.compat.v1.train.get_or_create_global_step", "tensorflow.compat.v1.summary.FileWriterCache.get", "matplotlib.pyplot.close", "matplotlib.pyplot.figure", "matplotlib.pyplot.title", "numpy.min", "matplotlib.pyplot.ylim", "tensorflow.python.training.training_util._get_or_create_global_step_read", "matplotlib.pyplot.savefig", "sklearn.metrics.roc_curve", "tensorflow.compat.v1.RunOptions", "tensorflow.compat.v1.get_collection", "sklearn.metrics.auc", "numpy.argsort", "tensorflow.python.training.basic_session_run_hooks._as_graph_element", "matplotlib.pyplot.xticks", "matplotlib.pyplot.ylabel", "tensorflow.core.framework.summary_pb2.Summary.Image", "tensorflow.compat.v1.get_default_graph", "tensorflow.compat.v1.device", "matplotlib.use", "sklearn.preprocessing.label_binarize", "numpy.set_printoptions", "tensorflow.python.platform.tf_logging.info", "numpy.argwhere", "numpy.ones", "matplotlib.pyplot.colorbar", "matplotlib.pyplot.xlim", "scipy.interp", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.yticks", "tensorflow.python.training.session_run_hook.SessionRunArgs", "tensorflow.compat.v1.Summary" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
belakaria/USeMO
[ "063fbd8b8c39c3cc54f9abd8c79ff01eda9dc803" ]
[ "benchmarks.py" ]
[ "import math\nimport numpy as np\nfrom scipy.interpolate import interp1d\nfrom copy import deepcopy\n\ndef Rosen(x1, d):\n x=list(4*np.asarray(x1)-2)\n sum_i = 0\n for i in range(d-1):\n sum_i =sum_i + (100 * ((x[i]**2) - x[i+1])**2 + (x[i] - 1)**2)\n return sum_i\n\n\ndef Sphere(x1,d):\n x=list(4*np.asarray(x1)-2)\n sum_i = 0\n for i in range(d):\n sum_i =sum_i + (x[i]**2)\n return sum_i\n\n\ndef AckleyD(x1, d):\n x=list(4*np.asarray(x1)-2)\n sum_i = 0\n for i in range(d):\n sum_i = sum_i + x[i]*x[i]\n square_sum = sum_i/d\n sum_i = 0\n for i in range(d):\n sum_i = sum_i + math.cos(2*3.1416*x[i])\n cos_sum = sum_i/d\n f_original = -20.0*math.exp(-0.2*math.sqrt(square_sum)) - math.exp(cos_sum) + 20 + math.exp(1)\n return f_original\n################################################\n\ndef Currin(x, d):\n return float(((1 - math.exp(-0.5*(1/x[1]))) * ((2300*pow(x[0],3) + 1900*x[0]*x[0] + 2092*x[0] + 60)/(100*pow(x[0],3) + 500*x[0]*x[0] + 4*x[0] + 20))))\n\ndef branin(x1,d):\n x=deepcopy(x1)\n x[0]= 15* x[0]-5\n x[1]=15*x[1]\n return float(np.square(x[1] - (5.1/(4*np.square(math.pi)))*np.square(x[0]) + (5/math.pi)*x[0]- 6) + 10*(1-(1./(8*math.pi)))*np.cos(x[0]) + 10)\n################################################\ndef Powell(xx,d):\n\n vmin=-4\n vmax=5\n x=[None]+list(vmin + np.asarray(xx) * (vmax-vmin))\n f_original=0\n for i in range(1,int(math.floor(d/4)+1)):\n f_original=f_original+pow(x[4*i-3]+10*x[4*i-2],2)+5*pow(x[4*i-1]-x[4*i],2)+pow(x[4*i-2]-2*x[4*i-1],4)+10*pow(x[4*i-3]-2*x[4*i],4)\n return float(f_original)\n\ndef Perm(xx,d):\n \n vmin=-1*d\n vmax=d\n beta=10\n x=[None]+list(vmin + np.asarray(xx) * (vmax-vmin))\n f_original=0\n for i in range(1,d+1):\n sum1=0\n for j in range(1,d+1):\n sum1=sum1+(j+beta)*(x[j]-math.pow(j,-1*i)) \n f_original=f_original+math.pow(sum1,2)\n return f_original\n\ndef Dixon(xx,d):\n vmin=-10\n vmax=10\n x=[None]+list(vmin + np.asarray(xx) * (vmax-vmin))\n f_original=0\n for i in range(2,d+1): \n f_original=f_original+i*math.pow(2*math.pow(x[i],2)-x[i-1],2)\n f_original=f_original+math.pow(x[1]-1,1)\n return f_original\ndef ZAKHAROV(xx,d):\n vmin=-5\n vmax=10\n x=[None]+list(vmin + np.asarray(xx) * (vmax-vmin))\n term1=0\n term2=0\n for i in range(1,d+1):\n term1=term1+x[i]**2\n term2=term2+0.5*i*x[i]\n f_original=term1+math.pow(term2,2)+math.pow(term2,4)\n return f_original\ndef RASTRIGIN(xx,d):\n vmin=-5.12\n vmax=5.12\n x=[None]+list(vmin + np.asarray(xx) * (vmax-vmin))\n f_original=0\n for i in range(1,d+1):\n f_original=f_original+(x[i]**2-10*math.cos(2*x[i]*math.pi))\n f_original=f_original+10*d\n return f_original\ndef SumSquares(xx,d):\n vmin=-5.12\n vmax=5.12\n x=[None]+list(vmin + np.asarray(xx) * (vmax-vmin))\n f_original=0\n for i in range(1,d+1):\n f_original=f_original+(i*math.pow(x[i],2))\n return f_original\n################################################\ndef DTLZ14f_1(x, d):\n g=0\n for i in range(d):\n g=g+pow(x[i]-0.5,2)-math.cos(20*math.pi*(x[i]-0.5)) \n g=100*(d+g)\n y1=(1+g)*0.5*x[0]*x[1]*x[2]\n return y1\ndef DTLZ14f_2(x, d):\n g=0\n for i in range(d):\n g=g+pow(x[i]-0.5,2)-math.cos(20*math.pi*(x[i]-0.5)) \n g=100*(d+g)\n y2=(1+g)*0.5*(1-x[2])*x[0]*x[1]\n return y2\ndef DTLZ14f_3(x, d):\n g=0\n for i in range(d):\n g=g+pow(x[i]-0.5,2)-math.cos(20*math.pi*(x[i]-0.5)) \n g=100*(d+g)\n y3=(1+g)*0.5*(1-x[1])*x[0]\n return y3\ndef DTLZ14f_4(x, d):\n g=0\n for i in range(d):\n g=g+pow(x[i]-0.5,2)-math.cos(20*math.pi*(x[i]-0.5)) \n g=100*(d+g)\n y4=(1+g)*0.5*(1-x[0])\n return y4\n\n#########################################\n#d=4\ndef ZDT1_1(x, d):\n y1=x[0]\n return y1\ndef ZDT1_2(x, d):\n y1=x[0]\n g=0\n for i in range(1,d):\n g=g+x[i] \n g=g*(9./(d-1))+1\n h=1-math.sqrt(y1)/math.sqrt(g)\n y2=g*h\n return y2 \n###########################################" ]
[ [ "numpy.asarray", "numpy.square", "numpy.cos" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ryota2425/zed-yolo
[ "a5672d30e7d11b7542b8cdb0ac1cd882741fb150", "a5672d30e7d11b7542b8cdb0ac1cd882741fb150" ]
[ "zed_python_sample/darknet_zed.py", "zed_python_sample/nagasa2.py" ]
[ "#!python3\n\"\"\"\nPython 3 wrapper for identifying objects in images\n\nRequires DLL compilation\n\nOriginal *nix 2.7: https://github.com/pjreddie/darknet/blob/0f110834f4e18b30d5f101bf8f1724c34b7b83db/python/darknet.py\nWindows Python 2.7 version: https://github.com/AlexeyAB/darknet/blob/fc496d52bf22a0bb257300d3c79be9cd80e722cb/build/darknet/x64/darknet.py\n\n@author: Philip Kahn, Aymeric Dujardin\n@date: 20180911\n\"\"\"\n# pylint: disable=R, W0401, W0614, W0703\nimport os\nimport sys\nimport time\nimport logging\nimport random\nfrom random import randint\nimport math\nimport statistics\nimport getopt\nfrom ctypes import *\nimport numpy as np\nimport cv2\nimport pyzed.sl as sl\n\n# Get the top-level logger object\nlog = logging.getLogger(__name__)\nlogging.basicConfig(level=logging.INFO)\n\n\ndef sample(probs):\n s = sum(probs)\n probs = [a/s for a in probs]\n r = random.uniform(0, 1)\n for i in range(len(probs)):\n r = r - probs[i]\n if r <= 0:\n return i\n return len(probs)-1\n\n\ndef c_array(ctype, values):\n arr = (ctype*len(values))()\n arr[:] = values\n return arr\n\n\nclass BOX(Structure):\n _fields_ = [(\"x\", c_float),\n (\"y\", c_float),\n (\"w\", c_float),\n (\"h\", c_float)]\n\n\nclass DETECTION(Structure):\n _fields_ = [(\"bbox\", BOX),\n (\"classes\", c_int),\n (\"prob\", POINTER(c_float)),\n (\"mask\", POINTER(c_float)),\n (\"objectness\", c_float),\n (\"sort_class\", c_int)]\n\n\nclass IMAGE(Structure):\n _fields_ = [(\"w\", c_int),\n (\"h\", c_int),\n (\"c\", c_int),\n (\"data\", POINTER(c_float))]\n\n\nclass METADATA(Structure):\n _fields_ = [(\"classes\", c_int),\n (\"names\", POINTER(c_char_p))]\n\n\n#lib = CDLL(\"/home/pjreddie/documents/darknet/libdarknet.so\", RTLD_GLOBAL)\n#lib = CDLL(\"darknet.so\", RTLD_GLOBAL)\nhasGPU = True\nif os.name == \"nt\":\n cwd = os.path.dirname(__file__)\n os.environ['PATH'] = cwd + ';' + os.environ['PATH']\n winGPUdll = os.path.join(cwd, \"yolo_cpp_dll.dll\")\n winNoGPUdll = os.path.join(cwd, \"yolo_cpp_dll_nogpu.dll\")\n envKeys = list()\n for k, v in os.environ.items():\n envKeys.append(k)\n try:\n try:\n tmp = os.environ[\"FORCE_CPU\"].lower()\n if tmp in [\"1\", \"true\", \"yes\", \"on\"]:\n raise ValueError(\"ForceCPU\")\n else:\n log.info(\"Flag value '\"+tmp+\"' not forcing CPU mode\")\n except KeyError:\n # We never set the flag\n if 'CUDA_VISIBLE_DEVICES' in envKeys:\n if int(os.environ['CUDA_VISIBLE_DEVICES']) < 0:\n raise ValueError(\"ForceCPU\")\n try:\n global DARKNET_FORCE_CPU\n if DARKNET_FORCE_CPU:\n raise ValueError(\"ForceCPU\")\n except NameError:\n pass\n # log.info(os.environ.keys())\n # log.warning(\"FORCE_CPU flag undefined, proceeding with GPU\")\n if not os.path.exists(winGPUdll):\n raise ValueError(\"NoDLL\")\n lib = CDLL(winGPUdll, RTLD_GLOBAL)\n except (KeyError, ValueError):\n hasGPU = False\n if os.path.exists(winNoGPUdll):\n lib = CDLL(winNoGPUdll, RTLD_GLOBAL)\n log.warning(\"Notice: CPU-only mode\")\n else:\n # Try the other way, in case no_gpu was\n # compile but not renamed\n lib = CDLL(winGPUdll, RTLD_GLOBAL)\n log.warning(\"Environment variables indicated a CPU run, but we didn't find `\" +\n winNoGPUdll+\"`. Trying a GPU run anyway.\")\nelse:\n lib = CDLL(\"../libdarknet/libdarknet.so\", RTLD_GLOBAL)\nlib.network_width.argtypes = [c_void_p]\nlib.network_width.restype = c_int\nlib.network_height.argtypes = [c_void_p]\nlib.network_height.restype = c_int\n\npredict = lib.network_predict\npredict.argtypes = [c_void_p, POINTER(c_float)]\npredict.restype = POINTER(c_float)\n\nif hasGPU:\n set_gpu = lib.cuda_set_device\n set_gpu.argtypes = [c_int]\n\nmake_image = lib.make_image\nmake_image.argtypes = [c_int, c_int, c_int]\nmake_image.restype = IMAGE\n\nget_network_boxes = lib.get_network_boxes\nget_network_boxes.argtypes = [c_void_p, c_int, c_int, c_float, c_float, POINTER(\n c_int), c_int, POINTER(c_int), c_int]\nget_network_boxes.restype = POINTER(DETECTION)\n\nmake_network_boxes = lib.make_network_boxes\nmake_network_boxes.argtypes = [c_void_p]\nmake_network_boxes.restype = POINTER(DETECTION)\n\nfree_detections = lib.free_detections\nfree_detections.argtypes = [POINTER(DETECTION), c_int]\n\nfree_ptrs = lib.free_ptrs\nfree_ptrs.argtypes = [POINTER(c_void_p), c_int]\n\nnetwork_predict = lib.network_predict\nnetwork_predict.argtypes = [c_void_p, POINTER(c_float)]\n\nreset_rnn = lib.reset_rnn\nreset_rnn.argtypes = [c_void_p]\n\nload_net = lib.load_network\nload_net.argtypes = [c_char_p, c_char_p, c_int]\nload_net.restype = c_void_p\n\nload_net_custom = lib.load_network_custom\nload_net_custom.argtypes = [c_char_p, c_char_p, c_int, c_int]\nload_net_custom.restype = c_void_p\n\ndo_nms_obj = lib.do_nms_obj\ndo_nms_obj.argtypes = [POINTER(DETECTION), c_int, c_int, c_float]\n\ndo_nms_sort = lib.do_nms_sort\ndo_nms_sort.argtypes = [POINTER(DETECTION), c_int, c_int, c_float]\n\nfree_image = lib.free_image\nfree_image.argtypes = [IMAGE]\n\nletterbox_image = lib.letterbox_image\nletterbox_image.argtypes = [IMAGE, c_int, c_int]\nletterbox_image.restype = IMAGE\n\nload_meta = lib.get_metadata\nlib.get_metadata.argtypes = [c_char_p]\nlib.get_metadata.restype = METADATA\n\nload_image = lib.load_image_color\nload_image.argtypes = [c_char_p, c_int, c_int]\nload_image.restype = IMAGE\n\nrgbgr_image = lib.rgbgr_image\nrgbgr_image.argtypes = [IMAGE]\n\npredict_image = lib.network_predict_image\npredict_image.argtypes = [c_void_p, IMAGE]\npredict_image.restype = POINTER(c_float)\n\n\ndef array_to_image(arr):\n import numpy as np\n # need to return old values to avoid python freeing memory\n arr = arr.transpose(2, 0, 1)\n c = arr.shape[0]\n h = arr.shape[1]\n w = arr.shape[2]\n arr = np.ascontiguousarray(arr.flat, dtype=np.float32) / 255.0\n data = arr.ctypes.data_as(POINTER(c_float))\n im = IMAGE(w, h, c, data)\n return im, arr\n\n\ndef classify(net, meta, im):\n out = predict_image(net, im)\n res = []\n for i in range(meta.classes):\n if altNames is None:\n name_tag = meta.names[i]\n else:\n name_tag = altNames[i]\n res.append((name_tag, out[i]))\n res = sorted(res, key=lambda x: -x[1])\n return res\n\n\ndef detect(net, meta, image, thresh=.5, hier_thresh=.5, nms=.45, debug=False):\n \"\"\"\n Performs the detection\n \"\"\"\n custom_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n custom_image = cv2.resize(custom_image, (lib.network_width(\n net), lib.network_height(net)), interpolation=cv2.INTER_LINEAR)\n im, arr = array_to_image(custom_image)\n num = c_int(0)\n pnum = pointer(num)\n predict_image(net, im)\n dets = get_network_boxes(\n net, image.shape[1], image.shape[0], thresh, hier_thresh, None, 0, pnum, 0)\n num = pnum[0]\n if nms:\n do_nms_sort(dets, num, meta.classes, nms)\n res = []\n if debug:\n log.debug(\"about to range\")\n for j in range(num):\n for i in range(meta.classes):\n if dets[j].prob[i] > 0:\n b = dets[j].bbox\n if altNames is None:\n name_tag = meta.names[i]\n else:\n name_tag = altNames[i]\n res.append((name_tag, dets[j].prob[i], (b.x, b.y, b.w, b.h), i))\n res = sorted(res, key=lambda x: -x[1])\n free_detections(dets, num)\n return res\n\n\nnetMain = None\nmetaMain = None\naltNames = None\n\n\ndef get_object_depth(depth, bounds):\n '''\n Calculates the median x, y, z position of top slice(area_div) of point cloud\n in camera frame.\n Arguments:\n depth: Point cloud data of whole frame.\n bounds: Bounding box for object in pixels.\n bounds[0]: x-center\n bounds[1]: y-center\n bounds[2]: width of bounding box.\n bounds[3]: height of bounding box.\n\n Return:\n x, y, z: Location of object in meters.\n '''\n area_div = 2\n\n x_vect = []\n y_vect = []\n z_vect = []\n\n for j in range(int(bounds[0] - area_div), int(bounds[0] + area_div)):\n for i in range(int(bounds[1] - area_div), int(bounds[1] + area_div)):\n z = depth[i, j, 2]\n if not np.isnan(z) and not np.isinf(z):\n x_vect.append(depth[i, j, 0])\n y_vect.append(depth[i, j, 1])\n z_vect.append(z)\n try:\n x_median = statistics.median(x_vect)\n y_median = statistics.median(y_vect)\n z_median = statistics.median(z_vect)\n except Exception:\n x_median = -1\n y_median = -1\n z_median = -1\n pass\n\n return x_median, y_median, z_median\n\n\ndef generate_color(meta_path):\n '''\n Generate random colors for the number of classes mentioned in data file.\n Arguments:\n meta_path: Path to .data file.\n\n Return:\n color_array: RGB color codes for each class.\n '''\n random.seed(42)\n with open(meta_path, 'r') as f:\n content = f.readlines()\n class_num = int(content[0].split(\"=\")[1])\n color_array = []\n for x in range(0, class_num):\n color_array.append((randint(0, 255), randint(0, 255), randint(0, 255)))\n return color_array\n\n\ndef main(argv):\n\n thresh = 0.25\n darknet_path=\"../libdarknet/\"\n config_path = darknet_path + \"cfg/yolov3-tiny.cfg\"\n weight_path = \"yolov3-tiny.weights\"\n meta_path = \"coco.data\"\n svo_path = None\n zed_id = 0\n\n help_str = 'darknet_zed.py -c <config> -w <weight> -m <meta> -t <threshold> -s <svo_file> -z <zed_id>'\n try:\n opts, args = getopt.getopt(\n argv, \"hc:w:m:t:s:z:\", [\"config=\", \"weight=\", \"meta=\", \"threshold=\", \"svo_file=\", \"zed_id=\"])\n except getopt.GetoptError:\n log.exception(help_str)\n sys.exit(2)\n for opt, arg in opts:\n if opt == '-h':\n log.info(help_str)\n sys.exit()\n elif opt in (\"-c\", \"--config\"):\n config_path = arg\n elif opt in (\"-w\", \"--weight\"):\n weight_path = arg\n elif opt in (\"-m\", \"--meta\"):\n meta_path = arg\n elif opt in (\"-t\", \"--threshold\"):\n thresh = float(arg)\n elif opt in (\"-s\", \"--svo_file\"):\n svo_path = arg\n elif opt in (\"-z\", \"--zed_id\"):\n zed_id = int(arg)\n\n input_type = sl.InputType()\n if svo_path is not None:\n log.info(\"SVO file : \" + svo_path)\n input_type.set_from_svo_file(svo_path)\n else:\n # Launch camera by id\n input_type.set_from_camera_id(zed_id)\n\n init = sl.InitParameters(input_t=input_type)\n init.coordinate_units = sl.UNIT.METER\n\n cam = sl.Camera()\n if not cam.is_opened():\n log.info(\"Opening ZED Camera...\")\n status = cam.open(init)\n if status != sl.ERROR_CODE.SUCCESS:\n log.error(repr(status))\n exit()\n\n runtime = sl.RuntimeParameters()\n # Use STANDARD sensing mode\n runtime.sensing_mode = sl.SENSING_MODE.STANDARD\n mat = sl.Mat()\n point_cloud_mat = sl.Mat()\n\n # Import the global variables. This lets us instance Darknet once,\n # then just call performDetect() again without instancing again\n global metaMain, netMain, altNames # pylint: disable=W0603\n assert 0 < thresh < 1, \"Threshold should be a float between zero and one (non-inclusive)\"\n if not os.path.exists(config_path):\n raise ValueError(\"Invalid config path `\" +\n os.path.abspath(config_path)+\"`\")\n if not os.path.exists(weight_path):\n raise ValueError(\"Invalid weight path `\" +\n os.path.abspath(weight_path)+\"`\")\n if not os.path.exists(meta_path):\n raise ValueError(\"Invalid data file path `\" +\n os.path.abspath(meta_path)+\"`\")\n if netMain is None:\n netMain = load_net_custom(config_path.encode(\n \"ascii\"), weight_path.encode(\"ascii\"), 0, 1) # batch size = 1\n if metaMain is None:\n metaMain = load_meta(meta_path.encode(\"ascii\"))\n if altNames is None:\n # In thon 3, the metafile default access craps out on Windows (but not Linux)\n # Read the names file and create a list to feed to detect\n try:\n with open(meta_path) as meta_fh:\n meta_contents = meta_fh.read()\n import re\n match = re.search(\"names *= *(.*)$\", meta_contents,\n re.IGNORECASE | re.MULTILINE)\n if match:\n result = match.group(1)\n else:\n result = None\n try:\n if os.path.exists(result):\n with open(result) as names_fh:\n names_list = names_fh.read().strip().split(\"\\n\")\n altNames = [x.strip() for x in names_list]\n except TypeError:\n pass\n except Exception:\n pass\n\n color_array = generate_color(meta_path)\n\n log.info(\"Running...\")\n\n key = ''\n while key != 113: # for 'q' key\n start_time = time.time() # start time of the loop\n err = cam.grab(runtime)\n if err == sl.ERROR_CODE.SUCCESS:\n cam.retrieve_image(mat, sl.VIEW.LEFT)\n image = mat.get_data()\n\n cam.retrieve_measure(\n point_cloud_mat, sl.MEASURE.XYZRGBA)\n depth = point_cloud_mat.get_data()\n\n # Do the detection\n detections = detect(netMain, metaMain, image, thresh)\n\n log.info(chr(27) + \"[2J\"+\"**** \" + str(len(detections)) + \" Results ****\")\n for detection in detections:\n label = detection[0]\n confidence = detection[1]\n pstring = label+\": \"+str(np.rint(100 * confidence))+\"%\"\n log.info(pstring)\n bounds = detection[2]\n y_extent = int(bounds[3])\n x_extent = int(bounds[2])\n # Coordinates are around the center\n x_coord = int(bounds[0] - bounds[2]/2)\n y_coord = int(bounds[1] - bounds[3]/2)\n #boundingBox = [[x_coord, y_coord], [x_coord, y_coord + y_extent], [x_coord + x_extent, y_coord + y_extent], [x_coord + x_extent, y_coord]]\n thickness = 1\n x, y, z = get_object_depth(depth, bounds)\n distance = math.sqrt(x * x + y * y + z * z)\n distance = \"{:.2f}\".format(distance)\n cv2.rectangle(image, (x_coord - thickness, y_coord - thickness),\n (x_coord + x_extent + thickness, y_coord + (18 + thickness*4)),\n color_array[detection[3]], -1)\n cv2.putText(image, label + \" \" + (str(distance) + \" m\"),\n (x_coord + (thickness * 4), y_coord + (10 + thickness * 4)),\n cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)\n cv2.rectangle(image, (x_coord - thickness, y_coord - thickness),\n (x_coord + x_extent + thickness, y_coord + y_extent + thickness),\n color_array[detection[3]], int(thickness*2))\n\n cv2.imshow(\"ZED\", image)\n key = cv2.waitKey(5)\n log.info(\"FPS: {}\".format(1.0 / (time.time() - start_time)))\n else:\n key = cv2.waitKey(5)\n cv2.destroyAllWindows()\n\n cam.close()\n log.info(\"\\nFINISH\")\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n", "#!python3\n\"\"\"\nPython 3 wrapper for identifying objects in images\n\nRequires DLL compilation\n\nOriginal *nix 2.7: https://github.com/pjreddie/darknet/blob/0f110834f4e18b30d5f101bf8f1724c34b7b83db/python/darknet.py\nWindows Python 2.7 version: https://github.com/AlexeyAB/darknet/blob/fc496d52bf22a0bb257300d3c79be9cd80e722cb/build/darknet/x64/darknet.py\n\n@author: Philip Kahn, Aymeric Dujardin\n@date: 20180911\n\"\"\"\n# pylint: disable=R, W0401, W0614, W0703\nimport os\nimport sys\nimport time\nimport logging\nimport random\nfrom random import randint\nimport math\nimport statistics\nimport getopt\nfrom ctypes import *\nimport numpy as np\nimport cv2\nimport pyzed.sl as sl\n\n# Get the top-level logger object\nlog = logging.getLogger(__name__)\nlogging.basicConfig(level=logging.INFO)\n\n\ndef sample(probs):\n s = sum(probs)\n probs = [a/s for a in probs]\n r = random.uniform(0, 1)\n for i in range(len(probs)):\n r = r - probs[i]\n if r <= 0:\n return i\n return len(probs)-1\n\n\ndef c_array(ctype, values):\n arr = (ctype*len(values))()\n arr[:] = values\n return arr\n\n\nclass BOX(Structure):\n _fields_ = [(\"x\", c_float),\n (\"y\", c_float),\n (\"w\", c_float),\n (\"h\", c_float)]\n\n\nclass DETECTION(Structure):\n _fields_ = [(\"bbox\", BOX),\n (\"classes\", c_int),\n (\"prob\", POINTER(c_float)),\n (\"mask\", POINTER(c_float)),\n (\"objectness\", c_float),\n (\"sort_class\", c_int)]\n\n\nclass IMAGE(Structure):\n _fields_ = [(\"w\", c_int),\n (\"h\", c_int),\n (\"c\", c_int),\n (\"data\", POINTER(c_float))]\n\n\nclass METADATA(Structure):\n _fields_ = [(\"classes\", c_int),\n (\"names\", POINTER(c_char_p))]\n\n\n#lib = CDLL(\"/home/pjreddie/documents/darknet/libdarknet.so\", RTLD_GLOBAL)\n#lib = CDLL(\"darknet.so\", RTLD_GLOBAL)\nhasGPU = True\nif os.name == \"nt\":\n cwd = os.path.dirname(__file__)\n os.environ['PATH'] = cwd + ';' + os.environ['PATH']\n winGPUdll = os.path.join(cwd, \"yolo_cpp_dll.dll\")\n winNoGPUdll = os.path.join(cwd, \"yolo_cpp_dll_nogpu.dll\")\n envKeys = list()\n for k, v in os.environ.items():\n envKeys.append(k)\n try:\n try:\n tmp = os.environ[\"FORCE_CPU\"].lower()\n if tmp in [\"1\", \"true\", \"yes\", \"on\"]:\n raise ValueError(\"ForceCPU\")\n else:\n log.info(\"Flag value '\"+tmp+\"' not forcing CPU mode\")\n except KeyError:\n # We never set the flag\n if 'CUDA_VISIBLE_DEVICES' in envKeys:\n if int(os.environ['CUDA_VISIBLE_DEVICES']) < 0:\n raise ValueError(\"ForceCPU\")\n try:\n global DARKNET_FORCE_CPU\n if DARKNET_FORCE_CPU:\n raise ValueError(\"ForceCPU\")\n except NameError:\n pass\n # log.info(os.environ.keys())\n # log.warning(\"FORCE_CPU flag undefined, proceeding with GPU\")\n if not os.path.exists(winGPUdll):\n raise ValueError(\"NoDLL\")\n lib = CDLL(winGPUdll, RTLD_GLOBAL)\n except (KeyError, ValueError):\n hasGPU = False\n if os.path.exists(winNoGPUdll):\n lib = CDLL(winNoGPUdll, RTLD_GLOBAL)\n log.warning(\"Notice: CPU-only mode\")\n else:\n # Try the other way, in case no_gpu was\n # compile but not renamed\n lib = CDLL(winGPUdll, RTLD_GLOBAL)\n log.warning(\"Environment variables indicated a CPU run, but we didn't find `\" +\n winNoGPUdll+\"`. Trying a GPU run anyway.\")\nelse:\n lib = CDLL(\"../libdarknet/libdarknet.so\", RTLD_GLOBAL)\nlib.network_width.argtypes = [c_void_p]\nlib.network_width.restype = c_int\nlib.network_height.argtypes = [c_void_p]\nlib.network_height.restype = c_int\n\npredict = lib.network_predict\npredict.argtypes = [c_void_p, POINTER(c_float)]\npredict.restype = POINTER(c_float)\n\nif hasGPU:\n set_gpu = lib.cuda_set_device\n set_gpu.argtypes = [c_int]\n\nmake_image = lib.make_image\nmake_image.argtypes = [c_int, c_int, c_int]\nmake_image.restype = IMAGE\n\nget_network_boxes = lib.get_network_boxes\nget_network_boxes.argtypes = [c_void_p, c_int, c_int, c_float, c_float, POINTER(\n c_int), c_int, POINTER(c_int), c_int]\nget_network_boxes.restype = POINTER(DETECTION)\n\nmake_network_boxes = lib.make_network_boxes\nmake_network_boxes.argtypes = [c_void_p]\nmake_network_boxes.restype = POINTER(DETECTION)\n\nfree_detections = lib.free_detections\nfree_detections.argtypes = [POINTER(DETECTION), c_int]\n\nfree_ptrs = lib.free_ptrs\nfree_ptrs.argtypes = [POINTER(c_void_p), c_int]\n\nnetwork_predict = lib.network_predict\nnetwork_predict.argtypes = [c_void_p, POINTER(c_float)]\n\nreset_rnn = lib.reset_rnn\nreset_rnn.argtypes = [c_void_p]\n\nload_net = lib.load_network\nload_net.argtypes = [c_char_p, c_char_p, c_int]\nload_net.restype = c_void_p\n\nload_net_custom = lib.load_network_custom\nload_net_custom.argtypes = [c_char_p, c_char_p, c_int, c_int]\nload_net_custom.restype = c_void_p\n\ndo_nms_obj = lib.do_nms_obj\ndo_nms_obj.argtypes = [POINTER(DETECTION), c_int, c_int, c_float]\n\ndo_nms_sort = lib.do_nms_sort\ndo_nms_sort.argtypes = [POINTER(DETECTION), c_int, c_int, c_float]\n\nfree_image = lib.free_image\nfree_image.argtypes = [IMAGE]\n\nletterbox_image = lib.letterbox_image\nletterbox_image.argtypes = [IMAGE, c_int, c_int]\nletterbox_image.restype = IMAGE\n\nload_meta = lib.get_metadata\nlib.get_metadata.argtypes = [c_char_p]\nlib.get_metadata.restype = METADATA\n\nload_image = lib.load_image_color\nload_image.argtypes = [c_char_p, c_int, c_int]\nload_image.restype = IMAGE\n\nrgbgr_image = lib.rgbgr_image\nrgbgr_image.argtypes = [IMAGE]\n\npredict_image = lib.network_predict_image\npredict_image.argtypes = [c_void_p, IMAGE]\npredict_image.restype = POINTER(c_float)\n\n\ndef array_to_image(arr):\n import numpy as np\n # need to return old values to avoid python freeing memory\n arr = arr.transpose(2, 0, 1)\n c = arr.shape[0]\n h = arr.shape[1]\n w = arr.shape[2]\n arr = np.ascontiguousarray(arr.flat, dtype=np.float32) / 255.0\n data = arr.ctypes.data_as(POINTER(c_float))\n im = IMAGE(w, h, c, data)\n return im, arr\n\n\ndef classify(net, meta, im):\n out = predict_image(net, im)\n res = []\n for i in range(meta.classes):\n if altNames is None:\n name_tag = meta.names[i]\n else:\n name_tag = altNames[i]\n res.append((name_tag, out[i]))\n res = sorted(res, key=lambda x: -x[1])\n return res\n\n\ndef detect(net, meta, image, thresh=.5, hier_thresh=.5, nms=.45, debug=False):\n \"\"\"\n Performs the detection\n \"\"\"\n custom_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n custom_image = cv2.resize(custom_image, (lib.network_width(\n net), lib.network_height(net)), interpolation=cv2.INTER_LINEAR)\n im, arr = array_to_image(custom_image)\n num = c_int(0)\n pnum = pointer(num)\n predict_image(net, im)\n dets = get_network_boxes(\n net, image.shape[1], image.shape[0], thresh, hier_thresh, None, 0, pnum, 0)\n num = pnum[0]\n if nms:\n do_nms_sort(dets, num, meta.classes, nms)\n res = []\n if debug:\n log.debug(\"about to range\")\n for j in range(num):\n for i in range(meta.classes):\n if dets[j].prob[i] > 0:\n b = dets[j].bbox\n if altNames is None:\n name_tag = meta.names[i]\n else:\n name_tag = altNames[i]\n res.append((name_tag, dets[j].prob[i], (b.x, b.y, b.w, b.h), i))\n res = sorted(res, key=lambda x: -x[1])\n free_detections(dets, num)\n return res\n\n\nnetMain = None\nmetaMain = None\naltNames = None\n\n\ndef get_object_depth(depth, bounds):\n '''\n Calculates the median x, y, z position of top slice(area_div) of point cloud\n in camera frame.\n Arguments:\n\n depth: Point cloud data of whole frame.\n bounds: Bounding box for object in pixels.\n bounds[0]: x-center\n bounds[1]: y-center\n bounds[2]: width of bounding box.\n bounds[3]: height of bounding box.\n\n Return:\n x, y, z: Location of object in meters.\n '''\n area_div = 2\n\n x_vect = []\n y_vect = []\n z_vect = []\n\n for j in range(int(bounds[0] - area_div), int(bounds[0] + area_div)):\n for i in range(int(bounds[1] - area_div), int(bounds[1] + area_div)):\n z = depth[i, j, 2]\n if not np.isnan(z) and not np.isinf(z):\n x_vect.append(depth[i, j, 0])\n y_vect.append(depth[i, j, 1])\n z_vect.append(z)\n try:\n x_median = statistics.median(x_vect)\n y_median = statistics.median(y_vect)\n z_median = statistics.median(z_vect)\n except Exception:\n x_median = -1\n y_median = -1\n z_median = -1\n pass\n\n return x_median, y_median, z_median\n\n\ndef generate_color(meta_path):\n '''\n Generate random colors for the number of classes mentioned in data file.\n Arguments:\n meta_path: Path to .data file.\n\n Return:\n color_array: RGB color codes for each class.\n '''\n random.seed(42)\n with open(meta_path, 'r') as f:\n content = f.readlines()\n class_num = int(content[0].split(\"=\")[1])\n color_array = []\n for x in range(0, class_num):\n color_array.append((randint(0, 255), randint(0, 255), randint(0, 255)))\n return color_array\n\n\ndef main(argv):\n\n thresh = 0.25\n darknet_path=\"../libdarknet/\"\n config_path = darknet_path + \"cfg/yolov3-tiny.cfg\"\n weight_path = \"yolov3-tiny.weights\"\n meta_path = \"coco.data\"\n svo_path = None\n zed_id = 0\n\n help_str = 'darknet_zed.py -c <config> -w <weight> -m <meta> -t <threshold> -s <svo_file> -z <zed_id>'\n try:\n opts, args = getopt.getopt(\n argv, \"hc:w:m:t:s:z:\", [\"config=\", \"weight=\", \"meta=\", \"threshold=\", \"svo_file=\", \"zed_id=\"])\n except getopt.GetoptError:\n log.exception(help_str)\n sys.exit(2)\n for opt, arg in opts:\n if opt == '-h':\n log.info(help_str)\n sys.exit()\n elif opt in (\"-c\", \"--config\"):\n config_path = arg\n elif opt in (\"-w\", \"--weight\"):\n weight_path = arg\n elif opt in (\"-m\", \"--meta\"):\n meta_path = arg\n elif opt in (\"-t\", \"--threshold\"):\n thresh = float(arg)\n elif opt in (\"-s\", \"--svo_file\"):\n svo_path = arg\n elif opt in (\"-z\", \"--zed_id\"):\n zed_id = int(arg)\n\n input_type = sl.InputType()\n if svo_path is not None:\n log.info(\"SVO file : \" + svo_path)\n input_type.set_from_svo_file(svo_path)\n else:\n # Launch camera by id\n input_type.set_from_camera_id(zed_id)\n\n init = sl.InitParameters(input_t=input_type)\n init.coordinate_units = sl.UNIT.METER\n\n cam = sl.Camera()\n if not cam.is_opened():\n log.info(\"Opening ZED Camera...\")\n status = cam.open(init)\n if status != sl.ERROR_CODE.SUCCESS:\n log.error(repr(status))\n exit()\n\n runtime = sl.RuntimeParameters()\n # Use STANDARD sensing mode\n runtime.sensing_mode = sl.SENSING_MODE.STANDARD\n mat = sl.Mat()\n point_cloud_mat = sl.Mat()\n\n # Import the global variables. This lets us instance Darknet once,\n # then just call performDetect() again without instancing again\n global metaMain, netMain, altNames # pylint: disable=W0603\n assert 0 < thresh < 1, \"Threshold should be a float between zero and one (non-inclusive)\"\n if not os.path.exists(config_path):\n raise ValueError(\"Invalid config path `\" +\n os.path.abspath(config_path)+\"`\")\n if not os.path.exists(weight_path):\n raise ValueError(\"Invalid weight path `\" +\n os.path.abspath(weight_path)+\"`\")\n if not os.path.exists(meta_path):\n raise ValueError(\"Invalid data file path `\" +\n os.path.abspath(meta_path)+\"`\")\n if netMain is None:\n netMain = load_net_custom(config_path.encode(\n \"ascii\"), weight_path.encode(\"ascii\"), 0, 1) # batch size = 1\n if metaMain is None:\n metaMain = load_meta(meta_path.encode(\"ascii\"))\n if altNames is None:\n # In thon 3, the metafile default access craps out on Windows (but not Linux)\n # Read the names file and create a list to feed to detect\n try:\n with open(meta_path) as meta_fh:\n meta_contents = meta_fh.read()\n import re\n match = re.search(\"names *= *(.*)$\", meta_contents,\n re.IGNORECASE | re.MULTILINE)\n if match:\n result = match.group(1)\n else:\n result = None\n try:\n if os.path.exists(result):\n with open(result) as names_fh:\n names_list = names_fh.read().strip().split(\"\\n\")\n altNames = [x.strip() for x in names_list]\n except TypeError:\n pass\n except Exception:\n pass\n\n color_array = generate_color(meta_path)\n\n log.info(\"Running...\")\n\n key = ''\n while key != 113: # for 'q' key\n start_time = time.time() # start time of the loop\n err = cam.grab(runtime)\n if err == sl.ERROR_CODE.SUCCESS:\n cam.retrieve_image(mat, sl.VIEW.LEFT)\n image = mat.get_data()\n\n cam.retrieve_measure(\n point_cloud_mat, sl.MEASURE.XYZRGBA)\n depth = point_cloud_mat.get_data()\n\n # Do the detection\n detections = detect(netMain, metaMain, image, thresh)\n\n log.info(chr(27) + \"[2J\"+\"**** \" + str(len(detections)) + \" Results ****\")\n for detection in detections:\n label = detection[0]\n confidence = detection[1]\n pstring = label+\": \"+str(np.rint(100 * confidence))+\"%\"\n log.info(pstring)\n bounds = detection[2]\n y_extent = int(bounds[3])\n x_extent = int(bounds[2])\n # Coordinates are around the sidecorner\n x_coord = int(bounds[0] - bounds[2]/2)\n y_coord = int(bounds[1] - bounds[3]/2)\n #boundingBox = [[x_coord, y_coord], [x_coord, y_coord + y_extent], [x_coord + x_extent, y_coord + y_extent], [x_coord + x_extent, y_coord]]\n bounds2 = [x_coord,y_coord]\n thickness = 1\n x, y, z = get_object_depth(depth, bounds)\n print(bounds)\n print(bounds2)\n bounds3 = [x_coord + x_extent,y_coord]\n x_1,y_1,z_1 = get_object_depth(depth,bounds2) \n x_2,y_2,z_2 = get_object_depth(depth,bounds3) \n #distance = math.sqrt((x_2 - x_1) * (x_2 - x_1) + (y_2 - y_1) * (y_2 - y_1) + (z_2 - z_1) * (z_2 - z_1))\n distance = (x_2 - x_1) * pixel_size\n distance = \"{:.2f}\".format(distance)\n cv2.rectangle(image, (x_coord - thickness, y_coord - thickness),\n (x_coord + x_extent + thickness, y_coord + (18 + thickness*4)),\n color_array[detection[3]], -1)\n cv2.putText(image, label + \" \" + (str(distance) + \" m\"),\n (x_coord + (thickness * 4), y_coord + (10 + thickness * 4)),\n cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)\n cv2.rectangle(image, (x_coord - thickness, y_coord - thickness),\n (x_coord + x_extent + thickness, y_coord + y_extent + thickness),\n color_array[detection[3]], int(thickness*2))\n\n cv2.imshow(\"ZED\", image)\n key = cv2.waitKey(5)\n log.info(\"FPS: {}\".format(1.0 / (time.time() - start_time)))\n else:\n key = cv2.waitKey(5)\n cv2.destroyAllWindows()\n\n cam.close()\n log.info(\"\\nFINISH\")\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n" ]
[ [ "numpy.ascontiguousarray", "numpy.rint", "numpy.isnan", "numpy.isinf" ], [ "numpy.ascontiguousarray", "numpy.rint", "numpy.isnan", "numpy.isinf" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ljbuaa/HLDAGN
[ "787462a43d6c0f47dc1ebfd6ef9bfbd1eb5246a7" ]
[ "torchFunc.py" ]
[ "from torch.autograd import Variable\nimport torch.nn.functional as F\nfrom torch import nn\nfrom torch import Tensor\nfrom torch.nn import Parameter\n\ndef l2normalize(v, eps=1e-12):\n return v / (v.norm() + eps)\n\n\nclass SpectralNorm(nn.Module):\n def __init__(self, module, name='weight', power_iterations=1):\n super(SpectralNorm, self).__init__()\n self.module = module\n self.name = name\n self.power_iterations = power_iterations\n if not self._made_params():\n self._make_params()\n\n def _update_u_v(self):\n u = getattr(self.module, self.name + \"_u\")\n v = getattr(self.module, self.name + \"_v\")\n w = getattr(self.module, self.name + \"_bar\")\n\n height = w.data.shape[0]\n for _ in range(self.power_iterations):\n v.data = l2normalize(torch.mv(torch.t(w.view(height,-1).data), u.data))\n u.data = l2normalize(torch.mv(w.view(height,-1).data, v.data))\n\n # sigma = torch.dot(u.data, torch.mv(w.view(height,-1).data, v.data))\n sigma = u.dot(w.view(height, -1).mv(v))\n setattr(self.module, self.name, w / sigma.expand_as(w))\n\n def _made_params(self):\n try:\n u = getattr(self.module, self.name + \"_u\")\n v = getattr(self.module, self.name + \"_v\")\n w = getattr(self.module, self.name + \"_bar\")\n return True\n except AttributeError:\n return False\n\n\n def _make_params(self):\n w = getattr(self.module, self.name)\n\n height = w.data.shape[0]\n width = w.view(height, -1).data.shape[1]\n\n u = Parameter(w.data.new(height).normal_(0, 1), requires_grad=False)\n v = Parameter(w.data.new(width).normal_(0, 1), requires_grad=False)\n u.data = l2normalize(u.data)\n v.data = l2normalize(v.data)\n w_bar = Parameter(w.data)\n\n del self.module._parameters[self.name]\n\n self.module.register_parameter(self.name + \"_u\", u)\n self.module.register_parameter(self.name + \"_v\", v)\n self.module.register_parameter(self.name + \"_bar\", w_bar)\n\n\n def forward(self, *args):\n self._update_u_v()\n return self.module.forward(*args)" ]
[ [ "torch.nn.Parameter" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
yuzhd/Text2Scene
[ "a357b7d869f559f7d09a5ac6002757ec705b2a76", "a357b7d869f559f7d09a5ac6002757ec705b2a76" ]
[ "lib/modules/composites_simulator.py", "tools/test_layout_dataset.py" ]
[ "#!/usr/bin/env python\n\nimport numpy as np\nfrom copy import deepcopy\nimport matplotlib.pyplot as plt\nfrom nntable import AllCategoriesTables\n\nfrom composites_utils import *\n\n\nclass simulator(object):\n def __init__(self, db, batch_size=None, nn_table=None):\n self.db = db\n self.cfg = db.cfg\n self.batch_size = batch_size if batch_size is not None else self.cfg.batch_size\n if nn_table is None:\n self.nn_table = AllCategoriesTables(db)\n self.nn_table.build_nntables_for_all_categories()\n else:\n self.nn_table = nn_table\n\n def reset(self):\n self.scenes = []\n frames = []\n if self.cfg.use_color_volume:\n channel_dim = 3 * self.cfg.output_vocab_size\n else:\n channel_dim = 4 + self.cfg.output_vocab_size\n for i in range(self.batch_size):\n scene = {}\n scene['out_inds'] = []\n scene['out_vecs'] = []\n scene['out_patches'] = []\n frame = np.zeros(\n ( self.cfg.input_image_size[1],\n self.cfg.input_image_size[0],\n channel_dim\n )\n )\n scene['last_frame'] = frame\n scene['last_label'] = np.zeros(\n ( self.cfg.input_image_size[1],\n self.cfg.input_image_size[0]\n ), dtype=np.int32\n )\n scene['last_mask'] = np.zeros(\n ( self.cfg.input_image_size[1],\n self.cfg.input_image_size[0]\n ), dtype=np.float32\n )\n self.scenes.append(scene)\n frames.append(frame)\n frames = np.stack(frames, axis=0)\n return torch.from_numpy(frames)\n\n def batch_render_to_pytorch(self, out_inds, out_vecs):\n assert(len(out_inds) == self.batch_size)\n outputs = []\n for i in range(self.batch_size):\n frame = self.update_scene(self.scenes[i],\n {'out_inds': out_inds[i], 'out_vec': out_vecs[i]})\n outputs.append(frame)\n outputs = np.stack(outputs, 0)\n return torch.from_numpy(outputs)\n\n def batch_redraw(self, return_sequence=False):\n out_frames, out_noises, out_masks, out_labels, out_scenes = [], [], [], [], []\n for i in range(len(self.scenes)):\n predicted_scene = self.db.prediction_outputs_to_scene(self.scenes[i], self.nn_table)\n predicted_scene['patches'] = self.scenes[i]['out_patches']\n frames, noises, masks, labels = self.render_predictions_as_output(predicted_scene, return_sequence)\n if not return_sequence:\n frames = frames[None, ...]\n noises = noises[None, ...]\n masks = masks[None, ...]\n labels = labels[None, ...]\n out_frames.append(frames)\n out_noises.append(noises)\n out_masks.append(masks)\n out_labels.append(labels)\n out_scenes.append(predicted_scene)\n return out_frames, out_noises, out_masks, out_labels, out_scenes\n\n def render_predictions_as_output(self, scene, return_sequence):\n width = scene['width']\n height = scene['height']\n clses = scene['clses']\n boxes = scene['boxes']\n patches = scene['patches']\n\n if self.cfg.use_color_volume:\n channel_dim = 3 * self.cfg.output_vocab_size\n else:\n channel_dim = 4 + self.cfg.output_vocab_size\n\n frame = np.zeros((height, width, channel_dim))\n noise = np.zeros((height, width, channel_dim))\n label = np.zeros((height, width), dtype=np.int32)\n mask = np.zeros((height, width), dtype=np.float32)\n\n out_frames, out_noises, out_labels, out_masks = [], [], [], []\n for i in range(len(clses)):\n cls_ind = clses[i]\n xywh = boxes[i]\n patch = patches[i]\n xyxy = xywh_to_xyxy(xywh, width, height)\n if self.cfg.use_color_volume:\n frame[:,:,3*cls_ind:3*(cls_ind+1)], mask, _, label, noise[:,:,3*cls_ind:3*(cls_ind+1)] = \\\n patch_compose_and_erose(frame[:,:,3*cls_ind:3*(cls_ind+1)], mask, label, \\\n xyxy, patch, self.db, noise[:,:,3*cls_ind:3*(cls_ind+1)])\n else:\n frame[:,:,-3:], mask, _, label, noise[:,:,-3:] = \\\n patch_compose_and_erose(frame[:,:,-3:], mask, label, xyxy, patch, self.db, noise[:,:,-3:])\n frame[:,:,-4] = np.maximum(mask*255, frame[:,:,-4])\n frame[:,:,cls_ind] = np.maximum(mask*255, frame[:,:,cls_ind])\n out_frames.append(frame.copy())\n out_noises.append(noise.copy())\n out_labels.append(label.copy())\n out_masks.append(mask.copy())\n\n if len(clses) == 0:\n out_frames.append(frame.copy())\n out_noises.append(noise.copy())\n out_labels.append(label.copy())\n out_masks.append(mask.copy())\n\n if return_sequence:\n return np.stack(out_frames, 0), np.stack(out_noises, 0), np.stack(out_masks, 0), np.stack(out_labels, 0)\n else:\n return out_frames[-1], out_noises[-1], out_masks[-1], out_labels[-1]\n\n def update_scene(self, scene, step_prediction):\n ##############################################################\n # Update the scene and the last instance of the scene\n ##############################################################\n out_inds = step_prediction['out_inds'].flatten()\n out_vec = step_prediction['out_vec'].flatten()\n scene['out_inds'].append(out_inds)\n scene['out_vecs'].append(out_vec)\n scene['last_frame'], scene['last_mask'], scene['last_label'], current_patch = \\\n self.update_frame(scene['last_frame'], scene['last_mask'], scene['last_label'], out_inds, out_vec)\n scene['out_patches'].append(current_patch)\n return scene['last_frame']\n\n def update_frame(self, input_frame, input_mask, input_label, input_inds, input_vec):\n if input_inds[0] <= self.cfg.EOS_idx:\n return input_frame, input_mask, input_label, None\n w = input_frame.shape[-2]\n h = input_frame.shape[-3]\n cls_ind = input_inds[0]\n xywh = self.db.index2box(input_inds[1:])\n xywh = xywh * np.array([w, h, w, h])\n xyxy = xywh_to_xyxy(xywh, w, h)\n patch = self.nn_table.retrieve(cls_ind, input_vec)[0]\n # print(patch)\n # print(patch['name'])\n\n # update the frame\n if self.cfg.use_color_volume:\n input_frame[:,:,3*cls_ind:3*(cls_ind+1)], input_mask, _, input_label, _ = \\\n patch_compose_and_erose(input_frame[:,:,3*cls_ind:3*(cls_ind+1)], input_mask, input_label, xyxy, patch, self.db)\n else:\n input_frame[:,:,-3:], input_mask, _, input_label, _ = \\\n patch_compose_and_erose(input_frame[:,:,-3:], input_mask, input_label, xyxy, patch, self.db)\n input_frame[:,:,-4] = np.maximum(255*input_mask, input_frame[:,:,-4])\n input_frame[:,:,cls_ind] = np.maximum(255*input_mask, input_frame[:,:,cls_ind])\n return input_frame, input_mask, input_label, patch\n", "#!/usr/bin/env python\n\nimport _init_paths\nimport os, sys, cv2, math, PIL, cairo, random\nimport numpy as np\nimport os.path as osp\nfrom time import time\nfrom copy import deepcopy\nfrom glob import glob\nimport matplotlib.pyplot as plt\nfrom nltk.tokenize import word_tokenize\nfrom collections import OrderedDict\n\nfrom pycocotools.coco import COCO\nfrom pycocotools import mask as COCOmask\n\nimport torch, torchtext\nfrom torch.utils.data import Dataset\n\nfrom layout_config import get_config\nfrom layout_utils import *\nfrom datasets.layout_coco import layout_coco\n\n\ndef test_dataset(config):\n traindb = layout_coco(config, 'train')\n valdb = layout_coco(config, 'val')\n db = layout_coco(config, 'test')\n plt.switch_backend('agg')\n output_dir = osp.join(config.model_dir, 'test_dataset')\n maybe_create(output_dir)\n\n indices = np.random.permutation(range(len(db)))\n indices = indices[:config.n_samples]\n\n for i in indices:\n entry = db[i]\n layouts = db.render_indices_as_output(entry)\n image_idx = entry['image_idx']\n name = '%03d_'%i + str(image_idx).zfill(12)\n out_path = osp.join(output_dir, name+'.png')\n color = cv2.imread(entry['color_path'], cv2.IMREAD_COLOR)\n color, _, _ = create_squared_image(color)\n \n fig = plt.figure(figsize=(32, 16))\n plt.suptitle(entry['sentence'], fontsize=30)\n\n for j in range(len(layouts)):\n plt.subplot(3, 5, j+1)\n plt.imshow(layouts[j])\n plt.axis('off')\n\n plt.subplot(3, 5, 15)\n plt.imshow(color[:,:,::-1])\n plt.axis('off')\n \n fig.savefig(out_path, bbox_inches='tight')\n plt.close(fig)\n\n\ndef test_loader(config):\n from torch.utils.data import DataLoader\n transformer = volume_normalize('background')\n db = layout_coco(config, 'test', transform=transformer)\n \n loader = DataLoader(db, \n batch_size=config.batch_size, \n shuffle=True, \n num_workers=config.num_workers)\n for cnt, batched in enumerate(loader):\n # print(batched['background'].size())\n print(batched['word_inds'].size())\n print(batched['word_lens'].size())\n # print(batched['word_inds'][1])\n # print(batched['word_lens'][1])\n print(batched['out_inds'].size())\n print(batched['out_msks'].size())\n print(batched['out_inds'][0])\n print(batched['out_msks'][0])\n # print(batched['trans_inds'].size())\n # print(batched['cls_mask'].size())\n # print(batched['pos_mask'].size())\n # cls_inds = batched['cls_inds']\n # fg_onehots = batched['foreground_onehots']\n # foo = np.argmax(fg_onehots, axis=-1)\n # assert((cls_inds == foo).all())\n # print(cls_inds, foo)\n # print(batched['word_vecs'].shape)\n # A = batched['output_clip_indices']\n # B = batched['output_clip_onehots']\n # C = np.argmax(B, axis=-1)\n # assert((A==C).all())\n # print(A[0], C[0])\n break\n\n\ndef test_lang_vocab(config):\n train_db = coco(config, 'train')\n val_db = coco(config, 'val')\n\n scenedb = train_db.scenedb\n lang_vocab = val_db.lang_vocab\n\n sent_lens = []\n for i in range(len(scenedb)):\n group_sents = scenedb[i]['captions']\n for j in range(len(group_sents)):\n sentence = group_sents[j]\n tokens = word_tokenize(sentence.lower())\n tokens = further_token_process(tokens)\n word_inds = [lang_vocab.word_to_index(w) for w in tokens]\n # word_inds = [wi for wi in word_inds if wi > config.EOS_idx] \n sent_lens.append(len(word_inds))\n\n \n print('sent len: ', np.median(sent_lens), np.amax(sent_lens), np.amin(sent_lens))\n ps = [80.0, 90.0, 95.0, 99.0]\n for p in ps:\n print('p %d/100: '%(int(p)), np.percentile(sent_lens, p))\n # 10.0 50 6\n\n print(\"vocab size: \", len(lang_vocab.index2word))\n print(\"vocab: \", lang_vocab.index2word[:10])\n\n obj_lens = []\n for i in range(len(scenedb)):\n clses = scenedb[i]['clses']\n obj_lens.append(len(clses))\n print('obj len: ', np.median(obj_lens), np.amax(obj_lens), np.amin(obj_lens))\n for p in ps:\n print('p %d/100: '%(int(p)), np.percentile(obj_lens, p))\n # 4.0 38 2\n\n\ndef test_overlay_boxes(config):\n db = coco(config, 'test')\n plt.switch_backend('agg')\n output_dir = osp.join(config.model_dir, 'test_overlay_boxes')\n maybe_create(output_dir)\n indices = np.random.permutation(range(len(db)))\n indices = indices[:config.n_samples]\n for i in indices:\n entry = db[i]\n layouts = db.overlay_boxes(entry)\n image_idx = entry['image_idx']\n name = '%03d_'%i + str(image_idx).zfill(12)\n out_path = osp.join(output_dir, name+'.png')\n color = cv2.imread(entry['color_path'], cv2.IMREAD_COLOR)\n color, _, _ = create_squared_image(color)\n \n fig = plt.figure(figsize=(32, 16))\n plt.suptitle(entry['sentence'], fontsize=30)\n\n for j in range(len(layouts)):\n plt.subplot(3, 5, j+1)\n plt.imshow(layouts[j])\n plt.axis('off')\n\n plt.subplot(3, 5, 15)\n plt.imshow(color[:,:,::-1])\n plt.axis('off')\n \n fig.savefig(out_path, bbox_inches='tight')\n plt.close(fig)\n\n\ndef bbox_statistic(config):\n train_db = coco(config, 'train')\n val_db = coco(config, 'val')\n scenedb = train_db.scenedb + val_db.scenedb\n\n all_boxes = []\n for i in range(len(scenedb)):\n boxes = scenedb[i]['boxes']\n all_boxes.append(boxes)\n all_boxes = np.concatenate(all_boxes, axis=0)\n print(all_boxes.shape)\n print('--------')\n print('boxes: ', np.median(all_boxes, axis=0), np.amax(all_boxes, axis=0), np.amin(all_boxes, axis=0))\n\n\ndef statistic(config):\n train_db = coco(config, 'train')\n val_db = coco(config, 'val')\n test_db = coco(config, 'test')\n\n print(len(train_db))\n print(len(val_db))\n print(len(test_db))\n\n\n # scenedb = train_db.scenedb\n # lang_vocab = val_db.lang_vocab\n\n # sent_lens = []\n # areas = []\n # for i in range(len(scenedb)):\n # group_sents = scenedb[i]['captions']\n # for j in range(len(group_sents)):\n # sentence = group_sents[j]\n # tokens = word_tokenize(sentence.lower())\n # tokens = further_token_process(tokens)\n # word_inds = [lang_vocab.word_to_index(w) for w in tokens]\n # # word_inds = [wi for wi in word_inds if wi > config.EOS_idx] \n # sent_lens.append(len(word_inds))\n\n # curr_areas = deepcopy(scenedb[i]['areas'])\n # areas.extend(curr_areas.tolist())\n\n # areas = np.array(areas)\n \n # print('sent len: ', np.median(sent_lens), np.amax(sent_lens), np.amin(sent_lens))\n # ps = [80.0, 90.0, 95.0, 99.0]\n # for p in ps:\n # print('p %d/100: '%(int(p)), np.percentile(sent_lens, p))\n\n # print('areas: ', np.median(areas), np.amax(areas), np.amin(areas))\n # ps = [80.0, 90.0, 95.0, 99.0]\n # for p in ps:\n # print('p %d/100: '%(int(p)), np.percentile(-areas, p))\n\n # print(\"vocab size: \", len(lang_vocab.index2word))\n # print(\"vocab: \", lang_vocab.index2word[:10])\n\n # obj_lens = []\n # for i in range(len(scenedb)):\n # clses = scenedb[i]['clses']\n # obj_lens.append(len(clses))\n # print('obj len: ', np.median(obj_lens), np.amax(obj_lens), np.amin(obj_lens))\n # for p in ps:\n # print('p %d/100: '%(int(p)), np.percentile(obj_lens, p))\n # # 4.0 38 2\n\n\nif __name__ == '__main__':\n config, unparsed = get_config()\n config = layout_arguments(config)\n np.random.seed(config.seed)\n random.seed(config.seed)\n torch.manual_seed(config.seed)\n if(config.cuda):\n torch.cuda.manual_seed_all(config.seed)\n prepare_directories(config)\n\n \n # test_dataset(config)\n test_loader(config)\n # test_lang_vocab(config)\n # test_overlay_boxes(config)\n # bbox_statistic(config)\n # statistic(config)\n" ]
[ [ "numpy.maximum", "numpy.array", "numpy.zeros", "numpy.stack" ], [ "matplotlib.pyplot.imshow", "numpy.amax", "numpy.random.seed", "numpy.amin", "matplotlib.pyplot.switch_backend", "torch.manual_seed", "numpy.median", "torch.utils.data.DataLoader", "numpy.percentile", "numpy.concatenate", "matplotlib.pyplot.subplot", "matplotlib.pyplot.close", "matplotlib.pyplot.axis", "torch.cuda.manual_seed_all", "matplotlib.pyplot.suptitle", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
PratyushaMaiti/gtsfm
[ "0d03dca0b6fb9293c9a3fb619a2141903168269a", "0d03dca0b6fb9293c9a3fb619a2141903168269a" ]
[ "gtsfm/utils/viz.py", "gtsfm/scene_optimizer.py" ]
[ "\"\"\"Functions to visualize outputs at different stages of GTSFM.\n\nAuthors: Ayush Baid\n\"\"\"\nimport os\nfrom typing import List, Optional, Tuple\n\nimport cv2 as cv\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom gtsam import Pose3\nfrom matplotlib.axes._axes import Axes\n\nimport gtsfm.utils.geometry_comparisons as comp_utils\nimport gtsfm.utils.images as image_utils\nimport gtsfm.utils.io as io_utils\nfrom gtsfm.common.gtsfm_data import GtsfmData\nfrom gtsfm.common.image import Image\nfrom gtsfm.common.keypoints import Keypoints\n\n\nCOLOR_RED = (255, 0, 0)\nCOLOR_GREEN = (0, 255, 0)\n\n\ndef set_axes_equal(ax: Axes):\n \"\"\"\n Make axes of 3D plot have equal scale so that spheres appear as spheres, cubes as cubes, etc.. This is one\n possible solution to Matplotlib's ax.set_aspect('equal') and ax.axis('equal') not working for 3D.\n\n Ref: https://github.com/borglab/gtsam/blob/develop/python/gtsam/utils/plot.py#L13\n\n Args:\n ax: axis for the plot.\n \"\"\"\n # get the min and max value for each of (x, y, z) axes as 3x2 matrix.\n # This gives us the bounds of the minimum volume cuboid encapsulating all\n # data.\n limits = np.array([ax.get_xlim3d(), ax.get_ylim3d(), ax.get_zlim3d()])\n\n # find the centroid of the cuboid\n centroid = np.mean(limits, axis=1)\n\n # pick the largest edge length for this cuboid\n largest_edge_length = np.max(np.abs(limits[:, 1] - limits[:, 0]))\n\n # set new limits to draw a cube using the largest edge length\n radius = 0.5 * largest_edge_length\n ax.set_xlim3d([centroid[0] - radius, centroid[0] + radius])\n ax.set_ylim3d([centroid[1] - radius, centroid[1] + radius])\n ax.set_zlim3d([centroid[2] - radius, centroid[2] + radius])\n\n\ndef draw_circle_cv2(image: Image, x: int, y: int, color: Tuple[int, int, int], circle_size: int = 10) -> Image:\n \"\"\"Draw a solid circle on the image.\n\n Args:\n image: image to draw the circle on.\n x: x coordinate of the center of the circle.\n y: y coordinate of the center of the circle.\n color: RGB color of the circle.\n circle_size (optional): the size of the circle (in pixels). Defaults to 10.\n\n Returns:\n Image: image with the circle drawn on it.\n \"\"\"\n return Image(\n cv.circle(image.value_array, center=(x, y), radius=circle_size, color=color, thickness=-1) # solid circle\n )\n\n\ndef draw_line_cv2(\n image: Image, x1: int, y1: int, x2: int, y2: int, line_color: Tuple[int, int, int], line_thickness: int = 10,\n) -> Image:\n \"\"\"Draw a line on the image from coordinates (x1, y1) to (x2, y2).\n\n Args:\n image: image to draw the line on.\n x1: x coordinate of start of the line.\n y1: y coordinate of start of the line.\n x2: x coordinate of end of the line.\n y2: y coordinate of end of the line.\n line_color: color of the line.\n line_thickness (optional): line thickness. Defaults to 10.\n\n Returns:\n Image: image with the line drawn on it.\n \"\"\"\n return Image(cv.line(image.value_array, (x1, y1), (x2, y2), line_color, line_thickness, cv.LINE_AA))\n\n\ndef plot_twoview_correspondences(\n image_i1: Image,\n image_i2: Image,\n kps_i1: Keypoints,\n kps_i2: Keypoints,\n corr_idxs_i1i2: np.ndarray,\n inlier_mask: Optional[np.ndarray] = None,\n dot_color: Optional[Tuple[int, int, int]] = None,\n max_corrs: Optional[int] = 50,\n) -> Image:\n \"\"\"Plot correspondences between two images as lines between two circles.\n\n Args:\n image_i1: first image.\n image_i2: second image.\n kps_i1: keypoints for image_i1.\n kps_i2: keypoints for image_i2.\n corr_idxs_i1i2: indices of correspondences between i1 and i2.\n inlier_mask (optional): inlier mask for correspondences as boolean array. Defaults to None.\n dot_color (optional): color for keypoints. Defaults to (0, 0, 0).\n max_corrs (optional): max number of correspondences to plot. Defaults to 50.\n\n Returns:\n image visualizing correspondences between two images.\n \"\"\"\n image_i1, image_i2, scale_i1, scale_i2 = image_utils.match_image_widths(image_i1, image_i2)\n\n result = image_utils.vstack_image_pair(image_i1, image_i2)\n\n if max_corrs is not None and corr_idxs_i1i2.shape[0] > max_corrs:\n # subsample matches\n corr_idxs_i1i2 = corr_idxs_i1i2[np.random.choice(corr_idxs_i1i2.shape[0], max_corrs)]\n\n for corr_idx in range(corr_idxs_i1i2.shape[0]):\n # mark the points in both images as circles, and draw connecting line\n idx_i1, idx_i2 = corr_idxs_i1i2[corr_idx]\n\n x_i1 = (kps_i1.coordinates[idx_i1, 0] * scale_i1[0]).astype(np.int32)\n y_i1 = (kps_i1.coordinates[idx_i1, 1] * scale_i1[1]).astype(np.int32)\n x_i2 = (kps_i2.coordinates[idx_i2, 0] * scale_i2[0]).astype(np.int32)\n y_i2 = (kps_i2.coordinates[idx_i2, 1] * scale_i2[1]).astype(np.int32) + image_i1.height\n\n # drawing correspondences with optional inlier mask\n if inlier_mask is None:\n line_color = tuple([int(c) for c in np.random.randint(0, 255 + 1, 3)])\n elif inlier_mask[corr_idx]:\n line_color = COLOR_GREEN\n else:\n line_color = COLOR_RED\n\n result = draw_line_cv2(result, x_i1, y_i1, x_i2, y_i2, line_color, line_thickness=2)\n\n if dot_color is None:\n dot_color = line_color\n result = draw_circle_cv2(result, x_i1, y_i1, dot_color, circle_size=2)\n result = draw_circle_cv2(result, x_i2, y_i2, dot_color, circle_size=2)\n\n return result\n\n\ndef plot_sfm_data_3d(sfm_data: GtsfmData, ax: Axes, max_plot_radius: float = 50) -> None:\n \"\"\"Plot the camera poses and landmarks in 3D matplotlib plot.\n\n Args:\n sfm_data: SfmData object with camera and tracks.\n ax: axis to plot on.\n max_plot_radius: maximum distance threshold away from any camera for which a point\n will be plotted\n \"\"\"\n camera_poses = [sfm_data.get_camera(i).pose() for i in sfm_data.get_valid_camera_indices()]\n plot_poses_3d(camera_poses, ax)\n\n num_tracks = sfm_data.number_tracks()\n # Restrict 3d points to some radius of camera poses\n points_3d = np.array([list(sfm_data.get_track(j).point3()) for j in range(num_tracks)])\n\n nearby_points_3d = comp_utils.get_points_within_radius_of_cameras(camera_poses, points_3d, max_plot_radius)\n\n # plot 3D points\n for landmark in nearby_points_3d:\n ax.plot(landmark[0], landmark[1], landmark[2], \"g.\", markersize=1)\n\n\ndef plot_poses_3d(\n wTi_list: List[Pose3], ax: Axes, center_marker_color: str = \"k\", label_name: Optional[str] = None\n) -> None:\n \"\"\"Plot poses in 3D as dots for centers and lines denoting the orthonormal\n coordinate system for each camera.\n\n Color convention: R -> x axis, G -> y axis, B -> z axis.\n\n Args:\n wTi_list: list of poses to plot.\n ax: axis to plot on.\n center_marker_color (optional): color for camera center marker. Defaults to \"k\".\n name:\n \"\"\"\n spec = \"{}.\".format(center_marker_color)\n\n for i, wTi in enumerate(wTi_list):\n x, y, z = wTi.translation().squeeze()\n\n if i > 0:\n # for the first loop iteration, add the label to the plot\n # for the rest of iterations, set label to None (otherwise would be duplicated in legend)\n label_name = None\n ax.plot(x, y, z, spec, markersize=10, label=label_name)\n\n R = wTi.rotation().matrix()\n\n # getting the direction of the coordinate system (x, y, z axes)\n default_axis_length = 0.5\n v1 = R[:, 0] * default_axis_length\n v2 = R[:, 1] * default_axis_length\n v3 = R[:, 2] * default_axis_length\n\n ax.plot3D([x, x + v1[0]], [y, y + v1[1]], [z, z + v1[2]], c=\"r\")\n ax.plot3D([x, x + v2[0]], [y, y + v2[1]], [z, z + v2[2]], c=\"g\")\n ax.plot3D([x, x + v3[0]], [y, y + v3[1]], [z, z + v3[2]], c=\"b\")\n\n\ndef plot_and_compare_poses_3d(wTi_list: List[Pose3], wTi_list_: List[Pose3]) -> None:\n \"\"\"Plots two sets poses in 3D with different markers to compare.\n\n The markers are colored black (k) and cyan (c) for the two lists.\n\n Args:\n wTi_list: first set of poses.\n wTi_list_: second set of poses.\n \"\"\"\n fig = plt.figure()\n ax = fig.gca(projection=\"3d\")\n\n plot_poses_3d(wTi_list, ax, center_marker_color=\"k\")\n plot_poses_3d(wTi_list_, ax, center_marker_color=\"c\")\n set_axes_equal(ax)\n\n plt.show()\n\n\ndef save_twoview_correspondences_viz(\n image_i1: Image,\n image_i2: Image,\n keypoints_i1: Keypoints,\n keypoints_i2: Keypoints,\n corr_idxs_i1i2: np.ndarray,\n file_path: str,\n) -> None:\n \"\"\"Visualize correspondences between pairs of images.\n\n Args:\n image_i1: image #i1.\n image_i2: image #i2.\n keypoints_i1: detected Keypoints for image #i1.\n keypoints_i2: detected Keypoints for image #i2.\n corr_idxs_i1i2: correspondence indices.\n file_path: file path to save the visualization.\n \"\"\"\n plot_img = plot_twoview_correspondences(image_i1, image_i2, keypoints_i1, keypoints_i2, corr_idxs_i1i2)\n\n io_utils.save_image(plot_img, file_path)\n\n\ndef save_sfm_data_viz(sfm_data: GtsfmData, folder_name: str) -> None:\n \"\"\"Visualize the camera poses and 3d points in SfmData.\n\n Args:\n sfm_data: data to visualize.\n folder_name: folder to save the visualization at.\n \"\"\"\n fig = plt.figure()\n ax = fig.add_subplot(projection=\"3d\")\n\n plot_sfm_data_3d(sfm_data, ax)\n set_axes_equal(ax)\n\n # save the 3D plot in the original view\n fig.savefig(os.path.join(folder_name, \"3d.png\"))\n\n # save the BEV representation\n default_camera_elevation = 100 # in metres above ground\n ax.view_init(azim=0, elev=default_camera_elevation)\n fig.savefig(os.path.join(folder_name, \"bev.png\"))\n\n plt.close(fig)\n\n\ndef save_camera_poses_viz(\n pre_ba_sfm_data: GtsfmData, post_ba_sfm_data: GtsfmData, gt_pose_graph: Optional[List[Pose3]], folder_name: str\n) -> None:\n \"\"\"Visualize the camera pose and save to disk.\n\n Args:\n pre_ba_sfm_data: data input to bundle adjustment.\n post_ba_sfm_data: output of bundle adjustment.\n gt_pose_graph: ground truth poses.\n folder_name: folder to save the visualization at.\n \"\"\"\n # extract camera poses\n pre_ba_poses = []\n for i in pre_ba_sfm_data.get_valid_camera_indices():\n pre_ba_poses.append(pre_ba_sfm_data.get_camera(i).pose())\n\n post_ba_poses = []\n for i in post_ba_sfm_data.get_valid_camera_indices():\n post_ba_poses.append(post_ba_sfm_data.get_camera(i).pose())\n\n fig = plt.figure()\n ax = fig.add_subplot(projection=\"3d\")\n\n if gt_pose_graph is not None:\n plot_poses_3d(gt_pose_graph, ax, center_marker_color=\"m\", label_name=\"GT\")\n\n plot_poses_3d(pre_ba_poses, ax, center_marker_color=\"c\", label_name=\"Pre-BA\")\n plot_poses_3d(post_ba_poses, ax, center_marker_color=\"k\", label_name=\"Post-BA\")\n\n ax.legend(loc=\"upper left\")\n set_axes_equal(ax)\n\n # save the 3D plot in the original view\n fig.savefig(os.path.join(folder_name, \"poses_3d.png\"))\n\n # save the BEV representation\n default_camera_elevation = 100 # in metres above ground\n ax.view_init(azim=0, elev=default_camera_elevation)\n fig.savefig(os.path.join(folder_name, \"poses_bev.png\"))\n\n plt.close(fig)\n", "\"\"\"The main class which integrates all the modules.\n\nAuthors: Ayush Baid, John Lambert\n\"\"\"\nfrom gtsfm.common.gtsfm_data import GtsfmData\nimport logging\nimport os\nfrom pathlib import Path\nfrom typing import Any, Dict, List, Optional, Tuple\n\nimport dask\nimport matplotlib\nfrom gtsam import Pose3, Similarity3\n\nmatplotlib.use(\"Agg\")\n\nfrom dask.delayed import Delayed\n\nimport gtsfm.averaging.rotation.cycle_consistency as cycle_consistency\nimport gtsfm.evaluation.metrics_report as metrics_report\nimport gtsfm.two_view_estimator as two_view_estimator\nimport gtsfm.utils.ellipsoid as ellipsoid_utils\nimport gtsfm.utils.io as io_utils\nimport gtsfm.utils.logger as logger_utils\nimport gtsfm.utils.metrics as metrics_utils\nimport gtsfm.utils.viz as viz_utils\nfrom gtsfm.common.image import Image\nfrom gtsfm.feature_extractor import FeatureExtractor\nfrom gtsfm.multi_view_optimizer import MultiViewOptimizer\nfrom gtsfm.two_view_estimator import TwoViewEstimator, TwoViewEstimationReport\n\n# base paths for storage\nPLOT_BASE_PATH = Path(__file__).resolve().parent.parent / \"plots\"\nMETRICS_PATH = Path(__file__).resolve().parent.parent / \"result_metrics\"\nRESULTS_PATH = Path(__file__).resolve().parent.parent / \"results\"\n\n# plot paths\nPLOT_CORRESPONDENCE_PATH = PLOT_BASE_PATH / \"correspondences\"\nPLOT_BA_INPUT_PATH = PLOT_BASE_PATH / \"ba_input\"\nPLOT_RESULTS_PATH = PLOT_BASE_PATH / \"results\"\n\n\n# Paths to Save Output in React Folders.\nREACT_METRICS_PATH = Path(__file__).resolve().parent.parent / \"rtf_vis_tool\" / \"src\" / \"result_metrics\"\nREACT_RESULTS_PATH = Path(__file__).resolve().parent.parent / \"rtf_vis_tool\" / \"public\" / \"results\"\n\nlogger = logger_utils.get_logger()\n\nmpl_logger = logging.getLogger(\"matplotlib\")\nmpl_logger.setLevel(logging.WARNING)\n\npil_logger = logging.getLogger(\"PIL\")\npil_logger.setLevel(logging.INFO)\n\n# number of digits (significant figures) to include in each entry of error metrics\nPRINT_NUM_SIG_FIGS = 2\n\n\nclass SceneOptimizer:\n \"\"\"Wrapper combining different modules to run the whole pipeline on a\n loader.\"\"\"\n\n def __init__(\n self,\n feature_extractor: FeatureExtractor,\n two_view_estimator: TwoViewEstimator,\n multiview_optimizer: MultiViewOptimizer,\n save_two_view_correspondences_viz: bool,\n save_3d_viz: bool,\n save_gtsfm_data: bool,\n pose_angular_error_thresh: float,\n ) -> None:\n \"\"\"pose_angular_error_thresh is given in degrees\"\"\"\n self.feature_extractor = feature_extractor\n self.two_view_estimator = two_view_estimator\n self.multiview_optimizer = multiview_optimizer\n\n self._save_two_view_correspondences_viz = save_two_view_correspondences_viz\n self._save_3d_viz = save_3d_viz\n\n self._save_gtsfm_data = save_gtsfm_data\n self._pose_angular_error_thresh = pose_angular_error_thresh\n\n # make directories for persisting data\n os.makedirs(PLOT_BASE_PATH, exist_ok=True)\n os.makedirs(METRICS_PATH, exist_ok=True)\n os.makedirs(RESULTS_PATH, exist_ok=True)\n\n os.makedirs(PLOT_CORRESPONDENCE_PATH, exist_ok=True)\n os.makedirs(PLOT_BA_INPUT_PATH, exist_ok=True)\n os.makedirs(PLOT_RESULTS_PATH, exist_ok=True)\n\n # Save duplicate directories within React folders.\n os.makedirs(REACT_RESULTS_PATH, exist_ok=True)\n os.makedirs(REACT_METRICS_PATH, exist_ok=True)\n\n def create_computation_graph(\n self,\n num_images: int,\n image_pair_indices: List[Tuple[int, int]],\n image_graph: List[Delayed],\n camera_intrinsics_graph: List[Delayed],\n image_shape_graph: List[Delayed],\n gt_pose_graph: Optional[List[Delayed]] = None,\n ) -> Delayed:\n \"\"\"The SceneOptimizer plate calls the FeatureExtractor and TwoViewEstimator plates several times.\"\"\"\n\n # auxiliary graph elements for visualizations and saving intermediate\n # data for analysis, not returned to the user.\n auxiliary_graph_list = []\n metrics_graph_list = []\n\n # detection and description graph\n keypoints_graph_list = []\n descriptors_graph_list = []\n for delayed_image in image_graph:\n (delayed_dets, delayed_descs) = self.feature_extractor.create_computation_graph(delayed_image)\n keypoints_graph_list += [delayed_dets]\n descriptors_graph_list += [delayed_descs]\n\n # estimate two-view geometry and get indices of verified correspondences.\n i2Ri1_graph_dict = {}\n i2Ui1_graph_dict = {}\n v_corr_idxs_graph_dict = {}\n\n two_view_reports_dict = {}\n\n for (i1, i2) in image_pair_indices:\n if gt_pose_graph is not None:\n # compute GT relative pose\n gt_i2Ti1 = dask.delayed(lambda x, y: x.between(y))(gt_pose_graph[i2], gt_pose_graph[i1])\n else:\n gt_i2Ti1 = None\n\n (i2Ri1, i2Ui1, v_corr_idxs, two_view_report,) = self.two_view_estimator.create_computation_graph(\n keypoints_graph_list[i1],\n keypoints_graph_list[i2],\n descriptors_graph_list[i1],\n descriptors_graph_list[i2],\n camera_intrinsics_graph[i1],\n camera_intrinsics_graph[i2],\n image_shape_graph[i1],\n image_shape_graph[i2],\n gt_i2Ti1,\n )\n\n i2Ri1_graph_dict[(i1, i2)] = i2Ri1\n i2Ui1_graph_dict[(i1, i2)] = i2Ui1\n v_corr_idxs_graph_dict[(i1, i2)] = v_corr_idxs\n\n two_view_reports_dict[(i1, i2)] = two_view_report\n\n if self._save_two_view_correspondences_viz:\n auxiliary_graph_list.append(\n dask.delayed(viz_utils.save_twoview_correspondences_viz)(\n image_graph[i1],\n image_graph[i2],\n keypoints_graph_list[i1],\n keypoints_graph_list[i2],\n v_corr_idxs,\n file_path=os.path.join(PLOT_CORRESPONDENCE_PATH, f\"{i1}_{i2}.jpg\"),\n )\n )\n\n # persist all front-end metrics and its summary\n auxiliary_graph_list.append(\n dask.delayed(save_full_frontend_metrics)(two_view_reports_dict, image_graph, filename=\"frontend_full.json\")\n )\n if gt_pose_graph is not None:\n metrics_graph_list.append(\n dask.delayed(two_view_estimator.aggregate_frontend_metrics)(\n two_view_reports_dict, self._pose_angular_error_thresh, metric_group_name=\"frontend_summary\"\n )\n )\n\n # as visualization tasks are not to be provided to the user, we create a\n # dummy computation of concatenating viz tasks with the output graph,\n # forcing computation of viz tasks. Doing this here forces the\n # frontend's auxiliary tasks to be computed before the multi-view stage.\n keypoints_graph_list = dask.delayed(lambda x, y: (x, y))(keypoints_graph_list, auxiliary_graph_list)[0]\n auxiliary_graph_list = []\n\n # ensure cycle consistency in triplets\n i2Ri1_graph_dict, i2Ui1_graph_dict, v_corr_idxs_graph_dict, rcc_metrics_graph = dask.delayed(\n cycle_consistency.filter_to_cycle_consistent_edges, nout=4\n )(i2Ri1_graph_dict, i2Ui1_graph_dict, v_corr_idxs_graph_dict, two_view_reports_dict)\n metrics_graph_list.append(rcc_metrics_graph)\n\n def _filter_dict_keys(dict: Dict[Any, Any], ref_dict: Dict[Any, Any]) -> Dict[Any, Any]:\n \"\"\"Return a subset of a dictionary based on keys present in the reference dictionary.\"\"\"\n valid_keys = list(ref_dict.keys())\n return {k: v for k, v in dict.items() if k in valid_keys}\n\n if gt_pose_graph is not None:\n two_view_reports_dict_cycle_consistent = dask.delayed(_filter_dict_keys)(\n dict=two_view_reports_dict, ref_dict=i2Ri1_graph_dict\n )\n metrics_graph_list.append(\n dask.delayed(two_view_estimator.aggregate_frontend_metrics)(\n two_view_reports_dict_cycle_consistent,\n self._pose_angular_error_thresh,\n metric_group_name=\"cycle_consistent_frontend_summary\",\n )\n )\n auxiliary_graph_list.append(\n dask.delayed(save_full_frontend_metrics)(\n two_view_reports_dict_cycle_consistent,\n image_graph,\n filename=\"cycle_consistent_frontend_full.json\",\n )\n )\n\n # Note: the MultiviewOptimizer returns BA input and BA output that are aligned to GT via Sim(3).\n (ba_input_graph, ba_output_graph, optimizer_metrics_graph) = self.multiview_optimizer.create_computation_graph(\n image_graph,\n num_images,\n keypoints_graph_list,\n i2Ri1_graph_dict,\n i2Ui1_graph_dict,\n v_corr_idxs_graph_dict,\n camera_intrinsics_graph,\n gt_pose_graph,\n )\n\n # aggregate metrics for multiview optimizer\n if optimizer_metrics_graph is not None:\n metrics_graph_list.extend(optimizer_metrics_graph)\n\n # Save metrics to JSON and generate HTML report.\n auxiliary_graph_list.extend(save_metrics_reports(metrics_graph_list))\n\n # # Modify BA input and BA output to have point clouds and frustums aligned with x,y,z axes.\n # ba_input_graph, ba_output_graph, gt_pose_graph = dask.delayed(align_estimated_gtsfm_data, nout=3)(\n # ba_input_graph, ba_output_graph, gt_pose_graph\n # )\n\n if self._save_3d_viz:\n auxiliary_graph_list.extend(save_visualizations(ba_input_graph, ba_output_graph, gt_pose_graph))\n\n if self._save_gtsfm_data:\n auxiliary_graph_list.extend(save_gtsfm_data(image_graph, ba_input_graph, ba_output_graph))\n\n # as visualization tasks are not to be provided to the user, we create a\n # dummy computation of concatenating viz tasks with the output graph,\n # forcing computation of viz tasks\n output_graph = dask.delayed(lambda x, y: (x, y))(ba_output_graph, auxiliary_graph_list)\n\n # return the entry with just the sfm result\n return output_graph[0]\n\n\ndef align_estimated_gtsfm_data(\n ba_input: GtsfmData, ba_output: GtsfmData, gt_pose_graph: List[Pose3]\n) -> Tuple[GtsfmData, GtsfmData, List[Pose3]]:\n \"\"\"Creates modified GtsfmData objects that emulate ba_input and ba_output but with point cloud and camera\n frustums aligned to the x,y,z axes. Also transforms GT camera poses to be aligned to axes.\n\n Args:\n ba_input: GtsfmData input to bundle adjustment.\n ba_output: GtsfmData output from bundle adjustment.\n gt_pose_graph: list of GT camera poses.\n\n Returns:\n Updated ba_input GtsfmData object aligned to axes.\n Updated ba_output GtsfmData object aligned to axes.\n Updated gt_pose_graph with GT poses aligned to axes.\n \"\"\"\n walignedTw = ellipsoid_utils.get_ortho_axis_alignment_transform(ba_output)\n walignedTw = Similarity3(R=walignedTw.rotation(), t=walignedTw.translation(), s=1.0)\n ba_input = ba_input.apply_Sim3(walignedTw)\n ba_output = ba_output.apply_Sim3(walignedTw)\n gt_pose_graph = [walignedTw.transformFrom(wTi) for wTi in gt_pose_graph]\n return ba_input, ba_output, gt_pose_graph\n\n\ndef save_visualizations(\n ba_input_graph: Delayed, ba_output_graph: Delayed, gt_pose_graph: Optional[List[Delayed]]\n) -> List[Delayed]:\n \"\"\"Save SfmData before and after bundle adjustment and camera poses for visualization.\n\n Accepts delayed GtsfmData before and after bundle adjustment, along with GT poses,\n saves them and returns a delayed object.\n\n Args:\n ba_input_graph: Delayed GtsfmData input to bundle adjustment.\n ba_output_graph: Delayed GtsfmData output from bundle adjustment.\n gt_pose_graph: Delayed ground truth poses.\n\n Returns:\n A list of Delayed objects after saving the different visualizations.\n \"\"\"\n viz_graph_list = []\n viz_graph_list.append(dask.delayed(viz_utils.save_sfm_data_viz)(ba_input_graph, PLOT_BA_INPUT_PATH))\n viz_graph_list.append(dask.delayed(viz_utils.save_sfm_data_viz)(ba_output_graph, PLOT_RESULTS_PATH))\n viz_graph_list.append(\n dask.delayed(viz_utils.save_camera_poses_viz)(ba_input_graph, ba_output_graph, gt_pose_graph, PLOT_RESULTS_PATH)\n )\n return viz_graph_list\n\n\ndef save_gtsfm_data(image_graph: Delayed, ba_input_graph: Delayed, ba_output_graph: Delayed) -> List[Delayed]:\n \"\"\"Saves the Gtsfm data before and after bundle adjustment.\n\n Args:\n image_graph: input image wrapped as Delayed objects.\n ba_input_graph: GtsfmData input to bundle adjustment wrapped as Delayed.\n ba_output_graph: GtsfmData output to bundle adjustment wrapped as Delayed.\n\n Returns:\n A list of delayed objects after saving the input and outputs to bundle adjustment.\n \"\"\"\n saving_graph_list = []\n # Save a duplicate in REACT_RESULTS_PATH.\n for output_dir in [RESULTS_PATH, REACT_RESULTS_PATH]:\n # Save the input to Bundle Adjustment (from data association).\n saving_graph_list.append(\n dask.delayed(io_utils.export_model_as_colmap_text)(\n ba_input_graph, image_graph, save_dir=os.path.join(output_dir, \"ba_input\")\n )\n )\n # Save the output of Bundle Adjustment.\n saving_graph_list.append(\n dask.delayed(io_utils.export_model_as_colmap_text)(\n ba_output_graph, image_graph, save_dir=os.path.join(output_dir, \"ba_output\")\n )\n )\n return saving_graph_list\n\n\ndef save_metrics_reports(metrics_graph_list: Delayed) -> List[Delayed]:\n \"\"\"Saves metrics to JSON and HTML report.\n\n Args:\n metrics_graph: List of GtsfmMetricsGroup from different modules wrapped as Delayed.\n\n Returns:\n List of delayed objects after saving metrics.\n \"\"\"\n save_metrics_graph_list = []\n\n if len(metrics_graph_list) == 0:\n return save_metrics_graph_list\n\n # Save metrics to JSON\n save_metrics_graph_list.append(dask.delayed(metrics_utils.save_metrics_as_json)(metrics_graph_list, METRICS_PATH))\n save_metrics_graph_list.append(\n dask.delayed(metrics_utils.save_metrics_as_json)(metrics_graph_list, REACT_METRICS_PATH)\n )\n save_metrics_graph_list.append(\n dask.delayed(metrics_report.generate_metrics_report_html)(\n metrics_graph_list, os.path.join(METRICS_PATH, \"gtsfm_metrics_report.html\")\n )\n )\n return save_metrics_graph_list\n\n\ndef save_full_frontend_metrics(\n two_view_report_dict: Dict[Tuple[int, int], TwoViewEstimationReport], images: List[Image], filename: str\n) -> None:\n \"\"\"Converts the TwoViewEstimationReports for all image pairs to a Dict and saves it as JSON.\n\n Args:\n two_view_report_dict: front-end metrics for pairs of images.\n images: list of all images for this scene, in order of image/frame index.\n filename: file name to use when saving report to JSON.\n \"\"\"\n metrics_list = []\n\n for (i1, i2), report in two_view_report_dict.items():\n\n # Note: if GT is unknown, then R_error_deg, U_error_deg, and inlier_ratio_gt_model will be None\n metrics_list.append(\n {\n \"i1\": i1,\n \"i2\": i2,\n \"i1_filename\": images[i1].file_name,\n \"i2_filename\": images[i2].file_name,\n \"rotation_angular_error\": round(report.R_error_deg, PRINT_NUM_SIG_FIGS) if report.R_error_deg else None,\n \"translation_angular_error\": round(report.U_error_deg, PRINT_NUM_SIG_FIGS)\n if report.U_error_deg\n else None,\n \"num_inliers_gt_model\": report.num_inliers_gt_model if report.num_inliers_gt_model else None,\n \"inlier_ratio_gt_model\": round(report.inlier_ratio_gt_model, PRINT_NUM_SIG_FIGS)\n if report.inlier_ratio_gt_model\n else None,\n \"inlier_ratio_est_model\": round(report.inlier_ratio_est_model, PRINT_NUM_SIG_FIGS),\n \"num_inliers_est_model\": report.num_inliers_est_model,\n }\n )\n\n io_utils.save_json_file(os.path.join(METRICS_PATH, filename), metrics_list)\n\n # Save duplicate copy of 'frontend_full.json' within React Folder.\n io_utils.save_json_file(os.path.join(REACT_METRICS_PATH, filename), metrics_list)\n" ]
[ [ "numpy.abs", "numpy.random.choice", "numpy.mean", "numpy.random.randint", "matplotlib.pyplot.close", "matplotlib.pyplot.show", "matplotlib.pyplot.figure" ], [ "matplotlib.use" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
aidiary/freesound-audio-tagging
[ "71093fdc838214f4ec2dc5b29b00e7de72ad36d0" ]
[ "dataset.py" ]
[ "import os\nimport librosa\nimport numpy as np\nimport torch.utils.data\n\n\ndef random_crop(y, max_length=176400):\n \"\"\"音声波形を固定長にそろえる\n\n max_lengthより長かったらランダムに切り取る\n max_lengthより短かったらランダムにパディングする\n \"\"\"\n if len(y) > max_length:\n max_offset = len(y) - max_length\n offset = np.random.randint(max_offset)\n y = y[offset:max_length + offset]\n else:\n if max_length > len(y):\n max_offset = max_length - len(y)\n offset = np.random.randint(max_offset)\n else:\n offset = 0\n y = np.pad(y, (offset, max_length - len(y) - offset), 'constant')\n return y\n\n\nclass AudioDataset(torch.utils.data.Dataset):\n\n def __init__(self, df, wav_dir, test=False,\n sr=None, max_length=4.0, window_size=0.02, hop_size=0.01,\n n_feature=64, feature='mfcc', model_type='alex2d'):\n if not os.path.exists(wav_dir):\n print('ERROR: not found %s' % wav_dir)\n exit(1)\n self.df = df\n self.wav_dir = wav_dir\n self.test = test\n self.sr = sr\n self.max_length = max_length # sec\n self.window_size = window_size # sec\n self.hop_size = hop_size # sec\n self.n_feature = n_feature\n self.feature = feature\n self.model_type = model_type\n\n def __len__(self):\n return len(self.df)\n\n def __getitem__(self, index):\n fpath = os.path.join(self.wav_dir, self.df.fname[index])\n y, sr = librosa.load(fpath, sr=self.sr)\n if sr is None:\n print('WARNING:', fpath)\n sr = 44100\n\n # ランダムクロップ\n y = random_crop(y, int(self.max_length * sr))\n\n # 特徴抽出\n n_fft = int(self.window_size * sr)\n hop_length = int(self.hop_size * sr)\n\n if self.feature == 'mfcc':\n feature = librosa.feature.mfcc(y=y, sr=sr, n_fft=n_fft, hop_length=hop_length, n_mfcc=self.n_feature)\n elif self.feature == 'melgram':\n feature = librosa.feature.melspectrogram(y, sr=sr, n_fft=n_fft, hop_length=hop_length, n_mels=self.n_feature)\n else:\n print('Invalid feature name: %s' % self.feature)\n exit(1)\n\n data = torch.from_numpy(feature).float()\n s = data.size()\n\n if self.model_type == 'alex2d' or self.model_type == 'resnet':\n # Conv2dの場合は (channel, features, frames)\n data.resize_(1, s[0], s[1])\n elif self.model_type == 'alex1d' or self.model_type == 'lstm':\n # Conv1dの場合は (features, frames)\n data.resize_(s[0], s[1])\n else:\n print('Invalid conv type: %s' % self.model_type)\n exit(1)\n\n mean = data.mean()\n std = data.std()\n if std != 0:\n data.add_(-mean)\n data.div_(std)\n\n if self.test:\n # テストモードのときは正解ラベルがないのでデータだけ返す\n return data\n else:\n # label\n label = self.df.label_idx[index]\n\n return data, label\n" ]
[ [ "numpy.random.randint" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Hardcode84/dpbench
[ "e6bc1fc6493cb80a1b5a2ffcca4cc1348dd3ad99" ]
[ "numba/knn/GPU/base_knn.py" ]
[ "# *****************************************************************************\n# Copyright (c) 2020, Intel Corporation All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n#\n# Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\n# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,\n# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n# *****************************************************************************\n\nimport argparse\nimport sys\nimport numpy as np\n\nDATA_DIM = 16\n\n\ntry:\n import itimer as it\n\n now = it.itime\n get_mops = it.itime_mops_now\nexcept:\n from timeit import default_timer\n\n now = default_timer\n get_mops = lambda t0, t1, n: (n / (t1 - t0),t1-t0)\n\n######################################################\n# GLOBAL DECLARATIONS THAT WILL BE USED IN ALL FILES #\n######################################################\n\n# make xrange available in python 3\ntry:\n xrange\nexcept NameError:\n xrange = range\n\n\n###############################################\ndef gen_data_x(nopt, data_dim=DATA_DIM):\n data = np.random.rand(nopt, data_dim)\n return data\n\n\ndef gen_data_y(nopt, classes_num=3):\n data = np.random.randint(classes_num, size=nopt)\n return data\n\n\n##############################################\n\ndef run(name, alg, sizes=10, step=2, nopt=2**10):\n parser = argparse.ArgumentParser()\n parser.add_argument('--steps', type=int, default=sizes,\n help='Number of steps')\n parser.add_argument('--step', type=int, default=step,\n help='Factor for each step')\n parser.add_argument('--size', type=int, default=nopt,\n help='Initial data size')\n parser.add_argument('--repeat', type=int, default=100,\n help='Iterations inside measured region')\n parser.add_argument('--text', default='', help='Print with each result')\n\n args = parser.parse_args()\n nopt = args.size\n repeat = args.repeat\n train_data_size = 2**10\n\n with open('perf_output.csv', 'w', 1) as fd, open(\"runtimes.csv\", 'w', 1) as fd2:\n for _ in xrange(args.steps):\n\n print(\"TRAIN_DATA_SIZE: \", train_data_size)\n print(\"TEST_DATA_SIZE: \", nopt)\n\n x_train, y_train = gen_data_x(train_data_size), gen_data_y(train_data_size)\n x_test = gen_data_x(nopt)\n\n n_neighbors = 5\n\n print('ERF: {}: Size: {}'.format(name, nopt), end=' ', flush=True)\n sys.stdout.flush()\n\n predictions = alg(x_train, y_train, x_test, k=n_neighbors) # warmup\n\n t0 = now()\n for _ in xrange(repeat):\n predictions = alg(x_train, y_train, x_test, k=n_neighbors)\n mops, time = get_mops(t0, now(), nopt)\n\n result_mops = mops * repeat\n print('MOPS:', result_mops, args.text)\n fd.write('{},{}\\n'.format(nopt, result_mops))\n fd2.write('{},{}\\n'.format(nopt, time))\n print(\"TIME: \", time)\n\n nopt *= args.step\n repeat = max(repeat - args.step, 1)\n" ]
[ [ "numpy.random.rand", "numpy.random.randint" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
OminiaVincit/scale-variant-topo
[ "6945bc42aacd0d71a6fb472c87e09da223821e1e" ]
[ "graph-kernels2/calculate_kernels.py" ]
[ "import numpy as np\nimport os\n\nimport time\n\nfrom sklearn import svm\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.model_selection import cross_val_predict\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.metrics import accuracy_score\n\nfrom grakel import datasets\nfrom grakel import GraphKernel\nfrom grakel.kernels import VertexHistogram, ShortestPath, WeisfeilerLehman, RandomWalkLabeled, MultiscaleLaplacianFast\n\nfrom six import itervalues, iteritems\n\nimport argparse\n\ndef sec_to_time(sec):\n \"\"\"Print time in a correct format.\"\"\"\n dt = list()\n days = int(sec // 86400)\n if days > 0:\n sec -= 86400*days\n dt.append(str(days) + \" d\")\n\n hrs = int(sec // 3600)\n if hrs > 0:\n sec -= 3600*hrs\n dt.append(str(hrs) + \" h\")\n\n mins = int(sec // 60)\n if mins > 0:\n sec -= 60*mins\n dt.append(str(mins) + \" m\")\n\n if sec > 0:\n dt.append(str(round(sec, 2)) + \" s\")\n return \" \".join(dt)\n\nlb_kernels = {\n \"GraphletSampling\": [{\"name\": \"graphlet_sampling\", \"sampling\": {\"n_samples\": 150}}],\n \"WL-Subtree\": [{\"name\": \"weisfeiler_lehman\", \"niter\": 5}, {\"name\": \"subtree_wl\"}],\n \"WL-ShortestPath\": [{\"name\": \"weisfeiler_lehman\", \"niter\": 5}, {\"name\": \"shortest_path\"}]\n}\n\nulb_kernels = {\n \"ShortestPath\" : [{\"name\": \"shortest_path\", \"with_labels\": False}],\n \"GraphletSampling\": [{\"name\": \"graphlet_sampling\", \"sampling\": {\"n_samples\": 150}}],\n \"GeometricRandomWalk\" : [{\"name\": \"random_walk\", \"method_type\": \"fast\", \"with_labels\": False, \"kernel_type\": \"geometric\"}], #ill defined, donot normalize\n \"ExponentialRandomWalk\" : [{\"name\": \"random_walk\", \"method_type\": \"fast\", \"with_labels\": False, \"kernel_type\": \"exponential\"}],\n # Must have node attribute \"MultiScaleLaplacianFast\" : [{\"name\": \"multiscale_laplacian\", \"which\": \"fast\"}],\n \"LovaszTheta\" : [{\"name\": \"lovasz_theta\"}], #slow\n #\"SvmTheta\" : [{\"name\": \"svm_theta\"}] #fast\n}\n#gk = WeisfeilerLehman(niter=1, normalize=True, base_kernel=VertexHistogram)\n#gk = VertexHistogram(normalize=True)\n\ndef save_kernel(G, gk, outpath, dataname, kername, b, handle=False):\n start = time.time()\n print('Compute kernel {} use handle = {}'.format(kername, handle))\n n = len(G)\n #TODO: Let's use multi-processing but need to handle with large memory consuming problem\n K = np.zeros((n,n))\n if handle == True:\n for i in range(0, n, b):\n ib = min(n, i+b)\n Gs = G[i:ib]\n Ks = gk.fit_transform(Gs)\n K[i:ib, i:ib] = Ks\n for j in range(ib, n, b):\n jb = min(n, j+b)\n Gn = G[j:jb]\n Kn = gk.transform(Gn)\n K[i:ib, j:jb] = Kn.T\n K[j:jb, i:ib] = Kn\n elapse = sec_to_time(round(time.time()-start, 2))\n print('i={}, j={}, b={}, {}'.format(i, j, b, elapse))\n else:\n K = gk.fit_transform(G)\n # P = gk.fit_transform(G)\n # print('K')\n # print(K)\n # print('P')\n # print(P)\n # print('K-P')\n # print(np.max(np.abs(P-K)))\n\n outfile = os.path.join(outpath, '{}_{}.txt'.format(dataname, kername))\n end = time.time()\n elapse = sec_to_time(round(end-start, 2))\n print('Calculate kernel {} in {} '.format(kername, elapse))\n np.savetxt(outfile, K)\n print('Saved kernel ', kername, K.shape)\n print('')\n\ndef to_one_hot(G):\n # Index all discrete labels\n mp = {dl: i for (i, dl) in enumerate(set(l for g in G for l in itervalues(g[1])))}\n def make_vec(k):\n vec = np.zeros((len(mp),), dtype=float)\n vec[k] = 1.0\n return vec\n return [(g[0], {i: make_vec(mp[k]) for (i, k) in iteritems(g[1])}) for g in G]\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--exppath', '-e', type=str, required=True)\n parser.add_argument('--folder', '-f', type=str, default='gkernel')\n parser.add_argument('--njobs', '-j', type=int, default=-1)\n parser.add_argument('--norm', '-n', type=int, default=1)\n parser.add_argument('--handle', type=int, default=0)\n parser.add_argument('--batchsize', '-b', type=int, default=128)\n parser.add_argument('--label', type=int, default=0)\n parser.add_argument('--dataname', '-d', type=str, default='')\n parser.add_argument('--kername', '-k', type=str, default='')\n \n args = parser.parse_args()\n print(args)\n njobs = None\n norm, handle, b, label = args.norm, args.handle, args.batchsize, args.label\n if args.njobs > 0:\n njobs = args.njobs\n\n dname, kname = args.dataname, args.kername\n\n lb_datalist = ['MUTAG', 'BZR', 'COX2', 'DHFR', 'ENZYMES', 'PROTEINS', 'NCI1', 'NCI109', 'DD', 'MSRC_9']\n ulb_datalist = ['IMDB-BINARY', 'IMDB-MULTI', 'REDDIT-BINARY','FRANKENSTEIN', 'COLLAB']\n\n if label > 0:\n datalist = lb_datalist\n kernels = lb_kernels\n else:\n datalist = ulb_datalist\n kernels = ulb_kernels\n\n rows = sorted(list(kernels.keys()))\n\n if dname != '' and dname not in datalist:\n raise ValueError('Not found specified data: {}'.format(dname))\n \n if kname != '' and kname not in kernels:\n raise ValueError('Not found specified kernel: {}'.format(kname))\n\n for dataname in datalist:\n if dname != '' and dataname != dname:\n continue\n outpath = os.path.join(args.exppath,dataname)\n outpath = os.path.join(outpath, args.folder)\n if not os.path.isdir(outpath):\n os.makedirs(outpath)\n \n dat = datasets.fetch_dataset(dataname, as_graphs=True)\n G, y = dat.data, dat.target\n print(dataname, y.shape)\n \n # Need to run each of below kernels separately\n if False and label > 0:\n gk = VertexHistogram(normalize=norm, n_jobs=njobs)\n save_kernel(G, gk, outpath, dataname, 'VertexHist', b, handle=handle)\n\n gk = ShortestPath(normalize=norm, n_jobs=njobs)\n save_kernel(G, gk, outpath, dataname, 'ShortestPath', b, handle=handle)\n\n if False and label > 0:\n gk = WeisfeilerLehman(niter=5, normalize=norm, base_kernel=VertexHistogram, n_jobs=None)\n save_kernel(G, gk, outpath, dataname, 'WL-VertexHist', b, handle=handle)\n\n # if False:\n # for rwtype in ['geometric', 'exponential']:\n # gk = RandomWalkLabeled(normalize=True, kernel_type=rwtype)\n # save_kernel(G, gk, outpath, dataname, 'randomwalk_{}'.format(rwtype))\n\n if True:\n for (i, kername) in enumerate(rows):\n if kname != '' and kername != kname:\n continue\n print(kername, end=\" \")\n gk = GraphKernel(kernel=kernels[kername], normalize=norm, n_jobs=njobs)\n print(\"\", end=\".\")\n use_handy = False\n if 'WL' in kername and len(G) > 256:\n use_handy = True\n save_kernel(G, gk, outpath, dataname, kername.replace('/', '-'), b, handle=use_handy)\n \n" ]
[ [ "numpy.savetxt", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
sdpython/mlprodic
[ "9367dacc91d35ec670c8a8a76708300a75bbc993", "9367dacc91d35ec670c8a8a76708300a75bbc993", "9367dacc91d35ec670c8a8a76708300a75bbc993", "9367dacc91d35ec670c8a8a76708300a75bbc993", "9367dacc91d35ec670c8a8a76708300a75bbc993", "9367dacc91d35ec670c8a8a76708300a75bbc993", "9367dacc91d35ec670c8a8a76708300a75bbc993", "9367dacc91d35ec670c8a8a76708300a75bbc993" ]
[ "_unittests/ut_onnxrt/test_rt_valid_model_gaussian_mixture.py", "_unittests/ut_onnx_conv/test_onnx_conv_knn.py", "_unittests/ut_onnx_conv/test_onnx_conv_graph_optimisation.py", "_unittests/ut_onnxrt/test_rt_valid_model_naive.py", "mlprodict/onnxrt/ops_cpu/op_argmin.py", "_unittests/ut_onnxrt/test_onnxrt_simple.py", "mlprodict/asv_benchmark/common_asv_skl.py", "mlprodict/onnxrt/validate/validate_helper.py" ]
[ "\"\"\"\n@brief test log(time=16s)\n\"\"\"\nimport unittest\nfrom logging import getLogger\nfrom pandas import DataFrame\nfrom pyquickhelper.loghelper import fLOG\nfrom pyquickhelper.pycode import ExtTestCase\nfrom pyquickhelper.pandashelper import df2rst\nfrom sklearn.exceptions import ConvergenceWarning\ntry:\n from sklearn.utils._testing import ignore_warnings\nexcept ImportError:\n from sklearn.utils.testing import ignore_warnings\nfrom skl2onnx import __version__ as skl2onnx_version\nfrom mlprodict.onnxrt.validate import enumerate_validated_operator_opsets, summary_report\nfrom mlprodict.onnxrt.doc.doc_write_helper import split_columns_subsets\n\n\nclass TestRtValidateGaussianMixture(ExtTestCase):\n\n @ignore_warnings(category=(UserWarning, ConvergenceWarning, RuntimeWarning))\n def test_rt_GaussianMixture_python(self):\n fLOG(__file__, self._testMethodName, OutputPrint=__name__ == \"__main__\")\n logger = getLogger('skl2onnx')\n logger.disabled = True\n verbose = 1 if __name__ == \"__main__\" else 0\n\n debug = False\n buffer = []\n\n def myprint(*args, **kwargs):\n buffer.append(\" \".join(map(str, args)))\n\n rows = list(enumerate_validated_operator_opsets(\n verbose, models={\"GaussianMixture\"}, opset_min=9,\n opset_max=11, fLOG=myprint,\n runtime='python', debug=debug,\n filter_exp=lambda m, p: 'mix' in p))\n self.assertGreater(len(rows), 1)\n self.assertIn('skl_nop', rows[-1])\n keys = set()\n for row in rows:\n keys.update(set(row))\n self.assertIn('onx_size', keys)\n piv = summary_report(DataFrame(rows))\n opset = [c for c in piv.columns if 'opset' in c]\n self.assertTrue('opset11' in opset or 'opset10' in opset)\n self.assertGreater(len(buffer), 1 if debug else 0)\n common, subsets = split_columns_subsets(piv)\n try:\n conv = df2rst(piv, split_col_common=common, # pylint: disable=E1123\n split_col_subsets=subsets)\n self.assertIn('| GaussianMixture |', conv)\n except TypeError as e:\n if \"got an unexpected keyword argument 'split_col_common'\" in str(e):\n return\n raise e\n\n\nif __name__ == \"__main__\":\n unittest.main()\n", "\"\"\"\n@brief test log(time=5s)\n\"\"\"\nimport unittest\nfrom logging import getLogger\nimport warnings\nimport numpy\nfrom pandas import DataFrame\nfrom scipy.spatial.distance import cdist as scipy_cdist\nfrom pyquickhelper.pycode import ExtTestCase, ignore_warnings as igw\nfrom sklearn.calibration import CalibratedClassifierCV\nfrom sklearn.datasets import load_iris, make_regression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.neighbors import (\n KNeighborsRegressor, KNeighborsClassifier, NearestNeighbors)\nfrom skl2onnx.common.data_types import FloatTensorType\nfrom skl2onnx.algebra.onnx_ops import ( # pylint: disable=E0611\n OnnxAdd, OnnxIdentity)\nfrom skl2onnx import convert_sklearn\nfrom skl2onnx.common.data_types import Int64TensorType\nimport skl2onnx\nfrom skl2onnx.algebra.complex_functions import onnx_cdist\nfrom mlprodict.onnx_conv import (\n register_converters, to_onnx)\nfrom mlprodict.onnxrt import OnnxInference\nfrom mlprodict.onnxrt.ops_cpu.op_topk import topk_sorted_implementation\nfrom mlprodict.tools.asv_options_helper import (\n get_opset_number_from_onnx, get_ir_version_from_onnx)\nfrom mlprodict.testing.test_utils import _capture_output\nfrom mlprodict.tools.ort_wrapper import OrtInvalidArgument\n\n\ndef old_topk_sorted_implementation(X, k, axis, largest):\n \"\"\"\n Retrieves the top-k elements.\n @param X data\n @param k k in top-k\n @param axis axis chosen to select the top-k elements\n @param largest largest (1) or smallest (0)\n @return top-k values, top-k indices\n \"\"\"\n sorted_indices = numpy.argsort(X, axis=axis)\n sorted_values = numpy.sort(X, axis=axis)\n if largest:\n sorted_indices = numpy.flip(sorted_indices, axis=axis)\n sorted_values = numpy.flip(sorted_values, axis=axis)\n ark = numpy.arange(k)\n topk_sorted_indices = numpy.take(sorted_indices, ark, axis=axis)\n topk_sorted_values = numpy.take(sorted_values, ark, axis=axis)\n return topk_sorted_values, topk_sorted_indices\n\n\nclass TestOnnxConvKNN(ExtTestCase):\n\n def setUp(self):\n logger = getLogger('skl2onnx')\n logger.disabled = True\n\n @igw((DeprecationWarning, FutureWarning))\n def test_topk_sorted_implementation(self):\n X = numpy.array([[0, 1, 0, 2],\n [1, 0, 4, 5],\n [9, 8, 5, 6]], dtype=numpy.float64)\n vals, inds = old_topk_sorted_implementation(X, 2, 1, 0)\n vals2, inds2 = topk_sorted_implementation(X, 2, 1, 0)\n self.assertEqualArray(vals, vals2)\n self.assertEqualArray(inds, inds2)\n\n X = numpy.array([[0, 1, 0, 2],\n [1, 0, 4, 5],\n [9, 8, 5, 6]], dtype=numpy.float64)\n vals, inds = old_topk_sorted_implementation(X, 2, 1, 1)\n vals2, inds2 = topk_sorted_implementation(X, 2, 1, 1)\n self.assertEqualArray(vals, vals2)\n self.assertEqualArray(inds, inds2)\n\n @igw((DeprecationWarning, FutureWarning))\n def test_onnx_example_cdist_in_euclidean(self):\n for metric in ['euclidean', 'minkowski']:\n for opv in [11, get_opset_number_from_onnx()]:\n with self.subTest(metric=metric, opv=opv):\n x = numpy.array([1, 2, 4, 5, 5, 4]).astype(\n numpy.float32).reshape((3, 2))\n x2 = numpy.array([1.1, 2.1, 4.01, 5.01,\n 5.001, 4.001, 0, 0]).astype(\n numpy.float32).reshape((4, 2))\n cop = OnnxAdd('input', 'input',\n op_version=opv)\n\n if metric == \"minkowski\":\n cop2 = OnnxIdentity(\n onnx_cdist(cop, x2, dtype=numpy.float32,\n metric=metric, op_version=opv, p=2),\n output_names=['cdist'], op_version=opv)\n else:\n cop2 = OnnxIdentity(\n onnx_cdist(cop, x2, dtype=numpy.float32,\n metric=metric, op_version=opv),\n output_names=['cdist'], op_version=opv)\n\n model_def = cop2.to_onnx(\n inputs=[('input', FloatTensorType([None, None]))],\n outputs=[('cdist', FloatTensorType())],\n target_opset=opv)\n\n sess = OnnxInference(model_def)\n res = sess.run({'input': x})['cdist']\n exp = scipy_cdist(x * 2, x2, metric=metric)\n self.assertEqualArray(exp, res, decimal=5)\n\n if metric == \"minkowski\":\n continue\n x = numpy.array(\n [[6.1, 2.8, 4.7, 1.2],\n [5.7, 3.8, 1.7, 0.3],\n [7.7, 2.6, 6.9, 2.3],\n [6.0, 2.9, 4.5, 1.5],\n [6.8, 2.8, 4.8, 1.4],\n [5.4, 3.4, 1.5, 0.4],\n [5.6, 2.9, 3.6, 1.3],\n [6.9, 3.1, 5.1, 2.3]], dtype=numpy.float32)\n cop = OnnxAdd('input', 'input', op_version=opv)\n cop2 = OnnxIdentity(onnx_cdist(cop, x, dtype=numpy.float32,\n op_version=opv),\n output_names=['cdist'], op_version=opv)\n\n model_def = cop2.to_onnx(\n inputs=[('input', FloatTensorType([None, None]))],\n outputs=[('cdist', FloatTensorType())],\n target_opset=opv)\n\n sess = OnnxInference(model_def)\n res = sess.run({'input': x})['cdist']\n exp = scipy_cdist(x * 2, x, metric=\"sqeuclidean\")\n self.assertEqualArray(exp, res, decimal=4)\n\n @igw((DeprecationWarning, FutureWarning))\n def test_onnx_example_cdist_in_minkowski(self):\n x = numpy.array([1, 2, 1, 3, 2, 2, 2, 3]).astype(\n numpy.float32).reshape((4, 2))\n x2 = numpy.array([[1, 2], [2, 2], [2.1, 2.1], [2, 2]]).astype(\n numpy.float32).reshape((4, 2))\n for pp in [1, 2]:\n with self.subTest(pp=pp):\n cop = OnnxIdentity(\n 'input', op_version=get_opset_number_from_onnx())\n cop2 = OnnxIdentity(\n onnx_cdist(cop, x2, dtype=numpy.float32,\n metric=\"minkowski\", p=pp,\n op_version=get_opset_number_from_onnx()),\n output_names=['cdist'],\n op_version=get_opset_number_from_onnx())\n\n model_def = cop2.to_onnx(\n inputs=[('input', FloatTensorType([None, None]))],\n outputs=[('cdist', FloatTensorType())])\n\n try:\n sess = OnnxInference(model_def)\n except RuntimeError as e:\n raise AssertionError(\"Issue\\n{}\".format(model_def)) from e\n res = sess.run({'input': x})['cdist']\n exp = scipy_cdist(x, x2, metric=\"minkowski\", p=pp)\n self.assertEqualArray(exp, res, decimal=5)\n\n with self.subTest(pp=3):\n x = numpy.array(\n [[6.1, 2.8, 4.7, 1.2],\n [5.7, 3.8, 1.7, 0.3],\n [7.7, 2.6, 6.9, 2.3],\n [6.0, 2.9, 4.5, 1.5],\n [6.8, 2.8, 4.8, 1.4],\n [5.4, 3.4, 1.5, 0.4],\n [5.6, 2.9, 3.6, 1.3],\n [6.9, 3.1, 5.1, 2.3]], dtype=numpy.float32)\n cop = OnnxAdd('input', 'input',\n op_version=get_opset_number_from_onnx())\n cop2 = OnnxIdentity(\n onnx_cdist(cop, x, dtype=numpy.float32, metric=\"minkowski\",\n p=3, op_version=get_opset_number_from_onnx()),\n output_names=['cdist'], op_version=get_opset_number_from_onnx())\n\n model_def = cop2.to_onnx(\n inputs=[('input', FloatTensorType([None, None]))],\n outputs=[('cdist', FloatTensorType())])\n\n sess = OnnxInference(model_def)\n res = sess.run({'input': x})['cdist']\n exp = scipy_cdist(x * 2, x, metric=\"minkowski\", p=3)\n self.assertEqualArray(exp, res, decimal=4)\n\n @igw((DeprecationWarning, FutureWarning))\n def test_register_converters(self):\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\", ResourceWarning)\n res = register_converters(True)\n self.assertGreater(len(res), 2)\n\n def onnx_test_knn_single_classreg(self, dtype, n_targets=1, debug=False,\n add_noise=False, runtime='python',\n target_opset=None, optim=None,\n kind='reg', level=1, largest0=True,\n metric_params=None, **kwargs):\n iris = load_iris()\n X, y = iris.data, iris.target\n if add_noise:\n X += numpy.random.randn(X.shape[0], X.shape[1]) * 10\n if kind == 'reg':\n y = y.astype(dtype)\n elif kind == 'bin':\n y = (y % 2).astype(numpy.int64)\n elif kind == 'mcl':\n y = y.astype(numpy.int64)\n else:\n raise AssertionError(\"unknown '{}'\".format(kind))\n\n if n_targets != 1:\n yn = numpy.empty((y.shape[0], n_targets), dtype=dtype)\n for i in range(n_targets):\n yn[:, i] = y + i\n y = yn\n X_train, X_test, y_train, _ = train_test_split(X, y, random_state=11)\n X_test = X_test.astype(dtype)\n if kind in ('bin', 'mcl'):\n clr = KNeighborsClassifier(\n metric_params=metric_params, **kwargs)\n elif kind == 'reg':\n clr = KNeighborsRegressor(\n metric_params=metric_params, **kwargs)\n else:\n raise NotImplementedError(kind)\n clr.fit(X_train, y_train)\n\n if optim is None:\n options = None\n else:\n options = {clr.__class__: {'optim': 'cdist'}}\n if not largest0:\n if options is None:\n options = {}\n if clr.__class__ not in options:\n options[clr.__class__] = {}\n options[clr.__class__].update({'largest0': False})\n\n if target_opset is None:\n opsets = list(sorted(set([\n 9, 10, 11, 12, 13, 14, 15, get_opset_number_from_onnx()]))) # opset=13, 14, ...\n else:\n opsets = [target_opset]\n for ops in opsets:\n if ops is None:\n raise AssertionError(\"Cannot happen: {}.\".format(opsets))\n with self.subTest(target_opset=ops):\n try:\n model_def = to_onnx(\n clr, X_train.astype(dtype), rewrite_ops=True,\n target_opset=ops, options=options)\n except NameError as e:\n if \"Option 'largest0' not in\" in str(e):\n continue\n if 'onnxruntime' in runtime:\n model_def.ir_version = get_ir_version_from_onnx()\n try:\n if runtime == 'onnxruntime2':\n oinf = _capture_output(\n lambda: OnnxInference(\n model_def, runtime=runtime), # pylint: disable=W0640\n 'c')[0]\n else:\n oinf = OnnxInference(model_def, runtime=runtime)\n except (RuntimeError, TypeError, OrtInvalidArgument) as e:\n if \"No Op registered for Identity with domain_version of 12\" in str(e):\n continue\n if debug:\n raise AssertionError(\n \"Unable to create a model for target_opset={}\\n----\\n{}\\n----\".format(\n ops, str(model_def)[:100])) from e\n if \"Unknown model file format version.\" in str(e):\n continue\n raise AssertionError(\n \"Unable to create model for opset={} and runtime='{}'\\n{}\"\n \"\".format(ops, runtime, str(model_def)[:100])) from e\n\n if debug:\n y = oinf.run({'X': X_test}, verbose=level, fLOG=print)\n else:\n y = oinf.run({'X': X_test})\n\n lexp = clr.predict(X_test)\n if kind == 'reg':\n self.assertEqual(list(sorted(y)), ['variable'])\n if dtype == numpy.float32:\n self.assertEqualArray(\n lexp, y['variable'], decimal=5, squeeze=True)\n else:\n self.assertEqualArray(\n lexp, y['variable'], squeeze=True)\n else:\n self.assertEqual(list(sorted(y)),\n ['output_label', 'output_probability'])\n self.assertEqualArray(lexp, y['output_label'])\n lprob = clr.predict_proba(X_test)\n self.assertEqualArray(\n lprob, DataFrame(y['output_probability']).values,\n decimal=5)\n\n @igw((DeprecationWarning, FutureWarning))\n def test_onnx_test_knn_single_reg32(self):\n self.onnx_test_knn_single_classreg(numpy.float32)\n\n @igw((DeprecationWarning, FutureWarning))\n def test_onnx_test_knn_single_reg32_cdist(self):\n self.onnx_test_knn_single_classreg(numpy.float32, optim='cdist')\n\n @igw((DeprecationWarning, FutureWarning))\n def test_onnx_test_knn_single_reg32_op10(self):\n self.onnx_test_knn_single_classreg(\n numpy.float32, target_opset=10, debug=False)\n\n @igw((DeprecationWarning, FutureWarning))\n def test_onnx_test_knn_single_reg32_onnxruntime1(self):\n self.onnx_test_knn_single_classreg(\n numpy.float32, runtime=\"onnxruntime1\", target_opset=10)\n\n @igw((DeprecationWarning, FutureWarning))\n def test_onnx_test_knn_single_reg32_onnxruntime2(self):\n try:\n self.onnx_test_knn_single_classreg(\n numpy.float32, runtime=\"onnxruntime2\", target_opset=10,\n debug=False)\n except (RuntimeError, OrtInvalidArgument) as e:\n if \"Invalid rank for input: Ar_Z0 Got: 2 Expected: 1\" in str(e):\n return\n if \"Got invalid dimensions for input:\" in str(e):\n return\n raise e\n\n @igw((DeprecationWarning, FutureWarning))\n def test_onnx_test_knn_single_reg32_balltree(self):\n self.onnx_test_knn_single_classreg(\n numpy.float32, algorithm='ball_tree')\n\n @igw((DeprecationWarning, FutureWarning))\n def test_onnx_test_knn_single_reg32_kd_tree(self):\n self.onnx_test_knn_single_classreg(numpy.float32, algorithm='kd_tree')\n\n @igw((DeprecationWarning, FutureWarning))\n def test_onnx_test_knn_single_reg32_brute(self):\n self.onnx_test_knn_single_classreg(numpy.float32, algorithm='brute')\n\n @igw((DeprecationWarning, FutureWarning))\n def test_onnx_test_knn_single_reg64(self):\n self.onnx_test_knn_single_classreg(numpy.float64)\n\n @igw((DeprecationWarning, FutureWarning))\n def test_onnx_test_knn_single_reg32_target2(self):\n self.onnx_test_knn_single_classreg(numpy.float32, n_targets=2)\n\n @igw((DeprecationWarning, FutureWarning))\n def test_onnx_test_knn_single_reg32_target2_onnxruntime(self):\n self.onnx_test_knn_single_classreg(\n numpy.float32, n_targets=2, runtime=\"onnxruntime1\")\n\n @igw((DeprecationWarning, FutureWarning))\n def test_onnx_test_knn_single_reg32_k1(self):\n self.onnx_test_knn_single_classreg(numpy.float32, n_neighbors=1)\n\n @igw((DeprecationWarning, FutureWarning))\n def test_onnx_test_knn_single_reg32_k1_target2(self):\n self.onnx_test_knn_single_classreg(\n numpy.float32, n_neighbors=1, n_targets=2)\n\n @igw((DeprecationWarning, FutureWarning))\n def test_onnx_test_knn_single_reg32_minkowski(self):\n self.onnx_test_knn_single_classreg(numpy.float32, metric='minkowski')\n\n @igw((DeprecationWarning, SyntaxWarning))\n def test_onnx_test_knn_single_reg32_minkowski_p1(self):\n self.onnx_test_knn_single_classreg(numpy.float32, metric='minkowski',\n metric_params={'p': 1}, add_noise=True)\n\n @igw((DeprecationWarning, SyntaxWarning))\n def test_onnx_test_knn_single_reg32_minkowski_p21(self):\n self.onnx_test_knn_single_classreg(numpy.float32, metric='minkowski',\n algorithm='brute', metric_params={'p': 2.1})\n\n @igw((DeprecationWarning, FutureWarning))\n def test_onnx_test_knn_single_reg32_distance(self):\n self.onnx_test_knn_single_classreg(numpy.float32, weights='distance',\n largest0=False)\n\n @igw((DeprecationWarning, FutureWarning))\n def test_onnx_test_knn_single_reg_equal(self):\n # We would like to make scikit-learn and the runtime handles the\n # ex aequo the same way but that's difficult.\n X = numpy.full((20, 4), 1, dtype=numpy.float32)\n X[::2, 3] = 20\n X[1::5, 1] = 30\n X[::5, 2] = 40\n y = X.sum(axis=1) + numpy.arange(X.shape[0]) / 10\n X_train, X_test, y_train, _ = train_test_split(\n X, y, random_state=11, test_size=0.5)\n clr = KNeighborsRegressor(algorithm='brute', n_neighbors=3)\n clr.fit(X_train, y_train)\n\n model_def = to_onnx(clr, X_train, rewrite_ops=True)\n oinf = OnnxInference(model_def, runtime='python')\n y = oinf.run({'X': X_test})\n self.assertEqual(list(sorted(y)), ['variable'])\n lexp = clr.predict(X_test)\n self.assertEqualArray(lexp, y['variable'], decimal=5, squeeze=True)\n\n # classification\n\n @igw((DeprecationWarning, FutureWarning))\n def test_onnx_test_knn_single_bin32(self):\n self.onnx_test_knn_single_classreg(numpy.float32, kind='bin')\n\n @igw((DeprecationWarning, FutureWarning))\n def test_onnx_test_knn_single_bin32_onnxruntime(self):\n self.onnx_test_knn_single_classreg(\n numpy.float32, kind='bin', runtime=\"onnxruntime1\")\n\n @igw((DeprecationWarning, FutureWarning))\n def test_onnx_test_knn_single_bin32_cdist(self):\n self.onnx_test_knn_single_classreg(\n numpy.float32, kind='bin', optim='cdist')\n\n @igw((DeprecationWarning, FutureWarning))\n def test_onnx_test_knn_single_mcl32(self):\n self.onnx_test_knn_single_classreg(numpy.float32, kind='mcl')\n\n @igw((DeprecationWarning, FutureWarning))\n def test_onnx_test_knn_single_weights_bin32(self):\n self.onnx_test_knn_single_classreg(numpy.float32, kind='bin',\n weights='distance', largest0=False)\n\n @igw((DeprecationWarning, FutureWarning))\n def test_onnx_test_knn_single_weights_bin32_cdist(self):\n self.onnx_test_knn_single_classreg(numpy.float32, kind='bin',\n weights='distance', optim='cdist',\n largest0=False)\n\n @igw((DeprecationWarning, FutureWarning))\n def test_onnx_test_knn_single_weights_mcl32(self):\n self.onnx_test_knn_single_classreg(numpy.float32, kind='mcl',\n weights='distance', largest0=False)\n\n @igw((DeprecationWarning, FutureWarning))\n def test_onnx_test_knn_single_bin64(self):\n self.onnx_test_knn_single_classreg(numpy.float64, kind='bin')\n\n @igw((DeprecationWarning, FutureWarning))\n def test_onnx_test_knn_single_mcl64(self):\n self.onnx_test_knn_single_classreg(numpy.float64, kind='mcl')\n\n @igw((DeprecationWarning, FutureWarning))\n def test_onnx_test_knn_single_weights_bin64(self):\n self.onnx_test_knn_single_classreg(numpy.float64, kind='bin',\n weights='distance', largest0=False)\n\n @igw((DeprecationWarning, FutureWarning))\n def test_onnx_test_knn_single_weights_mcl64(self):\n self.onnx_test_knn_single_classreg(numpy.float64, kind='mcl',\n weights='distance', largest0=False)\n\n # transform\n\n @igw((DeprecationWarning, FutureWarning))\n def test_onnx_test_knn_transform(self):\n iris = load_iris()\n X, _ = iris.data, iris.target\n\n X_train, X_test = train_test_split(X, random_state=11)\n clr = NearestNeighbors(n_neighbors=3)\n clr.fit(X_train)\n\n for to in (10, 11, 12, 13, 14, 15): # opset=13, 14, ...\n if to > get_opset_number_from_onnx():\n break\n try:\n model_def = to_onnx(\n clr, X_train.astype(numpy.float32),\n rewrite_ops=True, options={NearestNeighbors: {'largest0': False}},\n target_opset=to)\n except NameError as e:\n if \"Option 'largest0' not in\" in str(e):\n continue\n oinf = OnnxInference(model_def, runtime='python')\n\n X_test = X_test[:3]\n y = oinf.run({'X': X_test.astype(numpy.float32)})\n dist, ind = clr.kneighbors(X_test)\n\n self.assertEqual(list(sorted(y)), ['distance', 'index'])\n self.assertEqualArray(ind, y['index'])\n self.assertEqualArray(dist, DataFrame(\n y['distance']).values, decimal=5)\n\n # calibrated\n\n @igw((DeprecationWarning, FutureWarning))\n def test_model_calibrated_classifier_cv_isotonic_binary_knn(self):\n data = load_iris()\n X, y = data.data, data.target\n y[y > 1] = 1\n clf = KNeighborsClassifier().fit(X, y)\n model = CalibratedClassifierCV(clf, cv=2, method=\"isotonic\").fit(X, y)\n model_onnx = skl2onnx.convert_sklearn(\n model,\n \"scikit-learn CalibratedClassifierCV\",\n [(\"input\", FloatTensorType([None, X.shape[1]]))],\n )\n oinf = OnnxInference(model_onnx, runtime='python')\n y = oinf.run({'input': X.astype(numpy.float32)})\n pred = clf.predict(X)\n probs = clf.predict_proba(X)\n self.assertEqual(pred, y['output_label'])\n self.assertEqual(probs, DataFrame(y['output_probability']).values)\n\n @igw((DeprecationWarning, FutureWarning))\n def test_model_knn_regressor_equal____(self):\n X, y = make_regression( # pylint: disable=W0632\n n_samples=1000, n_features=100, random_state=42)\n X = X.astype(numpy.int64)\n X_train, X_test, y_train, _ = train_test_split(\n X, y, test_size=0.5, random_state=42)\n model = KNeighborsRegressor(\n algorithm='brute', metric='manhattan').fit(X_train, y_train)\n model_onnx = convert_sklearn(\n model, 'knn',\n [('input', Int64TensorType([None, X_test.shape[1]]))])\n exp = model.predict(X_test)\n\n sess = OnnxInference(model_onnx)\n res = sess.run({'input': numpy.array(X_test)})['variable']\n\n # The conversion has discrepencies when\n # neighbours are at the exact same distance.\n maxd = 1000\n accb = numpy.abs(exp.ravel() - res.ravel()) > maxd\n ind = [i for i, a in enumerate(accb) if a == 1]\n self.assertEqual(len(ind), 0)\n\n accp = numpy.abs(exp - res) < maxd\n acc = numpy.sum(accp)\n ratio = acc * 1.0 / res.shape[0]\n self.assertGreater(ratio, 0.7)\n # Explainable discrepencies.\n # self.assertEqualArray(exp, res)\n self.assertEqual(numpy.squeeze(exp).shape, numpy.squeeze(res).shape)\n\n\nif __name__ == \"__main__\":\n unittest.main(verbosity=2)\n", "\"\"\"\n@brief test log(time=3s)\n\"\"\"\nfrom collections import OrderedDict\nimport unittest\nimport numpy\nfrom pyquickhelper.pycode import ExtTestCase, ignore_warnings\nfrom sklearn.datasets import load_iris\nfrom sklearn.neighbors import KNeighborsRegressor\nfrom sklearn.metrics import make_scorer\nfrom mlprodict.onnx_conv import to_onnx\nfrom mlprodict.onnxrt import OnnxInference\nfrom mlprodict.tools.asv_options_helper import (\n get_opset_number_from_onnx)\nfrom mlprodict.onnx_conv.scorers.cdist_score import score_cdist_sum\n\n\nclass TestOnnxConvGraphOptimisation(ExtTestCase):\n\n def test_to_onnx_rename_names(self):\n data = load_iris()\n X, y = data.data, data.target\n model = KNeighborsRegressor(n_neighbors=2).fit(X, y)\n\n model_onnx = to_onnx(\n model, X[:1], target_opset=get_opset_number_from_onnx())\n oinf1 = OnnxInference(model_onnx)\n y1 = oinf1.run({'X': X})['variable']\n\n model_onnx = to_onnx(\n model, X[:1], target_opset=get_opset_number_from_onnx(),\n rename_strategy='simple')\n oinf1 = OnnxInference(model_onnx)\n y2 = oinf1.run({'X': X})['variable']\n self.assertEqualArray(y1, y2)\n\n @ignore_warnings((DeprecationWarning, UserWarning))\n def test_to_onnx_rename_names_scorer(self):\n X = numpy.array([[0, 1, 0, 2],\n [1, 0, 4, 5],\n [9, 8, 5, 6]], dtype=numpy.float64)\n Y = X[:2].copy()\n Y[0, :] = 0\n\n init_types = OrderedDict([('X', X), ('Y', Y)])\n opset = get_opset_number_from_onnx()\n scorer = make_scorer(\n score_cdist_sum, metric='sqeuclidean',\n greater_is_better=False)\n\n monx1 = to_onnx(scorer, init_types, target_opset=opset,\n rewrite_ops=True)\n monx2 = to_onnx(scorer, init_types, target_opset=opset,\n rewrite_ops=True, rename_strategy='simple')\n\n oinf1 = OnnxInference(monx1)\n oinf2 = OnnxInference(monx2)\n res0 = score_cdist_sum(X, Y, metric='sqeuclidean')\n res1 = oinf1.run({'X': X, 'Y': Y})['scores']\n res2 = oinf2.run({'X': X, 'Y': Y})['scores']\n self.assertEqualArray(res1, res0, decimal=5)\n self.assertEqualArray(res2, res0, decimal=5)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n", "\"\"\"\n@brief test log(time=16s)\n\"\"\"\nimport unittest\nimport numpy\nfrom pandas import DataFrame\nfrom pyquickhelper.pycode import ExtTestCase\nfrom sklearn.datasets import make_classification\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.naive_bayes import BernoulliNB\nfrom skl2onnx import convert_sklearn\nfrom skl2onnx.common.data_types import FloatTensorType\nfrom mlprodict.onnxrt import OnnxInference\nfrom mlprodict.tools.asv_options_helper import get_opset_number_from_onnx, get_ir_version_from_onnx\nfrom mlprodict.testing.test_utils import _capture_output\n\n\nclass TestRtValidateNaive(ExtTestCase):\n\n def fit_classification_model(self, model, n_classes, is_int=False,\n pos_features=False, label_string=False):\n X, y = make_classification(n_classes=n_classes, n_features=100,\n n_samples=1000,\n random_state=42, n_informative=7)\n if label_string:\n y = numpy.array(['cl%d' % cl for cl in y])\n X = X.astype(numpy.int64) if is_int else X.astype(numpy.float32)\n if pos_features:\n X = numpy.abs(X)\n X_train, X_test, y_train, _ = train_test_split(X, y, test_size=0.5,\n random_state=42)\n model.fit(X_train, y_train)\n return model, X_test\n\n def test_model_bernoulli_nb_bc_python(self):\n model, X = self.fit_classification_model(BernoulliNB(), 2)\n model_onnx = convert_sklearn(\n model, \"?\", [(\"input\", FloatTensorType([None, X.shape[1]]))])\n exp1 = model.predict(X)\n exp = model.predict_proba(X)\n\n oinf = OnnxInference(model_onnx, runtime='python')\n got = oinf.run({'input': X})\n self.assertEqualArray(exp1, got['output_label'])\n got2 = DataFrame(got['output_probability']).values\n self.assertEqualArray(exp, got2, decimal=4)\n\n def test_model_bernoulli_nb_bc_onnxruntime1(self):\n model, X = self.fit_classification_model(BernoulliNB(), 2)\n model_onnx = convert_sklearn(\n model, \"?\", [(\"input\", FloatTensorType([None, X.shape[1]]))],\n target_opset=get_opset_number_from_onnx())\n exp1 = model.predict(X)\n exp = model.predict_proba(X)\n\n model_onnx.ir_version = get_ir_version_from_onnx()\n oinf = _capture_output(\n lambda: OnnxInference(model_onnx, runtime='onnxruntime1'),\n 'c')[0]\n got = oinf.run({'input': X})\n self.assertEqualArray(exp1, got['output_label'])\n got2 = DataFrame(got['output_probability']).values\n self.assertEqualArray(exp, got2, decimal=4)\n\n def test_model_bernoulli_nb_bc_onnxruntime2(self):\n model, X = self.fit_classification_model(BernoulliNB(), 2)\n model_onnx = convert_sklearn(\n model, \"?\", [(\"input\", FloatTensorType([None, X.shape[1]]))],\n options={id(model): {'zipmap': False}},\n target_opset=get_opset_number_from_onnx())\n exp1 = model.predict(X)\n exp = model.predict_proba(X)\n\n model_onnx.ir_version = get_ir_version_from_onnx()\n oinf = _capture_output(\n lambda: OnnxInference(model_onnx, runtime='onnxruntime2'),\n 'c')[0]\n got = oinf.run({'input': X})\n self.assertEqualArray(exp1, got['label'])\n got2 = DataFrame(got['probabilities']).values\n self.assertEqualArray(exp, got2, decimal=4)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n", "# -*- encoding: utf-8 -*-\n# pylint: disable=E0203,E1101,C0111\n\"\"\"\n@file\n@brief Runtime operator.\n\"\"\"\nimport numpy\nfrom onnx.defs import onnx_opset_version\nfrom ._op import OpRunArg\n\n\ndef _argmin(data, axis=0, keepdims=True):\n result = numpy.argmin(data, axis=axis)\n if keepdims and len(result.shape) < len(data.shape):\n result = numpy.expand_dims(result, axis)\n return result.astype(numpy.int64)\n\n\ndef _argmin_use_numpy_select_last_index(\n data, axis=0, keepdims=True):\n data = numpy.flip(data, axis)\n result = numpy.argmin(data, axis=axis)\n result = data.shape[axis] - result - 1\n if keepdims:\n result = numpy.expand_dims(result, axis)\n return result.astype(numpy.int64)\n\n\nclass _ArgMin(OpRunArg):\n \"\"\"\n Base class for runtime for operator `ArgMin\n <https://github.com/onnx/onnx/blob/master/docs/\n Operators.md#ArgMin>`_.\n \"\"\"\n\n def __init__(self, onnx_node, desc=None,\n expected_attributes=None, **options):\n OpRunArg.__init__(self, onnx_node, desc=desc,\n expected_attributes=expected_attributes,\n **options)\n\n def _run(self, data): # pylint: disable=W0221\n return (_argmin(data, axis=self.axis, keepdims=self.keepdims), )\n\n\nclass ArgMin_11(_ArgMin):\n\n atts = {'axis': 0, 'keepdims': 1}\n\n def __init__(self, onnx_node, desc=None, **options):\n _ArgMin.__init__(self, onnx_node, desc=desc,\n expected_attributes=ArgMin_11.atts,\n **options)\n\n def to_python(self, inputs):\n return ('import numpy\\nfrom mlprodict.onnxrt.ops_cpu.op_argmin import _argmin',\n 'return _argmin(%s, axis=axis, keepdims=keepdims)' % inputs[0])\n\n\nclass ArgMin_12(_ArgMin):\n\n atts = {'axis': 0, 'keepdims': 1, 'select_last_index': 0}\n\n def __init__(self, onnx_node, desc=None, **options):\n _ArgMin.__init__(self, onnx_node, desc=desc,\n expected_attributes=ArgMin_12.atts,\n **options)\n\n def _run(self, data): # pylint: disable=W0221\n if self.select_last_index == 0:\n return _ArgMin._run(self, data)\n return (_argmin_use_numpy_select_last_index(\n data, axis=self.axis, keepdims=self.keepdims), )\n\n def to_python(self, inputs):\n lines = [\n \"if select_last_index == 0:\",\n \" return _argmin({0}, axis=axis, keepdims=keepdims)\",\n \"return _argmin_use_numpy_select_last_index(\",\n \" {0}, axis=axis, keepdims=keepdims)\"]\n return ('import numpy\\nfrom mlprodict.onnxrt.ops_cpu.op_argmin import _argmin, _argmin_use_numpy_select_last_index',\n \"\\n\".join(lines).format(inputs[0]))\n\n\nif onnx_opset_version() >= 12:\n ArgMin = ArgMin_12\nelse:\n ArgMin = ArgMin_11 # pragma: no cover\n", "\"\"\"\n@brief test log(time=24s)\n\"\"\"\nimport os\nimport sys\nfrom io import BytesIO\nimport pickle\nimport unittest\nimport warnings\nfrom logging import getLogger\nimport numpy\nimport pandas\nfrom onnx.onnx_cpp2py_export.checker import ValidationError # pylint: disable=E0401,E0611\nfrom onnx.helper import (\n make_tensor, make_node, make_graph, make_tensor_value_info,\n make_model)\nfrom onnx import TensorProto\nfrom sklearn.datasets import load_iris\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.linear_model import LogisticRegression, LinearRegression\nfrom pyquickhelper.pycode import ExtTestCase, get_temp_folder, ignore_warnings\nfrom skl2onnx.algebra.onnx_ops import ( # pylint: disable=E0611\n OnnxAdd, OnnxLinearRegressor, OnnxLinearClassifier,\n OnnxConstantOfShape, OnnxShape, OnnxIdentity,\n OnnxIf, OnnxSub, OnnxGreater, OnnxReduceSum)\nfrom skl2onnx.common.data_types import FloatTensorType, Int64TensorType\nfrom skl2onnx import __version__ as skl2onnx_version\nfrom mlprodict.onnx_conv import to_onnx\nfrom mlprodict.onnxrt import OnnxInference\nfrom mlprodict.tools import get_opset_number_from_onnx\n\n\nclass TestOnnxrtSimple(ExtTestCase):\n\n def setUp(self):\n logger = getLogger('skl2onnx')\n logger.disabled = True\n\n @ignore_warnings(DeprecationWarning)\n def test_onnxt_idi(self):\n idi = numpy.identity(2).astype(numpy.float32)\n onx = OnnxAdd('X', idi, output_names=['Y'],\n op_version=get_opset_number_from_onnx())\n model_def = onx.to_onnx({'X': idi.astype(numpy.float32)},\n target_opset=get_opset_number_from_onnx())\n\n oinf = OnnxInference(model_def)\n res = str(oinf)\n self.assertIn('op_type: \"Add\"', res)\n\n sb = model_def.SerializeToString()\n oinf = OnnxInference(sb)\n res = str(oinf)\n self.assertIn('op_type: \"Add\"', res)\n\n sb = BytesIO(model_def.SerializeToString())\n oinf = OnnxInference(sb)\n res = str(oinf)\n self.assertIn('op_type: \"Add\"', res)\n\n temp = get_temp_folder(__file__, \"temp_onnxrt_idi\")\n name = os.path.join(temp, \"m.onnx\")\n with open(name, \"wb\") as f:\n f.write(model_def.SerializeToString())\n\n oinf = OnnxInference(name)\n res = str(oinf)\n self.assertIn('op_type: \"Add\"', res)\n\n @ignore_warnings(DeprecationWarning)\n def test_onnxt_pickle_check(self):\n idi = numpy.identity(2).astype(numpy.float32)\n onx = OnnxAdd('X', idi, output_names=['Y'],\n op_version=get_opset_number_from_onnx())\n model_def = onx.to_onnx({'X': idi.astype(numpy.float32)},\n target_opset=get_opset_number_from_onnx())\n oinf = OnnxInference(model_def)\n shape = oinf.shape_inference()\n self.assertNotEmpty(shape)\n if not sys.platform.startswith('win'):\n # Crashes (onnx crashes).\n try:\n oinf.check_model()\n except ValidationError as e:\n warnings.warn(\"Why? \" + str(e)) # pylint: disable=E1101\n\n pkl = pickle.dumps(oinf)\n obj = pickle.loads(pkl)\n self.assertEqual(str(oinf), str(obj))\n\n @ignore_warnings(DeprecationWarning)\n def test_onnxt_dot(self):\n idi = numpy.identity(2).astype(numpy.float32)\n idi2 = (numpy.identity(2) * 2).astype(numpy.float32)\n onx = OnnxAdd(\n OnnxAdd('X', idi, op_version=get_opset_number_from_onnx()),\n idi2, output_names=['Y'],\n op_version=get_opset_number_from_onnx())\n model_def = onx.to_onnx({'X': idi.astype(numpy.float32)},\n target_opset=get_opset_number_from_onnx())\n oinf = OnnxInference(model_def)\n dot = oinf.to_dot()\n self.assertIn('Add [', dot)\n self.assertIn('Add1 [', dot)\n self.assertIn('Add\\\\n(Ad_Add)', dot)\n self.assertIn('Add\\\\n(Ad_Add1)', dot)\n self.assertIn('X -> Ad_Add;', dot)\n self.assertIn('Ad_Addcst1 -> Ad_Add1;', dot)\n self.assertIn('Ad_Addcst -> Ad_Add;', dot)\n self.assertIn('Ad_Add1 -> Y;', dot)\n\n @ignore_warnings(DeprecationWarning)\n def test_onnxt_text(self):\n idi = numpy.identity(2).astype(numpy.float32)\n idi2 = (numpy.identity(2) * 2).astype(numpy.float32)\n onx = OnnxAdd(\n OnnxAdd('X', idi, op_version=get_opset_number_from_onnx()),\n idi2, output_names=['Y'],\n op_version=get_opset_number_from_onnx())\n model_def = onx.to_onnx({'X': idi.astype(numpy.float32)},\n target_opset=get_opset_number_from_onnx())\n oinf = OnnxInference(model_def)\n text = oinf.to_text()\n self.assertIn('Init', text)\n self.assertIn('Input-0', text)\n self.assertIn('Output-0', text)\n self.assertIn('inout', text)\n self.assertIn('O0 I0', text)\n self.assertIn('Ad_Addcst', text)\n\n @ignore_warnings(DeprecationWarning)\n def test_onnxt_text_seq(self):\n idi = numpy.identity(2).astype(numpy.float32)\n idi2 = (numpy.identity(2) * 2).astype(numpy.float32)\n onx = OnnxAdd(\n OnnxAdd('X', idi, op_version=get_opset_number_from_onnx()),\n idi2, output_names=['Y'],\n op_version=get_opset_number_from_onnx())\n model_def = onx.to_onnx({'X': idi.astype(numpy.float32)},\n target_opset=get_opset_number_from_onnx())\n oinf = OnnxInference(model_def)\n text = oinf.to_text(kind='seq')\n self.assertIn('input:', text)\n\n @ignore_warnings(DeprecationWarning)\n def test_onnxt_dot_onnx(self):\n idi = numpy.identity(2).astype(numpy.float32)\n idi2 = (numpy.identity(2) * 2).astype(numpy.float32)\n onx = OnnxAdd(\n OnnxAdd('X', idi, op_version=get_opset_number_from_onnx()),\n idi2, output_names=['Y'],\n op_version=get_opset_number_from_onnx())\n model_def = onx.to_onnx({'X': idi.astype(numpy.float32)},\n target_opset=get_opset_number_from_onnx())\n oinf = OnnxInference(model_def)\n dot = oinf.to_dot(use_onnx=True)\n self.assertIn('[label=\"Ad_Addcst1\"', dot)\n\n @ignore_warnings(DeprecationWarning)\n def test_onnxt_dot_shape(self):\n idi = numpy.identity(2).astype(numpy.float32)\n idi2 = (numpy.identity(2) * 2).astype(numpy.float32)\n onx = OnnxAdd(\n OnnxAdd('X', idi, op_version=get_opset_number_from_onnx()),\n idi2, output_names=['Y'],\n op_version=get_opset_number_from_onnx())\n model_def = onx.to_onnx({'X': idi.astype(numpy.float32)},\n target_opset=get_opset_number_from_onnx())\n oinf = OnnxInference(model_def)\n dot = oinf.to_dot(add_rt_shapes=True)\n self.assertIn('Add [', dot)\n self.assertIn('Add1 [', dot)\n self.assertIn('Add\\\\n(Ad_Add)', dot)\n self.assertIn('Add\\\\n(Ad_Add1)', dot)\n self.assertIn('X -> Ad_Add;', dot)\n self.assertIn('Ad_Addcst1 -> Ad_Add1;', dot)\n self.assertIn('Ad_Addcst -> Ad_Add;', dot)\n self.assertIn('Ad_Add1 -> Y;', dot)\n self.assertIn('shape=(n, 2)', dot)\n self.assertIn('inplace', dot)\n\n @ignore_warnings(DeprecationWarning)\n def test_onnxt_lreg(self):\n pars = dict(coefficients=numpy.array([1., 2.]), intercepts=numpy.array([1.]),\n post_transform='NONE')\n onx = OnnxLinearRegressor('X', output_names=['Y'], **pars)\n model_def = onx.to_onnx({'X': pars['coefficients'].astype(numpy.float32)},\n outputs=[('Y', FloatTensorType([1]))],\n target_opset=get_opset_number_from_onnx())\n oinf = OnnxInference(model_def)\n dot = oinf.to_dot()\n self.assertIn('coefficients=[1. 2.]', dot)\n self.assertIn('LinearRegressor', dot)\n\n @ignore_warnings(DeprecationWarning)\n def test_onnxt_lrc(self):\n pars = dict(coefficients=numpy.array([1., 2.]), intercepts=numpy.array([1.]),\n classlabels_ints=[0, 1], post_transform='NONE')\n onx = OnnxLinearClassifier('X', output_names=['Y', 'Yp'], **pars)\n model_def = onx.to_onnx({'X': pars['coefficients'].astype(numpy.float32)},\n outputs=[('Y', Int64TensorType()),\n ('Yp', FloatTensorType())],\n target_opset=get_opset_number_from_onnx())\n oinf = OnnxInference(model_def)\n dot = oinf.to_dot()\n self.assertIn('coefficients=[1. 2.]', dot)\n self.assertIn('LinearClassifier', dot)\n\n @ignore_warnings(DeprecationWarning)\n def test_onnxt_lrc_iris(self):\n iris = load_iris()\n X, y = iris.data, iris.target\n X_train, _, y_train, __ = train_test_split(X, y, random_state=11)\n clr = LogisticRegression(solver=\"liblinear\")\n clr.fit(X_train, y_train)\n\n model_def = to_onnx(clr, X_train.astype(numpy.float32),\n target_opset=get_opset_number_from_onnx())\n oinf = OnnxInference(model_def)\n dot = oinf.to_dot()\n self.assertIn('ZipMap', dot)\n self.assertIn('LinearClassifier', dot)\n\n @ignore_warnings(DeprecationWarning)\n def test_onnxt_lrc_iris_json(self):\n iris = load_iris()\n X, y = iris.data, iris.target\n X_train, _, y_train, __ = train_test_split(X, y, random_state=11)\n clr = LogisticRegression(solver=\"liblinear\")\n clr.fit(X_train, y_train)\n\n model_def = to_onnx(clr, X_train.astype(numpy.float32),\n target_opset=get_opset_number_from_onnx())\n oinf = OnnxInference(model_def)\n js = oinf.to_json()\n self.assertIn('\"producer_name\": \"skl2onnx\",', js)\n self.assertIn('\"name\": \"output_label\",', js)\n self.assertIn('\"name\": \"output_probability\",', js)\n self.assertIn('\"name\": \"LinearClassifier\",', js)\n self.assertIn('\"coefficients\": {', js)\n self.assertIn('\"name\": \"Normalizer\",', js)\n self.assertIn('\"name\": \"Cast\",', js)\n self.assertIn('\"name\": \"ZipMap\",', js)\n\n @ignore_warnings(DeprecationWarning)\n def test_onnxt_json(self):\n idi = numpy.identity(2).astype(numpy.float32)\n idi2 = (numpy.identity(2) * 2).astype(numpy.float32)\n onx = OnnxAdd(\n OnnxAdd('X', idi, op_version=get_opset_number_from_onnx()),\n idi2, output_names=['Y'],\n op_version=get_opset_number_from_onnx())\n model_def = onx.to_onnx({'X': idi.astype(numpy.float32)},\n target_opset=get_opset_number_from_onnx())\n oinf = OnnxInference(model_def)\n js = oinf.to_json()\n self.assertIn('\"initializers\": {', js)\n\n @ignore_warnings(DeprecationWarning)\n def test_onnxt_graph(self):\n idi = numpy.identity(2).astype(numpy.float32)\n idi2 = (numpy.identity(2) * 2).astype(numpy.float32)\n onx = OnnxAdd(\n OnnxAdd('X', idi, op_version=get_opset_number_from_onnx()),\n idi2, output_names=['Y'],\n op_version=get_opset_number_from_onnx())\n model_def = onx.to_onnx({'X': idi.astype(numpy.float32)},\n target_opset=get_opset_number_from_onnx())\n oinf = OnnxInference(model_def)\n js = oinf.to_sequence()\n self.assertIn('inits', js)\n self.assertIn('inputs', js)\n self.assertIn('outputs', js)\n self.assertIn('intermediate', js)\n self.assertIn('nodes', js)\n self.assertIn('sequence', js)\n self.assertEqual(len(js['sequence']), 2)\n self.assertEqual(len(js['intermediate']), 2)\n\n @ignore_warnings(DeprecationWarning)\n def test_onnxt_run(self):\n idi = numpy.identity(2, dtype=numpy.float32)\n idi2 = (numpy.identity(2) * 2).astype(numpy.float32)\n onx = OnnxAdd(\n OnnxAdd('X', idi, op_version=get_opset_number_from_onnx()),\n idi2, output_names=['Y'],\n op_version=get_opset_number_from_onnx())\n model_def = onx.to_onnx({'X': idi.astype(numpy.float32)},\n target_opset=get_opset_number_from_onnx())\n oinf = OnnxInference(model_def)\n X = numpy.array([[1, 1], [3, 3]])\n y = oinf.run({'X': X.astype(numpy.float32)})\n exp = numpy.array([[4, 1], [3, 6]], dtype=numpy.float32)\n self.assertEqual(list(y), ['Y'])\n self.assertEqualArray(y['Y'], exp)\n\n @ignore_warnings(DeprecationWarning)\n def test_onnxt_lrreg_iris_run(self):\n iris = load_iris()\n X, y = iris.data, iris.target\n X_train, X_test, y_train, _ = train_test_split(X, y, random_state=11)\n clr = LinearRegression()\n clr.fit(X_train, y_train)\n\n model_def = to_onnx(clr, X_train.astype(numpy.float32),\n target_opset=get_opset_number_from_onnx())\n oinf = OnnxInference(model_def)\n y = oinf.run({'X': X_test})\n exp = clr.predict(X_test)\n self.assertEqual(list(sorted(y)), ['variable'])\n self.assertEqualArray(exp, y['variable'].ravel(), decimal=6)\n\n @ignore_warnings(DeprecationWarning)\n def test_onnxt_lrc_iris_run(self):\n iris = load_iris()\n X, y = iris.data, iris.target\n X_train, X_test, y_train, _ = train_test_split(X, y, random_state=11)\n clr = LogisticRegression(solver=\"liblinear\")\n clr.fit(X_train, y_train)\n\n model_def = to_onnx(clr, X_train.astype(numpy.float32),\n target_opset=get_opset_number_from_onnx())\n oinf = OnnxInference(model_def)\n y = oinf.run({'X': X_test})\n self.assertEqual(list(sorted(y)), [\n 'output_label', 'output_probability'])\n lexp = clr.predict(X_test)\n self.assertEqualArray(lexp, y['output_label'])\n\n exp = clr.predict_proba(X_test)\n got = pandas.DataFrame(list(y['output_probability'])).values\n self.assertEqualArray(exp, got, decimal=5)\n\n @ignore_warnings(DeprecationWarning)\n def test_onnxt_knn_iris_dot(self):\n iris = load_iris()\n X, y = iris.data, iris.target\n X_train, __, y_train, _ = train_test_split(X, y, random_state=11)\n clr = KNeighborsClassifier()\n clr.fit(X_train, y_train)\n\n model_def = to_onnx(clr, X_train.astype(numpy.float32),\n target_opset=get_opset_number_from_onnx())\n oinf = OnnxInference(model_def, skip_run=True)\n dot = oinf.to_dot()\n self.assertNotIn(\"class_labels_0 -> ;\", dot)\n\n @ignore_warnings(DeprecationWarning)\n def test_getitem(self):\n iris = load_iris()\n X, y = iris.data, iris.target\n X_train, __, y_train, _ = train_test_split(X, y, random_state=11)\n clr = KNeighborsClassifier()\n clr.fit(X_train, y_train)\n\n model_def = to_onnx(clr, X_train.astype(numpy.float32),\n target_opset=get_opset_number_from_onnx())\n oinf = OnnxInference(model_def, skip_run=True)\n\n exp_name = 'blab_ArrayFeatureExtractor'\n if exp_name not in str(model_def):\n exp_name = \"knny_ArrayFeatureExtractor\"\n topk = oinf[exp_name]\n self.assertIn(exp_name, str(topk))\n zm = oinf['ZipMap']\n self.assertIn('ZipMap', str(zm))\n par = oinf['ZipMap', 'classlabels_int64s']\n self.assertIn('classlabels_int64s', str(par))\n\n @ignore_warnings(DeprecationWarning)\n def test_constant_of_shape(self):\n x = numpy.array([1, 2, 4, 5, 5, 4]).astype(\n numpy.float32).reshape((3, 2))\n tensor_value = make_tensor(\n \"value\", TensorProto.FLOAT, (1,), [-5]) # pylint: disable=E1101\n cop2 = OnnxConstantOfShape(\n OnnxShape('input', op_version=get_opset_number_from_onnx()),\n value=tensor_value,\n output_names=['mat'],\n op_version=get_opset_number_from_onnx())\n model_def = cop2.to_onnx({'input': x},\n outputs=[('mat', FloatTensorType())],\n target_opset=get_opset_number_from_onnx())\n oinf = OnnxInference(model_def, skip_run=True)\n dot = oinf.to_dot()\n self.assertIn('ConstantOfShape', dot)\n\n @ignore_warnings(DeprecationWarning)\n def test_onnxt_pdist_dot(self):\n from skl2onnx.algebra.complex_functions import onnx_squareform_pdist # pylint: disable=E0401,E0611\n x = numpy.array([1, 2, 4, 5, 5, 4]).astype(\n numpy.float32).reshape((3, 2))\n cop = OnnxAdd('input', 'input',\n op_version=get_opset_number_from_onnx())\n cdist = onnx_squareform_pdist(cop, dtype=numpy.float32,\n op_version=get_opset_number_from_onnx())\n cop2 = OnnxIdentity(cdist, output_names=['cdist'],\n op_version=get_opset_number_from_onnx())\n\n model_def = cop2.to_onnx(\n {'input': x}, outputs=[('cdist', FloatTensorType())],\n target_opset=get_opset_number_from_onnx())\n\n oinf = OnnxInference(model_def, skip_run=True)\n dot = oinf.to_dot(recursive=True)\n self.assertIn(\"B_next_out\", dot)\n self.assertIn(\"cluster\", dot)\n\n @ignore_warnings(DeprecationWarning)\n def test_onnxt_lrc_iris_run_node_time(self):\n iris = load_iris()\n X, y = iris.data, iris.target\n X_train, X_test, y_train, _ = train_test_split(X, y, random_state=11)\n clr = LogisticRegression(solver=\"liblinear\")\n clr.fit(X_train, y_train)\n\n model_def = to_onnx(clr, X_train.astype(numpy.float32),\n target_opset=get_opset_number_from_onnx())\n oinf = OnnxInference(model_def)\n _, mt = oinf.run({'X': X_test}, node_time=True)\n self.assertIsInstance(mt, list)\n self.assertGreater(len(mt), 1)\n self.assertIsInstance(mt[0], dict)\n\n rows = []\n\n def myprint(*args):\n rows.append(' '.join(map(str, args)))\n\n _, mt = oinf.run({'X': X_test}, node_time=True,\n verbose=1, fLOG=myprint)\n self.assertIsInstance(mt, list)\n self.assertGreater(len(mt), 1)\n self.assertIsInstance(mt[0], dict)\n\n @ignore_warnings(DeprecationWarning)\n def test_blofat16(self):\n node1 = make_node(\"Min\", [\"X\", \"Y\"], [\"Z\"], name=\"trans\")\n\n graph = make_graph(\n [node1], \"min_graph\",\n [make_tensor_value_info(\"X\", TensorProto.FLOAT16, [3]), # pylint: disable=E1101\n make_tensor_value_info(\"Y\", TensorProto.FLOAT16, [3])], # pylint: disable=E1101\n [make_tensor_value_info(\"Z\", TensorProto.FLOAT16, [3])]) # pylint: disable=E1101\n model_proto = make_model(\n graph, producer_name='mlprodict', ir_version=6, producer_version='0.1')\n\n oinf = OnnxInference(model_proto)\n x_val = [1, 2, -3]\n y_val = [4, -5, -6]\n res = oinf.run({\"X\": numpy.array(x_val, dtype=numpy.float16),\n \"Y\": numpy.array(y_val, dtype=numpy.float16)})\n self.assertEqualArray(res['Z'], numpy.array(\n [1, -5, -6], dtype=numpy.float16))\n dot = oinf.to_dot()\n self.assertIn('float16', dot)\n\n oinf = OnnxInference(model_proto, runtime='python_compiled')\n res = oinf.run({\"X\": numpy.array(x_val, dtype=numpy.float16),\n \"Y\": numpy.array(y_val, dtype=numpy.float16)})\n self.assertEqualArray(res['Z'], numpy.array(\n [1, -5, -6], dtype=numpy.float16))\n self.assertIn('n0_min(X, Y)', str(oinf))\n\n @ignore_warnings(DeprecationWarning)\n def test_onnx_if_to_dot(self):\n opv = 15\n x1 = numpy.array([[0, 3], [7, 0]], dtype=numpy.float32)\n x2 = numpy.array([[1, 0], [2, 0]], dtype=numpy.float32)\n\n node = OnnxAdd(\n 'x1', 'x2', output_names=['absxythen'], op_version=opv)\n then_body = node.to_onnx(\n {'x1': x1, 'x2': x2}, target_opset=opv,\n outputs=[('absxythen', FloatTensorType())])\n node = OnnxSub(\n 'x1', 'x2', output_names=['absxyelse'], op_version=opv)\n else_body = node.to_onnx(\n {'x1': x1, 'x2': x2}, target_opset=opv,\n outputs=[('absxyelse', FloatTensorType())])\n del else_body.graph.input[:]\n del then_body.graph.input[:]\n\n cond = OnnxGreater(\n OnnxReduceSum('x1', op_version=opv),\n OnnxReduceSum('x2', op_version=opv),\n op_version=opv)\n ifnode = OnnxIf(cond, then_branch=then_body.graph,\n else_branch=else_body.graph,\n op_version=opv, output_names=['y'])\n model_def = ifnode.to_onnx(\n {'x1': x1, 'x2': x2}, target_opset=opv,\n outputs=[('y', FloatTensorType())])\n dot = OnnxInference(model_def, skip_run=True).to_dot(recursive=True)\n self.assertIn(\"subgraph cluster_If\", dot)\n\n @ignore_warnings(DeprecationWarning)\n def test_onnx_if_to_dot2(self):\n opv = get_opset_number_from_onnx()\n x1 = numpy.array([[0, 3], [7, 0]], dtype=numpy.float32)\n x2 = numpy.array([[1, 0], [2, 0]], dtype=numpy.float32)\n\n node = OnnxAdd(\n 'x1', 'x2', output_names=['absxythen'], op_version=opv)\n then_body = node.to_onnx(\n {'x1': x1, 'x2': x2}, target_opset=opv,\n outputs=[('absxythen', FloatTensorType())])\n node = OnnxSub(\n 'x1', 'x2', output_names=['absxyelse'], op_version=opv)\n else_body = node.to_onnx(\n {'x1': x1, 'x2': x2}, target_opset=opv,\n outputs=[('absxyelse', FloatTensorType())])\n del else_body.graph.input[:]\n del then_body.graph.input[:]\n\n cond = OnnxGreater(\n OnnxReduceSum('x1', op_version=opv),\n OnnxReduceSum('x2', op_version=opv),\n op_version=opv)\n ifnode = OnnxIf(cond, then_branch=then_body.graph,\n else_branch=else_body.graph,\n op_version=opv, output_names=['y'])\n model_def = ifnode.to_onnx(\n {'x1': x1, 'x2': x2}, target_opset=opv,\n outputs=[('y', FloatTensorType())])\n dot = OnnxInference(model_def).to_dot(recursive=True)\n self.assertIn('[lhead=cluster_If', dot)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n", "\"\"\"\nCommon class for all benchmarks testing\nconverted models from :epkg:`scikit-learn`\nwith :epkg:`asv`. The benchmark can be run through\nfile :epkg:`run_asv.sh` on Linux or :epkg:`run_asv.bat` on\nWindows.\n\n.. warning::\n On Windows, you should avoid cloning the repository\n on a folder with a long full name. Visual Studio tends to\n abide by the rule of the maximum path length even though\n the system is told otherwise.\n\"\"\"\nimport os\nfrom datetime import datetime\nimport pickle\nfrom logging import getLogger\nimport numpy\nfrom sklearn import set_config\nfrom sklearn.datasets import load_iris\nfrom sklearn.metrics import (\n accuracy_score, mean_absolute_error,\n silhouette_score)\nfrom sklearn.model_selection import train_test_split\nfrom mlprodict.onnxrt import OnnxInference\nfrom mlprodict.onnx_conv import (\n to_onnx, register_rewritten_operators, register_converters)\nfrom mlprodict.onnxrt.validate.validate_benchmark import make_n_rows\nfrom mlprodict.onnxrt.validate.validate_problems import _modify_dimension\nfrom mlprodict.onnx_tools.optim import onnx_statistics\nfrom mlprodict.tools.asv_options_helper import (\n expand_onnx_options, get_opset_number_from_onnx,\n get_ir_version_from_onnx, version2number)\nfrom mlprodict.tools.model_info import set_random_state\nfrom mlprodict.tools.ort_wrapper import onnxrt_version\n\n\nclass _CommonAsvSklBenchmark:\n \"\"\"\n Common tests to all benchmarks testing converted\n :epkg:`scikit-learn` models. See `benchmark attributes\n <https://asv.readthedocs.io/en/stable/benchmarks.html#general>`_.\n \"\"\"\n\n # Part which changes.\n # params and param_names may be changed too.\n\n params = [\n ['skl', 'pyrtc', 'ort'], # values for runtime\n [1, 10, 100, 10000], # values for N\n [4, 20], # values for nf\n [get_opset_number_from_onnx()], # values for opset\n [\"float\", \"double\"], # values for dtype\n [None], # values for optim\n ]\n param_names = ['rt', 'N', 'nf', 'opset', 'dtype', 'optim']\n chk_method_name = None\n version = datetime.now().isoformat()\n pretty_source = \"disabled\"\n\n par_ydtype = numpy.int64\n par_dofit = True\n par_convopts = None\n\n def _create_model(self): # pragma: no cover\n raise NotImplementedError(\"This method must be overwritten.\")\n\n def _create_onnx_and_runtime(self, runtime, model, X, opset, dtype, optim): # pragma: no cover\n raise NotImplementedError(\"This method must be overwritten.\")\n\n def _score_metric(self, X, y_exp, y_pred): # pragma: no cover\n raise NotImplementedError(\"This method must be overwritten.\")\n\n def _optimize_onnx(self, onx):\n return onx\n\n def _get_xdtype(self, dtype):\n if dtype in ('float', numpy.float32):\n return numpy.float32\n elif dtype in ('double', '64', 64, numpy.float64):\n return numpy.float64\n raise ValueError( # pragma: no cover\n \"Unknown dtype '{}'.\".format(dtype))\n\n def _get_dataset(self, nf, dtype):\n xdtype = self._get_xdtype(dtype)\n data = load_iris()\n X, y = data.data, data.target\n state = numpy.random.RandomState(seed=34) # pylint: disable=E1101\n rnd = state.randn(*X.shape) / 3\n X += rnd\n X = _modify_dimension(X, nf)\n X_train, X_test, y_train, y_test = train_test_split(\n X, y, random_state=42)\n Xt = X_test.astype(xdtype)\n yt = y_test.astype(self.par_ydtype)\n return (X_train, y_train), (Xt, yt)\n\n def _to_onnx(self, model, X, opset, dtype, optim):\n if optim is None or len(optim) == 0:\n options = self.par_convopts\n elif self.par_convopts and len(self.par_convopts) > 0:\n raise NotImplementedError( # pragma: no cover\n \"Conflict between par_convopts={} and optim={}\".format(\n self.par_convopts, optim))\n else:\n # Expand common onnx options, see _nick_name_options.\n options = expand_onnx_options(model, optim)\n\n return to_onnx(model, X, options=options, target_opset=opset)\n\n def _create_onnx_inference(self, onx, runtime):\n if 'onnxruntime' in runtime:\n old = onx.ir_version\n onx.ir_version = get_ir_version_from_onnx()\n else:\n old = None\n\n try:\n res = OnnxInference(\n onx, runtime=runtime, runtime_options=dict(\n log_severity_level=3))\n except RuntimeError as e: # pragma: no cover\n if \"[ONNXRuntimeError]\" in str(e):\n return RuntimeError(\"onnxruntime fails due to {}\".format(str(e)))\n raise e\n if old is not None:\n onx.ir_version = old\n return res\n\n # Part which does not change.\n\n def _check_rt(self, rt, meth):\n \"\"\"\n Checks that runtime has the appropriate method.\n \"\"\"\n if rt is None:\n raise ValueError(\"rt cannot be empty.\") # pragma: no cover\n if not hasattr(rt, meth):\n raise TypeError( # pragma: no cover\n \"rt of type %r has no method %r.\" % (type(rt), meth))\n\n def runtime_name(self, runtime):\n \"\"\"\n Returns the runtime shortname.\n \"\"\"\n if runtime == 'skl':\n name = runtime\n elif runtime == 'ort':\n name = 'onnxruntime1'\n elif runtime == 'ort2':\n name = 'onnxruntime2' # pragma: no cover\n elif runtime == 'pyrt':\n name = 'python'\n elif runtime == 'pyrtc':\n name = 'python_compiled'\n else:\n raise ValueError( # pragma: no cover\n \"Unknown runtime '{}'.\".format(runtime))\n return name\n\n def _name(self, nf, opset, dtype):\n last = 'cache-{}-nf{}-op{}-dt{}.pickle'.format(\n self.__class__.__name__, nf, opset, dtype)\n return last\n\n def setup_cache(self):\n \"asv API\"\n for dtype in self.params[4]:\n for opv in self.params[3]:\n for nf in self.params[2]:\n (X_train, y_train), (X, y) = self._get_dataset(nf, dtype)\n model = self._create_model()\n if self.par_dofit:\n set_random_state(model)\n model.fit(X_train, y_train)\n stored = {'model': model, 'X': X, 'y': y}\n filename = self._name(nf, opv, dtype)\n with open(filename, \"wb\") as f:\n pickle.dump(stored, f)\n if not os.path.exists(filename):\n raise RuntimeError( # pragma: no cover\n \"Unable to dump model %r into %r.\" % (\n model, filename))\n\n def setup(self, runtime, N, nf, opset, dtype, optim):\n \"asv API\"\n logger = getLogger('skl2onnx')\n logger.disabled = True\n register_converters()\n register_rewritten_operators()\n with open(self._name(nf, opset, dtype), \"rb\") as f:\n stored = pickle.load(f)\n self.stored = stored\n self.model = stored['model']\n self.X, self.y = make_n_rows(stored['X'], N, stored['y'])\n onx, rt_, rt_fct_, rt_fct_track_ = self._create_onnx_and_runtime(\n runtime, self.model, self.X, opset, dtype, optim)\n self.onx = onx\n setattr(self, \"rt_\" + runtime, rt_)\n setattr(self, \"rt_fct_\" + runtime, rt_fct_)\n setattr(self, \"rt_fct_track_\" + runtime, rt_fct_track_)\n set_config(assume_finite=True)\n\n def time_predict(self, runtime, N, nf, opset, dtype, optim):\n \"asv API\"\n return getattr(self, \"rt_fct_\" + runtime)(self.X)\n\n def peakmem_predict(self, runtime, N, nf, opset, dtype, optim):\n \"asv API\"\n return getattr(self, \"rt_fct_\" + runtime)(self.X)\n\n def track_score(self, runtime, N, nf, opset, dtype, optim):\n \"asv API\"\n yp = getattr(self, \"rt_fct_track_\" + runtime)(self.X)\n return self._score_metric(self.X, self.y, yp)\n\n def track_onnxsize(self, runtime, N, nf, opset, dtype, optim):\n \"asv API\"\n return len(self.onx.SerializeToString())\n\n def track_nbnodes(self, runtime, N, nf, opset, dtype, optim):\n \"asv API\"\n stats = onnx_statistics(self.onx)\n return stats.get('nnodes', 0)\n\n def track_vmlprodict(self, runtime, N, nf, opset, dtype, optim):\n \"asv API\"\n from mlprodict import __version__\n return version2number(__version__)\n\n def track_vsklearn(self, runtime, N, nf, opset, dtype, optim):\n \"asv API\"\n from sklearn import __version__\n return version2number(__version__)\n\n def track_vort(self, runtime, N, nf, opset, dtype, optim):\n \"asv API\"\n return version2number(onnxrt_version)\n\n def check_method_name(self, method_name):\n \"Does some verifications. Fails if inconsistencies.\"\n if getattr(self, 'chk_method_name', None) not in (None, method_name):\n raise RuntimeError( # pragma: no cover\n \"Method name must be '{}'.\".format(method_name))\n if getattr(self, 'chk_method_name', None) is None:\n raise RuntimeError( # pragma: no cover\n \"Unable to check that the method name is correct \"\n \"(expected is '{}')\".format(\n method_name))\n\n\nclass _CommonAsvSklBenchmarkClassifier(_CommonAsvSklBenchmark):\n \"\"\"\n Common class for a classifier.\n \"\"\"\n chk_method_name = 'predict_proba'\n\n def _score_metric(self, X, y_exp, y_pred):\n return accuracy_score(y_exp, y_pred)\n\n def _create_onnx_and_runtime(self, runtime, model, X, opset, dtype, optim):\n self.check_method_name('predict_proba')\n onx_ = self._to_onnx(model, X, opset, dtype, optim)\n onx = self._optimize_onnx(onx_)\n name = self.runtime_name(runtime)\n if name == 'skl':\n rt_ = None\n rt_fct_ = lambda X: model.predict_proba(X)\n rt_fct_track_ = lambda X: model.predict(X)\n else:\n rt_ = self._create_onnx_inference(onx, name)\n self._check_rt(rt_, 'run')\n rt_fct_ = lambda pX: rt_.run({'X': pX})\n rt_fct_track_ = lambda pX: rt_fct_(pX)['output_label']\n return onx, rt_, rt_fct_, rt_fct_track_\n\n\nclass _CommonAsvSklBenchmarkClassifierRawScore(_CommonAsvSklBenchmark):\n \"\"\"\n Common class for a classifier.\n \"\"\"\n chk_method_name = 'decision_function'\n\n def _score_metric(self, X, y_exp, y_pred):\n return accuracy_score(y_exp, y_pred)\n\n def _create_onnx_and_runtime(self, runtime, model, X, opset, dtype, optim):\n self.check_method_name('decision_function')\n onx_ = self._to_onnx(model, X, opset, dtype, optim)\n onx = self._optimize_onnx(onx_)\n name = self.runtime_name(runtime)\n if name == 'skl':\n rt_ = None\n rt_fct_ = lambda X: model.decision_function(X)\n rt_fct_track_ = lambda X: model.predict(X)\n else:\n rt_ = self._create_onnx_inference(onx, name)\n self._check_rt(rt_, 'run')\n rt_fct_ = lambda X: rt_.run({'X': X})\n rt_fct_track_ = lambda X: rt_fct_(X)['output_label']\n return onx, rt_, rt_fct_, rt_fct_track_\n\n\nclass _CommonAsvSklBenchmarkClustering(_CommonAsvSklBenchmark):\n \"\"\"\n Common class for a clustering algorithm.\n \"\"\"\n chk_method_name = 'predict'\n\n def _score_metric(self, X, y_exp, y_pred):\n if X.shape[0] == 1:\n return 0. # pragma: no cover\n elif set(y_pred) == 1:\n return 0. # pragma: no cover\n return silhouette_score(X, y_pred)\n\n def _create_onnx_and_runtime(self, runtime, model, X, opset, dtype, optim):\n self.check_method_name('predict')\n onx_ = self._to_onnx(model, X, opset, dtype, optim)\n onx = self._optimize_onnx(onx_)\n name = self.runtime_name(runtime)\n if name == 'skl':\n rt_ = None\n rt_fct_ = lambda X: model.predict(X.astype(numpy.float64))\n rt_fct_track_ = lambda X: model.predict(X.astype(numpy.float64))\n else:\n rt_ = self._create_onnx_inference(onx, name)\n self._check_rt(rt_, 'run')\n rt_fct_ = lambda X: rt_.run({'X': X})\n rt_fct_track_ = lambda X: rt_fct_(X)['label']\n return onx, rt_, rt_fct_, rt_fct_track_\n\n\nclass _CommonAsvSklBenchmarkMultiClassifier(_CommonAsvSklBenchmark):\n \"\"\"\n Common class for a multi-classifier.\n \"\"\"\n chk_method_name = 'predict_proba'\n\n def _get_dataset(self, nf, dtype):\n xdtype = self._get_xdtype(dtype)\n data = load_iris()\n X, y = data.data, data.target\n state = numpy.random.RandomState(seed=34) # pylint: disable=E1101\n rnd = state.randn(*X.shape) / 3\n X += rnd\n nbclass = len(set(y))\n y_ = numpy.zeros((y.shape[0], nbclass), dtype=y.dtype)\n for i, vy in enumerate(y):\n y_[i, vy] = 1\n y = y_\n X = _modify_dimension(X, nf)\n X_train, X_test, y_train, y_test = train_test_split(\n X, y, random_state=42)\n X = X_test.astype(xdtype)\n y = y_test.astype(self.par_ydtype)\n return (X_train, y_train), (X, y)\n\n def _score_metric(self, X, y_exp, y_pred):\n return accuracy_score(y_exp.ravel(), y_pred.ravel())\n\n def _create_onnx_and_runtime(self, runtime, model, X, opset, dtype, optim):\n self.check_method_name('predict_proba')\n onx_ = self._to_onnx(model, X, opset, dtype, optim)\n onx = self._optimize_onnx(onx_)\n name = self.runtime_name(runtime)\n if name == 'skl':\n rt_ = None\n rt_fct_ = lambda X: model.predict_proba(X)\n rt_fct_track_ = lambda X: model.predict(X)\n else:\n rt_ = self._create_onnx_inference(onx, name)\n self._check_rt(rt_, 'run')\n rt_fct_ = lambda X: rt_.run({'X': X})\n rt_fct_track_ = lambda X: rt_fct_(X)['output_label']\n return onx, rt_, rt_fct_, rt_fct_track_\n\n\nclass _CommonAsvSklBenchmarkOutlier(_CommonAsvSklBenchmark):\n \"\"\"\n Common class for outlier detection.\n \"\"\"\n chk_method_name = 'predict'\n\n def _score_metric(self, X, y_exp, y_pred):\n return numpy.sum(y_pred) / y_pred.shape[0]\n\n def _create_onnx_and_runtime(self, runtime, model, X, opset, dtype, optim):\n self.check_method_name('predict')\n onx_ = self._to_onnx(model, X, opset, dtype, optim)\n onx = self._optimize_onnx(onx_)\n name = self.runtime_name(runtime)\n if name == 'skl':\n rt_ = None\n rt_fct_ = lambda X: model.predict(X)\n rt_fct_track_ = lambda X: model.predict(X)\n else:\n rt_ = self._create_onnx_inference(onx, name)\n self._check_rt(rt_, 'run')\n rt_fct_ = lambda X: rt_.run({'X': X})\n rt_fct_track_ = lambda X: rt_fct_(X)['scores']\n return onx, rt_, rt_fct_, rt_fct_track_\n\n\nclass _CommonAsvSklBenchmarkRegressor(_CommonAsvSklBenchmark):\n \"\"\"\n Common class for a regressor.\n \"\"\"\n chk_method_name = 'predict'\n\n def _score_metric(self, X, y_exp, y_pred):\n return mean_absolute_error(y_exp, y_pred)\n\n def _create_onnx_and_runtime(self, runtime, model, X, opset, dtype, optim):\n self.check_method_name('predict')\n onx = self._to_onnx(model, X, opset, dtype, optim)\n name = self.runtime_name(runtime)\n if name == 'skl':\n rt_ = None\n rt_fct_ = lambda X: model.predict(X)\n rt_fct_track_ = lambda X: model.predict(X)\n else:\n rt_ = self._create_onnx_inference(onx, name)\n self._check_rt(rt_, 'run')\n rt_fct_ = lambda X: rt_.run({'X': X})\n rt_fct_track_ = lambda X: rt_fct_(X)['variable']\n return onx, rt_, rt_fct_, rt_fct_track_\n\n\nclass _CommonAsvSklBenchmarkTrainableTransform(_CommonAsvSklBenchmark):\n \"\"\"\n Common class for a trainable transformer.\n \"\"\"\n chk_method_name = 'transform'\n\n def _score_metric(self, X, y_exp, y_pred):\n return numpy.sum(y_pred) / y_pred.shape[0]\n\n def _create_onnx_and_runtime(self, runtime, model, X, opset, dtype, optim):\n self.check_method_name('transform')\n onx_ = self._to_onnx(model, X, opset, dtype, optim)\n onx = self._optimize_onnx(onx_)\n name = self.runtime_name(runtime)\n if name == 'skl':\n rt_ = None\n rt_fct_ = lambda X: model.transform(X)\n rt_fct_track_ = lambda X: model.transform(X)\n else:\n rt_ = self._create_onnx_inference(onx, name)\n self._check_rt(rt_, 'run')\n rt_fct_ = lambda X: rt_.run({'X': X})\n rt_fct_track_ = lambda X: rt_fct_(X)['variable']\n return onx, rt_, rt_fct_, rt_fct_track_\n\n\nclass _CommonAsvSklBenchmarkTransform(_CommonAsvSklBenchmark):\n \"\"\"\n Common class for a transformer.\n \"\"\"\n chk_method_name = 'transform'\n\n def _score_metric(self, X, y_exp, y_pred):\n return numpy.sum(y_pred) / y_pred.shape[0]\n\n def _create_onnx_and_runtime(self, runtime, model, X, opset, dtype, optim):\n self.check_method_name('transform')\n onx_ = self._to_onnx(model, X, opset, dtype, optim)\n onx = self._optimize_onnx(onx_)\n name = self.runtime_name(runtime)\n if name == 'skl':\n rt_ = None\n rt_fct_ = lambda X: model.transform(X)\n rt_fct_track_ = lambda X: model.transform(X)\n else:\n rt_ = self._create_onnx_inference(onx, name)\n self._check_rt(rt_, 'run')\n rt_fct_ = lambda X: rt_.run({'X': X})\n rt_fct_track_ = lambda X: rt_fct_(X)['variable']\n return onx, rt_, rt_fct_, rt_fct_track_\n\n\nclass _CommonAsvSklBenchmarkTransformPositive(_CommonAsvSklBenchmarkTransform):\n \"\"\"\n Common class for a transformer for positive features.\n \"\"\"\n chk_method_name = 'transform'\n\n def _get_dataset(self, nf, dtype):\n xdtype = self._get_xdtype(dtype)\n data = load_iris()\n X, y = data.data, data.target\n state = numpy.random.RandomState(seed=34) # pylint: disable=E1101\n rnd = state.randn(*X.shape) / 3\n X += rnd\n X = _modify_dimension(X, nf)\n X = numpy.abs(X)\n X_train, X_test, y_train, y_test = train_test_split(\n X, y, random_state=42)\n X = X_test.astype(xdtype)\n y = y_test.astype(self.par_ydtype)\n return (X_train, y_train), (X, y)\n", "\"\"\"\n@file\n@brief Validates runtime for many :epkg:`scikit-learn` operators.\nThe submodule relies on :epkg:`onnxconverter_common`,\n:epkg:`sklearn-onnx`.\n\"\"\"\nimport math\nimport copy\nimport os\nimport warnings\nfrom importlib import import_module\nimport pickle\nfrom time import perf_counter\nimport numpy\nfrom cpyquickhelper.numbers import measure_time as _c_measure_time\nfrom sklearn.base import BaseEstimator\nfrom sklearn.linear_model._base import LinearModel\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import __all__ as sklearn__all__, __version__ as sklearn_version\nfrom .validate_problems import _problems\n\n\nclass RuntimeBadResultsError(RuntimeError):\n \"\"\"\n Raised when the results are too different from\n :epkg:`scikit-learn`.\n \"\"\"\n\n def __init__(self, msg, obs):\n \"\"\"\n :param msg: to display\n :param obs: observations\n \"\"\"\n RuntimeError.__init__(self, msg)\n self.obs = obs\n\n\ndef _dictionary2str(di):\n el = []\n for k in sorted(di):\n el.append('{}={}'.format(k, di[k]))\n return '/'.join(el)\n\n\ndef modules_list():\n \"\"\"\n Returns modules and versions currently used.\n\n .. runpython::\n :showcode:\n :rst:\n :warningout: DeprecationWarning\n\n from mlprodict.onnxrt.validate.validate_helper import modules_list\n from pyquickhelper.pandashelper import df2rst\n from pandas import DataFrame\n print(df2rst(DataFrame(modules_list())))\n \"\"\"\n def try_import(name):\n try:\n mod = import_module(name)\n except ImportError: # pragma: no cover\n return None\n return (dict(name=name, version=mod.__version__)\n if hasattr(mod, '__version__') else dict(name=name))\n\n rows = []\n for name in sorted(['pandas', 'numpy', 'sklearn', 'mlprodict',\n 'skl2onnx', 'onnxmltools', 'onnx', 'onnxruntime',\n 'scipy']):\n res = try_import(name)\n if res is not None:\n rows.append(res)\n return rows\n\n\ndef _dispsimple(arr, fLOG):\n if isinstance(arr, (tuple, list)):\n for i, a in enumerate(arr):\n fLOG(\"output %d\" % i)\n _dispsimple(a, fLOG)\n elif hasattr(arr, 'shape'):\n if len(arr.shape) == 1:\n threshold = 8\n else:\n threshold = min(\n 50, min(50 // arr.shape[1], 8) * arr.shape[1])\n fLOG(numpy.array2string(arr, max_line_width=120,\n suppress_small=True,\n threshold=threshold))\n else: # pragma: no cover\n s = str(arr)\n if len(s) > 50:\n s = s[:50] + \"...\"\n fLOG(s)\n\n\ndef _merge_options(all_conv_options, aoptions):\n if aoptions is None:\n return copy.deepcopy(all_conv_options)\n if not isinstance(aoptions, dict):\n return copy.deepcopy(aoptions) # pragma: no cover\n merged = {}\n for k, v in all_conv_options.items():\n if k in aoptions:\n merged[k] = _merge_options(v, aoptions[k])\n else:\n merged[k] = copy.deepcopy(v)\n for k, v in aoptions.items():\n if k in all_conv_options:\n continue\n merged[k] = copy.deepcopy(v)\n return merged\n\n\ndef sklearn_operators(subfolder=None, extended=False,\n experimental=True):\n \"\"\"\n Builds the list of operators from :epkg:`scikit-learn`.\n The function goes through the list of submodule\n and get the list of class which inherit from\n :epkg:`scikit-learn:base:BaseEstimator`.\n\n :param subfolder: look into only one subfolder\n :param extended: extends the list to the list of operators\n this package implements a converter for\n :param experimental: includes experimental module from\n :epkg:`scikit-learn` (see `sklearn.experimental\n <https://github.com/scikit-learn/scikit-learn/\n tree/master/sklearn/experimental>`_)\n :return: the list of found operators\n \"\"\"\n if experimental:\n from sklearn.experimental import ( # pylint: disable=W0611\n enable_hist_gradient_boosting,\n enable_iterative_imputer)\n\n subfolders = sklearn__all__ + ['mlprodict.onnx_conv']\n found = []\n for subm in sorted(subfolders):\n if isinstance(subm, list):\n continue # pragma: no cover\n if subfolder is not None and subm != subfolder:\n continue\n\n if subm == 'feature_extraction':\n subs = [subm, 'feature_extraction.text']\n else:\n subs = [subm]\n\n for sub in subs:\n if '.' in sub and sub not in {'feature_extraction.text'}:\n name_sub = sub\n else:\n name_sub = \"{0}.{1}\".format(\"sklearn\", sub)\n try:\n mod = import_module(name_sub)\n except ModuleNotFoundError:\n continue\n\n if hasattr(mod, \"register_converters\"):\n fct = getattr(mod, \"register_converters\")\n cls = fct()\n else:\n cls = getattr(mod, \"__all__\", None)\n if cls is None:\n cls = list(mod.__dict__)\n cls = [mod.__dict__[cl] for cl in cls]\n\n for cl in cls:\n try:\n issub = issubclass(cl, BaseEstimator)\n except TypeError:\n continue\n if cl.__name__ in {'Pipeline', 'ColumnTransformer',\n 'FeatureUnion', 'BaseEstimator',\n 'BaseEnsemble', 'BaseDecisionTree'}:\n continue\n if cl.__name__ in {'CustomScorerTransform'}:\n continue\n if (sub in {'calibration', 'dummy', 'manifold'} and\n 'Calibrated' not in cl.__name__):\n continue\n if issub:\n pack = \"sklearn\" if sub in sklearn__all__ else cl.__module__.split('.')[\n 0]\n found.append(\n dict(name=cl.__name__, subfolder=sub, cl=cl, package=pack))\n\n if extended:\n from ...onnx_conv import register_converters\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\", ResourceWarning)\n models = register_converters(True)\n\n done = set(_['name'] for _ in found)\n for m in models:\n try:\n name = m.__module__.split('.')\n except AttributeError as e: # pragma: no cover\n raise AttributeError(\"Unexpected value, m={}\".format(m)) from e\n sub = '.'.join(name[1:])\n pack = name[0]\n if m.__name__ not in done:\n found.append(\n dict(name=m.__name__, cl=m, package=pack, sub=sub))\n\n # let's remove models which cannot predict\n all_found = found\n found = []\n for mod in all_found:\n cl = mod['cl']\n if hasattr(cl, 'fit_predict') and not hasattr(cl, 'predict'):\n continue\n if hasattr(cl, 'fit_transform') and not hasattr(cl, 'transform'):\n continue\n if (not hasattr(cl, 'transform') and\n not hasattr(cl, 'predict') and\n not hasattr(cl, 'decision_function')):\n continue\n found.append(mod)\n return found\n\n\ndef _measure_time(fct, repeat=1, number=1, first_run=True):\n \"\"\"\n Measures the execution time for a function.\n\n :param fct: function to measure\n :param repeat: number of times to repeat\n :param number: number of times between two measures\n :param first_run: if True, runs the function once before measuring\n :return: last result, average, values\n \"\"\"\n res = None\n values = []\n if first_run:\n fct()\n for __ in range(repeat):\n begin = perf_counter()\n for _ in range(number):\n res = fct()\n end = perf_counter()\n values.append(end - begin)\n if repeat * number == 1:\n return res, values[0], values\n return res, sum(values) / (repeat * number), values # pragma: no cover\n\n\ndef _shape_exc(obj):\n if hasattr(obj, 'shape'):\n return obj.shape\n if isinstance(obj, (list, dict, tuple)):\n return \"[{%d}]\" % len(obj)\n return None\n\n\ndef dump_into_folder(dump_folder, obs_op=None, is_error=True,\n **kwargs):\n \"\"\"\n Dumps information when an error was detected\n using :epkg:`*py:pickle`.\n\n :param dump_folder: dump_folder\n :param obs_op: obs_op (information)\n :param is_error: is it an error or not?\n :param kwargs: additional parameters\n :return: name\n \"\"\"\n if dump_folder is None:\n raise ValueError(\"dump_folder cannot be None.\")\n optim = obs_op.get('optim', '')\n optim = str(optim)\n optim = optim.replace(\"<class 'sklearn.\", \"\")\n optim = optim.replace(\"<class '\", \"\")\n optim = optim.replace(\" \", \"\")\n optim = optim.replace(\">\", \"\")\n optim = optim.replace(\"=\", \"\")\n optim = optim.replace(\"{\", \"\")\n optim = optim.replace(\"}\", \"\")\n optim = optim.replace(\":\", \"\")\n optim = optim.replace(\"'\", \"\")\n optim = optim.replace(\"/\", \"\")\n optim = optim.replace(\"\\\\\", \"\")\n parts = (obs_op['runtime'], obs_op['name'], obs_op['scenario'],\n obs_op['problem'], optim,\n \"op\" + str(obs_op.get('opset', '-')),\n \"nf\" + str(obs_op.get('n_features', '-')))\n name = \"dump-{}-{}.pkl\".format(\n \"ERROR\" if is_error else \"i\",\n \"-\".join(map(str, parts)))\n name = os.path.join(dump_folder, name)\n obs_op = obs_op.copy()\n fcts = [k for k in obs_op if k.startswith('lambda')]\n for fct in fcts:\n del obs_op[fct]\n kwargs.update({'obs_op': obs_op})\n with open(name, \"wb\") as f:\n pickle.dump(kwargs, f)\n return name\n\n\ndef default_time_kwargs():\n \"\"\"\n Returns default values *number* and *repeat* to measure\n the execution of a function.\n\n .. runpython::\n :showcode:\n :warningout: DeprecationWarning\n\n from mlprodict.onnxrt.validate.validate_helper import default_time_kwargs\n import pprint\n pprint.pprint(default_time_kwargs())\n\n keys define the number of rows,\n values defines *number* and *repeat*.\n \"\"\"\n return {\n 1: dict(number=15, repeat=20),\n 10: dict(number=10, repeat=20),\n 100: dict(number=4, repeat=10),\n 1000: dict(number=4, repeat=4),\n 10000: dict(number=2, repeat=2),\n }\n\n\ndef measure_time(stmt, x, repeat=10, number=50, div_by_number=False,\n first_run=True, max_time=None):\n \"\"\"\n Measures a statement and returns the results as a dictionary.\n\n :param stmt: string\n :param x: matrix\n :param repeat: average over *repeat* experiment\n :param number: number of executions in one row\n :param div_by_number: divide by the number of executions\n :param first_run: if True, runs the function once before measuring\n :param max_time: execute the statement until the total goes\n beyond this time (approximatively), *repeat* is ignored,\n *div_by_number* must be set to True\n :return: dictionary\n\n See `Timer.repeat <https://docs.python.org/3/library/timeit.html?timeit.Timer.repeat>`_\n for a better understanding of parameter *repeat* and *number*.\n The function returns a duration corresponding to\n *number* times the execution of the main statement.\n \"\"\"\n if x is None:\n raise ValueError(\"x cannot be None\") # pragma: no cover\n\n def fct():\n stmt(x)\n\n if first_run:\n try:\n fct()\n except RuntimeError as e: # pragma: no cover\n raise RuntimeError(\"{}-{}\".format(type(x), x.dtype)) from e\n\n return _c_measure_time(fct, context={}, repeat=repeat, number=number,\n div_by_number=div_by_number, max_time=max_time)\n\n\ndef _multiply_time_kwargs(time_kwargs, time_kwargs_fact, inst):\n \"\"\"\n Multiplies values in *time_kwargs* following strategy\n *time_kwargs_fact* for a given model *inst*.\n\n :param time_kwargs: see below\n :param time_kwargs_fact: see below\n :param inst: :epkg:`scikit-learn` model\n :return: new *time_kwargs*\n\n Possible values for *time_kwargs_fact*:\n\n - a integer: multiplies *number* by this number\n - `'lin'`: multiplies value *number* for linear models depending\n on the number of rows to process (:math:`\\\\propto 1/\\\\log_{10}(n)`)\n\n .. runpython::\n :showcode:\n :warningout: DeprecationWarning\n\n from pprint import pprint\n from sklearn.linear_model import LinearRegression\n from mlprodict.onnxrt.validate.validate_helper import (\n default_time_kwargs, _multiply_time_kwargs)\n\n lr = LinearRegression()\n kw = default_time_kwargs()\n pprint(kw)\n\n kw2 = _multiply_time_kwargs(kw, 'lin', lr)\n pprint(kw2)\n \"\"\"\n if time_kwargs is None:\n raise ValueError(\"time_kwargs cannot be None.\") # pragma: no cover\n if time_kwargs_fact in ('', None):\n return time_kwargs\n try:\n vi = int(time_kwargs_fact)\n time_kwargs_fact = vi\n except (TypeError, ValueError):\n pass\n if isinstance(time_kwargs_fact, int):\n time_kwargs_modified = copy.deepcopy(time_kwargs)\n for k in time_kwargs_modified:\n time_kwargs_modified[k]['number'] *= time_kwargs_fact\n return time_kwargs_modified\n if time_kwargs_fact == 'lin':\n if isinstance(inst, LinearModel):\n time_kwargs_modified = copy.deepcopy(time_kwargs)\n for k in time_kwargs_modified:\n kl = max(int(math.log(k) / math.log(10) + 1e-5), 1)\n f = max(int(10 / kl + 0.5), 1)\n time_kwargs_modified[k]['number'] *= f\n time_kwargs_modified[k]['repeat'] *= 1\n return time_kwargs_modified\n return time_kwargs\n raise ValueError( # pragma: no cover\n \"Unable to interpret time_kwargs_fact='{}'.\".format(\n time_kwargs_fact))\n\n\ndef _get_problem_data(prob, n_features):\n data_problem = _problems[prob](n_features=n_features)\n if len(data_problem) == 6:\n X_, y_, init_types, method, output_index, Xort_ = data_problem\n dofit = True\n elif len(data_problem) == 7:\n X_, y_, init_types, method, output_index, Xort_, dofit = data_problem\n else:\n raise RuntimeError( # pragma: no cover\n \"Unable to interpret problem '{}'.\".format(prob))\n if (len(X_.shape) == 2 and X_.shape[1] != n_features and\n n_features is not None):\n raise RuntimeError( # pragma: no cover\n \"Problem '{}' with n_features={} returned {} features\"\n \"(func={}).\".format(prob, n_features, X_.shape[1],\n _problems[prob]))\n if y_ is None:\n (X_train, X_test, Xort_train, # pylint: disable=W0612\n Xort_test) = train_test_split(\n X_, Xort_, random_state=42)\n y_train, y_test = None, None\n else:\n (X_train, X_test, y_train, y_test, # pylint: disable=W0612\n Xort_train, Xort_test) = train_test_split(\n X_, y_, Xort_, random_state=42)\n if isinstance(init_types, tuple):\n init_types, conv_options = init_types\n else:\n conv_options = None\n\n if isinstance(method, tuple):\n method_name, predict_kwargs = method\n else:\n method_name = method\n predict_kwargs = {}\n\n return (X_train, X_test, y_train,\n y_test, Xort_test,\n init_types, conv_options, method_name,\n output_index, dofit, predict_kwargs)\n" ]
[ [ "sklearn.utils.testing.ignore_warnings", "pandas.DataFrame" ], [ "numpy.take", "numpy.squeeze", "pandas.DataFrame", "numpy.random.randn", "numpy.arange", "numpy.full", "sklearn.neighbors.KNeighborsClassifier", "sklearn.neighbors.NearestNeighbors", "sklearn.datasets.load_iris", "sklearn.model_selection.train_test_split", "scipy.spatial.distance.cdist", "numpy.argsort", "numpy.array", "numpy.flip", "numpy.sum", "numpy.abs", "numpy.sort", "sklearn.neighbors.KNeighborsRegressor", "sklearn.datasets.make_regression", "sklearn.calibration.CalibratedClassifierCV", "numpy.empty" ], [ "sklearn.neighbors.KNeighborsRegressor", "numpy.array", "sklearn.datasets.load_iris", "sklearn.metrics.make_scorer" ], [ "sklearn.datasets.make_classification", "numpy.abs", "sklearn.model_selection.train_test_split", "pandas.DataFrame", "sklearn.naive_bayes.BernoulliNB", "numpy.array" ], [ "numpy.expand_dims", "numpy.flip", "numpy.argmin" ], [ "sklearn.linear_model.LogisticRegression", "sklearn.datasets.load_iris", "sklearn.model_selection.train_test_split", "sklearn.neighbors.KNeighborsClassifier", "numpy.identity", "sklearn.linear_model.LinearRegression", "numpy.array" ], [ "numpy.abs", "sklearn.metrics.silhouette_score", "sklearn.metrics.mean_absolute_error", "sklearn.datasets.load_iris", "sklearn.model_selection.train_test_split", "sklearn.set_config", "numpy.random.RandomState", "numpy.zeros", "numpy.sum", "sklearn.metrics.accuracy_score" ], [ "numpy.array2string", "sklearn.model_selection.train_test_split" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [ "0.13", "1.6", "0.14", "1.10", "0.15", "1.4", "0.16", "1.9", "0.19", "1.5", "0.18", "1.2", "1.7", "0.12", "1.0", "0.17", "1.3", "1.8" ], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
biolins/frivolous_dnns
[ "23d9a057ac517770cdfe9d8ac71543c328fcf76d" ]
[ "resnet/official/utils/misc/distribution_utils_test.py" ]
[ "# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\" Tests for distribution util functions.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf # pylint: disable=g-bad-import-order\n\nfrom official.utils.misc import distribution_utils\n\n\nclass GetDistributionStrategyTest(tf.test.TestCase):\n \"\"\"Tests for get_distribution_strategy.\"\"\"\n\n def test_one_device_strategy_cpu(self):\n ds = distribution_utils.get_distribution_strategy(num_gpus=0)\n self.assertEquals(ds.num_replicas_in_sync, 1)\n self.assertEquals(len(ds.extended.worker_devices), 1)\n self.assertIn('CPU', ds.extended.worker_devices[0])\n\n def test_one_device_strategy_gpu(self):\n ds = distribution_utils.get_distribution_strategy(num_gpus=1)\n self.assertEquals(ds.num_replicas_in_sync, 1)\n self.assertEquals(len(ds.extended.worker_devices), 1)\n self.assertIn('GPU', ds.extended.worker_devices[0])\n\n def test_mirrored_strategy(self):\n ds = distribution_utils.get_distribution_strategy(num_gpus=5)\n self.assertEquals(ds.num_replicas_in_sync, 5)\n self.assertEquals(len(ds.extended.worker_devices), 5)\n for device in ds.extended.worker_devices:\n self.assertIn('GPU', device)\n\n\nclass PerReplicaBatchSizeTest(tf.test.TestCase):\n \"\"\"Tests for per_replica_batch_size.\"\"\"\n\n def test_batch_size(self):\n self.assertEquals(\n distribution_utils.per_replica_batch_size(147, num_gpus=0), 147)\n self.assertEquals(\n distribution_utils.per_replica_batch_size(147, num_gpus=1), 147)\n self.assertEquals(\n distribution_utils.per_replica_batch_size(147, num_gpus=7), 21)\n\n def test_batch_size_with_remainder(self):\n with self.assertRaises(ValueError):\n distribution_utils.per_replica_batch_size(147, num_gpus=5)\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n" ]
[ [ "tensorflow.test.main" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
manueltonneau/simpletransformers
[ "7374b786857008e023604789e89c1690ad8bde97" ]
[ "simpletransformers/conv_ai/conv_ai_utils.py" ]
[ "# Copyright (c) 2019-present, HuggingFace Inc.\n# All rights reserved. This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree.\nimport json\nimport logging\nimport os\nimport socket\nimport tarfile\nimport tempfile\nfrom datetime import datetime\nfrom multiprocessing import Pool\n\nimport torch\nfrom tqdm.auto import tqdm\nfrom transformers import cached_path\n\nPERSONACHAT_URL = \"https://s3.amazonaws.com/datasets.huggingface.co/personachat/personachat_self_original.json\"\nHF_FINETUNED_MODEL = (\n \"https://s3.amazonaws.com/models.huggingface.co/transfer-learning-chatbot/gpt_personachat_cache.tar.gz\" # noqa\n)\n\nlogger = logging.getLogger(__file__)\n\n\ndef download_pretrained_model():\n \"\"\" Download and extract finetuned model from S3 \"\"\"\n resolved_archive_file = cached_path(HF_FINETUNED_MODEL)\n tempdir = tempfile.mkdtemp()\n logger.info(\"extracting archive file {} to temp dir {}\".format(resolved_archive_file, tempdir))\n with tarfile.open(resolved_archive_file, \"r:gz\") as archive:\n archive.extractall(tempdir)\n return tempdir\n\n\ndef tokenize_multi(data):\n obj, tokenizer = data\n if isinstance(obj, str):\n return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(obj))\n if isinstance(obj, dict):\n return dict((n, tokenize_multi((o, tokenizer))) for n, o in obj.items())\n return list(tokenize_multi((o, tokenizer)) for o in obj)\n\n\ndef get_dataset(\n tokenizer,\n dataset_path,\n dataset_cache,\n process_count,\n proxies,\n evaluate=False,\n interact=False,\n no_cache=False,\n args=None,\n):\n \"\"\" Get tokenized PERSONACHAT dataset from S3 or cache.\"\"\"\n dataset_path = dataset_path or PERSONACHAT_URL\n\n mode = \"eval\" if evaluate else \"train\"\n if interact:\n mode = \"interact\"\n\n dataset_cache = (\n dataset_cache + \"_\" + type(tokenizer).__name__ + \"_\" + mode\n ) # To avoid using GPT cache for GPT-2 and vice-versa\n if dataset_cache and os.path.isfile(dataset_cache) and not no_cache:\n logger.info(\"Load tokenized dataset from cache at %s\", dataset_cache)\n dataset = torch.load(dataset_cache)\n else:\n logger.info(\"Download dataset from %s\", dataset_path)\n personachat_file = cached_path(dataset_path, proxies=proxies)\n with open(personachat_file, \"r\", encoding=\"utf-8\") as f:\n dataset = json.loads(f.read())\n\n logger.info(\"Tokenize and encode the dataset\")\n\n def tokenize(obj):\n if isinstance(obj, str):\n return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(obj))\n if isinstance(obj, dict):\n return dict((n, tokenize(o)) for n, o in obj.items())\n\n data = [(d, tokenizer) for d in obj]\n\n if args.multiprocessing_chunksize == -1:\n chunksize = max(len(data) // (args.process_count * 2), 500)\n else:\n chunksize = args.multiprocessing_chunksize\n\n with Pool(process_count) as p:\n tokenized_data = list(tqdm(p.imap(tokenize_multi, data, chunksize=chunksize), total=len(data)))\n return tokenized_data\n\n if not interact and dataset_path == PERSONACHAT_URL:\n if not evaluate:\n dataset = dataset[\"train\"]\n else:\n dataset = dataset[\"valid\"]\n\n dataset = tokenize(dataset)\n torch.save(dataset, dataset_cache)\n return dataset\n\n\nclass AttrDict(dict):\n def __init__(self, *args, **kwargs):\n super(AttrDict, self).__init__(*args, **kwargs)\n self.__dict__ = self\n" ]
[ [ "torch.save", "torch.load" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
laurentletg/pyradiomics
[ "b30a7fe086417999481bc6792dced4bf3dc3de32" ]
[ "radiomics/imageoperations.py" ]
[ "from __future__ import print_function\n\nimport logging\n\nimport numpy\nimport pywt\nimport SimpleITK as sitk\nimport six\nfrom six.moves import range\n\nlogger = logging.getLogger(__name__)\n\n\ndef getMask(mask, **kwargs):\n \"\"\"\n Function to get the correct mask. Includes enforcing a correct pixel data type (UInt32).\n\n Also supports extracting the mask for a segmentation (stored as SimpleITK Vector image) if necessary.\n In this case, the mask at index ``label_channel`` is extracted. The resulting 3D volume is then treated as it were a\n scalar input volume (i.e. with the region of interest defined by voxels with value matching ``label``).\n\n Finally, checks if the mask volume contains an ROI identified by ``label``. Raises a value error if the label is not\n present (including a list of valid labels found).\n\n :param mask: SimpleITK Image object representing the mask. Can be a vector image to allow for overlapping masks.\n :param kwargs: keyword arguments. If argument ``label_channel`` is present, this is used to select the channel.\n Otherwise label_channel ``0`` is assumed.\n :return: SimpleITK.Image with pixel type UInt32 representing the mask volume\n \"\"\"\n global logger\n label = kwargs.get('label', 1)\n label_channel = kwargs.get('label_channel', 0)\n if 'vector' in mask.GetPixelIDTypeAsString().lower():\n logger.debug('Mask appears to be a segmentation object (=stored as vector image).')\n n_components = mask.GetNumberOfComponentsPerPixel()\n assert label_channel < n_components, \\\n \"Mask %i requested, but segmentation object only contains %i objects\" % (label_channel, n_components)\n\n logger.info('Extracting mask at index %i', label_channel)\n selector = sitk.VectorIndexSelectionCastImageFilter()\n selector.SetIndex(label_channel)\n mask = selector.Execute(mask)\n\n logger.debug('Force casting mask to UInt32 to ensure correct datatype.')\n mask = sitk.Cast(mask, sitk.sitkUInt32)\n\n labels = numpy.unique(sitk.GetArrayFromImage(mask))\n if len(labels) == 1:\n raise ValueError('No labels found in this mask (i.e. nothing is segmented)!')\n if label not in labels:\n raise ValueError('Label (%g) not present in mask. Choose from %s' % (label, labels[labels != 0]))\n\n return mask\n\n\ndef getBinEdges(parameterValues, **kwargs):\n r\"\"\"\n Calculate and return the histogram using parameterValues (1D array of all segmented voxels in the image).\n\n **Fixed bin width:**\n\n Returns the bin edges, a list of the edges of the calculated bins, length is N(bins) + 1. Bins are defined such, that\n the bin edges are equally spaced from zero, and that the leftmost edge :math:`\\leq \\min(X_{gl})`. These bin edges\n represent the half-open ranges of each bin :math:`[\\text{lower_edge}, \\text{upper_edge})` and result in gray value\n discretization as follows:\n\n .. math::\n X_{b, i} = \\lfloor \\frac{X_{gl, i}}{W} \\rfloor - \\lfloor \\frac {\\min(X_{gl})}{W} \\rfloor + 1\n\n Here, :math:`X_{gl, i}` and :math:`X_{b, i}` are gray level intensities before and after discretization, respectively.\n :math:`{W}` is the bin width value (specfied in ``binWidth`` parameter). The first part of the formula ensures that\n the bins are equally spaced from 0, whereas the second part ensures that the minimum gray level intensity inside the\n ROI after binning is always 1.\n\n In the case where the maximum gray level intensity is equally dividable by the binWidth, i.e.\n :math:`\\max(X_{gl}) \\mod W = 0`, this will result in that maximum gray level being assigned to bin\n :math:`[\\max(X_{gl}), \\max(X_{gl}) + W)`, which is consistent with numpy.digitize, but different from the behaviour\n of numpy.histogram, where the final bin has a closed range, including the maximum gray level, i.e.\n :math:`[\\max(X_{gl}) - W, \\max(X_{gl})]`.\n\n .. note::\n This method is slightly different from the fixed bin size discretization method described by IBSI. The two most\n notable differences are 1) that PyRadiomics uses a floor division (and adds 1), as opposed to a ceiling division and\n 2) that in PyRadiomics, bins are always equally spaced from 0, as opposed to equally spaced from the minimum\n gray level intensity.\n\n *Example: for a ROI with values ranging from 54 to 166, and a bin width of 25, the bin edges will be [50, 75, 100,\n 125, 150, 175].*\n\n This value can be directly passed to ``numpy.histogram`` to generate a histogram or ``numpy.digitize`` to discretize\n the ROI gray values. See also :py:func:`binImage()`.\n\n **Fixed bin Count:**\n\n .. math::\n X_{b, i} = \\left\\{ {\\begin{array}{lcl}\n \\lfloor N_b\\frac{(X_{gl, i} - \\min(X_{gl})}{\\max(X_{gl}) - \\min(X_{gl})} \\rfloor + 1 &\n \\mbox{for} & X_{gl, i} < \\max(X_{gl}) \\\\\n N_b & \\mbox{for} & X_{gl, i} = \\max(X_{gl}) \\end{array}} \\right.\n\n Here, :math:`N_b` is the number of bins to use, as defined in ``binCount``.\n\n References\n\n - Leijenaar RTH, Nalbantov G, Carvalho S, et al. The effect of SUV discretization in quantitative FDG-PET Radiomics:\n the need for standardized methodology in tumor texture analysis. Sci Rep. 2015;5(August):11075.\n \"\"\"\n global logger\n binWidth = kwargs.get('binWidth', 25)\n binCount = kwargs.get('binCount')\n\n if binCount is not None:\n binEdges = numpy.histogram(parameterValues, binCount)[1]\n binEdges[-1] += 1 # Ensures that the maximum value is included in the topmost bin when using numpy.digitize\n else:\n minimum = min(parameterValues)\n maximum = max(parameterValues)\n\n # Start binning form the first value lesser than or equal to the minimum value and evenly dividable by binwidth\n lowBound = minimum - (minimum % binWidth)\n # Add + 2* binwidth to ensure the maximum value is included in the range generated by numpy.arange, and that values\n # equal to highbound are binned into a separate bin by numpy.histogram (This ensures ALL bins are half open, as\n # numpy.histogram treats the last bin as a closed interval. Moreover, this ensures consistency with numpy.digitize,\n # which will assign len(bins) + 1 to values equal to rightmost bin edge, treating all bins as half-open)\n highBound = maximum + 2 * binWidth\n\n binEdges = numpy.arange(lowBound, highBound, binWidth)\n\n # if min(parameterValues) % binWidth = 0 and min(parameterValues) = max(parameterValues), binEdges will only contain\n # 1 value. If this is the case (flat region) ensure that numpy.histogram creates 1 bin (requires 2 edges). For\n # numpy.histogram, a binCount (1) would also suffice, however, this is not accepted by numpy.digitize, which also uses\n # binEdges calculated by this function.\n if len(binEdges) == 1: # Flat region, ensure that there is 1 bin\n binEdges = [binEdges[0] - .5, binEdges[0] + .5] # Simulates binEdges returned by numpy.histogram if bins = 1\n\n logger.debug('Calculated %d bins for bin width %g with edges: %s)', len(binEdges) - 1, binWidth, binEdges)\n\n return binEdges # numpy.histogram(parameterValues, bins=binedges)\n\n\ndef binImage(parameterMatrix, parameterMatrixCoordinates=None, **kwargs):\n r\"\"\"\n Discretizes the parameterMatrix (matrix representation of the gray levels in the ROI) using the binEdges calculated\n using :py:func:`getBinEdges`. Only voxels defined by parameterMatrixCoordinates (defining the segmentation) are used\n for calculation of histogram and subsequently discretized. Voxels outside segmentation are left unchanged.\n \"\"\"\n global logger\n logger.debug('Discretizing gray levels inside ROI')\n\n discretizedParameterMatrix = numpy.zeros(parameterMatrix.shape, dtype='int')\n if parameterMatrixCoordinates is None:\n binEdges = getBinEdges(parameterMatrix.flatten(), **kwargs)\n discretizedParameterMatrix = numpy.digitize(parameterMatrix, binEdges)\n else:\n binEdges = getBinEdges(parameterMatrix[parameterMatrixCoordinates], **kwargs)\n discretizedParameterMatrix[parameterMatrixCoordinates] = numpy.digitize(parameterMatrix[parameterMatrixCoordinates], binEdges)\n\n return discretizedParameterMatrix, binEdges\n\n\ndef checkMask(imageNode, maskNode, **kwargs):\n \"\"\"\n Checks whether the Region of Interest (ROI) defined in the mask size and dimensions match constraints, specified in\n settings. The following checks are performed.\n\n 1. Check whether the mask corresponds to the image (i.e. has a similar size, spacing, direction and origin). **N.B.\n This check is performed by SimpleITK, if it fails, an error is logged, with additional error information from\n SimpleITK logged with level DEBUG (i.e. logging-level has to be set to debug to store this information in the log\n file).** The tolerance can be increased using the ``geometryTolerance`` parameter. Alternatively, if the\n ``correctMask`` parameter is ``True``, PyRadiomics will check if the mask contains a valid ROI (inside image\n physical area) and if so, resample the mask to image geometry. See :ref:`radiomics-settings-label` for more info.\n\n 2. Check if the label is present in the mask\n 3. Count the number of dimensions in which the size of the ROI > 1 (i.e. does the ROI represent a single voxel (0), a\n line (1), a surface (2) or a volume (3)) and compare this to the minimum number of dimension required (specified in\n ``minimumROIDimensions``).\n 4. Optional. Check if there are at least N voxels in the ROI. N is defined in ``minimumROISize``, this test is skipped\n if ``minimumROISize = None``.\n\n This function returns a tuple of two items. The first item is the bounding box of the mask. The second item is the\n mask that has been corrected by resampling to the input image geometry (if that resampling was successful).\n\n If a check fails, a ValueError is raised. No features will be extracted for this mask.\n If the mask passes all tests, this function returns the bounding box, which is used in the :py:func:`cropToTumorMask`\n function.\n\n The bounding box is calculated during (1.) and used for the subsequent checks. The bounding box is\n calculated by SimpleITK.LabelStatisticsImageFilter() and returned as a tuple of indices: (L_x, U_x, L_y, U_y, L_z,\n U_z), where 'L' and 'U' are lower and upper bound, respectively, and 'x', 'y' and 'z' the three image dimensions.\n\n By reusing the bounding box calculated here, calls to SimpleITK.LabelStatisticsImageFilter() are reduced, improving\n performance.\n\n Uses the following settings:\n\n - minimumROIDimensions [1]: Integer, range 1-3, specifies the minimum dimensions (1D, 2D or 3D, respectively).\n Single-voxel segmentations are always excluded.\n - minimumROISize [None]: Integer, > 0, specifies the minimum number of voxels required. Test is skipped if\n this parameter is set to None.\n\n .. note::\n\n If the first check fails there are generally 2 possible causes:\n\n 1. The image and mask are matched, but there is a slight difference in origin, direction or spacing. The exact\n cause, difference and used tolerance are stored with level DEBUG in a log (if enabled). For more information on\n setting up logging, see \":ref:`setting up logging <radiomics-logging-label>`\" and the helloRadiomics examples\n (located in the ``pyradiomics/examples`` folder). This problem can be fixed by changing the global tolerance\n (``geometryTolerance`` parameter) or enabling mask correction (``correctMask`` parameter).\n 2. The image and mask do not match, but the ROI contained within the mask does represent a physical volume\n contained within the image. If this is the case, resampling is needed to ensure matching geometry between image\n and mask before features can be extracted. This can be achieved by enabling mask correction using the\n ``correctMask`` parameter.\n \"\"\"\n global logger\n\n correctedMask = None\n\n label = kwargs.get('label', 1)\n minDims = kwargs.get('minimumROIDimensions', 2)\n minSize = kwargs.get('minimumROISize', None)\n\n logger.debug('Checking mask with label %d', label)\n logger.debug('Calculating bounding box')\n # Determine bounds\n lsif = sitk.LabelStatisticsImageFilter()\n try:\n lsif.Execute(imageNode, maskNode)\n\n # If lsif fails, and mask is corrected, it includes a check whether the label is present. Therefore, perform\n # this test here only if lsif does not fail on the first attempt.\n if label not in lsif.GetLabels():\n raise ValueError('Label (%g) not present in mask' % label)\n except RuntimeError as e:\n # If correctMask = True, try to resample the mask to the image geometry, otherwise return None (\"fail\")\n if not kwargs.get('correctMask', False):\n if \"Both images for LabelStatisticsImageFilter don't match type or dimension!\" in e.args[0]:\n logger.debug('Additional information on error.', exc_info=True)\n raise ValueError('Image/Mask datatype or size mismatch. Potential fix: enable correctMask, see '\n 'Documentation:Usage:Customizing the Extraction:Settings:correctMask for more information')\n elif \"Inputs do not occupy the same physical space!\" in e.args[0]:\n logger.debug('Additional information on error.', exc_info=True)\n raise ValueError('Image/Mask geometry mismatch. Potential fix: increase tolerance using geometryTolerance, '\n 'see Documentation:Usage:Customizing the Extraction:Settings:geometryTolerance for more '\n 'information')\n else:\n raise e # unhandled error\n\n logger.warning('Image/Mask geometry mismatch, attempting to correct Mask')\n\n correctedMask = _correctMask(imageNode, maskNode, **kwargs) # Raises Value error if ROI outside image physical space\n\n # Resampling successful, try to calculate boundingbox\n try:\n lsif.Execute(imageNode, correctedMask)\n except RuntimeError:\n logger.debug('Bounding box calculation with resampled mask failed', exc_info=True)\n raise ValueError('Calculation of bounding box failed, for more information run with DEBUG logging and check log')\n\n # LBound and UBound of the bounding box, as (L_X, U_X, L_Y, U_Y, L_Z, U_Z)\n boundingBox = numpy.array(lsif.GetBoundingBox(label))\n\n logger.debug('Checking minimum number of dimensions requirements (%d)', minDims)\n ndims = numpy.sum((boundingBox[1::2] - boundingBox[0::2] + 1) > 1) # UBound - LBound + 1 = Size\n if ndims == 0:\n raise ValueError('mask only contains 1 segmented voxel! Cannot extract features for a single voxel.')\n elif ndims < minDims:\n raise ValueError('mask has too few dimensions (number of dimensions %d, minimum required %d)' % (ndims, minDims))\n\n if minSize is not None:\n logger.debug('Checking minimum size requirements (minimum size: %d)', minSize)\n roiSize = lsif.GetCount(label)\n if roiSize <= minSize:\n raise ValueError('Size of the ROI is too small (minimum size: %g, ROI size: %g' % (minSize, roiSize))\n\n return boundingBox, correctedMask\n\n\ndef _correctMask(imageNode, maskNode, **kwargs):\n \"\"\"\n If the mask geometry does not match the image geometry, this function can be used to resample the mask to the image\n physical space.\n\n First, the mask is checked for a valid ROI (i.e. maskNode contains an ROI with the given label value, which does not\n include areas outside of the physical image bounds).\n\n If the ROI is valid, the maskNode is resampled using the imageNode as a reference image and a nearest neighbor\n interpolation.\n\n If the ROI is valid, the resampled mask is returned, otherwise ``None`` is returned.\n \"\"\"\n global logger\n logger.debug('Resampling mask to image geometry')\n\n _checkROI(imageNode, maskNode, **kwargs) # Raises a value error if ROI is invalid\n\n rif = sitk.ResampleImageFilter()\n rif.SetReferenceImage(imageNode)\n rif.SetInterpolator(sitk.sitkNearestNeighbor)\n\n logger.debug('Resampling...')\n\n return rif.Execute(maskNode)\n\n\ndef _checkROI(imageNode, maskNode, **kwargs):\n \"\"\"\n Check whether maskNode contains a valid ROI defined by label:\n\n 1. Check whether the label value is present in the maskNode.\n 2. Check whether the ROI defined by the label does not include an area outside the physical area of the image.\n\n For the second check, a tolerance of 1e-3 is allowed.\n\n If the ROI is valid, the bounding box (lower bounds, followd by size in all dimensions (X, Y, Z ordered)) is\n returned. Otherwise, a ValueError is raised.\n \"\"\"\n global logger\n label = kwargs.get('label', 1)\n\n logger.debug('Checking ROI validity')\n\n # Determine bounds of cropped volume in terms of original Index coordinate space\n lssif = sitk.LabelShapeStatisticsImageFilter()\n lssif.Execute(maskNode)\n\n logger.debug('Checking if label %d is persent in the mask', label)\n if label not in lssif.GetLabels():\n raise ValueError('Label (%d) not present in mask', label)\n\n # LBound and size of the bounding box, as (L_X, L_Y, [L_Z], S_X, S_Y, [S_Z])\n bb = numpy.array(lssif.GetBoundingBox(label))\n Nd = maskNode.GetDimension()\n\n # Determine if the ROI is within the physical space of the image\n\n logger.debug('Comparing physical space of bounding box to physical space of image')\n # Step 1: Get the origin and UBound corners of the bounding box in physical space\n # The additional 0.5 represents the difference between the voxel center and the voxel corner\n # Upper bound index of ROI = bb[:Nd] + bb[Nd:] - 1 (LBound + Size - 1), .5 is added to get corner\n ROIBounds = (maskNode.TransformContinuousIndexToPhysicalPoint(bb[:Nd] - .5), # Origin\n maskNode.TransformContinuousIndexToPhysicalPoint(bb[:Nd] + bb[Nd:] - 0.5)) # UBound\n # Step 2: Translate the ROI physical bounds to the image coordinate space\n ROIBounds = (imageNode.TransformPhysicalPointToContinuousIndex(ROIBounds[0]), # Origin\n imageNode.TransformPhysicalPointToContinuousIndex(ROIBounds[1]))\n\n logger.debug('ROI bounds (image coordinate space): %s', ROIBounds)\n\n # Check if any of the ROI bounds are outside the image indices (i.e. -0.5 < ROI < Im.Size -0.5)\n # The additional 0.5 is to allow for different spacings (defines the edges, not the centers of the edge-voxels\n tolerance = 1e-3 # Define a tolerance to correct for machine precision errors\n if numpy.any(numpy.min(ROIBounds, axis=0) < (- .5 - tolerance)) or \\\n numpy.any(numpy.max(ROIBounds, axis=0) > (numpy.array(imageNode.GetSize()) - .5 + tolerance)):\n raise ValueError('Bounding box of ROI is larger than image space:\\n\\t'\n 'ROI bounds (x, y, z image coordinate space) %s\\n\\tImage Size %s' %\n (ROIBounds, imageNode.GetSize()))\n\n logger.debug('ROI valid, calculating resampling grid')\n\n return bb\n\n\ndef cropToTumorMask(imageNode, maskNode, boundingBox, **kwargs):\n \"\"\"\n Create a sitkImage of the segmented region of the image based on the input label.\n\n Create a sitkImage of the labelled region of the image, cropped to have a\n cuboid shape equal to the ijk boundaries of the label.\n\n :param boundingBox: The bounding box used to crop the image. This is the bounding box as returned by\n :py:func:`checkMask`.\n :param label: [1], value of the label, onto which the image and mask must be cropped.\n :return: Cropped image and mask (SimpleITK image instances).\n\n \"\"\"\n global logger\n padDistance = kwargs.get('padDistance', 0)\n\n size = numpy.array(maskNode.GetSize())\n\n ijkMinBounds = boundingBox[0::2] - padDistance\n ijkMaxBounds = size - boundingBox[1::2] - padDistance - 1\n\n # Ensure cropped area is not outside original image bounds\n ijkMinBounds = numpy.maximum(ijkMinBounds, 0)\n ijkMaxBounds = numpy.maximum(ijkMaxBounds, 0)\n\n # Crop Image\n logger.debug('Cropping to size %s', (boundingBox[1::2] - boundingBox[0::2]) + 1)\n cif = sitk.CropImageFilter()\n try:\n cif.SetLowerBoundaryCropSize(ijkMinBounds)\n cif.SetUpperBoundaryCropSize(ijkMaxBounds)\n except TypeError:\n # newer versions of SITK/python want a tuple or list\n cif.SetLowerBoundaryCropSize(ijkMinBounds.tolist())\n cif.SetUpperBoundaryCropSize(ijkMaxBounds.tolist())\n croppedImageNode = cif.Execute(imageNode)\n croppedMaskNode = cif.Execute(maskNode)\n\n return croppedImageNode, croppedMaskNode\n\n\ndef resampleImage(imageNode, maskNode, **kwargs):\n \"\"\"\n Resamples image and mask to the specified pixel spacing (The default interpolator is Bspline).\n\n Resampling can be enabled using the settings 'interpolator' and 'resampledPixelSpacing' in the parameter file or as\n part of the settings passed to the feature extractor. See also\n :ref:`feature extractor <radiomics-featureextractor-label>`.\n\n 'imageNode' and 'maskNode' are SimpleITK Objects, and 'resampledPixelSpacing' is the output pixel spacing (sequence of\n 3 elements).\n\n If only in-plane resampling is required, set the output pixel spacing for the out-of-plane dimension (usually the last\n dimension) to 0. Spacings with a value of 0 are replaced by the spacing as it is in the original mask.\n\n Only part of the image and labelmap are resampled. The resampling grid is aligned to the input origin, but only voxels\n covering the area of the image ROI (defined by the bounding box) and the padDistance are resampled. This results in a\n resampled and partially cropped image and mask. Additional padding is required as some filters also sample voxels\n outside of segmentation boundaries. For feature calculation, image and mask are cropped to the bounding box without\n any additional padding, as the feature classes do not need the gray level values outside the segmentation.\n\n The resampling grid is calculated using only the input mask. Even when image and mask have different directions, both\n the cropped image and mask will have the same direction (equal to direction of the mask). Spacing and size are\n determined by settings and bounding box of the ROI.\n\n .. note::\n Before resampling the bounds of the non-padded ROI are compared to the bounds. If the ROI bounding box includes\n areas outside of the physical space of the image, an error is logged and (None, None) is returned. No features will\n be extracted. This enables the input image and mask to have different geometry, so long as the ROI defines an area\n within the image.\n\n .. note::\n The additional padding is adjusted, so that only the physical space within the mask is resampled. This is done to\n prevent resampling outside of the image. Please note that this assumes the image and mask to image the same physical\n space. If this is not the case, it is possible that voxels outside the image are included in the resampling grid,\n these will be assigned a value of 0. It is therefore recommended, but not enforced, to use an input mask which has\n the same or a smaller physical space than the image.\n \"\"\"\n global logger\n resampledPixelSpacing = kwargs['resampledPixelSpacing']\n interpolator = kwargs.get('interpolator', sitk.sitkBSpline)\n padDistance = kwargs.get('padDistance', 5)\n label = kwargs.get('label', 1)\n\n logger.debug('Resampling image and mask')\n\n if imageNode is None or maskNode is None:\n raise ValueError('Requires both image and mask to resample')\n\n maskSpacing = numpy.array(maskNode.GetSpacing())\n imageSpacing = numpy.array(imageNode.GetSpacing())\n\n Nd_resampled = len(resampledPixelSpacing)\n Nd_mask = len(maskSpacing)\n assert Nd_resampled == Nd_mask, \\\n 'Wrong dimensionality (%i-D) of resampledPixelSpacing!, %i-D required' % (Nd_resampled, Nd_mask)\n\n # If spacing for a direction is set to 0, use the original spacing (enables \"only in-slice\" resampling)\n logger.debug('Where resampled spacing is set to 0, set it to the original spacing (mask)')\n resampledPixelSpacing = numpy.array(resampledPixelSpacing)\n resampledPixelSpacing = numpy.where(resampledPixelSpacing == 0, maskSpacing, resampledPixelSpacing)\n\n # Check if the maskNode contains a valid ROI. If ROI is valid, the bounding box needed to calculate the resampling\n # grid is returned.\n bb = _checkROI(imageNode, maskNode, **kwargs)\n\n # Do not resample in those directions where labelmap spans only one slice.\n maskSize = numpy.array(maskNode.GetSize())\n resampledPixelSpacing = numpy.where(bb[Nd_mask:] != 1, resampledPixelSpacing, maskSpacing)\n\n # If current spacing is equal to resampledPixelSpacing, no interpolation is needed\n # Tolerance = 1e-5 + 1e-8*abs(resampledSpacing)\n logger.debug('Comparing resampled spacing to original spacing (image')\n if numpy.allclose(imageSpacing, resampledPixelSpacing):\n logger.info('New spacing equal to original image spacing, just resampling the mask')\n\n # Ensure that image and mask geometry match\n rif = sitk.ResampleImageFilter()\n rif.SetReferenceImage(imageNode)\n rif.SetInterpolator(sitk.sitkNearestNeighbor)\n maskNode = rif.Execute(maskNode)\n\n # re-calculate the bounding box of the mask\n lssif = sitk.LabelShapeStatisticsImageFilter()\n lssif.Execute(maskNode)\n bb = numpy.array(lssif.GetBoundingBox(label))\n\n low_up_bb = numpy.empty(Nd_mask * 2, dtype=int)\n low_up_bb[::2] = bb[:3]\n low_up_bb[1::2] = bb[:3] + bb[3:] - 1\n return cropToTumorMask(imageNode, maskNode, low_up_bb, **kwargs)\n\n spacingRatio = maskSpacing / resampledPixelSpacing\n\n # Determine bounds of cropped volume in terms of new Index coordinate space,\n # round down for lowerbound and up for upperbound to ensure entire segmentation is captured (prevent data loss)\n # Pad with an extra .5 to prevent data loss in case of upsampling. For Ubound this is (-1 + 0.5 = -0.5)\n bbNewLBound = numpy.floor((bb[:Nd_mask] - 0.5) * spacingRatio - padDistance)\n bbNewUBound = numpy.ceil((bb[:Nd_mask] + bb[Nd_mask:] - 0.5) * spacingRatio + padDistance)\n\n # Ensure resampling is not performed outside bounds of original image\n maxUbound = numpy.ceil(maskSize * spacingRatio) - 1\n bbNewLBound = numpy.where(bbNewLBound < 0, 0, bbNewLBound)\n bbNewUBound = numpy.where(bbNewUBound > maxUbound, maxUbound, bbNewUBound)\n\n # Calculate the new size. Cast to int to prevent error in sitk.\n newSize = numpy.array(bbNewUBound - bbNewLBound + 1, dtype='int').tolist()\n\n # Determine continuous index of bbNewLBound in terms of the original Index coordinate space\n bbOriginalLBound = bbNewLBound / spacingRatio\n\n # Origin is located in center of first voxel, e.g. 1/2 of the spacing\n # from Corner, which corresponds to 0 in the original Index coordinate space.\n # The new spacing will be in 0 the new Index coordinate space. Here we use continuous\n # index to calculate where the new 0 of the new Index coordinate space (of the original volume\n # in terms of the original spacing, and add the minimum bounds of the cropped area to\n # get the new Index coordinate space of the cropped volume in terms of the original Index coordinate space.\n # Then use the ITK functionality to bring the continuous index into the physical space (mm)\n newOriginIndex = numpy.array(.5 * (resampledPixelSpacing - maskSpacing) / maskSpacing)\n newCroppedOriginIndex = newOriginIndex + bbOriginalLBound\n newOrigin = maskNode.TransformContinuousIndexToPhysicalPoint(newCroppedOriginIndex)\n\n imagePixelType = imageNode.GetPixelID()\n maskPixelType = maskNode.GetPixelID()\n\n direction = numpy.array(maskNode.GetDirection())\n\n logger.info('Applying resampling from spacing %s and size %s to spacing %s and size %s',\n maskSpacing, maskSize, resampledPixelSpacing, newSize)\n\n try:\n if isinstance(interpolator, six.string_types):\n interpolator = getattr(sitk, interpolator)\n except Exception:\n logger.warning('interpolator \"%s\" not recognized, using sitkBSpline', interpolator)\n interpolator = sitk.sitkBSpline\n\n rif = sitk.ResampleImageFilter()\n\n rif.SetOutputSpacing(resampledPixelSpacing)\n rif.SetOutputDirection(direction)\n rif.SetSize(newSize)\n rif.SetOutputOrigin(newOrigin)\n\n logger.debug('Resampling image')\n rif.SetOutputPixelType(imagePixelType)\n rif.SetInterpolator(interpolator)\n resampledImageNode = rif.Execute(imageNode)\n\n logger.debug('Resampling mask')\n rif.SetOutputPixelType(maskPixelType)\n rif.SetInterpolator(sitk.sitkNearestNeighbor)\n resampledMaskNode = rif.Execute(maskNode)\n\n return resampledImageNode, resampledMaskNode\n\n\ndef normalizeImage(image, **kwargs):\n r\"\"\"\n Normalizes the image by centering it at the mean with standard deviation. Normalization is based on all gray values in\n the image, not just those inside the segementation.\n\n :math:`f(x) = \\frac{s(x - \\mu_x)}{\\sigma_x}`\n\n Where:\n\n - :math:`x` and :math:`f(x)` are the original and normalized intensity, respectively.\n - :math:`\\mu_x` and :math:`\\sigma_x` are the mean and standard deviation of the image instensity values.\n - :math:`s` is an optional scaling defined by ``scale``. By default, it is set to 1.\n\n Optionally, outliers can be removed, in which case values for which :math:`x > \\mu_x + n\\sigma_x` or\n :math:`x < \\mu_x - n\\sigma_x` are set to :math:`\\mu_x + n\\sigma_x` and :math:`\\mu_x - n\\sigma_x`, respectively.\n Here, :math:`n>0` and defined by ``outliers``. This, in turn, is controlled by the ``removeOutliers`` parameter.\n Removal of outliers is done after the values of the image are normalized, but before ``scale`` is applied.\n \"\"\"\n global logger\n scale = kwargs.get('normalizeScale', 1)\n outliers = kwargs.get('removeOutliers')\n\n logger.debug('Normalizing image with scale %d', scale)\n image = sitk.Normalize(image)\n\n if outliers is not None:\n logger.debug('Removing outliers > %g standard deviations', outliers)\n imageArr = sitk.GetArrayFromImage(image)\n\n imageArr[imageArr > outliers] = outliers\n imageArr[imageArr < -outliers] = -outliers\n\n newImage = sitk.GetImageFromArray(imageArr)\n newImage.CopyInformation(image)\n image = newImage\n\n image *= scale\n\n return image\n\n\ndef resegmentMask(imageNode, maskNode, **kwargs):\n r\"\"\"\n Resegment the Mask based on the range specified by the threshold(s) in ``resegmentRange``. Either 1 or 2 thresholds\n can be defined. In case of 1 threshold, all values equal to or higher than that threshold are included. If there are\n 2 thresholds, all voxels with a value inside the closed-range defined by these thresholds is included\n (i.e. a voxels is included if :math:`T_{lower} \\leq X_gl \\leq T_{upper}`).\n The resegmented mask is therefore always equal or smaller in size than the original mask.\n In the case where either resegmentRange or resegmentMode contains illigal values, a ValueError is raised.\n\n There are 3 modes for defining the threshold:\n\n 1. absolute (default): The values in resegmentRange define as absolute values (i.e. corresponding to the gray values\n in the image\n 2. relative: The values in resegmentRange define the threshold as relative to the maximum value found in the ROI.\n (e.g. 0.5 indicates a threshold at 50% of maximum gray value)\n 3. sigma: The threshold is defined as the number of sigma from the mean. (e.g. resegmentRange [-3, 3] will include\n all voxels that have a value that differs 3 or less standard deviations from the mean).\n\n \"\"\"\n global logger\n resegmentRange = kwargs['resegmentRange']\n resegmentMode = kwargs.get('resegmentMode', 'absolute')\n label = kwargs.get('label', 1)\n\n if resegmentRange is None:\n raise ValueError('resegmentRange is None.')\n if len(resegmentRange) == 0 or len(resegmentRange) > 2:\n raise ValueError('Length %i is not allowed for resegmentRange' % len(resegmentRange))\n\n logger.debug('Resegmenting mask (range %s, mode %s)', resegmentRange, resegmentMode)\n\n im_arr = sitk.GetArrayFromImage(imageNode)\n ma_arr = (sitk.GetArrayFromImage(maskNode) == label) # boolean array\n\n oldSize = numpy.sum(ma_arr)\n\n if resegmentMode == 'absolute':\n logger.debug('Resegmenting in absolute mode')\n thresholds = sorted(resegmentRange)\n elif resegmentMode == 'relative':\n max_gl = numpy.max(im_arr[ma_arr])\n logger.debug('Resegmenting in relative mode, max %g', max_gl)\n thresholds = [max_gl * th for th in sorted(resegmentRange)]\n elif resegmentMode == 'sigma':\n mean_gl = numpy.mean(im_arr[ma_arr])\n sd_gl = numpy.std(im_arr[ma_arr])\n logger.debug('Resegmenting in sigma mode, mean %g, std %g', mean_gl, sd_gl)\n thresholds = [mean_gl + sd_gl * th for th in sorted(resegmentRange)]\n else:\n raise ValueError('Resegment mode %s not recognized.' % resegmentMode)\n\n # Apply lower threshold\n logger.debug('Applying lower threshold (%g)', thresholds[0])\n ma_arr[ma_arr] = im_arr[ma_arr] >= thresholds[0]\n\n # If 2 thresholds are defined, also apply an upper threshold\n if len(thresholds) == 2:\n logger.debug('Applying upper threshold (%g)', thresholds[1])\n ma_arr[ma_arr] = im_arr[ma_arr] <= thresholds[1]\n\n roiSize = numpy.sum(ma_arr)\n\n if roiSize <= 1:\n raise ValueError(\"Resegmentation excluded too many voxels with label %i (retained %i voxel(s))! \"\n \"Cannot extract features\" % (label, roiSize))\n\n # Transform the boolean array back to an image with the correct voxels set to the label value\n newMask_arr = numpy.zeros(ma_arr.shape, dtype='int')\n newMask_arr[ma_arr] = label\n\n newMask = sitk.GetImageFromArray(newMask_arr)\n newMask.CopyInformation(maskNode)\n logger.debug('Resegmentation complete, new size: %d voxels (excluded %d voxels)', roiSize, oldSize - roiSize)\n\n return newMask\n\n\ndef getOriginalImage(inputImage, inputMask, **kwargs):\n \"\"\"\n This function does not apply any filter, but returns the original image. This function is needed to\n dynamically expose the original image as a valid image type.\n\n :return: Yields original image, 'original' and ``kwargs``\n \"\"\"\n global logger\n logger.debug('Yielding original image')\n yield inputImage, 'original', kwargs\n\n\ndef getLoGImage(inputImage, inputMask, **kwargs):\n r\"\"\"\n Applies a Laplacian of Gaussian filter to the input image and yields a derived image for each sigma value specified.\n\n A Laplacian of Gaussian image is obtained by convolving the image with the second derivative (Laplacian) of a Gaussian\n kernel.\n\n The Gaussian kernel is used to smooth the image and is defined as\n\n .. math::\n\n G(x, y, z, \\sigma) = \\frac{1}{(\\sigma \\sqrt{2 \\pi})^3}e^{-\\frac{x^2 + y^2 + z^2}{2\\sigma^2}}\n\n The Gaussian kernel is convolved by the laplacian kernel :math:`\\nabla^2G(x, y, z)`, which is sensitive to areas with\n rapidly changing intensities, enhancing edges. The width of the filter in the Gaussian kernel is determined by\n :math:`\\sigma` and can be used to emphasize more fine (low :math:`\\sigma` values) or coarse (high :math:`\\sigma`\n values) textures.\n\n .. warning::\n\n The LoG filter implemented in PyRadiomics is a 3D LoG filter, and therefore requires 3D input. Features using a\n single slice (2D) segmentation can still be extracted, but the input image *must* be a 3D image, with a minimum size\n in all dimensions :math:`\\geq \\sigma`. If input image is too small, a warning is logged and :math:`\\sigma` value is\n skipped. Moreover, the image size *must* be at least 4 voxels in each dimensions, if this constraint is not met, no\n LoG derived images can be generated.\n\n Following settings are possible:\n\n - sigma: List of floats or integers, must be greater than 0. Filter width (mm) to use for the Gaussian kernel\n (determines coarseness).\n\n .. warning::\n Setting for sigma must be provided. If omitted, no LoG image features are calculated and the function\n will return an empty dictionary.\n\n Returned filter name reflects LoG settings:\n log-sigma-<sigmaValue>-3D.\n\n References:\n\n - `SimpleITK Doxygen documentation\n <https://itk.org/SimpleITKDoxygen/html/classitk_1_1simple_1_1LaplacianRecursiveGaussianImageFilter.html>`_\n - `ITK Doxygen documentation <https://itk.org/Doxygen/html/classitk_1_1LaplacianRecursiveGaussianImageFilter.html>`_\n - `<https://en.wikipedia.org/wiki/Blob_detection#The_Laplacian_of_Gaussian>`_\n\n :return: Yields log filtered image for each specified sigma, corresponding image type name and ``kwargs`` (customized\n settings).\n \"\"\"\n global logger\n\n logger.debug('Generating LoG images')\n\n # Check if size of image is > 4 in all 3D directions (otherwise, LoG filter will fail)\n size = numpy.array(inputImage.GetSize())\n spacing = numpy.array(inputImage.GetSpacing())\n\n if numpy.min(size) < 4:\n logger.warning('Image too small to apply LoG filter, size: %s', size)\n return\n\n sigmaValues = kwargs.get('sigma', [])\n\n for sigma in sigmaValues:\n logger.info('Computing LoG with sigma %g', sigma)\n\n if sigma > 0.0:\n if numpy.all(size >= numpy.ceil(sigma / spacing) + 1):\n lrgif = sitk.LaplacianRecursiveGaussianImageFilter()\n lrgif.SetNormalizeAcrossScale(True)\n lrgif.SetSigma(sigma)\n inputImageName = 'log-sigma-%s-mm-3D' % (str(sigma).replace('.', '-'))\n logger.debug('Yielding %s image', inputImageName)\n yield lrgif.Execute(inputImage), inputImageName, kwargs\n else:\n logger.warning('applyLoG: sigma(%g)/spacing(%s) + 1 must be greater than the size(%s) of the inputImage',\n sigma,\n spacing,\n size)\n else:\n logger.warning('applyLoG: sigma must be greater than 0.0: %g', sigma)\n\n\ndef getWaveletImage(inputImage, inputMask, **kwargs):\n \"\"\"\n Applies wavelet filter to the input image and yields the decompositions and the approximation.\n\n Following settings are possible:\n\n - start_level [0]: integer, 0 based level of wavelet which should be used as first set of decompositions\n from which a signature is calculated\n - level [1]: integer, number of levels of wavelet decompositions from which a signature is calculated.\n - wavelet [\"coif1\"]: string, type of wavelet decomposition. Enumerated value, validated against possible values\n present in the ``pyWavelet.wavelist()``. Current possible values (pywavelet version 0.4.0) (where an\n aditional number is needed, range of values is indicated in []):\n\n - haar\n - dmey\n - sym[2-20]\n - db[1-20]\n - coif[1-5]\n - bior[1.1, 1.3, 1.5, 2.2, 2.4, 2.6, 2.8, 3.1, 3.3, 3.5, 3.7, 3.9, 4.4, 5.5, 6.8]\n - rbio[1.1, 1.3, 1.5, 2.2, 2.4, 2.6, 2.8, 3.1, 3.3, 3.5, 3.7, 3.9, 4.4, 5.5, 6.8]\n\n Returned filter name reflects wavelet type:\n wavelet[level]-<decompositionName>\n\n N.B. only levels greater than the first level are entered into the name.\n\n :return: Yields each wavelet decomposition and final approximation, corresponding imaget type name and ``kwargs``\n (customized settings).\n \"\"\"\n global logger\n\n logger.debug('Generating Wavelet images')\n\n Nd = inputImage.GetDimension()\n axes = list(range(Nd - 1, -1, -1))\n if kwargs.get('force2D', False):\n axes.remove(kwargs.get('force2Ddimension', 0))\n\n approx, ret = _swt3(inputImage, tuple(axes), **kwargs)\n\n for idx, wl in enumerate(ret, start=1):\n for decompositionName, decompositionImage in wl.items():\n logger.info('Computing Wavelet %s', decompositionName)\n\n if idx == 1:\n inputImageName = 'wavelet-%s' % (decompositionName)\n else:\n inputImageName = 'wavelet%s-%s' % (idx, decompositionName)\n logger.debug('Yielding %s image', inputImageName)\n yield decompositionImage, inputImageName, kwargs\n\n if len(ret) == 1:\n inputImageName = 'wavelet-%s' % ('L' * len(axes))\n else:\n inputImageName = 'wavelet%s-%s' % (len(ret), ('L' * len(axes)))\n logger.debug('Yielding approximation (%s) image', inputImageName)\n yield approx, inputImageName, kwargs\n\n\ndef _swt3(inputImage, axes, **kwargs): # Stationary Wavelet Transform 3D\n wavelet = kwargs.get('wavelet', 'coif1')\n level = kwargs.get('level', 1)\n start_level = kwargs.get('start_level', 0)\n\n matrix = sitk.GetArrayFromImage(inputImage) # This function gets a numpy array from the SimpleITK Image \"inputImage\"\n matrix = numpy.asarray(matrix) # The function np.asarray converts \"matrix\" (which could be also a tuple) into an array.\n\n original_shape = matrix.shape\n # original_shape becomes a tuple (?,?,?) containing the number of rows, columns, and slices of the image\n # this is of course dependent on the number of dimensions, but the same principle holds\n padding = tuple([(0, 1 if dim % 2 != 0 else 0) for dim in original_shape])\n # padding is necessary because of pywt.swtn (see function Notes)\n data = matrix.copy() # creates a modifiable copy of \"matrix\" and we call it \"data\"\n data = numpy.pad(data, padding, 'wrap') # padding the tuple \"padding\" previously computed\n\n if not isinstance(wavelet, pywt.Wavelet):\n wavelet = pywt.Wavelet(wavelet)\n\n for i in range(0, start_level): # if start_level = 0 (default) this for loop never gets executed\n # compute all decompositions and saves them in \"dec\" dict\n dec = pywt.swtn(data, wavelet, level=1, start_level=0, axes=axes)[0]\n # copies in \"data\" just the \"aaa\" decomposition (i.e. approximation; No of consecutive 'a's = len(axes))\n data = dec['a' * len(axes)].copy()\n\n ret = [] # initialize empty list\n for i in range(start_level, start_level + level):\n # compute the n-dimensional stationary wavelet transform\n dec = pywt.swtn(data, wavelet, level=1, start_level=0, axes=axes)[0]\n # Copy the approximation into data (approximation in output / input for next levels)\n data = dec['a' * len(axes)].copy()\n\n dec_im = {} # initialize empty dict\n for decName, decImage in six.iteritems(dec):\n # Returning the approximiation is done only for the last loop,\n # and is handled separately below (by building it from `data`)\n # There for, skip it here\n if decName == 'a' * len(axes):\n continue\n decTemp = decImage.copy()\n decTemp = decTemp[tuple(slice(None, -1 if dim % 2 != 0 else None) for dim in original_shape)]\n sitkImage = sitk.GetImageFromArray(decTemp)\n sitkImage.CopyInformation(inputImage)\n dec_im[str(decName).replace('a', 'L').replace('d', 'H')] = sitkImage\n # modifies 'a' with 'L' (Low-pass filter) and 'd' with 'H' (High-pass filter)\n\n ret.append(dec_im) # appending all the filtered sitk images (stored in \"dec_im\") to the \"ret\" list\n\n data = data[tuple(slice(None, -1 if dim % 2 != 0 else None) for dim in original_shape)]\n approximation = sitk.GetImageFromArray(data)\n approximation.CopyInformation(inputImage)\n\n return approximation, ret # returns the approximation and the detail (ret) coefficients of the stationary wavelet decomposition\n\n\ndef getSquareImage(inputImage, inputMask, **kwargs):\n r\"\"\"\n Computes the square of the image intensities.\n\n Resulting values are rescaled on the range of the initial original image and negative intensities are made\n negative in resultant filtered image.\n\n :math:`f(x) = (cx)^2,\\text{ where } c=\\displaystyle\\frac{1}{\\sqrt{\\max(|x|)}}`\n\n Where :math:`x` and :math:`f(x)` are the original and filtered intensity, respectively.\n\n :return: Yields square filtered image, 'square' and ``kwargs`` (customized settings).\n \"\"\"\n global logger\n\n im = sitk.GetArrayFromImage(inputImage)\n im = im.astype('float64')\n coeff = 1 / numpy.sqrt(numpy.max(numpy.abs(im)))\n im = (coeff * im) ** 2\n im = sitk.GetImageFromArray(im)\n im.CopyInformation(inputImage)\n\n logger.debug('Yielding square image')\n yield im, 'square', kwargs\n\n\ndef getSquareRootImage(inputImage, inputMask, **kwargs):\n r\"\"\"\n Computes the square root of the absolute value of image intensities.\n\n Resulting values are rescaled on the range of the initial original image and negative intensities are made\n negative in resultant filtered image.\n\n :math:`f(x) = \\left\\{ {\\begin{array}{lcl}\n \\sqrt{cx} & \\mbox{for} & x \\ge 0 \\\\\n -\\sqrt{-cx} & \\mbox{for} & x < 0\\end{array}} \\right.,\\text{ where } c=\\max(|x|)`\n\n Where :math:`x` and :math:`f(x)` are the original and filtered intensity, respectively.\n\n :return: Yields square root filtered image, 'squareroot' and ``kwargs`` (customized settings).\n \"\"\"\n global logger\n\n im = sitk.GetArrayFromImage(inputImage)\n im = im.astype('float64')\n coeff = numpy.max(numpy.abs(im))\n im[im > 0] = numpy.sqrt(im[im > 0] * coeff)\n im[im < 0] = - numpy.sqrt(-im[im < 0] * coeff)\n im = sitk.GetImageFromArray(im)\n im.CopyInformation(inputImage)\n\n logger.debug('Yielding squareroot image')\n yield im, 'squareroot', kwargs\n\n\ndef getLogarithmImage(inputImage, inputMask, **kwargs):\n r\"\"\"\n Computes the logarithm of the absolute value of the original image + 1.\n\n Resulting values are rescaled on the range of the initial original image and negative intensities are made\n negative in resultant filtered image.\n\n :math:`f(x) = \\left\\{ {\\begin{array}{lcl}\n c\\log{(x + 1)} & \\mbox{for} & x \\ge 0 \\\\\n -c\\log{(-x + 1)} & \\mbox{for} & x < 0\\end{array}} \\right. \\text{, where } c=\\frac{\\max(|x|)}{\\log(\\max(|x|) + 1)}`\n\n Where :math:`x` and :math:`f(x)` are the original and filtered intensity, respectively.\n\n :return: Yields logarithm filtered image, 'logarithm' and ``kwargs`` (customized settings)\n \"\"\"\n global logger\n\n im = sitk.GetArrayFromImage(inputImage)\n im = im.astype('float64')\n im_max = numpy.max(numpy.abs(im))\n im[im > 0] = numpy.log(im[im > 0] + 1)\n im[im < 0] = - numpy.log(- (im[im < 0] - 1))\n im = im * (im_max / numpy.max(numpy.abs(im)))\n im = sitk.GetImageFromArray(im)\n im.CopyInformation(inputImage)\n\n logger.debug('Yielding logarithm image')\n yield im, 'logarithm', kwargs\n\n\ndef getExponentialImage(inputImage, inputMask, **kwargs):\n r\"\"\"\n Computes the exponential of the original image.\n\n Resulting values are rescaled on the range of the initial original image.\n\n :math:`f(x) = e^{cx},\\text{ where } c=\\displaystyle\\frac{\\log(\\max(|x|))}{\\max(|x|)}`\n\n Where :math:`x` and :math:`f(x)` are the original and filtered intensity, respectively.\n\n :return: Yields exponential filtered image, 'exponential' and ``kwargs`` (customized settings)\n \"\"\"\n global logger\n\n im = sitk.GetArrayFromImage(inputImage)\n im = im.astype('float64')\n im_max = numpy.max(numpy.abs(im))\n coeff = numpy.log(im_max) / im_max\n im = numpy.exp(coeff * im)\n im = sitk.GetImageFromArray(im)\n im.CopyInformation(inputImage)\n\n logger.debug('Yielding exponential image')\n yield im, 'exponential', kwargs\n\n\ndef getGradientImage(inputImage, inputMask, **kwargs):\n r\"\"\"\n Compute and return the Gradient Magnitude in the image.\n By default, takes into account the image spacing, this can be switched off by specifying\n ``gradientUseSpacing = False``.\n\n References:\n\n - `SimpleITK documentation\n <https://itk.org/SimpleITKDoxygen/html/classitk_1_1simple_1_1GradientMagnitudeImageFilter.html>`_\n - `<https://en.wikipedia.org/wiki/Image_gradient>`_\n \"\"\"\n gmif = sitk.GradientMagnitudeImageFilter()\n gmif.SetUseImageSpacing(kwargs.get('gradientUseSpacing', True))\n im = gmif.Execute(inputImage)\n yield im, 'gradient', kwargs\n\n\ndef getLBP2DImage(inputImage, inputMask, **kwargs):\n \"\"\"\n Compute and return the Local Binary Pattern (LBP) in 2D. If ``force2D`` is set to false (= feature extraction in 3D) a\n warning is logged, as this filter processes the image in a by-slice operation. The plane in which the LBP is\n applied can be controlled by the ``force2Ddimension`` parameter (see also :py:func:`generateAngles`).\n\n Following settings are possible (in addition to ``force2Ddimension``):\n\n - ``lbp2DRadius`` [1]: Float, specifies the radius in which the neighbours should be sampled\n - ``lbp2DSamples`` [9]: Integer, specifies the number of samples to use\n - ``lbp2DMethod`` ['uniform']: String, specifies the method for computing the LBP to use.\n\n For more information see `scikit documentation\n <http://scikit-image.org/docs/dev/api/skimage.feature.html#skimage.feature.local_binary_pattern>`_\n\n :return: Yields LBP filtered image, 'lbp-2D' and ``kwargs`` (customized settings)\n\n .. note::\n LBP can often return only a very small number of different gray levels. A customized bin width is often needed.\n .. warning::\n Requires package ``scikit-image`` to function. If not available, this filter logs a warning and does not yield an image.\n\n References:\n\n - T. Ojala, M. Pietikainen, and D. Harwood (1994), \"Performance evaluation of texture measures with classification\n based on Kullback discrimination of distributions\", Proceedings of the 12th IAPR International Conference on Pattern\n Recognition (ICPR 1994), vol. 1, pp. 582 - 585.\n - T. Ojala, M. Pietikainen, and D. Harwood (1996), \"A Comparative Study of Texture Measures with Classification Based\n on Feature Distributions\", Pattern Recognition, vol. 29, pp. 51-59.\n \"\"\"\n global logger\n try:\n from skimage.feature import local_binary_pattern\n except ImportError:\n logger.warning('Could not load required package \"skimage\", cannot implement filter LBP 2D')\n return\n\n lbp_radius = kwargs.get('lbp2DRadius', 1)\n lbp_samples = kwargs.get('lbp2DSamples', 8)\n lbp_method = kwargs.get('lbp2DMethod', 'uniform')\n\n im_arr = sitk.GetArrayFromImage(inputImage)\n\n Nd = inputImage.GetDimension()\n if Nd == 3:\n # Warn the user if features are extracted in 3D, as this function calculates LBP in 2D\n if not kwargs.get('force2D', False):\n logger.warning('Calculating Local Binary Pattern in 2D, but extracting features in 3D. Use with caution!')\n lbp_axis = kwargs.get('force2Ddimension', 0)\n\n im_arr = im_arr.swapaxes(0, lbp_axis)\n for idx in range(im_arr.shape[0]):\n im_arr[idx, ...] = local_binary_pattern(im_arr[idx, ...], P=lbp_samples, R=lbp_radius, method=lbp_method)\n im_arr = im_arr.swapaxes(0, lbp_axis)\n elif Nd == 2:\n im_arr = local_binary_pattern(im_arr, P=lbp_samples, R=lbp_radius, method=lbp_method)\n else:\n logger.warning('LBP 2D is only available for 2D or 3D with forced 2D extraction')\n return\n\n im = sitk.GetImageFromArray(im_arr)\n im.CopyInformation(inputImage)\n\n yield im, 'lbp-2D', kwargs\n\n\ndef getLBP3DImage(inputImage, inputMask, **kwargs):\n \"\"\"\n Compute and return the Local Binary Pattern (LBP) in 3D using spherical harmonics.\n If ``force2D`` is set to true (= feature extraction in 2D) a warning is logged.\n\n LBP is only calculated for voxels segmented in the mask\n\n Following settings are possible:\n\n - ``lbp3DLevels`` [2]: integer, specifies the the number of levels in spherical harmonics to use.\n - ``lbp3DIcosphereRadius`` [1]: Float, specifies the radius in which the neighbours should be sampled\n - ``lbp3DIcosphereSubdivision`` [1]: Integer, specifies the number of subdivisions to apply in the icosphere\n\n :return: Yields LBP filtered image for each level, 'lbp-3D-m<level>' and ``kwargs`` (customized settings).\n Additionally yields the kurtosis image, 'lbp-3D-k' and ``kwargs``.\n\n .. note::\n LBP can often return only a very small number of different gray levels. A customized bin width is often needed.\n .. warning::\n Requires package ``scipy`` and ``trimesh`` to function. If not available, this filter logs a warning and does not\n yield an image.\n\n References:\n\n - Banerjee, J, Moelker, A, Niessen, W.J, & van Walsum, T.W. (2013), \"3D LBP-based rotationally invariant region\n description.\" In: Park JI., Kim J. (eds) Computer Vision - ACCV 2012 Workshops. ACCV 2012. Lecture Notes in Computer\n Science, vol 7728. Springer, Berlin, Heidelberg. doi:10.1007/978-3-642-37410-4_3\n \"\"\"\n global logger\n Nd = inputImage.GetDimension()\n if Nd != 3:\n logger.warning('LBP 3D only available for 3 dimensional images, found %i dimensions', Nd)\n return\n\n try:\n from scipy.stats import kurtosis\n from scipy.ndimage.interpolation import map_coordinates\n from scipy.special import sph_harm\n from trimesh.creation import icosphere\n except ImportError:\n logger.warning('Could not load required package \"scipy\" or \"trimesh\", cannot implement filter LBP 3D')\n return\n\n # Warn the user if features are extracted in 2D, as this function calculates LBP in 3D\n if kwargs.get('force2D', False):\n logger.warning('Calculating Local Binary Pattern in 3D, but extracting features in 2D. Use with caution!')\n\n label = kwargs.get('label', 1)\n\n lbp_levels = kwargs.get('lbp3DLevels', 2)\n lbp_icosphereRadius = kwargs.get('lbp3DIcosphereRadius', 1)\n lbp_icosphereSubdivision = kwargs.get('lbp3DIcosphereSubdivision', 1)\n\n im_arr = sitk.GetArrayFromImage(inputImage)\n ma_arr = sitk.GetArrayFromImage(inputMask)\n\n # Variables used in the shape comments:\n # Np Number of voxels\n # Nv Number of vertices\n\n # Vertices icosahedron for spherical sampling\n coords_icosahedron = numpy.array(icosphere(lbp_icosphereSubdivision, lbp_icosphereRadius).vertices) # shape(Nv, 3)\n\n # Corresponding polar coordinates\n theta = numpy.arccos(numpy.true_divide(coords_icosahedron[:, 2], lbp_icosphereRadius))\n phi = numpy.arctan2(coords_icosahedron[:, 1], coords_icosahedron[:, 0])\n\n # Corresponding spherical harmonics coefficients Y_{m, n, theta, phi}\n Y = sph_harm(0, 0, theta, phi) # shape(Nv,)\n n_ix = numpy.array(0)\n\n for n in range(1, lbp_levels):\n for m in range(-n, n + 1):\n n_ix = numpy.append(n_ix, n)\n Y = numpy.column_stack((Y, sph_harm(m, n, theta, phi)))\n # shape (Nv, x) where x is the number of iterations in the above loops + 1\n\n # Get labelled coordinates\n ROI_coords = numpy.where(ma_arr == label) # shape(3, Np)\n\n # Interpolate f (samples on the spheres across the entire volume)\n coords = numpy.array(ROI_coords).T[None, :, :] + coords_icosahedron[:, None, :] # shape(Nv, Np, 3)\n f = map_coordinates(im_arr, coords.T, order=3) # Shape(Np, Nv) Note that 'Np' and 'Nv' are swapped due to .T\n\n # Compute spherical Kurtosis\n k = kurtosis(f, axis=1) # shape(Np,)\n\n # Apply sign function\n f_centroids = im_arr[ROI_coords] # Shape(Np,)\n f = numpy.greater_equal(f, f_centroids[:, None]).astype(int) # Shape(Np, Nv)\n\n # Compute c_{m,n} coefficients\n c = numpy.multiply(f[:, :, None], Y[None, :, :]) # Shape(Np, Nv, x)\n c = c.sum(axis=1) # Shape(Np, x)\n\n # Integrate over m\n f = numpy.multiply(c[:, None, n_ix == 0], Y[None, :, n_ix == 0]) # Shape (Np, Nv, 1)\n for n in range(1, lbp_levels):\n f = numpy.concatenate((f,\n numpy.sum(numpy.multiply(c[:, None, n_ix == n], Y[None, :, n_ix == n]),\n axis=2, keepdims=True)\n ),\n axis=2)\n # Shape f (Np, Nv, levels)\n\n # Compute L2-Norm\n f = numpy.sqrt(numpy.sum(f ** 2, axis=1)) # shape(Np, levels)\n\n # Keep only Real Part\n f = numpy.real(f) # shape(Np, levels)\n k = numpy.real(k) # shape(Np,)\n\n # Yield the derived images for each level\n result = numpy.ndarray(im_arr.shape)\n for l_idx in range(lbp_levels):\n result[ROI_coords] = f[:, l_idx]\n\n # Create a SimpleITK image\n im = sitk.GetImageFromArray(result)\n im.CopyInformation(inputImage)\n\n yield im, 'lbp-3D-m%d' % (l_idx + 1), kwargs\n\n # Yield Kurtosis\n result[ROI_coords] = k\n\n # Create a SimpleITK image\n im = sitk.GetImageFromArray(result)\n im.CopyInformation(inputImage)\n\n yield im, 'lbp-3D-k', kwargs\n" ]
[ [ "numpy.true_divide", "numpy.sqrt", "numpy.asarray", "numpy.ndarray", "scipy.ndimage.interpolation.map_coordinates", "numpy.arctan2", "numpy.max", "numpy.mean", "numpy.digitize", "numpy.exp", "numpy.where", "numpy.histogram", "numpy.allclose", "numpy.pad", "numpy.arange", "scipy.special.sph_harm", "numpy.greater_equal", "numpy.ceil", "numpy.real", "numpy.std", "numpy.zeros", "numpy.log", "numpy.multiply", "numpy.min", "numpy.append", "numpy.floor", "scipy.stats.kurtosis", "numpy.array", "numpy.sum", "numpy.maximum", "numpy.abs", "numpy.empty" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "1.6", "0.14", "1.10", "0.15", "1.4", "0.16", "1.9", "0.19", "1.5", "0.18", "1.2", "1.7", "0.12", "1.0", "0.17", "1.3", "1.8" ], "tensorflow": [] } ]
ccj5351/hmr_rgbd
[ "d1dcf81d72c11e1f502f2c494cd86425f384d9cc", "d1dcf81d72c11e1f502f2c494cd86425f384d9cc", "d1dcf81d72c11e1f502f2c494cd86425f384d9cc", "d1dcf81d72c11e1f502f2c494cd86425f384d9cc" ]
[ "debug/test_tf_funcs.py", "pytorch_src/ResnetV2.py", "src/util/surreal_in_extrinc.py", "src/datasets/common.py" ]
[ "# !/usr/bin/env python3\n# -*-coding:utf-8-*-\n# @file: test_tf_funcs.py\n# @brief:\n# @author: Changjiang Cai, [email protected], [email protected]\n# @version: 0.0.1\n# @creation date: 13-08-2019\n# @last modified: Tue 13 Aug 2019 05:38:05 PM EDT\n\nimport tensorflow as tf\nimport numpy as np\n\nif __name__ == \"__main__\":\n \n\n \n \"\"\" test tf.gather_nd \"\"\" \n # data is [[[ 0 1]\n # [ 2 3]\n # [ 4 5]]\n #\n # [[ 6 7]\n # [ 8 9]\n # [10 11]]]\n data = np.reshape(np.arange(12), [2, 3, 2])\n x = tf.constant(data)\n\n idx_1 = [[[0, 0, 0], [0, 1, 1]], [[1, 0, 1], [1, 1, 0]]] # 2 x 2 x 3\n result1 = tf.gather_nd(x, idx_1)\n \n idx_2 = [[0, 0, 0], [0, 1, 1], [1, 0, 1], [1, 1, 0]] # 4 x 3\n result2 = tf.gather_nd(x, idx_2)\n \n # Construct a 'Session' to execute the graph.\n sess = tf.Session()\n # Execute the graph and store the value that `e` represents in `result`.\n x, res1, res2 = sess.run([x, result1, result2])\n\n print ('x = {}'.format(x))\n print ('res1 = {}'.format(res1))\n print ('res2 = {}'.format(res2))\n", "# !/usr/bin/env python3\n# -*-coding:utf-8-*-\n# @file:\n# @brief:\n# @author: Changjiang Cai, [email protected], [email protected]\n# @version: 0.0.1\n# @creation date: 23-10-2019\n# @last modified: Wed 30 Oct 2019 03:17:36 PM EDT\n\"\"\"\n file: ResnetV2.py\n author: Changjiang Cai\n mark: adopted from:\n 1) pytorch source code, and \n 2) and https://github.com/MandyMo/pytorch_HMR.git\n 3) and https://github.com/lucasb-eyer/lbtoolbox/blob/master/lbtoolbox/pytorch.py#L61;\n\"\"\"\n\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch\nfrom torch.nn.parameter import Parameter\nimport torch.optim as optim\nimport numpy as np\nimport math\nimport torchvision\nimport sys\n#from dollections import OrderedDict\n\n\"\"\"Contains definitions for the preactivation form of Residual Networks.\n\nResidual networks (ResNets) were originally proposed in:\n[1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun\n Deep Residual Learning for Image Recognition. arXiv:1512.03385\n\nThe full preactivation 'v2' ResNet variant implemented in this module was\nintroduced by:\n[2] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun\n Identity Mappings in Deep Residual Networks. arXiv: 1603.05027\n\nThe key difference of the full preactivation 'v2' variant compared to the\n'v1' variant in [1] is the use of batch normalization before every weight layer.\n\n\"\"\"\n\n########################################\n# Kaiming's blocks\n########################################\ndef conv3x3(cin, cout, stride=1, groups=1, bias=False):\n return nn.Conv2d(cin, cout, kernel_size=3, stride=stride, padding=1, bias=bias, \n groups=groups)\n\n\ndef conv1x1(cin, cout, stride=1,bias=False):\n return nn.Conv2d(cin, cout, kernel_size=1, stride=stride, padding=0, bias=bias)\n\n# bottleneck_v2\n# x-->BN --> ReLU-->(conv1, BN, ReLU)-->(conv2, BN, ReLU) --> conv3\n# | |\n# | |\n# | |\n# |--------------------------------------------> Addition --> x_new\nclass Bottleneck_V2(nn.Module):\n expansion = 4\n def __init__(self, cin, cout, stride):\n super(Bottleneck_V2, self).__init__()\n cmid = cout// self.expansion\n \n self.relu = nn.ReLU(inplace=True)\n \"\"\" Pre Act \"\"\"\n self.bn0 = nn.BatchNorm2d(cin)\n \n \"\"\" (conv1, BN, ReLU)\"\"\"\n self.conv1 = conv1x1(cin, cmid, bias=False) #conv1\n self.bn1 = nn.BatchNorm2d(cmid) #conv1/BatchNorm\n \n \"\"\" (conv2, BN, ReLU)\"\"\"\n self.conv2 = conv3x3(cmid, cmid, stride, bias=False) #conv2\n self.bn2 = nn.BatchNorm2d(cmid) #conv2/BatchNorm\n \"\"\" (conv3 )\"\"\"\n self.conv3 = conv1x1(cmid, cout, bias=True) # conv3\n\n self.stride = stride\n self.maxpool2d= nn.MaxPool2d(kernel_size=1, stride = stride)\n self.shortcut = None\n if cin != cout:\n # conv, 1 x 1\n self.shortcut = conv1x1(cin, cout, stride, bias = True)\n\n def forward(self, x):\n \"\"\" Pre Act \"\"\"\n preact = self.relu(self.bn0(x))\n if self.shortcut is not None:\n shortcut = self.shortcut(preact) # e.g., stride = 2\n else:\n shortcut = self.maxpool2d(x)\n \n \"\"\" (conv1, BN, ReLU)\"\"\"\n residual = self.relu(self.bn1(self.conv1(preact)))\n \"\"\" (conv2, BN, ReLU)\"\"\"\n residual = self.relu(self.bn2(self.conv2(residual)))\n \"\"\" (conv3 )\"\"\"\n residual = self.conv3(residual)\n output = shortcut + residual\n return output\n\n\nclass ResNet_V2(nn.Module):\n def __init__(self, block, layers, num_classes=None, global_pool = True, \n isFetchDictForDebug = False):\n self.isFetchDictForDebug = isFetchDictForDebug\n self.inplanes = 64\n self.expansion = 4\n super(ResNet_V2, self).__init__()\n self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=True)\n # We do not include batch normalization or activation functions in\n # conv1 because the first ResNet unit will perform these. Cf.\n # Appendix of [2].\n #self.bn1 = nn.BatchNorm2d(64)\n\n #self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=0)\n #Updated to implement 'same' padding in tensorflow; do manually padding to bottom and right, \n # then apply the follwoing maxpool with padding = 0 as its argument;\n self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=0)\n # padding size: starting from the last dimension and moving forward;\n self.maxpool_pad = (0,1,0,1)# i.e, (padding_left, padding_right, padding_top, padding_bottom)\n\n self.layer1 = self._make_layer(block, 64, layers[0], stride=2)\n self.layer2 = self._make_layer(block, 128, layers[1], stride=2)\n self.layer3 = self._make_layer(block, 256, layers[2], stride=2)\n self.layer4 = self._make_layer(block, 512, layers[3], stride=1)\n \n # This is needed because the pre-activation variant does not have batch\n # normalization or activation functions in the residual unit output. See\n # Appendix of [2].\n self.postnorm = nn.BatchNorm2d(512*self.expansion)\n self.relu = nn.ReLU(inplace=True)\n #self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) # output is of size 1 x 1 here;\n self.global_pool = global_pool\n #Note: in HMR project, we set `num_classes=None`;\n if num_classes is not None:\n self.fc = nn.Linear(512 * block.expansion, num_classes)\n else:\n self.fc = None\n \n #leave it here FYI:\n #for m in self.modules():\n # if isinstance(m, nn.Conv2d):\n # n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n # m.weight.data.normal_(0, math.sqrt(2. / n))\n # elif isinstance(m, nn.BatchNorm2d):\n # m.weight.data.fill_(1)\n # m.bias.data.zero_()\n \n # the new version is shown below:\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')\n elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n\n #def __init__(self, cin, cout, stride=1):\n\n def _make_layer(self, block, planes, numBlocks, stride):\n expansion = block.expansion\n layers = []\n for i in range(0, numBlocks):\n cur_inplanes = planes * expansion if i > 0 else self.inplanes\n tmp_stride = 1 if i < (numBlocks - 1) else stride\n layers.append(block(cur_inplanes, planes*expansion, tmp_stride))\n #update self.inplanes = output planes, for next incoming Residual block, with new palnes #;\n self.inplanes = planes * expansion\n return nn.Sequential(*layers)\n\n def forward(self, x):\n \"\"\" fetch dict \"\"\"\n fetch_dict = {}\n \n x = self.conv1(x)\n fetch_dict['x_conv1'] = x\n\n #Updated to implement 'same' padding in tensorflow; do manually padding to bottom and right, \n # then apply the follwoing maxpool with padding = 0 as its argument;\n x = F.pad(x, pad = self.maxpool_pad, mode = 'constant', value = 0)\n x = self.maxpool(x)\n fetch_dict['x_maxpool'] = x\n\n x = self.layer1(x)\n fetch_dict['x_layer1'] = x\n x = self.layer2(x)\n fetch_dict['x_layer2'] = x\n x = self.layer3(x)\n fetch_dict['x_layer3'] = x\n x = self.layer4(x)\n fetch_dict['x_layer4'] = x\n x = self.postnorm(x)\n #Updated on 2019/10/30: missing the relu added!!!\n x = self.relu(x)\n fetch_dict['x_postnorm'] = x\n if self.global_pool:\n x = torch.mean(x, dim=[2,3], keepdim = True)\n fetch_dict['x_global_pool'] = x\n\n if self.fc is not None:\n x = self.fc(torch.flatten(x,1))\n if self.isFetchDictForDebug:\n return x, fetch_dict\n else:\n return x\n\n\ndef resnet_v2_50(num_classes=None, global_pool = True, isFetchDictForDebug = False):\n model = ResNet_V2(Bottleneck_V2, [3,4,6,3],num_classes, global_pool, isFetchDictForDebug)\n return model\n\ndef get_tf2pt_key_map_dict():\n map_dict = {\n '' : '',\n # for root block: conv1 --> pool1\n # that is: input x --> (conv1 --> pool1 )--> (residual-block1,2,3,4) --> postnorm --> global avg-pool --> output\n 'conv1/weights' : 'conv1.weight',\n 'conv1/biases' : 'conv1.bias',\n # for post norm:\n 'postnorm/beta': 'postnorm.bias',\n 'postnorm/gamma': 'postnorm.weight',\n 'postnorm/moving_mean': 'postnorm.running_mean',\n 'postnorm/moving_variance': 'postnorm.running_var',\n }\n\n \"\"\" block 1, has 3 unites \"\"\"\n \"\"\" block 2, has 4 unites \"\"\"\n \"\"\" block 3, has 6 unites \"\"\"\n \"\"\" block 4, has 3 unites \"\"\"\n # processing tf_key_1\n blks = [(1,3), (2,4), (3,6), (4,3)]\n for t in blks:\n b_idx = t[0]\n for u_idx in range(t[1]):\n key = 'block{}/unit_{}'.format(b_idx, u_idx + 1)\n vaule = 'layer{}.{}'.format(b_idx, u_idx )\n map_dict[key] = vaule\n \n # processing tf_key_2\n #Example: (tf_key, pt_key)\n \"\"\" In each bottleneck block: we have the following: \"\"\"\n bottleneck_tf_pt_tuples = [\n # Note: 'resnet_v2_50/block1/unit_1/bottleneck_v2/preact/beta/Adam':\n # 'Adam' is related to Adam Optimization, so here we do not use it!!!\n # Pre-Act: bn0\"\"\"\n # BN: out = gamma * X_norm + beta, so beta is bias, gamma is weight;\n ['preact/gamma','bn0.weight'],\n ['preact/beta', 'bn0.bias'],\n ['preact/moving_mean', 'bn0.running_mean'],\n ['preact/moving_variance', 'bn0.running_var'],\n #conv1 + bn1 + relu1\n ['conv1/weights', 'conv1.weight'],\n ['conv1/BatchNorm/gamma', 'bn1.weight'],\n ['conv1/BatchNorm/beta', 'bn1.bias'],\n ['conv1/BatchNorm/moving_mean', 'bn1.running_mean'],\n ['conv1/BatchNorm/moving_variance', 'bn1.running_var'],\n #conv2 + bn2 + relu2\n ['conv2/weights', 'conv2.weight'],\n ['conv2/BatchNorm/gamma', 'bn2.weight'],\n ['conv2/BatchNorm/beta', 'bn2.bias'],\n ['conv2/BatchNorm/moving_mean', 'bn2.running_mean'],\n ['conv2/BatchNorm/moving_variance', 'bn2.running_var'],\n #conv3\n ['conv3/weights', 'conv3.weight'],\n ['conv3/biases', 'conv3.bias'],\n\n #shortcut\n ['shortcut/weights', 'shortcut.weight'],\n ['shortcut/biases', 'shortcut.bias'],\n ]\n for cur_tuple in bottleneck_tf_pt_tuples:\n map_dict[cur_tuple[0]] = cur_tuple[1]\n #print (map_dict)\n return map_dict\n\ndef map_tf_dictKeys_2PyTorch_dictKeys( map_dict,\n tf_key = 'resnet_v2_50/block1/unit_1/bottleneck_v2/conv1/BatchNorm/beta'):\n # E.g.:\n # tf_key = 'resnet_v2_50/block1/unit_1/bottleneck_v2/conv1/BatchNorm/beta'\n # or tf_key = 'resnet_v2_50/conv1/biases'\n # 1) skip the first part : 'resnet_v2_50'\n tf_key = tf_key[len('resnet_v2_50')+1:]\n # 2) find 'bottleneck_v2' if exists, and pick the part before and after 'bottleneck_v2'\n pos = tf_key.find('bottleneck_v2')\n \n if pos > 0: # if found 'bottleneck_v2'\n tf_key_1, tf_key_2 = tf_key[0:pos-1], tf_key[pos+1+len('bottleneck_v2'):]\n else: # no found 'bottleneck_v2'\n tf_key_1, tf_key_2 = '', tf_key\n \n # processing tf_key_1\n #print (tf_key_1)\n pt_key_1 = map_dict[tf_key_1]\n #print (pt_key_1)\n #print (tf_key_2)\n pt_key_2 = map_dict[tf_key_2]\n #print (pt_key_2)\n if pt_key_1 == '':\n pt_key = pt_key_2\n else:\n pt_key = pt_key_1 + '.' + pt_key_2\n #print (\"[***] {} --> {}\".format(tf_key, pt_key))\n return pt_key\n \n\n\n#>see https://stackoverflow.com/questions/51628607/pytorch-passing-numpy-array-for-weight-initialization\ndef set_resnet_parameter_data(layer, parameter_name, new_torch_data):\n param = getattr(layer, parameter_name)\n param.data = new_torch_data\n\ndef pass_np_model_state_to_resnet(src_np_model_state_dict, dst_resnet_model):\n map_dict = get_tf2pt_key_map_dict()\n dst_state_dict = dst_resnet_model.state_dict()\n n_valid = 0\n n_adam = 0\n tf_var_names = list(src_np_model_state_dict['resnet_v2_50_names'])\n N = len(tf_var_names)\n\n for tf_key in sorted(src_np_model_state_dict.keys()):\n # Note: 'resnet_v2_50/block1/unit_1/bottleneck_v2/preact/beta/Adam':\n # 'Adam' is related to Adam Optimization, so here we do not use it!!!\n param = src_np_model_state_dict[tf_key]\n if 'Adam' in tf_key:\n #print('Adam! {} is only for Adam Optimization, not uesed here!!'.format(tf_key))\n n_adam += 1\n tf_var_names.remove(tf_key)\n continue\n elif 'resnet_v2_50_names' == tf_key:\n continue\n pt_key = map_tf_dictKeys_2PyTorch_dictKeys(map_dict, tf_key)\n if pt_key not in dst_state_dict:\n print('unexpected ', pt_key, ' !')\n continue\n if not isinstance(param, np.ndarray):\n raise ValueError('Expected a np.ndarray')\n else:\n # !!! Note: added by CCJ on 2019/10/24;\n # tensorflow conv2d weight in size of [kernel_size[0], kernel_size[1], in_channels, out_channels], \n # e.g., weight in size [7,7,3,64] means applying 7x7-kernel-size convolution to input image with 3 channel \n # and output channel is 64;\n # While, PyTorch will have its weight in shape [out_channels, in_channels/groups, kernel_size[0], kernel_size[1]], \n # here we assume gropus = 1; \n if param.ndim == 4:\n param = np.transpose(param, [3,2,0,1])\n param = torch.from_numpy(param).contiguous()\n try:\n dst_state_dict[pt_key].copy_(param)\n n_valid += 1\n tf_var_names.remove(tf_key)\n except:\n print(pt_key, ' is inconsistent!')\n print ('src np.ndarray in shape {}, dst tensor in shape {}'.format(param.shape, \n dst_state_dict[pt_key].shape))\n n_valid -= 1\n tf_var_names.append(tf_key)\n continue\n \n \n \n print('%d out of %d variables processed! Wherein:'%(n_valid + n_adam, N))\n print(' [***] Copyed state dict for %d variables and finished!' %n_valid)\n print(' [***] Skip %d adam variables, which are related to Adam optimaization state' %(n_adam))\n print(' [***] {} variables are left unprocessed!'.format(len(tf_var_names)))\n if n_valid + n_adam == N:\n print (\" [***] Resnet_V2_50 loading Numpy weights Succeed!!!\")\n else:\n print (\" [***] Resnet_V2_50 loading Numpy weights Failed !!!\")\n #print('[***] Including: ', tf_var_names)\n\n\ndef load_Res50ModelFromNpyFile(npy_file = '/home/ccj/hmr-rgbd/results/saved_weights/hmr_pre_trained_resnet_v2_50.npy'):\n dst_resnet_model = resnet_v2_50()\n assert (npy_file is not None)\n # this npy file is generated by Python2, due to Tensorflow is installed in Python2;\n # load this npy file (generated by Python2) to Python3, due to PyTorch is installed in Python3;\n src_np_model_state_dict = np.load(npy_file, allow_pickle= True, encoding = 'latin1').item()\n #tmp_name = 'resnet_v2_50/block4/unit_3/bottleneck_v2/conv2/weights'\n # check the variable dimensionality\n # print should be : [3, 3, 512, 512];\n #print(src_np_model_state_dict[tmp_name].shape)\n \n pass_np_model_state_to_resnet(src_np_model_state_dict, dst_resnet_model)\n return dst_resnet_model\n\n\nif __name__ == '__main__':\n \n if 0:\n print ('resnet_v2_50 state_dict():')\n n = 0\n for k,v in resnet_v2_50().state_dict().items():\n print (k, v.shape)\n n += 1\n print (n)\n \n if 0: \n \"\"\" load dictionary \"\"\" \n npy_file = '/home/ccj/hmr-rgbd/results/saved_weights/hmr_pre_trained_resnet_v2_50.npy'\n resnet_dict2 = np.load(npy_file, allow_pickle= True, encoding = 'latin1').item()\n print ('loaded var_names : ', resnet_dict2['resnet_v2_50_names'])\n tmp_name = 'resnet_v2_50/block4/unit_3/bottleneck_v2/conv2/weights'\n # check the variable dimensionality\n # print should be : [3, 3, 512, 512];\n print (resnet_dict2[tmp_name].shape)\n \n \"\"\" load numpy dictionary to Pytorch model and save the model\"\"\" \n if 1:\n # this npy file is generated by Python2, due to Tensorflow is installed in Python2;\n npy_file = '/home/ccj/hmr-rgbd/results/saved_weights/hmr_pre_trained_resnet_v2_50.npy'\n # load this npy file (generated by Python2) to Python3, due to PyTorch is installed in Python3;\n dst_resnet_model = load_Res50ModelFromNpyFile(npy_file)\n dst_state_dict = dst_resnet_model.state_dict()\n\n model_path = '/home/ccj/hmr-rgbd/results/saved_weights/hmr_pre_trained_resnet_v2_50.pt'\n torch.save(dst_state_dict, model_path)\n print ('saved %s' % model_path)\n #n = 0\n #for k,v in dst_state_dict.items():\n # print (k, v.shape)\n # n += 1\n #print (n)\n if 1:\n # get a new model\n resnet_v2_50 = resnet_v2_50()\n model_path = '/home/ccj/hmr-rgbd/results/saved_weights/hmr_pre_trained_resnet_v2_50.pt'\n # load the weights\n resnet_v2_50.load_state_dict(torch.load(model_path))\n print ('Loading %s' % model_path)\n", "# !/usr/bin/env python3\n# -*-coding:utf-8-*-\n# @file: surreal_in_extrinc.py\n# @brief:\n# @author: Changjiang Cai, [email protected], [email protected]\n# @version: 0.0.1\n# @creation date: 03-07-2019\n# @last modified: Thu 18 Jul 2019 04:47:09 PM EDT\nimport numpy as np\nimport sys,os\nimport scipy.io as sio\nimport cv2\nimport math\nimport transforms3d\n\n\n#NOTE: added by CCJ:\n# Intrinsic camera matrix\n# > see https://github.com/gulvarol/surreal/blob/8af8ae195e6b4bb39a0fb64524a15a434ea620f6/datageneration/misc/3Dto2D/getIntrinsicBlender.m \n\ndef get_intrinsic():\n \"\"\" \n Returns:\n cam: (3,), [f, px, py] intrinsic camera parameters.\n e.g.\n [ 600 0 160 ;\n 0 600 120 ;\n 0 0 1 ];\n \"\"\"\n res_x_px = 320.0 # *scn.render.resolution_x\n res_y_px = 240.0 # *scn.render.resolution_y\n f_mm = 60.0 # *cam_ob.data.lens\n sensor_w_mm = 32.0 # *cam_ob.data.sensor_width\n sensor_h_mm = sensor_w_mm * res_y_px / res_x_px # *cam_ob.data.sensor_height (function of others)\n\n scale = 1. # *scn.render.resolution_percentage/100\n skew = .0 # only use rectangular pixels\n pixel_aspect_ratio = 1. \n\n fx_px = f_mm * res_x_px * scale / sensor_w_mm \n fy_px = f_mm * res_y_px * scale * pixel_aspect_ratio / sensor_h_mm \n \n # Center of the image\n u = res_x_px * scale / 2. \n v = res_y_px * scale / 2. \n \n # Intrinsic camera matrix\n intrinsic = [fx_px, skew, u, .0, fy_px, v, .0, .0, 1.]\n K = np.array([np.float(cont) for cont in intrinsic]).reshape(3, 3)\n #\"\"\" \n #K = [ fx_px skew u \n # 0 fy_px v \n # 0 0 1 ]\n #\"\"\"\n cam = np.zeros(3,dtype=np.float32)\n #print (\"K = {}, {}, cam = {}, {}\".format(K, K.shape, cam, cam.shape))\n cam[0] = 0.5 * (K[0, 0] + K[1, 1])\n cam[1] = K[0, 2]\n cam[2] = K[1, 2]\n return K, cam\n\n#\"\"\"\n#def get_surreal_to_lsp_joints_idx():\n# surreal_to_lsp_joints_idx = [\n# 7, # 7: rightFoot -> 0: R ankle\n# 4, # 4: rightLeg -> 1: R knee\n# 1, # 1: rightUpLeg -> 2: R hip\n# 2, # 2: leftUpLeg -> 3: L hip\n# 5, # 5: leftLeg -> 4: L knee\n# 8, # 8: leftFoot -> 5: L ankle\n# 20, # 20: rightHand -> 6: R Wrist\n# 18, # 18: rightForeArm-> 7: R Elbow\n# 13, # 13: rightShoulder -> 8: R shoulder\n# 14, # 14: leftShoulder -> 9: L shoulder\n# 19, # 19: leftForeArm -> 10: L Elbow\n# 21, # 21: leftHand -> 11: L Wrist\n# 12, # 12 neck -> 12: # Neck top\n# 15, # 15: head -> 13: # Head top\n# ]\n \n# return surreal_to_lsp_joints_idx\n#\"\"\"\n\ndef get_lsp_idx_from_smpl_joints():\n # Mapping from SMPL 24 joints to LSP joints (0:13). In this roder:\n _COMMON_JOINT_IDS = [\n 8, # 8: rightFoot -> 0: R ankle\n 5, # 5: rightLeg -> 1: R knee\n 2, # 2: rightUpLeg -> 2: R hip\n 1, # 1: leftUpLeg -> 3: L hip\n 4, # 4: leftLeg -> 4: L knee\n 7, # 7: leftFoot -> 5: L ankle\n 21, # 21: rightHand -> 6: R Wrist\n 19, # 19: rightForeArm-> 7: R Elbow\n 14, # 14: rightShoulder -> 8: R shoulder\n 13, # 13: leftShoulder -> 9: L shoulder\n 18, # 18: leftForeArm -> 10: L Elbow\n 20, # 20: leftHand -> 11: L Wrist\n 12, # 12 neck -> 12: # Neck top\n 15, # 15: head -> 13: # Head top\n ]\n \n return _COMMON_JOINT_IDS\n\n\n\ndef get_smpl_joint_names():\n smpl_joint_names = [\n 'hips', # 0\n 'leftUpLeg', # 1\n 'rightUpLeg', # 2\n 'spine', # 3\n 'leftLeg', # 4\n 'rightLeg', # 5\n 'spine1', # 6\n 'leftFoot',# 7\n 'rightFoot',# 8\n 'spine2', #9\n 'leftToeBase',# 10\n 'rightToeBase',# 11\n 'neck', # 12\n 'leftShoulder',# 13\n 'rightShoulder', # 14\n 'head', # 15\n 'leftArm', # 16\n 'rightArm', # 17\n 'leftForeArm', # 18\n 'rightForeArm',# 19\n 'leftHand', # 20\n 'rightHand', # 21\n 'leftHandIndex1', # 22\n 'rightHandIndex1' # 23\n ]\n assert len(smpl_joint_names == 24)\n #NOTE:\n \"\"\" it seems that surreal dataset has left/right swapped joints, \n but the smpl joint names provided here is correct.\n What you have to do is to swap the joints and pose/shape of surreal dataset to\n satisfy this smpl joints order shown above !!!\n \"\"\"\n return smpl_joint_names\n\n\n# extract 14 lsp joints from surreal;\n# return : \n # joints2d: 3 x 14 \n # joints3d * 1000. # NOTE: used unites : millimeter \ndef read_joints(currFrameJoints2D, currFrameJoints3D, Extrinsic):\n #currFrameJoints2D = currInfoDict['joints2D']\n #currFrameJoints3D = currFrameInfoDict['joints3D'] \n\n \"\"\"\n Reads joints in the common joint order.\n\n Returns:\n joints2d: 3 x |common joints|, e.g., 3 x 14;\n joints3d: |common joints| x 3, e.g., 14 x 3;\n\n \"\"\"\n # Mapping from SMPL 24 joints to LSP joints (0:13). In this roder:\n _COMMON_JOINT_IDS = get_lsp_idx_from_smpl_joints()\n # Go over each common joint ids\n # 2d joints is 3 x 14 (lsp order)\n joints2d = np.zeros((3, len(_COMMON_JOINT_IDS)))\n # 3d joints is 3 x 14 (lsp order)\n \n #NOTE:\n #joints3d = np.zeros((3, len(_COMMON_JOINT_IDS)))\n # updated the returned joints3d shape from [3,14] to [14, 3], \n # now it is consistent with that in tfrecord example parsing;\n joints3d = np.zeros((len(_COMMON_JOINT_IDS), 3))\n for i, jid in enumerate(_COMMON_JOINT_IDS):\n # 2d joints is 3 x 14 (lsp order)\n joints2d[0, i] = currFrameJoints2D[0,jid] # x\n joints2d[1, i] = currFrameJoints2D[1,jid] # y\n #NOTE: currently we just set this value as 1. But this value is not provided in the SURREAL dataset.\n joints2d[2, i] = 1 # visible\n \n \n #NOTE:???\n isWorldCoord = True\n #isWorldCoord = False\n if isWorldCoord:\n joints3d[i,:] = currFrameJoints3D[:,jid] # x,y,z: in real world meters;\n else:\n # 3d joints, 3 x 14\n # convert value from the world coordinate to camera coordinate;\n x,y,z = currFrameJoints3D[:,jid] # x,y,z: in real world meters;\n p_c = np.matmul(Extrinsic, np.reshape(np.array([x,y,z,1.0]), [4, -1]))\n joints3d[i,:] = p_c[:, 0] # x,y,z, camera-coordinate in meters;\n\n return joints2d, joints3d * 1000. # NOTE: used unites : millimeter \n #return joints2d, joints3d # NOTE: used unites : meter \n\n\ndef normalizeDepth(depthImg, isNormalized = True):\n loc = depthImg!=float(1e10)\n normDepth = depthImg\n if isNormalized:\n normDepth[loc] = (depthImg[loc] - np.min(depthImg[loc]))/(np.max(depthImg[loc])-np.min(depthImg[loc]))\n normDepth[~loc]= .0\n return normDepth\n \n\n# added by CCJ:\n# copied from https://github.com/gulvarol/surreal/blob/master/datageneration/misc/smpl_relations/smpl_relations.py\ndef get_frame(filevideo, t=0):\n cap = cv2.VideoCapture(filevideo)\n cap.set(propId=1, value=t)\n ret, frame = cap.read()\n frame = frame[:, :, [2, 1, 0]]\n return frame\n\n# added by CCJ:\n# copied from https://github.com/gulvarol/surreal/blob/master/datageneration/misc/smpl_relations/smpl_relations.py\ndef rotateBody(RzBody, pelvisRotVec):\n angle = np.linalg.norm(pelvisRotVec)\n Rpelvis = transforms3d.axangles.axangle2mat(pelvisRotVec / angle, angle)\n globRotMat = np.dot(RzBody, Rpelvis)\n R90 = transforms3d.euler.euler2mat(np.pi / 2, 0, 0)\n globRotAx, globRotAngle = transforms3d.axangles.mat2axangle(np.dot(R90, globRotMat))\n globRotVec = globRotAx * globRotAngle\n return globRotVec\n\n\n# added by CCJ:\n# copied from https://github.com/gulvarol/surreal/blob/master/datageneration/misc/smpl_relations/smpl_relations.py\n# args:\n# points: 3D points in shape [24, 3];\n# intrinsic : camera intrinsic matrix, in shape [3, 3] matrix;\n# extrinsic : camera extrinsic matrix, in shape [3, 4] matrix;\ndef project_vertices(points, intrinsic, extrinsic):\n homo_coords = np.concatenate([points, np.ones((points.shape[0], 1))], axis=1).transpose()\n proj_coords = np.dot(intrinsic, np.dot(extrinsic, homo_coords))\n proj_coords = proj_coords / proj_coords[2]\n proj_coords = proj_coords[:2].transpose()\n return proj_coords # in shape [24, 2]\n\n\n\n# > see https://github.com/gulvarol/surreal/blob/8af8ae195e6b4bb39a0fb64524a15a434ea620f6/datageneration/misc/3Dto2D/getExtrinsicBlender.m\ndef get_extrinsic(T):\n \"\"\" T: camera location \"\"\" \n R_world2bcam = np.array([[.0, .0, 1.],[.0, -1., .0],[-1., .0, .0]]).transpose()\n T_world2bcam = -1.0 * np.matmul(R_world2bcam, T)\n #print R_world2bcam, T_world2bcam\n # Following is needed to convert Blender camera to computer vision camera\n R_bcam2cv = np.array([[1.,.0,.0], [.0,-1.,.0], [.0,.0,-1.]])\n \n #Build the coordinate transform matrix from world to computer vision camera\n R_world2cv = np.dot(R_bcam2cv, R_world2bcam)\n T_world2cv = np.dot(R_bcam2cv, T_world2bcam)\n # Put into 3x4 matrix\n RT = np.concatenate([R_world2cv, T_world2cv], axis=1)\n return RT\n\n\n\ndef draw_joints2D(img, joints2D, ax=None, kintree_table=None, with_text=True, color='g'):\n import matplotlib.pyplot as plt\n if not ax:\n fig = plt.figure()\n ax = fig.add_subplot(111)\n plt.imshow(img)\n for i in range(1, kintree_table.shape[1]):\n j1 = kintree_table[0][i]\n j2 = kintree_table[1][i]\n ax.plot([joints2D[j1, 0], joints2D[j2, 0]],\n [joints2D[j1, 1], joints2D[j2, 1]],\n color=color, linestyle='-', linewidth=2, marker='o', markersize=5)\n if with_text:\n ax.text(joints2D[j2, 0],\n joints2D[j2, 1],\n s= get_smpl_joint_names()[j2],\n color=color,\n fontsize=8)\n print (\"idx %d, joint %s, (x,y) = (%d,%d)\" % (j2, get_smpl_joint_names()[j2], joints2D[j2,0], joints2D[j2,1]))\n plt.savefig('/home/hmr/results/surreal_debug/smpl_joints24_proj.png')\n\n#*************************************************\n#NOTE: swap the left/right joints poses, due to \n# the left/right inconsitency which exists in the \n# surreal dataset itself;\n# This function is copied and revised from src/util/data_utils.py;\n#*************************************************\ndef swap_right_left_pose(pose):\n \"\"\"\n Input is a 72-Dim vector.\n Global rotation (first 3) is left alone.\n \"\"\"\n \n \"\"\"\n # How I got the indices:\n joints_names = ['hips', 'leftUpLeg', 'rightUpLeg', 'spine', 'leftLeg', 'rightLeg', 'spine1',\n 'leftFoot', 'rightFoot', 'spine2', 'leftToeBase', 'rightToeBase', 'neck',\n 'leftShoulder', 'rightShoulder', 'head', 'leftArm', 'rightArm', 'leftForeArm',\n 'rightForeArm', 'leftHand', 'rightHand', 'leftHandIndex1', 'rightHandIndex1' ]\n right = [11, 8, 5, 2, 14, 17, 19, 21, 23] # right joints;\n left = [10, 7, 4, 1, 13, 16, 18, 20, 22] # left joints;\n new_map = {}\n for r_id, l_id in zip(right, left):\n for axis in range(0, 3):\n rind = r_id * 3 + axis\n lind = l_id * 3 + axis\n new_map[rind] = lind\n new_map[lind] = rind\n asis = [id for id in np.arange(0, 24) if id not in right + left]\n for a_id in asis:\n for axis in range(0, 3):\n aind = a_id * 3 + axis\n new_map[aind] = aind\n swap_inds = np.array([new_map[k] for k in sorted(new_map.keys())])\n \"\"\"\n swap_inds = np.array([\n 0, 1, 2, 6, 7, 8, 3, 4, 5, 9, 10, 11, 15, 16, 17, 12, 13, 14, \n 18, 19, 20, 24, 25, 26, 21, 22, 23, 27, 28, 29, 33, 34, 35, 30, 31, 32,\n 36, 37, 38, 42, 43, 44, 39, 40, 41, 45, 46, 47, 51, 52, 53, 48, 49,\n 50, 57, 58, 59, 54, 55, 56, 63, 64, 65, 60, 61, 62, 69, 70, 71, 66,\n 67, 68\n ], np.int32)\n\n # sign_flip = np.tile([1, -1, -1], (24)) (with the first 3 kept)\n sign_flip = np.array([ \n #\"\"\" sing_flip all the joints with the first joint kept\"\"\"\n #1, -1, -1, 1, -1, -1, 1, -1, -1, 1, -1, -1, 1, -1, -1, 1, -1,\n #-1, 1, -1, -1, 1, -1, -1, 1, -1, -1, 1, -1, -1, 1, -1, -1, 1,\n #-1, -1, 1, -1, -1, 1, -1, -1, 1, -1, -1, 1, -1, -1, 1, -1, -1,\n #1, -1, -1, 1, -1, -1, 1, -1, -1, 1, -1, -1, 1, -1, -1, 1, -1,\n #-1, 1, -1, -1\n \n #\"\"\" sign_flip all the left/right joints with the others (e.g., spin, neck, etc) kept \"\"\"\n 1, 1, 1, # hip\n 1, -1, -1, 1, -1, -1, \n 1, 1, 1, # spine\n 1, -1, -1, 1, -1, -1, \n 1, 1, 1, # spine1\n 1, -1, -1, 1, -1, -1, \n 1, 1, 1, # spine 2\n 1, -1, -1, 1, -1, -1, \n #1, 1, 1, #NOTE: neck, flip or not ???\n 1, -1, -1, #NOTE: neck, flip or not ???\n 1, -1, -1, 1, -1, -1, \n #1, 1, 1, #NOTE: head flip or not??\n 1, -1, -1, #NOTE: head flip or not??\n 1, -1, -1, 1, -1, -1, 1, -1, -1, 1, -1, -1, 1, -1, -1, 1, -1, -1, 1, -1, -1, 1, -1, -1\n ], dtype=pose.dtype)\n\n new_pose = np.take(pose, swap_inds) * sign_flip\n\n return new_pose\n\n#\"\"\"\ndef reflect_lsp_14_joints3d(joints):\n # Assumes input is 14 x 3 (the LSP skeleton subset of H3.6M)\n swap_inds = np.array([5, 4, 3, 2, 1, 0, 11, 10, 9, 8, 7, 6, 12, 13], np.int32)\n joints_ref = np.take(joints, swap_inds, axis = 0)\n flip_mat = np.array([[-1, 0, 0], [0, 1, 0], [0, 0, 1]], np.float32)\n joints_ref = np.matmul(flip_mat, joints_ref.T).T\n # Assumes all joints3d are mean subtracted\n joints_ref = joints_ref - np.mean(joints_ref, axis=0)\n return joints_ref\n#\"\"\"\n\ndef swap_right_left_joints(joints_2d_or_3d):\n assert joints_2d_or_3d.shape[1] == 24\n # Assumes input is 3 x 24 (the SMPL joints)\n swap_inds = np.array([0, 2, 1, 3, 5, 4, 6, 8, 7, 9, 11,10,12,14,13, 15, 17,16, 19,18,21,20,23,22], np.int32)\n joints_swap = np.take(joints_2d_or_3d, swap_inds, axis = 1)\n return joints_swap", "\"\"\"\nHelpers for tfrecord conversion.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\nimport numpy as np\n\n\nclass ImageCoder(object):\n \"\"\"Helper class that provides TensorFlow image coding utilities.\n Taken from\n https://github.com/tensorflow/models/blob/master/inception/inception/data/build_image_data.py\n \"\"\"\n\n def __init__(self):\n # Create a single Session to run all image coding calls.\n self._sess = tf.Session()\n\n # Initializes function that converts PNG to JPEG data.\n self._png_data = tf.placeholder(dtype=tf.string)\n image = tf.image.decode_png(self._png_data, channels=3)\n self._png_to_jpeg = tf.image.encode_jpeg(\n image, format='rgb', quality=100)\n\n # Initializes function that decodes RGB JPEG data.\n self._decode_jpeg_data = tf.placeholder(dtype=tf.string)\n self._decode_jpeg = tf.image.decode_jpeg(\n self._decode_jpeg_data, channels=3)\n\n self._encode_jpeg_data = tf.placeholder(dtype=tf.uint8)\n self._encode_jpeg = tf.image.encode_jpeg(\n self._encode_jpeg_data, format='rgb')\n \n # png: uint8\n self._decode_png_data = tf.placeholder(dtype=tf.string)\n # the previous value is channels=3 in this code;\n self._decode_png = tf.image.decode_png(self._decode_png_data, channels = 0, \n dtype= tf.uint8)\n \n #NOTE: to decode the PNG depth map;\n # png: uint16\n self._decode_png_uint16_data = tf.placeholder(dtype=tf.string)\n self._decode_png_uint16 = tf.image.decode_png(self._decode_png_uint16_data, channels = 0, \n dtype= tf.uint16)\n \"\"\" here I use channels=1 :\n 0: Use the number of channels in the PNG-encoded image.\n 1: output a grayscale image.\n 3: output an RGB image.\n 4: output an RGBA image.\"\"\"\n\n self._encode_png_data = tf.placeholder(dtype=tf.uint8)\n self._encode_png = tf.image.encode_png(self._encode_png_data)\n\n def png_to_jpeg(self, image_data):\n return self._sess.run(\n self._png_to_jpeg, feed_dict={\n self._png_data: image_data\n })\n\n def decode_jpeg(self, image_data):\n image = self._sess.run(\n self._decode_jpeg, feed_dict={\n self._decode_jpeg_data: image_data\n })\n assert len(image.shape) == 3\n assert image.shape[2] == 3\n return image\n\n def encode_jpeg(self, image):\n image_data = self._sess.run(\n self._encode_jpeg, feed_dict={\n self._encode_jpeg_data: image\n })\n return image_data\n\n def encode_png(self, image):\n image_data = self._sess.run(\n self._encode_png, feed_dict={\n self._encode_png_data: image,\n })\n return image_data\n\n def decode_png(self, image_data):\n image = self._sess.run(\n self._decode_png, feed_dict={\n self._decode_png_data: image_data,\n })\n assert len(image.shape) == 3\n assert image.shape[2] == 3\n return image\n \n def decode_png_uint16(self, image_data):\n image = self._sess.run(\n self._decode_png_uint16, feed_dict={ self._decode_png_uint16_data: image_data,})\n assert len(image.shape) == 3\n assert image.shape[2] == 1\n return image\n\ndef int64_feature(value):\n \"\"\"Wrapper for inserting int64 features into Example proto.\"\"\"\n if not isinstance(value, list) and not isinstance(value, np.ndarray):\n value = [value]\n return tf.train.Feature(int64_list=tf.train.Int64List(value=value))\n\n\ndef float_feature(value):\n \"\"\"Wrapper for inserting float features into Example proto.\"\"\"\n if not isinstance(value, list) and not isinstance(value, np.ndarray):\n value = [value]\n return tf.train.Feature(float_list=tf.train.FloatList(value=value))\n\n\ndef bytes_feature(value):\n \"\"\"Wrapper for inserting bytes features into Example proto.\"\"\"\n return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))\n\n\ndef convert_to_example(image_data, image_path, height, width, label, center):\n \"\"\"Build an Example proto for an image example.\n Args:\n image_data: string, JPEG encoding of RGB image;\n image_path: string, path to this image file\n labels: 3 x 14 joint location + visibility --> This could be 3 x 19\n height, width: integers, image shapes in pixels.\n center: 2 x 1 center of the tight bbox\n Returns:\n Example proto\n \"\"\"\n from os.path import basename\n\n image_format = 'JPEG'\n add_face = False\n if label.shape[1] == 19:\n add_face = True\n # Split and save facepts on it's own.\n face_pts = label[:, 14:]\n label = label[:, :14]\n\n feat_dict = {\n 'image/height': int64_feature(height),\n 'image/width': int64_feature(width),\n 'image/center': int64_feature(center.astype(np.int)),\n 'image/x': float_feature(label[0, :].astype(np.float32)),\n 'image/y': float_feature(label[1, :].astype(np.float32)),\n 'image/visibility': int64_feature(label[2, :].astype(np.int)),\n 'image/format': bytes_feature(tf.compat.as_bytes(image_format)),\n 'image/filename': bytes_feature(\n tf.compat.as_bytes(basename(image_path))),\n 'image/encoded': bytes_feature(tf.compat.as_bytes(image_data)),\n }\n if add_face:\n # 3 x 5\n feat_dict.update({\n 'image/face_pts':\n float_feature(face_pts.ravel().astype(np.float32))\n })\n\n example = tf.train.Example(features=tf.train.Features(feature=feat_dict))\n\n return example\n\n# added by CCJ:\n# convert to example with depth data;\ndef convert_to_example_wdepth(depth_binary, image_data, image_path, height, width, label, center):\n \"\"\"Build an Example proto for an image example.\n Args:\n image_data: string, PNG encoding of RGB image;\n image_path: string, path to this image file\n labels: 3 x 14 joint location + visibility --> This could be 3 x 19\n height, width: integers, image shapes in pixels.\n center: 2 x 1 center of the tight bbox\n Returns:\n Example proto\n \"\"\"\n from os.path import basename\n\n image_format = 'JPEG'\n add_face = False\n if label.shape[1] == 19:\n add_face = True\n # Split and save facepts on it's own.\n face_pts = label[:, 14:]\n label = label[:, :14]\n\n feat_dict = {\n 'image/height': int64_feature(height),\n 'image/width': int64_feature(width),\n 'image/center': int64_feature(center.astype(np.int)),\n 'image/x': float_feature(label[0, :].astype(np.float32)),\n 'image/y': float_feature(label[1, :].astype(np.float32)),\n 'image/visibility': int64_feature(label[2, :].astype(np.int)),\n 'image/format': bytes_feature(tf.compat.as_bytes(image_format)),\n 'image/filename': bytes_feature(\n tf.compat.as_bytes(basename(image_path))),\n 'image/encoded': bytes_feature(tf.compat.as_bytes(image_data)),\n 'depth/raw': bytes_feature(tf.compat.as_bytes(depth_binary)),\n 'depth/size': bytes_feature(tf.compat.as_bytes(np.array([height, width, 1], np.int32).tobytes())),\n }\n if add_face:\n # 3 x 5\n feat_dict.update({\n 'image/face_pts':\n float_feature(face_pts.ravel().astype(np.float32))\n })\n\n example = tf.train.Example(features=tf.train.Features(feature=feat_dict))\n\n return example\n\n# added by CCJ on 6/13/2019;\ndef convert_to_example_wmosh_wdepth(depth_binary, image_data, image_path, height, width, label, \n center, gt3d, pose, shape, scale_factors, start_pt, cam, gender_vect):\n\n \"\"\"Build an Example proto for an image example.\n Args:\n image_data: string, JPEG encoding of RGB image;\n image_path: string, path to this image file\n label: 3 x 14 joint location + visibility\n height, width: integers, image shapes in pixels.\n center: 2 x 1 center of the tight bbox\n gt3d: 14x3 3D joint locations\n scale_factors: 2 x 1, scale factor used to scale image.\n start_pt: the left corner used to crop the _scaled_ image to 300x300\n cam: (3,), [f, px, py] intrinsic camera parameters.\n gender: string, \"male\", \"female\", or \"neutral\" otherwise; # newly added on 07/19/2019;\n Returns:\n Example proto\n \"\"\"\n from os.path import basename\n image_format = 'JPEG'\n if label.shape[0] != 3:\n label = label.T\n if label.shape[1] > 14:\n print('This shouldnt be happening')\n import ipdb\n ipdb.set_trace()\n if pose is None:\n has_3d = 0\n # Use -1 to save.\n pose = -np.ones(72)\n shape = -np.ones(10)\n else:\n has_3d = 1\n\n example = tf.train.Example(\n features=tf.train.Features(feature={\n 'image/height':\n int64_feature(height),\n 'image/width':\n int64_feature(width),\n 'image/center':\n int64_feature(center.astype(np.int)),\n 'image/x':\n float_feature(label[0, :].astype(np.float32)),\n 'image/y':\n float_feature(label[1, :].astype(np.float32)),\n 'image/visibility':\n int64_feature(label[2, :].astype(np.int)),\n 'image/format':\n bytes_feature(tf.compat.as_bytes(image_format)),\n 'image/filename':\n bytes_feature(tf.compat.as_bytes(basename(image_path))),\n 'image/encoded':\n bytes_feature(tf.compat.as_bytes(image_data)),\n \n # added by CCJ;\n 'depth/raw': \n bytes_feature(tf.compat.as_bytes(depth_binary)),\n 'depth/size': \n bytes_feature(tf.compat.as_bytes(np.array([height, width, 1], np.int32).tobytes())),\n \n 'mosh/pose':\n float_feature(pose.astype(np.float32)),\n 'mosh/shape':\n float_feature(shape.astype(np.float32)),\n 'smpl/gender': # added for smpl gender info;\n float_feature(gender_vect.astype(np.float32)),\n #NOTE: comment added by CCJ:\n # (x,y,z) values of 3d joints in camera coordinate system;\n 'mosh/gt3d': \n float_feature(gt3d.ravel().astype(np.float32)),\n 'meta/scale_factors':\n float_feature(np.array(scale_factors).astype(np.float32)),\n 'meta/crop_pt':\n int64_feature(start_pt.astype(np.int)),\n 'meta/has_3d': # pose and shape of smpl modle of 3d joints;\n int64_feature(has_3d),\n 'image/cam':\n float_feature(cam.astype(np.float32)),\n }))\n\n return example\n\n\n# save variables to h5py files for evaluation, added by CCJ on 8/18/2019;\ndef convert_to_h5_wmosh_wdepth(depth_data, image_data, image_path, height, width, label, \n center, gt3d, pose, shape, scale_factors, start_pt, cam, gender_vect):\n\n \"\"\"Build an Example proto for an image example.\n Args:\n image_data: string, JPEG encoding of RGB image;\n image_path: string, path to this image file\n label: 3 x 14 joint location + visibility\n height, width: integers, image shapes in pixels.\n center: 2 x 1 center of the tight bbox\n gt3d: 14x3 3D joint locations\n scale_factors: 2 x 1, scale factor used to scale image.\n start_pt: the left corner used to crop the _scaled_ image to 300x300\n cam: (3,), [f, px, py] intrinsic camera parameters.\n gender: string, \"male\", \"female\", or \"neutral\" otherwise; # newly added on 07/19/2019;\n Returns:\n Example proto\n \"\"\"\n \n from os.path import basename\n if label.shape[0] != 3:\n label = label.T\n if label.shape[1] > 14:\n print('This shouldnt be happening')\n import ipdb\n ipdb.set_trace()\n if pose is None:\n has_3d = 0\n # Use -1 to save.\n pose = -np.ones(72)\n shape = -np.ones(10)\n else:\n has_3d = 1\n\n example = {\n 'image_height': height,\n 'image_width': width,\n 'image_center': center.astype(np.int),\n 'image_x': label[0, :].astype(np.float32),\n 'image_y': label[1, :].astype(np.float32),\n 'image_visibility': label[2, :].astype(np.int),\n 'image_filename': basename(image_path),\n 'image_img_rgb': image_data,\n \n # added by CCJ;\n 'depth_data': depth_data,\n\n 'mosh_pose': pose.astype(np.float32),\n 'mosh_shape': shape.astype(np.float32),\n 'smpl_gender': gender_vect.astype(np.float32),\n 'mosh_gt3d': gt3d.ravel().astype(np.float32),\n 'meta_scale_factors': np.array(scale_factors).astype(np.float32),\n 'meta_crop_pt':start_pt.astype(np.int),\n # pose and shape of smpl modle of 3d joints;\n 'meta_has_3d': has_3d,\n 'image_cam': cam.astype(np.float32),\n }\n \n return example\n\ndef convert_to_example_wmosh(image_data, image_path, height, width, label,\n center, gt3d, pose, shape, scale_factors,\n start_pt, cam):\n \"\"\"Build an Example proto for an image example.\n Args:\n image_data: string, JPEG encoding of RGB image;\n image_path: string, path to this image file\n labels: 3 x 14 joint location + visibility\n height, width: integers, image shapes in pixels.\n center: 2 x 1 center of the tight bbox\n gt3d: 14x3 3D joint locations\n scale_factors: 2 x 1, scale factor used to scale image.\n start_pt: the left corner used to crop the _scaled_ image to 300x300\n cam: (3,), [f, px, py] intrinsic camera parameters.\n Returns:\n Example proto\n \"\"\"\n from os.path import basename\n image_format = 'JPEG'\n if label.shape[0] != 3:\n label = label.T\n if label.shape[1] > 14:\n print('This shouldnt be happening')\n import ipdb\n ipdb.set_trace()\n if pose is None:\n has_3d = 0\n # Use -1 to save.\n pose = -np.ones(72)\n shape = -np.ones(10)\n else:\n has_3d = 1\n \n assert(gt3d.shape[1] == 3)\n example = tf.train.Example(\n features=tf.train.Features(feature={\n 'image/height':\n int64_feature(height),\n 'image/width':\n int64_feature(width),\n 'image/center':\n int64_feature(center.astype(np.int)),\n 'image/x':\n float_feature(label[0, :].astype(np.float32)),\n 'image/y':\n float_feature(label[1, :].astype(np.float32)),\n 'image/visibility':\n int64_feature(label[2, :].astype(np.int)),\n 'image/format':\n bytes_feature(tf.compat.as_bytes(image_format)),\n 'image/filename':\n bytes_feature(tf.compat.as_bytes(basename(image_path))),\n 'image/encoded':\n bytes_feature(tf.compat.as_bytes(image_data)),\n 'mosh/pose':\n float_feature(pose.astype(np.float32)),\n 'mosh/shape':\n float_feature(shape.astype(np.float32)),\n 'mosh/gt3d': # (x,y,z) values of 3d joints;\n float_feature(gt3d.ravel().astype(np.float32)),\n 'meta/scale_factors':\n float_feature(np.array(scale_factors).astype(np.float32)),\n 'meta/crop_pt':\n int64_feature(start_pt.astype(np.int)),\n 'meta/has_3d': # pose and shape of smpl modle of 3d joints;\n int64_feature(has_3d),\n 'image/cam': # cam: (3,), [f, px, py] intrinsic camera parameters.\n float_feature(cam.astype(np.float32)),\n }))\n\n return example\n\n\ndef resize_img(img, scale_factor):\n import cv2\n import numpy as np\n new_size = (np.floor(np.array(img.shape[0:2]) * scale_factor)).astype(int)\n new_img = cv2.resize(img, (new_size[1], new_size[0]))\n # This is scale factor of [height, width] i.e. [y, x]\n actual_factor = [\n new_size[0] / float(img.shape[0]), new_size[1] / float(img.shape[1])\n ]\n return new_img, actual_factor\n\n\ndef read_images_from_tfrecords(tf_path, img_size=224, sess=None):\n \"\"\"\n Returns image, kp, and gt3d from the tf_paths\n\n This returns a preprocessed image, cropped around img_size.\n \"\"\"\n from time import time\n from os.path import exists\n if not exists(tf_path):\n print('%s doesnt exist!' % tf_path)\n exit(1)\n\n if sess is None:\n sess = tf.Session()\n\n t0 = time()\n all_images, all_kps, all_gt3ds = [], [], []\n\n itr = 0\n\n # Decode op graph\n image_data_pl = tf.placeholder(dtype=tf.string)\n decode_op = tf.image.decode_jpeg(image_data_pl)\n\n for serialized_ex in tf.python_io.tf_record_iterator(tf_path):\n example = tf.train.Example()\n example.ParseFromString(serialized_ex)\n image_data = example.features.feature['image/encoded'].bytes_list.value[0]\n image = sess.run(decode_op, feed_dict={image_data_pl: image_data})\n\n x = example.features.feature['image/x'].float_list.value\n y = example.features.feature['image/y'].float_list.value\n vis = example.features.feature['image/visibility'].int64_list.value\n center = example.features.feature['image/center'].int64_list.value\n\n x = np.array(x)\n y = np.array(y)\n vis = np.array(vis, dtype='bool')\n center = np.array(center)\n\n # Crop img_size.\n # Pad in case.\n margin = int(img_size/2)\n image_pad = np.pad(image, ((margin,), (margin,), (0,)), mode='edge')\n\n # figure out starting point\n start_pt = center\n end_pt = center + 2*margin\n\n x_crop = x + margin - start_pt[0]\n y_crop = y + margin - start_pt[1]\n kp_crop = np.vstack([x_crop, y_crop])\n kp_final = 2 * (kp_crop / img_size) - 1\n kp_final = np.vstack((vis * kp_final, vis)).T\n # crop:\n crop = image_pad[start_pt[1]:end_pt[1], start_pt[0]:end_pt[0], :]\n \n # Normalize image to [-1, 1]\n crop = 2 * ((crop / 255.) - 0.5)\n\n # Note: This says mosh but gt3d is the gt H3.6M joints & not from mosh.\n gt3d = example.features.feature['mosh/gt3d'].float_list.value\n gt3d = np.array(gt3d).reshape(-1, 3)\n\n all_images.append(crop)\n all_kps.append(kp_final)\n all_gt3ds.append(gt3d)\n\n itr += 1\n\n images = np.stack(all_images)\n kps = np.stack(all_kps)\n gt3ds = np.stack(all_gt3ds)\n\n print('Read %d images, %g secs' % (images.shape[0], time()-t0))\n\n return images, kps, gt3ds\n\n\n# added by CCJ on 7/22/2019;\ndef convert_to_example_smpl_pose_joints3d_pairs(\n image_path, joints3d_smpl, trans, pose, shape, gender_vect):\n\n \"\"\"Build an Example proto for an image example.\n Args:\n image_path: string, path to this image file\n joints3d_smpl: 24x3 3D joint locations inferred from smpl model, given the grouhd truth pose and shape as input;\n trans: translation between root_gt in surreal dataset and root_gt of smpl model;\n gender: \\in R^3, 3-d vector for:\n \"female\": [1.0, 0.0, .0], \n \"male\": [.0, 1.0, .0], \n \"nuetral\": [.0, 0.0, 1.0];\n pose: in shape (72,)\n shape: in shape (10,)\n\n Returns:\n Example proto\n \"\"\"\n from os.path import basename\n assert(joints3d_smpl.shape[1] == 3)\n example = tf.train.Example(\n features=tf.train.Features(feature={\n 'image/filename':\n bytes_feature(tf.compat.as_bytes(basename(image_path))),\n 'mosh/pose':\n float_feature(pose.astype(np.float32)),\n 'mosh/shape':\n float_feature(shape.astype(np.float32)),\n 'smpl/gender': # added for smpl gender info;\n float_feature(gender_vect.astype(np.float32)),\n 'smpl/trans':\n float_feature(trans.astype(np.float32)),\n #NOTE: comment added by CCJ:\n # (x,y,z) values of 3d joints in camera coordinate system;\n 'mosh/joints3d_from_smpl':\n # np.ravel() : returns contiguous flattened array\n float_feature(joints3d_smpl.ravel().astype(np.float32)),\n }))\n\n return example\n\n \n# added by CCJ on 8/01/2019;\n\"\"\" 14 lsp joints3d \"\"\"\ndef convert_to_example_smpl_pose_lsp_joints3d_pairs(\n image_path, lsp_joints3d_smpl, root, pose, shape):\n\n \"\"\"Build an Example proto for an image example.\n Args:\n image_path: string, path to this image file\n lsp_joints3d_smpl: 14x3 3D joint locations inferred from smpl model, \n given the grouhd truth pose and shape as input. Also,\n the joints3d is the distance w.r.t. the root joint.\n That is, joints3d = joints3d - root; \n So we also keep the root info\n root: the root joint of 24-smpl joints;\n pose: in shape (72,)\n shape: in shape (10,)\n\n Returns:\n Example proto\n \"\"\"\n from os.path import basename\n assert(lsp_joints3d_smpl.shape[1] == 3 and lsp_joints3d_smpl.shape[0] == 14)\n example = tf.train.Example(\n features=tf.train.Features(feature={\n 'image/filename':\n bytes_feature(tf.compat.as_bytes(basename(image_path))),\n 'mosh/pose':\n float_feature(pose.astype(np.float32)),\n 'mosh/shape':\n float_feature(shape.astype(np.float32)),\n #'smpl/gender': # added for smpl gender info;\n #float_feature(gender_vect.astype(np.float32)),\n 'smpl/root':\n float_feature(root.astype(np.float32)),\n #NOTE: comment added by CCJ:\n # (x,y,z) values of 3d joints in camera coordinate system;\n 'mosh/lsp_joints3d_from_smpl':\n # np.ravel() : returns contiguous flattened array\n float_feature(lsp_joints3d_smpl.ravel().astype(np.float32)),\n }))\n\n return example" ]
[ [ "numpy.arange", "tensorflow.constant", "tensorflow.gather_nd", "tensorflow.Session" ], [ "torch.nn.Sequential", "torch.mean", "torch.load", "torch.nn.init.constant_", "torch.nn.Conv2d", "torch.from_numpy", "numpy.transpose", "torch.flatten", "torch.nn.MaxPool2d", "torch.nn.Linear", "torch.nn.BatchNorm2d", "numpy.load", "torch.nn.ReLU", "torch.nn.init.kaiming_normal_", "torch.nn.functional.pad", "torch.save" ], [ "numpy.dot", "matplotlib.pyplot.imshow", "numpy.take", "numpy.min", "numpy.matmul", "numpy.linalg.norm", "matplotlib.pyplot.savefig", "numpy.ones", "numpy.concatenate", "numpy.max", "numpy.mean", "numpy.array", "numpy.zeros", "numpy.float", "matplotlib.pyplot.figure" ], [ "tensorflow.train.Int64List", "tensorflow.image.encode_jpeg", "numpy.pad", "tensorflow.train.Example", "tensorflow.image.decode_png", "tensorflow.placeholder", "numpy.stack", "tensorflow.image.encode_png", "tensorflow.compat.as_bytes", "numpy.ones", "tensorflow.Session", "tensorflow.train.FloatList", "tensorflow.python_io.tf_record_iterator", "tensorflow.train.BytesList", "tensorflow.train.Features", "numpy.array", "numpy.vstack", "tensorflow.image.decode_jpeg" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.5", "1.7", "0.12", "1.0", "1.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
agarwalrounak/optuna
[ "9331374a2460da067a6922e4ea09dd4706f3d950", "b5fd0439dc33c94c06251974b8cb023a3f9bccc7" ]
[ "tests/storages_tests/rdb_tests/test_with_server.py", "optuna/visualization/matplotlib/_contour.py" ]
[ "from multiprocessing import Pool\nimport os\nfrom typing import Sequence\nfrom typing import Tuple\n\nimport numpy as np\nimport pytest\n\nimport optuna\n\n\n_STUDY_NAME = \"_test_multiprocess\"\n\n\ndef f(x: float, y: float) -> float:\n return (x - 3) ** 2 + y\n\n\ndef objective(trial: optuna.Trial) -> float:\n x = trial.suggest_float(\"x\", -10, 10)\n y = trial.suggest_float(\"y\", -10, 10)\n trial.report(x, 0)\n trial.report(y, 1)\n trial.set_user_attr(\"x\", x)\n trial.set_system_attr(\"y\", y)\n return f(x, y)\n\n\ndef run_optimize(args: Tuple[str, str]) -> None:\n study_name = args[0]\n storage_url = args[1]\n # Create a study\n study = optuna.load_study(study_name=study_name, storage=storage_url)\n # Run optimization\n study.optimize(objective, n_trials=20)\n\n\[email protected]\ndef storage_url() -> str:\n if \"TEST_DB_URL\" not in os.environ:\n pytest.skip(\"This test requires TEST_DB_URL.\")\n storage_url = os.environ[\"TEST_DB_URL\"]\n try:\n optuna.study.delete_study(_STUDY_NAME, storage_url)\n except KeyError:\n pass\n return storage_url\n\n\ndef _check_trials(trials: Sequence[optuna.trial.FrozenTrial]) -> None:\n # Check trial states.\n assert all(trial.state == optuna.trial.TrialState.COMPLETE for trial in trials)\n\n # Check trial values and params.\n assert all(\"x\" in trial.params for trial in trials)\n assert all(\"y\" in trial.params for trial in trials)\n assert all(\n np.isclose(\n np.asarray([trial.value for trial in trials]),\n [f(trial.params[\"x\"], trial.params[\"y\"]) for trial in trials],\n atol=1e-4,\n ).tolist()\n )\n\n # Check intermediate values.\n assert all(len(trial.intermediate_values) == 2 for trial in trials)\n assert all(trial.params[\"x\"] == trial.intermediate_values[0] for trial in trials)\n assert all(trial.params[\"y\"] == trial.intermediate_values[1] for trial in trials)\n\n # Check attrs.\n assert all(\n np.isclose(\n [trial.user_attrs[\"x\"] for trial in trials],\n [trial.params[\"x\"] for trial in trials],\n atol=1e-4,\n ).tolist()\n )\n assert all(\n np.isclose(\n [trial.system_attrs[\"y\"] for trial in trials],\n [trial.params[\"y\"] for trial in trials],\n atol=1e-4,\n ).tolist()\n )\n\n\ndef test_loaded_trials(storage_url: str) -> None:\n # Please create the tables by placing this function before the multi-process tests.\n\n N_TRIALS = 20\n study = optuna.create_study(study_name=_STUDY_NAME, storage=storage_url)\n # Run optimization\n study.optimize(objective, n_trials=N_TRIALS)\n\n trials = study.trials\n assert len(trials) == N_TRIALS\n\n _check_trials(trials)\n\n # Create a new study to confirm the study can load trial properly.\n loaded_study = optuna.load_study(study_name=_STUDY_NAME, storage=storage_url)\n _check_trials(loaded_study.trials)\n\n\ndef test_multiprocess(storage_url: str) -> None:\n n_workers = 8\n study_name = _STUDY_NAME\n optuna.create_study(storage=storage_url, study_name=study_name)\n with Pool(n_workers) as pool:\n pool.map(run_optimize, [(study_name, storage_url)] * n_workers)\n\n study = optuna.load_study(study_name=study_name, storage=storage_url)\n\n trials = study.trials\n assert len(trials) == n_workers * 20\n\n _check_trials(trials)\n", "from collections import defaultdict\nfrom typing import Callable\nfrom typing import DefaultDict\nfrom typing import List\nfrom typing import Optional\nfrom typing import Tuple\nfrom typing import Union\n\nimport numpy as np\nfrom scipy.interpolate import griddata\n\nfrom optuna._experimental import experimental\nfrom optuna.logging import get_logger\nfrom optuna.study import Study\nfrom optuna.study import StudyDirection\nfrom optuna.trial import FrozenTrial\nfrom optuna.trial import TrialState\nfrom optuna.visualization._utils import _check_plot_args\nfrom optuna.visualization.matplotlib._matplotlib_imports import _imports\nfrom optuna.visualization.matplotlib._utils import _is_categorical\nfrom optuna.visualization.matplotlib._utils import _is_log_scale\n\n\nif _imports.is_successful():\n from optuna.visualization.matplotlib._matplotlib_imports import Axes\n from optuna.visualization.matplotlib._matplotlib_imports import Colormap\n from optuna.visualization.matplotlib._matplotlib_imports import ContourSet\n from optuna.visualization.matplotlib._matplotlib_imports import plt\n\n_logger = get_logger(__name__)\n\n\n@experimental(\"2.2.0\")\ndef plot_contour(\n study: Study,\n params: Optional[List[str]] = None,\n *,\n target: Optional[Callable[[FrozenTrial], float]] = None,\n target_name: str = \"Objective Value\",\n) -> \"Axes\":\n \"\"\"Plot the parameter relationship as contour plot in a study with Matplotlib.\n\n Note that, if a parameter contains missing values, a trial with missing values is not plotted.\n\n .. seealso::\n Please refer to :func:`optuna.visualization.plot_contour` for an example.\n\n Warnings:\n Output figures of this Matplotlib-based\n :func:`~optuna.visualization.matplotlib.plot_contour` function would be different from\n those of the Plotly-based :func:`~optuna.visualization.plot_contour`.\n\n Example:\n\n The following code snippet shows how to plot the parameter relationship as contour plot.\n\n .. plot::\n\n import optuna\n\n\n def objective(trial):\n x = trial.suggest_float(\"x\", -100, 100)\n y = trial.suggest_categorical(\"y\", [-1, 0, 1])\n return x ** 2 + y\n\n\n sampler = optuna.samplers.TPESampler(seed=10)\n study = optuna.create_study(sampler=sampler)\n study.optimize(objective, n_trials=30)\n\n optuna.visualization.matplotlib.plot_contour(study, params=[\"x\", \"y\"])\n\n Args:\n study:\n A :class:`~optuna.study.Study` object whose trials are plotted for their target values.\n params:\n Parameter list to visualize. The default is all parameters.\n target:\n A function to specify the value to display. If it is :obj:`None` and ``study`` is being\n used for single-objective optimization, the objective values are plotted.\n\n .. note::\n Specify this argument if ``study`` is being used for multi-objective optimization.\n target_name:\n Target's name to display on the color bar.\n\n Returns:\n A :class:`matplotlib.axes.Axes` object.\n\n Raises:\n :exc:`ValueError`:\n If ``target`` is :obj:`None` and ``study`` is being used for multi-objective\n optimization.\n \"\"\"\n\n _imports.check()\n _check_plot_args(study, target, target_name)\n _logger.warning(\n \"Output figures of this Matplotlib-based `plot_contour` function would be different from \"\n \"those of the Plotly-based `plot_contour`.\"\n )\n return _get_contour_plot(study, params, target, target_name)\n\n\ndef _get_contour_plot(\n study: Study,\n params: Optional[List[str]] = None,\n target: Optional[Callable[[FrozenTrial], float]] = None,\n target_name: str = \"Objective Value\",\n) -> \"Axes\":\n # Calculate basic numbers for plotting.\n trials = [trial for trial in study.trials if trial.state == TrialState.COMPLETE]\n\n if len(trials) == 0:\n _logger.warning(\"Your study does not have any completed trials.\")\n _, ax = plt.subplots()\n return ax\n\n all_params = {p_name for t in trials for p_name in t.params.keys()}\n\n if params is None:\n sorted_params = sorted(list(all_params))\n elif len(params) <= 1:\n _logger.warning(\"The length of params must be greater than 1.\")\n _, ax = plt.subplots()\n return ax\n else:\n for input_p_name in params:\n if input_p_name not in all_params:\n raise ValueError(\"Parameter {} does not exist in your study.\".format(input_p_name))\n sorted_params = sorted(list(set(params)))\n n_params = len(sorted_params)\n\n plt.style.use(\"ggplot\") # Use ggplot style sheet for similar outputs to plotly.\n if n_params == 2:\n # Set up the graph style.\n fig, axs = plt.subplots()\n axs.set_title(\"Contour Plot\")\n cmap = _set_cmap(study, target)\n contour_point_num = 1000\n\n # Prepare data and draw contour plots.\n if params:\n x_param = params[0]\n y_param = params[1]\n else:\n x_param = sorted_params[0]\n y_param = sorted_params[1]\n cs = _generate_contour_subplot(\n trials, x_param, y_param, axs, cmap, contour_point_num, target\n )\n if isinstance(cs, ContourSet):\n axcb = fig.colorbar(cs)\n axcb.set_label(target_name)\n else:\n # Set up the graph style.\n fig, axs = plt.subplots(n_params, n_params)\n fig.suptitle(\"Contour Plot\")\n cmap = _set_cmap(study, target)\n contour_point_num = 100\n\n # Prepare data and draw contour plots.\n cs_list = []\n for x_i, x_param in enumerate(sorted_params):\n for y_i, y_param in enumerate(sorted_params):\n ax = axs[y_i, x_i]\n cs = _generate_contour_subplot(\n trials, x_param, y_param, ax, cmap, contour_point_num, target\n )\n if isinstance(cs, ContourSet):\n cs_list.append(cs)\n if cs_list:\n axcb = fig.colorbar(cs_list[0], ax=axs)\n axcb.set_label(target_name)\n\n return axs\n\n\ndef _set_cmap(study: Study, target: Optional[Callable[[FrozenTrial], float]]) -> \"Colormap\":\n cmap = \"Blues_r\" if target is None and study.direction == StudyDirection.MINIMIZE else \"Blues\"\n return plt.get_cmap(cmap)\n\n\ndef _convert_categorical2int(values: List[str]) -> Tuple[List[int], List[str], List[int]]:\n vocab = defaultdict(lambda: len(vocab)) # type: DefaultDict[str, int]\n [vocab[v] for v in sorted(values)]\n values_converted = [vocab[v] for v in values]\n vocab_item_sorted = sorted(vocab.items(), key=lambda x: x[1])\n cat_param_labels = [v[0] for v in vocab_item_sorted]\n cat_param_pos = [v[1] for v in vocab_item_sorted]\n\n return values_converted, cat_param_labels, cat_param_pos\n\n\ndef _calculate_griddata(\n trials: List[FrozenTrial],\n x_param: str,\n x_indices: List[Union[str, int, float]],\n y_param: str,\n y_indices: List[Union[str, int, float]],\n contour_point_num: int,\n target: Optional[Callable[[FrozenTrial], float]],\n) -> Tuple[\n np.ndarray,\n np.ndarray,\n np.ndarray,\n List[Union[int, float]],\n List[Union[int, float]],\n List[Union[int, float]],\n List[Union[int, float]],\n List[int],\n List[str],\n List[int],\n List[str],\n int,\n int,\n]:\n\n # Extract values for x, y, z axes from each trail.\n x_values = []\n y_values = []\n z_values = []\n for trial in trials:\n if x_param not in trial.params or y_param not in trial.params:\n continue\n x_values.append(trial.params[x_param])\n y_values.append(trial.params[y_param])\n\n if target is None:\n value = trial.value\n else:\n value = target(trial)\n\n if isinstance(value, int):\n value = float(value)\n elif not isinstance(value, float):\n raise ValueError(\n \"Trial{} has COMPLETE state, but its target value is non-numeric.\".format(\n trial.number\n )\n )\n z_values.append(value)\n\n # Return empty values when x or y has no value.\n if len(x_values) == 0 or len(y_values) == 0:\n return (\n np.array([]),\n np.array([]),\n np.array([]),\n x_values,\n y_values,\n [],\n [],\n [],\n [],\n [],\n [],\n 0,\n 0,\n )\n\n # Add dummy values for grid data calculation when a parameter has one unique value.\n x_values_dummy = []\n y_values_dummy = []\n if len(set(x_values)) == 1:\n x_values_dummy = [x for x in x_indices if x not in x_values]\n x_values = x_values + x_values_dummy * len(x_values)\n y_values = y_values + (y_values * len(x_values_dummy))\n z_values = z_values + (z_values * len(x_values_dummy))\n if len(set(y_values)) == 1:\n y_values_dummy = [y for y in y_indices if y not in y_values]\n y_values = y_values + y_values_dummy * len(y_values)\n x_values = x_values + (x_values * len(y_values_dummy))\n z_values = z_values + (z_values * len(y_values_dummy))\n\n # Convert categorical values to int.\n cat_param_labels_x = [] # type: List[str]\n cat_param_pos_x = [] # type: List[int]\n cat_param_labels_y = [] # type: List[str]\n cat_param_pos_y = [] # type: List[int]\n if _is_categorical(trials, x_param):\n x_values = [str(x) for x in x_values]\n (\n x_values,\n cat_param_labels_x,\n cat_param_pos_x,\n ) = _convert_categorical2int(x_values)\n if _is_categorical(trials, y_param):\n y_values = [str(y) for y in y_values]\n (\n y_values,\n cat_param_labels_y,\n cat_param_pos_y,\n ) = _convert_categorical2int(y_values)\n\n # Calculate min and max of x and y.\n x_values_min = min(x_values)\n x_values_max = max(x_values)\n y_values_min = min(y_values)\n y_values_max = max(y_values)\n\n # Calculate grid data points.\n # For x and y, create 1-D array of evenly spaced coordinates on linear or log scale.\n xi = np.array([])\n yi = np.array([])\n zi = np.array([])\n if x_param != y_param:\n if _is_log_scale(trials, x_param):\n xi = np.logspace(np.log10(x_values_min), np.log10(x_values_max), contour_point_num)\n else:\n xi = np.linspace(x_values_min, x_values_max, contour_point_num)\n if _is_log_scale(trials, y_param):\n yi = np.logspace(np.log10(y_values_min), np.log10(y_values_max), contour_point_num)\n else:\n yi = np.linspace(y_values_min, y_values_max, contour_point_num)\n\n # Interpolate z-axis data on a grid with cubic interpolator.\n # TODO(ytknzw): Implement Plotly-like interpolation algorithm.\n zi = griddata(\n np.column_stack((x_values, y_values)),\n z_values,\n (xi[None, :], yi[:, None]),\n method=\"cubic\",\n )\n\n return (\n xi,\n yi,\n zi,\n x_values,\n y_values,\n [x_values_min, x_values_max],\n [y_values_min, y_values_max],\n cat_param_pos_x,\n cat_param_labels_x,\n cat_param_pos_y,\n cat_param_labels_y,\n len(x_values_dummy),\n len(y_values_dummy),\n )\n\n\ndef _generate_contour_subplot(\n trials: List[FrozenTrial],\n x_param: str,\n y_param: str,\n ax: \"Axes\",\n cmap: \"Colormap\",\n contour_point_num: int,\n target: Optional[Callable[[FrozenTrial], float]],\n) -> \"ContourSet\":\n\n x_indices = sorted(list({t.params[x_param] for t in trials if x_param in t.params}))\n y_indices = sorted(list({t.params[y_param] for t in trials if y_param in t.params}))\n if len(x_indices) < 2:\n _logger.warning(\"Param {} unique value length is less than 2.\".format(x_param))\n return ax\n if len(y_indices) < 2:\n _logger.warning(\"Param {} unique value length is less than 2.\".format(y_param))\n return ax\n\n (\n xi,\n yi,\n zi,\n x_values,\n y_values,\n x_values_range,\n y_values_range,\n x_cat_param_pos,\n x_cat_param_label,\n y_cat_param_pos,\n y_cat_param_label,\n x_values_dummy_count,\n y_values_dummy_count,\n ) = _calculate_griddata(\n trials, x_param, x_indices, y_param, y_indices, contour_point_num, target\n )\n cs = None\n ax.set(xlabel=x_param, ylabel=y_param)\n if len(zi) > 0:\n ax.set_xlim(x_values_range[0], x_values_range[1])\n ax.set_ylim(y_values_range[0], y_values_range[1])\n ax.set(xlabel=x_param, ylabel=y_param)\n if _is_log_scale(trials, x_param):\n ax.set_xscale(\"log\")\n if _is_log_scale(trials, y_param):\n ax.set_yscale(\"log\")\n if x_param != y_param:\n # Contour the gridded data.\n ax.contour(xi, yi, zi, 15, linewidths=0.5, colors=\"k\")\n cs = ax.contourf(xi, yi, zi, 15, cmap=cmap)\n # Plot data points.\n if x_values_dummy_count > 0:\n x_org_len = int(len(x_values) / (x_values_dummy_count + 1))\n y_org_len = int(len(y_values) / (x_values_dummy_count + 1))\n elif y_values_dummy_count > 0:\n x_org_len = int(len(x_values) / (y_values_dummy_count + 1))\n y_org_len = int(len(y_values) / (y_values_dummy_count + 1))\n else:\n x_org_len = len(x_values)\n y_org_len = len(x_values)\n ax.scatter(\n x_values[:x_org_len],\n y_values[:y_org_len],\n marker=\"o\",\n c=\"black\",\n s=20,\n edgecolors=\"grey\",\n )\n if x_cat_param_pos:\n ax.set_xticks(x_cat_param_pos)\n ax.set_xticklabels(x_cat_param_label)\n if y_cat_param_pos:\n ax.set_yticks(y_cat_param_pos)\n ax.set_yticklabels(y_cat_param_label)\n ax.label_outer()\n return cs\n" ]
[ [ "numpy.asarray", "numpy.isclose" ], [ "numpy.log10", "numpy.array", "numpy.linspace", "numpy.column_stack" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
chunzhang-hub/PaddleHub
[ "9a3b23295947e22149cc85c17cb4cf23c03f9e06", "9a3b23295947e22149cc85c17cb4cf23c03f9e06", "9a3b23295947e22149cc85c17cb4cf23c03f9e06", "9a3b23295947e22149cc85c17cb4cf23c03f9e06", "9a3b23295947e22149cc85c17cb4cf23c03f9e06", "9a3b23295947e22149cc85c17cb4cf23c03f9e06" ]
[ "modules/text/language_model/lda_webpage/vose_alias.py", "modules/image/semantic_segmentation/humanseg_mobile/module.py", "modules/text/language_model/lda_webpage/semantic_matching.py", "modules/image/semantic_segmentation/humanseg_mobile/data_feed.py", "modules/image/object_detection/ssd_vgg16_512_coco2017/processor.py", "modules/image/object_detection/retinanet_resnet50_fpn_coco2017/retina_head.py" ]
[ "import os\n\nimport numpy as np\nfrom paddlehub.common.logger import logger\n\nfrom lda_webpage.util import rand, rand_k\n\n\nclass VoseAlias(object):\n \"\"\"Vose's Alias Method.\n \"\"\"\n\n def __init__(self):\n self.__alias = None\n self.__prob = None # np.array\n\n def initialize(self, distribution):\n \"\"\"Initialize the alias table according to the input distribution\n Arg:\n distribution: Numpy array.\n \"\"\"\n size = distribution.shape[0]\n self.__alias = np.zeros(size, dtype=np.int64)\n self.__prob = np.zeros(size)\n sum_ = np.sum(distribution)\n p = distribution / sum_ * size # Scale up probability.\n large, small = [], []\n for i, p_ in enumerate(p):\n if p_ < 1.0:\n small.append(i)\n else:\n large.append(i)\n\n while large and small:\n l = small[0]\n g = large[0]\n small.pop(0)\n large.pop(0)\n self.__prob[l] = p[l]\n self.__alias[l] = g\n p[g] = p[g] + p[l] - 1 # A more numerically stable option.\n if p[g] < 1.0:\n small.append(g)\n else:\n large.append(g)\n\n while large:\n g = large[0]\n large.pop(0)\n self.__prob[g] = 1.0\n\n while small:\n l = small[0]\n small.pop(0)\n self.__prob[l] = 1.0\n\n def generate(self):\n \"\"\"Generate samples from given distribution.\n \"\"\"\n dart1 = rand_k(self.size())\n dart2 = int(rand())\n return dart1 if dart2 > self.__prob[dart1] else self.__alias[dart1]\n\n def size(self):\n return self.__prob.shape[0]\n", "# -*- coding:utf-8 -*-\n# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport ast\nimport os\nimport os.path as osp\nimport argparse\n\nimport cv2\nimport numpy as np\nimport paddle.fluid as fluid\nimport paddlehub as hub\nfrom paddle.fluid.core import PaddleTensor, AnalysisConfig, create_paddle_predictor\nfrom paddlehub.module.module import moduleinfo, runnable, serving\n\nfrom humanseg_mobile.processor import postprocess, base64_to_cv2, cv2_to_base64, check_dir\nfrom humanseg_mobile.data_feed import reader, preprocess_v\nfrom humanseg_mobile.optimal import postprocess_v, threshold_mask\n\n\n@moduleinfo(\n name=\"humanseg_mobile\",\n type=\"CV/semantic_segmentation\",\n author=\"paddlepaddle\",\n author_email=\"\",\n summary=\"HRNet_w18_samll_v1 is a semantic segmentation model.\",\n version=\"1.1.0\")\nclass HRNetw18samllv1humanseg(hub.Module):\n def _initialize(self):\n self.default_pretrained_model_path = os.path.join(self.directory, \"humanseg_mobile_inference\")\n self._set_config()\n\n def _set_config(self):\n \"\"\"\n predictor config setting\n \"\"\"\n self.model_file_path = os.path.join(self.default_pretrained_model_path, '__model__')\n self.params_file_path = os.path.join(self.default_pretrained_model_path, '__params__')\n cpu_config = AnalysisConfig(self.model_file_path, self.params_file_path)\n cpu_config.disable_glog_info()\n cpu_config.disable_gpu()\n self.cpu_predictor = create_paddle_predictor(cpu_config)\n try:\n _places = os.environ[\"CUDA_VISIBLE_DEVICES\"]\n int(_places[0])\n use_gpu = True\n except:\n use_gpu = False\n if use_gpu:\n gpu_config = AnalysisConfig(self.model_file_path, self.params_file_path)\n gpu_config.disable_glog_info()\n gpu_config.enable_use_gpu(memory_pool_init_size_mb=1000, device_id=0)\n self.gpu_predictor = create_paddle_predictor(gpu_config)\n\n def segment(self,\n images=None,\n paths=None,\n batch_size=1,\n use_gpu=False,\n visualization=False,\n output_dir='humanseg_mobile_output'):\n \"\"\"\n API for human segmentation.\n\n Args:\n images (list(numpy.ndarray)): images data, shape of each is [H, W, C], the color space is BGR.\n paths (list[str]): The paths of images.\n batch_size (int): batch size.\n use_gpu (bool): Whether to use gpu.\n visualization (bool): Whether to save image or not.\n output_dir (str): The path to store output images.\n\n Returns:\n res (list[dict]): each element in the list is a dict, the keys and values are:\n save_path (str, optional): the path to save images. (Exists only if visualization is True)\n data (numpy.ndarray): data of post processed image.\n \"\"\"\n if use_gpu:\n try:\n _places = os.environ[\"CUDA_VISIBLE_DEVICES\"]\n int(_places[0])\n except:\n raise RuntimeError(\"Environment Variable CUDA_VISIBLE_DEVICES is not set correctly.\"\n \"If you wanna use gpu, please set CUDA_VISIBLE_DEVICES as cuda_device_id.\")\n\n # compatibility with older versions\n\n all_data = list()\n for yield_data in reader(images, paths):\n all_data.append(yield_data)\n total_num = len(all_data)\n loop_num = int(np.ceil(total_num / batch_size))\n res = list()\n for iter_id in range(loop_num):\n batch_data = list()\n handle_id = iter_id * batch_size\n for image_id in range(batch_size):\n try:\n batch_data.append(all_data[handle_id + image_id])\n except:\n pass\n # feed batch image\n batch_image = np.array([data['image'] for data in batch_data])\n batch_image = PaddleTensor(batch_image.copy())\n output = self.gpu_predictor.run([batch_image]) if use_gpu else self.cpu_predictor.run([batch_image])\n output = output[1].as_ndarray()\n output = np.expand_dims(output[:, 1, :, :], axis=1)\n # postprocess one by one\n for i in range(len(batch_data)):\n out = postprocess(\n data_out=output[i],\n org_im=batch_data[i]['org_im'],\n org_im_shape=batch_data[i]['org_im_shape'],\n org_im_path=batch_data[i]['org_im_path'],\n output_dir=output_dir,\n visualization=visualization)\n res.append(out)\n return res\n\n def video_stream_segment(self, frame_org, frame_id, prev_gray, prev_cfd, use_gpu=False):\n \"\"\"\n API for human video segmentation.\n\n Args:\n frame_org (numpy.ndarray): frame data, shape of each is [H, W, C], the color space is BGR.\n frame_id (int): index of the frame to be decoded.\n prev_gray (numpy.ndarray): gray scale image of last frame, shape of each is [H, W]\n prev_cfd (numpy.ndarray): fusion image from optical flow image and segment result, shape of each is [H, W]\n use_gpu (bool): Whether to use gpu.\n\n Returns:\n img_matting (numpy.ndarray): data of segmentation mask.\n cur_gray (numpy.ndarray): gray scale image of current frame, shape of each is [H, W]\n optflow_map (numpy.ndarray): optical flow image of current frame, shape of each is [H, W]\n\n \"\"\"\n resize_h = 192\n resize_w = 192\n is_init = True\n width = int(frame_org.shape[0])\n height = int(frame_org.shape[1])\n disflow = cv2.DISOpticalFlow_create(cv2.DISOPTICAL_FLOW_PRESET_ULTRAFAST)\n frame = preprocess_v(frame_org, resize_w, resize_h)\n image = PaddleTensor(np.array([frame.copy()]))\n output = self.gpu_predictor.run([image]) if use_gpu else self.cpu_predictor.run([image])\n score_map = output[1].as_ndarray()\n frame = np.transpose(frame, axes=[1, 2, 0])\n score_map = np.transpose(np.squeeze(score_map, 0), axes=[1, 2, 0])\n cur_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n cur_gray = cv2.resize(cur_gray, (resize_w, resize_h))\n score_map = 255 * score_map[:, :, 1]\n if frame_id == 1:\n prev_gray = np.zeros((resize_h, resize_w), np.uint8)\n prev_cfd = np.zeros((resize_h, resize_w), np.float32)\n optflow_map = postprocess_v(cur_gray, score_map, prev_gray, prev_cfd, disflow, is_init)\n else:\n optflow_map = postprocess_v(cur_gray, score_map, prev_gray, prev_cfd, disflow, is_init)\n optflow_map = cv2.GaussianBlur(optflow_map, (3, 3), 0)\n optflow_map = threshold_mask(optflow_map, thresh_bg=0.2, thresh_fg=0.8)\n img_matting = cv2.resize(optflow_map, (height, width), cv2.INTER_LINEAR)\n return [img_matting, cur_gray, optflow_map]\n\n def video_segment(self, video_path=None, use_gpu=False, save_dir='humanseg_mobile_video_result'):\n \"\"\"\n API for human video segmentation.\n\n Args:\n video_path (str): The path to take the video under preprocess. If video_path is None, it will capture\n the vedio from your camera.\n use_gpu (bool): Whether to use gpu.\n save_dir (str): The path to store output video.\n\n \"\"\"\n if use_gpu:\n try:\n _places = os.environ[\"CUDA_VISIBLE_DEVICES\"]\n int(_places[0])\n except:\n raise RuntimeError(\"Environment Variable CUDA_VISIBLE_DEVICES is not set correctly. \"\n \"If you wanna use gpu, please set CUDA_VISIBLE_DEVICES as cuda_device_id.\")\n\n resize_h = 192\n resize_w = 192\n if not video_path:\n cap_video = cv2.VideoCapture(0)\n else:\n cap_video = cv2.VideoCapture(video_path)\n if not cap_video.isOpened():\n raise IOError(\"Error opening video stream or file, \"\n \"--video_path whether existing: {}\"\n \" or camera whether working\".format(video_path))\n width = int(cap_video.get(cv2.CAP_PROP_FRAME_WIDTH))\n height = int(cap_video.get(cv2.CAP_PROP_FRAME_HEIGHT))\n disflow = cv2.DISOpticalFlow_create(cv2.DISOPTICAL_FLOW_PRESET_ULTRAFAST)\n prev_gray = np.zeros((resize_h, resize_w), np.uint8)\n prev_cfd = np.zeros((resize_h, resize_w), np.float32)\n is_init = True\n fps = cap_video.get(cv2.CAP_PROP_FPS)\n if video_path is not None:\n print('Please wait. It is computing......')\n if not osp.exists(save_dir):\n os.makedirs(save_dir)\n save_path = osp.join(save_dir, 'result' + '.avi')\n cap_out = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'), fps, (width, height))\n while cap_video.isOpened():\n ret, frame_org = cap_video.read()\n if ret:\n frame = preprocess_v(frame_org, resize_w, resize_h)\n image = PaddleTensor(np.array([frame.copy()]))\n output = self.gpu_predictor.run([image]) if use_gpu else self.cpu_predictor.run([image])\n score_map = output[1].as_ndarray()\n frame = np.transpose(frame, axes=[1, 2, 0])\n score_map = np.transpose(np.squeeze(score_map, 0), axes=[1, 2, 0])\n cur_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n cur_gray = cv2.resize(cur_gray, (resize_w, resize_h))\n score_map = 255 * score_map[:, :, 1]\n optflow_map = postprocess_v(cur_gray, score_map, prev_gray, prev_cfd, disflow, is_init)\n prev_gray = cur_gray.copy()\n prev_cfd = optflow_map.copy()\n optflow_map = cv2.GaussianBlur(optflow_map, (3, 3), 0)\n optflow_map = threshold_mask(optflow_map, thresh_bg=0.2, thresh_fg=0.8)\n img_matting = cv2.resize(optflow_map, (width, height), cv2.INTER_LINEAR)\n img_matting = np.repeat(img_matting[:, :, np.newaxis], 3, axis=2)\n bg_im = np.ones_like(img_matting) * 255\n comb = (img_matting * frame_org + (1 - img_matting) * bg_im).astype(np.uint8)\n cap_out.write(comb)\n else:\n break\n cap_video.release()\n cap_out.release()\n else:\n while cap_video.isOpened():\n ret, frame_org = cap_video.read()\n if ret:\n frame = preprocess_v(frame_org, resize_w, resize_h)\n image = PaddleTensor(np.array([frame.copy()]))\n output = self.gpu_predictor.run([image]) if use_gpu else self.cpu_predictor.run([image])\n score_map = output[1].as_ndarray()\n frame = np.transpose(frame, axes=[1, 2, 0])\n score_map = np.transpose(np.squeeze(score_map, 0), axes=[1, 2, 0])\n cur_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n cur_gray = cv2.resize(cur_gray, (resize_w, resize_h))\n score_map = 255 * score_map[:, :, 1]\n optflow_map = postprocess_v(cur_gray, score_map, prev_gray, prev_cfd, disflow, is_init)\n prev_gray = cur_gray.copy()\n prev_cfd = optflow_map.copy()\n optflow_map = cv2.GaussianBlur(optflow_map, (3, 3), 0)\n optflow_map = threshold_mask(optflow_map, thresh_bg=0.2, thresh_fg=0.8)\n img_matting = cv2.resize(optflow_map, (width, height), cv2.INTER_LINEAR)\n img_matting = np.repeat(img_matting[:, :, np.newaxis], 3, axis=2)\n bg_im = np.ones_like(img_matting) * 255\n comb = (img_matting * frame_org + (1 - img_matting) * bg_im).astype(np.uint8)\n cv2.imshow('HumanSegmentation', comb)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n else:\n break\n cap_video.release()\n\n def save_inference_model(self,\n dirname='humanseg_mobile_model',\n model_filename=None,\n params_filename=None,\n combined=True):\n if combined:\n model_filename = \"__model__\" if not model_filename else model_filename\n params_filename = \"__params__\" if not params_filename else params_filename\n place = fluid.CPUPlace()\n exe = fluid.Executor(place)\n program, feeded_var_names, target_vars = fluid.io.load_inference_model(\n dirname=self.default_pretrained_model_path,\n model_filename=model_filename,\n params_filename=params_filename,\n executor=exe)\n fluid.io.save_inference_model(\n dirname=dirname,\n main_program=program,\n executor=exe,\n feeded_var_names=feeded_var_names,\n target_vars=target_vars,\n model_filename=model_filename,\n params_filename=params_filename)\n\n @serving\n def serving_method(self, images, **kwargs):\n \"\"\"\n Run as a service.\n \"\"\"\n images_decode = [base64_to_cv2(image) for image in images]\n results = self.segment(images=images_decode, **kwargs)\n results = [{'data': cv2_to_base64(result['data'])} for result in results]\n return results\n\n @runnable\n def run_cmd(self, argvs):\n \"\"\"\n Run as a command.\n \"\"\"\n self.parser = argparse.ArgumentParser(\n description=\"Run the {} module.\".format(self.name),\n prog='hub run {}'.format(self.name),\n usage='%(prog)s',\n add_help=True)\n self.arg_input_group = self.parser.add_argument_group(title=\"Input options\", description=\"Input data. Required\")\n self.arg_config_group = self.parser.add_argument_group(\n title=\"Config options\", description=\"Run configuration for controlling module behavior, not required.\")\n self.add_module_config_arg()\n self.add_module_input_arg()\n args = self.parser.parse_args(argvs)\n results = self.segment(\n paths=[args.input_path],\n batch_size=args.batch_size,\n use_gpu=args.use_gpu,\n output_dir=args.output_dir,\n visualization=args.visualization)\n if args.save_dir is not None:\n check_dir(args.save_dir)\n self.save_inference_model(args.save_dir)\n\n return results\n\n def add_module_config_arg(self):\n \"\"\"\n Add the command config options.\n \"\"\"\n self.arg_config_group.add_argument(\n '--use_gpu', type=ast.literal_eval, default=False, help=\"whether use GPU or not\")\n self.arg_config_group.add_argument(\n '--output_dir', type=str, default='humanseg_mobile_output', help=\"The directory to save output images.\")\n self.arg_config_group.add_argument(\n '--save_dir', type=str, default='humanseg_mobile_model', help=\"The directory to save model.\")\n self.arg_config_group.add_argument(\n '--visualization', type=ast.literal_eval, default=False, help=\"whether to save output as images.\")\n self.arg_config_group.add_argument('--batch_size', type=ast.literal_eval, default=1, help=\"batch size.\")\n\n def add_module_input_arg(self):\n \"\"\"\n Add the command input options.\n \"\"\"\n self.arg_input_group.add_argument('--input_path', type=str, help=\"path to image.\")\n\n\nif __name__ == \"__main__\":\n m = HRNetw18samllv1humanseg()\n img = cv2.imread('photo.jpg')\n #res = m.segment(images=[img], visualization=True)\n #print(res[0]['data'])\n #m.video_segment('')\n cap_video = cv2.VideoCapture('video_test.mp4')\n fps = cap_video.get(cv2.CAP_PROP_FPS)\n save_path = 'result_frame.avi'\n width = int(cap_video.get(cv2.CAP_PROP_FRAME_WIDTH))\n height = int(cap_video.get(cv2.CAP_PROP_FRAME_HEIGHT))\n cap_out = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'), fps, (width, height))\n prev_gray = None\n prev_cfd = None\n while cap_video.isOpened():\n ret, frame_org = cap_video.read()\n if ret:\n [img_matting, prev_gray, prev_cfd] = m.video_stream_segment(\n frame_org=frame_org, frame_id=cap_video.get(1), prev_gray=prev_gray, prev_cfd=prev_cfd)\n img_matting = np.repeat(img_matting[:, :, np.newaxis], 3, axis=2)\n bg_im = np.ones_like(img_matting) * 255\n comb = (img_matting * frame_org + (1 - img_matting) * bg_im).astype(np.uint8)\n cap_out.write(comb)\n else:\n break\n cap_video.release()\n cap_out.release()\n", "import os\n\nimport numpy as np\nfrom paddlehub.common.logger import logger\n\nfrom lda_webpage.vocab import OOV\n\nEPS = 1e-06\n\n\nclass WordAndDis(object):\n def __init__(self):\n self.word = None\n self.distance = None\n\n\nclass SemanticMatching(object):\n def __init__(self):\n pass\n\n def l2_norm(self, vec):\n \"\"\"Calculate the length of vector.\n \"\"\"\n result = np.sqrt(np.sum(vec**2))\n return result\n\n def cosine_similarity(self, vec1, vec2):\n norm1 = self.l2_norm(vec1)\n norm2 = self.l2_norm(vec2)\n result = np.sum(vec1 * vec2) / norm1 / norm2\n return result\n\n def likelihood_based_similarity(self, terms, doc_topic_dist, model):\n \"\"\"\n Args:\n terms: list of strings\n doc_topic_dist: list of Topic class\n model: TopicModel class\n \"\"\"\n num_of_term_in_vocab = 0\n result = 0\n for i in range(len(terms)):\n term_id = model.term_id(terms[i])\n if term_id == OOV:\n continue\n num_of_term_in_vocab += 1\n for j in range(len(doc_topic_dist)):\n topic_id = doc_topic_dist[j].tid\n prob = doc_topic_dist[j].prob\n result += model.word_topic_value(term_id, topic_id) * 1.0 / \\\n model.topic_sum_value(topic_id) * prob\n\n if num_of_term_in_vocab == 0:\n return result\n return result / num_of_term_in_vocab\n\n def kullback_leibler_divergence(self, dist1, dist2):\n assert dist1.shape == dist2.shape\n dist2[dist2 < EPS] = EPS\n result = np.sum(dist1 * np.log(dist1 / dist2))\n return result\n\n def jensen_shannon_divergence(self, dist1, dist2):\n assert dist1.shape == dist2.shape\n dist1[dist1 < EPS] = EPS\n dist2[dist2 < EPS] = EPS\n mean = (dist1 + dist2) * 0.5\n jsd = self.kullback_leibler_divergence(dist1, mean) * 0.5 + \\\n self.kullback_leibler_divergence(dist2, mean) * 0.5\n return jsd\n\n def hellinger_distance(self, dist1, dist2):\n assert dist1.shape == dist2.shape\n result = np.sum((np.sqrt(dist1) - np.sqrt(dist2))**2)\n result = np.sqrt(result) * 0.7071067812\n return result\n", "# -*- coding:utf-8 -*-\nimport os\nimport time\nfrom collections import OrderedDict\n\nimport cv2\nimport numpy as np\n\n__all__ = ['reader', 'preprocess_v']\n\n\ndef preprocess_v(img, w, h):\n img = cv2.resize(img, (w, h), cv2.INTER_LINEAR).astype(np.float32)\n img_mean = np.array([0.5, 0.5, 0.5]).reshape((3, 1, 1))\n img_std = np.array([0.5, 0.5, 0.5]).reshape((3, 1, 1))\n img = img.transpose((2, 0, 1)) / 255\n img -= img_mean\n img /= img_std\n return img\n\n\ndef reader(images=None, paths=None):\n \"\"\"\n Preprocess to yield image.\n\n Args:\n images (list(numpy.ndarray)): images data, shape of each is [H, W, C]\n paths (list[str]): paths to images.\n\n Yield:\n each (collections.OrderedDict): info of original image, preprocessed image.\n \"\"\"\n component = list()\n if paths:\n for im_path in paths:\n each = OrderedDict()\n assert os.path.isfile(im_path), \"The {} isn't a valid file path.\".format(im_path)\n #print(im_path)\n im = cv2.imread(im_path).astype('float32')\n each['org_im'] = im\n each['org_im_path'] = im_path\n each['org_im_shape'] = im.shape\n component.append(each)\n if images is not None:\n assert type(images) is list, \"images should be a list.\"\n for im in images:\n each = OrderedDict()\n each['org_im'] = im\n each['org_im_path'] = 'ndarray_time={}'.format(round(time.time(), 6) * 1e6)\n each['org_im_shape'] = im.shape\n component.append(each)\n\n for element in component:\n img = element['org_im'].copy()\n img = cv2.resize(img, (192, 192)).astype(np.float32)\n img_mean = np.array([0.5, 0.5, 0.5]).reshape((3, 1, 1))\n img_std = np.array([0.5, 0.5, 0.5]).reshape((3, 1, 1))\n img = img.transpose((2, 0, 1)) / 255\n img -= img_mean\n img /= img_std\n element['image'] = img\n yield element\n", "# coding=utf-8\nimport base64\nimport os\n\nimport cv2\nimport numpy as np\nfrom PIL import Image, ImageDraw\n\n__all__ = ['base64_to_cv2', 'load_label_info', 'postprocess']\n\n\ndef base64_to_cv2(b64str):\n data = base64.b64decode(b64str.encode('utf8'))\n data = np.fromstring(data, np.uint8)\n data = cv2.imdecode(data, cv2.IMREAD_COLOR)\n return data\n\n\ndef get_save_image_name(img, output_dir, image_path):\n \"\"\"\n Get save image name from source image path.\n \"\"\"\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n image_name = os.path.split(image_path)[-1]\n name, ext = os.path.splitext(image_name)\n\n if img.format == 'PNG':\n ext = '.png'\n elif img.format == 'JPEG':\n ext = '.jpg'\n elif img.format == 'BMP':\n ext = '.bmp'\n else:\n if img.mode == \"RGB\" or img.mode == \"L\":\n ext = \".jpg\"\n elif img.mode == \"RGBA\" or img.mode == \"P\":\n ext = '.png'\n\n return os.path.join(output_dir, \"{}\".format(name)) + ext\n\n\ndef draw_bounding_box_on_image(image_path, data_list, save_dir):\n image = Image.open(image_path)\n draw = ImageDraw.Draw(image)\n for data in data_list:\n left, right, top, bottom = data['left'], data['right'], data['top'], data['bottom']\n\n # draw bbox\n draw.line([(left, top), (left, bottom), (right, bottom), (right, top), (left, top)], width=2, fill='red')\n\n # draw label\n if image.mode == 'RGB':\n text = data['label'] + \": %.2f%%\" % (100 * data['confidence'])\n textsize_width, textsize_height = draw.textsize(text=text)\n draw.rectangle(\n xy=(left, top - (textsize_height + 5), left + textsize_width + 10, top), fill=(255, 255, 255))\n draw.text(xy=(left, top - 15), text=text, fill=(0, 0, 0))\n\n save_name = get_save_image_name(image, save_dir, image_path)\n if os.path.exists(save_name):\n os.remove(save_name)\n\n image.save(save_name)\n\n return save_name\n\n\ndef clip_bbox(bbox, img_width, img_height):\n xmin = max(min(bbox[0], img_width), 0.)\n ymin = max(min(bbox[1], img_height), 0.)\n xmax = max(min(bbox[2], img_width), 0.)\n ymax = max(min(bbox[3], img_height), 0.)\n return float(xmin), float(ymin), float(xmax), float(ymax)\n\n\ndef load_label_info(file_path):\n with open(file_path, 'r') as fr:\n text = fr.readlines()\n label_names = []\n for info in text:\n label_names.append(info.strip())\n return label_names\n\n\ndef postprocess(paths, images, data_out, score_thresh, label_names, output_dir, handle_id, visualization=True):\n \"\"\"\n postprocess the lod_tensor produced by fluid.Executor.run\n\n Args:\n paths (list[str]): the path of images.\n images (list(numpy.ndarray)): list of images, shape of each is [H, W, C].\n data_out (lod_tensor): data produced by executor.run.\n score_thresh (float): the low limit of bounding box.\n label_names (list[str]): label names.\n output_dir (str): output directory.\n handle_id (int): The number of images that have been handled.\n visualization (bool): whether to save as images.\n\n Returns:\n res (list[dict]): The result of vehicles detecion. keys include 'data', 'save_path', the corresponding value is:\n data (dict): the result of object detection, keys include 'left', 'top', 'right', 'bottom', 'label', 'confidence', the corresponding value is:\n left (float): The X coordinate of the upper left corner of the bounding box;\n top (float): The Y coordinate of the upper left corner of the bounding box;\n right (float): The X coordinate of the lower right corner of the bounding box;\n bottom (float): The Y coordinate of the lower right corner of the bounding box;\n label (str): The label of detection result;\n confidence (float): The confidence of detection result.\n save_path (str): The path to save output images.\n \"\"\"\n lod_tensor = data_out[0]\n lod = lod_tensor.lod[0]\n results = lod_tensor.as_ndarray()\n if handle_id < len(paths):\n unhandled_paths = paths[handle_id:]\n unhandled_paths_num = len(unhandled_paths)\n else:\n unhandled_paths_num = 0\n\n output = []\n for index in range(len(lod) - 1):\n output_i = {'data': []}\n if index < unhandled_paths_num:\n org_img_path = unhandled_paths[index]\n org_img = Image.open(org_img_path)\n output_i['path'] = org_img_path\n else:\n org_img = images[index - unhandled_paths_num]\n org_img = org_img.astype(np.uint8)\n org_img = Image.fromarray(org_img[:, :, ::-1])\n if visualization:\n org_img_path = get_save_image_name(org_img, output_dir, 'image_numpy_{}'.format((handle_id + index)))\n org_img.save(org_img_path)\n org_img_height = org_img.height\n org_img_width = org_img.width\n result_i = results[lod[index]:lod[index + 1]]\n for row in result_i:\n if len(row) != 6:\n continue\n if row[1] < score_thresh:\n continue\n category_id = int(row[0])\n confidence = row[1]\n bbox = row[2:]\n bbox[0] = bbox[0] * org_img_width\n bbox[1] = bbox[1] * org_img_height\n bbox[2] = bbox[2] * org_img_width\n bbox[3] = bbox[3] * org_img_height\n dt = {}\n dt['label'] = label_names[category_id]\n dt['confidence'] = float(confidence)\n dt['left'], dt['top'], dt['right'], dt['bottom'] = clip_bbox(bbox, org_img_width, org_img_height)\n output_i['data'].append(dt)\n\n output.append(output_i)\n if visualization:\n output_i['save_path'] = draw_bounding_box_on_image(org_img_path, output_i['data'], output_dir)\n\n return output\n", "# coding=utf-8\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport paddle.fluid as fluid\nfrom paddle.fluid.param_attr import ParamAttr\nfrom paddle.fluid.initializer import Normal, Constant\nfrom paddle.fluid.regularizer import L2Decay\n\n__all__ = ['AnchorGenerator', 'RetinaTargetAssign', 'RetinaOutputDecoder', 'RetinaHead']\n\n\nclass AnchorGenerator(object):\n # __op__ = fluid.layers.anchor_generator\n def __init__(self,\n stride=[16.0, 16.0],\n anchor_sizes=[32, 64, 128, 256, 512],\n aspect_ratios=[0.5, 1., 2.],\n variance=[1., 1., 1., 1.]):\n self.anchor_sizes = anchor_sizes\n self.aspect_ratios = aspect_ratios\n self.variance = variance\n self.stride = stride\n\n\nclass RetinaTargetAssign(object):\n # __op__ = fluid.layers.retinanet_target_assign\n def __init__(self, positive_overlap=0.5, negative_overlap=0.4):\n self.positive_overlap = positive_overlap\n self.negative_overlap = negative_overlap\n\n\nclass RetinaOutputDecoder(object):\n # __op__ = fluid.layers.retinanet_detection_output\n def __init__(self, score_thresh=0.05, nms_thresh=0.3, pre_nms_top_n=1000, detections_per_im=100, nms_eta=1.0):\n super(RetinaOutputDecoder, self).__init__()\n self.score_threshold = score_thresh\n self.nms_threshold = nms_thresh\n self.nms_top_k = pre_nms_top_n\n self.keep_top_k = detections_per_im\n self.nms_eta = nms_eta\n\n\nclass RetinaHead(object):\n \"\"\"\n Retina Head\n\n Args:\n anchor_generator (object): `AnchorGenerator` instance\n target_assign (object): `RetinaTargetAssign` instance\n output_decoder (object): `RetinaOutputDecoder` instance\n num_convs_per_octave (int): Number of convolution layers in each octave\n num_chan (int): Number of octave output channels\n max_level (int): Highest level of FPN output\n min_level (int): Lowest level of FPN output\n prior_prob (float): Used to set the bias init for the class prediction layer\n base_scale (int): Anchors are generated based on this scale\n num_scales_per_octave (int): Number of anchor scales per octave\n num_classes (int): Number of classes\n gamma (float): The parameter in focal loss\n alpha (float): The parameter in focal loss\n sigma (float): The parameter in smooth l1 loss\n \"\"\"\n __inject__ = ['anchor_generator', 'target_assign', 'output_decoder']\n __shared__ = ['num_classes']\n\n def __init__(self,\n anchor_generator=AnchorGenerator(),\n target_assign=RetinaTargetAssign(),\n output_decoder=RetinaOutputDecoder(),\n num_convs_per_octave=4,\n num_chan=256,\n max_level=7,\n min_level=3,\n prior_prob=0.01,\n base_scale=4,\n num_scales_per_octave=3,\n num_classes=81,\n gamma=2.0,\n alpha=0.25,\n sigma=3.0151134457776365):\n self.anchor_generator = anchor_generator\n self.target_assign = target_assign\n self.output_decoder = output_decoder\n self.num_convs_per_octave = num_convs_per_octave\n self.num_chan = num_chan\n self.max_level = max_level\n self.min_level = min_level\n self.prior_prob = prior_prob\n self.base_scale = base_scale\n self.num_scales_per_octave = num_scales_per_octave\n self.num_classes = num_classes\n self.gamma = gamma\n self.alpha = alpha\n self.sigma = sigma\n\n def _class_subnet(self, body_feats, spatial_scale):\n \"\"\"\n Get class predictions of all level FPN level.\n\n Args:\n fpn_dict(dict): A dictionary represents the output of FPN with\n their name.\n spatial_scale(list): A list of multiplicative spatial scale factor.\n\n Returns:\n cls_pred_input(list): Class prediction of all input fpn levels.\n \"\"\"\n assert len(body_feats) == self.max_level - self.min_level + 1\n fpn_name_list = list(body_feats.keys())\n cls_pred_list = []\n for lvl in range(self.min_level, self.max_level + 1):\n fpn_name = fpn_name_list[self.max_level - lvl]\n subnet_blob = body_feats[fpn_name]\n for i in range(self.num_convs_per_octave):\n conv_name = 'retnet_cls_conv_n{}_fpn{}'.format(i, lvl)\n conv_share_name = 'retnet_cls_conv_n{}_fpn{}'.format(i, self.min_level)\n subnet_blob_in = subnet_blob\n subnet_blob = fluid.layers.conv2d(\n input=subnet_blob_in,\n num_filters=self.num_chan,\n filter_size=3,\n stride=1,\n padding=1,\n act='relu',\n name=conv_name,\n param_attr=ParamAttr(name=conv_share_name + '_w', initializer=Normal(loc=0., scale=0.01)),\n bias_attr=ParamAttr(name=conv_share_name + '_b', learning_rate=2., regularizer=L2Decay(0.)))\n\n # class prediction\n cls_name = 'retnet_cls_pred_fpn{}'.format(lvl)\n cls_share_name = 'retnet_cls_pred_fpn{}'.format(self.min_level)\n num_anchors = self.num_scales_per_octave * len(self.anchor_generator.aspect_ratios)\n cls_dim = num_anchors * (self.num_classes - 1)\n # bias initialization: b = -log((1 - pai) / pai)\n bias_init = float(-np.log((1 - self.prior_prob) / self.prior_prob))\n out_cls = fluid.layers.conv2d(\n input=subnet_blob,\n num_filters=cls_dim,\n filter_size=3,\n stride=1,\n padding=1,\n act=None,\n name=cls_name,\n param_attr=ParamAttr(name=cls_share_name + '_w', initializer=Normal(loc=0., scale=0.01)),\n bias_attr=ParamAttr(\n name=cls_share_name + '_b',\n initializer=Constant(value=bias_init),\n learning_rate=2.,\n regularizer=L2Decay(0.)))\n cls_pred_list.append(out_cls)\n\n return cls_pred_list\n\n def _bbox_subnet(self, body_feats, spatial_scale):\n \"\"\"\n Get bounding box predictions of all level FPN level.\n\n Args:\n fpn_dict(dict): A dictionary represents the output of FPN with\n their name.\n spatial_scale(list): A list of multiplicative spatial scale factor.\n\n Returns:\n bbox_pred_input(list): Bounding box prediction of all input fpn\n levels.\n \"\"\"\n assert len(body_feats) == self.max_level - self.min_level + 1\n fpn_name_list = list(body_feats.keys())\n bbox_pred_list = []\n for lvl in range(self.min_level, self.max_level + 1):\n fpn_name = fpn_name_list[self.max_level - lvl]\n subnet_blob = body_feats[fpn_name]\n for i in range(self.num_convs_per_octave):\n conv_name = 'retnet_bbox_conv_n{}_fpn{}'.format(i, lvl)\n conv_share_name = 'retnet_bbox_conv_n{}_fpn{}'.format(i, self.min_level)\n subnet_blob_in = subnet_blob\n subnet_blob = fluid.layers.conv2d(\n input=subnet_blob_in,\n num_filters=self.num_chan,\n filter_size=3,\n stride=1,\n padding=1,\n act='relu',\n name=conv_name,\n param_attr=ParamAttr(name=conv_share_name + '_w', initializer=Normal(loc=0., scale=0.01)),\n bias_attr=ParamAttr(name=conv_share_name + '_b', learning_rate=2., regularizer=L2Decay(0.)))\n\n # bbox prediction\n bbox_name = 'retnet_bbox_pred_fpn{}'.format(lvl)\n bbox_share_name = 'retnet_bbox_pred_fpn{}'.format(self.min_level)\n num_anchors = self.num_scales_per_octave * len(self.anchor_generator.aspect_ratios)\n bbox_dim = num_anchors * 4\n out_bbox = fluid.layers.conv2d(\n input=subnet_blob,\n num_filters=bbox_dim,\n filter_size=3,\n stride=1,\n padding=1,\n act=None,\n name=bbox_name,\n param_attr=ParamAttr(name=bbox_share_name + '_w', initializer=Normal(loc=0., scale=0.01)),\n bias_attr=ParamAttr(name=bbox_share_name + '_b', learning_rate=2., regularizer=L2Decay(0.)))\n bbox_pred_list.append(out_bbox)\n return bbox_pred_list\n\n def _anchor_generate(self, body_feats, spatial_scale):\n \"\"\"\n Get anchor boxes of all level FPN level.\n\n Args:\n fpn_dict(dict): A dictionary represents the output of FPN with their name.\n spatial_scale(list): A list of multiplicative spatial scale factor.\n\n Return:\n anchor_input(list): Anchors of all input fpn levels with shape of.\n anchor_var_input(list): Anchor variance of all input fpn levels with shape.\n \"\"\"\n assert len(body_feats) == self.max_level - self.min_level + 1\n fpn_name_list = list(body_feats.keys())\n anchor_list = []\n anchor_var_list = []\n for lvl in range(self.min_level, self.max_level + 1):\n anchor_sizes = []\n stride = int(1 / spatial_scale[self.max_level - lvl])\n for octave in range(self.num_scales_per_octave):\n anchor_size = stride * (2**(float(octave) / float(self.num_scales_per_octave))) * self.base_scale\n anchor_sizes.append(anchor_size)\n fpn_name = fpn_name_list[self.max_level - lvl]\n anchor, anchor_var = fluid.layers.anchor_generator(\n input=body_feats[fpn_name],\n anchor_sizes=anchor_sizes,\n aspect_ratios=self.anchor_generator.aspect_ratios,\n stride=[stride, stride],\n variance=self.anchor_generator.variance)\n anchor_list.append(anchor)\n anchor_var_list.append(anchor_var)\n return anchor_list, anchor_var_list\n\n def _get_output(self, body_feats, spatial_scale):\n \"\"\"\n Get class, bounding box predictions and anchor boxes of all level FPN level.\n\n Args:\n fpn_dict(dict): A dictionary represents the output of FPN with\n their name.\n spatial_scale(list): A list of multiplicative spatial scale factor.\n\n Returns:\n cls_pred_input(list): Class prediction of all input fpn levels.\n bbox_pred_input(list): Bounding box prediction of all input fpn\n levels.\n anchor_input(list): Anchors of all input fpn levels with shape of.\n anchor_var_input(list): Anchor variance of all input fpn levels with\n shape.\n \"\"\"\n assert len(body_feats) == self.max_level - self.min_level + 1\n # class subnet\n cls_pred_list = self._class_subnet(body_feats, spatial_scale)\n # bbox subnet\n bbox_pred_list = self._bbox_subnet(body_feats, spatial_scale)\n #generate anchors\n anchor_list, anchor_var_list = self._anchor_generate(body_feats, spatial_scale)\n cls_pred_reshape_list = []\n bbox_pred_reshape_list = []\n anchor_reshape_list = []\n anchor_var_reshape_list = []\n for i in range(self.max_level - self.min_level + 1):\n cls_pred_transpose = fluid.layers.transpose(cls_pred_list[i], perm=[0, 2, 3, 1])\n cls_pred_reshape = fluid.layers.reshape(cls_pred_transpose, shape=(0, -1, self.num_classes - 1))\n bbox_pred_transpose = fluid.layers.transpose(bbox_pred_list[i], perm=[0, 2, 3, 1])\n bbox_pred_reshape = fluid.layers.reshape(bbox_pred_transpose, shape=(0, -1, 4))\n anchor_reshape = fluid.layers.reshape(anchor_list[i], shape=(-1, 4))\n anchor_var_reshape = fluid.layers.reshape(anchor_var_list[i], shape=(-1, 4))\n cls_pred_reshape_list.append(cls_pred_reshape)\n bbox_pred_reshape_list.append(bbox_pred_reshape)\n anchor_reshape_list.append(anchor_reshape)\n anchor_var_reshape_list.append(anchor_var_reshape)\n output = {}\n output['cls_pred'] = cls_pred_reshape_list\n output['bbox_pred'] = bbox_pred_reshape_list\n output['anchor'] = anchor_reshape_list\n output['anchor_var'] = anchor_var_reshape_list\n return output\n\n def get_prediction(self, body_feats, spatial_scale, im_info):\n \"\"\"\n Get prediction bounding box in test stage.\n\n Args:\n fpn_dict(dict): A dictionary represents the output of FPN with\n their name.\n spatial_scale(list): A list of multiplicative spatial scale factor.\n im_info (Variable): A 2-D LoDTensor with shape [B, 3]. B is the\n number of input images, each element consists of im_height,\n im_width, im_scale.\n\n Returns:\n pred_result(Variable): Prediction result with shape [N, 6]. Each\n row has 6 values: [label, confidence, xmin, ymin, xmax, ymax].\n N is the total number of prediction.\n \"\"\"\n output = self._get_output(body_feats, spatial_scale)\n cls_pred_reshape_list = output['cls_pred']\n bbox_pred_reshape_list = output['bbox_pred']\n anchor_reshape_list = output['anchor']\n for i in range(self.max_level - self.min_level + 1):\n cls_pred_reshape_list[i] = fluid.layers.sigmoid(cls_pred_reshape_list[i])\n pred_result = fluid.layers.retinanet_detection_output(\n bboxes=bbox_pred_reshape_list,\n scores=cls_pred_reshape_list,\n anchors=anchor_reshape_list,\n im_info=im_info,\n score_threshold=self.output_decoder.score_threshold,\n nms_threshold=self.output_decoder.nms_threshold,\n nms_top_k=self.output_decoder.nms_top_k,\n keep_top_k=self.output_decoder.keep_top_k,\n nms_eta=self.output_decoder.nms_eta)\n return pred_result\n\n def get_loss(self, body_feats, spatial_scale, im_info, gt_box, gt_label, is_crowd):\n \"\"\"\n Calculate the loss of retinanet.\n Args:\n fpn_dict(dict): A dictionary represents the output of FPN with\n their name.\n spatial_scale(list): A list of multiplicative spatial scale factor.\n im_info(Variable): A 2-D LoDTensor with shape [B, 3]. B is the\n number of input images, each element consists of im_height,\n im_width, im_scale.\n gt_box(Variable): The ground-truth bounding boxes with shape [M, 4].\n M is the number of groundtruth.\n gt_label(Variable): The ground-truth labels with shape [M, 1].\n M is the number of groundtruth.\n is_crowd(Variable): Indicates groud-truth is crowd or not with\n shape [M, 1]. M is the number of groundtruth.\n\n Returns:\n Type: dict\n loss_cls(Variable): focal loss.\n loss_bbox(Variable): smooth l1 loss.\n \"\"\"\n output = self._get_output(body_feats, spatial_scale)\n cls_pred_reshape_list = output['cls_pred']\n bbox_pred_reshape_list = output['bbox_pred']\n anchor_reshape_list = output['anchor']\n anchor_var_reshape_list = output['anchor_var']\n\n cls_pred_input = fluid.layers.concat(cls_pred_reshape_list, axis=1)\n bbox_pred_input = fluid.layers.concat(bbox_pred_reshape_list, axis=1)\n anchor_input = fluid.layers.concat(anchor_reshape_list, axis=0)\n anchor_var_input = fluid.layers.concat(anchor_var_reshape_list, axis=0)\n score_pred, loc_pred, score_tgt, loc_tgt, bbox_weight, fg_num = \\\n fluid.layers.rpn_target_assign(\n bbox_pred=bbox_pred_input,\n cls_logits=cls_pred_input,\n anchor_box=anchor_input,\n anchor_var=anchor_var_input,\n gt_boxes=gt_box,\n gt_labels=gt_label,\n is_crowd=is_crowd,\n im_info=im_info,\n num_classes=self.num_classes - 1,\n rpn_batch_size_per_im=self.target_assign.rpn_batch_size_per_im,\n rpn_straddle_thresh=self.target_assign.rpn_straddle_thresh,\n rpn_fg_fraction=self.target_assign.rpn_fg_fraction,\n rpn_positive_overlap=self.target_assign.rpn_positive_overlap,\n rpn_negative_overlap=self.target_assign.rpn_negative_overlap,\n use_random=self.target_assign.use_random)\n fg_num = fluid.layers.reduce_sum(fg_num, name='fg_num')\n score_tgt = fluid.layers.cast(score_tgt, 'int32')\n loss_cls = fluid.layers.sigmoid_focal_loss(\n x=score_pred, label=score_tgt, fg_num=fg_num, gamma=self.gamma, alpha=self.alpha)\n loss_cls = fluid.layers.reduce_sum(loss_cls, name='loss_cls')\n loss_bbox = fluid.layers.smooth_l1(\n x=loc_pred, y=loc_tgt, sigma=self.sigma, inside_weight=bbox_weight, outside_weight=bbox_weight)\n loss_bbox = fluid.layers.reduce_sum(loss_bbox, name='loss_bbox')\n loss_bbox = loss_bbox / fg_num\n return {'loss_cls': loss_cls, 'loss_bbox': loss_bbox}\n" ]
[ [ "numpy.zeros", "numpy.sum" ], [ "numpy.expand_dims", "numpy.ones_like", "numpy.squeeze", "numpy.ceil", "numpy.transpose", "numpy.repeat", "numpy.array", "numpy.zeros" ], [ "numpy.sqrt", "numpy.sum", "numpy.log" ], [ "numpy.array" ], [ "numpy.fromstring" ], [ "numpy.log" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
franktoffel/dapper
[ "373a27273ea109f349e5edcdcef0cfe0b83b925e", "373a27273ea109f349e5edcdcef0cfe0b83b925e" ]
[ "mods/Lorenz95/core.py", "tools/viz.py" ]
[ "# \"Lorenz-95\" (or 96) model. For a deeper introduction, see\n# \"DAPPER/tutorials/T4 - Dynamical systems, chaos, Lorenz.ipynb\"\n#\n# Note: implementation is ndim-agnostic.\n\nimport numpy as np\nfrom tools.math import rk4, integrate_TLM, is1d\n\nForce = 8.0\n\n# Note: the model is unstable (blows up) if there are large peaks\n# (as may be occasioned by the analysis update, especially with partial obs). \n# Example: integrate 4 steps with dt=0.05 from x0 = [0,-30,0,30].\n# This is effectively a CFL condition... Can be addressed by:\n# - lowering dt\n# - using an implicit time stepping scheme instead of rk4\n# - stupidly crop amplitudes, as is done here:\nprevent_blow_up = False\n\nTplot = 10\n\nx0 = lambda M: 2.3*np.ones(M)\n\ndef dxdt(x):\n a = x.ndim-1\n s = lambda x,n: np.roll(x,-n,axis=a)\n return (s(x,1)-s(x,-2))*s(x,-1) - x + Force\n\ndef step(x0, t, dt):\n\n if prevent_blow_up:\n clip = abs(x0)>30\n x0[clip] *= 0.1\n\n return rk4(lambda t,x: dxdt(x), x0, np.nan, dt)\n\n################################################\n# OPTIONAL (not necessary for EnKF or PartFilt):\n################################################\ndef TLM(x):\n \"\"\"Tangent linear model\"\"\"\n assert is1d(x)\n Nx = len(x)\n TLM = np.zeros((Nx,Nx))\n md = lambda i: np.mod(i,Nx)\n for i in range(Nx):\n TLM[i,i] = -1.0\n TLM[i, i-2 ] = -x[i-1]\n TLM[i,md(i+1)] = +x[i-1]\n TLM[i, i-1 ] = x[md(i+1)]-x[i-2]\n return TLM\n\ndef dfdx(x,t,dt):\n \"\"\"Integral of TLM. Jacobian of step.\"\"\"\n # method='analytic' is a substantial upgrade for Lor95 \n return integrate_TLM(TLM(x),dt,method='analytic')\n\n\n################################################\n# Add some non-default liveplotters\n################################################\nimport tools.liveplotting as LP\ndef LPs(jj=None): return [\n (11, 1, LP.spatial1d(jj) ),\n (12, 1, LP.correlations ),\n (15, 0, LP.spectral_errors),\n (13, 0, LP.phase3d(jj) ),\n (11, 0, LP.sliding_marginals(jj)) ,\n ]\n\n\n", "from common import *\n\n#from mpl_toolkits.mplot3d import Axes3D\nfrom mpl_toolkits.mplot3d.art3d import juggle_axes\n\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nfrom mpl_toolkits.axes_grid1.inset_locator import inset_axes\n\nfrom matplotlib import colors\nfrom matplotlib.ticker import MaxNLocator\n\n\ndef setup_wrapping(M,periodic=True):\n \"\"\"\n Make periodic indices and a corresponding function\n (that works for ensemble input).\n \"\"\"\n\n if periodic:\n ii = np.hstack([-0.5, arange(M), M-0.5])\n def wrap(E):\n midpoint = (E[[0],...] + E[[-1],...])/2\n return ccat(midpoint,E,midpoint)\n\n else:\n ii = arange(M)\n wrap = lambda x: x\n\n return ii, wrap\n \ndef adjust_position(ax,adjust_extent=False,**kwargs):\n \"\"\"\n Adjust values (add) to get_position().\n kwarg must be one of 'x0','y0','width','height'.\n \"\"\"\n # Load get_position into d\n pos = ax.get_position()\n d = OrderedDict()\n for key in ['x0','y0','width','height']:\n d[key] = getattr(pos,key)\n # Make adjustments\n for key,item in kwargs.items():\n d[key] += item\n if adjust_extent:\n if key=='x0': d['width'] -= item\n if key=='y0': d['height'] -= item\n # Set\n ax.set_position(d.values())\n\ndef span(xx,axis=None):\n a = xx.min(axis)\n b = xx.max(axis)\n return a, b\n\ndef stretch(a,b,factor=1,int=False):\n \"\"\"\n Stretch distance a-b by factor.\n Return a,b.\n If int: floor(a) and ceil(b)\n \"\"\"\n c = (a+b)/2\n a = c + factor*(a-c) \n b = c + factor*(b-c) \n if int:\n a = floor(a)\n b = ceil(b)\n return a, b\n\n\ndef set_ilim(ax,i,Min=None,Max=None):\n \"\"\"Set bounds on axis i.\"\"\" \n if i is 0: ax.set_xlim(Min,Max)\n if i is 1: ax.set_ylim(Min,Max)\n if i is 2: ax.set_zlim(Min,Max)\n\n# Examples:\n# K_lag = estimate_good_plot_length(stats.xx,chrono,mult = 80)\ndef estimate_good_plot_length(xx,chrono=None,mult=100):\n \"\"\"\n Estimate good length for plotting stuff\n from the time scale of the system.\n Provide sensible fall-backs (better if chrono is supplied).\n \"\"\"\n if xx.ndim == 2:\n # If mult-dim, then average over dims (by ravel)....\n # But for inhomogeneous variables, it is important\n # to subtract the mean first!\n xx = xx - mean(xx,axis=0)\n xx = xx.ravel(order='F')\n\n try:\n K = mult * estimate_corr_length(xx)\n except ValueError:\n K = 0\n\n if chrono != None:\n t = chrono\n K = int(min(max(K, t.dkObs), t.K))\n T = round2sigfig(t.tt[K],2) # Could return T; T>tt[-1]\n K = find_1st_ind(t.tt >= T)\n if K: return K\n else: return t.K\n else:\n K = int(min(max(K, 1), len(xx)))\n T = round2sigfig(K,2)\n return K\n\ndef get_plot_inds(xx,chrono,K=None,T=None,**kwargs):\n \"\"\"\n Def subset of kk for plotting, from one of\n - K\n - T\n - mult * auto-correlation length of xx\n \"\"\"\n t = chrono\n if K is None:\n if T: K = find_1st_ind(t.tt >= min(T,t.T))\n else: K = estimate_good_plot_length(xx,chrono=t,**kwargs)\n plot_kk = t.kk[:K+1]\n plot_kkObs = t.kkObs[t.kkObs<=K]\n return plot_kk, plot_kkObs\n\n\ndef plot_hovmoller(xx,chrono=None,**kwargs):\n \"\"\"\n Plot Hovmöller diagram.\n kwargs forwarded to get_plot_inds().\n \"\"\"\n #cm = mpl.colors.ListedColormap(sns.color_palette(\"BrBG\", 256)) # RdBu_r\n #cm = plt.get_cmap('BrBG')\n fig, ax = plt.subplots(num=16,figsize=(4,3.5))\n set_figpos('3311 mac')\n\n Nx = xx.shape[1]\n\n if chrono!=None:\n kk,_ = get_plot_inds(xx,chrono,mult=40,**kwargs)\n tt = chrono.tt[kk]\n ax.set_ylabel('Time (t)')\n else:\n K = estimate_good_plot_length(xx,mult=40)\n tt = arange(K)\n ax.set_ylabel('Time indices (k)')\n\n plt.contourf(arange(Nx),tt,xx[kk],25)\n plt.colorbar()\n ax.set_position([0.125, 0.20, 0.62, 0.70])\n ax.set_title(\"Hovmoller diagram (of 'Truth')\")\n ax.set_xlabel('Dimension index (i)')\n add_endpoint_xtick(ax)\n\n\ndef add_endpoint_xtick(ax):\n \"\"\"Useful when xlim(right) is e.g. 39 (instead of 40).\"\"\"\n xF = ax.get_xlim()[1]\n ticks = ax.get_xticks()\n if ticks[-1] > xF:\n ticks = ticks[:-1]\n ticks = np.append(ticks, xF)\n ax.set_xticks(ticks)\n\n\ndef integer_hist(E,N,centrd=False,weights=None,**kwargs):\n \"\"\"Histogram for integers.\"\"\"\n ax = plt.gca()\n rnge = (-0.5,N+0.5) if centrd else (0,N+1)\n ax.hist(E,bins=N+1,range=rnge,normed=1,weights=weights,**kwargs)\n ax.set_xlim(rnge)\n\n\ndef not_available_text(ax,txt=None,fs=20):\n if txt is None: txt = '[Not available]'\n else: txt = '[' + txt + ']'\n ax.text(0.5,0.5,txt,\n fontsize=fs,\n transform=ax.transAxes,\n va='center',ha='center',\n wrap=True)\n\ndef plot_err_components(stats):\n \"\"\"\n Plot components of the error.\n Note: it was chosen to plot(ii, mean_in_time(abs(err_i))),\n and thus the corresponding spread measure is MAD.\n If one chose instead: plot(ii, std_in_time(err_i)),\n then the corresponding measure of spread would have been std.\n This choice was made in part because (wrt. subplot 2)\n the singular values (svals) correspond to rotated MADs,\n and because rms(umisf) seems to convoluted for interpretation.\n \"\"\"\n fgE = plt.figure(15,figsize=(6,6)).clf()\n set_figpos('1312 mac')\n\n chrono = stats.HMM.t\n Nx = stats.xx.shape[1]\n\n err = mean( abs(stats.err .a) ,0)\n sprd = mean( stats.mad .a ,0)\n umsft = mean( abs(stats.umisf.a) ,0)\n usprd = mean( stats.svals.a ,0)\n\n ax_r = plt.subplot(311)\n ax_r.plot( arange(Nx), err,'k',lw=2, label='Error')\n if Nx<10**3:\n ax_r.fill_between(arange(Nx),[0]*len(sprd),sprd,alpha=0.7,label='Spread')\n else:\n ax_r.plot( arange(Nx), sprd,alpha=0.7,label='Spread')\n #ax_r.set_yscale('log')\n ax_r.set_title('Element-wise error comparison')\n ax_r.set_xlabel('Dimension index (i)')\n ax_r.set_ylabel('Time-average (_a) magnitude')\n ax_r.set_ylim(bottom=mean(sprd)/10)\n ax_r.set_xlim(right=Nx-1); add_endpoint_xtick(ax_r)\n ax_r.get_xaxis().set_major_locator(MaxNLocator(integer=True))\n plt.subplots_adjust(hspace=0.55) # OR: [0.125,0.6, 0.78, 0.34]\n ax_r.legend()\n\n ax_s = plt.subplot(312)\n ax_s.set_xlabel('Principal component index')\n ax_s.set_ylabel('Time-average (_a) magnitude')\n ax_s.set_title('Spectral error comparison')\n has_been_computed = np.any(np.isfinite(umsft))\n if has_been_computed:\n L = len(umsft)\n ax_s.plot( arange(L), umsft,'k',lw=2, label='Error')\n ax_s.fill_between(arange(L),[0]*L,usprd,alpha=0.7,label='Spread')\n ax_s.set_yscale('log')\n ax_s.set_ylim(bottom=1e-4*usprd.sum())\n ax_s.set_xlim(right=Nx-1); add_endpoint_xtick(ax_s)\n ax_s.get_xaxis().set_major_locator(MaxNLocator(integer=True))\n ax_s.legend()\n else:\n not_available_text(ax_s)\n\n rmse = stats.rmse.a[chrono.maskObs_BI]\n ax_R = plt.subplot(313)\n ax_R.hist(rmse,bins=30,normed=0)\n ax_R.set_ylabel('Num. of occurence (_a)')\n ax_R.set_xlabel('RMSE')\n ax_R.set_title('Histogram of RMSE values')\n\n\ndef plot_rank_histogram(stats):\n chrono = stats.HMM.t\n\n has_been_computed = \\\n hasattr(stats,'rh') and \\\n not all(stats.rh.a[-1]==array(np.nan).astype(int))\n\n fig, ax = freshfig(24, (6,3))\n set_figpos('3331 mac')\n ax.set_title('(Mean of marginal) rank histogram (_a)')\n ax.set_ylabel('Freq. of occurence\\n (of truth in interval n)')\n ax.set_xlabel('ensemble member index (n)')\n adjust_position(ax, y0=0.05, x0=0.05, adjust_extent=True)\n\n if has_been_computed:\n ranks = stats.rh.a[chrono.maskObs_BI]\n Nx = ranks.shape[1]\n N = stats.config.N\n if not hasattr(stats,'w'):\n # Ensemble rank histogram\n integer_hist(ranks.ravel(),N)\n else:\n # Experimental: weighted rank histogram.\n # Weight ranks by inverse of particle weight. Why? Coz, with correct\n # importance weights, the \"expected value\" histogram is then flat.\n # Potential improvement: interpolate weights between particles.\n w = stats.w.a[chrono.maskObs_BI]\n K = len(w)\n w = np.hstack([w, ones((K,1))/N]) # define weights for rank N+1\n w = array([ w[arange(K),ranks[arange(K),i]] for i in range(Nx)])\n w = w.T.ravel()\n w = np.maximum(w, 1/N/100) # Artificial cap. Reduces variance, but introduces bias.\n w = 1/w\n integer_hist(ranks.ravel(),N,weights=w)\n else:\n not_available_text(ax)\n \n\ndef adjustable_box_or_forced():\n \"For set_aspect(), adjustable='box-forced' replaced by 'box' since mpl 2.2.0.\"\n from pkg_resources import parse_version as pv\n return 'box-forced' if pv(mpl.__version__) < pv(\"2.2.0\") else 'box'\n\n\ndef freshfig(num,figsize=None,*args,**kwargs):\n \"\"\"Create/clear figure.\n - If the figure does not exist: create figure it.\n This allows for figure sizing -- even on Macs.\n - Otherwise: clear figure (we avoid closing/opening so as\n to keep (potentially manually set) figure pos and size.\n - The rest is the same as:\n >>> fig, ax = suplots()\n \"\"\"\n fig = plt.figure(num=num,figsize=figsize)\n fig.clf()\n _, ax = plt.subplots(num=fig.number,*args,**kwargs)\n return fig, ax\n\ndef show_figs(fignums=None):\n \"\"\"Move all fig windows to top\"\"\"\n if fignums == None:\n fignums = plt.get_fignums()\n try:\n fignums = list(fignums)\n except:\n fignums = [fignums]\n for f in fignums:\n plt.figure(f)\n fmw = plt.get_current_fig_manager().window\n fmw.attributes('-topmost',1) # Bring to front, but\n fmw.attributes('-topmost',0) # don't keep in front\n\ndef set_figpos(loc):\n \"\"\"\n Place figure on screen, where 'loc' can be either\n NW, E, ...\n or\n 4 digits (as str or int) to define grid M,N,i,j.\n \"\"\"\n\n #Only works with both:\n #- Patrick's monitor setup (Dell with Mac central-below)\n #- TkAgg backend. (Previously: Qt4Agg)\n if not user_is_patrick or mpl.get_backend() != 'TkAgg':\n return\n fmw = plt.get_current_fig_manager().window\n\n loc = str(loc)\n\n # Qt4Agg only:\n # # Current values \n # w_now = fmw.width()\n # h_now = fmw.height()\n # x_now = fmw.x()\n # y_now = fmw.y()\n # # Constants \n # Dell_w = 2560\n # Dell_h = 1440\n # Mac_w = 2560\n # Mac_h = 1600\n # # Why is Mac monitor scaled by 1/2 ?\n # Mac_w /= 2\n # Mac_h /= 2\n # Append the string 'mac' to place on mac monitor.\n # if 'mac' in loc:\n # x0 = Dell_w/4\n # y0 = Dell_h+44\n # w0 = Mac_w\n # h0 = Mac_h-44\n # else:\n # x0 = 0\n # y0 = 0\n # w0 = Dell_w\n # h0 = Dell_h\n\n # TkAgg\n x0 = 0\n y0 = 0\n w0 = 1280\n h0 = 752\n \n # Def place function with offsets\n def place(x,y,w,h):\n #fmw.setGeometry(x0+x,y0+y,w,h) # For Qt4Agg\n geo = str(int(w)) + 'x' + str(int(h)) + \\\n '+' + str(int(x)) + '+' + str(int(y))\n fmw.geometry(newGeometry=geo) # For TkAgg\n\n if not loc[:4].isnumeric():\n if loc.startswith('NW'): loc = '2211'\n elif loc.startswith('SW'): loc = '2221'\n elif loc.startswith('NE'): loc = '2212'\n elif loc.startswith('SE'): loc = '2222'\n elif loc.startswith('W' ): loc = '1211'\n elif loc.startswith('E' ): loc = '1212'\n elif loc.startswith('S' ): loc = '2121'\n elif loc.startswith('N' ): loc = '2111'\n\n # Place\n M,N,i,j = [int(x) for x in loc[:4]]\n assert M>=i>0 and N>=j>0\n h0 -= (M-1)*25\n yoff = 25*(i-1)\n if i>1:\n yoff += 25\n place((j-1)*w0/N, yoff + (i-1)*h0/M, w0/N, h0/M)\n\n\n# stackoverflow.com/a/7396313\nfrom matplotlib import transforms as mtransforms\ndef autoscale_based_on(ax, line_handles):\n \"Autoscale axis based (only) on line_handles.\"\n ax.dataLim = mtransforms.Bbox.unit()\n for iL,lh in enumerate(line_handles):\n xy = np.vstack(lh.get_data()).T\n ax.dataLim.update_from_data_xy(xy, ignore=(iL==0))\n ax.autoscale_view()\n\n\nfrom matplotlib.widgets import CheckButtons\nimport textwrap\ndef toggle_lines(ax=None,autoscl=True,numbering=False,txtwidth=15,txtsize=None,state=None):\n \"\"\"\n Make checkbuttons to toggle visibility of each line in current plot.\n autoscl : Rescale axis limits as required by currently visible lines.\n numbering: Add numbering to labels.\n txtwidth : Wrap labels to this length.\n\n State of checkboxes can be inquired by \n OnOff = [lh.get_visible() for lh in ax.findobj(lambda x: isinstance(x,mpl.lines.Line2D))[::2]]\n \"\"\"\n\n if ax is None: ax = plt.gca()\n if txtsize is None: txtsize = mpl.rcParams['font.size']\n\n # Get lines and their properties\n lines = {'handle': list(ax.get_lines())}\n for prop in ['label','color','visible']:\n lines[prop] = [plt.getp(x,prop) for x in lines['handle']]\n # Put into pandas for some reason\n lines = pd.DataFrame(lines)\n # Rm those that start with _\n lines = lines[~lines.label.str.startswith('_')]\n\n # Adjust labels\n if numbering: lines['label'] = [str(i)+': '+lbl for i,lbl in enumerate(lines['label'])]\n if txtwidth: lines['label'] = [textwrap.fill(lbl,width=txtwidth) for lbl in lines['label']]\n\n # Set state. BUGGY? sometimes causes MPL complaints after clicking boxes\n if state is not None:\n state = array(state).astype(bool)\n lines.visible = state\n for i,x in enumerate(state):\n lines['handle'][i].set_visible(x)\n\n # Setup buttons\n # When there's many, the box-sizing is awful, but difficult to fix.\n W = 0.23 * txtwidth/15 * txtsize/10\n N = len(lines)\n nBreaks = sum(lbl.count('\\n') for lbl in lines['label']) # count linebreaks\n H = min(1,0.05*(N+nBreaks))\n plt.subplots_adjust(left=W+0.12,right=0.97)\n rax = plt.axes([0.05, 0.5-H/2, W, H])\n check = CheckButtons(rax, lines.label, lines.visible)\n\n # Adjust button style\n for i in range(N):\n check.rectangles[i].set(lw=0,facecolor=lines.color[i])\n check.labels[i].set(color=lines.color[i])\n if txtsize: check.labels[i].set(size=txtsize)\n\n # Callback\n def toggle_visible(label):\n ind = lines.label==label\n handle = lines[ind].handle.item()\n vs = not lines[ind].visible.item()\n handle.set_visible( vs )\n lines.loc[ind,'visible'] = vs\n if autoscl:\n autoscale_based_on(ax,lines[lines.visible].handle)\n plt.draw()\n check.on_clicked(toggle_visible)\n\n # Return focus\n plt.sca(ax)\n\n # Must return (and be received) so as not to expire.\n return check\n\n\ndef toggle_viz(*handles,prompt=False,legend=False,pause=True):\n \"\"\"Toggle visibility of the graphics with handle handles.\"\"\"\n\n are_viz = []\n for h in handles:\n\n # Core functionality: turn on/off\n is_viz = not h.get_visible()\n h.set_visible(is_viz)\n are_viz += [is_viz]\n\n # Legend updating. Basic version: works by\n # - setting line's label to actual_label/'_nolegend_' if is_viz/not\n # - re-calling legend()\n if legend:\n if is_viz:\n try:\n h.set_label(h.actual_label)\n except AttributeError:\n pass\n else:\n h.actual_label = h.get_label()\n h.set_label('_nolegend_')\n # Legend refresh\n ax = h.axes\n with warnings.catch_warnings():\n warnings.simplefilter(\"error\",category=UserWarning)\n try:\n ax.legend()\n except UserWarning:\n # If all labels are '_nolabel_' then ax.legend() throws warning,\n # and quits before refreshing. => Refresh by creating/rm another legend.\n ax.legend('TMP').remove()\n\n if prompt: input(\"Press <Enter> to continue...\")\n if pause: plt.pause(0.02)\n\n return are_viz\n\n\ndef savefig_n(f=None, ext='.pdf'):\n \"\"\"\n Simplify the exporting of a figure, especially when it's part of a series.\n \"\"\"\n assert savefig_n.index>=0, \"Initalize using savefig_n.index = 1 in your script\"\n if f is None:\n f = inspect.getfile(inspect.stack()[1][0]) # Get __file__ of caller\n f = save_dir(f) # Prep save dir\n f = f + str(savefig_n.index) + ext # Compose name\n print(\"Saving fig to:\",f) # Print\n plt.savefig(f) # Save\n savefig_n.index += 1 # Increment index\n plt.pause(0.1) # For safety?\nsavefig_n.index = -1\n\n\n\ndef nrowcol(nTotal,AR=1):\n \"Return integer nrows and ncols such that nTotal ≈ nrows*ncols.\"\n nrows = int(floor(sqrt(nTotal)/AR))\n ncols = int(ceil(nTotal/nrows))\n return nrows, ncols\n\n\nfrom matplotlib.gridspec import GridSpec\ndef axes_with_marginals(n_joint, n_marg,**kwargs):\n \"\"\"\n Create a joint axis along with two marginal axes.\n\n Example:\n >>> ax_s, ax_x, ax_y = axes_with_marginals(4, 1)\n >>> x, y = np.random.randn(2,500)\n >>> ax_s.scatter(x,y)\n >>> ax_x.hist(x)\n >>> ax_y.hist(y,orientation=\"horizontal\")\n \"\"\"\n\n N = n_joint + n_marg\n\n # Method 1\n #fig, ((ax_s, ax_y), (ax_x, _)) = plt.subplots(2,2,num=plt.gcf().number,\n #sharex='col',sharey='row',gridspec_kw={\n #'height_ratios':[n_joint,n_marg],\n #'width_ratios' :[n_joint,n_marg]})\n #_.set_visible(False) # Actually removing would bug the axis ticks etc.\n \n # Method 2\n gs = GridSpec(N,N,**kwargs)\n fig = plt.gcf()\n ax_s = fig.add_subplot(gs[n_marg:N ,0 :n_joint])\n ax_x = fig.add_subplot(gs[0 :n_marg,0 :n_joint],sharex=ax_s)\n ax_y = fig.add_subplot(gs[n_marg:N ,n_joint:N ],sharey=ax_s)\n # Cannot delete ticks coz axis are shared\n plt.setp(ax_x.get_xticklabels(), visible=False)\n plt.setp(ax_y.get_yticklabels(), visible=False)\n\n return ax_s, ax_x, ax_y\n\nfrom matplotlib.patches import Ellipse\ndef cov_ellipse(ax, mu, sigma, **kwargs):\n \"\"\"\n Draw ellipse corresponding to (Gaussian) 1-sigma countour of cov matrix.\n\n Inspired by stackoverflow.com/q/17952171\n\n Example:\n >>> ellipse = cov_ellipse(ax, y, R,\n >>> facecolor='none', edgecolor='y',lw=4,label='$1\\\\sigma$')\n \"\"\"\n\n # Cov --> Width, Height, Theta\n vals, vecs = np.linalg.eigh(sigma)\n x, y = vecs[:, -1] # x-y components of largest (last) eigenvector\n theta = np.degrees(np.arctan2(y, x))\n theta = theta % 180\n\n h, w = 2 * np.sqrt(vals.clip(0))\n\n # Get artist\n e = Ellipse(mu, w, h, theta, **kwargs)\n\n ax.add_patch(e)\n e.set_clip_box(ax.bbox) # why is this necessary?\n\n # Return artist\n return e\n \n\n\n\n" ]
[ [ "numpy.mod", "numpy.zeros", "numpy.roll", "numpy.ones" ], [ "matplotlib.transforms.Bbox.unit", "matplotlib.patches.Ellipse", "matplotlib.widgets.CheckButtons", "matplotlib.ticker.MaxNLocator", "matplotlib.gridspec.GridSpec" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
pyl1b/decay
[ "7200516455fc03351ad658af66b5cc39b2b2d50a", "7200516455fc03351ad658af66b5cc39b2b2d50a" ]
[ "decay/decays/sample/half_sudden.py", "decay/decays/sample/sudden.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nContains the definition of the SuddenDecay class.\n\"\"\"\nfrom __future__ import unicode_literals\nfrom __future__ import print_function\n\nimport logging\nimport numpy as np\n\nfrom . import SampleBasedDecay\n\nlogger = logging.getLogger('decay.half_sudden')\n\n\nclass HalfSuddenDecay(SampleBasedDecay):\n \"\"\"\n Class that decays the value following the sigmoid curve.\n\n Sigmoid is:\n k\n Y = --------------------- + 1\n a + bx\n 1 + e\n\n This curve used a=10, b=-10, k=-2\n This intersects the Y axis at\n +1 and the X axis at -1 and +1. We're interested only in the\n positive x.\n \"\"\"\n def __init__(self, *args, **kwargs):\n \"\"\" Constructor. \"\"\"\n super(HalfSuddenDecay, self).__init__(\n decay_name='.decay.half_sudden.', *args, **kwargs)\n\n def __str__(self):\n \"\"\" Represent this object as a human-readable string. \"\"\"\n return 'SuddenDecay()'\n\n def __repr__(self):\n \"\"\" Represent this object as a python constructor. \"\"\"\n return 'SuddenDecay()'\n\n decay_x = np.array([\n 0.0,\n 0.05263157894736842,\n 0.10526315789473684,\n 0.15789473684210525,\n 0.21052631578947367,\n 0.2631578947368421,\n 0.3157894736842105,\n 0.3684210526315789,\n 0.42105263157894735,\n 0.47368421052631576,\n 0.5263157894736842,\n 0.5789473684210527,\n 0.631578947368421,\n 0.6842105263157894,\n 0.7368421052631579,\n 0.7894736842105263,\n 0.8421052631578947,\n 0.894736842105263,\n 0.9473684210526315,\n 1.0,\n ])\n\n decay_y = np.array([\n 1.0,\n 0.9998463162863197,\n 0.9997398757902081,\n 0.9995597314205974,\n 0.999254877774581,\n 0.9987390684889199,\n 0.9978665723466811,\n 0.9963914462121438,\n 0.9938994809709213,\n 0.9896955173948945,\n 0.9826197888368629,\n 0.9707568136416107,\n 0.9509968204584932,\n 0.9184373437414545,\n 0.8657330022308358,\n 0.7828273568190789,\n 0.6581107760257361,\n 0.4825598285864794,\n 0.2572468384313463,\n 0.0,\n ])\n", "# -*- coding: utf-8 -*-\n\"\"\"\nContains the definition of the SuddenDecay class.\n\"\"\"\nfrom __future__ import unicode_literals\nfrom __future__ import print_function\n\nimport logging\nimport numpy as np\n\nfrom . import SampleBasedDecay\n\nlogger = logging.getLogger('decay.sudden')\n\n\nclass SuddenDecay(SampleBasedDecay):\n \"\"\"\n Class that decays the value following the sigmoid curve.\n\n Sigmoid is:\n k\n Y = --------------------- + 1\n a + bx\n 1 + e\n\n This curve used a=100, b=-100, k=-2\n\n This intersects the Y axis at\n +1 and the X axis at -1 and +1. We're interested only in the\n positive x.\n \"\"\"\n def __init__(self, *args, **kwargs):\n \"\"\" Constructor. \"\"\"\n super(SuddenDecay, self).__init__(\n decay_name='.decay.sudden.', *args, **kwargs)\n\n def __str__(self):\n \"\"\" Represent this object as a human-readable string. \"\"\"\n return 'SuddenDecay()'\n\n def __repr__(self):\n \"\"\" Represent this object as a python constructor. \"\"\"\n return 'SuddenDecay()'\n\n decay_x = np.array([\n 0.0,\n 0.05263157894736842,\n 0.10526315789473684,\n 0.15789473684210525,\n 0.21052631578947367,\n 0.2631578947368421,\n 0.3157894736842105,\n 0.3684210526315789,\n 0.42105263157894735,\n 0.47368421052631576,\n 0.5263157894736842,\n 0.5789473684210527,\n 0.631578947368421,\n 0.6842105263157894,\n 0.7368421052631579,\n 0.7894736842105263,\n 0.8421052631578947,\n 0.894736842105263,\n 0.9473684210526315,\n 1.0,\n ])\n\n decay_y = np.array([\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 1.0,\n 0.9999999999999998,\n 0.9999999999999614,\n 0.9999999999925487,\n 0.9999999985612403,\n 0.9999997221895089,\n 0.9999463589234484,\n 0.9896955173948946,\n 0.0,\n ])\n" ]
[ [ "numpy.array" ], [ "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
glauberrleite/system-identifier
[ "982e04b7df84211d5797d259e9cb431d83b00529", "982e04b7df84211d5797d259e9cb431d83b00529" ]
[ "test.py", "LeastSquares.py" ]
[ "from Util import Util\nimport numpy\nimport matplotlib.pyplot as pyplot\n\ninputArray = numpy.ones(100)\ntheta = [ 2.705, -2.448, 0.7408, 0.0523, -0.0855, 0.035 ]\norderOutput = 3\norderInput = 3\nsampleRate = 0.1\n\n\ny = Util.computeOutput(inputArray, theta, orderOutput, orderInput)\nt = numpy.arange(0, len(y)*sampleRate, sampleRate)\n\npyplot.plot(t, y, 'r')\npyplot.plot(t, inputArray, 'b--')\npyplot.show()\n", "import numpy\n\nclass LeastSquares:\n def __init__(self, y, u, e, orderOutput, orderInput, orderError):\n self.y = y\n self.u = u\n self.e = e\n self.estimative = numpy.zeros(len(y))\n self.error = numpy.zeros(len(y))\n\n self.phi = self.__buildRegressionMatrix(orderOutput, orderInput, orderError)\n\n self.theta = numpy.dot(numpy.linalg.pinv(self.phi), y)\n\n self._estimate()\n\n self.error = self.y - self.estimative\n \n def _estimate(self):\n self.estimative = numpy.dot(self.phi , self.theta)\n\n def showResults(self):\n print(\"Theta:\")\n print(self.theta)\n\n print(\"Error:\")\n print(numpy.mean(self.error))\n\n\n def __buildRegressionMatrix(self, orderOutput, orderInput, orderError):\n regressionMatrix = numpy.zeros((len(self.y), orderOutput + orderInput + orderError))\n\n for i in range(len(regressionMatrix)):\n for j in range(1, orderOutput + 1):\n if (i - j) < 0:\n regressionMatrix[i, j - 1] = 0\n else:\n regressionMatrix[i, j - 1] = self.y[i - j]\n\n for j in range(1, orderInput + 1):\n if (i - j) < 0:\n regressionMatrix[i, j - 1 + orderOutput] = 0\n else:\n regressionMatrix[i, j - 1 + orderOutput] = self.u[i - j]\n\n for j in range(1, orderError + 1):\n if (i - j) < 0:\n regressionMatrix[i, j - 1 + orderOutput + orderInput] = 0\n else:\n regressionMatrix[i, j - 1 + orderOutput + orderInput] = self.e[i - j]\n\n return regressionMatrix\n\n" ]
[ [ "matplotlib.pyplot.plot", "matplotlib.pyplot.show", "numpy.ones" ], [ "numpy.dot", "numpy.mean", "numpy.linalg.pinv" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [ "1.10", "1.12", "1.11", "1.19", "1.24", "1.13", "1.16", "1.9", "1.18", "1.23", "1.21", "1.22", "1.20", "1.7", "1.15", "1.14", "1.17", "1.8" ], "pandas": [], "scipy": [], "tensorflow": [] } ]
Imperial-lord/IITG
[ "df4233905d2954511d5b16666f0d44cc38b9df90", "df4233905d2954511d5b16666f0d44cc38b9df90" ]
[ "Semester 6/MA 374 (Financial Engg. Lab)/Lab 1/180123062_ABSatyaprakash_q1 1.py", "Semester 6/MA 322 (Scientific Computing Theory)/Labs/Lab 4/Code/q5.py" ]
[ "# Q.1 Run your program for M = 1, 5, 10, 20, 50, 100, 200, 400 \n# to get the initial option prices and tabulate them\n\n# Pandas : pip install pandas \n# Matplotlib: pip install matplotlib \n# Numpy: pip install numpy \n# Ipython: pip install ipython\n\n\nimport math\nimport pandas as pd\nfrom IPython.display import display\n\n# Function to get Option Price for a given M\ndef getOptionPrice(M, u, d, p):\n callList = [0]*(M+1)\n putList = [0]*(M+1)\n \n for i in range(M+1):\n callList[i] = max(S0*(u**i)*(d**(M-i)) - K, 0)\n putList[i] = max(0, K - S0*(u**i)*(d**(M-i)))\n \n for i in range(M):\n for j in range(M-i):\n callList[j] = ((1-p)*callList[j] + p*callList[j+1])*math.exp(-r*T/M)\n putList[j] = ((1-p)*putList[j] + p*putList[j+1])*math.exp(-r*T/M)\n return callList[0], putList[0]\n\n# Given data\nS0=100\nK=105\nT=5\nr=0.05\nsig=0.3\nMList=[1, 5, 10, 20, 50, 100, 200, 400]\n\n# Lists to store the option prices\ncallPrices = []\nputPrices = []\n\n\nfor M in MList:\n dt = T/M\n u = math.exp(sig*math.sqrt(dt)+(r-sig*sig/2)*dt)\n d = math.exp(-sig*math.sqrt(dt)+(r-sig*sig/2)*dt)\n p = (math.exp(r*dt)-d)/(u-d)\n \n # Check if No Arbitrage Principle has got violated\n if p < 0 or p > 1:\n print(\"No Arbitrage Principle has been Violated\")\n CallPrices.append('-')\n PutPrices.append('-')\n continue\n \n call, put = getOptionPrice(M, u, d, p)\n callPrices.append(call)\n putPrices.append(put)\n\n# Display the data using Pandas Dataframe\ndf = pd.DataFrame({'Step Size':MList,'Call Option Price': callPrices, 'Put Option Price': putPrices},)\ndisplay(df)\n", "# Question 05, Lab 04\n# AB Satyaprakash - 180123062\n\n# imports ----------------------------------------------------------------------------\nfrom sympy.abc import t\nfrom sympy import evalf, integrate\nfrom math import ceil, sqrt\nimport numpy as np\n\n# functions --------------------------------------------------------------------------\n\n\ndef f(x):\n return 1/(x+4)\n\n\ndef errorCompositeTrapezoidal(a, b):\n err = 10**(-5)\n d2fmax = 1/32\n val = (1/err)*(b-a)*(b-a)*(b-a)*(1/12)*d2fmax\n n = ceil(sqrt(val))\n print(\"Constraints :\", \"h <=\", (b-a)/sqrt(val), \"and n >=\", n)\n return n\n\n\ndef errCompositeSimpson(a, b):\n err = 10**(-5)\n d4fmax = 24/(4**5)\n val = (1/err)*pow(b-a, 5)*(1/180)*d4fmax\n n = ceil(sqrt(sqrt(val)))\n if n % 2 == 0:\n print(\"Constraints :\", \"h <=\", (b-a) /\n sqrt(sqrt(val)), \"and n >=\", n)\n return n\n else:\n print(\"Constraints :\", \"h <=\", (b-a) /\n sqrt(sqrt(val)), \"and n >=\", n+1)\n return n+1\n\n\ndef errCompositeMidpoint(a, b):\n err = 10**(-5)\n d2fmax = 1/32\n val = (1/err)*(b-a)*(b-a)*(b-a)*(1/6)*d2fmax\n n = ceil(sqrt(val))\n if n % 2 == 0:\n print(\"Constraints :\", \"h <=\", (b-a)/sqrt(val), \"and n >=\", n)\n return n\n else:\n print(\"Constraints :\", \"h <=\", (b-a)/sqrt(val), \"and n >=\", n+1)\n return n+1\n\n\ndef compositeTrapezoidalRule(X):\n sum = 0\n a, b = X[0], X[-1]\n n = X.shape[0]\n h = (b-a)/(n-1)\n for i in range(n):\n x = X[i]\n if(i == 0 or i == n-1):\n sum += f(x)/2\n else:\n sum += f(x)\n return (h*sum)\n\n\ndef compositeSimpsonRule(X):\n sum = 0\n a, b = X[0], X[-1]\n n = X.shape[0]\n h = (b-a)/(n-1)\n for i in range(n):\n x = X[i]\n if(i == 0 or i == n-1):\n sum += f(x)\n else:\n if(i % 2 == 0):\n sum += 2*f(x)\n else:\n sum += 4*f(x)\n return (h*sum)/3\n\n\ndef compositeMidpointRule(X):\n a, b = X[0], X[-1]\n n = X.shape[0]-1\n h = (b-a)/(n)\n sum = 0\n for i in range(n):\n xi = a+i*h\n xi_nex = a+(i+1)*h\n pt = (xi+xi_nex)/2\n sum += f(pt)\n return h*sum\n\n\n# program body\nfunc = 1/(t+4)\na, b = 0, 2\n\n\nI = integrate(func, (t, a, b)).evalf()\nprint('Actual value of integral is', I)\n\nprint(\"\\nFor part a: (Trapezoidal Rule)\")\nn = errorCompositeTrapezoidal(a, b)\nh = (b-a)/n\nX = np.arange(a, b+h/2, h)\nestimatedIntegral = compositeTrapezoidalRule(X)\nprint('Required tuple (n,h) with error < 0.00001 is ({}, {})'.format(n, h))\nprint('Estimated value of integral is', estimatedIntegral)\nprint('Error in this case is', abs(estimatedIntegral-I))\n\nprint(\"\\nFor part b: (Simpson Rule)\")\nn = errCompositeSimpson(a, b)\nh = (b-a)/n\nX = np.arange(a, b+h/2, h)\nestimatedIntegral = compositeSimpsonRule(X)\nprint('Required tuple (n,h) with error < 0.00001 is ({}, {})'.format(n, h))\nprint('Estimated value of integral is', estimatedIntegral)\nprint('Error in this case is', abs(estimatedIntegral-I))\n\nprint(\"\\nFor part c: (Midpoint Rule)\")\nn = errCompositeMidpoint(a, b)\nh = (b-a)/n\nX = np.arange(a, b+h/2, h)\nestimatedIntegral = compositeMidpointRule(X)\nprint('Required tuple (n,h) with error < 0.00001 is ({}, {})'.format(n, h))\nprint('Estimated value of integral is', estimatedIntegral)\nprint('Error in this case is', abs(estimatedIntegral-I))\n" ]
[ [ "pandas.DataFrame" ], [ "numpy.arange" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Pathology-Consistent-Stain-Transfer/Unpaired-Stain-Transfer-using-Pathology-Consistent-Constrained-Generative-Adversarial-Networks
[ "b57c56b314e65a0f31d9e44f57174108599c8b14" ]
[ "Stain_seperation/stain_Norm_Vahadane.py" ]
[ "\"\"\"\nStain normalization inspired by method of:\n\nA. Vahadane et al., ‘Structure-Preserving Color Normalization and Sparse Stain Separation for Histological Images’, IEEE Transactions on Medical Imaging, vol. 35, no. 8, pp. 1962–1971, Aug. 2016.\n\nUses the spams package:\n\nhttp://spams-devel.gforge.inria.fr/index.html\n\nUse with python via e.g https://anaconda.org/conda-forge/python-spams\n\"\"\"\n# windows: pip install spams-bin\n# linux:pip install python-spams\nimport spams\nimport numpy as np\nimport Stain_seperation.stain_utils as ut\n\n\ndef get_stain_matrix(I, threshold=0.8, lamda=0.1):\n \"\"\"\n Get 2x3 stain matrix. First row H and second row E\n :param I:\n :param threshold:\n :param lamda:\n :return:\n \"\"\"\n mask = ut.notwhite_mask(I, thresh=threshold).reshape((-1,))\n OD = ut.RGB_to_OD(I).reshape((-1, 3))\n OD = OD[mask]\n dictionary = spams.trainDL(OD.T, K=2, lambda1=lamda, mode=2, modeD=0, posAlpha=True, posD=True, verbose=False).T\n if dictionary[0, 0] < dictionary[1, 0]:\n dictionary = dictionary[[1, 0], :]\n dictionary = ut.normalize_rows(dictionary)\n return dictionary\n\n\nclass normalizer(object):\n \"\"\"\n A stain normalization object\n \"\"\"\n\n def __init__(self):\n\n self.stain_matrix_target = np.array([[0.62600721, 0.62330743, 0.46861798],\n [0.3203682, 0.5473311, 0.77317067]])\n # Ki67 Normalization initial matirx obtained from \"Sample_target\"\n # [[0.58594418, 0.68469766, 0.43342651]\n # [0.3203682, 0.5473311, 0.77317067]]\n\n # [[0.62600721,0.62330743,0.46861798],\n # [0.35395456,0.58236586,0.73182387]]\n\n # [[0.58583788, 0.66078505, 0.46920901],\n # [0.3536072, 0.56354522, 0.74657801]]\n\n # HE Normalization initial matirx obtained from \"Sample_target\"\n # self.stain_matrix_target = np.array([[0.60559458, 0.69559906, 0.38651928],\n # [0.1100605, 0.94701408, 0.30174662]])\n # [[0.59958405,0.70248408,0.38342546]\n # [0.06893222,0.95236792,0.2970584]]\n\n # [[0.60559458 0.69559906 0.38651928]\n # [0.1100605 0.94701408 0.30174662]]\n\n # [[0.60715608 0.72015621 0.3357626]\n # [0.21154943 0.9271104 0.30937542]]\n\n def fit(self, target_list):\n if target_list.__len__() > 1:\n Ws = []\n for f_id in range(target_list.__len__()):\n target = ut.read_image(target_list[f_id])\n target = ut.standardize_brightness(target)\n stain_matrix_target = get_stain_matrix(target)\n Ws.append(stain_matrix_target)\n Ws = np.asarray(Ws)\n Median_W = np.median(Ws, axis=0)\n self.stain_matrix_target = ut.normalize_rows(Median_W)\n print('WSI target stain matrix: ', self.stain_matrix_target)\n else:\n target = ut.read_image(target_list[0])\n target = ut.standardize_brightness(target)\n self.stain_matrix_target = get_stain_matrix(target)\n print('Single target image stain matrix: ', self.stain_matrix_target)\n\n def stains_Vec_RGB(self, stain_matrix_target):\n return ut.OD_to_RGB(stain_matrix_target)\n\n def transform(self, I):\n I = ut.standardize_brightness(I)\n stain_matrix_source = get_stain_matrix(I)\n source_concentrations = ut.get_concentrations(I, stain_matrix_source)\n return (255 * np.exp(-1 * np.dot(source_concentrations, self.stain_matrix_target).reshape(I.shape))).astype(\n np.uint8)\n\n def hematoxylin_eosin(self, I):\n I = ut.standardize_brightness(I)\n h, w, _ = I.shape\n stain_matrix_source = get_stain_matrix(I)\n source_concentrations = ut.get_concentrations(I, stain_matrix_source)\n\n H = source_concentrations[:, 0].reshape(h, w)\n H = np.exp(-1 * H)\n\n E = source_concentrations[:, 1].reshape(h, w)\n E = np.exp(-1 * E)\n\n # H = np.reshape(source_concentrations[:, 0], newshape=(h*w, 1))\n # H = (255 * np.exp(-1 * np.dot(H, np.reshape(stain_matrix_source[0],\n # newshape=(1, 3))).reshape(I.shape))).astype(np.uint8)\n # E = np.reshape(source_concentrations[:, 1], newshape=(h*w, 1))\n # E = (255 * np.exp(-1 * np.dot(E, np.reshape(stain_matrix_source[1],\n # newshape=(1, 3))).reshape(I.shape))).astype(np.uint8)\n return H, E\n" ]
[ [ "numpy.dot", "numpy.asarray", "numpy.median", "numpy.array", "numpy.exp" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Meghanath-Data/ml-on-gcp
[ "bfd96dce610e26236c4448ba0d4eb430ca2817ff" ]
[ "example_zoo/tensorflow/models/mnist/official/mnist/mnist.py" ]
[ "# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Convolutional Neural Network Estimator for MNIST, built with tf.layers.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom absl import app as absl_app\nfrom absl import flags\nflags.DEFINE_string(name=\"job-dir\", default=\"/tmp\", help=\"AI Platform Training passes this to the training script.\")\nimport tensorflow as tf # pylint: disable=g-bad-import-order\n\nfrom official.mnist import dataset\nfrom official.utils.flags import core as flags_core\nfrom official.utils.logs import hooks_helper\nfrom official.utils.misc import distribution_utils\nfrom official.utils.misc import model_helpers\n\n\nLEARNING_RATE = 1e-4\n\n\ndef create_model(data_format):\n \"\"\"Model to recognize digits in the MNIST dataset.\n\n Network structure is equivalent to:\n https://github.com/tensorflow/tensorflow/blob/r1.5/tensorflow/examples/tutorials/mnist/mnist_deep.py\n and\n https://github.com/tensorflow/models/blob/master/tutorials/image/mnist/convolutional.py\n\n But uses the tf.keras API.\n\n Args:\n data_format: Either 'channels_first' or 'channels_last'. 'channels_first' is\n typically faster on GPUs while 'channels_last' is typically faster on\n CPUs. See\n https://www.tensorflow.org/performance/performance_guide#data_formats\n\n Returns:\n A tf.keras.Model.\n \"\"\"\n if data_format == 'channels_first':\n input_shape = [1, 28, 28]\n else:\n assert data_format == 'channels_last'\n input_shape = [28, 28, 1]\n\n l = tf.keras.layers\n max_pool = l.MaxPooling2D(\n (2, 2), (2, 2), padding='same', data_format=data_format)\n # The model consists of a sequential chain of layers, so tf.keras.Sequential\n # (a subclass of tf.keras.Model) makes for a compact description.\n return tf.keras.Sequential(\n [\n l.Reshape(\n target_shape=input_shape,\n input_shape=(28 * 28,)),\n l.Conv2D(\n 32,\n 5,\n padding='same',\n data_format=data_format,\n activation=tf.nn.relu),\n max_pool,\n l.Conv2D(\n 64,\n 5,\n padding='same',\n data_format=data_format,\n activation=tf.nn.relu),\n max_pool,\n l.Flatten(),\n l.Dense(1024, activation=tf.nn.relu),\n l.Dropout(0.4),\n l.Dense(10)\n ])\n\n\ndef define_mnist_flags():\n flags_core.define_base()\n flags_core.define_performance(num_parallel_calls=False)\n flags_core.define_image()\n flags.adopt_module_key_flags(flags_core)\n flags_core.set_defaults(data_dir='/tmp/mnist_data',\n model_dir='/tmp/mnist_model',\n batch_size=100,\n train_epochs=40)\n\n\ndef model_fn(features, labels, mode, params):\n \"\"\"The model_fn argument for creating an Estimator.\"\"\"\n model = create_model(params['data_format'])\n image = features\n if isinstance(image, dict):\n image = features['image']\n\n if mode == tf.estimator.ModeKeys.PREDICT:\n logits = model(image, training=False)\n predictions = {\n 'classes': tf.argmax(logits, axis=1),\n 'probabilities': tf.nn.softmax(logits),\n }\n return tf.estimator.EstimatorSpec(\n mode=tf.estimator.ModeKeys.PREDICT,\n predictions=predictions,\n export_outputs={\n 'classify': tf.estimator.export.PredictOutput(predictions)\n })\n if mode == tf.estimator.ModeKeys.TRAIN:\n optimizer = tf.train.AdamOptimizer(learning_rate=LEARNING_RATE)\n\n logits = model(image, training=True)\n loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits)\n accuracy = tf.metrics.accuracy(\n labels=labels, predictions=tf.argmax(logits, axis=1))\n\n # Name tensors to be logged with LoggingTensorHook.\n tf.identity(LEARNING_RATE, 'learning_rate')\n tf.identity(loss, 'cross_entropy')\n tf.identity(accuracy[1], name='train_accuracy')\n\n # Save accuracy scalar to Tensorboard output.\n tf.summary.scalar('train_accuracy', accuracy[1])\n\n return tf.estimator.EstimatorSpec(\n mode=tf.estimator.ModeKeys.TRAIN,\n loss=loss,\n train_op=optimizer.minimize(loss, tf.train.get_or_create_global_step()))\n if mode == tf.estimator.ModeKeys.EVAL:\n logits = model(image, training=False)\n loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits)\n return tf.estimator.EstimatorSpec(\n mode=tf.estimator.ModeKeys.EVAL,\n loss=loss,\n eval_metric_ops={\n 'accuracy':\n tf.metrics.accuracy(\n labels=labels, predictions=tf.argmax(logits, axis=1)),\n })\n\n\ndef run_mnist(flags_obj):\n \"\"\"Run MNIST training and eval loop.\n\n Args:\n flags_obj: An object containing parsed flag values.\n \"\"\"\n model_helpers.apply_clean(flags_obj)\n model_function = model_fn\n\n session_config = tf.ConfigProto(\n inter_op_parallelism_threads=flags_obj.inter_op_parallelism_threads,\n intra_op_parallelism_threads=flags_obj.intra_op_parallelism_threads,\n allow_soft_placement=True)\n\n distribution_strategy = distribution_utils.get_distribution_strategy(\n flags_core.get_num_gpus(flags_obj), flags_obj.all_reduce_alg)\n\n run_config = tf.estimator.RunConfig(\n train_distribute=distribution_strategy, session_config=session_config)\n\n data_format = flags_obj.data_format\n if data_format is None:\n data_format = ('channels_first'\n if tf.test.is_built_with_cuda() else 'channels_last')\n mnist_classifier = tf.estimator.Estimator(\n model_fn=model_function,\n model_dir=flags_obj.model_dir,\n config=run_config,\n params={\n 'data_format': data_format,\n })\n\n # Set up training and evaluation input functions.\n def train_input_fn():\n \"\"\"Prepare data for training.\"\"\"\n\n # When choosing shuffle buffer sizes, larger sizes result in better\n # randomness, while smaller sizes use less memory. MNIST is a small\n # enough dataset that we can easily shuffle the full epoch.\n ds = dataset.train(flags_obj.data_dir)\n ds = ds.cache().shuffle(buffer_size=50000).batch(flags_obj.batch_size)\n\n # Iterate through the dataset a set number (`epochs_between_evals`) of times\n # during each training session.\n ds = ds.repeat(flags_obj.epochs_between_evals)\n return ds\n\n def eval_input_fn():\n return dataset.test(flags_obj.data_dir).batch(\n flags_obj.batch_size).make_one_shot_iterator().get_next()\n\n # Set up hook that outputs training logs every 100 steps.\n train_hooks = hooks_helper.get_train_hooks(\n flags_obj.hooks, model_dir=flags_obj.model_dir,\n batch_size=flags_obj.batch_size)\n\n # Train and evaluate model.\n for _ in range(flags_obj.train_epochs // flags_obj.epochs_between_evals):\n mnist_classifier.train(input_fn=train_input_fn, hooks=train_hooks)\n eval_results = mnist_classifier.evaluate(input_fn=eval_input_fn)\n print('\\nEvaluation results:\\n\\t%s\\n' % eval_results)\n\n if model_helpers.past_stop_threshold(flags_obj.stop_threshold,\n eval_results['accuracy']):\n break\n\n # Export the model\n if flags_obj.export_dir is not None:\n image = tf.placeholder(tf.float32, [None, 28, 28])\n input_fn = tf.estimator.export.build_raw_serving_input_receiver_fn({\n 'image': image,\n })\n mnist_classifier.export_savedmodel(flags_obj.export_dir, input_fn,\n strip_default_attrs=True)\n\n\ndef main(_):\n run_mnist(flags.FLAGS)\n\n\nif __name__ == '__main__':\n tf.logging.set_verbosity(tf.logging.INFO)\n define_mnist_flags()\n absl_app.run(main)\n" ]
[ [ "tensorflow.nn.softmax", "tensorflow.estimator.Estimator", "tensorflow.losses.sparse_softmax_cross_entropy", "tensorflow.estimator.export.PredictOutput", "tensorflow.estimator.export.build_raw_serving_input_receiver_fn", "tensorflow.test.is_built_with_cuda", "tensorflow.identity", "tensorflow.placeholder", "tensorflow.train.get_or_create_global_step", "tensorflow.ConfigProto", "tensorflow.logging.set_verbosity", "tensorflow.train.AdamOptimizer", "tensorflow.estimator.RunConfig", "tensorflow.argmax", "tensorflow.summary.scalar" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]