repo_name
stringlengths 6
130
| hexsha
sequence | file_path
sequence | code
sequence | apis
sequence | possible_versions
list |
---|---|---|---|---|---|
geraldmc/DL4CV-2022 | [
"d734290849244816e4861efc0578325684c58409"
] | [
"project-I/loader/gtsrb_data.py"
] | [
"import os\nimport torch\nimport pandas as pd\nfrom skimage import io, transform\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms, utils\nfrom PIL import Image\n\nfrom loader.transforms import base_transform\n\n# See: https://debuggercafe.com/custom-dataset-and-dataloader-in-pytorch/\n\nclass GTSRB_Test(Dataset):\n\n def __init__(self, root_dir, test=True):\n \"\"\"\n \"\"\"\n self.root_dir = root_dir\n if test:\n self.sub_directory = 'Final_Test/Images/'\n self.csv_file_name = 'GT-final_test.csv'\n self.transform = base_transform\n self.frame = None\n\n csv_file_path = os.path.join(self.root_dir, \n self.sub_directory, \n self.csv_file_name)\n \n self.csv_data = pd.read_csv(csv_file_path, sep=';')\n\n def __len__(self):\n return len(self.csv_data)\n\n def __getitem__(self, idx):\n img_path = os.path.join(self.root_dir, \n self.sub_directory,\n self.csv_data.iloc[idx, 0])\n img_frame_coords = ( self.csv_data.iloc[idx, 3:7]) # Roi.X1, Roi.Y1, Roi.X2, Roi.Y2\n \n img = Image.open(img_path)\n class_id = self.csv_data.iloc[idx, 7]\n\n if self.transform is not None:\n img = self.transform(img)\n\n return img, class_id"
] | [
[
"pandas.read_csv"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
Shikhargupta/rl-teacher-atari | [
"fd6c399921d347333d7c5b4b12c63f1a955cea5c"
] | [
"agents/ga3c/ga3c/Environment.py"
] | [
"# Copyright (c) 2016, NVIDIA 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\n# are met:\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n# * Neither the name of NVIDIA CORPORATION nor the names of its\n# contributors may be used to endorse or promote products derived\n# from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY\n# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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\n# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\n# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nimport sys\n\nimport numpy as np\nimport scipy.misc as misc\n\nfrom ga3c.Config import Config\nfrom ga3c.GameManager import GameManager\n\nif sys.version_info >= (3, 0):\n from queue import Queue\nelse:\n from Queue import Queue\n\n\nclass Environment:\n def __init__(self):\n self.game = GameManager(Config.ATARI_GAME, Config.MAKE_ENV_FUNCTION, display=Config.PLAY_MODE)\n self.atari = self.game.is_atari()\n self.nb_frames = Config.STACKED_FRAMES\n self.frame_q = Queue(maxsize=self.nb_frames)\n self.previous_state = None\n self.current_state = None\n self.total_reward = 0\n\n self.reset()\n\n @staticmethod\n def _rgb2gray(rgb):\n return np.dot(rgb[..., :3], [0.299, 0.587, 0.114])\n\n @staticmethod\n def _preprocess(image):\n image = Environment._rgb2gray(image)\n image = misc.imresize(image, [Config.IMAGE_HEIGHT, Config.IMAGE_WIDTH], 'bilinear')\n image = image.astype(np.float32) / 128.0 - 1.0\n return image\n\n def _get_current_state(self):\n if not self.frame_q.full():\n return None # frame queue is not full yet.\n x_ = np.array(self.frame_q.queue)\n x_ = np.transpose(x_, [1, 2, 0]) # move channels\n return x_\n\n def _update_frame_q(self, frame):\n if self.frame_q.full():\n self.frame_q.get()\n if self.atari:\n frame = Environment._preprocess(frame)\n self.frame_q.put(frame)\n\n def get_num_actions(self):\n return self.game.env.action_space.n\n\n def reset(self):\n self.total_reward = 0\n self.frame_q.queue.clear()\n self._update_frame_q(self.game.reset())\n self.previous_state = self.current_state = None\n\n def step(self, action):\n observation, reward, done, info = self.game.step(action)\n\n self.total_reward += reward\n self._update_frame_q(observation)\n\n self.previous_state = self.current_state\n self.current_state = self._get_current_state()\n return reward, done, info\n"
] | [
[
"numpy.dot",
"scipy.misc.imresize",
"numpy.array",
"numpy.transpose"
]
] | [
{
"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": []
}
] |
nickmarton/kaggle | [
"ca1a0e0de18be505e271ad2e4018c8524fd7c33d"
] | [
"Titanic/Visualizer.py"
] | [
"\"\"\"Visualize data.\"\"\"\n\nfrom __future__ import division, print_function\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n\ndef zipper(frame, *columns):\n \"\"\"Zip given columns of a frame together.\"\"\"\n return (np.array(frame[[col for col in columns]]))\n\n\ndef ticket_bucketizer(row):\n \"\"\".\"\"\"\n try:\n bucket = int(row[0][0])\n if bucket == 1 or bucket == 2:\n return [bucket, row[1]]\n else:\n return [3, row[1]]\n except ValueError:\n bucket = ord(row[0][0])\n if bucket == 80:\n return [bucket, row[1]]\n else:\n return [-1, row[1]]\n\n\ndef replace_name_with_title(names):\n \"\"\"Replace a given name with the respective title contained within.\"\"\"\n for entry in (names[0].split()):\n if '.' in entry:\n title = entry\n break\n return [title, names[1]]\n\n\ndef plot(arr_2d, y_min=None, y_max=None, transform=None):\n \"\"\".\"\"\"\n if transform:\n for i, row in enumerate(arr_2d):\n arr_2d[i] = (transform(row))\n\n from collections import Counter\n alive = arr_2d[arr_2d[:, 1] == 1]\n dead = arr_2d[arr_2d[:, 1] == 0]\n alive_counts = (Counter(alive[:, 0]))\n dead_counts = (Counter(dead[:, 0]))\n\n not_in_alive = []\n not_in_dead = []\n for key in alive_counts.keys():\n if key not in dead_counts.keys():\n not_in_dead.append(key)\n\n for key in dead_counts.keys():\n if key not in alive_counts.keys():\n not_in_alive.append(key)\n\n for key in not_in_dead:\n dead_counts[key] = 0\n for key in not_in_alive:\n alive_counts[key] = 0\n\n alive_nums, alive_labels = [], []\n alive_counts = sorted(alive_counts.iteritems(), key=lambda x: x[0])\n for pair in alive_counts:\n alive_labels.append(pair[0])\n alive_nums.append(pair[1])\n\n dead_nums, dead_labels = [], []\n dead_counts = sorted(dead_counts.iteritems(), key=lambda x: x[0])\n for pair in dead_counts:\n dead_labels.append(pair[0])\n dead_nums.append(pair[1])\n\n ind = (np.arange(len(alive_counts)))\n width = 0.35 # the width of the bars\n\n fig, ax = plt.subplots()\n rects1 = ax.bar(ind, alive_nums, width, color='r')\n rects2 = ax.bar(ind + width, dead_nums, width, color='b')\n\n ax.set_ylabel('Number of people')\n\n if y_min and y_max:\n ax.set_ylim(y_min, y_max)\n elif y_min:\n ax.set_ylim(bottom=y_min)\n elif y_max:\n ax.set_ylim(top=y_max)\n else:\n pass\n\n ax.set_xticks(ind + width)\n ax.set_xticklabels(alive_labels)\n\n ax.legend((rects1[0], rects2[0]), ('Alive', 'Dead'))\n\n plt.show()\n\n\ndef main():\n \"\"\".\"\"\"\n X_train, X_test = pd.read_csv(\"train.csv\"), pd.read_csv(\"test.csv\")\n '''\n names = zipper(X_train, \"Name\", \"Survived\")\n plot(names, transform=replace_name_with_title)\n '''\n\n sex = zipper(X_train, \"Ticket\", \"Survived\")\n plot(sex, transform=ticket_bucketizer)\n\nif __name__ == \"__main__\":\n main()\n"
] | [
[
"pandas.read_csv",
"numpy.array",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.show"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
sundarjhu/DAWGI_Lectures_2021 | [
"8d6d1db3eff6505d1e90597b8b94c6db39240ac3"
] | [
"Demo_DAWGI_HBM/Pleiades/Marginal_SFH_Bar_NoScale.py"
] | [
"import matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.interpolate\nimport a_statistics_def_fun as st_def\nplt.style.use('classic')\n\n\ndef list_ticks(x):\n x_tk=[]\n for i in x:\n if i%1.==0.:\n x_tk.append(str(int(i)))\n else:\n x_tk.append(str(i))\n \n return x_tk\n\n##################\n\ndef marg_Z(ax, nag, n_z):\n a_mar = []\n x1, x2 = 0, nag\n for i in range(n_z):\n a_mar.append(np.sum(ax[x1:x2]))\n x1+=nag\n x2+=nag\n return np.array(a_mar)\n\n\ndef marg_AGE(ax, nag):\n a_mar = []\n x1, x2 = 0, nag\n for i in range(nag):\n a_mar.append(np.sum(ax[i::nag]))\n return np.array(a_mar)\n\n\n################################################################################\n################################################################################\n################################################################################\n\ndef marg_sfh_bar_age(name,sfh,a_sp,fig):\n\n Z0, age0, mode = sfh[0], sfh[1], sfh[4]\n\n Z = np.unique(Z0)\n Nz=len(Z)\n idx_Z = range(1,Nz+1)\n\n age = np.unique(age0)\n age_list = list_ticks(np.round(age,1))\n Nag=len(age)\n age_aux= np.arange(1,Nag+1)\n\n SFR_mode_marg = marg_AGE(mode, Nag)\n \n ##\n a_age = []\n cont=0\n for ai in a_sp:\n a_aux = marg_AGE(ai, Nag)\n a_age.append(a_aux)\n\n a_age = np.array(a_age)\n\n perc = st_def.a_stat(a_age.T)\n ##\n\n sfh_mgl=[]\n for i in range(Nag):\n sfh_mgl.append([age_aux[i], SFR_mode_marg[i], perc[i][0], perc[i][1], perc[i][2]])\n sfh_mgl = np.array(sfh_mgl)\n \n sfh_mgl = sfh_mgl.T\n \n\n \n ###########################################\n\n ax = fig.add_subplot(132)\n\n violin_parts = ax.violinplot(a_age, positions=age_aux, showmedians=True)\n \n for partname in ('cbars','cmins','cmaxes','cmedians'):\n vp = violin_parts[partname]\n vp.set_edgecolor('black')\n vp.set_linewidth(1)\n\n # Make the violin body blue with a red border:\n for vp in violin_parts['bodies']:\n vp.set_facecolor('y')\n vp.set_edgecolor('black')\n vp.set_linewidth(1)\n vp.set_alpha(0.3)\n\n \n labels = age_list\n ax.set_xticks(np.arange(1,len(labels) + 1))\n ax.set_xticklabels(labels)\n \n ax.set_xlim(age_aux[-1]+0.5,age_aux[0]-0.5)\n ax.set_ylim(0.,1.)\n\n ax.set_xlabel('Age(Gyr)')\n ax.set_ylabel('$a_{AGE}$', fontsize=15)\n \n\n \n\n################################################################################\n################################################################################\n################################################################################\n\n\ndef marg_sfh_bar_Z(name,sfh,a_sp, niso,fig):\n\n Z0, age0, mode = sfh[0], sfh[1], sfh[2]\n\n Z = np.unique(Z0)\n Z_list = list_ticks(Z)\n Nz=len(Z)\n idx_Z = range(1,Nz+1)\n\n age = np.unique(age0)\n Nag=len(age)\n age_int = np.append(0.,age)\n \n SFR_mode_marg = marg_Z(mode, Nag, Nz)\n\n ##\n a_z = []\n for ai in a_sp:\n a_z.append(marg_Z(ai, Nag, Nz))\n a_z = np.array(a_z)\n perc = st_def.a_stat(a_z.T)\n\n ##\n sfh_mgl=[]\n for i in range(Nz):\n sfh_mgl.append([idx_Z[i], SFR_mode_marg[i], perc[i][0], perc[i][1], perc[i][2]])\n sfh_mgl = np.array(sfh_mgl)\n\n sfh_mgl = sfh_mgl.T\n \n ###########################################\n ###########################################\n \n ax = fig.add_subplot(133)\n\n violin_parts = ax.violinplot(a_z, positions=idx_Z, showmedians=True)\n\n for partname in ('cbars','cmins','cmaxes','cmedians'):\n vp = violin_parts[partname]\n vp.set_edgecolor('black')\n vp.set_linewidth(1)\n\n # Make the violin body blue with a red border:\n for vp in violin_parts['bodies']:\n vp.set_facecolor('y')\n vp.set_edgecolor('black')\n vp.set_linewidth(1)\n vp.set_alpha(0.3)\n \n\n labels = ['0.014', '0.017', '0.020']\n\n tk=np.arange(1, len(labels) + 1)\n ax.set_xticks(tk)\n ax.set_xticklabels(labels)\n ax.set_xlim(tk[0]-0.5,tk[-1]+0.5)\n\n ax.set_ylim(0.,1.0)\n \n ax.set_xlabel('Z')\n ax.set_ylabel('$a_Z$', fontsize=15)\n\n"
] | [
[
"numpy.sum",
"numpy.unique",
"numpy.arange",
"numpy.round",
"numpy.append",
"numpy.array",
"matplotlib.pyplot.style.use"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jvmcgovern/model2roms_MI | [
"0085acd29d15b319dbe76ce27fe76bebbe5c5352"
] | [
"clim2bry.py"
] | [
"\"\"\"\nThis is CLM2BRY\n\"\"\"\nfrom datetime import datetime\n\nimport numpy as np\nfrom netCDF4 import Dataset, num2date\n\nimport IOBry\n\n__author__ = 'Trond Kristiansen'\n__email__ = '[email protected]'\n__created__ = datetime(2009, 3, 2)\n__modified__ = datetime(2019, 3, 12)\n__version__ = \"1.5\"\n__status__ = \"Development\"\n\n\ndef myhelp():\n \"\"\"\n This script generates boundary (BRY) files from the climatology (CLIM) files. The\n climatology files are created using createForcing option in main.py of soda2roms package.\n\n Since the variables have different lengths in eta and xi directions, the\n clips of data along the East, WEst, and North and South transects will differ in size. The correct\n sizes are defined below, where No is the number of vertical levels (length of s_rho):\n\n Define the sizes of the clips along xi :\n North and South = salt(No,Lpo),\n temp(No,Lpo),\n v(No,Lpo),\n vbar(1,Lpo),\n zeta(1,Lpo),\n u(No,Lp)\n ubar(1,Lp)\n\n Define the sizes of the clips along eta :\n East and West = salt(No,Mpo),\n temp(No,Mpo),\n v(No,Mp),\n vbar(1,Mp),\n zeta(1,Mpo),\n u(No,Mpo)\n ubar(1,Mpo)\"\"\"\n\n\ndef writebry(confM2R):\n # See myhelp function for definition of these variables:\n grdROMS = confM2R.grdROMS\n\n Lpo = grdROMS.Lp\n Mpo = grdROMS.Mp\n Lp = grdROMS.Lp - 1\n Mp = grdROMS.Mp - 1\n\n # Open the CLIM file\n clim = Dataset(confM2R.clim_name, 'r')\n # Generate the BRY netcdf4 file that we will use to fill in data\n IOBry.createBryFile(confM2R)\n # Now open the file we created\n f = Dataset(confM2R.bry_name, mode='a', format=confM2R.output_format, zlib=confM2R.use_zlib)\n\n # Get the time from the clim file\n climtime = np.array(clim.variables[\"ocean_time\"][:])\n ntimes = len(climtime)\n\n # For each time in CLIM file, save clips of boundary data to BRY file\n for itime in range(ntimes):\n\n temp = np.array(clim.variables[\"temp\"][itime, :, :, :])\n salt = np.array(clim.variables[\"salt\"][itime, :, :, :])\n ssh = np.array(clim.variables[\"zeta\"][itime, :, :])\n u = np.array(clim.variables[\"u\"][itime, :, :, :])\n v = np.array(clim.variables[\"v\"][itime, :, :, :])\n ubar = np.array(clim.variables[\"ubar\"][itime, :, :])\n vbar = np.array(clim.variables[\"vbar\"][itime, :, :])\n\n if confM2R.write_bcg:\n O3_c = np.array(clim.variables[\"O3_c\"][itime, :, :, :])\n O3_TA = np.array(clim.variables[\"O3_TA\"][itime, :, :, :])\n N1_p = np.array(clim.variables[\"N1_p\"][itime, :, :, :])\n N3_n = np.array(clim.variables[\"N3_n\"][itime, :, :, :])\n N5_s = np.array(clim.variables[\"N5_s\"][itime, :, :, :])\n O2_o = np.array(clim.variables[\"O2_o\"][itime, :, :, :])\n\n # Cut the boundary sections along Lpo, and Mpo to create the\n # North, South, West, and East boundary clips. Write each clip\n # to file for each time step\n\n # NOTE: For East and West only V current (v,vbar) have size Mp, others have size Mpo\n temp_west = np.squeeze(temp[:, :, 0])\n salt_west = np.squeeze(salt[:, :, 0])\n ssh_west = np.squeeze(ssh[:, 0])\n u_west = np.squeeze(u[:, :, 0])\n v_west = np.squeeze(v[:, :, 0])\n ubar_west = np.squeeze(ubar[:, 0])\n vbar_west = np.squeeze(vbar[:, 0])\n\n if confM2R.write_bcg:\n O3_c_west = np.squeeze(O3_c[:, :, 0])\n O3_ta_west = np.squeeze(O3_TA[:, :, 0])\n N1_p_west = np.squeeze(N1_p[:, :, 0])\n N3_n_west = np.squeeze(N3_n[:, :, 0])\n N5_s_west = np.squeeze(N5_s[:, :, 0])\n O2_o_west = np.squeeze(O2_o[:, :, 0])\n\n temp_east = np.squeeze(temp[:, :, Lp])\n salt_east = np.squeeze(salt[:, :, Lp])\n ssh_east = np.squeeze(ssh[:, Lp])\n u_east = np.squeeze(u[:, :, Lp - 1])\n v_east = np.squeeze(v[:, :, Lp])\n ubar_east = np.squeeze(ubar[:, Lp - 1])\n vbar_east = np.squeeze(vbar[:, Lp])\n\n if confM2R.write_bcg:\n O3_c_east = np.squeeze(O3_c[:, :, Lp])\n O3_ta_east = np.squeeze(O3_TA[:, :, Lp])\n N1_p_east = np.squeeze(N1_p[:, :, Lp])\n N3_n_east = np.squeeze(N3_n[:, :, Lp])\n N5_s_east = np.squeeze(N5_s[:, :, Lp])\n O2_o_east = np.squeeze(O2_o[:, :, Lp])\n\n # NOTE: For South and North only U current (u,ubar) have size Lp, others have size Lpo\n temp_south = np.squeeze(temp[:, 0, :])\n salt_south = np.squeeze(salt[:, 0, :])\n ssh_south = np.squeeze(ssh[0, :])\n u_south = np.squeeze(u[:, 0, :])\n v_south = np.squeeze(v[:, 0, :])\n ubar_south = np.squeeze(ubar[0, :])\n vbar_south = np.squeeze(vbar[0, :])\n\n if confM2R.write_bcg:\n O3_c_south = np.squeeze(O3_c[:, 0, :])\n O3_ta_south = np.squeeze(O3_TA[:, 0, :])\n N1_p_south = np.squeeze(N1_p[:, 0, :])\n N3_n_south = np.squeeze(N3_n[:, 0, :])\n N5_s_south = np.squeeze(N5_s[:, 0, :])\n O2_o_south = np.squeeze(O2_o[:, 0, :])\n\n temp_north = np.squeeze(temp[:, Mp, :])\n salt_north = np.squeeze(salt[:, Mp, :])\n ssh_north = np.squeeze(ssh[Mp, :])\n u_north = np.squeeze(u[:, Mp, :])\n v_north = np.squeeze(v[:, Mp - 1, :])\n ubar_north = np.squeeze(ubar[Mp, :])\n vbar_north = np.squeeze(vbar[Mp - 1, :])\n\n if confM2R.write_bcg:\n O3_c_north = np.squeeze(O3_c[:, Mp, :])\n O3_ta_north = np.squeeze(O3_TA[:, Mp, :])\n N1_p_north = np.squeeze(N1_p[:, Mp, :])\n N3_n_north = np.squeeze(N3_n[:, Mp, :])\n N5_s_north = np.squeeze(N5_s[:, Mp, :])\n O2_o_north = np.squeeze(O2_o[:, Mp, :])\n\n if confM2R.write_ice:\n ageice = np.array(clim.variables[\"ageice\"][itime, :, :])\n uice = np.array(clim.variables[\"uice\"][itime, :, :])\n vice = np.array(clim.variables[\"vice\"][itime, :, :])\n aice = np.array(clim.variables[\"aice\"][itime, :, :])\n hice = np.array(clim.variables[\"hice\"][itime, :, :])\n snow_thick = np.array(clim.variables[\"snow_thick\"][itime, :, :])\n ti = np.array(clim.variables[\"ti\"][itime, :, :])\n sfwat = np.array(clim.variables[\"sfwat\"][itime, :, :])\n tisrf = np.array(clim.variables[\"tisrf\"][itime, :, :])\n sig11 = np.array(clim.variables[\"sig11\"][itime, :, :])\n sig12 = np.array(clim.variables[\"sig12\"][itime, :, :])\n sig22 = np.array(clim.variables[\"sig22\"][itime, :, :])\n\n ageice_west = np.squeeze(ageice[:, 0])\n ageice_east = np.squeeze(ageice[:, Lp])\n ageice_south = np.squeeze(ageice[0, :])\n ageice_north = np.squeeze(ageice[Mp, :])\n\n uice_west = np.squeeze(uice[:, 0])\n uice_east = np.squeeze(uice[:, Lp - 1])\n uice_south = np.squeeze(uice[0, :])\n uice_north = np.squeeze(uice[Mp, :])\n\n vice_west = np.squeeze(vice[:, 0])\n vice_east = np.squeeze(vice[:, Lp])\n vice_south = np.squeeze(vice[0, :])\n vice_north = np.squeeze(vice[Mp - 1, :])\n\n aice_west = np.squeeze(aice[:, 0])\n aice_east = np.squeeze(aice[:, Lp])\n aice_south = np.squeeze(aice[0, :])\n aice_north = np.squeeze(aice[Mp, :])\n\n hice_west = np.squeeze(hice[:, 0])\n hice_east = np.squeeze(hice[:, Lp])\n hice_south = np.squeeze(hice[0, :])\n hice_north = np.squeeze(hice[Mp, :])\n\n snow_thick_west = np.squeeze(snow_thick[:, 0])\n snow_thick_east = np.squeeze(snow_thick[:, Lp])\n snow_thick_south = np.squeeze(snow_thick[0, :])\n snow_thick_north = np.squeeze(snow_thick[Mp, :])\n\n ti_west = np.squeeze(ti[:, 0])\n ti_east = np.squeeze(ti[:, Lp])\n ti_south = np.squeeze(ti[0, :])\n ti_north = np.squeeze(ti[Mp, :])\n\n sfwat_west = np.squeeze(sfwat[:, 0])\n sfwat_east = np.squeeze(sfwat[:, Lp])\n sfwat_south = np.squeeze(sfwat[0, :])\n sfwat_north = np.squeeze(sfwat[Mp, :])\n\n tisrf_west = np.squeeze(tisrf[:, 0])\n tisrf_east = np.squeeze(tisrf[:, Lp])\n tisrf_south = np.squeeze(tisrf[0, :])\n tisrf_north = np.squeeze(tisrf[Mp, :])\n\n sig11_west = np.squeeze(sig11[:, 0])\n sig11_east = np.squeeze(sig11[:, Lp])\n sig11_south = np.squeeze(sig11[0, :])\n sig11_north = np.squeeze(sig11[Mp, :])\n\n sig12_west = np.squeeze(sig12[:, 0])\n sig12_east = np.squeeze(sig12[:, Lp])\n sig12_south = np.squeeze(sig12[0, :])\n sig12_north = np.squeeze(sig12[Mp, :])\n\n sig22_west = np.squeeze(sig22[:, 0])\n sig22_east = np.squeeze(sig22[:, Lp])\n sig22_south = np.squeeze(sig22[0, :])\n sig22_north = np.squeeze(sig22[Mp, :])\n\n # ------- Write time to file -------------------------------\n d = num2date(climtime[itime], units=clim.variables['ocean_time'].long_name,\n calendar=clim.variables['ocean_time'].calendar)\n print('clim2bry.py => Appending data to file %s for time %s' % (confM2R.bry_name, d))\n\n f.variables['ocean_time'][itime] = climtime[itime]\n\n # ------- Write out western boundary variables ------------\n\n f.variables['temp_west'][itime, :, :] = temp_west\n f.variables['salt_west'][itime, :, :] = salt_west\n f.variables['zeta_west'][itime, :] = ssh_west\n\n f.variables['u_west'][itime, :, :] = u_west\n f.variables['v_west'][itime, :, :] = v_west\n f.variables['ubar_west'][itime, :] = ubar_west\n f.variables['vbar_west'][itime, :] = vbar_west\n\n if confM2R.write_bcg:\n f.variables['O3_c_west'][itime, :, :] = O3_c_west\n f.variables['O3_TA_west'][itime, :, :] = O3_ta_west\n f.variables['N1_p_west'][itime, :, :] = N1_p_west\n f.variables['N3_n_west'][itime, :, :] = N3_n_west\n f.variables['N5_s_west'][itime, :, :] = N5_s_west\n f.variables['O2_o_west'][itime, :, :] = O2_o_west\n\n # ------- Write out eastern boundary variables ------------\n\n f.variables['temp_east'][itime, :, :] = temp_east\n f.variables['salt_east'][itime, :, :] = salt_east\n f.variables['zeta_east'][itime, :] = ssh_east\n f.variables['u_east'][itime, :, :] = u_east\n f.variables['v_east'][itime, :, :] = v_east\n f.variables['ubar_east'][itime, :] = ubar_east\n f.variables['vbar_east'][itime, :] = vbar_east\n\n if confM2R.write_bcg:\n f.variables['O3_c_east'][itime, :, :] = O3_c_east\n f.variables['O3_TA_east'][itime, :, :] = O3_ta_east\n f.variables['N1_p_east'][itime, :, :] = N1_p_east\n f.variables['N3_n_east'][itime, :, :] = N3_n_east\n f.variables['N5_s_east'][itime, :, :] = N5_s_east\n f.variables['O2_o_east'][itime, :, :] = O2_o_east\n\n # ------- Write out southern boundary variables ------------\n\n f.variables['temp_south'][itime, :, :] = temp_south\n f.variables['salt_south'][itime, :, :] = salt_south\n f.variables['zeta_south'][itime, :] = ssh_south\n f.variables['u_south'][itime, :, :] = u_south\n f.variables['v_south'][itime, :, :] = v_south\n f.variables['ubar_south'][itime, :] = ubar_south\n f.variables['vbar_south'][itime, :] = vbar_south\n\n if confM2R.write_bcg:\n f.variables['O3_c_south'][itime, :, :] = O3_c_south\n f.variables['O3_TA_south'][itime, :, :] = O3_ta_south\n f.variables['N1_p_south'][itime, :, :] = N1_p_south\n f.variables['N3_n_south'][itime, :, :] = N3_n_south\n f.variables['N5_s_south'][itime, :, :] = N5_s_south\n f.variables['O2_o_south'][itime, :, :] = O2_o_south\n\n # ------- Write out northern boundary variables ------------\n\n f.variables['temp_north'][itime, :, :] = temp_north\n f.variables['salt_north'][itime, :, :] = salt_north\n f.variables['zeta_north'][itime, :] = ssh_north\n f.variables['u_north'][itime, :, :] = u_north\n f.variables['v_north'][itime, :, :] = v_north\n f.variables['ubar_north'][itime, :] = ubar_north\n f.variables['vbar_north'][itime, :] = vbar_north\n\n if confM2R.write_bcg:\n f.variables['O3_c_north'][itime, :, :] = O3_c_north\n f.variables['O3_TA_north'][itime, :, :] = O3_ta_north\n f.variables['N1_p_north'][itime, :, :] = N1_p_north\n f.variables['N3_n_north'][itime, :, :] = N3_n_north\n f.variables['N5_s_north'][itime, :, :] = N5_s_north\n f.variables['O2_o_north'][itime, :, :] = O2_o_north\n\n if confM2R.write_ice:\n f.variables['ageice_west'][itime, :] = ageice_west\n f.variables['ageice_east'][itime, :] = ageice_east\n f.variables['ageice_south'][itime, :] = ageice_south\n f.variables['ageice_north'][itime, :] = ageice_north\n\n f.variables['uice_west'][itime, :] = uice_west\n f.variables['uice_east'][itime, :] = uice_east\n f.variables['uice_south'][itime, :] = uice_south\n f.variables['uice_north'][itime, :] = uice_north\n\n f.variables['vice_west'][itime, :] = vice_west\n f.variables['vice_east'][itime, :] = vice_east\n f.variables['vice_south'][itime, :] = vice_south\n f.variables['vice_north'][itime, :] = vice_north\n\n f.variables['aice_west'][itime, :] = aice_west\n f.variables['aice_east'][itime, :] = aice_east\n f.variables['aice_south'][itime, :] = aice_south\n f.variables['aice_north'][itime, :] = aice_north\n\n f.variables['hice_west'][itime, :] = hice_west\n f.variables['hice_east'][itime, :] = hice_east\n f.variables['hice_south'][itime, :] = hice_south\n f.variables['hice_north'][itime, :] = hice_north\n\n f.variables['snow_thick_west'][itime, :] = snow_thick_west\n f.variables['snow_thick_east'][itime, :] = snow_thick_east\n f.variables['snow_thick_south'][itime, :] = snow_thick_south\n f.variables['snow_thick_north'][itime, :] = snow_thick_north\n\n f.variables['ti_west'][itime, :] = ti_west\n f.variables['ti_east'][itime, :] = ti_east\n f.variables['ti_south'][itime, :] = ti_south\n f.variables['ti_north'][itime, :] = ti_north\n\n f.variables['sfwat_west'][itime, :] = sfwat_west\n f.variables['sfwat_east'][itime, :] = sfwat_east\n f.variables['sfwat_south'][itime, :] = sfwat_south\n f.variables['sfwat_north'][itime, :] = sfwat_north\n\n f.variables['tisrf_west'][itime, :] = tisrf_west\n f.variables['tisrf_east'][itime, :] = tisrf_east\n f.variables['tisrf_south'][itime, :] = tisrf_south\n f.variables['tisrf_north'][itime, :] = tisrf_north\n\n f.variables['sig11_west'][itime, :] = sig11_west\n f.variables['sig11_east'][itime, :] = sig11_east\n f.variables['sig11_south'][itime, :] = sig11_south\n f.variables['sig11_north'][itime, :] = sig11_north\n\n f.variables['sig12_west'][itime, :] = sig12_west\n f.variables['sig12_east'][itime, :] = sig12_east\n f.variables['sig12_south'][itime, :] = sig12_south\n f.variables['sig12_north'][itime, :] = sig12_north\n\n f.variables['sig22_west'][itime, :] = sig22_west\n f.variables['sig22_east'][itime, :] = sig22_east\n f.variables['sig22_south'][itime, :] = sig22_south\n f.variables['sig22_north'][itime, :] = sig22_north\n f.close()\n"
] | [
[
"numpy.squeeze",
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
loveisacat/mappo | [
"8a9f705858232bfc7622f051e0ec78db895ff2f2"
] | [
"onpolicy/runner/shared/base_runner.py"
] | [
"import wandb\nimport os\nimport numpy as np\nimport torch\nfrom tensorboardX import SummaryWriter\nfrom onpolicy.utils.shared_buffer import SharedReplayBuffer\nfrom onpolicy.algorithms.utils.darnet import DarNet\nfrom onpolicy.algorithms.utils.tranback import BackNet\n\n\n\ndef _t2n(x):\n \"\"\"Convert torch tensor to a numpy array.\"\"\"\n return x.detach().cpu().numpy()\n\nclass Runner(object):\n \"\"\"\n Base class for training recurrent policies.\n :param config: (dict) Config dictionary containing parameters for training.\n \"\"\"\n def __init__(self, config):\n\n self.all_args = config['all_args']\n self.envs = config['envs']\n self.eval_envs = config['eval_envs']\n self.device = config['device']\n self.num_agents = config['num_agents']\n if config.__contains__(\"render_envs\"):\n self.render_envs = config['render_envs'] \n\n # parameters\n self.env_name = self.all_args.env_name\n self.algorithm_name = self.all_args.algorithm_name\n self.experiment_name = self.all_args.experiment_name\n self.use_centralized_V = self.all_args.use_centralized_V\n self.use_obs_instead_of_state = self.all_args.use_obs_instead_of_state\n self.num_env_steps = self.all_args.num_env_steps\n self.episode_length = self.all_args.episode_length\n self.n_rollout_threads = self.all_args.n_rollout_threads\n self.n_eval_rollout_threads = self.all_args.n_eval_rollout_threads\n self.n_render_rollout_threads = self.all_args.n_render_rollout_threads\n self.use_linear_lr_decay = self.all_args.use_linear_lr_decay\n self.hidden_size = self.all_args.hidden_size\n self.use_wandb = self.all_args.use_wandb\n self.use_render = self.all_args.use_render\n self.recurrent_N = self.all_args.recurrent_N\n\n # interval\n self.save_interval = self.all_args.save_interval\n self.use_eval = self.all_args.use_eval\n self.eval_interval = self.all_args.eval_interval\n self.log_interval = self.all_args.log_interval\n\n # dir\n self.model_dir = self.all_args.model_dir\n\n #darnet \n rep = DarNet(self.num_agents, 5, self.device)\n atta = BackNet(self.device)\n self.rep = rep\n self.atta = atta\n\n\n if self.use_wandb:\n self.save_dir = str(wandb.run.dir)\n self.run_dir = str(wandb.run.dir)\n else:\n self.run_dir = config[\"run_dir\"]\n self.log_dir = str(self.run_dir / 'logs')\n if not os.path.exists(self.log_dir):\n os.makedirs(self.log_dir)\n self.writter = SummaryWriter(self.log_dir)\n self.save_dir = str(self.run_dir / 'models')\n if not os.path.exists(self.save_dir):\n os.makedirs(self.save_dir)\n\n from onpolicy.algorithms.r_mappo.r_mappo import R_MAPPO as TrainAlgo\n from onpolicy.algorithms.r_mappo.algorithm.rMAPPOPolicy import R_MAPPOPolicy as Policy\n\n share_observation_space = self.envs.share_observation_space[0] if self.use_centralized_V else self.envs.observation_space[0]\n\n # policy network\n self.policy = Policy(self.all_args,\n self.envs.observation_space[0],\n share_observation_space,\n self.envs.action_space[0],\n device = self.device)\n\n #self.model_dir = \"/home/stephen/codebase/mappo/onpolicy/scripts/results/StarCraft2/4m/mappo/smac/run1/models\"\n #self.model_dir = \"/home/bchen7/codebase/mappo/onpolicy/scripts/results/StarCraft2/4m/mappo/smac/run1/models\"\n if self.model_dir is not None:\n self.restore()\n\n # algorithm\n self.trainer = TrainAlgo(self.all_args, self.policy, device = self.device)\n \n # buffer\n self.buffer = SharedReplayBuffer(self.all_args,\n self.num_agents,\n self.envs.observation_space[0],\n share_observation_space,\n self.envs.action_space[0])\n def run(self):\n \"\"\"Collect training data, perform training updates, and evaluate policy.\"\"\"\n raise NotImplementedError\n\n def warmup(self):\n \"\"\"Collect warmup pre-training data.\"\"\"\n raise NotImplementedError\n\n def collect(self, step):\n \"\"\"Collect rollouts for training.\"\"\"\n raise NotImplementedError\n\n def insert(self, data):\n \"\"\"\n Insert data into buffer.\n :param data: (Tuple) data to insert into training buffer.\n \"\"\"\n raise NotImplementedError\n \n @torch.no_grad()\n def compute(self):\n \"\"\"Calculate returns for the collected data.\"\"\"\n self.trainer.prep_rollout()\n next_values = self.trainer.policy.get_values(np.concatenate(self.buffer.share_obs[-1]),\n np.concatenate(self.buffer.rnn_states_critic[-1]),\n np.concatenate(self.buffer.masks[-1]))\n next_values = np.array(np.split(_t2n(next_values), self.n_rollout_threads))\n self.buffer.compute_returns(next_values, self.trainer.value_normalizer)\n \n def train(self):\n \"\"\"Train policies with data in buffer. \"\"\"\n self.trainer.prep_training()\n train_infos = self.trainer.train(self.buffer) \n self.buffer.after_update()\n return train_infos\n\n def save(self):\n \"\"\"Save policy's actor and critic networks.\"\"\"\n \n torch.save(self.rep.state_dict(), str(self.save_dir) + \"/darnet.pt\")\n policy_actor = self.trainer.policy.actor\n torch.save(policy_actor.state_dict(), str(self.save_dir) + \"/actor.pt\")\n policy_critic = self.trainer.policy.critic\n torch.save(policy_critic.state_dict(), str(self.save_dir) + \"/critic.pt\")\n '''\n for name in self.rep.state_dict():\n print(name,'\\t',self.rep.state_dict()[name].shape)\n print(\"================\")\n \n for name in policy_actor.state_dict():\n print(name,'\\t',policy_actor.state_dict()[name].shape)\n \n print(\"================\")\n for name in policy_critic.state_dict():\n print(name,'\\t',policy_critic.state_dict()[name].shape)\n '''\n\n def restore(self):\n \"\"\"Restore policy's networks from a saved model.\"\"\"\n policy_actor_state_dict = torch.load(str(self.model_dir) + '/actor.pt')\n self.policy.actor.load_state_dict(policy_actor_state_dict)\n \n self.rep.load_state_dict(torch.load(str(self.model_dir) + '/darnet.pt'))\n \n if not self.all_args.use_render:\n policy_critic_state_dict = torch.load(str(self.model_dir) + '/critic.pt')\n self.policy.critic.load_state_dict(policy_critic_state_dict)\n \n def log_train(self, train_infos, total_num_steps):\n \"\"\"\n Log training info.\n :param train_infos: (dict) information about training update.\n :param total_num_steps: (int) total number of training env steps.\n \"\"\"\n for k, v in train_infos.items():\n if self.use_wandb:\n wandb.log({k: v}, step=total_num_steps)\n else:\n self.writter.add_scalars(k, {k: v}, total_num_steps)\n\n def log_env(self, env_infos, total_num_steps):\n \"\"\"\n Log env info.\n :param env_infos: (dict) information about env state.\n :param total_num_steps: (int) total number of training env steps.\n \"\"\"\n for k, v in env_infos.items():\n if len(v)>0:\n if self.use_wandb:\n wandb.log({k: np.mean(v)}, step=total_num_steps)\n else:\n self.writter.add_scalars(k, {k: np.mean(v)}, total_num_steps)\n"
] | [
[
"numpy.concatenate",
"torch.no_grad",
"numpy.mean"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Anthony102899/Lego-ImageGenerator | [
"52b19c8bb20f77a3394675e7c037c943a50c1e15",
"52b19c8bb20f77a3394675e7c037c943a50c1e15"
] | [
"solvers/rigidity_solver/main_3d.py",
"solvers/rigidity_solver/eigen_analysis.py"
] | [
"from bricks_modeling.file_IO.model_reader import read_bricks_from_file\nfrom bricks_modeling.file_IO.model_writer import write_bricks_to_file\nfrom bricks_modeling.connectivity_graph import ConnectivityGraph\nimport numpy as np\nfrom util.debugger import MyDebugger\nfrom solvers.rigidity_solver.algo_core import solve_rigidity\nfrom solvers.rigidity_solver.internal_structure import structure_sampling\nimport visualization.model_visualizer as vis\nfrom solvers.rigidity_solver.eigen_analysis import get_motions, get_weakest_displacement\nimport solvers.rigidity_solver.test_cases.cases_3D as cases3d\nfrom solvers.rigidity_solver.algo_core import rigidity_matrix,spring_energy_matrix_accelerate_3D\nfrom util.geometry_util import trivial_basis,clear_redundance_vecs,clear_trivial_motion\n\n\nif __name__ == \"__main__\":\n debugger = MyDebugger(\"test\")\n\n bricks, points, edges, abstract_edges, points_on_brick = cases3d.lego_models(\"example1\")\n\n # is_rigid, eigen_pairs = solve_rigidity(points, edges + abstract_edges, dim=3)\n\n K = spring_energy_matrix_accelerate_3D(points,edges,abstract_edges)\n\n w,V = np.linalg.eigh(K)\n V_normalized = map(lambda v: v / np.linalg.norm(v), V.T)\n eigen_pairs = sorted(list(zip(w, V_normalized)), key=lambda pair: pair[0])\n non_zero_eigenspace = [(e_val, e_vec) for e_val, e_vec in eigen_pairs if abs(e_val) >= 1e-7]\n zero_motions = [(e_val, e_vec) for e_val, e_vec in eigen_pairs if\n abs(e_val) < 1e-7]\n trivial_vec = trivial_basis(points, 3)\n basis = list(zip(*zero_motions))\n non_zero_eigenvecs = np.array(basis[1])\n ortho_basis = clear_redundance_vecs(non_zero_eigenvecs)\n after_clear = clear_redundance_vecs(clear_trivial_motion(ortho_basis, trivial_vec))\n F = K @ non_zero_eigenspace[0][1]\n print(\"the degree of freedom:\", np.linalg.matrix_rank(after_clear))\n if np.linalg.matrix_rank(after_clear) == 6:\n is_rigid = True\n else:\n is_rigid = False\n\n\n if is_rigid:\n\n vis.visualize_3D(points, lego_bricks=bricks, arrows=(after_clear[0]).reshape(-1, 3))\n else:\n vis.visualize_3D(points, lego_bricks=bricks, arrows=(non_zero_eigenspace[0][1]).reshape(-1, 3))\n\n\n",
"import util.geometry_util as geo_util\nfrom numpy import linalg as LA\nimport numpy as np\nimport scipy\n\nimport solvers.rigidity_solver.algo_core as core\nfrom solvers.rigidity_solver import constraints_3d\n\n\ndef eigen_analysis(points, edges, constraints, stiffness=None, fix_stiffness=False):\n dim = 3\n if stiffness is not None:\n M = stiffness\n else:\n M = core.spring_energy_matrix(points, edges, dim=dim)\n\n A = constraints\n\n B = scipy.linalg.null_space(A)\n T = np.transpose(B) @ B\n S = B.T @ M @ B\n\n L = scipy.linalg.cholesky(T)\n L_inv = np.linalg.inv(L)\n\n Q = LA.multi_dot([L_inv.T, S, L_inv])\n # compute eigenvalues / vectors\n eigen_pairs = geo_util.eigen(Q, symmetric=True)\n eigen_pairs = [(e_val, B @ e_vec) for e_val, e_vec in eigen_pairs]\n\n return eigen_pairs\n\n\n# to get basis forming the motion space\ndef get_motions(eigen_pairs, points, dim):\n # collect all eigen vectors with zero eigen value\n zeroeigenspace = [e_vec for e_val, e_vec in eigen_pairs]\n\n # Trivial basis -- orthonormalized translation along / rotation wrt 3 axes\n basis = geo_util.trivial_basis(points, dim)\n\n # cast the eigenvectors corresponding to zero eigenvalues into nullspace of the trivial basis,\n # in other words, the new vectors don't have any components (projection) in the span of the trivial basis\n\n if geo_util.is_subspace(basis, zeroeigenspace):\n reduced_zeroeigenspace = [geo_util.subtract_orthobasis(vec, basis) for vec in zeroeigenspace]\n motion_basis = geo_util.rref(reduced_zeroeigenspace)\n trivial_motion_dim = 3 if dim == 2 else 6\n else:\n motion_basis = zeroeigenspace\n trivial_motion_dim = 0\n\n result_motions = []\n for i in range(len(motion_basis) - trivial_motion_dim):\n e_vec = motion_basis[i]\n e_vec = e_vec / LA.norm(e_vec)\n delta_x = e_vec.reshape(-1, dim)\n result_motions.append(delta_x)\n\n return result_motions\n\n\ndef get_weakest_displacement(eigen_pairs, dim):\n e_val, e_vec = eigen_pairs[0]\n return e_vec.reshape(-1, dim), e_val"
] | [
[
"numpy.array",
"numpy.linalg.eigh",
"numpy.linalg.norm",
"numpy.linalg.matrix_rank"
],
[
"numpy.linalg.inv",
"numpy.linalg.multi_dot",
"numpy.linalg.norm",
"scipy.linalg.cholesky",
"numpy.transpose",
"scipy.linalg.null_space"
]
] | [
{
"matplotlib": [],
"numpy": [
"1.11",
"1.10",
"1.12",
"1.19",
"1.24",
"1.13",
"1.16",
"1.9",
"1.18",
"1.23",
"1.21",
"1.22",
"1.20",
"1.7",
"1.15",
"1.14",
"1.17",
"1.8"
],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
KonstantinKlepikov/covid-kaliningrad | [
"bd7402c07661cf93ad0e4bda69d22c7449660d60"
] | [
"supportFunction.py"
] | [
"import streamlit as st\nimport numpy as np\nimport pandas as pd\nfrom drawTools import Linear\n\n\n\"\"\"Support functions for data visualistion, wraped with cache decorator\nreduces app loading time\n\"\"\"\n\n\ncTime = 900. # cache time\n\n\[email protected](allow_output_mutation=True, ttl=cTime)\ndef dataloader(url):\n \"\"\"Load .csv data\n\n Args:\n url (string): public url for load\n\n Returns:\n pandas DataFrame: loaded data\n \"\"\"\n return pd.read_csv(url)\n\n\[email protected]()\ndef pagemaker():\n \"\"\"Make a site paginator\n\n Returns:\n dict, list: dict, where keys are names for tabs of paginator, values are strings for headers of pages\n list of keys is used for create streamlit paginator\n \"\"\"\n p = {'intro': 'Введение',\n 'cases': 'Динамика заражения', \n 'infection rate': 'Infection Rate', \n 'deaths': 'Данные об умерших', \n 'capacity': 'Нагрузка на систему', \n 'tests': 'Тестирование', \n 'vaccination': 'Вакцинация',\n 'regions': 'Регионы',\n 'regions detail': 'Регионы (детально)',\n 'demographics': 'Демография',\n 'demographics detail': 'Демография (детально)'\n }\n paginator = [n for n in p.keys()]\n\n return p, paginator\n\n\[email protected](ttl=cTime)\ndef slicedData(data, query):\n \"\"\"Slice data and remove zeros for point sparced charts\n\n Args:\n data (pandas DataFrame): main data\n\n Returns:\n pandas DataFrame: prepared data\n \"\"\"\n df = data.query(query)\n df.set_index('дата', inplace=True)\n df = df[(df.T != 0).any()]\n df.reset_index(inplace=True)\n return df.replace(0, np.nan)\n\n\[email protected](suppress_st_warning=True, ttl=cTime)\ndef asidedata(data, rstat, people=1012512):\n \"\"\"Create data for sidebar\n\n Args:\n data (pandas DataFrame): main data\n people (int, optional): number of people, who leaves in region. Defaults to 1012512.\n\n Returns:\n dict: where keys are name ofe fields, and values are values\n \"\"\"\n ds = {}\n ds['sick'] = data['всего'].sum()\n ds['proc'] = round(ds['sick'] * 100 / people, 2)\n ds['dead'] = data['умерли от ковид'].sum()\n ds['let'] = round(ds['dead'] * 100 / ds['sick'], 2)\n ds['ex'] = data['выписали'].sum()\n ds['update'] = data['дата'].iloc[-1]\n pr = slicedData(data[['дата', 'компонент 1', 'компонент 2']], \"'2020-08-01' <= дата \")\n ds['pr1'] = int(pr['компонент 1'].iloc[-1])\n ds['pr2'] = int(pr['компонент 2'].iloc[-1])\n ds['prproc1'] = round(ds['pr1']* 100 / people, 2)\n ds['prproc2'] = round(ds['pr2']* 100 / people, 2)\n ds['rstat_dead'] = rstat['умерли от ковид, вирус определен'].sum() + rstat['предположительно умерли от ковид'].sum() + rstat['умерли не от ковид, вирус оказал влияние'].sum() + rstat['умерли не от ковид, не оказал влияние'].sum()\n # rosstat lerality\n d = rstat['Месяц'].iloc[-1].split('.')\n d.reverse()\n ds['rstat_date'] = '-'.join(d)\n ds['rstat_sick'] = data.set_index('дата').loc[:ds['rstat_date'], 'всего'].sum()\n ds['rstat_let'] = round(ds['rstat_dead'] * 100 / ds['rstat_sick'], 2)\n # covid/pneumonia letality\n lock = data.loc[data['умерли в палатах для ковид/пневмония с 1 апреля'].idxmax()]\n ds['cov_pnew_dead'] = lock['умерли в палатах для ковид/пневмония с 1 апреля']\n ds['cov_pnew_date'] = lock['дата']\n cov_all = data.set_index('дата').loc[:lock['дата'], 'всего'].sum()\n ds['cov_pnew_let'] = round(ds['cov_pnew_dead'] * 100 / cov_all, 2)\n\n return ds\n\n\[email protected](ttl=cTime)\ndef ratio(data, above, below):\n \"\"\"Ratio of dara\n\n Args:\n data (pandas DataFrame): main data\n above (str): above column name\n below (str: below column name)\n\n Returns:\n pandas DataFrame: prepared data\n \"\"\"\n data['shape'] = data[above] * 100 / data[below]\n data['shape'] = data['shape'].astype(np.float16)\n data['shape'] = data['shape'].apply(lambda x: round(x, 2))\n return data[['дата', 'shape']]\n\n\[email protected]()\ndef regDistr(data):\n \"\"\"Make list of columns name for creating region cases destribution\n\n Args:\n data (pandas DataFrame): main data\n\n Returns:\n list of strings: list of columns name\n \"\"\"\n _cols = [col for col in data.columns if 'округ' in col]\n _cols.append('дата')\n _cols.append('Калининград')\n return _cols\n\n\[email protected](ttl=cTime)\ndef irDestrib(data):\n \"\"\"Calculate destribution of Infection Rate\n\n Args:\n data (pandas DataFrame): main data\n\n Returns:\n pandad DataFrames: two frames with destribution of Infection Rate\n \"\"\"\n df = data[['дата', 'infection rate']]\n high = df[df['infection rate'] >= 1].shape[0]\n low = df[df['infection rate'] < 1].shape[0]\n return high, low\n\n\[email protected](ttl=cTime)\ndef profession(data):\n \"\"\"Make list of columns name for creating profession cases destribution\n\n Args:\n data (pandas DataFrame): main data\n\n Returns:\n list of strings: list of columns name\n \"\"\"\n _cols = [col for col in data.columns if '>' in col]\n _cols.append('дата')\n return _cols\n\n\[email protected]()\ndef ageDestr(data):\n \"\"\"Make list of ages for age destribution chart\n\n Args:\n data (pandas DataFrame): main data\n\n Returns:\n list of strings: list of ages\n \"\"\"\n _cols = [\n 'до года',\n 'от 01 до 07', \n 'от 07 до 14',\n 'от 15 до 17',\n 'от 18 до 29',\n 'от 30 до 49',\n 'от 50 до 64',\n 'от 65'\n ]\n _cols.append('дата')\n return _cols\n\[email protected](allow_output_mutation=True)\ndef precision(title, data):\n ch = Linear(\n title, \n data, \n height=120,\n grid=False\n )\n ch.legend=None\n ch.draw()\n ch.richchart()\n return ch.emptychart()\n"
] | [
[
"pandas.read_csv"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
Lcrypto/CGO2019-AE | [
"cba7598b42f10eab655a8907a6db71094c1f558d"
] | [
"fb-tc/fb-wo-tuning/input_tccg_1.py"
] | [
"# tccg-1\nimport time\nimport tensor_comprehensions as tc\nimport torch\n\nlang = \"\"\"\ndef tccg1(float(G, D, A, B) L, float(E, F, G, C) R) -> (O) {\n\tO(a, b, c, d, e, f) +=! L(g, d, a, b) * R(e, f, g, c)\n}\n\"\"\"\n\nprint (\"tccg-40: O(a, b, c, d, e, f) +=! L(g, d, a, b) * R(e, f, g, c)\")\nprint (\"(a,b,c,d,e,f,g) = (24,16,16,16,24,16,24)\")\nprint (\"# of Operations: \", 24*16*16*16*24*16*24)\n\nmatmul = tc.define(lang, name=\"tccg1\")\nmat1, mat2 = torch.randn(24, 16, 24, 16).cuda(), torch.randn(24, 16, 24, 16).cuda()\n\nout = matmul(mat1, mat2)\n\ntorch.cuda.synchronize()\nstart = time.process_time()\nfor i in range(0, 10):\n\tout = matmul(mat1, mat2)\ntorch.cuda.synchronize()\nend = time.process_time()\n\nprint (\"time :\", float(end - start) / 10)\n"
] | [
[
"torch.randn",
"torch.cuda.synchronize"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
raeidsaqur/ml-gradientdescent | [
"a061423c8e9c131ad05970d7cbaf2f42f646db1c"
] | [
"optdemo.py"
] | [
"import numpy as np\nimport pylab\nfrom scipy.optimize import line_search\n\ndef steepest_descent(grad_fun,params,num_iters, *varargs):\n ## Learning Rates\n #eta = 0.1\n eta = 2\n #eta = 3\n\n ## Momentum\n alpha=0.7\n momentum=True\n\n d = np.ones(params.shape)\n d = d / np.linalg.norm(d)\n\n mom = np.zeros(params.shape)\n for i in range(num_iters):\n grad = grad_fun(params,*varargs)\n params_old = params\n if momentum:\n # Add momentum to the update\n mom = -eta*grad + alpha*mom\n else:\n # Just use the gradient\n mom = -eta*grad\n params = params + mom\n\n pylab.plot([params_old[0],params[0]],[params_old[1],params[1]],'-k',lw=2)\n raw_input(\"Press Enter to continue...\")\n\ndef ls_fun(params,A):\n return ls(params,A)[0]\n\ndef ls_grad(params,A):\n return ls(params,A)[1]\n\ndef ls(params,A):\n f = 0.5*np.dot(params,A).dot(params)\n df = np.dot(A,params)\n\n return f,df\n\ndef ls_contour(X,Y,A):\n x = X.ravel()[:,None]\n y = Y.ravel()[:,None]\n data = np.hstack((x,y))\n z = 0.5*(np.dot(data,A)*data).sum(1)\n return z.reshape(X.shape)\n\nif __name__ == '__main__':\n np.random.seed(0)\n A = np.random.randn(2,2)\n A = np.dot(A.T,A)\n A = np.dot(A.T,A)\n A = A / np.linalg.norm(A)\n x = np.linspace(-5,5,100)\n X,Y = np.meshgrid(x,x)\n Z = ls_contour(X,Y,A)\n #Z = rosenbrock_contour(x)\n\n pylab.ion()\n pylab.contour(X,Y,Z,100)\n pylab.show()\n\n init_params = np.array([4,-4])\n #init_params = np.array([-3,-4])\n pylab.plot(init_params[0],init_params[1],'.r',ms=25)\n\n raw_input(\"Press Enter to continue...\")\n\n steepest_descent(ls_grad,init_params,1000,A)"
] | [
[
"numpy.dot",
"numpy.hstack",
"numpy.random.seed",
"numpy.linspace",
"numpy.linalg.norm",
"numpy.ones",
"numpy.random.randn",
"numpy.array",
"numpy.meshgrid",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
bratao/DeepSpeed | [
"c50d8955e942e5e26cf81835d59ec3f20ef8540d"
] | [
"deepspeed/runtime/activation_checkpointing/checkpointing.py"
] | [
"'''\r\nCopyright (c) Microsoft Corporation\r\nLicensed under the MIT license.\r\n\r\nUse to partition the activations stored for backward propagation\r\nTherefore reduces the memory consumption\r\nAlso implements CPU checkpointing and contiguous memory checkpointing\r\nReduces memory consumption and memory fragmentation\r\n\r\nCode for rng checkpointing taken from NVIDIA Megatron-LM mpu/random.py\r\nb886b7bb972afe72bac0f5de4f42a4a7bae8ebef\r\n'''\r\n\r\n# Parts of the code here are adapted from PyTorch\r\n# repo: https://github.com/pytorch/pytorch\r\nimport copy\r\nimport torch\r\nimport contextlib\r\nimport torch.distributed as dist\r\n\r\nfrom torch import _C\r\nfrom torch.cuda import _lazy_call, device as device_ctx_manager\r\n\r\nfrom deepspeed.runtime.config import DeepSpeedConfig\r\nfrom deepspeed.utils import logger\r\nfrom deepspeed.utils.timer import SynchronizedWallClockTimer as Timers\r\n\r\n#DeepSpeed Checkpointing Enabled or Disabled\r\ndeepspeed_checkpointing_enabled = False\r\n\r\n#MP parameters\r\nmpu = None\r\nmp_rank = None\r\nmp_size = None\r\nmp_group = None\r\n\r\n#Model Parameters\r\nnum_layers = None\r\n\r\n#Checkpointing buffers\r\ncontiguous_data_buffers = []\r\ndata_offsets = []\r\n\r\ncontiguous_size_buffers = []\r\nsize_offsets = []\r\n\r\ntimers = None\r\n\r\n#optimization flags\r\nPARTITION_ACTIVATIONS = False\r\nPA_TO_CPU = False\r\nCONTIGUOUS_CHECKPOINTING = False\r\nSYNCHRONIZE = False\r\nPROFILE_TIME = False\r\n\r\n\r\ndef see_memory_usage(message, force=False):\r\n #return\r\n if not force:\r\n return\r\n #dist.barrier()\r\n if dist.get_rank() == 0:\r\n logger.info(message)\r\n logger.info(\r\n \"Memory Allocated %s GigaBytes\",\r\n torch.cuda.memory_allocated() / (1024 * 1024 * 1024),\r\n )\r\n logger.info(\r\n \"Max Memory Allocated %s GigaBytes\",\r\n torch.cuda.max_memory_allocated() / (1024 * 1024 * 1024),\r\n )\r\n logger.info(\r\n \"Cache Allocated %s GigaBytes\",\r\n torch.cuda.memory_cached() / (1024 * 1024 * 1024),\r\n )\r\n logger.info(\r\n \"Max cache Allocated %s GigaBytes\",\r\n torch.cuda.max_memory_cached() / (1024 * 1024 * 1024),\r\n )\r\n #input(\"Press Any Key To Continue ..\")\r\n\r\n\r\n# Default name for the model parallel rng tracker.\r\n_MODEL_PARALLEL_RNG_TRACKER_NAME = 'model-parallel-rng'\r\ntransport_stream = None\r\ncuda_device = None\r\n\r\n\r\ndef detach_variable(inputs, device=None):\r\n if isinstance(inputs, tuple):\r\n out = []\r\n for inp in inputs:\r\n if not isinstance(inp, torch.Tensor):\r\n out.append(inp)\r\n continue\r\n\r\n requires_grad = inp.requires_grad\r\n\r\n if device is not None:\r\n x = inp.to(device=device)\r\n else:\r\n x = inp\r\n\r\n x = x.detach()\r\n x.requires_grad = requires_grad\r\n out.append(x)\r\n return tuple(out)\r\n else:\r\n raise RuntimeError(\r\n \"Only tuple of tensors is supported. Got Unsupported input type: \",\r\n type(inputs).__name__)\r\n\r\n\r\ndef _set_cuda_rng_state(new_state, device=-1):\r\n \"\"\"Sets the random number generator state of the current GPU.\r\n\r\n Arguments:\r\n new_state (torch.ByteTensor): The desired state\r\n This function is adapted from PyTorch repo (torch.cuda.set_rng_state)\r\n with a single change: the input state is not cloned. Cloning caused\r\n major performance issues for +4 GPU cases.\r\n \"\"\"\r\n if hasattr(_C, '_cuda_setRNGState') and callable(_C._cuda_setRNGState):\r\n # older PyTorch\r\n def cb():\r\n with device_ctx_manager(device):\r\n _C._cuda_setRNGState(new_state)\r\n else:\r\n # newer PyTorch\r\n if device == -1:\r\n device = torch.device('cuda')\r\n elif isinstance(device, str):\r\n device = torch.device(device)\r\n elif isinstance(device, int):\r\n device = torch.device('cuda', device)\r\n\r\n def cb():\r\n idx = device.index\r\n if idx is None:\r\n idx = torch.cuda.current_device()\r\n default_generator = torch.cuda.default_generators[idx]\r\n default_generator.set_state(new_state)\r\n\r\n _lazy_call(cb)\r\n\r\n\r\nclass CudaRNGStatesTracker:\r\n \"\"\"Tracker for the cuda RNG states.\r\n\r\n Using the `add` method, a cuda rng state is initialized based on\r\n the input `seed` and is assigned to `name`. Later, by forking the\r\n rng state, we can perform operations and return to our starting\r\n cuda state.\r\n \"\"\"\r\n def __init__(self):\r\n # Map from a string name to the cuda rng state.\r\n self.states_ = {}\r\n # Seeds are just for book keeping and ensure no seed is set twice.\r\n self.seeds_ = set()\r\n\r\n def reset(self):\r\n \"\"\"Set to the initial state (no tracker).\"\"\"\r\n self.states_ = {}\r\n self.seeds_ = set()\r\n\r\n def get_states(self):\r\n \"\"\"Get rng states. Copy the dictionary so we have direct\r\n pointers to the states, not just a pointer to the dictionary.\"\"\"\r\n return copy.copy(self.states_)\r\n\r\n def set_states(self, states):\r\n \"\"\"Set the rng states. For efficiency purposes, we do not check\r\n the size of seed for compatibility.\"\"\"\r\n self.states_ = states\r\n\r\n def add(self, name, seed):\r\n \"\"\"Track the rng state.\"\"\"\r\n # Check seed is not already used.\r\n if seed in self.seeds_:\r\n raise Exception('seed {} already exists'.format(seed))\r\n self.seeds_.add(seed)\r\n # Check that state is not already defined.\r\n if name in self.states_:\r\n raise Exception('cuda rng state {} already exists'.format(name))\r\n # Get the current rng state.\r\n orig_rng_state = torch.cuda.get_rng_state()\r\n # Set the new state and store it.\r\n torch.cuda.manual_seed(seed)\r\n self.states_[name] = torch.cuda.get_rng_state()\r\n # Reset rng state to what it was.\r\n _set_cuda_rng_state(orig_rng_state)\r\n\r\n @contextlib.contextmanager\r\n def fork(self, name=_MODEL_PARALLEL_RNG_TRACKER_NAME):\r\n \"\"\"Fork the cuda rng state, perform operations, and exit with\r\n the original state.\"\"\"\r\n # Check if we have added the state\r\n if name not in self.states_:\r\n raise Exception('cuda rng state {} is not added'.format(name))\r\n # Store current rng state.\r\n orig_cuda_rng_state = torch.cuda.get_rng_state()\r\n # Set rng state to the desired one\r\n _set_cuda_rng_state(self.states_[name])\r\n # Do the stuff we wanted to do.\r\n try:\r\n yield\r\n finally:\r\n # Update the current rng state for later use.\r\n self.states_[name] = torch.cuda.get_rng_state()\r\n # And set the state to the original state we started with.\r\n _set_cuda_rng_state(orig_cuda_rng_state)\r\n\r\n\r\n# RNG tracker object.\r\n_CUDA_RNG_STATE_TRACKER = CudaRNGStatesTracker()\r\n\r\n\r\ndef get_cuda_rng_tracker():\r\n \"\"\"Get cuda rng tracker.\"\"\"\r\n return _CUDA_RNG_STATE_TRACKER\r\n\r\n\r\ndef model_parallel_cuda_manual_seed(seed):\r\n \"\"\"Initialize model parallel cuda seed.\r\n\r\n This function should be called after the model parallel is\r\n initialized. Also, no torch.cuda.manual_seed should be called\r\n after this function. Basically, this is replacement for that\r\n function.\r\n Two set of RNG states are tracked:\r\n default state: This is for data parallelism and is the same among a\r\n set of model parallel GPUs but different across\r\n different model paralle groups. This is used for\r\n example for dropout in the non-model-parallel regions.\r\n model-parallel state: This state is different among a set of model\r\n parallel GPUs, but the same across data parallel\r\n groups. This is used for example for dropout in\r\n model parallel regions.\r\n \"\"\"\r\n global mpu\r\n # 2718 is just for fun and any POSITIVE value will work.\r\n offset = seed + 2718\r\n model_parallel_seed = offset + mpu.get_model_parallel_rank()\r\n # Data parallel gets the original sedd.\r\n data_parallel_seed = seed\r\n\r\n if torch.distributed.get_rank() == 0:\r\n logger.info(\r\n '> initializing model parallel cuda seeds on global rank {}, '\r\n 'model parallel rank {}, and data parallel rank {} with '\r\n 'model parallel seed: {} and data parallel seed: {}'.format(\r\n torch.distributed.get_rank(),\r\n mpu.get_model_parallel_rank(),\r\n mpu.get_data_parallel_rank(),\r\n model_parallel_seed,\r\n data_parallel_seed),\r\n )\r\n _CUDA_RNG_STATE_TRACKER.reset()\r\n # Set the default state.\r\n torch.cuda.manual_seed(data_parallel_seed)\r\n # and model parallel state.\r\n _CUDA_RNG_STATE_TRACKER.add(_MODEL_PARALLEL_RNG_TRACKER_NAME, model_parallel_seed)\r\n\r\n\r\ndef get_partition_start(item):\r\n global mp_rank, mp_size, mp_group\r\n size = item.numel()\r\n partition_size = size / mp_size\r\n start = partition_size * mp_rank\r\n return int(start)\r\n\r\n\r\ndef get_partition_size(item):\r\n global mp_rank, mp_size, mp_group\r\n size = item.numel()\r\n assert size % mp_size == 0, \"Doesn't handle if partition activation if item is not divisible by mp size\"\r\n partition_size = size / mp_size\r\n return int(partition_size)\r\n\r\n\r\ndef get_full_inputs(tensors, device=None):\r\n inputs = []\r\n num_args = int(len(tensors) / 2)\r\n for i in range(num_args - 1):\r\n\r\n item = tensors[2 * i]\r\n size = tensors[2 * i + 1]\r\n\r\n partition_size = item.numel()\r\n tensor_size = partition_size * mp_size\r\n if device is not None:\r\n flat_tensor = torch.zeros([tensor_size], dtype=item.dtype, device=device)\r\n else:\r\n flat_tensor = torch.zeros([tensor_size],\r\n dtype=item.dtype,\r\n device=item.device)\r\n partitions = []\r\n for i in range(mp_size):\r\n part_i = flat_tensor.narrow(0, partition_size * i, partition_size)\r\n if i == mp_rank:\r\n part_i.copy_(item)\r\n partitions.append(part_i)\r\n if mp_group is not None:\r\n dist.all_gather(partitions, partitions[mp_rank], group=mp_group)\r\n input_tensor = flat_tensor.view(list(size.numpy()))\r\n item.data = input_tensor.data\r\n\r\n inputs.append(item)\r\n inputs.append(tensors[-2])\r\n\r\n return tuple(inputs)\r\n\r\n\r\nclass CheckpointFunction(torch.autograd.Function):\r\n \"\"\"This function is adapted from torch.utils.checkpoint with\r\n two main changes:\r\n 1) torch.cuda.set_rng_state is replaced with `_set_cuda_rng_state`\r\n 2) the states in the model parallel tracker are also properly\r\n tracked/set/reset.\r\n 3) Performance activation partitioning, contiguous memory optimization\r\n 4) CPU Checkpointing\r\n 5) Profile forward and backward functions\r\n \"\"\"\r\n @staticmethod\r\n def forward(ctx, run_function, *args):\r\n global mpu, timers, SYNCHRONIZE, PROFILE_TIME\r\n\r\n if SYNCHRONIZE:\r\n torch.cuda.synchronize()\r\n\r\n if timers is None and PROFILE_TIME:\r\n timers = Timers()\r\n\r\n if PROFILE_TIME:\r\n timers('forward').start()\r\n\r\n ctx.run_function = run_function\r\n global num_layers\r\n global mp_rank, mp_size, mp_group\r\n global contiguous_data_buffers, contiguous_size_buffers\r\n global data_offsets, size_offsets\r\n if mp_rank is None:\r\n if mpu is not None:\r\n mp_rank = mpu.get_model_parallel_rank()\r\n mp_size = mpu.get_model_parallel_world_size()\r\n mp_group = mpu.get_model_parallel_group()\r\n else:\r\n mp_rank = 0\r\n mp_size = 1\r\n mp_group = None\r\n\r\n global cuda_device, transport_stream, PARTITION_ACTIVATIONS, buffer_0, buffer_1, buffer_0_offset, buffer_1_offset\r\n\r\n if cuda_device is None:\r\n see_memory_usage(\"First Forward Begining\", force=True)\r\n if dist.get_rank() == 0:\r\n logger.info(f\"Activation Checkpointing Information\")\r\n logger.info(\r\n f\"----Partition Activations {PARTITION_ACTIVATIONS}, CPU CHECKPOINTING {PA_TO_CPU}\"\r\n )\r\n logger.info(\r\n f\"----contiguous Memory Checkpointing {CONTIGUOUS_CHECKPOINTING} with {num_layers} total layers\"\r\n )\r\n logger.info(f\"----Synchronization {SYNCHRONIZE}\")\r\n logger.info(f\"----Profiling {PROFILE_TIME}\")\r\n\r\n cuda_device = torch.cuda.current_device()\r\n transport_stream = torch.cuda.Stream(device=cuda_device)\r\n\r\n if PARTITION_ACTIVATIONS:\r\n #inputs = [item.detach().contiguous().view(-1).narrow(0, get_partition_start(item), get_partition_size(item)).clone() for item in args[:-1]]\r\n #inputs.append(args[-1])\r\n\r\n inputs = []\r\n for i, item in enumerate(args[:-1]):\r\n partition_size = get_partition_size(item)\r\n partition = item.detach().contiguous().view(-1).narrow(\r\n 0,\r\n get_partition_start(item),\r\n partition_size).clone()\r\n\r\n if CONTIGUOUS_CHECKPOINTING:\r\n buffer_device = torch.device(\r\n 'cpu') if PA_TO_CPU else partition.device\r\n\r\n if i >= len(contiguous_data_buffers):\r\n tensor_list = [\r\n torch.tensor(()).new_empty([partition_size],\r\n dtype=partition.dtype,\r\n device=buffer_device)\r\n for i in range(num_layers)\r\n ]\r\n contiguous_data_buffers.append(tensor_list)\r\n data_offsets.append(0)\r\n elif contiguous_data_buffers[i] is None:\r\n tensor_list = [\r\n torch.tensor(()).new_empty([partition_size],\r\n dtype=partition.dtype,\r\n device=buffer_device)\r\n for i in range(num_layers)\r\n ]\r\n contiguous_data_buffers[i] = tensor_list\r\n data_offsets[i] = 0\r\n\r\n contiguous_partition = contiguous_data_buffers[i][\r\n data_offsets[i]].data.copy_(partition.data)\r\n data_offsets[i] = data_offsets[i] + 1\r\n inputs.append(contiguous_partition)\r\n else:\r\n partition = partition.cpu() if PA_TO_CPU else partition\r\n inputs.append(partition)\r\n\r\n inputs.append(args[-1])\r\n\r\n #just in case something funky is happening such as reuse of inputs\r\n inputs_cuda = [item.to(cuda_device) for item in args]\r\n\r\n # Copy the rng states.\r\n ctx.fwd_cpu_rng_state = torch.get_rng_state()\r\n ctx.fwd_cuda_rng_state = torch.cuda.get_rng_state()\r\n ctx.fwd_cuda_rng_state_tracker = get_cuda_rng_tracker().get_states()\r\n\r\n #ctx.save_for_backward(*args)\r\n with torch.no_grad():\r\n outputs = run_function(*inputs_cuda)\r\n\r\n del inputs_cuda\r\n\r\n #with torch.cuda.stream(transport_stream):\r\n #if PARTITION_ACTIVATIONS:\r\n # new_args = []\r\n # for arg, inp in zip(args,inputs):\r\n # size= torch.tensor(arg.size())\r\n # arg.data = inp.data\r\n # new_args.append(arg)\r\n # new_args.append(size)\r\n # ctx.save_for_backward(*new_args)\r\n\r\n if PARTITION_ACTIVATIONS:\r\n new_args = []\r\n for i, (arg, inp) in enumerate(zip(args, inputs)):\r\n size = torch.tensor(arg.size())\r\n\r\n arg.data = inp.data\r\n new_args.append(arg)\r\n\r\n if CONTIGUOUS_CHECKPOINTING:\r\n numel = size.numel()\r\n if i >= len(contiguous_size_buffers):\r\n tmp = torch.tensor(())\r\n contiguous_size_buffers.append(\r\n tmp.new_empty([numel * num_layers],\r\n dtype=size.dtype,\r\n device=size.device))\r\n size_offsets.append(0)\r\n elif contiguous_size_buffers[i] is None:\r\n tmp = torch.tensor(())\r\n contiguous_size_buffers[i] = tmp.new_empty([numel * num_layers],\r\n dtype=size.dtype,\r\n device=size.device)\r\n size_offsets[i] = 0\r\n\r\n contiguous_size = contiguous_size_buffers[i].narrow(\r\n 0,\r\n size_offsets[i],\r\n numel).data.copy_(size.data)\r\n contiguous_size = contiguous_size.view_as(size)\r\n size_offsets[i] = size_offsets[i] + numel\r\n new_args.append(contiguous_size)\r\n else:\r\n new_args.append(size)\r\n #if dist.get_rank() == 0:\r\n # logger.info(f\"The stored tensor is {contiguous_size} and orginal one is {size} \")\r\n\r\n ctx.save_for_backward(*new_args)\r\n else:\r\n ctx.save_for_backward(*args)\r\n if PROFILE_TIME:\r\n timers('forward').stop()\r\n timers.log(['forward'])\r\n if SYNCHRONIZE:\r\n torch.cuda.synchronize()\r\n\r\n # Tensors returned from forward() may not be differentiable.\r\n if torch.is_tensor(outputs):\r\n non_grad_outputs = [outputs] if not outputs.is_floating_point() else []\r\n else:\r\n non_grad_outputs = [o for o in outputs if not o.is_floating_point()]\r\n ctx.mark_non_differentiable(*non_grad_outputs)\r\n return outputs\r\n\r\n @staticmethod\r\n def backward(ctx, *grads):\r\n global timers\r\n #see_memory_usage(\"In backward\", force=True)\r\n #removing pointers to the contiguous buffer memory\r\n #so that they can be garbage collected once the checkpoints\r\n #have been used\r\n if SYNCHRONIZE:\r\n torch.cuda.synchronize()\r\n if PROFILE_TIME:\r\n timers('backward').start()\r\n\r\n if CONTIGUOUS_CHECKPOINTING:\r\n global data_offsets, size_offsets\r\n global contiguous_data_buffers, contiguous_size_buffers\r\n\r\n for buffers in contiguous_data_buffers:\r\n buffers = []\r\n\r\n #frees up all the pointers to the checkpoints except for the ones\r\n #stored by save for backward\r\n contiguous_data_buffers = []\r\n contiguous_size_buffers = []\r\n data_offsets = []\r\n size_offsets = []\r\n\r\n #see_memory_usage(\"In backward checkpointing code\", force=True)\r\n if not torch.autograd._is_checkpoint_valid():\r\n raise RuntimeError(\"Checkpointing is not compatible with .grad(), \"\r\n \"please use .backward() if possible\")\r\n\r\n global cuda_device, transport_stream, PARTITION_ACTIVATIONS\r\n\r\n if PARTITION_ACTIVATIONS:\r\n #with torch.cuda.stream(transport_stream):\r\n inputs = get_full_inputs(ctx.saved_tensors,\r\n device=cuda_device if PA_TO_CPU else None)\r\n detached_inputs = detach_variable(inputs)\r\n else:\r\n inputs = ctx.saved_tensors\r\n detached_inputs = detach_variable(inputs)\r\n\r\n # Store the current states.\r\n bwd_cpu_rng_state = torch.get_rng_state()\r\n bwd_cuda_rng_state = torch.cuda.get_rng_state()\r\n bwd_cuda_rng_state_tracker = get_cuda_rng_tracker().get_states()\r\n\r\n # Set the states to what it used to be before the forward pass.\r\n torch.set_rng_state(ctx.fwd_cpu_rng_state)\r\n _set_cuda_rng_state(ctx.fwd_cuda_rng_state)\r\n get_cuda_rng_tracker().set_states(ctx.fwd_cuda_rng_state_tracker)\r\n\r\n # if PARTITION_ACTIVATIONS:\r\n # current_stream=torch.cuda.current_stream()\r\n # current_stream.wait_stream(transport_stream)\r\n\r\n with torch.enable_grad():\r\n outputs = ctx.run_function(*detached_inputs)\r\n\r\n # Set the states back to what it was at the start of this function.\r\n torch.set_rng_state(bwd_cpu_rng_state)\r\n _set_cuda_rng_state(bwd_cuda_rng_state)\r\n get_cuda_rng_tracker().set_states(bwd_cuda_rng_state_tracker)\r\n\r\n if isinstance(outputs, torch.Tensor):\r\n outputs = (outputs, )\r\n\r\n # Construct arguments to autograd.backward().\r\n # This is usually just outputs and grads, but forward() can return tensors that\r\n # are not differentiable.\r\n output_tensors = []\r\n grad_tensors = []\r\n for out, grad in zip(outputs, grads):\r\n if out.requires_grad:\r\n output_tensors.append(out)\r\n grad_tensors.append(grad)\r\n\r\n torch.autograd.backward(output_tensors, grad_tensors)\r\n\r\n if PROFILE_TIME:\r\n timers('backward').stop()\r\n timers.log(['backward'])\r\n if SYNCHRONIZE:\r\n torch.cuda.synchronize()\r\n return (None, ) + tuple(inp.grad for inp in detached_inputs)\r\n\r\n\r\ndef checkpoint(function, *args):\r\n \"\"\"Checkpoint a model or part of the model.\r\n This has been directly copied from torch.utils.checkpoint. \"\"\"\r\n return CheckpointFunction.apply(function, *args)\r\n\r\n\r\ndef partition_activations_in_checkpoint(partition_activation):\r\n global PARTITION_ACTIVATIONS\r\n PARTITION_ACTIVATIONS = partition_activation\r\n if dist.get_rank() == 0:\r\n logger.info(\r\n f\"**************Partition Activations {PARTITION_ACTIVATIONS}************\")\r\n\r\n\r\ndef set_num_layers(nlayers):\r\n global num_layers\r\n num_layers = nlayers\r\n\r\n\r\ndef reset():\r\n \"\"\"Resets memory buffers related to contiguous memory optimizations.\r\n Should be called during eval when multiple forward propagations are\r\n computed without any backward propagation that usually clears these\r\n buffers.\r\n Arguments:\r\n None\r\n\r\n Return:\r\n None\r\n \"\"\"\r\n if CONTIGUOUS_CHECKPOINTING:\r\n global data_offsets, size_offsets\r\n global contiguous_data_buffers, contiguous_size_buffers\r\n\r\n for buffers in contiguous_data_buffers:\r\n buffers = []\r\n\r\n #frees up all the pointers to the checkpoints except for the ones\r\n #stored by save for backward\r\n contiguous_data_buffers = []\r\n contiguous_size_buffers = []\r\n data_offsets = []\r\n size_offsets = []\r\n\r\n\r\ndef _configure_using_config_file(deepspeed_config, mpu=None):\r\n global num_layers, PARTITION_ACTIVATIONS, CONTIGUOUS_CHECKPOINTING, \\\r\n PA_TO_CPU, SYNCHRONIZE, PROFILE_TIME\r\n\r\n config = DeepSpeedConfig(deepspeed_config, mpu=mpu).activation_checkpointing_config\r\n logger.info(config.repr())\r\n PARTITION_ACTIVATIONS = config.partition_activations\r\n CONTIGUOUS_CHECKPOINTING = config.contiguous_memory_optimization\r\n num_layers = config.number_checkpoints\r\n PA_TO_CPU = config.cpu_checkpointing\r\n SYNCHRONIZE = config.synchronize_checkpoint_boundary\r\n PROFILE_TIME = config.profile\r\n\r\n\r\ndef _configure_defaults():\r\n\r\n global mpu, num_layers, deepspeed_checkpointing_enabled\r\n\r\n global PARTITION_ACTIVATIONS, CONTIGUOUS_CHECKPOINTING, \\\r\n PA_TO_CPU, SYNCHRONIZE, PROFILE_TIME\r\n\r\n PARTITION_ACTIVATIONS = False\r\n CONTIGUOUS_CHECKPOINTING = False\r\n num_layers = False\r\n PA_TO_CPU = False\r\n SYNCHRONIZE = False\r\n PROFILE_TIME = False\r\n deepspeed_checkpointing_enabled = True\r\n\r\n\r\ndef configure(\r\n mpu_,\r\n deepspeed_config=None,\r\n partition_activations=None,\r\n contiguous_checkpointing=None,\r\n num_checkpoints=None,\r\n checkpoint_in_cpu=None,\r\n synchronize=None,\r\n profile=None,\r\n):\r\n \"\"\"Configure DeepSpeed Activation Checkpointing.\r\n\r\n Arguments:\r\n mpu_: Optional: An object that implements the following methods\r\n get_model_parallel_rank/group/world_size, and get_data_parallel_rank/group/world_size\r\n\r\n deepspeed_config: Optional: DeepSpeed Config json file when provided will be used to\r\n configure DeepSpeed Activation Checkpointing\r\n\r\n partition_activations: Optional: Partitions activation checkpoint across model parallel\r\n GPUs when enabled. By default False. Will overwrite deepspeed_config if provided\r\n\r\n contiguous_checkpointing: Optional: Copies activation checkpoints to a contiguous memory\r\n buffer. Works only with homogeneous checkpoints when partition_activations is enabled.\r\n Must provide num_checkpoints. By default False. Will overwrite deepspeed_config if\r\n provided\r\n\r\n num_checkpoints: Optional: Number of activation checkpoints stored during the forward\r\n propagation of the model. Used to calculate the buffer size for contiguous_checkpointing\r\n Will overwrite deepspeed_config if provided\r\n\r\n checkpoint_in_cpu: Optional: Moves the activation checkpoint to CPU. Only works with\r\n partition_activation. Default is false. Will overwrite deepspeed_config if provided\r\n\r\n synchronize: Optional: Performs torch.cuda.synchronize() at the beginning and end of\r\n each call to deepspeed.checkpointing.checkpoint for both forward and backward pass.\r\n By default false. Will overwrite deepspeed_config if provided\r\n\r\n profile: Optional: Logs the forward and backward time for each\r\n deepspeed.checkpointing.checkpoint invocation. Will overwrite deepspeed_config\r\n if provided\r\n\r\n Returns:\r\n None\r\n \"\"\"\r\n global mpu, num_layers, deepspeed_checkpointing_enabled\r\n\r\n global PARTITION_ACTIVATIONS, CONTIGUOUS_CHECKPOINTING, \\\r\n PA_TO_CPU, SYNCHRONIZE, PROFILE_TIME\r\n\r\n _configure_defaults()\r\n\r\n if mpu_ is not None:\r\n mpu = mpu_\r\n\r\n if deepspeed_config is not None:\r\n _configure_using_config_file(deepspeed_config, mpu=mpu)\r\n\r\n if partition_activations is not None:\r\n PARTITION_ACTIVATIONS = partition_activations\r\n\r\n if contiguous_checkpointing is not None:\r\n CONTIGUOUS_CHECKPOINTING = contiguous_checkpointing\r\n\r\n if num_checkpoints is not None:\r\n num_layers = num_checkpoints\r\n\r\n if checkpoint_in_cpu is not None:\r\n PA_TO_CPU = checkpoint_in_cpu\r\n\r\n if synchronize is not None:\r\n SYNCHRONIZE = synchronize\r\n\r\n if profile is not None:\r\n PROFILE_TIME = profile\r\n\r\n if PA_TO_CPU or CONTIGUOUS_CHECKPOINTING:\r\n assert PARTITION_ACTIVATIONS, \"CPU Checkpointing/Contiguous Checkpointing is only availble with partitioned activations. Set partitioned activations to true in deepspeed config\"\r\n if CONTIGUOUS_CHECKPOINTING:\r\n assert num_layers is not None, \"Must specify the number of layers with contiguous memory checkpointing\"\r\n\r\n\r\ndef is_configured():\r\n \"\"\"True if deepspeed activation checkpointing has been configured\r\n by calling deepspeed.checkpointing.configure, else returns false\r\n\r\n Arguments:\r\n None\r\n\r\n Return:\r\n True of configured, else False\r\n \"\"\"\r\n return deepspeed_checkpointing_enabled\r\n"
] | [
[
"torch.set_rng_state",
"torch.cuda._lazy_call",
"torch.zeros",
"torch.no_grad",
"torch.device",
"torch.distributed.get_rank",
"torch.cuda.synchronize",
"torch.autograd.backward",
"torch.tensor",
"torch.cuda.memory_cached",
"torch.enable_grad",
"torch.cuda.current_device",
"torch.is_tensor",
"torch.get_rng_state",
"torch.cuda.Stream",
"torch.cuda.max_memory_cached",
"torch.cuda.manual_seed",
"torch.autograd._is_checkpoint_valid",
"torch.distributed.all_gather",
"torch._C._cuda_setRNGState",
"torch.cuda.max_memory_allocated",
"torch.cuda.device",
"torch.cuda.get_rng_state",
"torch.cuda.memory_allocated"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
paulromano/armi | [
"6c4fea1ca9d256a2599efd52af5e5ebe9860d192"
] | [
"armi/bookkeeping/db/tests/test_database3.py"
] | [
"# Copyright 2019 TerraPower, LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport unittest\n\nimport numpy\nimport h5py\n\nfrom armi.bookkeeping import db\nfrom armi.bookkeeping.db import database3\nfrom armi.reactor import grids\nfrom armi.reactor.tests import test_reactors\nfrom armi.settings import caseSettings\n\nfrom armi.tests import TEST_ROOT\n\n\nclass TestDatabase3(unittest.TestCase):\n def setUp(self):\n self.o, self.r = test_reactors.loadTestReactor(TEST_ROOT)\n cs = self.o.cs\n\n self.dbi = database3.DatabaseInterface(self.r, cs)\n self.dbi.initDB(fName=self._testMethodName + \".h5\")\n self.db: db.Database3 = self.dbi.database\n self.stateRetainer = self.r.retainState().__enter__()\n\n # used to test location-based history. see details below\n self.centralAssemSerialNums = []\n self.centralTopBlockSerialNums = []\n\n def tearDown(self):\n self.db.close()\n self.stateRetainer.__exit__()\n\n def makeHistory(self):\n \"\"\"\n Walk the reactor through a few time steps and write them to the db.\n \"\"\"\n for cycle, node in ((cycle, node) for cycle in range(3) for node in range(3)):\n self.r.p.cycle = cycle\n self.r.p.timeNode = node\n # something that splitDatabase won't change, so that we can make sure that\n # the right data went to the right new groups/cycles\n self.r.p.cycleLength = cycle\n\n self.db.writeToDB(self.r)\n\n def makeShuffleHistory(self):\n \"\"\"\n Walk the reactor through a few time steps with some shuffling.\n \"\"\"\n # Serial numbers *are not stable* (i.e., they can be different between test runs\n # due to parallelism and test run order). However, they are the simplest way to\n # check correctness of location-based history tracking. So we stash the serial\n # numbers at the location of interest so that we can use them later to check our\n # work.\n self.centralAssemSerialNums = []\n self.centralTopBlockSerialNums = []\n\n grid = self.r.core.spatialGrid\n for cycle in range(3):\n a1 = self.r.core.childrenByLocator[grid[cycle, 0, 0]]\n a2 = self.r.core.childrenByLocator[grid[0, 0, 0]]\n olda1Loc = a1.spatialLocator\n a1.moveTo(a2.spatialLocator)\n a2.moveTo(olda1Loc)\n c = self.r.core.childrenByLocator[grid[0, 0, 0]]\n self.centralAssemSerialNums.append(c.p.serialNum)\n self.centralTopBlockSerialNums.append(c[-1].p.serialNum)\n\n for node in range(3):\n self.r.p.cycle = cycle\n self.r.p.timeNode = node\n # something that splitDatabase won't change, so that we can make sure\n # that the right data went to the right new groups/cycles\n self.r.p.cycleLength = cycle\n\n self.db.writeToDB(self.r)\n # add some more data that isnt written to the database to test the\n # DatabaseInterface API\n self.r.p.cycle = 3\n self.r.p.timeNode = 0\n self.r.p.cycleLength = cycle\n self.r.core[0].p.chargeTime = 3\n\n def _compareArrays(self, ref, src):\n \"\"\"\n Compare two numpy arrays.\n\n Comparing numpy arrays that may have unsavory data (NaNs, Nones, jagged\n data, etc.) is really difficult. For now, convert to a list and compare\n element-by-element.\n \"\"\"\n self.assertEqual(type(ref), type(src))\n if isinstance(ref, numpy.ndarray):\n ref = ref.tolist()\n src = src.tolist()\n\n for v1, v2 in zip(ref, src):\n # Entries may be None\n if isinstance(v1, numpy.ndarray):\n v1 = v1.tolist()\n if isinstance(v2, numpy.ndarray):\n v2 = v2.tolist()\n self.assertEqual(v1, v2)\n\n def _compareRoundTrip(self, data):\n \"\"\"\n Make sure that data is unchanged by packing/unpacking.\n \"\"\"\n packed, attrs = database3.packSpecialData(data, \"testing\")\n roundTrip = database3.unpackSpecialData(packed, attrs, \"testing\")\n self._compareArrays(data, roundTrip)\n\n def test_computeParents(self):\n # The below arrays represent a tree structure like this:\n # 71 -----------------------.\n # | \\\n # 12--.-----.------. 72\n # / | \\ \\ \\\n # 22 30 4---. 6 18-.\n # / | | | \\ \\ / | \\\n # 8 17 2 32 52 62 1 9 10\n #\n # This should cover a handful of corner cases\n numChildren = [2, 5, 2, 0, 0, 1, 0, 3, 0, 0, 0, 0, 3, 0, 0, 0, 0]\n serialNums = [71, 12, 22, 8, 17, 30, 2, 4, 32, 53, 62, 6, 18, 1, 9, 10, 72]\n\n expected_1 = [None, 71, 12, 22, 22, 12, 30, 12, 4, 4, 4, 12, 12, 18, 18, 18, 71]\n expected_2 = [\n None,\n None,\n 71,\n 12,\n 12,\n 71,\n 12,\n 71,\n 12,\n 12,\n 12,\n 71,\n 71,\n 12,\n 12,\n 12,\n None,\n ]\n expected_3 = [\n None,\n None,\n None,\n 71,\n 71,\n None,\n 71,\n None,\n 71,\n 71,\n 71,\n None,\n None,\n 71,\n 71,\n 71,\n None,\n ]\n\n self.assertEqual(\n database3.Layout.computeAncestors(serialNums, numChildren), expected_1\n )\n self.assertEqual(\n database3.Layout.computeAncestors(serialNums, numChildren, 2), expected_2\n )\n self.assertEqual(\n database3.Layout.computeAncestors(serialNums, numChildren, 3), expected_3\n )\n\n def test_history(self) -> None:\n self.makeShuffleHistory()\n\n grid = self.r.core.spatialGrid\n testAssem = self.r.core.childrenByLocator[grid[0, 0, 0]]\n testBlock = testAssem[-1]\n\n # Test assem\n hist = self.db.getHistoryByLocation(\n testAssem, params=[\"chargeTime\", \"serialNum\"]\n )\n expectedSn = {\n (c, n): self.centralAssemSerialNums[c] for c in range(3) for n in range(3)\n }\n self.assertEqual(expectedSn, hist[\"serialNum\"])\n\n # test block\n hists = self.db.getHistoriesByLocation(\n [testBlock], params=[\"serialNum\"], timeSteps=[(0, 0), (1, 0), (2, 0)]\n )\n expectedSn = {(c, 0): self.centralTopBlockSerialNums[c] for c in range(3)}\n self.assertEqual(expectedSn, hists[testBlock][\"serialNum\"])\n\n # cant mix blocks and assems, since they are different distance from core\n with self.assertRaises(ValueError):\n self.db.getHistoriesByLocation([testAssem, testBlock], params=[\"serialNum\"])\n\n # if requested time step isnt written, return no content\n hist = self.dbi.getHistory(\n self.r.core[0], params=[\"chargeTime\", \"serialNum\"], byLocation=True\n )\n self.assertIn((3, 0), hist[\"chargeTime\"].keys())\n self.assertEqual(hist[\"chargeTime\"][(3, 0)], 3)\n\n def test_replaceNones(self):\n \"\"\"\n This definitely needs some work.\n \"\"\"\n data3 = numpy.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n data1 = numpy.array([1, 2, 3, 4, 5, 6, 7, 8])\n data1iNones = numpy.array([1, 2, None, 5, 6])\n data1fNones = numpy.array([None, 2.0, None, 5.0, 6.0])\n data2fNones = numpy.array([None, [[1.0, 2.0, 6.0], [2.0, 3.0, 4.0]]])\n dataJag = numpy.array([[[1, 2], [3, 4]], [[1, 2, 3], [4, 5, 6], [7, 8, 9]]])\n dataJagNones = numpy.array(\n [[[1, 2], [3, 4]], [[1], [1]], [[1, 2, 3], [4, 5, 6], [7, 8, 9]]]\n )\n dataDict = numpy.array(\n [{\"bar\": 2, \"baz\": 3}, {\"foo\": 4, \"baz\": 6}, {\"foo\": 7, \"bar\": 8}]\n )\n self._compareRoundTrip(data3)\n self._compareRoundTrip(data1)\n self._compareRoundTrip(data1iNones)\n self._compareRoundTrip(data1fNones)\n self._compareRoundTrip(data2fNones)\n self._compareRoundTrip(dataJag)\n self._compareRoundTrip(dataJagNones)\n self._compareRoundTrip(dataDict)\n\n def test_mergeHistory(self):\n self.makeHistory()\n\n # put some big data in an HDF5 attribute. This will exercise the code that pulls\n # such attributes into a formal dataset and a reference.\n self.r.p.cycle = 1\n self.r.p.timeNode = 0\n tnGroup = self.db.getH5Group(self.r)\n database3._writeAttrs(\n tnGroup[\"layout/serialNum\"],\n tnGroup,\n {\n \"fakeBigData\": numpy.eye(6400),\n \"someString\": \"this isn't a reference to another dataset\",\n },\n )\n\n db2 = database3.Database3(\"restartDB.h5\", \"w\")\n with db2:\n db2.mergeHistory(self.db, 2, 2)\n self.r.p.cycle = 1\n self.r.p.timeNode = 0\n tnGroup = db2.getH5Group(self.r)\n\n # this test is a little bit implementation-specific, but nice to be explicit\n self.assertEqual(\n tnGroup[\"layout/serialNum\"].attrs[\"fakeBigData\"],\n \"@/c01n00/attrs/0_fakeBigData\",\n )\n\n # actually exercise the _resolveAttrs function\n attrs = database3._resolveAttrs(tnGroup[\"layout/serialNum\"].attrs, tnGroup)\n self.assertTrue(numpy.array_equal(attrs[\"fakeBigData\"], numpy.eye(6400)))\n\n def test_splitDatabase(self):\n self.makeHistory()\n\n self.db.splitDatabase(\n [(c, n) for c in (1, 2) for n in range(3)], \"-all-iterations\"\n )\n\n # Closing to copy back from fast path\n self.db.close()\n\n with h5py.File(\"test_splitDatabase.h5\", \"r\") as newDb:\n self.assertTrue(newDb[\"c00n00/Reactor/cycle\"][()] == 0)\n self.assertTrue(newDb[\"c00n00/Reactor/cycleLength\"][()] == 1)\n self.assertTrue(\"c02n00\" not in newDb)\n self.assertTrue(newDb.attrs[\"databaseVersion\"] == database3.DB_VERSION)\n\n\nclass Test_LocationPacking(unittest.TestCase):\n def test_locationPacking(self):\n # pylint: disable=protected-access\n loc1 = grids.IndexLocation(1, 2, 3, None)\n loc2 = grids.CoordinateLocation(4.0, 5.0, 6.0, None)\n loc3 = grids.MultiIndexLocation(None)\n loc3.append(grids.IndexLocation(7, 8, 9, None))\n loc3.append(grids.IndexLocation(10, 11, 12, None))\n\n locs = [loc1, loc2, loc3]\n tp, data = database3._packLocations(locs)\n\n self.assertEqual(tp[0], database3.LOC_INDEX)\n self.assertEqual(tp[1], database3.LOC_COORD)\n self.assertEqual(tp[2], database3.LOC_MULTI + \"2\")\n\n unpackedData = database3._unpackLocations(tp, data)\n\n self.assertEqual(unpackedData[0], (1, 2, 3))\n self.assertEqual(unpackedData[1], (4.0, 5.0, 6.0))\n self.assertEqual(unpackedData[2], (7, 8, 9))\n\n\nif __name__ == \"__main__\":\n import sys\n\n # sys.argv = [\"\", \"TestDatabase3.test_splitDatabase\"]\n unittest.main()\n"
] | [
[
"numpy.eye",
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
grst/scanorama | [
"75f1a80166cb3b29e8a4b7adff7f76d0379d848e"
] | [
"bin/integration_panorama.py"
] | [
"from process import load_names\nfrom scanorama import *\n\nfrom time import time\nimport numpy as np\n\nNAMESPACE = 'panorama_integrated'\n\nif __name__ == '__main__':\n from config import data_names\n\n datasets, genes_list, n_cells = load_names(data_names)\n datasets, genes = merge_datasets(datasets, genes_list)\n\n labels = []\n names = []\n curr_label = 0\n for i, a in enumerate(datasets):\n labels += list(np.zeros(a.shape[0]) + curr_label)\n names.append(data_names[i])\n curr_label += 1\n labels = np.array(labels, dtype=int)\n \n ########################\n ## Scanorama Assembly ##\n ########################\n\n datasets_dimred, genes = process_data(datasets, genes)\n \n # Put each of the datasets into a panorama.\n t0 = time()\n datasets_dimred = assemble(\n datasets_dimred, ds_names=data_names\n )\n if VERBOSE:\n print('Integrated panoramas in {:.3f}s'.format(time() - t0))\n\n embedding = visualize(\n datasets_dimred, labels, NAMESPACE, data_names,\n multicore_tsne=False\n )\n\n np.savetxt('data/{}_embedding.txt'.format(NAMESPACE),\n embedding, delimiter='\\t')\n"
] | [
[
"numpy.array",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
chanakya1310/background-score-prediction | [
"e56a5534e9a26a459a8ff561594a2fdef5276f7f"
] | [
"src/main/python/Emotion_Detection2.py"
] | [
"from keras.preprocessing.image import img_to_array\nimport imutils\nimport cv2\nfrom keras.models import load_model\nimport numpy as np\nimport argparse\nfrom collections import Counter \nimport time\nfrom tensorflow import keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten\nfrom keras.layers import Conv2D\nfrom keras.optimizers import Adam\nfrom keras.layers import MaxPooling2D\nfrom keras.preprocessing.image import ImageDataGenerator\n\ndef Emotion_Detection(emotion_model_path, prototext, model, input_video, c):\n\n net = cv2.dnn.readNetFromCaffe(prototext, model)\n model=Sequential()\n\n model.add(Conv2D(32,kernel_size=(3,3),activation='relu',input_shape=(48,48,1)))\n model.add(Conv2D(64,kernel_size=(3,3),activation='relu'))\n model.add(MaxPooling2D(pool_size=(2,2)))\n model.add(Dropout(0.25))\n\n model.add(Conv2D(128,kernel_size=(3,3),activation='relu'))\n model.add(MaxPooling2D(pool_size=(2,2)))\n model.add(Conv2D(128,kernel_size=(3,3),activation='relu'))\n model.add(MaxPooling2D(pool_size=(2,2)))\n model.add(Dropout(0.25))\n\n model.add(Flatten())\n model.add(Dense(1024,activation='relu'))\n model.add(Dropout(0.5))\n model.add(Dense(7,activation='softmax'))\n\n model.load_weights(emotion_model_path)\n #print(model.summary())\n emotion_dict={0:\"Angry\",1:\"Disgusted\",2:\"Fearful\",3:\"Happy\",4:\"Neutral\",5:\"Sad\",6:\"Surprised\"}\n\n cap = cv2.VideoCapture(input_video)\n\n property_id = int(cv2.CAP_PROP_FRAME_COUNT) \n total_no_of_frames = int(cv2.VideoCapture.get(cap, property_id)) \n # print(\"Total nunmber of frames in the video are\", total_no_of_frames)\n\n fps = cap.get(cv2.CAP_PROP_FPS)\n # print(\"Frames per second for this video is : {0}\".format(fps))\n seconds_interval = fps * 10\n no_of_loops = int(total_no_of_frames // seconds_interval) + 1\n # print(\"No of loops to be covered\", no_of_loops)\n loops_covered = 0 # Tracks the number of 10 seconds interval covered.\n\n limit = 0 # A variable used to wait until seconds_interval is reached\n count = 0\n \n labels = []\n probabilities = []\n sum_of_emotions_probabilities = np.array([0, 0, 0, 0, 0, 0, 0])\n cv2.ocl.setUseOpenCL(False)\n while True:\n ret, frame = cap.read()\n\n if not ret:\n break\n\n frame = imutils.resize(frame, width = 400)\n limit += 1\n\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n (h,w) = frame.shape[:2]\n \n blob = cv2.dnn.blobFromImage(cv2.resize(frame,(300,300)),1.0,(300,300),(104.0,177.0,123.0))\n\n net.setInput(blob)\n detections = net.forward()\n # print(detections)\n no_of_person = 0\n\n for i in range(0,detections.shape[2]):\n confidence = detections[0, 0, i, 2]\n\n if confidence < c:\n break\n\n # print(confidence)\n no_of_person += 1\n box = detections[0, 0, i, 3 : 7] * np.array([w, h, w, h])\n (startX, startY, endX, endY) = box.astype(\"int\")\n count += 1\n\n text = \"{:.2f}%\".format(confidence*100)\n y = startY - 10 if startY - 10 > 10 else startY + 10\n cv2.rectangle(frame, (startX, startY), (endX, endY), (0,0,255), 1)\n cv2.putText(frame, text, (startX, y), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 255, 0), 1)\n # coordinates_for_multi_person.append([startX, startY, endX, endY])\n # print(coordinates_for_multi_person)\n \n # Extract the ROI of the face from the grayscale image\n roi = gray[startY : endY, startX : endX]\n # print(roi.shape)\n if roi.shape[0] == 0 or roi.shape[1] == 0:\n break\n roi = np.expand_dims(np.expand_dims(cv2.resize(roi, (48, 48)), -1), 0)\n\n preds = model.predict(roi)[0]\n pred1 = np.array(preds)\n # print(pred1)\n\n sum_of_emotions_probabilities = sum_of_emotions_probabilities + pred1\n # print(\"Limit\", limit)\n # if limit == int(seconds_interval):\n # loops_covered += 1\n # sum_of_emotions_probabilities = sum_of_emotions_probabilities / seconds_interval\n # sum_of_emotions_probabilities = [ '%.2f' % elem for elem in sum_of_emotions_probabilities]\n # sum_of_emotions_probabilities = [float(elem) for elem in sum_of_emotions_probabilities]\n # emotion_probability = np.max(sum_of_emotions_probabilities)\n # label = EMOTIONS[emotion_probability.argmax()]\n # labels.append(label)\n # probabilities.append(sum_of_emotions_probabilities)\n # print(sum_of_emotions_probabilities)\n # print(label)\n # sum_of_emotions_probabilities = np.array([0, 0, 0, 0, 0, 0, 0])\n # limit = 0\n # print(sum_of_emotions_probabilities)\n if limit == int(seconds_interval):\n loops_covered += 1\n sum_of_emotions_probabilities = list(sum_of_emotions_probabilities)\n if sum_of_emotions_probabilities == [0, 0, 0, 0, 0, 0, 0]:\n probabilities.append([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])\n labels.append(\"No Person Detected\")\n # print(\"10 seconds paased\")\n else:\n sum_of_emotions_probabilities = np.array(sum_of_emotions_probabilities)\n sum_of_emotions_probabilities = sum_of_emotions_probabilities / count\n sum_of_emotions_probabilities = [ '%.2f' % elem for elem in sum_of_emotions_probabilities]\n sum_of_emotions_probabilities = [float(elem) for elem in sum_of_emotions_probabilities]\n maxindex=int(np.argmax(sum_of_emotions_probabilities))\n label=emotion_dict[maxindex]\n # print(label)\n labels.append(label)\n probabilities.append(sum_of_emotions_probabilities)\n # print(sum_of_emotions_probabilities)\n # print(label)\n sum_of_emotions_probabilities = np.array([0, 0, 0, 0, 0, 0, 0])\n count = 0\n # print(\"10 seconds passed\")\n limit = 0\n\n\n\n\n # print(\"Confidence score is\", confidence)\n # print(\"No of person\", no_of_person)\n # print(\"limit\", limit)\n # if no_of_person == 0 and limit == int(seconds_interval):\n # loops_covered += 1\n # probabilities.append([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])\n # labels.append(\"No Person Detected\")\n # limit = 0\n # print(\"Count is\", count)\n # print(\"No person detected\")\n\n # print(\"One person detection over ----\", label)\n # print(\"Number of people in the frame\", no_of_person)\n # print(\"Frame number\", total_no_of_frames) \n\n # cv2.imshow('your_face', frame)\n # if cv2.waitKey(1) & 0xFF == ord('q'):\n # break\n\n cap.release()\n cv2.destroyAllWindows()\n if limit < seconds_interval:\n loops_covered += 1\n # print(sum_of_emotions_probabilities)\n # print(\"Sum_of_Emotional_Probabilities\", sum_of_emotions_probabilities)\n sum_of_emotions_probabilities = list(sum_of_emotions_probabilities)\n if sum_of_emotions_probabilities == [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]:\n labels.append(\"No person detected\")\n probabilities.append([0.0] * 7)\n else:\n sum_of_emotions_probabilities = np.array(sum_of_emotions_probabilities)\n sum_of_emotions_probabilities = sum_of_emotions_probabilities / count\n sum_of_emotions_probabilities = [ '%.2f' % elem for elem in sum_of_emotions_probabilities]\n sum_of_emotions_probabilities = [float(elem) for elem in sum_of_emotions_probabilities]\n maxindex = int(np.argmax(sum_of_emotions_probabilities))\n label = emotion_dict[maxindex]\n labels.append(label)\n probabilities.append(list(sum_of_emotions_probabilities))\n # print(\"Total nunmber of frames in the video are\", total_no_of_frames)\n # print(\"Frames per second for this video is : {0}\".format(fps))\n # print(\"No of loops to be covered\", no_of_loops)\n # print(\"Loops covered\", loops_covered)\n # print(\"Emotion Labels\", labels)\n # print(\"Emotion Probabilities \", probabilities)\n # print(\"Length of Emotion Probabilities\", len(probabilities))\n\n return [labels, probabilities]"
] | [
[
"numpy.array",
"numpy.argmax"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
paramraghavan/beginners-py-learn | [
"120db42b3ad304915d5be172f4ebc555ef2cb405"
] | [
"src/funstuff/zoom_word_cloud.py"
] | [
"'''\nCreate background image for online work meetings and interviews.\nReferenced from :\nhttps://towardsdatascience.com/fun-valentines-day-gift-ideas-for-python-programmers-a27e87b9211b\nhttps://python-course.eu/applications-python/python-wordcloud-tutorial.php\nhttps://python-course.eu/applications-python\nhttps://www.tutorialexample.com/python-create-word-cloud-image-by-word-frequency-or-weight-value-python-wordcloud-tutorial/\n'''\nfrom wordcloud import WordCloud, STOPWORDS\nimport imageio\nimport matplotlib.pyplot as plt\n\ntext = 'bigdata,pyspark,aws,s3,emr,lambda,'\\\n 'api_gateway,dynamodb,elb,glue,iam,code_commit,redshift,docker, aws_batch,'\\\n 'ci_cd,serverless_framework,rds,java,python,shell_scripting,sql,neo4j,pyflask' \\\n ',aurora, oracle, postgres'\n\n\nprint(STOPWORDS)\nwordcloud = WordCloud(width=1900,\n height=1080,\n prefer_horizontal=0.5,\n #background_color=\"rgba(255, 255, 255, 0)\",\n #mode=\"RGBA\"\n ).generate(text)\n\n#plt.imshow(wordcloud, interpolation='bilinear')\nplt.imshow(wordcloud)\nplt.axis(\"off\")\nplt.show()\nwordcloud.to_file(\"zoom_background.png\")\n#plt.savefig(\"simple.png\")\n#wordcloud.to_file(\"simple.png\")\n"
] | [
[
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.show",
"matplotlib.pyplot.axis"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
iamshayankarami/write_with_pen_with_python | [
"90603edef33dc9b9d089e456fdccab2dfdf747d5"
] | [
"Test_image.py"
] | [
"import cv2\n\nimport numpy as np\nimport sys\nimport imutils, argparse\nfrom collections import deque\n\nvideo = cv2.VideoCapture(0)\n\nlow_blue = np.array([110,50,50])\nhigh_blue = np.array([130,255,255])\nshow_line = True\npoint = []\nwhile True:\n ret, frame = video.read()\n Shape = frame.shape\n if frame is None:\n break\n #frame = cv2.resize(frame, (300, 300), interpolation=cv2.INTER_AREA)\n blure = cv2.GaussianBlur(frame, (11, 11), 0)\n hsv = cv2.cvtColor(blure, cv2.COLOR_BGR2HSV)\n mask = cv2.inRange(hsv, low_blue, high_blue)\n mask = cv2.erode(mask, None, iterations=2)\n mask = cv2.dilate(mask, None, iterations=2)\n if cv2.waitKey(4) & 0xFF == ord(\"w\"):\n if show_line == True:\n show_line = False\n point = []\n else:\n show_line = True\n cuts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n cuts = imutils.grab_contours(cuts)\n center = None\n if len(cuts) > 0:\n c = max(cuts, key=cv2.contourArea)\n ((x, y), radius) = cv2.minEnclosingCircle(c)\n M = cv2.moments(c)\n Center = (int(M[\"m10\"] / M[\"m00\"]), int(M[\"m01\"] / M[\"m00\"]))\n center = (Shape[1]-Center[0], Center[1])\n #pgi.moveTo(center[0], center[1], duration=0)\n if radius > 10:\n cv2.circle(frame, (int(x), int(y)), int(radius), (0, 0, 255), 2)\n cv2.circle(frame, center, 5, (0,255,0), -1)\n if show_line:\n point.append(center)\n for i in range(1, len(point)):\n if point[i-1] is None or point[i] is None:\n continue\n cv2.line(frame, point[i-1], point[i], (255,255,0), 2)\n mask2 = cv2.inRange(frame, (255,255,0), (255,255,0))\n cv2.imshow(\"mask@\", mask2)\n #if center <= (100,100):\n # point = []\n #print(center[1])\n cv2.imshow(\"frame\", frame)\n if cv2.waitKey(4) & 0XFF == ord(\"a\"):\n point = []\n if cv2.waitKey(4) & 0XFF == ord(\"q\"):\n break\ncv2.destroyAllWindows()\n"
] | [
[
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
TnTech-CEROC/irp-logs-mining | [
"e20b409688e950da9f5bf5e5b94d98ebec0a842d"
] | [
"Dataset/data_processing.py"
] | [
"__author__ = \"Md. Ahsan Ayub\"\n__license__ = \"GPL\"\n__credits__ = [\"Ayub, Md. Ahsan\", \"Martindale, Nathan\", \"Smith, Steven\",\n \"Siraj, Ambareen\"]\n__maintainer__ = \"Md. Ahsan Ayub\"\n__email__ = \"[email protected]\"\n__status__ = \"Prototype\"\n\n# Importing libraries\nimport os\nimport glob\nimport pandas as pd\nimport numpy as np\nfrom datetime import datetime\nimport aggregator as aggregator\n \n\n'''# Scanning all the file names\nos.chdir(\"research/irp-logs-mining/Dataset/benign-irp-logs/machine_7\")\nall_filenames = [i for i in glob.glob('*')]\nall_filenames = sorted(all_filenames)'''\n\n# NPSY flags\ndef generateStringForIRPFlags(x):\n val = \"0:0:0:0\"\n if(len(x) != 4):\n return val\n else:\n if(x[0] != '-'): # N flag\n val = '1:'\n else:\n val = '0:'\n \n if(x[1] != '-'): # P flag\n val += '1:'\n else:\n val += '0:'\n \n if(x[2] != '-'): # S flag\n val += '1:'\n else:\n val += '0:'\n \n if(x[3] != '-'): # Y flag\n val += '1'\n else:\n val += '0'\n \n return val\n\n\ndef main(raw_dataset):\n # The following are the column names to be used for the processed dataset\n column_names = [\n \"operation_irp\", \"operation_fsf\", \"operation_fio\", #categorical / string -> int as flags\n \"sequence_number\", #hex / string -> int\n \"pre_operation_time\", \"post_operation_time\", #timestamp -> float\n \"operation_elapsed\", #float\n \"process_id\", \"thread_id\", \"parent_id\", #numerical\n \"process_name\", #string\n \"major_operation_type\", \"minor_operation_type\", #categorical / string\n \"irp_flag\", #hex / string -> int\n \"irp_nocache\", \"irp_paging_io\", \"irp_synchoronous_api\", \"irp_synchoronous_paging_io\", #flag values\n \"device_object\", \"file_object\", \"transaction\", \"status\", \"inform\", #hex / string -> int\n \"arg1\", \"arg2\", \"arg3\", \"arg4\", \"arg5\", \"arg6\", # hex / string -> int\n \"buffer_length\", \"entropy\", #numerical\n \"file_name\", #string\n \"family_id\", #numerical / multiclass\n \"class\" #binary\n ]\n \n raw_dataset = raw_dataset.drop(raw_dataset.index[0]) # Removing the first row \n raw_dataset.columns = raw_dataset.columns.str.strip()\n \n # Operation Type\n raw_dataset['Opr'] = raw_dataset['Opr'].str.strip()\n raw_dataset = raw_dataset.drop(raw_dataset[(raw_dataset['Opr'] != 'IRP') & (raw_dataset['Opr'] != 'FSF') & (raw_dataset['Opr'] != 'FIO')].index)\n \n # OneHotEncoding and then concat for operation\n one_hot = pd.get_dummies(raw_dataset.Opr, prefix='operation')\n raw_dataset = raw_dataset.drop('Opr', axis=1)\n raw_dataset = one_hot.join(raw_dataset)\n del one_hot\n \n # Sequence Number\n raw_dataset['SeqNum'] = raw_dataset['SeqNum'].str.strip()\n \n # Pre Operation Time\n raw_dataset['PreOp Time'] = raw_dataset['PreOp Time'].str.strip()\n raw_dataset['PreOp Time'] = [datetime.strptime(i, \"%H:%M:%S:%f\").strftime(\"%H:%M:%S.%f\") for i in raw_dataset['PreOp Time']]\n raw_dataset['PreOp Time'] = pd.to_timedelta(raw_dataset['PreOp Time']).dt.total_seconds()\n \n # Post Operation Time\n raw_dataset['PostOp Time'] = raw_dataset['PostOp Time'].str.strip()\n raw_dataset['PostOp Time'] = [datetime.strptime(i, \"%H:%M:%S:%f\").strftime(\"%H:%M:%S.%f\") for i in raw_dataset['PostOp Time']]\n raw_dataset['PostOp Time'] = pd.to_timedelta(raw_dataset['PostOp Time']).dt.total_seconds()\n \n # Operation Elapsed\n raw_dataset['operation_elapsed'] = raw_dataset['PostOp Time'] - raw_dataset['PreOp Time']\n \n # Parent ID\n raw_dataset['PPID'] = raw_dataset['PPID'].apply(str)\n raw_dataset['PPID'] = raw_dataset['PPID'].str.strip()\n raw_dataset['PPID'] = raw_dataset['PPID'].fillna(np.NaN) # Missing Value\n raw_dataset['PPID'] = raw_dataset['PPID'].str.replace('None', '-1') # nan and -1 does not represent anything\n try:\n raw_dataset['parent_id'] = raw_dataset['PPID'].astype('int32')\n except:\n raw_dataset['parent_id'] = raw_dataset['PPID'].astype(float)\n raw_dataset['parent_id'] = raw_dataset['parent_id'].astype('int32')\n raw_dataset = raw_dataset.drop('PPID', axis=1)\n \n # Process ID and Thread ID\n raw_dataset['Process.Thrd'] = raw_dataset['Process.Thrd'].apply(str)\n raw_dataset['Process.Thrd'] = raw_dataset['Process.Thrd'].str.strip()\n raw_dataset[['process_id', 'thread_id']] = raw_dataset['Process.Thrd'].str.split('.',expand=True)\n raw_dataset = raw_dataset.drop('Process.Thrd', axis=1)\n \n raw_dataset['process_id'] = raw_dataset['process_id'].fillna(np.NaN) # Missing Value\n raw_dataset['process_id'] = raw_dataset['process_id'].str.replace('None', '-1') # nan and -1 does not represent anything\n raw_dataset['process_id'] = raw_dataset['process_id'].astype('int32')\n \n raw_dataset['thread_id'] = raw_dataset['thread_id'].fillna(np.NaN) # Missing Value\n raw_dataset['thread_id'] = raw_dataset['thread_id'].str.replace('None', '-1') # nan and -1 does not represent anything\n raw_dataset['thread_id'] = raw_dataset['thread_id'].astype('int32')\n \n # Process Name\n raw_dataset['Process Name'] = raw_dataset['Process Name'].str.strip()\n \n # Major Operation\n raw_dataset['Major Operation'] = raw_dataset['Major Operation'].str.strip()\n raw_dataset['Major Operation'] = raw_dataset['Major Operation'].fillna(np.NaN) # Missing Value\n \n # Minor Operation\n raw_dataset['Minor Operation'] = raw_dataset['Minor Operation'].str.strip()\n raw_dataset['Minor Operation'] = raw_dataset['Minor Operation'].fillna(np.NaN) # Missing Value\n \n # IRP Flags\n raw_dataset['IrpFlags'] = raw_dataset['IrpFlags'].str.strip()\n raw_dataset[['irp_flag', 'temp']] = raw_dataset['IrpFlags'].str.split(' ',expand=True)\n raw_dataset['irp_flag'] = raw_dataset['irp_flag'].apply(str)\n raw_dataset['irp_flag'] = raw_dataset['irp_flag'].fillna(np.NaN) # Missing Value\n raw_dataset['irp_flag'] = raw_dataset['irp_flag'].str.replace('nan', '-0x1') # nan and -1 does not represent anything\n raw_dataset['irp_flag'] = raw_dataset['irp_flag'].str.replace('None', '-0x1') # None and -1 does not represent anything\n raw_dataset['irp_flag'] = raw_dataset['irp_flag'].apply(int, base=16)\n \n # Four Distinct IRP Flags - NPSY\n raw_dataset['temp'] = raw_dataset['temp'].apply(str)\n raw_dataset[[\"irp_nocache\", \"irp_paging_io\", \"irp_synchoronous_api\",\n \"irp_synchoronous_paging_io\"]] = raw_dataset['temp'].apply(lambda x : generateStringForIRPFlags(x)).str.split(':',expand=True)\n raw_dataset = raw_dataset.drop(['temp', 'IrpFlags'], axis=1)\n \n # Device Objects\n raw_dataset['DevObj'] = raw_dataset['DevObj'].str.strip()\n raw_dataset['DevObj'] = raw_dataset['DevObj'].fillna(np.NaN) # Missing Value\n \n # File Objects\n raw_dataset['FileObj'] = raw_dataset['FileObj'].str.strip()\n raw_dataset['FileObj'] = raw_dataset['FileObj'].fillna(np.NaN) # Missing Value\n \n # Transaction\n raw_dataset['Transactn'] = raw_dataset['Transactn'].str.strip()\n raw_dataset['Transactn'] = raw_dataset['Transactn'].fillna(np.NaN) # Missing Value\n \n # Status and Inform\n raw_dataset['status:inform'] = raw_dataset['status:inform'].apply(str)\n raw_dataset['status:inform'] = raw_dataset['status:inform'].str.strip()\n raw_dataset[['status', 'inform']] = raw_dataset['status:inform'].str.split(':',expand=True)\n raw_dataset['status'] = raw_dataset['status'].fillna(np.NaN) # Missing Value\n raw_dataset['status'] = raw_dataset['status'].str.replace('None', '-0x1') # None and -1 does not represent anything\n raw_dataset['status'] = raw_dataset['status'].str.replace('nan', '-0x1') # nan and -1 does not represent anything\n raw_dataset['status'] = raw_dataset['status'].apply(int, base=16) # Convert hex to int\n raw_dataset = raw_dataset.drop('status:inform', axis=1)\n \n # Arguments\n raw_dataset['Arg 1'] = raw_dataset['Arg 1'].str.strip()\n raw_dataset['Arg 1'] = raw_dataset['Arg 1'].fillna(np.NaN) # Missing Value\n raw_dataset['Arg 2'] = raw_dataset['Arg 2'].str.strip()\n raw_dataset['Arg 2'] = raw_dataset['Arg 2'].fillna(np.NaN) # Missing Value\n raw_dataset['Arg 3'] = raw_dataset['Arg 3'].str.strip()\n raw_dataset['Arg 3'] = raw_dataset['Arg 3'].fillna(np.NaN) # Missing Value\n raw_dataset['Arg 4'] = raw_dataset['Arg 4'].str.strip()\n raw_dataset['Arg 4'] = raw_dataset['Arg 4'].fillna(np.NaN) # Missing Value\n raw_dataset['Arg 5'] = raw_dataset['Arg 5'].str.strip()\n raw_dataset['Arg 5'] = raw_dataset['Arg 5'].fillna(np.NaN) # Missing Value\n raw_dataset['Arg 6'] = raw_dataset['Arg 6'].str.strip()\n raw_dataset['Arg 6'] = raw_dataset['Arg 6'].fillna(np.NaN) # Missing Value\n \n # Buffer Length\n raw_dataset['BufferLength'] = raw_dataset['BufferLength'].apply(str)\n raw_dataset['BufferLength'] = raw_dataset['BufferLength'].str.strip()\n raw_dataset['BufferLength'] = raw_dataset['BufferLength'].fillna(np.NaN) # Missing Value\n raw_dataset['BufferLength'] = raw_dataset['BufferLength'].str.replace('None', '0') # None and 0 does not represent anything\n raw_dataset['BufferLength'] = raw_dataset['BufferLength'].str.replace('nan', '0') # nan and 0 does not represent anything'''\n raw_dataset['buffer_length'] = raw_dataset['BufferLength'].astype(float)\n raw_dataset = raw_dataset.drop('BufferLength', axis=1)\n \n # Entropy\n raw_dataset['Entropy'] = raw_dataset['Entropy'].apply(str)\n raw_dataset['Entropy'] = raw_dataset['Entropy'].str.strip()\n raw_dataset['Entropy'] = raw_dataset['Entropy'].fillna(np.NaN) # Missing Value\n raw_dataset['Entropy'] = raw_dataset['Entropy'].str.replace('None', '0') # None and 0 does not represent anything\n raw_dataset['Entropy'] = raw_dataset['Entropy'].str.replace('nan', '0') # nan and 0 does not represent anything\n raw_dataset['entropy'] = raw_dataset['Entropy'].astype(float)\n raw_dataset = raw_dataset.drop('Entropy', axis=1)\n \n # File Name\n raw_dataset['Name'] = raw_dataset['Name'].str.strip()\n raw_dataset['Name'] = raw_dataset['Name'].fillna(np.NaN) # Missing Value\n \n # Additional two columns for class and family id\n raw_dataset['class'] = 0\n raw_dataset['family_id'] = 0\n \n # Renaming column names as per defination\n raw_dataset = raw_dataset.rename(columns={ 'operation_IRP' : 'operation_irp',\n 'operation_FSF' : 'operation_fsf',\n 'operation_FIO' : 'operation_fio',\n 'SeqNum' : 'sequence_number',\n 'PreOp Time' : 'pre_operation_time',\n 'PostOp Time' : 'post_operation_time',\n 'Process Name' : 'process_name',\n 'Major Operation' : 'major_operation_type',\n 'Minor Operation' : 'minor_operation_type',\n 'DevObj' : 'device_object',\n 'FileObj' : 'file_object',\n 'Transactn' : 'transaction',\n 'Arg 1' : 'arg1',\n 'Arg 2' : 'arg2',\n 'Arg 3' : 'arg3',\n 'Arg 4' : 'arg4',\n 'Arg 5' : 'arg5',\n 'Arg 6' : 'arg6',\n 'Name' : 'file_name' })\n \n # Returning the processed dataframe\n return raw_dataset[column_names]\n\n\nif __name__ == '__main__':\n \n '''all_filenames = [i for i in glob.glob('2*')]\n all_filenames = sorted(all_filenames)\n print(all_filenames)'''\n \n \n all_given_files = [i for i in glob.glob('./ransomware-irp-logs-9/*')]\n all_given_files = sorted(all_given_files)\n all_given_files_hashes = [filename.split('/')[-1] for filename in all_given_files]\n all_given_files_hashes = [filename.split('.')[0] for filename in all_given_files_hashes]\n \n all_available_files_hashes = [i for i in glob.glob('./ransomware-irp-logs/Time_Interval_Dataset/*')]\n all_available_files_hashes = [filename.split('/')[-1] for filename in all_available_files_hashes]\n all_available_files_hashes = [filename.split('.')[0] for filename in all_available_files_hashes]\n all_available_files_hashes = sorted(all_available_files_hashes)\n \n for i in range(len(all_given_files_hashes)):\n if(all_given_files_hashes[i] in all_available_files_hashes):\n all_given_files_hashes[i] = 0\n os.remove(all_given_files[i])\n all_given_files.pop(i)\n \n # File Name for the csv file \n #file_name = '02ef81bb120472b87d413516a8ccc8202d9e04d686ebdedbfcd963b6a9673109'\n i = 1\n \n for file_name in all_given_files:\n \n # Initialize a process dataframe\n #processed_dataset = main(pd.read_csv('../../ransomware-lrp-logs/' + str(file_name), engine='python', sep = '\\t'))\n \n try:\n processed_dataset = main(pd.read_csv(str(file_name), engine='python', sep = '\\t', compression='gzip'))\n print(\"Data processing is done.\")\n \n # Generate aggregated dataframe\n processed_aggregate_dataset = aggregator.aggegateData(processed_dataset)\n print(\"Aggegating the processed dataset is also done.\")\n \n file_name_copy = file_name\n file_name = file_name.split('/')[-1]\n file_name = file_name.split('.')[0]\n \n # Dump processed dataset\n # processed_dataset.to_csv(\"./ransomware-irp-logs/\" + str(file_name) + \"_processed.csv.gz\", compression='gzip')\n processed_dataset.to_pickle(\"./ransomware-irp-logs/\" + str(file_name) + \"_processed.pkl.gz\", compression='gzip')\n print(\"Processed dataset is dumped, shape %s\" % str(processed_dataset.shape))\n \n # Dump aggregated dataframe\n processed_aggregate_dataset.to_csv(\"./ransomware-irp-logs/\" + str(file_name) + \"_processed_aggregated.csv.gz\", compression='gzip')\n print(\"Aggregated dataset is dumped, shape %s\" % str(processed_aggregate_dataset.shape))\n \n del processed_dataset, processed_aggregate_dataset\n \n os.remove(file_name_copy)\n print(\"%s is removed\" % file_name)\n \n print(i)\n i += 1\n\n except:\n print(i)\n i += 1\n continue\n"
] | [
[
"pandas.to_timedelta",
"pandas.get_dummies"
]
] | [
{
"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": []
}
] |
funcional-health-analytics/covid19-analytics | [
"8aba46dd6f75b8313f26d073078c40065e62ec21"
] | [
"src/app_interactive_seir/visualization/plot_simulation.py"
] | [
"import pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport streamlit as st\n\n# plt.style.use(\"seaborn-whitegrid\")\n\n\ndef plot_simulation_output(df: pd.DataFrame, target_location: str):\n df = df[[\"S\", \"E\", \"I\", \"R\", \"E+I\", \"E+I+R\"]]\n\n fig1 = plt.figure()\n sns.despine()\n plt.grid()\n ax = sns.lineplot(data=df)\n ax.set_title(\"Visão Geral da Epidemia\")\n\n fig2 = plt.figure()\n sns.despine()\n plt.grid()\n ax = sns.lineplot(data=df[[\"E\", \"I\", \"E+I\", \"E+I+R\"]])\n ax.set_title(\"Apenas Expostos e Infectados\")\n\n zoom_length = 30\n peak_date = df[\"I\"].idxmax().date()\n zoom_on = (pd.Timestamp(peak_date) - pd.DateOffset(days=zoom_length)).date()\n\n zoom_end = (pd.Timestamp(peak_date) + pd.DateOffset(days=zoom_length)).date()\n fig3 = plt.figure()\n sns.despine()\n plt.grid()\n ax = sns.lineplot(\n data=df[[\"E\", \"I\", \"E+I\"]][zoom_on:zoom_end], markers=True\n )\n ax.set_title(f\"Zoom (de {zoom_on} a {zoom_end})\")\n plt.xticks(fontsize=8, rotation=30)\n\n return st.markdown(f\"# Modelo SEIR - {target_location}\"), st.pyplot(fig1), st.pyplot(fig2), st.pyplot(fig3)\n\n\ndef display_peaks_from_simulation(peak_value: int, peak_date: pd.DatetimeIndex, category: str = \"I\") -> None:\n category_dict = {\n \"S\": \"Suscetíveis\",\n \"E\": \"Expostos\",\n \"I\": \"Infectados\",\n \"R\": \"Recuperados\",\n }\n st.markdown(f\"# Datas e Valores de Pico ({category_dict[category]})\")\n st.markdown(f\"Data: **{str(peak_date)[:10]}**\")\n st.markdown(f\"{category_dict[category]}: **{int(round(peak_value, 0))}**\")\n"
] | [
[
"pandas.DateOffset",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.xticks",
"pandas.Timestamp",
"matplotlib.pyplot.figure"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Lewis-Picker/VIP | [
"494190d124dd19e3494b0825b4c82c37d8207074"
] | [
"vip_hci/var/fit_2d.py"
] | [
"#! /usr/bin/env python\n\n\"\"\"\n2d fitting and creation of synthetic PSFs.\n\"\"\"\n\n\n__author__ = 'Carlos Alberto Gomez Gonzalez'\n__all__ = ['create_synth_psf',\n 'fit_2dgaussian',\n 'fit_2dmoffat',\n 'fit_2dairydisk']\n\nimport pdb\nimport numpy as np\nimport pandas as pd\nimport photutils\nfrom hciplot import plot_frames\nfrom astropy.modeling import models, fitting\nfrom astropy.stats import (gaussian_sigma_to_fwhm, gaussian_fwhm_to_sigma,\n sigma_clipped_stats)\nfrom .shapes import get_square, frame_center\nfrom ..conf import check_array\n\n\ndef create_synth_psf(model='gauss', shape=(9, 9), amplitude=1, x_mean=None,\n y_mean=None, fwhm=4, theta=0, gamma=None, alpha=1,\n radius=None, msdi=False):\n \"\"\" Creates a synthetic 2d or 3d PSF with a 2d model: Airy disk, Gaussian or\n Moffat, depending on ``model``.\n\n Parameters\n ----------\n model : {'gauss', 'moff', 'airy'}, str optional\n Model to be used to create the synthetic PSF.\n shape : tuple of ints, optional\n Shape of the output 2d array.\n amplitude : float, optional\n Value of the amplitude of the 2d distribution.\n x_mean : float or None, optional\n Value of the centroid in X of the distributions: the mean of the\n Gaussian or the location of the maximum of the Moffat or Airy disk\n models. If None, the centroid is placed at the center of the array.\n y_mean : float or None, optional\n Value of the centroid in Y of the distributions: the mean of the\n Gaussian or the location of the maximum of the Moffat or Airy disk\n models. If None, the centroid is placed at the center of the array.\n fwhm : float, tuple of floats, list or np.ndarray, optional\n FWHM of the model in pixels. For the Gaussian case, it controls the\n standard deviation of the Gaussian. If a tuple is given, then the\n Gaussian will be elongated (fwhm in x, fwhm in y). For the Moffat, it is\n related to the gamma and alpha parameters. For the Airy disk, it is\n related to the radius (of the first zero) parameter. If ``msdi`` is True\n then ``fwhm`` must be a list of 1d np.ndarray (for example for\n SPHERE/IFS this sounds like a reasonable FWHM: np.linspace(4.5,6.7,39)).\n theta : float, optional\n Rotation angle in degrees of the Gaussian.\n gamma : float or None, optional\n Gamma parameter of core width of the Moffat model. If None, then it is\n calculated to correspond to the given ``fwhm``.\n alpha : float, optional\n Power index of the Moffat model.\n radius : float or None, optional\n The radius of the Airy disk (radius of the first zero). If None, then it\n is calculated to correspond to the given ``fwhm``.\n msdi : bool, optional\n Creates a 3d PSF, for emulating an IFS PSF.\n\n Returns\n -------\n im : numpy ndarray\n 2d array with given ``shape`` and containing the synthetic PSF.\n\n Notes\n -----\n http://docs.astropy.org/en/stable/api/astropy.modeling.functional_models.Gaussian2D.html\n http://docs.astropy.org/en/stable/api/astropy.modeling.functional_models.Moffat2D.html\n http://docs.astropy.org/en/stable/api/astropy.modeling.functional_models.AiryDisk2D.html\n\n https://www.gnu.org/software/gnuastro/manual/html_node/PSF.html\n web.ipac.caltech.edu/staff/fmasci/home/astro_refs/PSFtheory.pdf\n web.ipac.caltech.edu/staff/fmasci/home/astro_refs/PSFsAndSampling.pdf\n \"\"\"\n # 2d case\n if not msdi:\n sizex, sizey = shape\n if x_mean is None or y_mean is None:\n y_mean, x_mean = frame_center(np.zeros((sizey, sizex)))\n x = np.arange(sizex)\n y = np.arange(sizey)\n x, y = np.meshgrid(x, y)\n\n if model == 'gauss':\n if isinstance(fwhm, (tuple, list)):\n fwhm_x, fwhm_y = fwhm\n else:\n fwhm_y = fwhm\n fwhm_x = fwhm\n gauss = models.Gaussian2D(amplitude=amplitude, x_mean=x_mean,\n y_mean=y_mean,\n x_stddev=fwhm_x * gaussian_fwhm_to_sigma,\n y_stddev=fwhm_y * gaussian_fwhm_to_sigma,\n theta=np.deg2rad(theta))\n im = gauss(x, y)\n elif model == 'moff':\n if gamma is None and fwhm is not None:\n gamma = fwhm / (2. * np.sqrt(2 ** (1 / alpha) - 1))\n moffat = models.Moffat2D(amplitude=amplitude, x_0=x_mean,\n y_0=y_mean, gamma=gamma, alpha=alpha)\n im = moffat(x, y)\n elif model == 'airy':\n if radius is None and fwhm is not None:\n diam_1st_zero = (fwhm * 2.44) / 1.028\n radius = diam_1st_zero / 2.\n airy = models.AiryDisk2D(amplitude=amplitude, x_0=x_mean,\n y_0=y_mean, radius=radius)\n im = airy(x, y)\n return im\n # 3d case\n else:\n if not isinstance(fwhm, (list, np.ndarray)):\n raise ValueError('`Fwhm` must be a 1d vector')\n\n cube = []\n for fwhm_i in fwhm:\n cube.append(create_synth_psf(model, shape, amplitude, x_mean,\n y_mean, fwhm_i, theta, gamma, alpha,\n radius))\n cube = np.array(cube)\n return cube\n\n\ndef fit_2dgaussian(array, crop=False, cent=None, cropsize=15, fwhmx=4, fwhmy=4,\n theta=0, threshold=False, sigfactor=6, full_output=True,\n debug=True):\n \"\"\" Fitting a 2D Gaussian to the 2D distribution of the data.\n\n Parameters\n ----------\n array : numpy ndarray\n Input frame with a single PSF.\n crop : bool, optional\n If True an square sub image will be cropped.\n cent : tuple of int, optional\n X,Y integer position of source in the array for extracting the subimage.\n If None the center of the frame is used for cropping the subframe (the\n PSF is assumed to be ~ at the center of the frame).\n cropsize : int, optional\n Size of the subimage.\n fwhmx, fwhmy : float, optional\n Initial values for the standard deviation of the fitted Gaussian, in px.\n theta : float, optional\n Angle of inclination of the 2d Gaussian counting from the positive X\n axis.\n threshold : bool, optional\n If True the background pixels (estimated using sigma clipped statistics)\n will be replaced by small random Gaussian noise.\n sigfactor : int, optional\n The background pixels will be thresholded before fitting a 2d Gaussian\n to the data using sigma clipped statistics. All values smaller than\n (MEDIAN + sigfactor*STDDEV) will be replaced by small random Gaussian\n noise.\n full_output : bool, optional\n If False it returns just the centroid, if True also returns the\n FWHM in X and Y (in pixels), the amplitude and the rotation angle,\n and the uncertainties on each parameter.\n debug : bool, optional\n If True, the function prints out parameters of the fit and plots the\n data, model and residuals.\n\n Returns\n -------\n mean_y : float\n Source centroid y position on input array from fitting.\n mean_x : float\n Source centroid x position on input array from fitting.\n\n If ``full_output`` is True it returns a Pandas dataframe containing the\n following columns:\n 'amplitude' : Float value. Amplitude of the Gaussian.\n 'centroid_x' : Float value. X coordinate of the centroid.\n 'centroid_y' : Float value. Y coordinate of the centroid.\n 'fwhm_x' : Float value. FHWM in X [px].\n 'fwhm_y' : Float value. FHWM in Y [px].\n 'theta' : Float value. Rotation angle.\n\n \"\"\"\n check_array(array, dim=2, msg='array')\n\n if crop:\n if cent is None:\n ceny, cenx = frame_center(array)\n else:\n cenx, ceny = cent\n\n imside = array.shape[0]\n psf_subimage, suby, subx = get_square(array, min(cropsize, imside),\n ceny, cenx, position=True)\n else:\n psf_subimage = array.copy()\n\n if threshold:\n _, clipmed, clipstd = sigma_clipped_stats(psf_subimage, sigma=2)\n indi = np.where(psf_subimage <= clipmed + sigfactor * clipstd)\n subimnoise = np.random.randn(psf_subimage.shape[0],\n psf_subimage.shape[1]) * clipstd\n psf_subimage[indi] = subimnoise[indi]\n\n # Creating the 2D Gaussian model\n init_amplitude = np.ptp(psf_subimage)\n xcom, ycom = photutils.centroid_com(psf_subimage)\n gauss = models.Gaussian2D(amplitude=init_amplitude, theta=theta,\n x_mean=xcom, y_mean=ycom,\n x_stddev=fwhmx * gaussian_fwhm_to_sigma,\n y_stddev=fwhmy * gaussian_fwhm_to_sigma)\n # Levenberg-Marquardt algorithm\n fitter = fitting.LevMarLSQFitter()\n y, x = np.indices(psf_subimage.shape)\n fit = fitter(gauss, x, y, psf_subimage)\n\n if crop:\n mean_y = fit.y_mean.value + suby\n mean_x = fit.x_mean.value + subx\n else:\n mean_y = fit.y_mean.value\n mean_x = fit.x_mean.value\n fwhm_y = fit.y_stddev.value*gaussian_sigma_to_fwhm\n fwhm_x = fit.x_stddev.value*gaussian_sigma_to_fwhm\n amplitude = fit.amplitude.value\n theta = np.rad2deg(fit.theta.value)\n \n # compute uncertainties\n if fitter.fit_info['param_cov'] is not None:\n perr = np.sqrt(np.diag(fitter.fit_info['param_cov']))\n amplitude_e, theta_e, mean_x_e, mean_y_e, fwhm_x_e, fwhm_y_e = perr\n fwhm_x_e /= gaussian_fwhm_to_sigma\n fwhm_y_e /= gaussian_fwhm_to_sigma\n else:\n amplitude_e, theta_e, mean_x_e = None, None, None\n mean_y_e, fwhm_x_e, fwhm_y_e = None, None, None\n\n if debug:\n if threshold:\n label = ('Subimage thresholded', 'Model', 'Residuals')\n else:\n label = ('Subimage', 'Model', 'Residuals')\n plot_frames((psf_subimage, fit(x, y), psf_subimage-fit(x, y)),\n grid=True, grid_spacing=1, label=label)\n print('FWHM_y =', fwhm_y)\n print('FWHM_x =', fwhm_x, '\\n')\n print('centroid y =', mean_y)\n print('centroid x =', mean_x)\n print('centroid y subim =', fit.y_mean.value)\n print('centroid x subim =', fit.x_mean.value, '\\n')\n print('amplitude =', amplitude)\n print('theta =', theta)\n\n if full_output:\n return pd.DataFrame({'centroid_y': mean_y, 'centroid_x': mean_x,\n 'fwhm_y': fwhm_y, 'fwhm_x': fwhm_x,\n 'amplitude': amplitude, 'theta': theta,\n 'centroid_y_err': mean_y_e, \n 'centroid_x_err': mean_x_e,\n 'fwhm_y_err': fwhm_y_e, 'fwhm_x_err': fwhm_x_e,\n 'amplitude_err': amplitude_e, \n 'theta_err': theta_e}, index=[0])\n else:\n return mean_y, mean_x\n\n\ndef fit_2dmoffat(array, crop=False, cent=None, cropsize=15, fwhm=4,\n threshold=False, sigfactor=6, full_output=True, debug=True):\n \"\"\" Fitting a 2D Moffat to the 2D distribution of the data.\n\n Parameters\n ----------\n array : numpy ndarray\n Input frame with a single PSF.\n crop : bool, optional\n If True an square sub image will be cropped.\n cent : tuple of int, optional\n X,Y integer position of source in the array for extracting the subimage.\n If None the center of the frame is used for cropping the subframe (the\n PSF is assumed to be ~ at the center of the frame).\n cropsize : int, optional\n Size of the subimage.\n fwhm : float, optional\n Initial values for the FWHM of the fitted 2d Moffat, in px.\n threshold : bool, optional\n If True the background pixels (estimated using sigma clipped statistics)\n will be replaced by small random Gaussian noise.\n sigfactor : int, optional\n The background pixels will be thresholded before fitting a 2d Moffat\n to the data using sigma clipped statistics. All values smaller than\n (MEDIAN + sigfactor*STDDEV) will be replaced by small random Gaussian\n noise.\n full_output : bool, optional\n If False it returns just the centroid, if True also returns the\n FWHM in X and Y (in pixels), the amplitude and the rotation angle.\n debug : bool, optional\n If True, the function prints out parameters of the fit and plots the\n data, model and residuals.\n\n Returns\n -------\n mean_y : float\n Source centroid y position on input array from fitting.\n mean_x : float\n Source centroid x position on input array from fitting.\n\n If ``full_output`` is True it returns a Pandas dataframe containing the\n following columns:\n 'alpha': Float value. Alpha parameter.\n 'amplitude' : Float value. Moffat Amplitude.\n 'centroid_x' : Float value. X coordinate of the centroid.\n 'centroid_y' : Float value. Y coordinate of the centroid.\n 'fwhm' : Float value. FHWM [px].\n 'gamma' : Float value. Gamma parameter.\n\n \"\"\"\n check_array(array, dim=2, msg='array')\n\n if crop:\n if cent is None:\n ceny, cenx = frame_center(array)\n else:\n cenx, ceny = cent\n\n imside = array.shape[0]\n psf_subimage, suby, subx = get_square(array, min(cropsize, imside),\n ceny, cenx, position=True)\n else:\n psf_subimage = array.copy()\n\n if threshold:\n _, clipmed, clipstd = sigma_clipped_stats(psf_subimage, sigma=2)\n indi = np.where(psf_subimage <= clipmed + sigfactor * clipstd)\n subimnoise = np.random.randn(psf_subimage.shape[0],\n psf_subimage.shape[1]) * clipstd\n psf_subimage[indi] = subimnoise[indi]\n\n # Creating the 2D Moffat model\n init_amplitude = np.ptp(psf_subimage)\n xcom, ycom = photutils.centroid_com(psf_subimage)\n moffat = models.Moffat2D(amplitude=init_amplitude, x_0=xcom, y_0=ycom,\n gamma=fwhm / 2., alpha=1)\n # Levenberg-Marquardt algorithm\n fitter = fitting.LevMarLSQFitter()\n y, x = np.indices(psf_subimage.shape)\n fit = fitter(moffat, x, y, psf_subimage)\n\n if crop:\n mean_y = fit.y_0.value + suby\n mean_x = fit.x_0.value + subx\n else:\n mean_y = fit.y_0.value\n mean_x = fit.x_0.value\n\n fwhm = fit.fwhm\n amplitude = fit.amplitude.value\n alpha = fit.alpha.value\n gamma = fit.gamma.value\n\n\n\n if debug:\n if threshold:\n label = ('Subimage thresholded', 'Model', 'Residuals')\n else:\n label = ('Subimage', 'Model', 'Residuals')\n plot_frames((psf_subimage, fit(x, y), psf_subimage - fit(x, y)),\n grid=True, grid_spacing=1, label=label)\n print('FWHM =', fwhm)\n print('centroid y =', mean_y)\n print('centroid x =', mean_x)\n print('centroid y subim =', fit.y_0.value)\n print('centroid x subim =', fit.x_0.value, '\\n')\n print('amplitude =', amplitude)\n print('alpha =', alpha)\n print('gamma =', gamma)\n\n # compute uncertainties\n if fitter.fit_info['param_cov'] is not None:\n perr = np.sqrt(np.diag(fitter.fit_info['param_cov']))\n amplitude_err, mean_x_err, mean_y_err, gamma_err, alpha_err = perr\n fwhm_err = 2*gamma_err\n else:\n amplitude_err, mean_x_err, mean_y_err = None, None, None\n gamma_err, alpha_err, fwhm_err = None, None, None\n \n if full_output:\n return pd.DataFrame({'centroid_y': mean_y, 'centroid_x': mean_x,\n 'fwhm': fwhm, 'alpha': alpha, 'gamma': gamma,\n 'amplitude': amplitude, 'centroid_y_err': mean_y_err, \n 'centroid_x_err': mean_x_err,\n 'fwhm_err': fwhm_err, 'alpha_err': alpha_err, \n 'gamma_err': gamma_err, \n 'amplitude_err': amplitude_err}, index=[0])\n else:\n return mean_y, mean_x\n\n\ndef fit_2dairydisk(array, crop=False, cent=None, cropsize=15, fwhm=4,\n threshold=False, sigfactor=6, full_output=True,\n debug=True):\n \"\"\" Fitting a 2D Airy to the 2D distribution of the data.\n\n Parameters\n ----------\n array : numpy ndarray\n Input frame with a single PSF.\n crop : bool, optional\n If True an square sub image will be cropped.\n cent : tuple of int, optional\n X,Y integer position of source in the array for extracting the subimage.\n If None the center of the frame is used for cropping the subframe (the\n PSF is assumed to be ~ at the center of the frame).\n cropsize : int, optional\n Size of the subimage.\n fwhm : float, optional\n Initial values for the FWHM of the fitted 2d Moffat, in px.\n threshold : bool, optional\n If True the background pixels (estimated using sigma clipped statistics)\n will be replaced by small random Gaussian noise.\n sigfactor : int, optional\n The background pixels will be thresholded before fitting a 2d Moffat\n to the data using sigma clipped statistics. All values smaller than\n (MEDIAN + sigfactor*STDDEV) will be replaced by small random Gaussian\n noise.\n full_output : bool, optional\n If False it returns just the centroid, if True also returns the\n FWHM in X and Y (in pixels), the amplitude and the rotation angle.\n debug : bool, optional\n If True, the function prints out parameters of the fit and plots the\n data, model and residuals.\n\n Returns\n -------\n mean_y : float\n Source centroid y position on input array from fitting.\n mean_x : float\n Source centroid x position on input array from fitting.\n\n If ``full_output`` is True it returns a Pandas dataframe containing the\n following columns:\n 'alpha': Float value. Alpha parameter.\n 'amplitude' : Float value. Moffat Amplitude.\n 'centroid_x' : Float value. X coordinate of the centroid.\n 'centroid_y' : Float value. Y coordinate of the centroid.\n 'fwhm' : Float value. FHWM [px].\n\n \"\"\"\n check_array(array, dim=2, msg='array')\n\n if crop:\n if cent is None:\n ceny, cenx = frame_center(array)\n else:\n cenx, ceny = cent\n\n imside = array.shape[0]\n psf_subimage, suby, subx = get_square(array, min(cropsize, imside),\n ceny, cenx, position=True)\n else:\n psf_subimage = array.copy()\n\n if threshold:\n _, clipmed, clipstd = sigma_clipped_stats(psf_subimage, sigma=2)\n indi = np.where(psf_subimage <= clipmed + sigfactor * clipstd)\n subimnoise = np.random.randn(psf_subimage.shape[0],\n psf_subimage.shape[1]) * clipstd\n psf_subimage[indi] = subimnoise[indi]\n\n # Creating the 2d Airy disk model\n init_amplitude = np.ptp(psf_subimage)\n xcom, ycom = photutils.centroid_com(psf_subimage)\n diam_1st_zero = (fwhm * 2.44) / 1.028\n airy = models.AiryDisk2D(amplitude=init_amplitude, x_0=xcom, y_0=ycom,\n radius=diam_1st_zero/2.)\n # Levenberg-Marquardt algorithm\n fitter = fitting.LevMarLSQFitter()\n y, x = np.indices(psf_subimage.shape)\n fit = fitter(airy, x, y, psf_subimage)\n\n if crop:\n mean_y = fit.y_0.value + suby\n mean_x = fit.x_0.value + subx\n else:\n mean_y = fit.y_0.value\n mean_x = fit.x_0.value\n\n amplitude = fit.amplitude.value\n radius = fit.radius.value\n fwhm = ((radius * 1.028) / 2.44) * 2\n\n # compute uncertainties\n if fitter.fit_info['param_cov'] is not None:\n perr = np.sqrt(np.diag(fitter.fit_info['param_cov']))\n amplitude_err, mean_x_err, mean_y_err, radius_err = perr\n fwhm_err = ((radius_err * 1.028) / 2.44) * 2\n else:\n amplitude_err, mean_x_err, mean_y_err = None, None, None\n radius_err, fwhm_err = None, None\n\n if debug:\n if threshold:\n label = ('Subimage thresholded', 'Model', 'Residuals')\n else:\n label = ('Subimage', 'Model', 'Residuals')\n plot_frames((psf_subimage, fit(x, y), psf_subimage - fit(x, y)),\n grid=True, grid_spacing=1, label=label)\n print('FWHM =', fwhm)\n print('centroid y =', mean_y)\n print('centroid x =', mean_x)\n print('centroid y subim =', fit.y_0.value)\n print('centroid x subim =', fit.x_0.value, '\\n')\n print('amplitude =', amplitude)\n print('radius =', radius)\n\n if full_output:\n return pd.DataFrame({'centroid_y': mean_y, 'centroid_x': mean_x,\n 'fwhm': fwhm, 'radius': radius,\n 'amplitude': amplitude, \n 'centroid_y_err': mean_y_err, \n 'centroid_x_err': mean_x_err, \n 'fwhm_err': fwhm_err, 'radius_err': radius_err,\n 'amplitude_err': amplitude_err}, index=[0])\n else:\n return mean_y, mean_x\n"
] | [
[
"numpy.diag",
"numpy.sqrt",
"numpy.arange",
"numpy.indices",
"numpy.ptp",
"numpy.rad2deg",
"pandas.DataFrame",
"numpy.deg2rad",
"numpy.random.randn",
"numpy.array",
"numpy.meshgrid",
"numpy.where",
"numpy.zeros"
]
] | [
{
"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": []
}
] |
mle-infrastructure/mle-monitor | [
"5451986d3ca6855ec78be343a8147235f893ef8f"
] | [
"mle_monitor/resource/gcp.py"
] | [
"import time\nimport subprocess as sp\nimport pandas as pd\nfrom typing import Union\n\n\nclass GCPResource(object):\n def __init__(self, monitor_config: Union[dict, None]):\n self.resource_name = \"gcp-cloud\"\n self.monitor_config = monitor_config\n\n def monitor(self):\n \"\"\"Helper to get all utilisation data for resource.\"\"\"\n return self.get_data()\n\n def get_data(self):\n \"\"\"Helper to get all utilisation data for GCP resource.\"\"\"\n while True:\n try:\n check_cmd = [\n \"gcloud\",\n \"compute\",\n \"instances\",\n \"list\",\n \"--verbosity\",\n \"error\",\n ]\n out = sp.check_output(check_cmd)\n break\n except sp.CalledProcessError:\n time.sleep(1)\n\n # Clean up and check if vm_name is in list of all jobs\n job_info = out.split(b\"\\n\")[1:-1]\n df_gcp = {\"experiment_type\": [], \"status\": []}\n for i in range(len(job_info)):\n decoded_job_info = job_info[i].decode(\"utf-8\").split()\n df_gcp[\"experiment_type\"].append(decoded_job_info[2])\n df_gcp[\"status\"].append(decoded_job_info[-1])\n df_gcp = pd.DataFrame(df_gcp)\n\n gcp_data = {\"experiment_type\": [], \"run\": [], \"stop\": [], \"stage\": []}\n for jt in df_gcp.experiment_type.unique():\n sub_df = df_gcp[df_gcp.experiment_type == jt]\n run = (sub_df[\"status\"] == \"RUNNING\").sum()\n stop = (sub_df[\"status\"] == \"STOPPING\").sum()\n stage = (sub_df[\"status\"] == \"STAGING\").sum()\n gcp_data[\"experiment_type\"].append(jt)\n gcp_data[\"run\"].append(run)\n gcp_data[\"stop\"].append(stop)\n gcp_data[\"stage\"].append(stage)\n # Return list of different machine types and their status\n return gcp_data\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": []
}
] |
mmurray/merged_depth | [
"a99a518b228c1693e1078d2f4832bcbc03e0924c"
] | [
"merged_depth/nets/DiverseDepth/lib/models/lateral_net.py"
] | [
"import torch\r\nimport torch.nn as nn\r\nfrom lib.core.config import cfg\r\nimport lib.models.ResNeXt as ResNeXt\r\nimport lib.utils.resnext_weights_helper as resnext_utils\r\nimport lib.utils.mobilenetv2_weight_helper as mobilenet_utils\r\nfrom torch.nn import functional as F\r\nimport math\r\n\r\ndef lateral_resnext50_32x4d_body_stride16():\r\n return lateral(ResNeXt.ResNeXt50_32x4d_body_stride16)\r\n\r\n\r\nclass lateral(nn.Module):\r\n def __init__(self, conv_body_func):\r\n super().__init__()\r\n\r\n self.dim_in = cfg.MODEL.RESNET_BOTTLENECK_DIM\r\n self.dim_in = self.dim_in[-1:0:-1]\r\n self.dim_out = cfg.MODEL.LATERAL_OUT\r\n\r\n self.num_lateral_stages = len(self.dim_in)\r\n self.topdown_lateral_modules = nn.ModuleList()\r\n\r\n for i in range(self.num_lateral_stages):\r\n self.topdown_lateral_modules.append(\r\n lateral_block(self.dim_in[i], self.dim_out[i]))\r\n\r\n self.bottomup = conv_body_func()\r\n dilation_rate = [4, 8, 12] if 'stride_8' in cfg.MODEL.ENCODER else [2, 4, 6]\r\n encoder_stride = 8 if 'stride8' in cfg.MODEL.ENCODER else 16\r\n self.bottomup_top = ASPP_block(self.dim_in[0], self.dim_out[0], dilation_rate, encoder_stride) if 'resnext' in cfg.MODEL.ENCODER.lower() \\\r\n else Global_pool_block(self.dim_in[0], self.dim_out[0])\r\n self._init_modules(cfg.MODEL.INIT_TYPE)\r\n\r\n def _init_modules(self, init_type):\r\n if cfg.MODEL.LOAD_IMAGENET_PRETRAINED_WEIGHTS:\r\n if 'resnext' in cfg.MODEL.ENCODER.lower():\r\n resnext_utils.load_pretrained_imagenet_resnext_weights(self.bottomup)\r\n elif 'mobilenetv2' in cfg.MODEL.ENCODER.lower():\r\n mobilenet_utils.load_pretrained_imagenet_resnext_weights(self.bottomup)\r\n\r\n self._init_weights(init_type)\r\n\r\n def _init_weights(self, init_type='xavier'):\r\n def init_func(m):\r\n if isinstance(m, nn.Conv2d):\r\n if init_type == 'xavier':\r\n nn.init.xavier_normal_(m.weight)\r\n if init_type == 'kaiming':\r\n nn.init.kaiming_normal_(m.weight)\r\n if init_type == 'gaussian':\r\n nn.init.normal_(m.weight, std=0.01)\r\n if m.bias is not None:\r\n nn.init.constant_(m.bias, 0.0)\r\n elif isinstance(m, nn.BatchNorm2d):\r\n nn.init.constant_(m.weight.data, 1.0)\r\n nn.init.constant_(m.bias.data, 0.0)\r\n def init_model_weight(m):\r\n for child_m in m.children():\r\n if not isinstance(child_m, nn.ModuleList):\r\n child_m.apply(init_func)\r\n\r\n if cfg.MODEL.LOAD_IMAGENET_PRETRAINED_WEIGHTS:\r\n init_model_weight(self.topdown_lateral_modules)\r\n init_model_weight(self.bottomup_top)\r\n else:\r\n init_model_weight(self)\r\n\r\n def forward(self, x):\r\n _, _, h, w = x.shape\r\n backbone_stage_size = [(math.ceil(h/(2.0**i)), math.ceil(w/(2.0**i))) for i in range(5, 0, -1)]\r\n backbone_stage_size.append((h, w))\r\n bottemup_blocks_out = [self.bottomup.res1(x)]\r\n for i in range(1, self.bottomup.convX):\r\n bottemup_blocks_out.append(\r\n getattr(self.bottomup, 'res%d' % (i + 1))(bottemup_blocks_out[-1])\r\n )\r\n bottemup_top_out = self.bottomup_top(bottemup_blocks_out[-1])\r\n lateral_blocks_out = [bottemup_top_out]\r\n for i in range(self.num_lateral_stages):\r\n lateral_blocks_out.append(self.topdown_lateral_modules[i](\r\n bottemup_blocks_out[-(i + 1)]\r\n ))\r\n return lateral_blocks_out, backbone_stage_size\r\n\r\n\r\nclass ASPP_block(nn.Module):\r\n def __init__(self, dim_in, dim_out, dilate_rates, stride):\r\n super().__init__()\r\n self.dim_in = dim_in\r\n self.dim_out = dim_out\r\n self.dilate_rates = dilate_rates\r\n self.aspp_conv1x1 = nn.Conv2d(self.dim_in, self.dim_out, 1, stride=1, padding=0, bias=False)\r\n self.aspp_conv3_1 = nn.Conv2d(self.dim_in, self.dim_out, 3, stride=1, padding=self.dilate_rates[0],\r\n dilation=self.dilate_rates[0], bias=False)\r\n self.aspp_conv3_2 = nn.Conv2d(self.dim_in, self.dim_out, 3, stride=1, padding=self.dilate_rates[1],\r\n dilation=self.dilate_rates[1], bias=False)\r\n self.aspp_conv3_3 = nn.Conv2d(self.dim_in, self.dim_out, 3, stride=1, padding=self.dilate_rates[2],\r\n dilation=self.dilate_rates[2], bias=False)\r\n self.aspp_bn1x1 = nn.BatchNorm2d(self.dim_out, momentum=0.5)\r\n self.aspp_bn3_1 = nn.BatchNorm2d(self.dim_out, momentum=0.5)\r\n self.aspp_bn3_2 = nn.BatchNorm2d(self.dim_out, momentum=0.5)\r\n self.aspp_bn3_3 = nn.BatchNorm2d(self.dim_out, momentum=0.5)\r\n\r\n self.globalpool = nn.AdaptiveAvgPool2d((1, 1))\r\n self.globalpool_conv1x1 = nn.Conv2d(self.dim_in, self.dim_out, 1, stride=1, padding=0, bias=False)\r\n self.globalpool_bn = nn.BatchNorm2d(self.dim_out, momentum=0.5)\r\n\r\n def forward(self, x):\r\n x1 = self.aspp_conv1x1(x)\r\n x1 = self.aspp_bn1x1(x1)\r\n x2 = self.aspp_conv3_1(x)\r\n x2 = self.aspp_bn3_1(x2)\r\n x3 = self.aspp_conv3_2(x)\r\n x3 = self.aspp_bn3_2(x3)\r\n x4 = self.aspp_conv3_3(x)\r\n x4 = self.aspp_bn3_3(x4)\r\n\r\n x5 = self.globalpool(x)\r\n x5 = self.globalpool_conv1x1(x5)\r\n x5 = self.globalpool_bn(x5)\r\n w, h = x1.size(2), x1.size(3)\r\n x5 = F.interpolate(input=x5, size=(w, h), mode='bilinear', align_corners=True)\r\n\r\n out = torch.cat([x1, x2, x3, x4, x5], 1)\r\n return out\r\n\r\nclass Global_pool_block(nn.Module):\r\n def __init__(self, dim_in, dim_out):\r\n super().__init__()\r\n self.dim_in = dim_in\r\n self.dim_out = dim_out\r\n self.globalpool_conv1x1 = nn.Conv2d(self.dim_in, self.dim_out, 1, stride=1, padding=0, bias=False)\r\n self.globalpool = nn.AdaptiveAvgPool2d((1, 1))\r\n self.globalpool_bn = nn.BatchNorm2d(self.dim_out, momentum=0.9)\r\n\r\n def forward(self, x):\r\n out = self.globalpool_conv1x1(x)\r\n out = self.globalpool_bn(out)\r\n w, h = x.size(2), x.size(3)\r\n out = self.globalpool(out)\r\n out = F.interpolate(input=out, size=(w, h), mode='bilinear', align_corners=True)\r\n return out\r\n\r\nclass lateral_block(nn.Module):\r\n def __init__(self, dim_in, dim_out):\r\n super().__init__()\r\n self.dim_in = dim_in\r\n self.dim_out = dim_out\r\n self.lateral = FTB_block(dim_in, dim_out)\r\n\r\n def forward(self, x):\r\n out = self.lateral(x)\r\n return out\r\n\r\n\r\nclass fcn_topdown(nn.Module):\r\n def __init__(self):\r\n super().__init__()\r\n\r\n self.dim_in = cfg.MODEL.FCN_DIM_IN\r\n self.dim_out = cfg.MODEL.FCN_DIM_OUT + [cfg.MODEL.DECODER_OUTPUT_C]\r\n\r\n self.num_fcn_topdown = len(self.dim_in)\r\n self.top_conv_num = 5 if 'resnext' in cfg.MODEL.ENCODER.lower() else 1\r\n self.top = nn.Sequential(\r\n nn.Conv2d(self.dim_in[0] * self.top_conv_num, self.dim_in[0], 1, stride=1, padding=0, bias=False),\r\n nn.BatchNorm2d(self.dim_in[0], 0.5)\r\n )\r\n self.topdown_fcn1 = fcn_topdown_block(self.dim_in[0], self.dim_out[0])\r\n self.topdown_fcn2 = fcn_topdown_block(self.dim_in[1], self.dim_out[1])\r\n self.topdown_fcn3 = fcn_topdown_block(self.dim_in[2], self.dim_out[2])\r\n self.topdown_fcn4 = fcn_topdown_block(self.dim_in[3], self.dim_out[3])\r\n self.topdown_fcn5 = fcn_last_block(self.dim_in[4], self.dim_out[4])\r\n self.topdown_predict = fcn_topdown_predict(self.dim_in[5], self.dim_out[5])\r\n\r\n self.init_type = cfg.MODEL.INIT_TYPE\r\n self._init_modules(self.init_type)\r\n\r\n def _init_modules(self, init_type):\r\n self._init_weights(init_type)\r\n\r\n def _init_weights(self, init_type='xavier'):\r\n def init_func(m):\r\n if isinstance(m, nn.Conv2d):\r\n if init_type == 'xavier':\r\n nn.init.xavier_normal_(m.weight)\r\n if init_type == 'kaiming':\r\n nn.init.kaiming_normal(m.weight)\r\n if init_type == 'gaussian':\r\n nn.init.normal_(m.weight, std=0.01)\r\n if m.bias is not None:\r\n nn.init.constant_(m.bias, 0.0)\r\n elif isinstance(m, nn.BatchNorm2d):\r\n nn.init.normal_(m.weight.data, 1.0, 1e-3)\r\n nn.init.constant_(m.bias.data, 0.0)\r\n\r\n for child_m in self.children():\r\n child_m.apply(init_func)\r\n\r\n def forward(self, laterals, backbone_stage_size):\r\n x = self.top(laterals[0])\r\n x1 = self.topdown_fcn1(laterals[1], x)\r\n x2 = self.topdown_fcn2(laterals[2], x1)\r\n x3 = self.topdown_fcn3(laterals[3], x2)\r\n x4 = self.topdown_fcn4(laterals[4], x3)\r\n x5 = self.topdown_fcn5(x4, backbone_stage_size)\r\n x6 = self.topdown_predict(x5)\r\n return x6\r\n\r\n\r\nclass fcn_topdown_block(nn.Module):\r\n def __init__(self, dim_in, dim_out):\r\n super().__init__()\r\n self.dim_in = dim_in\r\n self.dim_out = dim_out\r\n self.afa_block = AFA_block(dim_in)\r\n self.ftb_block = FTB_block(self.dim_in, self.dim_out)\r\n\r\n def forward(self, lateral, top, size=None):\r\n if lateral.shape != top.shape:\r\n h, w = lateral.size(2), lateral.size(3)\r\n top = F.interpolate(input=top, size=(h, w), mode='bilinear',align_corners=True)\r\n out = self.afa_block(lateral, top)\r\n out = self.ftb_block(out)\r\n return out\r\n\r\n\r\nclass fcn_topdown_predict(nn.Module):\r\n def __init__(self, dim_in, dim_out):\r\n super().__init__()\r\n self.dim_in = dim_in\r\n self.dim_out = dim_out\r\n self.dropout = nn.Dropout2d(0.0)\r\n self.conv1 = nn.Conv2d(self.dim_in, self.dim_out, 3, stride=1, padding=2, dilation=2, bias=True)\r\n self.softmax = nn.Softmax(dim=1)\r\n\r\n def forward(self, x):\r\n x = self.dropout(x)\r\n x = self.conv1(x)\r\n x_softmax = self.softmax(x)\r\n return x, x_softmax\r\n\r\n\r\nclass FTB_block(nn.Module):\r\n def __init__(self, dim_in, dim_out):\r\n super().__init__()\r\n self.dim_in = dim_in\r\n self.dim_out = dim_out\r\n self.conv1 = nn.Conv2d(self.dim_in, self.dim_out, 1, stride=1, padding=0, bias=False)\r\n self.conv2 = nn.Conv2d(self.dim_out, self.dim_out, 3, stride=1, padding=2, dilation=2, bias=True)\r\n self.bn1 = nn.BatchNorm2d(self.dim_out, momentum=0.5)\r\n self.relu = nn.ReLU(inplace=True)\r\n self.conv3 = nn.Conv2d(self.dim_out, self.dim_out, 3, stride=1, padding=2, dilation=2, bias=False)\r\n\r\n def forward(self, x):\r\n x = self.conv1(x)\r\n residual = x\r\n out = self.conv2(x)\r\n out = self.bn1(out)\r\n out = self.relu(out)\r\n out = self.conv3(out)\r\n out += residual\r\n out = self.relu(out)\r\n return out\r\n\r\n\r\nclass AFA_block(nn.Module):\r\n def __init__(self, dim):\r\n super().__init__()\r\n self.dim_in = dim * 2\r\n self.dim_out = dim\r\n self.dim_mid = int(dim / 8)\r\n self.globalpool = nn.AdaptiveAvgPool2d(1)\r\n self.conv1 = nn.Conv2d(self.dim_in, self.dim_mid, 1, stride=1, padding=0, bias=False)\r\n self.relu = nn.ReLU(inplace=True)\r\n self.conv2 = nn.Conv2d(self.dim_mid, self.dim_out, 1, stride=1, padding=0, bias=False)\r\n self.sigmd = nn.Sigmoid()\r\n\r\n def forward(self, lateral, top):\r\n w = torch.cat([lateral, top], 1)\r\n w = self.globalpool(w)\r\n w = self.conv1(w)\r\n w = self.relu(w)\r\n w = self.conv2(w)\r\n w = self.sigmd(w)\r\n out = w * lateral + top\r\n return out\r\n\r\n\r\nclass fcn_last_block(nn.Module):\r\n def __init__(self, dim_in, dim_out):\r\n super().__init__()\r\n self.dim_in = dim_in\r\n self.dim_out = dim_out\r\n self.ftb = FTB_block(dim_in, dim_out)\r\n\r\n def forward(self, input, backbone_stage_size):\r\n out = F.interpolate(input=input, size=(backbone_stage_size[4][0], backbone_stage_size[4][1]), mode='bilinear', align_corners=True)\r\n out = self.ftb(out)\r\n out = F.interpolate(input=out, size=(backbone_stage_size[5][0], backbone_stage_size[5][1]), mode='bilinear', align_corners=True)\r\n return out\r\n"
] | [
[
"torch.nn.init.kaiming_normal",
"torch.nn.Softmax",
"torch.nn.Dropout2d",
"torch.cat",
"torch.nn.init.constant_",
"torch.nn.ModuleList",
"torch.nn.Conv2d",
"torch.nn.init.xavier_normal_",
"torch.nn.Sigmoid",
"torch.nn.AdaptiveAvgPool2d",
"torch.nn.init.normal_",
"torch.nn.functional.interpolate",
"torch.nn.BatchNorm2d",
"torch.nn.ReLU",
"torch.nn.init.kaiming_normal_"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
EdisonLeeeee/SGAttack | [
"406a836e85294e5588503cf0a6495a82d58ada77"
] | [
"src/ego_graph.py"
] | [
"import numpy as np\r\n\r\nfrom numba import njit\r\nfrom numba import types\r\nfrom numba.typed import Dict\r\n\r\nfrom typing import Union, Tuple\r\n\r\n\r\n\r\n@njit\r\ndef extra_edges(indices, indptr,\r\n last_level, seen,\r\n hops: int):\r\n edges = []\r\n mapping = Dict.empty(\r\n key_type=types.int64,\r\n value_type=types.int64,\r\n )\r\n for u in last_level:\r\n nbrs = indices[indptr[u]:indptr[u + 1]]\r\n nbrs = nbrs[seen[nbrs] == hops]\r\n mapping[u] = 1\r\n for v in nbrs:\r\n if not v in mapping:\r\n edges.append((u, v))\r\n return edges\r\n\r\n\r\ndef ego_graph(adj_matrix, targets, hops: int = 1):\r\n \"\"\"Returns induced subgraph of neighbors centered at node n within\r\n a given radius.\r\n\r\n Parameters\r\n ----------\r\n adj_matrix : A Scipy sparse adjacency matrix\r\n representing a graph\r\n\r\n targets : Center nodes\r\n A single node or a list of nodes\r\n\r\n hops : number, optional\r\n Include all neighbors of distance<=hops from nodes.\r\n\r\n Returns\r\n -------\r\n (edges, nodes):\r\n edges: shape [2, M], the edges of the subgraph\r\n nodes: shape [N], the nodes of the subgraph\r\n\r\n Notes\r\n -----\r\n This is a faster implementation of \r\n `networkx.ego_graph`\r\n\r\n\r\n See Also\r\n --------\r\n networkx.ego_graph\r\n\r\n \"\"\"\r\n\r\n if np.ndim(targets) == 0:\r\n targets = [targets]\r\n\r\n indices = adj_matrix.indices\r\n indptr = adj_matrix.indptr\r\n\r\n edges = {}\r\n start = 0\r\n N = adj_matrix.shape[0]\r\n seen = np.zeros(N) - 1\r\n seen[targets] = 0\r\n for level in range(hops):\r\n end = len(targets)\r\n while start < end:\r\n head = targets[start]\r\n nbrs = indices[indptr[head]:indptr[head + 1]]\r\n for u in nbrs:\r\n if seen[u] < 0:\r\n targets.append(u)\r\n seen[u] = level + 1\r\n if (u, head) not in edges:\r\n edges[(head, u)] = level + 1\r\n\r\n start += 1\r\n\r\n if len(targets[start:]):\r\n e = extra_edges(indices, indptr, np.array(targets[start:]), seen, hops)\r\n else:\r\n e = []\r\n\r\n return np.asarray(list(edges.keys()) + e), np.asarray(targets)\r\n"
] | [
[
"numpy.ndim",
"numpy.array",
"numpy.zeros",
"numpy.asarray"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
JoOkuma/DifferentiableSketching | [
"6672508bd362d90e9bfc07966cb7907879d01385"
] | [
"dsketch/models/decoders.py"
] | [
"from numbers import Number\n\nimport torch\nimport torch.nn as nn\n\nfrom dsketch.raster.composite import softor\nfrom dsketch.raster.disttrans import line_edt2\nfrom dsketch.raster.raster import exp\n\n\nclass _RasteriserBase(nn.Module):\n def __init__(self, sz):\n super(_RasteriserBase, self).__init__()\n\n # build the coordinate grid:\n if isinstance(sz, Number.number):\n sz = (sz, sz)\n\n r = torch.linspace(-1, 1, sz[0])\n c = torch.linspace(-1, 1, sz[1])\n grid = torch.meshgrid(r, c)\n grid = torch.stack(grid, dim=2)\n self.register_buffer(\"grid\", grid)\n\n\nclass SimplePrimitiveRenderer(_RasteriserBase):\n \"\"\"\n Simple Primitive decoder for a fixed number of primatives/image and a single scalar rasterisation sigma.\n\n Args:\n raster: rasterisation function\n comp: composition function\n sz: image size (integer or tuple of two integers)\n \"\"\"\n def __init__(self, edt2=line_edt2, raster=exp, comp=softor, sz=256):\n super(SimplePrimitiveRenderer, self).__init__(sz)\n\n self.edt2 = edt2\n self.raster = raster\n self.comp = comp\n\n def forward(self, params, sigma):\n bs = params.shape[0]\n params = params.view(bs, -1, self.edt2.param_dim, 2) # -> [batch, n_prims, param_dim, 2]\n\n rasters = self.raster(self.edt2(params, self.grid), sigma) # -> [batch, n_prims, sz, sz]\n\n return self.comp(rasters).unsqueeze(1) # -> [batch, 1, sz, sz]\n\n\nclass SimpleConfigurablePrimitiveRenderer(_RasteriserBase):\n \"\"\"\n Simple Primitive decoder for a fixed number of primatives/image and a single scalar rasterisation sigma.\n\n Args:\n raster: rasterisation function\n comp: composition function\n sz: image size (integer or tuple of two integers)\n \"\"\"\n def __init__(self, edt2=line_edt2, raster=exp, comp=softor, sz=256):\n super(SimpleConfigurablePrimitiveRenderer, self).__init__(sz)\n\n self.edt2 = edt2\n self.raster = raster\n self.comp = comp\n\n def forward(self, shape_params, colour_params, thickness_params, sigma):\n bs = shape_params.shape[0]\n params = shape_params.view(bs, -1, self.edt2.param_dim, 2) # -> [batch, n_prims, param_dim, 2]\n\n rasters = self.raster(self.edt2(params, self.grid), sigma) # -> [batch, n_prims, sz, sz]\n\n return self.comp(rasters).unsqueeze(1) # -> [batch, 1, sz, sz]\n"
] | [
[
"torch.stack",
"torch.linspace",
"torch.meshgrid"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
estshorter/robotics | [
"38db0e3097b547a94e5a604e1a23b3bd7228f00b"
] | [
"rrt_star.py"
] | [
"import math\r\n\r\nimport matplotlib.pyplot as plt\r\n\r\nfrom rrt import RRT\r\n\r\nshow_animation = True\r\n\r\n\"\"\"\r\nPath planning Sample Code with Randomized Rapidly-Exploring Random Trees (RRT)\r\nauthor: AtsushiSakai(@Atsushi_twi)\r\n\r\nThe MIT License (MIT)\r\n\r\nCopyright (c) 2016 - 2021 Atsushi Sakai\r\n\r\nPermission is hereby granted, free of charge, to any person obtaining a copy\r\nof this software and associated documentation files (the \"Software\"), to deal\r\nin the Software without restriction, including without limitation the rights\r\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\ncopies of the Software, and to permit persons to whom the Software is\r\nfurnished to do so, subject to the following conditions:\r\n\r\nThe above copyright notice and this permission notice shall be included in all\r\ncopies or substantial portions of the Software.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\nSOFTWARE.\r\n\"\"\"\r\n\r\n\r\nclass RRTStar(RRT):\r\n class Node(RRT.Node):\r\n def __init__(self, x, y) -> None:\r\n super().__init__(x, y)\r\n self.cost = 0.0\r\n\r\n def __init__(\r\n self,\r\n start,\r\n goal,\r\n obstacle_list,\r\n rand_area,\r\n expand_dis=30.0,\r\n path_resolution=1.0,\r\n goal_sample_rate=20,\r\n max_iter=300,\r\n connect_circle_dist=50.0,\r\n search_until_max_iter=True,\r\n ):\r\n \"\"\"\r\n Setting Parameter\r\n start:Start Position [x,y]\r\n goal:Goal Position [x,y]\r\n obstacleList:obstacle Positions [[x,y,size],...]\r\n randArea:Random Sampling Area [min,max]\r\n \"\"\"\r\n super().__init__(\r\n start,\r\n goal,\r\n obstacle_list,\r\n rand_area,\r\n expand_dis,\r\n path_resolution,\r\n goal_sample_rate,\r\n max_iter,\r\n )\r\n self.connect_circle_dist = connect_circle_dist\r\n self.goal_node = self.Node(goal[0], goal[1])\r\n self.search_until_max_iter = search_until_max_iter\r\n\r\n def planning(self, animation=True):\r\n self.node_list = [self.start]\r\n for i in range(self.max_iter):\r\n print(\"Iter:\", i, \", number of nodes:\", len(self.node_list))\r\n rnd_node = self.get_random_node()\r\n nearest_ind = self.get_nearest_node_index(self.node_list, rnd_node)\r\n nearest_node = self.node_list[nearest_ind]\r\n\r\n new_node = self.steer(nearest_node, rnd_node, self.expand_dis)\r\n new_node.cost = nearest_node.cost + math.hypot(\r\n new_node.x - nearest_node.x + new_node.y - nearest_node.y\r\n )\r\n\r\n if not self.collide_with_obstacles(new_node, self.obstacle_list):\r\n near_inds = self.find_near_nodes(new_node)\r\n node_with_updated_parent = self.choose_parent(new_node, near_inds)\r\n if node_with_updated_parent:\r\n self.rewire(node_with_updated_parent, near_inds)\r\n self.node_list.append(node_with_updated_parent)\r\n else:\r\n self.node_list.append(new_node)\r\n if animation:\r\n self.draw_graph(rnd_node, i)\r\n\r\n if (not self.search_until_max_iter) and new_node:\r\n last_index = self.search_best_goal_node()\r\n if last_index is not None:\r\n return self.generate_final_course(last_index), i\r\n print(\"reached max iteration\")\r\n\r\n last_index = self.search_best_goal_node()\r\n if last_index is not None:\r\n return self.generate_final_course(last_index), self.max_iter - 1\r\n return None, None\r\n\r\n def choose_parent(self, new_node, near_inds):\r\n if not near_inds:\r\n return None\r\n\r\n costs = []\r\n for near_ind in near_inds:\r\n near_node = self.node_list[near_ind]\r\n t_node = self.steer(near_node, new_node)\r\n if t_node and not self.collide_with_obstacles(t_node, self.obstacle_list):\r\n costs.append(self.calc_new_cost(near_node, new_node))\r\n else:\r\n costs.append(float(\"inf\"))\r\n min_cost = min(costs)\r\n\r\n if min_cost == float(\"inf\"):\r\n print(\"There is no good path.(min_cost is inf)\")\r\n return None\r\n\r\n min_ind = near_inds[costs.index(min_cost)]\r\n new_node = self.steer(self.node_list[min_ind], new_node)\r\n new_node.cost = min_cost\r\n return new_node\r\n\r\n def search_best_goal_node(self):\r\n dist_to_goal_list = [self.calc_dist_to_goal(n.x, n.y) for n in self.node_list]\r\n # ゴールに近いノードのインデックス\r\n goal_inds = [\r\n dist_to_goal_list.index(dist_to_goal)\r\n for dist_to_goal in dist_to_goal_list\r\n if dist_to_goal <= self.expand_dis\r\n ]\r\n\r\n safe_goal_inds = []\r\n for goal_ind in goal_inds:\r\n t_node = self.steer(self.node_list[goal_ind], self.goal_node)\r\n if not self.collide_with_obstacles(t_node, self.obstacle_list):\r\n safe_goal_inds.append(goal_ind)\r\n\r\n if not safe_goal_inds:\r\n return None\r\n\r\n min_cost = min(\r\n [self.node_list[safe_goal_ind].cost for safe_goal_ind in safe_goal_inds]\r\n )\r\n for safe_goal_ind in safe_goal_inds:\r\n if self.node_list[safe_goal_ind].cost == min_cost:\r\n return safe_goal_ind\r\n\r\n return None\r\n\r\n def find_near_nodes(self, new_node):\r\n num_node = len(self.node_list) + 1\r\n r = self.connect_circle_dist * math.sqrt((math.log(num_node) / num_node))\r\n if hasattr(self, \"expand_dis\"):\r\n r = min(r, self.expand_dis)\r\n dist_list = [\r\n (node.x - new_node.x) ** 2 + (node.y - new_node.y) ** 2\r\n for node in self.node_list\r\n ]\r\n r_sqr = r ** 2\r\n near_inds = [dist_list.index(dist) for dist in dist_list if dist <= r_sqr]\r\n return near_inds\r\n\r\n def rewire(self, new_node, near_inds):\r\n for near_ind in near_inds:\r\n near_node = self.node_list[near_ind]\r\n edge_node = self.steer(new_node, near_node)\r\n if not edge_node:\r\n continue\r\n edge_node.cost = self.calc_new_cost(new_node, near_node)\r\n\r\n no_collision = not self.collide_with_obstacles(\r\n edge_node, self.obstacle_list\r\n )\r\n improved_cost = near_node.cost > edge_node.cost\r\n\r\n if no_collision and improved_cost:\r\n near_node.x = edge_node.x\r\n near_node.y = edge_node.y\r\n near_node.cost = edge_node.cost\r\n near_node.path_x = edge_node.path_x\r\n near_node.path_y = edge_node.path_y\r\n near_node.parent = edge_node.parent\r\n self.propagate_cost_to_leaves(new_node)\r\n\r\n def calc_new_cost(self, from_node, to_node):\r\n d, _ = self.calc_distance_and_angle(from_node, to_node)\r\n return from_node.cost + d\r\n\r\n def propagate_cost_to_leaves(self, parent_node):\r\n for node in self.node_list:\r\n if node.parent == parent_node:\r\n node.cost = self.calc_new_cost(parent_node, node)\r\n self.propagate_cost_to_leaves(node)\r\n\r\n\r\ndef main(gx=6.0, gy=10.0):\r\n print(\"start \" + __file__)\r\n\r\n # ====Search Path with RRT====\r\n obstacle_list = [\r\n (5, 5, 1),\r\n (3, 6, 2),\r\n (3, 8, 2),\r\n (3, 10, 2),\r\n (7, 5, 2),\r\n (9, 5, 2),\r\n (8, 10, 1),\r\n (6, 12, 1),\r\n ] # [x, y, radius]\r\n # Set Initial parameters\r\n max_iter = 10000\r\n rrt_star = RRTStar(\r\n start=[0, 0],\r\n goal=[6, 10],\r\n rand_area=[-2, 15],\r\n obstacle_list=obstacle_list,\r\n expand_dis=1,\r\n max_iter=max_iter,\r\n )\r\n path, num_iter = rrt_star.planning(animation=False)\r\n\r\n if path is None:\r\n print(\"cannnot find path\")\r\n else:\r\n print(\"path found\")\r\n\r\n if show_animation:\r\n rrt_star.draw_graph(num_iter=num_iter)\r\n plt.plot([x for (x, _) in path], [y for (_, y) in path], \"-r\")\r\n plt.pause(0.1)\r\n plt.xlim([-2, 15])\r\n plt.ylim([-2, 15])\r\n plt.savefig(\"rrt-star.png\", bbox_inches=\"tight\", dpi=200)\r\n plt.show()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n"
] | [
[
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.show",
"matplotlib.pyplot.pause"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
flaviodsr/examples | [
"7d7c2c448e49d89289a7821061aa99ba5a3126e5"
] | [
"codesets/mlflow/onnx/train.py"
] | [
"# The data set used in this example is from http://archive.ics.uci.edu/ml/datasets/Wine+Quality\n# P. Cortez, A. Cerdeira, F. Almeida, T. Matos and J. Reis.\n# Modeling wine preferences by data mining from physicochemical properties. In Decision Support Systems, Elsevier, 47(4):547-553, 2009.\n\nimport os\nimport warnings\nimport sys\n\nimport pandas as pd\nimport numpy as np\nfrom sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import ElasticNet\nfrom skl2onnx import to_onnx\nfrom skl2onnx.common.data_types import FloatTensorType\n\nimport mlflow\nimport mlflow.sklearn\n\n\ndef eval_metrics(actual, pred):\n rmse = np.sqrt(mean_squared_error(actual, pred))\n mae = mean_absolute_error(actual, pred)\n r2 = r2_score(actual, pred)\n return rmse, mae, r2\n\n\n\nif __name__ == \"__main__\":\n warnings.filterwarnings(\"ignore\")\n np.random.seed(40)\n\n # Read the wine-quality csv file (make sure you're running this from the root of MLflow!)\n wine_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), \"wine-quality.csv\")\n data = pd.read_csv(wine_path)\n\n # Split the data into training and test sets. (0.75, 0.25) split.\n train, test = train_test_split(data)\n\n # The predicted column is \"quality\" which is a scalar from [3, 9]\n train_x = train.drop([\"quality\"], axis=1)\n test_x = test.drop([\"quality\"], axis=1)\n train_y = train[[\"quality\"]]\n test_y = test[[\"quality\"]]\n\n alpha = float(sys.argv[1]) if len(sys.argv) > 1 else 0.5\n l1_ratio = float(sys.argv[2]) if len(sys.argv) > 2 else 0.5\n\n with mlflow.start_run():\n lr = ElasticNet(alpha=alpha, l1_ratio=l1_ratio, random_state=42)\n lr.fit(train_x, train_y)\n\n predicted_qualities = lr.predict(test_x)\n\n (rmse, mae, r2) = eval_metrics(test_y, predicted_qualities)\n\n print(\"Elasticnet model (alpha=%f, l1_ratio=%f):\" % (alpha, l1_ratio))\n print(\" RMSE: %s\" % rmse)\n print(\" MAE: %s\" % mae)\n print(\" R2: %s\" % r2)\n\n mlflow.log_param(\"alpha\", alpha)\n mlflow.log_param(\"l1_ratio\", l1_ratio)\n mlflow.log_metric(\"rmse\", rmse)\n mlflow.log_metric(\"r2\", r2)\n mlflow.log_metric(\"mae\", mae)\n\n initial_type = [ ('input-0', FloatTensorType([None, 11])) ]\n onnx_model = to_onnx(lr, target_opset=14, initial_types=initial_type)\n\n mlflow.onnx.log_model(onnx_model, \"model\")\n"
] | [
[
"pandas.read_csv",
"sklearn.metrics.r2_score",
"numpy.random.seed",
"sklearn.linear_model.ElasticNet",
"sklearn.metrics.mean_absolute_error",
"sklearn.model_selection.train_test_split",
"sklearn.metrics.mean_squared_error"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
raphaelvallat/yasa | [
"4d23501a77e16d878779250706f16df4f5eb6296"
] | [
"yasa/spectral.py"
] | [
"\"\"\"\nThis file contains several helper functions to calculate spectral power from\n1D and 2D EEG data.\n\"\"\"\nimport mne\nimport logging\nimport numpy as np\nimport pandas as pd\nfrom scipy import signal\nfrom scipy.integrate import simps\nfrom scipy.interpolate import RectBivariateSpline\n\nlogger = logging.getLogger('yasa')\n\n__all__ = ['bandpower', 'bandpower_from_psd', 'bandpower_from_psd_ndarray',\n 'irasa', 'stft_power']\n\n\ndef bandpower(data, sf=None, ch_names=None, hypno=None, include=(2, 3),\n win_sec=4, relative=True, bandpass=False,\n bands=[(0.5, 4, 'Delta'), (4, 8, 'Theta'), (8, 12, 'Alpha'),\n (12, 16, 'Sigma'), (16, 30, 'Beta'), (30, 40, 'Gamma')],\n kwargs_welch=dict(average='median', window='hamming')):\n \"\"\"\n Calculate the Welch bandpower for each channel and, if specified,\n for each sleep stage.\n\n .. versionadded:: 0.1.6\n\n Parameters\n ----------\n data : np.array_like or :py:class:`mne.io.BaseRaw`\n 1D or 2D EEG data. Can also be a :py:class:`mne.io.BaseRaw`, in which\n case ``data``, ``sf``, and ``ch_names`` will be automatically\n extracted, and ``data`` will also be converted from Volts (MNE default)\n to micro-Volts (YASA).\n sf : float\n The sampling frequency of data AND the hypnogram.\n Can be omitted if ``data`` is a :py:class:`mne.io.BaseRaw`.\n ch_names : list\n List of channel names, e.g. ['Cz', 'F3', 'F4', ...]. If None,\n channels will be labelled ['CHAN000', 'CHAN001', ...].\n Can be omitted if ``data`` is a :py:class:`mne.io.BaseRaw`.\n hypno : array_like\n Sleep stage (hypnogram). If the hypnogram is loaded, the\n bandpower will be extracted for each sleep stage defined in\n ``include``.\n\n The hypnogram must have the exact same number of samples as ``data``.\n To upsample your hypnogram, please refer to\n :py:func:`yasa.hypno_upsample_to_data`.\n\n .. note::\n The default hypnogram format in YASA is a 1D integer\n vector where:\n\n - -2 = Unscored\n - -1 = Artefact / Movement\n - 0 = Wake\n - 1 = N1 sleep\n - 2 = N2 sleep\n - 3 = N3 sleep\n - 4 = REM sleep\n include : tuple, list or int\n Values in ``hypno`` that will be included in the mask. The default is\n (2, 3), meaning that the bandpower are sequentially calculated\n for N2 and N3 sleep. This has no effect when ``hypno`` is None.\n win_sec : int or float\n The length of the sliding window, in seconds, used for the Welch PSD\n calculation. Ideally, this should be at least two times the inverse of\n the lower frequency of interest (e.g. for a lower frequency of interest\n of 0.5 Hz, the window length should be at least 2 * 1 / 0.5 =\n 4 seconds).\n relative : boolean\n If True, bandpower is divided by the total power between the min and\n max frequencies defined in ``band``.\n bandpass : boolean\n If True, apply a standard FIR bandpass filter using the minimum and\n maximum frequencies in ``bands``. Fore more details, refer to\n :py:func:`mne.filter.filter_data`.\n bands : list of tuples\n List of frequency bands of interests. Each tuple must contain the\n lower and upper frequencies, as well as the band name\n (e.g. (0.5, 4, 'Delta')).\n kwargs_welch : dict\n Optional keywords arguments that are passed to the\n :py:func:`scipy.signal.welch` function.\n\n Returns\n -------\n bandpowers : :py:class:`pandas.DataFrame`\n Bandpower dataframe, in which each row is a channel and each column\n a spectral band.\n\n Notes\n -----\n For an example of how to use this function, please refer to\n https://github.com/raphaelvallat/yasa/blob/master/notebooks/08_bandpower.ipynb\n \"\"\"\n # Type checks\n assert isinstance(bands, list), 'bands must be a list of tuple(s)'\n assert isinstance(relative, bool), 'relative must be a boolean'\n assert isinstance(bandpass, bool), 'bandpass must be a boolean'\n\n # Check if input data is a MNE Raw object\n if isinstance(data, mne.io.BaseRaw):\n sf = data.info['sfreq'] # Extract sampling frequency\n ch_names = data.ch_names # Extract channel names\n data = data.get_data() * 1e6 # Convert from V to uV\n _, npts = data.shape\n else:\n # Safety checks\n assert isinstance(data, np.ndarray), 'Data must be a numpy array.'\n data = np.atleast_2d(data)\n assert data.ndim == 2, 'Data must be of shape (nchan, n_samples).'\n nchan, npts = data.shape\n # assert nchan < npts, 'Data must be of shape (nchan, n_samples).'\n assert sf is not None, 'sf must be specified if passing a numpy array.'\n assert isinstance(sf, (int, float))\n if ch_names is None:\n ch_names = ['CHAN' + str(i).zfill(3) for i in range(nchan)]\n else:\n ch_names = np.atleast_1d(np.asarray(ch_names, dtype=str))\n assert ch_names.ndim == 1, 'ch_names must be 1D.'\n assert len(ch_names) == nchan, 'ch_names must match data.shape[0].'\n\n if bandpass:\n # Apply FIR bandpass filter\n all_freqs = np.hstack([[b[0], b[1]] for b in bands])\n fmin, fmax = min(all_freqs), max(all_freqs)\n data = mne.filter.filter_data(data.astype('float64'), sf, fmin, fmax,\n verbose=0)\n\n win = int(win_sec * sf) # nperseg\n\n if hypno is None:\n # Calculate the PSD over the whole data\n freqs, psd = signal.welch(data, sf, nperseg=win, **kwargs_welch)\n return bandpower_from_psd(psd, freqs, ch_names, bands=bands,\n relative=relative).set_index('Chan')\n else:\n # Per each sleep stage defined in ``include``.\n hypno = np.asarray(hypno)\n assert include is not None, 'include cannot be None if hypno is given'\n include = np.atleast_1d(np.asarray(include))\n assert hypno.ndim == 1, 'Hypno must be a 1D array.'\n assert hypno.size == npts, 'Hypno must have same size as data.shape[1]'\n assert include.size >= 1, '`include` must have at least one element.'\n assert hypno.dtype.kind == include.dtype.kind, ('hypno and include '\n 'must have same dtype')\n assert np.in1d(hypno, include).any(), ('None of the stages '\n 'specified in `include` '\n 'are present in hypno.')\n # Initialize empty dataframe and loop over stages\n df_bp = pd.DataFrame([])\n for stage in include:\n if stage not in hypno:\n continue\n data_stage = data[:, hypno == stage]\n freqs, psd = signal.welch(data_stage, sf, nperseg=win,\n **kwargs_welch)\n bp_stage = bandpower_from_psd(psd, freqs, ch_names, bands=bands,\n relative=relative)\n bp_stage['Stage'] = stage\n df_bp = df_bp.append(bp_stage)\n return df_bp.set_index(['Stage', 'Chan'])\n\n\ndef bandpower_from_psd(psd, freqs, ch_names=None, bands=[(0.5, 4, 'Delta'),\n (4, 8, 'Theta'), (8, 12, 'Alpha'), (12, 16, 'Sigma'),\n (16, 30, 'Beta'), (30, 40, 'Gamma')], relative=True):\n \"\"\"Compute the average power of the EEG in specified frequency band(s)\n given a pre-computed PSD.\n\n .. versionadded:: 0.1.5\n\n Parameters\n ----------\n psd : array_like\n Power spectral density of data, in uV^2/Hz.\n Must be of shape (n_channels, n_freqs).\n See :py:func:`scipy.signal.welch` for more details.\n freqs : array_like\n Array of frequencies.\n ch_names : list\n List of channel names, e.g. ['Cz', 'F3', 'F4', ...]. If None,\n channels will be labelled ['CHAN000', 'CHAN001', ...].\n bands : list of tuples\n List of frequency bands of interests. Each tuple must contain the\n lower and upper frequencies, as well as the band name\n (e.g. (0.5, 4, 'Delta')).\n relative : boolean\n If True, bandpower is divided by the total power between the min and\n max frequencies defined in ``band`` (default 0.5 to 40 Hz).\n\n Returns\n -------\n bandpowers : :py:class:`pandas.DataFrame`\n Bandpower dataframe, in which each row is a channel and each column\n a spectral band.\n \"\"\"\n # Type checks\n assert isinstance(bands, list), 'bands must be a list of tuple(s)'\n assert isinstance(relative, bool), 'relative must be a boolean'\n\n # Safety checks\n freqs = np.asarray(freqs)\n assert freqs.ndim == 1\n psd = np.atleast_2d(psd)\n assert psd.ndim == 2, 'PSD must be of shape (n_channels, n_freqs).'\n all_freqs = np.hstack([[b[0], b[1]] for b in bands])\n fmin, fmax = min(all_freqs), max(all_freqs)\n idx_good_freq = np.logical_and(freqs >= fmin, freqs <= fmax)\n freqs = freqs[idx_good_freq]\n res = freqs[1] - freqs[0]\n nchan = psd.shape[0]\n assert nchan < psd.shape[1], 'PSD must be of shape (n_channels, n_freqs).'\n if ch_names is not None:\n ch_names = np.atleast_1d(np.asarray(ch_names, dtype=str))\n assert ch_names.ndim == 1, 'ch_names must be 1D.'\n assert len(ch_names) == nchan, 'ch_names must match psd.shape[0].'\n else:\n ch_names = ['CHAN' + str(i).zfill(3) for i in range(nchan)]\n bp = np.zeros((nchan, len(bands)), dtype=np.float)\n psd = psd[:, idx_good_freq]\n total_power = simps(psd, dx=res)\n total_power = total_power[..., np.newaxis]\n\n # Check if there are negative values in PSD\n if (psd < 0).any():\n msg = (\n \"There are negative values in PSD. This will result in incorrect \"\n \"bandpower values. We highly recommend working with an \"\n \"all-positive PSD. For more details, please refer to: \"\n \"https://github.com/raphaelvallat/yasa/issues/29\")\n logger.warning(msg)\n\n # Enumerate over the frequency bands\n labels = []\n for i, band in enumerate(bands):\n b0, b1, la = band\n labels.append(la)\n idx_band = np.logical_and(freqs >= b0, freqs <= b1)\n bp[:, i] = simps(psd[:, idx_band], dx=res)\n\n if relative:\n bp /= total_power\n\n # Convert to DataFrame\n bp = pd.DataFrame(bp, columns=labels)\n bp['TotalAbsPow'] = np.squeeze(total_power)\n bp['FreqRes'] = res\n # bp['WindowSec'] = 1 / res\n bp['Relative'] = relative\n bp['Chan'] = ch_names\n bp = bp.set_index('Chan').reset_index()\n # Add hidden attributes\n bp.bands_ = str(bands)\n return bp\n\n\ndef bandpower_from_psd_ndarray(psd, freqs, bands=[(0.5, 4, 'Delta'),\n (4, 8, 'Theta'), (8, 12, 'Alpha'),\n (12, 16, 'Sigma'), (16, 30, 'Beta'),\n (30, 40, 'Gamma')], relative=True):\n \"\"\"Compute bandpowers in N-dimensional PSD.\n\n This is a NumPy-only implementation of the\n :py:func:`yasa.bandpower_from_psd` function,\n which supports 1-D arrays of shape (n_freqs),\n or N-dimensional arays\n (e.g. 2-D (n_chan, n_freqs) or 3-D (n_chan, n_epochs, n_freqs))\n\n .. versionadded:: 0.2.0\n\n Parameters\n ----------\n psd : :py:class:`numpy.ndarray`\n Power spectral density of data, in uV^2/Hz.\n Must be a N-D array of shape (..., n_freqs).\n See :py:func:`scipy.signal.welch` for more details.\n freqs : :py:class:`numpy.ndarray`\n Array of frequencies. Must be a 1-D array of shape (n_freqs,)\n bands : list of tuples\n List of frequency bands of interests. Each tuple must contain the\n lower and upper frequencies, as well as the band name\n (e.g. (0.5, 4, 'Delta')).\n relative : boolean\n If True, bandpower is divided by the total power between the min and\n max frequencies defined in ``band`` (default 0.5 to 40 Hz).\n\n Returns\n -------\n bandpowers : :py:class:`numpy.ndarray`\n Bandpower array of shape *(n_bands, ...)*.\n \"\"\"\n # Type checks\n assert isinstance(bands, list), 'bands must be a list of tuple(s)'\n assert isinstance(relative, bool), 'relative must be a boolean'\n\n # Safety checks\n freqs = np.asarray(freqs)\n psd = np.asarray(psd)\n assert freqs.ndim == 1, 'freqs must be a 1-D array of shape (n_freqs,)'\n assert psd.shape[-1] == freqs.shape[-1], 'n_freqs must be last axis of psd'\n\n # Extract frequencies of interest\n all_freqs = np.hstack([[b[0], b[1]] for b in bands])\n fmin, fmax = min(all_freqs), max(all_freqs)\n idx_good_freq = np.logical_and(freqs >= fmin, freqs <= fmax)\n freqs = freqs[idx_good_freq]\n res = freqs[1] - freqs[0]\n\n # Trim PSD to frequencies of interest\n psd = psd[..., idx_good_freq]\n\n # Check if there are negative values in PSD\n if (psd < 0).any():\n msg = (\n \"There are negative values in PSD. This will result in incorrect \"\n \"bandpower values. We highly recommend working with an \"\n \"all-positive PSD. For more details, please refer to: \"\n \"https://github.com/raphaelvallat/yasa/issues/29\")\n logger.warning(msg)\n\n # Calculate total power\n total_power = simps(psd, dx=res, axis=-1)\n total_power = total_power[np.newaxis, ...]\n\n # Initialize empty array\n bp = np.zeros((len(bands), *psd.shape[:-1]), dtype=np.float)\n\n # Enumerate over the frequency bands\n labels = []\n for i, band in enumerate(bands):\n b0, b1, la = band\n labels.append(la)\n idx_band = np.logical_and(freqs >= b0, freqs <= b1)\n bp[i] = simps(psd[..., idx_band], dx=res, axis=-1)\n\n if relative:\n bp /= total_power\n return bp\n\n\ndef irasa(data, sf=None, ch_names=None, band=(1, 30),\n hset=[1.1, 1.15, 1.2, 1.25, 1.3, 1.35, 1.4, 1.45, 1.5, 1.55, 1.6,\n 1.65, 1.7, 1.75, 1.8, 1.85, 1.9], return_fit=True, win_sec=4,\n kwargs_welch=dict(average='median', window='hamming')):\n r\"\"\"\n Separate the aperiodic (= fractal, or 1/f) and oscillatory component\n of the power spectra of EEG data using the IRASA method.\n\n .. versionadded:: 0.1.7\n\n Parameters\n ----------\n data : :py:class:`numpy.ndarray` or :py:class:`mne.io.BaseRaw`\n 1D or 2D EEG data. Can also be a :py:class:`mne.io.BaseRaw`, in which\n case ``data``, ``sf``, and ``ch_names`` will be automatically\n extracted, and ``data`` will also be converted from Volts (MNE default)\n to micro-Volts (YASA).\n sf : float\n The sampling frequency of data AND the hypnogram.\n Can be omitted if ``data`` is a :py:class:`mne.io.BaseRaw`.\n ch_names : list\n List of channel names, e.g. ['Cz', 'F3', 'F4', ...]. If None,\n channels will be labelled ['CHAN000', 'CHAN001', ...].\n Can be omitted if ``data`` is a :py:class:`mne.io.BaseRaw`.\n band : tuple or None\n Broad band frequency range.\n Default is 1 to 30 Hz.\n hset : list or :py:class:`numpy.ndarray`\n Resampling factors used in IRASA calculation. Default is to use a range\n of values from 1.1 to 1.9 with an increment of 0.05.\n return_fit : boolean\n If True (default), fit an exponential function to the aperiodic PSD\n and return the fit parameters (intercept, slope) and :math:`R^2` of\n the fit.\n\n The aperiodic signal, :math:`L`, is modeled using an exponential\n function in semilog-power space (linear frequencies and log PSD) as:\n\n .. math:: L = a + \\text{log}(F^b)\n\n where :math:`a` is the intercept, :math:`b` is the slope, and\n :math:`F` the vector of input frequencies.\n win_sec : int or float\n The length of the sliding window, in seconds, used for the Welch PSD\n calculation. Ideally, this should be at least two times the inverse of\n the lower frequency of interest (e.g. for a lower frequency of interest\n of 0.5 Hz, the window length should be at least 2 * 1 / 0.5 =\n 4 seconds).\n kwargs_welch : dict\n Optional keywords arguments that are passed to the\n :py:func:`scipy.signal.welch` function.\n\n Returns\n -------\n freqs : :py:class:`numpy.ndarray`\n Frequency vector.\n psd_aperiodic : :py:class:`numpy.ndarray`\n The fractal (= aperiodic) component of the PSD.\n psd_oscillatory : :py:class:`numpy.ndarray`\n The oscillatory (= periodic) component of the PSD.\n fit_params : :py:class:`pandas.DataFrame` (optional)\n Dataframe of fit parameters. Only if ``return_fit=True``.\n\n Notes\n -----\n The Irregular-Resampling Auto-Spectral Analysis (IRASA) method is\n described in Wen & Liu (2016). In a nutshell, the goal is to separate the\n fractal and oscillatory components in the power spectrum of EEG signals.\n\n The steps are:\n\n 1. Compute the original power spectral density (PSD) using Welch's method.\n 2. Resample the EEG data by multiple non-integer factors and their\n reciprocals (:math:`h` and :math:`1/h`).\n 3. For every pair of resampled signals, calculate the PSD and take the\n geometric mean of both. In the resulting PSD, the power associated with\n the oscillatory component is redistributed away from its original\n (fundamental and harmonic) frequencies by a frequency offset that varies\n with the resampling factor, whereas the power solely attributed to the\n fractal component remains the same power-law statistical distribution\n independent of the resampling factor.\n 4. It follows that taking the median of the PSD of the variously\n resampled signals can extract the power spectrum of the fractal\n component, and the difference between the original power spectrum and\n the extracted fractal spectrum offers an approximate estimate of the\n power spectrum of the oscillatory component.\n\n Note that an estimate of the original PSD can be calculated by simply\n adding ``psd = psd_aperiodic + psd_oscillatory``.\n\n For an example of how to use this function, please refer to\n https://github.com/raphaelvallat/yasa/blob/master/notebooks/09_IRASA.ipynb\n\n References\n ----------\n [1] Wen, H., & Liu, Z. (2016). Separating Fractal and Oscillatory\n Components in the Power Spectrum of Neurophysiological Signal.\n Brain Topography, 29(1), 13–26.\n https://doi.org/10.1007/s10548-015-0448-0\n\n [2] https://github.com/fieldtrip/fieldtrip/blob/master/specest/\n\n [3] https://github.com/fooof-tools/fooof\n\n [4] https://www.biorxiv.org/content/10.1101/299859v1\n \"\"\"\n import fractions\n # Check if input data is a MNE Raw object\n if isinstance(data, mne.io.BaseRaw):\n sf = data.info['sfreq'] # Extract sampling frequency\n ch_names = data.ch_names # Extract channel names\n data = data.get_data() * 1e6 # Convert from V to uV\n else:\n # Safety checks\n assert isinstance(data, np.ndarray), 'Data must be a numpy array.'\n data = np.atleast_2d(data)\n assert data.ndim == 2, 'Data must be of shape (nchan, n_samples).'\n nchan, npts = data.shape\n assert nchan < npts, 'Data must be of shape (nchan, n_samples).'\n assert sf is not None, 'sf must be specified if passing a numpy array.'\n assert isinstance(sf, (int, float))\n if ch_names is None:\n ch_names = ['CHAN' + str(i).zfill(3) for i in range(nchan)]\n else:\n ch_names = np.atleast_1d(np.asarray(ch_names, dtype=str))\n assert ch_names.ndim == 1, 'ch_names must be 1D.'\n assert len(ch_names) == nchan, 'ch_names must match data.shape[0].'\n\n # Check the other arguments\n hset = np.asarray(hset)\n assert hset.ndim == 1, 'hset must be 1D.'\n assert hset.size > 1, '2 or more resampling fators are required.'\n hset = np.round(hset, 4) # avoid float precision error with np.arange.\n band = sorted(band)\n assert band[0] > 0, 'first element of band must be > 0.'\n assert band[1] < (sf / 2), 'second element of band must be < (sf / 2).'\n win = int(win_sec * sf) # nperseg\n\n # Calculate the original PSD over the whole data\n freqs, psd = signal.welch(data, sf, nperseg=win, **kwargs_welch)\n\n # Start the IRASA procedure\n psds = np.zeros((len(hset), *psd.shape))\n\n for i, h in enumerate(hset):\n # Get the upsampling/downsampling (h, 1/h) factors as integer\n rat = fractions.Fraction(str(h))\n up, down = rat.numerator, rat.denominator\n # Much faster than FFT-based resampling\n data_up = signal.resample_poly(data, up, down, axis=-1)\n data_down = signal.resample_poly(data, down, up, axis=-1)\n # Calculate the PSD using same params as original\n freqs_up, psd_up = signal.welch(data_up, h * sf, nperseg=win,\n **kwargs_welch)\n freqs_dw, psd_dw = signal.welch(data_down, sf / h, nperseg=win,\n **kwargs_welch)\n # Geometric mean of h and 1/h\n psds[i, :] = np.sqrt(psd_up * psd_dw)\n\n # Now we take the median PSD of all the resampling factors, which gives\n # a good estimate of the aperiodic component of the PSD.\n psd_aperiodic = np.median(psds, axis=0)\n\n # We can now calculate the oscillations (= periodic) component.\n psd_osc = psd - psd_aperiodic\n\n # Let's crop to the frequencies defined in band\n mask_freqs = np.ma.masked_outside(freqs, *band).mask\n freqs = freqs[~mask_freqs]\n psd_aperiodic = np.compress(~mask_freqs, psd_aperiodic, axis=-1)\n psd_osc = np.compress(~mask_freqs, psd_osc, axis=-1)\n\n if return_fit:\n # Aperiodic fit in semilog space for each channel\n from scipy.optimize import curve_fit\n intercepts, slopes, r_squared = [], [], []\n\n def func(t, a, b):\n # See https://github.com/fooof-tools/fooof\n return a + np.log(t**b)\n\n for y in np.atleast_2d(psd_aperiodic):\n y_log = np.log(y)\n # Note that here we define bounds for the slope but not for the\n # intercept.\n popt, pcov = curve_fit(func, freqs, y_log, p0=(2, -1),\n bounds=((-np.inf, -10), (np.inf, 2)))\n intercepts.append(popt[0])\n slopes.append(popt[1])\n # Calculate R^2: https://stackoverflow.com/q/19189362/10581531\n residuals = y_log - func(freqs, *popt)\n ss_res = np.sum(residuals**2)\n ss_tot = np.sum((y_log - np.mean(y_log))**2)\n r_squared.append(1 - (ss_res / ss_tot))\n\n # Create fit parameters dataframe\n fit_params = {'Chan': ch_names, 'Intercept': intercepts,\n 'Slope': slopes, 'R^2': r_squared,\n 'std(osc)': np.std(psd_osc, axis=-1, ddof=1)}\n return freqs, psd_aperiodic, psd_osc, pd.DataFrame(fit_params)\n else:\n return freqs, psd_aperiodic, psd_osc\n\n\ndef stft_power(data, sf, window=2, step=.2, band=(1, 30), interp=True,\n norm=False):\n \"\"\"Compute the pointwise power via STFT and interpolation.\n\n Parameters\n ----------\n data : array_like\n Single-channel data.\n sf : float\n Sampling frequency of the data.\n window : int\n Window size in seconds for STFT.\n 2 or 4 seconds are usually a good default.\n Higher values = higher frequency resolution = lower time resolution.\n step : int\n Step in seconds for the STFT.\n A step of 0.2 second (200 ms) is usually a good default.\n\n * If ``step`` == 0, overlap at every sample (slowest)\n * If ``step`` == nperseg, no overlap (fastest)\n\n Higher values = higher precision = slower computation.\n band : tuple or None\n Broad band frequency range.\n Default is 1 to 30 Hz.\n interp : boolean\n If True, a cubic interpolation is performed to ensure that the output\n is the same size as the input (= pointwise power).\n norm : bool\n If True, return bandwise normalized band power, i.e. for each time\n point, the sum of power in all the frequency bins equals 1.\n\n Returns\n -------\n f : :py:class:`numpy.ndarray`\n Frequency vector\n t : :py:class:`numpy.ndarray`\n Time vector\n Sxx : :py:class:`numpy.ndarray`\n Power in the specified frequency bins of shape (f, t)\n\n Notes\n -----\n 2D Interpolation is done using\n :py:class:`scipy.interpolate.RectBivariateSpline`\n which is much faster than :py:class:`scipy.interpolate.interp2d`\n for a rectangular grid. The default is to use a bivariate spline with\n 3 degrees.\n \"\"\"\n # Safety check\n data = np.asarray(data)\n assert step <= window\n\n step = 1 / sf if step == 0 else step\n\n # Define STFT parameters\n nperseg = int(window * sf)\n noverlap = int(nperseg - (step * sf))\n\n # Compute STFT and remove the last epoch\n f, t, Sxx = signal.stft(data, sf, nperseg=nperseg, noverlap=noverlap,\n detrend=False, padded=True)\n\n # Let's keep only the frequency of interest\n if band is not None:\n idx_band = np.logical_and(f >= band[0], f <= band[1])\n f = f[idx_band]\n Sxx = Sxx[idx_band, :]\n\n # Compute power\n Sxx = np.square(np.abs(Sxx))\n\n # Interpolate\n if interp:\n func = RectBivariateSpline(f, t, Sxx)\n t = np.arange(data.size) / sf\n Sxx = func(f, t)\n\n if norm:\n sum_pow = Sxx.sum(0).reshape(1, -1)\n np.divide(Sxx, sum_pow, out=Sxx)\n return f, t, Sxx\n"
] | [
[
"numpy.sqrt",
"numpy.asarray",
"scipy.signal.stft",
"numpy.squeeze",
"numpy.ma.masked_outside",
"numpy.in1d",
"pandas.DataFrame",
"numpy.round",
"numpy.mean",
"scipy.optimize.curve_fit",
"numpy.divide",
"scipy.signal.welch",
"numpy.hstack",
"numpy.arange",
"numpy.std",
"numpy.log",
"scipy.interpolate.RectBivariateSpline",
"scipy.signal.resample_poly",
"numpy.median",
"numpy.atleast_2d",
"scipy.integrate.simps",
"numpy.logical_and",
"numpy.sum",
"numpy.abs",
"numpy.compress"
]
] | [
{
"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.10",
"1.4",
"1.3",
"1.9",
"0.19",
"1.5",
"1.7",
"1.0",
"1.2",
"1.8"
],
"tensorflow": []
}
] |
coreqode/DataAug_GUI | [
"2c830b76c57a5b860d03c122c961cac692c70d04"
] | [
"transfer.py"
] | [
"\"\"\"\nCopyright (c) 2019 NAVER Corp.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\"\"\"\n\nimport os\nimport tqdm\nimport argparse\nimport sys\n\n\nimport torch\nfrom torchvision.utils import save_image\n\nfrom model import WaveEncoder, WaveDecoder\n\nfrom utils.core import feature_wct\nfrom utils.io import Timer, open_image, load_segment, compute_label_info\n\n\nIMG_EXTENSIONS = [\n '.jpg', '.JPG', '.jpeg', '.JPEG',\n '.png', '.PNG',\n]\n\n\ndef is_image_file(filename):\n return any(filename.endswith(extension) for extension in IMG_EXTENSIONS)\n\n\nclass WCT2:\n def __init__(self, model_path='./model_checkpoints', transfer_at=['encoder', 'skip', 'decoder'], option_unpool='cat5', device='cpu', verbose=False):\n\n self.transfer_at = set(transfer_at)\n assert not(self.transfer_at - set(['encoder', 'decoder', 'skip'])), 'invalid transfer_at: {}'.format(transfer_at)\n assert self.transfer_at, 'empty transfer_at'\n\n self.device = torch.device(device)\n self.verbose = verbose\n self.encoder = WaveEncoder(option_unpool).to(self.device)\n self.decoder = WaveDecoder(option_unpool).to(self.device)\n self.encoder.load_state_dict(torch.load(os.path.join(model_path, 'wave_encoder_{}_l4.pth'.format(option_unpool)), map_location=lambda storage, loc: storage))\n self.decoder.load_state_dict(torch.load(os.path.join(model_path, 'wave_decoder_{}_l4.pth'.format(option_unpool)), map_location=lambda storage, loc: storage))\n\n def print_(self, msg):\n if self.verbose:\n print(msg)\n\n def encode(self, x, skips, level):\n return self.encoder.encode(x, skips, level)\n\n def decode(self, x, skips, level):\n return self.decoder.decode(x, skips, level)\n\n def get_all_feature(self, x):\n skips = {}\n feats = {'encoder': {}, 'decoder': {}}\n for level in [1, 2, 3, 4]:\n x = self.encode(x, skips, level)\n if 'encoder' in self.transfer_at:\n feats['encoder'][level] = x\n\n if 'encoder' not in self.transfer_at:\n feats['decoder'][4] = x\n for level in [4, 3, 2]:\n x = self.decode(x, skips, level)\n if 'decoder' in self.transfer_at:\n feats['decoder'][level - 1] = x\n return feats, skips\n\n def transfer(self, content, style, content_segment, style_segment, alpha=1):\n label_set, label_indicator = compute_label_info(content_segment, style_segment)\n content_feat, content_skips = content, {}\n style_feats, style_skips = self.get_all_feature(style)\n\n wct2_enc_level = [1, 2, 3, 4]\n wct2_dec_level = [1, 2, 3, 4]\n wct2_skip_level = ['pool1', 'pool2', 'pool3']\n\n for level in [1, 2, 3, 4]:\n content_feat = self.encode(content_feat, content_skips, level)\n if 'encoder' in self.transfer_at and level in wct2_enc_level:\n content_feat = feature_wct(content_feat, style_feats['encoder'][level],\n content_segment, style_segment,\n label_set, label_indicator,\n alpha=alpha, device=self.device)\n self.print_('transfer at encoder {}'.format(level))\n if 'skip' in self.transfer_at:\n for skip_level in wct2_skip_level:\n for component in [0, 1, 2]: # component: [LH, HL, HH]\n content_skips[skip_level][component] = feature_wct(content_skips[skip_level][component], style_skips[skip_level][component],\n content_segment, style_segment,\n label_set, label_indicator,\n alpha=alpha, device=self.device)\n self.print_('transfer at skip {}'.format(skip_level))\n\n for level in [4, 3, 2, 1]:\n if 'decoder' in self.transfer_at and level in style_feats['decoder'] and level in wct2_dec_level:\n content_feat = feature_wct(content_feat, style_feats['decoder'][level],\n content_segment, style_segment,\n label_set, label_indicator,\n alpha=alpha, device=self.device)\n self.print_('transfer at decoder {}'.format(level))\n content_feat = self.decode(content_feat, content_skips, level)\n return content_feat\n\n\ndef get_all_transfer():\n ret = []\n for e in ['encoder', None]:\n for d in ['decoder', None]:\n for s in ['skip', None]:\n _ret = set([e, d, s]) & set(['encoder', 'decoder', 'skip'])\n if _ret:\n ret.append(_ret)\n return ret\n\n\ndef run_bulk(config):\n device = 'cpu' if config.cpu or not torch.cuda.is_available() else 'cuda:0'\n device = torch.device(device)\n\n transfer_at = set()\n if config.transfer_at_encoder:\n transfer_at.add('encoder')\n if config.transfer_at_decoder:\n transfer_at.add('decoder')\n if config.transfer_at_skip:\n transfer_at.add('skip')\n\n # The filenames of the content and style pair should match\n fnames = set(os.listdir(config.content)) & set(os.listdir(config.style))\n\n if config.content_segment and config.style_segment:\n fnames &= set(os.listdir(config.content_segment))\n fnames &= set(os.listdir(config.style_segment))\n\n for fname in tqdm.tqdm(fnames):\n if not is_image_file(fname):\n print('invalid file (is not image), ', fname)\n continue\n _content = os.path.join(config.content, fname)\n _style = os.path.join(config.style, fname)\n _content_segment = os.path.join(config.content_segment, fname) if config.content_segment else None\n _style_segment = os.path.join(config.style_segment, fname) if config.style_segment else None\n _output = os.path.join(config.output, fname)\n\n content = open_image(_content, config.image_size).to(device)\n style = open_image(_style, config.image_size).to(device)\n content_segment = load_segment(_content_segment, config.image_size)\n style_segment = load_segment(_style_segment, config.image_size)\n\n if not config.transfer_all:\n with Timer('Elapsed time in whole WCT: {}', config.verbose):\n postfix = '_'.join(sorted(list(transfer_at)))\n fname_output = _output.replace('.png', '_{}_{}.png'.format(config.option_unpool, postfix))\n print('------ transfer:', _output)\n wct2 = WCT2(transfer_at=transfer_at, option_unpool=config.option_unpool, device=device, verbose=config.verbose)\n with torch.no_grad():\n img = wct2.transfer(content, style, content_segment, style_segment, alpha=config.alpha)\n save_image(img.clamp_(0, 1), fname_output, padding=0)\n else:\n for _transfer_at in get_all_transfer():\n with Timer('Elapsed time in whole WCT: {}', config.verbose):\n postfix = '_'.join(sorted(list(_transfer_at)))\n fname_output = _output.replace('.png', '_{}_{}.png'.format(config.option_unpool, postfix))\n print('------ transfer:', fname)\n wct2 = WCT2(transfer_at=_transfer_at, option_unpool=config.option_unpool, device=device, verbose=config.verbose)\n with torch.no_grad():\n img = wct2.transfer(content, style, content_segment, style_segment, alpha=config.alpha)\n save_image(img.clamp_(0, 1), fname_output, padding=0)\n\n\n# if __name__ == '__main__':\ndef main(image_size, cpu, unpool, e, d, s, a, alpha):\n path = os.getcwd()\n sys.path.append(path)\n parser = argparse.ArgumentParser()\n # parser.add_argument('--content', type=str, default='/home/chandradeep_p/repositories/WCT2/examples/content')\n # parser.add_argument('--content_segment', type=str, default='/home/chandradeep_p/repositories/WCT2/examples/content_segment')\n # parser.add_argument('--style', type=str, default='/home/chandradeep_p/repositories/WCT2/examples/style')\n # parser.add_argument('--style_segment', type=str, default='/home/chandradeep_p/repositories/WCT2/examples/style_segment')\n # parser.add_argument('--output', type=str, default='./outputs')\n # parser.add_argument('--image_size', type=int, default=512)\n # parser.add_argument('--alpha', type=float, default=1)\n # parser.add_argument('--option_unpool', type=str, default='cat5', choices=['sum', 'cat5'])\n # parser.add_argument('-e', '--transfer_at_encoder', action='store_true')\n # parser.add_argument('-d', '--transfer_at_decoder', action='store_true')\n # parser.add_argument('-s', '--transfer_at_skip', action='store_true')\n # parser.add_argument('-a', '--transfer_all', action='store_true')\n # parser.add_argument('--cpu', action='store_true')\n # parser.add_argument('--verbose', action='store_true')\n config = parser.parse_args()\n config.content = path + '/input_dataset/target_images'\n config.content_segment = path + '/input_dataset/target_masks'\n config.style = path + '/input_dataset/style_images'\n config.style_segment = path + '/input_dataset/style_masks'\n config.output = path + '/input_dataset/outputs'\n config.image_size = int(image_size)\n config.alpha = float(alpha)\n config.option_unpool = unpool\n config.e, config.d, config.s, config.a = e,d,s,a\n config.transfer_at_encoder, config.transfer_at_decoder, config.transfer_at_skip, config.transfer_all = config.e, config.d, config.s, config.a\n config.cpu = cpu\n config.verbose = True\n\n print(config)\n\n if not os.path.exists(os.path.join(config.output)):\n os.makedirs(os.path.join(config.output))\n\n '''\n CUDA_VISIBLE_DEVICES=6 python transfer.py --content ./examples/content --style ./examples/style --content_segment ./examples/content_segment --style_segment ./examples/style_segment/ --output ./outputs/ --verbose --image_size 512 -a\n '''\n run_bulk(config)\n"
] | [
[
"torch.device",
"torch.no_grad",
"torch.cuda.is_available"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
hugofloresgarcia/MusEEG | [
"f648a4028b529bfdfc6bd0e9b282983ba6993a93"
] | [
"docs/_documentation/chapters/code/classifier.py"
] | [
"import os\nimport pandas\nimport numpy as np\nfrom tensorflow import keras\nfrom keras import regularizers\nfrom MusEEG import parentDir\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.externals import joblib\n\nimport matplotlib.pyplot as plt\n\nclass classifier:\n hiddenNeurons = 20\n numberOfTargets = 10\n inputShape = 350\n\n def __init__(self):\n self.scaler = None\n\n def loadTrainingData(self, percentTrain=0.75,\n address=os.path.join(parentDir, 'data', 'training' ),\n inputFilename='inputs.csv',\n targetFilename='targets.csv', normalize=True):\n inputsAll = pandas.read_csv(os.path.join(address, inputFilename)).values\n targetsAll = pandas.read_csv(os.path.join(address, targetFilename)).values\n # use index from 1 on bc index 0 is just a counter for some reason.\n inputsAll[:, 0] = targetsAll[:, 1]\n # first column of inputsAll will now be the targets (sorry programming gods, I'm going crazy over this one)\n trainingData = pandas.DataFrame(inputsAll)\n #shuffle the data!!!\n trainingData = trainingData.reindex(np.random.permutation(trainingData.index))\n trainingData = trainingData.values\n\n #slice it up, baby\n slice = round(len(trainingData[:, 0])*percentTrain)\n train_inputs = trainingData[0:slice, 1:]\n train_targets = trainingData[0:slice, 0]\n test_inputs = trainingData[slice:, 1:]\n test_targets = trainingData[slice:, 0]\n if normalize:\n self.scaler = MinMaxScaler()\n self.scaler.fit(train_inputs)\n train_inputs = self.scaler.transform(train_inputs)\n plt.plot(train_inputs)\n test_inputs = self.scaler.transform(test_inputs)\n else:\n self.scaler = None\n\n return train_inputs, train_targets, test_inputs, test_targets\n\n # build the model\n def build_model(self, inputShape, hiddenNeurons, numberOfTargets, hiddenActivation='relu',\n outputActivation='softmax', regularization='l2_l2', optimizer='adam',\n loss='sparse_categorical_crossentropy'):\n if regularization == 'l1':\n reg = regularizers.l1(0.001)\n self.model = keras.Sequential([\n keras.layers.Dense(hiddenNeurons,\n activation=hiddenActivation,\n activity_regularizer=reg,\n input_dim=inputShape),\n keras.layers.Dense(numberOfTargets, activation=outputActivation),\n ])\n elif regularization == 'l2':\n reg = regularizers.l2(0.001)\n self.model = keras.Sequential([\n keras.layers.Dense(hiddenNeurons,\n activation=hiddenActivation,\n activity_regularizer=reg,\n input_dim=inputShape),\n keras.layers.Dense(numberOfTargets, activation=outputActivation),\n ])\n elif regularization == 'l1_l2':\n reg = regularizers.l1_l2(0.001)\n self.model = keras.Sequential([\n keras.layers.Dense(hiddenNeurons,\n activation=hiddenActivation,\n activity_regularizer=reg,\n input_dim=inputShape),\n keras.layers.Dense(numberOfTargets, activation=outputActivation),\n ])\n else:\n self.model = keras.Sequential([\n keras.layers.Dense(hiddenNeurons, activation=hiddenActivation,\n input_dim=inputShape),\n keras.layers.Dense(numberOfTargets, activation=outputActivation)])\n\n self.model.compile(optimizer=optimizer,\n loss=loss,\n metrics=['accuracy'])\n self.hiddenNeurons = hiddenNeurons\n self.numberOfTargets = numberOfTargets\n self.inputShape = inputShape\n return self.model\n\n # train the model\n def train_model(self, train_inputs, train_targets, nEpochs, verbose=0):\n self.model.fit(train_inputs, train_targets, epochs=nEpochs, verbose=verbose)\n\n def evaluate_model(self, test_inputs, test_targets, verbose=2):\n test_loss, test_acc = self.model.evaluate(test_inputs, test_targets, verbose)\n print('\\nTest accuracy:', test_acc)\n return test_acc\n\n def print_confusion(self, test_inputs, test_targets):\n prediction = self.model.predict(test_inputs)\n prediction = np.array([np.argmax(row) for row in prediction])\n cm = confusion_matrix(test_targets, prediction)\n print(cm)\n return cm\n\n def normalizeInput(self, inputVector):\n if self.scaler is not None:\n return self.scaler.transform(inputVector)\n\n def classify(self, inputVector):\n if self.scaler is not None:\n inputVector = self.scaler.transform(inputVector)\n\n prediction = self.model.predict(inputVector)\n output = np.argmax(prediction)\n return output\n\n def clear(self):\n keras.backend.clear_session()\n\n def savemodel(self, filename, address=os.path.join(parentDir, 'data', 'savedModels')):\n if self.scaler is not None:\n joblib.dump(self.scaler, os.path.join(parentDir, 'data', 'savedModels',filename+'_scaler'))\n self.model.save(os.path.join(address, filename), save_format='tf')\n\n def loadmodel(self, filename, address=os.path.join(parentDir, 'data', 'savedModels'), loadScaler=False):\n \"\"\"\n load a saved keras model\n :param filename: name of the savedModel\n :param address: address (relative to the parent directory) where your model is stored. defaults to /data/SavedModels\n :return:\n \"\"\"\n if loadScaler:\n self.scaler = joblib.load(filename+'_scaler')\n self.model = keras.models.load_model(os.path.join(address, filename))\n\n\n\n"
] | [
[
"tensorflow.keras.layers.Dense",
"sklearn.metrics.confusion_matrix",
"pandas.DataFrame",
"matplotlib.pyplot.plot",
"numpy.random.permutation",
"numpy.argmax",
"tensorflow.keras.backend.clear_session",
"sklearn.externals.joblib.load",
"sklearn.preprocessing.MinMaxScaler"
]
] | [
{
"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": [
"1.10",
"2.7",
"2.6",
"2.4",
"2.3",
"2.5",
"2.2"
]
}
] |
gdiprisco/VisualFlickr | [
"f793d1fe2694c2ed31d527a5092150db26b6f3c7"
] | [
"modules/classifier.py"
] | [
"import os\nimport numpy as np\nimport json\n\n\ndef caffe_import(verbose):\n \"\"\"\n VERBOSE LEVELS\n 0 - debug\n 1 - info\n 2 - warnings\n 3 - errors\n :param verbose: int\n :return:\n \"\"\"\n os.environ['GLOG_minloglevel'] = str(verbose)\n global caffe\n try:\n import caffe\n except ModuleNotFoundError:\n print('CAFFE MODULE NOT FOUND. Suggest: Install caffe-cpu or caffe-cuda')\n\n\nclass LangException(Exception):\n def __init__(self):\n super().__init__(\"Classifier not available with the inserted language.\")\n\n\nclass Classifier(object):\n __slots__ = \"net\", \"transformer\", \"labels\", \"verbose\", \"language\"\n\n def __init__(self, structure_model, pre_trained_model, mean_file, labels_file, verbose='0', language=\"english\"):\n caffe_import(verbose)\n if os.path.splitext(mean_file)[1] == \".binaryproto\":\n mean_file = Classifier._protobuf_mean(mean_file)\n self.net, self.transformer = Classifier._build_classifier(structure_model, pre_trained_model, mean_file)\n self.labels = np.genfromtxt(labels_file, delimiter='\\t', converters={0: lambda x: x.decode()})\n self.verbose = int(verbose)\n self.language = language\n\n @staticmethod\n def parse_settings(settings_path, lang=\"english\"):\n with open(settings_path, 'r') as settings_file:\n try:\n settings = json.load(settings_file)[lang]\n except KeyError:\n raise LangException\n structure_model = settings[\"structure_model\"]\n pre_trained_model = settings[\"pre_trained_model\"]\n mean_file = settings[\"mean_file\"]\n labels_file = settings[\"labels_file\"]\n verbose = settings[\"verbose\"]\n return Classifier(structure_model, pre_trained_model, mean_file, labels_file, verbose=verbose, language=lang)\n\n @staticmethod\n def _build_classifier(structure_model, pretrained_model, mean_file):\n net = caffe.Net(structure_model, pretrained_model, caffe.TEST)\n transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape})\n transformer.set_mean('data', np.load(mean_file).mean(1).mean(1))\n transformer.set_transpose('data', (2, 0, 1))\n transformer.set_channel_swap('data', (2, 1, 0))\n transformer.set_raw_scale('data', 255.0)\n net.blobs['data'].reshape(10, 3, 224, 224)\n return net, transformer\n\n @staticmethod\n def _protobuf_mean(protobuf_input, meanfile_output=None):\n if meanfile_output is None:\n meanfile_output = os.path.splitext(protobuf_input)[0] + \".npy\"\n blob = caffe.proto.caffe_pb2.BlobProto()\n data = open(protobuf_input, 'rb').read()\n blob.ParseFromString(data)\n # data = np.array(blob.data)\n arr = np.array(caffe.io.blobproto_to_array(blob))\n out = arr[0]\n np.save(meanfile_output, out)\n return meanfile_output\n\n def set_labels(self, labels_file):\n self.labels = np.genfromtxt(labels_file, delimiter='\\t', converters={0: lambda x: x.decode()})\n\n def get_labels(self):\n return self.labels\n\n def get_verbose_level(self):\n return self.verbose\n\n def get_language(self):\n return self.language\n\n def classify_image(self, image):\n image_labels = None\n im = caffe.io.load_image(image)\n self.net.blobs['data'].data[...] = self.transformer.preprocess('data', im)\n out = self.net.forward()\n image_class_ids = out['prob'].argmax()\n if self.verbose == 0:\n print(image_class_ids)\n top_k = self.net.blobs['prob'].data[0].flatten().argsort()[-1:-6:-1]\n if self.labels is not None:\n image_labels = self.labels[top_k]\n if self.verbose == 0:\n print(image_labels)\n return image_labels if image_labels is not None else []\n\n\nif __name__ == \"__main__\":\n language = 'english'\n image_test_dir = '../image_test'\n labels_file_t = \"../net/{lang}/{lang}_label.txt\".format(lang=language)\n structure_model_proto = '../net/{lang}/{lang}_inception_mvso-hybrid.prototxt'.format(lang=language)\n # or 'english_lr10_iter_210000.prototxt'\n pre_trained_caffemodel = '../net/{lang}/{lang}_inception_mvso-hybrid.caffemodel'.format(lang=language)\n # or 'english_lr10_iter_210000.caffemodel'\n mean_proto = '../net/{lang}/{lang}_meanimage.binaryproto'.format(lang=language)\n\n # classifier = Classifier(structure_model_proto, pre_trained_caffemodel, mean_proto, labels_file_t, verbose='2')\n classifier = Classifier.parse_settings(\"../settings/classifier_settings.json\", \"english\")\n for image_t in os.listdir(image_test_dir):\n if image_t.endswith(\".jpg\"):\n tags = classifier.classify_image(os.path.join(image_test_dir, image_t))\n print(\"IMAGE : \", image_t)\n print(\"TAGS : {}\".format(\" \".join(tags)))\n"
] | [
[
"numpy.load",
"numpy.save"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
mrakitin/caproto | [
"ad49ffbe1a69ddc63cac9ec7f1a3468a4965e465"
] | [
"caproto/ioc_examples/too_clever/trigger_with_pc.py"
] | [
"#!/usr/bin/env python3\nimport contextvars\nimport functools\nimport random\nimport sys\nfrom textwrap import dedent\n\nimport numpy as np\n\nfrom caproto import ChannelType\nfrom caproto.server import PVGroup, ioc_arg_parser, pvproperty, run\n\ninternal_process = contextvars.ContextVar('internal_process',\n default=False)\n\n\ndef no_reentry(func):\n @functools.wraps(func)\n async def inner(*args, **kwargs):\n if internal_process.get():\n return\n try:\n internal_process.set(True)\n return (await func(*args, **kwargs))\n finally:\n internal_process.set(False)\n\n return inner\n\n\nclass TriggeredIOC(PVGroup):\n \"\"\"\n A triggered IOC with put-completion support\n\n\n Scalar PVs\n ----------\n exposure_time : float\n The simulated exposure time\n\n acquire : {'idle', 'acquiring'}\n The acquire button, put-complete will indicate when done.\n\n reading : float\n Random number, updates when 'acquisition' finishes.\n\n gain : float\n Sets the range of the random number for the reading.\n\n enabled : {'off', 'on'}\n\n wait : float\n wait_time : int\n \"\"\"\n\n gain = pvproperty(value=2.0)\n exposure_time = pvproperty(value=2.0)\n reading = pvproperty(value=0.1, alarm_group='acq')\n\n acquire = pvproperty(value='idle',\n enum_strings=['idle', 'acquiring'],\n dtype=ChannelType.ENUM,\n alarm_group='acq')\n\n enabled = pvproperty(value='on',\n enum_strings=['off', 'on'],\n dtype=ChannelType.ENUM,\n alarm_group='acq')\n\n @acquire.putter\n @no_reentry\n async def acquire(self, instance, value):\n if self.enabled.value == 'off':\n raise RuntimeError(\"Device must be enabled\")\n if not instance.ev.is_set():\n await instance.ev.wait()\n return 'idle'\n\n if value == 'acquiring':\n instance.ev.clear()\n try:\n await instance.write(1)\n\n await instance.async_lib.library.sleep(\n self.exposure_time.value)\n\n await self.reading.write(np.random.rand())\n\n finally:\n instance.ev.set()\n\n return 'idle'\n\n @acquire.startup\n async def acquire(self, instance, async_lib):\n # monkey patch the instance like whoa\n instance.async_lib = async_lib\n instance.ev = async_lib.Event()\n instance.ev.set()\n\n wait = pvproperty(value=2.0)\n wait_time = pvproperty(value=0)\n\n @wait.startup\n async def wait(self, instance, async_lib):\n instance.async_lib = async_lib\n\n @wait.getter\n async def wait(self, instance):\n sleep_time = random.randint(0, 15)\n await self.wait_time.write(sleep_time)\n await instance.async_lib.library.sleep(sleep_time)\n return sleep_time\n\n fatal = pvproperty(value=0)\n\n @fatal.putter\n async def fatal(self, val):\n sys.exit(0)\n\n\nif __name__ == '__main__':\n ioc_options, run_options = ioc_arg_parser(\n default_prefix='trigger_with_pc:',\n desc=dedent(TriggeredIOC.__doc__))\n ioc = TriggeredIOC(**ioc_options)\n run(ioc.pvdb, **run_options)\n"
] | [
[
"numpy.random.rand"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
LeiSoft/CueObserve | [
"cc5254df7d0cb817a8b3ec427f5cb54a1d420f7e"
] | [
"api/ops/tasks/detection/core/detectionTypes/percentageChange.py"
] | [
"import dateutil.parser as dp\nfrom dateutil.relativedelta import relativedelta\nimport pandas as pd, datetime as dt\n\n\ndef checkLatestAnomaly(df):\n \"\"\"\n Looks up latest anomaly in dataframe\n \"\"\"\n anomalies = df[df[\"anomaly\"] == 15]\n if anomalies.shape[0] > 0:\n lastAnomalyRow = anomalies.iloc[-1]\n anomalyTime = lastAnomalyRow[\"ds\"]\n higher = lastAnomalyRow[\"percentageChange\"] > 0\n\n return {\n \"highOrLow\": \"high\" if higher else \"low\",\n \"value\": float(lastAnomalyRow[\"y\"]),\n \"percent\": abs(lastAnomalyRow[\"percentageChange\"]),\n \"anomalyTimeISO\": dp.parse(anomalyTime).isoformat(),\n \"anomalyTime\": dp.parse(anomalyTime).timestamp() * 1000,\n }\n return {}\n\ndef percentChangeDetect(df, granularity, threshold):\n \"\"\"\n Method to perform anomaly detection on given dataframe using fbProphet\n \"\"\"\n threshold = float(threshold)\n today = dt.datetime.now()\n df[\"ds\"] = pd.to_datetime(df[\"ds\"])\n df = df.sort_values(\"ds\")\n df[\"ds\"] = df[\"ds\"].apply(lambda date: date.isoformat()[:19])\n todayISO = today.replace(hour=0, minute=0, second=0, microsecond=0, tzinfo=None).isoformat()[:19]\n df = df[df[\"ds\"] < todayISO]\n df[\"percentageChange\"] = 100 * (df.y - df.y.shift(1)) / df.y.shift(1)\n df[\"anomaly\"] = (abs(df[\"percentageChange\"]) > threshold) * 14 + 1\n anomalyLatest = checkLatestAnomaly(df)\n df = df[[\"ds\", \"y\", \"anomaly\"]]\n numActual = 45 if granularity == \"day\" else 24 * 7\n output = {\n \"anomalyData\": {\n \"actual\": df[-numActual:].to_dict(\"records\")\n },\n \"anomalyLatest\": anomalyLatest\n }\n return output"
] | [
[
"pandas.to_datetime"
]
] | [
{
"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": []
}
] |
KyleLevi/BAM_Scripts | [
"71805b57ee81cb3bd4e30f96a6236d8d8e148df7"
] | [
"bin/csv_to_heatmap.py"
] | [
"import numpy as np\nfrom numpy import vstack # VSTACK((a,b)) stacks B on TOP of A\nimport seaborn as sns; sns.set()\nimport matplotlib.pyplot as plt\nimport math\nimport argparse\nimport sys\n\n\ndef csv_to_numpy(csv_file):\n \"\"\"\n Reads in a CSV file and returns a numpy array\n :param csv_file: String, the location and name of the CSV file\n :return: a Numpy array the dimensions of the CSV\n \"\"\"\n with open(csv_file, 'r') as infile:\n lines = infile.readlines()\n stack = None\n for line in lines:\n newline = []\n for x in [int(y) for y in line.split(',')]:\n if x <= 0:\n newline.append(0)\n else:\n newline.append(math.log(x, 10))\n x = np.array(newline)\n if not stack:\n stack = x\n else:\n try:\n stack = vstack((stack, x)) # Double (( )) on purpose\n except Exception as e:\n if False:\n print('Error: cannot vstack len:{}'.format(len(x)))\n return stack\n\n\ndef sort_numpy_array(numpy_array):\n \"\"\"\n Sorts a 2d Numpy array by the sum of each row (highest sum is at the top)\n :param numpy_array: A 2d numpy array\n :return: a sorted 2d numpy array\n \"\"\"\n numpy_array = numpy_array.tolist()\n numpy_array.sort(key=sum, reverse=True)\n numpy_array = np.array(numpy_array)\n return numpy_array\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Reads in a CSV file and outputs a basic heatmap of the data')\n parser.add_argument('-i', '--input', help='The location of the CSV file to be made into a heatmap', required=True)\n parser.add_argument('-o', '--output', help='File name of the figure', required=True)\n\n try:\n args = parser.parse_args()\n except:\n parser.print_help()\n sys.exit(0)\n\n csv_array = csv_to_numpy(args.input)\n csv_array = sort_numpy_array(csv_array)\n\n # This is where you can customize your figure! --------\n # Documentation for the seaborn heatmap can be found here:\n # http://seaborn.pydata.org/generated/seaborn.heatmap.html\n # Feel free to change this to suit your needs, csv_array is a 2d numpy array\n # of the data to be plotted, and most graphing modules can read numpy arrays\n ax = sns.heatmap(csv_array, xticklabels=[], yticklabels=[])\n\n\n\n\n # plt.show() # Uncommenting this line will show the figure before saving\n plt.savefig(args.output)\n\n\n\n\n\n\n"
] | [
[
"numpy.vstack",
"numpy.array",
"matplotlib.pyplot.savefig"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
szczeles/feast | [
"ae1e4b9677e737d289464283f11222fd48f1960d"
] | [
"tests/e2e/test_historical_features.py"
] | [
"from datetime import datetime, timedelta\nfrom typing import Union\nfrom urllib.parse import urlparse\n\nimport gcsfs\nimport numpy as np\nimport pandas as pd\nfrom google.protobuf.duration_pb2 import Duration\nfrom pandas._testing import assert_frame_equal\nfrom pyarrow import parquet\n\nfrom feast import Client, Entity, Feature, FeatureTable, ValueType\nfrom feast.data_source import BigQuerySource, FileSource\n\nnp.random.seed(0)\n\n\ndef read_parquet(uri):\n parsed_uri = urlparse(uri)\n if parsed_uri.scheme == \"file\":\n return pd.read_parquet(parsed_uri.path)\n elif parsed_uri.scheme == \"gs\":\n fs = gcsfs.GCSFileSystem()\n files = [\"gs://\" + path for path in fs.glob(uri + \"/part-*\")]\n ds = parquet.ParquetDataset(files, filesystem=fs)\n return ds.read().to_pandas()\n elif parsed_uri.scheme == \"s3\":\n import s3fs\n\n fs = s3fs.S3FileSystem()\n files = [\"s3://\" + path for path in fs.glob(uri + \"/part-*\")]\n ds = parquet.ParquetDataset(files, filesystem=fs)\n return ds.read().to_pandas()\n else:\n raise ValueError(f\"Unsupported URL scheme {uri}\")\n\n\ndef generate_data():\n retrieval_date = datetime.utcnow().replace(tzinfo=None)\n retrieval_outside_max_age_date = retrieval_date + timedelta(1)\n event_date = retrieval_date - timedelta(2)\n creation_date = retrieval_date - timedelta(1)\n\n customers = [1001, 1002, 1003, 1004, 1005]\n daily_transactions = [np.random.rand() * 10 for _ in customers]\n total_transactions = [np.random.rand() * 100 for _ in customers]\n\n transactions_df = pd.DataFrame(\n {\n \"event_timestamp\": [event_date for _ in customers],\n \"created_timestamp\": [creation_date for _ in customers],\n \"user_id\": customers,\n \"daily_transactions\": daily_transactions,\n \"total_transactions\": total_transactions,\n }\n )\n customer_df = pd.DataFrame(\n {\n \"event_timestamp\": [retrieval_date for _ in customers]\n + [retrieval_outside_max_age_date for _ in customers],\n \"user_id\": customers + customers,\n }\n )\n return transactions_df, customer_df\n\n\ndef test_historical_features(\n feast_client: Client, batch_source: Union[BigQuerySource, FileSource]\n):\n customer_entity = Entity(\n name=\"user_id\", description=\"Customer\", value_type=ValueType.INT64\n )\n feast_client.apply_entity(customer_entity)\n\n max_age = Duration()\n max_age.FromSeconds(2 * 86400)\n\n transactions_feature_table = FeatureTable(\n name=\"transactions\",\n entities=[\"user_id\"],\n features=[\n Feature(\"daily_transactions\", ValueType.DOUBLE),\n Feature(\"total_transactions\", ValueType.DOUBLE),\n ],\n batch_source=batch_source,\n max_age=max_age,\n )\n\n feast_client.apply_feature_table(transactions_feature_table)\n\n transactions_df, customers_df = generate_data()\n feast_client.ingest(transactions_feature_table, transactions_df)\n\n feature_refs = [\"transactions:daily_transactions\"]\n\n job = feast_client.get_historical_features(feature_refs, customers_df)\n output_dir = job.get_output_file_uri()\n joined_df = read_parquet(output_dir)\n\n expected_joined_df = pd.DataFrame(\n {\n \"event_timestamp\": customers_df.event_timestamp.tolist(),\n \"user_id\": customers_df.user_id.tolist(),\n \"transactions__daily_transactions\": transactions_df.daily_transactions.tolist()\n + [None] * transactions_df.shape[0],\n }\n )\n\n assert_frame_equal(\n joined_df.sort_values(by=[\"user_id\", \"event_timestamp\"]).reset_index(drop=True),\n expected_joined_df.sort_values(by=[\"user_id\", \"event_timestamp\"]).reset_index(\n drop=True\n ),\n )\n"
] | [
[
"pandas.read_parquet",
"numpy.random.rand",
"numpy.random.seed",
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"0.24",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
jshower/models | [
"c48b1c51d1eb581c399a5046ad61b34ebad4f1a6"
] | [
"fluid/PaddleCV/gan/cycle_gan/train.py"
] | [
"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport os\nimport random\nimport sys\nimport paddle\nimport argparse\nimport functools\nimport time\nimport numpy as np\nfrom scipy.misc import imsave\nimport paddle.fluid as fluid\nimport paddle.fluid.profiler as profiler\nfrom paddle.fluid import core\nimport data_reader\nfrom utility import add_arguments, print_arguments, ImagePool\nfrom trainer import *\n\n\nparser = argparse.ArgumentParser(description=__doc__)\nadd_arg = functools.partial(add_arguments, argparser=parser)\n# yapf: disable\nadd_arg('batch_size', int, 1, \"Minibatch size.\")\nadd_arg('epoch', int, 2, \"The number of epoched to be trained.\")\nadd_arg('output', str, \"./output_0\", \"The directory the model and the test result to be saved to.\")\nadd_arg('init_model', str, None, \"The init model file of directory.\")\nadd_arg('save_checkpoints', bool, True, \"Whether to save checkpoints.\")\nadd_arg('run_test', bool, True, \"Whether to run test.\")\nadd_arg('use_gpu', bool, True, \"Whether to use GPU to train.\")\nadd_arg('profile', bool, False, \"Whether to profile.\")\nadd_arg('run_ce', bool, False, \"Whether to run for model ce.\")\n# yapf: enable\n\n\ndef train(args):\n\n max_images_num = data_reader.max_images_num()\n shuffle=True\n if args.run_ce:\n np.random.seed(10)\n fluid.default_startup_program().random_seed = 90\n max_images_num = 1\n shuffle = False\n data_shape = [-1] + data_reader.image_shape()\n\n input_A = fluid.layers.data(\n name='input_A', shape=data_shape, dtype='float32')\n input_B = fluid.layers.data(\n name='input_B', shape=data_shape, dtype='float32')\n fake_pool_A = fluid.layers.data(\n name='fake_pool_A', shape=data_shape, dtype='float32')\n fake_pool_B = fluid.layers.data(\n name='fake_pool_B', shape=data_shape, dtype='float32')\n\n g_A_trainer = GATrainer(input_A, input_B)\n g_B_trainer = GBTrainer(input_A, input_B)\n d_A_trainer = DATrainer(input_A, fake_pool_A)\n d_B_trainer = DBTrainer(input_B, fake_pool_B)\n\n # prepare environment\n place = fluid.CPUPlace()\n if args.use_gpu:\n place = fluid.CUDAPlace(0)\n exe = fluid.Executor(place)\n exe.run(fluid.default_startup_program())\n A_pool = ImagePool()\n B_pool = ImagePool()\n \n A_reader = paddle.batch(data_reader.a_reader(shuffle=shuffle), args.batch_size)()\n B_reader = paddle.batch(data_reader.b_reader(shuffle=shuffle), args.batch_size)()\n if not args.run_ce:\n A_test_reader = data_reader.a_test_reader()\n B_test_reader = data_reader.b_test_reader()\n\n def test(epoch):\n out_path = args.output + \"/test\"\n if not os.path.exists(out_path):\n os.makedirs(out_path)\n i = 0\n for data_A, data_B in zip(A_test_reader(), B_test_reader()):\n A_name = data_A[1]\n B_name = data_B[1]\n tensor_A = core.LoDTensor()\n tensor_B = core.LoDTensor()\n tensor_A.set(data_A[0], place)\n tensor_B.set(data_B[0], place)\n fake_A_temp, fake_B_temp, cyc_A_temp, cyc_B_temp = exe.run(\n g_A_trainer.infer_program,\n fetch_list=[\n g_A_trainer.fake_A, g_A_trainer.fake_B, g_A_trainer.cyc_A,\n g_A_trainer.cyc_B\n ],\n feed={\"input_A\": tensor_A,\n \"input_B\": tensor_B})\n fake_A_temp = np.squeeze(fake_A_temp[0]).transpose([1, 2, 0])\n fake_B_temp = np.squeeze(fake_B_temp[0]).transpose([1, 2, 0])\n cyc_A_temp = np.squeeze(cyc_A_temp[0]).transpose([1, 2, 0])\n cyc_B_temp = np.squeeze(cyc_B_temp[0]).transpose([1, 2, 0])\n input_A_temp = np.squeeze(data_A[0]).transpose([1, 2, 0])\n input_B_temp = np.squeeze(data_B[0]).transpose([1, 2, 0])\n\n imsave(out_path + \"/fakeB_\" + str(epoch) + \"_\" + A_name, (\n (fake_B_temp + 1) * 127.5).astype(np.uint8))\n imsave(out_path + \"/fakeA_\" + str(epoch) + \"_\" + B_name, (\n (fake_A_temp + 1) * 127.5).astype(np.uint8))\n imsave(out_path + \"/cycA_\" + str(epoch) + \"_\" + A_name, (\n (cyc_A_temp + 1) * 127.5).astype(np.uint8))\n imsave(out_path + \"/cycB_\" + str(epoch) + \"_\" + B_name, (\n (cyc_B_temp + 1) * 127.5).astype(np.uint8))\n imsave(out_path + \"/inputA_\" + str(epoch) + \"_\" + A_name, (\n (input_A_temp + 1) * 127.5).astype(np.uint8))\n imsave(out_path + \"/inputB_\" + str(epoch) + \"_\" + B_name, (\n (input_B_temp + 1) * 127.5).astype(np.uint8))\n i += 1\n\n def checkpoints(epoch):\n out_path = args.output + \"/checkpoints/\" + str(epoch)\n if not os.path.exists(out_path):\n os.makedirs(out_path)\n fluid.io.save_persistables(\n exe, out_path + \"/g_a\", main_program=g_A_trainer.program, filename=\"params\")\n fluid.io.save_persistables(\n exe, out_path + \"/g_b\", main_program=g_B_trainer.program, filename=\"params\")\n fluid.io.save_persistables(\n exe, out_path + \"/d_a\", main_program=d_A_trainer.program, filename=\"params\")\n fluid.io.save_persistables(\n exe, out_path + \"/d_b\", main_program=d_B_trainer.program, filename=\"params\")\n print(\"saved checkpoint to {}\".format(out_path))\n sys.stdout.flush()\n\n def init_model():\n assert os.path.exists(\n args.init_model), \"[%s] cann't be found.\" % args.init_mode\n fluid.io.load_persistables(\n exe, args.init_model + \"/g_a\", main_program=g_A_trainer.program)\n fluid.io.load_persistables(\n exe, args.init_model + \"/g_b\", main_program=g_B_trainer.program)\n fluid.io.load_persistables(\n exe, args.init_model + \"/d_a\", main_program=d_A_trainer.program)\n fluid.io.load_persistables(\n exe, args.init_model + \"/d_b\", main_program=d_B_trainer.program)\n print(\"Load model from {}\".format(args.init_model))\n\n if args.init_model:\n init_model()\n losses=[[], []]\n t_time = 0\n for epoch in range(args.epoch):\n batch_id = 0\n for i in range(max_images_num):\n data_A = next(A_reader)\n data_B = next(B_reader)\n tensor_A = core.LoDTensor()\n tensor_B = core.LoDTensor()\n tensor_A.set(data_A, place)\n tensor_B.set(data_B, place)\n s_time = time.time()\n # optimize the g_A network\n g_A_loss, fake_B_tmp = exe.run(\n g_A_trainer.program,\n fetch_list=[g_A_trainer.g_loss_A, g_A_trainer.fake_B],\n feed={\"input_A\": tensor_A,\n \"input_B\": tensor_B})\n\n fake_pool_B = B_pool.pool_image(fake_B_tmp)\n\n # optimize the d_B network\n d_B_loss = exe.run(\n d_B_trainer.program,\n fetch_list=[d_B_trainer.d_loss_B],\n feed={\"input_B\": tensor_B,\n \"fake_pool_B\": fake_pool_B})[0]\n\n # optimize the g_B network\n g_B_loss, fake_A_tmp = exe.run(\n g_B_trainer.program,\n fetch_list=[g_B_trainer.g_loss_B, g_B_trainer.fake_A],\n feed={\"input_A\": tensor_A,\n \"input_B\": tensor_B})\n\n fake_pool_A = A_pool.pool_image(fake_A_tmp)\n\n # optimize the d_A network\n d_A_loss = exe.run(\n d_A_trainer.program,\n fetch_list=[d_A_trainer.d_loss_A],\n feed={\"input_A\": tensor_A,\n \"fake_pool_A\": fake_pool_A})[0]\n t_time += (time.time() - s_time)\n print(\"epoch{}; batch{}; g_A_loss: {}; d_B_loss: {}; g_B_loss: {}; d_A_loss: {};\".format(\n epoch, batch_id, g_A_loss[0], d_B_loss[0], g_B_loss[0],\n d_A_loss[0]))\n losses[0].append(g_A_loss[0])\n losses[1].append(d_A_loss[0])\n sys.stdout.flush()\n batch_id += 1\n\n if args.run_test and not args.run_ce:\n test(epoch)\n if args.save_checkpoints and not args.run_ce:\n checkpoints(epoch)\n if args.run_ce:\n print(\"kpis,g_train_cost,{}\".format(np.mean(losses[0])))\n print(\"kpis,d_train_cost,{}\".format(np.mean(losses[1])))\n print(\"kpis,duration,{}\".format(t_time / args.epoch))\n\n\nif __name__ == \"__main__\":\n args = parser.parse_args()\n print_arguments(args)\n if args.profile:\n if args.use_gpu:\n with profiler.cuda_profiler(\"cuda_profiler.txt\", 'csv') as nvprof:\n train(args)\n else:\n with profiler.profiler(\"CPU\", sorted_key='total') as cpuprof:\n train(args)\n else:\n train(args)\n"
] | [
[
"numpy.squeeze",
"numpy.mean",
"numpy.random.seed"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
annakuchko/FinNetwork | [
"4566ff96b33fb5668f9b28f41a94791d1cf9249c"
] | [
"finetwork/transformer/market_cycles.py"
] | [
"import pandas as pd\r\nimport numpy as np\r\nfrom finetwork.data_collector.import_data import FinData\r\nfrom finetwork.transformer.splitter import Split\r\nimport finetwork.plotter._plot_market_cycles as pmc\r\n\r\nclass MarketCycle:\r\n def __init__(self, \r\n benchmark_index,\r\n from_date, \r\n to_date, \r\n country,\r\n market,\r\n criterion='trading_day',\r\n window=6,\r\n theta_min=0.45,\r\n theta_max=0.55):\r\n \r\n self.from_date = from_date\r\n self.to_date = to_date\r\n self.country = country\r\n self.benchmark_index = benchmark_index\r\n self.market = market\r\n self.window = window\r\n self.criterion = criterion\r\n self.theta_min = theta_min\r\n self.theta_max = theta_max\r\n self.index_data = None\r\n \r\n def _import_index(self):\r\n from_date = self.from_date\r\n to_date = self.to_date\r\n benchmark_index = self.benchmark_index\r\n country = self.country\r\n market = self.market\r\n \r\n data = FinData(\r\n from_date=from_date, \r\n to_date=to_date,\r\n tickers=benchmark_index,\r\n country=country,\r\n market=market,\r\n index=True).get_data()\r\n return data\r\n \r\n def _split_data(self):\r\n window = self.window\r\n from_date = self.from_date\r\n to_date = self.to_date\r\n dat = self._import_index()\r\n data = dat[0]\r\n original_data = dat[1]\r\n dates_list = pd.to_datetime(list(data.keys()))\r\n list_of_windows = [dates_list[0]]\r\n for i in np.arange(0, len(dates_list)-window*22, window*22):\r\n start_dt = dates_list[i]\r\n end_dt = start_dt + pd.DateOffset(months=window)\r\n list_of_windows.append(end_dt)\r\n \r\n data_split = Split(\r\n data_dict=data,\r\n from_date=from_date,\r\n to_date=to_date,\r\n window_size=window\r\n ).split_index() \r\n original_data_split = Split(\r\n data_dict=original_data,\r\n from_date=from_date,\r\n to_date=to_date,\r\n window_size=window\r\n ).split_index() \r\n \r\n return data_split, original_data_split\r\n \r\n def fit(self, return_criterion_vals=False):\r\n \r\n theta_min = self.theta_min\r\n theta_max = self.theta_max\r\n \r\n dat = self._split_data()\r\n data = dat[0]\r\n orig_data = dat[1]\r\n self.index_data = data\r\n criterion = self.criterion\r\n criterion_dict = {}\r\n rd_dict = {}\r\n rf_dict = {}\r\n \r\n for i in data.keys():\r\n period_data = np.array(list(data[i].values()))\r\n period_data = period_data[~np.isnan(period_data)]\r\n \r\n rd = (period_data>0).sum() / len(period_data)\r\n rd_dict[i] = rd\r\n \r\n rf = np.abs(\r\n period_data[period_data>0]\r\n ).sum() / np.abs(\r\n period_data\r\n ).sum()\r\n rf_dict[i] = rf\r\n if criterion == 'trading_day': \r\n if rd > theta_max:\r\n criterion_val='markup'\r\n elif rd < theta_min:\r\n criterion_val='markdown'\r\n else:\r\n criterion_val='flat'\r\n \r\n elif criterion == 'amplitude':\r\n if rf > theta_max:\r\n criterion_val='markup' \r\n elif rf < theta_min:\r\n criterion_val='markdown'\r\n else:\r\n criterion_val='flat'\r\n \r\n elif criterion == 'and':\r\n if rd > theta_max and rf > theta_max:\r\n criterion_val = 'markup'\r\n elif rd < theta_min and rf < theta_min:\r\n criterion_val = 'markdown'\r\n else:\r\n criterion_val = 'flat'\r\n\r\n elif criterion == 'or':\r\n if rd > theta_max or rf > theta_max:\r\n criterion_val = 'markup'\r\n elif rd < theta_min or rf < theta_min:\r\n criterion_val = 'markdown'\r\n else:\r\n criterion_val = 'flat'\r\n \r\n criterion_dict[i] = criterion_val\r\n list_of_periods = list(criterion_dict.keys())\r\n \r\n for i in np.arange(0, len(list_of_periods)):\r\n period = list_of_periods[i]\r\n \r\n if i == 0 and criterion_dict[period]=='flat':\r\n criterion_dict[period] = 'accumulation'\r\n else:\r\n prev_period = list_of_periods[i-1]\r\n \r\n if criterion_dict[period] == 'flat' and\\\r\n criterion_dict[prev_period]=='markup':\r\n criterion_dict[period] = 'accumulation'\r\n elif criterion_dict[period] == 'flat' and\\\r\n criterion_dict[prev_period]=='accumulation':\r\n criterion_dict[period] = 'accumulation'\r\n elif criterion_dict[period] == 'flat' and\\\r\n criterion_dict[prev_period]=='markdown':\r\n criterion_dict[period] = 'distribution'\r\n elif criterion_dict[period] == 'flat' and\\\r\n criterion_dict[prev_period]=='distribution':\r\n criterion_dict[period] = 'distribution'\r\n if return_criterion_vals:\r\n return rd_dict, rf_dict\r\n else:\r\n return criterion_dict, orig_data\r\n\r\n def plot_cycles(self):\r\n data = self.fit(return_criterion_vals=True)\r\n pmc._plot_cycles(data,\r\n self.theta_min, \r\n self.theta_max, \r\n self.window, \r\n self.benchmark_index)\r\n \r\n def plot_index_with_cycles(self, name=None, save=False):\r\n data = self.fit(return_criterion_vals=False)\r\n pmc._plot_index_with_market_cycles(data[0],\r\n data[1], \r\n self.benchmark_index,\r\n self.criterion,\r\n self.window,\r\n self.from_date,\r\n self.to_date,\r\n name,\r\n save)\r\n"
] | [
[
"numpy.isnan",
"pandas.DateOffset",
"numpy.abs"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"0.19",
"0.24",
"0.20",
"1.0",
"0.25"
],
"scipy": [],
"tensorflow": []
}
] |
GuQiangJS/LSTM-for-Stock | [
"3bae9e5075f5c612a125726777c8275e805ccd9e"
] | [
"samples/jupyter_helper.py"
] | [
"import os\nimport sys\nimport time\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\n# import wmi\nfrom keras.backend import clear_session\nfrom scipy import stats\n\nfrom LSTM_for_Stock.data_processor import DataHelper\nfrom LSTM_for_Stock.data_processor import DataLoaderStock\nfrom LSTM_for_Stock.data_processor import Normalize\nfrom LSTM_for_Stock.data_processor import Wrapper_default\nfrom LSTM_for_Stock.loss import root_mean_squared_error\nfrom LSTM_for_Stock.model import SequentialModel\n\nnb_dir = os.path.split(os.getcwd())[0]\nif nb_dir not in sys.path:\n sys.path.append(nb_dir)\n\nmatplotlib.rcParams[\"figure.figsize\"] = [16, 5]\nmatplotlib.rcParams['font.family'] = 'sans-serif'\nmatplotlib.rcParams['font.sans-serif'] = ['Noto Sans CJK SC', 'SimHei']\nmatplotlib.rcParams['axes.unicode_minus'] = False # 用来正常显示负号\\n\n\n\n# def print_system_info():\n# computer = wmi.WMI()\n# computer_info = computer.Win32_ComputerSystem()[0]\n# os_info = computer.Win32_OperatingSystem()[0]\n# proc_info = computer.Win32_Processor()[0]\n# gpu_info = computer.Win32_VideoController()[0]\n\n# os_name = os_info.Name.encode('utf-8').split(b'|')[0]\n# os_version = ' '.join([os_info.Version, os_info.BuildNumber])\n# system_ram = float(os_info.TotalVisibleMemorySize) / 1048576 # KB to GB\n\n# print('OS Name: {0}'.format(os_name))\n# print('OS Version: {0}'.format(os_version))\n# print('CPU: {0}'.format(proc_info.Name))\n# print('RAM: {0} GB'.format(system_ram))\n# print('Graphics Card: {0}'.format(gpu_info.Name))\n\n\ndef do(code='000002',\n window=3,\n days=1,\n wrapper=Wrapper_default(),\n norm=Normalize(),\n *args,\n **kwargs):\n \"\"\"\n\n Args:\n layers [dict]: 训练层定义。默认为LSTM。第一层的`input_shape`和最后一层的`unit`会自动设置。\n\n \"\"\"\n dl = DataLoaderStock(\n code, wrapper=wrapper, appends=kwargs.pop('appends', []))\n df = dl.load()\n # print(df.head(window+2))\n train, test = DataHelper.train_test_split(df, batch_size=window + days,train_size=kwargs.pop('train_size',0.85))\n # print(train[0])\n X_train, Y_train = DataHelper.xy_split_2(train, window, days, norm=norm)\n X_test, Y_test = DataHelper.xy_split_2(test, window, days, norm=norm)\n # print(X_train[0])\n # print(Y_train[0])\n # print(X_test[0])\n # print(Y_test[0])\n batch_size = kwargs.pop('batch_size', 128)\n verbose = kwargs.pop('verbose', 0)\n\n X_train_arr = []\n Y_train_arr = []\n for x in X_train:\n X_train_arr.append(x.values)\n for y in Y_train:\n Y_train_arr.append(y.values)\n X_test_arr = []\n Y_test_arr = []\n for x in X_test:\n X_test_arr.append(x.values)\n for y in Y_test:\n Y_test_arr.append(y.values)\n\n clear_session()\n model = SequentialModel()\n # https://www.researchgate.net/publication/327967988_Predicting_Stock_Prices_Using_LSTM\n # For analyzing the efficiency of the system we are used the\n # Root Mean Square Error(RMSE). The error or the difference between\n # the target and the obtained output value is minimized by\n # using RMSE value. RMSE is the square root of the mean/average of the\n # square of all of the error. The use of RMSE is highly common and\n # it makes an excellent general purpose error metric for\n # numerical predictions. Compared to the similar Mean Absolute Error,\n # RMSE amplifies and severely punishes large errors.\n\n ls = kwargs.pop(\"layers\", [])\n c = kwargs.pop('compile', {'loss': root_mean_squared_error,\n 'optimizer': 'rmsprop',\n 'metrics': [\"mae\", \"acc\"]})\n if not ls:\n ls.append({'type': 'lstm', 'units': 128})\n ls.append({'type': 'dense'})\n ls[0]['input_shape'] = X_train_arr[0].shape\n ls[-1]['units'] = days\n\n start = time.time()\n model.build_model(ls, c)\n\n model.train(np.array(X_train_arr),\n np.array(Y_train_arr), callbacks=kwargs.pop('cbs', None),\n train={'epochs': kwargs.pop('epochs', 500),\n 'shuffle': kwargs.pop('shuffle', False),\n 'verbose': verbose,\n 'batch_size': batch_size,\n 'validation_split': kwargs.pop('validation_split',\n 0.15)})\n\n # history = model.fit(\n # np.array(X_train_arr),\n # np.array(Y_train_arr),\n # epochs=kwargs.pop('epochs', 500),\n # shuffle=kwargs.pop('shuffle', False),\n # verbose=verbose,\n # batch_size=batch_size,\n # validation_split=kwargs.pop('validation_split', 0.15),\n # callbacks=cbs)\n if kwargs.pop('summary', True):\n model.model.summary()\n end = time.time()\n return {\n 'start': start,\n 'end': end,\n 'X_test_arr': X_test_arr,\n 'Y_test_arr': Y_test_arr,\n 'model': model.model,\n 'code': code,\n 'window': window,\n 'days': days,\n 'batch_size': batch_size,\n 'history': model.history,\n 'data': df,\n 'X_train': X_train,\n 'Y_train': Y_train,\n 'X_test': X_test,\n 'Y_test': Y_test\n }\n\n\ndef show_history(h, *args, **kwargs):\n start = h['start']\n end = h['end']\n X_test_arr = h['X_test_arr']\n Y_test_arr = h['Y_test_arr']\n model = h['model']\n code = h['code']\n window = h['window']\n days = h['days']\n batch_size = h['batch_size']\n history = h['history']\n\n print('Net time using : ', end - start, ' secs.')\n\n score = model.evaluate(np.array(X_test_arr), np.array(Y_test_arr))\n\n if kwargs.pop('print_score', True):\n print(\"Score:\")\n for i in range(len(model.metrics_names)):\n print(' {0}:{1}'.format(model.metrics_names[i], score[i]))\n\n show_plt = kwargs.pop('show_plt', True)\n\n if show_plt:\n plt.figure(figsize=(15, 8))\n\n # 绘制训练 & 验证的准确率值\n plt.plot(history.history['acc'])\n plt.plot(history.history['val_acc'])\n plt.title('Model accuracy')\n plt.ylabel('Accuracy')\n plt.xlabel('Epoch')\n plt.legend(['Train', 'Test'], loc='upper left')\n plt.show()\n\n plt.figure(figsize=(15, 8))\n # 绘制训练 & 验证的损失值\n plt.plot(history.history['loss'])\n plt.plot(history.history['val_loss'])\n plt.title('Model loss')\n plt.ylabel('Loss')\n plt.xlabel('Epoch')\n plt.legend(['Train', 'Test'], loc='upper left')\n plt.show()\n\n pred = model.predict(np.array(X_test_arr))\n pred_slope = []\n for day in range(days):\n df_result = pd.DataFrame({\n 'pred': pred[:, day],\n 'real': np.array(Y_test_arr)[:, day]\n })\n\n if show_plt:\n plt.figure(figsize=(15, 8))\n plt.title(\n '预测。code={0},window={1},day={2}/{3},batch_size={4}'.format(\n code, window, day + 1, days, batch_size))\n plt.plot(df_result['pred'])\n plt.plot(df_result['real'])\n plt.show()\n\n sns.regplot(x=pred[:, day], y=np.array(Y_test_arr)[:, day])\n plt.show()\n slope = stats.linregress(pred[:, day],\n np.array(Y_test_arr)[:, day]).slope\n # print('Slope Day{0}:{1}'.format(day + 1, slope))\n pred_slope.append(slope)\n plt.close('all')\n\n return {\n 'score': score,\n 'pred': pred,\n 'real': np.array(Y_test_arr),\n 'slope': pred_slope\n }\n"
] | [
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.title",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.close",
"matplotlib.pyplot.xlabel",
"numpy.array",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
fangfy/wofs | [
"504cb53bfc33c9a667fafba99f2160c0ddcb281c"
] | [
"wofs/terrain.py"
] | [
"import math\n\nimport ephem\nimport numpy\nimport xarray\nfrom datacube.utils.geometry import CRS, line\nfrom pandas import to_datetime\nfrom scipy import ndimage\n\nUNKNOWN = -1\nLIT = 255\nSHADED = 0\n\n\ndef _shade_row(shade_mask, elev_m, sun_alt_deg, pixel_scale_m, no_data, fuzz=0.0):\n \"\"\"\n shade the supplied row of the elevation model\n \"\"\"\n\n # threshold is TAN of sun's altitude\n tan_sun_alt = math.tan(sun_alt_deg)\n\n # pure terrain angle shadow\n shade_mask[0] = LIT\n shade_mask[1:] = numpy.where((elev_m[:-1] - elev_m[1:]) / pixel_scale_m < tan_sun_alt, LIT, SHADED)\n\n # project shadows from tips (light->shadow transition)\n switch = numpy.where(shade_mask[:-1] != shade_mask[1:])\n for i in switch[0]: # note: could use flatnonzero instead of where; or else switch,=; to avoid [0]. --BL\n if shade_mask[i] == LIT:\n # TODO: horizontal fuzz?\n shadow_level = (elev_m[i] + fuzz) - numpy.arange(shade_mask.size - i) * (tan_sun_alt * pixel_scale_m)\n shade_mask[i:][shadow_level > elev_m[i:]] = SHADED\n\n shade_mask[elev_m == no_data] = UNKNOWN\n\n return shade_mask\n\n\ndef vector_to_crs(point, vector, original_crs, destination_crs):\n \"\"\"\n Transform a vector (in the tangent space of a particular point) to a new CRS\n\n Expects point and vector to each be a 2-tuple in the original CRS.\n Returns a pair of 2-tuples (transformed point and vector).\n Order of coordinates is specified by the CRS (or the OGR library).\n \"\"\"\n # pylint: disable=zip-builtin-not-iterating\n # theoretically should use infinitesimal displacement\n # i.e. jacobian of the transformation\n # but here just use a finite displatement (for convenience of implementation)\n original_line = line([point, tuple(map(sum, zip(point, vector)))], crs=original_crs)\n transformed_line = original_line.to_crs(destination_crs)\n\n transformed_point, transformed_end = transformed_line.points\n\n # take difference (i.e. remove origin offset)\n transformed_vector = tuple(map(lambda x: x[1] - x[0], zip(*transformed_line.points)))\n return transformed_point, transformed_vector\n\n\ndef solar_vector(point, time, crs):\n (lon, lat), (dlon, dlat) = vector_to_crs(point, (0, 100),\n original_crs=CRS(crs),\n destination_crs=CRS('EPSG:4326'))\n\n # azimuth north to east of the vertical direction of the crs\n vert_az = math.atan2(dlon * math.cos(math.radians(lat)), dlat)\n\n observer = ephem.Observer()\n # pylint: disable=assigning-non-slot\n observer.lat = math.radians(lat)\n observer.lon = math.radians(lon)\n observer.date = time\n sun = ephem.Sun(observer)\n\n sun_az = sun.az - vert_az\n x = math.sin(sun_az) * math.cos(sun.alt)\n y = -math.cos(sun_az) * math.cos(sun.alt)\n z = math.sin(sun.alt)\n\n return x, y, z, sun_az, sun.alt\n\n\n# pylint: disable=too-many-locals\ndef shadows_and_slope(tile, time):\n \"\"\"\n Terrain shadow masking (Greg's implementation) and slope masking.\n\n Input: Digital Surface Model xarray DataSet (need metadata e.g. resolution, CRS)\n\n Uses Sobel filter to estimate the slope gradients (assuming raster is non-rotated wrt. crs) and magnitude.\n Ignores curvature of earth (picking middle of tile for solar elevation and azimuth) calculating surface incidence.\n Reprojects (rotates/resamples) DSM to align rows with shadows (at 25m resolution,\n and assuming the input projection is Mercator-like i.e. preserves bearings).\n For each row, finds each threshold pixel (where the slope just turns away from the sun) and raytraces\n (i.e. using a ramp, masks the other pixels shaded by the pillar of that pixel).\n Reprojects shadow mask (and undoes border enlargement associated with the rotation).\n\n TODO (BL) -- profile, and explore numpy.minimum.accumulate (make-monotonic) style alternative\n and maybe fewer resamplings (or come up with something better still).\n \"\"\"\n\n y_size, x_size = tile.elevation.shape\n\n # row spacing\n pixel_scale_m = abs(tile.affine.e)\n\n # gradient and slope\n xgrad = ndimage.sobel(tile.elevation, axis=1) / abs(8 * tile.affine.a)\n ygrad = ndimage.sobel(tile.elevation, axis=0) / abs(8 * tile.affine.e)\n\n # length of the terrain normal vector\n norm_len = numpy.sqrt((xgrad * xgrad) + (ygrad * ygrad) + 1.0)\n\n # hypot = numpy.hypot(xgrad, ygrad)\n # slope = numpy.degrees(numpy.arctan(hypot))\n\n slope = numpy.degrees(numpy.arccos(1.0 / norm_len))\n\n x, y = tile.dims.keys()\n tile_center = (tile[x].values[x_size // 2], tile[y].values[y_size // 2])\n solar_vec = solar_vector(tile_center, to_datetime(time), tile.crs)\n sia = (solar_vec[2] - (xgrad * solar_vec[0]) - (ygrad * solar_vec[1])) / norm_len\n sia = 90 - numpy.degrees(numpy.arccos(sia))\n\n # # TODO: water_band=SolarTerrainShadowSlope(self.dsm_path).filter(water_band)\n rot_degrees = 90.0 + math.degrees(solar_vec[3])\n sun_alt_deg = math.degrees(solar_vec[4])\n # print solar_vec, rot_degrees, sun_alt_deg\n no_data = -1000\n\n buff_elv_array = numpy.pad(tile.elevation.values, 4, mode='edge')\n rotated_elv_array = ndimage.interpolation.rotate(buff_elv_array,\n rot_degrees,\n reshape=True,\n output=numpy.float32,\n cval=no_data,\n prefilter=False)\n\n # create the shadow mask by ray-tracying along each row\n shadows = numpy.zeros_like(rotated_elv_array)\n for row in range(0, rotated_elv_array.shape[0]):\n _shade_row(shadows[row], rotated_elv_array[row], solar_vec[4], pixel_scale_m, no_data, fuzz=10.0)\n\n del rotated_elv_array\n del buff_elv_array\n\n shadows = ndimage.interpolation.rotate(shadows, -rot_degrees, reshape=False, output=numpy.float32, cval=no_data,\n prefilter=False)\n\n dr = (shadows.shape[0] - y_size) // 2\n dc = (shadows.shape[1] - x_size) // 2\n\n shadows = shadows[dr:dr + y_size, dc:dc + x_size]\n shadows = xarray.DataArray(shadows.reshape(tile.elevation.shape), coords=tile.elevation.coords)\n\n return shadows, slope, sia\n"
] | [
[
"pandas.to_datetime",
"numpy.sqrt",
"numpy.pad",
"numpy.arange",
"scipy.ndimage.sobel",
"numpy.arccos",
"scipy.ndimage.interpolation.rotate",
"numpy.zeros_like",
"numpy.where"
]
] | [
{
"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",
"0.15",
"1.4",
"0.10",
"1.3",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"0.12",
"1.0",
"0.17",
"0.16"
],
"tensorflow": []
}
] |
shjoshi/vispy | [
"2f3d169aa60c738467e766c59096f51570483d6f",
"2f3d169aa60c738467e766c59096f51570483d6f"
] | [
"vispy/util/tests/test_dataio.py",
"examples/demo/gloo/boids.py"
] | [
"import numpy as np\nfrom os import path as op\nfrom nose.tools import assert_equal, assert_raises\nfrom numpy.testing import assert_allclose, assert_array_equal\nimport warnings\n\nfrom vispy.util.dataio import write_mesh, read_mesh, crate, imsave, imread\nfrom vispy.util._geom import _fast_cross_3d\nfrom vispy.util import _TempDir\nfrom vispy.testing import requires_img_lib\n\ntemp_dir = _TempDir()\n\n\ndef test_wavefront():\n \"\"\"Test wavefront reader\"\"\"\n fname_mesh = 'triceratops.obj'\n\n fname_out = op.join(temp_dir, 'temp.obj')\n mesh1 = read_mesh(fname_mesh)\n assert_raises(ValueError, read_mesh, 'foo')\n assert_raises(ValueError, read_mesh, op.abspath(__file__))\n assert_raises(ValueError, write_mesh, fname_out, mesh1[0], mesh1[1],\n mesh1[2], mesh1[3], format='foo')\n write_mesh(fname_out, mesh1[0], mesh1[1], mesh1[2], mesh1[3])\n assert_raises(IOError, write_mesh, fname_out, mesh1[0], mesh1[1],\n mesh1[2], mesh1[3])\n write_mesh(fname_out, mesh1[0], mesh1[1], mesh1[2], mesh1[3],\n overwrite=True)\n mesh2 = read_mesh(fname_out)\n assert_equal(len(mesh1), len(mesh2))\n for m1, m2 in zip(mesh1, mesh2):\n if m1 is None:\n assert_equal(m2, None)\n else:\n assert_allclose(m1, m2)\n # test our efficient normal calculation routine\n assert_allclose(mesh1[2], _slow_calculate_normals(mesh1[0], mesh1[1]),\n rtol=1e-10, atol=1e-10)\n\n\n@requires_img_lib()\ndef test_read_write_image():\n \"\"\"Test reading and writing of images\"\"\"\n fname = op.join(temp_dir, 'out.png')\n im1 = crate()\n imsave(fname, im1, format='png')\n with warnings.catch_warnings(record=True): # PIL unclosed file\n im2 = imread(fname)\n assert_allclose(im1, im2)\n\n\ndef _slow_calculate_normals(rr, tris):\n \"\"\"Efficiently compute vertex normals for triangulated surface\"\"\"\n # first, compute triangle normals\n rr = rr.astype(np.float64)\n r1 = rr[tris[:, 0], :]\n r2 = rr[tris[:, 1], :]\n r3 = rr[tris[:, 2], :]\n tri_nn = np.cross((r2 - r1), (r3 - r1))\n\n # Triangle normals and areas\n size = np.sqrt(np.sum(tri_nn * tri_nn, axis=1))\n zidx = np.where(size == 0)[0]\n size[zidx] = 1.0 # prevent ugly divide-by-zero\n tri_nn /= size[:, np.newaxis]\n\n # accumulate the normals\n nn = np.zeros((len(rr), 3))\n for p, verts in enumerate(tris):\n nn[verts] += tri_nn[p, :]\n size = np.sqrt(np.sum(nn * nn, axis=1))\n size[size == 0] = 1.0 # prevent ugly divide-by-zero\n nn /= size[:, np.newaxis]\n return nn\n\n\ndef test_huge_cross():\n \"\"\"Test cross product with lots of elements\n \"\"\"\n x = np.random.rand(100000, 3)\n y = np.random.rand(1, 3)\n z = np.cross(x, y)\n zz = _fast_cross_3d(x, y)\n assert_array_equal(z, zz)\n",
"# !/usr/bin/env python\n# -*- coding: utf-8 -*-\n# vispy: gallery 30\n\n\"\"\"\nDemonstration of boids simulation. Boids is an artificial life\nprogram, developed by Craig Reynolds in 1986, which simulates the\nflocking behaviour of birds.\nBased on code from glumpy by Nicolas Rougier.\n\"\"\"\n\nimport time\n\nimport numpy as np\nfrom scipy.spatial import cKDTree\n\nfrom vispy import gloo\nfrom vispy import app\n\n# Create boids\nn = 1000\nparticles = np.zeros(2 + n, [('position', 'f4', 3),\n ('position_1', 'f4', 3),\n ('position_2', 'f4', 3),\n ('velocity', 'f4', 3),\n ('color', 'f4', 4),\n ('size', 'f4', 1)])\nboids = particles[2:]\ntarget = particles[0]\npredator = particles[1]\n\nboids['position'] = np.random.uniform(-0.25, +0.25, (n, 3))\nboids['velocity'] = np.random.uniform(-0.00, +0.00, (n, 3))\nboids['size'] = 4\nboids['color'] = 1, 1, 1, 1\n\ntarget['size'] = 16\ntarget['color'][:] = 1, 1, 0, 1\npredator['size'] = 16\npredator['color'][:] = 1, 0, 0, 1\ntarget['position'][:] = 0.25, 0.0, 0\n\nVERT_SHADER = \"\"\"\n#version 120\nattribute vec3 position;\nattribute vec4 color;\nattribute float size;\n\nvarying vec4 v_color;\nvoid main (void) {\n gl_Position = vec4(position, 1.0);\n v_color = color;\n gl_PointSize = size;\n}\n\"\"\"\n\nFRAG_SHADER = \"\"\"\n#version 120\nvarying vec4 v_color;\nvoid main()\n{\n float x = 2.0*gl_PointCoord.x - 1.0;\n float y = 2.0*gl_PointCoord.y - 1.0;\n float a = 1.0 - (x*x + y*y);\n gl_FragColor = vec4(v_color.rgb, a*v_color.a);\n}\n\n\"\"\"\n\n\nclass Canvas(app.Canvas):\n\n def __init__(self):\n app.Canvas.__init__(self, close_keys='escape')\n\n # Time\n self._t = time.time()\n self._pos = 0.0, 0.0\n self._button = None\n\n # Create program\n self.program = gloo.Program(VERT_SHADER, FRAG_SHADER)\n\n # Create vertex buffers\n self.vbo_position = gloo.VertexBuffer(particles['position'])\n self.vbo_color = gloo.VertexBuffer(particles['color'])\n self.vbo_size = gloo.VertexBuffer(particles['size'])\n\n # Bind vertex buffers\n self.program['color'] = self.vbo_color\n self.program['size'] = self.vbo_size\n self.program['position'] = self.vbo_position\n\n def on_initialize(self, event):\n gloo.set_state(clear_color=(0, 0, 0, 1), blend=True,\n blend_func=('src_alpha', 'one'))\n\n def on_resize(self, event):\n width, height = event.size\n gloo.set_viewport(0, 0, width, height)\n\n def on_mouse_press(self, event):\n self._button = event.button\n self.on_mouse_move(event)\n\n def on_mouse_release(self, event):\n self._button = None\n self.on_mouse_move(event)\n\n def on_mouse_move(self, event):\n if not self._button:\n return\n w, h = self.size\n x, y = event.pos\n sx = 2 * x / float(w) - 1.0\n sy = - (2 * y / float(h) - 1.0)\n\n if self._button == 1:\n target['position'][:] = sx, sy, 0\n elif self._button == 2:\n predator['position'][:] = sx, sy, 0\n\n def on_draw(self, event):\n gloo.clear()\n\n # Draw\n self.program.draw('points')\n\n # Next iteration\n self._t = self.iteration(time.time() - self._t)\n\n # Invoke a new draw\n self.update()\n\n def iteration(self, dt):\n t = self._t\n\n t += 0.5 * dt\n #target[...] = np.array([np.sin(t),np.sin(2*t),np.cos(3*t)])*.1\n\n t += 0.5 * dt\n #predator[...] = np.array([np.sin(t),np.sin(2*t),np.cos(3*t)])*.2\n\n boids['position_2'] = boids['position_1']\n boids['position_1'] = boids['position']\n n = len(boids)\n P = boids['position']\n V = boids['velocity']\n\n # Cohesion: steer to move toward the average position of local\n # flockmates\n C = -(P - P.sum(axis=0) / n)\n\n # Alignment: steer towards the average heading of local flockmates\n A = -(V - V.sum(axis=0) / n)\n\n # Repulsion: steer to avoid crowding local flockmates\n D, I = cKDTree(P).query(P, 5)\n M = np.repeat(D < 0.05, 3, axis=1).reshape(n, 5, 3)\n Z = np.repeat(P, 5, axis=0).reshape(n, 5, 3)\n R = -((P[I] - Z) * M).sum(axis=1)\n\n # Target : Follow target\n T = target['position'] - P\n\n # Predator : Move away from predator\n dP = P - predator['position']\n D = np.maximum(0, 0.3 -\n np.sqrt(dP[:, 0] ** 2 +\n dP[:, 1] ** 2 +\n dP[:, 2] ** 2))\n D = np.repeat(D, 3, axis=0).reshape(n, 3)\n dP *= D\n\n #boids['velocity'] += 0.0005*C + 0.01*A + 0.01*R + 0.0005*T + 0.0025*dP\n boids['velocity'] += 0.0005 * C + 0.01 * \\\n A + 0.01 * R + 0.0005 * T + 0.025 * dP\n boids['position'] += boids['velocity']\n\n self.vbo_position.set_data(particles['position'])\n\n return t\n\n\nif __name__ == '__main__':\n c = Canvas()\n c.show()\n app.run()\n"
] | [
[
"numpy.testing.assert_array_equal",
"numpy.random.rand",
"numpy.cross",
"numpy.where",
"numpy.sum",
"numpy.testing.assert_allclose"
],
[
"numpy.sqrt",
"numpy.random.uniform",
"numpy.repeat",
"numpy.zeros",
"scipy.spatial.cKDTree"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
orchardbirds/bokbokbok | [
"3a8c52b7e2f6f80b803ff2e7073f3cfbf8f76b6c"
] | [
"bokbokbok/loss_functions/regression/regression_loss_functions.py"
] | [
"import numpy as np\n\n\ndef LogCoshLoss():\n \"\"\"\n [Log Cosh Loss](https://openreview.net/pdf?id=rkglvsC9Ym) is an alternative to Mean Absolute Error.\n \"\"\"\n\n def _gradient(yhat, dtrain):\n \"\"\"Compute the log cosh gradient.\n\n Args:\n yhat (np.array): Predictions\n dtrain: The XGBoost / LightGBM dataset\n\n Returns:\n log cosh gradient\n \"\"\"\n\n y = dtrain.get_label()\n return -np.tanh(y - yhat)\n\n def _hessian(yhat, dtrain):\n \"\"\"Compute the log cosh hessian.\n\n Args:\n yhat (np.array): Predictions\n dtrain: The XGBoost / LightGBM dataset\n\n Returns:\n log cosh Hessian\n \"\"\"\n\n y = dtrain.get_label()\n return 1. / np.power(np.cosh(y - yhat), 2)\n\n def log_cosh_loss(\n yhat,\n dtrain\n ):\n \"\"\"\n Calculate gradient and hessian for log cosh loss.\n\n Args:\n yhat (np.array): Predictions\n dtrain: The XGBoost / LightGBM dataset\n\n Returns:\n grad: log cosh loss gradient\n hess: log cosh loss Hessian\n \"\"\"\n grad = _gradient(yhat, dtrain)\n\n hess = _hessian(yhat, dtrain)\n\n return grad, hess\n\n return log_cosh_loss\n\n\ndef SPELoss():\n \"\"\"\n Squared Percentage Error loss\n \"\"\"\n\n def _gradient(yhat, dtrain):\n \"\"\"\n Compute the gradient squared percentage error.\n Args:\n yhat (np.array): Predictions\n dtrain: The XGBoost / LightGBM dataset\n\n Returns:\n SPE Gradient\n \"\"\"\n y = dtrain.get_label()\n return -2*(y-yhat)/(y**2)\n\n def _hessian(yhat, dtrain):\n \"\"\"\n Compute the hessian for squared percentage error.\n Args:\n yhat (np.array): Predictions\n dtrain: The XGBoost / LightGBM dataset\n\n Returns:\n SPE Hessian\n \"\"\"\n y = dtrain.get_label()\n return 2/(y**2)\n\n def squared_percentage(yhat, dtrain):\n \"\"\"\n Calculate gradient and hessian for squared percentage error.\n\n Args:\n yhat (np.array): Predictions\n dtrain: The XGBoost / LightGBM dataset\n\n Returns:\n grad: SPE loss gradient\n hess: SPE loss Hessian\n \"\"\"\n #yhat[yhat < -1] = -1 + 1e-6\n grad = _gradient(yhat, dtrain)\n\n hess = _hessian(yhat, dtrain)\n\n return grad, hess\n\n return squared_percentage"
] | [
[
"numpy.tanh",
"numpy.cosh"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jeffrey-hokanson/scipy | [
"ac75879731ff3a40853263f00f51419ab7a11d49"
] | [
"scipy/sparse/linalg/dsolve/linsolve.py"
] | [
"from __future__ import division, print_function, absolute_import\n\nfrom warnings import warn\n\nimport numpy as np\nfrom numpy import asarray, empty, ravel, nonzero\nfrom scipy.sparse import (isspmatrix_csc, isspmatrix_csr, isspmatrix,\n SparseEfficiencyWarning, csc_matrix)\n\nfrom . import _superlu\n\nnoScikit = False\ntry:\n import scikits.umfpack as umfpack\nexcept ImportError:\n noScikit = True\n\nuseUmfpack = not noScikit\n\n__all__ = ['use_solver', 'spsolve', 'splu', 'spilu', 'factorized',\n 'MatrixRankWarning']\n\n\nclass MatrixRankWarning(UserWarning):\n pass\n\n\ndef use_solver(**kwargs):\n \"\"\"\n Select default sparse direct solver to be used.\n\n Parameters\n ----------\n useUmfpack : bool, optional\n Use UMFPACK over SuperLU. Has effect only if scikits.umfpack is\n installed. Default: True\n\n Notes\n -----\n The default sparse solver is umfpack when available\n (scikits.umfpack is installed). This can be changed by passing\n useUmfpack = False, which then causes the always present SuperLU\n based solver to be used.\n\n Umfpack requires a CSR/CSC matrix to have sorted column/row indices. If\n sure that the matrix fulfills this, pass ``assumeSortedIndices=True``\n to gain some speed.\n\n \"\"\"\n if 'useUmfpack' in kwargs:\n globals()['useUmfpack'] = kwargs['useUmfpack']\n\n #TODO: pass other options to scikit\n\ndef _get_umf_family(A):\n \"\"\"Get umfpack family string given the sparse matrix dtype.\"\"\"\n family = {'di': 'di', 'Di': 'zi', 'dl': 'dl', 'Dl': 'zl'}\n dt = A.dtype.char + A.indices.dtype.char\n return family[dt]\n\ndef spsolve(A, b, permc_spec=None, use_umfpack=True):\n \"\"\"Solve the sparse linear system Ax=b, where b may be a vector or a matrix.\n\n Parameters\n ----------\n A : ndarray or sparse matrix\n The square matrix A will be converted into CSC or CSR form\n b : ndarray or sparse matrix\n The matrix or vector representing the right hand side of the equation.\n If a vector, b.shape must be (n,) or (n, 1).\n permc_spec : str, optional\n How to permute the columns of the matrix for sparsity preservation.\n (default: 'COLAMD')\n\n - ``NATURAL``: natural ordering.\n - ``MMD_ATA``: minimum degree ordering on the structure of A^T A.\n - ``MMD_AT_PLUS_A``: minimum degree ordering on the structure of A^T+A.\n - ``COLAMD``: approximate minimum degree column ordering\n use_umfpack : bool, optional\n if True (default) then use umfpack for the solution. This is\n only referenced if b is a vector and ``scikit-umfpack`` is installed.\n\n Returns\n -------\n x : ndarray or sparse matrix\n the solution of the sparse linear equation.\n If b is a vector, then x is a vector of size A.shape[1]\n If b is a matrix, then x is a matrix of size (A.shape[1], b.shape[1])\n\n Notes\n -----\n For solving the matrix expression AX = B, this solver assumes the resulting\n matrix X is sparse, as is often the case for very sparse inputs. If the\n resulting X is dense, the construction of this sparse result will be\n relatively expensive. In that case, consider converting A to a dense\n matrix and using scipy.linalg.solve or its variants.\n \"\"\"\n if not (isspmatrix_csc(A) or isspmatrix_csr(A)):\n A = csc_matrix(A)\n warn('spsolve requires A be CSC or CSR matrix format',\n SparseEfficiencyWarning)\n\n # b is a vector only if b have shape (n,) or (n, 1)\n b_is_sparse = isspmatrix(b)\n if not b_is_sparse:\n b = asarray(b)\n b_is_vector = ((b.ndim == 1) or (b.ndim == 2 and b.shape[1] == 1))\n\n A.sort_indices()\n A = A.asfptype() # upcast to a floating point format\n\n # validate input shapes\n M, N = A.shape\n if (M != N):\n raise ValueError(\"matrix must be square (has shape %s)\" % ((M, N),))\n\n if M != b.shape[0]:\n raise ValueError(\"matrix - rhs dimension mismatch (%s - %s)\"\n % (A.shape, b.shape[0]))\n\n use_umfpack = use_umfpack and useUmfpack\n\n if b_is_vector and use_umfpack:\n if b_is_sparse:\n b_vec = b.toarray()\n else:\n b_vec = b\n b_vec = asarray(b_vec, dtype=A.dtype).ravel()\n\n if noScikit:\n raise RuntimeError('Scikits.umfpack not installed.')\n\n if A.dtype.char not in 'dD':\n raise ValueError(\"convert matrix data to double, please, using\"\n \" .astype(), or set linsolve.useUmfpack = False\")\n\n umf = umfpack.UmfpackContext(_get_umf_family(A))\n x = umf.linsolve(umfpack.UMFPACK_A, A, b_vec,\n autoTranspose=True)\n else:\n if b_is_vector and b_is_sparse:\n b = b.toarray()\n b_is_sparse = False\n\n if not b_is_sparse:\n if isspmatrix_csc(A):\n flag = 1 # CSC format\n else:\n flag = 0 # CSR format\n\n options = dict(ColPerm=permc_spec)\n x, info = _superlu.gssv(N, A.nnz, A.data, A.indices, A.indptr,\n b, flag, options=options)\n if info != 0:\n warn(\"Matrix is exactly singular\", MatrixRankWarning)\n x.fill(np.nan)\n if b_is_vector:\n x = x.ravel()\n else:\n # b is sparse\n Afactsolve = factorized(A)\n\n if not isspmatrix_csc(b):\n warn('spsolve is more efficient when sparse b '\n 'is in the CSC matrix format', SparseEfficiencyWarning)\n b = csc_matrix(b)\n\n # Create a sparse output matrix by repeatedly applying\n # the sparse factorization to solve columns of b.\n data_segs = []\n row_segs = []\n col_segs = []\n for j in range(b.shape[1]):\n bj = b[:, j].A.ravel()\n xj = Afactsolve(bj)\n w = np.flatnonzero(xj)\n segment_length = w.shape[0]\n row_segs.append(w)\n col_segs.append(np.ones(segment_length, dtype=int)*j)\n data_segs.append(np.asarray(xj[w], dtype=A.dtype))\n sparse_data = np.concatenate(data_segs)\n sparse_row = np.concatenate(row_segs)\n sparse_col = np.concatenate(col_segs)\n x = A.__class__((sparse_data, (sparse_row, sparse_col)),\n shape=b.shape, dtype=A.dtype)\n\n return x\n\n\ndef splu(A, permc_spec=None, diag_pivot_thresh=None,\n drop_tol=None, relax=None, panel_size=None, options=dict()):\n \"\"\"\n Compute the LU decomposition of a sparse, square matrix.\n\n Parameters\n ----------\n A : sparse matrix\n Sparse matrix to factorize. Should be in CSR or CSC format.\n permc_spec : str, optional\n How to permute the columns of the matrix for sparsity preservation.\n (default: 'COLAMD')\n\n - ``NATURAL``: natural ordering.\n - ``MMD_ATA``: minimum degree ordering on the structure of A^T A.\n - ``MMD_AT_PLUS_A``: minimum degree ordering on the structure of A^T+A.\n - ``COLAMD``: approximate minimum degree column ordering\n\n diag_pivot_thresh : float, optional\n Threshold used for a diagonal entry to be an acceptable pivot.\n See SuperLU user's guide for details [1]_\n drop_tol : float, optional\n (deprecated) No effect.\n relax : int, optional\n Expert option for customizing the degree of relaxing supernodes.\n See SuperLU user's guide for details [1]_\n panel_size : int, optional\n Expert option for customizing the panel size.\n See SuperLU user's guide for details [1]_\n options : dict, optional\n Dictionary containing additional expert options to SuperLU.\n See SuperLU user guide [1]_ (section 2.4 on the 'Options' argument)\n for more details. For example, you can specify\n ``options=dict(Equil=False, IterRefine='SINGLE'))``\n to turn equilibration off and perform a single iterative refinement.\n\n Returns\n -------\n invA : scipy.sparse.linalg.SuperLU\n Object, which has a ``solve`` method.\n\n See also\n --------\n spilu : incomplete LU decomposition\n\n Notes\n -----\n This function uses the SuperLU library.\n\n References\n ----------\n .. [1] SuperLU http://crd.lbl.gov/~xiaoye/SuperLU/\n\n \"\"\"\n\n if not isspmatrix_csc(A):\n A = csc_matrix(A)\n warn('splu requires CSC matrix format', SparseEfficiencyWarning)\n\n A.sort_indices()\n A = A.asfptype() # upcast to a floating point format\n\n M, N = A.shape\n if (M != N):\n raise ValueError(\"can only factor square matrices\") # is this true?\n\n _options = dict(DiagPivotThresh=diag_pivot_thresh, ColPerm=permc_spec,\n PanelSize=panel_size, Relax=relax)\n if options is not None:\n _options.update(options)\n return _superlu.gstrf(N, A.nnz, A.data, A.indices, A.indptr,\n ilu=False, options=_options)\n\n\ndef spilu(A, drop_tol=None, fill_factor=None, drop_rule=None, permc_spec=None,\n diag_pivot_thresh=None, relax=None, panel_size=None, options=None):\n \"\"\"\n Compute an incomplete LU decomposition for a sparse, square matrix.\n\n The resulting object is an approximation to the inverse of `A`.\n\n Parameters\n ----------\n A : (N, N) array_like\n Sparse matrix to factorize\n drop_tol : float, optional\n Drop tolerance (0 <= tol <= 1) for an incomplete LU decomposition.\n (default: 1e-4)\n fill_factor : float, optional\n Specifies the fill ratio upper bound (>= 1.0) for ILU. (default: 10)\n drop_rule : str, optional\n Comma-separated string of drop rules to use.\n Available rules: ``basic``, ``prows``, ``column``, ``area``,\n ``secondary``, ``dynamic``, ``interp``. (Default: ``basic,area``)\n\n See SuperLU documentation for details.\n\n Remaining other options\n Same as for `splu`\n\n Returns\n -------\n invA_approx : scipy.sparse.linalg.SuperLU\n Object, which has a ``solve`` method.\n\n See also\n --------\n splu : complete LU decomposition\n\n Notes\n -----\n To improve the better approximation to the inverse, you may need to\n increase `fill_factor` AND decrease `drop_tol`.\n\n This function uses the SuperLU library.\n\n \"\"\"\n if not isspmatrix_csc(A):\n A = csc_matrix(A)\n warn('splu requires CSC matrix format', SparseEfficiencyWarning)\n\n A.sort_indices()\n A = A.asfptype() # upcast to a floating point format\n\n M, N = A.shape\n if (M != N):\n raise ValueError(\"can only factor square matrices\") # is this true?\n\n _options = dict(ILU_DropRule=drop_rule, ILU_DropTol=drop_tol,\n ILU_FillFactor=fill_factor,\n DiagPivotThresh=diag_pivot_thresh, ColPerm=permc_spec,\n PanelSize=panel_size, Relax=relax)\n if options is not None:\n _options.update(options)\n return _superlu.gstrf(N, A.nnz, A.data, A.indices, A.indptr,\n ilu=True, options=_options)\n\n\ndef factorized(A):\n \"\"\"\n Return a fuction for solving a sparse linear system, with A pre-factorized.\n\n Parameters\n ----------\n A : (N, N) array_like\n Input.\n\n Returns\n -------\n solve : callable\n To solve the linear system of equations given in `A`, the `solve`\n callable should be passed an ndarray of shape (N,).\n\n Examples\n --------\n >>> from scipy.sparse.linalg import factorized\n >>> A = np.array([[ 3. , 2. , -1. ],\n ... [ 2. , -2. , 4. ],\n ... [-1. , 0.5, -1. ]])\n >>> solve = factorized(A) # Makes LU decomposition.\n >>> rhs1 = np.array([1, -2, 0])\n >>> solve(rhs1) # Uses the LU factors.\n array([ 1., -2., -2.])\n\n \"\"\"\n if useUmfpack:\n if noScikit:\n raise RuntimeError('Scikits.umfpack not installed.')\n\n if not isspmatrix_csc(A):\n A = csc_matrix(A)\n warn('splu requires CSC matrix format', SparseEfficiencyWarning)\n\n A.sort_indices()\n A = A.asfptype() # upcast to a floating point format\n\n if A.dtype.char not in 'dD':\n raise ValueError(\"convert matrix data to double, please, using\"\n \" .astype(), or set linsolve.useUmfpack = False\")\n\n umf = umfpack.UmfpackContext(_get_umf_family(A))\n\n # Make LU decomposition.\n umf.numeric(A)\n\n def solve(b):\n return umf.solve(umfpack.UMFPACK_A, A, b, autoTranspose=True)\n\n return solve\n else:\n return splu(A).solve\n"
] | [
[
"scipy.sparse.isspmatrix",
"scipy.sparse.csc_matrix",
"numpy.asarray",
"numpy.flatnonzero",
"numpy.concatenate",
"numpy.ones",
"scipy.sparse.isspmatrix_csr",
"scipy.sparse.isspmatrix_csc"
]
] | [
{
"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": []
}
] |
tcstewar/nengo_learning_display | [
"bd2940182743475d0d19b436d295a3398bbb328e"
] | [
"nengo_learning_display/two_dim.py"
] | [
"import nengo\nimport numpy as np\nimport base64\n\ntry:\n from cStringIO import StringIO # Python 2\nexcept ImportError:\n from io import BytesIO as StringIO # Python 3\n\nclass Plot2D(nengo.Node):\n def __init__(self, connection, domain, range, dimension=0):\n import PIL\n from PIL import Image\n self.connection = connection\n\n ensemble = connection.pre_obj\n\n self.decoder_probe = nengo.Probe(connection, 'weights')\n\n self.ensemble = ensemble\n\n if domain.shape[2] != ensemble.dimensions:\n raise Exception('domain must be (X-pts x Y-pts x dimensions)')\n self.domain = domain\n\n self.sim = None\n self.w = None\n self.range = range\n\n self.a = None\n self.dimension = dimension\n\n template = '''\n <svg width=\"100%%\" height=\"100%%\" viewbox=\"0 0 100 100\">\n %s\n </svg>'''\n\n def plot(t):\n if self.w is None:\n return\n y = np.dot(self.a, self.w.T)\n\n y = (y - self.range[0])/(self.range[1] - self.range[0])\n\n y = np.clip(y * 255, 0, 255)\n\n y = y.astype('uint8')\n\n png = Image.fromarray(y[:,:])\n buffer = StringIO()\n png.save(buffer, format=\"PNG\")\n img_str = base64.b64encode(buffer.getvalue()).decode('utf-8')\n \n img = '''<image width=\"100%%\" height=\"100%%\"\n xlink:href=\"data:image/png;base64,%s\" \n style=\"image-rendering: pixelated;\">\n ''' % img_str\n\n plot._nengo_html_ = template % img\n\n super(Plot2D, self).__init__(plot, size_in=0, size_out=0)\n self.output._nengo_html_ = template % ''\n\n def update(self, sim):\n if sim is None:\n return\n if self.a is None:\n _, self.a = nengo.utils.ensemble.tuning_curves(self.ensemble, \n sim, self.domain)\n self.w = sim._probe_outputs[self.decoder_probe][-1][self.dimension]\n del sim._probe_outputs[self.decoder_probe][:]\n"
] | [
[
"numpy.dot",
"numpy.clip"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ypapanik/TDC | [
"3739a918cf3bbb4fc2ef8d6c96d8b809dd8c4d2a"
] | [
"tdc/multi_pred/bi_pred_dataset.py"
] | [
"# -*- coding: utf-8 -*-\n# Author: TDC Team\n# License: MIT\n\nimport pandas as pd\nimport numpy as np\nimport os, sys, json \nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nfrom .. import base_dataset\nfrom ..utils import dataset2target_lists, \\\n fuzzy_search, \\\n interaction_dataset_load, \\\n label_transform, \\\n NegSample, \\\n install,\\\n create_fold,\\\n create_fold_setting_cold,\\\n create_combination_split,\\\n create_fold_time,\\\n print_sys\n\nclass DataLoader(base_dataset.DataLoader):\n\n \"\"\"A base data loader class that each bi-instance prediction task dataloader class can inherit from.\n \n Attributes: TODO\n \n \"\"\"\n \n def __init__(self, name, path, label_name, print_stats, dataset_names):\n \"\"\"Create a base dataloader object that each multi-instance prediction task dataloader class can inherit from.\n \n Args:\n name (str): name of dataloader \n path (str): the path where data is saved\n label_name (str): name of label\n print_stats (bool): whether to print statistics of dataset\n dataset_names (str): A list of dataset names available for a task \n\n Raises:\n ValueError: label name is not available\n \"\"\"\n if name.lower() in dataset2target_lists.keys():\n # print_sys(\"Tip: Use tdc.utils.retrieve_label_name_list(\n # '\" + name.lower() + \"') to retrieve all available label names.\")\n if label_name is None:\n raise ValueError(\n \"Please select a label name. \"\n \"You can use tdc.utils.retrieve_label_name_list('\" +\n name.lower() + \"') to retrieve all available label names.\")\n\n name = fuzzy_search(name, dataset_names)\n if name == 'bindingdb_patent':\n aux_column = 'Year'\n else:\n aux_column = None\n\n entity1, entity2, raw_y, entity1_idx, entity2_idx, aux_column_val = \\\n interaction_dataset_load(name, path, label_name, dataset_names, aux_column = aux_column)\n\n self.name = name\n self.entity1 = entity1\n self.entity2 = entity2\n self.raw_y = raw_y\n self.y = raw_y\n self.entity1_idx = entity1_idx\n self.entity2_idx = entity2_idx\n self.path = path\n self.file_format = 'csv'\n self.label_name = label_name\n\n self.entity1_name = 'Entity1'\n self.entity2_name = 'Entity2'\n self.aux_column = aux_column\n self.aux_column_val = aux_column_val\n\n self.two_types = False\n\n def get_data(self, format='df'):\n \"\"\"generate data in some format, e.g., pandas.DataFrame\n \n Args:\n format (str, optional): \n format of data, the default value is 'df' (DataFrame)\n \n Returns:\n pandas DataFrame/dict: a dataframe of a dataset/a dictionary for key information in the dataset\n \n Raises:\n AttributeError: Use the correct format input (df, dict, DeepPurpose)\n \"\"\"\n if format == 'df':\n if self.aux_column is None:\n return pd.DataFrame({self.entity1_name + '_ID': self.entity1_idx,\n self.entity1_name: self.entity1,\n self.entity2_name + '_ID': self.entity2_idx,\n self.entity2_name: self.entity2, 'Y': self.y})\n else:\n return pd.DataFrame({self.entity1_name + '_ID': self.entity1_idx,\n self.entity1_name: self.entity1,\n self.entity2_name + '_ID': self.entity2_idx,\n self.entity2_name: self.entity2, 'Y': self.y, \n self.aux_column: self.aux_column_val})\n\n elif format == 'DeepPurpose':\n return self.entity1.values, self.entity2.values, self.y.values\n elif format == 'dict':\n return {self.entity1_name + '_ID': self.entity1_idx.values,\n self.entity1_name: self.entity1.values,\n self.entity2_name + '_ID': self.entity2_idx.values,\n self.entity2_name: self.entity2.values, 'Y': self.y.values}\n else:\n raise AttributeError(\"Please use the correct format input\")\n\n def print_stats(self):\n \"\"\"print the statistics of the dataset\n \"\"\"\n print_sys('--- Dataset Statistics ---')\n try:\n x = np.unique(self.entity1)\n except:\n x = np.unique(self.entity1_idx)\n\n try:\n y = np.unique(self.entity2)\n except:\n y = np.unique(self.entity2_idx)\n\n print(str(len(x)) + ' unique ' + self.entity1_name.lower() + 's.',\n flush=True, file=sys.stderr)\n print(str(len(y)) + ' unique ' + self.entity2_name.lower() + 's.',\n flush=True, file=sys.stderr)\n print(str(len(self.y)) + ' ' + self.entity1_name.lower() +\n '-' + self.entity2_name.lower() + ' pairs.',\n flush=True, file=sys.stderr)\n print_sys('--------------------------')\n \n def get_split(self, method='random', seed=42,\n frac=[0.7, 0.1, 0.2], column_name=None, time_column=None):\n \"\"\"split dataset into train/validation/test. \n\n Args:\n method (str, optional):\n split method, the default value is 'random'\n seed (int, optional):\n random seed, defaults to '42'\n frac (list, optional):\n train/val/test split fractions, defaults to '[0.7, 0.1, 0.2]'\n column_name (Optional[Union[str, List[str]]]): Optional column name(s) to\n split on for cold splits. Defaults to None.\n time_column (None, optional): Description\n\n Returns:\n dict: a dictionary with three keys ('train', 'valid', 'test'), each value\n is a pandas dataframe object of the splitted dataset.\n\n Raises:\n AttributeError: the input split method is not available.\n\n \"\"\"\n df = self.get_data(format='df')\n\n if isinstance(column_name, str):\n column_name = [column_name]\n\n if method == 'random':\n return create_fold(df, seed, frac)\n elif method == 'cold_' + self.entity1_name.lower():\n return create_fold_setting_cold(df, seed, frac, self.entity1_name)\n elif method == 'cold_' + self.entity2_name.lower():\n return create_fold_setting_cold(df, seed, frac, self.entity2_name)\n elif method == 'cold_split':\n if (\n column_name is None or\n not all(list(map(lambda x: x in df.columns.values, column_name)))\n ):\n raise AttributeError(\n \"For cold_split, please provide one or multiple column names \"\n \"that are contained in the dataframe.\"\n )\n return create_fold_setting_cold(df, seed, frac, column_name)\n elif method == 'combination':\n return create_combination_split(df, seed, frac)\n elif method == 'time':\n if time_column is None:\n raise ValueError('Please specify the column that has the time variable using time_column.')\n return create_fold_time(df, frac, time_column)\n\n else:\n raise AttributeError(\n \"Please select method from random, time, combination or cold_split.\"\n )\n\n def neg_sample(self, frac=1):\n \"\"\"negative sampling \n \n Args:\n frac (int, optional): the ratio between negative and positive samples. \n \n Returns:\n DataLoader, the class itself. \n \"\"\"\n df = NegSample(df=self.get_data(format='df'),\n column_names=[self.entity1_name + '_ID',\n self.entity1_name,\n self.entity2_name + '_ID',\n self.entity2_name], frac=frac, two_types = self.two_types)\n self.entity1_idx = df[self.entity1_name + '_ID']\n self.entity2_idx = df[self.entity2_name + '_ID']\n self.entity1 = df[self.entity1_name]\n self.entity2 = df[self.entity2_name]\n self.y = df['Y']\n self.raw_y = self.y\n return self\n\n def to_graph(self, threshold=None, format='edge_list', split=True,\n frac=[0.7, 0.1, 0.2], seed=42, order='descending'):\n \"\"\"Summary TODO\n \n Args:\n threshold (float, optional): threshold to binarize the data. \n format (str, optional): format of data, defaults to 'edge_list'\n split (bool, optional): if we need to split data into train/valid/test. \n frac (list, optional): train/val/test split fractions, defaults to '[0.7, 0.1, 0.2]'\n seed (int, optional): random seed, defaults to '42'\n order (str, optional): order of label transform \n\n Returns:\n dict: a dictionary for key information in the dataset\n \n Raises:\n AttributeError: the threshold is not available. \n ImportError: install the required package\n \"\"\"\n df = self.get_data(format='df')\n\n if len(np.unique(self.raw_y)) > 2:\n print(\"The dataset label consists of affinity scores. \"\n \"Binarization using threshold \" +\n str(threshold) +\n \" is conducted to construct the positive edges in the network. \"\n \"Adjust the threshold by to_graph(threshold = X)\",\n flush=True, file=sys.stderr)\n if threshold is None:\n raise AttributeError(\n \"Please specify the threshold to binarize the data by \"\n \"'to_graph(threshold = N)'!\")\n df['label_binary'] = label_transform(self.raw_y, True, threshold,\n False, verbose=False,\n order=order)\n else:\n # already binary\n df['label_binary'] = df['Y']\n\n df[self.entity1_name + '_ID'] = df[self.entity1_name + '_ID'].astype(str)\n df[self.entity2_name + '_ID'] = df[self.entity2_name + '_ID'].astype(str)\n df_pos = df[df.label_binary == 1]\n df_neg = df[df.label_binary == 0]\n\n return_dict = {}\n\n pos_edges = df_pos[\n [self.entity1_name + '_ID', self.entity2_name + '_ID']].values\n neg_edges = df_neg[\n [self.entity1_name + '_ID', self.entity2_name + '_ID']].values\n edges = df[\n [self.entity1_name + '_ID', self.entity2_name + '_ID']].values\n\n if format == 'edge_list':\n return_dict['edge_list'] = pos_edges\n return_dict['neg_edges'] = neg_edges\n elif format == 'dgl':\n try:\n import dgl\n except:\n install(\"dgl\")\n import dgl\n unique_entities = np.unique(pos_edges.T.flatten()).tolist()\n index = list(range(len(unique_entities)))\n dict_ = dict(zip(unique_entities, index))\n edge_list1 = np.array([dict_[i] for i in pos_edges.T[0]])\n edge_list2 = np.array([dict_[i] for i in pos_edges.T[1]])\n return_dict['dgl_graph'] = dgl.DGLGraph((edge_list1, edge_list2))\n return_dict['index_to_entities'] = dict_\n\n elif format == 'pyg':\n try:\n import torch\n from torch_geometric.data import Data\n except:\n raise ImportError(\n \"Please see https://pytorch-geometric.readthedocs.io/en/latest/notes/installation.html to install pytorch geometric!\")\n\n unique_entities = np.unique(pos_edges.T.flatten()).tolist()\n index = list(range(len(unique_entities)))\n dict_ = dict(zip(unique_entities, index))\n edge_list1 = np.array([dict_[i] for i in pos_edges.T[0]])\n edge_list2 = np.array([dict_[i] for i in pos_edges.T[1]])\n\n edge_index = torch.tensor([edge_list1, edge_list2],\n dtype=torch.long)\n x = torch.tensor(np.array(index), dtype=torch.float)\n data = Data(x=x, edge_index=edge_index)\n return_dict['pyg_graph'] = data\n return_dict['index_to_entities'] = dict_\n\n elif format == 'df':\n return_dict['df'] = df\n\n if split:\n return_dict['split'] = create_fold(df, seed, frac)\n\n return return_dict\n"
] | [
[
"torch.tensor",
"numpy.array",
"pandas.DataFrame",
"numpy.unique"
]
] | [
{
"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": []
}
] |
kenkenjlab/burger_war_kit | [
"9332494aa1212805330c01cacc389776a8a354b6"
] | [
"enemy_bot/enemy_bot_level10/teb_local_planner/scripts/export_to_mat.py"
] | [
"#!/usr/bin/env python\n\n# This small script subscribes to the FeedbackMsg message of teb_local_planner\n# and exports data to a mat file.\n# publish_feedback must be turned on such that the planner publishes this information.\n# Author: [email protected]\n\nimport rospy, math\nfrom teb_local_planner.msg import FeedbackMsg, TrajectoryMsg, TrajectoryPointMsg\nfrom geometry_msgs.msg import PolygonStamped, Point32, Quaternion\nfrom tf.transformations import euler_from_quaternion\nimport numpy as np\nimport scipy.io as sio\nimport time\n\ndef feedback_callback(data):\n global got_data\n\n if not data.trajectories: # empty\n trajectory = []\n return\n \n if got_data:\t\t\n return\n\n got_data = True\n \n # copy trajectory\n trajectories = []\n for traj in data.trajectories:\n trajectory = []\n# # store as struct and cell array\n# for point in traj.trajectory:\n# (roll,pitch,yaw) = euler_from_quaternion([point.pose.orientation.x,point.pose.orientation.y,point.pose.orientation.z,point.pose.orientation.w])\n# pose = {'x': point.pose.position.x, 'y': point.pose.position.y, 'theta': yaw}\n# velocity = {'v': point.velocity.linear.x, 'omega': point.velocity.angular.z}\n# time_from_start = point.time_from_start.to_sec()\n# trajectory.append({'pose': pose, 'velocity': velocity, 'time_from_start': time_from_start})\n \n # store as all-in-one mat\n arr = np.zeros([6, len(traj.trajectory)], dtype='double'); # x, y, theta, v, omega, t\n for index, point in enumerate(traj.trajectory):\n arr[0,index] = point.pose.position.x\n arr[1,index] = point.pose.position.y\n (roll,pitch,yaw) = euler_from_quaternion([point.pose.orientation.x,point.pose.orientation.y,point.pose.orientation.z,point.pose.orientation.w])\n arr[2,index] = yaw\n arr[3,index] = point.velocity.linear.x\n arr[4,index] = point.velocity.angular.z\n arr[5,index] = point.time_from_start.to_sec()\n \n# trajectories.append({'raw': trajectory, 'mat': arr})\n trajectories.append({'data': arr, 'legend': ['x','y','theta','v','omega','t']})\n \n # copy obstacles\n obstacles = []\n for obst_id, obst in enumerate(data.obstacle_msg.obstacles):\n #polygon = []\n #for point in obst.polygon.points:\n # polygon.append({'x': point.x, 'y': point.y, 'z': point.z})\n obst_arr = np.zeros([4, len(obst.polygon.points)], dtype='double'); # x, y\n for index, point in enumerate(obst.polygon.points):\n obst_arr[0, index] = point.x\n obst_arr[1, index] = point.y\n obst_arr[2, index] = data.obstacle_msg.velocities[obst_id].twist.linear.x\n obst_arr[3, index] = data.obstacle_msg.velocities[obst_id].twist.linear.y\n\n #obstacles.append(polygon)\n obstacles.append({'data': obst_arr, 'legend': ['x','y', 'v_x', 'v_y']})\n \n \n # create main struct:\n mat = {'selected_trajectory_idx': data.selected_trajectory_idx, 'trajectories': trajectories, 'obstacles': obstacles}\n\n timestr = time.strftime(\"%Y%m%d_%H%M%S\")\n filename = '/home/albers/MasterThesis/Matlab/Homotopie/test_optim_node/' + 'teb_data_' + timestr + '.mat'\n \n rospy.loginfo(\"Saving mat-file '%s'.\", filename)\n sio.savemat(filename, mat)\n \n\n \n \n \ndef feedback_exporter():\n global got_data\n\n rospy.init_node(\"export_to_mat\", anonymous=True)\n \n \n topic_name = \"/test_optim_node/teb_feedback\" # define feedback topic here!\n\n rospy.Subscriber(topic_name, FeedbackMsg, feedback_callback, queue_size = 1) \n\n rospy.loginfo(\"Waiting for feedback message on topic %s.\", topic_name)\n \n r = rospy.Rate(2) # define rate here\n while not rospy.is_shutdown():\n \n if got_data:\n rospy.loginfo(\"Data export completed.\")\n return\n\n r.sleep()\n\nif __name__ == '__main__': \n try:\n global got_data\n got_data = False\n feedback_exporter()\n except rospy.ROSInterruptException:\n pass\n\n"
] | [
[
"scipy.io.savemat"
]
] | [
{
"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": []
}
] |
Philyzh8/Nature-inspired-CS | [
"65e6aa9e983014823ba440205aadb9800d79f4cd"
] | [
"sample_similarity.py"
] | [
"import numpy as np\nfrom dl_simulation import random_phi, get_observations\nfrom union_of_transforms import random_submatrix\nfrom analyze_predictions import *\nfrom scipy.spatial import distance\nfrom scipy.stats import spearmanr\nfrom sklearn.manifold import Isomap, MDS\nimport glob, os\nimport sys\n\n#fp, snr = sys.argv[1:]\n\nfilename = {\"data1\": \"GSE71858.npy\", #\n \"data2\": \"GSE60361.npy\", #\n \"data3\": \"GSE62270.npy\", #\n \"data4\": \"GSE48968.npy\", #\n \"data5\": \"GSE52529.npy\", #\n \"data6\": \"GSE77564.npy\",\n \"data7\": \"GSE78779.npy\", #\n \"data8\": \"GSE10247.npy\", #\n \"data9\": \"GSE69405.npy\"}\nsnr = 2\nsnr = float(snr)\n\niters = 10\nM = [10, 25, 50, 100, 200, 400]\nfp = \"./Data/GSE71858.npy\"\n#prefix = fp[:fp.rfind('/')]\nX = np.load(fp)\nthresh = np.percentile(X, 99.5)\nX[(X > thresh)] = thresh\nfor m in M:\n Pearson = []\n Spearman = []\n Pearson_p = []\n Spearman_p = []\n Pearson_MDS = []\n Pearson_Iso = []\n Pearson_MDS_p = []\n Pearson_Iso_p = []\n Pearson_svd = []\n Spearman_svd = []\n Cluster = []\n Cluster_svd = []\n for _ in range(iters):\n Phi = random_phi(m, X.shape[0])\n Y, noise = get_observations(X, Phi, snr=snr, return_noise=True)\n pearson_dist, spearman_dist = compare_distances(X, Y, pvalues=True)\n #cluster_similarity = compare_clusters(X, Y)\n Pearson.append(pearson_dist[0])\n #Spearman.append(spearman_dist[0])\n #Pearson_p.append(pearson_dist[1])\n #Spearman_p.append(spearman_dist[1])\n #Cluster.append(cluster_similarity)\n #X_mds = MDS().fit_transform(X.T).T\n #Y_mds = MDS().fit_transform(Y.T).T\n #X_iso = Isomap().fit_transform(X.T).T\n #Y_iso = Isomap().fit_transform(Y.T).T\n #pearson_mds, spearman_mds = compare_distances(X_mds, Y_mds, pvalues=True)\n #pearson_iso, spearman_iso = compare_distances(X_iso, Y_iso, pvalues=True)\n #Pearson_MDS.append(pearson_mds[0])\n #Pearson_Iso.append(pearson_iso[0])\n #Pearson_MDS_p.append(pearson_mds[1])\n #Pearson_Iso_p.append(pearson_mds[1])\n #ua, sa, vta = np.linalg.svd(X + noise, full_matrices=False)\n #Vt = np.diag(sa).dot(vta)\n #pearson_svd, spearman_svd = compare_distances(Vt[:m], Y, pvalues=False)\n #cluster_similarity_svd = compare_clusters(Vt[:m], Y)\n #Pearson_svd.append(pearson_svd)\n #Spearman_svd.append(spearman_svd)\n #Cluster_svd.append(cluster_similarity_svd)\n\n # sys.stdout = open('./Data/similarity1.log', 'a')\n\n #print fp, m, np.average(Pearson), np.average(Pearson_p), np.average(Spearman), np.average(\n # Spearman_p), np.average(Pearson_MDS), np.average(Pearson_MDS_p), np.average(Pearson_Iso), np.average(\n # Pearson_Iso_p), np.average(Cluster), np.average(Pearson_svd), np.average(Spearman_svd), np.average(Cluster_svd)\n print(fp, m, np.average(Pearson))\n"
] | [
[
"numpy.load",
"numpy.average",
"numpy.percentile"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
rwlee/cudf | [
"77d28496fec322bc80e874be72d832417cf798a1"
] | [
"python/cudf/cudf/groupby/legacy_groupby.py"
] | [
"# Copyright (c) 2018, NVIDIA CORPORATION.\n\nfrom collections import OrderedDict, defaultdict, namedtuple\nfrom itertools import chain\n\nimport numpy as np\nfrom numba import cuda\n\nfrom librmm_cffi import librmm as rmm\n\nfrom cudf.bindings.sort import apply_segsort\nfrom cudf.comm.serialize import register_distributed_serializer\nfrom cudf.dataframe.buffer import Buffer\nfrom cudf.dataframe.column import Column\nfrom cudf.dataframe.dataframe import DataFrame\nfrom cudf.dataframe.series import Series\nfrom cudf.multi import concat\nfrom cudf.utils import cudautils\n\n\ndef _auto_generate_grouper_agg(members):\n def make_fun(f):\n def groupby_agg(self):\n return self.agg(f)\n\n return groupby_agg\n\n for k, f in members[\"_NAMED_FUNCTIONS\"].items():\n fn = make_fun(f)\n fn.__name__ = k\n fn.__doc__ = \"\"\"Compute the {} of each group\n\nReturns\n-------\n\nresult : DataFrame\n\"\"\".format(\n k\n )\n members[k] = fn\n\n\[email protected]\ndef group_mean(data, segments, output):\n i = cuda.grid(1)\n if i < segments.size:\n s = segments[i]\n e = segments[i + 1] if (i + 1) < segments.size else data.size\n # mean calculation\n carry = 0.0\n n = e - s\n for j in range(s, e):\n carry += data[j]\n output[i] = carry / n\n\n\[email protected]\ndef group_max(data, segments, output):\n i = cuda.grid(1)\n if i < segments.size:\n s = segments[i]\n e = segments[i + 1] if (i + 1) < segments.size else data.size\n\n tmp = data[s]\n for j in range(s + 1, e):\n tmp = max(tmp, data[j])\n output[i] = tmp\n\n\[email protected]\ndef group_min(data, segments, output):\n i = cuda.grid(1)\n if i < segments.size:\n s = segments[i]\n e = segments[i + 1] if (i + 1) < segments.size else data.size\n\n tmp = data[s]\n for j in range(s + 1, e):\n tmp = min(tmp, data[j])\n output[i] = tmp\n\n\n_dfsegs_pack = namedtuple(\"_dfsegs_pack\", [\"df\", \"segs\"])\n\n\nclass Groupby(object):\n \"\"\"Groupby object returned by cudf.DataFrame.groupby().\n \"\"\"\n\n _NAMED_FUNCTIONS = {\n \"mean\": Series.mean,\n \"std\": Series.std,\n \"var\": Series.var,\n \"min\": Series.min,\n \"max\": Series.max,\n \"count\": Series.count,\n \"sum\": Series.sum,\n \"sum_of_squares\": Series.sum_of_squares,\n }\n\n def __init__(self, df, by):\n \"\"\"\n Parameters\n ----------\n df : DataFrame\n by : str of list of str\n Column(s) that grouping is based on.\n It can be a single or list of column names.\n \"\"\"\n self._df = df\n self._by = [by] if isinstance(by, str) else list(by)\n self._val_columns = [\n idx for idx in self._df.columns if idx not in self._by\n ]\n\n def serialize(self, serialize):\n header = {\"by\": self._by}\n header[\"df\"], frames = serialize(self._df)\n return header, frames\n\n @classmethod\n def deserialize(cls, deserialize, header, frames):\n by = header[\"by\"]\n df = deserialize(header[\"df\"], frames)\n return Groupby(df, by)\n\n def __iter__(self):\n return self._group_iterator()\n\n def _group_iterator(self):\n \"\"\"Group iterator\n\n Returns each group as a DataFrame.\n \"\"\"\n grouped = self.as_df()\n segs = grouped.segs.to_array()\n for begin, end in zip(segs, chain(segs[1:], [len(grouped.df)])):\n yield grouped.df[begin:end]\n\n def as_df(self):\n \"\"\"Get the intermediate dataframe after shuffling the rows into\n groups.\n\n Returns\n -------\n (df, segs) : namedtuple\n - df : DataFrame\n - segs : Series\n Beginning offsets of each group.\n\n Examples\n --------\n .. code-block:: python\n\n from cudf import DataFrame\n\n df = DataFrame()\n df['key'] = [0, 0, 1, 1, 2, 2, 2]\n df['val'] = [0, 1, 2, 3, 4, 5, 6]\n groups = df.groupby(['key'], method='cudf')\n\n df_groups = groups.as_df()\n\n # DataFrame indexes of group starts\n print(df_groups[1])\n\n # DataFrame itself\n print(df_groups[0])\n\n Output:\n\n .. code-block:: python\n\n # DataFrame indexes of group starts\n 0 0\n 1 2\n 2 4\n\n # DataFrame itself\n key val\n 0 0 0\n 1 0 1\n 2 1 2\n 3 1 3\n 4 2 4\n 5 2 5\n 6 2 6\n\n \"\"\"\n return self._group_dataframe(self._df, self._by)\n\n def _agg_groups(self, functors):\n \"\"\"Aggregate the groups\n\n Parameters\n ----------\n functors: dict\n Contains key for column names and value for list of functors.\n\n \"\"\"\n functors_mapping = OrderedDict()\n # The \"value\" columns\n for k, vs in functors.items():\n if k not in self._df.columns:\n raise NameError(\"column {} not found\".format(k))\n if len(vs) == 1:\n [functor] = vs\n functors_mapping[k] = {k: functor}\n else:\n functors_mapping[k] = cur_fn_mapping = OrderedDict()\n for functor in vs:\n newk = \"{}_{}\".format(k, functor.__name__)\n cur_fn_mapping[newk] = functor\n\n del functor\n # Grouping\n grouped_df, sr_segs = self._group_dataframe(self._df, self._by)\n # Grouped values\n outdf = DataFrame()\n segs = sr_segs.to_array()\n\n for k in self._by:\n outdf[k] = (\n grouped_df[k]\n .take(sr_segs.to_gpu_array())\n .reset_index(drop=True)\n )\n\n size = len(outdf)\n\n # Append value columns\n for k, infos in functors_mapping.items():\n values = defaultdict(lambda: np.zeros(size, dtype=np.float64))\n begin = segs\n sr = grouped_df[k].reset_index(drop=True)\n for newk, functor in infos.items():\n if functor.__name__ == \"mean\":\n dev_begins = rmm.to_device(np.asarray(begin))\n dev_out = rmm.device_array(size, dtype=np.float64)\n if size > 0:\n group_mean.forall(size)(\n sr.to_gpu_array(), dev_begins, dev_out\n )\n values[newk] = dev_out\n\n elif functor.__name__ == \"max\":\n dev_begins = rmm.to_device(np.asarray(begin))\n dev_out = rmm.device_array(size, dtype=sr.dtype)\n if size > 0:\n group_max.forall(size)(\n sr.to_gpu_array(), dev_begins, dev_out\n )\n values[newk] = dev_out\n\n elif functor.__name__ == \"min\":\n dev_begins = rmm.to_device(np.asarray(begin))\n dev_out = rmm.device_array(size, dtype=sr.dtype)\n if size > 0:\n group_min.forall(size)(\n sr.to_gpu_array(), dev_begins, dev_out\n )\n values[newk] = dev_out\n else:\n end = chain(segs[1:], [len(grouped_df)])\n for i, (s, e) in enumerate(zip(begin, end)):\n values[newk][i] = functor(sr[s:e])\n # Store\n for k, buf in values.items():\n outdf[k] = buf\n\n return outdf\n\n def _group_dataframe(self, df, levels):\n \"\"\"Group dataframe.\n\n The output dataframe has the same number of rows as the input\n dataframe. The rows are shuffled so that the groups are moved\n together in ascending order based on the multi-level index.\n\n Parameters\n ----------\n df : DataFrame\n levels : list[str]\n Column names for the multi-level index.\n\n Returns\n -------\n (df, segs) : namedtuple\n * df : DataFrame\n The grouped dataframe.\n * segs : Series.\n Group starting index.\n \"\"\"\n if len(df) == 0:\n # Groupby on empty dataframe\n return _dfsegs_pack(df=df, segs=Buffer(np.asarray([])))\n # Prepare dataframe\n orig_df = df.copy()\n df = df.loc[:, levels].reset_index(drop=True)\n df = df.to_frame() if isinstance(df, Series) else df\n rowid_column = \"__cudf.groupby.rowid\"\n df[rowid_column] = df.index.as_column()\n\n col_order = list(levels)\n\n # Perform grouping\n df, segs, markers = self._group_first_level(\n col_order[0], rowid_column, df\n )\n rowidcol = df[rowid_column]\n sorted_keys = [Series(df.index.as_column())]\n del df\n\n more_keys, reordering_indices, segs = self._group_inner_levels(\n col_order[1:], rowidcol, segs, markers=markers\n )\n sorted_keys.extend(more_keys)\n valcols = [k for k in orig_df.columns if k not in levels]\n # Prepare output\n # All key columns are already sorted\n out_df = DataFrame()\n for k, sr in zip(levels, sorted_keys):\n out_df[k] = sr\n # Shuffle the value columns\n self._group_shuffle(\n orig_df.loc[:, valcols], reordering_indices, out_df\n )\n return _dfsegs_pack(df=out_df, segs=segs)\n\n def _group_first_level(self, col, rowid_column, df):\n \"\"\"Group first level *col* of *df*\n\n Parameters\n ----------\n col : str\n Name of the first group key column.\n df : DataFrame\n The dataframe being grouped.\n\n Returns\n -------\n (df, segs)\n - df : DataFrame\n Sorted by *col- * index\n - segs : Series\n Group begin offsets\n \"\"\"\n df = df.loc[:, [col, rowid_column]]\n df = df.set_index(col).sort_index()\n segs, markers = df.index._find_segments()\n return df, Series(segs), markers\n\n def _group_inner_levels(self, columns, rowidcol, segs, markers):\n \"\"\"Group the second and onwards level.\n\n Parameters\n ----------\n columns : sequence[str]\n Group keys. The order is important.\n rowid_column : str\n The name of the special column with the original rowid.\n It's internally used to determine the shuffling order.\n df : DataFrame\n The dataframe being grouped.\n segs : Series\n First level group begin offsets.\n\n Returns\n -------\n (sorted_keys, reordering_indices, segments)\n - sorted_keys : list[Series]\n List of sorted key columns.\n Column order is same as arg *columns*.\n - reordering_indices : device array\n The indices to gather on to shuffle the dataframe\n into the grouped seqence.\n - segments : Series\n Group begin offsets.\n \"\"\"\n dsegs = segs.astype(dtype=np.int32).data.mem\n sorted_keys = []\n plan_cache = {}\n for col in columns:\n # Shuffle the key column according to the previous groups\n srkeys = self._df[col].take(\n rowidcol.to_gpu_array(), ignore_index=True\n )\n # Segmented sort on the key\n shuf = Column(Buffer(cudautils.arange(len(srkeys))))\n\n cache_key = (len(srkeys), srkeys.dtype, shuf.dtype)\n plan = plan_cache.get(cache_key)\n plan = apply_segsort(srkeys._column, shuf, dsegs, plan=plan)\n plan_cache[cache_key] = plan\n\n sorted_keys.append(srkeys) # keep sorted key cols\n # Determine segments\n dsegs, markers = cudautils.find_segments(\n srkeys.to_gpu_array(), dsegs, markers=markers\n )\n # Shuffle\n rowidcol = rowidcol.take(shuf.to_gpu_array(), ignore_index=True)\n\n reordering_indices = rowidcol.to_gpu_array()\n return sorted_keys, reordering_indices, Series(dsegs)\n\n def _group_shuffle(self, src_df, reordering_indices, out_df):\n \"\"\"Shuffle columns in *src_df* with *reordering_indices*\n and store the new columns into *out_df*\n \"\"\"\n src_df = src_df.to_frame() if isinstance(src_df, Series) else src_df\n for k in src_df.columns:\n col = src_df[k].reset_index(drop=True)\n newcol = col.take(reordering_indices, ignore_index=True)\n out_df[k] = newcol\n return out_df\n\n def agg(self, args):\n \"\"\"Invoke aggregation functions on the groups.\n\n Parameters\n ----------\n args: dict, list, str, callable\n - str\n The aggregate function name.\n - callable\n The aggregate function.\n - list\n List of *str* or *callable* of the aggregate function.\n - dict\n key-value pairs of source column name and list of\n aggregate functions as *str* or *callable*.\n\n Returns\n -------\n result : DataFrame\n\n Notes\n -----\n \"\"\"\n\n def _get_function(x):\n if isinstance(x, str):\n return self._NAMED_FUNCTIONS[x]\n else:\n return x\n\n functors = OrderedDict()\n if isinstance(args, (tuple, list)):\n for k in self._val_columns:\n functors[k] = [_get_function(x) for x in args]\n\n elif isinstance(args, dict):\n for k, v in args.items():\n functors[k] = (\n [_get_function(v)]\n if not isinstance(v, (tuple, list))\n else [_get_function(x) for x in v]\n )\n else:\n return self.agg([args])\n return self._agg_groups(functors)\n\n _auto_generate_grouper_agg(locals())\n\n def apply(self, function):\n \"\"\"Apply a python transformation function over the grouped chunk.\n\n\n Parameters\n ----------\n func : function\n The python transformation function that will be applied\n on the grouped chunk.\n\n Examples\n --------\n .. code-block:: python\n\n from cudf import DataFrame\n df = DataFrame()\n df['key'] = [0, 0, 1, 1, 2, 2, 2]\n df['val'] = [0, 1, 2, 3, 4, 5, 6]\n groups = df.groupby(['key'], method='cudf')\n\n # Define a function to apply to each row in a group\n def mult(df):\n df['out'] = df['key'] * df['val']\n return df\n\n result = groups.apply(mult)\n print(result)\n\n Output:\n\n .. code-block:: python\n\n key val out\n 0 0 0 0\n 1 0 1 0\n 2 1 2 2\n 3 1 3 3\n 4 2 4 8\n 5 2 5 10\n 6 2 6 12\n \"\"\"\n if not callable(function):\n raise TypeError(\"type {!r} is not callable\", type(function))\n\n df, segs = self.as_df()\n ends = chain(segs[1:], [None])\n chunks = [df[s:e] for s, e in zip(segs, ends)]\n return concat([function(chk) for chk in chunks])\n\n def apply_grouped(self, function, **kwargs):\n \"\"\"Apply a transformation function over the grouped chunk.\n\n This uses numba's CUDA JIT compiler to convert the Python\n transformation function into a CUDA kernel, thus will have a\n compilation overhead during the first run.\n\n Parameters\n ----------\n func : function\n The transformation function that will be executed on the CUDA GPU.\n incols: list\n A list of names of input columns.\n outcols: list\n A dictionary of output column names and their dtype.\n kwargs : dict\n name-value of extra arguments. These values are passed directly into\n the function.\n\n Examples\n --------\n .. code-block:: python\n\n from cudf import DataFrame\n from numba import cuda\n import numpy as np\n\n df = DataFrame()\n df['key'] = [0, 0, 1, 1, 2, 2, 2]\n df['val'] = [0, 1, 2, 3, 4, 5, 6]\n groups = df.groupby(['key'], method='cudf')\n\n # Define a function to apply to each group\n def mult_add(key, val, out1, out2):\n for i in range(cuda.threadIdx.x, len(key), cuda.blockDim.x):\n out1[i] = key[i] * val[i]\n out2[i] = key[i] + val[i]\n\n result = groups.apply_grouped(mult_add,\n incols=['key', 'val'],\n outcols={'out1': np.int32,\n 'out2': np.int32},\n # threads per block\n tpb=8)\n\n print(result)\n\n Output:\n\n .. code-block:: python\n\n key val out1 out2\n 0 0 0 0 0\n 1 0 1 0 1\n 2 1 2 2 3\n 3 1 3 3 4\n 4 2 4 8 6\n 5 2 5 10 7\n 6 2 6 12 8\n\n\n\n .. code-block:: python\n\n import cudf\n import numpy as np\n from numba import cuda\n import pandas as pd\n from random import randint\n\n\n # Create a random 15 row dataframe with one categorical\n # feature and one random integer valued feature\n df = cudf.DataFrame(\n {\n \"cat\": [1] * 5 + [2] * 5 + [3] * 5,\n \"val\": [randint(0, 100) for _ in range(15)],\n }\n )\n\n # Group the dataframe by its categorical feature\n groups = df.groupby(\"cat\", method=\"cudf\")\n\n # Define a kernel which takes the moving average of a\n # sliding window\n def rolling_avg(val, avg):\n win_size = 3\n for row, i in enumerate(range(cuda.threadIdx.x,\n len(val), cuda.blockDim.x)):\n if row < win_size - 1:\n # If there is not enough data to fill the window,\n # take the average to be NaN\n avg[i] = np.nan\n else:\n total = 0\n for j in range(i - win_size + 1, i + 1):\n total += val[j]\n avg[i] = total / win_size\n\n # Compute moving avgs on all groups\n results = groups.apply_grouped(rolling_avg,\n incols=['val'],\n outcols=dict(avg=np.float64))\n print(\"Results:\", results)\n\n # Note this gives the same result as its pandas equivalent\n pdf = df.to_pandas()\n pd_results = pdf.groupby('cat')['val'].rolling(3).mean()\n\n\n Output:\n\n .. code-block:: python\n\n Results:\n cat val avg\n 0 1 16\n 1 1 45\n 2 1 62 41.0\n 3 1 45 50.666666666666664\n 4 1 26 44.333333333333336\n 5 2 5\n 6 2 51\n 7 2 77 44.333333333333336\n 8 2 1 43.0\n 9 2 46 41.333333333333336\n [5 more rows]\n\n This is functionally equivalent to `pandas.DataFrame.Rolling\n <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rolling.html>`_\n\n \"\"\"\n if not callable(function):\n raise TypeError(\"type {!r} is not callable\", type(function))\n\n df, segs = self.as_df()\n kwargs.update({\"chunks\": segs})\n return df.apply_chunks(function, **kwargs)\n\n\nregister_distributed_serializer(Groupby)\n"
] | [
[
"numpy.asarray",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
hsc1993/GaussianGND | [
"71291384268165a8310d872c055bba4e63532336"
] | [
"main.py"
] | [
"#!/usr/bin/env python\nimport scipy\nfrom scipy import spatial\nfrom scipy.spatial import ConvexHull\n\nimport datetime\nimport gnd_functions\nimport os\nfrom os import path\n\n\n\n#\n# # Face class is used for the combining of multiple coplanar faces of a polyhedron for better visualization and performance\n# class Faces():\n# def __init__(self, tri, sig_dig=3, method=\"convexhull\"):\n# self.method = method\n# self.tri = np.around(np.array(tri), sig_dig)\n# self.grpinx = list(range(len(tri))) # group index\n# norms = np.around([self.norm(s) for s in self.tri], sig_dig) #\n# _, self.inv = np.unique(norms, return_inverse=True, axis=0) # self.inv:indices of the unique array\n#\n# def norm(self, sq):\n# cr = np.cross(sq[2] - sq[0], sq[1] - sq[0])\n# return np.abs(cr / np.linalg.norm(cr))\n#\n# def isneighbor(self, tr1, tr2):\n# a = np.concatenate((tr1, tr2), axis=0)\n# return len(a) == len(np.unique(a, axis=0)) + 2\n#\n# def order(self, v):\n# v = np.unique(v, axis=0)\n# n = self.norm(v[:3])\n# y = np.cross(n, v[1] - v[0])\n# y = y / np.linalg.norm(y)\n# c = np.dot(v, np.c_[v[1] - v[0], y])\n# if self.method == \"convexhull\":\n# h = scipy.spatial.ConvexHull(c)\n# return v[h.vertices]\n# else:\n# mean = np.mean(c, axis=0)\n# d = c - mean\n# s = np.arctan2(d[:, 0], d[:, 1])\n# return v[np.argsort(s)]\n#\n# def simplify(self):\n# for i, tri1 in enumerate(self.tri):\n# for j, tri2 in enumerate(self.tri):\n# if j > i:\n# # if two tri are neighbors and their norm is the same, override bigger group index with smaller one\n# if self.isneighbor(tri1, tri2) and \\\n# np.isclose(self.inv[i], self.inv[j], atol=1e-03):\n# self.grpinx[j] = self.grpinx[i]\n# groups = []\n# for i in np.unique(self.grpinx): # iterate through unique group indecies\n# u = self.tri[self.grpinx == i]\n# u = np.concatenate([d for d in u])\n# u = self.order(u)\n#\n# groups.append(u)\n#\n# return groups\n\n\n\ndef main():\n case_string = 'before'\n # case_string = 'during'\n # case_string = 'after'\n #\n # case_string = 'before_cubic_edgevariate'\n # case_string = 'during_cubic_edgevariate'\n # case_string = 'after_cubic_edgevariate'\n\n number_seeds_list = []\n n = int(input(\"Enter length of seeds' list : \"))\n for i in range(0, n):\n ele = int(input())\n number_seeds_list.append(ele) # adding the element\n\n for number_seeds in number_seeds_list:\n current_path = os.getcwd()\n target_path = current_path + '/' + case_string\n max_filenum = 1\n\n my_file = target_path + str(number_seeds) + '/n' + str(number_seeds) + '_vorvx' + str(\n max_filenum) + '.txt'\n print('my_file=', my_file)\n print('path.exists(my_file)=', path.exists(my_file))\n\n if path.exists(my_file):\n max_filenum = max_filenum + 1\n flag_max_filenum_found = 0\n my_file = target_path + str(number_seeds) + '/n' + str(number_seeds) + '_vorvx' + str(\n max_filenum) + '.txt'\n else:\n print('no file associated with this number of seed is in the directory')\n flag_max_filenum_found = 1\n\n while flag_max_filenum_found == 0:\n if path.exists(my_file):\n max_filenum = max_filenum + 1\n my_file = target_path + str(number_seeds) + '/n' + str(number_seeds) + '_vorvx' + str(\n max_filenum) + '.txt'\n else:\n flag_max_filenum_found = 1\n\n print('max_filenum=', max_filenum)\n for ii in range(1, max_filenum):\n begin_time = datetime.datetime.now()\n\n # use dislocation information modify range of voronoi cells span\n dislocation_file = open('MDdata_' + case_string + '/dislocation111.txt', \"r\")\n burgers_file = open('MDdata_' + case_string + '/dislocation111_burgers.txt', \"r\")\n\n if 'after' in case_string:\n bound = [[-112, 65], [-184, 48], [-191.8, -187]]\n else:\n bound = None\n dislocation_vertices, dislocation_seg_object_list = gnd_functions.dislocation_vertices_generation(dislocation_file,\n burgers_file, bound)\n print('len(dislocation_seg_object_list)=',len(dislocation_seg_object_list))\n\n gnd_sum = 0\n for dislocation in dislocation_seg_object_list:\n gnd_sum = gnd_sum + dislocation.gnd\n\n gnd_nonabs_sum = 0\n for dislocation in dislocation_seg_object_list:\n gnd_nonabs_sum = gnd_nonabs_sum + dislocation.gnd_nonabs\n\n total_length = 0\n for dislocation in dislocation_seg_object_list:\n total_length = total_length + dislocation.length\n\n # read and scale Voronoi cell vertices\n vorvx_file = case_string + str(number_seeds) + '/' + 'n{}_vorvx{}.txt'.format(number_seeds, ii)\n print('vorvx_file=', vorvx_file)\n vorvx_data_scaled = gnd_functions.voronoiVerticesRead(vorvx_file)\n\n # a list storing the volume of all cells\n cell_list = []\n cell_volume_list = []\n cell_length_list = []\n for idx, vorvx in enumerate(vorvx_data_scaled):\n hull = scipy.spatial.ConvexHull(vorvx, incremental=True)\n cell_list.append(hull)\n cell_volume_list.append(hull.volume)\n cell_length_list.append(pow(hull.volume, 1 / 3))\n\n cell_volume_average = 0\n for volume in cell_volume_list:\n cell_volume_average = cell_volume_average + volume\n\n mean_cell_length_list = sum(cell_length_list) / len(cell_length_list)\n cell_volume_average = cell_volume_average / len(cell_volume_list)\n cell_length_average = pow(cell_volume_average, 1 / 3)\n\n # associate start and stop point with Voronoi cells (initialize 'iscut' in the meantime)\n print('associate start and stop point with Voronoi cells')\n # determine which segs are cut\n gnd_functions.determine_iscut(dislocation_seg_object_list, vorvx_data_scaled)\n\n # generate dislocation subsegments (subsegment) if the parent dislocation is cut by cell boundaries\n # use subsegments to determine the intersection point with cell walls\n print('generate sub-dislocation segments')\n # dislocation_seg_object_list_with_intersection is the new list used to calculate GND signal\n dislocation_seg_object_list_with_intersection = []\n for idx_seg, seg in enumerate(dislocation_seg_object_list):\n # complete segs are directly added to the new list\n if seg.iscut != 1:\n dislocation_seg_object_list_with_intersection.append(seg)\n\n # segs with intersections are partitioned into subsegments\n if seg.iscut == 1:\n subsegmentEndpoint_list = gnd_functions.generateSubsegmentEndpoints(seg, cell_length_average)\n\n # create list of subsegments for intersection calculation\n # subsegment_list contains subsegments created by partitioning the seg of current for-loop\n subsegment_list = []\n for idx_subsegEndpoint, subsegEndpoint in enumerate(subsegmentEndpoint_list):\n # cell_id_list[idx_subsegEndpoint] is the ID of cell that contains subsegEndpoint\n subsegment_temp = []\n if idx_subsegEndpoint == len(subsegmentEndpoint_list) - 1:\n break\n subsegment_temp.append(subsegEndpoint)\n subsegment_temp.append(subsegmentEndpoint_list[idx_subsegEndpoint + 1])\n subsegment_list.append(subsegment_temp)\n\n # seg_new_endPoints contains the endpoints of original seg and intersection points that are obtained\n # through loop below\n seg_new_endPoints = []\n seg_new_endPoints.append(seg.start)\n for subsegment in subsegment_list:\n # for each subsegment, find its corresponding cell first\n commonPlaneVertices = gnd_functions.extractPlaneVertices(subsegment, vorvx_data_scaled)\n\n # then calculate intersection with common plane\n # if commonPlaneVertices is empty, it means the two endpoints of subsegments are not in neighboring cells, ignore this scenario\n if len(commonPlaneVertices) > 3:\n intersectionPoint = gnd_functions.calIntersection(commonPlaneVertices, subsegment)\n seg_new_endPoints.append(intersectionPoint)\n\n seg_new_endPoints.append(seg.stop)\n\n # use new endpoints to generate new segments\n for idx in range(len(seg_new_endPoints) - 1):\n seg_new = gnd_functions.Dislocation_Segment(seg_new_endPoints[idx], seg_new_endPoints[idx + 1], seg.burgers)\n\n # problem! some id_cell_new are identical\n dislocation_seg_object_list_with_intersection.append(seg_new)\n\n # num of segs = num of endpoints-1\n if idx == len(seg_new_endPoints) - 1:\n break\n\n # associate start and stop points for each new segments with cells\n for seg in dislocation_seg_object_list_with_intersection:\n seg.start_voroid = gnd_functions.associatePointsWithCells(seg.start, vorvx_data_scaled)\n seg.stop_voroid = gnd_functions.associatePointsWithCells(seg.start, vorvx_data_scaled)\n\n # calculate segment-cell relation\n segment_cell_list = []\n for seg in dislocation_seg_object_list_with_intersection:\n seg.idx_cell_belong = gnd_functions.associatePointsWithCells(seg.start, vorvx_data_scaled)\n segment_cell_list.append(seg.idx_cell_belong)\n\n voro_cell_list = []\n for idx_vorvx, vorvx in enumerate(vorvx_data_scaled):\n voro_cell = gnd_functions.Voronoi_Cell(vorvx)\n voro_cell_list.append(voro_cell)\n\n # determine each cell contains which dislocation segments\n for idx_seg, seg in enumerate(dislocation_seg_object_list_with_intersection):\n if seg.start_voroid != seg.stop_voroid:\n print('found trouble')\n start = seg.start\n stop = seg.stop\n middle_point = [0.5 * (start[0] + stop[0]), 0.5 * (start[1] + stop[1]),\n 0.5 * (start[2] + stop[2])]\n middle_point_vorvxid = gnd_functions.associatePointsWithCells(middle_point, vorvx_data_scaled)\n\n if middle_point_vorvxid == idx_vorvx:\n voro_cell.dislocation_start_included.append(idx_seg)\n\n for idx_seg, seg in enumerate(dislocation_seg_object_list_with_intersection):\n if (seg.start_voroid == idx_vorvx) & (seg.stop_voroid == idx_vorvx):\n voro_cell.dislocation_start_included.append(idx_seg)\n\n voro_gnd_list = gnd_functions.addGNDToCells(voro_cell_list, dislocation_seg_object_list_with_intersection)\n\n count_voro_gnd_nonzero = 0\n for voro_gnd in voro_gnd_list:\n if voro_gnd != 0:\n count_voro_gnd_nonzero = count_voro_gnd_nonzero + 1\n\n f_dislocation_cell_belong = open(\n (case_string + str(number_seeds) + '/' + \"{}_plot_dislocation_seg_cell_belong{}.dat\".format(\n number_seeds, ii)),\n \"w+\")\n for seg in dislocation_seg_object_list_with_intersection:\n flag_end = 0\n if seg == dislocation_seg_object_list_with_intersection[-1]:\n flag_end = 1\n line_start = ['%f,' % abs(seg.idx_cell_belong)]\n f_dislocation_cell_belong.writelines(line_start)\n if flag_end == 0:\n f_dislocation_cell_belong.write('\\n')\n\n f_gnd = open((case_string + str(number_seeds) + '/' + \"{}_plot_voro_gnd{}.dat\".format(number_seeds, ii)),\n \"w+\")\n for gnd in voro_gnd_list:\n f_gnd.write('%f' % gnd)\n f_gnd.write('\\n')\n\n f_volume = open(\n (case_string + str(number_seeds) + '/' + \"{}_plot_voro_volume{}.dat\".format(number_seeds, ii)),\n \"w+\")\n for volume in cell_volume_list:\n f_volume.write('%f' % volume)\n f_volume.write('\\n')\n\n f_dislocation_start = open(\n (case_string + str(number_seeds) + '/' + \"{}_plot_dislocation_seg_start{}.dat\".format(number_seeds,\n ii)), \"w+\")\n for seg in dislocation_seg_object_list:\n flag_end = 0\n if seg == dislocation_seg_object_list[-1]:\n flag_end = 1\n line_start = ['%f,' % seg.start[0], '%f,' % seg.start[1], '%f' % seg.start[2]]\n f_dislocation_start.writelines(line_start)\n if flag_end == 0:\n f_dislocation_start.write('\\n')\n\n f_dislocation_end = open(\n (case_string + str(number_seeds) + '/' + \"{}_plot_dislocation_seg_end{}.dat\".format(number_seeds, ii)),\n \"w+\")\n for seg in dislocation_seg_object_list:\n flag_end = 0\n if seg == dislocation_seg_object_list[-1]:\n flag_end = 1\n line_end = ['%f,' % seg.stop[0], '%f,' % seg.stop[1], '%f' % seg.stop[2]]\n f_dislocation_end.writelines(line_end)\n if flag_end == 0:\n f_dislocation_end.write('\\n')\n\n f_vorvx_scaled = open(\n (case_string + str(number_seeds) + '/' + \"{}_plot_vorvx_scaled{}.dat\".format(number_seeds, ii)), \"w+\")\n for vorvx in vorvx_data_scaled:\n for vertice in vorvx:\n line_vertice = ['%f,' % vertice[0], '%f,' % vertice[1], '%f' % vertice[2]]\n f_vorvx_scaled.writelines(line_vertice)\n f_vorvx_scaled.write('\\n')\n f_vorvx_scaled.write('new_seg\\n')\n\n f_vorvx_scaled = open(\n (case_string + str(number_seeds) + '/' + \"{}_cpu_time{}.dat\".format(number_seeds, ii)), \"w+\")\n f_vorvx_scaled.writelines(str(datetime.datetime.now() - begin_time))\n f_vorvx_scaled.write('\\n')\n\n f_config = open((case_string + str(number_seeds) + '/' + \"{}_config{}.dat\".format(number_seeds, ii)), \"w+\")\n f_config.writelines('cell_length_average = ' + str(cell_length_average) + '\\n')\n f_config.writelines('cell_volume_average = ' + str(cell_volume_average) + '\\n')\n f_config.writelines('gnd_sum = ' + str(gnd_sum) + '\\n')\n f_config.writelines('gnd_nonabs_sum = ' + str(gnd_nonabs_sum) + '\\n')\n f_config.writelines('total_length = ' + str(total_length) + '\\n')\n f_config.writelines('number_seeds = ' + str(number_seeds) + '\\n')\n\n print('cell_length_average = ', cell_length_average)\n print('cell_volume_average = ', cell_volume_average)\n print('gnd_sum = ', gnd_sum)\n print('gnd_nonabs_sum = ', gnd_nonabs_sum)\n print('total_length = ', total_length)\n print('num_seeds = ', number_seeds)\n\n\nif __name__ == \"__main__\":\n main()\n"
] | [
[
"scipy.spatial.ConvexHull"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ellagupta/optical-rl-gym | [
"184d9fd8765060a3165e3dfbda8586f9437bd5d1"
] | [
"optical_rl_gym/envs/deeprmsa_env_sbpp.py"
] | [
"import gym\r\nimport numpy as np\r\n\r\nfrom .rmsa_env_sbpp import RMSASBPPEnv\r\nfrom .optical_network_env import OpticalNetworkEnv\r\n\r\n\r\nclass DeepRMSASBPPEnv(RMSASBPPEnv):\r\n\r\n def __init__(self, topology=None, j=1,\r\n episode_length=1000,\r\n mean_service_holding_time=25.0,\r\n mean_service_inter_arrival_time=.1,\r\n num_spectrum_resources=1000,\r\n node_request_probabilities=None,\r\n seed=None,\r\n k_paths=5,\r\n allow_rejection=False): # Do we need to add another J?\r\n super().__init__(topology=topology,\r\n episode_length=episode_length,\r\n load=mean_service_holding_time / mean_service_inter_arrival_time,\r\n mean_service_holding_time=mean_service_holding_time,\r\n num_spectrum_resources=num_spectrum_resources,\r\n node_request_probabilities=node_request_probabilities,\r\n seed=seed,\r\n k_paths=k_paths,\r\n allow_rejection=allow_rejection,\r\n reset=False)\r\n\r\n self.j = j\r\n shape = 1 + 2 * self.topology.number_of_nodes() + (2 * self.j + 3) * self.k_paths * 2 # Doubled\r\n self.observation_space = gym.spaces.Box(low=0, high=1, dtype=np.uint8, shape=(shape,))\r\n self.action_space = gym.spaces.Discrete(\r\n self.k_paths * self.j * 2 + self.reject_action) # Need to be doubled (modified)\r\n self.action_space.seed(self.rand_seed)\r\n self.observation_space.seed(self.rand_seed)\r\n self.reset(only_counters=False)\r\n\r\n def step(self, action: int):\r\n if action < self.k_paths * self.j * 2: # action is for assigning a path needs to be doubled or deleted (get_path_block_id takes it into consideration)\r\n # path, block = self._get_path_block_id(action)\r\n working_path, block_working, backup_path, block_backup = self._get_path_block_id(action)\r\n # print(\"------------------\")\r\n # print(\"Working path: \", working_path)\r\n #Maybe add prints\r\n working_initial_indices, working_lengths = self.get_available_blocks_working(working_path) #here\r\n # print(\"Initial indices working : {}; LengthsW :{} \".format(working_initial_indices, working_lengths))\r\n backup_initial_indices, backup_lengths = self.get_available_blocks_backup(backup_path) #here\r\n backup_dpp_initial_indices, backup_lengths_dpp = self.get_available_blocks_working(backup_path)\r\n # print(\"BU path: \", backup_path)\r\n # print(\"Initial indices BU : {}; LengthsB :{} \".format(backup_initial_indices, backup_lengths))\r\n if (block_working < len(working_initial_indices)) and (block_backup < len(backup_initial_indices)) and (block_backup < len(backup_dpp_initial_indices)): #shared and dedicated\r\n return super().step([working_path, working_initial_indices[block_working], backup_path,\r\n backup_initial_indices[block_backup], backup_path, backup_dpp_initial_indices[block_backup]])\r\n\r\n if ((block_working < len(working_initial_indices)) and (block_backup < len(backup_dpp_initial_indices))): #shared or dedicated only\r\n return super().step([working_path, working_initial_indices[block_working], backup_path, \r\n backup_dpp_initial_indices[block_backup], backup_path, backup_dpp_initial_indices[block_backup]])\r\n\r\n if ((block_working < len(working_initial_indices)) and (block_backup < len(backup_initial_indices))): #shared or dedicated only\r\n return super().step([working_path, working_initial_indices[block_working], backup_path,\r\n backup_initial_indices[block_backup], backup_path, backup_initial_indices[block_backup]])\r\n\r\n else:\r\n return super().step([self.k_paths, self.num_spectrum_resources,self.k_paths, self.num_spectrum_resources,self.k_paths, self.num_spectrum_resources])\r\n else:\r\n return super().step([self.k_paths, self.num_spectrum_resources,self.k_paths, self.num_spectrum_resources,self.k_paths, self.num_spectrum_resources]) \r\n\r\n def observation(self):\r\n # observation space defined as in https://github.com/xiaoliangchenUCD/DeepRMSA/blob/eb2f2442acc25574e9efb4104ea245e9e05d9821/DeepRMSA_Agent.py#L384\r\n source_destination_tau = np.zeros((2, self.topology.number_of_nodes()))\r\n min_node = min(self.service.source_id, self.service.destination_id)\r\n max_node = max(self.service.source_id, self.service.destination_id)\r\n source_destination_tau[0, min_node] = 1\r\n source_destination_tau[1, max_node] = 1\r\n spectrum_obs = np.full((self.k_paths*2, (2 * self.j + 3)), fill_value=-1.)\r\n for idp, path in enumerate(self.k_shortest_paths[self.service.source, self.service.destination]):\r\n available_slots = self.get_available_slots_working(path)\r\n num_slots = self.get_number_slots(path)\r\n initial_indices, lengths = self.get_available_blocks_working(idp)\r\n\r\n for idb, (initial_index, length) in enumerate(zip(initial_indices, lengths)):\r\n # initial slot index\r\n spectrum_obs[idp, idb * 2 + 0] = 2 * (\r\n initial_index - .5 * self.num_spectrum_resources) / self.num_spectrum_resources\r\n\r\n # number of contiguous FS available\r\n spectrum_obs[idp, idb * 2 + 1] = (length - 8) / 8\r\n spectrum_obs[idp, self.j * 2] = (num_slots - 5.5) / 3.5 # number of FSs necessary\r\n\r\n idx, values, lengths = DeepRMSASBPPEnv.rle(available_slots)\r\n\r\n av_indices = np.argwhere(values == 1) # getting indices which have value 1\r\n spectrum_obs[idp, self.j * 2 + 1] = 2 * (np.sum(\r\n available_slots) - .5 * self.num_spectrum_resources) / self.num_spectrum_resources # total number available FSs\r\n spectrum_obs[idp, self.j * 2 + 2] = (np.mean(\r\n lengths[av_indices]) - 4) / 4 # avg. number of FS blocks available\r\n bit_rate_obs = np.zeros((1, 1))\r\n bit_rate_obs[0, 0] = self.service.bit_rate / 100\r\n \r\n return np.concatenate((bit_rate_obs, source_destination_tau.reshape((1, np.prod(source_destination_tau.shape))),\r\n spectrum_obs.reshape((1, np.prod(spectrum_obs.shape)))), axis=1) \\\r\n .reshape(self.observation_space.shape)\r\n\r\n def reward(self):\r\n if self.service.shared:\r\n return 2\r\n\r\n if self.service.dpp:\r\n return 1\r\n \r\n if not self.service.accepted:\r\n return -1\r\n\r\n def reset(self, only_counters=True):\r\n return super().reset(only_counters=only_counters)\r\n\r\n def _get_path_block_id(self, action: int) -> (int, int, int, int): \r\n \r\n #Changed to take into account the 4 variables \r\n working_path = action // (self.j * self.j * self.k_paths) % self.k_paths\r\n\r\n block_working = action // (self.j*self.k_paths) %self.j \r\n\r\n backup_path = action % (self.j*self.k_paths) // self.j\r\n\r\n block_backup = action % self.j\r\n\r\n return working_path, block_working, backup_path, block_backup\r\n\r\n\r\ndef shortest_path_first_fit(env: DeepRMSASBPPEnv) -> int:\r\n if not env.allow_rejection:\r\n return 0\r\n else:\r\n initial_indices, lengths = env.get_available_blocks(0)\r\n if len(initial_indices) > 0: # if there are available slots\r\n return 0\r\n else:\r\n return env.k_paths * env.j\r\n\r\n\r\ndef shortest_available_path_first_fit(env: DeepRMSASBPPEnv) -> int:\r\n for idp, path in enumerate(env.k_shortest_paths[env.service.source, env.service.destination]):\r\n initial_indices, lengths = env.get_available_blocks(idp)\r\n if len(initial_indices) > 0: # if there are available slots\r\n return idp * env.j # this path uses the first one\r\n return env.k_paths * env.j"
] | [
[
"numpy.argwhere",
"numpy.full",
"numpy.mean",
"numpy.prod",
"numpy.zeros",
"numpy.sum"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
TungyuYoung/PaSST | [
"d78688c39faf62b067256e58fa40c3fbe13d9906"
] | [
"models/passt.py"
] | [
"\"\"\"\nMost of this code comes from the timm library.\nWe tried to disentangle from the timm library version.\n\nAdapted from https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py\n\n\"\"\"\nimport math\nimport logging\nimport warnings\nfrom functools import partial\nfrom collections import OrderedDict\nfrom copy import deepcopy\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom timm.models.layers.helpers import to_2tuple\n\nfrom .helpers.vit_helpers import update_default_cfg_and_kwargs, DropPath, trunc_normal_, build_model_with_cfg\n\n_logger = logging.getLogger()\n\nIMAGENET_DEFAULT_MEAN = (0.485, 0.456, 0.406)\nIMAGENET_DEFAULT_STD = (0.229, 0.224, 0.225)\nIMAGENET_INCEPTION_MEAN = (0.5, 0.5, 0.5)\nIMAGENET_INCEPTION_STD = (0.5, 0.5, 0.5)\n\n\ndef _cfg(url='', **kwargs):\n return {\n 'url': url,\n 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': None,\n 'crop_pct': .9, 'interpolation': 'bicubic', 'fixed_input_size': True,\n 'mean': IMAGENET_INCEPTION_MEAN, 'std': IMAGENET_INCEPTION_STD,\n 'first_conv': 'patch_embed.proj', 'classifier': 'head',\n **kwargs\n }\n\n\ndefault_cfgs = {\n # patch models (weights from official Google JAX impl)\n 'vit_tiny_patch16_224': _cfg(\n url='https://storage.googleapis.com/vit_models/augreg/'\n 'Ti_16-i21k-300ep-lr_0.001-aug_none-wd_0.03-do_0.0-sd_0.0--imagenet2012-steps_20k-lr_0.03-res_224.npz'),\n 'vit_tiny_patch16_384': _cfg(\n url='https://storage.googleapis.com/vit_models/augreg/'\n 'Ti_16-i21k-300ep-lr_0.001-aug_none-wd_0.03-do_0.0-sd_0.0--imagenet2012-steps_20k-lr_0.03-res_384.npz',\n input_size=(3, 384, 384), crop_pct=1.0),\n 'vit_small_patch32_224': _cfg(\n url='https://storage.googleapis.com/vit_models/augreg/'\n 'S_32-i21k-300ep-lr_0.001-aug_light1-wd_0.03-do_0.0-sd_0.0--imagenet2012-steps_20k-lr_0.03-res_224.npz'),\n 'vit_small_patch32_384': _cfg(\n url='https://storage.googleapis.com/vit_models/augreg/'\n 'S_32-i21k-300ep-lr_0.001-aug_light1-wd_0.03-do_0.0-sd_0.0--imagenet2012-steps_20k-lr_0.03-res_384.npz',\n input_size=(3, 384, 384), crop_pct=1.0),\n 'vit_small_patch16_224': _cfg(\n url='https://storage.googleapis.com/vit_models/augreg/'\n 'S_16-i21k-300ep-lr_0.001-aug_light1-wd_0.03-do_0.0-sd_0.0--imagenet2012-steps_20k-lr_0.03-res_224.npz'),\n 'vit_small_patch16_384': _cfg(\n url='https://storage.googleapis.com/vit_models/augreg/'\n 'S_16-i21k-300ep-lr_0.001-aug_light1-wd_0.03-do_0.0-sd_0.0--imagenet2012-steps_20k-lr_0.03-res_384.npz',\n input_size=(3, 384, 384), crop_pct=1.0),\n 'vit_base_patch32_224': _cfg(\n url='https://storage.googleapis.com/vit_models/augreg/'\n 'B_32-i21k-300ep-lr_0.001-aug_medium1-wd_0.03-do_0.0-sd_0.0--imagenet2012-steps_20k-lr_0.03-res_224.npz'),\n 'vit_base_patch32_384': _cfg(\n url='https://storage.googleapis.com/vit_models/augreg/'\n 'B_32-i21k-300ep-lr_0.001-aug_light1-wd_0.1-do_0.0-sd_0.0--imagenet2012-steps_20k-lr_0.03-res_384.npz',\n input_size=(3, 384, 384), crop_pct=1.0),\n 'vit_base_patch16_224': _cfg(\n url='https://storage.googleapis.com/vit_models/augreg/'\n 'B_16-i21k-300ep-lr_0.001-aug_medium1-wd_0.1-do_0.0-sd_0.0--imagenet2012-steps_20k-lr_0.01-res_224.npz'),\n 'vit_base_patch16_384': _cfg(\n url='https://storage.googleapis.com/vit_models/augreg/'\n 'B_16-i21k-300ep-lr_0.001-aug_medium1-wd_0.1-do_0.0-sd_0.0--imagenet2012-steps_20k-lr_0.01-res_384.npz',\n input_size=(3, 384, 384), crop_pct=1.0),\n 'vit_large_patch32_224': _cfg(\n url='', # no official model weights for this combo, only for in21k\n ),\n 'vit_large_patch32_384': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-vitjx/jx_vit_large_p32_384-9b920ba8.pth',\n input_size=(3, 384, 384), crop_pct=1.0),\n 'vit_large_patch16_224': _cfg(\n url='https://storage.googleapis.com/vit_models/augreg/'\n 'L_16-i21k-300ep-lr_0.001-aug_medium1-wd_0.1-do_0.1-sd_0.1--imagenet2012-steps_20k-lr_0.01-res_224.npz'),\n 'vit_large_patch16_384': _cfg(\n url='https://storage.googleapis.com/vit_models/augreg/'\n 'L_16-i21k-300ep-lr_0.001-aug_medium1-wd_0.1-do_0.1-sd_0.1--imagenet2012-steps_20k-lr_0.01-res_384.npz',\n input_size=(3, 384, 384), crop_pct=1.0),\n\n # patch models, imagenet21k (weights from official Google JAX impl)\n 'vit_tiny_patch16_224_in21k': _cfg(\n url='https://storage.googleapis.com/vit_models/augreg/Ti_16-i21k-300ep-lr_0.001-aug_none-wd_0.03-do_0.0-sd_0.0.npz',\n num_classes=21843),\n 'vit_small_patch32_224_in21k': _cfg(\n url='https://storage.googleapis.com/vit_models/augreg/S_32-i21k-300ep-lr_0.001-aug_light1-wd_0.03-do_0.0-sd_0.0.npz',\n num_classes=21843),\n 'vit_small_patch16_224_in21k': _cfg(\n url='https://storage.googleapis.com/vit_models/augreg/S_16-i21k-300ep-lr_0.001-aug_light1-wd_0.03-do_0.0-sd_0.0.npz',\n num_classes=21843),\n 'vit_base_patch32_224_in21k': _cfg(\n url='https://storage.googleapis.com/vit_models/augreg/B_32-i21k-300ep-lr_0.001-aug_medium1-wd_0.03-do_0.0-sd_0.0.npz',\n num_classes=21843),\n 'vit_base_patch16_224_in21k': _cfg(\n url='https://storage.googleapis.com/vit_models/augreg/B_16-i21k-300ep-lr_0.001-aug_medium1-wd_0.1-do_0.0-sd_0.0.npz',\n num_classes=21843),\n 'vit_large_patch32_224_in21k': _cfg(\n url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-vitjx/jx_vit_large_patch32_224_in21k-9046d2e7.pth',\n num_classes=21843),\n 'vit_large_patch16_224_in21k': _cfg(\n url='https://storage.googleapis.com/vit_models/augreg/L_16-i21k-300ep-lr_0.001-aug_medium1-wd_0.1-do_0.1-sd_0.1.npz',\n num_classes=21843),\n 'vit_huge_patch14_224_in21k': _cfg(\n url='https://storage.googleapis.com/vit_models/imagenet21k/ViT-H_14.npz',\n hf_hub='timm/vit_huge_patch14_224_in21k',\n num_classes=21843),\n\n # SAM trained models (https://arxiv.org/abs/2106.01548)\n 'vit_base_patch32_sam_224': _cfg(\n url='https://storage.googleapis.com/vit_models/sam/ViT-B_32.npz'),\n 'vit_base_patch16_sam_224': _cfg(\n url='https://storage.googleapis.com/vit_models/sam/ViT-B_16.npz'),\n\n # deit models (FB weights)\n 'deit_tiny_patch16_224': _cfg(\n url='https://dl.fbaipublicfiles.com/deit/deit_tiny_patch16_224-a1311bcf.pth',\n mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD),\n 'deit_small_patch16_224': _cfg(\n url='https://dl.fbaipublicfiles.com/deit/deit_small_patch16_224-cd65a155.pth',\n mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD),\n 'deit_base_patch16_224': _cfg(\n url='https://dl.fbaipublicfiles.com/deit/deit_base_patch16_224-b5f2ef4d.pth',\n mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD),\n 'deit_base_patch16_384': _cfg(\n url='https://dl.fbaipublicfiles.com/deit/deit_base_patch16_384-8de9b5d1.pth',\n mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, input_size=(3, 384, 384), crop_pct=1.0),\n 'deit_tiny_distilled_patch16_224': _cfg(\n url='https://dl.fbaipublicfiles.com/deit/deit_tiny_distilled_patch16_224-b40b3cf7.pth',\n mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, classifier=('head', 'head_dist')),\n 'deit_small_distilled_patch16_224': _cfg(\n url='https://dl.fbaipublicfiles.com/deit/deit_small_distilled_patch16_224-649709d9.pth',\n mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, classifier=('head', 'head_dist')),\n 'deit_base_distilled_patch16_224': _cfg(\n url='https://dl.fbaipublicfiles.com/deit/deit_base_distilled_patch16_224-df68dfff.pth',\n mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, classifier=('head', 'head_dist')),\n 'deit_base_distilled_patch16_384': _cfg(\n url='https://dl.fbaipublicfiles.com/deit/deit_base_distilled_patch16_384-d0272ac0.pth',\n mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, input_size=(3, 384, 384), crop_pct=1.0,\n classifier=('head', 'head_dist')),\n\n # ViT ImageNet-21K-P pretraining by MILL\n 'vit_base_patch16_224_miil_in21k': _cfg(\n url='https://miil-public-eu.oss-eu-central-1.aliyuncs.com/model-zoo/ImageNet_21K_P/models/timm/vit_base_patch16_224_in21k_miil.pth',\n mean=(0, 0, 0), std=(1, 1, 1), crop_pct=0.875, interpolation='bilinear', num_classes=11221,\n ),\n 'vit_base_patch16_224_miil': _cfg(\n url='https://miil-public-eu.oss-eu-central-1.aliyuncs.com/model-zoo/ImageNet_21K_P/models/timm'\n '/vit_base_patch16_224_1k_miil_84_4.pth',\n mean=(0, 0, 0), std=(1, 1, 1), crop_pct=0.875, interpolation='bilinear',\n ),\n # PaSST\n 'passt_s_swa_p16_128_ap476': _cfg(\n url='https://github.com/kkoutini/PaSST/releases/download/v0.0.1-audioset/passt-s-f128-p16-s10-ap.476-swa.pt',\n mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, input_size=(1, 128, 998), crop_pct=1.0,\n classifier=('head.1', 'head_dist'), num_classes=527),\n 'passt_s_swa_p16_128_ap4761': _cfg(\n url='https://github.com/kkoutini/PaSST/releases/download/v0.0.2-audioset/passt-s-f128-p16-s10-ap.4761-swa.pt',\n mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, input_size=(1, 128, 998), crop_pct=1.0,\n classifier=('head.1', 'head_dist'), num_classes=527),\n 'passt_s_p16_128_ap472': _cfg(\n url='https://github.com/kkoutini/PaSST/releases/download/v0.0.2-audioset/passt-s-f128-p16-s10-ap.472.pt',\n mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, input_size=(1, 128, 998), crop_pct=1.0,\n classifier=('head.1', 'head_dist'), num_classes=527),\n 'passt_s_p16_s16_128_ap468': _cfg(\n url='https://github.com/kkoutini/PaSST/releases/download/v0.0.2-audioset/passt-s-f128-p16-s16-ap.468.pt',\n mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, input_size=(1, 128, 998), crop_pct=1.0,\n classifier=('head.1', 'head_dist'), num_classes=527),\n 'passt_s_swa_p16_s16_128_ap473': _cfg(\n url='https://github.com/kkoutini/PaSST/releases/download/v0.0.2-audioset/passt-s-f128-p16-s16-ap.473-swa.pt',\n mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, input_size=(1, 128, 998), crop_pct=1.0,\n classifier=('head.1', 'head_dist'), num_classes=527),\n 'passt_s_swa_p16_s14_128_ap471': _cfg(\n url='https://github.com/kkoutini/PaSST/releases/download/v0.0.2-audioset/passt-s-f128-p16-s14-ap.471-swa.pt',\n mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, input_size=(1, 128, 998), crop_pct=1.0,\n classifier=('head.1', 'head_dist'), num_classes=527),\n 'passt_s_p16_s14_128_ap469': _cfg(\n url='https://github.com/kkoutini/PaSST/releases/download/v0.0.2-audioset/passt-s-f128-p16-s14-ap.469.pt',\n mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, input_size=(1, 128, 998), crop_pct=1.0,\n classifier=('head.1', 'head_dist'), num_classes=527),\n 'passt_s_swa_p16_s12_128_ap473': _cfg(\n url='https://github.com/kkoutini/PaSST/releases/download/v0.0.2-audioset/passt-s-f128-p16-s12-ap.473-swa.pt',\n mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, input_size=(1, 128, 998), crop_pct=1.0,\n classifier=('head.1', 'head_dist'), num_classes=527),\n 'passt_s_p16_s12_128_ap470': _cfg(\n url='https://github.com/kkoutini/PaSST/releases/download/v0.0.2-audioset/passt-s-f128-p16-s12-ap.470.pt',\n mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, input_size=(1, 128, 998), crop_pct=1.0,\n classifier=('head.1', 'head_dist'), num_classes=527),\n 'passt_s_swa_f128_stfthop100_p16_s10_ap473': _cfg(\n url='https://github.com/kkoutini/PaSST/releases/download/v0.0.3-audioset/passt-s-f128-stfthop100-p16-s10-ap.473-swa.pt',\n mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, input_size=(1, 128, 3200), crop_pct=1.0,\n classifier=('head.1', 'head_dist'), num_classes=527),\n 'passt_s_swa_f128_stfthop160_p16_s10_ap473': _cfg(\n url='https://github.com/kkoutini/PaSST/releases/download/v0.0.3-audioset/passt-s-f128-stfthop160-p16-s10-ap.473-swa.pt',\n mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, input_size=(1, 128, 2000), crop_pct=1.0,\n classifier=('head.1', 'head_dist'), num_classes=527),\n 'openmic2008_passt_u_f128_p16_s10_ap85_swa': _cfg(\n url='https://github.com/kkoutini/PaSST/releases/download/v0.0.4-openmic/openmic2008.passt-u-f128-p16-s10-ap.85-swa.pt',\n mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, input_size=(1, 128, 3200), crop_pct=1.0,\n classifier=('head.1', 'head_dist'), num_classes=20),\n 'openmic2008_passt_u_f128_p16_s10_ap85 ': _cfg(\n url='https://github.com/kkoutini/PaSST/releases/download/v0.0.4-openmic/openmic2008.passt-u-f128-p16-s10-ap.85.pt',\n mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, input_size=(1, 128, 2000), crop_pct=1.0,\n classifier=('head.1', 'head_dist'), num_classes=20),\n}\n\n\ndef adapt_input_conv(in_chans, conv_weight):\n conv_type = conv_weight.dtype\n conv_weight = conv_weight.float() # Some weights are in torch.half, ensure it's float for sum on CPU\n O, I, J, K = conv_weight.shape\n if in_chans == 1:\n if I > 3:\n assert conv_weight.shape[1] % 3 == 0\n # For models with space2depth stems\n conv_weight = conv_weight.reshape(O, I // 3, 3, J, K)\n conv_weight = conv_weight.sum(dim=2, keepdim=False)\n else:\n conv_weight = conv_weight.sum(dim=1, keepdim=True)\n elif in_chans != 3:\n if I != 3:\n raise NotImplementedError('Weight format not supported by conversion.')\n else:\n # NOTE this strategy should be better than random init, but there could be other combinations of\n # the original RGB input layer weights that'd work better for specific cases.\n repeat = int(math.ceil(in_chans / 3))\n conv_weight = conv_weight.repeat(1, repeat, 1, 1)[:, :in_chans, :, :]\n conv_weight *= (3 / float(in_chans))\n conv_weight = conv_weight.to(conv_type)\n return conv_weight\n\n\nclass Mlp(nn.Module):\n \"\"\" MLP as used in Vision Transformer, MLP-Mixer and related networks\n \"\"\"\n\n def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):\n super().__init__()\n out_features = out_features or in_features\n hidden_features = hidden_features or in_features\n self.fc1 = nn.Linear(in_features, hidden_features)\n self.act = act_layer()\n self.fc2 = nn.Linear(hidden_features, out_features)\n self.drop = nn.Dropout(drop)\n\n def forward(self, x):\n x = self.fc1(x)\n x = self.act(x)\n x = self.drop(x)\n x = self.fc2(x)\n x = self.drop(x)\n return x\n\n\nfirst_RUN = True\n\n\nclass PatchEmbed(nn.Module):\n \"\"\" 2D Image to Patch Embedding\n \"\"\"\n\n def __init__(self, img_size=224, patch_size=16, stride=16, in_chans=3, embed_dim=768, norm_layer=None,\n flatten=True):\n super().__init__()\n img_size = to_2tuple(img_size)\n patch_size = to_2tuple(patch_size)\n stride = to_2tuple(stride)\n self.img_size = img_size\n self.patch_size = patch_size\n self.stride = stride\n self.grid_size = (img_size[0] // stride[0], img_size[1] // stride[1])\n self.num_patches = self.grid_size[0] * self.grid_size[1]\n self.flatten = flatten\n self.embed_dim = embed_dim\n self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=stride)\n self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()\n\n def forward(self, x):\n B, C, H, W = x.shape\n if not (H == self.img_size[0] and W == self.img_size[1]):\n warnings.warn(f\"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]}).\")\n # to do maybe replace weights\n x = self.proj(x)\n if self.flatten:\n x = x.flatten(2).transpose(1, 2) # BCHW -> BNC\n x = self.norm(x)\n if first_RUN: print(\"self.norm(x)\", x.size())\n return x\n\n\nclass Attention(nn.Module):\n def __init__(self, dim, num_heads=8, qkv_bias=False, attn_drop=0., proj_drop=0.):\n super().__init__()\n self.num_heads = num_heads\n head_dim = dim // num_heads\n self.scale = head_dim ** -0.5\n\n self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)\n self.attn_drop = nn.Dropout(attn_drop)\n self.proj = nn.Linear(dim, dim)\n self.proj_drop = nn.Dropout(proj_drop)\n\n def forward(self, x):\n B, N, C = x.shape\n qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)\n q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)\n\n attn = (q @ k.transpose(-2, -1)) * self.scale\n attn = attn.softmax(dim=-1)\n attn = self.attn_drop(attn)\n\n x = (attn @ v).transpose(1, 2).reshape(B, N, C)\n x = self.proj(x)\n x = self.proj_drop(x)\n return x\n\n\nclass Block(nn.Module):\n\n def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, drop=0., attn_drop=0.,\n drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm):\n super().__init__()\n self.norm1 = norm_layer(dim)\n self.attn = Attention(dim, num_heads=num_heads, qkv_bias=qkv_bias, attn_drop=attn_drop, proj_drop=drop)\n # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here\n self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()\n self.norm2 = norm_layer(dim)\n mlp_hidden_dim = int(dim * mlp_ratio)\n self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)\n\n def forward(self, x):\n x = x + self.drop_path(self.attn(self.norm1(x)))\n x = x + self.drop_path(self.mlp(self.norm2(x)))\n return x\n\n\nclass PaSST(nn.Module):\n \"\"\"\n\n Based on the implementation of Vision Transformer in timm library.\n Take a look at the get_model function, adapting the weights of pretrained imagenet models.\n\n \"\"\"\n\n def __init__(self, u_patchout=0, s_patchout_t=0, s_patchout_f=0, img_size=(128, 998), patch_size=16, stride=16,\n in_chans=1, num_classes=527, embed_dim=768, depth=12,\n num_heads=12, mlp_ratio=4., qkv_bias=True, representation_size=None, distilled=False,\n drop_rate=0., attn_drop_rate=0., drop_path_rate=0., embed_layer=PatchEmbed, norm_layer=None,\n act_layer=None, weight_init=''):\n \"\"\"\n Args:\n u_patchout: Unstructured Patchout integer, number of items to be removed from the final sequence\n s_patchout_t: structured Patchout time integer, number of columns to be removed from the patches grid\n s_patchout_f: structured Patchout Frequency integer, number of rows to be removed from the patches grid\n img_size (int, tuple): input image size\n patch_size (int, tuple): patch size\n in_chans (int): number of input channels\n num_classes (int): number of classes for classification head\n embed_dim (int): embedding dimension\n depth (int): depth of transformer\n num_heads (int): number of attention heads\n mlp_ratio (int): ratio of mlp hidden dim to embedding dim\n qkv_bias (bool): enable bias for qkv if True\n representation_size (Optional[int]): enable and set representation layer (pre-logits) to this value if set\n distilled (bool): model includes a distillation token and head as in DeiT models\n drop_rate (float): dropout rate\n attn_drop_rate (float): attention dropout rate\n drop_path_rate (float): stochastic depth rate\n embed_layer (nn.Module): patch embedding layer\n norm_layer: (nn.Module): normalization layer\n weight_init: (str): weight init scheme\n \"\"\"\n super().__init__()\n self.num_classes = num_classes\n self.u_patchout = u_patchout\n self.s_patchout_t = s_patchout_t\n self.s_patchout_f = s_patchout_f\n self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models\n self.num_tokens = 2 if distilled else 1\n norm_layer = norm_layer or partial(nn.LayerNorm, eps=1e-6)\n act_layer = act_layer or nn.GELU\n\n self.patch_embed = embed_layer(\n img_size=img_size, patch_size=patch_size, stride=stride, in_chans=in_chans, embed_dim=embed_dim,\n flatten=False)\n num_patches = self.patch_embed.num_patches\n\n self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))\n self.dist_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) if distilled else None\n # PaSST\n # refer to https://arxiv.org/abs/2110.05069 Section 2\n self.new_pos_embed = nn.Parameter(torch.zeros(1, self.num_tokens, embed_dim)) # for C and D tokens\n self.freq_new_pos_embed = nn.Parameter(torch.zeros(1, embed_dim, self.patch_embed.grid_size[0], 1)) # | f\n self.time_new_pos_embed = nn.Parameter(torch.zeros(1, embed_dim, 1, self.patch_embed.grid_size[1])) # __ t\n ####\n self.pos_drop = nn.Dropout(p=drop_rate)\n\n dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule\n self.blocks = nn.Sequential(*[\n Block(\n dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, drop=drop_rate,\n attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer, act_layer=act_layer)\n for i in range(depth)])\n self.norm = norm_layer(embed_dim)\n\n # Representation layer\n if representation_size and not distilled:\n self.num_features = representation_size\n self.pre_logits = nn.Sequential(OrderedDict([\n ('fc', nn.Linear(embed_dim, representation_size)),\n ('act', nn.Tanh())\n ]))\n else:\n self.pre_logits = nn.Identity()\n\n # Classifier head(s)\n self.head = nn.Sequential(nn.LayerNorm(self.num_features),\n nn.Linear(self.num_features, num_classes) if num_classes > 0 else nn.Identity())\n self.head_dist = None\n if distilled:\n self.head_dist = nn.Linear(self.embed_dim, self.num_classes) if num_classes > 0 else nn.Identity()\n\n self.init_weights(weight_init)\n\n def init_weights(self, mode=''):\n assert mode in ('jax', 'jax_nlhb', 'nlhb', '')\n head_bias = -math.log(self.num_classes) if 'nlhb' in mode else 0.\n trunc_normal_(self.new_pos_embed, std=.02)\n trunc_normal_(self.freq_new_pos_embed, std=.02)\n trunc_normal_(self.time_new_pos_embed, std=.02)\n if self.dist_token is not None:\n trunc_normal_(self.dist_token, std=.02)\n if mode.startswith('jax'):\n # leave cls token as zeros to match jax impl\n raise RuntimeError(\"Not supported yet\")\n else:\n trunc_normal_(self.cls_token, std=.02)\n self.apply(_init_vit_weights)\n\n def _init_weights(self, m):\n # this fn left here for compat with downstream users\n _init_vit_weights(m)\n\n @torch.jit.ignore\n def no_weight_decay(self):\n return {'new_pos_embed', 'freq_new_pos_embed', 'time_new_pos_embed', 'cls_token', 'dist_token'}\n\n def get_classifier(self):\n if self.dist_token is None:\n return self.head\n else:\n return self.head, self.head_dist\n\n def reset_classifier(self, num_classes, global_pool=''):\n self.num_classes = num_classes\n self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity()\n if self.num_tokens == 2:\n self.head_dist = nn.Linear(self.embed_dim, self.num_classes) if num_classes > 0 else nn.Identity()\n\n def forward_features(self, x):\n global first_RUN # not jit friendly? use trace instead\n x = self.patch_embed(x) # [b, e, f, t]\n B_dim, E_dim, F_dim, T_dim = x.shape # slow\n if first_RUN: print(\" patch_embed : \", x.shape)\n # Adding Time/Freq information\n if first_RUN: print(\" self.time_new_pos_embed.shape\", self.time_new_pos_embed.shape)\n time_new_pos_embed = self.time_new_pos_embed\n if x.shape[-1] != time_new_pos_embed.shape[-1]:\n time_new_pos_embed = time_new_pos_embed[:, :, :, :x.shape[-1]]\n if first_RUN: print(\" CUT time_new_pos_embed.shape\", time_new_pos_embed.shape)\n x = x + time_new_pos_embed\n if first_RUN: print(\" self.freq_new_pos_embed.shape\", self.freq_new_pos_embed.shape)\n x = x + self.freq_new_pos_embed\n\n # Structured Patchout https://arxiv.org/abs/2110.05069 Section 2.2\n if self.training and self.s_patchout_t:\n if first_RUN: print(f\"X Before time Patchout of {self.s_patchout_t} \", x.size())\n # ([1, 768, 1, 82])\n random_indices = torch.randperm(T_dim)[:T_dim - self.s_patchout_t].sort().values\n x = x[:, :, :, random_indices]\n if first_RUN: print(\"X after time Patchout\", x.size())\n if self.training and self.s_patchout_f:\n if first_RUN: print(f\"X Before Freq Patchout of {self.s_patchout_f} \", x.size())\n # [1, 768, 12, 1]\n random_indices = torch.randperm(F_dim)[:F_dim - self.s_patchout_f].sort().values\n x = x[:, :, random_indices, :]\n if first_RUN: print(\" \\n X after freq Patchout: \", x.size())\n ###\n # Flatten the sequence\n x = x.flatten(2).transpose(1, 2)\n # Unstructured Patchout\n if first_RUN: print(\"X flattened\", x.size())\n if self.training and self.u_patchout:\n seq_len = x.shape[1]\n random_indices = torch.randperm(seq_len)[:seq_len - self.u_patchout].sort().values\n x = x[:, random_indices, :]\n if first_RUN: print(\"X After Unstructured Patchout\", x.size())\n ####\n # Add the C/D tokens\n if first_RUN: print(\" self.new_pos_embed.shape\", self.new_pos_embed.shape)\n cls_tokens = self.cls_token.expand(B_dim, -1, -1) + self.new_pos_embed[:, :1, :]\n if first_RUN: print(\" self.cls_tokens.shape\", cls_tokens.shape)\n if self.dist_token is None:\n x = torch.cat((cls_tokens, x), dim=1)\n else:\n dist_token = self.dist_token.expand(B_dim, -1, -1) + self.new_pos_embed[:, 1:, :]\n if first_RUN: print(\" self.dist_token.shape\", dist_token.shape)\n x = torch.cat((cls_tokens, dist_token, x), dim=1)\n\n if first_RUN: print(\" final sequence x\", x.shape)\n x = self.pos_drop(x)\n x = self.blocks(x)\n if first_RUN: print(f\" after {len(self.blocks)} atten blocks x\", x.shape)\n x = self.norm(x)\n if self.dist_token is None:\n return self.pre_logits(x[:, 0])\n else:\n return x[:, 0], x[:, 1]\n\n def forward(self, x):\n global first_RUN\n if first_RUN: print(\"x\", x.size())\n\n x = self.forward_features(x)\n\n if self.head_dist is not None:\n features = (x[0] + x[1]) / 2\n if first_RUN: print(\"forward_features\", features.size())\n x = self.head(features)\n if first_RUN: print(\"head\", x.size())\n first_RUN = False\n return x, features\n else:\n features = x\n if first_RUN: print(\"forward_features\", features.size())\n x = self.head(x)\n if first_RUN: print(\"head\", x.size())\n first_RUN = False\n return x, features\n\n\ndef _init_vit_weights(module: nn.Module, name: str = '', head_bias: float = 0., jax_impl: bool = False):\n \"\"\" ViT weight initialization\n * When called without n, head_bias, jax_impl args it will behave exactly the same\n as my original init for compatibility with prev hparam / downstream use cases (ie DeiT).\n * When called w/ valid n (module name) and jax_impl=True, will (hopefully) match JAX impl\n \"\"\"\n if isinstance(module, nn.Linear):\n if name.startswith('head'):\n nn.init.zeros_(module.weight)\n nn.init.constant_(module.bias, head_bias)\n elif name.startswith('pre_logits'):\n lecun_normal_(module.weight)\n nn.init.zeros_(module.bias)\n else:\n if jax_impl:\n nn.init.xavier_uniform_(module.weight)\n if module.bias is not None:\n if 'mlp' in name:\n nn.init.normal_(module.bias, std=1e-6)\n else:\n nn.init.zeros_(module.bias)\n else:\n trunc_normal_(module.weight, std=.02)\n if module.bias is not None:\n nn.init.zeros_(module.bias)\n elif jax_impl and isinstance(module, nn.Conv2d):\n # NOTE conv was left to pytorch default in my original init\n lecun_normal_(module.weight)\n if module.bias is not None:\n nn.init.zeros_(module.bias)\n elif isinstance(module, (nn.LayerNorm, nn.GroupNorm, nn.BatchNorm2d)):\n nn.init.zeros_(module.bias)\n nn.init.ones_(module.weight)\n\n\ndef resize_pos_embed(posemb, posemb_new, num_tokens=1, gs_new=(), mode='bicubic'):\n # Rescale the grid of position embeddings when loading from state_dict. Adapted from\n # https://github.com/google-research/vision_transformer/blob/00883dd691c63a6830751563748663526e811cee/vit_jax/checkpoint.py#L224\n _logger.info('Resized position embedding: %s to %s with %s cls/dis tokens', posemb.shape, posemb_new.shape,\n num_tokens)\n ntok_new = posemb_new.shape[1]\n if num_tokens:\n posemb_tok, posemb_grid = posemb[:, :num_tokens], posemb[0, num_tokens:]\n ntok_new -= num_tokens\n else:\n posemb_tok, posemb_grid = posemb[:, :0], posemb[0]\n gs_old = int(math.sqrt(len(posemb_grid)))\n if not len(gs_new): # backwards compatibility\n gs_new = [int(math.sqrt(ntok_new))] * 2\n assert len(gs_new) >= 2\n _logger.info('Position embedding grid-size from %s to %s', [gs_old, gs_old], gs_new)\n posemb_grid = posemb_grid.reshape(1, gs_old, gs_old, -1).permute(0, 3, 1, 2)\n posemb_grid = F.interpolate(posemb_grid, size=gs_new, mode=mode, align_corners=False)\n posemb_grid = posemb_grid.permute(0, 2, 3, 1).reshape(1, gs_new[0] * gs_new[1], -1)\n posemb = torch.cat([posemb_tok, posemb_grid], dim=1)\n return posemb\n\n\ndef adapt_image_pos_embed_to_passt(posemb, num_tokens=1, gs_new=(), mode='bicubic'):\n # Rescale the grid of position embeddings when loading from state_dict. Adapted from\n # https://github.com/google-research/vision_transformer/blob/00883dd691c63a6830751563748663526e811cee/vit_jax/checkpoint.py#L224\n _logger.info('Resized position embedding: %s to %s with %s cls/dis tokens', posemb.shape, gs_new,\n num_tokens)\n if num_tokens:\n posemb_tok, posemb_grid = posemb[:, :num_tokens], posemb[0, num_tokens:]\n else:\n posemb_tok, posemb_grid = posemb[:, :0], posemb[0]\n gs_old = int(math.sqrt(len(posemb_grid)))\n\n assert len(gs_new) >= 2\n _logger.info('Position embedding grid-size from %s to %s', [gs_old, gs_old], gs_new)\n posemb_grid = posemb_grid.reshape(1, gs_old, gs_old, -1).permute(0, 3, 1, 2)\n posemb_grid = F.interpolate(posemb_grid, size=gs_new, mode=mode, align_corners=False)\n freq_new_pos_embed = posemb_grid.mean(dim=3, keepdim=True)\n time_new_pos_embed = posemb_grid.mean(dim=2, keepdim=True)\n _logger.info('New Position cls/dstl embedding %s', posemb_tok.shape)\n _logger.info('New FREQ Position embedding %s', freq_new_pos_embed.shape)\n _logger.info('New TIME Position embedding %s', time_new_pos_embed.shape)\n return posemb_tok, freq_new_pos_embed, time_new_pos_embed\n\n\ndef checkpoint_filter_fn(state_dict, model):\n \"\"\" convert patch embedding weight from manual patchify + linear proj to conv\"\"\"\n out_dict = {}\n if 'model' in state_dict:\n # For deit models\n state_dict = state_dict['model']\n state_dict = {k: v for k, v in state_dict.items()}\n if \"time_new_pos_embed\" not in state_dict:\n # we are working with ImageNet model\n _logger.info(\"Adapting pos embedding from ImageNet pretrained model to PaSST.\")\n v = state_dict.pop(\"pos_embed\")\n new_pos_embed, freq_new_pos_embed, time_new_pos_embed = adapt_image_pos_embed_to_passt(\n v, getattr(model, 'num_tokens', 1), model.patch_embed.grid_size)\n state_dict[\"new_pos_embed\"] = new_pos_embed\n state_dict[\"freq_new_pos_embed\"] = freq_new_pos_embed\n state_dict[\"time_new_pos_embed\"] = time_new_pos_embed\n\n for k, v in state_dict.items():\n if 'patch_embed.proj.weight' in k and len(v.shape) < 4:\n # For old models that I trained prior to conv based patchification\n O, I, H, W = model.patch_embed.proj.weight.shape\n v = v.reshape(O, -1, H, W)\n elif k == 'pos_embed' and v.shape != model.pos_embed.shape:\n # this should never occur\n v = resize_pos_embed(\n v, model.pos_embed, getattr(model, 'num_tokens', 1), model.patch_embed.grid_size)\n out_dict[k] = v\n return out_dict\n\n\ndef _create_vision_transformer(variant, pretrained=False, default_cfg=None, **kwargs):\n default_cfg = default_cfg or default_cfgs[variant]\n if kwargs.get('features_only', None):\n raise RuntimeError('features_only not implemented for Vision Transformer models.')\n\n # NOTE this extra code to support handling of repr size for in21k pretrained models\n default_num_classes = default_cfg['num_classes']\n num_classes = kwargs.get('num_classes', default_num_classes)\n repr_size = kwargs.pop('representation_size', None)\n if repr_size is not None and num_classes != default_num_classes:\n # Remove representation layer if fine-tuning. This may not always be the desired action,\n # but I feel better than doing nothing by default for fine-tuning. Perhaps a better interface?\n _logger.warning(\"Removing representation layer for fine-tuning.\")\n repr_size = None\n\n model = build_model_with_cfg(\n PaSST, variant, pretrained,\n default_cfg=default_cfg,\n representation_size=repr_size,\n pretrained_filter_fn=checkpoint_filter_fn,\n pretrained_custom_load='npz' in default_cfg['url'],\n **kwargs)\n return model\n\n\ndef vit_huge_patch14_224_in21k(pretrained=False, **kwargs):\n \"\"\" ViT-Huge model (ViT-H/14) from original paper (https://arxiv.org/abs/2010.11929).\n ImageNet-21k weights @ 224x224, source https://github.com/google-research/vision_transformer.\n NOTE: this model has a representation layer but the 21k classifier head is zero'd out in original weights\n \"\"\"\n model_kwargs = dict(\n patch_size=14, embed_dim=1280, depth=32, num_heads=16, representation_size=1280, **kwargs)\n model = _create_vision_transformer('vit_huge_patch14_224_in21k', pretrained=pretrained, **model_kwargs)\n return model\n\n\ndef deit_base_distilled_patch16_384(pretrained=False, **kwargs):\n \"\"\" DeiT-base distilled model @ 384x384 from paper (https://arxiv.org/abs/2012.12877).\n ImageNet-1k weights from https://github.com/facebookresearch/deit.\n \"\"\"\n print(\"\\n\\n Loading DEIT BASE 384\\n\\n\")\n model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs)\n model = _create_vision_transformer(\n 'deit_base_distilled_patch16_384', pretrained=pretrained, distilled=True, **model_kwargs)\n return model\n\n\ndef passt_s_swa_p16_128_ap476(pretrained=False, **kwargs):\n \"\"\" PaSST pre-trained on AudioSet\n \"\"\"\n print(\"\\n\\n Loading PaSST pre-trained on AudioSet Patch 16 stride 10 structured patchout mAP=476 SWA \\n\\n\")\n model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs)\n if model_kwargs.get(\"stride\") != (10, 10):\n warnings.warn(\n f\"This model was pre-trained with strides {(10, 10)}, but now you set (fstride,tstride) to {model_kwargs.get('stride')}.\")\n model = _create_vision_transformer(\n 'passt_s_swa_p16_128_ap476', pretrained=pretrained, distilled=True, **model_kwargs)\n return model\n\n\ndef passt_s_swa_p16_128_ap4761(pretrained=False, **kwargs):\n \"\"\" PaSST pre-trained on AudioSet\n \"\"\"\n print(\"\\n\\n Loading PaSST pre-trained on AudioSet Patch 16 stride 10 structured patchout mAP=4763 SWA \\n\\n\")\n model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs)\n if model_kwargs.get(\"stride\") != (10, 10):\n warnings.warn(\n f\"This model was pre-trained with strides {(10, 10)}, but now you set (fstride,tstride) to {model_kwargs.get('stride')}.\")\n model = _create_vision_transformer(\n 'passt_s_swa_p16_128_ap4761', pretrained=pretrained, distilled=True, **model_kwargs)\n return model\n\n\ndef passt_s_p16_128_ap472(pretrained=False, **kwargs):\n \"\"\" PaSST pre-trained on AudioSet\n \"\"\"\n print(\"\\n\\n Loading PaSST pre-trained on AudioSet Patch 16 stride 10 structured patchout mAP=472 \\n\\n\")\n model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs)\n if model_kwargs.get(\"stride\") != (10, 10):\n warnings.warn(\n f\"This model was pre-trained with strides {(10, 10)}, but now you set (fstride,tstride) to {model_kwargs.get('stride')}.\")\n model = _create_vision_transformer(\n 'passt_s_p16_128_ap472', pretrained=pretrained, distilled=True, **model_kwargs)\n return model\n\n\ndef passt_s_p16_s12_128_ap470(pretrained=False, **kwargs):\n \"\"\" PaSST pre-trained on AudioSet\n \"\"\"\n print(\"\\n\\n Loading PaSST pre-trained on AudioSet Patch 16 stride 12 structured patchout mAP=472 \\n\\n\")\n model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs)\n if model_kwargs.get(\"stride\") != (12, 12):\n warnings.warn(\n f\"This model was pre-trained with strides {(12, 12)}, but now you set (fstride,tstride) to {model_kwargs.get('stride')}.\")\n model = _create_vision_transformer(\n 'passt_s_p16_s12_128_ap470', pretrained=pretrained, distilled=True, **model_kwargs)\n return model\n\n\ndef passt_s_swa_p16_s12_128_ap473(pretrained=False, **kwargs):\n \"\"\" PaSST pre-trained on AudioSet\n \"\"\"\n print(\"\\n\\n Loading PaSST pre-trained on AudioSet Patch 16 stride 12 structured patchout mAP=472 \\n\\n\")\n model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs)\n if model_kwargs.get(\"stride\") != (12, 12):\n warnings.warn(\n f\"This model was pre-trained with strides {(12, 12)}, but now you set (fstride,tstride) to {model_kwargs.get('stride')}.\")\n model = _create_vision_transformer(\n 'passt_s_swa_p16_s12_128_ap473', pretrained=pretrained, distilled=True, **model_kwargs)\n return model\n\n\ndef passt_s_p16_s14_128_ap469(pretrained=False, **kwargs):\n \"\"\" PaSST pre-trained on AudioSet\n \"\"\"\n print(\"\\n\\n Loading PaSST pre-trained on AudioSet Patch 16 stride 14 structured patchout mAP=472 \\n\\n\")\n model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs)\n if model_kwargs.get(\"stride\") != (14, 14):\n warnings.warn(\n f\"This model was pre-trained with strides {(14, 14)}, but now you set (fstride,tstride) to {model_kwargs.get('stride')}.\")\n model = _create_vision_transformer(\n 'passt_s_p16_s14_128_ap469', pretrained=pretrained, distilled=True, **model_kwargs)\n return model\n\n\ndef passt_s_swa_p16_s14_128_ap471(pretrained=False, **kwargs):\n \"\"\" PaSST pre-trained on AudioSet\n \"\"\"\n print(\"\\n\\n Loading PaSST pre-trained on AudioSet Patch 16 stride 14 structured patchout mAP=472 \\n\\n\")\n model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs)\n if model_kwargs.get(\"stride\") != (14, 14):\n warnings.warn(\n f\"This model was pre-trained with strides {(14, 14)}, but now you set (fstride,tstride) to {model_kwargs.get('stride')}.\")\n model = _create_vision_transformer(\n 'passt_s_swa_p16_s14_128_ap471', pretrained=pretrained, distilled=True, **model_kwargs)\n return model\n\n\ndef passt_s_swa_p16_s16_128_ap473(pretrained=False, **kwargs):\n \"\"\" PaSST pre-trained on AudioSet\n \"\"\"\n print(\"\\n\\n Loading PaSST pre-trained on AudioSet Patch 16 stride 16 structured patchout mAP=472 \\n\\n\")\n model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs)\n if model_kwargs.get(\"stride\") != (16, 16):\n warnings.warn(\n f\"This model was pre-trained with strides {(16, 16)}, but now you set (fstride,tstride) to {model_kwargs.get('stride')}.\")\n model = _create_vision_transformer(\n 'passt_s_swa_p16_s16_128_ap473', pretrained=pretrained, distilled=True, **model_kwargs)\n return model\n\n\ndef passt_s_p16_s16_128_ap468(pretrained=False, **kwargs):\n \"\"\" PaSST pre-trained on AudioSet\n \"\"\"\n print(\"\\n\\n Loading PaSST pre-trained on AudioSet Patch 16 stride 16 structured patchout mAP=472 \\n\\n\")\n model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs)\n if model_kwargs.get(\"stride\") != (16, 16):\n warnings.warn(\n f\"This model was pre-trained with strides {(16, 16)}, but now you set (fstride,tstride) to {model_kwargs.get('stride')}.\")\n model = _create_vision_transformer(\n 'passt_s_p16_s16_128_ap468', pretrained=pretrained, distilled=True, **model_kwargs)\n return model\n\n\nfrom ba3l.ingredients.ingredient import Ingredient\n\nmodel_ing = Ingredient(\"passt\")\n\nmodel_ing.add_config(instance_cmd=\"get_model\")\n\n\n@model_ing.command\ndef fix_embedding_layer(model, embed=\"default\"):\n if embed == \"default\":\n return model\n if embed == \"overlap\":\n model.patch_embed = PatchEmbedAdaptiveMean(replace=model.patch_embed)\n if embed == \"am_keepconv\":\n model.patch_embed = PatchEmbedAdaptiveMeanKeepConv(replace=model.patch_embed)\n return model\n\n\n@model_ing.command\ndef get_model(arch=\"passt_s_swa_p16_128_ap476\", pretrained=True, n_classes=527, in_channels=1, fstride=10,\n tstride=10,\n input_fdim=128, input_tdim=998, u_patchout=0, s_patchout_t=0, s_patchout_f=0,\n ):\n \"\"\"\n :param arch: Base ViT or Deit architecture\n :param pretrained: use pretrained model on imagenet\n :param n_classes: number of classes\n :param in_channels: number of input channels: 1 for mono\n :param fstride: the patches stride over frequency.\n :param tstride: the patches stride over time.\n :param input_fdim: the expected input frequency bins.\n :param input_tdim: the expected input time bins.\n :param u_patchout: number of input patches to drop in Unstructured Patchout as defined in https://arxiv.org/abs/2110.05069\n :param s_patchout_t: number of input time frames to drop Structured Patchout as defined in https://arxiv.org/abs/2110.05069\n :param s_patchout_f: number of input frequency bins to drop Structured Patchout as defined in https://arxiv.org/abs/2110.05069\n :param audioset_pretrain: use pretrained models on Audioset.\n :return:\n\n \"\"\"\n model_func = None\n input_size = (input_fdim, input_tdim)\n stride = (fstride, tstride)\n if arch == \"passt_deit_bd_p16_384\": # base deit\n model_func = deit_base_distilled_patch16_384\n elif arch == \"passt_s_swa_p16_128_ap476\": # pretrained\n model_func = passt_s_swa_p16_128_ap476\n elif arch == \"passt_s_swa_p16_128_ap4761\":\n model_func = passt_s_swa_p16_128_ap4761\n elif arch == \"passt_s_p16_128_ap472\":\n model_func = passt_s_p16_128_ap472\n elif arch == \"passt_s_p16_s16_128_ap468\":\n model_func = passt_s_p16_s16_128_ap468\n elif arch == \"passt_s_swa_p16_s16_128_ap473\":\n model_func = passt_s_swa_p16_s16_128_ap473\n elif arch == \"passt_s_swa_p16_s14_128_ap471\":\n model_func = passt_s_swa_p16_s14_128_ap471\n elif arch == \"passt_s_p16_s14_128_ap469\":\n model_func = passt_s_p16_s14_128_ap469\n elif arch == \"passt_s_swa_p16_s12_128_ap473\":\n model_func = passt_s_swa_p16_s12_128_ap473\n elif arch == \"passt_s_p16_s12_128_ap470\":\n model_func = passt_s_p16_s12_128_ap470\n\n if model_func is None:\n raise RuntimeError(f\"Unknown model {arch}\")\n model = model_func(pretrained=pretrained, num_classes=n_classes, in_chans=in_channels,\n img_size=input_size, stride=stride, u_patchout=u_patchout,\n s_patchout_t=s_patchout_t, s_patchout_f=s_patchout_f)\n model = fix_embedding_layer(model)\n print(model)\n return model\n\n\nclass EnsembelerModel(nn.Module):\n def __init__(self, models):\n super(EnsembelerModel, self).__init__()\n self.models = nn.ModuleList(models)\n\n def forward(self, x):\n # ModuleList can act as an iterable, or be indexed using ints\n all_out = None\n for i, m in enumerate(self.models):\n out, _ = m(x)\n if all_out is None:\n all_out = out\n else:\n all_out = out + all_out\n all_out = all_out / len(self.models)\n return all_out, all_out\n\n\n@model_ing.command\ndef get_ensemble_model(arch_list=[]):\n # arch_list = [(passt_s_swa_p16_128_ap476,fstride,tstride)]\n models_list = [get_model(arch=arch, fstride=fstride, tstride=tstride) for arch, fstride, tstride in arch_list]\n model = EnsembelerModel(models_list)\n print(model)\n return model\n"
] | [
[
"torch.nn.Dropout",
"torch.linspace",
"torch.cat",
"torch.zeros",
"torch.nn.init.constant_",
"torch.nn.ModuleList",
"torch.nn.Conv2d",
"torch.randperm",
"torch.nn.LayerNorm",
"torch.nn.Tanh",
"torch.nn.Linear",
"torch.nn.Identity",
"torch.nn.init.ones_",
"torch.nn.init.xavier_uniform_",
"torch.nn.init.normal_",
"torch.nn.functional.interpolate",
"torch.nn.init.zeros_"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
thomasjo/nemo-redux | [
"c4196c0d99633dca011d60008be0cb7667c348b7"
] | [
"src/preprocessing/partition_mask_dataset.py"
] | [
"import json\nimport random\nimport shutil\n\nfrom argparse import ArgumentParser\nfrom pathlib import Path\n\nimport numpy as np\n\nfrom sklearn.model_selection import train_test_split\n\nEXCLUDED_CATEGORIES = [5, 6]\n\n\ndef main(args):\n random.seed(42)\n np.random.seed(42)\n\n json_file = args.source_dir / \"via.json\"\n with json_file.open() as fp:\n annotations = json.load(fp)\n annotations = list(annotations.values())\n\n entry_labels = []\n for entry in annotations:\n max_coords = []\n categories = []\n for region in entry[\"regions\"]:\n region_category = int(region[\"region_attributes\"][\"category\"])\n if region_category in EXCLUDED_CATEGORIES:\n continue\n\n categories.append(region_category)\n\n xs = np.array(region[\"shape_attributes\"][\"all_points_x\"])\n ys = np.array(region[\"shape_attributes\"][\"all_points_y\"])\n max_coords.append([np.max(xs), np.max(ys)])\n\n categories, num_categories = np.unique(categories, return_counts=True)\n category = categories[np.argmax(num_categories)]\n\n max_coords = np.max(max_coords, axis=0)\n is_large = int(np.any(max_coords > 5000))\n\n label = [category, is_large]\n entry_labels.append(label)\n\n _, num_entry_labels = np.unique(np.asarray(entry_labels)[:, 0], return_counts=True)\n # HACK: Check if stratified sampling is possible.\n if not np.all(num_entry_labels > 1):\n print(\"Warning: stratified sampling not possible\")\n entry_labels = None\n\n indices = np.arange(np.sum(num_entry_labels))\n train_idx, test_idx = train_test_split(indices, stratify=entry_labels, test_size=args.test_size)\n partitions = [(\"train\", train_idx), (\"test\", test_idx)]\n\n # entry_labels = np.array(entry_labels)\n # _, train_counts = np.unique(entry_labels[train_idx][:, 0], return_counts=True)\n # _, test_counts = np.unique(entry_labels[test_idx][:, 0], return_counts=True)\n # print(\"train:\", np.sum(train_counts), train_counts)\n # print(\" test:\", np.sum(test_counts), test_counts)\n\n # Safely prepare a fresh output directory.\n if args.output_dir.exists():\n # TODO: Fix assertion to ensure deleting the output directory is safe-ish.\n # partition_names = map(lambda x: x[0], partitions)\n # assert all(map(lambda x: x.is_dir() and x.name in partition_names, args.output_dir.iterdir()))\n shutil.rmtree(args.output_dir)\n args.output_dir.mkdir(parents=True)\n\n for partition_name, partition_idx in partitions:\n partition_dir = args.output_dir / partition_name\n\n old_images_dir = args.source_dir / \"images\"\n new_images_dir = partition_dir / \"images\"\n new_images_dir.mkdir(parents=True)\n\n json_payload = {}\n for num, entry in enumerate([annotations[i] for i in partition_idx], start=1):\n old_path = old_images_dir / entry[\"filename\"]\n\n new_name = \"{:04d}{}\".format(num, old_path.suffix)\n new_path = new_images_dir / new_name\n\n json_payload[\"{}{}\".format(new_name, entry[\"size\"])] = {\n \"filename\": new_name,\n \"size\": entry[\"size\"],\n \"regions\": entry[\"regions\"],\n \"file_attributes\": entry[\"file_attributes\"],\n }\n\n print(f\"{old_path=} -> {new_path=}\")\n shutil.copy(old_path, new_path, follow_symlinks=True)\n\n # Copy optional aux images.\n for aux_dir in old_images_dir.glob(\"aux-*\"):\n aux_file = aux_dir / old_path.name\n if not aux_file.exists():\n break\n\n new_aux_dir = new_images_dir / aux_dir.name\n new_aux_dir.mkdir(exist_ok=True)\n shutil.copy(aux_file, new_aux_dir / new_name, follow_symlinks=True)\n\n with (partition_dir / \"via.json\").open(\"w\") as fp:\n json.dump(json_payload, fp)\n\n\ndef parse_args():\n parser = ArgumentParser()\n parser.add_argument(\"--source-dir\", type=Path, required=True, metavar=\"PATH\", help=\"path to unpartitioned dataset directory\")\n parser.add_argument(\"--output-dir\", type=Path, required=True, metavar=\"PATH\", help=\"path to output directory\")\n parser.add_argument(\"--test-size\", type=float, default=0.27, metavar=\"NUM\", help=\"ratio of dataset to use for test partition\")\n\n return parser.parse_args()\n\n\nif __name__ == \"__main__\":\n main(parse_args())\n"
] | [
[
"numpy.random.seed",
"numpy.unique",
"numpy.asarray",
"sklearn.model_selection.train_test_split",
"numpy.all",
"numpy.max",
"numpy.argmax",
"numpy.any",
"numpy.array",
"numpy.sum"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
bwdeng20/thgsp | [
"785b3ff291d72ee51e51e4cdbfd4bab63f8de9ac"
] | [
"tests/test_sampling/test_fastgsss.py"
] | [
"import pytest\nimport torch\nimport math\nfrom thgsp.graphs.generators import random_graph\nfrom ..utils4t import devices, float_dtypes, snr_and_mse\nfrom thgsp.sampling.fastgsss import fastgsss, recon_fastssss\n\n\[email protected](\"device\", devices)\[email protected](\"dtype\", float_dtypes)\[email protected](\"cheb\", [True, False])\nclass TestFastGSSS:\n def test_fastgsss(self, device, dtype, cheb):\n N = 1000\n ds = 0.1\n order = 12\n M = 10\n g = random_graph(N, ds, dtype=dtype, device=device)\n S, T = fastgsss(g, M, N // 10, order=order, cheby=cheb)\n print(S)\n\n def test_fastgsss_rec(self, device, dtype, cheb):\n N = 8\n g = random_graph(N, 0.4, dtype=dtype, device=device)\n fs, U = g.spectral(lap_type=\"sym\")\n\n M = 4\n bw = 4\n nu = 3\n c = torch.rand(bw, dtype=dtype, device=device)\n f_band = U[:, :bw] @ c\n f_band_noise = f_band + math.sqrt(5e-3) * torch.randn(N, dtype=dtype, device=device)\n\n K = 12\n S, T = fastgsss(g, M, bw, nu, cheb, order=K)\n f_hat = recon_fastssss(f_band_noise[S], S, T, order=K)\n s, m = snr_and_mse(f_hat, f_band)\n assert m < 0.5\n"
] | [
[
"torch.randn",
"torch.rand"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
HoodedPitohui/impact_2021 | [
"dac2ff075649ee6ef61fb9db2577568cdd47c22e"
] | [
"code/testing-kshaji/haar1.py"
] | [
"import cv2\nfrom matplotlib import pyplot as plt\n#standard libraries\n# Opening image\nimg = cv2.imread(\"image3.jpg\")\n\nimg_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\nimg_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n# Use minSize because for not\n# bothering with extra-small\n# dots that would look like STOP signs\nstop_data = cv2.CascadeClassifier('stop_data.xml')\n\nfound = stop_data.detectMultiScale(img_gray,\n minSize=(20, 20))\n\n# Don't do anything if there's\n# no sign\namount_found = len(found)\n\nif amount_found != 0:\n\n # There may be more than one\n # sign in the image\n for (x, y, width, height) in found:\n # We draw a green rectangle around\n # every recognized sign\n cv2.rectangle(img_rgb, (x, y),\n (x + height, y + width),\n (0, 255, 0), 5)\n\n# Creates the environment of\n# the picture and shows it\nplt.subplot(1, 1, 1)\nplt.imshow(img_rgb)\nplt.show()"
] | [
[
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.show"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
gusleak/freeCodeCamp | [
"2a9e8ae5c1d8a1c738071f6ce26ef61b64ce5b65"
] | [
"Data_Analysis_with_Python/mean_var_stddev_calculator.py"
] | [
"import numpy as np\n\ndef calculate(initial_list):\n if len(initial_list) < 9:\n raise ValueError('List must contain nine numbers.')\n arr = np.array(initial_list)\n new_arr = arr.reshape(3,3)\n return {\n 'mean': [np.mean(new_arr, axis=0).tolist(), np.mean(new_arr, axis=1).tolist(), np.mean(arr)],\n 'variance': [np.var(new_arr, axis=0).tolist(), np.var(new_arr, axis=1).tolist(), np.var(arr)],\n 'standard deviation': [np.std(new_arr, axis=0).tolist(), np.std(new_arr, axis=1).tolist(), np.std(arr)],\n 'max': [np.max(new_arr, axis=0).tolist(), np.max(new_arr, axis=1).tolist(), np.max(arr)],\n 'min': [np.min(new_arr, axis=0).tolist(), np.min(new_arr, axis=1).tolist(), np.min(arr)],\n 'sum': [np.sum(new_arr, axis=0).tolist(), np.sum(new_arr, axis=1).tolist(), np.sum(arr)]\n }\n"
] | [
[
"numpy.min",
"numpy.max",
"numpy.std",
"numpy.mean",
"numpy.var",
"numpy.array",
"numpy.sum"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
bevarb/AutoDetect | [
"64118ae0d741618088a470cd4eb704ca38f32ce0"
] | [
"libs/detect/yolo4/nets/yolo_training.py"
] | [
" \nfrom random import shuffle\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport math\nimport torch.nn.functional as F\nfrom matplotlib.colors import rgb_to_hsv, hsv_to_rgb\nfrom PIL import Image\nfrom utils.utils import bbox_iou, merge_bboxes\n\ndef jaccard(_box_a, _box_b):\n b1_x1, b1_x2 = _box_a[:, 0] - _box_a[:, 2] / 2, _box_a[:, 0] + _box_a[:, 2] / 2\n b1_y1, b1_y2 = _box_a[:, 1] - _box_a[:, 3] / 2, _box_a[:, 1] + _box_a[:, 3] / 2\n b2_x1, b2_x2 = _box_b[:, 0] - _box_b[:, 2] / 2, _box_b[:, 0] + _box_b[:, 2] / 2\n b2_y1, b2_y2 = _box_b[:, 1] - _box_b[:, 3] / 2, _box_b[:, 1] + _box_b[:, 3] / 2\n box_a = torch.zeros_like(_box_a)\n box_b = torch.zeros_like(_box_b)\n box_a[:, 0], box_a[:, 1], box_a[:, 2], box_a[:, 3] = b1_x1, b1_y1, b1_x2, b1_y2\n box_b[:, 0], box_b[:, 1], box_b[:, 2], box_b[:, 3] = b2_x1, b2_y1, b2_x2, b2_y2\n A = box_a.size(0)\n B = box_b.size(0)\n max_xy = torch.min(box_a[:, 2:].unsqueeze(1).expand(A, B, 2),\n box_b[:, 2:].unsqueeze(0).expand(A, B, 2))\n min_xy = torch.max(box_a[:, :2].unsqueeze(1).expand(A, B, 2),\n box_b[:, :2].unsqueeze(0).expand(A, B, 2))\n inter = torch.clamp((max_xy - min_xy), min=0)\n\n inter = inter[:, :, 0] * inter[:, :, 1]\n # 计算先验框和真实框各自的面积\n area_a = ((box_a[:, 2]-box_a[:, 0]) *\n (box_a[:, 3]-box_a[:, 1])).unsqueeze(1).expand_as(inter) # [A,B]\n area_b = ((box_b[:, 2]-box_b[:, 0]) *\n (box_b[:, 3]-box_b[:, 1])).unsqueeze(0).expand_as(inter) # [A,B]\n # 求IOU\n union = area_a + area_b - inter\n return inter / union # [A,B]\n#---------------------------------------------------#\n# 平滑标签\n#---------------------------------------------------#\ndef smooth_labels(y_true, label_smoothing,num_classes):\n return y_true * (1.0 - label_smoothing) + label_smoothing / num_classes\n\ndef box_ciou(b1, b2):\n \"\"\"\n 输入为:\n ----------\n b1: tensor, shape=(batch, feat_w, feat_h, anchor_num, 4), xywh\n b2: tensor, shape=(batch, feat_w, feat_h, anchor_num, 4), xywh\n\n 返回为:\n -------\n ciou: tensor, shape=(batch, feat_w, feat_h, anchor_num, 1)\n \"\"\"\n # 求出预测框左上角右下角\n b1_xy = b1[..., :2]\n b1_wh = b1[..., 2:4]\n b1_wh_half = b1_wh/2.\n b1_mins = b1_xy - b1_wh_half\n b1_maxes = b1_xy + b1_wh_half\n # 求出真实框左上角右下角\n b2_xy = b2[..., :2]\n b2_wh = b2[..., 2:4]\n b2_wh_half = b2_wh/2.\n b2_mins = b2_xy - b2_wh_half\n b2_maxes = b2_xy + b2_wh_half\n\n # 求真实框和预测框所有的iou\n intersect_mins = torch.max(b1_mins, b2_mins)\n intersect_maxes = torch.min(b1_maxes, b2_maxes)\n intersect_wh = torch.max(intersect_maxes - intersect_mins, torch.zeros_like(intersect_maxes))\n intersect_area = intersect_wh[..., 0] * intersect_wh[..., 1]\n b1_area = b1_wh[..., 0] * b1_wh[..., 1]\n b2_area = b2_wh[..., 0] * b2_wh[..., 1]\n union_area = b1_area + b2_area - intersect_area\n iou = intersect_area / torch.clamp(union_area,min = 1e-6)\n\n # 计算中心的差距\n center_distance = torch.sum(torch.pow((b1_xy - b2_xy), 2), axis=-1)\n \n # 找到包裹两个框的最小框的左上角和右下角\n enclose_mins = torch.min(b1_mins, b2_mins)\n enclose_maxes = torch.max(b1_maxes, b2_maxes)\n enclose_wh = torch.max(enclose_maxes - enclose_mins, torch.zeros_like(intersect_maxes))\n # 计算对角线距离\n enclose_diagonal = torch.sum(torch.pow(enclose_wh,2), axis=-1)\n ciou = iou - 1.0 * (center_distance) / torch.clamp(enclose_diagonal,min = 1e-6)\n \n v = (4 / (math.pi ** 2)) * torch.pow((torch.atan(b1_wh[..., 0]/torch.clamp(b1_wh[..., 1],min = 1e-6)) - torch.atan(b2_wh[..., 0]/torch.clamp(b2_wh[..., 1],min = 1e-6))), 2)\n alpha = v / torch.clamp((1.0 - iou + v),min=1e-6)\n ciou = ciou - alpha * v\n return ciou\n \ndef clip_by_tensor(t,t_min,t_max):\n t=t.float()\n result = (t >= t_min).float() * t + (t < t_min).float() * t_min\n result = (result <= t_max).float() * result + (result > t_max).float() * t_max\n return result\n\ndef MSELoss(pred,target):\n return (pred-target)**2\n\ndef BCELoss(pred,target):\n epsilon = 1e-7\n pred = clip_by_tensor(pred, epsilon, 1.0 - epsilon)\n output = -target * torch.log(pred) - (1.0 - target) * torch.log(1.0 - pred)\n return output\n\nclass YOLOLoss(nn.Module):\n def __init__(self, anchors, num_classes, img_size, label_smooth=0, cuda=True):\n super(YOLOLoss, self).__init__()\n self.anchors = anchors\n self.num_anchors = len(anchors)\n self.num_classes = num_classes\n self.bbox_attrs = 5 + num_classes\n self.img_size = img_size\n self.feature_length = [img_size[0]//32, img_size[0]//16, img_size[0]//8]\n self.label_smooth = label_smooth\n\n self.ignore_threshold = 0.5\n self.lambda_conf = 1.0\n self.lambda_cls = 1.0\n self.lambda_loc = 1.0\n self.cuda = cuda\n\n def forward(self, input, targets=None):\n # input为bs,3*(5+num_classes),13,13\n \n # 一共多少张图片\n banch_size = input.size(0)\n # 特征层的高\n in_h = input.size(2)\n # 特征层的宽\n in_w = input.size(3)\n\n # 计算步长\n # 每一个特征点对应原来的图片上多少个像素点\n # 如果特征层为13x13的话,一个特征点就对应原来的图片上的32个像素点\n stride_h = self.img_size[1] / in_h\n stride_w = self.img_size[0] / in_w\n\n # 把先验框的尺寸调整成特征层大小的形式\n # 计算出先验框在特征层上对应的宽高\n scaled_anchors = [(a_w / stride_w, a_h / stride_h) for a_w, a_h in self.anchors]\n # bs,3*(5+num_classes),13,13 -> bs,3,13,13,(5+num_classes)\n prediction = input.view(banch_size,\n int(self.num_anchors/3),\n self.bbox_attrs,\n in_h,\n in_w).permute(0, 1, 3, 4, 2).contiguous()\n \n # 对prediction预测进行调整\n conf = torch.sigmoid(prediction[..., 4]) # Conf\n pred_cls = torch.sigmoid(prediction[..., 5:]) # Cls pred.\n\n # 找到哪些先验框内部包含物体\n mask, noobj_mask, t_box, tconf, tcls, box_loss_scale_x, box_loss_scale_y = self.get_target(targets, scaled_anchors,in_w, in_h,self.ignore_threshold)\n\n noobj_mask, pred_boxes_for_ciou = self.get_ignore(prediction, targets, scaled_anchors, in_w, in_h, noobj_mask)\n\n if self.cuda:\n mask, noobj_mask = mask.cuda(), noobj_mask.cuda()\n box_loss_scale_x, box_loss_scale_y= box_loss_scale_x.cuda(), box_loss_scale_y.cuda()\n tconf, tcls = tconf.cuda(), tcls.cuda()\n pred_boxes_for_ciou = pred_boxes_for_ciou.cuda()\n t_box = t_box.cuda()\n\n box_loss_scale = 2 - box_loss_scale_x * box_loss_scale_y\n # losses.\n ciou = (1 - box_ciou( pred_boxes_for_ciou[mask.bool()], t_box[mask.bool()]))* box_loss_scale[mask.bool()]\n\n loss_loc = torch.sum(ciou / banch_size)\n loss_conf = torch.sum(BCELoss(conf, mask) * mask / banch_size) + \\\n torch.sum(BCELoss(conf, mask) * noobj_mask / banch_size)\n \n # print(smooth_labels(tcls[mask == 1],self.label_smooth,self.num_classes))\n loss_cls = torch.sum(BCELoss(pred_cls[mask == 1], smooth_labels(tcls[mask == 1],self.label_smooth,self.num_classes))/bs)\n # print(loss_loc,loss_conf,loss_cls)\n loss = loss_conf * self.lambda_conf + loss_cls * self.lambda_cls + loss_loc * self.lambda_loc\n return loss, loss_conf.item(), loss_cls.item(), loss_loc.item()\n\n def get_target(self, target, anchors, in_w, in_h, ignore_threshold):\n # 计算一共有多少张图片\n bs = len(target)\n # 获得先验框\n anchor_index = [[0, 1, 2], [3, 4, 5], [6, 7, 8]][self.feature_length.index(in_w)]\n subtract_index = [0, 3, 6][self.feature_length.index(in_w)]\n # 创建全是0或者全是1的阵列\n mask = torch.zeros(bs, int(self.num_anchors/3), in_h, in_w, requires_grad=False)\n noobj_mask = torch.ones(bs, int(self.num_anchors/3), in_h, in_w, requires_grad=False)\n\n tx = torch.zeros(bs, int(self.num_anchors/3), in_h, in_w, requires_grad=False)\n ty = torch.zeros(bs, int(self.num_anchors/3), in_h, in_w, requires_grad=False)\n tw = torch.zeros(bs, int(self.num_anchors/3), in_h, in_w, requires_grad=False)\n th = torch.zeros(bs, int(self.num_anchors/3), in_h, in_w, requires_grad=False)\n t_box = torch.zeros(bs, int(self.num_anchors/3), in_h, in_w, 4, requires_grad=False)\n tconf = torch.zeros(bs, int(self.num_anchors/3), in_h, in_w, requires_grad=False)\n tcls = torch.zeros(bs, int(self.num_anchors/3), in_h, in_w, self.num_classes, requires_grad=False)\n\n box_loss_scale_x = torch.zeros(bs, int(self.num_anchors/3), in_h, in_w, requires_grad=False)\n box_loss_scale_y = torch.zeros(bs, int(self.num_anchors/3), in_h, in_w, requires_grad=False)\n for b in range(bs):\n for t in range(target[b].shape[0]):\n # 计算出在特征层上的点位\n gx = target[b][t, 0] * in_w\n gy = target[b][t, 1] * in_h\n \n gw = target[b][t, 2] * in_w\n gh = target[b][t, 3] * in_h\n\n # 计算出属于哪个网格\n gi = int(gx)\n gj = int(gy)\n\n # 计算真实框的位置\n gt_box = torch.FloatTensor(np.array([0, 0, gw, gh])).unsqueeze(0)\n \n # 计算出所有先验框的位置\n anchor_shapes = torch.FloatTensor(np.concatenate((np.zeros((self.num_anchors, 2)),\n np.array(anchors)), 1))\n # 计算重合程度\n anch_ious = bbox_iou(gt_box, anchor_shapes)\n \n # Find the best matching anchor box\n best_n = np.argmax(anch_ious)\n if best_n not in anchor_index:\n continue\n # Masks\n if (gj < in_h) and (gi < in_w):\n best_n = best_n - subtract_index\n # 判定哪些先验框内部真实的存在物体\n noobj_mask[b, best_n, gj, gi] = 0\n mask[b, best_n, gj, gi] = 1\n # 计算先验框中心调整参数\n tx[b, best_n, gj, gi] = gx\n ty[b, best_n, gj, gi] = gy\n # 计算先验框宽高调整参数\n tw[b, best_n, gj, gi] = gw\n th[b, best_n, gj, gi] = gh\n # 用于获得xywh的比例\n box_loss_scale_x[b, best_n, gj, gi] = target[b][t, 2]\n box_loss_scale_y[b, best_n, gj, gi] = target[b][t, 3]\n # 物体置信度\n tconf[b, best_n, gj, gi] = 1\n # 种类\n tcls[b, best_n, gj, gi, int(target[b][t, 4])] = 1\n else:\n print('Step {0} out of bound'.format(b))\n print('gj: {0}, height: {1} | gi: {2}, width: {3}'.format(gj, in_h, gi, in_w))\n continue\n t_box[..., 0] = tx\n t_box[..., 1] = ty\n t_box[..., 2] = tw\n t_box[..., 3] = th\n return mask, noobj_mask, t_box, tconf, tcls, box_loss_scale_x, box_loss_scale_y\n\n def get_ignore(self,prediction,target,scaled_anchors,in_w, in_h,noobj_mask):\n bs = len(target)\n anchor_index = [[0,1,2],[3,4,5],[6,7,8]][self.feature_length.index(in_w)]\n scaled_anchors = np.array(scaled_anchors)[anchor_index]\n # 先验框的中心位置的调整参数\n x = torch.sigmoid(prediction[..., 0]) \n y = torch.sigmoid(prediction[..., 1])\n # 先验框的宽高调整参数\n w = prediction[..., 2] # Width\n h = prediction[..., 3] # Height\n\n FloatTensor = torch.cuda.FloatTensor if x.is_cuda else torch.FloatTensor\n LongTensor = torch.cuda.LongTensor if x.is_cuda else torch.LongTensor\n\n # 生成网格,先验框中心,网格左上角\n grid_x = torch.linspace(0, in_w - 1, in_w).repeat(in_w, 1).repeat(\n int(bs*self.num_anchors/3), 1, 1).view(x.shape).type(FloatTensor)\n grid_y = torch.linspace(0, in_h - 1, in_h).repeat(in_h, 1).t().repeat(\n int(bs*self.num_anchors/3), 1, 1).view(y.shape).type(FloatTensor)\n\n # 生成先验框的宽高\n anchor_w = FloatTensor(scaled_anchors).index_select(1, LongTensor([0]))\n anchor_h = FloatTensor(scaled_anchors).index_select(1, LongTensor([1]))\n \n anchor_w = anchor_w.repeat(bs, 1).repeat(1, 1, in_h * in_w).view(w.shape)\n anchor_h = anchor_h.repeat(bs, 1).repeat(1, 1, in_h * in_w).view(h.shape)\n \n # 计算调整后的先验框中心与宽高\n pred_boxes = FloatTensor(prediction[..., :4].shape)\n pred_boxes[..., 0] = x + grid_x\n pred_boxes[..., 1] = y + grid_y\n pred_boxes[..., 2] = torch.exp(w) * anchor_w\n pred_boxes[..., 3] = torch.exp(h) * anchor_h\n for i in range(bs):\n pred_boxes_for_ignore = pred_boxes[i]\n pred_boxes_for_ignore = pred_boxes_for_ignore.view(-1, 4)\n if len(target[i]) > 0:\n gx = target[i][:, 0:1] * in_w\n gy = target[i][:, 1:2] * in_h\n gw = target[i][:, 2:3] * in_w\n gh = target[i][:, 3:4] * in_h\n gt_box = torch.FloatTensor(np.concatenate([gx, gy, gw, gh],-1)).type(FloatTensor)\n\n anch_ious = jaccard(gt_box, pred_boxes_for_ignore)\n for t in range(target[i].shape[0]):\n anch_iou = anch_ious[t].view(pred_boxes[i].size()[:3])\n noobj_mask[i][anch_iou>self.ignore_threshold] = 0\n return noobj_mask, pred_boxes\n\n\ndef rand(a=0, b=1):\n return np.random.rand()*(b-a) + a\n\n\nclass Generator(object):\n def __init__(self,batch_size,\n train_lines, image_size,\n ):\n \n self.batch_size = batch_size\n self.train_lines = train_lines\n self.train_batches = len(train_lines)\n self.image_size = image_size\n \n def get_random_data(self, annotation_line, input_shape, jitter=.3, hue=.1, sat=1.5, val=1.5):\n '''r实时数据增强的随机预处理'''\n line = annotation_line.split()\n image = Image.open(line[0])\n iw, ih = image.size\n h, w = input_shape\n box = np.array([np.array(list(map(int,box.split(',')))) for box in line[1:]])\n\n # resize image\n new_ar = w/h * rand(1-jitter,1+jitter)/rand(1-jitter,1+jitter)\n scale = rand(.25, 2)\n if new_ar < 1:\n nh = int(scale*h)\n nw = int(nh*new_ar)\n else:\n nw = int(scale*w)\n nh = int(nw/new_ar)\n image = image.resize((nw,nh), Image.BICUBIC)\n\n # place image\n dx = int(rand(0, w-nw))\n dy = int(rand(0, h-nh))\n new_image = Image.new('RGB', (w,h), (128,128,128))\n new_image.paste(image, (dx, dy))\n image = new_image\n\n # flip image or not\n flip = rand()<.5\n if flip: image = image.transpose(Image.FLIP_LEFT_RIGHT)\n\n # distort image\n hue = rand(-hue, hue)\n sat = rand(1, sat) if rand()<.5 else 1/rand(1, sat)\n val = rand(1, val) if rand()<.5 else 1/rand(1, val)\n x = rgb_to_hsv(np.array(image)/255.)\n x[..., 0] += hue\n x[..., 0][x[..., 0]>1] -= 1\n x[..., 0][x[..., 0]<0] += 1\n x[..., 1] *= sat\n x[..., 2] *= val\n x[x>1] = 1\n x[x<0] = 0\n image_data = hsv_to_rgb(x)*255 # numpy array, 0 to 1\n\n # correct boxes\n box_data = np.zeros((len(box),5))\n if len(box)>0:\n np.random.shuffle(box)\n box[:, [0,2]] = box[:, [0,2]]*nw/iw + dx\n box[:, [1,3]] = box[:, [1,3]]*nh/ih + dy\n if flip: box[:, [0,2]] = w - box[:, [2,0]]\n box[:, 0:2][box[:, 0:2]<0] = 0\n box[:, 2][box[:, 2]>w] = w\n box[:, 3][box[:, 3]>h] = h\n box_w = box[:, 2] - box[:, 0]\n box_h = box[:, 3] - box[:, 1]\n box = box[np.logical_and(box_w>1, box_h>1)] # discard invalid box\n box_data = np.zeros((len(box),5))\n box_data[:len(box)] = box\n if len(box) == 0:\n return image_data, []\n\n if (box_data[:,:4]>0).any():\n return image_data, box_data\n else:\n return image_data, []\n\n def get_random_data_with_Mosaic(self, annotation_line, input_shape, hue=.1, sat=1.5, val=1.5):\n '''random preprocessing for real-time data augmentation'''\n h, w = input_shape\n min_offset_x = 0.4\n min_offset_y = 0.4\n scale_low = 1-min(min_offset_x,min_offset_y)\n scale_high = scale_low+0.2\n\n image_datas = [] \n box_datas = []\n index = 0\n\n place_x = [0,0,int(w*min_offset_x),int(w*min_offset_x)]\n place_y = [0,int(h*min_offset_y),int(w*min_offset_y),0]\n for line in annotation_line:\n # 每一行进行分割\n line_content = line.split()\n # 打开图片\n image = Image.open(line_content[0])\n image = image.convert(\"RGB\") \n # 图片的大小\n iw, ih = image.size\n # 保存框的位置\n box = np.array([np.array(list(map(int,box.split(',')))) for box in line_content[1:]])\n \n # 是否翻转图片\n flip = rand()<.5\n if flip and len(box)>0:\n image = image.transpose(Image.FLIP_LEFT_RIGHT)\n box[:, [0,2]] = iw - box[:, [2,0]]\n\n # 对输入进来的图片进行缩放\n new_ar = w/h\n scale = rand(scale_low, scale_high)\n if new_ar < 1:\n nh = int(scale*h)\n nw = int(nh*new_ar)\n else:\n nw = int(scale*w)\n nh = int(nw/new_ar)\n image = image.resize((nw,nh), Image.BICUBIC)\n\n # 进行色域变换\n hue = rand(-hue, hue)\n sat = rand(1, sat) if rand()<.5 else 1/rand(1, sat)\n val = rand(1, val) if rand()<.5 else 1/rand(1, val)\n x = rgb_to_hsv(np.array(image)/255.)\n x[..., 0] += hue\n x[..., 0][x[..., 0]>1] -= 1\n x[..., 0][x[..., 0]<0] += 1\n x[..., 1] *= sat\n x[..., 2] *= val\n x[x>1] = 1\n x[x<0] = 0\n image = hsv_to_rgb(x)\n\n image = Image.fromarray((image*255).astype(np.uint8))\n # 将图片进行放置,分别对应四张分割图片的位置\n dx = place_x[index]\n dy = place_y[index]\n new_image = Image.new('RGB', (w,h), (128,128,128))\n new_image.paste(image, (dx, dy))\n image_data = np.array(new_image)\n\n \n index = index + 1\n box_data = []\n # 对box进行重新处理\n if len(box)>0:\n np.random.shuffle(box)\n box[:, [0,2]] = box[:, [0,2]]*nw/iw + dx\n box[:, [1,3]] = box[:, [1,3]]*nh/ih + dy\n box[:, 0:2][box[:, 0:2]<0] = 0\n box[:, 2][box[:, 2]>w] = w\n box[:, 3][box[:, 3]>h] = h\n box_w = box[:, 2] - box[:, 0]\n box_h = box[:, 3] - box[:, 1]\n box = box[np.logical_and(box_w>1, box_h>1)]\n box_data = np.zeros((len(box),5))\n box_data[:len(box)] = box\n \n image_datas.append(image_data)\n box_datas.append(box_data)\n\n # 将图片分割,放在一起\n cutx = np.random.randint(int(w*min_offset_x), int(w*(1 - min_offset_x)))\n cuty = np.random.randint(int(h*min_offset_y), int(h*(1 - min_offset_y)))\n\n new_image = np.zeros([h,w,3])\n new_image[:cuty, :cutx, :] = image_datas[0][:cuty, :cutx, :]\n new_image[cuty:, :cutx, :] = image_datas[1][cuty:, :cutx, :]\n new_image[cuty:, cutx:, :] = image_datas[2][cuty:, cutx:, :]\n new_image[:cuty, cutx:, :] = image_datas[3][:cuty, cutx:, :]\n\n # 对框进行进一步的处理\n new_boxes = np.array(merge_bboxes(box_datas, cutx, cuty))\n\n if len(new_boxes) == 0:\n return new_image, []\n if (new_boxes[:,:4]>0).any():\n return new_image, new_boxes\n else:\n return new_image, []\n\n def generate(self, train=True, mosaic=False):\n while True:\n shuffle(self.train_lines)\n lines = self.train_lines\n inputs = []\n targets = []\n flag = True\n n = len(lines)\n for i in range(len(lines)):\n if mosaic == True:\n if flag and (i+4) < n:\n img,y = self.get_random_data_with_Mosaic(lines[i:i+4], self.image_size[0:2])\n i = (i+4) % n\n else:\n img,y = self.get_random_data(lines[i], self.image_size[0:2])\n i = (i+1) % n\n flag = bool(1-flag)\n else:\n img,y = self.get_random_data(lines[i], self.image_size[0:2])\n i = (i+1) % n\n if len(y)!=0:\n boxes = np.array(y[:,:4],dtype=np.float32)\n boxes[:,0] = boxes[:,0]/self.image_size[1]\n boxes[:,1] = boxes[:,1]/self.image_size[0]\n boxes[:,2] = boxes[:,2]/self.image_size[1]\n boxes[:,3] = boxes[:,3]/self.image_size[0]\n\n boxes = np.maximum(np.minimum(boxes,1),0)\n boxes[:,2] = boxes[:,2] - boxes[:,0]\n boxes[:,3] = boxes[:,3] - boxes[:,1]\n \n boxes[:,0] = boxes[:,0] + boxes[:,2]/2\n boxes[:,1] = boxes[:,1] + boxes[:,3]/2\n y = np.concatenate([boxes,y[:,-1:]],axis=-1)\n \n img = np.array(img,dtype = np.float32)\n\n inputs.append(np.transpose(img/255.0,(2,0,1))) \n targets.append(np.array(y,dtype = np.float32))\n if len(targets) == self.batch_size:\n tmp_inp = np.array(inputs)\n tmp_targets = np.array(targets)\n inputs = []\n targets = []\n yield tmp_inp, tmp_targets\n"
] | [
[
"numpy.minimum",
"torch.max",
"matplotlib.colors.hsv_to_rgb",
"torch.sum",
"numpy.concatenate",
"torch.pow",
"numpy.argmax",
"numpy.zeros",
"torch.sigmoid",
"torch.linspace",
"torch.min",
"torch.zeros_like",
"torch.exp",
"torch.log",
"numpy.random.rand",
"numpy.transpose",
"numpy.logical_and",
"numpy.array",
"numpy.random.shuffle",
"torch.clamp"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
PacktPublishing/Artificial-Intelligence-with-Python-Sequence-Learning | [
"6de47b517b31e56a6fb39bd083ce5036f5418708"
] | [
"Section 2/hmm.py"
] | [
"import datetime\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom hmmlearn.hmm import GaussianHMM\n\nfrom timeseries import read_data \n\nimport warnings\nwarnings.simplefilter(\"ignore\", DeprecationWarning)\n\n# Load input data\ndata = np.loadtxt('data_1D.txt', delimiter=',')\n\n# Extract the data column (third column) for training\nX = np.column_stack([data[:, 2]])\n\n# Create a Gaussian HMM\nnum_components = 5\nhmm = GaussianHMM(n_components=num_components,\n covariance_type='diag', n_iter=1000)\n\n# Train the HMM\nprint('\\nTraining the Hidden Markov Model...')\nhmm.fit(X)\n\n# Print HMM stats\nprint('\\nMeans and variances:')\nfor i in range(hmm.n_components):\n print('\\nHidden state', i+1)\n print('Mean =', round(hmm.means_[i][0], 2))\n print('Variance =', round(np.diag(hmm.covars_[i])[0], 2))\n\n# Generate data using the HMM model\nnum_samples = 1200\ngenerated_data, _ = hmm.sample(num_samples)\nplt.plot(np.arange(num_samples), generated_data[:, 0], c='black')\nplt.title('Generated data')\n\nplt.show()\n"
] | [
[
"numpy.diag",
"matplotlib.pyplot.title",
"numpy.arange",
"numpy.column_stack",
"matplotlib.pyplot.show",
"numpy.loadtxt"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Sangarshanan/pandas | [
"90d7ad2cee84ae91e7eb0c6c2b7a142a3ba9351c"
] | [
"pandas/core/indexes/period.py"
] | [
"from datetime import datetime, timedelta\nimport weakref\n\nimport numpy as np\n\nfrom pandas._libs import index as libindex\nfrom pandas._libs.tslibs import NaT, frequencies as libfrequencies, iNaT, resolution\nfrom pandas._libs.tslibs.period import DIFFERENT_FREQ, IncompatibleFrequency, Period\nfrom pandas.util._decorators import Appender, Substitution, cache_readonly\n\nfrom pandas.core.dtypes.common import (\n ensure_platform_int,\n is_bool_dtype,\n is_datetime64_any_dtype,\n is_float,\n is_float_dtype,\n is_integer,\n is_integer_dtype,\n pandas_dtype,\n)\n\nfrom pandas.core.accessor import delegate_names\nfrom pandas.core.arrays.period import PeriodArray, period_array, validate_dtype_freq\nfrom pandas.core.base import _shared_docs\nimport pandas.core.common as com\nimport pandas.core.indexes.base as ibase\nfrom pandas.core.indexes.base import (\n _index_shared_docs,\n ensure_index,\n maybe_extract_name,\n)\nfrom pandas.core.indexes.datetimelike import (\n DatetimeIndexOpsMixin,\n DatetimelikeDelegateMixin,\n)\nfrom pandas.core.indexes.datetimes import DatetimeIndex, Index\nfrom pandas.core.indexes.numeric import Int64Index\nfrom pandas.core.missing import isna\nfrom pandas.core.ops import get_op_result_name\nfrom pandas.core.tools.datetimes import DateParseError, parse_time_string\n\nfrom pandas.tseries import frequencies\nfrom pandas.tseries.offsets import DateOffset, Tick\n\n_index_doc_kwargs = dict(ibase._index_doc_kwargs)\n_index_doc_kwargs.update(dict(target_klass=\"PeriodIndex or list of Periods\"))\n\n\n# --- Period index sketch\n\n\ndef _new_PeriodIndex(cls, **d):\n # GH13277 for unpickling\n values = d.pop(\"data\")\n if values.dtype == \"int64\":\n freq = d.pop(\"freq\", None)\n values = PeriodArray(values, freq=freq)\n return cls._simple_new(values, **d)\n else:\n return cls(values, **d)\n\n\nclass PeriodDelegateMixin(DatetimelikeDelegateMixin):\n \"\"\"\n Delegate from PeriodIndex to PeriodArray.\n \"\"\"\n\n _delegate_class = PeriodArray\n _raw_methods = {\"_format_native_types\"}\n _raw_properties = {\"is_leap_year\", \"freq\"}\n\n _delegated_properties = PeriodArray._datetimelike_ops + list(_raw_properties)\n _delegated_methods = set(PeriodArray._datetimelike_methods) | _raw_methods\n\n\n@delegate_names(PeriodArray, PeriodDelegateMixin._delegated_properties, typ=\"property\")\n@delegate_names(\n PeriodArray, PeriodDelegateMixin._delegated_methods, typ=\"method\", overwrite=True\n)\nclass PeriodIndex(DatetimeIndexOpsMixin, Int64Index, PeriodDelegateMixin):\n \"\"\"\n Immutable ndarray holding ordinal values indicating regular periods in time.\n\n Index keys are boxed to Period objects which carries the metadata (eg,\n frequency information).\n\n Parameters\n ----------\n data : array-like (1d int np.ndarray or PeriodArray), optional\n Optional period-like data to construct index with.\n copy : bool\n Make a copy of input ndarray.\n freq : str or period object, optional\n One of pandas period strings or corresponding objects\n year : int, array, or Series, default None\n month : int, array, or Series, default None\n quarter : int, array, or Series, default None\n day : int, array, or Series, default None\n hour : int, array, or Series, default None\n minute : int, array, or Series, default None\n second : int, array, or Series, default None\n tz : object, default None\n Timezone for converting datetime64 data to Periods.\n dtype : str or PeriodDtype, default None\n\n Attributes\n ----------\n day\n dayofweek\n dayofyear\n days_in_month\n daysinmonth\n end_time\n freq\n freqstr\n hour\n is_leap_year\n minute\n month\n quarter\n qyear\n second\n start_time\n week\n weekday\n weekofyear\n year\n\n Methods\n -------\n asfreq\n strftime\n to_timestamp\n\n See Also\n --------\n Index : The base pandas Index type.\n Period : Represents a period of time.\n DatetimeIndex : Index with datetime64 data.\n TimedeltaIndex : Index of timedelta64 data.\n period_range : Create a fixed-frequency PeriodIndex.\n\n Examples\n --------\n >>> idx = pd.PeriodIndex(year=year_arr, quarter=q_arr)\n \"\"\"\n\n _typ = \"periodindex\"\n _attributes = [\"name\", \"freq\"]\n\n # define my properties & methods for delegation\n _is_numeric_dtype = False\n _infer_as_myclass = True\n\n _data: PeriodArray\n\n _engine_type = libindex.PeriodEngine\n _supports_partial_string_indexing = True\n\n # ------------------------------------------------------------------------\n # Index Constructors\n\n def __new__(\n cls,\n data=None,\n ordinal=None,\n freq=None,\n tz=None,\n dtype=None,\n copy=False,\n name=None,\n **fields,\n ):\n\n valid_field_set = {\n \"year\",\n \"month\",\n \"day\",\n \"quarter\",\n \"hour\",\n \"minute\",\n \"second\",\n }\n\n if not set(fields).issubset(valid_field_set):\n argument = list(set(fields) - valid_field_set)[0]\n raise TypeError(f\"__new__() got an unexpected keyword argument {argument}\")\n\n name = maybe_extract_name(name, data, cls)\n\n if data is None and ordinal is None:\n # range-based.\n data, freq2 = PeriodArray._generate_range(None, None, None, freq, fields)\n # PeriodArray._generate range does validation that fields is\n # empty when really using the range-based constructor.\n freq = freq2\n\n data = PeriodArray(data, freq=freq)\n else:\n freq = validate_dtype_freq(dtype, freq)\n\n # PeriodIndex allow PeriodIndex(period_index, freq=different)\n # Let's not encourage that kind of behavior in PeriodArray.\n\n if freq and isinstance(data, cls) and data.freq != freq:\n # TODO: We can do some of these with no-copy / coercion?\n # e.g. D -> 2D seems to be OK\n data = data.asfreq(freq)\n\n if data is None and ordinal is not None:\n # we strangely ignore `ordinal` if data is passed.\n ordinal = np.asarray(ordinal, dtype=np.int64)\n data = PeriodArray(ordinal, freq)\n else:\n # don't pass copy here, since we copy later.\n data = period_array(data=data, freq=freq)\n\n if copy:\n data = data.copy()\n\n return cls._simple_new(data, name=name)\n\n @classmethod\n def _simple_new(cls, values, name=None, freq=None, **kwargs):\n \"\"\"\n Create a new PeriodIndex.\n\n Parameters\n ----------\n values : PeriodArray, PeriodIndex, Index[int64], ndarray[int64]\n Values that can be converted to a PeriodArray without inference\n or coercion.\n\n \"\"\"\n # TODO: raising on floats is tested, but maybe not useful.\n # Should the callers know not to pass floats?\n # At the very least, I think we can ensure that lists aren't passed.\n if isinstance(values, list):\n values = np.asarray(values)\n if is_float_dtype(values):\n raise TypeError(\"PeriodIndex._simple_new does not accept floats.\")\n if freq:\n freq = Period._maybe_convert_freq(freq)\n values = PeriodArray(values, freq=freq)\n\n if not isinstance(values, PeriodArray):\n raise TypeError(\"PeriodIndex._simple_new only accepts PeriodArray\")\n result = object.__new__(cls)\n result._data = values\n # For groupby perf. See note in indexes/base about _index_data\n result._index_data = values._data\n result.name = name\n result._reset_identity()\n return result\n\n # ------------------------------------------------------------------------\n # Data\n\n @property\n def values(self):\n return np.asarray(self)\n\n def _shallow_copy(self, values=None, **kwargs):\n # TODO: simplify, figure out type of values\n if values is None:\n values = self._data\n\n if isinstance(values, type(self)):\n values = values._values\n\n if not isinstance(values, PeriodArray):\n if isinstance(values, np.ndarray) and is_integer_dtype(values.dtype):\n values = PeriodArray(values, freq=self.freq)\n else:\n # in particular, I would like to avoid period_array here.\n # Some people seem to be calling use with unexpected types\n # Index.difference -> ndarray[Period]\n # DatetimelikeIndexOpsMixin.repeat -> ndarray[ordinal]\n # I think that once all of Datetime* are EAs, we can simplify\n # this quite a bit.\n values = period_array(values, freq=self.freq)\n\n # We don't allow changing `freq` in _shallow_copy.\n validate_dtype_freq(self.dtype, kwargs.get(\"freq\"))\n attributes = self._get_attributes_dict()\n\n attributes.update(kwargs)\n if not len(values) and \"dtype\" not in kwargs:\n attributes[\"dtype\"] = self.dtype\n return self._simple_new(values, **attributes)\n\n def _shallow_copy_with_infer(self, values=None, **kwargs):\n \"\"\" we always want to return a PeriodIndex \"\"\"\n return self._shallow_copy(values=values, **kwargs)\n\n @property\n def _box_func(self):\n \"\"\"Maybe box an ordinal or Period\"\"\"\n # TODO(DatetimeArray): Avoid double-boxing\n # PeriodArray takes care of boxing already, so we need to check\n # whether we're given an ordinal or a Period. It seems like some\n # places outside of indexes/period.py are calling this _box_func,\n # but passing data that's already boxed.\n def func(x):\n if isinstance(x, Period) or x is NaT:\n return x\n else:\n return Period._from_ordinal(ordinal=x, freq=self.freq)\n\n return func\n\n def _maybe_convert_timedelta(self, other):\n \"\"\"\n Convert timedelta-like input to an integer multiple of self.freq\n\n Parameters\n ----------\n other : timedelta, np.timedelta64, DateOffset, int, np.ndarray\n\n Returns\n -------\n converted : int, np.ndarray[int64]\n\n Raises\n ------\n IncompatibleFrequency : if the input cannot be written as a multiple\n of self.freq. Note IncompatibleFrequency subclasses ValueError.\n \"\"\"\n if isinstance(other, (timedelta, np.timedelta64, Tick, np.ndarray)):\n offset = frequencies.to_offset(self.freq.rule_code)\n if isinstance(offset, Tick):\n # _check_timedeltalike_freq_compat will raise if incompatible\n delta = self._data._check_timedeltalike_freq_compat(other)\n return delta\n elif isinstance(other, DateOffset):\n freqstr = other.rule_code\n base = libfrequencies.get_base_alias(freqstr)\n if base == self.freq.rule_code:\n return other.n\n\n msg = DIFFERENT_FREQ.format(\n cls=type(self).__name__, own_freq=self.freqstr, other_freq=other.freqstr\n )\n raise IncompatibleFrequency(msg)\n elif is_integer(other):\n # integer is passed to .shift via\n # _add_datetimelike_methods basically\n # but ufunc may pass integer to _add_delta\n return other\n\n # raise when input doesn't have freq\n msg = DIFFERENT_FREQ.format(\n cls=type(self).__name__, own_freq=self.freqstr, other_freq=None\n )\n raise IncompatibleFrequency(msg)\n\n # ------------------------------------------------------------------------\n # Rendering Methods\n\n def _mpl_repr(self):\n # how to represent ourselves to matplotlib\n return self.astype(object).values\n\n @property\n def _formatter_func(self):\n return self.array._formatter(boxed=False)\n\n # ------------------------------------------------------------------------\n # Indexing\n\n @cache_readonly\n def _engine(self):\n # To avoid a reference cycle, pass a weakref of self to _engine_type.\n period = weakref.ref(self)\n return self._engine_type(period, len(self))\n\n @Appender(_index_shared_docs[\"contains\"])\n def __contains__(self, key) -> bool:\n if isinstance(key, Period):\n if key.freq != self.freq:\n return False\n else:\n return key.ordinal in self._engine\n else:\n try:\n self.get_loc(key)\n return True\n except (TypeError, KeyError):\n # TypeError can be reached if we pass a tuple that is not hashable\n return False\n\n @cache_readonly\n def _int64index(self):\n return Int64Index._simple_new(self.asi8, name=self.name)\n\n # ------------------------------------------------------------------------\n # Index Methods\n\n def _coerce_scalar_to_index(self, item):\n \"\"\"\n we need to coerce a scalar to a compat for our index type\n\n Parameters\n ----------\n item : scalar item to coerce\n \"\"\"\n return PeriodIndex([item], **self._get_attributes_dict())\n\n def __array__(self, dtype=None):\n if is_integer_dtype(dtype):\n return self.asi8\n else:\n return self.astype(object).values\n\n def __array_wrap__(self, result, context=None):\n \"\"\"\n Gets called after a ufunc. Needs additional handling as\n PeriodIndex stores internal data as int dtype\n\n Replace this to __numpy_ufunc__ in future version\n \"\"\"\n if isinstance(context, tuple) and len(context) > 0:\n func = context[0]\n if func is np.add:\n pass\n elif func is np.subtract:\n name = self.name\n left = context[1][0]\n right = context[1][1]\n if isinstance(left, PeriodIndex) and isinstance(right, PeriodIndex):\n name = left.name if left.name == right.name else None\n return Index(result, name=name)\n elif isinstance(left, Period) or isinstance(right, Period):\n return Index(result, name=name)\n elif isinstance(func, np.ufunc):\n if \"M->M\" not in func.types:\n msg = f\"ufunc '{func.__name__}' not supported for the PeriodIndex\"\n # This should be TypeError, but TypeError cannot be raised\n # from here because numpy catches.\n raise ValueError(msg)\n\n if is_bool_dtype(result):\n return result\n # the result is object dtype array of Period\n # cannot pass _simple_new as it is\n return type(self)(result, freq=self.freq, name=self.name)\n\n def asof_locs(self, where, mask):\n \"\"\"\n where : array of timestamps\n mask : array of booleans where data is not NA\n\n \"\"\"\n where_idx = where\n if isinstance(where_idx, DatetimeIndex):\n where_idx = PeriodIndex(where_idx.values, freq=self.freq)\n\n locs = self._ndarray_values[mask].searchsorted(\n where_idx._ndarray_values, side=\"right\"\n )\n\n locs = np.where(locs > 0, locs - 1, 0)\n result = np.arange(len(self))[mask].take(locs)\n\n first = mask.argmax()\n result[\n (locs == 0) & (where_idx._ndarray_values < self._ndarray_values[first])\n ] = -1\n\n return result\n\n @Appender(_index_shared_docs[\"astype\"])\n def astype(self, dtype, copy=True, how=\"start\"):\n dtype = pandas_dtype(dtype)\n\n if is_datetime64_any_dtype(dtype):\n # 'how' is index-specific, isn't part of the EA interface.\n tz = getattr(dtype, \"tz\", None)\n return self.to_timestamp(how=how).tz_localize(tz)\n\n # TODO: should probably raise on `how` here, so we don't ignore it.\n return super().astype(dtype, copy=copy)\n\n @Substitution(klass=\"PeriodIndex\")\n @Appender(_shared_docs[\"searchsorted\"])\n def searchsorted(self, value, side=\"left\", sorter=None):\n if isinstance(value, Period):\n if value.freq != self.freq:\n msg = DIFFERENT_FREQ.format(\n cls=type(self).__name__,\n own_freq=self.freqstr,\n other_freq=value.freqstr,\n )\n raise IncompatibleFrequency(msg)\n value = value.ordinal\n elif isinstance(value, str):\n try:\n value = Period(value, freq=self.freq).ordinal\n except DateParseError:\n raise KeyError(f\"Cannot interpret '{value}' as period\")\n\n return self._ndarray_values.searchsorted(value, side=side, sorter=sorter)\n\n @property\n def is_full(self) -> bool:\n \"\"\"\n Returns True if this PeriodIndex is range-like in that all Periods\n between start and end are present, in order.\n \"\"\"\n if len(self) == 0:\n return True\n if not self.is_monotonic:\n raise ValueError(\"Index is not monotonic\")\n values = self.asi8\n return ((values[1:] - values[:-1]) < 2).all()\n\n @property\n def inferred_type(self) -> str:\n # b/c data is represented as ints make sure we can't have ambiguous\n # indexing\n return \"period\"\n\n def get_value(self, series, key):\n \"\"\"\n Fast lookup of value from 1-dimensional ndarray. Only use this if you\n know what you're doing\n \"\"\"\n s = com.values_from_object(series)\n try:\n return com.maybe_box(self, super().get_value(s, key), series, key)\n except (KeyError, IndexError):\n if isinstance(key, str):\n asdt, parsed, reso = parse_time_string(key, self.freq)\n grp = resolution.Resolution.get_freq_group(reso)\n freqn = resolution.get_freq_group(self.freq)\n\n vals = self._ndarray_values\n\n # if our data is higher resolution than requested key, slice\n if grp < freqn:\n iv = Period(asdt, freq=(grp, 1))\n ord1 = iv.asfreq(self.freq, how=\"S\").ordinal\n ord2 = iv.asfreq(self.freq, how=\"E\").ordinal\n\n if ord2 < vals[0] or ord1 > vals[-1]:\n raise KeyError(key)\n\n pos = np.searchsorted(self._ndarray_values, [ord1, ord2])\n key = slice(pos[0], pos[1] + 1)\n return series[key]\n elif grp == freqn:\n key = Period(asdt, freq=self.freq).ordinal\n return com.maybe_box(\n self, self._int64index.get_value(s, key), series, key\n )\n else:\n raise KeyError(key)\n\n period = Period(key, self.freq)\n key = period.value if isna(period) else period.ordinal\n return com.maybe_box(self, self._int64index.get_value(s, key), series, key)\n\n @Appender(_index_shared_docs[\"get_indexer\"] % _index_doc_kwargs)\n def get_indexer(self, target, method=None, limit=None, tolerance=None):\n target = ensure_index(target)\n\n if hasattr(target, \"freq\") and target.freq != self.freq:\n msg = DIFFERENT_FREQ.format(\n cls=type(self).__name__,\n own_freq=self.freqstr,\n other_freq=target.freqstr,\n )\n raise IncompatibleFrequency(msg)\n\n if isinstance(target, PeriodIndex):\n target = target.asi8\n self_index = self._int64index\n else:\n self_index = self\n\n if tolerance is not None:\n tolerance = self._convert_tolerance(tolerance, target)\n return Index.get_indexer(self_index, target, method, limit, tolerance)\n\n @Appender(_index_shared_docs[\"get_indexer_non_unique\"] % _index_doc_kwargs)\n def get_indexer_non_unique(self, target):\n target = ensure_index(target)\n\n if isinstance(target, PeriodIndex):\n target = target.asi8\n if hasattr(target, \"freq\") and target.freq != self.freq:\n msg = DIFFERENT_FREQ.format(\n cls=type(self).__name__,\n own_freq=self.freqstr,\n other_freq=target.freqstr,\n )\n raise IncompatibleFrequency(msg)\n\n indexer, missing = self._int64index.get_indexer_non_unique(target)\n return ensure_platform_int(indexer), missing\n\n def _get_unique_index(self, dropna=False):\n \"\"\"\n wrap Index._get_unique_index to handle NaT\n \"\"\"\n res = super()._get_unique_index(dropna=dropna)\n if dropna:\n res = res.dropna()\n return res\n\n def get_loc(self, key, method=None, tolerance=None):\n \"\"\"\n Get integer location for requested label\n\n Returns\n -------\n loc : int\n \"\"\"\n try:\n return self._engine.get_loc(key)\n except KeyError:\n if is_integer(key):\n raise\n\n try:\n asdt, parsed, reso = parse_time_string(key, self.freq)\n key = asdt\n except TypeError:\n pass\n except DateParseError:\n # A string with invalid format\n raise KeyError(f\"Cannot interpret '{key}' as period\")\n\n try:\n key = Period(key, freq=self.freq)\n except ValueError:\n # we cannot construct the Period\n # as we have an invalid type\n raise KeyError(key)\n\n try:\n ordinal = iNaT if key is NaT else key.ordinal\n if tolerance is not None:\n tolerance = self._convert_tolerance(tolerance, np.asarray(key))\n return self._int64index.get_loc(ordinal, method, tolerance)\n\n except KeyError:\n raise KeyError(key)\n\n def _maybe_cast_slice_bound(self, label, side, kind):\n \"\"\"\n If label is a string or a datetime, cast it to Period.ordinal according\n to resolution.\n\n Parameters\n ----------\n label : object\n side : {'left', 'right'}\n kind : {'ix', 'loc', 'getitem'}\n\n Returns\n -------\n bound : Period or object\n\n Notes\n -----\n Value of `side` parameter should be validated in caller.\n\n \"\"\"\n assert kind in [\"ix\", \"loc\", \"getitem\"]\n\n if isinstance(label, datetime):\n return Period(label, freq=self.freq)\n elif isinstance(label, str):\n try:\n _, parsed, reso = parse_time_string(label, self.freq)\n bounds = self._parsed_string_to_bounds(reso, parsed)\n return bounds[0 if side == \"left\" else 1]\n except ValueError:\n # string cannot be parsed as datetime-like\n # TODO: we need tests for this case\n raise KeyError(label)\n elif is_integer(label) or is_float(label):\n self._invalid_indexer(\"slice\", label)\n\n return label\n\n def _parsed_string_to_bounds(self, reso, parsed):\n if reso == \"year\":\n t1 = Period(year=parsed.year, freq=\"A\")\n elif reso == \"month\":\n t1 = Period(year=parsed.year, month=parsed.month, freq=\"M\")\n elif reso == \"quarter\":\n q = (parsed.month - 1) // 3 + 1\n t1 = Period(year=parsed.year, quarter=q, freq=\"Q-DEC\")\n elif reso == \"day\":\n t1 = Period(year=parsed.year, month=parsed.month, day=parsed.day, freq=\"D\")\n elif reso == \"hour\":\n t1 = Period(\n year=parsed.year,\n month=parsed.month,\n day=parsed.day,\n hour=parsed.hour,\n freq=\"H\",\n )\n elif reso == \"minute\":\n t1 = Period(\n year=parsed.year,\n month=parsed.month,\n day=parsed.day,\n hour=parsed.hour,\n minute=parsed.minute,\n freq=\"T\",\n )\n elif reso == \"second\":\n t1 = Period(\n year=parsed.year,\n month=parsed.month,\n day=parsed.day,\n hour=parsed.hour,\n minute=parsed.minute,\n second=parsed.second,\n freq=\"S\",\n )\n else:\n raise KeyError(reso)\n return (t1.asfreq(self.freq, how=\"start\"), t1.asfreq(self.freq, how=\"end\"))\n\n def _get_string_slice(self, key):\n if not self.is_monotonic:\n raise ValueError(\"Partial indexing only valid for ordered time series\")\n\n key, parsed, reso = parse_time_string(key, self.freq)\n grp = resolution.Resolution.get_freq_group(reso)\n freqn = resolution.get_freq_group(self.freq)\n if reso in [\"day\", \"hour\", \"minute\", \"second\"] and not grp < freqn:\n raise KeyError(key)\n\n t1, t2 = self._parsed_string_to_bounds(reso, parsed)\n return slice(\n self.searchsorted(t1.ordinal, side=\"left\"),\n self.searchsorted(t2.ordinal, side=\"right\"),\n )\n\n def _convert_tolerance(self, tolerance, target):\n tolerance = DatetimeIndexOpsMixin._convert_tolerance(self, tolerance, target)\n if target.size != tolerance.size and tolerance.size > 1:\n raise ValueError(\"list-like tolerance size must match target index size\")\n return self._maybe_convert_timedelta(tolerance)\n\n def insert(self, loc, item):\n if not isinstance(item, Period) or self.freq != item.freq:\n return self.astype(object).insert(loc, item)\n\n idx = np.concatenate(\n (self[:loc].asi8, np.array([item.ordinal]), self[loc:].asi8)\n )\n return self._shallow_copy(idx)\n\n def join(self, other, how=\"left\", level=None, return_indexers=False, sort=False):\n \"\"\"\n See Index.join\n \"\"\"\n self._assert_can_do_setop(other)\n\n if not isinstance(other, PeriodIndex):\n return self.astype(object).join(\n other, how=how, level=level, return_indexers=return_indexers, sort=sort\n )\n\n result = Int64Index.join(\n self,\n other,\n how=how,\n level=level,\n return_indexers=return_indexers,\n sort=sort,\n )\n\n if return_indexers:\n result, lidx, ridx = result\n return self._apply_meta(result), lidx, ridx\n return self._apply_meta(result)\n\n def _assert_can_do_setop(self, other):\n super()._assert_can_do_setop(other)\n\n # *Can't* use PeriodIndexes of different freqs\n # *Can* use PeriodIndex/DatetimeIndex\n if isinstance(other, PeriodIndex) and self.freq != other.freq:\n msg = DIFFERENT_FREQ.format(\n cls=type(self).__name__, own_freq=self.freqstr, other_freq=other.freqstr\n )\n raise IncompatibleFrequency(msg)\n\n def _wrap_setop_result(self, other, result):\n name = get_op_result_name(self, other)\n result = self._apply_meta(result)\n result.name = name\n return result\n\n def _apply_meta(self, rawarr):\n if not isinstance(rawarr, PeriodIndex):\n rawarr = PeriodIndex._simple_new(rawarr, freq=self.freq, name=self.name)\n return rawarr\n\n def __setstate__(self, state):\n \"\"\"Necessary for making this object picklable\"\"\"\n\n if isinstance(state, dict):\n super().__setstate__(state)\n\n elif isinstance(state, tuple):\n\n # < 0.15 compat\n if len(state) == 2:\n nd_state, own_state = state\n data = np.empty(nd_state[1], dtype=nd_state[2])\n np.ndarray.__setstate__(data, nd_state)\n\n # backcompat\n freq = Period._maybe_convert_freq(own_state[1])\n\n else: # pragma: no cover\n data = np.empty(state)\n np.ndarray.__setstate__(self, state)\n freq = None # ?\n\n data = PeriodArray(data, freq=freq)\n self._data = data\n\n else:\n raise Exception(\"invalid pickle state\")\n\n _unpickle_compat = __setstate__\n\n def memory_usage(self, deep=False):\n result = super().memory_usage(deep=deep)\n if hasattr(self, \"_cache\") and \"_int64index\" in self._cache:\n result += self._int64index.memory_usage(deep=deep)\n return result\n\n\nPeriodIndex._add_comparison_ops()\nPeriodIndex._add_numeric_methods_disabled()\nPeriodIndex._add_logical_methods_disabled()\n\n\ndef period_range(\n start=None, end=None, periods=None, freq=None, name=None\n) -> PeriodIndex:\n \"\"\"\n Return a fixed frequency PeriodIndex.\n\n The day (calendar) is the default frequency.\n\n Parameters\n ----------\n start : str or period-like, default None\n Left bound for generating periods.\n end : str or period-like, default None\n Right bound for generating periods.\n periods : int, default None\n Number of periods to generate.\n freq : str or DateOffset, optional\n Frequency alias. By default the freq is taken from `start` or `end`\n if those are Period objects. Otherwise, the default is ``\"D\"`` for\n daily frequency.\n name : str, default None\n Name of the resulting PeriodIndex.\n\n Returns\n -------\n PeriodIndex\n\n Notes\n -----\n Of the three parameters: ``start``, ``end``, and ``periods``, exactly two\n must be specified.\n\n To learn more about the frequency strings, please see `this link\n <https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases>`__.\n\n Examples\n --------\n\n >>> pd.period_range(start='2017-01-01', end='2018-01-01', freq='M')\n PeriodIndex(['2017-01', '2017-02', '2017-03', '2017-04', '2017-05',\n '2017-06', '2017-06', '2017-07', '2017-08', '2017-09',\n '2017-10', '2017-11', '2017-12', '2018-01'],\n dtype='period[M]', freq='M')\n\n If ``start`` or ``end`` are ``Period`` objects, they will be used as anchor\n endpoints for a ``PeriodIndex`` with frequency matching that of the\n ``period_range`` constructor.\n\n >>> pd.period_range(start=pd.Period('2017Q1', freq='Q'),\n ... end=pd.Period('2017Q2', freq='Q'), freq='M')\n PeriodIndex(['2017-03', '2017-04', '2017-05', '2017-06'],\n dtype='period[M]', freq='M')\n \"\"\"\n if com.count_not_none(start, end, periods) != 2:\n raise ValueError(\n \"Of the three parameters: start, end, and periods, \"\n \"exactly two must be specified\"\n )\n if freq is None and (not isinstance(start, Period) and not isinstance(end, Period)):\n freq = \"D\"\n\n data, freq = PeriodArray._generate_range(start, end, periods, freq, fields={})\n data = PeriodArray(data, freq=freq)\n return PeriodIndex(data, name=name)\n"
] | [
[
"pandas.tseries.frequencies.to_offset",
"pandas.core.missing.isna",
"pandas.core.indexes.numeric.Int64Index.join",
"numpy.asarray",
"pandas.core.accessor.delegate_names",
"pandas._libs.tslibs.resolution.get_freq_group",
"numpy.searchsorted",
"pandas._libs.tslibs.period.IncompatibleFrequency",
"pandas.core.common.values_from_object",
"numpy.where",
"pandas.util._decorators.Substitution",
"pandas._libs.tslibs.period.Period._from_ordinal",
"pandas.core.indexes.base.maybe_extract_name",
"pandas.core.arrays.period.PeriodArray",
"pandas.core.ops.get_op_result_name",
"pandas.core.dtypes.common.is_float_dtype",
"pandas.core.dtypes.common.is_float",
"pandas.core.dtypes.common.is_integer_dtype",
"pandas.util._decorators.Appender",
"pandas._libs.tslibs.period.Period._maybe_convert_freq",
"pandas.core.arrays.period.period_array",
"pandas.core.dtypes.common.pandas_dtype",
"pandas.core.dtypes.common.is_datetime64_any_dtype",
"pandas.core.indexes.base.ensure_index",
"pandas._libs.tslibs.period.Period",
"pandas.core.arrays.period.validate_dtype_freq",
"pandas.core.indexes.numeric.Int64Index._simple_new",
"pandas.core.dtypes.common.ensure_platform_int",
"pandas.core.indexes.datetimelike.DatetimeIndexOpsMixin._convert_tolerance",
"pandas._libs.tslibs.frequencies.get_base_alias",
"numpy.array",
"pandas.core.tools.datetimes.parse_time_string",
"pandas.core.common.count_not_none",
"pandas.core.dtypes.common.is_bool_dtype",
"pandas._libs.tslibs.resolution.Resolution.get_freq_group",
"pandas.core.arrays.period.PeriodArray._generate_range",
"pandas.core.dtypes.common.is_integer",
"pandas.core.indexes.datetimes.Index",
"pandas.core.indexes.datetimes.Index.get_indexer",
"numpy.ndarray.__setstate__",
"numpy.empty"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
michaelpdu/pytorch-CycleGAN-and-pix2pix | [
"7e7aa3fed935644f92c0e15f7de80ce0971bf510"
] | [
"tools/plot_depth_img.py"
] | [
"#!/usr/bin/env python\n#coding:utf8\n\nimport os\nimport argparse\nimport numpy as np\nimport struct\n\nfrom mpl_toolkits.mplot3d import axes3d\nfrom matplotlib import cm\nimport matplotlib.pyplot as plt\nfrom PIL import Image\n\n#from stl import mesh\n#from stl_tools import numpy2stl\n\ndef main(image_path):\n fig = plt.figure()\n img = Image.open(image_path)\n Z = np.asarray(img)\n Z = Z.copy()\n stl_alpha = Z.copy()\n z_min = Z[0][0]\n z_max = Z[0][0]\n\n # 高低翻转,记录最值,设置α通道\n for i in range(len(Z)):\n for j in range(len(Z[i])):\n stl_alpha[i,j] = 255\n\n if Z[i][j]> z_max:\n z_max = Z[i][j]\n if Z[i][j]< z_min:\n z_min = Z[i][j]\n\n # 去掉最值接近的值\n for i in range(len(Z)):\n for j in range(len(Z[i])):\n if Z[i][j]> z_max - 10 or Z[i][j]< z_min + 10:\n Z[i][j] = 0\n else:\n Z[i][j] = Z[i][j] * 640 / z_max\n Z[i,j]=640 - Z[i,j]\n \n Z[0,0]=640\n size = Z.shape\n Y = np.arange(0,size[0],1)\n X = np.arange(0,size[1],1)\n X,Y = np.meshgrid(X,Y)\n\n #stl = mesh.Mesh(np.zeros(Z.shape[0],dtype=mesh.Mesh.dtype),remove_empty_areas=False)\n #stl.x[:] = X[:]\n #stl.y[:] = Y[:]\n #stl.z[:] = Z[:]\n #save('test.stl')\n\n\n #stl_array = 10.0 *Z[:, : ] + 1.0*stl_alpha[:,:] # Compose RGBA channels to give depth\n \n #numpy2stl(stl_array, \"test.stl\", scale=0.1, solid=False)\n #numpy2stl(stl_array, \"test.stl\", scale=0.05, mask_val=5., solid=True)\n\n #ax = fig.gca(projection='3d')\n ax = fig.add_subplot(111,projection='3d')\n\n #ax.plot_surface(X,Y,Z,cmap=cm.jet)\n ax.plot_surface(X, Y, Z, cmap=cm.coolwarm, rcount = 100, ccount = 100, alpha=0.9, linewidth=0)#, antialiased=False)\n\n #ax.plot_wireframe(X, Y, Z, rcount=100, ccount=100, cmap=cm.jet)\n\n # 轮廓\n ax.contour(X,Y,Z, zdir='z',offset = 200,cmap=cm.jet)\n ax.contour(X,Y,Z, zdir='x',offset = 0,cmap=cm.coolwarm)\n ax.contour(X,Y,Z, zdir='y',offset = 0,cmap=cm.coolwarm)\n\n\n ## triangles\n #X2 = []\n #for each in range(640):\n # X2+=[each,]*640\n\n #Y2 = []\n #for each in range(640):\n # Y2 += list(range(640))\n #Z2 = ([0,]*640)*120\n #for each in z:\n # Z2+=each\n #Z2 += ([0,]*640)*120\n ##print len(X2),len(Y2),len(Z2)\n #ax.plot_trisurf(X2, Y2, Z2, cmap=cm.coolwarm) #,linewidth=0, antialiased=False)\n\n plt.show()\n\nif '__main__' == __name__:\n parser = argparse.ArgumentParser(description='Command Usages of plot_depth_image')\n parser.add_argument(\"input\", type=str, help=\"input image file\")\n args = parser.parse_args()\n if args.input:\n main(args.input)\n"
] | [
[
"numpy.asarray",
"numpy.arange",
"numpy.meshgrid",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
marcelrsoub/Force-Measurement-Unit | [
"576dc00e533804469d0469831171e535d1af9cf8"
] | [
"csv-to-graph.py"
] | [
"\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndata = np.loadtxt(open(\"samples/sample-S0229-P2-4-2.csv\", \"rb\"),delimiter=\",\")\n\ntime=data[:,0]\nvalue1=data[:,1]\nvalue2=data[:,2]\n\nplt.plot(time,value1,time,value2)\n# plt.title()\nplt.ylabel(\"Force (g)\")\nplt.xlabel(\"Time (s)\")\nplt.show()\n"
] | [
[
"matplotlib.pyplot.plot",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
gajrajgchouhan/DS3-Assignments | [
"b43937967f80eb3d6d9ebfc6001e0db8da3a2cf8"
] | [
"Lab Assignment 4/KNN.py"
] | [
"import warnings\nimport numpy as np\nimport pandas as pd\nfrom collections import Counter\n\nclass myKNN:\n\n \"\"\"\n My Implementation of KNN classifier.\n \"\"\"\n\n def __init__(self, k):\n\n if (k % 2 == 0):\n w = f\"k = {k} is even, it may not work in the KNN Classifier\"\n warnings.warn(w)\n \n self.k = k\n\n def fit(self, train : \"DataFrame\", label_train : \"Series\"):\n\n if train.empty or label_train.empty:\n\n raise Exception(\"Cannot use empty dataFrames\")\n\n if train.shape[0] != label_train.shape[0]:\n\n raise Exception(f\"Please input correct dataFrames, rows of DF1 = {train.shape[0]}\"\n f\"doesn't match rows of DF2 = {label_train.shape[0]}\")\n\n self.train = train\n self.label_train = label_train\n\n def _predict(self):\n prediction = []\n for index, row in self.test.iterrows():\n \n subtraction = self.train.sub(row.squeeze()) # subtract the row from every row of train data\n # to then find the euclidean distance\n after_sub = np.sqrt(np.square(subtraction).sum(axis=1)) # finding euclidean distance - sqrt(sum of squares of elements in vector)\n after_sub = pd.concat([after_sub, self.label_train], axis=1) # concat with label data\n \n final = after_sub.sort_values([after_sub.columns[0]]) # sort by distance\n final = final.iloc[:self.k, ] # get the first k neighbors\n final = list(final[self.label_train.name])\n final = Counter(final).most_common(1)[0][0] # most common neighbor\n \n prediction.append(final) # appending our final prediction\n \n return prediction\n\n def predict(self, test):\n\n if test.shape[1] != self.train.shape[1]:\n\n raise Exception(\"Input same number of columns of training and testing\"\n f\"Test Columns = {test.shape[1]}, Training Columns = {self.train.shape[1]}\")\n\n self.test = test\n return self._predict()\n"
] | [
[
"numpy.square",
"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": []
}
] |
tflovorn/displ | [
"094c194c54f02d463353075c6ca82f457f1247fa"
] | [
"displ/pwscf/parseScf.py"
] | [
"import numpy as np\n\ndef fermi_from_scf(scf_path):\n fp = open(scf_path, 'r')\n lines = fp.readlines()\n fp.close()\n\n for line in lines:\n if 'Fermi' in line:\n fermi = float(line.strip().split()[-2])\n return fermi\n # If we get here, didn't find 'Fermi' line in scf_path.\n return None\n\ndef alat_from_scf(scf_path):\n lines = None\n with open(scf_path, 'r') as fp:\n lines = fp.readlines()\n\n # Lattice parameter line has format:\n # lattice parameter (alat) = 10.2423 a.u.\n\n for line in lines:\n lsp = line.strip().split('=')\n if lsp[0].strip() == 'lattice parameter (alat)':\n rhs = lsp[-1].strip().split()\n return float(rhs[0])\n\ndef D_from_scf(scf_path):\n '''Returns D in units of alat.\n '''\n fp = open(scf_path, 'r')\n lines = fp.readlines()\n fp.close()\n\n D = np.zeros((3, 3), dtype=np.float64)\n for line_index, line in enumerate(lines):\n if \"crystal axes: (cart. coord. in units of alat)\" in line:\n a1_line = lines[line_index+1]\n a2_line = lines[line_index+2]\n a3_line = lines[line_index+3]\n D[:, 0] = list(map(float, a1_line.strip().split()[3:6]))\n D[:, 1] = list(map(float, a2_line.strip().split()[3:6]))\n D[:, 2] = list(map(float, a3_line.strip().split()[3:6]))\n break\n\n return D\n\ndef latVecs_from_scf(scf_path):\n '''Returns latVecs (= D.T) in distance units which are the same as alat\n (i.e. bohr units, not alat units).\n '''\n alat = alat_from_scf(scf_path)\n D = alat * np.array(D_from_scf(scf_path))\n return D.T\n\ndef num_electrons_from_scf(scf_path):\n fp = open(scf_path, 'r')\n lines = fp.readlines()\n fp.close()\n\n for line in lines:\n if 'number of electrons' in line:\n num_electrons = float(line.strip().split()[-1])\n return num_electrons\n # If we get here, didn't find num_electrons in scf_path.\n # Can't continue without it.\n raise ValueError(\"Did not find num_electrons in scf_path\")\n\ndef magnetization_from_scf(scf_path):\n total_mag, abs_mag, site_mags = None, None, []\n with open(scf_path, 'r') as fp:\n convergence_line = None\n lines = fp.readlines()\n for i, line in enumerate(lines):\n if 'convergence has been achieved' in line:\n convergence_line = i\n break\n total_mag_line = lines[convergence_line - 3].strip().split()\n abs_mag_line = lines[convergence_line - 2].strip().split()\n\n total_mag = float(total_mag_line[3])\n abs_mag = float(abs_mag_line[3])\n\n last_site_moms_line = None\n for i, line in enumerate(lines):\n if 'Magnetic moment per site' in line:\n last_site_moms_line = i\n\n mag_line = last_site_moms_line + 1\n if mag_line != None:\n spl = lines[mag_line].split()\n while len(spl) > 0 and spl[0] == 'atom:':\n mag = float(spl[5])\n site_mags.append(mag)\n mag_line += 1\n spl = lines[mag_line].split()\n\n return total_mag, abs_mag, site_mags\n\ndef total_energy_eV_from_scf(scf_path):\n eV_per_Ry = 13.605693\n\n with open(scf_path, 'r') as fp:\n lines = fp.readlines()\n\n total_energy_eV = None\n for line in lines:\n if line.startswith(\"! total energy\"):\n total_energy_Ry = float(line.strip().split()[-2])\n total_energy_eV = total_energy_Ry * eV_per_Ry\n break\n\n if total_energy_eV is None:\n raise ValueError(\"total energy not found\")\n\n return total_energy_eV\n\ndef initial_coordinates_from_scf(scf_path):\n '''Return the initial atomic coordinates, given in Cartesian coordinates\n in units of alat.\n '''\n with open(scf_path, 'r') as fp:\n lines = fp.readlines()\n\n coordinates_header_line = None\n for i, line in enumerate(lines):\n if line.strip() == \"Cartesian axes\":\n coordinates_header_line = i\n\n if coordinates_header_line is None:\n raise ValueError(\"could not find initial coordinates\")\n\n # Expect the following - check to make sure units are as expected.\n # site n. atom positions (alat units)\n second_header_line = lines[coordinates_header_line + 2].strip()\n if second_header_line.split()[-2] != \"(alat\":\n raise ValueError(\"expected initial coordinates header\")\n\n atom_symbols = []\n atom_alat_Cartesian_positions = []\n coordinate_line = coordinates_header_line + 3\n while len(lines[coordinate_line].strip()) > 0:\n line = list(filter(lambda x: len(x) > 0, lines[coordinate_line].strip().split()))\n atom_symbols.append(line[1])\n atom_alat_Cartesian_positions.append(list(map(lambda x: float(x), line[6:9])))\n\n coordinate_line += 1\n\n return atom_symbols, atom_alat_Cartesian_positions\n\ndef final_coordinates_from_scf(scf_path):\n '''Extract the final atomic coordinates produced by a relaxation run.\n\n Returns a tuple `(positions_type, atom_symbols, atom_positions)`,\n where `positions_type` gives the coordinate type\n '''\n with open(scf_path, 'r') as fp:\n lines = fp.readlines()\n\n final_block_start = None\n final_block_end = None\n for i, line in enumerate(lines):\n if 'Begin final coordinates' in line:\n final_block_start = i\n\n if 'End final coordinates' in line:\n final_block_end = i\n break\n\n if final_block_start is None or final_block_end is None:\n raise ValueError(\"final coordinates block not found\")\n\n # Before atomic positions list, have a line of the form\n # ATOMIC_POSITIONS (crystal)\n atomic_positions_line = lines[final_block_start + 2]\n positions_type = atomic_positions_line.split(\"(\")[1].strip()[:-1]\n\n atoms_start = final_block_start + 3\n atom_symbols, atom_positions = [], []\n for line in lines[atoms_start:final_block_end]:\n atom_line = list(filter(lambda x: len(x) > 0, line.split(' ')))\n atom_symbols.append(atom_line[0])\n atom_positions.append([])\n for coord in atom_line[1:]:\n if len(atom_positions[-1]) >= 3:\n break\n\n atom_positions[-1].append(float(coord))\n\n return positions_type, atom_symbols, atom_positions\n"
] | [
[
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
LuoMaimingS/django_virtual_stock_market | [
"cfeccdbb906f9998ec0a0633c2d2f39cdd87bf85"
] | [
"market/baselines/baselines/common/mpi_moments.py"
] | [
"from mpi4py import MPI\nimport numpy as np\nfrom market.baselines.baselines.common import zipsame\n\n\ndef mpi_mean(x, axis=0, comm=None, keepdims=False):\n x = np.asarray(x)\n assert x.ndim > 0\n if comm is None: comm = MPI.COMM_WORLD\n xsum = x.sum(axis=axis, keepdims=keepdims)\n n = xsum.size\n localsum = np.zeros(n+1, x.dtype)\n localsum[:n] = xsum.ravel()\n localsum[n] = x.shape[axis]\n globalsum = np.zeros_like(localsum)\n comm.Allreduce(localsum, globalsum, op=MPI.SUM)\n return globalsum[:n].reshape(xsum.shape) / globalsum[n], globalsum[n]\n\ndef mpi_moments(x, axis=0, comm=None, keepdims=False):\n x = np.asarray(x)\n assert x.ndim > 0\n mean, count = mpi_mean(x, axis=axis, comm=comm, keepdims=True)\n sqdiffs = np.square(x - mean)\n meansqdiff, count1 = mpi_mean(sqdiffs, axis=axis, comm=comm, keepdims=True)\n assert count1 == count\n std = np.sqrt(meansqdiff)\n if not keepdims:\n newshape = mean.shape[:axis] + mean.shape[axis+1:]\n mean = mean.reshape(newshape)\n std = std.reshape(newshape)\n return mean, std, count\n\n\ndef test_runningmeanstd():\n import subprocess\n subprocess.check_call(['mpirun', '-np', '3',\n 'python','-c',\n 'from baselines.common.mpi_moments import _helper_runningmeanstd; _helper_runningmeanstd()'])\n\ndef _helper_runningmeanstd():\n comm = MPI.COMM_WORLD\n np.random.seed(0)\n for (triple,axis) in [\n ((np.random.randn(3), np.random.randn(4), np.random.randn(5)),0),\n ((np.random.randn(3,2), np.random.randn(4,2), np.random.randn(5,2)),0),\n ((np.random.randn(2,3), np.random.randn(2,4), np.random.randn(2,4)),1),\n ]:\n\n\n x = np.concatenate(triple, axis=axis)\n ms1 = [x.mean(axis=axis), x.std(axis=axis), x.shape[axis]]\n\n\n ms2 = mpi_moments(triple[comm.Get_rank()],axis=axis)\n\n for (a1,a2) in zipsame(ms1, ms2):\n print(a1, a2)\n assert np.allclose(a1, a2)\n print(\"ok!\")\n\n"
] | [
[
"numpy.square",
"numpy.sqrt",
"numpy.random.seed",
"numpy.allclose",
"numpy.asarray",
"numpy.concatenate",
"numpy.zeros_like",
"numpy.random.randn",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Chaibot97/Sudoku_Solver | [
"db2d1cc1d05916c9b1c5eb7a73bdcfc5671c7977"
] | [
"sudoku_solver.py"
] | [
"\"\"\"\nSudoku solver\nauthor: Lizhou Cai\n\nrun:\npython3 sudoku_solver.py IN_FILE LEVEL(0-4)\n\"\"\"\n\nimport numpy as np\nimport argparse\nimport sys\nimport time\n\n\ndef parseArg():\n \"\"\"\n CMD argument parsing\n :return: the parser\n \"\"\"\n parser = argparse.ArgumentParser(description='SAT solver')\n parser.add_argument('infile', nargs=1, type=argparse.FileType('r'))\n parser.add_argument('level', nargs='?', default=0, type=int)\n return parser\n\n\n\"\"\"\nSudoku game\nlevel represents the group of methods that is used\nlevel:\n0: bt, bt+cp1, bt+cp2, bt+cp3, bt+cp3+mrv\n1: bt+cp1\n2: bt+cp2\n3: bt+cp3\n4: bt+cp3+mrv\nwhere:\nbt: backtracking\ncp1: one-candidate\ncp2: cp1+naked-pair+hidden-pair\ncp3: cp1+cp2+x-wing\nmrv: Minimum Remaining Values\n\"\"\"\nclass Sudoku:\n def __init__(self, grid, level):\n self.grid = grid\n self.n = self.grid.shape[0]\n self.steps = 0\n self.candidate = np.zeros((self.n, self.n, self.n), dtype=int)\n self.level = level\n self.time = time.time()\n sys.setrecursionlimit(2500)\n\n def __str__(self):\n res = ''\n for i in range(self.n):\n for j in range(self.n):\n n = self.grid[i][j]\n res += str(n) if n != 0 else '_'\n res += ' '\n res += '\\n'\n return res\n\n def sub_block(self, r, c):\n \"\"\"\n find the block (r,c) resides in\n \"\"\"\n sub_n = self.n ** 0.5\n i, j = r // sub_n, c // sub_n\n rs, re = int(sub_n * i), int(sub_n * (i + 1))\n cs, ce = int(sub_n * j), int(sub_n * (j + 1))\n return rs, re, cs, ce\n\n def check_valid(self):\n \"\"\"\n check if the whole puzzle is finished and valid\n \"\"\"\n if 0 in self.grid:\n return False\n for r in range(self.n):\n for c in range(self.n):\n n = self.grid[r, c]\n self.grid[r, c] = 0\n if not self.move_valid(n, r, c):\n return False\n self.grid[r, c] = n\n return True\n\n def move_valid(self, n, r, c):\n \"\"\"\n check if n is a valid digit to fill in at (r,c)\n \"\"\"\n rs, re, cs, ce = self.sub_block(r, c)\n return n not in self.grid[r, :] and n not in self.grid[:, c] and \\\n n not in self.grid[rs:re, cs:ce]\n\n \"\"\"\n Sudoku solver \n \"\"\"\n def solve(self):\n\n for r in range(self.n):\n for c in range(self.n):\n if self.grid[r][c] != 0:\n continue\n for n in range(1, self.n + 1):\n self.candidate[r][c][n - 1] = 1 if self.move_valid(n, r, c) else 0\n\n if self.back_track():\n t = time.time() - self.time\n assert self.check_valid()\n return str(self), self.steps, t\n else:\n t = time.time() - self.time\n return None, self.steps, t\n\n def back_track(self):\n \"\"\"\n Solver with back_tracking, Constrain propagation and minimum remaining values\n \"\"\"\n if 0 not in self.grid:\n return True\n\n self.steps += 1\n\n ind = np.where(self.grid == 0)\n t = 0\n if self.level >= 4:\n t = np.argmin(np.sum(self.candidate[ind], axis=-1))\n r, c = ind[0][t], ind[1][t]\n moves = np.where(self.candidate[r, c] == 1)[0]\n for n in moves:\n grid_backup = np.where(self.grid == 0)\n cand_backup = np.where(self.candidate == 1)\n self.grid[r, c] = n + 1\n self.eliminate(n, r, c)\n self.constrain_prop()\n res = self.back_track()\n if res:\n return True\n else:\n self.grid[grid_backup] = 0\n self.candidate[cand_backup] = 1\n return False\n\n def eliminate(self, n, r, c):\n \"\"\"\n eliminate candidates after fill in a value\n \"\"\"\n rs, re, cs, ce = self.sub_block(r, c)\n t = self.candidate[r, c, n]\n self.candidate[r, :, n] = 0\n self.candidate[:, c, n] = 0\n self.candidate[rs:re, cs:ce, n] = 0\n self.candidate[r, c, n] = t\n\n def constrain_prop(self):\n \"\"\"\n propagate constrains (eliminate candidates)\n \"\"\"\n if self.level >= 3:\n self.x_wing()\n if self.level >= 2:\n self.naked_pair()\n self.hidden_pairs()\n if self.level >= 1:\n self.single_candidate()\n\n \"\"\"\n cp3 strategies\n \"\"\"\n def x_wing(self):\n rows, cols = np.where(np.sum(self.candidate, axis=2) >= 2)\n pairs = []\n values, counts = np.unique(rows, return_counts=True)\n for r in values[counts > 1]:\n cs = cols[rows == r]\n for i in range(len(cs)):\n for j in range(i + 1, len(cs)):\n s = self.candidate[r, cs[i]] + self.candidate[r, cs[j]]\n if len(s[s == 2]) >= 1:\n for n in np.where(s == 2)[0]:\n if np.sum(self.candidate[r, :, n]) == 2:\n pairs.append(((r, cs[i]), (r, cs[j]), n))\n values, counts = np.unique(cols, return_counts=True)\n for c in values[counts > 1]:\n rs = rows[cols == c]\n for i in range(len(rs)):\n for j in range(i + 1, len(rs)):\n s = self.candidate[rs[i],c] + self.candidate[rs[j],c]\n if len(s[s == 2]) >= 1:\n for n in np.where(s == 2)[0]:\n if np.sum(self.candidate[:, c, n]) == 2:\n pairs.append(((rs[i],c), (rs[j],c), n))\n for i in range(len(pairs)):\n for j in range(i+1,len(pairs)):\n p1, p2 = pairs[i], pairs[j]\n if p1[-1] != p2[-1]:\n continue\n (r11, c11), (r12, c12), n1 = p1\n (r21, c21), (r22, c22), n2 = p2\n if self.candidate[r11, c11][n1] != 1 or self.candidate[r12, c12][n1] != 1 \\\n or self.candidate[r21, c21][n2] != 1 or self.candidate[r22, c22][n2] != 1:\n continue\n # x-wing in rows\n if r11 == r12 and r21 == r22 and c11 == c21 and c12 == c22:\n self.candidate[:, c11, n1] = 0\n self.candidate[:, c12, n1] = 0\n # x-wing in cols\n if c11 == c12 and c21 == c22 and r11 == r21 and r12 == r22:\n self.candidate[r11, :, n1] = 0\n self.candidate[r12, :, n1] = 0\n self.candidate[r11, c11, n1] = 1\n self.candidate[r12, c12, n1] = 1\n self.candidate[r21, c21, n1] = 1\n self.candidate[r22, c22, n1] = 1\n\n \"\"\"\n cp2 strategies\n \"\"\"\n def naked_pair(self):\n rows, cols = np.where(np.sum(self.candidate, axis=2) == 2)\n pairs = []\n values, counts = np.unique(rows, return_counts=True)\n for r in values[counts > 1]:\n cs = cols[rows == r]\n for i in range(len(cs)):\n for j in range(i + 1, len(cs)):\n if np.all(self.candidate[r, cs[i]] == self.candidate[r, cs[j]]):\n pairs.append(((r, cs[i]), (r, cs[j])))\n values, counts = np.unique(cols, return_counts=True)\n for c in values[counts > 1]:\n rs = rows[cols == c]\n for i in range(len(rs)):\n for j in range(i + 1, len(rs)):\n if np.all(self.candidate[rs[i], c] == self.candidate[rs[j], c]):\n pairs.append(((rs[i], c), (rs[j], c)))\n for pair in pairs:\n (r1, c1), (r2, c2) = pair\n if not np.all(self.candidate[r1, c1] == self.candidate[r2, c2]):\n continue\n n = np.where(self.candidate[r1, c1] == 1)[0]\n if r1 == r2:\n self.candidate[r1, :, n] = 0\n else:\n assert c1 == c2\n self.candidate[:, c1, n] = 0\n self.candidate[r1, c1, n] = 1\n self.candidate[r2, c2, n] = 1\n\n def hidden_pairs(self):\n rows, cols = np.where(np.sum(self.candidate, axis=2) >= 2)\n values, counts = np.unique(rows, return_counts=True)\n for r in values[counts > 1]:\n cs = cols[rows == r]\n for i in range(len(cs)):\n for j in range(i + 1, len(cs)):\n s = self.candidate[r, cs[i]] + self.candidate[r, cs[j]]\n if len(s[s == 2]) == 2 and np.sum(self.candidate[r, :, np.where(s == 2)[0]]) == 4:\n self.candidate[r, cs[i]] = np.where(s == 2, 1, 0)\n self.candidate[r, cs[j]] = np.where(s == 2, 1, 0)\n values, counts = np.unique(cols, return_counts=True)\n for c in values[counts > 1]:\n rs = rows[cols == c]\n for i in range(len(rs)):\n for j in range(i + 1, len(rs)):\n s = self.candidate[rs[i], c] + self.candidate[rs[j], c]\n if len(s[s == 2]) == 2 and np.sum(self.candidate[:, c, np.where(s == 2)[0]]) == 4:\n self.candidate[rs[i], c] = np.where(s == 2, 1, 0)\n self.candidate[rs[j], c] = np.where(s == 2, 1, 0)\n\n \"\"\"\n cp1 strategies\n \"\"\"\n def single_candidate(self):\n ind = np.where(np.sum(self.candidate, axis=2) == 1)\n if len(ind[0]) > 0:\n r, c = ind[0][0], ind[1][0]\n n = np.where(self.candidate[r, c] == 1)[0][0]\n self.grid[r, c] = n + 1\n self.candidate[r, c, n] = 0\n self.eliminate(n, r, c)\n self.single_candidate()\n\n\ndef parse_input(f):\n \"\"\"\n Read in the input file and generate a numpy grid\n \"\"\"\n grid = np.zeros((9, 9), dtype=int)\n for i, line in enumerate(f):\n line = list(line.strip())\n for j, n in enumerate(line):\n grid[i][j] = n if n != '_' else 0\n return grid\n\n\ndef run():\n args = parseArg().parse_args()\n grid = parse_input(args.infile[0])\n game = Sudoku(grid, args.level)\n solution, steps, runtime = game.solve()\n print('time(s):', runtime)\n print('Steps:', steps)\n print(solution)\n\n\nif __name__ == '__main__':\n run()\n"
] | [
[
"numpy.unique",
"numpy.all",
"numpy.where",
"numpy.zeros",
"numpy.sum"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
WasatchPhotonics/superman | [
"346fc0d590f40bfe0141630e3146ec8e7ee18be3"
] | [
"superman/baseline/rubberband.py"
] | [
"from __future__ import absolute_import\nimport numpy as np\nfrom scipy.spatial import ConvexHull\nfrom six.moves import xrange\nfrom .common import Baseline\n\n\ndef rubberband_baseline(bands, intensities, num_iters=8, num_ranges=64):\n '''Bruker OPUS method. If num_iters=0, uses basic method from OPUS.'''\n y = intensities.copy()\n for _ in xrange(num_iters):\n yrange = y.max() - y.min()\n x_center = (bands[-1] - bands[0]) / 2.\n tmp = (bands - x_center) ** 2\n y += yrange/10. * tmp / tmp[-1]\n baseline = _rubberband(bands, y, min(num_ranges, len(bands) // 2))\n # undo the n steps of convex function addition\n baseline -= (y - intensities)\n return baseline\n\n\ndef _rubberband(bands, intensities, num_ranges):\n '''Basic rubberband method,\n from p.77 of \"IR and Raman Spectroscopy\" (OPUS manual)'''\n # create n ranges of equal size in the spectrum\n range_size = len(intensities) // num_ranges\n y = intensities[:range_size*num_ranges].reshape((num_ranges, range_size))\n # find the smallest intensity point in each range\n idx = np.arange(num_ranges) * range_size + np.argmin(y, axis=1)\n # add in the start and end points as well, to avoid weird edge effects\n if idx[0] != 0:\n idx = np.append(0, idx)\n if idx[-1] != len(intensities) - 1:\n idx = np.append(idx, len(intensities) - 1)\n baseline_pts = np.column_stack((bands[idx], intensities[idx]))\n # wrap a rubber band around the baseline points\n hull = ConvexHull(baseline_pts)\n hidx = idx[hull.vertices]\n # take only the bottom side of the hull\n left = np.argmin(bands[hidx])\n right = np.argmax(bands[hidx])\n mask = np.ones(len(hidx), dtype=bool)\n for i in xrange(len(hidx)):\n if i > right and (i < left or right > left):\n mask[i] = False\n elif i < left and i < right:\n mask[i] = False\n hidx = hidx[mask]\n hidx = hidx[np.argsort(bands[hidx])]\n # interpolate a baseline\n return np.interp(bands, bands[hidx], intensities[hidx])\n\n\nclass Rubberband(Baseline):\n def __init__(self, num_iters=8, num_ranges=64):\n self.num_iters_ = num_iters\n self.num_ranges_ = num_ranges\n\n def _fit_one(self, bands, intensities):\n return rubberband_baseline(bands, intensities, num_iters=self.num_iters_,\n num_ranges=self.num_ranges_)\n\n def param_ranges(self):\n return {\n 'num_ranges_': (1, 100, 'integer'),\n 'num_iters_': (0, 36, 'integer')\n }\n"
] | [
[
"numpy.arange",
"numpy.append",
"numpy.argmax",
"numpy.argmin",
"numpy.interp",
"scipy.spatial.ConvexHull",
"numpy.argsort",
"numpy.column_stack"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
bit-bcilab/SiamDCA | [
"78a520f2bf6b89f8dee8b05ca7a9399813f77e92"
] | [
"training/DataLoader.py"
] | [
"\r\n\r\nimport numpy as np\r\n\r\nfrom configs.DataPath import TRAIN_PATH, ROOT_PATH, DET_PATH, TRAIN_JSON_PATH\r\nfrom utils.rand import random_sys\r\n\r\nimport cv2\r\nimport json\r\nimport random\r\n\r\n\r\nclass DataLoader(object):\r\n def __init__(self, data_settings, read_all_boxes=False):\r\n self.dataset_trained = []\r\n self.data_num = 0\r\n self.num_train = 0\r\n self.num_val = 0\r\n self.sub_datasets = {}\r\n self.val_index = []\r\n self.read_all_boxes = read_all_boxes\r\n\r\n for sub_dataset in data_settings['dataset_used']:\r\n\r\n self.sub_datasets[sub_dataset] = data_settings[sub_dataset]\r\n\r\n with open(TRAIN_JSON_PATH + self.sub_datasets[sub_dataset]['label_path']) as f:\r\n data = json.load(f)\r\n f.close()\r\n self.sub_datasets[sub_dataset]['data'] = data\r\n\r\n num_data = self.sub_datasets[sub_dataset]['num_data']\r\n assert num_data == len(data)\r\n\r\n multiply = self.sub_datasets[sub_dataset]['multiply']\r\n num_train = self.sub_datasets[sub_dataset]['num_train']\r\n num_val = self.sub_datasets[sub_dataset]['num_val']\r\n num_train_objects = self.sub_datasets[sub_dataset]['num_train_objects']\r\n num_val_objects = self.sub_datasets[sub_dataset]['num_val_objects']\r\n assert num_train_objects <= num_train * multiply\r\n assert num_val_objects <= num_val * multiply\r\n\r\n dataset = [sub_dataset] * num_data\r\n keys = list(data.keys())\r\n index = list(zip(dataset, keys))\r\n random.shuffle(index)\r\n\r\n if num_val > 0:\r\n train_index = index[:-num_val]\r\n val_index = index[-num_val:]\r\n\r\n val_index = val_index * multiply\r\n random.shuffle(val_index)\r\n val_index = val_index[:num_val_objects]\r\n else:\r\n train_index = index\r\n val_index = []\r\n\r\n self.sub_datasets[sub_dataset].update(dict(train_index=train_index, val_index=val_index))\r\n\r\n self.val_index += val_index\r\n self.num_train += num_train_objects\r\n self.num_val += num_val_objects\r\n\r\n print('load ' + sub_dataset + ' done, train: %d, val: %d' % (num_train_objects, num_val_objects))\r\n print('Dataloader done. Total train number: %d, Total val number: %d' % (self.num_train, self.num_val))\r\n random.shuffle(self.val_index)\r\n self.build_train_index()\r\n\r\n def build_train_index(self):\r\n self.train_index = []\r\n for sub_dataset in self.sub_datasets:\r\n sub_index = self.sub_datasets[sub_dataset]['train_index'].copy()\r\n if sub_index:\r\n random.shuffle(sub_index)\r\n\r\n sub_index = sub_index[:self.sub_datasets[sub_dataset]['num_train']]\r\n sub_index *= self.sub_datasets[sub_dataset]['multiply']\r\n random.shuffle(sub_index)\r\n\r\n sub_index = sub_index[:self.sub_datasets[sub_dataset]['num_train_objects']]\r\n\r\n self.dataset_trained.append(sub_dataset)\r\n\r\n self.train_index += sub_index\r\n random.shuffle(self.train_index)\r\n\r\n def get_random_data(self, read_all_boxes=False):\r\n random_dataset = random.choice(self.dataset_trained)\r\n random_index = random.choice(self.sub_datasets[random_dataset]['train_index'])\r\n return self.get_data(random_index, read_pair=False, read_all_boxes=read_all_boxes)\r\n\r\n def read(self, idx, validate, positive):\r\n if validate:\r\n index = self.val_index[idx]\r\n else:\r\n index = self.train_index[idx]\r\n\r\n if positive:\r\n all_boxes, search_img, search_box, template_img, template_box = self.get_data(index, read_pair=True, read_all_boxes=self.read_all_boxes)\r\n else:\r\n all_boxes, search_img, search_box = self.get_data(index, read_pair=False, read_all_boxes=self.read_all_boxes)\r\n _, template_img, template_box = self.get_random_data(read_all_boxes=False)\r\n\r\n return all_boxes, search_img, search_box, template_img, template_box\r\n\r\n def get_data(self, index, read_pair=True, read_all_boxes=False):\r\n dataset = index[0]\r\n index = index[1]\r\n data = self.sub_datasets[dataset]['data'][index]\r\n match_range = self.sub_datasets[dataset]['match_range']\r\n path = TRAIN_PATH[dataset] + '/' + index\r\n all_boxes = []\r\n\r\n if dataset in ['DET', 'DET_val', 'COCO', 'COCO_val']:\r\n if dataset == 'DET' or dataset == 'DET_val':\r\n if index[0] == 'a':\r\n search_path = ROOT_PATH + DET_PATH + index[:index.index('_')] + '/' + index[2:] + '.JPEG'\r\n else:\r\n search_path = path + '.JPEG'\r\n else:\r\n search_path = path + '.jpg'\r\n\r\n samples = list(data.keys())\r\n num_sample = len(data)\r\n if num_sample > 1:\r\n search_index = random.randint(0, num_sample - 1)\r\n else:\r\n search_index = 0\r\n search_box = data[samples[search_index]]['000000']\r\n\r\n if read_pair:\r\n template_path = search_path\r\n\r\n if read_all_boxes:\r\n for i in range(num_sample):\r\n if i != search_index:\r\n all_boxes.append(np.array(data[samples[i]]['000000'], dtype=np.float32))\r\n\r\n elif dataset in ['VID', 'VID_val']:\r\n num_sample = len(data)\r\n samples = list(data.keys())\r\n if num_sample == 1:\r\n sample_index = 0\r\n else:\r\n sample_index = random.randint(0, num_sample - 1)\r\n\r\n sample_data = data[samples[sample_index]]\r\n frames = list(sample_data.keys())\r\n num_frame = len(frames)\r\n search_index = random.randint(0, num_frame - 1)\r\n search_frame = frames[search_index]\r\n search_path = path + '/' + search_frame + '.JPEG'\r\n search_box = sample_data[search_frame]\r\n\r\n if read_pair:\r\n if match_range == 'all':\r\n template_index = random.randint(0, num_frame - 1)\r\n elif match_range == 'init':\r\n template_index = 0\r\n elif match_range == 'mix':\r\n if random_sys() > 0.5:\r\n template_index = 0\r\n else:\r\n template_index = random.randint(0, num_frame - 1)\r\n else:\r\n template_index = random.randint(max(search_index - match_range, 0),\r\n min(search_index + match_range, num_frame) - 1)\r\n\r\n template_path = path + '/' + frames[template_index] + '.JPEG'\r\n template_box = sample_data[frames[template_index]]\r\n\r\n if read_all_boxes:\r\n if num_sample > 1:\r\n for i in range(num_sample):\r\n if i != sample_index:\r\n sample_frames = list(data[samples[i]].keys())\r\n if search_frame in sample_frames:\r\n all_boxes.append(np.array(data[samples[i]][search_frame], dtype=np.float32))\r\n\r\n elif dataset in ['GOT', 'GOT_val', 'LaSOT']:\r\n if dataset == 'LaSOT':\r\n path = path + '/img/'\r\n\r\n frames = list(data.keys())\r\n num_frame = len(frames)\r\n search_index = random.randint(0, num_frame - 1)\r\n search_frame = frames[search_index]\r\n search_path = path + '/' + search_frame + '.jpg'\r\n search_box = data[search_frame]\r\n\r\n if read_pair:\r\n if match_range == 'all':\r\n template_index = random.randint(0, num_frame - 1)\r\n elif match_range == 'init':\r\n template_index = 0\r\n elif match_range == 'mix':\r\n if random_sys() > 0.5:\r\n template_index = 0\r\n else:\r\n template_index = random.randint(0, num_frame - 1)\r\n else:\r\n template_index = random.randint(max(search_index - match_range, 0),\r\n min(search_index + match_range, num_frame) - 1)\r\n\r\n template_path = path + '/' + frames[template_index] + '.jpg'\r\n template_box = data[frames[template_index]]\r\n\r\n search_img = cv2.imread(search_path)\r\n search_box = np.array(search_box, dtype=np.float32)\r\n\r\n if read_pair:\r\n if template_path == search_path:\r\n template_img = search_img\r\n template_box = search_box\r\n else:\r\n template_img = cv2.imread(template_path)\r\n template_box = np.array(template_box, dtype=np.float32)\r\n return all_boxes, search_img, search_box, template_img, template_box\r\n\r\n else:\r\n return all_boxes, search_img, search_box\r\n"
] | [
[
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
windcrusader/tides | [
"2898cf8f22528c91c18810187323213892bfe9d9"
] | [
"tidepredict/tide.py"
] | [
"from collections import OrderedDict\n#below for compatibility with Python < 3.8\ntry:\n from collections.abc import Iterable # noqa\nexcept ImportError:\n from collections import Iterable # noqa\nfrom itertools import takewhile, count\ntry:\n\tfrom itertools import izip, ifilter\nexcept ImportError: #Python3\n\tizip = zip\n\tifilter = filter\nfrom datetime import datetime, timedelta\nimport numpy as np\nfrom scipy.optimize import leastsq, fsolve\nfrom tidepredict.astro import astro\nimport tidepredict.constituent as constituent\n\nd2r, r2d = np.pi/180.0, 180.0/np.pi\n\nclass Tide(object):\n\tdtype = np.dtype([\n\t\t('constituent', object),\n\t\t('amplitude', float),\n\t\t('phase', float)])\n\n\tdef __init__(\n\t\t\tself,\n\t\t\tconstituents = None,\n\t\t\tamplitudes = None,\n\t\t\tphases = None,\n\t\t\tmodel = None,\n\t\t\tradians = False\n\t\t):\n\t\t\"\"\"\n\t\tInitialise a tidal model. Provide constituents, amplitudes and phases OR a model.\n\t\tArguments:\n\t\tconstituents -- list of constituents used in the model.\n\t\tamplitudes -- list of amplitudes corresponding to constituents\n\t\tphases -- list of phases corresponding to constituents\n\t\tmodel -- an ndarray of type Tide.dtype representing the constituents, amplitudes and phases.\n\t\tradians -- boolean representing whether phases are in radians (default False)\n\t\t\"\"\"\n\t\tif None not in [constituents, amplitudes, phases]:\n\t\t\tif len(constituents) == len(amplitudes) == len(phases):\n\t\t\t\tmodel = np.zeros(len(phases), dtype=Tide.dtype)\n\t\t\t\tmodel['constituent'] = np.array(constituents)\n\t\t\t\tmodel['amplitude'] = np.array(amplitudes)\n\t\t\t\tmodel['phase'] = np.array(phases)\n\t\t\telse:\n\t\t\t\traise ValueError(\"Constituents, amplitudes and phases should all be arrays of equal length.\")\n\t\telif model is not None:\n\t\t\tif not model.dtype == Tide.dtype:\n\t\t\t\traise ValueError(\"Model must be a numpy array with dtype == Tide.dtype\")\n\t\telse:\n\t\t\traise ValueError(\"Must be initialised with constituents, amplitudes and phases; or a model.\")\n\t\tif radians:\n\t\t\tmodel['phase'] = r2d*model['phase']\n\t\tself.model = model[:]\n\t\tself.normalize()\n\n\tdef prepare(self, *args, **kwargs):\n\t\treturn Tide._prepare(self.model['constituent'], *args, **kwargs)\n\n\t@staticmethod\n\tdef _prepare(constituents, t0, t = None, radians = True):\n\t\t\"\"\"\n\t\tReturn constituent speed and equilibrium argument at a given time, and constituent node factors at given times.\n\t\tArguments:\n\t\tconstituents -- list of constituents to prepare\n\t\tt0 -- time at which to evaluate speed and equilibrium argument for each constituent\n\t\tt -- list of times at which to evaluate node factors for each constituent (default: t0)\n\t\tradians -- whether to return the angular arguments in radians or degrees (default: True)\n\t\t\"\"\"\n\t\t#The equilibrium argument is constant and taken at the beginning of the\n\t\t#time series (t0). The speed of the equilibrium argument changes very\n\t\t#slowly, so again we take it to be constant over any length of data. The\n\t\t#node factors change more rapidly.\n\t\tif isinstance(t0, Iterable):\n\t\t\tt0 = t0[0]\n\t\tif t is None:\n\t\t\tt = [t0]\n\t\tif not isinstance(t, Iterable):\n\t\t\tt = [t]\n\t\ta0 = astro(t0)\n\t\ta = [astro(t_i) for t_i in t]\n\n\t\t#For convenience give u, V0 (but not speed!) in [0, 360)\n\t\tV0 = np.array([c.V(a0) for c in constituents])[:, np.newaxis]\n\t\tspeed = np.array([c.speed(a0) for c in constituents])[:, np.newaxis]\n\t\tu = [np.mod(np.array([c.u(a_i) for c in constituents])[:, np.newaxis], 360.0)\n\t\t\t for a_i in a]\n\t\tf = [np.mod(np.array([c.f(a_i) for c in constituents])[:, np.newaxis], 360.0)\n\t\t\t for a_i in a]\n\n\t\tif radians:\n\t\t\tspeed = d2r*speed\n\t\t\tV0 = d2r*V0\n\t\t\tu = [d2r*each for each in u]\n\t\treturn speed, u, f, V0\n\n\tdef at(self, t):\n\t\t\"\"\"\n\t\tReturn the modelled tidal height at given times.\n\t\tArguments:\n\t\tt -- array of times at which to evaluate the tidal height\n\t\t\"\"\"\n\t\tt0 = t[0]\n\t\thours = self._hours(t0, t)\n\t\tpartition = 240.0\n\t\tt = self._partition(hours, partition)\n\t\ttimes = self._times(t0, [(i + 0.5)*partition for i in range(len(t))])\n\t\tspeed, u, f, V0 = self.prepare(t0, times, radians = True)\n\t\tH = self.model['amplitude'][:, np.newaxis]\n\t\tp = d2r*self.model['phase'][:, np.newaxis]\n\n\t\treturn np.concatenate([\n\t\t\tTide._tidal_series(t_i, H, p, speed, u_i, f_i, V0)\n\t\t\tfor t_i, u_i, f_i in izip(t, u, f)\n\t\t])\n\n\tdef highs(self, *args):\n\t\t\"\"\"\n\t\tGenerator yielding only the high tides.\n\t\tArguments:\n\t\tsee Tide.extrema()\n\t\t\"\"\"\n\t\tfor t in ifilter(lambda e: e[2] == 'H', self.extrema(*args)):\n\t\t\tyield t\n\n\tdef lows(self, *args):\n\t\t\"\"\"\n\t\tGenerator yielding only the low tides.\n\t\tArguments:\n\t\tsee Tide.extrema()\n\t\t\"\"\"\n\t\tfor t in ifilter(lambda e: e[2] == 'L', self.extrema(*args)):\n\t\t\tyield t\n\n\tdef form_number(self):\n\t\t\"\"\"\n\t\tReturns the model's form number, a helpful heuristic for classifying tides.\n\t\t\"\"\"\n\t\tk1, o1, m2, s2 = (\n\t\t\tnp.extract(self.model['constituent'] == c, self.model['amplitude'])\n\t\t\tfor c in [constituent._K1, constituent._O1, constituent._M2, constituent._S2]\n\t\t)\n\t\treturn (k1+o1)/(m2+s2)\n\n\tdef classify(self):\n\t\t\"\"\"\n\t\tClassify the tide according to its form number\n\t\t\"\"\"\n\t\tform = self.form_number()\n\t\tif 0 <= form <= 0.25:\n\t\t\treturn 'semidiurnal'\n\t\telif 0.25 < form <= 1.5:\n\t\t\treturn 'mixed (semidiurnal)'\n\t\telif 1.5 < form <= 3.0:\n\t\t\treturn 'mixed (diurnal)'\n\t\telse:\n\t\t\treturn 'diurnal'\n\n\tdef extrema(self, t0, t1 = None, partition = 2400.0):\n\t\t\"\"\"\n\t\tA generator for high and low tides.\n\t\tArguments:\n\t\tt0 -- time after which extrema are sought\n\t\tt1 -- optional time before which extrema are sought (if not given, the generator is infinite)\n\t\tpartition -- number of hours for which we consider the node factors to be constant (default: 2400.0)\n\t\t\"\"\"\n\t\tif t1:\n\t\t\t#yield from in python 3.4\n\t\t\tfor e in takewhile(lambda t: t[0] < t1, self.extrema(t0)):\n\t\t\t\tyield e\n\t\telse:\n\t\t\t#We assume that extrema are separated by at least delta hours\n\t\t\tdelta = np.amin([\n\t\t\t\t90.0 / c.speed(astro(t0)) for c in self.model['constituent']\n\t\t\t\tif not c.speed(astro(t0)) == 0\n\t\t\t])\n\t\t\t#We search for stationary points from offset hours before t0 to\n\t\t\t#ensure we find any which might occur very soon after t0.\n\t\t\toffset = 24.0\n\t\t\tpartitions = (\n\t\t\t\tTide._times(t0, i*partition) for i in count()), (Tide._times(t0, i*partition) for i in count(1)\n\t\t\t)\n\n\t\t\t#We'll overestimate to be on the safe side;\n\t\t\t#values outside (start,end) won't get yielded.\n\t\t\tinterval_count = int(np.ceil((partition + offset) / delta)) + 1\n\t\t\tamplitude = self.model['amplitude'][:, np.newaxis]\n\t\t\tphase = d2r*self.model['phase'][:, np.newaxis]\n\n\t\t\tfor start, end in izip(*partitions):\n\t\t\t\tspeed, [u], [f], V0 = self.prepare(start, Tide._times(start, 0.5*partition))\n\t\t\t\t#These derivatives don't include the time dependence of u or f,\n\t\t\t\t#but these change slowly.\n\t\t\t\tdef d(t):\n\t\t\t\t\treturn np.sum(-speed*amplitude*f*np.sin(speed*t + (V0 + u) - phase), axis=0)\n\t\t\t\tdef d2(t):\n\t\t\t\t\treturn np.sum(-speed**2.0 * amplitude*f*np.cos(speed*t + (V0 + u) - phase), axis=0)\n\t\t\t\t#We'll overestimate to be on the safe side;\n\t\t\t\t#values outside (start,end) won't get yielded.\n\t\t\t\tintervals = (\n\t\t\t\t\tdelta * i -offset for i in range(interval_count)), (delta*(i+1) - offset for i in range(interval_count)\n\t\t\t\t)\n\t\t\t\tfor a, b in izip(*intervals):\n\t\t\t\t\tif d(a)*d(b) < 0:\n\t\t\t\t\t\textrema = fsolve(d, (a + b) / 2.0, fprime = d2)[0]\n\t\t\t\t\t\ttime = Tide._times(start, extrema)\n\t\t\t\t\t\t[height] = self.at([time])\n\t\t\t\t\t\thilo = 'H' if d2(extrema) < 0 else 'L'\n\t\t\t\t\t\tif start < time < end:\n\t\t\t\t\t\t\tyield (time, height, hilo)\n\n\t@staticmethod\n\tdef _hours(t0, t):\n\t\t\"\"\"\n\t\tReturn the hourly offset(s) of a (list of) time from a given time.\n\t\tArguments:\n\t\tt0 -- time from which offsets are sought\n\t\tt -- times to find hourly offsets from t0.\n\t\t\"\"\"\n\t\tif not isinstance(t, Iterable):\n\t\t\treturn Tide._hours(t0, [t])[0]\n\t\telif isinstance(t[0], datetime):\n\t\t\treturn np.array([(ti-t0).total_seconds() / 3600.0 for ti in t])\n\t\telse:\n\t\t\treturn t\n\n\t@staticmethod\n\tdef _partition(hours, partition = 3600.0):\n\t\t\"\"\"\n\t\tPartition a sorted list of numbers (or in this case hours).\n\t\tArguments:\n\t\thours -- sorted ndarray of hours.\n\t\tpartition -- maximum partition length (default: 3600.0)\n\t\t\"\"\"\n\t\tpartition = float(partition)\n\t\trelative = hours - hours[0]\n\t\ttotal_partitions = np.ceil(relative[-1] / partition + 10*np.finfo(np.float).eps).astype('int')\n\t\treturn [hours[np.floor(np.divide(relative, partition)) == i] for i in range(total_partitions)]\n\n\t@staticmethod\n\tdef _times(t0, hours):\n\t\t\"\"\"\n\t\tReturn a (list of) datetime(s) given an initial time and an (list of) hourly offset(s).\n\t\tArguments:\n\t\tt0 -- initial time\n\t\thours -- hourly offsets from t0\n\t\t\"\"\"\n\t\tif not isinstance(hours, Iterable):\n\t\t\treturn Tide._times(t0, [hours])[0]\n\t\telif not isinstance(hours[0], datetime):\n\t\t\treturn np.array([t0 + timedelta(hours=h) for h in hours])\n\t\telse:\n\t\t\treturn np.array(hours)\n\n\t@staticmethod\n\tdef _tidal_series(t, amplitude, phase, speed, u, f, V0):\n\t\treturn np.sum(amplitude*f*np.cos(speed*t + (V0 + u) - phase), axis=0)\n\n\tdef normalize(self):\n\t\t\"\"\"\n\t\tAdapt self.model so that amplitudes are positive and phases are in [0,360) as per convention\n\t\t\"\"\"\n\t\tfor i, (_, amplitude, phase) in enumerate(self.model):\n\t\t\tif amplitude < 0:\n\t\t\t\tself.model['amplitude'][i] = -amplitude\n\t\t\t\tself.model['phase'][i] = phase + 180.0\n\t\t\tself.model['phase'][i] = np.mod(self.model['phase'][i], 360.0)\n\n\t@classmethod\n\tdef decompose(\n\t\t\tcls,\n\t\t\theights,\n\t\t\tt = None,\n\t\t\tt0 = None,\n\t\t\tinterval = None,\n\t\t\tconstituents = constituent.noaa,\n\t\t\tinitial = None,\n\t\t\tn_period = 2,\n\t\t\tcallback = None,\n\t\t\tfull_output = False\n\t\t):\n\t\t\"\"\"\n\t\tReturn an instance of Tide which has been fitted to a series of tidal observations.\n\t\tArguments:\n\t\tIt is not necessary to provide t0 or interval if t is provided.\n\t\theights -- ndarray of tidal observation heights\n\t\tt -- ndarray of tidal observation times\n\t\tt0 -- datetime representing the time at which heights[0] was recorded\n\t\tinterval -- hourly interval between readings\n\t\tconstituents -- list of constituents to use in the fit (default: constituent.noaa)\n\t\tinitial -- optional Tide instance to use as first guess for least squares solver\n\t\tn_period -- only include constituents which complete at least this many periods (default: 2)\n\t\tcallback -- optional function to be called at each iteration of the solver\n\t\tfull_output -- whether to return the output of scipy's leastsq solver (default: False)\n\t\t\"\"\"\n\t\tif t is not None:\n\t\t\tif isinstance(t[0], datetime):\n\t\t\t\thours = Tide._hours(t[0], t)\n\t\t\t\tt0 = t[0]\n\t\t\telif t0 is not None:\n\t\t\t\thours = t\n\t\t\telse:\n\t\t\t\traise ValueError(\"t can be an array of datetimes, or an array \"\n\t\t\t\t \"of hours since t0 in which case t0 must be \"\n\t\t\t\t \"specified.\")\n\t\telif None not in [t0, interval]:\n\t\t\thours = np.arange(len(heights)) * interval\n\t\telse:\n\t\t\traise ValueError(\"Must provide t(datetimes), or t(hours) and \"\n\t\t\t \"t0(datetime), or interval(hours) and t0(datetime) \"\n\t\t\t \"so that each height can be identified with an \"\n\t\t\t \"instant in time.\")\n\n\t\t#Remove duplicate constituents (those which travel at exactly the same\n\t\t#speed, irrespective of phase)\n\t\tconstituents = list(OrderedDict.fromkeys(constituents))\n\n\t\t#No need for least squares to find the mean water level constituent z0,\n\t\t#work relative to mean\n\t\tconstituents = [c for c in constituents if not c == constituent._Z0]\n\t\tz0 = np.mean(heights)\n\t\theights = heights - z0\n\n\t\t#Only analyse frequencies which complete at least n_period cycles over\n\t\t#the data period.\n\t\tconstituents = [\n\t\t\tc for c in constituents\n\t\t\tif 360.0 * n_period < hours[-1] * c.speed(astro(t0))\n\t\t]\n\t\tn = len(constituents)\n\n\t\tsort = np.argsort(hours)\n\t\thours = hours[sort]\n\t\theights = heights[sort]\n\n\t\t#We partition our time/height data into intervals over which we consider\n\t\t#the values of u and f to assume a constant value (that is, their true\n\t\t#value at the midpoint of the interval). Constituent\n\t\t#speeds change much more slowly than the node factors, so we will\n\t\t#consider these constant and equal to their speed at t0, regardless of\n\t\t#the length of the time series.\n\n\t\tpartition = 240.0\n\n\t\tt = Tide._partition(hours, partition)\n\t\ttimes = Tide._times(t0, [(i + 0.5)*partition for i in range(len(t))])\n\n\t\tspeed, u, f, V0 = Tide._prepare(constituents, t0, times, radians = True)\n\n\t\t#Residual to be minimised by variation of parameters (amplitudes, phases)\n\t\tdef residual(hp):\n\t\t\tH, p = hp[:n, np.newaxis], hp[n:, np.newaxis]\n\t\t\ts = np.concatenate([\n\t\t\t\tTide._tidal_series(t_i, H, p, speed, u_i, f_i, V0)\n\t\t\t\tfor t_i, u_i, f_i in izip(t, u, f)\n\t\t\t])\n\t\t\tres = heights - s\n\t\t\tif callback:\n\t\t\t\tcallback(res)\n\t\t\treturn res\n\n\t\t#Analytic Jacobian of the residual - this makes solving significantly\n\t\t#faster than just using gradient approximation, especially with many\n\t\t#measurements / constituents.\n\t\tdef D_residual(hp):\n\t\t\tH, p = hp[:n, np.newaxis], hp[n:, np.newaxis]\n\t\t\tds_dH = np.concatenate([\n\t\t\t\tf_i*np.cos(speed*t_i+u_i+V0-p)\n\t\t\t\tfor t_i, u_i, f_i in izip(t, u, f)],\n\t\t\t\taxis = 1)\n\n\t\t\tds_dp = np.concatenate([\n\t\t\t\tH*f_i*np.sin(speed*t_i+u_i+V0-p)\n\t\t\t\tfor t_i, u_i, f_i in izip(t, u, f)],\n\t\t\t\taxis = 1)\n\n\t\t\treturn np.append(-ds_dH, -ds_dp, axis=0)\n\n\t\t#Initial guess for solver, haven't done any analysis on this since the\n\t\t#solver seems to converge well regardless of the initial guess We do\n\t\t#however scale the initial amplitude guess with some measure of the\n\t\t#variation\n\t\tamplitudes = np.ones(n) * (np.sqrt(np.dot(heights, heights)) / len(heights))\n\t\tphases = np.ones(n)\n\n\t\tif initial:\n\t\t\tfor (c0, amplitude, phase) in initial.model:\n\t\t\t\tfor i, c in enumerate(constituents):\n\t\t\t\t\tif c0 == c:\n\t\t\t\t\t\tamplitudes[i] = amplitude\n\t\t\t\t\t\tphases[i] = d2r*phase\n\n\t\tinitial = np.append(amplitudes, phases)\n\n\t\tlsq = leastsq(residual, initial, Dfun=D_residual, col_deriv=True, ftol=1e-7)\n\n\t\tmodel = np.zeros(1+n, dtype=cls.dtype)\n\t\tmodel[0] = (constituent._Z0, z0, 0)\n\t\tmodel[1:]['constituent'] = constituents[:]\n\t\tmodel[1:]['amplitude'] = lsq[0][:n]\n\t\tmodel[1:]['phase'] = lsq[0][n:]\n\n\t\tif full_output:\n\t\t\treturn cls(model = model, radians = True), lsq\n\t\treturn cls(model = model, radians = True)\n"
] | [
[
"numpy.dot",
"scipy.optimize.fsolve",
"numpy.cos",
"numpy.dtype",
"numpy.ones",
"numpy.sin",
"numpy.ceil",
"numpy.append",
"scipy.optimize.leastsq",
"numpy.mean",
"numpy.finfo",
"numpy.mod",
"numpy.argsort",
"numpy.array",
"numpy.extract",
"numpy.zeros",
"numpy.divide"
]
] | [
{
"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": []
}
] |
BehnazDibayee/syncnet_trainer | [
"77f5f345c48bf9496db07bd24f0ef43a1a4665e9"
] | [
"models/SyncNetModelMFCC.py"
] | [
"#! /usr/bin/python\n# -*- encoding: utf-8 -*-\n\nimport torch\nimport torch.nn as nn\nimport pytorch_mfcc\n \nclass SyncNetModel(nn.Module):\n def __init__(self, nOut = 1024, stride=1):\n super(SyncNetModel, self).__init__();\n\n self.netcnnaud = nn.Sequential(\n nn.Conv2d(1, 64, kernel_size=(3,3), stride=(1,1), padding=(1,1)),\n nn.BatchNorm2d(64),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=(1,1), stride=(1,1)),\n\n nn.Conv2d(64, 192, kernel_size=(3,3), stride=(1,1), padding=(1,1)),\n nn.BatchNorm2d(192),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=(3,3), stride=(1,2)),\n\n nn.Conv2d(192, 384, kernel_size=(3,3), padding=(1,1)),\n nn.BatchNorm2d(384),\n nn.ReLU(inplace=True),\n\n nn.Conv2d(384, 256, kernel_size=(3,3), padding=(1,1)),\n nn.BatchNorm2d(256),\n nn.ReLU(inplace=True),\n\n nn.Conv2d(256, 256, kernel_size=(3,3), padding=(1,1)),\n nn.BatchNorm2d(256),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=(3,3), stride=(2,2)),\n \n nn.Conv2d(256, 512, kernel_size=(5,4), padding=(0,0), stride=(1,stride)),\n nn.BatchNorm2d(512),\n nn.ReLU(),\n );\n\n self.netfcaud = nn.Sequential(\n nn.Conv1d(512, 512, kernel_size=1),\n nn.BatchNorm1d(512),\n nn.ReLU(),\n nn.Conv1d(512, nOut, kernel_size=1),\n );\n\n self.netfclip = nn.Sequential(\n nn.Conv1d(512, 512, kernel_size=1),\n nn.BatchNorm1d(512),\n nn.ReLU(),\n nn.Conv1d(512, nOut, kernel_size=1),\n );\n\n self.netfcspk = nn.Sequential(\n nn.Conv1d(512, 512, kernel_size=1),\n nn.BatchNorm1d(512),\n nn.ReLU(),\n nn.Conv1d(512, nOut, kernel_size=1),\n );\n\n self.netfcface = nn.Sequential(\n nn.Conv1d(512, 512, kernel_size=1),\n nn.BatchNorm1d(512),\n nn.ReLU(),\n nn.Conv1d(512, nOut, kernel_size=1),\n );\n\n self.netcnnlip = nn.Sequential(\n nn.Conv3d(3, 96, kernel_size=(5,7,7), stride=(stride,2,2), padding=0),\n nn.BatchNorm3d(96),\n nn.ReLU(inplace=True),\n nn.MaxPool3d(kernel_size=(1,3,3), stride=(1,2,2)),\n\n nn.Conv3d(96, 256, kernel_size=(1,5,5), stride=(1,2,2), padding=(0,1,1)),\n nn.BatchNorm3d(256),\n nn.ReLU(inplace=True),\n nn.MaxPool3d(kernel_size=(1,3,3), stride=(1,2,2), padding=(0,1,1)),\n\n nn.Conv3d(256, 256, kernel_size=(1,3,3), padding=(0,1,1)),\n nn.BatchNorm3d(256),\n nn.ReLU(inplace=True),\n\n nn.Conv3d(256, 256, kernel_size=(1,3,3), padding=(0,1,1)),\n nn.BatchNorm3d(256),\n nn.ReLU(inplace=True),\n\n nn.Conv3d(256, 256, kernel_size=(1,3,3), padding=(0,1,1)),\n nn.BatchNorm3d(256),\n nn.ReLU(inplace=True),\n nn.MaxPool3d(kernel_size=(1,3,3), stride=(1,2,2)),\n\n nn.Conv3d(256, 512, kernel_size=(1,6,6), padding=0),\n nn.BatchNorm3d(512),\n nn.ReLU(inplace=True),\n );\n\n self.mfcc_layer = pytorch_mfcc.MFCC(samplerate=16000)\n\n def forward_aud(self, x):\n\n x1,mfcc_lengths = self.mfcc_layer(x,[x.size()[1]]*x.size()[0]) # Do mfcc\n x1 = x1.unsqueeze(1).transpose(2,3).detach()\n \n mid = self.netcnnaud(x1); # N x ch x 24 x M\n mid = mid.view((mid.size()[0], mid.size()[1], -1)); # N x (ch x 24)\n\n out1 = self.netfcaud(mid);\n out2 = self.netfcspk(mid);\n\n return out1, out2;\n\n def forward_vid(self, x):\n\n mid = self.netcnnlip(x); \n mid = mid.view((mid.size()[0], mid.size()[1], -1)); # N x (ch x 24)\n\n out1 = self.netfclip(mid);\n out2 = self.netfcface(mid);\n\n return out1, out2;"
] | [
[
"torch.nn.BatchNorm1d",
"torch.nn.Conv2d",
"torch.nn.MaxPool2d",
"torch.nn.Conv3d",
"torch.nn.MaxPool3d",
"torch.nn.BatchNorm2d",
"torch.nn.Conv1d",
"torch.nn.ReLU",
"torch.nn.BatchNorm3d"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
DEVESHTARASIA/mnist-1 | [
"7e4d8e78a5c61bbbfb7f135f12d020e0597be3eb"
] | [
"mnist/__init__.py"
] | [
"import os\nimport functools\nimport operator\nimport gzip\nimport struct\nimport array\nimport tempfile\ntry:\n from urllib.request import urlretrieve\nexcept ImportError:\n from urllib import urlretrieve # py2\ntry:\n from urllib.parse import urljoin\nexcept ImportError:\n from urlparse import urljoin\nimport numpy as np\n\n\n# the url can be changed by the users of the library (not a constant)\ndatasets_url = 'http://yann.lecun.com/exdb/mnist/'\n\n\nclass IdxDecodeError(ValueError):\n \"\"\"Raised when an invalid idx file is parsed.\"\"\"\n pass\n\n\ndef download_file(fname, target_dir=None, force=False):\n \"\"\"Download fname from the datasets_url, and save it to target_dir,\n unless the file already exists, and force is False.\n\n Parameters\n ----------\n fname : str\n Name of the file to download\n\n target_dir : str\n Directory where to store the file\n\n force : bool\n Force downloading the file, if it already exists\n\n Returns\n -------\n fname : str\n Full path of the downloaded file\n \"\"\"\n if not target_dir:\n target_dir = tempfile.gettempdir()\n target_fname = os.path.join(target_dir, fname)\n\n if force or not os.path.isfile(target_fname):\n url = urljoin(datasets_url, fname)\n urlretrieve(url, target_fname)\n\n return target_fname\n\n\ndef parse_idx(fd):\n \"\"\"Parse an IDX file, and return it as a numpy array.\n\n Parameters\n ----------\n fd : file\n File descriptor of the IDX file to parse\n\n endian : str\n Byte order of the IDX file. See [1] for available options\n\n Returns\n -------\n data : numpy.ndarray\n Numpy array with the dimensions and the data in the IDX file\n\n 1. https://docs.python.org/3/library/struct.html#byte-order-size-and-alignment\n \"\"\"\n DATA_TYPES = {0x08: 'B', # unsigned byte\n 0x09: 'b', # signed byte\n 0x0b: 'h', # short (2 bytes)\n 0x0c: 'i', # int (4 bytes)\n 0x0d: 'f', # float (4 bytes)\n 0x0e: 'd'} # double (8 bytes)\n\n header = fd.read(4)\n if len(header) != 4:\n raise IdxDecodeError('Invalid IDX file, file empty or does not contain a full header.')\n\n zeros, data_type, num_dimensions = struct.unpack('>HBB', header)\n\n if zeros != 0:\n raise IdxDecodeError('Invalid IDX file, file must start with two zero bytes. '\n 'Found 0x%02x' % zeros)\n\n try:\n data_type = DATA_TYPES[data_type]\n except KeyError:\n raise IdxDecodeError('Unknown data type 0x%02x in IDX file' % data_type)\n\n dimension_sizes = struct.unpack('>' + 'I' * num_dimensions,\n fd.read(4 * num_dimensions))\n\n data = array.array(data_type, fd.read())\n data.byteswap() # looks like array.array reads data as little endian\n\n expected_items = functools.reduce(operator.mul, dimension_sizes)\n if len(data) != expected_items:\n raise IdxDecodeError('IDX file has wrong number of items. '\n 'Expected: %d. Found: %d' % (expected_items, len(data)))\n\n return np.array(data).reshape(dimension_sizes)\n\n\ndef download_and_parse_mnist_file(fname, target_dir=None, force=False):\n \"\"\"Download the IDX file named fname from the URL specified in dataset_url\n and return it as a numpy array.\n\n Parameters\n ----------\n fname : str\n File name to download and parse\n\n target_dir : str\n Directory where to store the file\n\n force : bool\n Force downloading the file, if it already exists\n\n Returns\n -------\n data : numpy.ndarray\n Numpy array with the dimensions and the data in the IDX file\n \"\"\"\n fname = download_file(fname, target_dir=target_dir, force=force)\n fopen = gzip.open if os.path.splitext(fname)[1] == '.gz' else open\n with fopen(fname, 'rb') as fd:\n return parse_idx(fd)\n\n\ndef train_images():\n \"\"\"Return train images from Yann LeCun MNIST database as a numpy array.\n Download the file, if not already found in the temporary directory of\n the system.\n\n Returns\n -------\n train_images : numpy.ndarray\n Numpy array with the images in the train MNIST database. The first\n dimension indexes each sample, while the other two index rows and\n columns of the image\n \"\"\"\n return download_and_parse_mnist_file('train-images-idx3-ubyte.gz')\n\n\ndef test_images():\n \"\"\"Return test images from Yann LeCun MNIST database as a numpy array.\n Download the file, if not already found in the temporary directory of\n the system.\n\n Returns\n -------\n test_images : numpy.ndarray\n Numpy array with the images in the train MNIST database. The first\n dimension indexes each sample, while the other two index rows and\n columns of the image\n \"\"\"\n return download_and_parse_mnist_file('t10k-images-idx3-ubyte.gz')\n\n\ndef train_labels():\n \"\"\"Return train labels from Yann LeCun MNIST database as a numpy array.\n Download the file, if not already found in the temporary directory of\n the system.\n\n Returns\n -------\n train_labels : numpy.ndarray\n Numpy array with the labels 0 to 9 in the train MNIST database.\n \"\"\"\n return download_and_parse_mnist_file('train-labels-idx1-ubyte.gz')\n\n\ndef test_labels():\n \"\"\"Return test labels from Yann LeCun MNIST database as a numpy array.\n Download the file, if not already found in the temporary directory of\n the system.\n\n Returns\n -------\n test_labels : numpy.ndarray\n Numpy array with the labels 0 to 9 in the train MNIST database.\n \"\"\"\n return download_and_parse_mnist_file('t10k-labels-idx1-ubyte.gz')\n"
] | [
[
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jihoonerd/deep-reinforcement-learning-with-double-q-learning | [
"f48c28a2dba06a3fbd656e8c41f16510bb85dd56"
] | [
"ddqn/agent/ddqn_agent.py"
] | [
"from collections import deque\nfrom datetime import datetime\n\nimport gym\nimport imageio\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras.optimizers import Adam\n\nfrom ddqn.environment.atari_env import Environment\nfrom ddqn.networks.dqn_network import DQNNetwork\nfrom ddqn.utils.memory import ReplayMemory, Transition\n\n\nclass Agent:\n \"\"\"\n Class for DDQN model architecture.\n \"\"\"\n def __init__(self, env=\"BreakoutNoFrameskip-v4\"):\n self.game_id = env\n self.env = Environment(self.game_id, train=True)\n self.discount_factor = 0.99\n self.minibatch_size = 32\n self.update_frequency = 4\n self.target_network_update_freq = 1000\n self.agent_history_length = 4\n self.memory = ReplayMemory(capacity=10000, minibatch_size=self.minibatch_size)\n self.main_network = DQNNetwork(num_actions=self.env.get_action_space_size(), agent_history_length=self.agent_history_length)\n self.target_network = DQNNetwork(num_actions=self.env.get_action_space_size(), agent_history_length=self.agent_history_length)\n self.optimizer = Adam(learning_rate=1e-4, epsilon=1e-6)\n self.init_explr = 1.0\n self.final_explr = 0.1\n self.final_explr_frame = 1000000\n self.replay_start_size = 10000\n self.loss = tf.keras.losses.Huber()\n self.loss_metric = tf.keras.metrics.Mean(name=\"loss\")\n self.q_metric = tf.keras.metrics.Mean(name=\"Q_value\")\n self.training_frames = int(1e7)\n self.log_path = \"./log/\" + datetime.now().strftime(\"%Y%m%d_%H%M%S\") + \"_\" + self.game_id\n self.summary_writer = tf.summary.create_file_writer(self.log_path + \"/summary/\")\n self.life_game = None\n self.print_log_interval = 10\n self.save_weight_interval = 10\n\n self.env.reset()\n _, _, _, info = self.env.step(0)\n if info[\"ale.lives\"] > 0:\n self.life_game = True\n else:\n self.life_game = False \n\n @tf.function\n def get_action(self, state, exploration_rate):\n \"\"\"Get action by ε-greedy method.\n\n Args:\n state (np.uint8): recent self.agent_history_length frames. (Default: (84, 84, 4))\n exploration_rate (int): Exploration rate for deciding random or optimal action.\n\n Returns:\n action (tf.int32): Action index\n \"\"\"\n recent_state = tf.expand_dims(state, axis=0)\n if tf.random.uniform((), minval=0, maxval=1, dtype=tf.float32) < exploration_rate:\n action = tf.random.uniform((), minval=0, maxval=self.env.get_action_space_size(), dtype=tf.int32)\n else:\n q_value = self.main_network(tf.cast(recent_state, tf.float32))\n action = tf.cast(tf.squeeze(tf.math.argmax(q_value, axis=1)), dtype=tf.int32)\n return action\n \n @tf.function\n def get_eps(self, current_step, terminal_eps=0.01, terminal_frame_factor=25):\n \"\"\"Use annealing schedule similar like: https://openai.com/blog/openai-baselines-dqn/ .\n\n Args:\n current_step (int): Number of entire steps agent experienced.\n terminal_eps (float): Final exploration rate arrived at terminal_frame_factor * self.final_explr_frame.\n terminal_frame_factor (int): Final exploration frame, which is terminal_frame_factor * self.final_explr_frame.\n\n Returns:\n eps (float): Calculated epsilon for ε-greedy at current_step.\n \"\"\"\n terminal_eps_frame = self.final_explr_frame * terminal_frame_factor\n\n if current_step < self.replay_start_size:\n eps = self.init_explr\n elif self.replay_start_size <= current_step and current_step < self.final_explr_frame:\n eps = (self.final_explr - self.init_explr) / (self.final_explr_frame - self.replay_start_size) * (current_step - self.replay_start_size) + self.init_explr\n elif self.final_explr_frame <= current_step and current_step < terminal_eps_frame:\n eps = (terminal_eps - self.final_explr) / (terminal_eps_frame - self.final_explr_frame) * (current_step - self.final_explr_frame) + self.final_explr\n else:\n eps = terminal_eps\n return eps\n \n @tf.function\n def update_main_q_network(self, state_batch, action_batch, reward_batch, next_state_batch, terminal_batch):\n \"\"\"Update main q network by experience replay method.\n\n Args:\n state_batch (tf.float32): Batch of states.\n action_batch (tf.int32): Batch of actions.\n reward_batch (tf.float32): Batch of rewards.\n next_state_batch (tf.float32): Batch of next states.\n terminal_batch (tf.bool): Batch or terminal status.\n\n Returns:\n loss (tf.float32): Huber loss of temporal difference.\n \"\"\"\n\n with tf.GradientTape() as tape:\n # Updated parts for DDQN from DQN\n q_online = self.main_network(next_state_batch) # Use q values from online network\n action_q_online = tf.math.argmax(q_online, axis=1) # optimal actions from the q_online\n q_target = self.target_network(next_state_batch) # q values from target netowkr\n ddqn_q = tf.reduce_sum(q_target * tf.one_hot(action_q_online, self.env.get_action_space_size(), 1.0, 0.0), axis=1)\n expected_q = reward_batch + self.discount_factor * ddqn_q * (1.0 - tf.cast(terminal_batch, tf.float32)) # Corresponds to equation (4) in ddqn paper\n main_q = tf.reduce_sum(self.main_network(state_batch) * tf.one_hot(action_batch, self.env.get_action_space_size(), 1.0, 0.0), axis=1)\n loss = self.loss(tf.stop_gradient(expected_q), main_q)\n\n gradients = tape.gradient(loss, self.main_network.trainable_variables)\n clipped_gradients = [tf.clip_by_norm(grad, 10) for grad in gradients]\n self.optimizer.apply_gradients(zip(clipped_gradients, self.main_network.trainable_variables))\n\n self.loss_metric.update_state(loss)\n self.q_metric.update_state(main_q)\n\n return loss\n\n @tf.function\n def update_target_network(self):\n \"\"\"Synchronize weights of target network by those of main network.\"\"\"\n \n main_vars = self.main_network.trainable_variables\n target_vars = self.target_network.trainable_variables\n for main_var, target_var in zip(main_vars, target_vars):\n target_var.assign(main_var)\n\n def train(self):\n \n total_step = 0\n episode = 0\n latest_100_score = deque(maxlen=100)\n\n while total_step < self.training_frames:\n \n state = self.env.reset()\n episode_step = 0\n episode_score = 0.0\n done = False\n\n while not done:\n \n eps = self.get_eps(tf.constant(total_step, tf.float32))\n action = self.get_action(tf.constant(state), tf.constant(eps, tf.float32))\n \n next_state, reward, done, info = self.env.step(action)\n episode_score += reward\n\n self.memory.push(state, action, reward, next_state, done)\n state = next_state\n\n if (total_step % self.update_frequency == 0) and (total_step > self.replay_start_size):\n indices = self.memory.get_minibatch_indices()\n state_batch, action_batch, reward_batch, next_state_batch, terminal_batch = self.memory.generate_minibatch_samples(indices)\n self.update_main_q_network(state_batch, action_batch, reward_batch, next_state_batch, terminal_batch)\n\n if (total_step % self.target_network_update_freq == 0) and (total_step > self.replay_start_size):\n loss = self.update_target_network()\n \n total_step += 1\n episode_step += 1\n\n if done:\n latest_100_score.append(episode_score)\n self.write_summary(episode, latest_100_score, episode_score, total_step, eps)\n episode += 1\n\n if episode % self.print_log_interval == 0:\n print(\"Episode: \", episode)\n print(\"Latest 100 avg: {:.4f}\".format(np.mean(latest_100_score)))\n print(\"Progress: {} / {} ( {:.2f} % )\".format(total_step, self.training_frames, \n np.round(total_step / self.training_frames, 3) * 100))\n\n if episode % self.save_weight_interval == 0:\n print(\"Saving weights...\")\n self.main_network.save_weights(self.log_path + \"/weights/episode_{}\".format(episode))\n self.play(self.log_path + \"/weights/\", episode=episode)\n\n def play(self, load_dir=None, episode=None, trial=5, max_playing_time=10):\n \n if load_dir:\n loaded_ckpt = tf.train.latest_checkpoint(load_dir)\n self.main_network.load_weights(loaded_ckpt)\n \n frame_set = []\n reward_set = []\n test_env = Environment(self.game_id, train=False)\n for _ in range(trial):\n\n state = test_env.reset()\n frames = []\n test_step = 0\n test_reward = 0\n done = False\n test_memory = ReplayMemory(10000, verbose=False)\n\n while not done:\n\n frames.append(test_env.render())\n\n action = self.get_action(tf.constant(state, tf.float32), tf.constant(0.0, tf.float32))\n \n next_state, reward, done, info = test_env.step(action)\n test_reward += reward\n\n test_memory.push(state, action, reward, next_state, done)\n state = next_state\n\n test_step += 1\n\n if done and self.life_game and (info[\"ale.lives\"] != 0):\n test_env.reset()\n test_step = 0\n done = False\n\n if len(frames) > 15 * 60 * max_playing_time: # To prevent falling infinite repeating sequences.\n print(\"Playing takes {} minutes. Force termination.\".format(max_playing_time))\n break\n\n reward_set.append(test_reward)\n frame_set.append(frames)\n\n best_score = np.max(reward_set)\n print(\"Best score of current network ({} trials): {}\".format(trial, best_score))\n best_score_ind = np.argmax(reward_set)\n imageio.mimsave(\"test.gif\", frame_set[best_score_ind], fps=15)\n\n if episode is not None:\n with self.summary_writer.as_default():\n tf.summary.scalar(\"Test score\", best_score, step=episode)\n\n def write_summary(self, episode, latest_100_score, episode_score, total_step, eps):\n\n with self.summary_writer.as_default():\n tf.summary.scalar(\"Reward (clipped)\", episode_score, step=episode)\n tf.summary.scalar(\"Latest 100 avg reward (clipped)\", np.mean(latest_100_score), step=episode)\n tf.summary.scalar(\"Loss\", self.loss_metric.result(), step=episode)\n tf.summary.scalar(\"Average Q\", self.q_metric.result(), step=episode)\n tf.summary.scalar(\"Total Frames\", total_step, step=episode)\n tf.summary.scalar(\"Epsilon\", eps, step=episode)\n\n self.loss_metric.reset_states()\n self.q_metric.reset_states()\n"
] | [
[
"tensorflow.math.argmax",
"tensorflow.train.latest_checkpoint",
"tensorflow.constant",
"tensorflow.random.uniform",
"tensorflow.cast",
"tensorflow.expand_dims",
"tensorflow.stop_gradient",
"tensorflow.clip_by_norm",
"tensorflow.keras.losses.Huber",
"numpy.max",
"tensorflow.keras.optimizers.Adam",
"numpy.argmax",
"tensorflow.GradientTape",
"numpy.mean",
"numpy.round",
"tensorflow.summary.scalar",
"tensorflow.keras.metrics.Mean",
"tensorflow.summary.create_file_writer"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Xiefan-Guo/Paper-PyTorch | [
"5dbb68ba78f427b56e75ddbd95a68475951e1514"
] | [
"GAN/WGAN/wgan.py"
] | [
"import argparse\nimport os\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\n\nimport torchvision.transforms as transforms\n\nfrom torchvision.utils import save_image\nfrom torch.utils.data import DataLoader\nfrom torch.autograd import Variable\nfrom torchvision import datasets\n\nos.makedirs(\"images\", exist_ok=True)\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--n_epochs\", type=int, default=20, help=\"number of epochs of training\")\nparser.add_argument(\"--batch_size\", type=int, default=64, help=\"size of the batches\")\nparser.add_argument(\"--lr\", type=float, default=0.00005, help=\"learning rate\")\nparser.add_argument(\"--n_cpu\", type=int, default=8, help=\"number of cpu threads to use during batch generation\")\nparser.add_argument(\"--latent_dim\", type=int, default=100, help=\"dimensionality of the latent space\")\nparser.add_argument(\"--img_size\", type=int, default=28, help=\"size of each image dimension\")\nparser.add_argument(\"--channels\", type=int, default=1, help=\"number of image channels\")\nparser.add_argument(\"--n_critic\", type=int, default=5, help=\"number of training steps for discriminator per iter\")\nparser.add_argument(\"--clip_value\", type=float, default=0.01, help=\"lower and upper clip value for discriminator weights\")\nparser.add_argument(\"--sample_interval\", type=int, default=1000, help=\"interval between image samples\")\nopt = parser.parse_args()\nprint(opt)\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nprint(device)\n\n# the size of image\nimg_shape = (opt.channels, opt.img_size, opt.img_size)\nprint(*img_shape)\n\n# Configure data loader\nos.makedirs(\"../../data/mnist\", exist_ok=True)\ndataloader = DataLoader(\n dataset=datasets.MNIST(\n root=\"../../data/mnist\",\n train=True,\n download=True,\n transform=transforms.Compose(\n [transforms.Resize(opt.img_size), transforms.ToTensor(), transforms.Normalize([0.5], [0.5])]\n )\n ),\n batch_size=opt.batch_size,\n shuffle=True\n)\n\n# ------\n# Models\n# ------\nclass Generator(nn.Module):\n\n def __init__(self):\n super(Generator, self).__init__()\n\n def block(in_feat, out_feat, normalize=True):\n layers = [nn.Linear(in_feat, out_feat)]\n if normalize:\n layers.append(nn.BatchNorm1d(out_feat, 0.8))\n layers.append(nn.LeakyReLU(0.2, inplace=True))\n return layers\n\n self.model = nn.Sequential(\n *block(opt.latent_dim, 128, normalize=False),\n *block(128, 256),\n *block(256, 512),\n *block(512, 1024),\n nn.Linear(1024, int(np.prod(img_shape))),\n nn.Tanh()\n )\n\n def forward(self, z):\n img = self.model(z)\n img = img.view(img.size(0), *img_shape)\n return img\n\n\nclass Discriminator(nn.Module):\n\n def __init__(self):\n super(Discriminator, self).__init__()\n\n self.model = nn.Sequential(\n nn.Linear(int(np.prod(img_shape)), 512),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Linear(512, 256),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Linear(256, 1),\n )\n\n def forward(self, img):\n img_flat = img.view(img.size(0), -1)\n validity = self.model(img_flat)\n return validity\n\n\n# Initialize generator and discriminator\ngenerator = Generator().to(device)\ndiscriminator = Discriminator().to(device)\n\n# Optimizers\noptimizer_G = torch.optim.RMSprop(generator.parameters(), lr=opt.lr)\noptimizer_D = torch.optim.RMSprop(discriminator.parameters(), lr=opt.lr)\n\nbatches_done = 0\n\n# --------\n# Training\n# --------\nfor epoch in range(opt.n_epochs):\n for i, (imgs, _) in enumerate(dataloader):\n\n real_imgs = Variable(imgs).to(device)\n\n # ----------------------\n # Training Discriminator\n # ----------------------\n\n optimizer_D.zero_grad()\n # noise\n z = Variable(torch.randn(imgs.size(0), opt.latent_dim)).to(device)\n\n fake_imgs = generator(z)\n loss_D = -torch.mean(discriminator(real_imgs)) + torch.mean(discriminator(fake_imgs))\n\n loss_D.backward()\n optimizer_D.step()\n\n # Clip weights of discriminator\n for w in discriminator.parameters():\n w.data.clamp_(-opt.clip_value, opt.clip_value)\n\n # ------------------\n # Training Generator\n # ------------------\n if i % opt.n_critic == 0:\n optimizer_G.zero_grad()\n\n gen_imgs = generator(z)\n # Adversarial loss\n loss_G = -torch.mean(discriminator(gen_imgs))\n\n loss_G.backward()\n optimizer_G.step()\n\n print(\n \"[Epoch %d/%d] [Batch %d/%d] [D loss: %f] [G loss: %f]\"\n % (epoch, opt.n_epochs, i % len(dataloader), len(dataloader), loss_D.item(), loss_G.item())\n )\n\n if batches_done % opt.sample_interval == 0:\n save_image(gen_imgs.data[:25], \"images/%d.png\" % batches_done, nrow=5, normalize=True)\n batches_done += 1\n"
] | [
[
"torch.nn.BatchNorm1d",
"torch.nn.Tanh",
"torch.nn.Linear",
"torch.nn.LeakyReLU",
"torch.cuda.is_available",
"numpy.prod",
"torch.autograd.Variable"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
lwanger/python_ray_tracer | [
"b0e41885a41953eac1cd97402319f5abdf8c477c"
] | [
"test/stl_test.py"
] | [
"from pathlib import Path\n\nimport numpy as np\nfrom stl import mesh # numpy-stl\n\nfrom mpl_toolkits import mplot3d\nfrom matplotlib import pyplot\n\n\n#FILENAME=\"models/sauce_ramp_v2.stl\"\n#FILENAME=\"models/LRW pick (plate stiffener).stl\"\n#FILENAME=\"models/gyroid_20mm.stl\"\n#FILENAME=\"models/modern_hexagon_revisited.stl\"\nFILENAME=\"models/bar_6mm.stl\"\n\n\ndef bbox(my_mesh):\n min_x = my_mesh.x.min_val()\n max_x = my_mesh.x.max_val()\n min_y = my_mesh.y.min_val()\n max_y = my_mesh.y.max_val()\n min_z = my_mesh.z.min_val()\n max_z = my_mesh.z.max_val()\n return ((min_x, min_y, min_z), (max_x, max_y, max_z))\n\ndef scale(array, new_min, new_max):\n \"\"\"Rescale an arrary linearly.\"\"\"\n minimum, maximum = np.min(array), np.max(array)\n m = (new_max - new_min) / (maximum - minimum)\n b = new_min - m * minimum\n return m * array + b\n\n\nstl_filename = Path(FILENAME)\n\nmy_mesh = mesh.Mesh.from_file(stl_filename)\n\npoints = my_mesh.points.shape[0]\n\nprint(f'my_mesh num_triangles={my_mesh.points.shape[0]}, shape={my_mesh.points.shape}')\n\nb = bbox(my_mesh)\nprint(f'my_mesh bbox={b}')\n\n# v0 = my_mesh.points[0][0:3]\nv0 = my_mesh.points[0][0:3].tolist()\nv1 = my_mesh.points[0][3:6].tolist()\nv2 = my_mesh.points[0][6:9].tolist()\nprint(f'my_mesh triangle_1={(v0,v1,v2)}')\n\n# scale\nnew_mesh_data = scale(my_mesh, -1, 1)\nnew_mesh = mesh.Mesh(new_mesh_data)\nb = bbox(new_mesh)\nprint(f'new_mesh bbox={b}')\n\nfigure = pyplot.figure()\naxes = mplot3d.Axes3D(figure)\naxes.add_collection3d(mplot3d.art3d.Poly3DCollection(my_mesh.vectors))\n\nscale = my_mesh.points.flatten()\naxes.auto_scale_xyz(scale,scale,scale)\n\npyplot.show() # doesn't work in pycharm -- gives mac() arg is an empty sequence\n"
] | [
[
"numpy.max",
"numpy.min",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
nttcom/HSICLassoVI | [
"4d841feb25f24ae8af5ecfb7bf109dbb12afd2d5"
] | [
"HSICLassoVI/features/make_kernel.py"
] | [
"import numpy as np\nfrom joblib import Parallel, delayed\n\nfrom .kernels import *\n\n\ndef make_kernel(X, Y, y_kernel, x_kernel='Gaussian', n_jobs=-1, discarded=0, B=0, M=1):\n\n d, n = X.shape\n dy = Y.shape[0]\n\n L = compute_kernel(Y, y_kernel, B, M, discarded)\n L = np.reshape(L,(n * B * M,1))\n\n result = Parallel(n_jobs=n_jobs)([delayed(parallel_compute_kernel)(\n np.reshape(X[k,:],(1,n)), x_kernel, k, B, M, n, discarded) for k in range(d)])\n\n result = dict(result)\n\n K = np.array([result[k] for k in range(d)]).T\n KtL = np.dot(K.T, L)\n\n return K, KtL, L\n\n\n\n\n\n\ndef compute_kernel(x, kernel, B = 0, M = 1, discarded = 0):\n\n d,n = x.shape\n\n H = np.eye(B, dtype=np.float32) - 1 / B * np.ones(B, dtype=np.float32)\n K = np.zeros(n * B * M, dtype=np.float32)\n\n if kernel in ['Gaussian', 'RationalQuadratic', 'Matern32', 'Matern52', 'ExpSineSquared', 'DotProduct', 'Constant', 'Laplacian', 'Periodic']:\n x = (x / (x.std() + 10e-20)).astype(np.float32)\n\n st = 0\n ed = B ** 2\n index = np.arange(n)\n for m in range(M):\n np.random.seed(m)\n index = np.random.permutation(index)\n\n for i in range(0, n - discarded, B):\n j = min(n, i + B)\n\n if kernel == 'Gaussian':\n k = kernel_gaussian(x[:,index[i:j]], x[:,index[i:j]], np.sqrt(d))\n elif kernel == 'Delta':\n k = kernel_delta_norm(x[:,index[i:j]], x[:, index[i:j]])\n \n elif kernel == 'White':\n k = kernel_white(x[:,index[i:j]], x[:, index[i:j]])\n elif kernel == 'RationalQuadratic':\n k = kernel_rational_quadratic(x[:,index[i:j]], x[:, index[i:j]])\n elif kernel == 'Matern32':\n k = kernel_matern(x[:,index[i:j]], x[:, index[i:j]], nu = 1.5)\n elif kernel == 'Matern52':\n k = kernel_matern(x[:,index[i:j]], x[:, index[i:j]], nu = 2.5)\n elif kernel == 'ExpSineSquared':\n k = kernel_exp_sine_squared(x[:,index[i:j]], x[:, index[i:j]])\n elif kernel == 'DotProduct':\n k = kernel_dot_product(x[:,index[i:j]], x[:, index[i:j]])\n elif kernel == 'Constant':\n k = kernel_constant(x[:,index[i:j]], x[:, index[i:j]])\n elif kernel == 'Laplacian':\n k = kernel_exponential(x[:,index[i:j]], x[:, index[i:j]])\n elif kernel == 'Periodic':\n k = kernel_periodic_exponential(x[:,index[i:j]], x[:, index[i:j]])\n elif kernel == 'Periodic':\n k = kernel_periodic_exponential(x[:,index[i:j]], x[:, index[i:j]])\n elif kernel == 'RandomFourier':\n k = kernel_Random_Fourier(x[:,index[i:j]], x[:, index[i:j]])\n \n else:\n raise ValueError('Kernel Error')\n\n k = np.dot(np.dot(H, k), H)\n\n k = k / (np.linalg.norm(k, 'fro') + 10e-10)\n K[st:ed] = k.flatten()\n st += B ** 2\n ed += B ** 2\n\n return K\n\n\n\n\n\n\ndef parallel_compute_kernel(x, kernel, feature_idx, B, M, n, discarded):\n\n return (feature_idx, compute_kernel(x, kernel, B, M, discarded))"
] | [
[
"numpy.dot",
"numpy.sqrt",
"numpy.random.seed",
"numpy.reshape",
"numpy.arange",
"numpy.eye",
"numpy.linalg.norm",
"numpy.ones",
"numpy.random.permutation",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
CedArctic/VP-Tree | [
"2c85e9dfa57330b541bd09c679794f385b095c6f"
] | [
"vp-tree.py"
] | [
"# Imports\nimport random\nimport matplotlib.pyplot as plt\nimport utilities\nfrom utilities import Node, Point, DQueue\n\n# Constants\nPOINTS_NUMBER = 1000 # Number of randomly generated points\nNEIGHBORS_NUMBER = 5 # Number of neighbors to find\n\n\ndef divideAndConquer(points):\n # Check to end recursion: if points array is of size 0 - we are returning a leaf\n if len(points) == 1:\n return Node([points[0], 0])\n\n # Select a random point and remove it from the list\n point = random.choice(points)\n points.remove(point)\n\n # Calculate median distance of point and add it with the point into the local node.\n # Node data is in the form of [point, median]\n distances = []\n for p in points:\n distances.append(p.distance(point))\n distances.sort()\n if len(distances) % 2 == 0:\n median = 0.5 * (distances[int(len(distances) / 2) - 1] + distances[int(len(distances) / 2)])\n else:\n median = distances[int((len(distances) + 1) / 2) - 1]\n localNode = Node([point, median])\n\n # Add vantage points to plot\n ax.add_patch(\n plt.Circle((point.X, point.Y), median, color=(random.uniform(0, 1), random.uniform(0, 1), random.uniform(0, 1)),\n alpha=0.1))\n\n # Sort points into two new arrays: the ones within median range and ones outside.\n # Those with distance less than median go on the left\n leftPoints = []\n rightPoints = []\n for p in points:\n if point.distance(p) < median:\n leftPoints.append(p)\n else:\n rightPoints.append(p)\n\n # Recursively call on left and right child of node\n if len(leftPoints) == 0:\n localNode.left = None\n else:\n localNode.left = divideAndConquer(leftPoints)\n\n if len(rightPoints) == 0:\n localNode.right = None\n else:\n localNode.right = divideAndConquer(rightPoints)\n\n # Return local node\n return localNode\n\n\n# Call searchTree to find the query's neighbors\ndef searchTree(startingNode):\n # This is the radius around the query defined by the distance of query-furthest current neighbor\n if neighbors.length() is not 0:\n searchRadius = neighbors.peek_distance()\n else:\n # This is just a big default radius just so it will be directly replaced the first time searchTree is called\n searchRadius = 999999\n\n # Check if startingNode can be a neighbor based on its distance to the query point and already recorded neighbors\n nodePoint = startingNode.data[0]\n distance = nodePoint.distance(query)\n if distance < searchRadius:\n neighbors.insert(nodePoint, distance)\n # Update searchRadius after adding a neighbor\n searchRadius = neighbors.peek_distance()\n\n # First search by scaling down the tree following the left or right subtree each time according to the query's\n # distance to the subtree root node.\n # Also check if we should check the other subtree by checking if the other subtree root intersects with the maximum\n # radius around the query. This decision is made after we have completely scaled down the tree.\n\n # NodePointRadius is the radius around the nodePoint defined by the median of points around it\n nodePointRadius = startingNode.data[1]\n\n # If nodePointRadius is 0 it means we've reached a leaf in the binary tree so we end the recursion\n if nodePointRadius == 0:\n return\n\n # In this case the query point is within the nodePointRadius so we scale down the left subtree and decide if we also\n # want to search the right subtree of the startingNode.\n if (distance < nodePointRadius) and (startingNode.left is not None):\n searchTree(startingNode.left)\n\n # If this is true, it means that part of the search area around our query point intersects with the area outside\n # of the one covered by the left subtree. We refresh the searchRadius variable because it is possible that it\n # has been updated while searchTree(startingNode.left). We also test that the other subtree exists.\n searchRadius = neighbors.peek_distance()\n if (nodePointRadius < (distance + searchRadius)) and (startingNode.right is not None):\n searchTree(startingNode.right)\n\n # In this case the query point is outside the nodePointRadius so we scale down the right subtree and decide if we\n # also want to search the left subtree of the startingNode\n elif (distance >= nodePointRadius) and (startingNode.right is not None):\n searchTree(startingNode.right)\n\n # If this is true, it means that part of the search area around our query point intersects with the area outside\n # of the one covered by the right subtree. We refresh the searchRadius variable because it is possible that it\n # has been updated while searchTree(startingNode.left). We also test that the other subtree exists.\n searchRadius = neighbors.peek_distance()\n if (distance < (nodePointRadius + searchRadius)) and (startingNode.left is not None):\n searchTree(startingNode.left)\n else:\n return\n\n\n# Main program\n\n# Setup plot\nfig = plt.figure()\nax = fig.add_axes([0, 0, 1, 1])\nax.set_aspect(aspect='equal')\n\n# Generate random points on a two dimensional plane\npoints = utilities.random_points(POINTS_NUMBER)\n\n# Nodes contain the point and its median distance from all other points in the format Node([ point, median])\n# Call divideAndConquer to build the binary tree\nroot = divideAndConquer(points)\n\n# Generate a random point to use as a query\nquery = Point(random.random(), random.random())\n\n# Call searchTree to find the query's neighbors\nneighbors = DQueue(NEIGHBORS_NUMBER)\nsearchTree(root)\n\n# Print results and make the plot\nprint(\"Query Point: \\n\")\nquery.print()\nax.plot(query.X, query.Y, 'bo')\nax.add_patch(plt.Circle((query.X, query.Y), neighbors.peek_distance(), color='b', alpha=0.2))\nprint(\"Neighbors: \")\nfor point in points:\n ax.plot(point.X, point.Y, 'ro')\nfor neighbor in neighbors.data:\n neighbor[0].print()\n ax.plot(neighbor[0].X, neighbor[0].Y, 'go')\n\nplt.show()\n"
] | [
[
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
abdelabdalla/deepmind-research | [
"4b7e0379ca5ba85e27f6f246fa2b0c060bd86879"
] | [
"mesh/reader.py"
] | [
"import collections\nimport functools\nimport json\nimport os\nimport pickle\n\nfrom absl import app\nfrom absl import flags\nfrom absl import logging\nimport numpy as np\nimport tensorflow as tf\nimport tree\n\nfrom learning_to_simulate import reading_utils\n\ntf.enable_eager_execution()\n\ndef _read_metadata(data_path):\n with open(os.path.join(data_path, 'metadata.json'), 'rt') as fp:\n return json.loads(fp.read())\n\n\ndef prepare_inputs(tensor_dict):\n \"\"\"Prepares a single stack of inputs by calculating inputs and targets.\n\n Computes n_particles_per_example, which is a tensor that contains information\n about how to partition the axis - i.e. which nodes belong to which graph.\n\n Adds a batch axis to `n_particles_per_example` and `step_context` so they can\n later be batched using `batch_concat`. This batch will be the same as if the\n elements had been batched via stacking.\n\n Note that all other tensors have a variable size particle axis,\n and in this case they will simply be concatenated along that\n axis.\n\n\n\n Args:\n tensor_dict: A dict of tensors containing positions, and step context (\n if available).\n\n Returns:\n A tuple of input features and target positions.\n\n \"\"\"\n # Position is encoded as [sequence_length, num_particles, dim] but the model\n # expects [num_particles, sequence_length, dim].\n pos = tensor_dict['position']\n pos = tf.transpose(pos, perm=[1, 0, 2])\n\n # The target position is the final step of the stack of positions.\n target_position = pos[:, -1]\n\n # Remove the target from the input.\n tensor_dict['position'] = pos[:, :-1]\n\n # Compute the number of particles per example.\n num_particles = tf.shape(pos)[0]\n # Add an extra dimension for stacking via concat.\n tensor_dict['n_particles_per_example'] = num_particles[tf.newaxis]\n\n if 'step_context' in tensor_dict:\n # Take the input global context. We have a stack of global contexts,\n # and we take the penultimate since the final is the target.\n tensor_dict['step_context'] = tensor_dict['step_context'][-2]\n # Add an extra dimension for stacking via concat.\n tensor_dict['step_context'] = tensor_dict['step_context'][tf.newaxis]\n return tensor_dict, target_position\n\ndef prepare_rollout_inputs(context, features):\n \"\"\"Prepares an inputs trajectory for rollout.\"\"\"\n out_dict = {**context}\n # Position is encoded as [sequence_length, num_particles, dim] but the model\n # expects [num_particles, sequence_length, dim].\n pos = tf.transpose(features['position'], [1, 0, 2])\n # The target position is the final step of the stack of positions.\n target_position = pos[:, -1]\n # Remove the target from the input.\n out_dict['position'] = pos[:, :-1]\n # Compute the number of nodes\n out_dict['n_particles_per_example'] = [tf.shape(pos)[0]]\n if 'step_context' in features:\n out_dict['step_context'] = features['step_context']\n out_dict['is_trajectory'] = tf.constant([True], tf.bool)\n return out_dict, target_position\n\n\nINPUT_SEQUENCE_LENGTH = 6\n\npath = \"/tmp/datasets/WaterRamps\"\n\nmetadata = _read_metadata(path)\n\nds = tf.data.TFRecordDataset([os.path.join(path, 'valid.tfrecord')])\nds = ds.map(functools.partial(reading_utils.parse_serialized_simulation_example, metadata=metadata))\n\nsplit_with_window = functools.partial(\n reading_utils.split_trajectory,\n window_length=INPUT_SEQUENCE_LENGTH + 1)\nds = ds.flat_map(split_with_window)\n# Splits a chunk into input steps and target steps\nds = ds.map(prepare_inputs)\n\ni = 1\nfor feature in ds:\n #test = feature[0]\n i = i+1\n\nprint(i)"
] | [
[
"tensorflow.constant",
"tensorflow.enable_eager_execution",
"tensorflow.transpose",
"tensorflow.shape"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.7",
"1.10",
"1.12"
]
}
] |
ftramer/FaceCure | [
"35cef519396586028cf4f646b2867a1ea38c025c"
] | [
"lowkey_attack.py"
] | [
"import torch\nimport PIL\nfrom PIL import Image\nimport numpy as np\nfrom util.feature_extraction_utils import feature_extractor, normalize_transforms, warp_image, normalize_batch\nfrom backbone.model_irse import IR_50, IR_101, IR_152\nfrom backbone.model_resnet import ResNet_50, ResNet_101, ResNet_152\nfrom util.attack_utils import Attack\nfrom util.prepare_utils import prepare_models, prepare_dir_vec, get_ensemble, prepare_data\nfrom align.detector import detect_faces\nfrom align.align_trans import get_reference_facial_points, warp_and_crop_face\nimport argparse\nimport matplotlib.pyplot as plt\nimport copy\nimport torchvision.transforms as transforms\nimport sys, os\n\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nto_tensor = transforms.ToTensor()\n\n# Disable\ndef blockPrint():\n sys.stdout = open(os.devnull, 'w')\n\ndef enablePrint():\n sys.stdout = sys.__stdout__\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser()\n parser.add_argument('--dir', default = './', help = 'directory with images to protect')\n\n args = parser.parse_args()\n dir_root = args.dir\n\n eps = 0.05\n n_iters = 50\n input_size = [112, 112]\n attack_type = 'lpips'\n c_tv = None\n c_sim = 0.05\n lr = 0.0025\n net_type = 'alex'\n noise_size = 0.005\n n_starts = 1\n kernel_size_gf = 7\n sigma_gf = 3\n combination = True\n using_subspace = False\n V_reduction_root = './'\n model_backbones = ['IR_152', 'IR_152', 'ResNet_152', 'ResNet_152']\n model_roots = ['models/Backbone_IR_152_Arcface_Epoch_112.pth', 'models/Backbone_IR_152_Cosface_Epoch_70.pth', \\\n 'models/Backbone_ResNet_152_Arcface_Epoch_65.pth', 'models/Backbone_ResNet_152_Cosface_Epoch_68.pth'] \n direction = 1\n crop_size = 112\n scale = crop_size / 112.\n\n models_attack, V_reduction, dim = prepare_models(model_backbones,\n input_size,\n model_roots,\n kernel_size_gf,\n sigma_gf,\n combination,\n using_subspace,\n V_reduction_root,\n device)\n\n imgs = []\n paths = []\n for img_name in os.listdir(dir_root):\n\n if 'attacked' in img_name or 'small' in img_name:\n continue\n\n img_root = os.path.join(dir_root, img_name)\n\n if os.path.exists(img_root[:-4] + '_attacked.png'):\n print(f\"skipping {img_name}\")\n continue\n\n img = Image.open(img_root).convert(\"RGB\")\n img = img.resize((112, 112))\n img.save(img_root[:-4] + '_small.png')\n imgs.append(np.array(img))\n paths.append(img_root)\n\n idx = 0\n batch_size = 8\n print(len(imgs))\n\n while idx < len(imgs):\n print(f\"img {idx} to {idx+batch_size} of {len(imgs)}\")\n batch = imgs[idx:idx+batch_size]\n batch_paths = paths[idx:idx+batch_size]\n idx += batch_size\n\n reference = get_reference_facial_points(default_square = True) * scale\n\n tensor_img = torch.cat([to_tensor(i).unsqueeze(0) for i in batch], 0).to(device)\n print(tensor_img.shape)\n\n V_reduction = None\n dim = 512\n\n # find direction vector\n dir_vec_extractor = get_ensemble(models = models_attack, sigma_gf = None, kernel_size_gf = None, combination = False, V_reduction = V_reduction, warp = False, theta_warp = None)\n dir_vec = prepare_dir_vec(dir_vec_extractor, tensor_img, dim, combination)\n\n img_attacked = tensor_img.clone()\n attack = Attack(models_attack, dim, attack_type, eps, c_sim, net_type, lr,\n n_iters, noise_size, n_starts, c_tv, sigma_gf, kernel_size_gf,\n combination, warp=False, theta_warp=None, V_reduction = V_reduction)\n\n img_attacked = attack.execute(tensor_img, dir_vec, direction).detach().cpu()\n\n for img, img_root in zip(img_attacked, batch_paths):\n img_attacked_pil = transforms.ToPILImage()(img)\n img_attacked_pil.save(img_root[:-4] + '_attacked.png')\n"
] | [
[
"numpy.array",
"torch.cuda.is_available"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
kuzhamuratov/SAC | [
"9f4ebefb7207fd398371f18baa16f4417ad1a63b"
] | [
"main.py"
] | [
"import argparse\nimport datetime\nimport gym\nimport numpy as np\nimport itertools\nimport torch\nfrom sac import SAC\nfrom torch.utils.tensorboard import SummaryWriter\nfrom replay_memory import ReplayMemory\nimport robel\n\nparser = argparse.ArgumentParser(description='PyTorch Soft Actor-Critic Args')\nparser.add_argument('--env-name', default=\"HalfCheetah-v2\",\n help='Mujoco Gym environment (default: HalfCheetah-v2)')\nparser.add_argument('--policy', default=\"Gaussian\",\n help='Policy Type: Gaussian | Deterministic (default: Gaussian)')\nparser.add_argument('--eval', type=bool, default=True,\n help='Evaluates a policy a policy every 10 episode (default: True)')\nparser.add_argument('--gamma', type=float, default=0.99, metavar='G',\n help='discount factor for reward (default: 0.99)')\nparser.add_argument('--tau', type=float, default=0.005, metavar='G',\n help='target smoothing coefficient(τ) (default: 0.005)')\nparser.add_argument('--lr', type=float, default=0.0003, metavar='G',\n help='learning rate (default: 0.0003)')\nparser.add_argument('--alpha', type=float, default=0.2, metavar='G',\n help='Temperature parameter α determines the relative importance of the entropy\\\n term against the reward (default: 0.2)')\nparser.add_argument('--automatic_entropy_tuning', type=bool, default=False, metavar='G',\n help='Automaically adjust α (default: False)')\nparser.add_argument('--seed', type=int, default=123456, metavar='N',\n help='random seed (default: 123456)')\nparser.add_argument('--batch_size', type=int, default=256, metavar='N',\n help='batch size (default: 256)')\nparser.add_argument('--num_steps', type=int, default=5000001, metavar='N',\n help='maximum number of steps (default: 1000000)')\nparser.add_argument('--hidden_size', type=int, default=256, metavar='N',\n help='hidden size (default: 256)')\nparser.add_argument('--updates_per_step', type=int, default=1, metavar='N',\n help='model updates per simulator step (default: 1)')\nparser.add_argument('--start_steps', type=int, default=10000, metavar='N',\n help='Steps sampling random actions (default: 10000)')\nparser.add_argument('--target_update_interval', type=int, default=1, metavar='N',\n help='Value target update per no. of updates per step (default: 1)')\nparser.add_argument('--replay_size', type=int, default=1000000, metavar='N',\n help='size of replay buffer (default: 10000000)')\nparser.add_argument('--cuda', action=\"store_true\",\n help='run on CUDA (default: False)')\nargs = parser.parse_args()\n\n# Environment\n# env = NormalizedActions(gym.make(args.env_name))\nenv = gym.make(args.env_name)\nenv.seed(args.seed)\nenv.action_space.seed(args.seed)\nenv._max_episode_steps = 80 ####### TO CHECK ITs consistent with PEARL (Arsen)\ntorch.manual_seed(args.seed)\nnp.random.seed(args.seed)\n\n# Agent\nagent = SAC(env.observation_space.shape[0], env.action_space, args)\n\n# maximum_test_reward (to save model)\nmax_test_r = -np.inf\n\n#Tensorboard\nwriter = SummaryWriter('runs/{}_SAC_{}_{}_{}'.format(datetime.datetime.now().strftime(\"%Y-%m-%d_%H-%M-%S\"), args.env_name,\n args.policy, \"autotune\" if args.automatic_entropy_tuning else \"\"))\n\n# Memory\nmemory = ReplayMemory(args.replay_size, args.seed)\n\n# Training Loop\ntotal_numsteps = 0\nupdates = 0\n\nfor i_episode in itertools.count(1):\n episode_reward = 0\n episode_steps = 0\n done = False\n state = env.reset()\n# env.render()\n while not done:\n if args.start_steps > total_numsteps:\n action = env.action_space.sample() # Sample random action\n else:\n action = agent.select_action(state) # Sample action from policy\n\n if len(memory) > args.batch_size:\n # Number of updates per step in environment\n for i in range(args.updates_per_step):\n # Update parameters of all the networks\n critic_1_loss, critic_2_loss, policy_loss, ent_loss, alpha = agent.update_parameters(memory, args.batch_size, updates)\n\n writer.add_scalar('loss/critic_1', critic_1_loss, updates)\n writer.add_scalar('loss/critic_2', critic_2_loss, updates)\n writer.add_scalar('loss/policy', policy_loss, updates)\n writer.add_scalar('loss/entropy_loss', ent_loss, updates)\n writer.add_scalar('entropy_temprature/alpha', alpha, updates)\n updates += 1\n\n next_state, reward, done, _ = env.step(action) # Step\n episode_steps += 1\n total_numsteps += 1\n episode_reward += reward\n\n # Ignore the \"done\" signal if it comes from hitting the time horizon.\n # (https://github.com/openai/spinningup/blob/master/spinup/algos/sac/sac.py)\n mask = 1 if episode_steps == env._max_episode_steps else float(not done)\n\n memory.push(state, action, reward, next_state, mask) # Append transition to memory\n\n state = next_state\n\n if total_numsteps > args.num_steps:\n break\n\n writer.add_scalar('reward/train', episode_reward, i_episode)\n print(\"Episode: {}, total numsteps: {}, episode steps: {}, reward: {}\".format(i_episode, total_numsteps, episode_steps, round(episode_reward, 2)))\n\n if i_episode % 100 == 0 and args.eval is True:\n avg_reward = 0.\n episodes = 10\n for _ in range(episodes):\n state = env.reset()\n episode_reward = 0\n done = False\n while not done:\n action = agent.select_action(state, evaluate=True)\n next_state, reward, done, _ = env.step(action)\n episode_reward += reward\n\n\n state = next_state\n avg_reward += episode_reward\n avg_reward /= episodes\n\n if max_test_r<=avg_reward:\n max_test_r = avg_reward\n agent.save_model(args.env_name)#, suffix=str(i_episode))\n\n writer.add_scalar('avg_reward/test', avg_reward, i_episode)\n\n print(\"----------------------------------------\")\n print(\"Test Episodes: {}, Avg. Reward: {}\".format(episodes, round(avg_reward, 2)))\n print(\"----------------------------------------\")\n\nenv.close()\n\n"
] | [
[
"torch.manual_seed",
"numpy.random.seed"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
PGijsbers/categorical-encoding | [
"25cc10236626b8b95fa89ca8f52761db80fb1327"
] | [
"category_encoders/tests/test_woe.py"
] | [
"import pandas as pd\nfrom unittest2 import TestCase # or `from unittest import ...` if on Python 3.4+\nimport category_encoders.tests.helpers as th\nimport numpy as np\n\nimport category_encoders as encoders\n\nnp_X = th.create_array(n_rows=100)\nnp_X_t = th.create_array(n_rows=50, extras=True)\nnp_y = np.random.randn(np_X.shape[0]) > 0.5\nnp_y_t = np.random.randn(np_X_t.shape[0]) > 0.5\nX = th.create_dataset(n_rows=100)\nX_t = th.create_dataset(n_rows=50, extras=True)\ny = pd.DataFrame(np_y)\ny_t = pd.DataFrame(np_y_t)\n\n\nclass TestWeightOfEvidenceEncoder(TestCase):\n def test_woe(self):\n cols = ['unique_str', 'underscore', 'extra', 'none', 'invariant', 321, 'categorical', 'na_categorical', 'categorical_int']\n\n # balanced label with balanced features\n X_balanced = pd.DataFrame(data=['1', '1', '1', '2', '2', '2'], columns=['col1'])\n y_balanced = [True, False, True, False, True, False]\n enc = encoders.WOEEncoder()\n enc.fit(X_balanced, y_balanced)\n X1 = enc.transform(X_balanced)\n self.assertTrue(all(X1.sum() < 0.001),\n \"When the class label is balanced, WoE should sum to 0 in each transformed column\")\n\n enc = encoders.WOEEncoder(cols=cols)\n enc.fit(X, np_y)\n X1 = enc.transform(X_t)\n th.verify_numeric(X1[cols])\n self.assertTrue(np.isfinite(X1[cols].values).all(),\n 'There must not be any NaN, inf or -inf in the transformed columns')\n self.assertEqual(len(list(X_t)), len(list(X1)), 'The count of attributes must not change')\n self.assertEqual(len(X_t), len(X1), 'The count of rows must not change')\n X2 = enc.transform(X_t, np_y_t)\n th.verify_numeric(X2)\n self.assertTrue(np.isfinite(X2[cols].values).all(),\n 'There must not be any NaN, inf or -inf in the transformed columns')\n self.assertEqual(len(list(X_t)), len(list(X2)), 'The count of attributes must not change')\n self.assertEqual(len(X_t), len(X2), 'The count of rows must not change')\n X3 = enc.transform(X, np_y)\n th.verify_numeric(X3)\n self.assertTrue(np.isfinite(X3[cols].values).all(),\n 'There must not be any NaN, inf or -inf in the transformed columns')\n self.assertEqual(len(list(X)), len(list(X3)), 'The count of attributes must not change')\n self.assertEqual(len(X), len(X3), 'The count of rows must not change')\n self.assertTrue(X3['unique_str'].var() < 0.001, 'The unique string column must not be predictive of the label')\n X4 = enc.fit_transform(X, np_y)\n th.verify_numeric(X4)\n self.assertTrue(np.isfinite(X4[cols].values).all(),\n 'There must not be any NaN, inf or -inf in the transformed columns')\n self.assertEqual(len(list(X)), len(list(X4)), 'The count of attributes must not change')\n self.assertEqual(len(X), len(X4), 'The count of rows must not change')\n self.assertTrue(X4['unique_str'].var() < 0.001, 'The unique string column must not be predictive of the label')\n\n enc = encoders.WOEEncoder()\n enc.fit(X, np_y)\n X1 = enc.transform(X_t)\n self.assertEqual(len(list(X_t)), len(list(X1)), 'The count of attributes must not change')\n self.assertEqual(len(X_t), len(X1), 'The count of rows must not change')\n th.verify_numeric(X1)\n X2 = enc.transform(X_t, np_y_t)\n th.verify_numeric(X2)\n self.assertEqual(len(list(X_t)), len(list(X2)), 'The count of attributes must not change')\n self.assertEqual(len(X_t), len(X2), 'The count of rows must not change')\n\n # seed\n enc = encoders.WOEEncoder(cols=cols, random_state=2001, randomized=True)\n enc.fit(X, np_y)\n X1 = enc.transform(X_t, np_y_t)\n X2 = enc.transform(X_t, np_y_t)\n self.assertTrue(X1.equals(X2), \"When the seed is given, the results must be identical\")\n th.verify_numeric(X1)\n th.verify_numeric(X2)\n\n # invariant target\n y_invariant = [True, True, True, True, True, True]\n enc = encoders.WOEEncoder()\n with self.assertRaises(ValueError):\n enc.fit(X_balanced, y_invariant)\n\n # branch coverage unit tests - no cols\n enc = encoders.WOEEncoder(cols=[])\n enc.fit(X, np_y)\n self.assertTrue(enc.transform(X_t).equals(X_t))\n\n # missing values in the target\n y_missing = [True, True, None, True, True, True]\n enc = encoders.WOEEncoder()\n with self.assertRaises(ValueError):\n enc.fit(X_balanced, y_missing)\n\n # impute missing\n enc = encoders.WOEEncoder(handle_missing='return_nan')\n enc.fit(X, np_y)\n X1 = enc.transform(X_t)\n th.verify_numeric(X1)\n self.assertTrue(X1.isnull().values.any())\n self.assertEqual(len(list(X_t)), len(list(X1)), 'The count of attributes must not change')\n self.assertEqual(len(X_t), len(X1), 'The count of rows must not change')\n\n X2 = enc.transform(X_t, np_y_t)\n th.verify_numeric(X2)\n self.assertTrue(X1.isnull().values.any())\n self.assertEqual(len(list(X_t)), len(list(X2)), 'The count of attributes must not change')\n self.assertEqual(len(X_t), len(X2), 'The count of rows must not change')\n\n def test_HaveArrays_ExpectCalculatedProperly(self):\n X = ['a', 'a', 'b', 'b']\n y = [1, 0, 0, 0]\n enc = encoders.WOEEncoder()\n\n result = enc.fit_transform(X, y)\n\n expected = pd.Series([0.5108256237659906, .5108256237659906, -0.587786664902119, -0.587786664902119], name=0)\n pd.testing.assert_series_equal(expected, result[0])\n\n def test_HandleMissingValue_HaveMissingInTrain_ExpectEncoded(self):\n X = ['a', 'a', np.nan, np.nan]\n y = [1, 0, 0, 0]\n enc = encoders.WOEEncoder(handle_missing='value')\n\n result = enc.fit_transform(X, y)\n\n expected = pd.Series([0.5108256237659906, .5108256237659906, -0.587786664902119, -0.587786664902119], name=0)\n pd.testing.assert_series_equal(expected, result[0])\n\n def test_HandleMissingValue_HaveMissingInTest_ExpectEncodedWithZero(self):\n X = ['a', 'a', 'b', 'b']\n y = [1, 0, 0, 0]\n test = ['a', np.nan]\n enc = encoders.WOEEncoder(handle_missing='value')\n\n enc.fit(X, y)\n result = enc.transform(test)\n\n expected = pd.Series([0.5108256237659906, 0], name=0)\n pd.testing.assert_series_equal(expected, result[0])\n\n def test_HandleUnknownValue_HaveUnknown_ExpectEncodedWithZero(self):\n X = ['a', 'a', 'b', 'b']\n y = [1, 0, 0, 0]\n test = ['a', 'c']\n enc = encoders.WOEEncoder(handle_unknown='value')\n\n enc.fit(X, y)\n result = enc.transform(test)\n\n expected = pd.Series([0.5108256237659906, 0], name=0)\n pd.testing.assert_series_equal(expected, result[0])\n"
] | [
[
"pandas.testing.assert_series_equal",
"pandas.Series",
"numpy.isfinite",
"pandas.DataFrame",
"numpy.random.randn"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
ggosjw/PointNetVlad | [
"8e0d00b983abdb60d3db15be96840ce20f110c59"
] | [
"loading_pointclouds.py"
] | [
"import os\nimport pickle\nimport numpy as np\nimport random\nimport config as cfg\n\ndef get_queries_dict(filename):\n # key:{'query':file,'positives':[files],'negatives:[files], 'neighbors':[keys]}\n with open(filename, 'rb') as handle:\n queries = pickle.load(handle)\n print(\"Queries Loaded.\")\n return queries\n\n\ndef get_sets_dict(filename):\n #[key_dataset:{key_pointcloud:{'query':file,'northing':value,'easting':value}},key_dataset:{key_pointcloud:{'query':file,'northing':value,'easting':value}}, ...}\n with open(filename, 'rb') as handle:\n trajectories = pickle.load(handle)\n print(\"Trajectories Loaded.\")\n return trajectories\n\n\ndef load_pc_file(filename):\n # returns Nx3 matrix\n pc = np.fromfile(os.path.join(cfg.DATASET_FOLDER, filename), dtype=np.float64)\n\n if(pc.shape[0] != 4096*3):\n print(\"Error in pointcloud shape\")\n return np.array([])\n\n pc = np.reshape(pc,(pc.shape[0]//3, 3))\n return pc #[4096,3]\n\n\ndef load_pc_files(filenames):\n pcs = []\n for filename in filenames:\n # print(filename)\n pc = load_pc_file(filename)\n if(pc.shape[0] != 4096):\n continue\n pcs.append(pc)\n pcs = np.array(pcs)\n return pcs #[#,4096,3]\n\n\ndef rotate_point_cloud(batch_data):\n \"\"\" Randomly rotate the point clouds to augument the dataset\n rotation is per shape based along up direction\n Input:\n BxNx3 array, original batch of point clouds\n Return:\n BxNx3 array, rotated batch of point clouds\n \"\"\"\n rotated_data = np.zeros(batch_data.shape, dtype=np.float32)\n for k in range(batch_data.shape[0]):\n #rotation_angle = np.random.uniform() * 2 * np.pi\n #-90 to 90\n rotation_angle = (np.random.uniform()*np.pi) - np.pi/2.0\n cosval = np.cos(rotation_angle)\n sinval = np.sin(rotation_angle)\n rotation_matrix = np.array([[cosval, -sinval, 0],\n [sinval, cosval, 0],\n [0, 0, 1]])\n shape_pc = batch_data[k, ...]\n rotated_data[k, ...] = np.dot(\n shape_pc.reshape((-1, 3)), rotation_matrix)\n return rotated_data\n\n\ndef jitter_point_cloud(batch_data, sigma=0.005, clip=0.05):\n \"\"\" Randomly jitter points. jittering is per point.\n Input:\n BxNx3 array, original batch of point clouds\n Return:\n BxNx3 array, jittered batch of point clouds\n \"\"\"\n B, N, C = batch_data.shape\n assert(clip > 0)\n jittered_data = np.clip(sigma * np.random.randn(B, N, C), -1*clip, clip)\n jittered_data += batch_data\n return jittered_data\n\n\ndef get_query_tuple(dict_value, num_pos, num_neg, QUERY_DICT, hard_neg=[], other_neg=False):\n # get query tuple for dictionary entry\n\n # get_query_tuple(TRAINING_QUERIES[batch_keys[j]], cfg.TRAIN_POSITIVES_PER_QUERY,\n # cfg.TRAIN_NEGATIVES_PER_QUERY,TRAINING_QUERIES, hard_neg=[], other_neg=False)\n # Args:\n # dict_value ([dict]): {'query':file,'positives':[files],'negatives:[files], 'neighbors':[keys]}\n # num_pos ([int]): default:2\n # num_neg ([int]): default:18\n # QUERY_DICT ([type]): {key:{'query':file,'positives':[files],'negatives:[files], 'neighbors':[keys]}}\n # hard_neg (list, optional): Defaults to [].\n # other_neg (bool, optional): Defaults to False.\n #\n # Returns:\n # Triplet loss: return [query, positives, negatives]\n # Quatriplet loss: return [query, positives, negatives, neg2]\n\n query = load_pc_file(dict_value[\"query\"]) # Nx3\n random.shuffle(dict_value[\"positives\"])\n pos_files = []\n\n for i in range(num_pos):\n pos_files.append(QUERY_DICT[dict_value[\"positives\"][i]][\"query\"])\n #positives= load_pc_files(dict_value[\"positives\"][0:num_pos])\n positives = load_pc_files(pos_files) #[#,N,3]\n\n neg_files = []\n neg_indices = []\n if(len(hard_neg) == 0):\n random.shuffle(dict_value[\"negatives\"])\n for i in range(num_neg):\n neg_files.append(QUERY_DICT[dict_value[\"negatives\"][i]][\"query\"])\n neg_indices.append(dict_value[\"negatives\"][i])\n\n else:\n random.shuffle(dict_value[\"negatives\"])\n for i in hard_neg:\n neg_files.append(QUERY_DICT[i][\"query\"])\n neg_indices.append(i)\n j = 0\n while(len(neg_files) < num_neg):\n\n if not dict_value[\"negatives\"][j] in hard_neg:\n neg_files.append(\n QUERY_DICT[dict_value[\"negatives\"][j]][\"query\"])\n neg_indices.append(dict_value[\"negatives\"][j])\n j += 1\n\n negatives = load_pc_files(neg_files)\n\n if other_neg is False:\n return [query, positives, negatives]\n # For Quadruplet Loss\n else:\n # get neighbors of negatives and query\n neighbors = []\n for pos in dict_value[\"positives\"]:\n neighbors.append(pos)\n for neg in neg_indices:\n for pos in QUERY_DICT[neg][\"positives\"]:\n neighbors.append(pos)\n possible_negs = list(set(QUERY_DICT.keys())-set(neighbors)) #query point cloud的邻居减去 negative query 的邻居 得到possible negative queries\n random.shuffle(possible_negs)\n\n if(len(possible_negs) == 0):\n return [query, positives, negatives, np.array([])]\n\n neg2 = load_pc_file(QUERY_DICT[possible_negs[0]][\"query\"]) #只选第一个作为possible_neg\n\n return [query, positives, negatives, neg2]\n\n\ndef get_rotated_tuple(dict_value, num_pos, num_neg, QUERY_DICT, hard_neg=[], other_neg=False):\n query = load_pc_file(dict_value[\"query\"]) # Nx3\n q_rot = rotate_point_cloud(np.expand_dims(query, axis=0))\n q_rot = np.squeeze(q_rot)\n\n random.shuffle(dict_value[\"positives\"])\n pos_files = []\n for i in range(num_pos):\n pos_files.append(QUERY_DICT[dict_value[\"positives\"][i]][\"query\"])\n #positives= load_pc_files(dict_value[\"positives\"][0:num_pos])\n positives = load_pc_files(pos_files)\n p_rot = rotate_point_cloud(positives)\n\n neg_files = []\n neg_indices = []\n if(len(hard_neg) == 0):\n random.shuffle(dict_value[\"negatives\"])\n for i in range(num_neg):\n neg_files.append(QUERY_DICT[dict_value[\"negatives\"][i]][\"query\"])\n neg_indices.append(dict_value[\"negatives\"][i])\n else:\n random.shuffle(dict_value[\"negatives\"])\n for i in hard_neg:\n neg_files.append(QUERY_DICT[i][\"query\"])\n neg_indices.append(i)\n j = 0\n while(len(neg_files) < num_neg):\n if not dict_value[\"negatives\"][j] in hard_neg:\n neg_files.append(\n QUERY_DICT[dict_value[\"negatives\"][j]][\"query\"])\n neg_indices.append(dict_value[\"negatives\"][j])\n j += 1\n negatives = load_pc_files(neg_files)\n n_rot = rotate_point_cloud(negatives)\n\n if other_neg is False:\n return [q_rot, p_rot, n_rot]\n\n # For Quadruplet Loss\n else:\n # get neighbors of negatives and query\n neighbors = []\n for pos in dict_value[\"positives\"]:\n neighbors.append(pos)\n for neg in neg_indices:\n for pos in QUERY_DICT[neg][\"positives\"]:\n neighbors.append(pos)\n possible_negs = list(set(QUERY_DICT.keys())-set(neighbors))\n random.shuffle(possible_negs)\n\n if(len(possible_negs) == 0):\n return [q_jit, p_jit, n_jit, np.array([])]\n\n neg2 = load_pc_file(QUERY_DICT[possible_negs[0]][\"query\"])\n n2_rot = rotate_point_cloud(np.expand_dims(neg2, axis=0))\n n2_rot = np.squeeze(n2_rot)\n\n return [q_rot, p_rot, n_rot, n2_rot]\n\n\ndef get_jittered_tuple(dict_value, num_pos, num_neg, QUERY_DICT, hard_neg=[], other_neg=False):\n query = load_pc_file(dict_value[\"query\"]) # Nx3\n #q_rot= rotate_point_cloud(np.expand_dims(query, axis=0))\n q_jit = jitter_point_cloud(np.expand_dims(query, axis=0))\n q_jit = np.squeeze(q_jit)\n\n random.shuffle(dict_value[\"positives\"])\n pos_files = []\n for i in range(num_pos):\n pos_files.append(QUERY_DICT[dict_value[\"positives\"][i]][\"query\"])\n #positives= load_pc_files(dict_value[\"positives\"][0:num_pos])\n positives = load_pc_files(pos_files)\n p_jit = jitter_point_cloud(positives)\n\n neg_files = []\n neg_indices = []\n if(len(hard_neg) == 0):\n random.shuffle(dict_value[\"negatives\"])\n for i in range(num_neg):\n neg_files.append(QUERY_DICT[dict_value[\"negatives\"][i]][\"query\"])\n neg_indices.append(dict_value[\"negatives\"][i])\n else:\n random.shuffle(dict_value[\"negatives\"])\n for i in hard_neg:\n neg_files.append(QUERY_DICT[i][\"query\"])\n neg_indices.append(i)\n j = 0\n while(len(neg_files) < num_neg):\n if not dict_value[\"negatives\"][j] in hard_neg:\n neg_files.append(\n QUERY_DICT[dict_value[\"negatives\"][j]][\"query\"])\n neg_indices.append(dict_value[\"negatives\"][j])\n j += 1\n negatives = load_pc_files(neg_files)\n n_jit = jitter_point_cloud(negatives)\n\n if other_neg is False:\n return [q_jit, p_jit, n_jit]\n\n # For Quadruplet Loss\n else:\n # get neighbors of negatives and query\n neighbors = []\n for pos in dict_value[\"positives\"]:\n neighbors.append(pos)\n for neg in neg_indices:\n for pos in QUERY_DICT[neg][\"positives\"]:\n neighbors.append(pos)\n possible_negs = list(set(QUERY_DICT.keys())-set(neighbors))\n random.shuffle(possible_negs)\n\n if(len(possible_negs) == 0):\n return [q_jit, p_jit, n_jit, np.array([])]\n\n neg2 = load_pc_file(QUERY_DICT[possible_negs[0]][\"query\"])\n n2_jit = jitter_point_cloud(np.expand_dims(neg2, axis=0))\n n2_jit = np.squeeze(n2_jit)\n\n return [q_jit, p_jit, n_jit, n2_jit]\n"
] | [
[
"numpy.expand_dims",
"numpy.reshape",
"numpy.squeeze",
"numpy.cos",
"numpy.sin",
"numpy.random.randn",
"numpy.random.uniform",
"numpy.array",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
bamtercelboo/PyTorch_Biaffine_Dependency_Parsing | [
"65e5e0ed6129c75eb6609194bf031480e080c122"
] | [
"test.py"
] | [
"# @Author : bamtercelboo\n# @Datetime : 2018/8/24 15:27\n# @File : test.py\n# @Last Modify Time : 2018/8/24 15:27\n# @Contact : bamtercelboo@{gmail.com, 163.com}\n\n\"\"\"\n FILE : test.py\n FUNCTION : None\n\"\"\"\nimport os\nimport sys\nimport torch\nimport json\nimport numpy as np\nfrom DataUtils.utils import *\n\n\ndef load_test_model(model, config):\n \"\"\"\n :param model: initial model\n :param config: config\n :return: loaded model\n \"\"\"\n if config.t_model is None:\n test_model_dir = config.save_best_model_dir\n test_model_name = \"{}.pt\".format(config.model_name)\n test_model_path = os.path.join(test_model_dir, test_model_name)\n print(\"load default model from {}\".format(test_model_path))\n else:\n test_model_path = config.t_model\n print(\"load user model from {}\".format(test_model_path))\n model.load_state_dict(torch.load(test_model_path))\n return model\n\n\ndef load_test_data(train_iter=None, dev_iter=None, test_iter=None, config=None):\n \"\"\"\n :param train_iter: train data\n :param dev_iter: dev data\n :param test_iter: test data\n :param config: config\n :return: data for test\n \"\"\"\n data, path_source, path_result = None, None, None\n if config.t_data is None:\n print(\"default[test] for model test.\")\n data = test_iter\n sort_path = \"_\".join([config.test_file, \"sort.json\"])\n path_source = sort_path if os.path.exists(sort_path) else config.test_file\n path_result = \"{}_out.json\".format(path_source)\n elif config.t_data == \"train\":\n print(\"train data for model test.\")\n data = train_iter\n sort_path = \"_\".join([config.train_file, \"sort.json\"])\n path_source = sort_path if os.path.exists(sort_path) else config.train_file\n path_result = \"{}_out.json\".format(path_source)\n elif config.t_data == \"dev\":\n print(\"dev data for model test.\")\n data = dev_iter\n sort_path = \"_\".join([config.dev_file, \"sort.json\"])\n path_source = sort_path if os.path.exists(sort_path) else config.dev_file\n path_result = \"{}_out.json\".format(path_source)\n elif config.t_data == \"test\":\n print(\"test data for model test.\")\n data = test_iter\n sort_path = \"_\".join([config.test_file, \"sort.json\"])\n path_source = sort_path if os.path.exists(sort_path) else config.test_file\n path_result = \"{}_out.json\".format(path_source)\n else:\n print(\"Error value --- t_data = {}, must in [None, 'train', 'dev', 'test'].\".format(config.t_data))\n exit()\n return data, path_source, path_result\n\n\nclass Att_Instance(object):\n \"\"\"\n Instance\n \"\"\"\n def __init__(self):\n self.dict = {}\n self.sort_dict = {}\n\n\nclass T_Inference(object):\n \"\"\"\n Test Inference\n \"\"\"\n def __init__(self, model, data, path_source, path_result, alphabet, config):\n \"\"\"\n :param model: nn model\n :param data: infer data\n :param path_source: source data path\n :param path_result: result data path\n :param alphabet: alphabet\n :param config: config\n \"\"\"\n print(\"Initialize T_Inference\")\n self.model = model\n self.data = data\n self.path_source = path_source\n self.path_result = path_result\n self.alphabet = alphabet\n self.config = config\n\n def infer2file(self):\n \"\"\"\n :return: None\n \"\"\"\n print(\"Infer.....\")\n self.model.eval()\n predict_label = []\n att_list_all = []\n all_count = len(self.data)\n now_count = 0\n accusation_count = self.config.accu_class_num\n print(\"accusation count is {}.\".format(accusation_count))\n for data in self.data:\n now_count += 1\n sys.stdout.write(\"\\rInfer with batch number {}/{} .\".format(now_count, all_count))\n # accu, law, prison, e_time, d_time, att_score = self.model(data)\n accu, law, e_time, d_time, att_score = self.model(data)\n att_list = self.get_att_dict(data, att_score)\n att_list_all.extend(att_list)\n predict = getMaxindex_batch(accu.view(accu.size(0) * accu.size(1), -1))\n predict = self._chunks(predict, accusation_count)\n # print(predict)\n for i in range(len(predict)):\n elem_index = self._elem_index(predict[i], e=1)\n accu_label = self._id2label(elem_index)\n predict_label.append(accu_label)\n # print(predict_label)\n print(\"\\nInfer Finished.\")\n self._write2file(result=predict_label, att_list=att_list_all, path_source=self.path_source, path_result=self.path_result)\n\n def get_att_dict(self, data, att_score):\n \"\"\"\n :param data:\n :param att_score:\n :return:\n \"\"\"\n att_score = att_score.view(att_score.size(0), att_score.size(1) * att_score.size(2))\n att_list = []\n for id, inst in enumerate(data.inst):\n # print(inst.fact)\n att_inst = Att_Instance()\n for index, word in enumerate(inst.fact):\n att_inst.dict[word] = att_score[id][index].data.cpu().numpy()[0]\n att_inst.sort_dict = sorted(att_inst.dict.items(), key=lambda d: d[1], reverse=True)\n att_list.append(att_inst)\n\n return att_list\n\n def _id2label(self, elem):\n \"\"\"\n :param elem:\n :return:\n \"\"\"\n return [self.alphabet.accu_label_alphabet.from_id(i) for i in elem]\n\n @staticmethod\n def _chunks(L, n):\n \"\"\"\n :param arr:\n :param n:\n :return:\n \"\"\"\n return [L[i:i + n] for i in range(0, len(L), n)]\n\n @staticmethod\n def _elem_index(L, e):\n \"\"\"\n :param L: list\n :param e:\n :return:\n \"\"\"\n return [i for i, v in enumerate(L) if v == e]\n\n @staticmethod\n def _write2file(result, att_list, path_source, path_result):\n \"\"\"\n :param result:\n :param path_source:\n :param path_result:\n :return:\n \"\"\"\n print(\"write result to file {}\".format(path_result))\n if os.path.exists(path_source) is False:\n print(\"source data path[path_source] is not exist.\")\n if os.path.exists(path_result):\n os.remove(path_result)\n file_out = open(path_result, encoding=\"UTF-8\", mode=\"w\")\n\n with open(path_source, encoding=\"UTF-8\") as file:\n id = 0\n for line in file.readlines():\n sys.stdout.write(\"\\rwrite with {}/{} .\".format(id+1, len(result)))\n w_line = line\n line_json = json.loads(w_line)\n line_json[\"meta\"][\"predict_accu\"] = result[id]\n jsObj = json.dumps(line_json, ensure_ascii=False)\n file_out.write(jsObj + \"\\n\")\n att_dict = att_list[id].dict\n sort_att_dict = att_list[id].sort_dict\n for key, value in att_dict.items():\n file_out.write(\"[\" + key + \":\" + str(np.round(value, 6)) + \"]\\t\")\n file_out.write(\"\\n\")\n for key, value in sort_att_dict:\n file_out.write(\"[\" + key + \":\" + str(np.round(value, 6)) + \"]\\t\")\n file_out.write(\"\\n\")\n file_out.write(\"\\n\")\n id += 1\n if id >= len(result):\n break\n\n file_out.close()\n print(\"\\nFinished.\")\n\n\n\n\n\n\n\n\n"
] | [
[
"numpy.round",
"torch.load"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
DavidXu999/surveyequivalence | [
"83fc7f3095f7d58a32d5624afa8ec83895073277"
] | [
"surveyequivalence/examples/paper_running_example.py"
] | [
"import pandas as pd\nfrom matplotlib import pyplot as plt\n\nfrom surveyequivalence import AgreementScore, PluralityVote, CrossEntropyScore, \\\n AnonymousBayesianCombiner, FrequencyCombiner, \\\n AnalysisPipeline, Plot, ClassifierResults, DiscretePrediction, DiscreteDistributionPrediction\n\ndef main(path = f'data/running_example_50_items', num_bootstrap_item_samples=5, nrows=None):\n\n # read the reference rater labels from file\n if nrows:\n W = pd.read_csv(f\"{path}/ref_rater_labels.csv\", index_col=0, nrows=nrows)\n else:\n W = pd.read_csv(f\"{path}/ref_rater_labels.csv\", index_col=0)\n\n # read the predictions from file\n def str2prediction_instance(s):\n # s will be in format \"Prediction: [0.9, 0.1]\" or \"Prediction: neg\"\n suffix = s.split(\": \")[1]\n if suffix[0] == '[':\n pr_pos, pr_neg = suffix[1:-1].split(',')\n return DiscreteDistributionPrediction(['pos', 'neg'], [float(pr_pos), float(pr_neg)])\n else:\n return DiscretePrediction(suffix)\n\n if nrows:\n classifier_predictions = pd.read_csv(f\"{path}/predictions.csv\", index_col=0, nrows=nrows).applymap(str2prediction_instance)\n else:\n classifier_predictions = pd.read_csv(f\"{path}/predictions.csv\", index_col=0).applymap(str2prediction_instance)\n\n hard_classifiers = classifier_predictions.columns[:1] # ['mock hard classifier']\n soft_classifiers = classifier_predictions.columns[1:] # ['calibrated hard classifier', 'h_infinity: ideal classifier']\n\n color_map = {\n 'expert_power_curve': 'black',\n 'amateur_power_curve': 'green',\n 'mock hard classifier': 'red',\n 'calibrated hard classifier': 'red'\n }\n\n # #### Plurality combiner plus Agreement score ####\n # plurality_combiner = PluralityVote(allowable_labels=['pos', 'neg'])\n # agreement_score = AgreementScore()\n # pipeline = AnalysisPipeline(W,\n # expert_cols=list(W.columns),\n # classifier_predictions=classifier_predictions[hard_classifiers],\n # combiner=plurality_combiner,\n # scorer=agreement_score,\n # allowable_labels=['pos', 'neg'],\n # num_bootstrap_item_samples=num_bootstrap_item_samples,\n # verbosity = 1)\n # pipeline.save(path = pipeline.path_for_saving(\"running_example/plurality_plus_agreement\"),\n # msg = f\"\"\"\n # Running example with {len(W)} items and {len(W.columns)} raters per item\n # {num_bootstrap_item_samples} bootstrap itemsets\n # Plurality combiner with agreement score\n # \"\"\")\n #\n # fig, ax = plt.subplots()\n # fig.set_size_inches(8.5, 10.5)\n #\n #\n #\n # pl = Plot(ax,\n # pipeline.expert_power_curve,\n # classifier_scores=pipeline.classifier_scores,\n # color_map=color_map,\n # y_axis_label='percent agreement with reference rater',\n # y_range=(0, 1),\n # name='running example: majority vote + agreement score',\n # legend_label='k raters',\n # generate_pgf=True\n # )\n #\n # pl.plot(include_classifiers=True,\n # include_classifier_equivalences=True,\n # include_droplines=True,\n # include_expert_points='all',\n # connect_expert_points=True,\n # include_classifier_cis=True\n # )\n # pl.save(pipeline.path_for_saving(\"running_example/plurality_plus_agreement\"), fig=fig)\n\n #### ABC + CrossEntropy\n abc = AnonymousBayesianCombiner(allowable_labels=['pos', 'neg'])\n cross_entropy = CrossEntropyScore()\n # Here we set anonymous_raters to True, so that we will compute expected score against a randomly selected\n # rater for each item, rather than against a randomly selected column\n pipeline2 = AnalysisPipeline(W,\n expert_cols=list(W.columns),\n classifier_predictions=classifier_predictions[soft_classifiers],\n combiner=abc,\n scorer=cross_entropy,\n allowable_labels=['pos', 'neg'],\n num_bootstrap_item_samples=num_bootstrap_item_samples,\n anonymous_raters=True,\n verbosity = 1,\n procs=1)\n\n pipeline2.save(path=pipeline2.path_for_saving(\"running_example/abc_plus_cross_entropy\"),\n msg = f\"\"\"\n Running example with {len(W)} items and {len(W.columns)} raters per item\n {num_bootstrap_item_samples} bootstrap itemsets\n Anonymous Bayesian combiner with cross entropy score\n \"\"\")\n\n fig, ax = plt.subplots()\n fig.set_size_inches(8.5, 10.5)\n\n pl = Plot(ax,\n pipeline2.expert_power_curve,\n classifier_scores=ClassifierResults(pipeline2.classifier_scores.df[['calibrated hard classifier']]),\n color_map=color_map,\n y_axis_label='information gain ($c_k - c_0$)',\n center_on=pipeline2.expert_power_curve.values[0],\n y_range=(0, 0.4),\n name='running example: ABC + cross entropy',\n legend_label='k raters',\n generate_pgf=True\n )\n\n pl.plot(include_classifiers=True,\n include_classifier_equivalences=True,\n include_droplines=True,\n include_expert_points='all',\n connect_expert_points=True,\n include_classifier_cis=True\n )\n pl.save(path=pipeline2.path_for_saving(\"running_example/abc_plus_cross_entropy\"), fig=fig)\n\n # ###### Frequency combiner plus cross entropy ######\n # freq_combiner = FrequencyCombiner(allowable_labels=['pos', 'neg'])\n # pipeline3 = AnalysisPipeline(W,\n # expert_cols=list(W.columns),\n # classifier_predictions=classifier_predictions[soft_classifiers],\n # combiner=freq_combiner,\n # scorer=cross_entropy,\n # allowable_labels=['pos', 'neg'],\n # num_bootstrap_item_samples=num_bootstrap_item_samples,\n # verbosity = 1)\n #\n # pipeline3.save(path=pipeline.path_for_saving(\"running_example/frequency_plus_cross_entropy\"),\n # msg = f\"\"\"\n # Running example with {len(W)} items and {len(W.columns)} raters per item\n # {num_bootstrap_item_samples} bootstrap itemsets\n # frequency combiner with cross entropy score\n # \"\"\")\n\n\nif __name__ == '__main__':\n main(path = 'data/running_example', nrows=50)"
] | [
[
"pandas.read_csv",
"matplotlib.pyplot.subplots"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
Kartikey0412/epilespy_regression_predictions | [
"ec467fe5b93b948d62ef67e223f22b3939c7f63f"
] | [
"src/data/epilepsy_preprocess.py"
] | [
"#In this code we have preprocessed the epilepsy dataset before buidling the prediciton pipeline. We select the\n#desired features, and ascertain that contionus variables are numeric. Categorical varialbes have been binary encoded\n#or one-hot encoded. We have define a 80 - 20% train- test split for the model. #Imputation is done using sklearn\n#preproccessing using mean value for continous data and most-frequent value for categorical data.\n\n\nimport pandas as pd\nimport numpy as np\nimport random\nimport re\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import LabelBinarizer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.preprocessing import Imputer\n\n#Read csv into pandas data frame\n\n\ne = pd.read_csv(\"epilepsy.csv\")\n\nel = pd.DataFrame(list(e))\n\n#Remove eid column and second year variable columns except Number of Emergency visits in Year 2\n\nl = list(range(1,7)) + list(range(10,20)) + [27,29] + list(range(31,39)) + list(range(47,89))\n\ne2 = e.iloc[:,l]\n\n#checking data types\n\ne2df = pd.DataFrame(e2.dtypes)\n\n#any age like '>90' has been taken as 90\ne2['AgeAtFirstVisit'][e2['AgeAtFirstVisit'].str.match('\\d+\\D') == True] = \"90\"\n\ne2['AgeAtFirstVisit'] = pd.to_numeric(e2['AgeAtFirstVisit'])\n\n#Categorical gender and geo\nprint(e2['Gender'].value_counts())\nprint(e2['Gender'].value_counts())\n\n#Remove unknown Gender\n\ne2 = e2[e2['Gender'] != 'U']\n\n\n#Binary encode Gender\ne2.Gender[e2.Gender == 'M'] = 0\ne2.Gender[e2.Gender == 'F'] = 1\ne2['Gender'] = e2['Gender'].astype('category')\n\n\n#One-hot encode geo\n\nlb = LabelBinarizer()\n\nlb_geo = lb.fit_transform(e2['geo'])\nlb_geo_df = pd.DataFrame(lb_results, columns=lb.classes_)\n\n#print(lb_results_df.head())\n\ne3 = pd.concat([e2, lb_results_df], axis=1)\n\n\n#removing redundant columns\ne4 = e3.drop(['geo'], axis =1)\n#e4 = e4.drop(['ERNum_ptyr2'], axis =1)\ne4 = e4[pd.notnull(e4['ERNum_ptyr2'])]\n\n#x,y\ny = e4['ERNum_ptyr2']\nx = e4.drop(['ERNum_ptyr2'], axis = 1)\n\n#test-train split\n\nxtrain, xtest, ytrain, ytest = train_test_split(x, y, test_size = 0.2)\n\n#Missing data impute using mean values\n\n#Continous train set\nxtrdf = pd.DataFrame(xtrain.dtypes)\nxtrdf['counter'] = range(len(xtrdf))\nlcon = [0] + list(range(5,32)) + [65]\nlcat = list(range(1,5)) + list(range(32,65)) + list(range(66,77))\nxtrcon = xtrain.iloc[:,lcon]\nxtrcat = xtrain.iloc[:,lcat]\n\nnull_data = x[x.isnull().any(axis=1)]\n\n#Imputations mean value for continous data\nmean_imputer_con = Imputer(missing_values='NaN', strategy='mean', axis=0)\nmean_imputer = mean_imputer_con.fit(xtrcon)\nimputed_xtrcon = mean_imputer.transform(xtrcon)\nimputed_xtrcon_df = pd.DataFrame(imputed_xtrcon, columns = xtrcon.columns)\n\n#Imputing most frequent value for categorical data\nfreq_imputer_cat = Imputer(missing_values='NaN', strategy='most_frequent', axis=0)\nfreq_imputer = freq_imputer_cat.fit(xtrcat)\nimputed_xtrcat = freq_imputer.transform(xtrcat)\nimputed_xtrcat_df = pd.DataFrame(imputed_xtrcat, columns = xtrcat.columns)\n\ncol_cat_names = list(imputed_xtrcat_df)\n\nfor col in col_cat_names:\n imputed_xtrcat_df[col] = imputed_xtrcat_df[col].astype('category',copy=False)\n#xtris = pd.DataFrame(StandardScaler().fit_transform(xtri))\n\n#Normalizing the continous data\n\nimputed_xtrcon_norm = Normalizer().fit_transform(imputed_xtrcon_df)\nimputed_xtrcon_norm_df = pd.DataFrame(imputed_xtrcon_norm, columns = imputed_xtrcon_df.columns)\n\n\nxtrin = pd.concat([imputed_xtrcon_norm_df, imputed_xtrcat_df], axis=1)\nxtrin.to_csv(\"epilepsy_preprocess_imputed_scaledcontinouse_0405.csv\")\n\n\nxtest_nm = xtest.drop([7130, 8038])\n\n#Normalizing testing data\nxtest_nmn = Normalizer().fit_transform(xtest_nm)\nxtest_nmn = pd.DataFrame(xtest_nmn, columns = xtest_nm.columns)\n\n#pandas index 8038, 7130 is null\nytest_nm = ytest.drop([7130, 8038])\n\nxtrin.to_csv(\"xtrin_final.csv\")\nytrain.to_csv(\"ytrain_final.csv\")\nxtest_nm.to_csv(\"xtest_final.csv\")\nytest_nm.to_csv(\"ytest_final.csv\")\n\n#Unnorlmalized data\nxtri = pd.concat([imputed_xtrcon_df, imputed_xtrcat_df],axis =1)\nxtri.to_csv(\"epilepsy_preprocess_imputed_0406.csv\")"
] | [
[
"pandas.concat",
"pandas.read_csv",
"pandas.notnull",
"sklearn.model_selection.train_test_split",
"pandas.DataFrame",
"sklearn.preprocessing.Imputer",
"sklearn.preprocessing.LabelBinarizer",
"pandas.to_numeric"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
ruohoruotsi/pyACA | [
"339e9395b65a217aa5965638af941b32d5c95454"
] | [
"pyACA/FeatureSpectralTonalPowerRatio.py"
] | [
"# -*- coding: utf-8 -*-\n\"\"\"\ncomputes the tonal power ratio from the magnitude spectrum\n\n Args:\n X: spectrogram (dimension FFTLength X Observations)\n f_s: sample rate of audio data\n G_T: energy threshold\n\n Returns:\n vtpr tonal power ratio\n\"\"\"\n\nimport numpy as np\nfrom scipy.signal import find_peaks\n\n\ndef FeatureSpectralTonalPowerRatio(X, f_s, G_T=5e-4):\n\n isSpectrum = X.ndim == 1\n if isSpectrum:\n X = np.expand_dims(X, axis=1)\n\n X = X**2\n\n fSum = X.sum(axis=0)\n vtpr = np.zeros(fSum.shape)\n\n for n in range(0, X.shape[1]):\n if fSum[n] < G_T:\n continue\n\n # find local maxima above the threshold\n afPeaks = find_peaks(X[:, n], height=G_T)\n\n if not afPeaks[0].size:\n continue\n\n # calculate ratio\n vtpr[n] = X[afPeaks[0], n].sum() / fSum[n]\n\n return np.squeeze(vtpr) if isSpectrum else vtpr\n"
] | [
[
"numpy.squeeze",
"numpy.expand_dims",
"numpy.zeros",
"scipy.signal.find_peaks"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.6",
"1.10",
"1.4",
"1.9",
"1.5",
"1.2",
"1.7",
"1.3",
"1.8"
],
"tensorflow": []
}
] |
josepic99/mesas | [
"8453fe36b8536795ce5b80975fc9dbc604da42df"
] | [
"examples/Flockers/flockers/model.py"
] | [
"'''\nFlockers\n=============================================================\nA Mesa implementation of Craig Reynolds's Boids flocker model.\nUses numpy arrays to represent vectors.\n'''\n\n\nimport random\nimport numpy as np\n\nfrom mesa import Model\nfrom mesa.space import ContinuousSpace\nfrom mesa.time import RandomActivation\n\nfrom .boid import Boid\n\n\nclass BoidModel(Model):\n '''\n Flocker model class. Handles agent creation, placement and scheduling.\n '''\n\n def __init__(self, N, width, height, speed, vision, separation):\n '''\n Create a new Flockers model.\n\n Args:\n N: Number of Boids\n width, height: Size of the space.\n speed: How fast should the Boids move.\n vision: How far around should each Boid look for its neighbors\n separtion: What's the minimum distance each Boid will attempt to\n keep from any other\n '''\n self.N = N\n self.vision = vision\n self.speed = speed\n self.separation = separation\n self.schedule = RandomActivation(self)\n self.space = ContinuousSpace(width, height, True,\n grid_width=10, grid_height=10)\n self.make_agents()\n self.running = True\n\n def make_agents(self):\n '''\n Create N agents, with random positions and starting headings.\n '''\n for i in range(self.N):\n x = random.random() * self.space.x_max\n y = random.random() * self.space.y_max\n pos = (x, y)\n heading = np.random.random(2) * 2 - np.array((1, 1))\n heading /= np.linalg.norm(heading)\n boid = Boid(i, self, pos, self.speed, heading, self.vision,\n self.separation)\n self.space.place_agent(boid, pos)\n self.schedule.add(boid)\n\n def step(self):\n self.schedule.step()\n"
] | [
[
"numpy.array",
"numpy.random.random",
"numpy.linalg.norm"
]
] | [
{
"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": []
}
] |
SebMilardo/osmnx | [
"b304cd4be13a4aa2435328f045a7c83815576b86"
] | [
"osmnx/core.py"
] | [
"################################################################################\n# Module: core.py\n# Description: Retrieve and construct spatial geometries and street networks\n# from OpenStreetMap\n# License: MIT, see full license in LICENSE.txt\n# Web: https://github.com/gboeing/osmnx\n################################################################################\n\nimport geopandas as gpd\nimport logging as lg\nimport math\nimport networkx as nx\nimport numpy as np\nimport pandas as pd\nimport time\n\nfrom itertools import groupby\nfrom shapely.geometry import LineString\nfrom shapely.geometry import MultiPolygon\nfrom shapely.geometry import Point\nfrom shapely.geometry import Polygon\nfrom shapely.ops import unary_union\n\nfrom . import settings\nfrom .projection import project_geometry\nfrom .projection import project_gdf\nfrom .simplify import simplify_graph\nfrom .utils import make_str, log\nfrom .geo_utils import get_largest_component\nfrom .utils import great_circle_vec\nfrom .geo_utils import get_nearest_node\nfrom .geo_utils import geocode\nfrom .geo_utils import count_streets_per_node\nfrom .geo_utils import overpass_json_from_file\nfrom .downloader import osm_polygon_download\nfrom .downloader import get_osm_filter\nfrom .downloader import overpass_request\nfrom .errors import *\n\n\ndef gdf_from_place(query, gdf_name=None, which_result=1, buffer_dist=None):\n \"\"\"\n Create a GeoDataFrame from a single place name query.\n\n Parameters\n ----------\n query : string or dict\n query string or structured query dict to geocode/download\n gdf_name : string\n name attribute metadata for GeoDataFrame (this is used to save shapefile\n later)\n which_result : int\n max number of results to return and which to process upon receipt\n buffer_dist : float\n distance to buffer around the place geometry, in meters\n\n Returns\n -------\n GeoDataFrame\n \"\"\"\n # if no gdf_name is passed, just use the query\n assert (isinstance(query, dict) or isinstance(query, str)), 'query must be a dict or a string'\n if (gdf_name is None) and isinstance(query, dict):\n gdf_name = ', '.join(list(query.values()))\n elif (gdf_name is None) and isinstance(query, str):\n gdf_name = query\n\n # get the data from OSM\n data = osm_polygon_download(query, limit=which_result)\n if len(data) >= which_result:\n\n # extract data elements from the JSON response\n result = data[which_result - 1]\n bbox_south, bbox_north, bbox_west, bbox_east = [float(x) for x in result['boundingbox']]\n geometry = result['geojson']\n place = result['display_name']\n features = [{'type': 'Feature',\n 'geometry': geometry,\n 'properties': {'place_name': place,\n 'bbox_north': bbox_north,\n 'bbox_south': bbox_south,\n 'bbox_east': bbox_east,\n 'bbox_west': bbox_west}}]\n\n # if we got an unexpected geometry type (like a point), log a warning\n if geometry['type'] not in ['Polygon', 'MultiPolygon']:\n log('OSM returned a {} as the geometry.'.format(geometry['type']), level=lg.WARNING)\n\n # create the GeoDataFrame, name it, and set its original CRS to default_crs\n gdf = gpd.GeoDataFrame.from_features(features)\n gdf.gdf_name = gdf_name\n gdf.crs = settings.default_crs\n\n # if buffer_dist was passed in, project the geometry to UTM, buffer it\n # in meters, then project it back to lat-long\n if buffer_dist is not None:\n gdf_utm = project_gdf(gdf)\n gdf_utm['geometry'] = gdf_utm['geometry'].buffer(buffer_dist)\n gdf = project_gdf(gdf_utm, to_latlong=True)\n log('Buffered the GeoDataFrame \"{}\" to {} meters'.format(gdf.gdf_name, buffer_dist))\n\n # return the gdf\n log('Created GeoDataFrame with {} row for query \"{}\"'.format(len(gdf), query))\n return gdf\n else:\n # if there was no data returned (or fewer results than which_result\n # specified)\n log('OSM returned no results (or fewer than which_result) for query \"{}\"'.format(query), level=lg.WARNING)\n gdf = gpd.GeoDataFrame()\n gdf.gdf_name = gdf_name\n return gdf\n\n\ndef gdf_from_places(queries, gdf_name='unnamed', buffer_dist=None, which_results=None):\n \"\"\"\n Create a GeoDataFrame from a list of place names to query.\n\n Parameters\n ----------\n queries : list\n list of query strings or structured query dicts to geocode/download, one\n at a time\n gdf_name : string\n name attribute metadata for GeoDataFrame (this is used to save shapefile\n later)\n buffer_dist : float\n distance to buffer around the place geometry, in meters\n which_results : list\n if not None, a list of max number of results to return and which to process\n upon receipt, for each query in queries\n\n Returns\n -------\n GeoDataFrame\n \"\"\"\n # create an empty GeoDataFrame then append each result as a new row, checking for the presence of which_results\n gdf = gpd.GeoDataFrame()\n if which_results is not None:\n assert len(queries) == len(which_results), 'which_results list length must be the same as queries list length'\n for query, which_result in zip(queries, which_results):\n gdf = gdf.append(gdf_from_place(query, buffer_dist=buffer_dist, which_result=which_result))\n else:\n for query in queries:\n gdf = gdf.append(gdf_from_place(query, buffer_dist=buffer_dist))\n\n # reset the index, name the GeoDataFrame\n gdf = gdf.reset_index().drop(labels='index', axis=1)\n gdf.gdf_name = gdf_name\n\n # set the original CRS of the GeoDataFrame to default_crs, and return it\n gdf.crs = settings.default_crs\n log('Finished creating GeoDataFrame with {} rows from {} queries'.format(len(gdf), len(queries)))\n return gdf\n\n\ndef osm_net_download(polygon=None, north=None, south=None, east=None, west=None,\n network_type='all_private', timeout=180, memory=None,\n max_query_area_size=50*1000*50*1000, infrastructure='way[\"highway\"]',\n custom_filter=None, custom_settings=None):\n \"\"\"\n Download OSM ways and nodes within some bounding box from the Overpass API.\n\n Parameters\n ----------\n polygon : shapely Polygon or MultiPolygon\n geographic shape to fetch the street network within\n north : float\n northern latitude of bounding box\n south : float\n southern latitude of bounding box\n east : float\n eastern longitude of bounding box\n west : float\n western longitude of bounding box\n network_type : string\n {'walk', 'bike', 'drive', 'drive_service', 'all', 'all_private'} what\n type of street network to get\n timeout : int\n the timeout interval for requests and to pass to API\n memory : int\n server memory allocation size for the query, in bytes. If none, server\n will use its default allocation size\n max_query_area_size : float\n max area for any part of the geometry, in the units the geometry is in:\n any polygon bigger will get divided up for multiple queries to API\n (default is 50,000 * 50,000 units [ie, 50km x 50km in area, if units are\n meters])\n infrastructure : string\n download infrastructure of given type. default is streets, ie,\n 'way[\"highway\"]') but other infrastructures may be selected like power\n grids, ie, 'way[\"power\"~\"line\"]'\n custom_filter : string\n a custom network filter to be used instead of the network_type presets\n custom_settings : string\n custom settings to be used in the overpass query instead of the default\n ones\n\n Returns\n -------\n response_jsons : list\n \"\"\"\n\n # check if we're querying by polygon or by bounding box based on which\n # argument(s) where passed into this function\n by_poly = polygon is not None\n by_bbox = not (north is None or south is None or east is None or west is None)\n if not (by_poly or by_bbox):\n raise InsufficientNetworkQueryArguments(\n 'You must pass a polygon or north, south, east, and west')\n\n # create a filter to exclude certain kinds of ways based on the requested\n # network_type\n if custom_filter:\n osm_filter = custom_filter\n else:\n osm_filter = get_osm_filter(network_type)\n response_jsons = []\n\n # pass server memory allocation in bytes for the query to the API\n # if None, pass nothing so the server will use its default allocation size\n # otherwise, define the query's maxsize parameter value as whatever the\n # caller passed in\n if memory is None:\n maxsize = ''\n else:\n maxsize = '[maxsize:{}]'.format(memory)\n\n # use custom settings if delivered, otherwise just the default ones.\n if custom_settings:\n overpass_settings = custom_settings\n else:\n overpass_settings = settings.default_overpass_query_settings.format(timeout=timeout, maxsize=maxsize)\n\n # define the query to send the API\n # specifying way[\"highway\"] means that all ways returned must have a highway\n # key. the {filters} then remove ways by key/value. the '>' makes it recurse\n # so we get ways and way nodes. maxsize is in bytes.\n if by_bbox:\n # turn bbox into a polygon and project to local UTM\n polygon = Polygon([(west, south), (east, south), (east, north), (west, north)])\n geometry_proj, crs_proj = project_geometry(polygon)\n\n # subdivide it if it exceeds the max area size (in meters), then project\n # back to lat-long\n geometry_proj_consolidated_subdivided = consolidate_subdivide_geometry(geometry_proj, max_query_area_size=max_query_area_size)\n geometry, _ = project_geometry(geometry_proj_consolidated_subdivided, crs=crs_proj, to_latlong=True)\n log('Requesting network data within bounding box from API in {:,} request(s)'.format(len(geometry)))\n start_time = time.time()\n\n # loop through each polygon rectangle in the geometry (there will only\n # be one if original bbox didn't exceed max area size)\n for poly in geometry:\n # represent bbox as south,west,north,east and round lat-longs to 6\n # decimal places (ie, ~100 mm) so URL strings aren't different\n # due to float rounding issues (for consistent caching)\n west, south, east, north = poly.bounds\n query_template = '{settings};({infrastructure}{filters}({south:.6f},{west:.6f},{north:.6f},{east:.6f});>;);out;'\n query_str = query_template.format(north=north, south=south,\n east=east, west=west,\n infrastructure=infrastructure,\n filters=osm_filter,\n settings=overpass_settings)\n response_json = overpass_request(data={'data':query_str}, timeout=timeout)\n response_jsons.append(response_json)\n log('Got all network data within bounding box from API in {:,} request(s) and {:,.2f} seconds'.format(len(geometry), time.time()-start_time))\n\n elif by_poly:\n # project to utm, divide polygon up into sub-polygons if area exceeds a\n # max size (in meters), project back to lat-long, then get a list of\n # polygon(s) exterior coordinates\n geometry_proj, crs_proj = project_geometry(polygon)\n geometry_proj_consolidated_subdivided = consolidate_subdivide_geometry(geometry_proj, max_query_area_size=max_query_area_size)\n geometry, _ = project_geometry(geometry_proj_consolidated_subdivided, crs=crs_proj, to_latlong=True)\n polygon_coord_strs = get_polygons_coordinates(geometry)\n log('Requesting network data within polygon from API in {:,} request(s)'.format(len(polygon_coord_strs)))\n start_time = time.time()\n\n # pass each polygon exterior coordinates in the list to the API, one at\n # a time\n for polygon_coord_str in polygon_coord_strs:\n query_template = '{settings};({infrastructure}{filters}(poly:\"{polygon}\");>;);out;'\n query_str = query_template.format(polygon=polygon_coord_str,\n infrastructure=infrastructure,\n filters=osm_filter,\n settings=overpass_settings)\n response_json = overpass_request(data={'data':query_str}, timeout=timeout)\n response_jsons.append(response_json)\n log('Got all network data within polygon from API in {:,} request(s) and {:,.2f} seconds'.format(len(polygon_coord_strs), time.time()-start_time))\n\n return response_jsons\n\n\ndef consolidate_subdivide_geometry(geometry, max_query_area_size):\n \"\"\"\n Consolidate a geometry into a convex hull, then subdivide it into smaller sub-polygons if its area exceeds max size (in geometry's units).\n\n Parameters\n ----------\n geometry : shapely Polygon or MultiPolygon\n the geometry to consolidate and subdivide\n max_query_area_size : float\n max area for any part of the geometry, in the units the geometry is in.\n any polygon bigger will get divided up for multiple queries to API (\n default is 50,000 * 50,000 units (ie, 50km x 50km in area, if units are meters))\n\n Returns\n -------\n geometry : Polygon or MultiPolygon\n \"\"\"\n\n # let the linear length of the quadrats (with which to subdivide the\n # geometry) be the square root of max area size\n quadrat_width = math.sqrt(max_query_area_size)\n\n if not isinstance(geometry, (Polygon, MultiPolygon)):\n raise TypeError('Geometry must be a shapely Polygon or MultiPolygon')\n\n # if geometry is a MultiPolygon OR a single Polygon whose area exceeds the\n # max size, get the convex hull around the geometry\n if isinstance(geometry, MultiPolygon) or (isinstance(geometry, Polygon) and geometry.area > max_query_area_size):\n geometry = geometry.convex_hull\n\n # if geometry area exceeds max size, subdivide it into smaller sub-polygons\n if geometry.area > max_query_area_size:\n geometry = quadrat_cut_geometry(geometry, quadrat_width=quadrat_width)\n\n if isinstance(geometry, Polygon):\n geometry = MultiPolygon([geometry])\n\n return geometry\n\n\ndef get_polygons_coordinates(geometry):\n \"\"\"\n Extract exterior coordinates from polygon(s) to pass to OSM in a query by\n polygon. Ignore the interior (\"holes\") coordinates.\n\n Parameters\n ----------\n geometry : shapely Polygon or MultiPolygon\n the geometry to extract exterior coordinates from\n\n Returns\n -------\n polygon_coord_strs : list\n \"\"\"\n\n # extract the exterior coordinates of the geometry to pass to the API later\n polygons_coords = []\n if isinstance(geometry, Polygon):\n x, y = geometry.exterior.xy\n polygons_coords.append(list(zip(x, y)))\n elif isinstance(geometry, MultiPolygon):\n for polygon in geometry:\n x, y = polygon.exterior.xy\n polygons_coords.append(list(zip(x, y)))\n else:\n raise TypeError('Geometry must be a shapely Polygon or MultiPolygon')\n\n # convert the exterior coordinates of the polygon(s) to the string format\n # the API expects\n polygon_coord_strs = []\n for coords in polygons_coords:\n s = ''\n separator = ' '\n for coord in list(coords):\n # round floating point lats and longs to 6 decimal places (ie, ~100 mm),\n # so we can hash and cache strings consistently\n s = '{}{}{:.6f}{}{:.6f}'.format(s, separator, coord[1], separator, coord[0])\n polygon_coord_strs.append(s.strip(separator))\n\n return polygon_coord_strs\n\n\ndef get_node(element):\n \"\"\"\n Convert an OSM node element into the format for a networkx node.\n\n Parameters\n ----------\n element : dict\n an OSM node element\n\n Returns\n -------\n dict\n \"\"\"\n\n node = {}\n node['y'] = element['lat']\n node['x'] = element['lon']\n node['osmid'] = element['id']\n if 'tags' in element:\n for useful_tag in settings.useful_tags_node:\n if useful_tag in element['tags']:\n node[useful_tag] = element['tags'][useful_tag]\n return node\n\n\ndef get_path(element):\n \"\"\"\n Convert an OSM way element into the format for a networkx graph path.\n\n Parameters\n ----------\n element : dict\n an OSM way element\n\n Returns\n -------\n dict\n \"\"\"\n\n path = {}\n path['osmid'] = element['id']\n\n # remove any consecutive duplicate elements in the list of nodes\n grouped_list = groupby(element['nodes'])\n path['nodes'] = [group[0] for group in grouped_list]\n\n if 'tags' in element:\n for useful_tag in settings.useful_tags_path:\n if useful_tag in element['tags']:\n path[useful_tag] = element['tags'][useful_tag]\n return path\n\n\ndef parse_osm_nodes_paths(osm_data):\n \"\"\"\n Construct dicts of nodes and paths with key=osmid and value=dict of\n attributes.\n\n Parameters\n ----------\n osm_data : dict\n JSON response from from the Overpass API\n\n Returns\n -------\n nodes, paths : tuple\n \"\"\"\n\n nodes = {}\n paths = {}\n for element in osm_data['elements']:\n if element['type'] == 'node':\n key = element['id']\n nodes[key] = get_node(element)\n elif element['type'] == 'way': #osm calls network paths 'ways'\n key = element['id']\n paths[key] = get_path(element)\n\n return nodes, paths\n\n\ndef remove_isolated_nodes(G):\n \"\"\"\n Remove from a graph all the nodes that have no incident edges (ie, node\n degree = 0).\n\n Parameters\n ----------\n G : networkx multidigraph\n the graph from which to remove nodes\n\n Returns\n -------\n networkx multidigraph\n \"\"\"\n\n isolated_nodes = [node for node, degree in dict(G.degree()).items() if degree < 1]\n G.remove_nodes_from(isolated_nodes)\n log('Removed {:,} isolated nodes'.format(len(isolated_nodes)))\n return G\n\n\ndef truncate_graph_dist(G, source_node, max_distance=1000, weight='length', retain_all=False):\n \"\"\"\n Remove everything further than some network distance from a specified node\n in graph.\n\n Parameters\n ----------\n G : networkx multidigraph\n source_node : int\n the node in the graph from which to measure network distances to other\n nodes\n max_distance : int\n remove every node in the graph greater than this distance from the\n source_node\n weight : string\n how to weight the graph when measuring distance (default 'length' is\n how many meters long the edge is)\n retain_all : bool\n if True, return the entire graph even if it is not connected\n\n Returns\n -------\n networkx multidigraph\n \"\"\"\n\n # get the shortest distance between the node and every other node, then\n # remove every node further than max_distance away\n start_time = time.time()\n G = G.copy()\n distances = nx.shortest_path_length(G, source=source_node, weight=weight)\n distant_nodes = {key:value for key, value in dict(distances).items() if value > max_distance}\n G.remove_nodes_from(distant_nodes.keys())\n log('Truncated graph by weighted network distance in {:,.2f} seconds'.format(time.time()-start_time))\n\n # remove any isolated nodes and retain only the largest component (if\n # retain_all is True)\n if not retain_all:\n G = remove_isolated_nodes(G)\n G = get_largest_component(G)\n\n return G\n\n\ndef truncate_graph_bbox(G, north, south, east, west, truncate_by_edge=False, retain_all=False):\n \"\"\"\n Remove every node in graph that falls outside a bounding box.\n\n Needed because overpass returns entire ways that also include nodes outside\n the bbox if the way (that is, a way with a single OSM ID) has a node inside\n the bbox at some point.\n\n Parameters\n ----------\n G : networkx multidigraph\n north : float\n northern latitude of bounding box\n south : float\n southern latitude of bounding box\n east : float\n eastern longitude of bounding box\n west : float\n western longitude of bounding box\n truncate_by_edge : bool\n if True retain node if it's outside bbox but at least one of node's\n neighbors are within bbox\n retain_all : bool\n if True, return the entire graph even if it is not connected\n\n Returns\n -------\n networkx multidigraph\n \"\"\"\n\n start_time = time.time()\n G = G.copy()\n nodes_outside_bbox = []\n\n for node, data in G.nodes(data=True):\n if data['y'] > north or data['y'] < south or data['x'] > east or data['x'] < west:\n # this node is outside the bounding box\n if not truncate_by_edge:\n # if we're not truncating by edge, add node to list of nodes\n # outside the bounding box\n nodes_outside_bbox.append(node)\n else:\n # if we're truncating by edge, see if any of node's neighbors\n # are within bounding box\n any_neighbors_in_bbox = False\n neighbors = list(G.successors(node)) + list(G.predecessors(node))\n for neighbor in neighbors:\n x = G.nodes[neighbor]['x']\n y = G.nodes[neighbor]['y']\n if y < north and y > south and x < east and x > west:\n any_neighbors_in_bbox = True\n break\n\n # if none of its neighbors are within the bounding box, add node\n # to list of nodes outside the bounding box\n if not any_neighbors_in_bbox:\n nodes_outside_bbox.append(node)\n\n G.remove_nodes_from(nodes_outside_bbox)\n log('Truncated graph by bounding box in {:,.2f} seconds'.format(time.time()-start_time))\n\n # remove any isolated nodes and retain only the largest component (if\n # retain_all is True)\n if not retain_all:\n G = remove_isolated_nodes(G)\n G = get_largest_component(G)\n\n return G\n\n\ndef quadrat_cut_geometry(geometry, quadrat_width, min_num=3, buffer_amount=1e-9):\n \"\"\"\n Split a Polygon or MultiPolygon up into sub-polygons of a specified size,\n using quadrats.\n\n Parameters\n ----------\n geometry : shapely Polygon or MultiPolygon\n the geometry to split up into smaller sub-polygons\n quadrat_width : numeric\n the linear width of the quadrats with which to cut up the geometry (in\n the units the geometry is in)\n min_num : int\n the minimum number of linear quadrat lines (e.g., min_num=3 would\n produce a quadrat grid of 4 squares)\n buffer_amount : numeric\n buffer the quadrat grid lines by quadrat_width times buffer_amount\n\n Returns\n -------\n shapely MultiPolygon\n \"\"\"\n\n # create n evenly spaced points between the min and max x and y bounds\n west, south, east, north = geometry.bounds\n x_num = math.ceil((east-west) / quadrat_width) + 1\n y_num = math.ceil((north-south) / quadrat_width) + 1\n x_points = np.linspace(west, east, num=max(x_num, min_num))\n y_points = np.linspace(south, north, num=max(y_num, min_num))\n\n # create a quadrat grid of lines at each of the evenly spaced points\n vertical_lines = [LineString([(x, y_points[0]), (x, y_points[-1])]) for x in x_points]\n horizont_lines = [LineString([(x_points[0], y), (x_points[-1], y)]) for y in y_points]\n lines = vertical_lines + horizont_lines\n\n # buffer each line to distance of the quadrat width divided by 1 billion,\n # take their union, then cut geometry into pieces by these quadrats\n buffer_size = quadrat_width * buffer_amount\n lines_buffered = [line.buffer(buffer_size) for line in lines]\n quadrats = unary_union(lines_buffered)\n multipoly = geometry.difference(quadrats)\n\n return multipoly\n\n\ndef intersect_index_quadrats(gdf, geometry, quadrat_width=0.05, min_num=3, buffer_amount=1e-9):\n \"\"\"\n Intersect points with a polygon, using an r-tree spatial index and cutting\n the polygon up into smaller sub-polygons for r-tree acceleration.\n\n Parameters\n ----------\n gdf : GeoDataFrame\n the set of points to intersect\n geometry : shapely Polygon or MultiPolygon\n the geometry to intersect with the points\n quadrat_width : numeric\n the linear length (in degrees) of the quadrats with which to cut up the\n geometry (default = 0.05, approx 4km at NYC's latitude)\n min_num : int\n the minimum number of linear quadrat lines (e.g., min_num=3 would\n produce a quadrat grid of 4 squares)\n buffer_amount : numeric\n buffer the quadrat grid lines by quadrat_width times buffer_amount\n\n Returns\n -------\n GeoDataFrame\n \"\"\"\n\n # create an empty dataframe to append matches to\n points_within_geometry = pd.DataFrame()\n\n # cut the geometry into chunks for r-tree spatial index intersecting\n multipoly = quadrat_cut_geometry(geometry, quadrat_width=quadrat_width, buffer_amount=buffer_amount, min_num=min_num)\n\n # create an r-tree spatial index for the nodes (ie, points)\n start_time = time.time()\n sindex = gdf['geometry'].sindex\n log('Created r-tree spatial index for {:,} points in {:,.2f} seconds'.format(len(gdf), time.time()-start_time))\n\n # loop through each chunk of the geometry to find approximate and then\n # precisely intersecting points\n start_time = time.time()\n for poly in multipoly:\n\n # buffer by the tiny distance to account for any space lost in the\n # quadrat cutting, otherwise may miss point(s) that lay directly on\n # quadrat line\n buffer_size = quadrat_width * buffer_amount\n poly = poly.buffer(buffer_size).buffer(0)\n\n # find approximate matches with r-tree, then precise matches from those\n # approximate ones\n if poly.is_valid and poly.area > 0:\n possible_matches_index = list(sindex.intersection(poly.bounds))\n possible_matches = gdf.iloc[possible_matches_index]\n precise_matches = possible_matches[possible_matches.intersects(poly)]\n points_within_geometry = points_within_geometry.append(precise_matches)\n\n if len(points_within_geometry) > 0:\n # drop duplicate points, if buffered poly caused an overlap on point(s)\n # that lay directly on a quadrat line\n points_within_geometry = points_within_geometry.drop_duplicates(subset='node')\n else:\n # after simplifying the graph, and given the requested network type,\n # there are no nodes inside the polygon - can't create graph from that\n # so throw error\n raise Exception('There are no nodes within the requested geometry')\n\n log('Identified {:,} nodes inside polygon in {:,.2f} seconds'.format(len(points_within_geometry), time.time()-start_time))\n return points_within_geometry\n\n\ndef truncate_graph_polygon(G, polygon, retain_all=False, truncate_by_edge=False, quadrat_width=0.05, min_num=3, buffer_amount=1e-9):\n \"\"\"\n Remove every node in graph that falls outside some shapely Polygon or\n MultiPolygon.\n\n Parameters\n ----------\n G : networkx multidigraph\n polygon : Polygon or MultiPolygon\n only retain nodes in graph that lie within this geometry\n retain_all : bool\n if True, return the entire graph even if it is not connected\n truncate_by_edge : bool\n if True retain node if it's outside polygon but at least one of node's\n neighbors are within polygon\n quadrat_width : numeric\n passed on to intersect_index_quadrats: the linear length (in degrees) of\n the quadrats with which to cut up the geometry (default = 0.05, approx\n 4km at NYC's latitude)\n min_num : int\n passed on to intersect_index_quadrats: the minimum number of linear\n quadrat lines (e.g., min_num=3 would produce a quadrat grid of 4\n squares)\n buffer_amount : numeric\n passed on to intersect_index_quadrats: buffer the quadrat grid lines by\n quadrat_width times buffer_amount\n\n Returns\n -------\n networkx multidigraph\n \"\"\"\n\n start_time = time.time()\n G = G.copy()\n log('Identifying all nodes that lie outside the polygon...')\n\n # get a GeoDataFrame of all the nodes\n node_geom = [Point(data['x'], data['y']) for _, data in G.nodes(data=True)]\n gdf_nodes = gpd.GeoDataFrame({'node':list(G.nodes()), 'geometry':node_geom})\n gdf_nodes.crs = G.graph['crs']\n\n # find all the nodes in the graph that lie outside the polygon\n points_within_geometry = intersect_index_quadrats(gdf_nodes, polygon, quadrat_width=quadrat_width, min_num=min_num, buffer_amount=buffer_amount)\n nodes_outside_polygon = gdf_nodes[~gdf_nodes.index.isin(points_within_geometry.index)]\n\n if truncate_by_edge:\n nodes_to_remove = []\n for node in nodes_outside_polygon['node']:\n neighbors = pd.Series(list(G.successors(node)) + list(G.predecessors(node)))\n # check if all the neighbors of this node also lie outside polygon\n if neighbors.isin(nodes_outside_polygon['node']).all():\n nodes_to_remove.append(node)\n else:\n nodes_to_remove = nodes_outside_polygon['node']\n\n # now remove from the graph all those nodes that lie outside the place\n # polygon\n start_time = time.time()\n G.remove_nodes_from(nodes_to_remove)\n log('Removed {:,} nodes outside polygon in {:,.2f} seconds'.format(len(nodes_outside_polygon), time.time()-start_time))\n\n # remove any isolated nodes and retain only the largest component (if retain_all is False)\n if not retain_all:\n G = remove_isolated_nodes(G)\n G = get_largest_component(G)\n\n return G\n\n\ndef add_edge_lengths(G):\n \"\"\"\n Add length (meters) attribute to each edge by great circle distance between\n nodes u and v.\n\n Parameters\n ----------\n G : networkx multidigraph\n\n Returns\n -------\n G : networkx multidigraph\n \"\"\"\n\n start_time = time.time()\n\n # first load all the edges' origin and destination coordinates as a\n # dataframe indexed by u, v, key\n coords = np.array([[u, v, k, G.nodes[u]['y'], G.nodes[u]['x'], G.nodes[v]['y'], G.nodes[v]['x']] for u, v, k in G.edges(keys=True)])\n df_coords = pd.DataFrame(coords, columns=['u', 'v', 'k', 'u_y', 'u_x', 'v_y', 'v_x'])\n df_coords[['u', 'v', 'k']] = df_coords[['u', 'v', 'k']].astype(np.int64)\n df_coords = df_coords.set_index(['u', 'v', 'k'])\n\n # then calculate the great circle distance with the vectorized function\n gc_distances = great_circle_vec(lat1=df_coords['u_y'],\n lng1=df_coords['u_x'],\n lat2=df_coords['v_y'],\n lng2=df_coords['v_x'])\n\n # fill nulls with zeros and round to the millimeter\n gc_distances = gc_distances.fillna(value=0).round(3)\n nx.set_edge_attributes(G, name='length', values=gc_distances.to_dict())\n\n log('Added edge lengths to graph in {:,.2f} seconds'.format(time.time()-start_time))\n return G\n\n\ndef add_path(G, data, one_way):\n \"\"\"\n Add a path to the graph.\n\n Parameters\n ----------\n G : networkx multidigraph\n data : dict\n the attributes of the path\n one_way : bool\n if this path is one-way or if it is bi-directional\n\n Returns\n -------\n None\n \"\"\"\n\n # extract the ordered list of nodes from this path element, then delete it\n # so we don't add it as an attribute to the edge later\n path_nodes = data['nodes']\n del data['nodes']\n\n # set the oneway attribute to the passed-in value, to make it consistent\n # True/False values, but only do this if you aren't forcing all edges to\n # oneway with the all_oneway setting. With the all_oneway setting, you\n # likely still want to preserve the original OSM oneway attribute.\n if not settings.all_oneway:\n data['oneway'] = one_way\n\n # zip together the path nodes so you get tuples like (0,1), (1,2), (2,3)\n # and so on\n path_edges = list(zip(path_nodes[:-1], path_nodes[1:]))\n G.add_edges_from(path_edges, **data)\n\n # if the path is NOT one-way\n if not one_way:\n # reverse the direction of each edge and add this path going the\n # opposite direction\n path_edges_opposite_direction = [(v, u) for u, v in path_edges]\n G.add_edges_from(path_edges_opposite_direction, **data)\n\n\ndef add_paths(G, paths, bidirectional=False):\n \"\"\"\n Add a collection of paths to the graph.\n\n Parameters\n ----------\n G : networkx multidigraph\n paths : dict\n the paths from OSM\n bidirectional : bool\n if True, create bidirectional edges for one-way streets\n\n\n Returns\n -------\n None\n \"\"\"\n\n # the list of values OSM uses in its 'oneway' tag to denote True\n # updated list of of values OSM uses based on https://www.geofabrik.de/de/data/geofabrik-osm-gis-standard-0.7.pdf \n osm_oneway_values = ['yes', 'true', '1', '-1', 'T', 'F']\n\n for data in paths.values():\n\n if settings.all_oneway is True:\n add_path(G, data, one_way=True)\n # if this path is tagged as one-way and if it is not a walking network,\n # then we'll add the path in one direction only\n elif ('oneway' in data and data['oneway'] in osm_oneway_values) and not bidirectional:\n if data['oneway'] == '-1' or data['oneway'] == 'T':\n # paths with a one-way value of -1 or T are one-way, but in the\n # reverse direction of the nodes' order, see osm documentation \n data['nodes'] = list(reversed(data['nodes']))\n # add this path (in only one direction) to the graph\n add_path(G, data, one_way=True)\n\n elif ('junction' in data and data['junction'] == 'roundabout') and not bidirectional:\n # roundabout are also oneway but not tagged as is\n add_path(G, data, one_way=True)\n\n # else, this path is not tagged as one-way or it is a walking network\n # (you can walk both directions on a one-way street)\n else:\n # add this path (in both directions) to the graph and set its\n # 'oneway' attribute to False. if this is a walking network, this\n # may very well be a one-way street (as cars/bikes go), but in a\n # walking-only network it is a bi-directional edge\n add_path(G, data, one_way=False)\n\n return G\n\n\ndef create_graph(response_jsons, name='unnamed', retain_all=False, bidirectional=False):\n \"\"\"\n Create a networkx graph from Overpass API HTTP response objects.\n\n Parameters\n ----------\n response_jsons : list\n list of dicts of JSON responses from from the Overpass API\n name : string\n the name of the graph\n retain_all : bool\n if True, return the entire graph even if it is not connected\n bidirectional : bool\n if True, create bidirectional edges for one-way streets\n\n Returns\n -------\n networkx multidigraph\n \"\"\"\n\n log('Creating networkx graph from downloaded OSM data...')\n start_time = time.time()\n\n # make sure we got data back from the server requests\n elements = []\n for response_json in response_jsons:\n elements.extend(response_json['elements'])\n if len(elements) < 1:\n raise EmptyOverpassResponse('There are no data elements in the response JSON objects')\n\n # create the graph as a MultiDiGraph and set the original CRS to default_crs\n G = nx.MultiDiGraph(name=name, crs=settings.default_crs)\n\n # extract nodes and paths from the downloaded osm data\n nodes = {}\n paths = {}\n for osm_data in response_jsons:\n nodes_temp, paths_temp = parse_osm_nodes_paths(osm_data)\n for key, value in nodes_temp.items():\n nodes[key] = value\n for key, value in paths_temp.items():\n paths[key] = value\n\n # add each osm node to the graph\n for node, data in nodes.items():\n G.add_node(node, **data)\n\n # add each osm way (aka, path) to the graph\n G = add_paths(G, paths, bidirectional=bidirectional)\n\n # retain only the largest connected component, if caller did not\n # set retain_all=True\n if not retain_all:\n G = get_largest_component(G)\n\n log('Created graph with {:,} nodes and {:,} edges in {:,.2f} seconds'.format(len(list(G.nodes())), len(list(G.edges())), time.time()-start_time))\n\n # add length (great circle distance between nodes) attribute to each edge to\n # use as weight\n if len(G.edges) > 0:\n G = add_edge_lengths(G)\n\n return G\n\n\ndef bbox_from_point(point, distance=1000, project_utm=False, return_crs=False):\n \"\"\"\n Create a bounding box some distance in each direction (north, south, east,\n and west) from some (lat, lng) point.\n\n Parameters\n ----------\n point : tuple\n the (lat, lon) point to create the bounding box around\n distance : int\n how many meters the north, south, east, and west sides of the box should\n each be from the point\n project_utm : bool\n if True return bbox as UTM coordinates\n return_crs : bool\n if True and project_utm=True, return the projected CRS\n\n Returns\n -------\n north, south, east, west : tuple, if return_crs=False\n north, south, east, west, crs_proj : tuple, if return_crs=True\n \"\"\"\n\n # reverse the order of the (lat,lng) point so it is (x,y) for shapely, then\n # project to UTM and buffer in meters\n lat, lng = point\n point_proj, crs_proj = project_geometry(Point((lng, lat)))\n buffer_proj = point_proj.buffer(distance)\n\n if project_utm:\n west, south, east, north = buffer_proj.bounds\n log('Created bounding box {} meters in each direction from {} and projected it: {},{},{},{}'.format(distance, point, north, south, east, west))\n else:\n # if project_utm is False, project back to lat-long then get the\n # bounding coordinates\n buffer_latlong, _ = project_geometry(buffer_proj, crs=crs_proj, to_latlong=True)\n west, south, east, north = buffer_latlong.bounds\n log('Created bounding box {} meters in each direction from {}: {},{},{},{}'.format(distance, point, north, south, east, west))\n\n if return_crs:\n return north, south, east, west, crs_proj\n else:\n return north, south, east, west\n\n\ndef graph_from_bbox(north, south, east, west, network_type='all_private',\n simplify=True, retain_all=False, truncate_by_edge=False,\n name='unnamed', timeout=180, memory=None,\n max_query_area_size=50*1000*50*1000, clean_periphery=True,\n infrastructure='way[\"highway\"]', custom_filter=None,\n custom_settings=None):\n \"\"\"\n Create a networkx graph from OSM data within some bounding box.\n\n Parameters\n ----------\n north : float\n northern latitude of bounding box\n south : float\n southern latitude of bounding box\n east : float\n eastern longitude of bounding box\n west : float\n western longitude of bounding box\n network_type : string\n what type of street network to get\n simplify : bool\n if true, simplify the graph topology\n retain_all : bool\n if True, return the entire graph even if it is not connected\n truncate_by_edge : bool\n if True retain node if it's outside bbox but at least one of node's\n neighbors are within bbox\n name : string\n the name of the graph\n timeout : int\n the timeout interval for requests and to pass to API\n memory : int\n server memory allocation size for the query, in bytes. If none, server\n will use its default allocation size\n max_query_area_size : float\n max size for any part of the geometry, in square degrees: any polygon\n bigger will get divided up for multiple queries to API\n clean_periphery : bool\n if True (and simplify=True), buffer 0.5km to get a graph larger than\n requested, then simplify, then truncate it to requested spatial extent\n infrastructure : string\n download infrastructure of given type (default is streets (ie, 'way[\"highway\"]') but other\n infrastructures may be selected like power grids (ie, 'way[\"power\"~\"line\"]'))\n custom_filter : string\n a custom network filter to be used instead of the network_type presets\n custom_settings : string\n custom settings to be used in the overpass query instead of the default\n ones\n\n Returns\n -------\n networkx multidigraph\n \"\"\"\n\n if clean_periphery and simplify:\n # create a new buffered bbox 0.5km around the desired one\n buffer_dist = 500\n polygon = Polygon([(west, north), (west, south), (east, south), (east, north)])\n polygon_utm, crs_utm = project_geometry(geometry=polygon)\n polygon_proj_buff = polygon_utm.buffer(buffer_dist)\n polygon_buff, _ = project_geometry(geometry=polygon_proj_buff, crs=crs_utm, to_latlong=True)\n west_buffered, south_buffered, east_buffered, north_buffered = polygon_buff.bounds\n\n # get the network data from OSM then create the graph\n response_jsons = osm_net_download(north=north_buffered, south=south_buffered,\n east=east_buffered, west=west_buffered,\n network_type=network_type, timeout=timeout,\n memory=memory, max_query_area_size=max_query_area_size,\n infrastructure=infrastructure, custom_filter=custom_filter,\n custom_settings=custom_settings)\n G_buffered = create_graph(response_jsons, name=name, retain_all=retain_all,\n bidirectional=network_type in settings.bidirectional_network_types)\n G = truncate_graph_bbox(G_buffered, north, south, east, west, retain_all=True, truncate_by_edge=truncate_by_edge)\n\n # simplify the graph topology\n G_buffered = simplify_graph(G_buffered)\n\n # truncate graph by desired bbox to return the graph within the bbox\n # caller wants\n G = truncate_graph_bbox(G_buffered, north, south, east, west, retain_all=retain_all, truncate_by_edge=truncate_by_edge)\n\n # count how many street segments in buffered graph emanate from each\n # intersection in un-buffered graph, to retain true counts for each\n # intersection, even if some of its neighbors are outside the bbox\n G.graph['streets_per_node'] = count_streets_per_node(G_buffered, nodes=G.nodes())\n\n else:\n # get the network data from OSM\n response_jsons = osm_net_download(north=north, south=south, east=east,\n west=west, network_type=network_type,\n timeout=timeout, memory=memory,\n max_query_area_size=max_query_area_size,\n infrastructure=infrastructure, custom_filter=custom_filter,\n custom_settings=custom_settings)\n\n # create the graph, then truncate to the bounding box\n G = create_graph(response_jsons, name=name, retain_all=retain_all,\n bidirectional=network_type in settings.bidirectional_network_types)\n G = truncate_graph_bbox(G, north, south, east, west, retain_all=retain_all, truncate_by_edge=truncate_by_edge)\n\n # simplify the graph topology as the last step. don't truncate after\n # simplifying or you may have simplified out to an endpoint\n # beyond the truncation distance, in which case you will then strip out\n # your entire edge\n if simplify:\n G = simplify_graph(G)\n\n log('graph_from_bbox() returning graph with {:,} nodes and {:,} edges'.format(len(list(G.nodes())), len(list(G.edges()))))\n return G\n\n\ndef graph_from_point(center_point, distance=1000, distance_type='bbox',\n network_type='all_private', simplify=True, retain_all=False,\n truncate_by_edge=False, name='unnamed', timeout=180,\n memory=None, max_query_area_size=50*1000*50*1000,\n clean_periphery=True, infrastructure='way[\"highway\"]',\n custom_filter=None, custom_settings=None):\n \"\"\"\n Create a networkx graph from OSM data within some distance of some (lat,\n lon) center point.\n\n Parameters\n ----------\n center_point : tuple\n the (lat, lon) central point around which to construct the graph\n distance : int\n retain only those nodes within this many meters of the center of the\n graph, with distance determined according to distance_type argument\n distance_type : string\n {'network', 'bbox'} if 'bbox', retain only those nodes within a bounding\n box of the distance parameter. if 'network', retain only those nodes\n within some network distance from the center-most node.\n network_type : string\n what type of street network to get\n simplify : bool\n if true, simplify the graph topology\n retain_all : bool\n if True, return the entire graph even if it is not connected\n truncate_by_edge : bool\n if True retain node if it's outside bbox but at least one of node's\n neighbors are within bbox\n name : string\n the name of the graph\n timeout : int\n the timeout interval for requests and to pass to API\n memory : int\n server memory allocation size for the query, in bytes. If none, server\n will use its default allocation size\n max_query_area_size : float\n max size for any part of the geometry, in square degrees: any polygon\n bigger will get divided up for multiple queries to API\n clean_periphery : bool,\n if True (and simplify=True), buffer 0.5km to get a graph larger than\n requested, then simplify, then truncate it to requested spatial extent\n infrastructure : string\n download infrastructure of given type (default is streets (ie, 'way[\"highway\"]') but other\n infrastructures may be selected like power grids (ie, 'way[\"power\"~\"line\"]'))\n custom_filter : string\n a custom network filter to be used instead of the network_type presets\n custom_settings : string\n custom settings to be used in the overpass query instead of the default\n ones\n\n Returns\n -------\n networkx multidigraph\n \"\"\"\n\n if distance_type not in ['bbox', 'network']:\n raise InvalidDistanceType('distance_type must be \"bbox\" or \"network\"')\n\n # create a bounding box from the center point and the distance in each\n # direction\n north, south, east, west = bbox_from_point(center_point, distance)\n\n # create a graph from the bounding box\n G = graph_from_bbox(north, south, east, west, network_type=network_type, simplify=simplify,\n retain_all=retain_all, truncate_by_edge=truncate_by_edge, name=name,\n timeout=timeout, memory=memory, max_query_area_size=max_query_area_size,\n clean_periphery=clean_periphery, infrastructure=infrastructure,\n custom_filter=custom_filter, custom_settings=custom_settings)\n\n # if the network distance_type is network, find the node in the graph\n # nearest to the center point, and truncate the graph by network distance\n # from this node\n if distance_type == 'network':\n centermost_node = get_nearest_node(G, center_point)\n G = truncate_graph_dist(G, centermost_node, max_distance=distance)\n\n log('graph_from_point() returning graph with {:,} nodes and {:,} edges'.format(len(list(G.nodes())), len(list(G.edges()))))\n return G\n\n\ndef graph_from_address(address, distance=1000, distance_type='bbox',\n network_type='all_private', simplify=True, retain_all=False,\n truncate_by_edge=False, return_coords=False,\n name='unnamed', timeout=180, memory=None,\n max_query_area_size=50*1000*50*1000,\n clean_periphery=True, infrastructure='way[\"highway\"]',\n custom_filter=None, custom_settings=None):\n \"\"\"\n Create a networkx graph from OSM data within some distance of some address.\n\n Parameters\n ----------\n address : string\n the address to geocode and use as the central point around which to\n construct the graph\n distance : int\n retain only those nodes within this many meters of the center of the\n graph\n distance_type : string\n {'network', 'bbox'} if 'bbox', retain only those nodes within a bounding\n box of the distance parameter.\n if 'network', retain only those nodes within some network distance from\n the center-most node.\n network_type : string\n what type of street network to get\n simplify : bool\n if true, simplify the graph topology\n retain_all : bool\n if True, return the entire graph even if it is not connected\n truncate_by_edge : bool\n if True retain node if it's outside bbox but at least one of node's\n neighbors are within bbox\n return_coords : bool\n optionally also return the geocoded coordinates of the address\n name : string\n the name of the graph\n timeout : int\n the timeout interval for requests and to pass to API\n memory : int\n server memory allocation size for the query, in bytes. If none, server\n will use its default allocation size\n max_query_area_size\n float, max size for any part of the geometry, in square degrees: any\n polygon bigger will get divided up for multiple queries to API\n clean_periphery : bool,\n if True (and simplify=True), buffer 0.5km to get a graph larger than\n requested, then simplify, then truncate it to requested spatial extent\n infrastructure : string\n download infrastructure of given type (default is streets (ie, 'way[\"highway\"]') but other\n infrastructures may be selected like power grids (ie, 'way[\"power\"~\"line\"]'))\n custom_filter : string\n a custom network filter to be used instead of the network_type presets\n custom_settings : string\n custom settings to be used in the overpass query instead of the default\n ones\n\n Returns\n -------\n networkx multidigraph or tuple\n multidigraph or optionally (multidigraph, tuple)\n \"\"\"\n\n # geocode the address string to a (lat, lon) point\n point = geocode(query=address)\n\n # then create a graph from this point\n G = graph_from_point(point, distance, distance_type, network_type=network_type,\n simplify=simplify, retain_all=retain_all, truncate_by_edge=truncate_by_edge,\n name=name, timeout=timeout, memory=memory,\n max_query_area_size=max_query_area_size,\n clean_periphery=clean_periphery, infrastructure=infrastructure,\n custom_filter=custom_filter, custom_settings=custom_settings)\n log('graph_from_address() returning graph with {:,} nodes and {:,} edges'.format(len(list(G.nodes())), len(list(G.edges()))))\n\n if return_coords:\n return G, point\n else:\n return G\n\n\ndef graph_from_polygon(polygon, network_type='all_private', simplify=True,\n retain_all=False, truncate_by_edge=False, name='unnamed',\n timeout=180, memory=None,\n max_query_area_size=50*1000*50*1000,\n clean_periphery=True, infrastructure='way[\"highway\"]',\n custom_filter=None, custom_settings=None):\n \"\"\"\n Create a networkx graph from OSM data within the spatial boundaries of the\n passed-in shapely polygon.\n\n Parameters\n ----------\n polygon : shapely Polygon or MultiPolygon\n the shape to get network data within. coordinates should be in units of\n latitude-longitude degrees.\n network_type : string\n what type of street network to get\n simplify : bool\n if true, simplify the graph topology\n retain_all : bool\n if True, return the entire graph even if it is not connected\n truncate_by_edge : bool\n if True retain node if it's outside bbox but at least one of node's\n neighbors are within bbox\n name : string\n the name of the graph\n timeout : int\n the timeout interval for requests and to pass to API\n memory : int\n server memory allocation size for the query, in bytes. If none, server\n will use its default allocation size\n max_query_area_size : float\n max size for any part of the geometry, in square degrees: any polygon\n bigger will get divided up for multiple queries to API\n clean_periphery : bool\n if True (and simplify=True), buffer 0.5km to get a graph larger than\n requested, then simplify, then truncate it to requested spatial extent\n infrastructure : string\n download infrastructure of given type (default is streets\n (ie, 'way[\"highway\"]') but other infrastructures may be selected\n like power grids (ie, 'way[\"power\"~\"line\"]'))\n custom_filter : string\n a custom network filter to be used instead of the network_type presets\n custom_settings : string\n custom settings to be used in the overpass query instead of the default\n ones\n\n Returns\n -------\n networkx multidigraph\n \"\"\"\n\n # verify that the geometry is valid and is a shapely Polygon/MultiPolygon\n # before proceeding\n if not polygon.is_valid:\n raise TypeError('Shape does not have a valid geometry')\n if not isinstance(polygon, (Polygon, MultiPolygon)):\n raise TypeError('Geometry must be a shapely Polygon or MultiPolygon. If you requested '\n 'graph from place name or address, make sure your query resolves to a '\n 'Polygon or MultiPolygon, and not some other geometry, like a Point. '\n 'See OSMnx documentation for details.')\n\n if clean_periphery and simplify:\n # create a new buffered polygon 0.5km around the desired one\n buffer_dist = 500\n polygon_utm, crs_utm = project_geometry(geometry=polygon)\n polygon_proj_buff = polygon_utm.buffer(buffer_dist)\n polygon_buffered, _ = project_geometry(geometry=polygon_proj_buff, crs=crs_utm, to_latlong=True)\n\n # get the network data from OSM, create the buffered graph, then\n # truncate it to the buffered polygon\n response_jsons = osm_net_download(polygon=polygon_buffered, network_type=network_type,\n timeout=timeout, memory=memory,\n max_query_area_size=max_query_area_size,\n infrastructure=infrastructure, custom_filter=custom_filter,\n custom_settings=custom_settings)\n G_buffered = create_graph(response_jsons, name=name, retain_all=True,\n bidirectional=network_type in settings.bidirectional_network_types)\n G_buffered = truncate_graph_polygon(G_buffered, polygon_buffered, retain_all=True, truncate_by_edge=truncate_by_edge)\n\n # simplify the graph topology\n G_buffered = simplify_graph(G_buffered)\n\n # truncate graph by polygon to return the graph within the polygon that\n # caller wants. don't simplify again - this allows us to retain\n # intersections along the street that may now only connect 2 street\n # segments in the network, but in reality also connect to an\n # intersection just outside the polygon\n G = truncate_graph_polygon(G_buffered, polygon, retain_all=retain_all, truncate_by_edge=truncate_by_edge)\n\n # count how many street segments in buffered graph emanate from each\n # intersection in un-buffered graph, to retain true counts for each\n # intersection, even if some of its neighbors are outside the polygon\n G.graph['streets_per_node'] = count_streets_per_node(G_buffered, nodes=G.nodes())\n\n else:\n # download a list of API responses for the polygon/multipolygon\n response_jsons = osm_net_download(polygon=polygon, network_type=network_type,\n timeout=timeout, memory=memory,\n max_query_area_size=max_query_area_size,\n infrastructure=infrastructure, custom_filter=custom_filter,\n custom_settings=custom_settings)\n\n # create the graph from the downloaded data\n G = create_graph(response_jsons, name=name, retain_all=True,\n bidirectional=network_type in settings.bidirectional_network_types)\n\n # truncate the graph to the extent of the polygon\n G = truncate_graph_polygon(G, polygon, retain_all=retain_all, truncate_by_edge=truncate_by_edge)\n\n # simplify the graph topology as the last step. don't truncate after\n # simplifying or you may have simplified out to an endpoint beyond the\n # truncation distance, in which case you will then strip out your entire\n # edge\n if simplify:\n G = simplify_graph(G)\n\n log('graph_from_polygon() returning graph with {:,} nodes and {:,} edges'.format(len(list(G.nodes())), len(list(G.edges()))))\n return G\n\n\ndef graph_from_place(query, network_type='all_private', simplify=True,\n retain_all=False, truncate_by_edge=False, name='unnamed',\n which_result=1, buffer_dist=None, timeout=180, memory=None,\n max_query_area_size=50*1000*50*1000, clean_periphery=True,\n infrastructure='way[\"highway\"]', custom_filter=None,\n custom_settings=None):\n \"\"\"\n Create a networkx graph from OSM data within the spatial boundaries of some\n geocodable place(s).\n\n The query must be geocodable and OSM must have polygon boundaries for the\n geocode result. If OSM does not have a polygon for this place, you can\n instead get its street network using the graph_from_address function, which\n geocodes the place name to a point and gets the network within some distance\n of that point. Alternatively, you might try to vary the which_result\n parameter to use a different geocode result. For example, the first geocode\n result (ie, the default) might resolve to a point geometry, but the second\n geocode result for this query might resolve to a polygon, in which case you\n can use graph_from_place with which_result=2.\n\n Parameters\n ----------\n query : string or dict or list\n the place(s) to geocode/download data for\n network_type : string\n what type of street network to get\n simplify : bool\n if true, simplify the graph topology\n retain_all : bool\n if True, return the entire graph even if it is not connected\n truncate_by_edge : bool\n if True retain node if it's outside bbox but at least one of node's\n neighbors are within bbox\n name : string\n the name of the graph\n which_result : int\n max number of results to return and which to process upon receipt\n buffer_dist : float\n distance to buffer around the place geometry, in meters\n timeout : int\n the timeout interval for requests and to pass to API\n memory : int\n server memory allocation size for the query, in bytes. If none, server\n will use its default allocation size\n max_query_area_size : float\n max size for any part of the geometry, in square degrees: any polygon\n bigger will get divided up for multiple queries to API\n clean_periphery : bool\n if True (and simplify=True), buffer 0.5km to get a graph larger than\n requested, then simplify, then truncate it to requested spatial extent\n infrastructure : string\n download infrastructure of given type (default is streets (ie, 'way[\"highway\"]') but other\n infrastructures may be selected like power grids (ie, 'way[\"power\"~\"line\"]'))\n custom_filter : string\n a custom network filter to be used instead of the network_type presets\n custom_settings : string\n custom settings to be used in the overpass query instead of the default\n ones\n Returns\n -------\n networkx multidigraph\n \"\"\"\n\n # create a GeoDataFrame with the spatial boundaries of the place(s)\n if isinstance(query, str) or isinstance(query, dict):\n # if it is a string (place name) or dict (structured place query), then\n # it is a single place\n gdf_place = gdf_from_place(query, which_result=which_result, buffer_dist=buffer_dist)\n name = query\n elif isinstance(query, list):\n # if it is a list, it contains multiple places to get\n gdf_place = gdf_from_places(query, buffer_dist=buffer_dist)\n else:\n raise TypeError('query must be a string or a list of query strings')\n\n # extract the geometry from the GeoDataFrame to use in API query\n polygon = gdf_place['geometry'].unary_union\n log('Constructed place geometry polygon(s) to query API')\n\n # create graph using this polygon(s) geometry\n G = graph_from_polygon(polygon, network_type=network_type, simplify=simplify,\n retain_all=retain_all, truncate_by_edge=truncate_by_edge,\n name=name, timeout=timeout, memory=memory,\n max_query_area_size=max_query_area_size,\n clean_periphery=clean_periphery, infrastructure=infrastructure,\n custom_filter=custom_filter, custom_settings=custom_settings)\n\n log('graph_from_place() returning graph with {:,} nodes and {:,} edges'.format(len(list(G.nodes())), len(list(G.edges()))))\n return G\n\n\ndef graph_from_file(filename, bidirectional=False, simplify=True,\n retain_all=False, name='unnamed'):\n \"\"\"\n Create a networkx graph from OSM data in an XML file.\n\n Parameters\n ----------\n filename : string\n the name of a file containing OSM XML data\n bidirectional : bool\n if True, create bidirectional edges for one-way streets\n simplify : bool\n if True, simplify the graph topology\n retain_all : bool\n if True, return the entire graph even if it is not connected\n name : string\n the name of the graph\n\n Returns\n -------\n networkx multidigraph\n \"\"\"\n # transmogrify file of OSM XML data into JSON\n response_jsons = [overpass_json_from_file(filename)]\n\n # create graph using this response JSON\n G = create_graph(response_jsons, bidirectional=bidirectional,\n retain_all=retain_all, name=name)\n\n # simplify the graph topology as the last step.\n if simplify:\n G = simplify_graph(G)\n\n log('graph_from_file() returning graph with {:,} nodes and {:,} edges'.format(len(list(G.nodes())), len(list(G.edges()))))\n return G\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": []
}
] |
Icetalon21/Data-Science | [
"05eea4a027b194b3cfb5ddae5f0640ddcd44c5c7"
] | [
"PCA.py"
] | [
"import numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom sklearn import datasets as skdata\n\n#We will use the iris dataset\niris_dataset = skdata.load_iris()\nX = iris_dataset.data # (150, 4)\ny = iris_dataset.target\n\n#Compute the mean\nmu = np.mean(X, axis=0)\n\n#Center the data\nB = X - mu\n\n#Compute the covariance matrix\nC = np.matmul(B.T, B)/(B.shape[0]) #(4, 150) x (150, 4) => (4, 4)\n\n#Eigen decomposition\nS, V = np.linalg.eig(C)\n\n#Select the top 3 dimentions\norder = np.argsort(S)[::-1]\nW = V[:, order][:, 0:3] #Transformation for projecting X to subspace\n\n#Project our data\nZ = np.matmul(B, W) #(150, 3)\n\n#Let's visualize our new feature space\ndata_split = (Z[np.where(y==0)[0], :], Z[np.where(y==1)[0], :], Z[np.where(y==2)[0], :])\ncolors = ('blue', 'red', 'green')\nlabels = ('Setosa', 'Versicolor', 'Virginica')\nmarkers = ('o', '^', '+')\n\nfig = plt.figure()\nfig.suptitle('Projected Iris Data')\nax = fig.add_subplot(1, 1, 1, projection='3d')\nax.set_xlabel('PC1')\nax.set_ylabel('PC2')\nax.set_zlabel('PC3')\n\nfor z, c, l, m in zip(data_split, colors, labels, markers):\n ax.scatter(z[:, 0], z[:, 1], z[:, 2], c=c, label=l, marker=m)\n ax.legend(loc='upper right')\n\nplt.show()\n\n#Recover our data\nX_hat = np.matmul(Z, W.T)+mu\nmse = np.mean((X-X_hat)**2) #0.005919048088406607\n\n#Seems like we recovered our data pretty well\n#Let's instead choose only two dimentions\nW_2 = V[:, 0:2] #Transformation for projecting X to subspace\n\n#Project our data\nZ_2 = np.matmul(B, W_2)\n\nX_hat_2 = np.matmul(Z_2, W_2.T)+mu\nmse = np.mean((X-X_hat_2)**2) # 0.02534107393239825\n\n#As we reduce more dimentions, we lose more information\n"
] | [
[
"numpy.linalg.eig",
"sklearn.datasets.load_iris",
"numpy.matmul",
"numpy.mean",
"numpy.argsort",
"matplotlib.pyplot.show",
"numpy.where",
"matplotlib.pyplot.figure"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
zhanghang1989/autogluon-legacy | [
"8638fb6a71947161bdd4f6876cc7ad035229c95b"
] | [
"autogluon/core/decorator.py"
] | [
"import copy\nimport logging\nimport argparse\nimport functools\nfrom collections import OrderedDict\nimport numpy as np\nimport multiprocessing as mp\nimport ConfigSpace as CS\n\nfrom .space import *\nfrom .space import _add_hp, _add_cs, _rm_hp, _strip_config_space\nfrom ..utils import EasyDict as ezdict\nfrom ..utils.deprecate import make_deprecate\n\n__all__ = ['args', 'obj', 'func', 'sample_config',\n 'autogluon_register_args', 'autogluon_object', 'autogluon_function',\n 'autogluon_register_dict']\n\nlogger = logging.getLogger(__name__)\n\ndef sample_config(args, config):\n args = copy.deepcopy(args)\n striped_keys = [k.split('.')[0] for k in config.keys()]\n if isinstance(args, (argparse.Namespace, argparse.ArgumentParser)):\n args_dict = vars(args)\n else:\n args_dict = args\n for k, v in args_dict.items():\n # handle different type of configurations\n if k in striped_keys:\n if isinstance(v, NestedSpace):\n sub_config = _strip_config_space(config, prefix=k)\n args_dict[k] = v.sample(**sub_config)\n else:\n if '.' in k: continue\n args_dict[k] = config[k]\n elif isinstance(v, AutoGluonObject):\n args_dict[k] = v.init()\n return args\n\nclass _autogluon_method(object):\n SEED = mp.Value('i', 0)\n LOCK = mp.Lock()\n def __init__(self, f):\n self.f = f\n self.args = ezdict()\n functools.update_wrapper(self, f)\n\n def __call__(self, args, config, **kwargs):\n new_config = copy.deepcopy(config)\n self._rand_seed()\n args = sample_config(args, new_config)\n from ..scheduler.reporter import FakeReporter\n if 'reporter' not in kwargs:\n logger.debug('Creating FakeReporter for test purpose.')\n kwargs['reporter'] = FakeReporter()\n\n output = self.f(args, **kwargs)\n logger.debug('Reporter Done!')\n kwargs['reporter'](done=True)\n return output\n \n def register_args(self, default={}, **kwvars):\n if isinstance(default, (argparse.Namespace, argparse.ArgumentParser)):\n default = vars(default)\n self.kwvars = {}\n self.args = ezdict()\n self.args.update(default)\n self.update(**kwvars)\n\n def update(self, **kwargs):\n \"\"\"For searcher support ConfigSpace\n \"\"\"\n self.kwvars.update(kwargs)\n for k, v in self.kwvars.items():\n if isinstance(v, (NestedSpace)):\n self.args.update({k: v})\n elif isinstance(v, Space):\n hp = v.get_hp(name=k)\n self.args.update({k: hp.default_value})\n else:\n self.args.update({k: v})\n\n @property\n def cs(self):\n cs = CS.ConfigurationSpace()\n for k, v in self.kwvars.items():\n if isinstance(v, NestedSpace):\n _add_cs(cs, v.cs, k)\n elif isinstance(v, Space):\n hp = v.get_hp(name=k)\n _add_hp(cs, hp)\n else:\n _rm_hp(cs, k)\n return cs\n\n @property\n def kwspaces(self):\n \"\"\"For RL searcher/controller\n \"\"\"\n kw_spaces = OrderedDict()\n for k, v in self.kwvars.items():\n if isinstance(v, NestedSpace):\n if isinstance(v, Categorical):\n kw_spaces['{}.choice'.format(k)] = v\n for sub_k, sub_v in v.kwspaces.items():\n new_k = '{}.{}'.format(k, sub_k)\n kw_spaces[new_k] = sub_v\n elif isinstance(v, Space):\n kw_spaces[k] = v\n return kw_spaces\n\n def _rand_seed(self):\n _autogluon_method.SEED.value += 1\n np.random.seed(_autogluon_method.SEED.value)\n\n def __repr__(self):\n return repr(self.f)\n\n\ndef args(default={}, **kwvars):\n \"\"\"Decorator for customized training script, registering arguments or searchable spaces\n to the decorated function. The arguments should be python built-in objects,\n autogluon objects (see :func:`autogluon.obj`_ .), or autogluon search spaces\n (:class:`autogluon.space.Int`, :class:`autogluon.space.Real` ...).\n\n Example:\n >>> @ag.args(batch_size=10, lr=ag.Real(0.01, 0.1))\n >>> def my_train(args):\n ... print('Batch size is {}, LR is {}'.format(args.batch_size, arg.lr))\n\n \"\"\"\n kwvars['_default_config'] = default\n def registered_func(func):\n @_autogluon_method\n @functools.wraps(func)\n def wrapper_call(*args, **kwargs):\n return func(*args, **kwargs)\n\n default = kwvars['_default_config']\n wrapper_call.register_args(default=default, **kwvars)\n return wrapper_call\n\n return registered_func\n\n\ndef func(**kwvars):\n \"\"\"Register args or searchable spaces to the functions.\n\n Returns\n -------\n instance of :class:`autogluon.space.AutoGluonObject`:\n a lazy init object, which allows distributed training.\n\n Examples\n --------\n >>> from gluoncv.model_zoo import get_model\n >>> \n >>> @ag.func(pretrained=ag.space.Categorical(True, False))\n >>> def cifar_resnet(pretrained):\n ... return get_model('cifar_resnet20_v1', pretrained=pretrained)\n \"\"\"\n def registered_func(func):\n class autogluonobject(AutoGluonObject):\n @_autogluon_kwargs(**kwvars)\n def __init__(self, *args, **kwargs):\n self.func = func\n self.args = args\n self.kwargs = kwargs\n self._inited = False\n\n def sample(self, **config):\n kwargs = self.kwargs\n kwspaces = autogluonobject.kwspaces\n for k, v in kwargs.items():\n if k in kwspaces and isinstance(kwspaces[k], NestedSpace):\n sub_config = _strip_config_space(config, prefix=k)\n kwargs[k] = kwspaces[k].sample(**sub_config)\n elif k in config:\n kwargs[k] = config[k]\n \n return self.func(*self.args, **self.kwargs)\n\n @functools.wraps(func)\n def wrapper_call(*args, **kwargs):\n agobj = autogluonobject(*args, **kwargs)\n agobj.kwvars = agobj.__init__.kwvars\n return agobj\n return wrapper_call\n return registered_func\n\ndef obj(**kwvars):\n \"\"\"Register args or searchable spaces to the class.\n\n Returns\n -------\n instance of :class:`autogluon.space.AutoGluonObject`:\n a lazy init object, which allows distributed training.\n\n Examples\n --------\n >>> import autogluon as ag\n >>> from mxnet import optimizer as optim\n >>> @ag.obj(\n >>> learning_rate=ag.space.Real(1e-4, 1e-1, log=True),\n >>> wd=ag.space.Real(1e-4, 1e-1),\n >>> )\n >>> class Adam(optim.Adam):\n >>> pass\n\n \"\"\"\n def registered_class(Cls):\n class autogluonobject(AutoGluonObject):\n @_autogluon_kwargs(**kwvars)\n def __init__(self, *args, **kwargs):\n self._args = args\n self._kwargs = kwargs\n self._inited = False\n\n def sample(self, **config):\n kwargs = self._kwargs\n kwspaces = autogluonobject.kwspaces\n for k, v in kwargs.items():\n if k in kwspaces and isinstance(kwspaces[k], NestedSpace):\n sub_config = _strip_config_space(config, prefix=k)\n kwargs[k] = kwspaces[k].sample(**sub_config)\n elif k in config:\n kwargs[k] = config[k]\n\n args = self._args\n return Cls(*args, **kwargs)\n\n def __repr__(self):\n return 'AutoGluonObject -- ' + Cls.__name__\n\n autogluonobject.kwvars = autogluonobject.__init__.kwvars\n return autogluonobject\n\n return registered_class\n\ndef _autogluon_kwargs(**kwvars):\n def registered_func(func):\n kwspaces = OrderedDict()\n @functools.wraps(func)\n def wrapper_call(*args, **kwargs):\n kwvars.update(kwargs)\n for k, v in kwvars.items():\n if isinstance(v, NestedSpace):\n kwspaces[k] = v\n kwargs[k] = v\n elif isinstance(v, Space):\n kwspaces[k] = v\n hp = v.get_hp(name=k)\n kwargs[k] = hp.default_value\n else:\n kwargs[k] = v\n return func(*args, **kwargs)\n wrapper_call.kwspaces = kwspaces\n wrapper_call.kwvars = kwvars\n return wrapper_call\n return registered_func\n\nautogluon_register_args = make_deprecate(args, 'autogluon_register_args')\nautogluon_register_dict = make_deprecate(args, 'autogluon_register_dict')\nautogluon_function = make_deprecate(func, 'autogluon_function')\nautogluon_object = make_deprecate(obj, 'autogluon_object')\n"
] | [
[
"numpy.random.seed"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
matthieu637/DLM | [
"18fb6c80508abde6b81873d06c7e57f93e3425e3"
] | [
"difflogic/thutils.py"
] | [
"#! /usr/bin/env python3\n#\n# Copyright 2018 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# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Utility functions for PyTorch.\"\"\"\n\nimport torch\nimport torch.nn.functional as F\n\nfrom jactorch.utils.meta import as_float\nfrom jactorch.utils.meta import as_tensor\n\n__all__ = [\n 'binary_accuracy', 'rms', 'monitor_saturation', 'monitor_paramrms',\n 'monitor_gradrms'\n]\n\n\ndef binary_accuracy(label, raw_pred, eps=1e-20, return_float=True):\n \"\"\"get accuracy for binary classification problem.\"\"\"\n pred = as_tensor(raw_pred).squeeze(-1)\n pred = (pred > 0.5).float()\n label = as_tensor(label).float()\n # The $acc is micro accuracy = the correct ones / total\n acc = label.eq(pred).float()\n\n # The $balanced_accuracy is macro accuracy, with class-wide balance.\n nr_total = torch.ones(\n label.size(), dtype=label.dtype, device=label.device).sum(dim=-1)\n nr_pos = label.sum(dim=-1)\n nr_neg = nr_total - nr_pos\n pos_cnt = (acc * label).sum(dim=-1)\n neg_cnt = acc.sum(dim=-1) - pos_cnt\n balanced_acc = ((pos_cnt + eps) / (nr_pos + eps) + (neg_cnt + eps) /\n (nr_neg + eps)) / 2.0\n\n # $sat means the saturation rate of the predication,\n # measure how close the predections are to 0 or 1.\n sat = 1 - (raw_pred - pred).abs()\n if return_float:\n acc = as_float(acc.mean())\n balanced_acc = as_float(balanced_acc.mean())\n sat_mean = as_float(sat.mean())\n sat_min = as_float(sat.min())\n else:\n sat_mean = sat.mean(dim=-1)\n sat_min = sat.min(dim=-1)[0]\n\n return {\n 'accuracy': acc,\n 'balanced_accuracy': balanced_acc,\n 'saturation/mean': sat_mean,\n 'saturation/min': sat_min,\n }\n\n\ndef rms(p):\n \"\"\"Root mean square function.\"\"\"\n return as_float((as_tensor(p)**2).mean()**0.5)\n\n\ndef monitor_saturation(model):\n \"\"\"Monitor the saturation rate.\"\"\"\n monitors = {}\n for name, p in model.named_parameters():\n p = F.sigmoid(p)\n sat = 1 - (p - (p > 0.5).float()).abs()\n monitors['sat/' + name] = sat\n return monitors\n\n\ndef monitor_paramrms(model):\n \"\"\"Monitor the rms of the parameters.\"\"\"\n monitors = {}\n for name, p in model.named_parameters():\n monitors['paramrms/' + name] = rms(p)\n return monitors\n\n\ndef monitor_gradrms(model):\n \"\"\"Monitor the rms of the gradients of the parameters.\"\"\"\n monitors = {}\n for name, p in model.named_parameters():\n if p.grad is not None:\n monitors['gradrms/' + name] = rms(p.grad) / max(rms(p), 1e-8)\n return monitors\n"
] | [
[
"torch.nn.functional.sigmoid"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Leggerla/lama | [
"6b4e9d4920a3160a2102b6e863204944202a0d90"
] | [
"saicinpainting/training/trainers/__init__.py"
] | [
"import logging\nimport torch\nfrom .default import DefaultInpaintingTrainingModule\n\n\ndef get_training_model_class(kind):\n if kind == 'default':\n return DefaultInpaintingTrainingModule\n\n raise ValueError(f'Unknown trainer module {kind}')\n\n\ndef make_training_model(config):\n kind = config.training_model.kind\n kwargs = dict(config.training_model)\n kwargs.pop('kind')\n kwargs['use_ddp'] = config.trainer.kwargs.get('accelerator', None) == 'ddp'\n\n logging.info(f'Make training model {kind}')\n\n cls = get_training_model_class(kind)\n return cls(config, **kwargs)\n\n\ndef load_checkpoint(train_config, path, map_location='cuda', strict=True):\n model: torch.nn.Module = make_training_model(train_config)\n state = torch.load(path, map_location=map_location)\n model.load_state_dict(state['state_dict'], strict=strict)\n model.on_load_checkpoint(state)\n return model\n"
] | [
[
"torch.load"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ratt-ru/radiopadre | [
"3bf934eba69144d9707777a57da0e827625517a3"
] | [
"radiopadre/casatable.py"
] | [
"import os.path\nfrom collections import OrderedDict\nimport itertools\nimport numpy as np\nfrom numpy.ma import masked_array\nfrom contextlib import contextmanager\n\nimport radiopadre\nfrom radiopadre import casacore_tables\nfrom radiopadre import settings\nfrom .filelist import FileList\nfrom .render import render_table, rich_string, render_status_message, \\\n render_error, TransientMessage, render_preamble, render_titled_content\n\n\n\nclass CasaTable(radiopadre.file.FileBase):\n \"\"\"\n\n \"\"\"\n class ColumnProxy(object):\n def __init__(self, casatable, name, flagrow=False, flag=False):\n self._casatable = casatable\n self._name = name\n self._flagrow = flagrow\n self._flag = flag\n\n def __call__(self, start=0, nrow=-1, incr=1, flag=False):\n return self._casatable.getcol(self._name, start, nrow, incr, flagrow=flag or self._flagrow, flag=flag or self._flag)\n\n @staticmethod\n def _slice_to_casa(slc, row_based=True):\n \"\"\"\n Helper method to convert a slice element into CASA slicing indices (which uses either\n (start, nrows, step), or (start, end, incr), depending on context)\n\n :param slc: slice object or integer index\n :param row_based: if True, return start, nrows, step. Else return start, end, step\n :return: 4-tuple of start, {nrows or end}, step, index,\n where index is 0 if slc was an integer, or slice(None) if it was a slice\n \"\"\"\n if type(slc) is int:\n if slc < 0:\n raise IndexError(\"{} is not a valid table column index\".format(slc))\n start = end = slc\n step = 1\n elif type(slc) is slice:\n start = 0 if slc.start is None else slc.start\n if start < 0:\n raise IndexError(\"start index in {} is not valid for a table column\".format(slc))\n if slc.stop is None:\n end = -1\n else:\n if slc.stop < start:\n raise IndexError(\"end index in {} is not valid for a table column\".format(slc))\n end = slc.stop - 1\n step = 1 if slc.step is None else slc.step\n if step < 1:\n raise IndexError(\"step index in {} is not valid for a table column\".format(slc))\n else:\n raise IndexError(\"{} is not a valid table column index\".format(slc))\n # convert end to nrows, unless it is set to -1\n if row_based and end >= 0:\n end = end - start + 1\n return start, end, step, (0 if type(slc) is int else slice(None))\n\n def __getitem__(self, item):\n if type(item) is not tuple:\n item = (item, )\n if len(item) < 1:\n raise IndexError(\"{} is not a valid table column index\".format(item))\n\n # parse the index elements. First one selects rows, subsequent ones select column slice\n start, nrows, step, index = self._slice_to_casa(item[0], row_based=True)\n blc = []\n trc = []\n incr = []\n posterior_slice = [index]\n indexing_elements = [blc, trc, incr, posterior_slice]\n for slc in item[1:]:\n for i, element in enumerate(self._slice_to_casa(slc, row_based=False)):\n indexing_elements[i].append(element)\n\n return self._casatable.getcol(self._name, start, nrows, step,\n blc or None, trc or None, incr or None,\n flagrow=self._flagrow, flag=self._flag)[tuple(posterior_slice)]\n\n\n def __init__(self, name, table=None, title=None, parent=None, **kwargs):\n \"\"\"\n\n :param args:\n :param kwargs:\n \"\"\"\n self._error = self._dir_obj = None\n self._table = table\n self._writeable = table and table.iswritable()\n self._num_locks = 0\n self._writeable_lock = False\n self._subtables_obj = None\n self._parent = parent\n self._dynamic_attributes = set() # keep track of attributes added in scan_impl\n radiopadre.file.FileBase.__init__(self, name, title=title)\n\n\n @contextmanager\n def lock_table(self, write=False):\n \"\"\"Context manager. Sets lock on table. For use, see examples below.\"\"\"\n if casacore_tables is None:\n raise RuntimeError(\"no casacore.tables installed\")\n # check for writability\n writable = casacore_tables.tableiswritable(self.fullpath) if self._table is None else self._writeable\n\n if write and not writable:\n raise IOError(\"table is not writable\")\n\n # if table object is not open, we won't hold one outside of the context (and auto-locking is good enough)\n if self._table is None:\n tab = casacore_tables.table(self.fullpath, readonly=not write)\n yield tab\n tab.close()\n # if table object is open (i.e. we were created with a query or a sub-table), count locks\n else:\n # lock first time. If write-lock requested and no write lock set, lock again\n if not self._num_locks or (write and not self._writeable_lock):\n self._writeable_lock = write\n self._table.lock(write=write)\n self._num_locks += 1\n yield self._table\n # unlock\n self._num_locks -= 1\n if self._num_locks <= 0:\n self._num_locks = 0\n self._table.unlock()\n\n @property\n def wtable(self):\n return self.lock_table(True)\n\n @property\n def table(self):\n return self.lock_table(False)\n\n @property\n def downloadable_url(self):\n return None\n\n def _scan_impl(self):\n radiopadre.file.FileBase._scan_impl(self)\n self._dir_obj = None\n\n if casacore_tables is None:\n msg = \"python-casacore not installed\"\n self.description = self.size = self._error = rich_string(msg, render_status_message(msg, 'yellow'))\n return\n\n if self._table is None:\n self._writeable = casacore_tables.tableiswritable(self.fullpath)\n self._table = casacore_tables.table(self.fullpath, ack=False, readonly=not self._writeable, lockoptions='user')\n else:\n self._table.resync()\n\n with self.table as tab:\n self.nrows = tab.nrows()\n self.rownumbers = tab.rownumbers()\n self.columns = tab.colnames()\n self.keywords = tab.getkeywords()\n self._subtables = list(tab.getsubtables())\n self._error = None\n self.size = \"{} rows, {} cols\".format(self.nrows, len(self.columns))\n self.description = \"{} rows, {} columns, {} keywords, {} subtables\".format(\n self.nrows, len(self.columns), len(self.keywords), len(self._subtables))\n flagrow = 'FLAG_ROW' in self.columns\n flagcol = 'FLAG' in self.columns\n\n # remove any previous dynamically-created attributes\n for attr in self._dynamic_attributes:\n if hasattr(self, attr):\n delattr(self, attr)\n self._dynamic_attributes = set()\n\n # make attributes for each column\n for name in tab.colnames():\n attrname = name\n while hasattr(self, attrname):\n attrname = attrname + \"_\"\n self._dynamic_attributes.add(attrname)\n setattr(self, attrname, CasaTable.ColumnProxy(self, name))\n # make _F versions for flagged columns\n flag = flagcol and (name.endswith('DATA') or name.endswith('SPECTRUM'))\n if flag or flagrow:\n attrname = \"{}_F\".format(name)\n while hasattr(self, attrname):\n attrname = attrname + \"_\"\n self._dynamic_attributes.add(attrname)\n setattr(self, attrname, CasaTable.ColumnProxy(self, name, flagrow=flagrow, flag=flag))\n\n # make attributes for each subtable\n self._subtables_dict = OrderedDict()\n self._subtables_obj = None\n for path in self._subtables:\n name = os.path.basename(path)\n while hasattr(self, name):\n name = name + \"_\"\n self._subtables_dict[name] = path\n self._dynamic_attributes.add(name)\n setattr(self, name, path)\n\n def putcol(self, colname, coldata, start=0, nrow=-1, rowincr=1, blc=None, trc=None, incr=None):\n with self.wtable as tab:\n msg = TransientMessage(\"Writing column {}\".format(colname))\n return tab.putcol(colname, coldata, start, nrow, rowincr) if blc is None else \\\n tab.putcolslice(colname, coldata, blc, trc, incr, start, nrow, rowincr)\n\n def copycol(self, fromcol, tocol):\n with self.wtable as tab:\n if tocol not in tab.colnames():\n self.addcol(tocol, likecol=fromcol)\n msg = TransientMessage(\"Copying column {} to {}\".format(fromcol, tocol))\n tab.putcol(tocol, tab.getcol(fromcol))\n\n def delcol(self, *columns):\n with self.wtable as tab:\n tab.removecols(columns)\n\n def addcol(self, colname, likecol='DATA', coltype=None):\n with self.wtable as tab:\n if colname in tab.colnames():\n raise IOError(\"column {} already exists\".format(colname))\n msg = TransientMessage(\"Adding column {} (based on {})\".format(colname, likecol))\n # new column needs to be inserted -- get column description from column 'like_col'\n desc = tab.getcoldesc(likecol)\n desc['name'] = colname\n desc['comment'] = desc['comment'].replace(\" \", \"_\") # got this from Cyril, not sure why\n dminfo = tab.getdminfo(likecol)\n dminfo[\"NAME\"] = \"{}-{}\".format(dminfo[\"NAME\"], colname)\n # if a different type is specified, insert that\n if coltype:\n desc['valueType'] = coltype\n tab.addcols(desc, dminfo)\n\n def getcol(self, colname, start=0, nrow=-1, rowincr=1, blc=None, trc=None, incr=None, flagrow=False, flag=False):\n \"\"\"Like standard getcol() or getcolslice() of a CASA table, but can also read a flag column to make a masked array\"\"\"\n with self.table as tab:\n msg = TransientMessage(\"Reading column {}\".format(colname))\n coldata = tab.getcol(colname, start, nrow, rowincr) if blc is None else \\\n tab.getcolslice(colname, blc, trc, incr, start, nrow, rowincr)\n if coldata is None:\n return None\n shape = coldata.shape if type(coldata) is np.ndarray else [len(coldata)]\n fr = fl = None\n if flagrow and \"FLAG_ROW\" in self.columns:\n fr = tab.getcol(\"FLAG_ROW\", start, nrow, rowincr)\n if fr.shape != (shape[0],):\n raise ValueError(\"FLAG_ROW column has unexpected shape {}\".format(fr.shape))\n if flag and \"FLAG\" in self.columns:\n fl = tab.getcol(\"FLAG\", start, nrow, rowincr) if blc is None else \\\n tab.getcolslice(\"FLAG\", blc, trc, incr, start, nrow, rowincr)\n if fl.shape != shape[-len(fl.shape):]:\n raise ValueError(\"FLAG column has unexpected shape {}\".format(fl.shape))\n if fr is not None or fl is not None:\n mask = np.zeros(shape, bool)\n if fr is not None:\n mask[fr,...] = True\n if fl is not None:\n mask[...,fl] = True\n return masked_array(coldata, mask)\n return coldata\n\n\n def __getattribute__(self, attr):\n try:\n subdict = radiopadre.file.FileBase.__getattribute__(self, '_subtables_dict')\n except AttributeError:\n return radiopadre.file.FileBase.__getattribute__(self, attr)\n if attr not in subdict:\n return radiopadre.file.FileBase.__getattribute__(self, attr)\n subtab = subdict.get(attr)\n if isinstance(subtab, str):\n subdict[attr] = subtab = CasaTable(subtab)\n setattr(self, attr, subtab)\n return subtab\n\n @property\n def dir(self):\n from .datadir import DataDir\n if self._dir_obj is None:\n self._dir_obj = DataDir(self.fullpath)\n return self._dir_obj\n\n @property\n def subtables(self):\n if not self._subtables_obj:\n for name, subtab in self._subtables_dict.items():\n if isinstance(subtab, str):\n self._subtables_dict[name] = CasaTable(subtab)\n setattr(self, name, subtab)\n self._subtables_obj = FileList(self._subtables_dict.values(),\n path=self.fullpath, extcol=False, showpath=False,\n parent=self._parent or self)\n return self._subtables_obj\n\n def _render_epoch(self, epoch, format):\n pass\n\n def _render_direction(self, direction, format):\n pass\n\n def _render_quantity(self, value, units, format):\n \"\"\"\n Helper method. Renders a quantity (values with units) to a string\n\n :param value: list of values\n :param units: list of units\n :param format:\n :return:\n \"\"\"\n import casacore.quanta\n if type(value) is np.ndarray:\n value = value.flatten()\n else:\n value = [value]\n if format:\n if format[0] == \"%\":\n return format%tuple(value)\n elif format[0] == \"{\":\n return format.format(*value)\n # >1 unit: include in render\n if type(units) is not str:\n qqs = [casacore.quanta.quantity(x, unit).formatted(format or '') for x, unit in zip(value, itertools.cycle(units))]\n else:\n qqs = [casacore.quanta.quantity(x, units).formatted(format or '') for x in value]\n single_unit = all([qq.endswith(units) for qq in qqs])\n if single_unit:\n qqs = [qq[:-len(units)].strip() for qq in qqs]\n return \" \".join(qqs)\n\n @staticmethod\n def _slice_to_text(slc):\n \"\"\"Helper function to convert an index (slice, int, or list of ints) into a string\"\"\"\n if type(slc) is slice:\n txt = \"{}:{}\".format('' if slc.start is None else slc.start, '' if slc.stop is None else slc.stop)\n if slc.step is not None:\n txt += \":{}\".format(slc.step)\n return txt\n elif type(slc) is list:\n return \",\".join(map(str, slc))\n else:\n return str(slc)\n\n @staticmethod\n def _parse_column_argument(arg, for_what):\n \"\"\"Helper function to parse a column argument.\n Returns tuple of slicer, description, format\"\"\"\n colformat = None\n if arg is True or arg is None:\n return None, None, None\n elif type(arg) is str:\n return None, None, arg\n elif type(arg) in (slice, int, list):\n slicer = [arg]\n elif type(arg) is tuple:\n slicer = [s for s in arg if type(s) is not str]\n formats = [s for s in arg if type(s) is str]\n if formats:\n colformat = formats[0]\n else:\n raise TypeError(\"unknown {} specifier of type {}\".format(for_what, type(arg)))\n if len(slicer):\n desc = \"[{}]\".format(\",\".join(map(CasaTable._slice_to_text, slicer)))\n else:\n desc = \"\"\n return slicer, desc, colformat\n\n def render_html(self, firstrow=0, nrows=100, native=False, allcols=False, _=None, context=None, title=None, collapsed=None, **columns):\n with self.transient_message(\"Rendering {}, please wait...\".format(self.fullpath)), \\\n self.table as tab:\n title_html = self._header_html(title=title) + \"\\n\\n\"\n content_html = \"\"\n if collapsed is None and settings.gen.collapsible:\n collapsed = False\n firstrow = firstrow or 0\n\n if isinstance(tab, Exception):\n content_html = render_error(\"Error accessing table {}: {}\".format(self.basename, tab))\n collapsed = None\n # empty? return\n elif not self.nrows:\n collapsed = None\n elif firstrow > self.nrows-1:\n content_html = render_error(\"Starting row {} out of range\".format(firstrow))\n collapsed = None\n # if first row is not specified, and columns not specified, fall back on casacore's own HTML renderer\n elif native:\n content_html = tab._repr_html_()\n else:\n # get subset of columns to use, and slicer objects\n column_slicers = {}\n column_formats = {}\n default_slicer = default_slicer_desc = None\n # _ keyword sets up default column slicer\n if _ is not None:\n default_slicer, default_slicer_desc, _ = self._parse_column_argument(_, \"default\")\n # any other optional keywords put us into column selection mode\n column_selection = []\n skip_columns = set()\n have_explicit_columns = False\n # build up column selection from arguments\n if columns:\n for col, slicer in columns.items():\n if slicer is None:\n skip_columns.add(col)\n else:\n have_explicit_columns = True\n if col in self.columns:\n slicer, desc, colformat = self._parse_column_argument(slicer, \"column {}\".format(col))\n column_formats[col] = colformat\n column_slicers[col] = slicer, desc\n column_selection.append(col)\n else:\n content_html += render_error(\"No such column: {}\".format(col))\n\n # if no columns at all were selected,\n if allcols or not have_explicit_columns:\n column_selection = [col for col in self.columns if col not in skip_columns]\n\n # else use ours\n nrows = min(self.nrows-firstrow, nrows)\n labels = [\"row\"] + list(column_selection)\n colvalues = {}\n styles = {}\n for icol, colname in enumerate(column_selection):\n style = None\n shape_suffix = \"\"\n formatter = error = colval = None\n column_has_shape = False\n\n # figure out formatting of measures/quanta columns\n colkw = tab.getcolkeywords(colname)\n units = colkw.get(\"QuantumUnits\", [])\n measinfo = colkw.get('MEASINFO', {})\n meastype = measinfo.get('type')\n\n if units:\n same_units = all([u==units[0] for u in units[1:]])\n if same_units:\n units = units[0]\n formatter = lambda value:self._render_quantity(value, units=units, format=column_formats.get(colname))\n if same_units and meastype != 'direction':\n labels[icol+1] += \", {}\".format(units)\n # getcol() is prone to \"RuntimeError: ... no array in row N\", so explicitly ignore that and render empty column\n try:\n colvalues[icol] = colval = tab.getcol(colname, firstrow, nrows)\n except RuntimeError:\n colvalues[icol] = [\"\"]*nrows\n continue\n except Exception as exc:\n error = exc\n\n if not error:\n try:\n colvalues[icol] = colval = tab.getcol(colname, firstrow, nrows)\n # work around variable-shaped string columns\n if type(colval) is dict:\n if 'array' not in colval or 'shape' not in colval:\n raise TypeError(\"unknown column shape\")\n colvalues[icol] = colval = np.array(colval['array'], dtype=object).reshape(colval['shape'])\n column_has_shape = type(colval) is np.ndarray and colval.ndim > 1\n if column_has_shape:\n shape_suffix = \" ({})\".format(\"x\".join(map(str, colval.shape[1:])))\n except Exception as exc:\n error = exc\n\n # render the value\n if not error:\n # apply slicer, if specified for this column. Render error if incorrect\n if colname in column_slicers:\n slicer, desc = column_slicers[colname]\n slicer = [slice(None)] + slicer\n try:\n colvalues[icol] = colvalues[icol][tuple(slicer)]\n except IndexError as exc:\n error = exc\n if desc:\n shape_suffix += \" \" + desc\n # else try to apply default slicer, if applicable. Retain column on error\n elif default_slicer and column_has_shape and colval.ndim > len(default_slicer):\n slicer = [Ellipsis] + default_slicer\n try:\n colvalues[icol] = colvalues[icol][tuple(slicer)]\n if default_slicer_desc:\n shape_suffix += \" \" + default_slicer_desc\n except IndexError:\n pass\n\n if formatter and not error:\n try:\n colvalues[icol] = list(map(formatter, colvalues[icol]))\n except Exception as exc:\n error = exc\n\n labels[icol+1] += shape_suffix\n\n # on any error, fill column with \"(error)\"\n if error:\n colvalues[icol] = [\"(error)\"]*nrows\n content_html += render_error(\"Column {}: {}: {}\".format(colname, error.__class__.__name__, str(error)))\n style = \"color: red\"\n if style:\n styles[labels[icol+1]] = style\n\n data = [[self.rownumbers[firstrow+i]] + [colvalues[icol][i] for icol,col in enumerate(column_selection)] for i in range(nrows)]\n\n content_html += render_table(data, labels, styles=styles, numbering=False)\n return render_preamble() + \\\n render_titled_content(title_html=title_html,\n content_html=content_html,\n collapsed=collapsed)\n\n def _select_rows_columns(self, rows, columns, desc):\n with self.table as tab:\n if rows is not None:\n tab = tab.selectrows(rows)\n if columns is not None:\n tab = tab.select(columns)\n return CasaTable(self.fullpath, title=\"{} [{}]\".format(self.title, desc), table=tab)\n\n def __getitem__(self, item):\n if self._error:\n return self._error\n if type(item) is slice:\n item = (item, )\n if type(item) is str:\n if item not in self.columns:\n raise ValueError(\"no such column {}\".format(item))\n return self._select_rows_columns(None, item, desc=item)\n elif type(item) is tuple:\n columns = []\n descs = []\n rows = set()\n for x in item:\n if type(x) is str:\n if x not in self.columns:\n raise ValueError(\"no such column {}\".format(x))\n columns.append(x)\n elif type(x) is int:\n rows.add(x)\n descs.append(str(x))\n elif type(x) is slice:\n rows.update(range(*x.indices(self.nrows)))\n desc = \"{}:{}\".format(\"\" if x.start is None else x.start,\n \"\" if (x.stop is None or x.stop > self.nrows) else x.stop)\n if x.step is not None:\n desc += \":{}\".format(x.step)\n descs.append(desc)\n else:\n raise TypeError(\"invalid index element {} of type {}\".format(x, type(x)))\n columns = \",\".join(columns)\n if columns:\n descs.append(columns)\n return self._select_rows_columns(sorted(rows) if rows else None, columns, \",\".join(descs))\n else:\n raise TypeError(\"invalid __getitem__ argument {} of type {}\".format(item, type(item)))\n\n # def __getslice__(self, *slicer):\n # return self[(slice(*slicer),)]\n\n def query(self, taql, sortlist='', columns='', limit=0, offset=0):\n if self._error:\n return self._error\n with self.table as tab0:\n tab = tab0.query(taql, sortlist=sortlist,columns=columns, limit=limit, offset=offset)\n return CasaTable(self.fullpath, title=\"{} ({})\".format(self.title, taql),\n table=tab)\n\n def __call__(self, taql, sortlist='', columns='', limit=0, offset=0):\n return self.query(taql, sortlist, columns, limit, offset)\n\n\n"
] | [
[
"numpy.array",
"numpy.zeros",
"numpy.ma.masked_array"
]
] | [
{
"matplotlib": [],
"numpy": [
"1.10",
"1.12",
"1.11",
"1.19",
"1.13",
"1.16",
"1.9",
"1.18",
"1.20",
"1.7",
"1.15",
"1.14",
"1.17",
"1.8"
],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
miguelammatos/FaultSee | [
"3e6272e351547b1d0e46178deb69096f646dd7bc"
] | [
"angainor-lsds/examples/nginx/parse.py"
] | [
"#!/usr/bin/env python\nimport json\nimport pandas as pd\nimport matplotlib\nimport matplotlib.pyplot as plt\n\n\ndef load(path):\n def read(path):\n with open(path) as f:\n for line in f:\n line = line.strip()\n split = line.split('\\t', 2)\n while len(split) < 3:\n split.append(\"\")\n time, id, msg = split\n time, subject = time.split(' ', 1)\n subject = subject[1:-1] # remove brackets\n\n print(split)\n print(\" \", \"time:\", time)\n print(\" \", \"id:\", id)\n print(\" \", \"msg:\", msg)\n print(\" \", \"subject:\", subject)\n\n data = dict(time=time, subject=subject, id=id)\n\n if subject == 'LOG':\n data['log'] = msg\n\n if subject == 'EVENT':\n msg = json.loads(msg)\n if msg['Type'] != 'container':\n continue\n\n attr = msg['Actor']['Attributes']\n data['service'] = attr.get('com.docker.swarm.service.name')\n data['signal'] = attr.get('signal')\n data['status'] = msg['status']\n\n if subject == 'STATS':\n msg = json.loads(msg)\n\n preread = msg['preread']\n if preread.startswith(\"0001\"):\n cpu = 0\n else:\n dt = (pd.to_datetime(msg['read'])\n - pd.to_datetime(preread)).to_timedelta64()\n dt = dt.astype('int')\n cpu = (msg['cpu_stats']['cpu_usage']['total_usage']\n - msg['precpu_stats']['cpu_usage']['total_usage'])\n # n=len(msg['cpu_stats']['cpu_usage']['percpu_usage'])\n cpu /= dt\n\n data['cpu'] = cpu\n data['mem'] = msg['memory_stats']['usage']\n data.update(msg['networks']['eth0'])\n\n if subject == 'HOST':\n msg = json.loads(msg)\n data['cpu'] = msg['cpuPercent'][0] / 100\n data['mem'] = msg['mem']['usedPercent'] / 100\n\n if subject == 'MARK':\n msg = json.loads(msg)\n if msg['type'] == 'benchmark':\n data['mark'] = msg['status']\n\n if msg['type'] == 'churn':\n data['mark'] = 'churn'\n op, num = msg['op'], msg['num']\n data['service'] = msg['service']\n if op != 'end':\n op += \":\" + str(num)\n data['churn'] = op\n\n yield data\n\n df = pd.DataFrame(read(path))\n print(df.time)\n df.time = pd.to_datetime(df.time)\n df = df.sort_values(by='time')\n\n start = df[df.mark == 'start'].iloc[0].time\n stop = df[df.mark == 'stop'].iloc[-1].time\n\n df = df[(df.time >= start) & (df.time <= stop)]\n df['dt'] = df.time - df.time.min()\n\n return df\n\n\ndef process(df):\n # find nginx & siege instances\n nginx = set(df[df.service == 'nginx'].id.unique())\n siege = set(df[df.service == 'siege'].id.unique())\n\n # compute requests/s for each nginx instance\n requests = pd.DataFrame()\n for id in nginx:\n r = df[(df.subject == 'LOG') & (df.id == id)][['dt']]\n r['requests'] = 1\n r = r.set_index('dt')\n r = r.groupby(pd.Grouper(freq='1S')).sum()\n r['id'] = id\n\n requests = requests.append(r)\n\n requests = requests.sort_index()\n requests['dt'] = requests.index\n requests = requests[['dt', 'id', 'requests']]\n\n # per-instance resource stats\n stats = df[(df.subject == 'STATS') & df.id.isin(nginx)]\n stats = stats[['dt', 'id', 'cpu', 'mem', 'rx_bytes', 'tx_bytes']]\n\n # compute bytes/s for each nginx instance\n for id in nginx:\n s = stats[stats.id == id]\n dt = s.dt.dt.total_seconds().diff()\n stats.loc[stats.id == id, 'rx_bw'] = s.rx_bytes.diff() / dt\n stats.loc[stats.id == id, 'tx_bw'] = s.tx_bytes.diff() / dt\n\n requests = requests.sort_index()\n requests['dt'] = requests.index\n requests = requests[['dt', 'id', 'requests']]\n\n # per-node resource stats\n nodes = df[df.subject == 'HOST']\n nodes = nodes[['dt', 'id', 'cpu', 'mem']]\n\n # compute up/down events for siege service\n events = df[df.id.isin(siege) & df.status.isin(['start', 'kill'])].copy()\n events.status = ((events.status == 'start').astype('int')\n - (events.status == 'kill').astype('int'))\n events['instances'] = events.status.cumsum()\n events['i'] = 0\n for i, id in enumerate(events.id.unique()):\n events.loc[events.id == id, 'i'] = i + 1\n\n events = events[['dt', 'id', 'i', 'status', 'instances']]\n\n # start/stop/churn marks\n marks = df[df.subject == 'MARK']\n # only keep marks of one node, they're all the same anyway\n marks = marks[marks.id == marks.id[0]]\n marks = marks[marks.mark == 'churn']\n # marks = marks[['dt', 'mark', 'service', 'churn']]\n\n return requests, stats, nodes, events, marks\n\n\ndef plot(requests, stats, nodes, events, marks, title=None):\n fig, axes = plt.subplots(\n nrows=5, ncols=1, sharex=True,\n figsize=(10, 12), dpi=300)\n\n ax_instances, ax_req, ax_cpu, ax_bw, ax_nodes = axes\n\n ax_instances.set_title(r\"Number of siege instances\")\n ax_req.set_title(r\"Served request rate [req/s]\")\n ax_cpu.set_title(r\"nginx CPU usage [\\%]\")\n ax_bw.set_title(r\"nginx bandwidth usage [MiB/s]\")\n ax_nodes.set_title(r\"Node CPU and memory usage [\\%]\")\n\n for ax in axes:\n ax.yaxis.grid()\n ax.set_xlim(0, nodes.dt.dt.total_seconds().max())\n\n for _, mark in marks.iterrows():\n if mark.service != 'siege':\n continue\n for ax in axes:\n ax.axvline(mark['dt'].total_seconds(),\n color=(0, 0, 0, .1), ls='--')\n\n instances = events.set_index('dt')\n instances = instances.resample('S').last().ffill()\n instances['dt'] = instances.index\n ax_instances.plot(instances.dt.dt.total_seconds(), instances.instances)\n\n for id in stats.id.unique():\n st = stats[stats.id == id]\n rq = requests[requests.id == id]\n ax_req.plot(rq.dt.dt.total_seconds(), rq.requests)\n dt = st.dt.dt.total_seconds()\n ax_cpu.plot(dt, st.cpu * 100)\n ax_bw.plot(dt, st.rx_bw / 1024 / 1024, label=\"Received\", ls=':')\n ax_bw.plot(dt, st.tx_bw / 1024 / 1024, label=\"Transmitted\")\n\n colors = matplotlib.rcParams['axes.prop_cycle']\n colors = [c['color'] for c in colors]\n manager = list(nodes.id.unique())[0]\n st_manager, st_worker = nodes[nodes.id\n == manager], nodes[nodes.id != manager]\n\n st = st_manager.set_index('dt')\n st = st.groupby(pd.Grouper(freq='5S')).mean()\n st['dt'] = st.index\n dt = st.dt.dt.total_seconds()\n name = 'Manager Node'\n ax_nodes.plot(dt, st.cpu * 100, label=name + \" CPU\", lw=2)\n ax_nodes.plot(dt, st.mem * 100, label=name + \" MEM\", lw=3, ls=':')\n\n st = st_worker.set_index('dt')\n st = st.groupby(pd.Grouper(freq='5S')).mean()\n st['dt'] = st.index\n dt = st.dt.dt.total_seconds()\n name = 'Workers Average'\n ax_nodes.plot(dt, st.cpu * 100, label=name + \" CPU\", lw=1)\n ax_nodes.plot(dt, st.mem * 100, label=name + \" MEM\", lw=1, ls='--')\n\n # for (i, id), c in zip(enumerate(nodes.id.unique()), colors):\n # st = nodes[nodes.id == id]\n # # smoothen stats\n # st = st.set_index('dt')\n # st = st.groupby(pd.Grouper(freq='5S')).mean()\n # st['dt'] = st.index\n # dt = st.dt.dt.total_seconds()\n # name = \"node-{}\".format(i)\n # ax_nodes.plot(dt, st.cpu * 100, label=name + \" CPU\", c=c)\n # ax_nodes.plot(dt, st.mem * 100, label=name + \" MEM\", c=c, ls=':')\n\n ax_instances.set_ylim(bottom=0)\n ax_req.set_ylim(bottom=0)\n ax_cpu.set_ylim(bottom=0)\n ax_bw.set_ylim(bottom=0)\n ax_nodes.set_ylim(bottom=0)\n\n ax_bw.legend()\n ax_nodes.legend()\n\n ax_nodes.set_xlabel(\"Time [s]\")\n\n if title:\n fig.suptitle(title, fontsize=20)\n\n fig.tight_layout()\n fig.subplots_adjust(top=.93, bottom=.07)\n return fig\n\n\nif __name__ == '__main__':\n import sys\n if len(sys.argv) < 3:\n print(\"Usage: {} LOG_FILE OUT_FILE [TITLE]\".format(sys.argv[0]))\n else:\n log_file = sys.argv[1]\n out_file = sys.argv[2]\n if len(sys.argv) > 3:\n title = sys.argv[3]\n else:\n title = out_file\n\n if type(title) == bytes:\n title = str(title, 'utf-8')\n\n plt.rc('text', usetex=True)\n plt.rc('font', family='serif')\n\n print(\"now processing\")\n data = process(load(log_file))\n print(\"creting plot\")\n fig = plot(*data, title)\n print(\"saving file\")\n fig.savefig(out_file + \".pdf\")\n"
] | [
[
"pandas.to_datetime",
"pandas.Grouper",
"matplotlib.pyplot.rc",
"matplotlib.pyplot.subplots",
"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": []
}
] |
jeremiedecock/fits-viewer | [
"191fe77e2e478c18ba5c3461b9dc0fee6b814744"
] | [
"fitsviewer/gui/tk_matplotlib.py"
] | [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# FITS Viewer\n\n# The MIT License\n#\n# Copyright (c) 2016 Jeremie DECOCK (http://www.jdhp.org)\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\n# Documentation: http://docs.astropy.org/en/stable/io/fits/index.html\n\n__all__ = ['TkGUI']\n\nimport matplotlib\nmatplotlib.use('TkAgg')\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg\n# implement the default mpl key bindings\nfrom matplotlib.backend_bases import key_press_handler\nfrom matplotlib import cm\n\nimport tkinter as tk\n\nimport argparse\nimport json\nimport os\n\nfrom astropy.io import fits\n\n###############################################################################\n\nCONFIG_FILE_NAME = \".fitsviewer.json\"\n\nLAST_OPENED_FILES_LIST_MAX_SIZE = 15\n\nDEFAULT_COLOR_MAP = \"gnuplot2\" # \"gray\"\n\n# histogram types : [‘bar’ | ‘barstacked’ | ‘step’ | ‘stepfilled’]\nHISTOGRAM_TYPE = 'bar'\n\n#IMAGE_INTERPOLATION = 'bilinear' # \"smooth\" map\nIMAGE_INTERPOLATION = 'nearest' # \"raw\" (non smooth) map\n\n###############################################################################\n\ndef get_colour_map_list():\n \"\"\"Return the list of the available colormaps.\"\"\"\n return sorted(plt.cm.datad)\n\n###############################################################################\n\nclass TkGUI:\n \"\"\"\n TODO...\n \"\"\"\n\n def __init__(self, root):\n \"\"\"\n TODO...\n \"\"\"\n\n self.hdu_list = None # The current HDU list\n self.hdu_index = None # The current HDU index\n self.last_opened_files = []\n\n # Matplotlib ##################\n\n self.fig = plt.figure(figsize=(8.0, 8.0))\n\n # Gui parameters ##############\n\n self._color_map = tk.StringVar()\n self._show_color_bar = tk.BooleanVar()\n self._show_image = tk.BooleanVar()\n self._show_histogram = tk.BooleanVar()\n\n # Make widgets ################\n\n self.root = root\n\n # Add a callback on WM_DELETE_WINDOW events\n self.root.protocol(\"WM_DELETE_WINDOW\", self.quit)\n\n # Canvas\n self.canvas = FigureCanvasTkAgg(self.fig, master=self.root)\n self.canvas.get_tk_widget().pack(fill=\"both\", expand=True)\n\n ## Buttons\n #quit_button = tk.Button(master=self.root, text='Quit', command=self.quit)\n #quit_button.pack(fill=\"x\", expand=True)\n\n # Make a menubar ##############\n\n # Create a toplevel menu\n self.menubar = tk.Menu(self.root)\n\n # Create a pulldown menu: /File #############################\n file_menu = tk.Menu(self.menubar, tearoff=0)\n\n # /File/Open\n file_menu.add_command(label=\"Open...\", command=self.select_fits_file)\n\n # /File/Open Recent\n self.open_recent_menu = tk.Menu(file_menu, tearoff=0)\n file_menu.add_cascade(label=\"Open Recent\", menu=self.open_recent_menu)\n\n # /File/Close\n file_menu.add_command(label=\"Close\", command=self.close_fits_file)\n\n file_menu.add_separator()\n\n # /File/Exit\n file_menu.add_command(label=\"Exit\", command=self.quit)\n\n self.menubar.add_cascade(label=\"File\", menu=file_menu)\n\n # Create a pulldown menu: /HDU ##############################\n self.hdu_menu = tk.Menu(self.menubar, tearoff=0)\n\n self.menubar.add_cascade(label=\"HDU\", menu=self.hdu_menu)\n\n # Init the HDU menu\n self.update_hdu_menu()\n\n # Create a pulldown menu: /View #############################\n view_menu = tk.Menu(self.menubar, tearoff=0)\n\n view_menu.add_checkbutton(label=\"Show color bar\",\n variable=self._show_color_bar,\n command=self.draw_figure)\n\n view_menu.add_checkbutton(label=\"Show image\",\n variable=self._show_image,\n command=self.draw_figure)\n\n view_menu.add_checkbutton(label=\"Show histogram\",\n variable=self._show_histogram,\n command=self.draw_figure)\n\n self.menubar.add_cascade(label=\"View\", menu=view_menu)\n\n # Create a pulldown menu: /View/Color Map\n colormap_menu = tk.Menu(view_menu, tearoff=0)\n\n for cmap_str in get_colour_map_list():\n colormap_menu.add_radiobutton(label=cmap_str,\n variable=self._color_map,\n value=cmap_str,\n command=self.draw_figure)\n\n view_menu.add_cascade(label=\"Color Map\", menu=colormap_menu)\n\n # Display the menu\n # The config method is used to attach the menu to the root window. The\n # contents of that menu is used to create a menubar at the top of the root\n # window. There is no need to pack the menu, since it is automatically\n # displayed by Tkinter.\n self.root.config(menu=self.menubar)\n\n\n def load_config(self):\n \"\"\"\n Load the user's configuration file.\n \"\"\"\n\n # Check whether config_file_path is a directory\n if os.path.isdir(self.config_file_path):\n error_msg = \"Error: please remove or rename the following direcory: \" + os.path.abspath(self.config_file_path)\n raise Exception(error_msg) # TODO\n\n # Load the configuration file if it exists\n if os.path.isfile(self.config_file_path):\n with open(self.config_file_path, \"r\") as fd:\n json_dict = json.load(fd)\n\n if \"last_opened_files\" in json_dict:\n self.last_opened_files = json_dict[\"last_opened_files\"]\n self.update_open_recent_menu()\n\n if (self.color_map is None) and (\"color_map\" in json_dict):\n self.color_map = json_dict[\"color_map\"]\n\n #if (self.show_color_bar is None) and (\"show_color_bar\" in json_dict):\n # self.show_color_bar = json_dict[\"show_color_bar\"]\n\n #if (self.show_image is None) and (\"show_image\" in json_dict):\n # self.show_image = json_dict[\"show_image\"]\n\n #if (self.show_histogram is None) and (\"show_histogram\" in json_dict):\n # self.show_histogram = json_dict[\"show_histogram\"]\n\n\n def save_config(self):\n \"\"\"\n Save the current setup in the user's configuration file.\n \"\"\"\n\n # Check whether config_file_path is a directory ###\n\n if os.path.isdir(self.config_file_path):\n error_msg = \"Error: please remove or rename the following direcory: \" + os.path.abspath(self.config_file_path)\n raise Exception(error_msg)\n\n # Make the JSON dictionary ########################\n\n json_dict = {}\n json_dict[\"last_opened_files\"] = self.last_opened_files\n json_dict[\"color_map\"] = self.color_map\n #json_dict[\"show_color_bar\"] = self.show_color_bar\n #json_dict[\"show_image\"] = self.show_image\n #json_dict[\"show_histogram\"] = self.show_histogram\n\n # Save the JSON file ##############################\n\n with open(self.config_file_path, \"w\") as fd:\n json.dump(json_dict, fd, sort_keys=True, indent=4)\n\n\n def run(self):\n \"\"\"\n Launch the main loop (Tk event loop).\n \"\"\"\n\n # TODO ???\n self.root.mainloop()\n\n\n def quit(self):\n self.save_config()\n self.root.quit() # stops mainloop\n self.root.destroy() # this is necessary on Windows to prevent\n # Fatal Python Error: PyEval_RestoreThread: NULL tstate\n\n\n def select_fits_file(self):\n \"\"\"\n Display a file dialog to select the FITS file to open.\n\n Return the path of the selected file.\n \"\"\"\n\n # Check and parse the file\n\n # FILE_TYPES = [(label1, pattern1), (label2, pattern2), ...]\n FILE_TYPES = [\n ('FITS Files', '.fits .fit .fts .fits.gz .fit.gz .fts.gz'),\n ('All Files', '.*')\n ]\n\n if (len(self.last_opened_files) > 0) and (os.path.isdir(os.path.dirname(self.last_opened_files[0]))):\n initial_directory = os.path.dirname(self.last_opened_files[0])\n else:\n initial_directory = os.path.expanduser(\"~\")\n\n path = tk.filedialog.askopenfilename(parent=self.root,\n filetypes=FILE_TYPES,\n defaultextension='.fits',\n initialdir=initial_directory,\n #initialfile='demo.fits', # optional\n title='Select your file')\n\n self.open_fits_file(path)\n\n\n def open_fits_file(self, file_path):\n \"\"\"\n Open and display the given FITS file.\n \"\"\"\n\n # READ THE INPUT FILE #################################################\n\n self.hdu_list = fits.open(file_path) # open the FITS file\n self.hdu_index = 0\n\n self.root.title(self.file_path)\n self.draw_figure()\n\n # UPDATE THE \"LAST OPEN FILE LIST\" ####################################\n\n # Add the opened path to the beginning of the list (or move it to the beginning if it's already in the list)\n if file_path in self.last_opened_files:\n self.last_opened_files.remove(file_path)\n self.last_opened_files.insert(0, file_path)\n\n # Keep the N first elements (with N = LAST_OPENED_FILES_LIST_MAX_SIZE)\n self.last_opened_files = self.last_opened_files[:LAST_OPENED_FILES_LIST_MAX_SIZE]\n\n # UPDATE THE SOME MENUS ###############################################\n\n self.update_open_recent_menu()\n self.update_hdu_menu()\n\n\n def select_hdu(self, hdu_index):\n \"\"\"\n Open and display the given HDU item.\n \"\"\"\n if (self.hdu_list is not None) and (0 <= hdu_index < len(self.hdu_list)):\n self.hdu_index = hdu_index\n self.draw_figure()\n else:\n raise Exception(\"Internal error.\")\n\n\n def update_hdu_menu(self):\n \"\"\"\n Update the \"HDU\" menu.\n \"\"\"\n # Remove all menu items\n self.hdu_menu.delete(0, 1000) # TODO: hugly but it seems that tkinter doesn't have any special value to delete all items and doesn't offer any method to count the number of items...\n\n if self.hdu_list is not None:\n # Enable the \"/HDU/Show HDU Info\" menu\n self.menubar.entryconfig(\"HDU\", state=\"normal\")\n\n # Populate the \"/HDU\" menu (add one button per HDU of the opened file)\n for hdu_index, hdu in enumerate(self.hdu_list):\n # TODO\n if hdu.is_image:\n _label = \"HDU{} ({}D image {} {})\".format(hdu_index,\n hdu.data.ndim,\n \"x\".join([str(dim) for dim in hdu.data.shape]),\n hdu.data.dtype.name)\n else:\n _label = \"HDU{} (table)\".format(hdu_index)\n # See:\n # - http://effbot.org/zone/tkinter-callbacks.htm\n # - http://stackoverflow.com/questions/728356/dynamically-creating-a-menu-in-tkinter-lambda-expressions\n # - http://stackoverflow.com/questions/938429/scope-of-python-lambda-functions-and-their-parameters\n # - http://stackoverflow.com/questions/19693782/callback-function-tkinter-button-with-variable-parameter\n self.hdu_menu.add_command(label=_label,\n command=lambda index=hdu_index: self.select_hdu(index))\n else:\n # Disable the \"/HDU/Show HDU Info\" menu\n self.menubar.entryconfig(\"HDU\", state=\"disabled\")\n\n\n def update_open_recent_menu(self):\n \"\"\"\n Update the \"File/Open Recent\" menu.\n \"\"\"\n\n # Remove all menu items\n self.open_recent_menu.delete(0, LAST_OPENED_FILES_LIST_MAX_SIZE + 2)\n\n # Add menu items\n for recent_file_str in self.last_opened_files:\n # See:\n # - http://effbot.org/zone/tkinter-callbacks.htm\n # - http://stackoverflow.com/questions/728356/dynamically-creating-a-menu-in-tkinter-lambda-expressions\n # - http://stackoverflow.com/questions/938429/scope-of-python-lambda-functions-and-their-parameters\n # - http://stackoverflow.com/questions/19693782/callback-function-tkinter-button-with-variable-parameter\n self.open_recent_menu.add_command(label=recent_file_str, # TODO: only display the filename, not the full path ?\n command=lambda file_path=recent_file_str: self.open_fits_file(file_path))\n\n # Add the \"Clear Menu\" item\n self.open_recent_menu.add_separator()\n self.open_recent_menu.add_command(label=\"Clear Menu\", command=self.clear_last_opened_files)\n\n\n def clear_last_opened_files(self):\n \"\"\"\n Clear the list of recent opened files.\n \"\"\"\n self.last_opened_files = []\n self.update_open_recent_menu()\n\n\n def close_fits_file(self):\n self.hdu_list.close()\n self.hdu_list = None\n self.hdu_index = None\n self.clear_figure()\n self.update_hdu_menu()\n\n\n def clear_figure(self):\n self.fig.clf()\n self.fig.canvas.draw()\n\n\n def draw_figure(self):\n if self.hdu_list is not None:\n if 0 <= self.hdu_index < len(self.hdu_list):\n\n # Clear the figure ##############\n self.fig.clf() # TODO\n\n # Get the image #################\n hdu = self.hdu_list[self.hdu_index]\n\n if hdu.is_image:\n # The current HDU is an image\n\n # Get the image #############\n if hdu.data.ndim <= 2:\n image_array = hdu.data\n elif hdu.data.ndim == 3:\n image_array = hdu.data[0] # TODO\n elif hdu.data.ndim == 4:\n image_array = hdu.data[0][0] # TODO\n else:\n raise Exception(\"Internal error.\")\n \n # Show the figure ###########\n if self.show_histogram and self.show_image:\n\n ax1 = self.fig.add_subplot(121)\n ax2 = self.fig.add_subplot(122)\n\n self._draw_histogram(ax1, image_array)\n self._draw_image(ax2, image_array)\n\n elif self.show_histogram or self.show_image:\n\n ax1 = self.fig.add_subplot(111)\n\n if self.show_histogram:\n self._draw_histogram(ax1, image_array)\n else:\n self._draw_image(ax1, image_array)\n else:\n # The current HDU is a table\n\n # TODO\n ax1 = self.fig.add_subplot(111)\n\n #ax1.text(0.5, 0.5, 'Table...', fontsize=15)\n ax1.text(0.5, 0.5,\n \"The FITS table visualization hasn't been implemented yet.\",\n ha='center', va='center',\n fontsize=15,\n transform=ax1.transAxes, wrap=True)\n\n #ax1.set_xlim([0, 1])\n #ax1.set_ylim([0, 1])\n ax1.set_axis_off()\n\n self.fig.canvas.draw()\n else:\n raise Exception(\"Internal error.\")\n\n\n def _draw_histogram(self, axis, image_array):\n\n #axis.set_title(self.file_path)\n bins = math.ceil(image_array.max() - image_array.min())\n\n # nparray.ravel(): Return a flattened array.\n values, bins, patches = axis.hist(image_array.ravel(),\n histtype=HISTOGRAM_TYPE,\n bins=bins,\n #range=(0., 255.),\n fc='k',\n ec='k')\n\n axis.set_xlim([image_array.min(), image_array.max()])\n\n\n def _draw_image(self, axis, image_array):\n\n if image_array.ndim == 1:\n image_array = np.tile(image_array, (256, 1)) # TODO ?\n axis.get_yaxis().set_visible(False)\n\n im = axis.imshow(image_array,\n origin='lower',\n interpolation=IMAGE_INTERPOLATION,\n cmap=self.color_map)\n\n #axis.set_axis_off()\n\n if self.show_color_bar:\n plt.colorbar(im, ax=axis) # draw the colorbar\n\n\n # PROPERTIES ##############################################################\n\n @property\n def file_path(self):\n _file_path = None\n if self.hdu_list is not None:\n _file_path = self.hdu_list.filename()\n return _file_path\n\n ###\n\n @property\n def config_file_path(self):\n home_path = os.path.expanduser(\"~\")\n return os.path.join(home_path, CONFIG_FILE_NAME)\n\n ###\n\n @property\n def show_color_bar(self):\n return self._show_color_bar.get()\n\n @show_color_bar.setter\n def show_color_bar(self, value):\n self._show_color_bar.set(value)\n\n ###\n\n @property\n def show_image(self):\n return self._show_image.get()\n\n @show_image.setter\n def show_image(self, value):\n self._show_image.set(value)\n\n ###\n\n @property\n def show_histogram(self):\n return self._show_histogram.get()\n\n @show_histogram.setter\n def show_histogram(self, value):\n self._show_histogram.set(value)\n\n ###\n\n @property\n def color_map(self):\n return self._color_map.get()\n\n @color_map.setter\n def color_map(self, value):\n self._color_map.set(value)\n\n\ndef main():\n\n root = tk.Tk() # TODO ?\n gui = TkGUI(root)\n\n gui.load_config()\n\n # PARSE OPTIONS ###########################################################\n\n parser = argparse.ArgumentParser(description=\"Display a FITS file.\")\n\n parser.add_argument(\"--cmap\", \"-C\", default=DEFAULT_COLOR_MAP, metavar=\"STRING\",\n help=\"the colormap to use. The list of available color maps is available here: \"\n \"http://matplotlib.org/examples/color/colormaps_reference.html\")\n\n parser.add_argument(\"--hidecbar\", \"-c\", action=\"store_true\",\n help=\"hide the color bar\")\n\n parser.add_argument(\"--hideimage\", \"-i\", action=\"store_true\",\n help=\"hide the image\")\n\n parser.add_argument(\"--showhist\", \"-H\", action=\"store_true\",\n help=\"show the histogram of the image\")\n\n parser.add_argument(\"filearg\", nargs=\"?\", metavar=\"FILE\", const=None,\n help=\"the FITS file to process\")\n\n args = parser.parse_args()\n\n input_file_path = args.filearg\n\n # SET OPTIONS #############################################################\n\n gui.color_map = args.cmap\n gui.show_color_bar = not args.hidecbar\n gui.show_image = not args.hideimage\n gui.show_histogram = args.showhist\n\n if input_file_path is not None:\n gui.open_fits_file(input_file_path)\n\n # LAUNCH THE MAIN LOOP ####################################################\n\n gui.run()\n\nif __name__ == \"__main__\":\n main()\n\n\n"
] | [
[
"matplotlib.use",
"matplotlib.pyplot.figure",
"numpy.tile",
"matplotlib.pyplot.colorbar",
"matplotlib.backends.backend_tkagg.FigureCanvasTkAgg"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
sanjibansg/nbox | [
"bf23b7cceb3179ba3d051a38aac0e32925a513e8"
] | [
"tests/test_hf.py"
] | [
"import os\nimport unittest\n\nimport nbox\nfrom nbox import utils\n\nfrom functools import lru_cache\n\n\n@lru_cache\ndef get_model(*args, **kwargs):\n return nbox.load(*args, **kwargs)\n\n\n@lru_cache\ndef get_parser(*args, **kwargs):\n model = get_model(*args, **kwargs)\n return model.text_parser\n\n\nclass ImportTest(unittest.TestCase):\n def test_hf_string(self):\n cache_dir = os.path.join(utils.folder(__file__), \"__ignore/\")\n os.makedirs(cache_dir, exist_ok=True)\n model = get_model(\"transformers/sshleifer/tiny-gpt2::AutoModelForCausalLM\", cache_dir=cache_dir)\n model.eval()\n out = model(\"Hello world\")\n self.assertEqual(out.logits.topk(4).indices.tolist(), [[[16046, 17192, 38361, 43423], [16046, 17192, 38361, 43423]]])\n\n def test_hf_string_batch(self):\n cache_dir = os.path.join(utils.folder(__file__), \"__ignore/\")\n os.makedirs(cache_dir, exist_ok=True)\n model = get_model(\"transformers/sshleifer/tiny-gpt2::AutoModelForCausalLM\", cache_dir=cache_dir)\n out = model([\"Hello world\", \"my foot\"])\n self.assertEqual(out.logits.argmax(-1).tolist(), [[16046, 16046], [16046, 16046]])\n\n def test_hf_masked_lm(self):\n cache_dir = os.path.join(utils.folder(__file__), \"__ignore/\")\n os.makedirs(cache_dir, exist_ok=True)\n model = nbox.load(\"transformers/prajjwal1/bert-tiny::AutoModelForMaskedLM\", cache_dir=cache_dir)\n out = model(\"hello world\")\n self.assertEqual(out.logits.argmax(-1).tolist(), [[1012, 7592, 2088, 1012]])\n\n def test_hf_numpy(self):\n import numpy as np\n\n cache_dir = os.path.join(utils.folder(__file__), \"__ignore/\")\n os.makedirs(cache_dir, exist_ok=True)\n model = get_model(\"transformers/sshleifer/tiny-gpt2::AutoModelForCausalLM\", cache_dir=cache_dir)\n out = model(np.array([[0, 1, 1, 2, 4, 5, 6, 6, 7, 8, 0]]))\n self.assertEqual(out.logits.argmax(-1).tolist(), [[16046, 16046, 16046, 5087, 16046, 16046, 5087, 5087, 16046, 16046, 16046]])\n\n\nclass ParserTest(unittest.TestCase):\n def test_string(self):\n cache_dir = os.path.join(utils.folder(__file__), \"__ignore/\")\n os.makedirs(cache_dir, exist_ok=True)\n parser = get_parser(\"transformers/sshleifer/tiny-gpt2::AutoModelForCausalLM\", cache_dir=cache_dir)\n out = parser(\"hello world\")\n\n self.assertEqual(\n {\n \"input_ids\": list(out[\"input_ids\"].shape),\n \"attention_mask\": list(out[\"attention_mask\"].shape),\n },\n {\n \"input_ids\": [1, 2],\n \"attention_mask\": [1, 2],\n },\n )\n\n def test_list_string(self):\n cache_dir = os.path.join(utils.folder(__file__), \"__ignore/\")\n os.makedirs(cache_dir, exist_ok=True)\n parser = get_parser(\"transformers/sshleifer/tiny-gpt2::AutoModelForCausalLM\", cache_dir=cache_dir)\n out = parser([\"wabba lubba dub dub\", \"BoJack Horseman - A wise man told me that\", \"I can't believe you just did that!\"])\n\n self.assertEqual(\n {\n \"input_ids\": list(out[\"input_ids\"].shape),\n \"attention_mask\": list(out[\"attention_mask\"].shape),\n },\n {\n \"input_ids\": [3, 11],\n \"attention_mask\": [3, 11],\n },\n )\n\n def test_dict_strings(self):\n cache_dir = os.path.join(utils.folder(__file__), \"__ignore/\")\n os.makedirs(cache_dir, exist_ok=True)\n parser = get_parser(\"transformers/sshleifer/tiny-gpt2::AutoModelForCausalLM\", cache_dir=cache_dir)\n out = parser({\"input_sentence\": \"hello world\", \"target_sentence\": \"wabba lubba dub dub\"})\n\n self.assertEqual(\n {\n \"input_sentence\": {\n \"input_ids\": list(out[\"input_sentence\"][\"input_ids\"].shape),\n \"attention_mask\": list(out[\"input_sentence\"][\"attention_mask\"].shape),\n },\n \"target_sentence\": {\n \"input_ids\": list(out[\"target_sentence\"][\"input_ids\"].shape),\n \"attention_mask\": list(out[\"target_sentence\"][\"attention_mask\"].shape),\n },\n },\n {\n \"input_sentence\": {\n \"input_ids\": [1, 2],\n \"attention_mask\": [1, 2],\n },\n \"target_sentence\": {\n \"input_ids\": [1, 7],\n \"attention_mask\": [1, 7],\n },\n },\n )\n\n def test_dict_list_strings(self):\n cache_dir = os.path.join(utils.folder(__file__), \"__ignore/\")\n os.makedirs(cache_dir, exist_ok=True)\n parser = get_parser(\"transformers/sshleifer/tiny-gpt2::AutoModelForCausalLM\", cache_dir=cache_dir)\n out = parser(\n {\"input_sentence\": \"hello world\", \"target_sentences\": [\"wabba lubba dub dub\", \"BoJack Horseman - A wise man told me that\"]}\n )\n\n self.assertEqual(\n {\n \"input_sentence\": {\n \"input_ids\": list(out[\"input_sentence\"][\"input_ids\"].shape),\n \"attention_mask\": list(out[\"input_sentence\"][\"attention_mask\"].shape),\n },\n \"target_sentences\": {\n \"input_ids\": list(out[\"target_sentences\"][\"input_ids\"].shape),\n \"attention_mask\": list(out[\"target_sentences\"][\"attention_mask\"].shape),\n },\n },\n {\n \"input_sentence\": {\"input_ids\": [1, 2], \"attention_mask\": [1, 2]},\n \"target_sentences\": {\"input_ids\": [2, 11], \"attention_mask\": [2, 11]},\n },\n )\n\n"
] | [
[
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
dxxx9/scikit-rf | [
"060257568f3c0bdcc817e89742ec29445df81a09"
] | [
"skrf/time.py"
] | [
"\"\"\"\n.. module:: skrf.time\n========================================\ntime (:mod:`skrf.time`)\n========================================\n\nTime domain functions\n\n\n.. autosummary::\n :toctree: generated/\n\n time_gate\n detect_span\n find_n_peaks\n indexes\n\n\"\"\"\nfrom .util import find_nearest_index\nfrom scipy.ndimage.filters import convolve1d\nfrom scipy import signal\nimport numpy as npy\nfrom numpy import fft\nfrom typing import List\n\n\ndef indexes(y: npy.ndarray, thres: float = 0.3, min_dist: int = 1) -> npy.ndarray:\n \"\"\"\n Peak detection routine.\n\n Finds the numeric index of the peaks in *y* by taking its first order difference. By using\n *thres* and *min_dist* parameters, it is possible to reduce the number of\n detected peaks. *y* must be signed.\n\n Parameters\n ----------\n y : ndarray (signed)\n 1D amplitude data to search for peaks.\n thres : float between [0., 1.], optional\n Normalized threshold. Only the peaks with amplitude higher than the\n threshold will be detected. Default is 0.3\n min_dist : int, optional\n Minimum distance between each detected peak. The peak with the highest\n amplitude is preferred to satisfy this constraint. Default is 1\n\n Returns\n -------\n ndarray\n Array containing the numeric indexes of the peaks that were detected\n\n Notes\n -----\n This function was taken from peakutils-1.1.0\n http://pythonhosted.org/PeakUtils/index.html\n\n \"\"\"\n #This function was taken from peakutils, and is covered\n # by the MIT license, included below:\n\n #The MIT License (MIT)\n\n #Copyright (c) 2014 Lucas Hermann Negri\n\n #Permission is hereby granted, free of charge, to any person obtaining a copy\n #of this software and associated documentation files (the \"Software\"), to deal\n #in the Software without restriction, including without limitation the rights\n #to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n #copies of the Software, and to permit persons to whom the Software is\n #furnished to do so, subject to the following conditions:\n\n #The above copyright notice and this permission notice shall be included in\n #all copies or substantial portions of the Software.\n\n #THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n #IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n #FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n #AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n #LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n #OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n #THE SOFTWARE.\n\n if isinstance(y, npy.ndarray) and npy.issubdtype(y.dtype, npy.unsignedinteger):\n raise ValueError(\"y must be signed\")\n\n thres = thres * (npy.max(y) - npy.min(y)) + npy.min(y)\n min_dist = int(min_dist)\n\n # compute first order difference\n dy = npy.diff(y)\n\n # propagate left and right values successively to fill all plateau pixels (0-value)\n zeros, = npy.where(dy == 0)\n\n # check if the singal is totally flat\n if len(zeros) == len(y) - 1:\n return npy.array([])\n\n while len(zeros):\n # add pixels 2 by 2 to propagate left and right value onto the zero-value pixel\n zerosr = npy.hstack([dy[1:], 0.])\n zerosl = npy.hstack([0., dy[:-1]])\n\n # replace 0 with right value if non zero\n dy[zeros]=zerosr[zeros]\n zeros, = npy.where(dy == 0)\n\n # replace 0 with left value if non zero\n dy[zeros] = zerosl[zeros]\n zeros, = npy.where(dy == 0)\n\n # find the peaks by using the first order difference\n peaks = npy.where((npy.hstack([dy, 0.]) < 0.)\n & (npy.hstack([0., dy]) > 0.)\n & (y > thres))[0]\n\n # handle multiple peaks, respecting the minimum distance\n if peaks.size > 1 and min_dist > 1:\n highest = peaks[npy.argsort(y[peaks])][::-1]\n rem = npy.ones(y.size, dtype=bool)\n rem[peaks] = False\n\n for peak in highest:\n if not rem[peak]:\n sl = slice(max(0, peak - min_dist), peak + min_dist + 1)\n rem[sl] = True\n rem[peak] = False\n\n peaks = npy.arange(y.size)[~rem]\n\n return peaks\n\n\ndef find_n_peaks(x: npy.ndarray, n: int, thres: float = 0.9, **kwargs) -> List[int]:\n \"\"\"\n Find a given number of peaks in a signal.\n\n Parameters\n ----------\n x : npy.ndarray\n signal\n n : int\n number of peaks to search for\n thres : float, optional\n threshold, default is 0.9\n **kwargs : optional keyword arguments passed to :func:`indexes`\n\n Returns\n -------\n peak_idxs : list of int\n List containing the numeric indexes of the peaks that were detected\n\n Raises\n ------\n ValueError\n If no peaks are found.\n \"\"\"\n for dummy in range(10):\n\n idx = indexes(x, **kwargs)\n if len(idx) < n:\n thres *= .5\n\n else:\n peak_vals = sorted(x[idx], reverse=True)[:n]\n peak_idxs = [x.tolist().index(k) for k in peak_vals]\n\n return peak_idxs\n raise ValueError('Couldnt find %i peaks' % n)\n\n\ndef detect_span(ntwk) -> float:\n \"\"\"\n Detect the correct time-span between two largest peaks.\n\n Parameters\n ----------\n ntwk : :class:`~skrf.network.Network`\n network to get data from\n\n Returns\n -------\n span : float\n \"\"\"\n x = ntwk.s_time_db.flatten()\n p1, p2 = find_n_peaks(x, n=2)\n # distance to nearest neighbor peak\n span = abs(ntwk.frequency.t_ns[p1]-ntwk.frequency.t_ns[p2])\n return span\n\n\ndef time_gate(ntwk, start: float = None, stop: float = None, center: float = None, span: float = None,\n mode: str = 'bandpass', window=('kaiser', 6), media=None,\n boundary: str = 'reflect', return_all: bool = False):\n \"\"\"\n Time-gate one-port s-parameters.\n\n The gate can be defined with start/stop times, or by\n center/span. all times are in units of nanoseconds. common\n windows are:\n\n * ('kaiser', 6)\n * 6 # integers are interpreted as kaiser beta-values\n * 'hamming'\n * 'boxcar' # a straight up rect\n\n If no parameters are passed this will try to auto-gate the largest\n peak.\n\n Parameters\n ----------\n ntwk : :class:`~skrf.network.Network`\n network to operate on\n start : number, or None\n start of time gate, (ns).\n stop : number, or None\n stop of time gate (ns).\n center : number, or None\n center of time gate, (ns). If None, and span is given,\n the gate will be centered on the peak.\n span : number, or None\n span of time gate, (ns). If None span will be half of the\n distance to the second tallest peak\n mode: ['bandpass','bandstop']\n mode of gate\n boundary: {'reflect', 'constant', 'nearest', 'mirror', 'wrap'},\n passed to `scipy.ndimage.filters.convolve1d`\n window : string, float, or tuple\n passed to `window` arg of `scipy.signal.get_window`\n\n Note\n ----\n You cant gate things that are 'behind' strong reflections. This\n is due to the multiple reflections that occur.\n\n If `center!=0`, then the ntwk's time response is shifted\n to t=0, gated, then shifted back to where it was. This is\n done in frequency domain using `ntwk.delay()`. If the media being\n gated is dispersive (ie waveguide), then the gate `span` will be\n span at t=0, which is different.\n\n If you need to time-gate an N-port network, then you should\n gate each s-parameter independently.\n\n Returns\n -------\n ntwk : Network\n copy of ntwk with time-gated s-parameters\n\n\n .. warning::\n Depending on sharpness of the gate, the band edges may be\n inaccurate, due to properties of FFT. We do not re-normalize\n anything.\n\n\n \"\"\"\n if ntwk.nports >1:\n raise ValueError('Time-gating only works on one-ports. try taking ntwk.s11 or ntwk.s21 first')\n\n if start is not None and stop is not None:\n start *= 1e-9\n stop *= 1e-9\n span = abs(stop-start)\n center = (stop+start)/2.\n\n else:\n if center is None:\n # they didnt provide center, so find the peak\n n = ntwk.s_time_mag.argmax()\n center = ntwk.frequency.t_ns[n]\n\n if span is None:\n span = detect_span(ntwk)\n\n center *= 1e-9\n span *= 1e-9\n start = center - span / 2.\n stop = center + span / 2.\n\n\n # find start/stop gate indices\n t = ntwk.frequency.t\n start_idx = find_nearest_index(t, start)\n stop_idx = find_nearest_index(t, stop)\n\n # create window\n window_width = abs(stop_idx - start_idx)\n window = signal.get_window(window, window_width)\n\n # create the gate by padding the window with zeros\n gate = npy.r_[npy.zeros(start_idx),\n window,\n npy.zeros(len(t) - stop_idx)]\n\n #FFT the gate, so we have it's frequency response, aka kernel\n kernel=fft.ifftshift(fft.fft(fft.fftshift(gate, axes=0), axis=0))\n kernel =abs(kernel).flatten() # take mag and flatten\n kernel=kernel/sum(kernel) # normalize kernel\n\n out = ntwk.copy()\n\n # conditionally delay ntwk, to center at t=0, this is\n # equivalent to gating at center. (this is probably very inefficient)\n if center!=0:\n out = out.delay(-center*1e9, 'ns',port=0,media=media)\n\n # waste of code to handle convolve1d suck\n re = out.s_re[:,0,0]\n im = out.s_im[:,0,0]\n s = convolve1d(re,kernel, mode=boundary)+\\\n 1j*convolve1d(im,kernel, mode=boundary)\n out.s[:,0,0] = s\n # conditionally un-delay ntwk\n if center!=0:\n out = out.delay(center*1e9, 'ns',port=0,media=media)\n\n if mode == 'bandstop':\n out = ntwk-out\n elif mode=='bandpass':\n pass\n else:\n raise ValueError('mode should be \\'bandpass\\' or \\'bandstop\\'')\n\n if return_all:\n # compute the gate ntwk and add delay\n gate_ntwk = out.s11.copy()\n gate_ntwk.s = kernel\n gate_ntwk= gate_ntwk.delay(center*1e9, 'ns', media=media)\n\n return {'gated_ntwk':out,\n 'gate':gate_ntwk}\n else:\n return out\n"
] | [
[
"numpy.hstack",
"scipy.signal.get_window",
"numpy.min",
"numpy.arange",
"numpy.issubdtype",
"numpy.fft.fftshift",
"numpy.ones",
"numpy.max",
"numpy.diff",
"scipy.ndimage.filters.convolve1d",
"numpy.argsort",
"numpy.array",
"numpy.where",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"1.6",
"0.14",
"0.15",
"1.4",
"0.10",
"1.3",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"0.12",
"1.0",
"0.17",
"0.16"
],
"tensorflow": []
}
] |
viniciusbarbosapaiva/Templates-Python | [
"9e19b84a707826b9aebe61c1f1f5b1afc1b67811"
] | [
"Templates_Machine_learning/Clustering/Template_clustering_tito.py"
] | [
"#K-means Clustering\n#%reset -f\n#Importing Libraries\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.cluster import DBSCAN\nfrom pyclustertend import hopkins\nfrom sklearn.cluster import MeanShift, estimate_bandwidth\nfrom sklearn.metrics import silhouette_score\n\n#Importing Dataset\ndf = pd.read_csv('appdata10.csv')\ndf_user = pd.DataFrame(np.arange(0,len(df)), columns=['user'])\ndf = pd.concat([df_user, df], axis=1)\ndf.info()\ndf.head()\ndf.tail()\ndf.columns.values\n\n#Converting columns to Datatime \ndf['Timestamp'] = pd.to_datetime(df['Timestamp'])\ntime_new = df['Timestamp'].iloc[0]\ndf['Hour'] = df['Timestamp'].apply(lambda time_new: time_new.hour)\ndf['Month'] = df['Timestamp'].apply(lambda time_new: time_new.month)\ndf['Day'] = df['Timestamp'].apply(lambda time_new: time_new.dayofweek)\ndf[\"hour\"] = df.hour.str.slice(1, 3).astype(int)\n\n#Data analysis\nstatistical = df.describe()\n\n#Verifying null values\nsns.heatmap(df.isnull(), yticklabels=False, cbar=False, cmap='viridis')\ndf.isna().any()\ndf.isna().sum()\n\n#Define X\nfeatures = ['tipo_de_negociacao','percentual_venda', 'quantas_correcoes',\n 'quantos_pontos_avancou', 'quantos_pontos_retornados', 'amplitude']\nX = df[features]\n\n#Taking care of missing data\n'''\nfrom sklearn.preprocessing import Imputer\nimputer = Imputer(missing_values='NaN', strategy='mean', axis=0)\nimputer = imputer.fit(X[:, 1:3])\nX[:, 1:3] = imputer.transform(X[:, 1:3] )\n'''\n\n#Encoding categorical data\n'''\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\nlabelenconder_x = LabelEncoder()\nX.iloc[:, 1] = labelenconder_x.fit_transform(X.iloc[:, 1])\nonehotencoder_x = OneHotEncoder(categorical_features=[1])\nX2 = pd.DataFrame(onehotencoder_x.fit_transform(X).toarray())\ny = pd.DataFrame(labelenconder_x.fit_transform(y))\n\n#Dummies Trap\nX2 = X2.iloc[:, 1:]\nX2 = X2.iloc[:,[0,1,2]]\nX2 = X2.rename(columns={1:'pay_schedule_1', 2:'pay_schedule_2', 3:'pay_schedule_3'})\nX = pd.concat([X,X2], axis=1)\nX = X.drop(['pay_schedule'], axis=1)\n'''\n\n#Visualizing data\nsns.pairplot(data=df, hue='target_names', vars= ['mean radius', 'mean texture', 'mean area', 'mean perimeter', 'mean smoothness'])\nsns.countplot(x='target_names', data=df, label='Count')\nsns.scatterplot(x='mean area', y='mean smoothness',hue='target_names', data=df)\nplt.figure(figsize=(20,10))\nsns.heatmap(data=df.corr(), annot=True, cmap='viridis')\n\n# Hopkins Test\n'''\nthe null hypothesis (no meaningfull cluster) happens when the hopkins test is \naround 0.5 and the hopkins test tends to 0 when meaningful cluster exists in \nthe space. Usually, we can believe in the existence of clusters when the \nhopkins score is bellow 0.25.\nHere the value of the hopkins test is quite high but one could think there is\n cluster in our subspace. BUT the hopkins test is highly influenced by outliers,\n let's try once again with normalised data.\n'''\nhopkins(X, X.shape[0])\n\n# Construção do modelo DBSCAN\ndbscan = DBSCAN(eps = 0.2, min_samples = 5, metric = 'euclidean')\ny_pred = dbscan.fit_predict(X)\n\n# Construção do modelo mean shift\n# bandwidth = Comprimento da Interação entre os exemplos, também conhecido como a largura de banda do algoritmo.\nbandwidth = estimate_bandwidth(X, quantile = .1, n_samples = 500)\nmean_shift = MeanShift(bandwidth = bandwidth, bin_seeding = True)\nmean_shift.fit(X)\n\n#Using the Elbow Method to find the optimal number of clusters\nfrom sklearn.cluster import KMeans\nwcss = []\nfor i in range(1,11):\n kmeans = KMeans(n_clusters=i, init='k-means++', n_init=10, max_iter=300, random_state=0) #n_init e max_iter são padrões.\n kmeans.fit(X)\n wcss.append(kmeans.inertia_)\nplt.plot(range(1,11), wcss)\nplt.title('The Elbow Method')\nplt.xlabel('Number of Clusters')\nplt.ylabel('WCSS')\nplt.show() #Quando parar de cair exageradamente no gráfico, este será o número de cluster. Neste caso serão 5 cluesters\n\n#Applying the K-means to Dataset\nkmeans = KMeans(n_clusters=5, init='k-means++', n_init=10, max_iter=300, random_state=0)\nkmeans.fit(X)\nprint(90*'_')\nprint(\"\\nCount of features in each cluster\")\nprint(90*'_')\npd.value_counts(kmeans.labels_, sort=False)\n\n# Silhouette Score\nlabels = modelo_v1.labels_\nsilhouette_score(pca, labels, metric = 'euclidean')\n\n# Function that creates a DataFrame with a column for Cluster Number\ndef pd_centers(featuresUsed, centers):\n\tcolNames = list(featuresUsed)\n\tcolNames.append('prediction')\n\n\t# Zip with a column called 'prediction' (index)\n\tZ = [np.append(A, index) for index, A in enumerate(centers)]\n\n\t# Convert to pandas data frame for plotting\n\tP = pd.DataFrame(Z, columns=colNames)\n\tP['prediction'] = P['prediction'].astype(int)\n\treturn P\n\n# Function that creates Parallel Plots\nfrom itertools import cycle, islice\nfrom pandas.plotting import parallel_coordinates\ndef parallel_plot(data):\n\tmy_colors = list(islice(cycle(['b', 'r', 'g', 'y', 'k']), None, len(data)))\n\tplt.figure(figsize=(15,8)).gca().axes.set_ylim([-3,+3])\n\tparallel_coordinates(data, 'prediction', color = my_colors, marker='o')\n\nP = pd_centers(featuresUsed=features, centers=kmeans.cluster_centers_)\nP\nparallel_plot(P)\ny_kmeans = kmeans.fit_predict(X)\n\n#Visualising the clusters\nplt.scatter(np.array(X)[y_kmeans == 0, 0], np.array(X)[y_kmeans == 0, 1], s = 100, c = 'red', label = 'Careful')\nplt.scatter(np.array(X)[y_kmeans == 1, 0], np.array(X)[y_kmeans == 1, 1], s = 100, c = 'blue', label = 'Standard')\nplt.scatter(np.array(X)[y_kmeans == 2, 0], np.array(X)[y_kmeans == 2, 1], s = 100, c = 'green', label = 'Target')\nplt.scatter(np.array(X)[y_kmeans == 3, 0], np.array(X)[y_kmeans == 3, 1], s = 100, c = 'cyan', label = 'Careless')\nplt.scatter(np.array(X)[y_kmeans == 4, 0], np.array(X)[y_kmeans == 4, 1], s = 100, c = 'magenta', label = 'Sensible') \nplt.scatter(kmeans.cluster_centers_[:,0], kmeans.cluster_centers_[:,1], s = 300 , c = 'yellow', label = 'Centroids')\nplt.title('Clusters of Clients')\nplt.xlabel('Annual Income (R$)')\nplt.ylabel('Spending Score (1 - 100)')\nplt.legend() \nplt.show()\n\n"
] | [
[
"sklearn.cluster.estimate_bandwidth",
"matplotlib.pyplot.legend",
"pandas.to_datetime",
"sklearn.cluster.KMeans",
"sklearn.metrics.silhouette_score",
"sklearn.cluster.DBSCAN",
"pandas.DataFrame",
"pandas.plotting.parallel_coordinates",
"pandas.read_csv",
"matplotlib.pyplot.figure",
"pandas.concat",
"sklearn.cluster.MeanShift",
"matplotlib.pyplot.title",
"numpy.append",
"pandas.value_counts",
"matplotlib.pyplot.show",
"numpy.array",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.xlabel"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
calwhi/molinExercises | [
"7ec4f55963b31c8ac3964ca5884a8ee7958d76e6"
] | [
"book_env/lib/python3.9/site-packages/mplfinance/_widths.py"
] | [
"import pandas as pd\nfrom mplfinance._arg_validators import _process_kwargs, _validate_vkwargs_dict\n\ndef _get_widths_df():\n '''\n Provide a dataframe of width data that appropriate scales widths of\n various aspects of the plot (candles,ohlc bars,volume bars) based on\n the amount or density of data. These numbers were arrived at by \n carefully testing many use-cases of plots with various styles, \n and observing which numbers gave the \"best\" appearance.\n '''\n numpoints = [n for n in range(30,241,30)]\n volume_width = (0.98, 0.96, 0.95, 0.925, 0.9, 0.9, 0.875, 0.825 )\n volume_linewidth = tuple([0.65]*8)\n candle_width = (0.65, 0.575, 0.50, 0.445, 0.435, 0.425, 0.420, 0.415)\n candle_linewidth = (1.00, 0.875, 0.75, 0.625, 0.500, 0.438, 0.435, 0.435)\n ohlc_tickwidth = tuple([0.35]*8)\n ohlc_linewidth = (1.50, 1.175, 0.85, 0.525, 0.525, 0.525, 0.525, 0.525)\n line_width = (2.25, 1.8, 1.3, 0.813, 0.807, 0.801, 0.796, 0.791)\n widths = {}\n widths['vw'] = volume_width\n widths['vlw'] = volume_linewidth\n widths['cw'] = candle_width\n widths['clw'] = candle_linewidth\n widths['ow'] = ohlc_tickwidth\n widths['olw'] = ohlc_linewidth\n widths['lw'] = line_width\n return pd.DataFrame(widths,index=numpoints)\n\n_widths = _get_widths_df()\n\ndef _valid_scale_width_kwargs():\n vkwargs = {\n 'ohlc' : { 'Default' : None,\n 'Validator' : lambda value: isinstance(value,(float,int)) },\n\n 'volume' : { 'Default' : None,\n 'Validator' : lambda value: isinstance(value,(float,int)) },\n\n 'candle' : { 'Default' : None,\n 'Validator' : lambda value: isinstance(value,(float,int)) },\n\n 'lines' : { 'Default' : None,\n 'Validator' : lambda value: isinstance(value,(float,int)) },\n\n 'volume_linewidth' : { 'Default' : None,\n 'Validator' : lambda value: isinstance(value,(float,int)) },\n\n 'ohlc_linewidth' : { 'Default' : None,\n 'Validator' : lambda value: isinstance(value,(float,int)) },\n\n 'candle_linewidth' : { 'Default' : None,\n 'Validator' : lambda value: isinstance(value,(float,int)) },\n }\n _validate_vkwargs_dict(vkwargs)\n return vkwargs\n\ndef _valid_update_width_kwargs():\n vkwargs = {\n\n 'ohlc_ticksize' : { 'Default' : None,\n 'Validator' : lambda value: isinstance(value,(float,int)) },\n\n 'ohlc_linewidth' : { 'Default' : None,\n 'Validator' : lambda value: isinstance(value,(float,int)) },\n\n 'volume_width' : { 'Default' : None,\n 'Validator' : lambda value: isinstance(value,(float,int)) },\n\n 'volume_linewidth' : { 'Default' : None,\n 'Validator' : lambda value: isinstance(value,(float,int)) },\n\n 'candle_width' : { 'Default' : None,\n 'Validator' : lambda value: isinstance(value,(float,int)) },\n\n 'candle_linewidth' : { 'Default' : None,\n 'Validator' : lambda value: isinstance(value,(float,int)) },\n\n 'line_width' : { 'Default' : None,\n 'Validator' : lambda value: isinstance(value,(float,int)) },\n }\n _validate_vkwargs_dict(vkwargs)\n return vkwargs\n\n\ndef _determine_width_config( xdates, config ):\n '''\n Given x-axis xdates, and `mpf.plot()` kwargs config,\n determine the widths and linewidths for candles,\n volume bars, ohlc bars, etc.\n '''\n datalen = len(xdates)\n avg_dist_between_points = (xdates[-1] - xdates[0]) / float(datalen)\n\n tweak = 1.06 if datalen > 100 else 1.03\n\n adjust = tweak*avg_dist_between_points if config['show_nontrading'] else 1.0\n\n width_config = {}\n\n if config['width_adjuster_version'] == 'v0': # Behave like original version of code:\n\n width_config['volume_width' ] = 0.5*avg_dist_between_points\n width_config['volume_linewidth'] = None\n width_config['ohlc_ticksize' ] = avg_dist_between_points / 2.5\n width_config['ohlc_linewidth' ] = None\n width_config['candle_width' ] = avg_dist_between_points / 2.0\n width_config['candle_linewidth'] = None\n width_config['line_width' ] = None\n\n else: # config['width_adjuster_version'] == 'v1'\n\n width_config['volume_width' ] = _dfinterpolate(_widths,datalen,'vw' ) * adjust\n width_config['volume_linewidth'] = _dfinterpolate(_widths,datalen,'vlw')\n width_config['ohlc_ticksize' ] = _dfinterpolate(_widths,datalen,'ow' ) * adjust\n width_config['ohlc_linewidth' ] = _dfinterpolate(_widths,datalen,'olw')\n width_config['candle_width' ] = _dfinterpolate(_widths,datalen,'cw' ) * adjust\n width_config['candle_linewidth'] = _dfinterpolate(_widths,datalen,'clw')\n width_config['line_width' ] = _dfinterpolate(_widths,datalen,'lw')\n\n if config['scale_width_adjustment'] is not None:\n\n scale = _process_kwargs(config['scale_width_adjustment'],_valid_scale_width_kwargs())\n if scale['volume'] is not None:\n width_config['volume_width'] *= scale['volume']\n if scale['ohlc'] is not None:\n width_config['ohlc_ticksize'] *= scale['ohlc']\n if scale['candle'] is not None:\n width_config['candle_width'] *= scale['candle']\n if scale['lines'] is not None:\n width_config['line_width'] *= scale['lines']\n if scale['volume_linewidth'] is not None:\n width_config['volume_linewidth'] *= scale['volume_linewidth']\n if scale['ohlc_linewidth'] is not None: \n width_config['ohlc_linewidth' ] *= scale['ohlc_linewidth']\n if scale['candle_linewidth'] is not None:\n width_config['candle_linewidth'] *= scale['candle_linewidth']\n\n if config['update_width_config'] is not None:\n \n update = _process_kwargs(config['update_width_config'],_valid_update_width_kwargs())\n uplist = [ (k,v) for k,v in update.items() if v is not None ]\n width_config.update(uplist)\n\n return width_config\n\n\ndef _dfinterpolate(df,key,column):\n '''\n Given a DataFrame, with all values and the Index as floats,\n and given a float key, find the row that matches the key, or \n find the two rows surrounding that key, and return the interpolated\n value for the specified column, based on where the key falls between\n the two rows. If they key is an exact match for a key in the index,\n the return the exact value from the column. If the key is less than\n or greater than any key in the index, then return either the first\n or last value for the column.\n '''\n s = df[column]\n s1 = s.loc[:key]\n if len(s1) < 1:\n return s.iloc[0]\n j1 = s1.index[-1]\n v1 = s1.iloc[-1]\n \n s2 = s.loc[key:]\n if len(s2) < 1:\n return s.iloc[-1]\n j2 = s2.index[0]\n v2 = s2.iloc[0]\n\n if j1 == j2:\n return v1\n delta = j2 - j1\n portion = (key - j1)/delta\n ans = v1 + (v2-v1)*portion\n return ans\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": []
}
] |
julianazk/stock_cnn | [
"bb809773cc11305048270feff879a73d41b85aef"
] | [
"src/data_generator.py"
] | [
"#\n# Copyright (c) 2020. Asutosh Nayak ([email protected])\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\nimport os\nimport re\nfrom operator import itemgetter\n\nimport pandas as pd\nimport pickle\nimport numpy as np\nimport sklearn.feature_selection\nimport sklearn.model_selection\nimport sklearn.preprocessing\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.feature_selection import SelectKBest\nfrom sklearn.feature_selection import f_classif\nfrom sklearn.feature_selection import mutual_info_classif\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.utils.class_weight import compute_class_weight\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import train_test_split\nimport sklearn.utils\nfrom tqdm.auto import tqdm\nfrom logger import Logger\nfrom utils import *\n\n\nclass DataGenerator:\n def __init__(self, company_code, data_path='./stock_history', output_path='./outputs', strategy_type='original',\n update=False, logger: Logger = None):\n self.company_code = company_code\n self.strategy_type = strategy_type\n self.data_path = data_path\n self.logger = logger\n self.BASE_URL = \"https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED\" \\\n \"&outputsize=full&apikey=KD1I9P1L06Y003R9&datatype=csv&symbol=\"\n self.output_path = output_path\n self.start_col = 'open'\n self.end_col = 'eom_26'\n self.update = update\n self.download_stock_data()\n ##calcula os indicadores e os labels\n self.df = self.create_features()\n ##define pixels das imagens\n self.feat_idx = self.feature_selection()\n self.one_hot_enc = OneHotEncoder(sparse=False, categories='auto')\n self.one_hot_enc.fit(self.df['labels'].values.reshape(-1, 1))\n self.batch_start_date = self.df.head(1).iloc[0][\"timestamp\"]\n self.test_duration_years = 1\n self.logger.append_log(\"{} has data for {} to {}\".format(data_path, self.batch_start_date,\n self.df.tail(1).iloc[0]['timestamp']))\n\n def log(self, text):\n if self.logger:\n self.logger.append_log(text)\n else:\n print(text)\n\n ##baixa os dados das ações\n def download_stock_data(self):\n path_to_company_data = self.data_path\n print(\"path to company data:\", path_to_company_data)\n parent_path = os.sep.join(path_to_company_data.split(os.sep)[:-1])\n if not os.path.exists(parent_path):\n os.makedirs(parent_path)\n print(\"Company Directory created\", parent_path)\n\n if not os.path.exists(path_to_company_data):\n self.log(\"Downloading \" + self.company_code + \" data\")\n download_save(self.BASE_URL + self.company_code, path_to_company_data, self.logger)\n else:\n self.log(\"Data for \" + self.company_code + \" ready to use\")\n\n def calculate_technical_indicators(self, df, col_name, intervals):\n # get_RSI(df, col_name, intervals) # faster but non-smoothed RSI\n get_RSI_smooth(df, col_name, intervals) # momentum\n get_williamR(df, col_name, intervals) # momentum\n get_mfi(df, intervals) # momentum\n # get_MACD(df, col_name, intervals) # momentum, ready to use +3\n # get_PPO(df, col_name, intervals) # momentum, ready to use +1\n get_ROC(df, col_name, intervals) # momentum\n get_CMF(df, col_name, intervals) # momentum, volume EMA\n get_CMO(df, col_name, intervals) # momentum\n get_SMA(df, col_name, intervals)\n get_SMA(df, 'open', intervals)\n get_EMA(df, col_name, intervals)\n get_WMA(df, col_name, intervals)\n get_HMA(df, col_name, intervals)\n get_TRIX(df, col_name, intervals) # trend\n get_CCI(df, col_name, intervals) # trend\n get_DPO(df, col_name, intervals) # Trend oscillator\n get_kst(df, col_name, intervals) # Trend\n get_DMI(df, col_name, intervals) # trend\n get_BB_MAV(df, col_name, intervals) # volatility\n # get_PSI(df, col_name, intervals) # can't find formula\n get_force_index(df, intervals) # volume\n get_kdjk_rsv(df, intervals) # ready to use, +2*len(intervals), 2 rows\n get_EOM(df, col_name, intervals) # volume momentum\n get_volume_delta(df) # volume +1\n get_IBR(df) # ready to use +1\n\n def create_labels(self, df, col_name, window_size=11):\n \"\"\"\n Data is labeled as per the logic in research paper\n Label code : BUY => 1, SELL => 0, HOLD => 2\n\n params :\n df => Dataframe with data\n col_name => name of column which should be used to determine strategy\n\n returns : numpy array with integer codes for labels with\n size = total-(window_size)+1\n \"\"\"\n\n self.log(\"creating label with original paper strategy\")\n row_counter = 0\n total_rows = len(df)\n labels = np.zeros(total_rows)\n labels[:] = np.nan\n print(\"Calculating labels\")\n pbar = tqdm(total=total_rows)\n\n\n while row_counter < total_rows:\n\n if row_counter >= window_size - 1:\n\n window_begin = row_counter - (window_size - 1)\n window_end = row_counter\n window_middle = (window_begin + window_end) // 2\n\n min_ = np.inf\n min_index = -1\n max_ = -np.inf\n max_index = -1\n\n for i in range(window_begin, window_end + 1):\n\n price = df.iloc[i][col_name]\n\n if price < min_:\n min_ = price\n min_index = i\n if price > max_:\n max_ = price\n max_index = i\n\n if max_index == window_middle:\n labels[window_middle] = 0\n elif min_index == window_middle:\n labels[window_middle] = 1\n else:\n labels[window_middle] = 2\n\n\n row_counter = row_counter + 1\n\n pbar.update(1)\n\n pbar.close()\n return labels\n\n\n def create_label_short_long_ma_crossover(self, df, col_name, short, long):\n \"\"\"\n if short = 30 and long = 90,\n Buy when 30 day MA < 90 day MA\n Sell when 30 day MA > 90 day MA\n\n Label code : BUY => 1, SELL => 0, HOLD => 2\n\n params :\n df => Dataframe with data\n col_name => name of column which should be used to determine strategy\n\n returns : numpy array with integer codes for labels\n \"\"\"\n\n def detect_crossover(diff_prev, diff):\n if diff_prev >= 0 > diff:\n # buy\n return 1\n elif diff_prev <= 0 < diff:\n return 0\n else:\n return 2\n\n get_SMA(df, 'close', [short, long])\n labels = np.zeros((len(df)))\n labels[:] = np.nan\n diff = df['close_sma_' + str(short)] - df['close_sma_' + str(long)]\n diff_prev = diff.shift()\n df['diff_prev'] = diff_prev\n df['diff'] = diff\n\n res = df.apply(lambda row: detect_crossover(row['diff_prev'], row['diff']), axis=1)\n print(\"labels count\", np.unique(res, return_counts=True))\n df.drop(columns=['diff_prev', 'diff'], inplace=True)\n return res\n\n ##calcula indicadores e labels\n def create_features(self):\n if not os.path.exists(os.path.join(self.output_path, \"df_\" + self.company_code+\".csv\")) or self.update:\n df = pd.read_csv(self.data_path, engine='python')\n df['timestamp'] = pd.to_datetime(df['timestamp'])\n df.sort_values('timestamp', inplace=True)\n df.reset_index(drop=True, inplace=True)\n intervals = range(6, 27) # 21\n self.calculate_technical_indicators(df, 'close', intervals)\n self.log(\"Saving dataframe...\")\n df.to_csv(os.path.join(self.output_path, \"df_\" + self.company_code+\".csv\"), index=False)\n else:\n self.log(\"Technical indicators already calculated. Loading...\")\n df = pd.read_csv(os.path.join(self.output_path, \"df_\" + self.company_code+\".csv\"))\n df['timestamp'] = pd.to_datetime(df['timestamp'])\n df.sort_values('timestamp', inplace=True)\n df.reset_index(drop=True, inplace=True)\n\n prev_len = len(df)\n df.dropna(inplace=True)\n df.reset_index(drop=True, inplace=True)\n\n if 'labels' not in df.columns or self.update:\n if re.match(r\"\\d+_\\d+_ma\", self.strategy_type):\n short = self.strategy_type.split('_')[0]\n long = self.strategy_type.split('_')[1]\n df['labels'] = self.create_label_short_long_ma_crossover(df, 'close', short, long)\n else:\n df['labels'] = self.create_labels(df, 'close')\n\n prev_len = len(df)\n df.dropna(inplace=True)\n df.reset_index(drop=True, inplace=True)\n\n df.drop(columns=['dividend_amount', 'split_coefficient'], inplace=True)\n df.to_csv(os.path.join(self.output_path, \"df_\" + self.company_code + \".csv\"), index=False)\n else:\n print(\"labels já calculados\")\n return df\n\n def feature_selection(self):\n ##define o intervalo em anos\n df_batch = self.df_by_date(None, 10)\n list_features = list(df_batch.loc[:, self.start_col:self.end_col].columns)\n\n ##normaliza os valores entre 0 e 1\n mm_scaler = MinMaxScaler(feature_range=(0, 1)) # or StandardScaler?\n ##mm_scaler = StandardScaler() # or StandardScaler?\n x_train = mm_scaler.fit_transform(df_batch.loc[:, self.start_col:self.end_col].values)\n y_train = df_batch['labels'].values\n num_features = 225 # should be a perfect square\n topk = 350\n select_k_best = SelectKBest(f_classif, k=topk)\n select_k_best.fit(x_train, y_train)\n selected_features_anova = itemgetter(*select_k_best.get_support(indices=True))(list_features)\n\n select_k_best = SelectKBest(mutual_info_classif, k=topk)\n select_k_best.fit(x_train, y_train)\n selected_features_mic = itemgetter(*select_k_best.get_support(indices=True))(list_features)\n\n common = list(set(selected_features_anova).intersection(selected_features_mic))\n self.log(\"common selected featues:\" + str(len(common)) + \", \" + str(common))\n if len(common) < num_features:\n raise Exception(\n 'number of common features found {} < {} required features. Increase \"topK\"'.format(len(common),\n num_features))\n feat_idx = []\n for c in common:\n feat_idx.append(list_features.index(c))\n feat_idx = sorted(feat_idx[0:225])\n self.log(str(feat_idx))\n return feat_idx\n\n def df_by_date(self, start_date=None, years=5):\n if not start_date:\n start_date = self.df.head(1).iloc[0][\"timestamp\"]\n\n end_date = start_date + pd.offsets.DateOffset(years=years)\n df_batch = self.df[(self.df[\"timestamp\"] >= start_date) & (self.df[\"timestamp\"] <= end_date)]\n return df_batch\n\n def get_data(self, start_date=None, years=5):\n df_batch = self.df_by_date(start_date, years)\n x = df_batch.loc[:, self.start_col:self.end_col].values\n x = x[:, self.feat_idx]\n print('x:')\n print(start_date)\n print(years)\n print(df_batch.loc[:, self.start_col:self.end_col].values)\n print(x)\n mm_scaler = MinMaxScaler(feature_range=(0, 1)) # or StandardScaler?\n x = mm_scaler.fit_transform(x)\n dim = int(np.sqrt(x.shape[1]))\n x = reshape_as_image(x, dim, dim)\n ##converte array em imagens\n x = save_array_as_images(x, dim, dim, './images', 'imagem')\n x = np.stack((x,) * 3, axis=-1)\n\n y = df_batch['labels'].values\n sample_weights = self.get_sample_weights(y)\n y = self.one_hot_enc.transform(y.reshape(-1, 1))\n\n return x, y, df_batch, sample_weights\n\n def get_sample_weights(self, y):\n \"\"\"\n calculate the sample weights based on class weights. Used for models with\n imbalanced data and one hot encoding prediction.\n\n params:\n y: class labels as integers\n \"\"\"\n\n y = y.astype(int) # compute_class_weight needs int labels\n class_weights = compute_class_weight('balanced', np.unique(y), y)\n\n print(\"real class weights are {}\".format(class_weights), np.unique(y))\n print(\"value_counts\", np.unique(y, return_counts=True))\n sample_weights = y.copy().astype(float)\n for i in np.unique(y):\n sample_weights[sample_weights == i] = class_weights[i] # if i == 2 else 0.8 * class_weights[i]\n # sample_weights = np.where(sample_weights == i, class_weights[int(i)], y_)\n\n return sample_weights\n\n\n"
] | [
[
"pandas.read_csv",
"pandas.to_datetime",
"numpy.sqrt",
"numpy.unique",
"sklearn.preprocessing.OneHotEncoder",
"pandas.offsets.DateOffset",
"numpy.stack",
"sklearn.feature_selection.SelectKBest",
"numpy.zeros",
"sklearn.preprocessing.MinMaxScaler"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
FredericoNesti/gym-idsgame | [
"4170cb5cb3ec787adf5911364e0c6395412b9de9"
] | [
"gym_idsgame/agents/training_agents/policy_gradient/actor_critic/actor_critic.py"
] | [
"\"\"\"\nAn agent for the IDSGameEnv that implements the REINFORCE with Baseline (Critic) Policy Gradient algorithm.\n\"\"\"\nfrom typing import Union, List\nimport numpy as np\nimport time\nimport tqdm\nimport torch\nimport copy\nfrom scipy.special import softmax\nfrom torch.distributions import Categorical\nfrom torch.utils.tensorboard import SummaryWriter\nfrom gym_idsgame.envs.rendering.video.idsgame_monitor import IdsGameMonitor\nfrom gym_idsgame.envs.idsgame_env import IdsGameEnv\nfrom gym_idsgame.agents.dao.experiment_result import ExperimentResult\nfrom gym_idsgame.envs.constants import constants\nfrom gym_idsgame.agents.training_agents.models.fnn_actor_critic import FFNActorCritic\nfrom gym_idsgame.agents.training_agents.policy_gradient.pg_agent import PolicyGradientAgent\nfrom gym_idsgame.agents.training_agents.policy_gradient.pg_agent_config import PolicyGradientAgentConfig\nfrom gym_idsgame.envs.util import idsgame_util\n\nclass ActorCriticAgent(PolicyGradientAgent):\n \"\"\"\n An implementation of the REINFORCE with Advantage Baseline (Actor Critic) Policy Gradient algorithm\n \"\"\"\n def __init__(self, env:IdsGameEnv, config: PolicyGradientAgentConfig):\n \"\"\"\n Initialize environment and hyperparameters\n\n :param config: the configuration\n \"\"\"\n super(ActorCriticAgent, self).__init__(env, config)\n self.attacker_policy_network = None\n self.defender_policy_network = None\n self.critic_loss_fn = None\n self.attacker_optimizer = None\n self.defender_optimizer = None\n self.attacker_lr_decay = None\n self.defender_lr_decay = None\n self.tensorboard_writer = SummaryWriter(self.config.tensorboard_dir)\n if self.config.opponent_pool and self.config.opponent_pool_config is not None:\n self.attacker_pool = []\n self.defender_pool = []\n self.initialize_models()\n self.tensorboard_writer.add_hparams(self.config.hparams_dict(), {})\n self.machine_eps = np.finfo(np.float32).eps.item()\n self.env.idsgame_config.save_trajectories = False\n self.env.idsgame_config.save_attack_stats = False\n self.train_attacker = True\n self.train_defender = True\n\n def initialize_models(self) -> None:\n \"\"\"\n Initialize models\n :return: None\n \"\"\"\n\n # Initialize models\n self.attacker_policy_network = FFNActorCritic(self.config.input_dim_attacker, self.config.output_dim_attacker,\n self.config.hidden_dim,\n num_hidden_layers=self.config.num_hidden_layers,\n hidden_activation=self.config.hidden_activation)\n self.defender_policy_network = FFNActorCritic(self.config.input_dim_defender, self.config.output_dim_defender,\n self.config.hidden_dim,\n num_hidden_layers=self.config.num_hidden_layers,\n hidden_activation=self.config.hidden_activation)\n\n # Specify device\n if torch.cuda.is_available() and self.config.gpu:\n device = torch.device(\"cuda:\" + str(self.config.gpu_id))\n self.config.logger.info(\"Running on the GPU\")\n else:\n device = torch.device(\"cpu\")\n self.config.logger.info(\"Running on the CPU\")\n\n self.attacker_policy_network.to(device)\n self.defender_policy_network.to(device)\n\n # Construct loss function\n if self.config.critic_loss_fn == \"MSE\":\n self.critic_loss_fn = torch.nn.MSELoss()\n elif self.config.critic_loss_fn == \"Huber\":\n self.critic_loss_fn = torch.nn.SmoothL1Loss()\n else:\n raise ValueError(\"Loss function not recognized\")\n\n # Define Optimizer. The call to model.parameters() in the optimizer constructor will contain the learnable\n # parameters of the layers in the model\n if self.config.optimizer == \"Adam\":\n self.attacker_optimizer = torch.optim.Adam(self.attacker_policy_network.parameters(), lr=self.config.alpha_attacker)\n self.defender_optimizer = torch.optim.Adam(self.defender_policy_network.parameters(), lr=self.config.alpha_defender)\n elif self.config.optimizer == \"SGD\":\n self.attacker_optimizer = torch.optim.SGD(self.attacker_policy_network.parameters(), lr=self.config.alpha_attacker)\n self.defender_optimizer = torch.optim.SGD(self.defender_policy_network.parameters(), lr=self.config.alpha_defender)\n else:\n raise ValueError(\"Optimizer not recognized\")\n\n # LR decay\n if self.config.lr_exp_decay:\n self.attacker_lr_decay = torch.optim.lr_scheduler.ExponentialLR(optimizer=self.attacker_optimizer,\n gamma=self.config.lr_decay_rate)\n self.defender_lr_decay = torch.optim.lr_scheduler.ExponentialLR(optimizer=self.defender_optimizer,\n gamma=self.config.lr_decay_rate)\n\n self.add_model_to_pool(attacker=True)\n self.add_model_to_pool(attacker=False)\n\n def add_model_to_pool(self, attacker=True) -> None:\n \"\"\"\n Adds a model to the pool of opponents\n\n :param attacker: boolean flag indicating whether adding attacker model or defender model\n :return: None\n \"\"\"\n if self.config.opponent_pool and self.config.opponent_pool_config is not None:\n if attacker:\n model_copy = copy.deepcopy(self.attacker_policy_network)\n if len(self.attacker_pool) >= self.config.opponent_pool_config.pool_maxsize:\n self.attacker_pool.pop(0)\n if self.config.opponent_pool_config.quality_scores:\n if len(self.attacker_pool) == 0:\n self.attacker_pool.append([model_copy, self.config.opponent_pool_config.initial_quality])\n elif len(self.attacker_pool) > 0:\n qualities = self.get_attacker_pool_quality_scores()\n max_q = max(qualities)\n self.attacker_pool.append([model_copy, max_q])\n else:\n self.attacker_pool.append(model_copy)\n else:\n model_copy = copy.deepcopy(self.defender_policy_network)\n if len(self.defender_pool) >= self.config.opponent_pool_config.pool_maxsize:\n self.defender_pool.pop(0)\n if self.config.opponent_pool_config.quality_scores:\n if len(self.defender_pool) == 0:\n self.defender_pool.append([model_copy, self.config.opponent_pool_config.initial_quality])\n elif len(self.defender_pool) > 0:\n qualities = self.get_defender_pool_quality_scores()\n max_q = max(qualities)\n self.defender_pool.append([model_copy, max_q])\n else:\n self.defender_pool.append(model_copy)\n\n def sample_opponent(self, attacker=True):\n if attacker:\n if self.config.opponent_pool_config.quality_scores:\n quality_scores = self.get_attacker_pool_quality_scores()\n softmax_dist = self.get_softmax_distribution(quality_scores)\n return np.random.choice(list(range(len(self.attacker_pool))), size=1, p=softmax_dist)[0]\n else:\n return np.random.choice(list(range(len(self.attacker_pool))), size=1)[0]\n else:\n if self.config.opponent_pool_config.quality_scores:\n quality_scores = self.get_defender_pool_quality_scores()\n softmax_dist = self.get_softmax_distribution(quality_scores)\n return np.random.choice(list(range(len(self.defender_pool))), size=1, p=softmax_dist)[0]\n else:\n return np.random.choice(list(range(len(self.defender_pool))), size=1)[0]\n\n def get_softmax_distribution(self, qualities) -> np.ndarray:\n \"\"\"\n Converts a list of quality scores into a distribution with softmax\n\n :param qualities: the list of quality scores\n :return: the softmax distribution\n \"\"\"\n return softmax(qualities)\n\n def get_attacker_pool_quality_scores(self):\n \"\"\"\n :return: Returns the quality scores from the attacker pool\n \"\"\"\n return list(map(lambda x: x[1], self.attacker_pool))\n\n def get_defender_pool_quality_scores(self):\n \"\"\"\n :return: Returns the quality scores from the defender pool\n \"\"\"\n return list(map(lambda x: x[1], self.defender_pool))\n\n def training_step(self, saved_rewards : List[List[float]], saved_log_probs : List[List[torch.Tensor]],\n saved_state_values : List[List[torch.Tensor]], attacker=True) -> torch.Tensor:\n \"\"\"\n Performs a training step of the Deep-Q-learning algorithm (implemented in PyTorch)\n\n :param saved_rewards list of rewards encountered in the latest episode trajectory\n :param saved_log_probs list of log-action probabilities (log p(a|s)) encountered in the latest episode trajectory\n :param saved_state_values list of state values encountered in the latest episode trajectory\n :return: loss\n \"\"\"\n\n policy_loss = [] # list to save actor (policy) loss\n value_loss = [] # list to save critic (value) loss\n num_batches = len(saved_rewards)\n\n for batch in range(num_batches):\n R = 0\n returns = [] # list to save the true (observed) values\n # Create discounted returns. When episode is finished we can go back and compute the observed cumulative\n # discounted reward by using the observed rewards\n for r in saved_rewards[batch][::-1]:\n R = r + self.config.gamma * R\n returns.insert(0, R)\n num_rewards = len(returns)\n\n # convert list to torch tensor\n returns = torch.tensor(returns)\n\n # normalize\n std = returns.std()\n if num_rewards < 2:\n std = 0\n returns = (returns - returns.mean()) / (std + self.machine_eps)\n\n # Compute PG \"loss\" which in reality is the expected reward, which we want to maximize with gradient ascent\n for log_prob, state_value, R in zip(saved_log_probs[batch], saved_state_values[batch], returns):\n # Compute the advantage which will be used as a baseline in REINFORCE to reduce the gradient variance\n # Intuitively, the advantage tells us how much better the observed reward was compared to the expected reward\n # If the advantage of an action is high, it means that the current policy should be modified to reinforce\n # that action. That is, the advantage tells us for every action much better that action is than\n # the average action.\n advantage = R - state_value.item()\n\n # negative log probsince we are doing gradient descent (not ascent)\n policy_loss.append(-log_prob * advantage)\n\n R_tensor = torch.tensor([R])\n\n # Move to GPU if using GPU\n if torch.cuda.is_available() and self.config.gpu:\n device = torch.device(\"cuda:\" + str(self.config.gpu_id))\n state_value = state_value.to(device)\n R_tensor = R_tensor.to(device)\n\n\n # calculate critic loss using Huber loss\n value_loss.append(self.critic_loss_fn(state_value, R_tensor))\n\n\n # Compute gradient and update models\n if attacker:\n # reset gradients\n self.attacker_optimizer.zero_grad()\n # sum up all the values of policy losses and value losses\n total_loss = (torch.stack(policy_loss).sum() + torch.stack(value_loss).sum())\n loss = total_loss/num_batches\n # perform backprop\n loss.backward()\n # maybe clip gradient\n if self.config.clip_gradient:\n torch.nn.utils.clip_grad_norm_(self.attacker_policy_network.parameters(), 1)\n # gradient descent step\n self.attacker_optimizer.step()\n else:\n # reset gradients\n self.defender_optimizer.zero_grad()\n # sum up all the values of policy losses and value losses\n total_loss = torch.stack(policy_loss).sum() + torch.stack(value_loss).sum()\n loss = total_loss / num_batches\n # perform backprop\n loss.backward()\n # maybe clip gradient\n if self.config.clip_gradient:\n torch.nn.utils.clip_grad_norm_(self.defender_policy_network.parameters(), 1)\n # gradient descent step\n self.defender_optimizer.step()\n\n return loss\n\n\n def get_action(self, state: np.ndarray, attacker : bool = True, opponent_pool = False,\n legal_actions: List = None, non_legal_actions: List = None) -> Union[int, torch.Tensor, torch.Tensor, np.ndarray]:\n \"\"\"\n Samples an action from the policy network\n\n :param state: the state to sample an action for\n :param attacker: boolean flag whether running in attacker mode (if false assume defender)\n :param opponent_pool: boolean flag, if true get model from opponent pool\n :param legal_actions: list of allowed actions\n :param non_legal_actions: list of disallowed actions\n :return: The sampled action id, log probability of action id, state value, action distribution\n \"\"\"\n state = torch.from_numpy(state.flatten()).float()\n\n # Move to GPU if using GPU\n if torch.cuda.is_available() and self.config.gpu:\n device = torch.device(\"cuda:\" + str(self.config.gpu_id))\n state = state.to(device)\n\n # Calculate legal actions\n if attacker:\n actions = list(range(self.env.num_attack_actions))\n if not self.env.local_view_features() or (legal_actions is None or non_legal_actions is None):\n legal_actions = list(filter(lambda action: self.env.is_attack_legal(action), actions))\n non_legal_actions = list(filter(lambda action: not self.env.is_attack_legal(action), actions))\n else:\n actions = list(range(self.env.num_defense_actions))\n legal_actions = list(filter(lambda action: self.env.is_defense_legal(action), actions))\n non_legal_actions = list(filter(lambda action: not self.env.is_defense_legal(action), actions))\n\n # Forward pass using the current policy network to predict P(a|s)\n if attacker:\n if opponent_pool:\n action_probs, state_value = self.attacker_opponent(state)\n else:\n action_probs, state_value = self.attacker_policy_network(state)\n else:\n if opponent_pool:\n action_probs, state_value = self.defender_opponent(state)\n else:\n action_probs, state_value = self.defender_policy_network(state)\n\n # Set probability of non-legal actions to 0\n action_probs_1 = action_probs.clone()\n if len(legal_actions) > 0:\n action_probs_1[non_legal_actions] = 0\n\n # Use torch.distributions package to create a parameterizable probability distribution of the learned policy\n # PG uses a trick to turn the gradient into a stochastic gradient which we can sample from in order to\n # approximate the true gradient (which we can’t compute directly). It can be seen as an alternative to the\n # reparameterization trick\n policy_dist = Categorical(action_probs_1)\n\n # Sample an action from the probability distribution\n action = policy_dist.sample()\n\n # log_prob returns the log of the probability density/mass function evaluated at value.\n # save the log_prob as it will use later on for computing the policy gradient\n # policy gradient theorem says that the stochastic gradient of the expected return of the current policy is\n # the log gradient of the policy times the expected return, therefore we save the log of the policy distribution\n # now and use it later to compute the gradient once the episode has finished.\n log_prob = policy_dist.log_prob(action)\n\n return action.item(), log_prob, state_value, action_probs\n\n\n def train(self) -> ExperimentResult:\n \"\"\"\n Runs the REINFORCE with Baseline algorithm\n\n :return: Experiment result\n \"\"\"\n self.config.logger.info(\"Starting Training\")\n self.config.logger.info(self.config.to_str())\n if len(self.train_result.avg_episode_steps) > 0:\n self.config.logger.warning(\"starting training with non-empty result object\")\n done = False\n obs = self.env.reset(update_stats=False)\n attacker_obs, defender_obs = obs\n\n attacker_state = self.update_state(attacker_obs=attacker_obs, defender_obs=defender_obs, state=[], attacker=True)\n defender_state = self.update_state(defender_obs=defender_obs, attacker_obs=attacker_obs, state=[], attacker=False)\n\n # Tracking metrics\n episode_attacker_rewards = []\n episode_defender_rewards = []\n episode_steps = []\n episode_avg_attacker_loss = []\n episode_avg_defender_loss = []\n\n # Logging\n self.outer_train.set_description_str(\"[Train] epsilon:{:.2f},avg_a_R:{:.2f},avg_d_R:{:.2f},\"\n \"avg_t:{:.2f},avg_h:{:.2f},acc_A_R:{:.2f},\" \\\n \"acc_D_R:{:.2f}\".format(self.config.epsilon, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0))\n\n train_attacker = True\n train_defender = True\n if self.config.alternating_optimization:\n train_attacker = False\n if self.config.opponent_pool and self.config.opponent_pool_config is not None:\n if np.random.rand() < self.config.opponent_pool_config.pool_prob:\n self.defender_opponent_idx = self.sample_opponent(attacker=False)\n if self.config.opponent_pool_config.quality_scores:\n self.defender_opponent = self.defender_pool[self.defender_opponent_idx][0]\n else:\n self.defender_opponent = self.defender_pool[self.defender_opponent_idx]\n else:\n self.defender_opponent = self.defender_policy_network\n self.defender_opponent_idx = None\n\n if np.random.rand() < self.config.opponent_pool_config.pool_prob:\n self.attacker_opponent_idx = self.sample_opponent(attacker=True)\n if self.config.opponent_pool_config.quality_scores:\n self.attacker_opponent = self.attacker_pool[self.attacker_opponent_idx][0]\n else:\n self.attacker_opponent = self.attacker_pool[self.attacker_opponent_idx]\n else:\n self.attacker_opponent = self.attacker_policy_network\n self.attacker_opponent_idx = None\n\n num_alt_iterations = 0\n num_attacker_pool_iterations = 0\n num_defender_pool_iterations = 0\n num_attacker_opponent_iterations = 0\n num_defender_opponent_iterations = 0\n\n attacker_initial_state_action_dist = np.zeros(self.config.output_dim_attacker)\n defender_initial_state_action_dist = np.zeros(self.config.output_dim_defender)\n\n saved_attacker_log_probs_batch = []\n saved_attacker_rewards_batch = []\n saved_attacker_state_values_batch = []\n saved_defender_log_probs_batch = []\n saved_defender_rewards_batch = []\n saved_defender_state_values_batch = []\n\n total_num_episodes = 0\n\n # Training\n for iter in range(self.config.num_episodes):\n # Batch\n for episode in range(self.config.batch_size):\n episode_attacker_reward = 0\n episode_defender_reward = 0\n episode_step = 0\n episode_attacker_loss = 0.0\n episode_defender_loss = 0.0\n saved_attacker_log_probs = []\n saved_attacker_rewards = []\n saved_attacker_state_values = []\n saved_defender_log_probs = []\n saved_defender_rewards = []\n saved_defender_state_values = []\n while not done:\n if self.config.render:\n self.env.render(mode=\"human\")\n\n if not self.config.attacker and not self.config.defender:\n raise AssertionError(\"Must specify whether training an attacker agent or defender agent\")\n\n # Default initialization\n attacker_action = 0\n defender_action = 0\n\n # Get attacker and defender actions\n if self.config.attacker:\n legal_actions = None\n illegal_actions = None\n if self.env.local_view_features():\n legal_actions, illegal_actions = self.get_legal_attacker_actions(attacker_obs)\n if self.config.alternating_optimization and not train_attacker \\\n and self.config.opponent_pool and self.config.opponent_pool_config is not None:\n attacker_action, attacker_log_prob, attacker_state_value, attacker_action_dist = self.get_action(\n attacker_state, attacker=True, opponent_pool=True, legal_actions=legal_actions,\n non_legal_actions=illegal_actions)\n else:\n attacker_action, attacker_log_prob, attacker_state_value, attacker_action_dist = \\\n self.get_action(attacker_state, attacker=True, opponent_pool=False,\n legal_actions=legal_actions, non_legal_actions=illegal_actions)\n if self.env.local_view_features():\n attacker_action = PolicyGradientAgent.convert_local_attacker_action_to_global(attacker_action, attacker_obs)\n saved_attacker_log_probs.append(attacker_log_prob)\n saved_attacker_state_values.append(attacker_state_value)\n if episode_step == 0:\n attacker_initial_state_action_dist = attacker_action_dist\n\n if self.config.defender:\n if self.config.alternating_optimization and not train_defender \\\n and self.config.opponent_pool and self.config.opponent_pool_config is not None:\n defender_action, defender_log_prob, defender_state_value, defender_action_dist = self.get_action(\n defender_state, attacker=False, opponent_pool=True)\n else:\n defender_action, defender_log_prob, defender_state_value, defender_action_dist = \\\n self.get_action(defender_state, attacker=False, opponent_pool=False)\n saved_defender_log_probs.append(defender_log_prob)\n saved_defender_state_values.append(defender_state_value)\n if episode_step == 0:\n defender_initial_state_action_dist = defender_action_dist\n\n action = (attacker_action, defender_action)\n\n # Take a step in the environment\n obs_prime, reward, done, _ = self.env.step(action)\n\n # Update metrics\n attacker_reward, defender_reward = reward\n obs_prime_attacker, obs_prime_defender = obs_prime\n episode_attacker_reward += attacker_reward\n saved_attacker_rewards.append(attacker_reward)\n episode_defender_reward += defender_reward\n saved_defender_rewards.append(defender_reward)\n episode_step += 1\n\n # Move to the next state\n obs = obs_prime\n attacker_obs = obs_prime_attacker\n defender_obs = obs_prime_defender\n attacker_state = self.update_state(attacker_obs=attacker_obs, defender_obs=defender_obs, state=attacker_state, attacker=True)\n defender_state = self.update_state(defender_obs=defender_obs, attacker_obs=attacker_obs, state=defender_state, attacker=False)\n\n\n # Render final frame\n if self.config.render:\n self.env.render(mode=\"human\")\n\n # Accumulate batch\n saved_attacker_log_probs_batch.append(saved_attacker_log_probs)\n saved_attacker_rewards_batch.append(saved_attacker_rewards)\n saved_attacker_state_values_batch.append(saved_attacker_state_values)\n saved_defender_log_probs_batch.append(saved_defender_log_probs)\n saved_defender_rewards_batch.append(saved_defender_rewards)\n saved_defender_state_values_batch.append(saved_defender_state_values)\n\n # Record episode metrics\n self.num_train_games += 1\n self.num_train_games_total += 1\n if self.env.state.hacked:\n self.num_train_hacks += 1\n self.num_train_hacks_total += 1\n\n episode_attacker_rewards.append(episode_attacker_reward)\n episode_defender_rewards.append(episode_defender_reward)\n episode_steps.append(episode_step)\n\n # Reset environment for the next episode and update game stats\n done = False\n attacker_obs, defender_obs = self.env.reset(update_stats=True)\n attacker_state = self.update_state(attacker_obs=attacker_obs, defender_obs=defender_obs, state=[],\n attacker=True)\n defender_state = self.update_state(defender_obs=defender_obs, attacker_obs=attacker_obs, state=[],\n attacker=False)\n\n # If using opponent pool, update the pool\n if self.config.opponent_pool and self.config.opponent_pool_config is not None:\n if train_attacker:\n if num_attacker_pool_iterations > self.config.opponent_pool_config.pool_increment_period:\n self.add_model_to_pool(attacker=True)\n num_attacker_pool_iterations = 0\n\n if num_defender_opponent_iterations > self.config.opponent_pool_config.head_to_head_period:\n if np.random.rand() < self.config.opponent_pool_config.pool_prob:\n self.defender_opponent_idx = self.sample_opponent(attacker=False)\n if self.config.opponent_pool_config.quality_scores:\n self.defender_opponent = self.defender_pool[self.defender_opponent_idx][0]\n else:\n self.defender_opponent = self.defender_pool[self.defender_opponent_idx]\n else:\n self.defender_opponent = self.defender_policy_network\n self.defender_opponent_idx = None\n num_defender_opponent_iterations = 0\n\n if train_defender:\n if num_defender_pool_iterations > self.config.opponent_pool_config.pool_increment_period:\n self.add_model_to_pool(attacker=False)\n num_defender_pool_iterations = 0\n\n if num_attacker_opponent_iterations > self.config.opponent_pool_config.head_to_head_period:\n if np.random.rand() < self.config.opponent_pool_config.pool_prob:\n self.attacker_opponent_idx = self.sample_opponent(attacker=True)\n if self.config.opponent_pool_config.quality_scores:\n self.attacker_opponent = self.attacker_pool[self.attacker_opponent_idx][0]\n else:\n self.attacker_opponent = self.attacker_pool[self.attacker_opponent_idx]\n else:\n self.attacker_opponent = self.attacker_policy_network\n self.attacker_opponent_idx = None\n\n num_attacker_opponent_iterations = 0\n total_num_episodes += 1\n\n # End Batch\n\n # Perform Policy Gradient updates\n if self.config.attacker:\n if not self.config.alternating_optimization or \\\n (self.config.alternating_optimization and train_attacker):\n loss = self.training_step(saved_attacker_rewards_batch, saved_attacker_log_probs_batch,\n saved_attacker_state_values_batch, attacker=True)\n episode_attacker_loss += loss.item()\n\n if self.config.defender:\n if not self.config.alternating_optimization or \\\n (self.config.alternating_optimization and train_defender):\n loss = self.training_step(saved_defender_rewards_batch, saved_defender_log_probs_batch,\n saved_defender_state_values_batch, attacker=False)\n episode_defender_loss += loss.item()\n\n # Reset batch\n saved_attacker_log_probs_batch = []\n saved_attacker_rewards_batch = []\n saved_attacker_state_values_batch = []\n saved_defender_log_probs_batch = []\n saved_defender_rewards_batch = []\n saved_defender_state_values_batch = []\n\n # Log values and gradients of the parameters (histogram summary) to tensorboard\n if self.config.attacker and train_attacker:\n for tag, value in self.attacker_policy_network.named_parameters():\n tag = tag.replace('.', '/')\n self.tensorboard_writer.add_histogram(tag, value.data.cpu().numpy(), iter)\n self.tensorboard_writer.add_histogram(tag + '_attacker/grad',\n value.grad.data.cpu().numpy(),\n iter)\n\n if self.config.defender and train_defender:\n for tag, value in self.defender_policy_network.named_parameters():\n tag = tag.replace('.', '/')\n self.tensorboard_writer.add_histogram(tag, value.data.cpu().numpy(), iter)\n self.tensorboard_writer.add_histogram(tag + '_defender/grad',\n value.grad.data.cpu().numpy(),\n iter)\n num_alt_iterations += 1\n\n if self.config.batch_size > 0:\n if self.config.attacker:\n episode_avg_attacker_loss.append(episode_attacker_loss / self.config.batch_size)\n if self.config.defender:\n episode_avg_defender_loss.append(episode_defender_loss / self.config.batch_size)\n else:\n if self.config.attacker:\n episode_avg_attacker_loss.append(episode_attacker_loss)\n if self.config.defender:\n episode_avg_defender_loss.append(episode_defender_loss)\n\n # Decay LR after every iteration\n lr_attacker = self.config.alpha_attacker\n if self.config.lr_exp_decay:\n self.attacker_lr_decay.step()\n lr_attacker = self.attacker_lr_decay.get_lr()[0]\n\n # Decay LR after every iter\n lr_defender = self.config.alpha_attacker\n if self.config.lr_exp_decay:\n self.defender_lr_decay.step()\n lr_defender = self.defender_lr_decay.get_lr()[0]\n\n if self.config.alternating_optimization and self.config.opponent_pool:\n if train_attacker:\n num_attacker_pool_iterations += 1\n num_defender_opponent_iterations += 1\n\n if train_defender:\n num_defender_pool_iterations += 1\n num_attacker_opponent_iterations += 1\n\n\n # Update opponent pool qualities\n if self.config.opponent_pool and self.config.opponent_pool_config is not None \\\n and self.config.opponent_pool_config.quality_scores:\n if train_attacker and self.defender_opponent_idx is not None and self.env.state.hacked:\n self.update_quality_score(self.defender_opponent_idx, attacker=False)\n if train_defender and self.attacker_opponent_idx is not None and not self.env.state.hacked:\n self.update_quality_score(self.attacker_opponent_idx, attacker=True)\n\n # Log average metrics every <self.config.train_log_frequency> iterations\n if iter % self.config.train_log_frequency == 0:\n if self.num_train_games > 0 and self.num_train_games_total > 0:\n self.train_hack_probability = self.num_train_hacks / self.num_train_games\n self.train_cumulative_hack_probability = self.num_train_hacks_total / self.num_train_games_total\n else:\n self.train_hack_probability = 0.0\n self.train_cumulative_hack_probability = 0.0\n a_pool = None\n d_pool = None\n if self.config.opponent_pool and self.config.opponent_pool_config is not None:\n a_pool = len(self.attacker_pool)\n d_pool = len(self.defender_pool)\n self.log_metrics(iter, self.train_result, episode_attacker_rewards, episode_defender_rewards, episode_steps,\n episode_avg_attacker_loss, episode_avg_defender_loss, lr_attacker=lr_attacker,\n lr_defender=lr_defender,\n train_attacker = (self.config.attacker and train_attacker),\n train_defender = (self.config.defender and train_defender),\n a_pool=a_pool, d_pool=d_pool, total_num_episodes=total_num_episodes)\n\n episode_attacker_rewards = []\n episode_defender_rewards = []\n episode_steps = []\n self.num_train_games = 0\n self.num_train_hacks = 0\n\n # Run evaluation every <self.config.eval_frequency> iterations\n if iter % self.config.eval_frequency == 0:\n self.eval(iter)\n if self.config.opponent_pool and self.config.opponent_pool_config is not None:\n self.log_action_dist(attacker_initial_state_action_dist, attacker=True)\n self.log_action_dist(defender_initial_state_action_dist, attacker=False)\n\n # Save models and other state every <self.config.checkpoint_frequency> iterations\n if iter % self.config.checkpoint_freq == 0:\n self.save_model()\n self.env.save_trajectories()\n self.env.save_attack_data(checkpoint=True)\n if self.config.save_dir is not None:\n time_str = str(time.time())\n self.train_result.to_csv(self.config.save_dir + \"/\" + time_str + \"_train_results_checkpoint.csv\")\n self.eval_result.to_csv(self.config.save_dir + \"/\" + time_str + \"_eval_results_checkpoint.csv\")\n if self.config.opponent_pool and self.config.opponent_pool_config is not None:\n self.create_policy_plot(attacker_initial_state_action_dist.data.cpu().numpy(), iter,\n attacker=True)\n self.create_policy_plot(defender_initial_state_action_dist.data.cpu().numpy(), iter,\n attacker=False)\n\n # If doing alternating optimization and the alternating period is up, change agent that is optimized\n if self.config.alternating_optimization and num_alt_iterations > self.config.alternating_period:\n train_defender = not train_defender\n train_attacker = not train_attacker\n num_alt_iterations = 0\n\n # Anneal epsilon linearly\n self.anneal_epsilon()\n\n self.outer_train.update(1)\n\n self.config.logger.info(\"Training Complete\")\n\n # Final evaluation (for saving Gifs etc)\n self.eval(self.config.num_episodes-1, log=False)\n\n # Save networks\n self.save_model()\n\n # Save other game data\n self.env.save_trajectories(checkpoint=False)\n self.env.save_attack_data(checkpoint=False)\n if self.config.save_dir is not None:\n time_str = str(time.time())\n self.train_result.to_csv(self.config.save_dir + \"/\" + time_str + \"_train_results_checkpoint.csv\")\n self.eval_result.to_csv(self.config.save_dir + \"/\" + time_str + \"_eval_results_checkpoint.csv\")\n\n return self.train_result\n\n def create_policy_plot(self, distribution, episode, attacker = True) -> None:\n \"\"\"\n Utility function for creating a density plot of the policy distribution p(a|s) and add to Tensorboard\n\n :param distribution: the distribution to plot\n :param episode: the episode when the distribution was recorded\n :param attacker: boolean flag whether it is the attacker or defender\n :return: None\n \"\"\"\n sample = np.random.choice(list(range(len(distribution))), size=1000, p=distribution)\n tag = \"Attacker\"\n file_suffix = \"initial_state_policy_attacker\"\n if not attacker:\n tag = \"Defender\"\n file_suffix = \"initial_state_policy_defender\"\n title = tag + \" Initial State Policy\"\n data = idsgame_util.action_dist_hist(sample, title=title, xlabel=\"Action\", ylabel=r\"$\\mathbb{P}(a|s)$\",\n file_name=self.config.save_dir + \"/\" + file_suffix + \"_\" + str(episode))\n self.tensorboard_writer.add_image(str(episode) + \"_initial_state_policy/\" + tag,\n data, global_step=episode, dataformats=\"HWC\")\n\n def update_quality_score(self, opponent_idx : int, attacker : bool = True) -> None:\n \"\"\"\n Updates the quality score of an opponent in the opponent pool. Using same update rule as was used in\n \"Dota 2 with Large Scale Deep Reinforcement Learning\" by Berner et. al.\n\n :param opponent_idx: the index of the opponent in the pool\n :param attacker: boolean flag whether attacker or defender pool to be updated\n :return: None\n \"\"\"\n if attacker:\n N = len(self.attacker_pool)\n qualities = self.get_attacker_pool_quality_scores()\n dist = self.get_softmax_distribution(qualities)\n p = dist[opponent_idx]\n self.attacker_pool[opponent_idx][1] = self.attacker_pool[opponent_idx][1] - \\\n (self.config.opponent_pool_config.quality_score_eta/(N*p))\n else:\n N = len(self.defender_pool)\n qualities = self.get_defender_pool_quality_scores()\n dist = self.get_softmax_distribution(qualities)\n p = dist[opponent_idx]\n self.defender_pool[opponent_idx][1] = self.defender_pool[opponent_idx][1] - \\\n (self.config.opponent_pool_config.quality_score_eta / (N * p))\n\n\n def eval(self, train_episode, log=True) -> ExperimentResult:\n \"\"\"\n Performs evaluation with the greedy policy with respect to the learned Q-values\n\n :param train_episode: the train episode to keep track of logging\n :param log: whether to log the result\n :return: None\n \"\"\"\n self.config.logger.info(\"Starting Evaluation\")\n time_str = str(time.time())\n\n self.num_eval_games = 0\n self.num_eval_hacks = 0\n\n if len(self.eval_result.avg_episode_steps) > 0:\n self.config.logger.warning(\"starting eval with non-empty result object\")\n if self.config.eval_episodes < 1:\n return\n done = False\n\n # Video config\n if self.config.video:\n if self.config.video_dir is None:\n raise AssertionError(\"Video is set to True but no video_dir is provided, please specify \"\n \"the video_dir argument\")\n self.env = IdsGameMonitor(self.env, self.config.video_dir + \"/\" + time_str, force=True,\n video_frequency=self.config.video_frequency)\n self.env.metadata[\"video.frames_per_second\"] = self.config.video_fps\n\n # Tracking metrics\n episode_attacker_rewards = []\n episode_defender_rewards = []\n episode_steps = []\n\n # Logging\n self.outer_eval = tqdm.tqdm(total=self.config.eval_episodes, desc='Eval Episode', position=1)\n self.outer_eval.set_description_str(\n \"[Eval] avg_a_R:{:.2f},avg_d_R:{:.2f},avg_t:{:.2f},avg_h:{:.2f},acc_A_R:{:.2f},\" \\\n \"acc_D_R:{:.2f}\".format(0.0, 0,0, 0.0, 0.0, 0.0, 0.0))\n\n # Eval\n attacker_obs, defender_obs = self.env.reset(update_stats=False)\n attacker_state = self.update_state(attacker_obs=attacker_obs, defender_obs=defender_obs, state=[], attacker=True)\n defender_state = self.update_state(defender_obs=defender_obs, attacker_obs=attacker_obs, state=[], attacker=False)\n\n for episode in range(self.config.eval_episodes):\n episode_attacker_reward = 0\n episode_defender_reward = 0\n episode_step = 0\n while not done:\n if self.config.eval_render:\n self.env.render()\n time.sleep(self.config.eval_sleep)\n\n # Default initialization\n attacker_action = 0\n defender_action = 0\n\n # Get attacker and defender actions\n if self.config.attacker:\n legal_actions = None\n illegal_actions = None\n if self.env.local_view_features():\n legal_actions, illegal_actions = self.get_legal_attacker_actions(attacker_obs)\n attacker_action, _, _, _ = self.get_action(attacker_state, attacker=True,\n legal_actions=legal_actions,\n non_legal_actions=illegal_actions)\n if self.env.local_view_features():\n attacker_action = PolicyGradientAgent.convert_local_attacker_action_to_global(attacker_action, attacker_obs)\n if self.config.defender:\n defender_action, _, _, _ = self.get_action(defender_state, attacker=False)\n action = (attacker_action, defender_action)\n\n # Take a step in the environment\n obs_prime, reward, done, _ = self.env.step(action)\n\n # Update state information and metrics\n attacker_reward, defender_reward = reward\n obs_prime_attacker, obs_prime_defender = obs_prime\n episode_attacker_reward += attacker_reward\n episode_defender_reward += defender_reward\n episode_step += 1\n attacker_obs = obs_prime_attacker\n defender_obs = obs_prime_defender\n attacker_state = self.update_state(attacker_obs=attacker_obs, defender_obs=defender_obs, state=attacker_state, attacker=True)\n defender_state = self.update_state(defender_obs=defender_obs, attacker_obs=attacker_obs, state=defender_state, attacker=False)\n\n # Render final frame when game completed\n if self.config.eval_render:\n self.env.render()\n time.sleep(self.config.eval_sleep)\n self.config.logger.info(\"Eval episode: {}, Game ended after {} steps\".format(episode, episode_step))\n\n # Record episode metrics\n episode_attacker_rewards.append(episode_attacker_reward)\n episode_defender_rewards.append(episode_defender_reward)\n episode_steps.append(episode_step)\n\n # Update eval stats\n self.num_eval_games +=1\n self.num_eval_games_total += 1\n if self.env.state.detected:\n self.eval_attacker_cumulative_reward -= constants.GAME_CONFIG.POSITIVE_REWARD\n self.eval_defender_cumulative_reward += constants.GAME_CONFIG.POSITIVE_REWARD\n if self.env.state.hacked:\n self.eval_attacker_cumulative_reward += constants.GAME_CONFIG.POSITIVE_REWARD\n self.eval_defender_cumulative_reward -= constants.GAME_CONFIG.POSITIVE_REWARD\n self.num_eval_hacks += 1\n self.num_eval_hacks_total +=1\n\n # Log average metrics every <self.config.eval_log_frequency> episodes\n if episode % self.config.eval_log_frequency == 0 and log:\n if self.num_eval_hacks > 0:\n self.eval_hack_probability = float(self.num_eval_hacks) / float(self.num_eval_games)\n if self.num_eval_games_total > 0:\n self.eval_cumulative_hack_probability = float(self.num_eval_hacks_total) / float(\n self.num_eval_games_total)\n a_pool = None\n d_pool = None\n if self.config.opponent_pool and self.config.opponent_pool_config is not None:\n a_pool = len(self.attacker_pool)\n d_pool = len(self.defender_pool)\n self.log_metrics(episode, self.eval_result, episode_attacker_rewards, episode_defender_rewards, episode_steps,\n eval = True, update_stats=False, a_pool=a_pool, d_pool = d_pool)\n\n # Save gifs\n if self.config.gifs and self.config.video:\n self.env.generate_gif(self.config.gif_dir + \"/episode_\" + str(train_episode) + \"_\"\n + time_str + \".gif\", self.config.video_fps)\n\n # Add frames to tensorboard\n for idx, frame in enumerate(self.env.episode_frames):\n self.tensorboard_writer.add_image(str(train_episode) + \"_eval_frames/\" + str(idx),\n frame, global_step=train_episode,\n dataformats = \"HWC\")\n\n\n # Reset for new eval episode\n done = False\n attacker_obs, defender_obs = self.env.reset(update_stats=False)\n attacker_state = self.update_state(attacker_obs=attacker_obs, defender_obs=defender_obs, state=attacker_state, attacker=True)\n defender_state = self.update_state(defender_obs=defender_obs, attacker_obs=attacker_obs, state=defender_state, attacker=False)\n self.outer_eval.update(1)\n\n # Log average eval statistics\n if log:\n if self.num_eval_hacks > 0:\n self.eval_hack_probability = float(self.num_eval_hacks) / float(self.num_eval_games)\n if self.num_eval_games_total > 0:\n self.eval_cumulative_hack_probability = float(self.num_eval_hacks_total) / float(\n self.num_eval_games_total)\n\n self.log_metrics(train_episode, self.eval_result, episode_attacker_rewards, episode_defender_rewards,\n episode_steps, eval=True, update_stats=True)\n\n self.env.close()\n self.config.logger.info(\"Evaluation Complete\")\n return self.eval_result\n\n def save_model(self) -> None:\n \"\"\"\n Saves the PyTorch Model Weights\n\n :return: None\n \"\"\"\n time_str = str(time.time())\n if self.config.save_dir is not None:\n if self.config.attacker:\n path = self.config.save_dir + \"/\" + time_str + \"_attacker_policy_network.pt\"\n self.config.logger.info(\"Saving policy-network to: {}\".format(path))\n torch.save(self.attacker_policy_network.state_dict(), path)\n if self.config.defender:\n path = self.config.save_dir + \"/\" + time_str + \"_defender_policy_network.pt\"\n self.config.logger.info(\"Saving policy-network to: {}\".format(path))\n torch.save(self.defender_policy_network.state_dict(), path)\n else:\n self.config.logger.warning(\"Save path not defined, not saving policy-networks to disk\")\n"
] | [
[
"torch.nn.SmoothL1Loss",
"torch.optim.lr_scheduler.ExponentialLR",
"torch.tensor",
"numpy.finfo",
"torch.distributions.Categorical",
"torch.utils.tensorboard.SummaryWriter",
"torch.cuda.is_available",
"numpy.random.rand",
"torch.device",
"scipy.special.softmax",
"torch.nn.MSELoss",
"numpy.zeros",
"torch.stack"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.6",
"1.10",
"1.4",
"1.9",
"1.5",
"1.2",
"1.7",
"1.3",
"1.8"
],
"tensorflow": []
}
] |
bartonlin/MWSD | [
"70ad446ee7f00a11988acb290270e32d8e6af925"
] | [
"metric_wsd/utils/utils.py"
] | [
"import os\nimport csv\nimport random\nimport subprocess\nfrom collections import Counter\nfrom argparse import Namespace\nimport glob\nimport yaml\n\nimport torch\nfrom torch.optim import AdamW\n\nfrom metric_wsd.models.models import CBERTLinear, CBERTProto, PairCBERTProto, CBERTProtoConcat\nfrom metric_wsd.config import Config\n\nconfig = Config()\n\n\ndef update_args(args):\n \"\"\"Make args compatible with different models and runs.\"\"\"\n if not hasattr(args, 'dist'):\n setattr(args, 'dist', 'dot')\n if not hasattr(args, 'ks_support_kq_query'):\n setattr(args, 'ks_support_kq_query', None)\n if not hasattr(args, 'global_step'):\n setattr(args, 'global_step', 0)\n if not hasattr(args, 'sample_strategy_threshold'):\n setattr(args, 'sample_strategy_threshold', 0)\n return args\n\n\ndef get_model_class(args):\n if args.model_type == 'cbert-linear':\n model_class = CBERTLinear\n elif args.model_type == 'cbert-proto':\n if args.dist in ('dot', 'l2'):\n model_class = CBERTProto\n elif args.dist == 'concat':\n model_class = CBERTProtoConcat\n elif args.dist.startswith('text'):\n model_class = PairCBERTProto\n else:\n raise ValueError('Model type not implemented.')\n return model_class\n\n\ndef save_ckpt(model, args, f1, epoch, global_step, optimizer, latest=False):\n if not latest:\n args.best_ckpt_path = args.filepath.format(epoch=epoch, f1=f1)\n args.best_model_score = f1\n checkpoint = {'ckpt_path': args.best_ckpt_path}\n else:\n checkpoint = {'ckpt_path': os.path.join(args.ckpt_dir, 'latest.ckpt')}\n\n args.current_epoch = epoch\n args.global_step = global_step\n checkpoint['args'] = vars(args)\n checkpoint['states'] = model.state_dict()\n checkpoint['optimizer_states'] = optimizer.state_dict()\n\n if not latest:\n for rm_path in glob.glob(os.path.join(args.ckpt_dir, '*.pt')):\n os.remove(rm_path)\n\n torch.save(checkpoint, checkpoint['ckpt_path'])\n print(f\"Model saved at: {checkpoint['ckpt_path']}\")\n\n\ndef load_ckpt(load_path):\n checkpoint = torch.load(load_path, map_location='cpu')\n args = Namespace(**checkpoint['args'])\n args = update_args(args)\n states = checkpoint['states']\n model_class = get_model_class(args)\n model = model_class(args)\n model.load_state_dict(states)\n model.eval()\n print('Model loaded from:', load_path)\n\n if 'optimizer_states' in checkpoint:\n optimizer = AdamW(model.parameters(), lr=args.lr)\n optimizer.load_state_dict(checkpoint['optimizer_states'])\n return model, args, optimizer\n else:\n return model, args, None\n\n\ndef save_args(args):\n with open(args.args_path, 'w') as f:\n yaml.dump(vars(args), f, default_flow_style=False)\n print(f'Arg file saved at: {args.args_path}')\n\n\ndef load_args(ckpt_dir, as_namespace):\n path = os.path.join(ckpt_dir, 'args.yaml')\n with open(path) as f:\n args = yaml.safe_load(f)\n if as_namespace:\n args = Namespace(**args)\n return args\n\n\ndef args_factory(args):\n args.filename = 'model-epoch={epoch:03d}-f1={f1:.1f}.pt'\n args.ckpt_dir = os.path.join(config.EXP_DIR, args.run_name)\n args.filepath = os.path.join(args.ckpt_dir, args.filename)\n args.args_path = os.path.join(args.ckpt_dir, 'args.yaml')\n\n if args.model_type == 'cbert-proto':\n assert args.episodic\n\n if args.episodic:\n args.accumulate_grad_batches, args.batch_size = args.batch_size, 1\n else:\n args.accumulate_grad_batches = 1\n \n args.num_sanity_val_steps = 0\n args.progress_bar_refresh_rate = 0\n return args\n\n\ndef sample_examples(keys, weights, k, seed):\n if seed is not None:\n random.seed(seed)\n sampled_keys = random.choices(keys, weights=weights, k=k) # sample with replacement\n return dict(Counter(sampled_keys))\n\n\ndef save_pred_file(predictions, args=None, filename=None):\n filename = 'result_key.txt' if filename is None else filename\n if args is None:\n pred_key_path = os.path.join(config.TMP_DIR, 'result_key.txt')\n else:\n pred_key_path = os.path.join(args.ckpt_dir, 'result_key.txt')\n with open(pred_key_path, 'w') as f:\n for pred in predictions:\n f.write(f'{pred}\\n')\n\n\ndef evaluate_from_pred_file(gold_key_path, args=None, filename=None):\n filename = 'tmp.key.txt' if filename is None else filename\n if args is None:\n pred_key_path = os.path.join(config.TMP_DIR, filename)\n else:\n pred_key_path = os.path.join(args.ckpt_dir, filename)\n eval_cmd = ['java', 'Scorer', gold_key_path, pred_key_path]\n os.chdir(config.SCORER_DIR)\n output = subprocess.Popen(eval_cmd, stdout=subprocess.PIPE).communicate()[0]\n output = str(output, 'utf-8')\n output = output.splitlines()\n _, _, f1 = [float(output[i].split('=')[-1].strip()[:-1]) for i in range(3)]\n return f1\n\n\ndef load_glosses(path):\n sensekey_to_gloss = {}\n with open(path) as f:\n csv_reader = csv.reader(f, delimiter='\\t')\n for line in csv_reader:\n sensekey_to_gloss[line[0]] = line[4]\n return sensekey_to_gloss"
] | [
[
"torch.load",
"torch.save"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
datalayer-contrib/holoviz-panel | [
"c97b57e8eaff4b5f542add41f496395da2483b23"
] | [
"panel/pane/vtk/synchronizable_deserializer.py"
] | [
"import json\nimport zipfile\nimport vtk\nimport re\nimport struct\n\nfrom .synchronizable_serializer import arrayTypesMapping\n\n\nMETHODS_RENAME = {\n \"AddTexture\": \"SetTexture\",\n \"SetUseGradientOpacity\": None,\n \"SetRGBTransferFunction\": \"SetColor\",\n}\nWRAP_ID_RE = re.compile(r\"instance:\\${([^}]+)}\")\nARRAY_TYPES = {\n 'Int8Array': vtk.vtkCharArray,\n 'Uint8Array': vtk.vtkUnsignedCharArray,\n 'Int16Array': vtk.vtkShortArray,\n 'UInt16Array': vtk.vtkUnsignedShortArray,\n 'Int32Array': vtk.vtkIntArray,\n 'Uint32Array': vtk.vtkUnsignedIntArray,\n 'Float32Array': vtk.vtkFloatArray,\n 'Float64Array': vtk.vtkDoubleArray,\n}\n\ndef capitalize(name):\n \"Upper the first letter letting the rest unchange\"\n return name[0].upper() + name[1:]\n\ndef fill_array(vtk_arr, state, zf):\n vtk_arr.SetNumberOfComponents(state['numberOfComponents'])\n vtk_arr.SetNumberOfTuples(state['size']//state['numberOfComponents'])\n data = zf.read('data/%s' % state['hash'])\n dataType = arrayTypesMapping[vtk_arr.GetDataType()]\n elementSize = struct.calcsize(dataType)\n if vtk_arr.GetDataType() == 12:\n # we need to cast the data to Uint64\n import numpy as np\n data = np.frombuffer(data, dtype=np.uint32).astype(np.uint64).tobytes()\n elementSize = 8\n vtk_arr.SetVoidArray(data, len(data)//elementSize, 1)\n vtk_arr._reference = data\n\ndef color_fun_builder(state, zf, register):\n instance = getattr(vtk, state['type'])()\n register.update({state['id']: instance})\n nodes = state['properties'].pop('nodes')\n set_properties(instance, state['properties'])\n for node in nodes:\n instance.AddRGBPoint(*node)\n\ndef piecewise_fun_builder(state, zf, register):\n instance = getattr(vtk, state['type'])()\n register.update({state['id']: instance})\n nodes = state['properties'].pop('nodes')\n set_properties(instance, state['properties'])\n for node in nodes:\n instance.AddPoint(*node)\n\ndef poly_data_builder(state, zf, register):\n instance = vtk.vtkPolyData()\n register.update({state['id']: instance})\n # geometry\n if 'points' in state['properties']:\n points = state['properties']['points']\n vtkpoints = vtk.vtkPoints()\n points_data_arr = ARRAY_TYPES[points['dataType']]()\n fill_array(points_data_arr, points, zf)\n vtkpoints.SetData(points_data_arr)\n instance.SetPoints(vtkpoints)\n for cell_type in ['verts', 'lines', 'polys', 'strips']:\n if cell_type in state['properties']:\n cell_arr = vtk.vtkCellArray()\n cell_data_arr = vtk.vtkIdTypeArray()\n fill_array(cell_data_arr, state['properties'][cell_type], zf)\n cell_arr.ImportLegacyFormat(cell_data_arr)\n getattr(instance, 'Set' + capitalize(cell_type))(cell_arr)\n \n # datasets\n fields = state['properties']['fields']\n for dataset in fields:\n data_arr = ARRAY_TYPES[dataset['dataType']]()\n fill_array(data_arr, dataset, zf)\n location = getattr(instance, 'Get' + capitalize(dataset['location']))()\n getattr(location, capitalize(dataset.get(\"registration\", \"addArray\")))(data_arr)\n\ndef volume_mapper_builder(state, zf, register):\n instance = generic_builder(state, zf, register)\n instance.SetScalarMode(1) #need to force the scalar mode to be on points\n\ndef generic_builder(state, zf, register=None):\n if register is None:\n register = {}\n instance = getattr(vtk, state['type'])()\n register.update({state['id']: instance})\n set_properties(instance, state['properties'])\n dependencies = state.get('dependencies', None)\n if dependencies:\n for dep in dependencies:\n builder = TYPE_HANDLERS[dep['type']]\n if builder:\n builder(dep, zf, register)\n else:\n print(f'No builder for {dep[\"type\"]}')\n calls = state.get('calls', None)\n if calls:\n for call in calls:\n args=[]\n skip=False\n for arg in call[1]:\n try:\n extract_instance = WRAP_ID_RE.findall(arg)[0]\n args.append(register[extract_instance])\n except (IndexError, TypeError):\n args.append(arg)\n except KeyError:\n skip = True\n if skip: continue\n if capitalize(call[0]) not in METHODS_RENAME:\n method = capitalize(call[0])\n else:\n method = METHODS_RENAME[capitalize(call[0])]\n if method is None: continue\n if method == \"SetInputData\" and len(args)==2:\n getattr(instance, method + \"Object\")(*args[::-1])\n else:\n getattr(instance, method)(*args)\n arrays = state.get('arrays', None)\n if arrays:\n for array_meta in arrays:\n vtk_array = ARRAY_TYPES[array_meta['dataType']]()\n fill_array(vtk_array, array_meta, zf)\n location = (instance \n if 'location' not in array_meta\n else getattr(instance, 'Get'+capitalize(array_meta['location']))())\n getattr(location, capitalize(array_meta['registration']))(vtk_array)\n return instance\n\ndef set_properties(instance, properties):\n for k, v in properties.items():\n fn = getattr(instance, 'Set'+capitalize(k), None)\n if fn:\n fn(v)\n\ndef import_synch_file(filename):\n with zipfile.ZipFile(filename, 'r') as zf:\n scene = json.loads(zf.read('index.json').decode())\n scene['properties']['numberOfLayers'] = 1\n renwin = generic_builder(scene, zf)\n return renwin\n\n\ndef make_type_handlers():\n aliases = {\n 'vtkMapper': ['vtkOpenGLPolyDataMapper', 'vtkCompositePolyDataMapper2', 'vtkDataSetMapper'],\n 'vtkProperty': ['vtkOpenGLProperty'],\n 'vtkRenderer': ['vtkOpenGLRenderer'],\n 'vtkCamera': ['vtkOpenGLCamera'],\n 'vtkColorTransferFunction': ['vtkPVDiscretizableColorTransferFunction'],\n 'vtkActor': ['vtkOpenGLActor', 'vtkPVLODActor'],\n 'vtkLight': ['vtkOpenGLLight', 'vtkPVLight'],\n 'vtkTexture': ['vtkOpenGLTexture'],\n 'vtkVolumeMapper': ['vtkFixedPointVolumeRayCastMapper', 'vtkSmartVolumeMapper'],\n \"vtkGlyph3DMapper\": [\"vtkOpenGLGlyph3DMapper\"],\n }\n\n type_handlers = {\n 'vtkRenderer': generic_builder,\n 'vtkLookupTable': generic_builder,\n 'vtkLight': None,\n 'vtkCamera': generic_builder,\n 'vtkPolyData': poly_data_builder,\n 'vtkImageData': generic_builder,\n 'vtkMapper': generic_builder,\n 'vtkGlyph3DMapper': generic_builder,\n 'vtkProperty': generic_builder,\n 'vtkActor': generic_builder,\n 'vtkFollower': generic_builder,\n 'vtkColorTransferFunction': color_fun_builder,\n 'vtkPiecewiseFunction': piecewise_fun_builder,\n 'vtkTexture': generic_builder,\n 'vtkVolumeMapper': volume_mapper_builder,\n 'vtkVolume': generic_builder,\n 'vtkVolumeProperty': generic_builder\n }\n\n for k, alias_list in aliases.items():\n for alias in alias_list:\n type_handlers.update({\n alias: type_handlers[k]\n })\n\n return type_handlers\n\nTYPE_HANDLERS = make_type_handlers()\n"
] | [
[
"numpy.frombuffer"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
caosenqi/Edward1 | [
"85f833d307512a585b85ebc2979445e17191ed81"
] | [
"tests/test-stats/test_stats_multivariate_normal_entropy.py"
] | [
"from __future__ import print_function\nimport numpy as np\nimport tensorflow as tf\n\nfrom edward.stats import multivariate_normal\nfrom scipy import stats\n\nsess = tf.Session()\n\ndef _assert_eq(val_ed, val_true):\n with sess.as_default():\n assert np.allclose(val_ed.eval(), val_true)\n\ndef test_entropy_empty():\n _assert_eq(multivariate_normal.entropy(),\n stats.multivariate_normal.entropy())\n\ndef test_entropy_1d():\n diag = [1.0, 1.0]\n cov = tf.constant(diag)\n _assert_eq(multivariate_normal.entropy(cov=cov),\n stats.multivariate_normal.entropy(cov=np.diag(diag)))\n _assert_eq(multivariate_normal.entropy(cov=np.diag(diag)),\n stats.multivariate_normal.entropy(cov=np.diag(diag)))\n\ndef test_entropy_2d_diag():\n cm = [[1.0, 0.0], [0.0, 1.0]]\n cov = tf.constant(cm)\n _assert_eq(multivariate_normal.entropy(cov=cov),\n stats.multivariate_normal.entropy(cov=np.array(cm)))\n _assert_eq(multivariate_normal.entropy(cov=np.array(cm)),\n stats.multivariate_normal.entropy(cov=np.array(cm)))\n\ndef test_entropy_2d_full():\n cm = [[1.0, 0.9], [0.9, 1.0]]\n cov = tf.constant(cm)\n _assert_eq(multivariate_normal.entropy(cov=cov),\n stats.multivariate_normal.entropy(cov=np.array(cm)))\n _assert_eq(multivariate_normal.entropy(cov=np.array(cm)),\n stats.multivariate_normal.entropy(cov=np.array(cm)))\n"
] | [
[
"numpy.diag",
"tensorflow.constant",
"tensorflow.Session",
"scipy.stats.multivariate_normal.entropy",
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"1.12",
"1.4",
"1.5",
"1.7",
"0.12",
"1.0",
"1.2"
]
}
] |
michael-iuzzolino/CascadedNets | [
"2746320395424697d7225e9042e5b0fa8657345e"
] | [
"modules/eval_handler.py"
] | [
"\"\"\"Evaluation function handler for sequential or cascaded.\"\"\"\nimport numpy as np\nimport sys\nimport torch\nimport torch.nn.functional as F\n\n\nclass SequentialEvalLoop:\n \"\"\"Evaluation loop for sequential model.\"\"\"\n\n def __init__(\n self, \n num_classes, \n keep_logits=False, \n keep_embeddings=False, \n verbose=False\n ):\n self.num_classes = num_classes\n self.keep_logits = keep_logits\n self.keep_embeddings = keep_embeddings\n self.verbose = verbose\n\n def __call__(self, net, loader, criterion, epoch_i, device):\n net.eval()\n\n batch_losses = []\n batch_correct = []\n batch_logits = []\n batch_embeddings = []\n ys = []\n global embedding\n sample_count = 0\n\n # Embedding hook\n def embedding_hook_fn(module, x, output): # pylint: disable=unused-argument\n global embedding # pylint: disable=global-variable-undefined\n embedding = x[0]\n _ = net.fc.register_forward_hook(embedding_hook_fn)\n\n for batch_i, (data, targets) in enumerate(loader):\n if self.verbose:\n sys.stdout.write(f\"\\rBatch {batch_i+1}/{len(loader)}\")\n sys.stdout.flush()\n \n # One-hot-ify targets\n y = torch.eye(self.num_classes)[targets]\n sample_count += y.shape[0]\n\n # Determine device placement\n data = data.to(device, non_blocking=True)\n\n # Forward pass\n with torch.no_grad():\n logits = net(data, t=0).cpu()\n\n if self.keep_logits:\n batch_logits.append(logits)\n ys.append(targets.cpu())\n \n if self.keep_embeddings:\n batch_embeddings.append(embedding.cpu())\n\n # Compute loss\n loss = criterion(logits, y)\n batch_losses.append(loss.item())\n\n # Predictions\n softmax = F.softmax(logits, dim=1)\n y_pred = torch.argmax(softmax, dim=1)\n\n # Updates running statistics\n n_correct = torch.eq(targets, y_pred).sum().item()\n batch_correct.append(n_correct)\n batch_accs = np.sum(batch_correct) / float(sample_count)\n \n logged_data = {}\n if self.keep_logits:\n logged_data[\"logits\"] = torch.cat(batch_logits)\n logged_data[\"y\"] = torch.cat(ys)\n \n if self.keep_embeddings:\n logged_data[\"embeddings\"] = torch.cat(batch_embeddings)\n \n return batch_losses, batch_accs, logged_data\n \n \nclass CascadedEvalLoop(object):\n \"\"\"Evaluation loop for cascaded model.\"\"\"\n\n def __init__(self, n_timesteps, num_classes, \n keep_logits=False, keep_embeddings=False, verbose=False):\n self.n_timesteps = n_timesteps\n self.num_classes = num_classes\n self.keep_logits = keep_logits\n self.keep_embeddings = keep_embeddings\n self.verbose = verbose\n\n def __call__(self, net, loader, criterion, epoch_i, device):\n net.eval()\n\n batch_logits = []\n batch_embeddings = []\n ys = []\n global embedding\n \n # Embedding hook\n def embedding_hook_fn(module, x, output): # pylint: disable=unused-argument\n global embedding # pylint: disable=global-variable-undefined\n embedding = x[0]\n \n if net._multiple_fcs:\n for i, fc in enumerate(net.fcs):\n fc.register_forward_hook(embedding_hook_fn)\n else:\n net.fc.register_forward_hook(embedding_hook_fn)\n \n batch_losses = []\n batch_correct = []\n sample_count = 0\n for batch_i, (x, targets) in enumerate(loader):\n if self.verbose:\n sys.stdout.write(f\"\\rBatch {batch_i+1}/{len(loader)}\")\n sys.stdout.flush()\n # One-hot-ify targets\n y = torch.eye(self.num_classes)[targets]\n sample_count += y.shape[0]\n\n if self.keep_logits:\n ys.append(targets)\n\n # Determine device placement\n x = x.to(device, non_blocking=True)\n\n timestep_correct = []\n timestep_losses = torch.zeros(self.n_timesteps)\n timestep_logits = []\n timestep_embeddings = []\n for t in range(self.n_timesteps):\n # Forward pass\n with torch.no_grad():\n logits_t = net(x, t).cpu()\n \n if self.keep_logits:\n timestep_logits.append(logits_t)\n \n if self.keep_embeddings:\n global embedding\n timestep_embeddings.append(embedding)\n\n # Compute loss\n loss_i = criterion(logits_t, y)\n\n # Log loss\n timestep_losses[t] = loss_i.item()\n\n # Predictions\n softmax_t = F.softmax(logits_t, dim=1)\n y_pred = torch.argmax(softmax_t, dim=1)\n\n # Updates running accuracy statistics\n n_correct = torch.eq(targets, y_pred).sum()\n timestep_correct.append(n_correct)\n\n # Update batch loss and compute average\n batch_losses.append(timestep_losses)\n batch_correct.append(torch.stack(timestep_correct))\n\n if self.keep_logits:\n # stack into shape=(time, batch, n_classes)\n timestep_logits = torch.stack(timestep_logits)\n batch_logits.append(timestep_logits)\n \n if self.keep_embeddings:\n timestep_embeddings = torch.stack(timestep_embeddings)\n batch_embeddings.append(timestep_embeddings)\n\n # Average over the batches per timestep\n batch_losses = torch.stack(batch_losses).detach().numpy()\n batch_correct = torch.stack(batch_correct).sum(dim=0)\n batch_accs = batch_correct.cpu().detach().numpy() / float(sample_count)\n\n # Compute loss and accuracy\n logged_data = {}\n if self.keep_logits:\n # concat over batch dim into shape=(time, batch, n_classes)\n batch_logits = torch.cat(batch_logits, dim=1)\n ys = torch.cat(ys)\n logged_data[\"logits\"] = batch_logits\n logged_data[\"y\"] = ys\n \n if self.keep_embeddings:\n # concat over batch dim into shape=(time, batch, n_features, spatial_dim)\n batch_embeddings = torch.cat(batch_embeddings, dim=1)\n logged_data[\"embeddings\"] = batch_embeddings\n \n return batch_losses, batch_accs, logged_data\n \n\ndef get_eval_loop(n_timesteps, num_classes, cascaded, flags,\n keep_logits=False, keep_embeddings=False, \n verbose=False, tau_handler=None):\n \"\"\"Retrieve sequential or cascaded eval function.\"\"\"\n if flags.train_mode == \"baseline\":\n eval_fxn = SequentialEvalLoop(\n num_classes, \n keep_logits, \n keep_embeddings, \n verbose\n )\n elif flags.train_mode == \"cascaded\":\n eval_fxn = CascadedEvalLoop(\n n_timesteps, \n num_classes, \n keep_logits, \n keep_embeddings, \n verbose\n )\n elif flags.train_mode == \"cascaded_seq\":\n eval_fxn = CascadedEvalLoop(\n n_timesteps, \n num_classes, \n keep_logits, \n keep_embeddings, \n verbose\n )\n return eval_fxn\n"
] | [
[
"torch.nn.functional.softmax",
"torch.zeros",
"torch.cat",
"torch.eq",
"torch.eye",
"torch.no_grad",
"torch.stack",
"numpy.sum",
"torch.argmax"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
catalys1/pytorch-lightning | [
"3bd48b85356e36b7a56b5d8f669403f0bfb9d717"
] | [
"tests/callbacks/test_gpu_stats_monitor.py"
] | [
"# Copyright The PyTorch Lightning team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport os\nfrom unittest import mock\n\nimport numpy as np\nimport pytest\nimport torch\n\nfrom pytorch_lightning import Trainer\nfrom pytorch_lightning.callbacks import GPUStatsMonitor\nfrom pytorch_lightning.loggers import CSVLogger\nfrom pytorch_lightning.loggers.csv_logs import ExperimentWriter\nfrom pytorch_lightning.utilities.exceptions import MisconfigurationException\nfrom tests.helpers import BoringModel\nfrom tests.helpers.runif import RunIf\n\n\n@RunIf(min_gpus=1)\ndef test_gpu_stats_monitor(tmpdir):\n \"\"\"Test GPU stats are logged using a logger.\"\"\"\n model = BoringModel()\n with pytest.deprecated_call(match=\"GPUStatsMonitor` callback was deprecated in v1.5\"):\n gpu_stats = GPUStatsMonitor(intra_step_time=True)\n logger = CSVLogger(tmpdir)\n log_every_n_steps = 2\n\n trainer = Trainer(\n default_root_dir=tmpdir,\n max_epochs=2,\n limit_train_batches=7,\n log_every_n_steps=log_every_n_steps,\n accelerator=\"gpu\",\n devices=1,\n callbacks=[gpu_stats],\n logger=logger,\n )\n\n trainer.fit(model)\n assert trainer.state.finished, f\"Training failed with {trainer.state}\"\n\n path_csv = os.path.join(logger.log_dir, ExperimentWriter.NAME_METRICS_FILE)\n met_data = np.genfromtxt(path_csv, delimiter=\",\", names=True, deletechars=\"\", replace_space=\" \")\n\n batch_time_data = met_data[\"batch_time/intra_step (ms)\"]\n batch_time_data = batch_time_data[~np.isnan(batch_time_data)]\n assert batch_time_data.shape[0] == trainer.global_step // log_every_n_steps\n\n fields = [\"utilization.gpu\", \"memory.used\", \"memory.free\", \"utilization.memory\"]\n\n for f in fields:\n assert any(f in h for h in met_data.dtype.names)\n\n\n@RunIf(min_gpus=1)\ndef test_gpu_stats_monitor_no_queries(tmpdir):\n \"\"\"Test GPU logger doesn't fail if no \"nvidia-smi\" queries are to be performed.\"\"\"\n model = BoringModel()\n with pytest.deprecated_call(match=\"GPUStatsMonitor` callback was deprecated in v1.5\"):\n gpu_stats = GPUStatsMonitor(\n memory_utilization=False,\n gpu_utilization=False,\n intra_step_time=True,\n inter_step_time=True,\n )\n trainer = Trainer(\n default_root_dir=tmpdir,\n max_epochs=1,\n limit_train_batches=2,\n limit_val_batches=0,\n log_every_n_steps=1,\n accelerator=\"gpu\",\n devices=1,\n callbacks=[gpu_stats],\n )\n with mock.patch(\"pytorch_lightning.loggers.tensorboard.TensorBoardLogger.log_metrics\") as log_metrics_mock:\n trainer.fit(model)\n\n assert log_metrics_mock.mock_calls[1:] == [\n mock.call({\"batch_time/intra_step (ms)\": mock.ANY}, step=0),\n mock.call({\"batch_time/inter_step (ms)\": mock.ANY}, step=1),\n mock.call({\"batch_time/intra_step (ms)\": mock.ANY}, step=1),\n ]\n\n\[email protected](torch.cuda.is_available(), reason=\"test requires CPU machine\")\ndef test_gpu_stats_monitor_cpu_machine(tmpdir):\n \"\"\"Test GPUStatsMonitor on CPU machine.\"\"\"\n with pytest.raises(MisconfigurationException, match=\"NVIDIA driver is not installed\"), pytest.deprecated_call(\n match=\"GPUStatsMonitor` callback was deprecated in v1.5\"\n ):\n GPUStatsMonitor()\n\n\n@RunIf(min_gpus=1)\ndef test_gpu_stats_monitor_no_logger(tmpdir):\n \"\"\"Test GPUStatsMonitor with no logger in Trainer.\"\"\"\n model = BoringModel()\n with pytest.deprecated_call(match=\"GPUStatsMonitor` callback was deprecated in v1.5\"):\n gpu_stats = GPUStatsMonitor()\n\n trainer = Trainer(\n default_root_dir=tmpdir, callbacks=[gpu_stats], max_epochs=1, accelerator=\"gpu\", devices=1, logger=False\n )\n\n with pytest.raises(MisconfigurationException, match=\"Trainer that has no logger.\"):\n trainer.fit(model)\n\n\n@RunIf(min_gpus=1)\ndef test_gpu_stats_monitor_no_gpu_warning(tmpdir):\n \"\"\"Test GPUStatsMonitor raises a warning when not training on GPU device.\"\"\"\n model = BoringModel()\n with pytest.deprecated_call(match=\"GPUStatsMonitor` callback was deprecated in v1.5\"):\n gpu_stats = GPUStatsMonitor()\n\n trainer = Trainer(default_root_dir=tmpdir, callbacks=[gpu_stats], max_steps=1, gpus=None)\n\n with pytest.raises(MisconfigurationException, match=\"not running on GPU\"):\n trainer.fit(model)\n\n\ndef test_gpu_stats_monitor_parse_gpu_stats():\n logs = GPUStatsMonitor._parse_gpu_stats([1, 2], [[3, 4, 5], [6, 7]], [(\"gpu\", \"a\"), (\"memory\", \"b\")])\n expected = {\n \"device_id: 1/gpu (a)\": 3,\n \"device_id: 1/memory (b)\": 4,\n \"device_id: 2/gpu (a)\": 6,\n \"device_id: 2/memory (b)\": 7,\n }\n assert logs == expected\n\n\[email protected](os.environ, {}, clear=True)\[email protected](\"torch.cuda.is_available\", return_value=True)\[email protected](\"torch.cuda.device_count\", return_value=2)\ndef test_gpu_stats_monitor_get_gpu_ids_cuda_visible_devices_unset(device_count_mock, is_available_mock):\n gpu_ids = GPUStatsMonitor._get_gpu_ids([1, 0])\n expected = [\"1\", \"0\"]\n assert gpu_ids == expected\n\n\[email protected](os.environ, {\"CUDA_VISIBLE_DEVICES\": \"3,2,4\"})\[email protected](\"torch.cuda.is_available\", return_value=True)\[email protected](\"torch.cuda.device_count\", return_value=3)\ndef test_gpu_stats_monitor_get_gpu_ids_cuda_visible_devices_integers(device_count_mock, is_available_mock):\n gpu_ids = GPUStatsMonitor._get_gpu_ids([1, 2])\n expected = [\"2\", \"4\"]\n assert gpu_ids == expected\n\n\[email protected](os.environ, {\"CUDA_VISIBLE_DEVICES\": \"GPU-01a23b4c,GPU-56d78e9f,GPU-02a46c8e\"})\[email protected](\"torch.cuda.is_available\", return_value=True)\[email protected](\"torch.cuda.device_count\", return_value=3)\ndef test_gpu_stats_monitor_get_gpu_ids_cuda_visible_devices_uuids(device_count_mock, is_available_mock):\n gpu_ids = GPUStatsMonitor._get_gpu_ids([1, 2])\n expected = [\"GPU-56d78e9f\", \"GPU-02a46c8e\"]\n assert gpu_ids == expected\n"
] | [
[
"numpy.isnan",
"torch.cuda.is_available",
"numpy.genfromtxt"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.